Skip to content

Modern Docker Management, Designed for Everyone

feat: add all environments ui preview (#4389)

Kyle Mendell298c8cf6a392
diff --git a/backend/api/handlers/diagnostics.go b/backend/api/handlers/diagnostics.go
index 43b4feb78..47d9ff02e 100644
--- a/backend/api/handlers/diagnostics.go
+++ b/backend/api/handlers/diagnostics.go
@@ -13,8 +13,8 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
)
-// DiagnosticsHandler serves the environment-scoped actor diagnostics the manager
-// collects from each agent. The diagnostics page itself uses the api/ws streams.
+// DiagnosticsHandler serves the environment-scoped actor and goroutine diagnostics.
+// The live diagnostics snapshots use the api/ws streams.
type DiagnosticsHandler struct {
diag *diagnostics.DiagnosticsService
}
@@ -27,6 +27,14 @@ type GetEnvironmentActorDiagnosticsOutput struct {
Body system.ActorDiagnostics
}
+type GetEnvironmentGoroutineDiagnosticsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type GetEnvironmentGoroutineDiagnosticsOutput struct {
+ Body system.GoroutineProfile
+}
+
// RegisterDiagnostics registers the Huma diagnostics REST endpoints.
func RegisterDiagnostics(api huma.API, diag *diagnostics.DiagnosticsService) {
h := &DiagnosticsHandler{diag: diag}
@@ -40,6 +48,16 @@ func RegisterDiagnostics(api huma.API, diag *diagnostics.DiagnosticsService) {
Tags: []string{"Diagnostics"},
Security: handlerutil.DefaultOperationSecurity(),
}, authz.PermDiagnosticsRead, h.GetEnvironmentActorDiagnostics)
+
+ middleware.RegisterWithPermission(api, huma.Operation{
+ OperationID: "get-environment-goroutine-diagnostics",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/diagnostics/goroutines",
+ Summary: "Get goroutine diagnostics for an environment",
+ Description: "Returns the live goroutines grouped by identical stack, largest group first.",
+ Tags: []string{"Diagnostics"},
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, authz.PermDiagnosticsRead, h.GetEnvironmentGoroutineDiagnostics)
}
func (h *DiagnosticsHandler) GetEnvironmentActorDiagnostics(ctx context.Context, _ *GetEnvironmentActorDiagnosticsInput) (*GetEnvironmentActorDiagnosticsOutput, error) {
@@ -49,3 +67,11 @@ func (h *DiagnosticsHandler) GetEnvironmentActorDiagnostics(ctx context.Context,
}
return &GetEnvironmentActorDiagnosticsOutput{Body: d}, nil
}
+
+func (h *DiagnosticsHandler) GetEnvironmentGoroutineDiagnostics(_ context.Context, _ *GetEnvironmentGoroutineDiagnosticsInput) (*GetEnvironmentGoroutineDiagnosticsOutput, error) {
+ profile, err := h.diag.Goroutines()
+ if err != nil {
+ return nil, huma.Error500InternalServerError("Failed to collect goroutine diagnostics: " + err.Error())
+ }
+ return &GetEnvironmentGoroutineDiagnosticsOutput{Body: profile}, nil
+}
diff --git a/backend/internal/auth/handler.go b/backend/internal/auth/handler.go
index 8dc3c53a8..a7ae85d26 100644
--- a/backend/internal/auth/handler.go
+++ b/backend/internal/auth/handler.go
@@ -336,6 +336,14 @@ func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfil
if v := p.AccentColor; v != nil && *v != "" && *v != "default" && !settingstypes.SafeAccentColor.MatchString(*v) {
return nil, huma.Error400BadRequest("invalid accentColor value")
}
+ // Keys are environment IDs; the caps keep one user's preferences from growing without bound.
+ if v := p.EnvironmentColors; v != nil {
+ for id, color := range *v {
+ if len(*v) > 1000 || id == "" || len(id) > 64 || !settingstypes.SafeAccentColor.MatchString(color) {
+ return nil, huma.Error400BadRequest("invalid environmentColors value")
+ }
+ }
+ }
// Keep the landing page a same-origin relative path. The frontend
// additionally validates it against the known nav pages, falling back to
// /dashboard.
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index 1df34e4d4..c109a7d64 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -105,6 +105,7 @@ var (
ErrVolumeWorkspaceNotFound = Classify(ErrNotFound, errors.New("Volume workspace file not found"))
ErrVolumeRenameInvalid = Classify(ErrBadRequest, errors.New("source and target volume names must be non-empty and different"))
ErrVolumeRenameProtected = Classify(ErrBadRequest, errors.New("Arcane's internal volumes cannot be renamed"))
+ ErrVolumeDeleteProtected = Classify(ErrBadRequest, errors.New("Arcane's backup volume cannot be removed"))
ErrProjectComposeFileNotFound = Classify(ErrNotFound, errors.New("Project compose file not found"))
ErrComposeFileNotFound = Classify(ErrNotFound, errors.New("no compose file found"))
ErrComposeFileEnvInvalid = Classify(ErrValidation, errors.New("invalid COMPOSE_FILE selection"))
diff --git a/backend/internal/diagnostics/service.go b/backend/internal/diagnostics/service.go
index 1541731de..60eb43f66 100644
--- a/backend/internal/diagnostics/service.go
+++ b/backend/internal/diagnostics/service.go
@@ -2,6 +2,7 @@ package diagnostics
import (
"bytes"
+ "cmp"
"context"
"errors"
"fmt"
@@ -11,6 +12,9 @@ import (
"runtime/debug"
"runtime/pprof"
"runtime/trace"
+ "slices"
+ "strconv"
+ "strings"
"sync"
"time"
@@ -138,6 +142,58 @@ func (s *DiagnosticsService) ScanGoroutineLeaks() (system.GoroutineLeakReport, e
}, nil
}
+// Goroutines groups the live goroutines by identical stack, largest group first.
+// Records that differ only by pprof labels share a stack and merge into one group.
+func (s *DiagnosticsService) Goroutines() (system.GoroutineProfile, error) {
+ var buf bytes.Buffer
+ if err := pprof.Lookup("goroutine").WriteTo(&buf, 1); err != nil {
+ return system.GoroutineProfile{}, fmt.Errorf("write goroutine profile: %w", err)
+ }
+
+ profile := system.GoroutineProfile{Groups: []system.GoroutineGroup{}, CapturedAt: time.Now().UTC()}
+ index := map[string]int{}
+ // debug=1 text holds "N @ pcs" records of "#\tpc\tfunc+off\tfile:line" frames, separated by blank lines.
+ // A tabwriter aligns the columns, so a run of tabs is one separator.
+ for record := range strings.SplitSeq(buf.String(), "\n\n") {
+ group := system.GoroutineGroup{Frames: []system.GoroutineFrame{}}
+ for line := range strings.Lines(record) {
+ fields := strings.FieldsFunc(line, func(r rune) bool { return r == '\t' || r == '\n' })
+ if len(fields) == 0 {
+ continue
+ }
+ switch head, _, isHead := strings.Cut(fields[0], " @"); {
+ case isHead && !strings.HasPrefix(head, "#"):
+ group.Count, _ = strconv.Atoi(head)
+ case len(fields) == 4 && fields[0] == "#":
+ function, _, _ := strings.Cut(fields[2], "+0x")
+ sep := strings.LastIndexByte(fields[3], ':')
+ lineNo, err := strconv.Atoi(fields[3][sep+1:])
+ hasLine := sep >= 0 && err == nil
+ group.Frames = append(group.Frames, system.GoroutineFrame{
+ Function: function,
+ File: kit.Ternary(hasLine, fields[3][:max(sep, 0)], fields[3]),
+ Line: kit.Ternary(hasLine, lineNo, 0),
+ })
+ // Frames run innermost first, so the last non-runtime frame is the entry point.
+ group.Label = kit.Ternary(group.Label == "" || !strings.HasPrefix(function, "runtime."), function, group.Label)
+ }
+ }
+ if group.Count == 0 {
+ continue
+ }
+ profile.Total += group.Count
+ key := fmt.Sprint(group.Frames)
+ if i, ok := index[key]; ok {
+ profile.Groups[i].Count += group.Count
+ continue
+ }
+ index[key] = len(profile.Groups)
+ profile.Groups = append(profile.Groups, group)
+ }
+ slices.SortStableFunc(profile.Groups, func(a, b system.GoroutineGroup) int { return cmp.Compare(b.Count, a.Count) })
+ return profile, nil
+}
+
// Profile captures a pprof profile in the given debug format. The CPU profile
// and execution trace sample for seconds or until ctx ends.
func (s *DiagnosticsService) Profile(ctx context.Context, name string, seconds, debugLevel int) ([]byte, error) {
diff --git a/backend/internal/diagnostics/service_test.go b/backend/internal/diagnostics/service_test.go
index 53aa83873..96e5e1337 100644
--- a/backend/internal/diagnostics/service_test.go
+++ b/backend/internal/diagnostics/service_test.go
@@ -1,12 +1,15 @@
package diagnostics
import (
+ "context"
"runtime"
"runtime/pprof"
+ "slices"
"strings"
"testing"
"time"
+ "github.com/getarcaneapp/arcane/types/v2/system"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -95,3 +98,38 @@ func leakUnbufferedChannelInternal() {
func blockForeverOnDroppedChannelInternal() {
<-make(chan struct{})
}
+
+func TestDiagnosticsServiceGoroutines(t *testing.T) {
+ s := NewDiagnosticsService(nil, nil, nil)
+ release := make(chan struct{})
+ defer close(release)
+ // Different pprof labels split debug=1 records; the service merges them by stack.
+ for _, worker := range []string{"a", "a", "b"} {
+ go func() {
+ pprof.Do(t.Context(), pprof.Labels("worker", worker), func(context.Context) { <-release })
+ }()
+ }
+
+ require.EventuallyWithT(t, func(c *assert.CollectT) {
+ profile, err := s.Goroutines()
+ require.NoError(c, err)
+ assert.True(c, slices.IsSortedFunc(profile.Groups, func(a, b system.GoroutineGroup) int { return b.Count - a.Count }))
+ assert.Equal(c, profile.Total, func() int {
+ total := 0
+ for _, g := range profile.Groups {
+ total += g.Count
+ }
+ return total
+ }())
+ // The label is the outermost frame, the started func; the blocking closure and pprof.Do sit inside it.
+ i := slices.IndexFunc(profile.Groups, func(g system.GoroutineGroup) bool {
+ return strings.HasSuffix(g.Label, "TestDiagnosticsServiceGoroutines.func1")
+ })
+ require.GreaterOrEqual(c, i, 0)
+ group := profile.Groups[i]
+ assert.Equal(c, 3, group.Count)
+ require.Len(c, group.Frames, 3)
+ assert.Equal(c, "runtime/pprof.Do", group.Frames[1].Function)
+ assert.False(c, slices.ContainsFunc(group.Frames, func(f system.GoroutineFrame) bool { return f.File == "" || f.Line <= 0 }))
+ }, 5*time.Second, 20*time.Millisecond)
+}
diff --git a/backend/internal/system/children/prune/service.go b/backend/internal/system/children/prune/service.go
index fb174e005..41900a9bc 100644
--- a/backend/internal/system/children/prune/service.go
+++ b/backend/internal/system/children/prune/service.go
@@ -577,7 +577,7 @@ func (s *Service) preparePrunePlanInternal(ctx context.Context, req system.Prune
if selectPruneImagesErr := s.selectPruneImagesInternal(&plan, usage, imageRefs); selectPruneImagesErr != nil {
return plan, selectPruneImagesErr
}
- selectPruneVolumesInternal(&plan, usage, volumeRefs)
+ s.selectPruneVolumesInternal(&plan, usage, volumeRefs)
if selectPruneNetworksErr := s.selectPruneNetworksInternal(ctx, dockerClient, &plan, selectedContainers); selectPruneNetworksErr != nil {
return plan, selectPruneNetworksErr
}
@@ -640,11 +640,13 @@ func (s *Service) selectPruneImagesInternal(plan *prunePlanInternal, usage clien
return nil
}
-func selectPruneVolumesInternal(plan *prunePlanInternal, usage client.DiskUsageResult, volumeRefs map[string]int) {
+func (s *Service) selectPruneVolumesInternal(plan *prunePlanInternal, usage client.DiskUsageResult, volumeRefs map[string]int) {
req := plan.Request
if req.Volumes != nil && req.Volumes.Mode != system.PruneVolumeModeNone {
for _, item := range usage.Volumes.Items {
- if item.UsageData == nil || item.UsageData.RefCount > int64(volumeRefs[item.Name]) || strings.EqualFold(item.Labels[libarcane.InternalResourceLabel], "true") {
+ // The backup volume is unused between backups but holds them, so it is never pruned.
+ if item.UsageData == nil || item.UsageData.RefCount > int64(volumeRefs[item.Name]) ||
+ strings.EqualFold(item.Labels[libarcane.InternalResourceLabel], "true") || s.volumeService.IsBackupVolume(item.Name) {
continue
}
if req.Volumes.Mode == system.PruneVolumeModeAnonymous {
@@ -960,7 +962,8 @@ func (s *Service) pruneResourceEligibleInternal(ctx context.Context, dockerClien
return false, true, nil
}
resource.Size = item.UsageData.Size
- return item.UsageData.RefCount == 0 && !strings.EqualFold(item.Labels[libarcane.InternalResourceLabel], "true"), true, nil
+ return item.UsageData.RefCount == 0 && !strings.EqualFold(item.Labels[libarcane.InternalResourceLabel], "true") &&
+ !s.volumeService.IsBackupVolume(item.Name), true, nil
}
}
}
diff --git a/backend/internal/volume/service.go b/backend/internal/volume/service.go
index 731ad0741..7e10a59be 100644
--- a/backend/internal/volume/service.go
+++ b/backend/internal/volume/service.go
@@ -461,6 +461,10 @@ func (s *VolumeService) CreateVolume(ctx context.Context, options client.VolumeC
func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force bool, user usertypes.Actor) error {
slog.DebugContext(ctx, "volume service: delete volume", "volume", name, "force", force, "user", user.ID)
+ // Clients may not know this environment's backup volume name, so its removal is refused here.
+ if s.IsBackupVolume(name) {
+ return common.ErrVolumeDeleteProtected
+ }
dockerClient, err := s.dockerService.GetClient(ctx)
if err != nil {
s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", name, name, user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force})
@@ -808,8 +812,13 @@ func (s *VolumeService) CountUsageFromSnapshot(dockerVolumes []volume.Volume, co
return counts
}
+// IsBackupVolume reports whether name is the volume that stores this environment's backups.
+func (s *VolumeService) IsBackupVolume(name string) bool {
+ return strings.EqualFold(strings.TrimSpace(name), strings.TrimSpace(s.backupVolumeName))
+}
+
func (s *VolumeService) isInternalVolumeInternal(v volumetypes.Volume) bool {
- if strings.EqualFold(strings.TrimSpace(v.Name), strings.TrimSpace(s.backupVolumeName)) {
+ if s.IsBackupVolume(v.Name) {
return true
}
diff --git a/backend/pkg/libarcane/edge/commands.go b/backend/pkg/libarcane/edge/commands.go
index c3709e921..dcebf9f08 100644
--- a/backend/pkg/libarcane/edge/commands.go
+++ b/backend/pkg/libarcane/edge/commands.go
@@ -221,6 +221,7 @@ var commandRoutes = []commandRoute{
{Method: http.MethodPost, PathPattern: "/api/environments/{id}/system/upgrade/all", CommandName: "system.upgrade.all"},
{Method: http.MethodGet, PathPattern: "/api/environments/{id}/system/upgrade/all/status", CommandName: "system.upgrade.all.status"},
{Method: http.MethodGet, PathPattern: "/api/environments/{id}/diagnostics/actors", CommandName: "diagnostics.actors"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/diagnostics/goroutines", CommandName: "diagnostics.goroutines"},
{Method: http.MethodGet, PathPattern: "/api/environments/{id}/swarm/services", CommandName: "swarm.service.list"},
{Method: http.MethodPost, PathPattern: "/api/environments/{id}/swarm/services", CommandName: "swarm.service.create"},
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 848261761..1f5fc300d 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -3345,6 +3345,11 @@
"diagnostics_leaks_count": "{count} leaked goroutines",
"diagnostics_error_scan_leaks": "Failed to scan for goroutine leaks",
"diagnostics_profile_goroutineleak": "Goroutine leaks",
+ "diagnostics_goroutines_hint": "Live goroutines grouped by identical stack. Each group is labeled with its entry point; expand it to see the full stack.",
+ "diagnostics_goroutines_summary": "{total} goroutines in {groups} groups",
+ "diagnostics_goroutines_filter_placeholder": "Filter by function or file…",
+ "diagnostics_goroutines_count": "Count",
+ "diagnostics_goroutines_entry_point": "Entry point",
"diagnostics_section_memory": "Memory / Heap",
"diagnostics_mem_in_use": "In use",
"diagnostics_mem_released": "Released",
@@ -3946,5 +3951,22 @@
"settings_section_avatars_description": "How user avatars are sourced and uploaded.",
"roles_details_section": "Role details",
"security_trivy_server_section": "Remote server",
- "security_trivy_resource_section": "Resource limits"
+ "security_trivy_resource_section": "Resource limits",
+ "all_environments_preview": "All environments (preview)",
+ "all_environments_preview_description": "Resource lists show and act on every enabled environment, with an Environment column.",
+ "all_environments_preview_turn_off": "Turn off preview",
+ "all_environments_request_failed": "Request to {environment} failed",
+ "all_environments_confirm_note": "This runs on all {count} environments.",
+ "all_environments_count": "{count} environments",
+ "all_environments_unavailable": "Not shown, these environments could not be loaded: {environments}",
+ "environment_colors": "Environment colors",
+ "environment_colors_description": "Colors for environment names in resource lists while the all environments preview is on.",
+ "environment_color_in_use": "That color is already used by another environment",
+ "environment_label_style": "Environment labels",
+ "environment_label_style_description": "Show the environment name in resource lists, or just its color dot with the name on hover.",
+ "environment_label_style_name": "Name",
+ "environment_label_style_dot": "Color dot",
+ "environment_column_short": "Env",
+ "previews": "Previews",
+ "previews_description": "Preview features are still in development. They may not work as expected and are subject to change or removal."
}
diff --git a/frontend/src/lib/components/accent-color/accent-color-picker.svelte b/frontend/src/lib/components/accent-color/accent-color-picker.svelte
index e2a9cb501..4133e9b52 100644
--- a/frontend/src/lib/components/accent-color/accent-color-picker.svelte
+++ b/frontend/src/lib/components/accent-color/accent-color-picker.svelte
@@ -4,44 +4,55 @@
import { Label } from '#lib/components/ui/label/index.js';
import * as RadioGroup from '#lib/components/ui/radio-group/index.js';
import { CheckIcon, AddIcon } from '#lib/icons/index.js';
- import { applyAccentColor, resolveThemePrimary } from '#lib/utils/theme.svelte.js';
+ import { resolveThemePrimary } from '#lib/utils/theme.svelte.js';
import CustomColorDialog from './custom-color.svelte';
+ type Swatch = { label: string; color: string };
+
+ const defaultColors: Swatch[] = [
+ { label: 'Purple', color: 'oklch(0.606 0.25 292.717)' },
+ { label: 'Rose', color: 'oklch(0.63 0.2 15)' },
+ { label: 'Orange', color: 'oklch(0.68 0.2 50)' },
+ { label: 'Amber', color: 'oklch(0.75 0.18 80)' },
+ { label: 'Green', color: 'oklch(0.65 0.2 150)' },
+ { label: 'Teal', color: 'oklch(0.6 0.15 180)' },
+ { label: 'Blue', color: 'oklch(0.6 0.2 240)' }
+ ];
+
let {
selectedColor = $bindable(),
previousColor,
disabled = false,
+ colors = defaultColors,
+ withTheme = true,
+ customColorTitle,
onSelect
}: {
selectedColor: string;
previousColor: string;
disabled?: boolean;
- /** Called whenever the user picks a different accent color. */
+ /** Preset swatches; defaults to the accent colors. */
+ colors?: Swatch[];
+ /** Offers the "inherit the application theme" swatch. */
+ withTheme?: boolean;
+ customColorTitle?: string;
+ /** Called whenever the user picks a different color. */
onSelect?: (color: string) => void;
} = $props();
let showCustomColorDialog = $state(false);
-
- const accentColors = [
- { label: 'Purple', color: 'oklch(0.606 0.25 292.717)' },
- { label: 'Rose', color: 'oklch(0.63 0.2 15)' },
- { label: 'Orange', color: 'oklch(0.68 0.2 50)' },
- { label: 'Amber', color: 'oklch(0.75 0.18 80)' },
- { label: 'Green', color: 'oklch(0.65 0.2 150)' },
- { label: 'Teal', color: 'oklch(0.6 0.15 180)' },
- { label: 'Blue', color: 'oklch(0.6 0.2 240)' }
- ];
+ // Several pickers can share a page, so radio IDs are scoped to this one.
+ const uid = $props.id();
const themePrimary = $derived(resolveThemePrimary(mode.current === 'dark'));
// Check if current accent color is a custom color (not in predefined list)
- let isCustomColor = $derived(selectedColor !== 'theme' && !accentColors.some((c) => c.color === selectedColor));
- let isPreviousColorCustom = $derived(previousColor !== 'theme' && !accentColors.some((c) => c.color === previousColor));
+ let isCustomColor = $derived(selectedColor !== 'theme' && !colors.some((c) => c.color === selectedColor));
+ let isPreviousColorCustom = $derived(previousColor !== 'theme' && !colors.some((c) => c.color === previousColor));
function handleAccentColorChange(accentValue: string) {
const storedValue = accentValue === 'theme' ? 'default' : accentValue;
selectedColor = accentValue;
- applyAccentColor(storedValue);
onSelect?.(storedValue);
}
</script>
@@ -55,8 +66,10 @@
}
}}
>
- {@render colorOption('Theme', 'theme', selectedColor === 'theme')}
- {#each accentColors as accent (accent.color)}
+ {#if withTheme}
+ {@render colorOption('Theme', 'theme', selectedColor === 'theme')}
+ {/if}
+ {#each colors as accent (accent.color)}
{@render colorOption(accent.label, accent.color, selectedColor === accent.color)}
{/each}
{#if isCustomColor || isPreviousColorCustom}
@@ -65,13 +78,13 @@
{@render colorOption('Custom', 'custom', false, true)}
</RadioGroup.Root>
-<CustomColorDialog bind:open={showCustomColorDialog} onApply={handleAccentColorChange} />
+<CustomColorDialog bind:open={showCustomColorDialog} title={customColorTitle} onApply={handleAccentColorChange} />
{#snippet colorOption(label: string, color: string, isSelected: boolean, isCustomColorSelection = false)}
<div class="group/item relative">
- <RadioGroup.Item id={color} value={color} class="sr-only" />
+ <RadioGroup.Item id={`${uid}-${color}`} value={color} class="sr-only" />
<Label
- for={color}
+ for={`${uid}-${color}`}
class={{
'cursor-pointer': !disabled,
'cursor-not-allowed': disabled,
diff --git a/frontend/src/lib/components/accent-color/custom-color.svelte b/frontend/src/lib/components/accent-color/custom-color.svelte
index d031491e2..ccf6d0cbd 100644
--- a/frontend/src/lib/components/accent-color/custom-color.svelte
+++ b/frontend/src/lib/components/accent-color/custom-color.svelte
@@ -8,9 +8,11 @@
let {
open = $bindable(false),
+ title = m.custom_accent_color(),
onApply
}: {
open: boolean;
+ title?: string;
onApply: (color: string) => void;
} = $props();
@@ -40,7 +42,7 @@
<Dialog.Root {open} {onOpenChange}>
<Dialog.Content class="max-w-md">
<Dialog.Header>
- <Dialog.Title><span class="flex items-center gap-2">{m.custom_accent_color()}</span></Dialog.Title>
+ <Dialog.Title><span class="flex items-center gap-2">{title}</span></Dialog.Title>
<Dialog.Description>
{m.custom_accent_color_description()}
</Dialog.Description>
diff --git a/frontend/src/lib/components/action-buttons.svelte b/frontend/src/lib/components/action-buttons.svelte
index a0b25d89e..555052d77 100644
--- a/frontend/src/lib/components/action-buttons.svelte
+++ b/frontend/src/lib/components/action-buttons.svelte
@@ -12,6 +12,7 @@
import { m } from '#lib/paraglide/messages.js';
import { containerService } from '#lib/services/container-service.js';
import { projectService } from '#lib/services/project-service.js';
+ import { settingsService } from '#lib/services/settings-service.js';
import settingsStore from '#lib/stores/config-store.svelte.js';
import { deployOptionsStore } from '#lib/stores/deploy-options.store.svelte.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
@@ -23,6 +24,7 @@
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { hasPermission } from '#lib/utils/auth.js';
import { isDepotBuildAvailable } from '#lib/utils/build-provider.js';
+ import { environmentHref } from '#lib/utils/environments.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import { attachProjectLogsToWatch } from '#lib/utils/watch-logs.js';
@@ -43,6 +45,7 @@
let {
id,
+ environmentId,
name,
type = 'container',
itemState = 'stopped',
@@ -62,6 +65,8 @@
onSaveChanges
}: {
id: string;
+ /** Environment that owns the resource; defaults to the selected one. */
+ environmentId?: string;
name?: string;
type?: TargetType;
itemState?: string;
@@ -118,8 +123,8 @@
mutationFn: () =>
tryCatch(
type === 'container'
- ? containerService.startContainer(id)
- : projectService.deployProject(id, 'up', deployOptionsStore.takeRequestOptions())
+ ? containerService.startContainer(id, currentEnvId)
+ : projectService.deployProject(id, 'up', deployOptionsStore.takeRequestOptions(), currentEnvId)
),
onMutate: () => setLoading('start', true),
onSettled: () => setLoading('start', false)
@@ -127,14 +132,24 @@
const stopMutation = createMutation(() => ({
mutationKey: ['action', 'stop', type, id],
- mutationFn: () => tryCatch(type === 'container' ? containerService.stopContainer(id) : projectService.downProject(id)),
+ mutationFn: (target: ActionTarget = actionTarget()) =>
+ tryCatch(
+ type === 'container'
+ ? containerService.stopContainer(target.id, target.environmentId)
+ : projectService.downProject(target.id, target.environmentId)
+ ),
onMutate: () => setLoading('stop', true),
onSettled: () => setLoading('stop', false)
}));
const restartMutation = createMutation(() => ({
mutationKey: ['action', 'restart', type, id],
- mutationFn: () => tryCatch(type === 'container' ? containerService.restartContainer(id) : projectService.restartProject(id)),
+ mutationFn: () =>
+ tryCatch(
+ type === 'container'
+ ? containerService.restartContainer(id, currentEnvId)
+ : projectService.restartProject(id, undefined, currentEnvId)
+ ),
onMutate: () => setLoading('restart', true),
onSettled: () => setLoading('restart', false)
}));
@@ -145,12 +160,12 @@
const redeployMutation = createMutation(() => ({
mutationKey: ['action', 'redeploy', type, id],
- mutationFn: ({ watch = false }: { watch?: boolean } = {}) =>
+ mutationFn: ({ watch = false, target }: { watch?: boolean; target: ActionTarget }) =>
tryCatch(
(type === 'container'
- ? containerService.redeployContainer(id)
+ ? containerService.redeployContainer(target.id, target.environmentId)
: projectService.deployProject(
- id,
+ target.id,
'redeploy',
(frame) => {
redeployActivityId = activityIdFromStreamFrame(frame) ?? redeployActivityId;
@@ -160,7 +175,8 @@
},
// Taken inside mutationFn so cancelling the confirm dialog doesn't
// spend the single-shot recreateVolumes opt-in.
- deployOptionsStore.takeRequestOptions()
+ deployOptionsStore.takeRequestOptions(),
+ target.environmentId
)) as Promise<ContainerDetailsDto | Project>
),
onMutate: () => {
@@ -172,11 +188,11 @@
const removeMutation = createMutation(() => ({
mutationKey: ['action', 'remove', type, id],
- mutationFn: ({ removeVolumes }: { removeVolumes: boolean }) =>
+ mutationFn: ({ removeVolumes, target }: { removeVolumes: boolean; target: ActionTarget }) =>
tryCatch(
type === 'container'
- ? containerService.deleteContainer(id, { volumes: removeVolumes })
- : projectService.destroyProject(id, removeVolumes)
+ ? containerService.deleteContainer(target.id, { volumes: removeVolumes, environmentId: target.environmentId })
+ : projectService.destroyProject(target.id, removeVolumes, target.environmentId)
),
onMutate: () => setLoading('remove', true),
onSettled: () => setLoading('remove', false)
@@ -199,7 +215,10 @@
// corresponding permission on the currently-selected environment. Project
// pull / build / redeploy all share the `projects:deploy` permission since
// they're stages of the deploy flow.
- const currentEnvId = $derived(environmentStore.selected?.id);
+ const currentEnvId = $derived(environmentId ?? environmentStore.selected?.id);
+ // Captured when an action starts: a confirmation or watch can outlive navigation to another resource.
+ type ActionTarget = { id: string; environmentId: string | undefined };
+ const actionTarget = (): ActionTarget => ({ id, environmentId: currentEnvId });
const canStart = $derived(
type === 'container' ? hasPermission('containers:start', currentEnvId) : hasPermission('projects:deploy', currentEnvId)
);
@@ -218,14 +237,6 @@
const canPull = $derived(type === 'project' && hasPermission('projects:deploy', currentEnvId));
const canBuild = $derived(type === 'project' && hasPermission('projects:deploy', currentEnvId));
const deployButtonLabel = $derived(projectHasBuildDirective ? m.compose_build_and_deploy() : m.common_up());
- const depotAvailable = $derived(isDepotBuildAvailable(settingsStore.current));
- const projectBuildProvider = $derived.by<'local' | 'depot'>(() => {
- const configuredProvider = (settingsStore.current?.buildProvider as 'local' | 'depot') ?? 'local';
- if (configuredProvider === 'depot' && !depotAvailable) {
- return 'local';
- }
- return configuredProvider;
- });
async function handleRefresh() {
if (!onRefresh) return;
@@ -234,6 +245,7 @@
function confirmAction(action: string) {
if (action === 'remove') {
+ const target = actionTarget();
openConfirmDialog({
title: type === 'project' ? m.compose_destroy() : m.common_confirm_removal_title(),
message:
@@ -246,7 +258,7 @@
action: async (checkboxStates) => {
const removeVolumes = checkboxStates['removeVolumes'] === true;
- const result = await removeMutation.mutateAsync({ removeVolumes });
+ const result = await removeMutation.mutateAsync({ removeVolumes, target });
await handleApiResultWithCallbacks({
result,
message: m.common_action_failed_with_type({
@@ -303,8 +315,9 @@
}
function confirmRedeploy(watch: boolean) {
+ const target = actionTarget();
if (hasUnsavedChanges) {
- confirmSaveBeforeDeploy(m.projects_save_and_redeploy(), () => handleRedeploy(watch));
+ confirmSaveBeforeDeploy(m.projects_save_and_redeploy(), () => handleRedeploy(watch, target));
return;
}
openConfirmDialog({
@@ -312,23 +325,25 @@
message: type === 'container' ? m.container_confirm_redeploy_message() : m.common_confirm_redeploy_message(),
confirm: {
label: m.common_redeploy(),
- action: () => handleRedeploy(watch)
+ action: () => handleRedeploy(watch, target)
}
});
}
- async function handleRedeploy(watch: boolean) {
+ async function handleRedeploy(watch: boolean, target: ActionTarget) {
const operationStartedAt = Math.floor(Temporal.Now.instant().epochMilliseconds / 1000);
+ // Follow-ups stay in the environment the redeploy ran in.
+ const operationEnvId = target.environmentId;
if (watch) {
operationWatchStore.start(`${m.common_redeploy()} — ${name ?? id}`);
}
- const result = await redeployMutation.mutateAsync({ watch });
+ const result = await redeployMutation.mutateAsync({ watch, target });
if (watch && result.error) {
operationWatchStore.fail(result.error.message || m.common_action_failed_with_type({ action: m.common_redeploy(), type }));
return;
}
if (watch) {
- enterInteractiveWatchInternal(operationStartedAt);
+ enterInteractiveWatchInternal(operationStartedAt, target);
}
await handleApiResultWithCallbacks({
result,
@@ -343,7 +358,8 @@
}
const containerData = data as ContainerDetailsDto;
if (type === 'container' && containerData?.id) {
- goto(`/containers/${containerData.id}`);
+ const path = `/containers/${containerData.id}`;
+ goto(operationEnvId ? environmentHref(path, operationEnvId) : path);
} else if (type === 'container') {
goto('/containers');
} else {
@@ -369,6 +385,7 @@
setLoading('start', true);
const operationStartedAt = Math.floor(Temporal.Now.instant().epochMilliseconds / 1000);
+ const target = actionTarget();
if (watch) {
operationWatchStore.start(`${deployButtonLabel} — ${name ?? id}`);
}
@@ -377,13 +394,14 @@
const operationResult1 = await tryCatch(
(async () => {
await projectService.deployProject(
- id,
+ target.id,
'up',
watch ? (frame: unknown) => operationWatchStore.onLine(frame) : () => {},
- options ?? deployOptionsStore.takeRequestOptions()
+ options ?? deployOptionsStore.takeRequestOptions(),
+ target.environmentId
);
if (watch) {
- enterInteractiveWatchInternal(operationStartedAt);
+ enterInteractiveWatchInternal(operationStartedAt, target);
}
await refreshAll();
itemState = 'running';
@@ -410,17 +428,17 @@
// output is followed by the containers' live logs — everything they wrote
// since the operation began — and dismissing the dialog is the Ctrl-C:
// the project is brought down.
- function enterInteractiveWatchInternal(operationStartedAt: number) {
+ function enterInteractiveWatchInternal(operationStartedAt: number, target: ActionTarget) {
operationWatchStore.append(`Attaching to ${name ?? id}`);
- const detach = attachProjectLogsToWatch(id, operationStartedAt);
+ const detach = attachProjectLogsToWatch(target.id, operationStartedAt, target.environmentId);
operationWatchStore.setOnClose(() => {
detach();
- void handleStop();
+ void handleStop(target);
});
}
- async function handleStop() {
- const result = await stopMutation.mutateAsync();
+ async function handleStop(target: ActionTarget = actionTarget()) {
+ const result = await stopMutation.mutateAsync(target);
await handleApiResultWithCallbacks({
result,
message: m.common_action_failed_with_type({ action: m.common_stop(), type }),
@@ -467,7 +485,11 @@
try {
const operationResult2 = await tryCatch(
(async () => {
- await projectService.pullProjectImages(id, watch ? (frame: unknown) => operationWatchStore.onLine(frame) : () => {});
+ await projectService.pullProjectImages(
+ id,
+ watch ? (frame: unknown) => operationWatchStore.onLine(frame) : () => {},
+ currentEnvId
+ );
await refreshAll();
onActionComplete(itemState);
})()
@@ -493,7 +515,13 @@
try {
const operationResult3 = await tryCatch(
(async () => {
- const buildProvider = projectBuildProvider;
+ // A project in another environment builds with that environment's provider settings.
+ const settings =
+ currentEnvId && currentEnvId !== environmentStore.selected?.id
+ ? await settingsService.getReadableSettings(currentEnvId)
+ : settingsStore.current;
+ const configuredProvider = (settings?.buildProvider as 'local' | 'depot') ?? 'local';
+ const buildProvider = configuredProvider === 'depot' && isDepotBuildAvailable(settings) ? 'depot' : 'local';
await projectService.buildProjectImages(
id,
{
@@ -501,7 +529,8 @@
push: buildProvider === 'depot',
load: buildProvider !== 'depot'
},
- () => {}
+ () => {},
+ currentEnvId
);
await refreshAll();
})()
diff --git a/frontend/src/lib/components/arcane-table/arcane-table-desktop-view.svelte b/frontend/src/lib/components/arcane-table/arcane-table-desktop-view.svelte
index 9627cd880..4d48fea96 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table-desktop-view.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table-desktop-view.svelte
@@ -229,7 +229,7 @@
rowMeasurement?: Attachment<HTMLTableRowElement>,
virtualIndex?: number
)}
- {@const rowId = row.original.id}
+ {@const rowId = row.id}
{@const isExpanded = expandedRows?.has(rowId) ?? false}
<Table.Row
{@attach rowMeasurement}
diff --git a/frontend/src/lib/components/arcane-table/arcane-table-mobile-view.svelte b/frontend/src/lib/components/arcane-table/arcane-table-mobile-view.svelte
index 64fb637d8..f9e0998aa 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table-mobile-view.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table-mobile-view.svelte
@@ -134,7 +134,7 @@
{/snippet}
{#snippet mobileRow(row: ArcaneRow<TData>)}
- {@const rowId = row.original.id}
+ {@const rowId = row.id}
{@const isExpanded = expandedRows?.has(rowId) ?? false}
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
diff --git a/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte b/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
index b650cd5d1..938f971a2 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
@@ -7,7 +7,9 @@
import * as Popover from '#lib/components/ui/popover/index.js';
import { ResetIcon, SearchIcon, FilterIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { cn } from '#lib/utils.js';
+ import { ENVIRONMENT_FILTER } from '#lib/utils/environments.js';
import { debounced } from '#lib/utils/ws.js';
import DataTableFacetedFilter from './arcane-table-filter.svelte';
@@ -63,6 +65,10 @@
}))
);
+ const environmentColumn = $derived(
+ table.getAllColumns().some((col) => col.id === ENVIRONMENT_FILTER) ? table.getColumn(ENVIRONMENT_FILTER) : undefined
+ );
+ const environmentFilterOptions = $derived(environmentStore.shown.map((env) => ({ label: env.name, value: env.id })));
const usageColumn = $derived(table.getAllColumns().some((col) => col.id === 'inUse') ? table.getColumn('inUse') : undefined);
const updatesColumn = $derived(
table.getAllColumns().some((col) => col.id === 'updates') ? table.getColumn('updates') : undefined
@@ -94,6 +100,7 @@
const hasFilterColumns = $derived(
!withoutFilters &&
[
+ environmentColumn,
typeColumn && typeColumnFilterOptions.length > 0,
tagsColumn && tagsColumnFilterOptions.length > 0,
labelColumn,
@@ -109,6 +116,9 @@
</script>
{#snippet filterList()}
+ {#if environmentColumn}
+ <DataTableFacetedFilter column={environmentColumn} title={m.resource_environment_cap()} options={environmentFilterOptions} />
+ {/if}
{#if typeColumn && typeColumnFilterOptions.length > 0}
<DataTableFacetedFilter column={typeColumn} title={m.common_type()} options={typeColumnFilterOptions} />
{/if}
diff --git a/frontend/src/lib/components/arcane-table/arcane-table.svelte b/frontend/src/lib/components/arcane-table/arcane-table.svelte
index 8fa664a9f..56c318d9e 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table.svelte
@@ -6,10 +6,16 @@
import type { Snippet } from 'svelte';
import type { Component } from 'svelte';
+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';
+ import * as Alert from '#lib/components/ui/alert/index.js';
import { TABLE_PAGE_SIZE_ALL } from '#lib/constants/table-pagination.js';
import { IsMobile } from '#lib/hooks/is-mobile.svelte.js';
+ import { AlertTriangleIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
+ import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+ import { rowKey, type EnvironmentFailure } from '#lib/utils/environments.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
import ArcaneTableCell from './arcane-table-cell.svelte';
import TableCheckbox from './arcane-table-checkbox.svelte';
@@ -82,7 +88,8 @@
expandedRowContent,
emptyState
}: {
- items: Paginated<TData>;
+ /** Merged lists carry the environments that could not be loaded. */
+ items: Paginated<TData> & { failedEnvironments?: EnvironmentFailure[] };
requestOptions: SearchPaginationSortRequest;
withoutSearch?: boolean;
withoutFilters?: boolean;
@@ -358,7 +365,7 @@
}
function onToggleAll(checked: boolean, table: ArcaneTable<TData>) {
- const pageIds = table.getRowModel().rows.map((r) => (r.original as TData).id);
+ const pageIds = table.getRowModel().rows.map((r) => r.id);
if (checked) {
const set = new Set([...(selectedIds ?? []), ...pageIds]);
selectedIds = Array.from(set);
@@ -396,7 +403,7 @@
cols.push({
id: 'select',
header: ({ table }) => {
- const pageIds = table.getRowModel().rows.map((r) => (r.original as TData).id);
+ const pageIds = table.getRowModel().rows.map((r) => r.id);
const selectedSet = new Set(selectedIds ?? []);
const total = pageIds.length;
const selectedOnPage = pageIds.filter((id) => selectedSet.has(id)).length;
@@ -411,7 +418,7 @@
});
},
cell: ({ row }) => {
- const id = (row.original as TData).id;
+ const id = row.id;
return renderComponent(TableCheckbox, {
checked: (selectedIds ?? []).includes(id),
onCheckedChange: (value, modifiers) => onToggleRow(!!value, id, modifiers),
@@ -520,7 +527,7 @@
// Stable row identity across server refreshes. Without this v9 keys rows by positional
// index, so every onRefresh fetch re-keys all rows and forces a full re-render; keying
// by the backing id lets unchanged rows (and their DOM/selection) be reused.
- getRowId: (row) => row.id,
+ getRowId: (row) => rowKey(row),
get data() {
return sortedData;
},
@@ -669,7 +676,7 @@
}))
);
- const rowIndex = $derived.by(() => new Map(table.getRowModel().rows.map((row, index) => [row.original.id, { row, index }])));
+ const rowIndex = $derived.by(() => new Map(table.getRowModel().rows.map((row, index) => [row.id, { row, index }])));
// Compute grouped rows when groupBy is provided
const effectiveGroupedRows = $derived.by((): GroupedData<TData>[] | null => {
@@ -702,7 +709,7 @@
// Get selection state for a group
function getGroupSelectionState(groupItems: TData[]): GroupSelectionState {
- const groupIds = groupItems.map((item) => item.id);
+ const groupIds = groupItems.map((item) => rowKey(item));
const selectedCount = groupIds.filter((id) => selectedIdSet.has(id)).length;
if (selectedCount === 0) return 'none';
@@ -712,7 +719,7 @@
// Toggle selection for all items in a group
function onToggleGroupSelection(groupItems: TData[]) {
- const groupIds = groupItems.map((item) => item.id);
+ const groupIds = groupItems.map((item) => rowKey(item));
const state = getGroupSelectionState(groupItems);
if (state === 'all') {
@@ -834,6 +841,29 @@
</div>
{/if}
+ {#if items.failedEnvironments?.length}
+ <div class="shrink-0 px-3 pt-3">
+ <Alert.Root variant="warning-subtle" size="sm" icon={AlertTriangleIcon}>
+ <div class="flex flex-wrap items-center justify-between gap-2">
+ <Alert.Description>
+ {m.all_environments_unavailable({
+ environments: items.failedEnvironments
+ .map(({ environment, message }) => `${environment.name} (${message})`)
+ .join(', ')
+ })}
+ </Alert.Description>
+ <ArcaneButton
+ action="refresh"
+ size="sm"
+ customLabel={m.common_retry()}
+ onClickPromise={async () =>
+ handleApiResultWithCallbacks({ result: await tryCatch(onRefresh(requestOptions)), message: m.common_failed() })}
+ />
+ </div>
+ </Alert.Root>
+ </div>
+ {/if}
+
{#if !isMobile.current}
<div
{@attach (node) => restoreScroll(node, 'desktop')}
diff --git a/frontend/src/lib/components/arcane-table/arcane-table.utils.ts b/frontend/src/lib/components/arcane-table/arcane-table.utils.ts
index b4c0e7110..2a53fe403 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table.utils.ts
+++ b/frontend/src/lib/components/arcane-table/arcane-table.utils.ts
@@ -5,6 +5,7 @@ import type { FilterMap, FilterValue } from '#lib/types/shared.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import type { TableDisplayEntry } from '#lib/types/table-display.js';
import type { PersistedPreferencesSnapshot } from '#lib/types/table-preferences.js';
+import { ENVIRONMENT_FILTER, environmentFilterIds, rowKey } from '#lib/utils/environments.js';
import type { CompactTablePrefs, GroupedData } from './arcane-table.types.svelte';
import { decodeFilters, decodeSort } from './arcane-table.types.svelte';
@@ -37,6 +38,7 @@ export function toFilterMap(filters: ColumnFiltersState): FilterMap {
* request `FilterMap`. Used to reflect externally-set `requestOptions.filters`
* (e.g. a clickable stat card) back into the faceted-filter UI. Values are kept
* as-is so they match the facet option `value` types (array, boolean, string).
+ * The environment filter keeps only shown environments, so a stale one never shows as active.
*/
export function fromFilterMap(map?: FilterMap): ColumnFiltersState {
if (!map) return [];
@@ -44,6 +46,11 @@ export function fromFilterMap(map?: FilterMap): ColumnFiltersState {
for (const [id, value] of Object.entries(map)) {
if (value === undefined || value === null) continue;
if (Array.isArray(value) && value.length === 0) continue;
+ if (id === ENVIRONMENT_FILTER) {
+ const environmentIds = environmentFilterIds(value);
+ if (environmentIds.length > 0) out.push({ id, value: environmentIds });
+ continue;
+ }
out.push({ id, value });
}
return out;
@@ -118,9 +125,9 @@ export function extractPersistedPreferences(
export function getTableRowsForItems<T extends RowData>(
rowIndex: ReadonlyMap<string, { row: ArcaneRow<T>; index: number }>,
- groupItems: Array<{ id: string }>
+ groupItems: Array<{ id: string; environmentId?: string }>
): ArcaneRow<T>[] {
- const ids = new Set(groupItems.map((item) => item.id));
+ const ids = new Set(groupItems.map((item) => rowKey(item)));
return Array.from(ids)
.flatMap((id) => {
const entry = rowIndex.get(id);
diff --git a/frontend/src/lib/components/arcane-table/cards/universal-mobile-card.svelte b/frontend/src/lib/components/arcane-table/cards/universal-mobile-card.svelte
index 41f78fc3e..a58fd9cab 100644
--- a/frontend/src/lib/components/arcane-table/cards/universal-mobile-card.svelte
+++ b/frontend/src/lib/components/arcane-table/cards/universal-mobile-card.svelte
@@ -1,8 +1,11 @@
<script lang="ts" generics="T">
import type { Snippet, Component } from 'svelte';
+ import EnvironmentCell from '#lib/components/arcane-table/cells/environment-cell.svelte';
import { Badge } from '#lib/components/ui/badge/index.js';
import * as Card from '#lib/components/ui/card/index.js';
+ import { m } from '#lib/paraglide/messages.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { cn } from '#lib/utils.js';
type IconVariant = 'emerald' | 'red' | 'amber' | 'blue' | 'purple' | 'gray' | 'sky' | 'orange';
@@ -83,7 +86,16 @@
resolvedIcon?.imageUrl && resolvedIcon.imageUrl !== errorImageUrl ? resolvedIcon.imageUrl : null
);
- const visibleFields = $derived(fields.filter((f) => f.show !== false));
+ // Merged rows carry their environment; show it while several environments are shown.
+ const environmentId = $derived(
+ environmentStore.shown.length > 1 ? (item as { environmentId?: string }).environmentId : undefined
+ );
+ const environmentField = $derived<FieldDefinition<T>[]>(
+ environmentId
+ ? [{ label: m.resource_environment_cap(), getValue: () => environmentId, type: 'component', component: EnvironmentValue }]
+ : []
+ );
+ const visibleFields = $derived([...environmentField, ...fields.filter((f) => f.show !== false)]);
const subtitleValue = $derived(subtitle?.(item));
const hasSubtitle = $derived(!!subtitleValue);
@@ -116,6 +128,10 @@
}
</script>
+{#snippet EnvironmentValue(value: string)}
+ <EnvironmentCell {value} />
+{/snippet}
+
{#snippet FieldValue(field: FieldDefinition<T>, value: any, isCompact: boolean)}
{#if field.type === 'badge' && field.badgeVariant}
<Badge variant={field.badgeVariant} size="sm" minWidth="20">{String(value)}</Badge>
diff --git a/frontend/src/lib/components/arcane-table/cells/environment-cell.svelte b/frontend/src/lib/components/arcane-table/cells/environment-cell.svelte
new file mode 100644
index 000000000..100c7316c
--- /dev/null
+++ b/frontend/src/lib/components/arcane-table/cells/environment-cell.svelte
@@ -0,0 +1,44 @@
+<script lang="ts">
+ import * as ArcaneTooltip from '#lib/components/arcane-tooltip/index.js';
+ import { EnvironmentsIcon, RemoteEnvironmentIcon } from '#lib/icons/index.js';
+ import { environmentColor } from '#lib/stores/environment-colors.store.svelte.js';
+ import { allEnvironmentsPreview, LOCAL_DOCKER_ENVIRONMENT_ID } from '#lib/stores/environment.store.svelte.js';
+ import userStore from '#lib/stores/user-store.svelte.js';
+ import { environmentName } from '#lib/utils/environments.js';
+
+ let { value }: { value: unknown } = $props();
+
+ const environmentId = $derived(String(value ?? ''));
+ const color = $derived(allEnvironmentsPreview.current ? environmentColor(environmentId) : undefined);
+ const showDot = $derived(!!color && userStore.current?.preferences?.environmentLabelStyle === 'dot');
+ const Icon = $derived(environmentId === LOCAL_DOCKER_ENVIRONMENT_ID ? EnvironmentsIcon : RemoteEnvironmentIcon);
+</script>
+
+{#if showDot}
+ <ArcaneTooltip.Root>
+ <!-- A plain span: the default trigger wrapper is interactive and would swallow the row click. -->
+ <ArcaneTooltip.Trigger>
+ {#snippet child({ props })}
+ <span {...props} class="inline-flex size-4 items-center justify-center" aria-label={environmentName(environmentId)}>
+ <span class="size-2.5 rounded-full bg-(--environment-color)" style:--environment-color={color}></span>
+ </span>
+ {/snippet}
+ </ArcaneTooltip.Trigger>
+ <ArcaneTooltip.Content>{environmentName(environmentId)}</ArcaneTooltip.Content>
+ </ArcaneTooltip.Root>
+{:else}
+ <!-- Mixing toward the foreground keeps any picked color readable in light and dark themes. -->
+ <span
+ class={['inline-flex min-w-0 items-center gap-1.5 text-sm', color ? 'environment-colored' : 'text-muted-foreground']}
+ style:--environment-color={color}
+ >
+ <Icon class="size-3.5 shrink-0" />
+ <span class="truncate">{environmentName(environmentId)}</span>
+ </span>
+{/if}
+
+<style>
+ .environment-colored {
+ color: color-mix(in srgb, var(--environment-color) 75%, var(--foreground));
+ }
+</style>
diff --git a/frontend/src/lib/components/arcane-table/environment-column.ts b/frontend/src/lib/components/arcane-table/environment-column.ts
new file mode 100644
index 000000000..ae4e2a513
--- /dev/null
+++ b/frontend/src/lib/components/arcane-table/environment-column.ts
@@ -0,0 +1,24 @@
+import { m } from '#lib/paraglide/messages.js';
+import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+import userStore from '#lib/stores/user-store.svelte.js';
+import { ENVIRONMENT_FILTER } from '#lib/utils/environments.js';
+
+import type { ColumnSpec } from './arcane-table.types.svelte';
+import EnvironmentCell from './cells/environment-cell.svelte';
+
+/** Environment column for merged lists; empty while one environment is shown. */
+export function environmentColumns<T extends { environmentId?: string }>(): ColumnSpec<T>[] {
+ if (environmentStore.shown.length < 2) return [];
+ // A color dot needs no more room than a short header.
+ const dots = userStore.current?.preferences?.environmentLabelStyle === 'dot';
+ return [
+ {
+ id: ENVIRONMENT_FILTER,
+ accessorFn: (row) => row.environmentId,
+ title: dots ? m.environment_column_short() : m.resource_environment_cap(),
+ sortable: true,
+ width: dots ? 'min' : undefined,
+ cellComponent: EnvironmentCell
+ }
+ ];
+}
diff --git a/frontend/src/lib/components/compose/compose-editor-wrapper.svelte b/frontend/src/lib/components/compose/compose-editor-wrapper.svelte
index 1d6e0a5a4..d347ec739 100644
--- a/frontend/src/lib/components/compose/compose-editor-wrapper.svelte
+++ b/frontend/src/lib/components/compose/compose-editor-wrapper.svelte
@@ -10,7 +10,7 @@
import { tryCatch } from '#lib/utils/try-catch.js';
let {
- projectId,
+ projectHref,
projectName,
gitOpsManagedBy = undefined,
fileTitle,
@@ -19,7 +19,7 @@
onSave,
children
}: {
- projectId: string;
+ projectHref: string;
projectName: string;
gitOpsManagedBy?: string;
fileTitle: string;
@@ -87,11 +87,6 @@
{#if !isReadOnly}
<ArcaneButton action="save" loading={isSaving} disabled={!isDirty} onclick={handleSave} />
{/if}
- <ArcaneButton
- action="base"
- href="/projects/{projectId}"
- icon={ExternalLinkIcon}
- customLabel={m.container_compose_view_project()}
- />
+ <ArcaneButton action="base" href={projectHref} icon={ExternalLinkIcon} customLabel={m.container_compose_view_project()} />
</div>
</div>
diff --git a/frontend/src/lib/components/containers/container-form/container-form.svelte b/frontend/src/lib/components/containers/container-form/container-form.svelte
index 7cec88c67..60921066d 100644
--- a/frontend/src/lib/components/containers/container-form/container-form.svelte
+++ b/frontend/src/lib/components/containers/container-form/container-form.svelte
@@ -21,7 +21,6 @@
import { imageService } from '#lib/services/image-service.js';
import { networkService } from '#lib/services/network-service.js';
import { volumeService } from '#lib/services/volume-service.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { ImageSearchResultDto } from '#lib/types/docker.js';
import { preventDefault, createForm } from '#lib/utils/settings.svelte.js';
import { tryCatch } from '#lib/utils/try-catch.js';
@@ -34,9 +33,11 @@
rows = $bindable(),
submitting = false,
cancelHref = '/containers',
+ environmentId,
onSubmit
}: {
mode: 'create' | 'edit';
+ environmentId: string;
form: ReturnType<typeof createForm<typeof containerFormSchema>>;
rows: ContainerFormRows;
submitting?: boolean;
@@ -47,7 +48,7 @@
// The form instance is created once by the page and never swapped.
// svelte-ignore state_referenced_locally
const inputs = form.inputs;
- const envId = $derived(environmentStore.selected?.id || '0');
+ const envId = $derived(environmentId);
let selectedTab = $state('general');
@@ -76,11 +77,11 @@
const listOptions = { pagination: { page: 1, limit: 500 } };
const volumesQuery = createQuery(() => ({
queryKey: queryKeys.volumes.table(envId, listOptions),
- queryFn: () => volumeService.getVolumes(listOptions)
+ queryFn: () => volumeService.getVolumesForEnvironment(envId, listOptions)
}));
const networksQuery = createQuery(() => ({
queryKey: queryKeys.networks.list(envId, listOptions),
- queryFn: () => networkService.getNetworks(listOptions)
+ queryFn: () => networkService.getNetworksForEnvironment(envId, listOptions)
}));
const volumeNames = $derived((volumesQuery.data?.data ?? []).map((volume) => volume.name));
@@ -101,7 +102,7 @@
imageSearchTimer = setTimeout(async () => {
const operationResult1 = await tryCatch(
(async () => {
- imageSuggestions = (await imageService.searchImages(term)).slice(0, 6);
+ imageSuggestions = (await imageService.searchImages(term, envId)).slice(0, 6);
})()
);
if (operationResult1.error !== null) {
diff --git a/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte b/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte
index d0da504ae..7d5e28258 100644
--- a/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte
@@ -14,12 +14,13 @@
import { queryKeys } from '#lib/query/query-keys.js';
import { environmentManagementService } from '#lib/services/env-mgmt-service.js';
import settingsStore from '#lib/stores/config-store.svelte.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+ import { allEnvironmentsPreview, environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { Environment } from '#lib/types/environment.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { cn } from '#lib/utils.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { tryCatch } from '#lib/utils/try-catch.js';
+ import { saveUserPreferences } from '#lib/utils/user-preferences.js';
import { debounced } from '#lib/utils/ws.js';
type Props = {
@@ -279,9 +280,24 @@
</div>
{:else}
<div class="space-y-1">
+ {#if allEnvironmentsPreview.current}
+ <div class="flex w-full items-center gap-3 rounded-lg border border-primary bg-primary/10 p-3 font-medium">
+ <div class="flex size-8 shrink-0 items-center justify-center rounded-md border border-primary bg-primary">
+ <EnvironmentsIcon class="size-4 text-primary-foreground" />
+ </div>
+ <span class="flex-1 truncate">{m.all_environments()}</span>
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ size="sm"
+ customLabel={m.all_environments_preview_turn_off()}
+ onclick={() => saveUserPreferences({ allEnvironmentsPreview: false })}
+ />
+ </div>
+ {/if}
{#each environments as env (env.id)}
- {@const isActive = environmentStore.selected?.id === env.id}
- {@const isDisabled = !env.enabled}
+ {@const isActive = !allEnvironmentsPreview.current && environmentStore.selected?.id === env.id}
+ {@const isDisabled = !env.enabled || allEnvironmentsPreview.current}
<div
class={cn(
'flex items-center gap-2 rounded-lg border p-1 transition-colors',
diff --git a/frontend/src/lib/components/dialogs/image-registry-search-dialog.svelte b/frontend/src/lib/components/dialogs/image-registry-search-dialog.svelte
index cb0ed5c18..a87ed7339 100644
--- a/frontend/src/lib/components/dialogs/image-registry-search-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/image-registry-search-dialog.svelte
@@ -2,6 +2,7 @@
import { toast } from 'svelte-sonner';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
+ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';
import * as InputGroup from '#lib/components/ui/input-group/index.js';
import { Label } from '#lib/components/ui/label/index.js';
import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';
@@ -9,6 +10,7 @@
import { m } from '#lib/paraglide/messages.js';
import { imageService } from '#lib/services/image-service.js';
import type { ImageSearchResultDto } from '#lib/types/docker.js';
+ import { destinationEnvironmentId } from '#lib/utils/environments.js';
import { tryCatch } from '#lib/utils/try-catch.js';
type Props = {
@@ -25,6 +27,8 @@
let hasSearched = $state(false);
let isSearching = $state(false);
let pullingImageName = $state<string | null>(null);
+ let pickedEnvironmentId = $state('');
+ const environmentId = $derived(destinationEnvironmentId(pickedEnvironmentId, 'images:pull'));
const normalizedTag = $derived(tag.trim() || 'latest');
const canSearch = $derived(query.trim().length > 0 && !isSearching);
@@ -34,6 +38,7 @@
tag = 'latest';
results = [];
hasSearched = false;
+ pickedEnvironmentId = '';
}
function handleOpenChange(nextOpen: boolean) {
@@ -56,7 +61,7 @@
try {
const operationResult1 = await tryCatch(
(async () => {
- results = await imageService.searchImages(term);
+ results = await imageService.searchImages(term, environmentId);
})()
);
if (operationResult1.error !== null) {
@@ -82,11 +87,12 @@
if (!imageRef || pullingImageName) return;
pullingImageName = imageRef;
+ const targetEnvironmentId = environmentId;
open = false;
onOpenChange?.(false);
resetDialog();
- const result = await imageService.pullImageStream(imageRef);
+ const result = await imageService.pullImageStream(imageRef, undefined, targetEnvironmentId);
pullingImageName = null;
if (result.cancelled) return;
if (!result.success) {
@@ -110,6 +116,10 @@
>
{#snippet children()}
<div class="grid gap-4 py-4">
+ <EnvironmentDestinationSelect
+ bind:value={() => environmentId, (value) => (pickedEnvironmentId = value)}
+ permission="images:pull"
+ />
<div class="grid gap-3 sm:grid-cols-content-36-action">
<div class="space-y-2">
<Label for="image-registry-search-query">{m.images_search_query()}</Label>
diff --git a/frontend/src/lib/components/form/environment-destination-select.svelte b/frontend/src/lib/components/form/environment-destination-select.svelte
new file mode 100644
index 000000000..be40ff04c
--- /dev/null
+++ b/frontend/src/lib/components/form/environment-destination-select.svelte
@@ -0,0 +1,69 @@
+<script lang="ts">
+ import { goto } from '$app/navigation';
+ import { page } from '$app/state';
+
+ import SelectWithLabel from '#lib/components/form/select-with-label.svelte';
+ import { m } from '#lib/paraglide/messages.js';
+ import { environmentStore, type EnvironmentRef } from '#lib/stores/environment.store.svelte.js';
+ import { hasPermission } from '#lib/utils/auth.js';
+
+ // Picks one environment while several are shown. A bound `value` is a create's destination and never changes
+ // the selected environment; callers derive it with destinationEnvironmentId, so it is always a permitted option.
+ // Without `value`, pages that show one environment at a time pick the route's or selected one, or the first option.
+ let {
+ value = $bindable(),
+ permission,
+ environments
+ }: { value?: string; permission?: string; environments?: EnvironmentRef[] } = $props();
+
+ const selectsEnvironment = $derived(value === undefined);
+ const options = $derived(
+ (environments ?? environmentStore.shown)
+ .filter((env) => !permission || hasPermission(permission, env.id))
+ .map((env) => ({ value: env.id, label: env.name }))
+ );
+ // Routes under /environments/[id] show that environment, which can differ from the selected one.
+ const routeEnvironmentId = $derived(page.route.id?.includes('/environments/[id]') ? page.params.id : undefined);
+ const pageEnvironmentId = $derived(
+ options.find((option) => option.value === (routeEnvironmentId ?? environmentStore.selected?.id))?.value ??
+ options[0]?.value ??
+ ''
+ );
+
+ function selectEnvironment(environmentId: string) {
+ const environment = environmentStore.available.find((env) => env.id === environmentId);
+ if (!environment) return;
+ // Picking the selected environment changes nothing in the store, so move the route to it directly.
+ if (routeEnvironmentId && environment.id === environmentStore.selected?.id) {
+ const pathname = page.url.pathname.replace(
+ `/environments/${encodeURIComponent(routeEnvironmentId)}`,
+ `/environments/${encodeURIComponent(environment.id)}`
+ );
+ void goto(`${pathname}${page.url.search}${page.url.hash}`);
+ return;
+ }
+ void environmentStore.setEnvironment(environment);
+ }
+</script>
+
+{#if environmentStore.shown.length > 1}
+ {#if selectsEnvironment}
+ <SelectWithLabel
+ id="page-environment"
+ label={m.resource_environment_cap()}
+ bind:value={() => pageEnvironmentId, selectEnvironment}
+ {options}
+ hideLabel
+ compact
+ />
+ {:else}
+ <div class="max-w-sm">
+ <SelectWithLabel
+ id="destination-environment"
+ label={m.resource_environment_cap()}
+ bind:value={() => value ?? '', (next) => (value = next)}
+ {options}
+ />
+ </div>
+ {/if}
+{/if}
diff --git a/frontend/src/lib/components/image-update-item.svelte b/frontend/src/lib/components/image-update-item.svelte
index d8beb323f..22f526b62 100644
--- a/frontend/src/lib/components/image-update-item.svelte
+++ b/frontend/src/lib/components/image-update-item.svelte
@@ -33,6 +33,8 @@
isLoadingInBackground?: boolean;
imageId?: string;
containerId?: string;
+ /** Environment that owns the image; defaults to the selected one. */
+ environmentId?: string;
tagUpdates?: boolean;
/** Image reference for ref-scoped checks when no local image ID exists (e.g. not-pulled refs) */
imageRef?: string;
@@ -51,6 +53,7 @@
isLoadingInBackground = false,
imageId,
containerId,
+ environmentId: rowEnvironmentId,
tagUpdates = false,
imageRef,
repo,
@@ -67,7 +70,7 @@
}
const imageUpdateQuery = createQuery<ImageUpdateData>(() => {
- const environmentId = environmentStore.selected?.id || '0';
+ const environmentId = rowEnvironmentId ?? (environmentStore.selected?.id || '0');
const target = { imageId, containerId, imageRef, tagUpdates };
let key = target.imageId || target.imageRef || '';
if (target.containerId) key = `container:${target.containerId}`;
@@ -76,10 +79,10 @@
queryFn: async () => {
let result: ImageUpdateInfoDto | undefined;
if (target.imageId && !(target.containerId && target.imageRef)) {
- result = await imageService.checkImageUpdateByID(target.imageId);
+ result = await imageService.checkImageUpdateByID(target.imageId, environmentId);
} else {
const ref = target.imageRef ?? '';
- result = (await imageService.checkMultipleImages([ref]))[ref];
+ result = (await imageService.checkMultipleImages([ref], environmentId))[ref];
}
if (!result) throw new Error(m.images_update_check_failed());
if (target.containerId) {
diff --git a/frontend/src/lib/components/logs/log-viewer.svelte b/frontend/src/lib/components/logs/log-viewer.svelte
index e631d7e82..b6a6720f9 100644
--- a/frontend/src/lib/components/logs/log-viewer.svelte
+++ b/frontend/src/lib/components/logs/log-viewer.svelte
@@ -24,6 +24,8 @@
interface Props {
class?: string;
containerId?: string | null;
+ /** Environment that owns the resource; defaults to the selected one. */
+ environmentId?: string;
projectId?: string | null;
serviceId?: string | null;
type?: 'container' | 'project' | 'service';
@@ -44,6 +46,7 @@
let {
class: className,
containerId = null,
+ environmentId,
projectId = null,
serviceId = null,
type = 'container',
@@ -162,10 +165,12 @@
let currentStreamKey: string | null = null;
let streamSession = 0;
let currentStreamSession = 0;
+ // The environment is part of the key: the same ID in another environment is a different stream.
function streamKey() {
- if (type === 'project') return projectId ? `project:${projectId}` : null;
- if (type === 'service') return serviceId ? `svc:${serviceId}` : null;
- return containerId ? `ctr:${containerId}` : null;
+ const env = environmentId ?? '';
+ if (type === 'project') return projectId ? `${env}:project:${projectId}` : null;
+ if (type === 'service') return serviceId ? `${env}:svc:${serviceId}` : null;
+ return containerId ? `${env}:ctr:${containerId}` : null;
}
const humanType = $derived(type === 'project' ? m.project() : type === 'service' ? m.swarm_service() : m.container());
@@ -178,7 +183,7 @@
}
async function buildLogWsEndpoint(): Promise<string> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const envId = environmentId ?? (await environmentStore.getCurrentEnvironmentId());
const basePath =
type === 'project'
? `/api/environments/${envId}/ws/projects/${projectId}/logs`
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 047aa4ab0..7e345699a 100644
--- a/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte
+++ b/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte
@@ -14,7 +14,7 @@
} from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import settingsStore from '#lib/stores/config-store.svelte.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+ import { allEnvironmentsPreview, environmentStore } from '#lib/stores/environment.store.svelte.js';
import userStore from '#lib/stores/user-store.svelte.js';
import type { User } from '#lib/types/auth.js';
import { cn } from '#lib/utils.js';
@@ -87,34 +87,36 @@
{#if userCardExpanded}
<div class="space-y-4 border-t border-border/20 bg-muted/10 p-4">
- <IfPermitted adminOnly>
- <button
- class="flex w-full items-center gap-3 rounded-2xl border border-border/20 bg-background/50 p-4 text-left transition-colors hover:bg-muted/30"
- onclick={() => (envDialogOpen = true)}
- >
- <div class="flex aspect-square size-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
- {#if environmentStore.selected?.id === '0'}
- <EnvironmentsIcon class="size-4" />
- {:else}
- <RemoteEnvironmentIcon class="size-4" />
- {/if}
- </div>
- <div class="min-w-0 flex-1">
- <div class="text-xs font-medium tracking-widest text-muted-foreground/70 uppercase">
- {m.resource_environment_cap()}
- </div>
- <div class="text-sm font-medium text-foreground">
- {environmentStore.selected ? environmentStore.selected.name : m.sidebar_no_environment()}
+ {#if !allEnvironmentsPreview.current}
+ <IfPermitted adminOnly>
+ <button
+ class="flex w-full items-center gap-3 rounded-2xl border border-border/20 bg-background/50 p-4 text-left transition-colors hover:bg-muted/30"
+ onclick={() => (envDialogOpen = true)}
+ >
+ <div class="flex aspect-square size-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
+ {#if environmentStore.selected?.id === '0'}
+ <EnvironmentsIcon class="size-4" />
+ {:else}
+ <RemoteEnvironmentIcon class="size-4" />
+ {/if}
</div>
- {#if environmentStore.selected}
- <div class="truncate text-xs text-muted-foreground/60">
- {getConnectionString()}
+ <div class="min-w-0 flex-1">
+ <div class="text-xs font-medium tracking-widest text-muted-foreground/70 uppercase">
+ {m.resource_environment_cap()}
</div>
- {/if}
- </div>
- <ArrowRightIcon class="size-5 shrink-0 text-muted-foreground/60" />
- </button>
- </IfPermitted>
+ <div class="text-sm font-medium text-foreground">
+ {environmentStore.selected ? environmentStore.selected.name : m.sidebar_no_environment()}
+ </div>
+ {#if environmentStore.selected}
+ <div class="truncate text-xs text-muted-foreground/60">
+ {getConnectionString()}
+ </div>
+ {/if}
+ </div>
+ <ArrowRightIcon class="size-5 shrink-0 text-muted-foreground/60" />
+ </button>
+ </IfPermitted>
+ {/if}
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
<div class="rounded-2xl border border-border/20 bg-background/50 p-4">
diff --git a/frontend/src/lib/components/project-update-item.svelte b/frontend/src/lib/components/project-update-item.svelte
index d5cde8e9e..42d381419 100644
--- a/frontend/src/lib/components/project-update-item.svelte
+++ b/frontend/src/lib/components/project-update-item.svelte
@@ -24,13 +24,15 @@
interface Props {
updateInfo?: ProjectUpdateInfo;
+ /** Environment that owns the project; defaults to the selected one. */
+ environmentId?: string;
class?: string;
onCheck?: () => void | Promise<void>;
checking?: boolean;
disabled?: boolean;
}
- let { updateInfo, class: className = '', onCheck, checking = false, disabled = false }: Props = $props();
+ let { updateInfo, environmentId, class: className = '', onCheck, checking = false, disabled = false }: Props = $props();
let isOpen = $state(false);
const status = $derived(getProjectUpdateStatus(updateInfo));
@@ -170,7 +172,7 @@
{#snippet refRow(imageRef: string)}
{@const parsed = parseImageRef(imageRef)}
<div class="flex items-center rounded-md bg-muted px-2 py-1">
- <ImageUpdateItem updateInfo={updateInfoByRef[imageRef]} {imageRef} repo={parsed.repo} tag={parsed.tag} />
+ <ImageUpdateItem updateInfo={updateInfoByRef[imageRef]} {imageRef} repo={parsed.repo} tag={parsed.tag} {environmentId} />
<span class="min-w-0 flex-1 font-mono text-xs break-all text-foreground">{imageRef}</span>
</div>
{/snippet}
@@ -291,7 +293,12 @@
{@const parsed = parseImageRef(service.imageRef)}
<div class="rounded-md bg-muted px-2 py-1.5">
<div class="flex items-center gap-2">
- <ImageUpdateItem updateInfo={service.updateInfo ?? undefined} repo={parsed.repo} tag={parsed.tag} />
+ <ImageUpdateItem
+ updateInfo={service.updateInfo ?? undefined}
+ repo={parsed.repo}
+ tag={parsed.tag}
+ {environmentId}
+ />
<span class="min-w-0 flex-1 text-xs font-medium break-all">{serviceName}</span>
</div>
<div class="mt-1 font-mono text-2xs break-all text-muted-foreground">{service.imageRef}</div>
diff --git a/frontend/src/lib/components/sheets/create-network-sheet.svelte b/frontend/src/lib/components/sheets/create-network-sheet.svelte
index a128e63fc..21ef2ccd8 100644
--- a/frontend/src/lib/components/sheets/create-network-sheet.svelte
+++ b/frontend/src/lib/components/sheets/create-network-sheet.svelte
@@ -2,6 +2,7 @@
import { z } from 'zod/v4';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
+ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';
import SheetFooterActions from '#lib/components/sheets/sheet-footer-actions.svelte';
import * as Accordion from '#lib/components/ui/accordion/index.js';
import { Checkbox } from '#lib/components/ui/checkbox/index.js';
@@ -12,6 +13,7 @@
import { CloseIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import type { IPAMConfig, NetworkCreateOptions } from '#lib/types/docker.js';
+ import { destinationEnvironmentId } from '#lib/utils/environments.js';
import { parseKeyValuePairs } from '#lib/utils/form-parsers.js';
import { createForm, preventDefault } from '#lib/utils/settings.svelte.js';
@@ -19,12 +21,15 @@
type CreateNetworkFormProps = {
open: boolean;
- onSubmit: (name: string, options: NetworkCreateOptions) => void;
+ onSubmit: (name: string, options: NetworkCreateOptions, environmentId: string) => void;
isLoading: boolean;
};
let { open = $bindable(false), onSubmit, isLoading }: CreateNetworkFormProps = $props();
+ let pickedEnvironmentId = $state('');
+ const environmentId = $derived(destinationEnvironmentId(pickedEnvironmentId, 'networks:create'));
+
const drivers = [
{ value: 'bridge', label: m.bridge() },
{ value: 'overlay', label: m.networks_overlay() },
@@ -122,13 +127,14 @@
}
}
- onSubmit(data.networkName.trim(), options);
+ onSubmit(data.networkName.trim(), options, environmentId);
}
function handleOpenChange(newOpenState: boolean) {
open = newOpenState;
if (!newOpenState) {
// Reset form data
+ pickedEnvironmentId = '';
inputs.networkName.value = '';
inputs.networkDriver.value = 'bridge';
inputs.checkDuplicate.value = true;
@@ -154,6 +160,10 @@
>
{#snippet children()}
<form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-6">
+ <EnvironmentDestinationSelect
+ bind:value={() => environmentId, (value) => (pickedEnvironmentId = value)}
+ permission="networks:create"
+ />
<div class="space-y-2">
<Label for="network-name">{m.network_name_label()}</Label>
<Input
diff --git a/frontend/src/lib/components/sheets/create-volume-sheet.svelte b/frontend/src/lib/components/sheets/create-volume-sheet.svelte
index 48e2c6c1e..c2e420109 100644
--- a/frontend/src/lib/components/sheets/create-volume-sheet.svelte
+++ b/frontend/src/lib/components/sheets/create-volume-sheet.svelte
@@ -1,12 +1,14 @@
<script lang="ts">
import { z } from 'zod/v4';
+ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';
import FormInput from '#lib/components/form/form-input.svelte';
import SheetFooterActions from '#lib/components/sheets/sheet-footer-actions.svelte';
import * as Accordion from '#lib/components/ui/accordion/index.js';
import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';
import { m } from '#lib/paraglide/messages.js';
import type { VolumeCreateRequest } from '#lib/types/docker.js';
+ import { destinationEnvironmentId } from '#lib/utils/environments.js';
import { parseKeyValuePairs } from '#lib/utils/form-parsers.js';
import { createForm, preventDefault } from '#lib/utils/settings.svelte.js';
@@ -14,12 +16,15 @@
type CreateVolumeFormProps = {
open: boolean;
- onSubmit: (data: VolumeCreateRequest) => void;
+ onSubmit: (data: VolumeCreateRequest, environmentId: string) => void;
isLoading: boolean;
};
let { open = $bindable(false), onSubmit, isLoading }: CreateVolumeFormProps = $props();
+ let pickedEnvironmentId = $state('');
+ const environmentId = $derived(destinationEnvironmentId(pickedEnvironmentId, 'volumes:create'));
+
const drivers = [
{ value: 'local', label: m.local() },
{ value: 'nfs', label: m.volume_driver_nfs() },
@@ -59,12 +64,13 @@
labels: Object.keys(labels).length ? labels : undefined
};
- onSubmit(volumeOptions);
+ onSubmit(volumeOptions, environmentId);
}
function handleOpenChange(newOpenState: boolean) {
open = newOpenState;
if (!newOpenState) {
+ pickedEnvironmentId = '';
inputs.volumeName.value = '';
inputs.volumeDriver.value = 'local';
inputs.volumeOptText.value = '';
@@ -83,6 +89,10 @@
>
{#snippet children()}
<form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-6">
+ <EnvironmentDestinationSelect
+ bind:value={() => environmentId, (value) => (pickedEnvironmentId = value)}
+ permission="volumes:create"
+ />
<FormInput
label={m.volume_name_label()}
id="volume-name"
diff --git a/frontend/src/lib/components/sheets/image-pull-sheet.svelte b/frontend/src/lib/components/sheets/image-pull-sheet.svelte
index 627e36f4b..86bd910fd 100644
--- a/frontend/src/lib/components/sheets/image-pull-sheet.svelte
+++ b/frontend/src/lib/components/sheets/image-pull-sheet.svelte
@@ -2,11 +2,13 @@
import { toast } from 'svelte-sonner';
import { z } from 'zod/v4';
+ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';
import FormInput from '#lib/components/form/form-input.svelte';
import SheetFooterActions from '#lib/components/sheets/sheet-footer-actions.svelte';
import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';
import { m } from '#lib/paraglide/messages.js';
import { imageService } from '#lib/services/image-service.js';
+ import { destinationEnvironmentId } from '#lib/utils/environments.js';
import { createForm, preventDefault } from '#lib/utils/settings.svelte.js';
type ImagePullFormProps = {
@@ -30,6 +32,8 @@
let inputs = $derived(form.inputs);
let isPulling = $state(false);
+ let pickedEnvironmentId = $state('');
+ const environmentId = $derived(destinationEnvironmentId(pickedEnvironmentId, 'images:pull'));
async function handleSubmit() {
const data = form.validate();
@@ -52,11 +56,11 @@
const fullImageName = `${imageName}:${imageTag}`;
open = false;
isPulling = false;
- void drainPullStream(fullImageName);
+ void drainPullStream(fullImageName, environmentId);
}
- async function drainPullStream(fullImageName: string) {
- const result = await imageService.pullImageStream(fullImageName);
+ async function drainPullStream(fullImageName: string, targetEnvironmentId: string) {
+ const result = await imageService.pullImageStream(fullImageName, undefined, targetEnvironmentId);
if (result.cancelled) return;
if (!result.success) {
const message = result.error || m.images_pull_unexpected_error();
@@ -74,6 +78,7 @@
open = newOpenState;
if (!newOpenState || newOpenState) {
+ pickedEnvironmentId = '';
inputs.imageRef.value = '';
inputs.tag.value = 'latest';
}
@@ -90,6 +95,10 @@
>
{#snippet children()}
<form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-6">
+ <EnvironmentDestinationSelect
+ bind:value={() => environmentId, (value) => (pickedEnvironmentId = value)}
+ permission="images:pull"
+ />
<FormInput
label={m.images_image_name_label()}
type="text"
diff --git a/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte b/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte
index cdb8f2b1e..06eb0eff7 100644
--- a/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar-env-switcher.svelte
@@ -3,7 +3,7 @@
import { EnvironmentsIcon, RemoteEnvironmentIcon, EdgeConnectionIcon, ArrowsUpDownIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import settingsStore from '#lib/stores/config-store.svelte.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+ import { allEnvironmentsPreview, environmentStore } from '#lib/stores/environment.store.svelte.js';
type Props = {
onOpenDialog?: () => void;
@@ -23,41 +23,44 @@
}
</script>
-<Sidebar.Menu>
- <Sidebar.MenuItem>
- <Sidebar.MenuButton
- size="lg"
- tooltipContent={environmentStore.selected ? environmentStore.selected.name : m.sidebar_no_environment()}
- onclick={() => onOpenDialog?.()}
- >
- {#if environmentStore.selected}
- <div class="flex aspect-square size-8 items-center justify-center rounded-lg bg-primary text-primary-foreground">
- {#if environmentStore.selected.id === '0'}
+<!-- Hidden while the all environments preview shows every environment. -->
+{#if !allEnvironmentsPreview.current}
+ <Sidebar.Menu>
+ <Sidebar.MenuItem>
+ <Sidebar.MenuButton
+ size="lg"
+ tooltipContent={environmentStore.selected ? environmentStore.selected.name : m.sidebar_no_environment()}
+ onclick={() => onOpenDialog?.()}
+ >
+ {#if environmentStore.selected}
+ <div class="flex aspect-square size-8 items-center justify-center rounded-lg bg-primary text-primary-foreground">
+ {#if environmentStore.selected.id === '0'}
+ <EnvironmentsIcon class="size-4" />
+ {:else if environmentStore.selected.isEdge}
+ <EdgeConnectionIcon class="size-4" />
+ {:else}
+ <RemoteEnvironmentIcon class="size-4" />
+ {/if}
+ </div>
+ <div class="grid flex-1 text-left text-sm leading-tight">
+ <span class="truncate font-medium">
+ {environmentStore.selected.name}
+ </span>
+ <span class="truncate text-xs">
+ {getConnectionString()}
+ </span>
+ </div>
+ {:else}
+ <div class="flex aspect-square size-8 items-center justify-center rounded-lg bg-primary text-primary-foreground">
<EnvironmentsIcon class="size-4" />
- {:else if environmentStore.selected.isEdge}
- <EdgeConnectionIcon class="size-4" />
- {:else}
- <RemoteEnvironmentIcon class="size-4" />
- {/if}
- </div>
- <div class="grid flex-1 text-left text-sm leading-tight">
- <span class="truncate font-medium">
- {environmentStore.selected.name}
- </span>
- <span class="truncate text-xs">
- {getConnectionString()}
- </span>
- </div>
- {:else}
- <div class="flex aspect-square size-8 items-center justify-center rounded-lg bg-primary text-primary-foreground">
- <EnvironmentsIcon class="size-4" />
- </div>
- <div class="grid flex-1 text-left text-sm leading-tight">
- <span class="truncate font-medium">{m.sidebar_no_environment()}</span>
- <span class="truncate text-xs">{m.sidebar_select_one()}</span>
- </div>
- {/if}
- <ArrowsUpDownIcon class="ml-auto" />
- </Sidebar.MenuButton>
- </Sidebar.MenuItem>
-</Sidebar.Menu>
+ </div>
+ <div class="grid flex-1 text-left text-sm leading-tight">
+ <span class="truncate font-medium">{m.sidebar_no_environment()}</span>
+ <span class="truncate text-xs">{m.sidebar_select_one()}</span>
+ </div>
+ {/if}
+ <ArrowsUpDownIcon class="ml-auto" />
+ </Sidebar.MenuButton>
+ </Sidebar.MenuItem>
+ </Sidebar.Menu>
+{/if}
diff --git a/frontend/src/lib/components/swarm/swarm-kv-page.svelte b/frontend/src/lib/components/swarm/swarm-kv-page.svelte
index 3973a9fc1..66a5f1a44 100644
--- a/frontend/src/lib/components/swarm/swarm-kv-page.svelte
+++ b/frontend/src/lib/components/swarm/swarm-kv-page.svelte
@@ -194,7 +194,14 @@
]);
</script>
-<ResourcePageLayout title={messages.pageTitle} subtitle={messages.pageSubtitle} {icon} {actionButtons} {statCards}>
+<ResourcePageLayout
+ title={messages.pageTitle}
+ subtitle={messages.pageSubtitle}
+ {icon}
+ {actionButtons}
+ {statCards}
+ environmentPicker
+>
{#snippet mainContent()}
<div class={canManage ? 'grid gap-4 lg:grid-cols-2' : 'grid gap-4'}>
{#if canManage}
diff --git a/frontend/src/lib/components/ui/alert/alert-description.svelte b/frontend/src/lib/components/ui/alert/alert-description.svelte
index d0cccae0d..733e49ea2 100644
--- a/frontend/src/lib/components/ui/alert/alert-description.svelte
+++ b/frontend/src/lib/components/ui/alert/alert-description.svelte
@@ -12,6 +12,11 @@
}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
</script>
-<div bind:this={ref} class={cn('text-sm group-data-[size=sm]/alert:text-xs [&_p]:leading-relaxed', className)} {...restProps}>
+<div
+ bind:this={ref}
+ data-slot="alert-description"
+ class={cn('text-sm group-data-[size=sm]/alert:text-xs [&_p]:leading-relaxed', className)}
+ {...restProps}
+>
{@render children?.()}
</div>
diff --git a/frontend/src/lib/components/ui/alert/alert.svelte b/frontend/src/lib/components/ui/alert/alert.svelte
index a0d5be360..05ac4965e 100644
--- a/frontend/src/lib/components/ui/alert/alert.svelte
+++ b/frontend/src/lib/components/ui/alert/alert.svelte
@@ -1,8 +1,9 @@
<script lang="ts" module>
import { type VariantProps, tv } from 'tailwind-variants';
+ // Without a title the icon centers on the description's first 20px line: 1rem of padding plus 2px.
export const alertVariants = tv({
- base: 'group/alert [&>svg]:text-foreground relative w-full rounded-xl border p-4 backdrop-blur-sm bg-card/80 [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg~*]:pl-7',
+ base: 'group/alert [&>svg]:text-foreground relative w-full rounded-xl border p-4 backdrop-blur-sm bg-card/80 [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&:has(>svg+[data-slot=alert-description])>svg]:top-[1.125rem] [&>svg~*]:pl-7',
variants: {
variant: {
default: 'text-foreground',
@@ -15,7 +16,7 @@
},
size: {
default: '',
- sm: 'py-2 [&>svg]:top-2'
+ sm: 'py-2 [&>svg]:top-2 [&:has(>svg+[data-slot=alert-description])>svg]:top-2'
}
},
defaultVariants: {
diff --git a/frontend/src/lib/components/ui/popover/popover-content.svelte b/frontend/src/lib/components/ui/popover/popover-content.svelte
index c6051e274..55aadb333 100644
--- a/frontend/src/lib/components/ui/popover/popover-content.svelte
+++ b/frontend/src/lib/components/ui/popover/popover-content.svelte
@@ -29,7 +29,7 @@
{sideOffset}
{align}
class={cn(
- 'z-(--arcane-z-surface) w-72 origin-(--bits-popover-content-transform-origin) overflow-hidden rounded-xl border bg-background/95 p-4 text-popover-foreground shadow-md outline-hidden backdrop-blur-2xl backdrop-saturate-150 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0 dark:bg-popover/20',
+ 'z-(--arcane-z-surface) w-72 origin-(--bits-popover-content-transform-origin) overflow-hidden rounded-xl border bg-background/95 p-4 wrap-break-word text-popover-foreground shadow-md outline-hidden backdrop-blur-2xl backdrop-saturate-150 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0 dark:bg-popover/20',
size === 'sm' && 'p-2',
variant === 'tooltip' &&
'w-fit max-w-(--max-width-tooltip) border-border/50 bg-popover/90 px-3 py-1.5 text-xs text-balance shadow-lg backdrop-blur-md',
diff --git a/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte b/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte
index 608f02624..96119fc9e 100644
--- a/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte
+++ b/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte
@@ -32,7 +32,7 @@
{sideOffset}
{side}
class={cn(
- 'z-(--arcane-z-surface) w-fit origin-(--bits-tooltip-content-transform-origin) rounded-xl border border-border/40 bg-popover/90 px-3 py-1.5 text-xs text-balance text-popover-foreground shadow-lg backdrop-blur-md backdrop-saturate-150 fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=delayed-open]:animate-in data-[state=instant-open]:animate-in dark:bg-popover/20',
+ 'z-(--arcane-z-surface) w-fit origin-(--bits-tooltip-content-transform-origin) rounded-xl border border-border/40 bg-popover/90 px-3 py-1.5 text-xs text-balance wrap-break-word text-popover-foreground shadow-lg backdrop-blur-md backdrop-saturate-150 fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=delayed-open]:animate-in data-[state=instant-open]:animate-in dark:bg-popover/20',
variant === 'panel' && 'p-0',
className
)}
diff --git a/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte b/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
index fa563a858..a1f004aef 100644
--- a/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
+++ b/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
@@ -21,11 +21,13 @@
interface Props {
scanSummary?: VulnerabilityScanSummary;
imageId: string;
+ /** Environment that owns the image; defaults to the selected one. */
+ environmentId?: string;
pollError?: string | null;
onScanned?: (data: VulnerabilityScanSummary) => void;
}
- let { scanSummary = $bindable(), imageId, pollError = null, onScanned }: Props = $props();
+ let { scanSummary = $bindable(), imageId, environmentId: rowEnvironmentId, pollError = null, onScanned }: Props = $props();
let isOpen = $state(false);
let lastScanRequestedAt = $state<string | null>(null);
@@ -124,7 +126,7 @@
async function startScan() {
if (isScanning) return;
const requestedImageId = imageId;
- const environmentId = await environmentStore.getCurrentEnvironmentId();
+ const environmentId = rowEnvironmentId ?? (await environmentStore.getCurrentEnvironmentId());
if (!featureStore.isEnabled('vulnerabilityManagement', environmentId)) return;
try {
@@ -135,7 +137,7 @@
destroyed ||
!featureStore.isEnabled('vulnerabilityManagement', environmentId) ||
requestedImageId !== imageId ||
- environmentId !== environmentStore.selected?.id
+ !environmentStore.shown.some((env) => env.id === environmentId)
)
return;
if (result) {
diff --git a/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte b/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte
index 4a8ea8ab8..bdf3d0c83 100644
--- a/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte
+++ b/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte
@@ -41,13 +41,15 @@
} from '#lib/utils/vulnerability.js';
interface Props {
+ /** The image's environment, which can differ from the selected one. */
+ environmentId: string;
scan?: VulnerabilityScanResult | null;
reportError?: string | null;
isScanning?: boolean;
onScan?: () => void;
}
- let { scan, reportError = null, isScanning = false, onScan }: Props = $props();
+ let { environmentId, scan, reportError = null, isScanning = false, onScan }: Props = $props();
const DEFAULT_PAGE_SIZE = 20;
@@ -107,7 +109,6 @@
const vulnerabilityQuery = createQuery(() => {
const imageId = scan?.imageId ?? '';
- const environmentId = environmentStore.selected?.id ?? '0';
const options = vulnerabilityRequestOptions;
const filters = { ...(options.filters ?? {}) };
if (filters['vulnSeverity']) {
@@ -146,11 +147,7 @@
async function refreshVulnerabilityTable(options: SearchPaginationSortRequest) {
vulnerabilityRequestOptions = options;
await tick();
- if (
- featureStore.isEnabled('vulnerabilityManagement', environmentStore.selected?.id ?? '0') &&
- scan?.imageId &&
- scan.status === 'completed'
- )
+ if (featureStore.isEnabled('vulnerabilityManagement', environmentId) && scan?.imageId && scan.status === 'completed')
await vulnerabilityQuery.refetch({ throwOnError: true });
return vulnerabilityItems;
}
diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.ts
index 92e8a5bdb..ab767dbca 100644
--- a/frontend/src/lib/config/navigation-config.ts
+++ b/frontend/src/lib/config/navigation-config.ts
@@ -29,10 +29,11 @@ import {
BackupIcon
} from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
+import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { featureStore } from '#lib/stores/features.store.svelte.js';
import type { PermissionsManifest, User } from '#lib/types/auth.js';
import type { FeatureID } from '#lib/types/features.js';
-import { canReachAccessSurface } from '#lib/utils/access-policy.js';
+import { canReachShownAccessSurface } from '#lib/utils/auth.js';
import type { ShortcutKey } from '#lib/utils/navigation.js';
export type NavigationItem = {
@@ -317,17 +318,23 @@ export function filterByPermissions(
return out;
}
+/** Whether a feature is enabled in `envId` or, while the all environments preview is on, in any shown environment. */
+function hasShownFeature(feature: FeatureID, envId: string): boolean {
+ const envIds = environmentStore.selected ? [envId, ...environmentStore.shown.map((env) => env.id)] : [envId];
+ return envIds.some((id) => featureStore.isEnabled(feature, id));
+}
+
function canSeeItem(
item: NavigationItem,
user: User,
currentEnvId: string | undefined,
accessManifest: PermissionsManifest | null | undefined
): boolean {
- if (item.requiredFeature && !featureStore.isEnabled(item.requiredFeature, currentEnvId ?? '0')) return false;
+ if (item.requiredFeature && !hasShownFeature(item.requiredFeature, currentEnvId ?? '0')) return false;
if (item.adminOnly && !user.isGlobalAdmin) return false;
if (!item.accessSurfaceId) return true;
if (!accessManifest?.accessSurfaces?.length) return true;
- return canReachAccessSurface(accessManifest, item.accessSurfaceId, user, currentEnvId);
+ return canReachShownAccessSurface(accessManifest, item.accessSurfaceId, user, currentEnvId);
}
/** Returns the title of the navigation item whose URL is the longest prefix of `pathname`. */
@@ -366,7 +373,9 @@ export function getSwarmNavigationItems(swarmEnabled: boolean | undefined, curre
if (swarmEnabled) {
return navigationItems.swarmItems;
}
- if (swarmEnabled === false && !featureStore.isSwarmEnabled(currentEnvId, false)) {
+ // With the preview on, Swarm may run on another shown environment; the cluster page's picker selects it.
+ const candidates = [currentEnvId, ...environmentStore.shown.map((env) => env.id)];
+ if (swarmEnabled === false && !candidates.some((id) => featureStore.isSwarmEnabled(id, false))) {
return [];
}
diff --git a/frontend/src/lib/hooks/use-environment-refresh.svelte.ts b/frontend/src/lib/hooks/use-environment-refresh.svelte.ts
index 413281ecb..63ece4aa6 100644
--- a/frontend/src/lib/hooks/use-environment-refresh.svelte.ts
+++ b/frontend/src/lib/hooks/use-environment-refresh.svelte.ts
@@ -2,23 +2,18 @@ import { onMount } from 'svelte';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
-// Refresh only when the selected environment ID changes after initial selection.
+// Refresh when the selected or shown environments change after the initial selection.
export function useEnvironmentRefresh(onRefresh: () => void | Promise<void>) {
onMount(() => {
- let lastEnvId = environmentStore.selected?.id ?? null;
+ const scopeKey = () => `${environmentStore.selected?.id}|${environmentStore.shownKey}`;
+ let lastScopeKey = environmentStore.selected ? scopeKey() : null;
return environmentStore.subscribeSelected((env) => {
if (!env) return;
- if (lastEnvId === null) {
- lastEnvId = env.id;
- return;
- }
-
- if (env.id !== lastEnvId) {
- lastEnvId = env.id;
- onRefresh();
- }
+ const previousScopeKey = lastScopeKey;
+ lastScopeKey = scopeKey();
+ if (previousScopeKey !== null && previousScopeKey !== lastScopeKey) onRefresh();
});
});
}
diff --git a/frontend/src/lib/hooks/use-environment-settings.svelte.ts b/frontend/src/lib/hooks/use-environment-settings.svelte.ts
new file mode 100644
index 000000000..d1ca8e471
--- /dev/null
+++ b/frontend/src/lib/hooks/use-environment-settings.svelte.ts
@@ -0,0 +1,20 @@
+import { createQuery } from '@tanstack/svelte-query';
+
+import { queryKeys } from '#lib/query/query-keys.js';
+import { settingsService } from '#lib/services/settings-service.js';
+import settingsStore from '#lib/stores/config-store.svelte.js';
+import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+
+// Settings of a resource's environment, which can differ from the selected one; undefined until loaded.
+export function useEnvironmentSettings(environmentId: () => string) {
+ const query = createQuery(() => ({
+ queryKey: queryKeys.settings.byEnvironment(environmentId()),
+ queryFn: () => settingsService.getReadableSettings(environmentId()),
+ enabled: environmentId() !== environmentStore.selected?.id
+ }));
+ return {
+ get current() {
+ return environmentId() === environmentStore.selected?.id ? settingsStore.current : query.data;
+ }
+ };
+}
diff --git a/frontend/src/lib/layouts/resource-page-layout.svelte b/frontend/src/lib/layouts/resource-page-layout.svelte
index 31b978379..c9341c164 100644
--- a/frontend/src/lib/layouts/resource-page-layout.svelte
+++ b/frontend/src/lib/layouts/resource-page-layout.svelte
@@ -21,6 +21,7 @@
import type { Snippet } from 'svelte';
import { ActionButtonGroup } from '#lib/components/action-button-group/index.js';
+ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';
import StatCard from '#lib/components/stat-card.svelte';
import type { IconType } from '#lib/icons/index.js';
import { cn } from '#lib/utils.js';
@@ -33,6 +34,8 @@
statCards?: StatCardConfig[];
mainContent: Snippet;
additionalContent?: Snippet;
+ /** The page shows one environment at a time; while several are shown it picks the selected one. */
+ environmentPicker?: boolean;
class?: string;
}
@@ -44,6 +47,7 @@
statCards = [],
mainContent,
additionalContent,
+ environmentPicker = false,
class: className = ''
}: Props = $props();
</script>
@@ -85,6 +89,9 @@
</div>
</div>
+ {#if environmentPicker}
+ <EnvironmentDestinationSelect />
+ {/if}
<ActionButtonGroup buttons={actionButtons} />
</header>
diff --git a/frontend/src/lib/layouts/settings-page-layout.svelte b/frontend/src/lib/layouts/settings-page-layout.svelte
index 8edc1e2d3..9532bc16a 100644
--- a/frontend/src/lib/layouts/settings-page-layout.svelte
+++ b/frontend/src/lib/layouts/settings-page-layout.svelte
@@ -5,6 +5,7 @@
import type { ActionButton } from '#lib/components/action-button-group/types.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { UiConfigDisabledTag } from '#lib/components/badges/index.js';
+ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';
import StatCard from '#lib/components/stat-card.svelte';
import { IsMobile } from '#lib/hooks/is-mobile.svelte.js';
import { getSettingsFormContext, hasSettingsFormContext } from '#lib/hooks/settings-form-context.js';
@@ -24,6 +25,8 @@
statCards?: SettingsStatCard[];
mainContent: Snippet;
additionalContent?: Snippet;
+ /** Per-environment settings; while several environments are shown it picks the selected one. */
+ environmentPicker?: boolean;
class?: string;
}
@@ -37,6 +40,7 @@
statCards = [],
mainContent,
additionalContent,
+ environmentPicker = false,
class: className = ''
}: Props = $props();
@@ -82,6 +86,10 @@
</div>
<div class="flex flex-1 items-center justify-end gap-2">
+ {#if environmentPicker}
+ <EnvironmentDestinationSelect />
+ {/if}
+
{#if showReadOnlyTag}
<UiConfigDisabledTag />
{/if}
diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.ts
index 8a69034fa..6a3c78da1 100644
--- a/frontend/src/lib/query/query-keys.ts
+++ b/frontend/src/lib/query/query-keys.ts
@@ -126,6 +126,7 @@ export const queryKeys = {
list: (environmentId: string, options: SearchPaginationSortRequest) =>
['images', environmentId, stableSerialize(options)] as const,
usageCounts: (environmentId: string) => ['images', 'usage-counts', environmentId] as const,
+ uploadLimit: (environmentId: string) => ['images', 'upload-limit', environmentId] as const,
history: (environmentId: string, imageId: string) => ['image', environmentId, imageId, 'history'] as const,
detail: (environmentId: string, imageId: string) => ['image', environmentId, imageId] as const,
updateCheck: (environmentId: string, imageId: string) => ['image-update', environmentId, imageId] as const,
@@ -177,6 +178,7 @@ export const queryKeys = {
},
volumes: {
sizes: (environmentId: string) => ['volume-sizes', environmentId] as const,
+ backupVolumeNames: (scope: string) => ['volume-backup-names', scope] as const,
table: (environmentId: string, options: SearchPaginationSortRequest) =>
['volumes', environmentId, stableSerialize(options)] as const,
detail: (environmentId: string, volumeName: string) => ['volume', environmentId, volumeName] as const,
diff --git a/frontend/src/lib/services/build-workspace-service.ts b/frontend/src/lib/services/build-workspace-service.ts
index d4fbab68e..7720aaaaa 100644
--- a/frontend/src/lib/services/build-workspace-service.ts
+++ b/frontend/src/lib/services/build-workspace-service.ts
@@ -6,24 +6,28 @@ import BaseAPIService from './api-service';
import { uploadService, type UploadProgressCallback } from './upload-service';
class BuildWorkspaceService extends BaseAPIService {
- async listDirectory(path: string = '/'): Promise<FileEntry[]> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ private async resolveEnvironmentId(environmentId?: string): Promise<string> {
+ return environmentId ?? (await environmentStore.getCurrentEnvironmentId());
+ }
+
+ async listDirectory(path: string = '/', environmentId?: string): Promise<FileEntry[]> {
+ const envId = await this.resolveEnvironmentId(environmentId);
const res = await this.api.get(`/environments/${envId}/builds/browse`, {
params: { path }
});
return res.data.data;
}
- async getFileContent(path: string): Promise<FileContentResponse> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async getFileContent(path: string, environmentId?: string): Promise<FileContentResponse> {
+ const envId = await this.resolveEnvironmentId(environmentId);
const res = await this.api.get(`/environments/${envId}/builds/browse/content`, {
params: { path }
});
return res.data.data;
}
- async downloadFile(path: string): Promise<void> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async downloadFile(path: string, environmentId?: string): Promise<void> {
+ const envId = await this.resolveEnvironmentId(environmentId);
const res = await this.api.get(`/environments/${envId}/builds/browse/download`, {
params: { path },
responseType: 'blob'
@@ -32,8 +36,8 @@ class BuildWorkspaceService extends BaseAPIService {
downloadBlob(res.data, filenameFromPath(path));
}
- async uploadFile(path: string, file: File, onProgress?: UploadProgressCallback): Promise<void> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async uploadFile(path: string, file: File, onProgress?: UploadProgressCallback, environmentId?: string): Promise<void> {
+ const envId = await this.resolveEnvironmentId(environmentId);
const uploadId = await uploadService.uploadFile(envId, 'build-workspace', file, onProgress);
return this.handleResponse(
this.api.post(
@@ -46,8 +50,8 @@ class BuildWorkspaceService extends BaseAPIService {
);
}
- async createDirectory(path: string): Promise<void> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async createDirectory(path: string, environmentId?: string): Promise<void> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(
this.api.post(`/environments/${envId}/builds/browse/mkdir`, null, {
params: { path }
@@ -55,8 +59,8 @@ class BuildWorkspaceService extends BaseAPIService {
);
}
- async deleteFile(path: string): Promise<void> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async deleteFile(path: string, environmentId?: string): Promise<void> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(
this.api.delete(`/environments/${envId}/builds/browse`, {
params: { path }
diff --git a/frontend/src/lib/services/container-service.ts b/frontend/src/lib/services/container-service.ts
index c429e6272..3dc8e0037 100644
--- a/frontend/src/lib/services/container-service.ts
+++ b/frontend/src/lib/services/container-service.ts
@@ -17,7 +17,12 @@ import { downloadFromUrl } from '#lib/utils/browser-download.js';
import { transformPaginationParams } from '#lib/utils/tables.js';
import { tryCatch } from '#lib/utils/try-catch.js';
-import BaseAPIService, { extractServerMessage, handleUnauthorizedResponseInternal, withSessionSignal } from './api-service';
+import BaseAPIService, {
+ type APIRequestConfig,
+ extractServerMessage,
+ handleUnauthorizedResponseInternal,
+ withSessionSignal
+} from './api-service';
export type ContainersPaginatedResponse = Paginated<ContainerSummaryDto, ContainerStatusCounts> & {
groups?: ContainerSummaryGroupDto[];
@@ -39,13 +44,14 @@ class ContainerService extends BaseAPIService {
async getContainersForEnvironment(
environmentId: string,
- options?: ContainerListRequestOptions
+ options?: ContainerListRequestOptions,
+ config?: APIRequestConfig
): Promise<ContainersPaginatedResponse> {
const params = transformPaginationParams(options);
if (options?.groupByProject) {
params['groupBy'] = 'project';
}
- const res = await this.api.get(`/environments/${environmentId}/containers`, { params });
+ const res = await this.api.get(`/environments/${environmentId}/containers`, { ...config, params });
return res.data;
}
@@ -68,13 +74,13 @@ class ContainerService extends BaseAPIService {
return this.handleResponse(this.api.get(`/environments/${environmentId}/containers/${containerId}`));
}
- async getContainerProcesses(containerId: string, signal?: AbortSignal): Promise<ContainerProcessesDto> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async getContainerProcesses(containerId: string, signal?: AbortSignal, environmentId?: string): Promise<ContainerProcessesDto> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.get(`/environments/${envId}/containers/${containerId}/processes`, { signal }));
}
- async startContainer(containerId: string): Promise<any> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async startContainer(containerId: string, environmentId?: string): Promise<any> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/start`));
}
@@ -83,35 +89,39 @@ class ContainerService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/containers`, options));
}
- async stopContainer(containerId: string): Promise<any> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async stopContainer(containerId: string, environmentId?: string): Promise<any> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/stop`));
}
- async restartContainer(containerId: string): Promise<any> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async restartContainer(containerId: string, environmentId?: string): Promise<any> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/restart`));
}
- async killContainer(containerId: string, signal?: string): Promise<any> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async killContainer(containerId: string, signal?: string, environmentId?: string): Promise<any> {
+ const envId = await this.resolveEnvironmentId(environmentId);
const params: Record<string, string> = {};
if (signal) params['signal'] = signal;
return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/kill`, undefined, { params }));
}
- async pauseContainer(containerId: string): Promise<any> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async pauseContainer(containerId: string, environmentId?: string): Promise<any> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/pause`));
}
- async unpauseContainer(containerId: string): Promise<any> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async unpauseContainer(containerId: string, environmentId?: string): Promise<any> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/unpause`));
}
- async commitContainer(containerId: string, request: ContainerCommitRequest): Promise<ContainerCommitResult> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async commitContainer(
+ containerId: string,
+ request: ContainerCommitRequest,
+ environmentId?: string
+ ): Promise<ContainerCommitResult> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/commit`, request));
}
@@ -135,8 +145,8 @@ class ContainerService extends BaseAPIService {
).then((activity) => ({ ...activity, sourceEnvironmentId: environmentId }));
}
- async redeployContainer(containerId: string): Promise<ContainerDetailsDto> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async redeployContainer(containerId: string, environmentId?: string): Promise<ContainerDetailsDto> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/redeploy`));
}
@@ -150,13 +160,17 @@ class ContainerService extends BaseAPIService {
return this.handleResponse(this.api.get(`/environments/${envId}/containers/${containerId}/edit-config`));
}
- async editContainer(containerId: string, request: ContainerEditRequest): Promise<ContainerDetailsDto> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async editContainer(containerId: string, request: ContainerEditRequest, environmentId?: string): Promise<ContainerDetailsDto> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/edit`, request));
}
- async setAutoUpdate(containerId: string, enabled: boolean): Promise<{ success: boolean; data: { message: string } }> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async setAutoUpdate(
+ containerId: string,
+ enabled: boolean,
+ environmentId?: string
+ ): Promise<{ success: boolean; data: { message: string } }> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.put(`/environments/${envId}/containers/${containerId}/auto-update`, { enabled }));
}
diff --git a/frontend/src/lib/services/diagnostics-service.ts b/frontend/src/lib/services/diagnostics-service.ts
new file mode 100644
index 000000000..3909fa30d
--- /dev/null
+++ b/frontend/src/lib/services/diagnostics-service.ts
@@ -0,0 +1,11 @@
+import type { GoroutineProfile } from '#lib/types/diagnostics.js';
+
+import BaseAPIService from './api-service';
+
+class DiagnosticsService extends BaseAPIService {
+ async getGoroutinesForEnvironment(environmentId: string): Promise<GoroutineProfile> {
+ return this.handleResponse(this.api.get(`/environments/${environmentId}/diagnostics/goroutines`));
+ }
+}
+
+export const diagnosticsService = new DiagnosticsService();
diff --git a/frontend/src/lib/services/image-service.ts b/frontend/src/lib/services/image-service.ts
index 24e645069..3fdb2f749 100644
--- a/frontend/src/lib/services/image-service.ts
+++ b/frontend/src/lib/services/image-service.ts
@@ -21,7 +21,7 @@ import { readNdjsonStream } from '#lib/utils/streaming.js';
import { transformPaginationParams } from '#lib/utils/tables.js';
import { tryCatch } from '#lib/utils/try-catch.js';
-import BaseAPIService, { isSessionCancelledError, withSessionSignal } from './api-service';
+import BaseAPIService, { type APIRequestConfig, isSessionCancelledError, withSessionSignal } from './api-service';
import { uploadService, type UploadProgressCallback } from './upload-service';
export type ImagePullResult = {
@@ -47,9 +47,13 @@ class ImageService extends BaseAPIService {
return this.getImagesForEnvironment(envId, options);
}
- async getImagesForEnvironment(environmentId: string, options?: SearchPaginationSortRequest): Promise<ImagesPaginatedResponse> {
+ async getImagesForEnvironment(
+ environmentId: string,
+ options?: SearchPaginationSortRequest,
+ config?: APIRequestConfig
+ ): Promise<ImagesPaginatedResponse> {
const params = transformPaginationParams(options);
- const res = await this.api.get(`/environments/${environmentId}/images`, { params });
+ const res = await this.api.get(`/environments/${environmentId}/images`, { ...config, params });
return res.data;
}
@@ -58,8 +62,8 @@ class ImageService extends BaseAPIService {
return this.getImageUsageCountsForEnvironment(envId);
}
- async getImageUsageCountsForEnvironment(environmentId: string): Promise<ImageUsageCounts> {
- const res = await this.api.get(`/environments/${environmentId}/images/counts`);
+ async getImageUsageCountsForEnvironment(environmentId: string, config?: APIRequestConfig): Promise<ImageUsageCounts> {
+ const res = await this.api.get(`/environments/${environmentId}/images/counts`, config);
return res.data.data;
}
@@ -89,28 +93,28 @@ class ImageService extends BaseAPIService {
);
}
- async tagImage(imageId: string, request: ImageTagRequest): Promise<any> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async tagImage(imageId: string, request: ImageTagRequest, environmentId?: string): Promise<any> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/images/${encodeURIComponent(imageId)}/tag`, request));
}
- async getImageHistory(imageId: string): Promise<ImageHistoryItemDto[]> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async getImageHistory(imageId: string, environmentId?: string): Promise<ImageHistoryItemDto[]> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.get(`/environments/${envId}/images/${encodeURIComponent(imageId)}/history`));
}
- async searchImages(term: string): Promise<ImageSearchResultDto[]> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async searchImages(term: string, environmentId?: string): Promise<ImageSearchResultDto[]> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.get(`/environments/${envId}/images/search`, { params: { term } }));
}
- async getImageExportUrl(imageId: string): Promise<string> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async getImageExportUrl(imageId: string, environmentId?: string): Promise<string> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return `/api/environments/${envId}/images/${encodeURIComponent(imageId)}/export`;
}
- async pullImageStream(imageName: string, onLine?: (data: any) => void): Promise<ImagePullResult> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async pullImageStream(imageName: string, onLine?: (data: any) => void, environmentId?: string): Promise<ImagePullResult> {
+ const envId = await this.resolveEnvironmentId(environmentId);
const operationResult = await tryCatch(
(async () => {
@@ -167,17 +171,19 @@ class ImageService extends BaseAPIService {
}
}
- async pullImage(imageName: string, tag: string = 'latest', auth?: any): Promise<any> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async pullImage(imageName: string, tag: string = 'latest', auth?: any, environmentId?: string): Promise<any> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/images/pull`, { imageName, tag, auth }));
}
- async deleteImage(imageId: string, options?: { force?: boolean; noprune?: boolean }): Promise<any> {
+ async deleteImage(imageId: string, options?: { force?: boolean; noprune?: boolean }, environmentId?: string): Promise<any> {
// Resolve the env id synchronously when possible so bulk deletes start
// their request inside the runWithActivityBatchId scope (see api-service).
- const envId = environmentStore.isInitialized()
- ? (environmentStore.selected?.id ?? LOCAL_DOCKER_ENVIRONMENT_ID)
- : await environmentStore.getCurrentEnvironmentId();
+ const envId =
+ environmentId ??
+ (environmentStore.isInitialized()
+ ? (environmentStore.selected?.id ?? LOCAL_DOCKER_ENVIRONMENT_ID)
+ : await environmentStore.getCurrentEnvironmentId());
return this.handleResponse(this.api.delete(`/environments/${envId}/images/${imageId}`, { params: options }));
}
@@ -186,22 +192,26 @@ class ImageService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/images/prune`, options));
}
- async patchImage(imageId: string, options?: ImagePatchOptions): Promise<ImagePatchRecordDto> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async patchImage(imageId: string, options?: ImagePatchOptions, environmentId?: string): Promise<ImagePatchRecordDto> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(
this.api.post(`/environments/${envId}/images/${encodeURIComponent(imageId)}/patch`, options ?? {})
);
}
- async listPatchTargets(options?: SearchPaginationSortRequest): Promise<Paginated<ImagePatchTargetDto>> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async listPatchTargets(
+ options?: SearchPaginationSortRequest,
+ environmentId?: string,
+ config?: APIRequestConfig
+ ): Promise<Paginated<ImagePatchTargetDto>> {
+ const envId = await this.resolveEnvironmentId(environmentId);
const params = transformPaginationParams(options);
- const res = await this.api.get(`/environments/${envId}/images/patch-targets`, { params });
+ const res = await this.api.get(`/environments/${envId}/images/patch-targets`, { ...config, params });
return res.data;
}
- async checkImageUpdateByID(imageId: string): Promise<ImageUpdateInfoDto> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async checkImageUpdateByID(imageId: string, environmentId?: string): Promise<ImageUpdateInfoDto> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/image-updates/check/${imageId}`, {}));
}
@@ -210,8 +220,8 @@ class ImageService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/image-updates/check-all`, {}));
}
- async checkMultipleImages(imageRefs: string[]): Promise<Record<string, ImageUpdateInfoDto>> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async checkMultipleImages(imageRefs: string[], environmentId?: string): Promise<Record<string, ImageUpdateInfoDto>> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/image-updates/check-batch`, { imageRefs }));
}
@@ -226,15 +236,19 @@ class ImageService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/images/upload`, { uploadId }));
}
- async getImageBuilds(options?: SearchPaginationSortRequest): Promise<Paginated<ImageBuildRecord>> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async getImageBuilds(
+ options?: SearchPaginationSortRequest,
+ environmentId?: string,
+ config?: APIRequestConfig
+ ): Promise<Paginated<ImageBuildRecord>> {
+ const envId = await this.resolveEnvironmentId(environmentId);
const params = transformPaginationParams(options);
- const res = await this.api.get(`/environments/${envId}/images/builds`, { params });
+ const res = await this.api.get(`/environments/${envId}/images/builds`, { ...config, params });
return res.data;
}
- async getImageBuild(buildId: string): Promise<ImageBuildRecord> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async getImageBuild(buildId: string, environmentId?: string): Promise<ImageBuildRecord> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.get(`/environments/${envId}/images/builds/${buildId}`));
}
}
diff --git a/frontend/src/lib/services/network-service.ts b/frontend/src/lib/services/network-service.ts
index f740c2368..567e9f516 100644
--- a/frontend/src/lib/services/network-service.ts
+++ b/frontend/src/lib/services/network-service.ts
@@ -10,7 +10,7 @@ import type {
import type { SearchPaginationSortRequest, Paginated } from '#lib/types/shared.js';
import { transformPaginationParams } from '#lib/utils/tables.js';
-import BaseAPIService from './api-service';
+import BaseAPIService, { type APIRequestConfig } from './api-service';
export type NetworksPaginatedResponse = Paginated<NetworkSummaryDto, NetworkUsageCounts>;
@@ -26,10 +26,11 @@ class NetworkService extends BaseAPIService {
async getNetworksForEnvironment(
environmentId: string,
- options?: SearchPaginationSortRequest
+ options?: SearchPaginationSortRequest,
+ config?: APIRequestConfig
): Promise<NetworksPaginatedResponse> {
const params = transformPaginationParams(options);
- const res = await this.api.get(`/environments/${environmentId}/networks`, { params });
+ const res = await this.api.get(`/environments/${environmentId}/networks`, { ...config, params });
return res.data;
}
@@ -67,21 +68,26 @@ class NetworkService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/networks`, request));
}
- async deleteNetwork(networkId: string): Promise<any> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async deleteNetwork(networkId: string, environmentId?: string): Promise<any> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.delete(`/environments/${envId}/networks/${networkId}`));
}
async connectContainer(
networkId: string,
- request: { containerId: string; aliases?: string[]; ipv4Address?: string; ipv6Address?: string }
+ request: { containerId: string; aliases?: string[]; ipv4Address?: string; ipv6Address?: string },
+ environmentId?: string
): Promise<any> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/networks/${networkId}/connect`, request));
}
- async disconnectContainer(networkId: string, request: { containerId: string; force?: boolean }): Promise<any> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async disconnectContainer(
+ networkId: string,
+ request: { containerId: string; force?: boolean },
+ environmentId?: string
+ ): Promise<any> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/networks/${networkId}/disconnect`, request));
}
}
diff --git a/frontend/src/lib/services/port-service.ts b/frontend/src/lib/services/port-service.ts
index 207f83ca4..a1c8b0346 100644
--- a/frontend/src/lib/services/port-service.ts
+++ b/frontend/src/lib/services/port-service.ts
@@ -3,7 +3,7 @@ import type { PortMappingDto } from '#lib/types/docker.js';
import type { SearchPaginationSortRequest, Paginated } from '#lib/types/shared.js';
import { transformPaginationParams } from '#lib/utils/tables.js';
-import BaseAPIService from './api-service';
+import BaseAPIService, { type APIRequestConfig } from './api-service';
export type PortsPaginatedResponse = Paginated<PortMappingDto>;
@@ -17,9 +17,13 @@ class PortService extends BaseAPIService {
return this.getPortsForEnvironment(envId, options);
}
- async getPortsForEnvironment(environmentId: string, options?: SearchPaginationSortRequest): Promise<PortsPaginatedResponse> {
+ async getPortsForEnvironment(
+ environmentId: string,
+ options?: SearchPaginationSortRequest,
+ config?: APIRequestConfig
+ ): Promise<PortsPaginatedResponse> {
const params = transformPaginationParams(options);
- const res = await this.api.get(`/environments/${environmentId}/ports`, { params });
+ const res = await this.api.get(`/environments/${environmentId}/ports`, { ...config, params });
return res.data;
}
}
diff --git a/frontend/src/lib/services/project-service.ts b/frontend/src/lib/services/project-service.ts
index de83746ef..afc6670d2 100644
--- a/frontend/src/lib/services/project-service.ts
+++ b/frontend/src/lib/services/project-service.ts
@@ -14,7 +14,7 @@ import type {
import { readNdjsonStream } from '#lib/utils/streaming.js';
import { transformPaginationParams } from '#lib/utils/tables.js';
-import BaseAPIService, { withSessionSignal } from './api-service';
+import BaseAPIService, { type APIRequestConfig, withSessionSignal } from './api-service';
class ProjectService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
@@ -26,29 +26,42 @@ class ProjectService extends BaseAPIService {
return this.getProjectsForEnvironment(envId, options);
}
- async getProjectsForEnvironment(environmentId: string, options?: SearchPaginationSortRequest): Promise<Paginated<Project>> {
+ async getProjectsForEnvironment(
+ environmentId: string,
+ options?: SearchPaginationSortRequest,
+ config?: APIRequestConfig
+ ): Promise<Paginated<Project>> {
const params = transformPaginationParams(options);
- const res = await this.api.get(`/environments/${environmentId}/projects`, { params });
+ const res = await this.api.get(`/environments/${environmentId}/projects`, { ...config, params });
return res.data;
}
- deployProject(projectId: string, mode: 'up' | 'redeploy', options?: DeployProjectOptions): Promise<Project>;
+ deployProject(
+ projectId: string,
+ mode: 'up' | 'redeploy',
+ options?: DeployProjectOptions,
+ environmentId?: string
+ ): Promise<Project>;
deployProject(
projectId: string,
mode: 'up' | 'redeploy',
onLine: (data: unknown) => void,
- options?: DeployProjectOptions
+ options?: DeployProjectOptions,
+ environmentId?: string
): Promise<Project>;
async deployProject(
projectId: string,
mode: 'up' | 'redeploy',
onLineOrOptions?: ((data: unknown) => void) | DeployProjectOptions,
- maybeOptions?: DeployProjectOptions
+ optionsOrEnvironmentId?: DeployProjectOptions | string,
+ maybeEnvironmentId?: string
): Promise<Project> {
- const envId = await environmentStore.getCurrentEnvironmentId();
- const url = `/api/environments/${envId}/projects/${projectId}/${mode}`;
const onLine = typeof onLineOrOptions === 'function' ? onLineOrOptions : undefined;
- const options = typeof onLineOrOptions === 'function' ? maybeOptions : onLineOrOptions;
+ const options = onLine
+ ? (optionsOrEnvironmentId as DeployProjectOptions | undefined)
+ : (onLineOrOptions as DeployProjectOptions);
+ const envId = await this.resolveEnvironmentId(onLine ? maybeEnvironmentId : (optionsOrEnvironmentId as string | undefined));
+ const url = `/api/environments/${envId}/projects/${projectId}/${mode}`;
await this.postProjectStream(url, options ?? {}, onLine, {
startFailed: (status) => m.progress_deploy_failed_to_start({ status }),
@@ -56,11 +69,11 @@ class ProjectService extends BaseAPIService {
});
// The deploy stream doesn't return the project object; fetch fresh details.
- return this.getProject(projectId);
+ return this.getProjectForEnvironment(envId, projectId);
}
- async downProject(projectName: string): Promise<Project> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async downProject(projectName: string, environmentId?: string): Promise<Project> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectName}/down`));
}
@@ -69,9 +82,10 @@ class ProjectService extends BaseAPIService {
composeContent: string,
envContent?: string,
workspaceFiles: ProjectWorkspaceFileDraft[] = [],
- tags: ProjectTag[] = []
+ tags: ProjectTag[] = [],
+ environmentId?: string
): Promise<Project> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const envId = await this.resolveEnvironmentId(environmentId);
const form = new FormData();
const uploads: File[] = [];
const fileChanges = workspaceFiles.map((file) => {
@@ -95,8 +109,8 @@ class ProjectService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/projects`, form));
}
- async checkUpdates(projectId: string): Promise<ProjectUpdateInfo> {
- const envId = await this.resolveEnvironmentId();
+ async checkUpdates(projectId: string, environmentId?: string): Promise<ProjectUpdateInfo> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(
this.api.post(`/environments/${envId}/updater/projects/${encodeURIComponent(projectId)}/check`, {})
);
@@ -171,22 +185,23 @@ class ProjectService extends BaseAPIService {
return this.getProjectStatusCountsForEnvironment(envId);
}
- async getProjectStatusCountsForEnvironment(environmentId: string): Promise<ProjectStatusCounts> {
- const res = await this.api.get(`/environments/${environmentId}/projects/counts`);
+ async getProjectStatusCountsForEnvironment(environmentId: string, config?: APIRequestConfig): Promise<ProjectStatusCounts> {
+ const res = await this.api.get(`/environments/${environmentId}/projects/counts`, config);
return res.data.data;
}
- async getProjectTagsForEnvironment(environmentId: string): Promise<ProjectTagOption[]> {
- return this.handleResponse(this.api.get(`/environments/${environmentId}/projects/tags`));
+ async getProjectTagsForEnvironment(environmentId: string, config?: APIRequestConfig): Promise<ProjectTagOption[]> {
+ return this.handleResponse(this.api.get(`/environments/${environmentId}/projects/tags`, config));
}
async updateProjectTag(
projectId: string,
name: string,
attached: boolean,
- color?: ProjectTagColor
+ color?: ProjectTagColor,
+ environmentId?: string
): Promise<{ tags: ProjectTag[]; activityId?: string }> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.patch(`/environments/${envId}/projects/${projectId}/tags`, { name, attached, color }));
}
@@ -195,9 +210,10 @@ class ProjectService extends BaseAPIService {
name?: string,
composeContent?: string,
envContent?: string,
- overrideContent?: string
+ overrideContent?: string,
+ environmentId?: string
): Promise<Project> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const envId = await this.resolveEnvironmentId(environmentId);
const payload: {
name?: string;
composeContent?: string;
@@ -219,8 +235,8 @@ class ProjectService extends BaseAPIService {
return this.handleResponse(this.api.put(`/environments/${envId}/projects/${projectId}`, payload));
}
- async restartProject(projectId: string, services?: string[]): Promise<unknown> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async restartProject(projectId: string, services?: string[], environmentId?: string): Promise<unknown> {
+ const envId = await this.resolveEnvironmentId(environmentId);
let params: URLSearchParams | undefined;
if (services && services.length > 0) {
params = new URLSearchParams();
@@ -231,18 +247,18 @@ class ProjectService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectId}/restart`, undefined, { params }));
}
- async archiveProject(projectId: string): Promise<void> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async archiveProject(projectId: string, environmentId?: string): Promise<void> {
+ const envId = await this.resolveEnvironmentId(environmentId);
await this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectId}/archive`));
}
- async unarchiveProject(projectId: string): Promise<void> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async unarchiveProject(projectId: string, environmentId?: string): Promise<void> {
+ const envId = await this.resolveEnvironmentId(environmentId);
await this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectId}/unarchive`));
}
- private async streamProjectPull(projectId: string, onLine?: (data: any) => void): Promise<void> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ private async streamProjectPull(projectId: string, onLine?: (data: any) => void, environmentId?: string): Promise<void> {
+ const envId = await this.resolveEnvironmentId(environmentId);
const url = `/api/environments/${envId}/projects/${projectId}/pull`;
const res = await fetch(url, { method: 'POST', signal: withSessionSignal() });
@@ -265,14 +281,16 @@ class ProjectService extends BaseAPIService {
buildProjectImages(
projectId: string,
options: { services?: string[]; provider?: 'local' | 'depot'; push?: boolean; load?: boolean } | undefined,
- onLine: (data: any) => void
+ onLine: (data: any) => void,
+ environmentId?: string
): Promise<void>;
async buildProjectImages(
projectId: string,
options?: { services?: string[]; provider?: 'local' | 'depot'; push?: boolean; load?: boolean },
- onLine?: (data: any) => void
+ onLine?: (data: any) => void,
+ environmentId?: string
): Promise<void> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const envId = await this.resolveEnvironmentId(environmentId);
const url = `/api/environments/${envId}/projects/${projectId}/build`;
await this.postProjectStream(url, options || {}, onLine, {
@@ -282,13 +300,13 @@ class ProjectService extends BaseAPIService {
}
pullProjectImages(projectId: string): Promise<void>;
- pullProjectImages(projectId: string, onLine: (data: any) => void): Promise<void>;
- async pullProjectImages(projectId: string, onLine?: (data: any) => void): Promise<void> {
- await this.streamProjectPull(projectId, onLine);
+ pullProjectImages(projectId: string, onLine: (data: any) => void, environmentId?: string): Promise<void>;
+ async pullProjectImages(projectId: string, onLine?: (data: any) => void, environmentId?: string): Promise<void> {
+ await this.streamProjectPull(projectId, onLine, environmentId);
}
- async destroyProject(projectName: string, removeVolumes = false): Promise<void> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async destroyProject(projectName: string, removeVolumes = false, environmentId?: string): Promise<void> {
+ const envId = await this.resolveEnvironmentId(environmentId);
await this.handleResponse(
this.api.delete(`/environments/${envId}/projects/${projectName}/destroy`, {
data: {
diff --git a/frontend/src/lib/services/settings-service.ts b/frontend/src/lib/services/settings-service.ts
index 7d6b67410..d1ee2acd0 100644
--- a/frontend/src/lib/services/settings-service.ts
+++ b/frontend/src/lib/services/settings-service.ts
@@ -63,6 +63,12 @@ class SettingsService extends BaseAPIService {
return { ...extractEnvironmentSettings(environmentSettings), ...extractLocalSettings(mainSettings) } as Settings;
}
+ /** The environment's merged settings, or only its public settings without `settings:read`. */
+ async getReadableSettings(environmentId: string): Promise<Settings> {
+ if (!userStore.hasPermission('settings:read', environmentId)) return this.getPublicSettings(environmentId);
+ return this.getSettingsForEnvironmentMerged(environmentId);
+ }
+
async updateSettings(settings: Partial<Settings>) {
// Wait for environment store to be initialized before updating settings
await environmentStore.ready;
@@ -105,8 +111,7 @@ class SettingsService extends BaseAPIService {
}
// Reload and return merged settings
- if (!userStore.hasPermission('settings:read', envId)) return this.getPublicSettings(envId);
- return this.getSettingsForEnvironmentMerged(envId);
+ return this.getReadableSettings(envId);
}
async getOidcStatus(): Promise<OidcStatusInfo> {
diff --git a/frontend/src/lib/services/volume-backup-service.ts b/frontend/src/lib/services/volume-backup-service.ts
index 7661968a8..2a3c07a84 100644
--- a/frontend/src/lib/services/volume-backup-service.ts
+++ b/frontend/src/lib/services/volume-backup-service.ts
@@ -16,18 +16,26 @@ import { uploadService, type UploadProgressCallback } from './upload-service';
export type VolumeBackupListResponse = Paginated<BackupEntry> & { warnings?: string[] };
class VolumeBackupService extends BaseAPIService {
- async getPolicies(volumeName: string): Promise<VolumeBackupPolicyCollection> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ private async resolveEnvironmentId(environmentId?: string): Promise<string> {
+ return environmentId ?? (await environmentStore.getCurrentEnvironmentId());
+ }
+
+ async getPolicies(volumeName: string, environmentId?: string): Promise<VolumeBackupPolicyCollection> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}/backup-policy`));
}
- async updatePolicies(volumeName: string, policies: UpdateVolumeBackupPolicy[]): Promise<VolumeBackupPolicyCollection> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async updatePolicies(
+ volumeName: string,
+ policies: UpdateVolumeBackupPolicy[],
+ environmentId?: string
+ ): Promise<VolumeBackupPolicyCollection> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.put(`/environments/${envId}/volumes/${volumeName}/backup-policy`, { policies }));
}
- async createBackup(volumeName: string, request?: CreateVolumeBackupRequest): Promise<BackupEntry> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async createBackup(volumeName: string, request?: CreateVolumeBackupRequest, environmentId?: string): Promise<BackupEntry> {
+ const envId = await this.resolveEnvironmentId(environmentId);
const res = await this.api.post(`/environments/${envId}/volumes/${volumeName}/backups`, request);
return res.data.data;
}
@@ -37,7 +45,7 @@ class VolumeBackupService extends BaseAPIService {
options?: SearchPaginationSortRequest,
environmentId?: string
): Promise<VolumeBackupListResponse> {
- const envId = environmentId ?? (await environmentStore.getCurrentEnvironmentId());
+ const envId = await this.resolveEnvironmentId(environmentId);
const params = transformPaginationParams(options);
const res = await this.api.get(`/environments/${envId}/volumes/${volumeName}/backups`, { params });
return res.data;
@@ -48,13 +56,18 @@ class VolumeBackupService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/volumes/backups/discover`, { s3DestinationId }));
}
- async restoreBackup(volumeName: string, backupId: string): Promise<unknown> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async restoreBackup(volumeName: string, backupId: string, environmentId?: string): Promise<unknown> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/volumes/${volumeName}/backups/${backupId}/restore`));
}
- async restoreBackupFiles(volumeName: string, backupId: string, selection: BackupRestoreSelection): Promise<unknown> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async restoreBackupFiles(
+ volumeName: string,
+ backupId: string,
+ selection: BackupRestoreSelection,
+ environmentId?: string
+ ): Promise<unknown> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(
this.api.post(`/environments/${envId}/volumes/${volumeName}/backups/${backupId}/restore-files`, {
...selection
@@ -62,8 +75,12 @@ class VolumeBackupService extends BaseAPIService {
);
}
- async browseBackupFiles(backupId: string, request: BackupFileBrowseRequest): Promise<Paginated<BackupFileEntry>> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async browseBackupFiles(
+ backupId: string,
+ request: BackupFileBrowseRequest,
+ environmentId?: string
+ ): Promise<Paginated<BackupFileEntry>> {
+ const envId = await this.resolveEnvironmentId(environmentId);
const response = await this.api.get(`/environments/${envId}/volumes/backups/${backupId}/files/browse`, {
params: request
});
@@ -71,7 +88,7 @@ class VolumeBackupService extends BaseAPIService {
}
async backupHasPath(backupId: string, filePath: string, environmentId?: string): Promise<boolean> {
- const envId = environmentId ?? (await environmentStore.getCurrentEnvironmentId());
+ const envId = await this.resolveEnvironmentId(environmentId);
const res = await this.api.get(`/environments/${envId}/volumes/backups/${backupId}/has-path`, {
params: { path: filePath }
});
@@ -84,8 +101,8 @@ class VolumeBackupService extends BaseAPIService {
return res.data.data ?? [];
}
- async downloadBackup(backupId: string): Promise<void> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async downloadBackup(backupId: string, environmentId?: string): Promise<void> {
+ const envId = await this.resolveEnvironmentId(environmentId);
const res = await this.api.get(`/environments/${envId}/volumes/backups/${backupId}/download`, {
responseType: 'blob'
});
@@ -99,13 +116,13 @@ class VolumeBackupService extends BaseAPIService {
link.remove();
}
- async deleteBackup(backupId: string): Promise<unknown> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async deleteBackup(backupId: string, environmentId?: string): Promise<unknown> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.delete(`/environments/${envId}/volumes/backups/${backupId}`));
}
- async uploadBackup(backupId: string, s3DestinationId: string): Promise<BackupEntry> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async uploadBackup(backupId: string, s3DestinationId: string, environmentId?: string): Promise<BackupEntry> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.post(`/environments/${envId}/volumes/backups/${backupId}/upload`, { s3DestinationId }));
}
diff --git a/frontend/src/lib/services/volume-service.ts b/frontend/src/lib/services/volume-service.ts
index b2e36159e..b40e407ab 100644
--- a/frontend/src/lib/services/volume-service.ts
+++ b/frontend/src/lib/services/volume-service.ts
@@ -11,7 +11,7 @@ import type {
import type { SearchPaginationSortRequest, Paginated } from '#lib/types/shared.js';
import { transformPaginationParams } from '#lib/utils/tables.js';
-import BaseAPIService from './api-service';
+import BaseAPIService, { type APIRequestConfig } from './api-service';
export type VolumesPaginatedResponse = Paginated<VolumeSummaryDto, VolumeUsageCounts>;
@@ -27,10 +27,11 @@ class VolumeService extends BaseAPIService {
async getVolumesForEnvironment(
environmentId: string,
- options?: SearchPaginationSortRequest
+ options?: SearchPaginationSortRequest,
+ config?: APIRequestConfig
): Promise<VolumesPaginatedResponse> {
const params = transformPaginationParams(options);
- const res = await this.api.get(`/environments/${environmentId}/volumes`, { params });
+ const res = await this.api.get(`/environments/${environmentId}/volumes`, { ...config, params });
return res.data;
}
@@ -43,8 +44,8 @@ class VolumeService extends BaseAPIService {
return this.handleResponse(this.api.get(`/environments/${environmentId}/volumes/${volumeName}`)) as Promise<VolumeDetailDto>;
}
- async getVolumeUsage(volumeName: string): Promise<VolumeUsageDto> {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ async getVolumeUsage(volumeName: string, environmentId?: string): Promise<VolumeUsageDto> {
+ const envId = await this.resolveEnvironmentId(environmentId);
return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}/usage`)) as Promise<VolumeUsageDto>;
}
@@ -54,8 +55,8 @@ class VolumeService extends BaseAPIService {
return res.data.data;
}
- async getVolumeSizes(environmentId: string): Promise<VolumeSizeInfo[]> {
- const res = await this.api.get(`/environments/${environmentId}/volumes/sizes`);
+ async getVolumeSizes(environmentId: string, config?: APIRequestConfig): Promise<VolumeSizeInfo[]> {
+ const res = await this.api.get(`/environments/${environmentId}/volumes/sizes`, config);
return res.data.data;
}
@@ -71,12 +72,14 @@ class VolumeService extends BaseAPIService {
) as Promise<VolumeDetailDto>;
}
- async deleteVolume(volumeName: string): Promise<any> {
+ async deleteVolume(volumeName: string, environmentId?: string): Promise<any> {
// Resolve the env id synchronously when possible so bulk deletes start
// their request inside the runWithActivityBatchId scope (see api-service).
- const envId = environmentStore.isInitialized()
- ? (environmentStore.selected?.id ?? LOCAL_DOCKER_ENVIRONMENT_ID)
- : await environmentStore.getCurrentEnvironmentId();
+ const envId =
+ environmentId ??
+ (environmentStore.isInitialized()
+ ? (environmentStore.selected?.id ?? LOCAL_DOCKER_ENVIRONMENT_ID)
+ : await environmentStore.getCurrentEnvironmentId());
return this.handleResponse(this.api.delete(`/environments/${envId}/volumes/${volumeName}`));
}
}
diff --git a/frontend/src/lib/services/vulnerability-service.ts b/frontend/src/lib/services/vulnerability-service.ts
index cd028ada1..efcde3cae 100644
--- a/frontend/src/lib/services/vulnerability-service.ts
+++ b/frontend/src/lib/services/vulnerability-service.ts
@@ -17,7 +17,7 @@ import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.j
import { filenameFromContentDisposition } from '#lib/utils/browser-download.js';
import { transformPaginationParams } from '#lib/utils/tables.js';
-import BaseAPIService from './api-service';
+import BaseAPIService, { type APIRequestConfig } from './api-service';
class VulnerabilityService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
@@ -96,10 +96,11 @@ class VulnerabilityService extends BaseAPIService {
async getAllVulnerabilitiesForEnvironment(
environmentId: string,
- options?: SearchPaginationSortRequest
+ options?: SearchPaginationSortRequest,
+ config?: APIRequestConfig
): Promise<Paginated<VulnerabilityWithImage>> {
const params = transformPaginationParams(options);
- const res = await this.api.get(`/environments/${environmentId}/vulnerabilities/all`, { params });
+ const res = await this.api.get(`/environments/${environmentId}/vulnerabilities/all`, { ...config, params });
return res.data;
}
@@ -126,7 +127,8 @@ class VulnerabilityService extends BaseAPIService {
async getAllVulnerabilityImageOptionsForEnvironment(
environmentId: string,
- options?: SearchPaginationSortRequest
+ options?: SearchPaginationSortRequest,
+ config?: APIRequestConfig
): Promise<string[]> {
const severityFilter = options?.filters?.['severity'];
const params: Record<string, string> = {};
@@ -135,7 +137,9 @@ class VulnerabilityService extends BaseAPIService {
params['severity'] = Array.isArray(severityFilter) ? severityFilter.join(',') : String(severityFilter);
}
- return this.handleResponse(this.api.get(`/environments/${environmentId}/vulnerabilities/image-options`, { params }));
+ return this.handleResponse(
+ this.api.get(`/environments/${environmentId}/vulnerabilities/image-options`, { ...config, params })
+ );
}
/**
diff --git a/frontend/src/lib/stores/config-store.svelte.ts b/frontend/src/lib/stores/config-store.svelte.ts
index 113775c9f..27caa4970 100644
--- a/frontend/src/lib/stores/config-store.svelte.ts
+++ b/frontend/src/lib/stores/config-store.svelte.ts
@@ -2,7 +2,6 @@ import { untrack } from 'svelte';
import { settingsService } from '#lib/services/settings-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
-import userStore from '#lib/stores/user-store.svelte.js';
import type { Settings } from '#lib/types/settings.js';
let current = $state.raw<Settings>();
@@ -10,9 +9,7 @@ const listeners = new Set<(settings: Settings | undefined) => void>();
const reload = async () => {
const environmentId = await environmentStore.getCurrentEnvironmentId();
- const settings = userStore.hasPermission('settings:read', environmentId)
- ? await settingsService.getSettingsForEnvironmentMerged(environmentId)
- : await settingsService.getPublicSettings(environmentId);
+ const settings = await settingsService.getReadableSettings(environmentId);
if (environmentId === environmentStore.selected?.id) set(settings);
};
diff --git a/frontend/src/lib/stores/environment-colors.store.svelte.ts b/frontend/src/lib/stores/environment-colors.store.svelte.ts
new file mode 100644
index 000000000..2ca1038b8
--- /dev/null
+++ b/frontend/src/lib/stores/environment-colors.store.svelte.ts
@@ -0,0 +1,75 @@
+import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+import userStore from '#lib/stores/user-store.svelte.js';
+
+// Mirrors the iOS app: one unique color per environment ID. Picks are saved in user preferences;
+// environments without one get the next free palette color, in ID order.
+export const environmentColorPalette = [
+ '#2680C2',
+ '#D06820',
+ '#289B66',
+ '#9657CA',
+ '#C64574',
+ '#168D97',
+ '#AB841A',
+ '#646DD6',
+ '#BB5142',
+ '#678B36',
+ '#A453A5',
+ '#477D91'
+];
+
+function normalizeColor(color: string): string {
+ return color.startsWith('#') ? color.toUpperCase() : color.toLowerCase();
+}
+
+function availableColor(used: Set<string>): string {
+ const color = environmentColorPalette.find((candidate) => !used.has(candidate));
+ if (color) return color;
+ // Walk the RGB space without repeating colors once the palette is exhausted.
+ for (let index = 1; index <= 0xffffff; index++) {
+ const candidate = `#${((index * 0x9e3779) & 0xffffff).toString(16).padStart(6, '0').toUpperCase()}`;
+ if (!used.has(candidate)) return candidate;
+ }
+ return environmentColorPalette[0]!;
+}
+
+function savedColors(): Record<string, string> {
+ return userStore.current?.preferences?.environmentColors ?? {};
+}
+
+/** Every environment's color: saved picks first, then unique defaults for the rest. */
+function effectiveColors(saved: Record<string, string>): Map<string, string> {
+ const colors = new Map<string, string>();
+ const used = new Set<string>();
+ for (const [id, color] of Object.entries(saved)) {
+ const normalized = normalizeColor(color);
+ if (used.has(normalized)) continue;
+ colors.set(id, normalized);
+ used.add(normalized);
+ }
+ const ids = environmentStore.available.map((env) => env.id).sort();
+ for (const id of ids.filter((id) => !colors.has(id))) {
+ const color = availableColor(used);
+ colors.set(id, color);
+ used.add(color);
+ }
+ return colors;
+}
+
+export function environmentColor(environmentId: string): string | undefined {
+ return effectiveColors(savedColors()).get(environmentId);
+}
+
+/**
+ * Colors to save after setting one environment's color, or clearing it with null so it falls back to a
+ * default. Every other environment keeps the color it shows now. Returns null when another
+ * environment already shows that color.
+ */
+export function withEnvironmentColor(environmentId: string, color: string | null): Record<string, string> | null {
+ const others = effectiveColors(savedColors());
+ others.delete(environmentId);
+ if (color === null) return Object.fromEntries(others);
+ const normalized = normalizeColor(color);
+ if ([...others.values()].includes(normalized)) return null;
+ return { ...Object.fromEntries(others), [environmentId]: normalized };
+}
diff --git a/frontend/src/lib/stores/environment.store.svelte.ts b/frontend/src/lib/stores/environment.store.svelte.ts
index 36b2212e3..79a9f24fc 100644
--- a/frontend/src/lib/stores/environment.store.svelte.ts
+++ b/frontend/src/lib/stores/environment.store.svelte.ts
@@ -2,11 +2,22 @@ import { goto, refreshAll } from '$app/navigation';
import { page } from '$app/state';
import { PersistedState } from 'runed';
+import userStore from '#lib/stores/user-store.svelte.js';
import type { Environment } from '#lib/types/environment.js';
import { isEnvironmentOnline } from '#lib/utils/docker.js';
export const LOCAL_DOCKER_ENVIRONMENT_ID = '0';
+export type EnvironmentRef = Pick<Environment, 'id' | 'name'>;
+
+// Preview: resource lists show and act on every enabled environment, like the CLI's previews.allEnvironments.
+// Saved in the user's preferences, so it follows them across browsers.
+export const allEnvironmentsPreview = {
+ get current(): boolean {
+ return userStore.current?.preferences?.allEnvironmentsPreview ?? false;
+ }
+};
+
function getResourceListPage(): string | null {
const routeId = page.route?.id;
if (!routeId) return null;
@@ -37,6 +48,7 @@ function createEnvironmentManagementStore() {
const _selectedSubscribers = new Set<(environment: Environment | null) => void>();
let _resolveReadyPromiseFunction: () => void;
+ let _selectionHold: Promise<void> | null = null;
const _readyPromise = new Promise<void>((resolve) => {
_resolveReadyPromiseFunction = resolve;
});
@@ -57,6 +69,14 @@ function createEnvironmentManagementStore() {
}
}
+ // Toggling the preview changes the shown environments, so selected subscribers refresh.
+ let _lastPreview = allEnvironmentsPreview.current;
+ userStore.onChange(() => {
+ if (allEnvironmentsPreview.current === _lastPreview) return;
+ _lastPreview = allEnvironmentsPreview.current;
+ _notifySelectedSubscribers();
+ });
+
function _isAutoSelectableEnvironment(environment: Environment): boolean {
if (!environment.enabled) return false;
if (environment.id === LOCAL_DOCKER_ENVIRONMENT_ID) return true;
@@ -116,6 +136,16 @@ function createEnvironmentManagementStore() {
get available(): Environment[] {
return _availableEnvironments;
},
+ // Environments that resource lists show: the selected one, or every enabled one with the preview on.
+ get shown(): EnvironmentRef[] {
+ const enabled = allEnvironmentsPreview.current ? _availableEnvironments.filter((env) => env.enabled) : [];
+ if (enabled.length > 0) return enabled.sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
+ return [_selectedEnvironment ?? { id: LOCAL_DOCKER_ENVIRONMENT_ID, name: '' }];
+ },
+ // Query-key scope for the shown environments.
+ get shownKey(): string {
+ return this.shown.map((env) => env.id).join(',');
+ },
initialize: async (environmentsData: Environment[]) => {
const available = _updateAvailable(environmentsData);
const hasRealEnvironments = environmentsData.length > 0;
@@ -157,12 +187,17 @@ function createEnvironmentManagementStore() {
const updated = available.find((env) => env.id === _selectedEnvironment!.id);
if (updated) {
_assignSelectedEnvironment(updated);
+ } else {
+ // The selection stays, but the shown environments changed, so subscribers still refresh.
+ _notifySelectedSubscribers();
}
},
- setEnvironment: async (environment: Environment) => {
+ // `navigate: false` only selects, for callers that are already loading the page that needs it.
+ setEnvironment: async (environment: Environment, { navigate = true }: { navigate?: boolean } = {}) => {
if (!environment.enabled) return;
if (_selectedEnvironment?.id !== environment.id) {
_assignSelectedEnvironment(environment);
+ if (!navigate) return;
// Check if we're on a resource detail page (e.g., /containers/abc123)
// These pages show environment-specific resources that won't exist in the new environment
@@ -196,8 +231,24 @@ function createEnvironmentManagementStore() {
isInitialized: () => _initialized,
getLocalEnvironment: () => _availableEnvironments.find((env) => env.id === LOCAL_DOCKER_ENVIRONMENT_ID) || null,
ready: _readyPromise,
+ // The root load can switch environments for the route it loads; lookups wait until it has chosen.
+ holdSelection: (): (() => void) => {
+ let release!: () => void;
+ const hold = new Promise<void>((resolve) => (release = resolve));
+ _selectionHold = hold;
+ return () => {
+ if (_selectionHold === hold) _selectionHold = null;
+ release();
+ };
+ },
+ getShownEnvironments: async (): Promise<EnvironmentRef[]> => {
+ await _readyPromise;
+ await _selectionHold;
+ return environmentStore.shown;
+ },
getCurrentEnvironmentId: async (): Promise<string> => {
await _readyPromise;
+ await _selectionHold;
return _selectedEnvironment ? _selectedEnvironment.id : LOCAL_DOCKER_ENVIRONMENT_ID;
}
};
diff --git a/frontend/src/lib/types/auth.ts b/frontend/src/lib/types/auth.ts
index b69d093e7..01fe5a6e1 100644
--- a/frontend/src/lib/types/auth.ts
+++ b/frontend/src/lib/types/auth.ts
@@ -133,6 +133,8 @@ export type TimeFormat = 'auto' | '12h' | '24h';
export type ProjectEditorLayout = 'auto' | 'classic' | 'tree';
+export type EnvironmentLabelStyle = 'name' | 'dot';
+
/**
* Personal display/UI preferences stored on the user record. Every field is
* optional: an unset value falls back to the frontend default.
@@ -151,6 +153,9 @@ export type UserPreferences = {
mobileNavigationShowLabels?: boolean;
defaultLandingPage?: string;
defaultProjectEditorLayout?: ProjectEditorLayout;
+ allEnvironmentsPreview?: boolean;
+ environmentColors?: Record<string, string>;
+ environmentLabelStyle?: EnvironmentLabelStyle;
};
export type User = {
diff --git a/frontend/src/lib/types/diagnostics.ts b/frontend/src/lib/types/diagnostics.ts
index bc2948a8f..e50c9c617 100644
--- a/frontend/src/lib/types/diagnostics.ts
+++ b/frontend/src/lib/types/diagnostics.ts
@@ -155,6 +155,26 @@ export interface GoroutineLeakReport {
scannedAt: string;
}
+export interface GoroutineFrame {
+ function: string;
+ file: string;
+ line: number;
+}
+
+export interface GoroutineGroup {
+ count: number;
+ /** Outermost non-runtime function, usually the goroutine's entry point. */
+ label: string;
+ /** Stack frames, innermost first. */
+ frames: GoroutineFrame[];
+}
+
+export interface GoroutineProfile {
+ total: number;
+ groups: GoroutineGroup[];
+ capturedAt: string;
+}
+
export type PprofProfile =
| 'heap'
| 'goroutine'
diff --git a/frontend/src/lib/utils/auth.ts b/frontend/src/lib/utils/auth.ts
index b1ad227bf..4a0361259 100644
--- a/frontend/src/lib/utils/auth.ts
+++ b/frontend/src/lib/utils/auth.ts
@@ -1,6 +1,6 @@
import { m } from '#lib/paraglide/messages.js';
import { APIError } from '#lib/services/api-service.js';
-import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID, type EnvironmentRef } from '#lib/stores/environment.store.svelte.js';
import userStore from '#lib/stores/user-store.svelte.js';
import { GLOBAL_SCOPE, SUDO_PERMISSION } from '#lib/types/auth.js';
import type { PermissionsManifest, User } from '#lib/types/auth.js';
@@ -10,6 +10,7 @@ import {
getRouteAccessSurfaces,
pathMatchesAccessSurface
} from '#lib/utils/access-policy.js';
+import { isEnvironmentOnline } from '#lib/utils/docker.js';
export function normalizeAuthenticationError(error: unknown, fallback: string): { kind: 'proxy' | 'other'; message: string } {
if (error instanceof APIError) {
@@ -115,13 +116,45 @@ function userHasAnyAccess(user: User): boolean {
return false;
}
+/** Whether a surface is reachable in `envId` or, while the all environments preview is on, in any shown environment. */
+export function canReachShownAccessSurface(
+ accessManifest: PermissionsManifest | null | undefined,
+ surfaceId: string | undefined,
+ user: User,
+ envId: string | undefined
+): boolean {
+ const envIds = environmentStore.selected ? [envId, ...environmentStore.shown.map((env) => env.id)] : [envId];
+ return envIds.some((id) => canReachAccessSurface(accessManifest, surfaceId, user, id));
+}
+
+/**
+ * The first shown environment that can open `path` when `envId` cannot. Pages that show one environment
+ * at a time load the selected one, so the preview switches to this one instead of failing.
+ */
+export function shownEnvironmentForRoute(
+ path: string,
+ user: User,
+ envId: string | undefined,
+ accessManifest: PermissionsManifest | null | undefined
+): EnvironmentRef | undefined {
+ const surface = getRouteAccessSurfaces(accessManifest).find((candidate) => pathMatchesAccessSurface(path, candidate));
+ if (!surface || canReachAccessSurface(accessManifest, surface.id, user, envId)) return undefined;
+ const reachable = environmentStore.shown.filter((env) => canReachAccessSurface(accessManifest, surface.id, user, env.id));
+ // An online environment is preferred, so the page can load; local is always reachable.
+ const online = reachable.find((env) => {
+ const environment = environmentStore.available.find((candidate) => candidate.id === env.id);
+ return env.id === LOCAL_DOCKER_ENVIRONMENT_ID || (!!environment && isEnvironmentOnline(environment));
+ });
+ return online ?? reachable[0];
+}
+
function pickFallbackRoute(
user: User,
envId: string | undefined,
accessManifest: PermissionsManifest | null | undefined
): string {
for (const surface of getFallbackAccessSurfaces(accessManifest)) {
- if (canReachAccessSurface(accessManifest, surface.id, user, envId)) {
+ if (canReachShownAccessSurface(accessManifest, surface.id, user, envId)) {
return surface.url ?? '/no-access';
}
}
@@ -164,7 +197,7 @@ export function getAuthRedirectPath(
}
const surface = getRouteAccessSurfaces(accessManifest).find((candidate) => pathMatchesAccessSurface(path, candidate));
- if (surface && !canReachAccessSurface(accessManifest, surface.id, user, envId)) {
+ if (surface && !canReachShownAccessSurface(accessManifest, surface.id, user, envId)) {
const fallback = pickFallbackRoute(user, envId, accessManifest);
return fallback === path ? '/no-access' : fallback;
}
diff --git a/frontend/src/lib/utils/bulk-actions.ts b/frontend/src/lib/utils/bulk-actions.ts
index 053eabc37..539bf67db 100644
--- a/frontend/src/lib/utils/bulk-actions.ts
+++ b/frontend/src/lib/utils/bulk-actions.ts
@@ -4,10 +4,12 @@ import { markActivityToastShown } from '#lib/components/activity/activity-comple
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { runWithActivityBatchId } from '#lib/services/api-service.js';
import { activityStore } from '#lib/stores/activity.store.svelte.js';
+import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID } from '#lib/stores/environment.store.svelte.js';
import type { Activity } from '#lib/types/activity.type.js';
import type { Result } from '#lib/types/result.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+import { parseRowKey } from '#lib/utils/environments.js';
import { streamCacheBuster } from '#lib/utils/streaming.js';
import { tryCatch } from '#lib/utils/try-catch.js';
@@ -33,10 +35,10 @@ export interface BulkOperationResult {
}
export interface RunBulkOperationOptions<T> {
- /** The ids to operate on. A no-op when empty. */
+ /** The ids or table row keys to operate on. A no-op when empty. */
ids: string[];
- /** Runs the operation for a single id. May throw — failures are tallied. */
- run: (id: string) => Promise<T>;
+ /** Runs the operation for a single id in its row's environment. May throw — failures are tallied. */
+ run: (id: string, environmentId: string) => Promise<T>;
messages: BulkOperationMessages;
/** Toggle a loading flag around the whole run. */
setLoading?: (loading: boolean) => void;
@@ -78,7 +80,8 @@ async function runBulkOperation<T>({
let firstActivityId: string | undefined;
const activityIds: string[] = [];
- const tally = (id: string, outcome: Result<T>) => {
+ const tally = (key: string, outcome: Result<T>) => {
+ const { id } = parseRowKey(key);
if (outcome.error) {
result.failed += 1;
onItemFailure?.(id, outcome.error);
@@ -96,14 +99,29 @@ async function runBulkOperation<T>({
setLoading?.(true);
try {
- // Multi-item runs share a batch id so the Activity Center renders one
+ // Multi-item runs share a batch id per environment so the Activity Center renders one
// batch row. Each request is STARTED inside the synchronous batch scope
// (awaited outside it), so concurrent unrelated actions never inherit it.
// streamCacheBuster instead of bare crypto.randomUUID: the latter is
// secure-context-only (throws on plain-HTTP deployments), and the fallback
// format matches the backend batch-id pattern ^[A-Za-z0-9_-]{1,64}$.
- const batchId = total > 1 ? streamCacheBuster() : null;
- const startRun = (id: string) => (batchId ? runWithActivityBatchId(batchId, () => tryCatch(run(id))) : tryCatch(run(id)));
+ const counts = new Map<string | undefined, number>();
+ for (const key of ids) {
+ const { environmentId } = parseRowKey(key);
+ counts.set(environmentId, (counts.get(environmentId) ?? 0) + 1);
+ }
+ const batchIds = new Map(
+ Array.from(counts, ([environmentId, count]) => [environmentId, count > 1 ? streamCacheBuster() : null])
+ );
+ const startRun = (key: string) => {
+ const { id, environmentId } = parseRowKey(key);
+ const batchId = batchIds.get(environmentId);
+ // Plain ids belong to the selected environment, as the services assume.
+ const rowEnvironmentId = environmentId ?? environmentStore.selected?.id ?? LOCAL_DOCKER_ENVIRONMENT_ID;
+ return batchId
+ ? runWithActivityBatchId(batchId, () => tryCatch(run(id, rowEnvironmentId)))
+ : tryCatch(run(id, rowEnvironmentId));
+ };
if (sequential) {
for (const id of ids) {
tally(id, await startRun(id));
@@ -152,8 +170,8 @@ export interface BulkConfirmAndRunOptions<T> extends Omit<RunBulkOperationOption
destructive?: boolean;
/** Optional confirm-dialog checkboxes (e.g. force / remove volumes). */
checkboxes?: BulkConfirmCheckbox[];
- /** Runs the operation for a single id, given the resolved checkbox states. */
- run: (id: string, checkboxStates: Record<string, boolean>) => Promise<T>;
+ /** Runs the operation for a single id in its row's environment, given the resolved checkbox states. */
+ run: (id: string, environmentId: string, checkboxStates: Record<string, boolean>) => Promise<T>;
}
/**
@@ -190,7 +208,7 @@ export function bulkConfirmAndRun<T>({
action: async (checkboxStates) => {
await runBulkOperation({
ids,
- run: (id) => run(id, checkboxStates),
+ run: (id, environmentId) => run(id, environmentId, checkboxStates),
messages,
setLoading,
onComplete,
diff --git a/frontend/src/lib/utils/container-actions.ts b/frontend/src/lib/utils/container-actions.ts
index b9a4e3e0a..19410123c 100644
--- a/frontend/src/lib/utils/container-actions.ts
+++ b/frontend/src/lib/utils/container-actions.ts
@@ -17,7 +17,7 @@ type ContainerRemoveStatus = 'removing' | '';
type ContainerLifecycleActionConfig = {
status: Exclude<ContainerLifecycleStatus, ''>;
- run: (id: string) => Promise<unknown>;
+ run: (id: string, environmentId?: string) => Promise<unknown>;
success: () => string;
failure: () => string;
};
@@ -25,31 +25,31 @@ type ContainerLifecycleActionConfig = {
const containerLifecycleActionConfigs: Record<ContainerLifecycleAction, ContainerLifecycleActionConfig> = {
start: {
status: 'starting',
- run: (id) => containerService.startContainer(id),
+ run: (id, environmentId) => containerService.startContainer(id, environmentId),
success: () => m.containers_start_success(),
failure: () => m.containers_start_failed()
},
stop: {
status: 'stopping',
- run: (id) => containerService.stopContainer(id),
+ run: (id, environmentId) => containerService.stopContainer(id, environmentId),
success: () => m.containers_stop_success(),
failure: () => m.containers_stop_failed()
},
restart: {
status: 'restarting',
- run: (id) => containerService.restartContainer(id),
+ run: (id, environmentId) => containerService.restartContainer(id, environmentId),
success: () => m.containers_restart_success(),
failure: () => m.containers_restart_failed()
},
pause: {
status: 'pausing',
- run: (id) => containerService.pauseContainer(id),
+ run: (id, environmentId) => containerService.pauseContainer(id, environmentId),
success: () => m.containers_pause_success(),
failure: () => m.containers_pause_failed()
},
unpause: {
status: 'unpausing',
- run: (id) => containerService.unpauseContainer(id),
+ run: (id, environmentId) => containerService.unpauseContainer(id, environmentId),
success: () => m.containers_unpause_success(),
failure: () => m.containers_unpause_failed()
}
@@ -58,6 +58,7 @@ const containerLifecycleActionConfigs: Record<ContainerLifecycleAction, Containe
type RunContainerLifecycleActionOptions = {
action: ContainerLifecycleAction;
containerId: string;
+ environmentId?: string;
setStatus: (status: ContainerLifecycleStatus) => void;
onRefresh?: () => Promise<unknown> | unknown;
};
@@ -65,6 +66,7 @@ type RunContainerLifecycleActionOptions = {
export async function runContainerLifecycleAction({
action,
containerId,
+ environmentId,
setStatus,
onRefresh
}: RunContainerLifecycleActionOptions) {
@@ -76,7 +78,7 @@ export async function runContainerLifecycleAction({
const operationResult = await tryCatch(
(async () => {
await handleApiResultWithCallbacks({
- result: await tryCatch(config.run(containerId)),
+ result: await tryCatch(config.run(containerId, environmentId)),
message: config.failure(),
setLoadingState: (value) => {
setStatus(value ? config.status : '');
@@ -99,6 +101,7 @@ export async function runContainerLifecycleAction({
type ConfirmAndRemoveContainerOptions = {
containerId: string;
containerName: string;
+ environmentId?: string;
setStatus: (status: ContainerRemoveStatus) => void;
onRefresh?: () => Promise<unknown> | unknown;
};
@@ -106,6 +109,7 @@ type ConfirmAndRemoveContainerOptions = {
export function confirmAndRemoveContainer({
containerId,
containerName,
+ environmentId,
setStatus,
onRefresh
}: ConfirmAndRemoveContainerOptions) {
@@ -124,7 +128,7 @@ export function confirmAndRemoveContainer({
const volumes = !!checkboxStates['volumes'];
setStatus('removing');
await handleApiResultWithCallbacks({
- result: await tryCatch(containerService.deleteContainer(containerId, { force, volumes })),
+ result: await tryCatch(containerService.deleteContainer(containerId, { force, volumes, environmentId })),
message: m.containers_remove_failed(),
setLoadingState: (value) => {
setStatus(value ? 'removing' : '');
@@ -176,7 +180,7 @@ export function confirmAndUpdateContainer({
canReadActivity ? activityToastOptions(activity.id, false, environmentId) : undefined
);
await onAccepted?.(activity, environmentId);
- if (!canReadActivity && environmentStore.selected?.id === environmentId) await onRefresh?.();
+ if (!canReadActivity && environmentStore.shown.some((env) => env.id === environmentId)) await onRefresh?.();
}
});
}
diff --git a/frontend/src/lib/utils/container-update-activities.ts b/frontend/src/lib/utils/container-update-activities.ts
index 8831f5932..da168fb99 100644
--- a/frontend/src/lib/utils/container-update-activities.ts
+++ b/frontend/src/lib/utils/container-update-activities.ts
@@ -3,7 +3,7 @@ import type { Activity } from '#lib/types/activity.type.js';
/** Tracks accepted updates and updates that were already running when a view mounted. */
export function createContainerUpdateActivityTracker(
- environmentId: () => string,
+ environmentIds: () => string[],
onTerminal: (activity: Activity) => void,
resourceId?: () => string
) {
@@ -11,10 +11,10 @@ export function createContainerUpdateActivityTracker(
const acceptedIds = new Set<string>();
const terminalIds = new Set<string>();
const refreshedIds = new Set<string>();
- let observedKey = `${environmentId()}:${resourceId?.() ?? ''}`;
+ let observedKey = `${environmentIds().join(',')}:${resourceId?.() ?? ''}`;
function observe(activities: readonly Activity[]) {
- const currentKey = `${environmentId()}:${resourceId?.() ?? ''}`;
+ const currentKey = `${environmentIds().join(',')}:${resourceId?.() ?? ''}`;
if (observedKey !== currentKey) {
activeIds.clear();
acceptedIds.clear();
@@ -26,7 +26,7 @@ export function createContainerUpdateActivityTracker(
if (
activity.type !== 'auto_update' ||
activity.resourceType !== 'container' ||
- (activity.sourceEnvironmentId || activity.environmentId) !== environmentId() ||
+ !environmentIds().includes(activity.sourceEnvironmentId || activity.environmentId || '') ||
(resourceId && activity.resourceId !== resourceId())
)
continue;
diff --git a/frontend/src/lib/utils/environments.ts b/frontend/src/lib/utils/environments.ts
new file mode 100644
index 000000000..a32b3b04d
--- /dev/null
+++ b/frontend/src/lib/utils/environments.ts
@@ -0,0 +1,333 @@
+import { error } from '@sveltejs/kit';
+import { toast } from 'svelte-sonner';
+
+import { TABLE_PAGE_SIZE_ALL } from '#lib/constants/table-pagination.js';
+import { m } from '#lib/paraglide/messages.js';
+import type { APIRequestConfig } from '#lib/services/api-service.js';
+import {
+ allEnvironmentsPreview,
+ environmentStore,
+ LOCAL_DOCKER_ENVIRONMENT_ID,
+ type EnvironmentRef
+} from '#lib/stores/environment.store.svelte.js';
+import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
+import { extractApiErrorMessage } from '#lib/utils/api.js';
+import { hasPermission } from '#lib/utils/auth.js';
+import { tryCatch } from '#lib/utils/try-catch.js';
+
+/** A row tagged by fetchAcrossEnvironments; `environmentTagged` tells it apart from DTOs that carry an environment. */
+export type EnvironmentRow<T> = T & { environmentId: string; environmentName: string; environmentTagged: true };
+export type EnvironmentFailure = { environment: EnvironmentRef; message: string };
+
+type Groups<T> = { groups?: { groupName: string; items: T[] }[] };
+type Page<T> = Paginated<T, unknown> & Groups<T>;
+export type EnvironmentPage<P extends Page<object>> = Omit<P, 'data' | 'groups'> & {
+ data: EnvironmentRow<P['data'][number]>[];
+ groups?: { groupName: string; items: EnvironmentRow<P['data'][number]>[] }[];
+ /** Environments whose request failed; the list renders without them. */
+ failedEnvironments?: EnvironmentFailure[];
+};
+
+// Unit separator: resource IDs never contain it, so table keys stay unambiguous.
+const KEY_SEPARATOR = '\u001f';
+
+/** Table row key; tagged rows are keyed by environment, since IDs can repeat across environments. */
+export function rowKey(row: { id: string; environmentId?: string; environmentTagged?: boolean }): string {
+ return row.environmentTagged && row.environmentId !== undefined ? `${row.environmentId}${KEY_SEPARATOR}${row.id}` : row.id;
+}
+
+export function tagEnvironment<T extends object>(row: T, environment: EnvironmentRef): EnvironmentRow<T> {
+ return { ...row, environmentId: environment.id, environmentName: environment.name, environmentTagged: true };
+}
+
+export function parseRowKey(key: string): { environmentId?: string; id: string } {
+ const index = key.indexOf(KEY_SEPARATOR);
+ if (index < 0) return { id: key };
+ return { environmentId: key.slice(0, index), id: key.slice(index + 1) };
+}
+
+export function environmentName(environmentId: string): string {
+ return environmentStore.available.find((env) => env.id === environmentId)?.name ?? environmentId;
+}
+
+/** Filter key of the environment facet; fetchAcrossEnvironments consumes it, so the backend never sees it. */
+export const ENVIRONMENT_FILTER = 'environment';
+
+/** Environment filter IDs among `environments`; stale IDs are dropped, and it is empty with one environment. */
+export function environmentFilterIds(value: unknown, environments: EnvironmentRef[] = environmentStore.shown): string[] {
+ if (environments.length < 2 || !Array.isArray(value)) return [];
+ return value.map(String).filter((id) => environments.some((env) => env.id === id));
+}
+
+/**
+ * Shown environments a page-wide action runs in: those granting every permission. When none do, all
+ * shown ones are returned so the server still reports the denial, as with one environment.
+ */
+export function actionEnvironments(...permissions: string[]): EnvironmentRef[] {
+ const permitted = environmentStore.shown.filter((env) => permissions.every((permission) => hasPermission(permission, env.id)));
+ return permitted.length > 0 ? permitted : environmentStore.shown;
+}
+
+/** Whether a permission is held in any shown environment; row actions check the row's own environment. */
+export function hasShownPermission(permission: string): boolean {
+ return environmentStore.shown.some((env) => hasPermission(permission, env.id));
+}
+
+/** Link to a resource detail page; `?env=` is added only for an environment other than the selected one. */
+export function environmentHref(path: string, environmentId: string): string {
+ if (environmentId === (environmentStore.selected?.id ?? LOCAL_DOCKER_ENVIRONMENT_ID)) return path;
+ return `${path}${path.includes('?') ? '&' : '?'}env=${encodeURIComponent(environmentId)}`;
+}
+
+/**
+ * Detail loaders: the `?env=` environment, otherwise the selected one. With the preview on, an `env` that is
+ * not shown is a 404 rather than the selected environment's resource of the same name. With it off, `env` is ignored.
+ */
+export async function resolveDetailEnvironmentId(url: URL): Promise<string> {
+ const current = await environmentStore.getCurrentEnvironmentId();
+ const requested = url.searchParams.get('env');
+ if (!requested || !allEnvironmentsPreview.current) return current;
+ if (!environmentStore.shown.some((env) => env.id === requested))
+ error(404, m.common_not_found_title({ resource: m.resource_environment_cap() }));
+ return requested;
+}
+
+/**
+ * Destination for a create: the picked shown environment that grants `permission`, else the selected
+ * one, else the first shown environment that grants it. With one shown environment this is the selected one.
+ */
+export function destinationEnvironmentId(picked: string, permission: string): string {
+ const selected = environmentStore.selected?.id ?? LOCAL_DOCKER_ENVIRONMENT_ID;
+ const permitted = environmentStore.shown.filter((env) => hasPermission(permission, env.id)).map((env) => env.id);
+ const candidate = permitted.includes(picked) ? picked : selected;
+ return permitted.includes(candidate) ? candidate : (permitted[0] ?? candidate);
+}
+
+/**
+ * List query scopes an operation in these environments affects: each environment's own, their
+ * merged one and the currently shown one. With one environment shown this is just its ID.
+ */
+export function listScopes(environmentIds: string[]): string[] {
+ return [...new Set([...environmentIds, environmentIds.join(','), environmentStore.shownKey])];
+}
+
+/** Appended to an existing confirmation when an action runs across several environments. */
+export function acrossEnvironmentsNote(environments: EnvironmentRef[]): string {
+ if (environments.length < 2) return '';
+ return m.all_environments_confirm_note({ count: environments.length });
+}
+
+/**
+ * Runs a read once per environment; failures are returned beside the values. When reporting inline
+ * (by default, when several environments are read), an access-denied response is left to the inline
+ * alert instead of a toast, and a failure names its environment.
+ */
+export async function collectAcrossEnvironments<T>(
+ environments: EnvironmentRef[],
+ run: (environmentId: string, config: APIRequestConfig) => Promise<T>,
+ reportInline = environments.length > 1
+): Promise<{ values: { environment: EnvironmentRef; value: T }[]; failures: EnvironmentFailure[] }> {
+ const config: APIRequestConfig = { suppressAccessDeniedToast: reportInline };
+ const outcomes = await Promise.all(
+ environments.map(async (environment) => ({ environment, result: await tryCatch(run(environment.id, config)) }))
+ );
+ const failed = outcomes.filter((outcome) => outcome.result.error !== null);
+ if (failed.length === 1 && outcomes.length === 1 && !reportInline) throw failed[0]!.result.error;
+ const failures = failed.map(({ environment, result }) => ({ environment, message: extractApiErrorMessage(result.error) }));
+ if (failed.length > 0 && failed.length === outcomes.length) {
+ throw new Error(failures.map(({ environment, message }) => `${environment.name}: ${message}`).join('\n'));
+ }
+ return {
+ values: outcomes.flatMap(({ environment, result }) => (result.error === null ? [{ environment, value: result.data }] : [])),
+ failures
+ };
+}
+
+/**
+ * Runs a user-initiated action once per environment, like the CLI. A failing environment is
+ * toasted and the others still return; it throws only when every environment failed.
+ */
+export async function settleAcrossEnvironments<T>(
+ environments: EnvironmentRef[],
+ run: (environmentId: string) => Promise<T>
+): Promise<{ environment: EnvironmentRef; value: T }[]> {
+ const { values, failures } = await collectAcrossEnvironments(environments, (id) => run(id));
+ for (const { environment, message } of failures) {
+ toast.error(m.all_environments_request_failed({ environment: environment.name }), {
+ id: `environment-request-failed-${environment.id}`,
+ description: message
+ });
+ }
+ return values;
+}
+
+function sumNumbers<C extends object>(values: C[]): C {
+ const total: Record<string, unknown> = { ...values[0] };
+ for (const value of values.slice(1)) {
+ for (const [key, entry] of Object.entries(value)) {
+ if (typeof entry === 'number') total[key] = Number(total[key] ?? 0) + entry;
+ }
+ }
+ return total as C;
+}
+
+/** Sums numeric count fields across environments; failing environments are reported, not counted. */
+export async function sumAcrossEnvironments<C extends object>(
+ environments: EnvironmentRef[],
+ fetch: (environmentId: string, config: APIRequestConfig) => Promise<C>
+): Promise<C & { failedEnvironments: EnvironmentFailure[] }> {
+ const { values, failures } = await collectAcrossEnvironments(environments, fetch);
+ return { ...sumNumbers(values.map((result) => result.value)), failedEnvironments: failures };
+}
+
+/** Adds failures from related reads, such as counts or tags, to a list's inline alert, once per environment. */
+export function withFailedEnvironments<P extends { failedEnvironments?: EnvironmentFailure[] }>(
+ page: P,
+ ...related: (EnvironmentFailure[] | undefined)[]
+): P {
+ const failures = [page.failedEnvironments, ...related].flatMap((list) => list ?? []);
+ if (failures.length === 0) return page;
+ return {
+ ...page,
+ failedEnvironments: failures.filter(
+ (failure, index) => failures.findIndex((other) => other.environment.id === failure.environment.id) === index
+ )
+ };
+}
+
+/** Orders two sort values, comparing arrays element by element; missing values always sort last, whatever the direction. */
+function compareSortValues(left: unknown, right: unknown, sign: number): number {
+ const leftMissing = left === undefined || left === null;
+ const rightMissing = right === undefined || right === null;
+ if (leftMissing || rightMissing) return Number(leftMissing) - Number(rightMissing);
+ if (Array.isArray(left) && Array.isArray(right)) {
+ return left.reduce<number>((result, value, index) => result || compareSortValues(value, right[index], sign), 0);
+ }
+ if (typeof left === 'number' && typeof right === 'number') return sign * (left - right);
+ // The backend sorts true first when ascending.
+ if (typeof left === 'boolean' && typeof right === 'boolean') return sign * (Number(right) - Number(left));
+ return sign * String(left).localeCompare(String(right), undefined, { numeric: true });
+}
+
+/** Splits units into pages the way the backend pages groups: a unit is never split, so the one crossing the limit finishes its page. */
+function pageUnits<T>(units: T[][], limit: number): T[][][] {
+ if (limit <= 0) return [units];
+ const pages: T[][][] = [[]];
+ let count = 0;
+ for (const unit of units) {
+ pages.at(-1)!.push(unit);
+ count += unit.length;
+ if (count >= limit) {
+ pages.push([]);
+ count = 0;
+ }
+ }
+ if (pages.length > 1 && pages.at(-1)!.length === 0) pages.pop();
+ return pages;
+}
+
+/**
+ * Runs the same list request per environment and tags each row with its environment. With one
+ * environment the request passes through; with several, every row is fetched, merged, sorted
+ * and sliced to the requested page. `sortValue` reads computed sort columns; it defaults to the
+ * row field named by the column. Same-named groups merge across environments and are paged whole.
+ * An `environment` filter narrows the environments queried.
+ */
+export async function fetchAcrossEnvironments<
+ P extends Page<T>,
+ O extends SearchPaginationSortRequest,
+ T extends object = P['data'][number]
+>(
+ environments: EnvironmentRef[],
+ options: O,
+ fetch: (environmentId: string, options: O, config: APIRequestConfig) => Promise<P>,
+ sortValue: (row: T, column: string) => unknown = (row, column) => row[column as keyof T]
+): Promise<EnvironmentPage<P>> {
+ const { [ENVIRONMENT_FILTER]: environmentFilter, ...filters } = options.filters ?? {};
+ // Picks are checked against every shown environment, so picking only ones this page skips shows nothing.
+ const picked = environmentFilterIds(environmentFilter);
+ const targets = picked.length > 0 ? environments.filter((env) => picked.includes(env.id)) : environments;
+ // The environment filter and sort are applied here, never by an environment's API.
+ const sortsByEnvironment = options.sort?.column === ENVIRONMENT_FILTER;
+ const scoped: O = { ...options, filters: options.filters && filters, sort: sortsByEnvironment ? undefined : options.sort };
+ if (targets.length === 0) {
+ const pagination = { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: options.pagination?.limit ?? 0 };
+ return { data: [], pagination, failedEnvironments: [] } as unknown as EnvironmentPage<P>;
+ }
+ const merging = targets.length > 1;
+ const request = merging ? { ...scoped, pagination: { page: 1, limit: TABLE_PAGE_SIZE_ALL } } : scoped;
+ // Filtering to one of several environments still reports its failure the merged way.
+ const { values: pages, failures } = await collectAcrossEnvironments(
+ targets,
+ (id, config) => fetch(id, request, config),
+ environments.length > 1
+ );
+ const tag = <R extends object>(environment: EnvironmentRef, rows: R[]) => rows.map((row) => tagEnvironment(row, environment));
+ const { environment: firstEnvironment, value: first } = pages[0]!;
+ // Environments without rows omit groups, so any response having them decides. If one with rows has none
+ // (an older agent), the merged list stays flat rather than dropping its rows.
+ const grouped = pages.some(({ value }) => value.groups) && pages.every(({ value }) => value.groups || value.data.length === 0);
+ if (!merging) {
+ return {
+ ...first,
+ data: tag(firstEnvironment, first.data),
+ groups: first.groups?.map((group) => ({ ...group, items: tag(firstEnvironment, group.items) })),
+ failedEnvironments: []
+ };
+ }
+
+ const { column, direction } = options.sort ?? {};
+ const sign = direction === 'desc' ? -1 : 1;
+ const rowSortValue = (row: EnvironmentRow<T>, sortColumn: string) =>
+ sortsByEnvironment ? row.environmentName : sortValue(row, sortColumn);
+ const rows = pages
+ .flatMap(({ environment, value }) => tag(environment, value.data))
+ .sort(
+ (a, b) =>
+ (column ? compareSortValues(rowSortValue(a, column), rowSortValue(b, column), sign) : 0) ||
+ a.environmentName.localeCompare(b.environmentName) ||
+ a.environmentId.localeCompare(b.environmentId)
+ );
+
+ // Group items are separate objects from the data rows, so membership is matched by environment and ID.
+ const memberKey = (environmentId: string, row: object) =>
+ `${environmentId}${KEY_SEPARATOR}${'id' in row ? String(row.id) : ''}`;
+ const groupOf = new Map(
+ pages.flatMap(({ environment, value }) =>
+ (value.groups ?? []).flatMap((group) =>
+ group.items.map((item) => [memberKey(environment.id, item), group.groupName] as const)
+ )
+ )
+ );
+ // Same-named groups merge across environments and follow the merged row order, like the backend groups its sorted rows.
+ const groups = new Map<string, { groupName: string; items: typeof rows }>();
+ for (const row of grouped ? rows : []) {
+ const groupName = groupOf.get(memberKey(row.environmentId, row));
+ if (groupName === undefined) continue;
+ const entry = groups.get(groupName) ?? { groupName, items: [] };
+ entry.items.push(row);
+ groups.set(groupName, entry);
+ }
+
+ const limit = options.pagination?.limit ?? TABLE_PAGE_SIZE_ALL;
+ const groupList = [...groups.values()];
+ const pageList = pageUnits(grouped ? groupList.map((group) => group.items) : rows.map((row) => [row]), limit);
+ const page = Math.min(limit > 0 ? (options.pagination?.page ?? 1) : 1, pageList.length);
+ const selected = pageList[page - 1]!;
+ const totals = sumNumbers(pages.map(({ value }) => value.pagination));
+ return {
+ ...first,
+ data: selected.flat(),
+ pagination: {
+ ...totals,
+ currentPage: page,
+ itemsPerPage: limit > 0 ? limit : totals.totalItems,
+ totalPages: pageList.length
+ },
+ counts: pages.some(({ value }) => value.counts)
+ ? sumNumbers(pages.flatMap(({ value }) => (value.counts ? [value.counts] : [])))
+ : undefined,
+ groups: grouped ? groupList.filter((group) => selected.includes(group.items)) : undefined,
+ failedEnvironments: failures
+ };
+}
diff --git a/frontend/src/lib/utils/resource-list-page.svelte.ts b/frontend/src/lib/utils/resource-list-page.svelte.ts
index 340266197..b486030fd 100644
--- a/frontend/src/lib/utils/resource-list-page.svelte.ts
+++ b/frontend/src/lib/utils/resource-list-page.svelte.ts
@@ -5,6 +5,7 @@ export class ResourceListPageState<TReq> {
selectedIds = $state<string[]>([]);
isCreateDialogOpen = $state(false);
envId = $derived(environmentStore.selected?.id || '0');
+ scope = $derived(environmentStore.shownKey);
constructor(requestOptions: TReq) {
this.requestOptions = requestOptions;
diff --git a/frontend/src/lib/utils/table-action-types.ts b/frontend/src/lib/utils/table-action-types.ts
index 3babeda32..afbf173a0 100644
--- a/frontend/src/lib/utils/table-action-types.ts
+++ b/frontend/src/lib/utils/table-action-types.ts
@@ -1,6 +1,6 @@
export type TableActionConfig<TStatus extends string> = {
status: TStatus;
- run: (id: string) => Promise<unknown>;
+ run: (id: string, environmentId: string) => Promise<unknown>;
success: () => string;
failure: () => string;
};
@@ -10,7 +10,7 @@ export type TableBulkActionConfig<TLoadingKey extends string> = {
message: (count: number) => string;
label: string;
loadingKey: TLoadingKey;
- run: (id: string) => Promise<unknown>;
+ run: (id: string, environmentId: string) => Promise<unknown>;
success: (count: number) => string;
partial: (success: number, total: number, failed: number) => string;
failure: () => string;
diff --git a/frontend/src/lib/utils/tables.ts b/frontend/src/lib/utils/tables.ts
index f4fcc87b0..9ccf1be1b 100644
--- a/frontend/src/lib/utils/tables.ts
+++ b/frontend/src/lib/utils/tables.ts
@@ -150,11 +150,14 @@ export async function resolveListPageLoadContext(
) {
const parentData = (await parent()) as { queryClient: QueryClientLike };
const envId = await environmentStore.getCurrentEnvironmentId();
+ const environments = await environmentStore.getShownEnvironments();
const requestOptions = resolveInitialListPageRequest(persistKey, sort, limit);
return {
queryClient: parentData.queryClient,
envId,
+ environments,
+ scope: environmentStore.shownKey,
requestOptions
};
}
diff --git a/frontend/src/lib/utils/update-actions.ts b/frontend/src/lib/utils/update-actions.ts
index ed7963053..6d002ab5b 100644
--- a/frontend/src/lib/utils/update-actions.ts
+++ b/frontend/src/lib/utils/update-actions.ts
@@ -6,10 +6,10 @@ import BaseAPIService from '#lib/services/api-service.js';
import systemUpgradeService from '#lib/services/api/system-upgrade-service.js';
import { imageService } from '#lib/services/image-service.js';
import { userService } from '#lib/services/user-service.js';
-import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { AutoUpdateResourceType, AutoUpdateResult } from '#lib/types/automation.js';
import { activityToastOptions } from '#lib/utils/activity-toast.js';
import { toastUpgradeError } from '#lib/utils/api.js';
+import { acrossEnvironmentsNote, actionEnvironments, settleAcrossEnvironments } from '#lib/utils/environments.js';
import { tryCatch } from '#lib/utils/try-catch.js';
/**
@@ -19,8 +19,12 @@ import { tryCatch } from '#lib/utils/try-catch.js';
*/
/** Applies pending updates for a single resource via a scoped updater run. */
-export function applyScopedUpdate(type: Extract<AutoUpdateResourceType, 'container' | 'project'>, id: string) {
- return imageService.runAutoUpdate({ type, resourceIds: [id] });
+export function applyScopedUpdate(
+ type: Extract<AutoUpdateResourceType, 'container' | 'project'>,
+ id: string,
+ environmentId?: string
+) {
+ return imageService.runAutoUpdate({ type, resourceIds: [id] }, environmentId);
}
type ThrowOnUpdateFailureOptions = {
@@ -111,13 +115,14 @@ async function disarmWhenBackendResponds() {
}
/**
- * Confirms, then applies every pending update on the host (an empty-body
+ * Confirms, then applies every pending update on each shown host (an empty-body
* updater run — the same path the nightly auto-update job takes).
*/
export function confirmAndApplyAllUpdates({ setLoading, onRefresh }: ConfirmAndApplyAllUpdatesOptions) {
+ const environments = actionEnvironments('image-updates:check');
openConfirmDialog({
title: m.update_all(),
- message: m.updates_update_all_confirm_message(),
+ message: `${m.updates_update_all_confirm_message()} ${acrossEnvironmentsNote(environments)}`.trim(),
confirm: {
label: m.update_all(),
destructive: false,
@@ -127,13 +132,13 @@ export function confirmAndApplyAllUpdates({ setLoading, onRefresh }: ConfirmAndA
// through self-upgrade, restarting this backend. Only the local
// manager hosts this frontend's API, so only it needs the flag that
// makes the restart a recoverable reconnect instead of a logout.
- const envId = await environmentStore.getCurrentEnvironmentId();
- const restartsThisBackend = envId === MANAGER_ENVIRONMENT_ID;
+ const restartsThisBackend = environments.some((env) => env.id === MANAGER_ENVIRONMENT_ID);
if (restartsThisBackend) BaseAPIService.setUpgradeInProgress(true);
try {
const operationResult = await tryCatch(
(async () => {
- summarizeUpdateResult(await imageService.runAutoUpdate());
+ const results = await settleAcrossEnvironments(environments, (id) => imageService.runAutoUpdate(undefined, id));
+ for (const { value } of results) summarizeUpdateResult(value);
await onRefresh?.();
})()
);
diff --git a/frontend/src/lib/utils/user-preferences.ts b/frontend/src/lib/utils/user-preferences.ts
new file mode 100644
index 000000000..7ce883ff1
--- /dev/null
+++ b/frontend/src/lib/utils/user-preferences.ts
@@ -0,0 +1,48 @@
+import { toast } from 'svelte-sonner';
+
+import { m } from '#lib/paraglide/messages.js';
+import { userService } from '#lib/services/user-service.js';
+import userStore from '#lib/stores/user-store.svelte.js';
+import type { User, UserPreferences } from '#lib/types/auth.js';
+import { tryCatch } from '#lib/utils/try-catch.js';
+
+let saves = Promise.resolve();
+// The user as last saved, and the changes still waiting to save, in order.
+let confirmed: User | undefined;
+const pending: Partial<UserPreferences>[] = [];
+
+/**
+ * Applies preferences to the current user at once, then saves them in order, so a quick follow-up
+ * change builds on this one. After each save the user is the saved one plus the changes still
+ * waiting; a failed change is dropped and its error shown.
+ */
+export function saveUserPreferences(patch: Partial<UserPreferences>): Promise<void> {
+ const current = userStore.current;
+ if (!current) return Promise.resolve();
+ if (pending.length === 0) confirmed = current;
+ pending.push(patch);
+ void userStore.setUser({ ...current, preferences: { ...current.preferences, ...patch } });
+ // A save is dropped, store update included, once its user has signed out or another has signed in.
+ const signedIn = () => userStore.current?.id === current.id;
+ const save = saves.then(async () => {
+ if (!signedIn()) {
+ pending.shift();
+ return;
+ }
+ const operationResult = await tryCatch(userService.updateMyProfile({ preferences: patch }));
+ pending.shift();
+ if (!signedIn()) return;
+ if (operationResult.error !== null) {
+ const error = operationResult.error;
+
+ toast.error(error instanceof Error ? error.message : m.common_update_failed({ resource: m.account_preferences() }));
+ } else {
+ confirmed = operationResult.data;
+ }
+ const saved = confirmed ?? current;
+ await userStore.setUser({ ...saved, preferences: Object.assign({}, saved.preferences, ...pending) });
+ });
+ // One failed save must not stop the ones queued after it.
+ saves = save.catch(() => undefined);
+ return save;
+}
diff --git a/frontend/src/lib/utils/vulnerability.ts b/frontend/src/lib/utils/vulnerability.ts
index 3cbae7219..dac90e66f 100644
--- a/frontend/src/lib/utils/vulnerability.ts
+++ b/frontend/src/lib/utils/vulnerability.ts
@@ -1,6 +1,8 @@
import { toast } from 'svelte-sonner';
import { m } from '#lib/paraglide/messages.js';
+import { environmentStore, type EnvironmentRef } from '#lib/stores/environment.store.svelte.js';
+import { featureStore } from '#lib/stores/features.store.svelte.js';
import type {
BulkVulnerabilityFilters,
SeveritySummary,
@@ -13,10 +15,12 @@ import type {
} from '#lib/types/environment.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
+import { hasPermission } from '#lib/utils/auth.js';
+import type { EnvironmentPage, EnvironmentRow } from '#lib/utils/environments.js';
export type VulnerabilitySeverityBadgeVariant = 'red' | 'orange' | 'amber' | 'green' | 'gray';
export type VulnerabilitySeverityIconVariant = 'red' | 'orange' | 'amber' | 'emerald' | 'gray';
-export type VulnerabilityRow = VulnerabilityWithImage & { id: string };
+export type VulnerabilityRow = EnvironmentRow<VulnerabilityWithImage> & { id: string };
type VulnerabilitySeveritySource = Pick<Vulnerability, 'severity'>;
type VulnerabilityToastSource = Pick<VulnerabilityScanResult | VulnerabilityScanSummary, 'status' | 'activityId' | 'error'>;
@@ -61,10 +65,12 @@ export function getSeverityBarClass(severity: string): string {
export type ShareBarSegment = { key: string; label: string; count: number; barClass: string };
+const severityOrder = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'UNKNOWN'] as const;
+
// getSeveritySegments orders a severity summary from critical to unknown for share bars and legends.
export function getSeveritySegments(summary: SeveritySummary | null | undefined): ShareBarSegment[] {
if (!summary) return [];
- return (['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'UNKNOWN'] as const)
+ return severityOrder
.map((severity) => ({
key: severity,
label: getSeverityLabel(severity),
@@ -163,8 +169,46 @@ function getVulnerabilityKey(vulnerability: VulnerabilityWithImage, index: numbe
].join('-');
}
+/**
+ * Environments the security overview can read: shown ones with vulnerability management loaded and on,
+ * where the user may read vulnerabilities. Any other would fail the page.
+ */
+export function vulnerabilityOverviewEnvironments(): EnvironmentRef[] {
+ return environmentStore.shown.filter(
+ (env) => featureStore.isEnabled('vulnerabilityManagement', env.id) && hasPermission('vulnerabilities:read', env.id)
+ );
+}
+
+/**
+ * Environment the security overview reads: the selected one when it can, otherwise the first that can.
+ * Overviews hold scores and rankings, so they are not summed.
+ */
+export function vulnerabilityOverviewEnvironment(): EnvironmentRef | undefined {
+ const environments = vulnerabilityOverviewEnvironments();
+ return environments.find((env) => env.id === environmentStore.selected?.id) ?? environments[0];
+}
+
+/** Sort value for a vulnerability column; severity sorts by rank from unknown to critical, as the backend does. */
+export function vulnerabilitySortValue(vulnerability: VulnerabilityWithImage, column: string): unknown {
+ if (column !== 'severity') return vulnerability[column as keyof VulnerabilityWithImage];
+ const index = severityOrder.indexOf(vulnerability.severity as (typeof severityOrder)[number]);
+ return index < 0 ? 0 : severityOrder.length - 1 - index;
+}
+
+/**
+ * Shown environments with vulnerability management enabled. With several shown, ones whose features
+ * could not load stay in, so their failure shows inline with a retry instead of silently missing.
+ */
+export function vulnerabilityEnvironments(): EnvironmentRef[] {
+ const merging = environmentStore.shown.length > 1;
+ return environmentStore.shown.filter(
+ (env) =>
+ (merging && featureStore.status(env.id) === 'unavailable') || featureStore.isEnabled('vulnerabilityManagement', env.id)
+ );
+}
+
export function mapVulnerabilityPage(
- page: Paginated<VulnerabilityWithImage>,
+ page: EnvironmentPage<Paginated<VulnerabilityWithImage>>,
options: SearchPaginationSortRequest
): Paginated<VulnerabilityRow> {
const pageNumber = options.pagination?.page ?? page.pagination?.currentPage ?? 1;
diff --git a/frontend/src/lib/utils/watch-logs.ts b/frontend/src/lib/utils/watch-logs.ts
index a102ddc53..03c788a2c 100644
--- a/frontend/src/lib/utils/watch-logs.ts
+++ b/frontend/src/lib/utils/watch-logs.ts
@@ -10,12 +10,17 @@ import { ReconnectingWebSocket } from '#lib/utils/ws.js';
* operation began (application startup included) without dredging up history
* from previous runs. Returns a detach function that closes the stream.
*/
-export function attachProjectLogsToWatch(projectId: string, sinceEpochSeconds: number): () => void {
+export function attachProjectLogsToWatch(
+ projectId: string,
+ sinceEpochSeconds: number,
+ environmentId: string | undefined
+): () => void {
let active = true;
const client = new ReconnectingWebSocket<string>({
buildUrl: async () => {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ // The project's own environment; the selected one only when none is given.
+ const envId = environmentId ?? (await environmentStore.getCurrentEnvironmentId());
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
return `${protocol}://${window.location.host}/api/environments/${envId}/ws/projects/${projectId}/logs?follow=true&tail=all&since=${sinceEpochSeconds}&timestamps=false&format=json&batched=true`;
},
diff --git a/frontend/src/routes/(app)/account/+page.svelte b/frontend/src/routes/(app)/account/+page.svelte
index f4baaf5b5..a02da96c1 100644
--- a/frontend/src/routes/(app)/account/+page.svelte
+++ b/frontend/src/routes/(app)/account/+page.svelte
@@ -10,7 +10,7 @@
import * as ImageCropper from '#lib/components/ui/image-cropper/index.js';
import * as Tabs from '#lib/components/ui/tabs/index.js';
import { useUrlTab } from '#lib/hooks/use-url-tab.svelte.js';
- import { UserIcon, SettingsIcon } from '#lib/icons/index.js';
+ import { UserIcon, SettingsIcon, TestIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import { userService } from '#lib/services/user-service.js';
import settingsStore from '#lib/stores/config-store.svelte.js';
@@ -24,14 +24,16 @@
import AccountApiKeysPanel from './components/account-api-keys-panel.svelte';
import AccountPreferencesPanel from './components/account-preferences-panel.svelte';
import AccountSecurityPanel from './components/account-security-panel.svelte';
+ import AllEnvironmentsPreferences from './components/all-environments-preferences.svelte';
- type AccountTab = 'account' | 'preferences';
+ type AccountTab = 'account' | 'preferences' | 'previews';
const accountTabItems = $derived.by(
() =>
[
{ value: 'account', label: m.common_account(), icon: UserIcon },
- { value: 'preferences', label: m.account_preferences(), icon: SettingsIcon }
+ { value: 'preferences', label: m.account_preferences(), icon: SettingsIcon },
+ { value: 'previews', label: m.previews(), icon: TestIcon }
] satisfies TabItem[]
);
const urlTab = useUrlTab<AccountTab>({
@@ -383,6 +385,10 @@
<Tabs.Content value="preferences" class="mt-6">
<AccountPreferencesPanel />
</Tabs.Content>
+
+ <Tabs.Content value="previews" class="mt-6">
+ <AllEnvironmentsPreferences />
+ </Tabs.Content>
</Tabs.Root>
{:else}
<div class="py-12 text-center text-sm text-muted-foreground">{m.account_loading()}</div>
diff --git a/frontend/src/routes/(app)/account/components/account-preferences-panel.svelte b/frontend/src/routes/(app)/account/components/account-preferences-panel.svelte
index 268fded2e..20bc6e48f 100644
--- a/frontend/src/routes/(app)/account/components/account-preferences-panel.svelte
+++ b/frontend/src/routes/(app)/account/components/account-preferences-panel.svelte
@@ -1,6 +1,5 @@
<script lang="ts">
import { mode } from 'mode-watcher';
- import { toast } from 'svelte-sonner';
import AccentColorPicker from '#lib/components/accent-color/accent-color-picker.svelte';
import ApplicationThemePicker from '#lib/components/application-theme/application-theme-picker.svelte';
@@ -15,15 +14,14 @@
import { DEFAULT_LANDING_PAGE, getLandingPageNavItems } from '#lib/config/navigation-config.js';
import { DockIcon, MonitorSpeakerIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
- import { userService } from '#lib/services/user-service.js';
import { getLayoutMode, layoutModeStore, type LayoutMode } from '#lib/stores/layout-mode.store.svelte.js';
import userStore from '#lib/stores/user-store.svelte.js';
import type { ProjectEditorLayout, UserPreferences } from '#lib/types/auth.js';
import type { ApplicationTheme, IconCatalog } from '#lib/types/settings.js';
import { cn } from '#lib/utils.js';
import { getMobileNavigation } from '#lib/utils/navigation.js';
- import { applyGlassEffects, applyInterfaceAnimations, applyOledMode } from '#lib/utils/theme.svelte.js';
- import { tryCatch } from '#lib/utils/try-catch.js';
+ import { applyAccentColor, applyGlassEffects, applyInterfaceAnimations, applyOledMode } from '#lib/utils/theme.svelte.js';
+ import { saveUserPreferences } from '#lib/utils/user-preferences.js';
import { debounced } from '#lib/utils/ws.js';
const mobileNavigation = getMobileNavigation();
@@ -72,28 +70,11 @@
return landingPageOptions.some((option) => option.value === current) ? current : DEFAULT_LANDING_PAGE;
});
- async function savePreferences(patch: Partial<UserPreferences>) {
- const previous = currentUser;
- if (!previous) return;
- const operationResult = await tryCatch(
- (async () => {
- const updated = await userService.updateMyProfile({ preferences: patch });
- await userStore.setUser(updated);
- })()
- );
- if (operationResult.error !== null) {
- const error = operationResult.error;
-
- toast.error(error instanceof Error ? error.message : m.common_update_failed({ resource: m.account_preferences() }));
- await userStore.setUser(previous);
- }
- }
-
let pendingPreferences: Partial<UserPreferences> = {};
const flushPreferences = debounced(() => {
const patch = pendingPreferences;
pendingPreferences = {};
- void savePreferences(patch);
+ void saveUserPreferences(patch);
}, 400);
function savePreferencesDebounced(patch: Partial<UserPreferences>) {
@@ -104,7 +85,7 @@
function selectMobileNavigationMode(value: 'floating' | 'docked') {
if (value === mobileNavigationMode) return;
mobileNavigation.visible = true;
- void savePreferences({ mobileNavigationMode: value });
+ void saveUserPreferences({ mobileNavigationMode: value });
}
</script>
@@ -125,7 +106,7 @@
triggerSize="sm"
value={projectEditorLayoutValue}
options={projectEditorLayoutOptions}
- onValueChange={(value) => void savePreferences({ defaultProjectEditorLayout: value as ProjectEditorLayout })}
+ onValueChange={(value) => void saveUserPreferences({ defaultProjectEditorLayout: value as ProjectEditorLayout })}
/>
</div>
</SettingsRow>
@@ -160,7 +141,7 @@
triggerSize="sm"
value={iconCatalogValue}
options={iconCatalogOptions}
- onValueChange={(value) => void savePreferences({ iconCatalog: value as IconCatalog })}
+ onValueChange={(value) => void saveUserPreferences({ iconCatalog: value as IconCatalog })}
/>
</div>
</SettingsRow>
@@ -175,7 +156,10 @@
<AccentColorPicker
previousColor={accentColorValue}
selectedColor={accentColorValue}
- onSelect={(value) => savePreferencesDebounced({ accentColor: value })}
+ onSelect={(value) => {
+ applyAccentColor(value);
+ savePreferencesDebounced({ accentColor: value });
+ }}
/>
</SettingsRow>
<SettingsRow label={m.oled_mode()} description={m.oled_mode_description()} layout="switch">
@@ -192,7 +176,7 @@
disabled={!isDefaultApplicationTheme}
onCheckedChange={(checked) => {
applyOledMode(checked);
- void savePreferences({ oledMode: checked });
+ void saveUserPreferences({ oledMode: checked });
}}
/>
</SettingsRow>
@@ -202,7 +186,7 @@
checked={glassEffectsEnabled}
onCheckedChange={(checked) => {
applyGlassEffects(checked);
- void savePreferences({ glassEffectsEnabled: checked });
+ void saveUserPreferences({ glassEffectsEnabled: checked });
}}
/>
</SettingsRow>
@@ -212,7 +196,7 @@
checked={animationsEnabled}
onCheckedChange={(checked) => {
applyInterfaceAnimations(checked);
- void savePreferences({ animationsEnabled: checked });
+ void saveUserPreferences({ animationsEnabled: checked });
}}
/>
</SettingsRow>
@@ -232,7 +216,7 @@
triggerSize="sm"
value={landingValue}
options={landingPageOptions}
- onValueChange={(value) => void savePreferences({ defaultLandingPage: value })}
+ onValueChange={(value) => void saveUserPreferences({ defaultLandingPage: value })}
/>
</div>
</SettingsRow>
@@ -244,7 +228,7 @@
<Switch
id="account-sidebar-hover-expansion"
checked={sidebarHoverExpansionEnabled}
- onCheckedChange={(checked) => void savePreferences({ sidebarHoverExpansion: checked })}
+ onCheckedChange={(checked) => void saveUserPreferences({ sidebarHoverExpansion: checked })}
/>
</SettingsRow>
<SettingsRow
@@ -255,7 +239,7 @@
<Switch
id="account-keyboard-shortcuts"
checked={keyboardShortcutsEnabled}
- onCheckedChange={(checked) => void savePreferences({ keyboardShortcutsEnabled: checked })}
+ onCheckedChange={(checked) => void saveUserPreferences({ keyboardShortcutsEnabled: checked })}
/>
</SettingsRow>
</SettingsSection>
@@ -285,7 +269,7 @@
<Switch
id="account-mobile-nav-labels"
checked={mobileNavigationShowLabels}
- onCheckedChange={(checked) => void savePreferences({ mobileNavigationShowLabels: checked })}
+ onCheckedChange={(checked) => void saveUserPreferences({ mobileNavigationShowLabels: checked })}
/>
</SettingsRow>
</SettingsSection>
diff --git a/frontend/src/routes/(app)/account/components/account-security-panel.svelte b/frontend/src/routes/(app)/account/components/account-security-panel.svelte
index 0bba1317c..ac0897203 100644
--- a/frontend/src/routes/(app)/account/components/account-security-panel.svelte
+++ b/frontend/src/routes/(app)/account/components/account-security-panel.svelte
@@ -114,12 +114,12 @@
{#if !autoLoginEnabled}
<section class="space-y-5">
- <div class="flex items-center gap-2">
- <ShieldAlertIcon class="size-4 text-destructive" />
- <div>
- <h2 class="text-base font-semibold tracking-tight sm:text-lg">{m.danger_zone()}</h2>
- <p class="mt-1 text-xs text-muted-foreground sm:text-sm">{m.account_danger_zone_desc()}</p>
- </div>
+ <div>
+ <h2 class="flex items-center gap-2 text-base font-semibold tracking-tight sm:text-lg">
+ <ShieldAlertIcon class="size-4 text-destructive" />
+ {m.danger_zone()}
+ </h2>
+ <p class="mt-1 text-xs text-muted-foreground sm:text-sm">{m.account_danger_zone_desc()}</p>
</div>
<div class="rounded-xl border border-destructive/30 bg-destructive/5 p-4">
<div class="grid gap-4 sm:grid-cols-2">
diff --git a/frontend/src/routes/(app)/account/components/all-environments-preferences.svelte b/frontend/src/routes/(app)/account/components/all-environments-preferences.svelte
new file mode 100644
index 000000000..7c38ae303
--- /dev/null
+++ b/frontend/src/routes/(app)/account/components/all-environments-preferences.svelte
@@ -0,0 +1,109 @@
+<script lang="ts">
+ import { toast } from 'svelte-sonner';
+
+ import AccentColorPicker from '#lib/components/accent-color/accent-color-picker.svelte';
+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';
+ import SelectWithLabel from '#lib/components/form/select-with-label.svelte';
+ import SettingsRow from '#lib/components/settings/settings-row.svelte';
+ import SettingsSection from '#lib/components/settings/settings-section.svelte';
+ import * as Alert from '#lib/components/ui/alert/index.js';
+ import { Switch } from '#lib/components/ui/switch/index.js';
+ import { AlertTriangleIcon, ResetIcon } from '#lib/icons/index.js';
+ import { m } from '#lib/paraglide/messages.js';
+ import {
+ environmentColor,
+ environmentColorPalette,
+ withEnvironmentColor
+ } from '#lib/stores/environment-colors.store.svelte.js';
+ import { allEnvironmentsPreview, environmentStore } from '#lib/stores/environment.store.svelte.js';
+ import { featureStore } from '#lib/stores/features.store.svelte.js';
+ import userStore from '#lib/stores/user-store.svelte.js';
+ import type { EnvironmentLabelStyle } from '#lib/types/auth.js';
+ import { saveUserPreferences } from '#lib/utils/user-preferences.js';
+
+ const environments = $derived(environmentStore.available.filter((env) => env.enabled));
+ const swatches = environmentColorPalette.map((color) => ({ label: color, color }));
+
+ const labelStyle = $derived(userStore.current?.preferences?.environmentLabelStyle ?? 'name');
+ const labelStyleOptions = [
+ { value: 'name', label: m.environment_label_style_name() },
+ { value: 'dot', label: m.environment_label_style_dot() }
+ ];
+
+ function pickColor(environmentId: string, color: string | null) {
+ const environmentColors = withEnvironmentColor(environmentId, color);
+ if (environmentColors) void saveUserPreferences({ environmentColors });
+ else toast.info(m.environment_color_in_use());
+ }
+
+ async function setPreview(enabled: boolean) {
+ await saveUserPreferences({ allEnvironmentsPreview: enabled });
+ // Navigation gates on features in any shown environment.
+ for (const env of environmentStore.shown) void featureStore.load(env.id);
+ }
+</script>
+
+<div class="space-y-6">
+ <Alert.Root variant="warning-subtle" icon={AlertTriangleIcon}>
+ <Alert.Description>{m.previews_description()}</Alert.Description>
+ </Alert.Root>
+
+ <SettingsSection title={m.all_environments()}>
+ <SettingsRow
+ label={m.all_environments_preview()}
+ description={m.all_environments_preview_description()}
+ layout="switch"
+ for="account-all-environments-preview"
+ >
+ <Switch
+ id="account-all-environments-preview"
+ checked={allEnvironmentsPreview.current}
+ onCheckedChange={(checked) => void setPreview(checked)}
+ />
+ </SettingsRow>
+ {#if allEnvironmentsPreview.current}
+ <SettingsRow label={m.environment_label_style()} description={m.environment_label_style_description()} layout="switch">
+ <div class="w-52">
+ <SelectWithLabel
+ id="account-environment-label-style"
+ label={m.environment_label_style()}
+ hideLabel
+ triggerSize="sm"
+ value={labelStyle}
+ options={labelStyleOptions}
+ onValueChange={(value) => void saveUserPreferences({ environmentLabelStyle: value as EnvironmentLabelStyle })}
+ />
+ </div>
+ </SettingsRow>
+ <SettingsRow label={m.environment_colors()} description={m.environment_colors_description()} layout="wide">
+ <div class="grid gap-4">
+ {#each environments as env (env.id)}
+ {@const color = environmentColor(env.id) ?? ''}
+ <div class="grid gap-2">
+ <div class="flex items-center justify-between gap-3">
+ <span class="min-w-0 truncate text-sm">{env.name}</span>
+ <ArcaneButton
+ action="base"
+ tone="ghost"
+ size="icon"
+ icon={ResetIcon}
+ showLabel={false}
+ customLabel={m.common_reset()}
+ onclick={() => pickColor(env.id, null)}
+ />
+ </div>
+ <!-- Controlled by the stored color, so a pick already used by another environment is not shown as selected. -->
+ <AccentColorPicker
+ bind:selectedColor={() => color, (next) => pickColor(env.id, next)}
+ previousColor={color}
+ colors={swatches}
+ withTheme={false}
+ customColorTitle={m.environment_colors()}
+ />
+ </div>
+ {/each}
+ </div>
+ </SettingsRow>
+ {/if}
+ </SettingsSection>
+</div>
diff --git a/frontend/src/routes/(app)/containers/+page.svelte b/frontend/src/routes/(app)/containers/+page.svelte
index b47828aa0..b42358e43 100644
--- a/frontend/src/routes/(app)/containers/+page.svelte
+++ b/frontend/src/routes/(app)/containers/+page.svelte
@@ -10,25 +10,26 @@
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { ContainerStatusCounts } from '#lib/types/docker.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
- import { hasPermission } from '#lib/utils/auth.js';
+ import { fetchAcrossEnvironments, hasShownPermission } from '#lib/utils/environments.js';
import { confirmAndApplyAllUpdates } from '#lib/utils/update-actions.js';
import ContainerEnvironmentSync from './components/container-environment-sync.svelte';
import ContainerTable from './components/container-table.svelte';
+ import { containerSortValue } from './container-table.helpers';
let { data } = $props();
let requestOptions = $derived(data.containerRequestOptions);
let selectedIds = $state<string[]>([]);
let containers = $derived(data.containers);
- const envId = $derived(environmentStore.selected?.id || '0');
- let displayedEnvId = $state<string | null>(untrack(() => (data.envId === envId ? data.envId : null)));
+ const scope = $derived(environmentStore.shownKey);
+ let displayedScope = $state<string | null>(untrack(() => (data.scope === scope ? data.scope : null)));
let isRefreshing = $state(false);
let refreshGeneration = 0;
let groupByProject = $state(false);
let hasSeenEnvironmentSync = $state(false);
let isApplyingUpdates = $state(false);
- const resourcesReady = $derived(displayedEnvId === envId);
+ const resourcesReady = $derived(displayedScope === scope);
const countsFallback: ContainerStatusCounts = {
runningContainers: 0,
@@ -43,21 +44,26 @@
};
}
- async function refreshContainers(options: ContainerListRequestOptions = buildRequestOptions(), requestedEnvId = envId) {
+ async function refreshContainers(options: ContainerListRequestOptions = buildRequestOptions(), requestedScope = scope) {
const generation = ++refreshGeneration;
- if (requestedEnvId === envId) {
+ if (requestedScope === scope) {
isRefreshing = true;
}
try {
- const next = await containerService.getContainersForEnvironment(requestedEnvId, options);
- if (requestedEnvId !== envId || generation !== refreshGeneration) {
+ const next = await fetchAcrossEnvironments(
+ environmentStore.shown,
+ options,
+ (id, request, config) => containerService.getContainersForEnvironment(id, request, config),
+ containerSortValue
+ );
+ if (requestedScope !== scope || generation !== refreshGeneration) {
return containers;
}
containers = next;
- displayedEnvId = requestedEnvId;
+ displayedScope = requestedScope;
return next;
} finally {
- if (requestedEnvId === envId && generation === refreshGeneration) {
+ if (requestedScope === scope && generation === refreshGeneration) {
isRefreshing = false;
}
}
@@ -66,14 +72,14 @@
function handleEnvironmentChange() {
if (!hasSeenEnvironmentSync) {
hasSeenEnvironmentSync = true;
- if (data.envId === envId) {
+ if (data.scope === scope) {
return;
}
}
refreshGeneration += 1;
isRefreshing = false;
- displayedEnvId = null;
+ displayedScope = null;
selectedIds = [];
const nextOptions: SearchPaginationSortRequest = {
@@ -84,10 +90,10 @@
}
};
requestOptions = nextOptions;
- if (!hasPermission('containers:list', envId)) {
+ if (!hasShownPermission('containers:list')) {
return;
}
- return refreshContainers(buildRequestOptions(nextOptions), envId);
+ return refreshContainers(buildRequestOptions(nextOptions), scope);
}
async function refresh() {
@@ -96,8 +102,8 @@
const containerStatusCounts = $derived(resourcesReady ? (containers.counts ?? countsFallback) : countsFallback);
- const canCreateContainers = $derived(hasPermission('containers:create', envId));
- const canAutoUpdate = $derived(hasPermission('containers:autoupdate', envId));
+ const canCreateContainers = $derived(hasShownPermission('containers:create'));
+ const canAutoUpdate = $derived(hasShownPermission('containers:autoupdate'));
const actionButtons: ActionButton[] = $derived(
[
@@ -160,7 +166,7 @@
]);
</script>
-{#key envId}
+{#key scope}
<ContainerEnvironmentSync onActivate={handleEnvironmentChange} />
{/key}
@@ -168,13 +174,13 @@
{#snippet mainContent()}
{#if resourcesReady}
<ContainerTable
- environmentId={displayedEnvId!}
+ scope={displayedScope!}
bind:containers
bind:selectedIds
bind:requestOptions
bind:groupByProject
onRefreshData={async (options) => {
- const requestedEnvId = envId;
+ const requestedScope = scope;
requestOptions = {
search: options.search,
pagination: options.pagination,
@@ -183,7 +189,7 @@
includeInternal: options.includeInternal,
includeHidden: options.includeHidden
};
- return refreshContainers(options, requestedEnvId);
+ return refreshContainers(options, requestedScope);
}}
/>
{/if}
diff --git a/frontend/src/routes/(app)/containers/+page.ts b/frontend/src/routes/(app)/containers/+page.ts
index dece11eff..b22efb609 100644
--- a/frontend/src/routes/(app)/containers/+page.ts
+++ b/frontend/src/routes/(app)/containers/+page.ts
@@ -3,14 +3,17 @@ import { containerService } from '#lib/services/container-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { throwPageLoadError } from '#lib/utils/api.js';
+import { fetchAcrossEnvironments } from '#lib/utils/environments.js';
import { resolveInitialTableRequest } from '#lib/utils/tables.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
+import { containerSortValue } from './container-table.helpers';
export const load: PageLoad = async ({ parent }) => {
const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const environments = await environmentStore.getShownEnvironments();
+ const scope = environmentStore.shownKey;
const containerRequestOptions = resolveInitialTableRequest('arcane-container-table', {
pagination: { page: 1, limit: 20 },
@@ -21,8 +24,14 @@ export const load: PageLoad = async ({ parent }) => {
const operationResult = await tryCatch(
(async () =>
queryClient.query({
- queryKey: queryKeys.containers.list(envId, containerRequestOptions),
- queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)
+ queryKey: queryKeys.containers.list(scope, containerRequestOptions),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ environments,
+ containerRequestOptions,
+ (id, request, config) => containerService.getContainersForEnvironment(id, request, config),
+ containerSortValue
+ )
}))()
);
if (operationResult.error !== null) {
@@ -34,7 +43,7 @@ export const load: PageLoad = async ({ parent }) => {
}
return {
- envId,
+ scope,
containers,
containerRequestOptions
};
diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
index eb2a20732..d44314cc3 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
@@ -36,7 +36,6 @@
import { projectWorkspaceService } from '#lib/services/project-workspace-service.js';
import { activityStore } from '#lib/stores/activity.store.svelte.js';
import settingsStore from '#lib/stores/config-store.svelte.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { ContainerDetailsDto, ContainerNetworkSettings, ContainerStats as ContainerStatsType } from '#lib/types/docker.js';
import type { IncludeFile } from '#lib/types/swarm.js';
import { extractApiErrorMessage } from '#lib/utils/api.js';
@@ -45,6 +44,7 @@
import { isAutoUpdateLabelDisabled } from '#lib/utils/container-auto-update.js';
import { createContainerUpdateActivityTracker } from '#lib/utils/container-update-activities.js';
import { calculateMemoryUsage, getThemedIconUrl } from '#lib/utils/docker.js';
+ import { environmentHref, listScopes } from '#lib/utils/environments.js';
import { bytes } from '#lib/utils/formatting.js';
import { tryCatch } from '#lib/utils/try-catch.js';
@@ -149,7 +149,7 @@
);
const showNetworkTab = $derived(hasNetworks || hasPorts);
const hasMounts = $derived(!!(container?.mounts && container.mounts.length > 0));
- const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const currentEnvId = $derived(data.envId);
const canViewLogs = $derived(hasPermission('containers:logs', currentEnvId));
const canExecShell = $derived(hasPermission('containers:exec', currentEnvId));
const canPauseContainer = $derived(hasPermission('containers:pause', currentEnvId));
@@ -179,7 +179,7 @@
let updateLoading = $state(false);
let updateViewMounted = false;
const updateActivities = createContainerUpdateActivityTracker(
- () => currentEnvId,
+ () => [currentEnvId],
() => {
void refreshAfterUpdate();
},
@@ -200,7 +200,9 @@
const result = await tryCatch(containerService.getContainerForEnvironment(environmentId, containerId));
if (!updateViewMounted || environmentId !== currentEnvId || containerId !== container.id) return;
if (result.error instanceof APIError && result.error.status === 404) {
- await queryClient.invalidateQueries({ queryKey: ['containers', environmentId] });
+ await Promise.all(
+ listScopes([environmentId]).map((scope) => queryClient.invalidateQueries({ queryKey: ['containers', scope] }))
+ );
if (!updateViewMounted || environmentId !== currentEnvId || containerId !== container.id) return;
await goto('/containers');
return;
@@ -212,9 +214,11 @@
return;
}
await Promise.all([
- queryClient.invalidateQueries({ queryKey: ['containers', environmentId] }),
+ ...listScopes([environmentId]).flatMap((scope) => [
+ queryClient.invalidateQueries({ queryKey: ['containers', scope] }),
+ queryClient.invalidateQueries({ queryKey: ['projects', scope] })
+ ]),
queryClient.invalidateQueries({ queryKey: queryKeys.containers.detail(environmentId, containerId) }),
- queryClient.invalidateQueries({ queryKey: ['projects', environmentId] }),
queryClient.invalidateQueries({ queryKey: queryKeys.projects.environment(environmentId) })
]);
if (updateViewMounted && environmentId === currentEnvId && containerId === container.id) await refreshAll();
@@ -241,6 +245,7 @@
await runContainerLifecycleAction({
action: 'pause',
containerId: container.id,
+ environmentId: currentEnvId,
setStatus: (status) => {
lifecycleStatus = status === 'pausing' ? status : '';
},
@@ -253,6 +258,7 @@
await runContainerLifecycleAction({
action: 'unpause',
containerId: container.id,
+ environmentId: currentEnvId,
setStatus: (status) => {
lifecycleStatus = status === 'unpausing' ? status : '';
},
@@ -306,10 +312,7 @@
const includes = proj.includeFiles ?? [];
if (includes.length === 0) return null;
- const envId = await tryCatch(environmentStore.getCurrentEnvironmentId()).then((result) =>
- result.error ? null : result.data
- );
- if (!envId) return null;
+ const envId = currentEnvId;
for (const f of includes) {
if (f.content && hasServiceInContent(f.content, svcName)) {
@@ -370,7 +373,7 @@
const projectId = page.url.searchParams.get('projectId');
if (from === 'project' && projectId) {
- return `/projects/${projectId}`;
+ return environmentHref(`/projects/${projectId}`, currentEnvId);
}
return '/containers';
@@ -386,7 +389,7 @@
label: m.common_edit(),
icon: EditIcon,
group: 'manage',
- href: `/containers/${container.id}/edit`
+ href: environmentHref(`/containers/${container.id}/edit`, currentEnvId)
});
}
if (canConvertToCompose) {
@@ -466,7 +469,13 @@
<Badge variant="amber" minWidth="20">{m.sidebar_update_available()}</Badge>
{/if}
{#if project && composeInfo}
- <Badge variant="gray" size="sm" href="/projects/{project.id}" title={m.projects_title()} class="max-w-40">
+ <Badge
+ variant="gray"
+ size="sm"
+ href={environmentHref(`/projects/${project.id}`, currentEnvId)}
+ title={m.projects_title()}
+ class="max-w-40"
+ >
<span class="block min-w-0 truncate">
{composeInfo.projectName}
</span>
@@ -479,9 +488,10 @@
{#await serviceComposeSourcePromise then serviceComposeSource}
{#if project && serviceComposeSource}
<Tabs.Content value="compose" class="h-full min-h-0">
- {#key `${project?.id}-${serviceComposeSource?.includeFile?.relativePath ?? 'root'}`}
+ {#key `${currentEnvId}:${project?.id}-${serviceComposeSource?.includeFile?.relativePath ?? 'root'}`}
<ContainerComposePanel
{project}
+ environmentId={currentEnvId}
serviceName={composeServiceName}
includeFile={serviceComposeSource.includeFile}
rootFilename={rootComposeFilename}
@@ -496,6 +506,7 @@
<Tabs.Content value="overview" class="h-full">
<ContainerOverview
{container}
+ environmentId={currentEnvId}
{primaryIpAddress}
{autoUpdateEnabled}
{autoUpdateLabelControlled}
@@ -527,15 +538,16 @@
<Tabs.Content value="processes" class="h-full">
{#if activeTab === 'processes'}
- <ContainerProcesses containerId={container.id} status={containerStatus} />
+ <ContainerProcesses containerId={container.id} environmentId={currentEnvId} status={containerStatus} />
{/if}
</Tabs.Content>
<Tabs.Content value="logs" class="h-full">
{#if activeTab === 'logs'}
- {#key container?.id}
+ {#key `${currentEnvId}:${container?.id}`}
<ContainerLogsPanel
containerId={container?.id}
+ environmentId={currentEnvId}
{stats}
{hasInitialStatsLoaded}
isRunning={!!container.state?.running}
@@ -549,7 +561,12 @@
{#if showShell}
<Tabs.Content value="shell" class="h-full">
{#if activeTab === 'shell'}
- <ContainerShell containerId={container?.id} labels={container?.labels} name={container?.name} />
+ <ContainerShell
+ containerId={container?.id}
+ environmentId={currentEnvId}
+ labels={container?.labels}
+ name={container?.name}
+ />
{/if}
</Tabs.Content>
{/if}
@@ -568,7 +585,7 @@
{#if showNetworkTab}
<Tabs.Content value="network" class="h-full">
- <ContainerNetwork {container} />
+ <ContainerNetwork {container} environmentId={currentEnvId} />
</Tabs.Content>
{/if}
@@ -589,6 +606,7 @@
{#key `${currentEnvId}:${container.id}`}
<ContainerDetailStatsSync
containerId={container.id}
+ environmentId={currentEnvId}
enabled={(activeTab === 'stats' || activeTab === 'logs') && !!container.state?.running}
bind:stats
bind:hasInitialStatsLoaded
@@ -604,6 +622,7 @@
{#snippet headerActions()}
<ActionButtons
id={container.id}
+ environmentId={currentEnvId}
name={containerDisplayName}
type="container"
itemState={container.state?.running ? 'running' : 'stopped'}
@@ -622,6 +641,7 @@
<KillContainerDialog
containerId={container.id}
containerName={containerDisplayName}
+ environmentId={currentEnvId}
onClose={() => (killDialogOpen = false)}
onComplete={() => {
killDialogOpen = false;
@@ -634,6 +654,7 @@
bind:open={commitDialogOpen}
containerId={container.id}
containerName={containerDisplayName}
+ environmentId={currentEnvId}
onCommitted={refreshContainerDetails}
/>
{/if}
diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.ts b/frontend/src/routes/(app)/containers/[containerId]/+page.ts
index a2936e465..0d3ae53ca 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/+page.ts
+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.ts
@@ -3,15 +3,15 @@ import { error } from '@sveltejs/kit';
import { queryKeys } from '#lib/query/query-keys.js';
import { containerService } from '#lib/services/container-service.js';
import { projectService } from '#lib/services/project-service.js';
-import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { throwPageLoadError } from '#lib/utils/api.js';
+import { resolveDetailEnvironmentId } from '#lib/utils/environments.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
-export const load: PageLoad = async ({ params, parent }) => {
+export const load: PageLoad = async ({ params, parent, url }) => {
const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const envId = await resolveDetailEnvironmentId(url);
const containerId = params.containerId;
const containerResult = await tryCatch(
@@ -61,6 +61,7 @@ export const load: PageLoad = async ({ params, parent }) => {
}
return {
+ envId,
container,
project
};
diff --git a/frontend/src/routes/(app)/containers/[containerId]/edit/+layout.svelte b/frontend/src/routes/(app)/containers/[containerId]/edit/+layout.svelte
new file mode 100644
index 000000000..7eaaf67f0
--- /dev/null
+++ b/frontend/src/routes/(app)/containers/[containerId]/edit/+layout.svelte
@@ -0,0 +1,12 @@
+<script lang="ts">
+ import { page } from '$app/state';
+
+ import type { LayoutProps } from './$types';
+
+ let { children }: LayoutProps = $props();
+</script>
+
+<!-- The editor reads its container once, so another container or environment gets a fresh editor. -->
+{#key `${page.data['envId']}:${page.params.containerId}`}
+ {@render children()}
+{/key}
diff --git a/frontend/src/routes/(app)/containers/[containerId]/edit/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.svelte
index 7ddc44370..87cbbfa76 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/edit/+page.svelte
+++ b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.svelte
@@ -20,6 +20,7 @@
import type { ContainerEditRequest } from '#lib/types/docker.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { extractApiErrorMessage } from '#lib/utils/api.js';
+ import { environmentHref } from '#lib/utils/environments.js';
import { createForm } from '#lib/utils/settings.svelte.js';
let { data } = $props();
@@ -31,13 +32,13 @@
let rows = $state(untrack(() => rowsFromEditConfig(data.editConfig)));
const editContainerMutation = createMutation(() => ({
- mutationFn: (request: ContainerEditRequest) => containerService.editContainer(data.containerId, request),
+ mutationFn: (request: ContainerEditRequest) => containerService.editContainer(data.containerId, request, data.envId),
onSuccess: async (details) => {
toast.success(m.edit_success(), activityToastOptions(extractActivityId(details)));
await queryClient.invalidateQueries({ queryKey: queryKeys.containers.all });
queryClient.removeQueries({ queryKey: queryKeys.containers.detail(data.envId, data.containerId) });
queryClient.removeQueries({ queryKey: queryKeys.containers.editConfig(data.envId, data.containerId) });
- goto(`/containers/${details.id}`);
+ goto(environmentHref(`/containers/${details.id}`, data.envId));
},
onError: (error) => {
toast.error(m.edit_failed(), { description: extractApiErrorMessage(error) });
@@ -69,7 +70,7 @@
action="base"
tone="ghost"
size="sm"
- href={`/containers/${data.containerId}`}
+ href={environmentHref(`/containers/${data.containerId}`, data.envId)}
class="gap-2 bg-transparent"
icon={ArrowLeftIcon}
customLabel={m.common_back()}
@@ -87,7 +88,8 @@
mode="edit"
{form}
bind:rows
- cancelHref={`/containers/${data.containerId}`}
+ cancelHref={environmentHref(`/containers/${data.containerId}`, data.envId)}
+ environmentId={data.envId}
submitting={editContainerMutation.isPending}
onSubmit={handleSubmit}
/>
diff --git a/frontend/src/routes/(app)/containers/[containerId]/edit/+page.ts b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.ts
index f92c8844b..828965b3e 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/edit/+page.ts
+++ b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.ts
@@ -2,18 +2,18 @@ import { redirect } from '@sveltejs/kit';
import { queryKeys } from '#lib/query/query-keys.js';
import { containerService } from '#lib/services/container-service.js';
-import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { userHasPermission } from '#lib/utils/auth.js';
+import { environmentHref, resolveDetailEnvironmentId } from '#lib/utils/environments.js';
import type { PageLoad } from './$types';
-export const load: PageLoad = async ({ params, parent }) => {
+export const load: PageLoad = async ({ params, parent, url }) => {
const { queryClient, user } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const envId = await resolveDetailEnvironmentId(url);
const containerId = params.containerId;
if (!userHasPermission(user, 'containers:edit', envId)) {
- redirect(302, `/containers/${containerId}`);
+ redirect(302, environmentHref(`/containers/${containerId}`, envId));
}
const editConfig = await queryClient.query({
@@ -24,7 +24,7 @@ export const load: PageLoad = async ({ params, parent }) => {
// Compose-managed containers are edited via their project; the running
// Arcane server or agent container cannot be edited at all.
if (editConfig.isCompose || editConfig.editDisabled) {
- redirect(302, `/containers/${containerId}`);
+ redirect(302, environmentHref(`/containers/${containerId}`, envId));
}
return { editConfig, envId, containerId };
diff --git a/frontend/src/routes/(app)/containers/components/container-commit-dialog.svelte b/frontend/src/routes/(app)/containers/components/container-commit-dialog.svelte
index 38add5c8c..973754a8b 100644
--- a/frontend/src/routes/(app)/containers/components/container-commit-dialog.svelte
+++ b/frontend/src/routes/(app)/containers/components/container-commit-dialog.svelte
@@ -17,11 +17,12 @@
open: boolean;
containerId: string;
containerName: string;
+ environmentId: string;
onOpenChange?: (open: boolean) => void;
onCommitted?: () => Promise<void> | void;
};
- let { open = $bindable(false), containerId, containerName, onOpenChange, onCommitted }: Props = $props();
+ let { open = $bindable(false), containerId, containerName, environmentId, onOpenChange, onCommitted }: Props = $props();
const schema = z.object({
repository: z.string().optional().default(''),
@@ -58,13 +59,17 @@
try {
const operationResult = await tryCatch(
(async () => {
- const result = await containerService.commitContainer(containerId, {
- repository: data.repository.trim() || undefined,
- tag: data.tag?.trim() || undefined,
- comment: data.comment.trim() || undefined,
- author: data.author.trim() || undefined,
- noPause: data.noPause
- });
+ const result = await containerService.commitContainer(
+ containerId,
+ {
+ repository: data.repository.trim() || undefined,
+ tag: data.tag?.trim() || undefined,
+ comment: data.comment.trim() || undefined,
+ author: data.author.trim() || undefined,
+ noPause: data.noPause
+ },
+ environmentId
+ );
toast.success(m.containers_commit_success({ imageId: result.id }));
didCommit = true;
open = false;
diff --git a/frontend/src/routes/(app)/containers/components/container-compose-panel.svelte b/frontend/src/routes/(app)/containers/components/container-compose-panel.svelte
index c267d2f37..d8ccd11ee 100644
--- a/frontend/src/routes/(app)/containers/components/container-compose-panel.svelte
+++ b/frontend/src/routes/(app)/containers/components/container-compose-panel.svelte
@@ -4,14 +4,17 @@
import { projectService } from '#lib/services/project-service.js';
import { projectWorkspaceService } from '#lib/services/project-workspace-service.js';
import type { Project, IncludeFile } from '#lib/types/swarm.js';
+ import { environmentHref } from '#lib/utils/environments.js';
let {
project,
+ environmentId,
serviceName,
includeFile = null,
rootFilename = 'compose.yml'
}: {
project: Project;
+ environmentId: string;
serviceName: string;
includeFile?: IncludeFile | null;
rootFilename?: string;
@@ -30,23 +33,24 @@
async function save() {
if (includeFile) {
- const workspace = await projectWorkspaceService.getWorkspace(project.id);
+ const workspace = await projectWorkspaceService.getWorkspace(project.id, environmentId);
await projectWorkspaceService.updateWorkspace(
project.id,
{
fileTreeRevision: workspace.fileTreeRevision,
fileChanges: [{ operation: 'update_file', relativePath: includeFile.relativePath, uploadIndex: 0 }]
},
- [new File([composeContent], includeFile.relativePath, { type: 'text/yaml' })]
+ [new File([composeContent], includeFile.relativePath, { type: 'text/yaml' })],
+ environmentId
);
} else {
- await projectService.updateProject(project.id, undefined, composeContent);
+ await projectService.updateProject(project.id, undefined, composeContent, undefined, undefined, environmentId);
}
}
</script>
<ComposeEditorWrapper
- projectId={project.id}
+ projectHref={environmentHref(`/projects/${project.id}`, environmentId)}
projectName={project.name}
gitOpsManagedBy={project.gitOpsManagedBy}
{fileTitle}
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 9fb46796b..2a5620d2a 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
@@ -2,19 +2,20 @@
import { refreshAll } from '$app/navigation';
import { onDestroy } from 'svelte';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { ContainerStats as ContainerStatsType, ContainerStatsHistorySample } from '#lib/types/docker.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import { createContainerStatsWebSocket, type ReconnectingWebSocket } from '#lib/utils/ws.js';
let {
containerId,
+ environmentId,
enabled,
stats = $bindable<ContainerStatsType | null>(null),
hasInitialStatsLoaded = $bindable(false),
statsError = $bindable(false)
}: {
containerId?: string;
+ environmentId: string;
enabled: boolean;
stats?: ContainerStatsType | null;
hasInitialStatsLoaded?: boolean;
@@ -42,7 +43,7 @@
const requestedContainerId = containerId;
const operationResult = await tryCatch(
(async () => {
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const envId = environmentId;
if (requestGeneration !== generation || !enabled || requestedContainerId !== containerId) return;
const ws = createContainerStatsWebSocket({
diff --git a/frontend/src/routes/(app)/containers/components/container-logs-panel.svelte b/frontend/src/routes/(app)/containers/components/container-logs-panel.svelte
index 7675d5602..c439406d4 100644
--- a/frontend/src/routes/(app)/containers/components/container-logs-panel.svelte
+++ b/frontend/src/routes/(app)/containers/components/container-logs-panel.svelte
@@ -23,6 +23,7 @@
let {
containerId,
+ environmentId,
stats = null,
hasInitialStatsLoaded = false,
isRunning = false,
@@ -32,6 +33,7 @@
onStop
}: {
containerId: string | undefined;
+ environmentId: string;
stats?: ContainerStats | null;
hasInitialStatsLoaded?: boolean;
isRunning?: boolean;
@@ -120,7 +122,7 @@
async function handleDownload() {
if (!containerId) return;
- const result = await tryCatch(containerService.downloadContainerLogs(containerId));
+ const result = await tryCatch(containerService.downloadContainerLogs(containerId, environmentId));
if (result.error !== null) {
toast.error(m.common_download_error(), { description: result.error.message });
}
@@ -215,6 +217,7 @@
bind:autoScroll
type="container"
{containerId}
+ {environmentId}
bind:showParsedJson={preferences.showParsedJson}
showStreamLabels={preferences.showStreamLabels}
tailLines={preferences.tailLines}
diff --git a/frontend/src/routes/(app)/containers/components/container-network.svelte b/frontend/src/routes/(app)/containers/components/container-network.svelte
index 4b6c1ba80..1208cd9b4 100644
--- a/frontend/src/routes/(app)/containers/components/container-network.svelte
+++ b/frontend/src/routes/(app)/containers/components/container-network.svelte
@@ -13,7 +13,6 @@
import { m } from '#lib/paraglide/messages.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { networkService } from '#lib/services/network-service.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { ContainerDetailsDto } from '#lib/types/docker.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { hasPermission } from '#lib/utils/auth.js';
@@ -21,11 +20,12 @@
interface Props {
container: ContainerDetailsDto;
+ environmentId: string;
}
- let { container }: Props = $props();
+ let { container, environmentId }: Props = $props();
- const envId = $derived(environmentStore.selected?.id || '0');
+ const envId = $derived(environmentId);
const canConnect = $derived(hasPermission('networks:connect', envId));
const canDisconnect = $derived(hasPermission('networks:disconnect', envId));
@@ -38,7 +38,7 @@
const networkListOptions = { pagination: { page: 1, limit: 500 } };
const networksQuery = createQuery(() => ({
queryKey: queryKeys.networks.list(envId, networkListOptions),
- queryFn: () => networkService.getNetworks(networkListOptions),
+ queryFn: () => networkService.getNetworksForEnvironment(envId, networkListOptions),
enabled: canConnect
}));
@@ -60,11 +60,15 @@
.split(',')
.map((alias) => alias.trim())
.filter(Boolean);
- await networkService.connectContainer(connectNetwork, {
- containerId: container.id,
- aliases: aliases.length > 0 ? aliases : undefined,
- ipv4Address: connectIp.trim() || undefined
- });
+ await networkService.connectContainer(
+ connectNetwork,
+ {
+ containerId: container.id,
+ aliases: aliases.length > 0 ? aliases : undefined,
+ ipv4Address: connectIp.trim() || undefined
+ },
+ envId
+ );
toast.success(m.network_connect_success());
connectNetwork = '';
connectAliases = '';
@@ -79,6 +83,8 @@
}
function handleDisconnect(networkName: string, networkId: string) {
+ // The dialog outlives navigation, so it disconnects the container it was opened for.
+ const target = { containerId: container.id, environmentId: envId };
openConfirmDialog({
title: m.network_disconnect_confirm_title(),
message: m.network_disconnect_confirm_message({ network: networkName }),
@@ -90,7 +96,11 @@
try {
const operationResult = await tryCatch(
(async () => {
- await networkService.disconnectContainer(networkId || networkName, { containerId: container.id, force: false });
+ await networkService.disconnectContainer(
+ networkId || networkName,
+ { containerId: target.containerId, force: false },
+ target.environmentId
+ );
toast.success(m.network_disconnect_success());
await refreshAll();
})()
diff --git a/frontend/src/routes/(app)/containers/components/container-overview.svelte b/frontend/src/routes/(app)/containers/components/container-overview.svelte
index 00f913195..e4a592081 100644
--- a/frontend/src/routes/(app)/containers/components/container-overview.svelte
+++ b/frontend/src/routes/(app)/containers/components/container-overview.svelte
@@ -15,6 +15,7 @@
interface Props {
container: ContainerDetailsDto;
+ environmentId: string;
primaryIpAddress: string;
autoUpdateEnabled?: boolean;
autoUpdateLabelControlled?: boolean;
@@ -28,6 +29,7 @@
let {
container,
+ environmentId,
primaryIpAddress,
autoUpdateEnabled = true,
autoUpdateLabelControlled = false,
@@ -43,7 +45,7 @@
async function handleAutoUpdateToggle(checked: boolean) {
autoUpdateToggling = true;
try {
- const operationResult = await tryCatch(containerService.setAutoUpdate(container.id, checked));
+ const operationResult = await tryCatch(containerService.setAutoUpdate(container.id, checked, environmentId));
if (operationResult.error !== null) {
toast.error(m.auto_update_failed(), { description: extractApiErrorMessage(operationResult.error) });
return;
diff --git a/frontend/src/routes/(app)/containers/components/container-processes.svelte b/frontend/src/routes/(app)/containers/components/container-processes.svelte
index ac7f8a32c..27f777e4f 100644
--- a/frontend/src/routes/(app)/containers/components/container-processes.svelte
+++ b/frontend/src/routes/(app)/containers/components/container-processes.svelte
@@ -11,21 +11,21 @@
import { m } from '#lib/paraglide/messages.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { containerService } from '#lib/services/container-service.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { extractApiErrorMessage } from '#lib/utils/api.js';
interface Props {
containerId: string;
+ environmentId: string;
status: string;
}
- let { containerId, status }: Props = $props();
+ let { containerId, environmentId, status }: Props = $props();
const canFetch = $derived(status === 'running' || status === 'paused');
const processesQuery = createQuery(() => ({
- queryKey: queryKeys.containers.processes(environmentStore.selected?.id ?? '', containerId),
- queryFn: ({ signal }) => containerService.getContainerProcesses(containerId, signal),
+ queryKey: queryKeys.containers.processes(environmentId, containerId),
+ queryFn: ({ signal }) => containerService.getContainerProcesses(containerId, signal, environmentId),
enabled: canFetch,
gcTime: 0,
retry: false,
diff --git a/frontend/src/routes/(app)/containers/components/container-shell.svelte b/frontend/src/routes/(app)/containers/components/container-shell.svelte
index 6adeb3547..44b955c8a 100644
--- a/frontend/src/routes/(app)/containers/components/container-shell.svelte
+++ b/frontend/src/routes/(app)/containers/components/container-shell.svelte
@@ -13,10 +13,12 @@
let {
containerId,
+ environmentId,
labels,
name
}: {
containerId: string | undefined;
+ environmentId: string;
labels: Record<string, string> | null | undefined;
name: string | undefined;
} = $props();
@@ -25,7 +27,7 @@
// Keyed by compose service (or container name) so the choice survives container recreation.
const shellKey = $derived.by(() => {
- const envId = environmentStore.selected?.id ?? '0';
+ const envId = environmentId;
const project = labels?.[COMPOSE_PROJECT_LABEL];
const service = labels?.[COMPOSE_SERVICE_LABEL];
if (project && service) return `${envId}:${project}/${service}`;
@@ -40,7 +42,7 @@
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)}`;
+ return `${protocol}//${page.url.host}/api/environments/${environmentId}/ws/containers/${containerId}/terminal?shell=${encodeURIComponent(selectedShell)}`;
});
function handleShellChange(shell: string) {
diff --git a/frontend/src/routes/(app)/containers/components/container-stats-manager.svelte.ts b/frontend/src/routes/(app)/containers/components/container-stats-manager.svelte.ts
index 469ac5ce1..084bc04a8 100644
--- a/frontend/src/routes/(app)/containers/components/container-stats-manager.svelte.ts
+++ b/frontend/src/routes/(app)/containers/components/container-stats-manager.svelte.ts
@@ -2,6 +2,7 @@ import { SvelteMap, SvelteSet } from 'svelte/reactivity';
import type { ContainerStats } from '#lib/types/docker.js';
import { calculateCPUPercent, calculateMemoryPercent, calculateMemoryUsage } from '#lib/utils/docker.js';
+import { parseRowKey } from '#lib/utils/environments.js';
import { createContainerStatsWebSocket } from '#lib/utils/ws.js';
import type { ReconnectingWebSocket } from '#lib/utils/ws.js';
@@ -11,16 +12,18 @@ export class ContainerStatsManager {
private loadingStates = new SvelteMap<string, boolean>();
private errorStates = new SvelteMap<string, boolean>();
private desiredIds = new SvelteSet<string>();
- private currentEnvId: string | null = null;
- connect(containerId: string, envId: string): void {
+ /** Keyed by table row key; the row's environment is decoded only for the websocket URL. */
+ connect(containerId: string): void {
if (this.connections.has(containerId)) return;
+ const { id, environmentId } = parseRowKey(containerId);
+ if (!environmentId) return;
this.loadingStates.set(containerId, true);
const ws = createContainerStatsWebSocket({
- getEnvId: () => envId,
- containerId,
+ getEnvId: () => environmentId,
+ containerId: id,
onMessage: (data: ContainerStats) => {
this.stats.set(containerId, data);
this.loadingStates.set(containerId, false);
@@ -86,31 +89,17 @@ export class ContainerStatsManager {
return Array.from(this.connections.keys());
}
- set envId(value: string) {
- if (this.currentEnvId === value) return;
- this.currentEnvId = value;
- this.resetConnections();
- this.syncConnections();
- }
-
+ /** Table row keys; each container streams from its row's environment. */
set targetIds(value: Set<string>) {
this.desiredIds = new SvelteSet(value);
this.syncConnections();
}
- private resetConnections(): void {
- const ids = Array.from(this.connections.keys());
- for (const id of ids) {
- this.disconnect(id);
- }
- }
-
private syncConnections(): void {
- if (!this.currentEnvId) return;
const connectedIds = new SvelteSet(this.connections.keys());
for (const id of this.desiredIds) {
if (!connectedIds.has(id)) {
- this.connect(id, this.currentEnvId);
+ this.connect(id);
}
}
diff --git a/frontend/src/routes/(app)/containers/components/container-stats-sync.svelte b/frontend/src/routes/(app)/containers/components/container-stats-sync.svelte
index 118684bf4..eed42397b 100644
--- a/frontend/src/routes/(app)/containers/components/container-stats-sync.svelte
+++ b/frontend/src/routes/(app)/containers/components/container-stats-sync.svelte
@@ -3,16 +3,13 @@
let {
statsManager,
- envId,
targetIds
}: {
statsManager: ContainerStatsManager;
- envId: string;
targetIds: Set<string>;
} = $props();
$effect(() => {
- statsManager.envId = envId;
statsManager.targetIds = targetIds;
});
</script>
diff --git a/frontend/src/routes/(app)/containers/components/container-table.svelte b/frontend/src/routes/(app)/containers/components/container-table.svelte
index f8da47eb3..5aaacc6d4 100644
--- a/frontend/src/routes/(app)/containers/components/container-table.svelte
+++ b/frontend/src/routes/(app)/containers/components/container-table.svelte
@@ -10,6 +10,7 @@
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import type { SortState } from '#lib/components/arcane-table/arcane-table.types.svelte';
import ActionMenuItem from '#lib/components/arcane-table/cells/action-menu-item.svelte';
+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';
import type { ColumnSpec, BulkAction } from '#lib/components/arcane-table/index.js';
import { UniversalMobileCard } from '#lib/components/arcane-table/index.js';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
@@ -43,6 +44,7 @@
InfoIcon
} from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
+ import { queryKeys } from '#lib/query/query-keys.js';
import {
containerService,
type ContainerListRequestOptions,
@@ -57,10 +59,20 @@
import { hasAnyLoadingState } from '#lib/utils/bulk-actions.js';
import { createContainerUpdateActivityTracker } from '#lib/utils/container-update-activities.js';
import { COMPOSE_PROJECT_LABEL, getContainerIpAddresses, getThemedIconUrl, parseImageRef } from '#lib/utils/docker.js';
+ import {
+ environmentHref,
+ fetchAcrossEnvironments,
+ hasShownPermission,
+ listScopes,
+ rowKey,
+ type EnvironmentPage,
+ type EnvironmentRow
+ } from '#lib/utils/environments.js';
import { formatDateTimeShort, truncateImageDigest } from '#lib/utils/formatting.js';
import { createContainerActions } from '../container-table.actions';
import {
+ containerSortValue,
getActionStatusMessage,
getContainerDisplayName,
getProjectName,
@@ -75,9 +87,11 @@
import KillContainerDialog from './kill-container-dialog.svelte';
type FieldVisibility = Record<string, boolean>;
+ type ContainerRow = EnvironmentRow<ContainerSummaryDto>;
+ type ContainerPage = EnvironmentPage<ContainersPaginatedResponse>;
let {
- environmentId,
+ scope,
containers = $bindable(),
selectedIds = $bindable(),
requestOptions = $bindable(),
@@ -85,13 +99,14 @@
withoutFilters = false,
onRefreshData
}: {
- environmentId: string;
- containers: ContainersPaginatedResponse;
+ /** Shown-environments scope the rows were loaded for. */
+ scope: string;
+ containers: ContainerPage;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
groupByProject?: boolean;
withoutFilters?: boolean;
- onRefreshData?: (options: ContainerListRequestOptions) => Promise<ContainersPaginatedResponse>;
+ onRefreshData?: (options: ContainerListRequestOptions) => Promise<ContainerPage>;
} = $props();
// Track action status per container ID (e.g., "starting", "stopping", "updating", "")
@@ -109,13 +124,17 @@
const queryClient = useQueryClient();
let updateTableMounted = false;
const updateActivities = createContainerUpdateActivityTracker(
- () => environmentId,
+ () => environmentStore.shown.map((env) => env.id),
() => {
- if (!updateTableMounted || environmentId !== environmentStore.selected?.id) return;
- void queryClient.invalidateQueries({ queryKey: ['containers', environmentId] });
- void queryClient.invalidateQueries({ queryKey: ['container', environmentId] });
- void queryClient.invalidateQueries({ queryKey: ['projects', environmentId] });
- void queryClient.invalidateQueries({ queryKey: ['project', environmentId] });
+ if (!updateTableMounted || scope !== environmentStore.shownKey) return;
+ for (const listScope of listScopes(environmentStore.shown.map((env) => env.id))) {
+ void queryClient.invalidateQueries({ queryKey: ['containers', listScope] });
+ void queryClient.invalidateQueries({ queryKey: ['projects', listScope] });
+ }
+ for (const env of environmentStore.shown) {
+ void queryClient.invalidateQueries({ queryKey: ['container', env.id] });
+ void queryClient.invalidateQueries({ queryKey: queryKeys.projects.environment(env.id) });
+ }
void refreshContainers(requestOptions);
}
);
@@ -141,8 +160,15 @@
};
}
- async function fetchContainers(request: ContainerListRequestOptions): Promise<ContainersPaginatedResponse> {
- return onRefreshData ? onRefreshData(request) : containerService.getContainers(request);
+ async function fetchContainers(request: ContainerListRequestOptions): Promise<ContainerPage> {
+ return onRefreshData
+ ? onRefreshData(request)
+ : fetchAcrossEnvironments(
+ environmentStore.shown,
+ request,
+ (id, request, config) => containerService.getContainersForEnvironment(id, request, config),
+ containerSortValue
+ );
}
// Refreshes can overlap: a resource poll may still be in flight when the user changes
@@ -222,11 +248,11 @@
refreshContainers: () => refreshContainers(requestOptions),
actionStatus,
isBulkLoading,
- environmentId: () => environmentId,
+ scope: () => scope,
onUpdateAccepted: (activity) => {
if (updateTableMounted) updateActivities.accept(activity);
},
- canRefreshUpdates: () => updateTableMounted && environmentId === environmentStore.selected?.id
+ canRefreshUpdates: () => updateTableMounted && scope === environmentStore.shownKey
});
const isAnyLoading = $derived(hasAnyLoadingState(actionStatus, isBulkLoading));
@@ -267,11 +293,10 @@
}
const runningContainers = containers.data?.filter((c) => c.state === 'running') ?? [];
- return new Set(runningContainers.map((c) => c.id));
+ return new Set(runningContainers.map((c) => rowKey(c)));
});
- const currentEnvId = $derived(environmentStore.selected?.id || '0');
- const resourcesCurrent = $derived(environmentId === currentEnvId);
+ const resourcesCurrent = $derived(scope === environmentStore.shownKey);
// Only the on/off state is tracked here. The callback reads requestOptions when
// it runs, so pagination or filter changes do not restart the poll cycle.
@@ -280,35 +305,34 @@
resourcePoller.start(() => refreshContainers(requestOptions));
return () => resourcePoller.stop();
});
- const canUpdateContainers = $derived(hasPermission('containers:autoupdate', currentEnvId));
- const canEditContainers = $derived(hasPermission('containers:edit', currentEnvId));
- const canStartContainers = $derived(hasPermission('containers:start', currentEnvId));
- const canStopContainers = $derived(hasPermission('containers:stop', currentEnvId));
- const canRestartContainers = $derived(hasPermission('containers:restart', currentEnvId));
- const canDeleteContainers = $derived(hasPermission('containers:delete', currentEnvId));
+ const canUpdateContainers = $derived(hasShownPermission('containers:autoupdate'));
+ const canStartContainers = $derived(hasShownPermission('containers:start'));
+ const canStopContainers = $derived(hasShownPermission('containers:stop'));
+ const canRestartContainers = $derived(hasShownPermission('containers:restart'));
+ const canDeleteContainers = $derived(hasShownPermission('containers:delete'));
// Reserve room for per-row state buttons so every State cell fits the width measured from the first rows.
const stateActionsMinWidth = $derived.by(() => {
if (canUpdateContainers) return 'min-w-15';
if (canStartContainers || canStopContainers) return 'min-w-7';
return '';
});
- const canKillContainers = $derived(hasPermission('containers:kill', currentEnvId));
const canConvertToCompose = $derived(
- hasPermission('projects:create', currentEnvId) && settingsStore.current?.experimentalFeaturesEnabled === true
+ hasShownPermission('projects:create') && settingsStore.current?.experimentalFeaturesEnabled === true
+ );
+ const selectedEnvironmentIds = $derived(
+ new Set(containers.data?.filter((c) => selectedIds?.includes(rowKey(c))).map((c) => c.environmentId))
);
function handleBulkConvert(ids: string[]) {
- const convertibleIds = ids.filter((id) => {
- const container = containers.data?.find((c) => c.id === id);
- return container && !container.labels?.[COMPOSE_PROJECT_LABEL];
- });
- if (convertibleIds.length === 0) return;
- goto(`/projects/new?fromContainers=${convertibleIds.join(',')}&fromEnv=${encodeURIComponent(currentEnvId)}`);
+ const convertible = (containers.data ?? []).filter((c) => ids.includes(rowKey(c)) && !c.labels?.[COMPOSE_PROJECT_LABEL]);
+ if (convertible.length === 0) return;
+ const fromEnv = encodeURIComponent(convertible[0]!.environmentId);
+ goto(`/projects/new?fromContainers=${convertible.map((c) => c.id).join(',')}&fromEnv=${fromEnv}`);
}
function filterUpdatableContainerIds() {
return selectedIds?.filter((id) => {
- const container = containers.data?.find((c) => c.id === id);
+ const container = containers.data?.find((c) => rowKey(c) === id);
return container?.updateInfo?.hasUpdate;
});
}
@@ -325,9 +349,9 @@
// The dialog is mounted only while a row is targeted, so it gets fresh state on
// every open; clearing the target unmounts it.
- let killTarget = $state<ContainerSummaryDto | null>(null);
+ let killTarget = $state<ContainerRow | null>(null);
- function openKillDialog(container: ContainerSummaryDto) {
+ function openKillDialog(container: ContainerRow) {
killTarget = container;
}
@@ -384,6 +408,7 @@
}
const columns = $derived([
+ ...environmentColumns<ContainerRow>(),
{ accessorKey: 'id', title: m.common_id(), cell: IdCell, hidden: true },
{
accessorKey: 'names',
@@ -420,14 +445,14 @@
id: 'cpuUsage',
// TanStack only treats accessor columns as sortable, so the sampled value is
// exposed even though ordering happens on the server.
- accessorFn: (row) => row.resourceSample?.cpuPercent ?? null,
+ accessorFn: (row) => containerSortValue(row, 'cpuUsage'),
title: m.cpu_usage(),
sortable: !groupByProject && resourceSortSupported,
cell: CPUCell
},
{
id: 'memoryUsage',
- accessorFn: (row) => row.resourceSample?.memoryUsageBytes ?? null,
+ accessorFn: (row) => containerSortValue(row, 'memoryUsage'),
title: m.memory_usage(),
sortable: !groupByProject && resourceSortSupported,
cell: MemoryCell
@@ -458,7 +483,7 @@
title: m.common_labels(),
hidden: true
}
- ] satisfies ColumnSpec<ContainerSummaryDto>[]);
+ ] satisfies ColumnSpec<ContainerRow>[]);
const mobileFields = [
{ id: 'id', label: m.common_id(), defaultVisible: false },
@@ -562,7 +587,7 @@
}),
action: 'base' as const,
onClick: handleBulkConvert,
- disabled: !resourcesCurrent || isAnyLoading,
+ disabled: !resourcesCurrent || isAnyLoading || selectedEnvironmentIds.size > 1,
icon: ProjectsIcon
}
]
@@ -574,13 +599,13 @@
return ProjectsIcon;
}
- function getGroupName(item: ContainerSummaryDto): string {
+ function getGroupName(item: ContainerRow): string {
return getProjectName(item);
}
</script>
{#if resourcesCurrent}
- <ContainerStatsSync {statsManager} envId={environmentId} targetIds={shouldConnect} />
+ <ContainerStatsSync {statsManager} targetIds={shouldConnect} />
{/if}
{#snippet IPAddressCell({ item }: { item: ContainerSummaryDto })}
@@ -618,9 +643,9 @@
/>
{:else}
<ContainerStatsCell
- value={statsManager.getCPUPercent(item.id)}
- loading={statsManager.isLoading(item.id) ?? false}
- unavailable={statsManager.hasError(item.id)}
+ value={statsManager.getCPUPercent(rowKey(item))}
+ loading={statsManager.isLoading(rowKey(item)) ?? false}
+ unavailable={statsManager.hasError(rowKey(item))}
stopped={item.state !== 'running'}
type="cpu"
/>
@@ -637,11 +662,11 @@
type="memory"
/>
{:else}
- {@const memoryData = statsManager.getMemoryUsage(item.id)}
+ {@const memoryData = statsManager.getMemoryUsage(rowKey(item))}
<ContainerStatsCell
value={memoryData?.usage}
limit={memoryData?.limit}
- unavailable={statsManager.hasError(item.id)}
+ unavailable={statsManager.hasError(rowKey(item))}
stopped={item.state !== 'running'}
type="memory"
/>
@@ -652,13 +677,15 @@
<PortBadge ports={item.ports ?? []} hideExposed={hideExposedPorts} wrap={false} />
{/snippet}
-{#snippet NameCell({ item }: { item: ContainerSummaryDto })}
+{#snippet NameCell({ item }: { item: ContainerRow })}
{@const displayName = getContainerDisplayName(item)}
{@const iconUrl = getThemedIconUrl(item, mode.current)}
{@const projectLabel = item.labels?.[COMPOSE_PROJECT_LABEL]}
<div class="flex items-center gap-2">
<IconImage src={iconUrl} alt={displayName} fallback={BoxIcon} class="size-6" containerClass="size-8 shrink-0" />
- <a class="min-w-0 truncate font-medium hover:underline" href="/containers/{item.id}">{displayName}</a>
+ <a class="min-w-0 truncate font-medium hover:underline" href={environmentHref(`/containers/${item.id}`, item.environmentId)}
+ >{displayName}</a
+ >
{#if item.hidden}
<Badge variant="gray" size="sm">{m.hidden()}</Badge>
{/if}
@@ -676,8 +703,8 @@
<span class="font-mono text-sm">{String(item.id)}</span>
{/snippet}
-{#snippet StateCell({ item }: { item: ContainerSummaryDto })}
- {@const status = actionStatus[item.id]}
+{#snippet StateCell({ item }: { item: ContainerRow })}
+ {@const status = actionStatus[rowKey(item)]}
<div class="flex items-center gap-2">
{#if status}
<div class="flex items-center gap-1.5">
@@ -690,30 +717,30 @@
<Badge variant={getStateBadgeVariant(item.state)} minWidth="20">{getContainerStatusLabel(item.state)}</Badge>
{/if}
<div class="flex items-center gap-1 {stateActionsMinWidth}">
- {#if !status && item.state !== 'running' && canStartContainers}
+ {#if !status && item.state !== 'running' && hasPermission('containers:start', item.environmentId)}
<ArcaneButton
action="base"
tone="outline"
size="sm"
class="size-7 border-transparent bg-transparent p-0 text-success shadow-none hover:bg-success/10 hover:text-success"
- onclick={() => performContainerAction('start', item.id)}
+ onclick={() => performContainerAction('start', item.id, item.environmentId)}
disabled={!resourcesCurrent || isAnyLoading}
icon={StartIcon}
title={m.common_start()}
/>
- {:else if !status && item.state === 'running' && canStopContainers}
+ {:else if !status && item.state === 'running' && hasPermission('containers:stop', item.environmentId)}
<ArcaneButton
action="base"
tone="outline"
size="sm"
class="size-7 border-transparent bg-transparent p-0 text-destructive shadow-none hover:bg-destructive/10 hover:text-destructive"
- onclick={() => performContainerAction('stop', item.id)}
+ onclick={() => performContainerAction('stop', item.id, item.environmentId)}
disabled={!resourcesCurrent || isAnyLoading}
title={m.common_stop()}
icon={StopIcon}
/>
{/if}
- {#if !status && item.updateInfo?.hasUpdate && canUpdateContainers}
+ {#if !status && item.updateInfo?.hasUpdate && hasPermission('containers:autoupdate', item.environmentId)}
<ArcaneButton
action="base"
tone="ghost"
@@ -729,24 +756,25 @@
</div>
{/snippet}
-{#snippet ContainerUpdateItem(item: ContainerSummaryDto)}
+{#snippet ContainerUpdateItem(item: ContainerRow)}
{@const imageRef = parseImageRef(item.image)}
<ImageUpdateItem
updateInfo={item.updateInfo}
imageId={item.imageId}
imageRef={item.image}
containerId={item.id}
+ environmentId={item.environmentId}
tagUpdates={item.updateStrategy
? item.updateStrategy !== 'digest'
: item.labels?.['com.getarcaneapp.arcane.updater.strategy']?.trim() === 'tag'}
repo={imageRef.repo}
tag={imageRef.tag}
- onUpdateContainer={canUpdateContainers ? () => handleUpdateContainer(item) : undefined}
+ onUpdateContainer={hasPermission('containers:autoupdate', item.environmentId) ? () => handleUpdateContainer(item) : undefined}
debugHasUpdate={false}
/>
{/snippet}
-{#snippet UpdatesCell({ item }: { item: ContainerSummaryDto })}
+{#snippet UpdatesCell({ item }: { item: ContainerRow })}
{@render ContainerUpdateItem(item)}
{/snippet}
@@ -773,7 +801,7 @@
item,
mobileFieldVisibility
}: {
- item: ContainerSummaryDto;
+ item: ContainerRow;
mobileFieldVisibility: FieldVisibility;
})}
<UniversalMobileCard
@@ -831,8 +859,8 @@
const cpu = item.resourceSample?.cpuPercent;
return cpu === undefined ? m.common_unavailable() : `${cpu.toFixed(1)}%`;
}
- const cpu = statsManager.getCPUPercent(item.id);
- if (cpu === undefined) return statsManager.hasError(item.id) ? m.common_unavailable() : '...';
+ const cpu = statsManager.getCPUPercent(rowKey(item));
+ if (cpu === undefined) return statsManager.hasError(rowKey(item)) ? m.common_unavailable() : '...';
return `${cpu.toFixed(1)}%`;
},
icon: ClockIcon,
@@ -847,8 +875,8 @@
const usage = item.resourceSample?.memoryUsageBytes;
return usage === undefined ? m.common_unavailable() : `${(usage / 1024 / 1024).toFixed(0)} MB`;
}
- const memData = statsManager.getMemoryUsage(item.id);
- if (!memData?.usage) return statsManager.hasError(item.id) ? m.common_unavailable() : '...';
+ const memData = statsManager.getMemoryUsage(rowKey(item));
+ if (!memData?.usage) return statsManager.hasError(rowKey(item)) ? m.common_unavailable() : '...';
return `${(memData.usage / 1024 / 1024).toFixed(0)} MB`;
},
icon: ClockIcon,
@@ -864,7 +892,7 @@
}
: undefined}
rowActions={RowActions}
- onclick={(item: ContainerSummaryDto) => goto(`/containers/${item.id}`)}
+ onclick={(item: ContainerRow) => goto(environmentHref(`/containers/${item.id}`, item.environmentId))}
>
{#if ((mobileFieldVisibility['ports'] ?? true) && item.ports && item.ports.length > 0) || (mobileFieldVisibility['updates'] ?? true)}
<div class="flex flex-row gap-4 border-t pt-3">
@@ -900,25 +928,26 @@
</UniversalMobileCard>
{/snippet}
-{#snippet RowActions({ item }: { item: ContainerSummaryDto })}
+{#snippet RowActions({ item }: { item: ContainerRow })}
{#if resourcesCurrent}
- {@const status = actionStatus[item.id]}
+ {@const status = actionStatus[rowKey(item)]}
+ {@const envId = item.environmentId}
<RowActionsMenu>
- <DropdownMenu.Item onclick={() => goto(`/containers/${item.id}`)} disabled={isAnyLoading}>
+ <DropdownMenu.Item onclick={() => goto(environmentHref(`/containers/${item.id}`, envId))} disabled={isAnyLoading}>
<InspectIcon class="size-4" />
{m.common_inspect()}
</DropdownMenu.Item>
- {#if canEditContainers && !item.redeployDisabled && !item.labels?.[COMPOSE_PROJECT_LABEL]}
- <DropdownMenu.Item onclick={() => goto(`/containers/${item.id}/edit`)} disabled={isAnyLoading}>
+ {#if hasPermission('containers:edit', envId) && !item.redeployDisabled && !item.labels?.[COMPOSE_PROJECT_LABEL]}
+ <DropdownMenu.Item onclick={() => goto(environmentHref(`/containers/${item.id}/edit`, envId))} disabled={isAnyLoading}>
<EditIcon class="size-4" />
{m.common_edit()}
</DropdownMenu.Item>
{/if}
- {#if canConvertToCompose && !item.labels?.[COMPOSE_PROJECT_LABEL]}
+ {#if canConvertToCompose && hasPermission('projects:create', envId) && !item.labels?.[COMPOSE_PROJECT_LABEL]}
<DropdownMenu.Item
- onclick={() => goto(`/projects/new?fromContainers=${item.id}&fromEnv=${encodeURIComponent(currentEnvId)}`)}
+ onclick={() => goto(`/projects/new?fromContainers=${item.id}&fromEnv=${encodeURIComponent(envId)}`)}
disabled={isAnyLoading}
>
<ProjectsIcon class="size-4" />
@@ -928,7 +957,7 @@
<DropdownMenu.Separator />
- {#if item.updateInfo?.hasUpdate && canUpdateContainers}
+ {#if item.updateInfo?.hasUpdate && hasPermission('containers:autoupdate', envId)}
<ActionMenuItem
onclick={() => handleUpdateContainer(item)}
disabled={isAnyLoading}
@@ -938,47 +967,47 @@
/>
{/if}
{#if item.state === 'paused'}
- <IfPermitted perm="containers:pause" envId={currentEnvId}>
+ <IfPermitted perm="containers:pause" {envId}>
<ActionMenuItem
- onclick={() => performContainerAction('unpause', item.id)}
+ onclick={() => performContainerAction('unpause', item.id, envId)}
disabled={isAnyLoading}
icon={PlayIcon}
label={m.common_unpause()}
loading={status === 'unpausing'}
/>
</IfPermitted>
- {:else if item.state !== 'running' && canStartContainers}
+ {:else if item.state !== 'running' && hasPermission('containers:start', envId)}
<ActionMenuItem
- onclick={() => performContainerAction('start', item.id)}
+ onclick={() => performContainerAction('start', item.id, envId)}
disabled={isAnyLoading}
icon={StartIcon}
label={m.common_start()}
loading={status === 'starting'}
/>
{:else if item.state === 'running'}
- <IfPermitted perm="containers:stop" envId={currentEnvId}>
+ <IfPermitted perm="containers:stop" {envId}>
<ActionMenuItem
icon={StopIcon}
label={m.common_stop()}
- onclick={() => performContainerAction('stop', item.id)}
+ onclick={() => performContainerAction('stop', item.id, envId)}
loading={status === 'stopping'}
disabled={isAnyLoading}
/>
</IfPermitted>
- <IfPermitted perm="containers:restart" envId={currentEnvId}>
+ <IfPermitted perm="containers:restart" {envId}>
<ActionMenuItem
icon={RefreshIcon}
label={m.common_restart()}
- onclick={() => performContainerAction('restart', item.id)}
+ onclick={() => performContainerAction('restart', item.id, envId)}
loading={status === 'restarting'}
disabled={isAnyLoading}
/>
</IfPermitted>
- <IfPermitted perm="containers:pause" envId={currentEnvId}>
+ <IfPermitted perm="containers:pause" {envId}>
<ActionMenuItem
- onclick={() => performContainerAction('pause', item.id)}
+ onclick={() => performContainerAction('pause', item.id, envId)}
disabled={isAnyLoading}
icon={PauseIcon}
label={m.common_pause()}
@@ -987,14 +1016,14 @@
</IfPermitted>
{/if}
- {#if (item.state === 'running' || item.state === 'paused') && canKillContainers}
+ {#if (item.state === 'running' || item.state === 'paused') && hasPermission('containers:kill', envId)}
<DropdownMenu.Item onclick={() => openKillDialog(item)} disabled={isAnyLoading}>
<ZapIcon class="size-4" />
{m.common_kill()}
</DropdownMenu.Item>
{/if}
- <IfPermitted perm="containers:redeploy" envId={currentEnvId}>
+ <IfPermitted perm="containers:redeploy" {envId}>
{#if item.redeployDisabled}
<DropdownMenu.Item disabled title={m.common_redeploy_disabled_arcane_self()}>
<RedeployIcon class="size-4 opacity-50" />
@@ -1013,11 +1042,11 @@
<DropdownMenu.Separator />
- <IfPermitted perm="containers:delete" envId={currentEnvId}>
+ <IfPermitted perm="containers:delete" {envId}>
<ActionMenuItem
icon={TrashIcon}
label={m.common_remove()}
- onclick={() => handleRemoveContainer(item.id, getContainerDisplayName(item))}
+ onclick={() => handleRemoveContainer(item.id, getContainerDisplayName(item), envId)}
loading={status === 'removing'}
disabled={isAnyLoading}
destructive
@@ -1096,6 +1125,7 @@
<KillContainerDialog
containerId={killTarget.id}
containerName={getContainerDisplayName(killTarget)}
+ environmentId={killTarget.environmentId}
onClose={() => (killTarget = null)}
onComplete={async () => {
await refreshContainers(requestOptions);
diff --git a/frontend/src/routes/(app)/containers/components/kill-container-dialog.svelte b/frontend/src/routes/(app)/containers/components/kill-container-dialog.svelte
index 8ef71af8c..e7ab7bde1 100644
--- a/frontend/src/routes/(app)/containers/components/kill-container-dialog.svelte
+++ b/frontend/src/routes/(app)/containers/components/kill-container-dialog.svelte
@@ -14,11 +14,12 @@
type Props = {
containerId: string;
containerName: string;
+ environmentId: string;
onClose?: () => void;
onComplete?: () => void | Promise<void>;
};
- let { containerId, containerName, onClose, onComplete }: Props = $props();
+ let { containerId, containerName, environmentId, onClose, onComplete }: Props = $props();
const SIGNALS = ['SIGKILL', 'SIGTERM', 'SIGINT', 'SIGHUP', 'SIGQUIT'];
let open = $state(true);
@@ -29,7 +30,7 @@
if (!containerId) return;
isSubmitting = true;
await handleApiResultWithCallbacks({
- result: await tryCatch(containerService.killContainer(containerId, signal)),
+ result: await tryCatch(containerService.killContainer(containerId, signal, environmentId)),
message: m.containers_kill_failed({ name: containerName }),
setLoadingState: (value) => {
isSubmitting = value;
diff --git a/frontend/src/routes/(app)/containers/container-table.actions.ts b/frontend/src/routes/(app)/containers/container-table.actions.ts
index 7427f9f04..a5b8a0ea6 100644
--- a/frontend/src/routes/(app)/containers/container-table.actions.ts
+++ b/frontend/src/routes/(app)/containers/container-table.actions.ts
@@ -4,6 +4,7 @@ import { toast } from 'svelte-sonner';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import { m } from '#lib/paraglide/messages.js';
import { containerService, type ContainersPaginatedResponse } from '#lib/services/container-service.js';
+import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { Activity } from '#lib/types/activity.type.js';
import type { ContainerSummaryDto } from '#lib/types/docker.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
@@ -15,6 +16,7 @@ import {
confirmAndUpdateContainer,
runContainerLifecycleAction
} from '#lib/utils/container-actions.js';
+import { hasShownPermission, rowKey, type EnvironmentPage, type EnvironmentRow } from '#lib/utils/environments.js';
import type { TableActionConfig, TableBulkActionConfig } from '#lib/utils/table-action-types.js';
import { tryCatch } from '#lib/utils/try-catch.js';
@@ -29,16 +31,20 @@ type BulkLoadingState = {
};
type ActionDeps = {
- setContainers: (next: ContainersPaginatedResponse) => void;
+ setContainers: (next: ContainerPage) => void;
setSelectedIds: (next: string[]) => void;
- refreshContainers: () => Promise<ContainersPaginatedResponse>;
+ refreshContainers: () => Promise<ContainerPage>;
actionStatus: Record<string, ActionStatus>;
isBulkLoading: BulkLoadingState;
- environmentId: () => string;
+ /** Shown-environments scope the table rendered; compared only, never sent to the API. */
+ scope: () => string;
onUpdateAccepted: (activity: Activity) => void;
canRefreshUpdates: () => boolean;
};
+type ContainerRow = EnvironmentRow<ContainerSummaryDto>;
+type ContainerPage = EnvironmentPage<ContainersPaginatedResponse>;
+
type ContainerActionKind = 'start' | 'stop' | 'restart' | 'pause' | 'unpause' | 'redeploy';
type ContainerActionConfig = TableActionConfig<ActionStatus>;
@@ -50,7 +56,7 @@ const containerActionConfigs: Record<
> = {
redeploy: {
status: 'redeploying',
- run: (id) => containerService.redeployContainer(id),
+ run: (id, environmentId) => containerService.redeployContainer(id, environmentId),
success: () => m.container_redeploy_success(),
failure: () => m.container_redeploy_failed()
}
@@ -62,7 +68,7 @@ export function createContainerActions({
refreshContainers,
actionStatus,
isBulkLoading,
- environmentId,
+ scope,
onUpdateAccepted,
canRefreshUpdates
}: ActionDeps) {
@@ -72,13 +78,15 @@ export function createContainerActions({
return result;
};
- async function performContainerAction(action: ContainerActionKind, id: string) {
+ async function performContainerAction(action: ContainerActionKind, id: string, environmentId: string) {
+ const key = rowKey({ id, environmentId, environmentTagged: true });
if (action === 'start' || action === 'stop' || action === 'restart' || action === 'pause' || action === 'unpause') {
await runContainerLifecycleAction({
action,
containerId: id,
+ environmentId,
setStatus: (status) => {
- actionStatus[id] = status;
+ actionStatus[key] = status;
},
onRefresh: reloadContainers
});
@@ -86,15 +94,15 @@ export function createContainerActions({
}
const config = containerActionConfigs[action];
- actionStatus[id] = config.status;
+ actionStatus[key] = config.status;
const operationResult = await tryCatch(
(async () => {
await handleApiResultWithCallbacks({
- result: await tryCatch(config.run(id)),
+ result: await tryCatch(config.run(id, environmentId)),
message: config.failure(),
setLoadingState: (value) => {
- actionStatus[id] = value ? config.status : '';
+ actionStatus[key] = value ? config.status : '';
},
async onSuccess(data) {
toast.success(config.success(), activityToastOptions(extractActivityId(data)));
@@ -108,37 +116,41 @@ export function createContainerActions({
console.error('Container action failed:', error);
toast.error(m.containers_action_error());
- actionStatus[id] = '';
+ actionStatus[key] = '';
}
}
- async function handleRemoveContainer(id: string, name: string) {
+ async function handleRemoveContainer(id: string, name: string, environmentId: string) {
+ const key = rowKey({ id, environmentId, environmentTagged: true });
confirmAndRemoveContainer({
containerId: id,
containerName: name,
+ environmentId,
setStatus: (status) => {
- actionStatus[id] = status;
+ actionStatus[key] = status;
},
onRefresh: reloadContainers
});
}
- async function handleUpdateContainer(container: ContainerSummaryDto) {
+ async function handleUpdateContainer(container: ContainerRow) {
+ const key = rowKey(container);
const containerName = getContainerDisplayName(container);
confirmAndUpdateContainer({
containerId: container.id,
containerName,
- environmentId: environmentId(),
+ environmentId: container.environmentId,
setLoading: (loading) => {
- actionStatus[container.id] = loading ? 'updating' : '';
+ actionStatus[key] = loading ? 'updating' : '';
},
onRefresh: () => (canRefreshUpdates() ? reloadContainers() : undefined),
onAccepted: onUpdateAccepted
});
}
- async function handleRedeployContainer(container: ContainerSummaryDto) {
+ async function handleRedeployContainer(container: ContainerRow) {
+ const key = rowKey(container);
openConfirmDialog({
title: m.container_confirm_redeploy_title(),
message: m.container_confirm_redeploy_message(),
@@ -146,12 +158,12 @@ export function createContainerActions({
label: m.common_redeploy(),
destructive: false,
action: async () => {
- actionStatus[container.id] = 'redeploying';
+ actionStatus[key] = 'redeploying';
await handleApiResultWithCallbacks({
- result: await tryCatch(containerService.redeployContainer(container.id)),
+ result: await tryCatch(containerService.redeployContainer(container.id, container.environmentId)),
message: m.container_redeploy_failed(),
setLoadingState: (value) => {
- actionStatus[container.id] = value ? 'redeploying' : '';
+ actionStatus[key] = value ? 'redeploying' : '';
},
async onSuccess(data) {
toast.success(m.container_redeploy_success(), activityToastOptions(extractActivityId(data)));
@@ -170,7 +182,7 @@ export function createContainerActions({
message: config.message(ids.length),
confirmLabel: config.label,
destructive: config.destructive ?? false,
- run: (id) => config.run(id),
+ run: (id, environmentId) => config.run(id, environmentId),
messages: {
success: config.success,
partial: config.partial,
@@ -190,7 +202,7 @@ export function createContainerActions({
message: (count) => m.containers_bulk_start_confirm_message({ count }),
label: m.common_start(),
loadingKey: 'start',
- run: (id) => containerService.startContainer(id),
+ run: (id, environmentId) => containerService.startContainer(id, environmentId),
success: (count) => m.containers_bulk_start_success({ count }),
partial: (success, total, failed) => m.containers_bulk_start_partial({ success, total, failed }),
failure: () => m.containers_start_failed()
@@ -203,7 +215,7 @@ export function createContainerActions({
message: (count) => m.containers_bulk_stop_confirm_message({ count }),
label: m.common_stop(),
loadingKey: 'stop',
- run: (id) => containerService.stopContainer(id),
+ run: (id, environmentId) => containerService.stopContainer(id, environmentId),
success: (count) => m.containers_bulk_stop_success({ count }),
partial: (success, total, failed) => m.containers_bulk_stop_partial({ success, total, failed }),
failure: () => m.containers_stop_failed()
@@ -216,7 +228,7 @@ export function createContainerActions({
message: (count) => m.containers_bulk_restart_confirm_message({ count }),
label: m.common_restart(),
loadingKey: 'restart',
- run: (id) => containerService.restartContainer(id),
+ run: (id, environmentId) => containerService.restartContainer(id, environmentId),
success: (count) => m.containers_bulk_restart_success({ count }),
partial: (success, total, failed) => m.containers_bulk_restart_partial({ success, total, failed }),
failure: () => m.containers_restart_failed()
@@ -224,7 +236,8 @@ export function createContainerActions({
}
function handleBulkUpdate(validIds: string[], allIds: string[]) {
- const updateEnvironmentId = environmentId();
+ const updateScope = scope();
+ const tracksActivities = environmentStore.shown.every((env) => hasPermission('activities:read', env.id));
const totalCount = allIds.length;
const filteredCount = validIds.length;
const message =
@@ -238,22 +251,19 @@ export function createContainerActions({
message,
confirmLabel: m.common_update(),
destructive: false,
- run: (id) => containerService.updateContainer(id, updateEnvironmentId),
+ run: (id, environmentId) => containerService.updateContainer(id, environmentId),
messages: {
success: (count) => m.containers_bulk_update_accepted({ count }),
partial: (success, total, failed) => m.containers_bulk_update_accept_partial({ success, total, failed }),
failure: () => m.containers_bulk_update_accept_failed()
},
acceptanceOnly: true,
- activityLink: hasPermission('activities:read', updateEnvironmentId),
+ activityLink: hasShownPermission('activities:read'),
onItemSuccess: (_id, activity) => onUpdateAccepted(activity),
setLoading: (loading) => {
isBulkLoading['update'] = loading;
},
- onComplete: () =>
- canRefreshUpdates() && updateEnvironmentId === environmentId() && !hasPermission('activities:read', updateEnvironmentId)
- ? reloadContainers()
- : undefined,
+ onComplete: () => (canRefreshUpdates() && updateScope === scope() && !tracksActivities ? reloadContainers() : undefined),
clearSelection: () => setSelectedIds([])
});
}
@@ -269,8 +279,12 @@ export function createContainerActions({
{ id: 'force', label: m.containers_remove_force_label(), initialState: false },
{ id: 'volumes', label: m.containers_remove_volumes_label(), initialState: false }
],
- run: (id, checkboxStates) =>
- containerService.deleteContainer(id, { force: !!checkboxStates['force'], volumes: !!checkboxStates['volumes'] }),
+ run: (id, environmentId, checkboxStates) =>
+ containerService.deleteContainer(id, {
+ force: !!checkboxStates['force'],
+ volumes: !!checkboxStates['volumes'],
+ environmentId
+ }),
messages: {
success: (count) => m.containers_bulk_remove_success({ count }),
partial: (success, total, failed) => m.containers_bulk_remove_partial({ success, total, failed }),
diff --git a/frontend/src/routes/(app)/containers/container-table.helpers.ts b/frontend/src/routes/(app)/containers/container-table.helpers.ts
index 33c7b8b21..2f74212bd 100644
--- a/frontend/src/routes/(app)/containers/container-table.helpers.ts
+++ b/frontend/src/routes/(app)/containers/container-table.helpers.ts
@@ -15,6 +15,35 @@ export type ActionStatus =
| '';
export type StateBadgeVariant = 'green' | 'red' | 'amber';
+/** The lowest published port, else the lowest private one, as the backend sorts ports. */
+function lowestPort(container: ContainerSummaryDto): number | null {
+ const ports = container.ports ?? [];
+ const lowest = (values: number[]) => (values.length > 0 ? Math.min(...values) : null);
+ return (
+ lowest(ports.flatMap((port) => (port.publicPort ? [port.publicPort] : []))) ??
+ lowest(ports.flatMap((port) => (port.privatePort > 0 ? [port.privatePort] : [])))
+ );
+}
+
+/** Sort value for a container column whose sort key is not a row field. */
+export function containerSortValue(container: ContainerSummaryDto, column: string): unknown {
+ switch (column) {
+ case 'name':
+ return container.names?.[0];
+ case 'cpuUsage':
+ return container.resourceSample?.cpuPercent ?? null;
+ case 'memoryUsage':
+ return container.resourceSample?.memoryUsageBytes ?? null;
+ case 'ports':
+ return lowestPort(container);
+ // The updates table sorts its image column as imageRef.
+ case 'imageRef':
+ return container.image;
+ default:
+ return container[column as keyof ContainerSummaryDto];
+ }
+}
+
export function getContainerDisplayName(container: ContainerSummaryDto): string {
const first = container.names?.[0];
if (first) {
diff --git a/frontend/src/routes/(app)/containers/new/+page.svelte b/frontend/src/routes/(app)/containers/new/+page.svelte
index 579bb0fae..524e93599 100644
--- a/frontend/src/routes/(app)/containers/new/+page.svelte
+++ b/frontend/src/routes/(app)/containers/new/+page.svelte
@@ -11,26 +11,29 @@
toCreateRequest
} from '#lib/components/containers/container-form/container-form-state.js';
import ContainerForm from '#lib/components/containers/container-form/container-form.svelte';
+ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';
import { ArrowLeftIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { containerService } from '#lib/services/container-service.js';
import { extractApiErrorMessage } from '#lib/utils/api.js';
+ import { destinationEnvironmentId, environmentHref } from '#lib/utils/environments.js';
import { createForm } from '#lib/utils/settings.svelte.js';
- let { data } = $props();
-
const queryClient = useQueryClient();
const form = createForm<typeof containerFormSchema>(containerFormSchema, emptyContainerFormValues());
let rows = $state(emptyContainerFormRows());
+ let pickedEnvironmentId = $state('');
+ const environmentId = $derived(destinationEnvironmentId(pickedEnvironmentId, 'containers:create'));
const createContainerMutation = createMutation(() => ({
- mutationKey: queryKeys.containers.create(data.envId),
- mutationFn: (request: ReturnType<typeof toCreateRequest>) => containerService.createContainer(request, data.envId),
- onSuccess: async (created) => {
+ mutationKey: queryKeys.containers.create(environmentId),
+ mutationFn: ({ request, destination }: { request: ReturnType<typeof toCreateRequest>; destination: string }) =>
+ containerService.createContainer(request, destination),
+ onSuccess: async (created, { destination }) => {
toast.success(m.common_create_success({ resource: m.resource_container() }));
await queryClient.invalidateQueries({ queryKey: queryKeys.containers.all });
- goto(`/containers/${created.id}`);
+ goto(environmentHref(`/containers/${created.id}`, destination));
},
onError: (error) => {
toast.error(m.containers_create_failed(), { description: extractApiErrorMessage(error) });
@@ -40,7 +43,7 @@
function handleSubmit() {
const values = form.validate();
if (!values) return;
- createContainerMutation.mutate(toCreateRequest(values, rows));
+ createContainerMutation.mutate({ request: toCreateRequest(values, rows), destination: environmentId });
}
</script>
@@ -61,7 +64,18 @@
</div>
</div>
- <div class="mx-auto w-full max-w-full px-6 py-6">
- <ContainerForm mode="create" {form} bind:rows submitting={createContainerMutation.isPending} onSubmit={handleSubmit} />
+ <div class="mx-auto w-full max-w-full space-y-6 px-6 py-6">
+ <EnvironmentDestinationSelect
+ bind:value={() => environmentId, (value) => (pickedEnvironmentId = value)}
+ permission="containers:create"
+ />
+ <ContainerForm
+ mode="create"
+ {form}
+ {environmentId}
+ bind:rows
+ submitting={createContainerMutation.isPending}
+ onSubmit={handleSubmit}
+ />
</div>
</div>
diff --git a/frontend/src/routes/(app)/containers/new/+page.ts b/frontend/src/routes/(app)/containers/new/+page.ts
index 76a652ede..f0ac44806 100644
--- a/frontend/src/routes/(app)/containers/new/+page.ts
+++ b/frontend/src/routes/(app)/containers/new/+page.ts
@@ -8,7 +8,8 @@ import type { PageLoad } from './$types';
export const load: PageLoad = async ({ parent }) => {
const { user } = await parent();
const envId = await environmentStore.getCurrentEnvironmentId();
- if (!userHasPermission(user, 'containers:create', envId)) {
+ const shown = await environmentStore.getShownEnvironments();
+ if (!shown.some((env) => userHasPermission(user, 'containers:create', env.id))) {
redirect(302, '/containers');
}
diff --git a/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte b/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte
index dfc67c183..852cdd081 100644
--- a/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte
@@ -260,7 +260,7 @@
]);
</script>
-<ResourcePageLayout title={m.git_syncs_title()} subtitle={m.git_subtitle()} {actionButtons} {statCards}>
+<ResourcePageLayout title={m.git_syncs_title()} subtitle={m.git_subtitle()} {actionButtons} {statCards} environmentPicker>
{#snippet mainContent()}
<SyncTable
{environmentId}
diff --git a/frontend/src/routes/(app)/events/+page.svelte b/frontend/src/routes/(app)/events/+page.svelte
index 31deefa1e..c485c964d 100644
--- a/frontend/src/routes/(app)/events/+page.svelte
+++ b/frontend/src/routes/(app)/events/+page.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import { createQuery, keepPreviousData } from '@tanstack/svelte-query';
- import { onMount } from 'svelte';
+ import { onMount, tick } from 'svelte';
import { AlertIcon, CheckIcon, CloseIcon, EventsIcon, InfoIcon } from '#lib/icons/index.js';
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';
@@ -20,12 +20,15 @@
let requestOptions = $derived(data.eventRequestOptions);
let isDeleting = $state(false);
- const eventsQuery = createQuery(() => ({
- queryKey: queryKeys.events.listGlobal(requestOptions),
- queryFn: () => eventService.getEvents(requestOptions),
- placeholderData: keepPreviousData,
- initialData: data.events
- }));
+ // The load already cached the first page under its key; seeding every key with it would hide other pages and filters.
+ const eventsQuery = createQuery(() => {
+ const options = requestOptions;
+ return {
+ queryKey: queryKeys.events.listGlobal(options),
+ queryFn: () => eventService.getEvents(options),
+ placeholderData: keepPreviousData
+ };
+ });
const statsQuery = createQuery(() => ({
queryKey: queryKeys.events.statsGlobal(),
@@ -208,7 +211,9 @@
bind:requestOptions
onRefreshData={async (options) => {
requestOptions = options;
- await refresh();
+ // Let the query switch to the new options first; the refetch then joins its fetch.
+ await tick();
+ await Promise.all([eventsQuery.refetch({ cancelRefetch: false }), statsQuery.refetch()]);
}}
/>
{/snippet}
diff --git a/frontend/src/routes/(app)/images/+page.svelte b/frontend/src/routes/(app)/images/+page.svelte
index 3133c5e24..7c0c00061 100644
--- a/frontend/src/routes/(app)/images/+page.svelte
+++ b/frontend/src/routes/(app)/images/+page.svelte
@@ -4,6 +4,7 @@
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import ImageRegistrySearchDialog from '#lib/components/dialogs/image-registry-search-dialog.svelte';
+ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';
import PruneModePicker from '#lib/components/prune/prune-mode-picker.svelte';
import SettingsRow from '#lib/components/settings/settings-row.svelte';
import SettingsSection from '#lib/components/settings/settings-section.svelte';
@@ -19,15 +20,25 @@
import { queryKeys } from '#lib/query/query-keys.js';
import { imageService } from '#lib/services/image-service.js';
import type { ChunkedUploadProgress } from '#lib/services/upload-service.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+ import { environmentStore, type EnvironmentRef } from '#lib/stores/environment.store.svelte.js';
import type { ImageUsageCounts } from '#lib/types/docker.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
- import { hasPermission } from '#lib/utils/auth.js';
+ import {
+ acrossEnvironmentsNote,
+ actionEnvironments,
+ destinationEnvironmentId,
+ fetchAcrossEnvironments,
+ hasShownPermission,
+ listScopes,
+ settleAcrossEnvironments,
+ sumAcrossEnvironments,
+ withFailedEnvironments
+ } from '#lib/utils/environments.js';
import { bytes } from '#lib/utils/formatting.js';
import { tryCatch } from '#lib/utils/try-catch.js';
- import ImageTable from './components/image-table.svelte';
+ import ImageTable, { imageSortValue } from './components/image-table.svelte';
let { data } = $props();
const queryClient = useQueryClient();
@@ -44,6 +55,7 @@
let imagePruneMode = $state<'dangling' | 'all' | 'olderThan'>('dangling');
let imagePruneUntil = $state('');
const envId = $derived(environmentStore.selected?.id || '0');
+ const scope = $derived(environmentStore.shownKey);
const imageUsageFallback: ImageUsageCounts = {
imagesInuse: 0,
imagesUnused: 0,
@@ -55,48 +67,74 @@
// the server still enforces the real limit.
const DEFAULT_MAX_UPLOAD_SIZE_MB = 500;
+ // The load already cached the first page under its key; seeding every key with it would hide other pages and filters.
const imagesQuery = createQuery(() => {
- const queryEnvId = envId;
+ const queryScope = scope;
+ const environments = environmentStore.shown;
const options = requestOptions;
return {
- queryKey: queryKeys.images.list(queryEnvId, options),
- queryFn: () => imageService.getImagesForEnvironment(queryEnvId, options),
+ queryKey: queryKeys.images.list(queryScope, options),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ environments,
+ options,
+ (id, request, config) => imageService.getImagesForEnvironment(id, request, config),
+ imageSortValue
+ ),
placeholderData: (previous, query) => {
- if (query?.queryKey[1] === queryEnvId) return previous;
+ if (query?.queryKey[1] === queryScope) return previous;
return undefined;
},
- initialData: data.envId === queryEnvId ? data.images : undefined,
- select: (value) => ({ envId: queryEnvId, value })
+ select: (value) => ({ envId: queryScope, value })
};
});
const imageUsageCountsQuery = createQuery(() => {
- const queryEnvId = envId;
+ const queryScope = scope;
+ const environments = environmentStore.shown;
return {
- queryKey: queryKeys.images.usageCounts(queryEnvId),
- queryFn: () => imageService.getImageUsageCountsForEnvironment(queryEnvId),
- initialData: data.envId === queryEnvId ? data.imageUsageCounts : undefined,
- select: (value) => ({ envId: queryEnvId, value })
+ queryKey: queryKeys.images.usageCounts(queryScope),
+ queryFn: () =>
+ sumAcrossEnvironments(environments, (id, config) => imageService.getImageUsageCountsForEnvironment(id, config)),
+ initialData: data.scope === queryScope ? data.imageUsageCounts : undefined,
+ select: (value) => ({ envId: queryScope, value })
};
});
const images = $derived(imagesQuery.data?.value ?? data.images);
- const maxUploadSizeMB = $derived(images?.maxImageUploadSize ?? DEFAULT_MAX_UPLOAD_SIZE_MB);
+ const countFailures = $derived(
+ imageUsageCountsQuery.data?.envId === scope ? imageUsageCountsQuery.data.value.failedEnvironments : []
+ );
+
+ const resourcesReady = $derived(imagesQuery.data?.envId === scope);
- const resourcesReady = $derived(imagesQuery.data?.envId === envId);
+ // The shown list refetches itself; the affected environments' other cached lists are marked stale.
+ function invalidateEnvironmentImages(results: { environment: EnvironmentRef }[], requestedScope: string) {
+ return Promise.all(
+ listScopes(results.map(({ environment }) => environment.id))
+ .filter((listScope) => listScope !== requestedScope)
+ .flatMap((listScope) => [
+ queryClient.invalidateQueries({ queryKey: ['images', listScope] }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.images.usageCounts(listScope) })
+ ])
+ );
+ }
const pruneImagesMutation = createMutation(() => ({
- mutationKey: ['images', 'prune', envId],
- mutationFn: (requestedEnvId: string) =>
- imageService.pruneImages(
- {
- mode: imagePruneMode,
- ...(imagePruneMode === 'olderThan' ? { until: imagePruneUntil } : {})
- },
- requestedEnvId
+ mutationKey: ['images', 'prune', scope],
+ mutationFn: (_requestedScope: string) =>
+ settleAcrossEnvironments(actionEnvironments('images:prune'), (id) =>
+ imageService.pruneImages(
+ {
+ mode: imagePruneMode,
+ ...(imagePruneMode === 'olderThan' ? { until: imagePruneUntil } : {})
+ },
+ id
+ )
),
- onSuccess: async (data, requestedEnvId) => {
- toast.success(m.images_pruned_success(), activityToastOptions(extractActivityId(data)));
- if (requestedEnvId === envId) {
+ onSuccess: async (results, requestedScope) => {
+ toast.success(m.images_pruned_success(), activityToastOptions(extractActivityId(results[0]?.value)));
+ await invalidateEnvironmentImages(results, requestedScope);
+ if (requestedScope === scope) {
await Promise.all([imagesQuery.refetch(), imageUsageCountsQuery.refetch()]);
isConfirmPruneDialogOpen = false;
}
@@ -107,11 +145,13 @@
}));
const checkUpdatesMutation = createMutation(() => ({
- mutationKey: ['images', 'check-updates', envId],
- mutationFn: (requestedEnvId: string) => imageService.checkAllImages(requestedEnvId),
- onSuccess: async (data, requestedEnvId) => {
- toast.success(m.images_update_check_completed(), activityToastOptions(extractActivityId(data)));
- if (requestedEnvId === envId) {
+ mutationKey: ['images', 'check-updates', scope],
+ mutationFn: (_requestedScope: string) =>
+ settleAcrossEnvironments(actionEnvironments('image-updates:check'), (id) => imageService.checkAllImages(id)),
+ onSuccess: async (results, requestedScope) => {
+ toast.success(m.images_update_check_completed(), activityToastOptions(extractActivityId(results[0]?.value)));
+ await invalidateEnvironmentImages(results, requestedScope);
+ if (requestedScope === scope) {
await imagesQuery.refetch();
}
},
@@ -120,6 +160,22 @@
}
}));
+ let pickedUploadEnvironmentId = $state('');
+ const uploadEnvironmentId = $derived(destinationEnvironmentId(pickedUploadEnvironmentId, 'images:upload'));
+ // Merged lists carry one environment's upload limit, so the destination's own is read while uploading.
+ // If it cannot be read, the browser sets no limit and the destination enforces its own.
+ const mergedUpload = $derived(environmentStore.shown.length > 1);
+ const uploadLimitQuery = createQuery(() => ({
+ queryKey: queryKeys.images.uploadLimit(uploadEnvironmentId),
+ queryFn: async () =>
+ (await imageService.getImagesForEnvironment(uploadEnvironmentId, { pagination: { page: 1, limit: 1 } })).maxImageUploadSize,
+ enabled: isUploadDialogOpen && mergedUpload,
+ retry: false
+ }));
+ const maxUploadSizeMB = $derived(
+ mergedUpload ? uploadLimitQuery.data : (images?.maxImageUploadSize ?? DEFAULT_MAX_UPLOAD_SIZE_MB)
+ );
+
const uploadImagesMutation = createMutation(() => ({
mutationKey: ['images', 'upload', envId],
mutationFn: async ({ files, requestedEnvId }: { files: File[]; requestedEnvId: string }) => {
@@ -140,9 +196,10 @@
}
},
onSuccess: async (_data, { requestedEnvId }) => {
- if (requestedEnvId === envId) {
+ if (environmentStore.shown.some((env) => env.id === requestedEnvId)) {
await Promise.all([imagesQuery.refetch(), imageUsageCountsQuery.refetch()]);
uploadedFiles = [];
+ pickedUploadEnvironmentId = '';
isUploadDialogOpen = false;
}
}
@@ -155,11 +212,12 @@
isUploadDialogOpen = false;
isConfirmPruneDialogOpen = false;
uploadedFiles = [];
+ pickedUploadEnvironmentId = '';
isRefreshing = false;
});
const imageUsageCounts = $derived(
- imageUsageCountsQuery.data?.envId === envId ? imageUsageCountsQuery.data.value : imageUsageFallback
+ imageUsageCountsQuery.data?.envId === scope ? imageUsageCountsQuery.data.value : imageUsageFallback
);
// Intentionally a manual flag, not $derived(query.isFetching): these queries also
@@ -183,15 +241,15 @@
toast.error(m.images_upload_file_required());
return;
}
- await uploadImagesMutation.mutateAsync({ files: uploadedFiles, requestedEnvId: envId });
+ await uploadImagesMutation.mutateAsync({ files: uploadedFiles, requestedEnvId: uploadEnvironmentId });
}
async function handleTriggerBulkUpdateCheck() {
- await checkUpdatesMutation.mutateAsync(envId);
+ await checkUpdatesMutation.mutateAsync(scope);
}
async function handlePruneImages() {
- await pruneImagesMutation.mutateAsync(envId);
+ await pruneImagesMutation.mutateAsync(scope);
}
const imagePruneModes = [
@@ -200,37 +258,45 @@
{ value: 'olderThan', label: m.prune_mode_older_than() }
];
- async function loadImages(options: SearchPaginationSortRequest = requestOptions, requestedEnvId: string = envId) {
+ async function loadImages(options: SearchPaginationSortRequest = requestOptions, requestedScope: string = scope) {
+ const environments = environmentStore.shown;
requestOptions = options;
await Promise.all([
queryClient.query({
- queryKey: queryKeys.images.list(requestedEnvId, options),
- queryFn: () => imageService.getImagesForEnvironment(requestedEnvId, options),
+ queryKey: queryKeys.images.list(requestedScope, options),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ environments,
+ options,
+ (id, request, config) => imageService.getImagesForEnvironment(id, request, config),
+ imageSortValue
+ ),
staleTime: 0
}),
queryClient.query({
- queryKey: queryKeys.images.usageCounts(requestedEnvId),
- queryFn: () => imageService.getImageUsageCountsForEnvironment(requestedEnvId),
+ queryKey: queryKeys.images.usageCounts(requestedScope),
+ queryFn: () =>
+ sumAcrossEnvironments(environments, (id, config) => imageService.getImageUsageCountsForEnvironment(id, config)),
staleTime: 0
})
]);
}
async function refresh() {
- const requestedEnvId = envId;
+ const requestedScope = scope;
isRefreshing = true;
try {
- await loadImages(requestOptions, requestedEnvId);
+ await loadImages(requestOptions, requestedScope);
} finally {
- if (requestedEnvId === envId) {
+ if (requestedScope === scope) {
isRefreshing = false;
}
}
}
- const canPullImage = $derived(hasPermission('images:pull', envId));
- const canUploadImage = $derived(hasPermission('images:upload', envId));
- const canPruneImage = $derived(hasPermission('images:prune', envId));
+ const canPullImage = $derived(hasShownPermission('images:pull'));
+ const canUploadImage = $derived(hasShownPermission('images:upload'));
+ const canPruneImage = $derived(hasShownPermission('images:prune'));
const actionButtons: ActionButton[] = $derived.by(() => {
const buttons: ActionButton[] = [];
@@ -317,14 +383,17 @@
<ResourcePageLayout title={m.images()} subtitle={m.images_subtitle()} {actionButtons} {statCards}>
{#snippet mainContent()}
{#if resourcesReady}
- {#key envId}
+ {#key scope}
<ImageTable
- bind:images={() => images, (value) => queryClient.setQueryData(queryKeys.images.list(envId, requestOptions), value)}
+ bind:images={
+ () => withFailedEnvironments(images, countFailures),
+ (value) => queryClient.setQueryData(queryKeys.images.list(scope, requestOptions), value)
+ }
bind:selectedIds
bind:requestOptions
loading={imagesQuery.isLoading}
onRefreshData={async (options) => {
- await loadImages(options, envId);
+ await loadImages(options, scope);
}}
onImageUpdated={async () => {
await imagesQuery.refetch();
@@ -356,10 +425,14 @@
<Dialog.Description>{m.images_upload_description()}</Dialog.Description>
</Dialog.Header>
<div class="space-y-4 py-4">
+ <EnvironmentDestinationSelect
+ bind:value={() => uploadEnvironmentId, (value) => (pickedUploadEnvironmentId = value)}
+ permission="images:upload"
+ />
<FileDropZone
{onUpload}
{onFileRejected}
- maxFileSize={maxUploadSizeMB * MEGABYTE}
+ maxFileSize={maxUploadSizeMB === undefined ? undefined : maxUploadSizeMB * MEGABYTE}
accept=".tar,.tar.gz,.tgz,.tar.xz"
maxFiles={10}
fileCount={uploadedFiles.length}
@@ -407,6 +480,7 @@
onclick={() => {
isUploadDialogOpen = false;
uploadedFiles = [];
+ pickedUploadEnvironmentId = '';
}}
disabled={isUploading}
/>
@@ -425,7 +499,10 @@
<Dialog.Content>
<Dialog.Header>
<Dialog.Title>{m.images_prune_confirm_title()}</Dialog.Title>
- <Dialog.Description>{m.images_prune_confirm_description({ mode: imagePruneMode })}</Dialog.Description>
+ <Dialog.Description>
+ {m.images_prune_confirm_description({ mode: imagePruneMode })}
+ {acrossEnvironmentsNote(actionEnvironments('images:prune'))}
+ </Dialog.Description>
</Dialog.Header>
<SettingsSection class="py-4">
<SettingsRow
diff --git a/frontend/src/routes/(app)/images/+page.ts b/frontend/src/routes/(app)/images/+page.ts
index 0ca72d64e..97b3bb43d 100644
--- a/frontend/src/routes/(app)/images/+page.ts
+++ b/frontend/src/routes/(app)/images/+page.ts
@@ -2,33 +2,43 @@ import { queryKeys } from '#lib/query/query-keys.js';
import { imageService } from '#lib/services/image-service.js';
import { featureStore } from '#lib/stores/features.store.svelte.js';
import { throwPageLoadError } from '#lib/utils/api.js';
+import { fetchAcrossEnvironments, sumAcrossEnvironments } from '#lib/utils/environments.js';
import { resolveListPageLoadContext } from '#lib/utils/tables.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
+import { imageSortValue } from './components/image-table.svelte';
export const load: PageLoad = async ({ parent }) => {
const {
queryClient,
- envId,
+ environments,
+ scope,
requestOptions: imageRequestOptions
} = await resolveListPageLoadContext(parent, 'arcane-image-table', {
column: 'created',
direction: 'desc'
});
- await featureStore.load(envId);
+ await Promise.all(environments.map((env) => featureStore.load(env.id)));
let images;
let imageUsageCounts;
const operationResult = await tryCatch(
(async () =>
Promise.all([
queryClient.query({
- queryKey: queryKeys.images.list(envId, imageRequestOptions),
- queryFn: () => imageService.getImagesForEnvironment(envId, imageRequestOptions)
+ queryKey: queryKeys.images.list(scope, imageRequestOptions),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ environments,
+ imageRequestOptions,
+ (id, request, config) => imageService.getImagesForEnvironment(id, request, config),
+ imageSortValue
+ )
}),
queryClient.query({
- queryKey: queryKeys.images.usageCounts(envId),
- queryFn: () => imageService.getImageUsageCountsForEnvironment(envId)
+ queryKey: queryKeys.images.usageCounts(scope),
+ queryFn: () =>
+ sumAcrossEnvironments(environments, (id, config) => imageService.getImageUsageCountsForEnvironment(id, config))
})
]))()
);
@@ -40,5 +50,5 @@ export const load: PageLoad = async ({ parent }) => {
[images, imageUsageCounts] = operationResult.data;
}
- return { envId, images, imageRequestOptions, imageUsageCounts };
+ return { scope, images, imageRequestOptions, imageUsageCounts };
};
diff --git a/frontend/src/routes/(app)/images/[imageId]/+page.svelte b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
index eb57d0383..8c74fdc29 100644
--- a/frontend/src/routes/(app)/images/[imageId]/+page.svelte
+++ b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
@@ -42,6 +42,7 @@
isVulnerabilityScanInProgress
} from '#lib/utils/docker.js';
import { parseImageRef } from '#lib/utils/docker.js';
+ import { environmentHref } from '#lib/utils/environments.js';
import { bytes, formatDateTimeShort, nowInstantString } from '#lib/utils/formatting.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import { toastVulnerabilityScanStatus } from '#lib/utils/vulnerability.js';
@@ -53,7 +54,7 @@
let { data } = $props();
let { image } = $derived(data);
- const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const currentEnvId = $derived(data.envId);
const vulnerabilityManagementEnabled = $derived(featureStore.isEnabled('vulnerabilityManagement', currentEnvId));
const urlTab = useUrlTab({
@@ -158,7 +159,7 @@
// Prefer the stored scan report when one exists; fall back to
// patching all outdated OS packages.
const options = vulnerabilityScan?.hasReport ? { scanId: image.id } : undefined;
- const result = await tryCatch(imageService.patchImage(image.id, options));
+ const result = await tryCatch(imageService.patchImage(image.id, options, currentEnvId));
await handleApiResultWithCallbacks({
result,
message: m.images_patch_failed(),
@@ -315,6 +316,8 @@
const pinnedRepository = $derived.by(() => (pinnedRefs[0] ? parseImageRef(pinnedRefs[0]).repo : ''));
async function handleImageRemove(id: string) {
+ // The dialog outlives navigation, so it removes the image from the environment it was opened for.
+ const environmentId = currentEnvId;
openConfirmDialog({
title: m.common_remove_title({ resource: m.resource_image() }),
message: m.images_remove_message(),
@@ -332,7 +335,7 @@
const force = !!checkboxStates['force'];
isLoading.removing = true;
await handleApiResultWithCallbacks({
- result: await tryCatch(imageService.deleteImage(id, { force })),
+ result: await tryCatch(imageService.deleteImage(id, { force }, environmentId)),
message: m.failed_to_remove_image(),
setLoadingState: (value) => (isLoading.removing = value),
onSuccess: async (data) => {
@@ -348,7 +351,7 @@
async function handleExportImage(id: string) {
isLoading.exporting = true;
try {
- const url = await imageService.getImageExportUrl(id);
+ const url = await imageService.getImageExportUrl(id, currentEnvId);
window.open(url, '_blank', 'noopener,noreferrer');
} finally {
isLoading.exporting = false;
@@ -502,14 +505,15 @@
</Tabs.Content>
<Tabs.Content value="history">
- <ImageHistoryPanel imageId={image.id} />
+ <ImageHistoryPanel imageId={image.id} environmentId={currentEnvId} />
</Tabs.Content>
<Tabs.Content value="attestations">
- <ImageAttestationsPanel {image} />
+ <ImageAttestationsPanel {image} environmentId={currentEnvId} />
</Tabs.Content>
{#if vulnerabilityManagementEnabled}
<Tabs.Content value="vulnerabilities">
<VulnerabilityScanPanel
+ environmentId={currentEnvId}
scan={vulnerabilityScan}
reportError={scanReportError}
isScanning={isLoading.scanning}
@@ -537,8 +541,9 @@
<ImageTagDialog
bind:open={tagDialogOpen}
imageId={image.id}
+ environmentId={currentEnvId}
defaultRepository={image.repoTags?.[0]?.split(':')[0] ??
(pinnedRepository || (image.repo && image.repo !== '<none>' ? image.repo : ''))}
- onTagged={() => goto(`/images/${image.id}`, { refreshAll: true })}
+ onTagged={() => goto(environmentHref(`/images/${image.id}`, currentEnvId), { refreshAll: true })}
/>
{/if}
diff --git a/frontend/src/routes/(app)/images/[imageId]/+page.ts b/frontend/src/routes/(app)/images/[imageId]/+page.ts
index b783d79a8..a838d73bf 100644
--- a/frontend/src/routes/(app)/images/[imageId]/+page.ts
+++ b/frontend/src/routes/(app)/images/[imageId]/+page.ts
@@ -2,22 +2,23 @@ import { error } from '@sveltejs/kit';
import { queryKeys } from '#lib/query/query-keys.js';
import { imageService } from '#lib/services/image-service.js';
-import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { featureStore } from '#lib/stores/features.store.svelte.js';
import type { ImageDetailSummaryDto } from '#lib/types/docker.js';
import { parseImageRef } from '#lib/utils/docker.js';
+import { resolveDetailEnvironmentId } from '#lib/utils/environments.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
type ImageDetailData = {
+ envId: string;
image: ImageDetailSummaryDto;
error?: string;
};
-export const load: PageLoad = async ({ params, parent }): Promise<ImageDetailData> => {
+export const load: PageLoad = async ({ params, parent, url }): Promise<ImageDetailData> => {
const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const envId = await resolveDetailEnvironmentId(url);
await featureStore.load(envId);
const { imageId } = params;
@@ -41,6 +42,7 @@ export const load: PageLoad = async ({ params, parent }): Promise<ImageDetailDat
}
return {
+ envId,
image: {
...image,
repo,
diff --git a/frontend/src/routes/(app)/images/[imageId]/components/image-attestations-panel.svelte b/frontend/src/routes/(app)/images/[imageId]/components/image-attestations-panel.svelte
index 66e49f8bc..6bf47d161 100644
--- a/frontend/src/routes/(app)/images/[imageId]/components/image-attestations-panel.svelte
+++ b/frontend/src/routes/(app)/images/[imageId]/components/image-attestations-panel.svelte
@@ -6,15 +6,14 @@
import { ArrowRightIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import { imageService } from '#lib/services/image-service.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { ImageAttestationDto, ImageAttestationListDto, ImageDetailSummaryDto } from '#lib/types/docker.js';
import { bytes } from '#lib/utils/formatting.js';
const ALL_FILTER = '__all__';
- let { image }: { image: ImageDetailSummaryDto } = $props();
+ let { image, environmentId }: { image: ImageDetailSummaryDto; environmentId: string } = $props();
- const envId = $derived(environmentStore.selected?.id || '0');
+ const envId = $derived(environmentId);
let selectedPlatform = $state(ALL_FILTER);
let selectedPredicateType = $state(ALL_FILTER);
let detailsOpen = $state(false);
diff --git a/frontend/src/routes/(app)/images/[imageId]/components/image-history-panel.svelte b/frontend/src/routes/(app)/images/[imageId]/components/image-history-panel.svelte
index ffc0ebf5f..ae7c97f32 100644
--- a/frontend/src/routes/(app)/images/[imageId]/components/image-history-panel.svelte
+++ b/frontend/src/routes/(app)/images/[imageId]/components/image-history-panel.svelte
@@ -13,17 +13,17 @@
import { hasPermission } from '#lib/utils/auth.js';
import { bytes, formatDateTimeShort } from '#lib/utils/formatting.js';
- let { imageId }: { imageId: string } = $props();
+ let { imageId, environmentId: imageEnvironmentId }: { imageId: string; environmentId: string } = $props();
const historyQuery = createQuery(() => {
- const environmentId = environmentStore.selected?.id;
+ const environmentId = imageEnvironmentId;
const requestedImageId = imageId;
userStore.current;
return {
queryKey: queryKeys.images.history(environmentId ?? '', requestedImageId),
queryFn: async () => {
await environmentStore.ready;
- return imageService.getImageHistory(requestedImageId);
+ return imageService.getImageHistory(requestedImageId, environmentId);
},
enabled: !!environmentId && !!requestedImageId && hasPermission('images:read', environmentId)
};
diff --git a/frontend/src/routes/(app)/images/builds/+page.svelte b/frontend/src/routes/(app)/images/builds/+page.svelte
index 213a6d61b..0cd6a1c63 100644
--- a/frontend/src/routes/(app)/images/builds/+page.svelte
+++ b/frontend/src/routes/(app)/images/builds/+page.svelte
@@ -15,12 +15,16 @@
import { queryKeys } from '#lib/query/query-keys.js';
import { isSessionCancelledError, withSessionSignal } from '#lib/services/api-service.js';
import { containerRegistryService } from '#lib/services/container-registry-service.js';
+ import { settingsService } from '#lib/services/settings-service.js';
import settingsStore from '#lib/stores/config-store.svelte.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { ImageBuildRecord } from '#lib/types/docker.js';
+ import type { Settings } from '#lib/types/settings.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
+ import { extractApiErrorMessage } from '#lib/utils/api.js';
import { isDepotBuildAvailable } from '#lib/utils/build-provider.js';
import { extractErrorMessage } from '#lib/utils/docker.js';
+ import { destinationEnvironmentId } from '#lib/utils/environments.js';
import { parseList } from '#lib/utils/form-parsers.js';
import { sanitizeLogText } from '#lib/utils/formatting.js';
import { buildImageReference, getRegistryDisplayName } from '#lib/utils/registry.js';
@@ -41,7 +45,17 @@
isGitBuildContextSource
} from './image-build-history';
- const buildsRoot = $derived(((settingsStore.current?.buildsDirectory ?? '/builds') as string).trim() || '/builds');
+ // The builds directory and providers come from the destination, which may differ from the selected environment.
+ const buildSettingsOptions = (environmentId: string) => ({
+ queryKey: queryKeys.settings.byEnvironment(environmentId),
+ queryFn: () => settingsService.getReadableSettings(environmentId)
+ });
+ const buildsRootOf = (settings: Settings | undefined) => (settings?.buildsDirectory ?? '/builds').trim() || '/builds';
+ let pickedEnvironmentId = $state('');
+ const buildEnvironmentId = $derived(destinationEnvironmentId(pickedEnvironmentId, 'images:build'));
+ const queryClient = useQueryClient();
+ const buildSettingsQuery = createQuery(() => buildSettingsOptions(buildEnvironmentId));
+ const buildsRoot = $derived(buildsRootOf(buildSettingsQuery.data));
const buildsRootLabel = $derived.by(() => {
const raw = buildsRoot.trim();
if (!raw) return '/builds';
@@ -52,7 +66,7 @@
return `…/${tail}`;
});
- const depotAvailable = $derived(isDepotBuildAvailable(settingsStore.current));
+ const depotAvailable = $derived(isDepotBuildAvailable(buildSettingsQuery.data));
const providerOptions = $derived.by<BuildProviderOption[]>(() => {
const options: BuildProviderOption[] = [
@@ -72,7 +86,9 @@
return options;
});
- let selectedContextPath = $state('/');
+ // A picked directory belongs to its destination; another destination starts at its builds root.
+ let selectedContext = $state({ environmentId: '', path: '/' });
+ const selectedContextPath = $derived(selectedContext.environmentId === buildEnvironmentId ? selectedContext.path : '/');
let contextMode = $state<'workspace' | 'remote'>('workspace');
let remoteContextSource = $state('');
@@ -160,7 +176,6 @@
let showAdvanced = $state(false);
const selectedEnvId = $derived(environmentStore.selected?.id || '0');
- const queryClient = useQueryClient();
const resolvedProvider = $derived(depotAvailable ? inputs.provider.value : 'local');
const isPushMode = $derived(resolvedProvider === 'depot' ? true : inputs.push.value);
@@ -329,9 +344,11 @@
appendLog(m.build_completed());
},
onSettled: async (_data, _error, variables) => {
- await queryClient.invalidateQueries({
- queryKey: queryKeys.images.builds(variables.envId)
- });
+ await Promise.all(
+ [variables.envId, environmentStore.shownKey].map((key) =>
+ queryClient.invalidateQueries({ queryKey: queryKeys.images.builds(key) })
+ )
+ );
}
}));
@@ -468,7 +485,19 @@
return provider === 'local' ? m.build_provider_unsupported_local({ fields }) : m.build_provider_unsupported_depot({ fields });
}
- function applyBuildConfig(build: ImageBuildRecord) {
+ let latestApply = 0;
+ async function applyBuildConfig(build: ImageBuildRecord, environmentId: string) {
+ // Load the destination's builds root first, so the whole choice is applied at once and a newer one wins.
+ const apply = ++latestApply;
+ const remote = isGitBuildContextSource(build.contextDir);
+ const settings = remote ? undefined : await tryCatch(queryClient.ensureQueryData(buildSettingsOptions(environmentId)));
+ if (apply !== latestApply) return;
+ // Without the destination's builds root the saved directory cannot be resolved, so nothing is applied.
+ if (settings?.error) {
+ toast.error(m.common_load_failed({ resource: m.settings() }), { description: extractApiErrorMessage(settings.error) });
+ return;
+ }
+ pickedEnvironmentId = environmentId;
for (const key of ['dockerfile', 'target', 'network', 'isolation'] as const) form.setValue(key, build[key] ?? '');
for (const key of ['privileged', 'noCache', 'pull', 'push'] as const) form.setValue(key, build[key] ?? false);
form.setValue('tags', build.tags?.join(', ') ?? '');
@@ -494,13 +523,16 @@
[build.buildArgs, build.labels, build.ulimits].some((values) => Object.keys(values ?? {}).length > 0) ||
(build.shmSize ?? 0) > 0;
- if (isGitBuildContextSource(build.contextDir)) {
+ if (remote) {
contextMode = 'remote';
remoteContextSource = build.contextDir;
} else {
contextMode = 'workspace';
remoteContextSource = '';
- selectedContextPath = getContextPathFromBuild(build, buildsRoot);
+ selectedContext = {
+ environmentId: buildEnvironmentId,
+ path: getContextPathFromBuild(build, buildsRootOf(settings?.data ?? undefined))
+ };
}
mainUrlTab.select('build');
rightPanelTab = 'config';
@@ -510,6 +542,17 @@
async function handleSubmit() {
const data = form.validate();
if (!data) return;
+ // Without the destination's settings, the context path and providers would be guesses.
+ if (!buildSettingsQuery.data && buildSettingsQuery.error) {
+ toast.error(m.common_load_failed({ resource: m.settings() }), {
+ description: extractApiErrorMessage(buildSettingsQuery.error)
+ });
+ return;
+ }
+ if (!buildSettingsQuery.data) {
+ toast.info(m.common_loading());
+ return;
+ }
if (!contextDir || contextDir.trim() === '') {
toast.error(contextMode === 'remote' ? m.build_remote_context_required() : m.build_context_required());
@@ -590,9 +633,8 @@
try {
const operationResult = await tryCatch(
(async () => {
- const resolvedEnvId = await environmentStore.getCurrentEnvironmentId();
await buildMutation.mutateAsync({
- envId: resolvedEnvId,
+ envId: buildEnvironmentId,
...payload
});
toast.success(m.build_completed());
@@ -633,13 +675,15 @@
remoteContext={remoteContextSource}
onModeChange={(mode) => (contextMode = mode)}
onRemoteContextChange={(value: string) => (remoteContextSource = value)}
- onSelectContext={(path: string) => (selectedContextPath = path)}
+ onSelectContext={(path: string) => (selectedContext = { environmentId: buildEnvironmentId, path })}
+ environmentId={buildEnvironmentId}
/>
</Card.Root>
{/snippet}
{#snippet configPanel()}
<BuildConfigPanel
+ bind:environmentId={() => buildEnvironmentId, (value) => (pickedEnvironmentId = value)}
bind:inputs
provider={resolvedProvider}
bind:showAdvanced
@@ -653,7 +697,7 @@
{/snippet}
{#snippet historyContent()}
- <ImageBuildHistoryPanel environmentId={selectedEnvId} onApplyBuild={applyBuildConfig} />
+ <ImageBuildHistoryPanel onApplyBuild={applyBuildConfig} />
{/snippet}
<!-- Right panel with tabs (config + output) -->
{#snippet rightPanel()}
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 2d5a4951c..213ef108d 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
@@ -1,4 +1,5 @@
<script lang="ts">
+ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';
import FormInput from '#lib/components/form/form-input.svelte';
import SelectWithLabel from '#lib/components/form/select-with-label.svelte';
import * as Collapsible from '#lib/components/ui/collapsible/index.js';
@@ -9,6 +10,7 @@
import type { BuildFormInputs, SelectOption } from './build-form.types';
let {
+ environmentId = $bindable(),
inputs = $bindable(),
provider,
showAdvanced = $bindable(false),
@@ -19,6 +21,7 @@
registryLoadFailed = false,
onSubmit
}: {
+ environmentId: string;
inputs: BuildFormInputs;
provider: 'local' | 'depot';
showAdvanced?: boolean;
@@ -36,6 +39,7 @@
<div class="space-y-7 p-8">
<form onsubmit={preventDefault(() => onSubmit?.())} class="space-y-7">
+ <EnvironmentDestinationSelect bind:value={environmentId} permission="images:build" />
<div class="space-y-4">
{#if isPushMode}
<SelectWithLabel
diff --git a/frontend/src/routes/(app)/images/builds/components/build-workspace-browser.svelte b/frontend/src/routes/(app)/images/builds/components/build-workspace-browser.svelte
index 5eb52b8fb..a1e3b337e 100644
--- a/frontend/src/routes/(app)/images/builds/components/build-workspace-browser.svelte
+++ b/frontend/src/routes/(app)/images/builds/components/build-workspace-browser.svelte
@@ -19,7 +19,6 @@
import { m } from '#lib/paraglide/messages.js';
import { queryKeys } from '#lib/query/query-keys.js';
import type { UploadProgressCallback } from '#lib/services/upload-service.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { FileEntry } from '#lib/types/shared.js';
import { extractApiErrorMessage } from '#lib/utils/api.js';
import { hasPermission } from '#lib/utils/auth.js';
@@ -30,17 +29,18 @@
rootLabel = '/builds',
rootPath,
persistKey = 'arcane-build-workspace-table',
- onSelectContext
+ onSelectContext,
+ environmentId: envId
}: {
provider: FileProvider;
rootLabel?: string;
rootPath?: string;
persistKey?: string;
onSelectContext?: (path: string) => void;
+ environmentId: string;
} = $props();
let currentPath = $state('/');
- const envId = $derived(environmentStore.selected?.id || '0');
const canBuildImage = $derived(hasPermission('images:build', envId));
const queryClient = useQueryClient();
diff --git a/frontend/src/routes/(app)/images/builds/components/build-workspace-panel.svelte b/frontend/src/routes/(app)/images/builds/components/build-workspace-panel.svelte
index 779fac759..53f92a02e 100644
--- a/frontend/src/routes/(app)/images/builds/components/build-workspace-panel.svelte
+++ b/frontend/src/routes/(app)/images/builds/components/build-workspace-panel.svelte
@@ -17,7 +17,8 @@
remoteContext,
onModeChange,
onRemoteContextChange,
- onSelectContext
+ onSelectContext,
+ environmentId
}: {
rootLabel: string;
rootPath: string;
@@ -27,15 +28,16 @@
onModeChange?: (mode: 'workspace' | 'remote') => void;
onRemoteContextChange?: (value: string) => void;
onSelectContext?: (path: string) => void;
+ environmentId: string;
} = $props();
const provider: FileProvider = {
- list: (path: string) => buildWorkspaceService.listDirectory(path),
- mkdir: (path: string) => buildWorkspaceService.createDirectory(path),
- upload: (path: string, file: File, onProgress) => buildWorkspaceService.uploadFile(path, file, onProgress),
- delete: (path: string) => buildWorkspaceService.deleteFile(path),
- download: (path: string) => buildWorkspaceService.downloadFile(path),
- getContent: (path: string) => buildWorkspaceService.getFileContent(path)
+ list: (path: string) => buildWorkspaceService.listDirectory(path, environmentId),
+ mkdir: (path: string) => buildWorkspaceService.createDirectory(path, environmentId),
+ upload: (path: string, file: File, onProgress) => buildWorkspaceService.uploadFile(path, file, onProgress, environmentId),
+ delete: (path: string) => buildWorkspaceService.deleteFile(path, environmentId),
+ download: (path: string) => buildWorkspaceService.downloadFile(path, environmentId),
+ getContent: (path: string) => buildWorkspaceService.getFileContent(path, environmentId)
};
</script>
@@ -98,7 +100,16 @@
<div class="flex min-h-0 flex-1 flex-col overflow-hidden">
<div class="flex min-h-0 flex-1 flex-col p-4">
{#if contextMode === 'workspace'}
- <BuildWorkspaceBrowser {provider} {rootLabel} {rootPath} onSelectContext={(path: string) => onSelectContext?.(path)} />
+ <!-- A new destination gets a fresh browser, so nothing pending, such as a delete confirmation, carries over. -->
+ {#key environmentId}
+ <BuildWorkspaceBrowser
+ {provider}
+ {rootLabel}
+ {rootPath}
+ {environmentId}
+ onSelectContext={(path: string) => onSelectContext?.(path)}
+ />
+ {/key}
{:else}
<div class="flex h-full flex-col rounded-2xl border border-border/20 bg-card p-5">
<div class="max-w-xl space-y-2">
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 132a669df..2ef6be46d 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
@@ -5,6 +5,7 @@
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';
import type { ColumnSpec, MobileFieldVisibility } from '#lib/components/arcane-table/index.js';
import { UniversalMobileCard } from '#lib/components/arcane-table/index.js';
import IfPermitted from '#lib/components/if-permitted.svelte';
@@ -28,8 +29,10 @@
import { m } from '#lib/paraglide/messages.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { imageService } from '#lib/services/image-service.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { ImageBuildRecord, ImageBuildStatus } from '#lib/types/docker.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
+ import { fetchAcrossEnvironments, type EnvironmentRow } from '#lib/utils/environments.js';
import {
buildHistoryStatusLabel,
@@ -41,15 +44,16 @@
parseBuildOutput
} from '../image-build-history';
+ type BuildRow = EnvironmentRow<ImageBuildRecord>;
+
interface Props {
- environmentId: string;
- onApplyBuild: (build: ImageBuildRecord) => void;
+ onApplyBuild: (build: ImageBuildRecord, environmentId: string) => void;
}
- let { environmentId, onApplyBuild }: Props = $props();
+ let { onApplyBuild }: Props = $props();
const queryClient = useQueryClient();
- const EMPTY_BUILD_HISTORY: Paginated<ImageBuildRecord> = {
+ const EMPTY_BUILD_HISTORY: Paginated<BuildRow> = {
data: [],
pagination: { totalPages: 1, totalItems: 0, currentPage: 1, itemsPerPage: 20 }
};
@@ -60,27 +64,29 @@
});
let selectedIds = $state<string[]>([]);
let mobileFieldVisibility = $state<Record<string, boolean>>({});
- let selectedOptimistic = $state<ImageBuildRecord | null>(null);
+ let selectedOptimistic = $state<BuildRow | null>(null);
let selectedId = $state<string | null>(null);
let detailsOpen = $state(false);
const historyQuery = createQuery(() => {
- const requestedEnvironmentId = environmentId;
+ const scope = environmentStore.shownKey;
+ const environments = environmentStore.shown;
const options = requestOptions;
return {
- queryKey: queryKeys.images.buildsList(requestedEnvironmentId, options),
- queryFn: () => imageService.getImageBuilds(options)
+ queryKey: queryKeys.images.buildsList(scope, options),
+ queryFn: () =>
+ fetchAcrossEnvironments(environments, options, (id, request, config) => imageService.getImageBuilds(request, id, config))
};
});
- const historyItems = $derived<Paginated<ImageBuildRecord>>(historyQuery.data ?? EMPTY_BUILD_HISTORY);
+ const historyItems = $derived<Paginated<BuildRow>>(historyQuery.data ?? EMPTY_BUILD_HISTORY);
const detailQuery = createQuery(() => {
- const requestedEnvironmentId = environmentId;
+ const requestedEnvironmentId = selectedOptimistic?.environmentId ?? 'none';
const buildId = selectedId;
return {
queryKey: queryKeys.images.buildRecord(requestedEnvironmentId, buildId ?? 'none'),
- queryFn: () => imageService.getImageBuild(buildId!),
+ queryFn: () => imageService.getImageBuild(buildId!, requestedEnvironmentId),
enabled: !!buildId && detailsOpen
};
});
@@ -110,11 +116,18 @@
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 })) {
+ if (
+ event.query ===
+ cache.find({ queryKey: queryKeys.images.buildsList(environmentStore.shownKey, requestOptions), exact: true })
+ ) {
reportError(event.query.state.error, false);
} else if (
selectedId &&
- event.query === cache.find({ queryKey: queryKeys.images.buildRecord(environmentId, selectedId), exact: true })
+ event.query ===
+ cache.find({
+ queryKey: queryKeys.images.buildRecord(selectedOptimistic?.environmentId ?? 'none', selectedId),
+ exact: true
+ })
) {
reportError(event.query.state.error, true);
}
@@ -123,7 +136,8 @@
const detailItems = $derived(selectedBuild ? getBuildDetailItems(selectedBuild) : []);
- const columns = [
+ const columns = $derived([
+ ...environmentColumns<BuildRow>(),
{
accessorKey: 'status',
title: m.common_status(),
@@ -152,7 +166,7 @@
title: m.duration(),
cell: BuildHistoryDurationCell
}
- ] satisfies ColumnSpec<ImageBuildRecord>[];
+ ] satisfies ColumnSpec<BuildRow>[]);
const mobileFields = [
{ id: 'status', label: m.common_status(), defaultVisible: true },
@@ -169,15 +183,15 @@
return result.data ?? historyQuery.data ?? EMPTY_BUILD_HISTORY;
}
- function openDetails(build: ImageBuildRecord) {
+ function openDetails(build: BuildRow) {
selectedId = build.id;
selectedOptimistic = build;
detailsOpen = true;
}
function applySelectedBuild() {
- if (!selectedBuild) return;
- onApplyBuild(selectedBuild);
+ if (!selectedBuild || !selectedOptimistic) return;
+ onApplyBuild(selectedBuild, selectedOptimistic.environmentId);
detailsOpen = false;
}
</script>
@@ -207,7 +221,7 @@
<span class="text-sm">{formatBuildDuration(Number(value ?? 0))}</span>
{/snippet}
-{#snippet BuildHistoryRowActions({ item }: { item: ImageBuildRecord })}
+{#snippet BuildHistoryRowActions({ item }: { item: BuildRow })}
<DropdownMenu.Root>
<DropdownMenu.Trigger data-row-select-ignore>
<ArcaneButton action="inspect" tone="ghost" size="icon" showLabel={false} icon={EllipsisIcon} />
@@ -225,7 +239,7 @@
item,
mobileFieldVisibility: fieldVisibility
}: {
- item: ImageBuildRecord;
+ item: BuildRow;
mobileFieldVisibility: MobileFieldVisibility;
})}
<UniversalMobileCard
@@ -273,7 +287,7 @@
show: fieldVisibility['durationMs'] ?? false
}
]}
- onclick={(item: ImageBuildRecord) => openDetails(item)}
+ onclick={(item: BuildRow) => openDetails(item)}
/>
{/snippet}
@@ -323,7 +337,7 @@
{/if}
<span class="text-muted-foreground">{formatBuildTimestamp(selectedBuild.createdAt)}</span>
</div>
- <IfPermitted perm="images:build">
+ <IfPermitted perm="images:build" envId={selectedOptimistic?.environmentId}>
<ArcaneButton
action="base"
tone="outline"
diff --git a/frontend/src/routes/(app)/images/components/image-table.svelte b/frontend/src/routes/(app)/images/components/image-table.svelte
index c329a1add..f5f75d696 100644
--- a/frontend/src/routes/(app)/images/components/image-table.svelte
+++ b/frontend/src/routes/(app)/images/components/image-table.svelte
@@ -1,3 +1,15 @@
+<script module lang="ts">
+ import type { ImageSummaryDto } from '#lib/types/docker.js';
+
+ /** Sort value for an image column; vulnerabilities sort by total, critical, then high, unscanned first, as the backend does. */
+ export function imageSortValue(image: ImageSummaryDto, column: string): unknown {
+ if (column !== 'vulnerabilities') return image[column as keyof ImageSummaryDto];
+ const scan = image.vulnerabilityScan;
+ if (scan?.status !== 'completed' || !scan.summary) return [-1];
+ return [scan.summary.total, scan.summary.critical, scan.summary.high];
+ }
+</script>
+
<script lang="ts">
import { goto } from '$app/navigation';
import { useQueryClient } from '@tanstack/svelte-query';
@@ -9,6 +21,7 @@
import UniversalMobileCard from '#lib/components/arcane-table/cards/universal-mobile-card.svelte';
import InUseStatus from '#lib/components/arcane-table/cells/in-use-status.svelte';
import UnixCreatedCell from '#lib/components/arcane-table/cells/unix-created-cell.svelte';
+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';
import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '#lib/components/arcane-table/index.js';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
@@ -33,25 +46,36 @@
} from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import { queryKeys } from '#lib/query/query-keys.js';
- import { imageService } from '#lib/services/image-service.js';
+ import { imageService, type ImagesPaginatedResponse } from '#lib/services/image-service.js';
import { vulnerabilityService } from '#lib/services/vulnerability-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { featureStore } from '#lib/stores/features.store.svelte.js';
import userStore from '#lib/stores/user-store.svelte.js';
- import type { ImageSummaryDto, ImageUpdateInfoDto } from '#lib/types/docker.js';
+ import type { ImageUpdateInfoDto } from '#lib/types/docker.js';
import type { VulnerabilityScanSummary } from '#lib/types/environment.js';
- import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
+ import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { handleApiResultWithCallbacks, extractApiErrorMessage } from '#lib/utils/api.js';
import { hasPermission } from '#lib/utils/auth.js';
import { bulkConfirmAndRun } from '#lib/utils/bulk-actions.js';
import { isLikelyStaleFailedSummary, isVulnerabilityScanInProgress } from '#lib/utils/docker.js';
+ import {
+ collectAcrossEnvironments,
+ environmentHref,
+ fetchAcrossEnvironments,
+ hasShownPermission,
+ rowKey,
+ type EnvironmentPage,
+ type EnvironmentRow
+ } from '#lib/utils/environments.js';
import { bytes, formatDateTimeShort, nowInstantString } from '#lib/utils/formatting.js';
import { inUseBadge } from '#lib/utils/mobile-card-badges.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import ImageTagDialog from './image-tag-dialog.svelte';
+ type ImageRow = EnvironmentRow<ImageSummaryDto>;
+
let {
images = $bindable(),
selectedIds = $bindable(),
@@ -60,7 +84,7 @@
onRefreshData,
loading = false
}: {
- images: Paginated<ImageSummaryDto>;
+ images: EnvironmentPage<ImagesPaginatedResponse>;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
onImageUpdated?: () => Promise<void>;
@@ -74,8 +98,9 @@
checking: false
});
- const currentEnvId = $derived(environmentStore.selected?.id || '0');
- const vulnerabilityManagementEnabled = $derived(featureStore.isEnabled('vulnerabilityManagement', currentEnvId));
+ const vulnerabilityManagementEnabled = $derived(
+ environmentStore.shown.some((env) => featureStore.isEnabled('vulnerabilityManagement', env.id))
+ );
$effect(() => {
if (!vulnerabilityManagementEnabled) stopBatchScanPolling();
});
@@ -83,30 +108,30 @@
// this the deriveds would cache pre-hydration falses forever.
const canDeleteImage = $derived.by(() => {
userStore.current;
- return hasPermission('images:delete', currentEnvId);
+ return hasShownPermission('images:delete');
});
const canPullImage = $derived.by(() => {
userStore.current;
- return hasPermission('images:pull', currentEnvId);
+ return hasShownPermission('images:pull');
});
const canScanImage = $derived.by(() => {
userStore.current;
- return vulnerabilityManagementEnabled && hasPermission('vulnerabilities:scan', currentEnvId);
+ return vulnerabilityManagementEnabled && hasShownPermission('vulnerabilities:scan');
});
const canTagImage = $derived.by(() => {
userStore.current;
- return hasPermission('images:tag', currentEnvId);
+ return hasShownPermission('images:tag');
});
const canPatchImage = $derived.by(() => {
userStore.current;
- return hasPermission('images:patch', currentEnvId);
+ return hasShownPermission('images:patch');
});
const canReadImage = $derived.by(() => {
userStore.current;
- return hasPermission('images:read', currentEnvId);
+ return hasShownPermission('images:read');
});
- let tagDialogImage = $state<ImageSummaryDto | null>(null);
+ let tagDialogImage = $state<ImageRow | null>(null);
let scanRequestedAtByImage = $state<Record<string, string>>({});
let scanPollTimeout: ReturnType<typeof setTimeout> | null = null;
let scanPollInFlight = false;
@@ -119,7 +144,12 @@
await onRefreshData(options);
return;
}
- images = await imageService.getImages(options);
+ images = await fetchAcrossEnvironments(
+ environmentStore.shown,
+ options,
+ (id, request, config) => imageService.getImagesForEnvironment(id, request, config),
+ imageSortValue
+ );
}
function handleDeleteSelected(ids: string[]) {
@@ -130,7 +160,8 @@
confirmLabel: m.common_remove(),
destructive: true,
checkboxes: [{ id: 'force', label: m.images_remove_force_label(), initialState: false }],
- run: (id, checkboxStates) => imageService.deleteImage(id, { force: !!checkboxStates['force'] }),
+ run: (id, environmentId, checkboxStates) =>
+ imageService.deleteImage(id, { force: !!checkboxStates['force'] }, environmentId),
messages: {
success: (count) => (count === 1 ? m.image_removed_successfully() : m.images_remove_success_many({ count })),
partial: (success, total, failed) => m.common_bulk_remove_partial({ success, total, failed, resource: m.images() }),
@@ -145,7 +176,7 @@
});
}
- async function deleteImage(id: string) {
+ async function deleteImage(id: string, environmentId: string) {
openConfirmDialog({
title: m.common_remove_title({ resource: m.resource_image() }),
message: m.images_remove_message(),
@@ -163,7 +194,7 @@
const force = !!checkboxStates['force'];
isLoading.removing = true;
- const result = await tryCatch(imageService.deleteImage(id, { force }));
+ const result = await tryCatch(imageService.deleteImage(id, { force }, environmentId));
await handleApiResultWithCallbacks({
result,
message: m.failed_to_remove_image(),
@@ -179,13 +210,13 @@
}
});
}
- async function handleInlineImagePull(repoTag: string) {
+ async function handleInlineImagePull(repoTag: string, environmentId: string) {
if (!repoTag || repoTag === '<none>:<none>') {
toast.error(m.images_pull_no_tag());
return;
}
- const result = await tryCatch(imageService.pullImage(repoTag));
+ const result = await tryCatch(imageService.pullImage(repoTag, undefined, undefined, environmentId));
await handleApiResultWithCallbacks({
result,
message: m.images_pull_failed(),
@@ -197,17 +228,17 @@
});
}
- async function handleInlineVulnerabilityScan(imageId: string) {
+ async function handleInlineVulnerabilityScan(image: ImageRow) {
if (!canScanImage) return;
- const requestedEnvId = currentEnvId;
- const result = await tryCatch(vulnerabilityService.scanImage(imageId, currentEnvId));
- if (destroyed || !vulnerabilityManagementEnabled || requestedEnvId !== currentEnvId) return;
+ const requestedScope = environmentStore.shownKey;
+ const result = await tryCatch(vulnerabilityService.scanImage(image.id, image.environmentId));
+ if (destroyed || !vulnerabilityManagementEnabled || requestedScope !== environmentStore.shownKey) return;
await handleApiResultWithCallbacks({
result,
message: m.vuln_scan_failed(),
setLoadingState: () => {},
onSuccess: async (data) => {
- scanRequestedAtByImage[imageId] = data.scanTime || nowInstantString();
+ scanRequestedAtByImage[rowKey(image)] = data.scanTime || nowInstantString();
const summary: VulnerabilityScanSummary = {
imageId: data.imageId,
scanTime: data.scanTime,
@@ -217,7 +248,7 @@
summary: data.summary,
error: data.error
};
- await handleVulnerabilityScanChanged(imageId, summary);
+ await handleVulnerabilityScanChanged(rowKey(image), summary);
if (data.status === 'completed') {
toast.success(m.vuln_scan_completed(), activityToastOptions(data.activityId));
@@ -234,13 +265,13 @@
});
}
- async function handleExportImage(imageId: string) {
- const url = await imageService.getImageExportUrl(imageId);
+ async function handleExportImage(imageId: string, environmentId: string) {
+ const url = await imageService.getImageExportUrl(imageId, environmentId);
window.open(url, '_blank', 'noopener,noreferrer');
}
- async function handleInlineImagePatch(imageId: string) {
- const result = await tryCatch(imageService.patchImage(imageId));
+ async function handleInlineImagePatch(imageId: string, environmentId: string) {
+ const result = await tryCatch(imageService.patchImage(imageId, undefined, environmentId));
await handleApiResultWithCallbacks({
result,
message: m.images_patch_failed(),
@@ -251,30 +282,30 @@
});
}
- async function handleUpdateInfoChanged(imageId: string, newUpdateInfo: ImageUpdateInfoDto) {
+ async function handleUpdateInfoChanged(key: string, newUpdateInfo: ImageUpdateInfoDto) {
if (destroyed) return;
images = {
...images,
data: images.data.map((image) => {
- if (image.id === imageId) return { ...image, updateInfo: newUpdateInfo };
+ if (rowKey(image) === key) return { ...image, updateInfo: newUpdateInfo };
return image;
})
};
await onImageUpdated?.();
}
- async function handleVulnerabilityScanChanged(imageId: string, newScanSummary: VulnerabilityScanSummary) {
+ async function handleVulnerabilityScanChanged(key: string, newScanSummary: VulnerabilityScanSummary) {
if (destroyed) return;
images = {
...images,
data: images.data.map((image) => {
- if (image.id === imageId) return { ...image, vulnerabilityScan: newScanSummary };
+ if (rowKey(image) === key) return { ...image, vulnerabilityScan: newScanSummary };
return image;
})
};
if (newScanSummary.status === 'completed' || newScanSummary.status === 'failed') {
- if (scanRequestedAtByImage[imageId]) {
- delete scanRequestedAtByImage[imageId];
+ if (scanRequestedAtByImage[key]) {
+ delete scanRequestedAtByImage[key];
scanRequestedAtByImage = { ...scanRequestedAtByImage };
}
}
@@ -292,19 +323,17 @@
}
}
- function getScanningImageIds(): string[] {
+ function getScanningImages(): ImageRow[] {
if (!vulnerabilityManagementEnabled) return [];
- return (images.data ?? [])
- .filter((item) => isVulnerabilityScanInProgress(item.vulnerabilityScan?.status))
- .map((item) => item.id);
+ return (images.data ?? []).filter((item) => isVulnerabilityScanInProgress(item.vulnerabilityScan?.status));
}
let scanPollError = $state<string | null>(null);
async function pollBatchScanSummaries() {
- const requestedEnvId = currentEnvId;
- const imageIds = getScanningImageIds();
- if (imageIds.length === 0) {
+ const requestedScope = environmentStore.shownKey;
+ const scanning = getScanningImages();
+ if (scanning.length === 0) {
stopBatchScanPolling();
return;
}
@@ -318,21 +347,30 @@
try {
const operationResult = await tryCatch(
(async () => {
- const response = await vulnerabilityService.getScanSummaries(imageIds, requestedEnvId);
- if (destroyed || !vulnerabilityManagementEnabled || requestedEnvId !== currentEnvId) return;
- const summaries = response?.summaries ?? {};
+ const environments = environmentStore.shown.filter((env) => scanning.some((image) => image.environmentId === env.id));
+ // A failing environment is reported; the others' summaries still apply.
+ const { values, failures } = await collectAcrossEnvironments(environments, async (environmentId) => {
+ const ids = scanning.filter((image) => image.environmentId === environmentId).map((image) => image.id);
+ const response = await vulnerabilityService.getScanSummaries(ids, environmentId);
+ return scanning
+ .filter((image) => image.environmentId === environmentId && response?.summaries?.[image.id])
+ .map((image) => [rowKey(image), response.summaries[image.id]!] as const);
+ });
+ if (destroyed || !vulnerabilityManagementEnabled || requestedScope !== environmentStore.shownKey) return [];
+ const summaries = Object.fromEntries(values.flatMap(({ value }) => value));
if (Object.keys(summaries).length > 0 && images.data?.length) {
let changed = false;
let completed = false;
const nextScanRequestedAtByImage = { ...scanRequestedAtByImage };
const nextData = images.data.map((img) => {
- const summary = summaries[img.id];
+ const key = rowKey(img);
+ const summary = summaries[key];
if (!summary) return img;
if (
summary.status === 'failed' &&
- isLikelyStaleFailedSummary(summary, nextScanRequestedAtByImage[img.id]) &&
+ isLikelyStaleFailedSummary(summary, nextScanRequestedAtByImage[key]) &&
isVulnerabilityScanInProgress(img.vulnerabilityScan?.status)
) {
return img;
@@ -341,7 +379,7 @@
changed = true;
if (summary.status === 'completed' || summary.status === 'failed') {
completed = true;
- delete nextScanRequestedAtByImage[img.id];
+ delete nextScanRequestedAtByImage[key];
}
return { ...img, vulnerabilityScan: summary };
});
@@ -353,12 +391,16 @@
await onImageUpdated?.();
}
}
+ return failures;
})()
);
- scanPollError = operationResult.error !== null ? extractApiErrorMessage(operationResult.error) : null;
+ scanPollError =
+ operationResult.error !== null
+ ? extractApiErrorMessage(operationResult.error)
+ : operationResult.data.map(({ environment, message }) => `${environment.name}: ${message}`).join('\n') || null;
} finally {
scanPollInFlight = false;
- if (!destroyed && getScanningImageIds().length > 0) {
+ if (!destroyed && getScanningImages().length > 0) {
scheduleBatchScanPolling();
}
}
@@ -378,13 +420,14 @@
const cache = queryClient.getQueryCache();
function updateScanPolling() {
if (destroyed) return;
- if (getScanningImageIds().length > 0) startBatchScanPolling();
+ if (getScanningImages().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;
+ if (event.query !== cache.find({ queryKey: queryKeys.images.list(environmentStore.shownKey, requestOptions), exact: true }))
+ return;
void tick().then(updateScanPolling);
});
});
@@ -394,7 +437,8 @@
stopBatchScanPolling();
});
- const allColumns = [
+ const allColumns = $derived([
+ ...environmentColumns<ImageRow>(),
{ accessorKey: 'id', title: m.common_id(), hidden: true },
{ accessorKey: 'repo', title: m.resource_repository_cap(), sortable: true, cell: RepoCell },
{ accessorKey: 'repoTags', title: m.common_tags(), cell: TagCell },
@@ -448,7 +492,7 @@
},
{ accessorKey: 'size', title: m.common_size(), sortable: true, cell: SizeCell },
{ accessorKey: 'created', title: m.common_created(), sortable: true, cellComponent: UnixCreatedCell }
- ] satisfies ColumnSpec<ImageSummaryDto>[];
+ ] satisfies ColumnSpec<ImageRow>[]);
const columns = $derived(allColumns.filter((column) => vulnerabilityManagementEnabled || column.id !== 'vulnerabilities'));
@@ -482,15 +526,15 @@
let mobileFieldVisibility = $state<Record<string, boolean>>({});
</script>
-{#snippet RepoCell({ item }: { item: ImageSummaryDto })}
+{#snippet RepoCell({ item }: { item: ImageRow })}
{#if item.repo && item.repo !== '<none>'}
- <a class="font-medium hover:underline" href="/images/{item.id}">{item.repo}</a>
+ <a class="font-medium hover:underline" href={environmentHref(`/images/${item.id}`, item.environmentId)}>{item.repo}</a>
{:else}
<span class="text-muted-foreground italic">{m.images_untagged()}</span>
{/if}
{/snippet}
-{#snippet TagCell({ item }: { item: ImageSummaryDto })}
+{#snippet TagCell({ item }: { item: ImageRow })}
{#if item.repoTags && item.repoTags.length > 0 && item.repoTags[0] !== '<none>:<none>'}
<div class="flex flex-wrap gap-1.5">
{#each item.repoTags.slice(0, 2) as repoTag, tagIndex (`${repoTag}-${tagIndex}`)}
@@ -541,15 +585,15 @@
{bytes.format(Number(value ?? 0))}
{/snippet}
-{#snippet StatusCell({ item }: { item: ImageSummaryDto })}
+{#snippet StatusCell({ item }: { item: ImageRow })}
<InUseStatus inUse={item.inUse} />
{/snippet}
-{#snippet UsageBadgeList(usages: NonNullable<ImageSummaryDto['usedBy']>)}
+{#snippet UsageBadgeList(usages: NonNullable<ImageSummaryDto['usedBy']>, environmentId: string)}
{#each usages as usage, usageIndex (`${usage.type}-${usage.id ?? usage.name}-${usageIndex}`)}
{#if usage.type === 'project'}
{#if usage.id}
- <Badge variant="outline" href={`/projects/${encodeURIComponent(usage.id)}`}>
+ <Badge variant="outline" href={environmentHref(`/projects/${encodeURIComponent(usage.id)}`, environmentId)}>
<ProjectsIcon class="size-3" />
<span>{usage.name}</span>
</Badge>
@@ -560,7 +604,7 @@
</Badge>
{/if}
{:else if usage.id}
- <Badge variant="outline" href={`/containers/${encodeURIComponent(usage.id)}`}>
+ <Badge variant="outline" href={environmentHref(`/containers/${encodeURIComponent(usage.id)}`, environmentId)}>
<ContainersIcon class="size-3" />
<span>{usage.name}</span>
</Badge>
@@ -573,14 +617,14 @@
{/each}
{/snippet}
-{#snippet UsedByCell({ item }: { item: ImageSummaryDto })}
+{#snippet UsedByCell({ item }: { item: ImageRow })}
{#if item.usedBy && item.usedBy.length > 0}
{@const maxVisible = 3}
{@const hasOverflow = item.usedBy.length > maxVisible}
{@const visibleUsage = hasOverflow ? item.usedBy.slice(0, maxVisible) : item.usedBy}
{@const overflowUsage = hasOverflow ? item.usedBy.slice(maxVisible) : []}
<div class="flex flex-wrap gap-1.5">
- {@render UsageBadgeList(visibleUsage)}
+ {@render UsageBadgeList(visibleUsage, item.environmentId)}
{#if hasOverflow}
<Tooltip.Provider>
<Tooltip.Root>
@@ -591,7 +635,7 @@
</Tooltip.Trigger>
<Tooltip.Content class="pointer-events-auto">
<div class="flex max-w-xs flex-wrap gap-1.5">
- {@render UsageBadgeList(overflowUsage)}
+ {@render UsageBadgeList(overflowUsage, item.environmentId)}
</div>
</Tooltip.Content>
</Tooltip.Root>
@@ -603,33 +647,36 @@
{/if}
{/snippet}
-{#snippet UpdatesCell({ item }: { item: ImageSummaryDto })}
+{#snippet UpdatesCell({ item }: { item: ImageRow })}
<div class="flex items-center justify-center">
<ImageUpdateItem
updateInfo={item.updateInfo}
imageId={item.id}
+ environmentId={item.environmentId}
repo={item.repo}
tag={item.tag}
isLocal={!item.repoDigests || item.repoDigests.length === 0}
- onUpdated={(newInfo) => handleUpdateInfoChanged(item.id, newInfo)}
+ onUpdated={(newInfo) => handleUpdateInfoChanged(rowKey(item), newInfo)}
/>
</div>
{/snippet}
-{#snippet VulnerabilitiesCell({ item }: { item: ImageSummaryDto })}
- {#if vulnerabilityManagementEnabled}
+{#snippet VulnerabilitiesCell({ item }: { item: ImageRow })}
+ <!-- The column shows when any environment scans; each row needs its own environment to. -->
+ {#if featureStore.isEnabled('vulnerabilityManagement', item.environmentId)}
<div class="flex items-center justify-center">
<VulnerabilityScanItem
scanSummary={item.vulnerabilityScan}
imageId={item.id}
+ environmentId={item.environmentId}
pollError={scanPollError}
- onScanned={(newSummary) => handleVulnerabilityScanChanged(item.id, newSummary)}
+ onScanned={(newSummary) => handleVulnerabilityScanChanged(rowKey(item), newSummary)}
/>
</div>
{/if}
{/snippet}
-{#snippet MobileTagsValue(item: ImageSummaryDto)}
+{#snippet MobileTagsValue(item: ImageRow)}
{#if item.repoTags && item.repoTags.length > 0 && item.repoTags[0] !== '<none>:<none>'}
<span class="font-mono text-xs">{item.repoTags.map((rt) => rt.split(':').pop() || rt).join(', ')}</span>
{:else if item.pinnedReferences && item.pinnedReferences.length > 0}
@@ -650,7 +697,7 @@
item,
mobileFieldVisibility
}: {
- item: ImageSummaryDto;
+ item: ImageRow;
mobileFieldVisibility: MobileFieldVisibility;
})}
<UniversalMobileCard
@@ -669,7 +716,7 @@
subtitle={(item) => ((mobileFieldVisibility['id'] ?? false) ? item.id : null)}
badges={[
inUseBadge(mobileFieldVisibility['inUse'] ?? true),
- (item: ImageSummaryDto) => {
+ (item: ImageRow) => {
if (!(mobileFieldVisibility['updates'] ?? false)) return null;
if (!item.repoDigests || item.repoDigests.length === 0) {
return { variant: 'gray' as const, text: m.image_update_local_title() };
@@ -684,14 +731,14 @@
fields={[
{
label: m.common_size(),
- getValue: (item: ImageSummaryDto) => bytes.format(Number(item.size ?? 0)),
+ getValue: (item: ImageRow) => bytes.format(Number(item.size ?? 0)),
icon: VolumesIcon,
iconVariant: 'blue' as const,
show: mobileFieldVisibility['size'] ?? true
},
{
label: m.common_tags(),
- getValue: (item: ImageSummaryDto) => item,
+ getValue: (item: ImageRow) => item,
type: 'component',
component: MobileTagsValue,
icon: ImagesIcon,
@@ -700,7 +747,7 @@
},
{
label: m.images_used_by(),
- getValue: (item: ImageSummaryDto) => item.usedBy?.map((usage) => usage.name).join(', ') || '—',
+ getValue: (item: ImageRow) => item.usedBy?.map((usage) => usage.name).join(', ') || '—',
icon: ImagesIcon,
iconVariant: 'purple' as const,
show: mobileFieldVisibility['usedBy'] ?? false
@@ -714,13 +761,14 @@
}
: undefined}
rowActions={RowActions}
- onclick={(item: ImageSummaryDto) => goto(`/images/${item.id}`)}
+ onclick={(item: ImageRow) => goto(environmentHref(`/images/${item.id}`, item.environmentId))}
/>
{/snippet}
-{#snippet RowActions({ item }: { item: ImageSummaryDto })}
+{#snippet RowActions({ item }: { item: ImageRow })}
+ {@const envId = item.environmentId}
<RowActionsMenu>
- <DropdownMenu.Item onclick={() => goto(`/images/${item.id}`)}>
+ <DropdownMenu.Item onclick={() => goto(environmentHref(`/images/${item.id}`, envId))}>
<InspectIcon class="size-4" />
{m.common_inspect()}
</DropdownMenu.Item>
@@ -729,38 +777,38 @@
<DropdownMenu.Separator />
{/if}
- {#if canTagImage}
+ {#if canTagImage && hasPermission('images:tag', envId)}
<DropdownMenu.Item onclick={() => (tagDialogImage = item)}>
<TagIcon class="size-4" />
{m.images_tag_image()}
</DropdownMenu.Item>
{/if}
- {#if canReadImage}
- <DropdownMenu.Item onclick={() => handleExportImage(item.id)}>
+ {#if canReadImage && hasPermission('images:read', envId)}
+ <DropdownMenu.Item onclick={() => handleExportImage(item.id, envId)}>
<DownloadIcon class="size-4" />
{m.images_export()}
</DropdownMenu.Item>
{/if}
{@const usableTag = item.repoTags?.find((tag) => tag !== '<none>:<none>')}
- {#if canPullImage}
- <DropdownMenu.Item onclick={() => handleInlineImagePull(usableTag || '')} disabled={!usableTag}>
+ {#if canPullImage && hasPermission('images:pull', envId)}
+ <DropdownMenu.Item onclick={() => handleInlineImagePull(usableTag || '', envId)} disabled={!usableTag}>
<DownloadIcon class="size-4" />
{m.pull()}
</DropdownMenu.Item>
{/if}
- {#if canScanImage}
- <DropdownMenu.Item onclick={() => handleInlineVulnerabilityScan(item.id)}>
+ {#if canScanImage && featureStore.isEnabled('vulnerabilityManagement', envId) && hasPermission('vulnerabilities:scan', envId)}
+ <DropdownMenu.Item onclick={() => handleInlineVulnerabilityScan(item)}>
<ScanIcon class="size-4" />
{m.vuln_scan()}
</DropdownMenu.Item>
{/if}
- {#if canPatchImage}
+ {#if canPatchImage && hasPermission('images:patch', envId)}
{@const imageIsLocal = !item.repoDigests || item.repoDigests.length === 0}
- <DropdownMenu.Item onclick={() => handleInlineImagePatch(item.id)} disabled={imageIsLocal || !usableTag}>
+ <DropdownMenu.Item onclick={() => handleInlineImagePatch(item.id, envId)} disabled={imageIsLocal || !usableTag}>
<ShieldCheckIcon class="size-4" />
<div class="flex flex-col items-start">
<span>{m.images_patch()}</span>
@@ -771,10 +819,10 @@
</DropdownMenu.Item>
{/if}
- {#if canDeleteImage}
+ {#if canDeleteImage && hasPermission('images:delete', envId)}
<DropdownMenu.Separator />
- <DropdownMenu.Item variant="destructive" onclick={() => deleteImage(item.id)} disabled={isLoading.removing}>
+ <DropdownMenu.Item variant="destructive" onclick={() => deleteImage(item.id, envId)} disabled={isLoading.removing}>
{#if isLoading.removing}
<Spinner class="size-4" />
{:else}
@@ -809,6 +857,7 @@
<ImageTagDialog
open={!!tagDialogImage}
imageId={tagDialogImage.id}
+ environmentId={tagDialogImage.environmentId}
defaultRepository={tagDialogImage.repo !== '<none>' ? tagDialogImage.repo : ''}
onOpenChange={(open) => {
if (!open) tagDialogImage = null;
diff --git a/frontend/src/routes/(app)/images/components/image-tag-dialog.svelte b/frontend/src/routes/(app)/images/components/image-tag-dialog.svelte
index b7a56a9a8..32687c7fb 100644
--- a/frontend/src/routes/(app)/images/components/image-tag-dialog.svelte
+++ b/frontend/src/routes/(app)/images/components/image-tag-dialog.svelte
@@ -13,12 +13,13 @@
type Props = {
open: boolean;
imageId: string;
+ environmentId?: string;
defaultRepository?: string;
onOpenChange?: (open: boolean) => void;
onTagged?: () => Promise<void> | void;
};
- let { open = $bindable(false), imageId, defaultRepository = '', onOpenChange, onTagged }: Props = $props();
+ let { open = $bindable(false), imageId, environmentId, defaultRepository = '', onOpenChange, onTagged }: Props = $props();
const schema = z.object({
repository: z.string().min(1, m.images_tag_repository_required()),
@@ -48,10 +49,14 @@
try {
const operationResult = await tryCatch(
(async () => {
- await imageService.tagImage(imageId, {
- repository: data.repository.trim(),
- tag: data.tag?.trim() || undefined
- });
+ await imageService.tagImage(
+ imageId,
+ {
+ repository: data.repository.trim(),
+ tag: data.tag?.trim() || undefined
+ },
+ environmentId
+ );
toast.success(m.images_tag_success());
await onTagged?.();
handleOpenChange(false);
diff --git a/frontend/src/routes/(app)/networks/+page.svelte b/frontend/src/routes/(app)/networks/+page.svelte
index 5723a0e57..446039464 100644
--- a/frontend/src/routes/(app)/networks/+page.svelte
+++ b/frontend/src/routes/(app)/networks/+page.svelte
@@ -10,13 +10,15 @@
import { m } from '#lib/paraglide/messages.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { networkService } from '#lib/services/network-service.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { NetworkCreateOptions, NetworkUsageCounts } from '#lib/types/docker.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { extractApiErrorMessage } from '#lib/utils/api.js';
+ import { fetchAcrossEnvironments } from '#lib/utils/environments.js';
import { ResourceListPageState } from '#lib/utils/resource-list-page.svelte.js';
import { tryCatch } from '#lib/utils/try-catch.js';
- import NetworkTable from './components/network-table.svelte';
+ import NetworkTable, { networkSortValue } from './components/network-table.svelte';
let { data } = $props();
const queryClient = useQueryClient();
@@ -24,21 +26,28 @@
const pageState = new ResourceListPageState(untrack(() => data.networkRequestOptions));
const countsFallback: NetworkUsageCounts = { inuse: 0, unused: 0, total: 0 };
+ // The load already cached the first page under its key; seeding every key with it would hide other pages and filters.
const networksQuery = createQuery(() => {
- const queryEnvId = pageState.envId;
+ const queryScope = pageState.scope;
+ const environments = environmentStore.shown;
const options = pageState.requestOptions;
return {
- queryKey: queryKeys.networks.list(queryEnvId, options),
- queryFn: () => networkService.getNetworksForEnvironment(queryEnvId, options),
+ queryKey: queryKeys.networks.list(queryScope, options),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ environments,
+ options,
+ (id, request, config) => networkService.getNetworksForEnvironment(id, request, config),
+ networkSortValue
+ ),
placeholderData: (previous, query) => {
- if (query?.queryKey[1] === queryEnvId) return previous;
+ if (query?.queryKey[1] === queryScope) return previous;
return undefined;
},
- initialData: data.envId === queryEnvId ? data.networks : undefined,
- select: (value) => ({ envId: queryEnvId, value })
+ select: (value) => ({ envId: queryScope, value })
};
});
- const resourcesReady = $derived(networksQuery.data?.envId === pageState.envId);
+ const resourcesReady = $derived(networksQuery.data?.envId === pageState.scope);
const networks = $derived(networksQuery.data?.value ?? data.networks);
const createNetworkMutation = createMutation(() => ({
@@ -50,8 +59,8 @@
m.common_create_success({ resource: `${m.resource_network()} "${variables.name}"` }),
activityToastOptions(extractActivityId(data))
);
- if (variables.requestedEnvId === pageState.envId) {
- await loadNetworks(pageState.requestOptions, variables.requestedEnvId);
+ if (environmentStore.shown.some((env) => env.id === variables.requestedEnvId)) {
+ await loadNetworks();
pageState.isCreateDialogOpen = false;
}
},
@@ -67,15 +76,22 @@
pageState.isCreateDialogOpen = false;
});
- async function handleCreate(name: string, options: NetworkCreateOptions) {
- await tryCatch(createNetworkMutation.mutateAsync({ name, options, requestedEnvId: pageState.envId }));
+ async function handleCreate(name: string, options: NetworkCreateOptions, environmentId: string) {
+ await tryCatch(createNetworkMutation.mutateAsync({ name, options, requestedEnvId: environmentId }));
}
- async function loadNetworks(options = pageState.requestOptions, requestedEnvId = pageState.envId) {
+ async function loadNetworks(options = pageState.requestOptions, requestedScope = pageState.scope) {
+ const environments = environmentStore.shown;
pageState.requestOptions = options;
await queryClient.query({
- queryKey: queryKeys.networks.list(requestedEnvId, options),
- queryFn: () => networkService.getNetworksForEnvironment(requestedEnvId, options),
+ queryKey: queryKeys.networks.list(requestedScope, options),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ environments,
+ options,
+ (id, request, config) => networkService.getNetworksForEnvironment(id, request, config),
+ networkSortValue
+ ),
staleTime: 0
});
}
@@ -131,11 +147,11 @@
<ResourcePageLayout title={m.resource_networks_cap()} subtitle={m.networks_subtitle()} {actionButtons} {statCards}>
{#snippet mainContent()}
{#if resourcesReady}
- {#key pageState.envId}
+ {#key pageState.scope}
<NetworkTable
bind:networks={
() => networks,
- (value) => queryClient.setQueryData(queryKeys.networks.list(pageState.envId, pageState.requestOptions), value)
+ (value) => queryClient.setQueryData(queryKeys.networks.list(pageState.scope, pageState.requestOptions), value)
}
bind:selectedIds={pageState.selectedIds}
bind:requestOptions={pageState.requestOptions}
diff --git a/frontend/src/routes/(app)/networks/+page.ts b/frontend/src/routes/(app)/networks/+page.ts
index 169283f78..5c98d9366 100644
--- a/frontend/src/routes/(app)/networks/+page.ts
+++ b/frontend/src/routes/(app)/networks/+page.ts
@@ -1,15 +1,18 @@
import { queryKeys } from '#lib/query/query-keys.js';
import { networkService } from '#lib/services/network-service.js';
import { throwPageLoadError } from '#lib/utils/api.js';
+import { fetchAcrossEnvironments } from '#lib/utils/environments.js';
import { resolveListPageLoadContext } from '#lib/utils/tables.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
+import { networkSortValue } from './components/network-table.svelte';
export const load: PageLoad = async ({ parent }) => {
const {
queryClient,
- envId,
+ environments,
+ scope,
requestOptions: networkRequestOptions
} = await resolveListPageLoadContext(parent, 'arcane-networks-table', {
column: 'name',
@@ -21,8 +24,14 @@ export const load: PageLoad = async ({ parent }) => {
const operationResult = await tryCatch(
(async () =>
queryClient.query({
- queryKey: queryKeys.networks.list(envId, networkRequestOptions),
- queryFn: () => networkService.getNetworksForEnvironment(envId, networkRequestOptions)
+ queryKey: queryKeys.networks.list(scope, networkRequestOptions),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ environments,
+ networkRequestOptions,
+ (id, request, config) => networkService.getNetworksForEnvironment(id, request, config),
+ networkSortValue
+ )
}))()
);
if (operationResult.error !== null) {
@@ -34,7 +43,7 @@ export const load: PageLoad = async ({ parent }) => {
}
return {
- envId,
+ scope,
networks,
networkRequestOptions,
// Use counts from the networks response
diff --git a/frontend/src/routes/(app)/networks/[networkId]/+page.svelte b/frontend/src/routes/(app)/networks/[networkId]/+page.svelte
index 456fa5b75..663d0d7eb 100644
--- a/frontend/src/routes/(app)/networks/[networkId]/+page.svelte
+++ b/frontend/src/routes/(app)/networks/[networkId]/+page.svelte
@@ -28,6 +28,7 @@
import type { NetworkInspectDto, IPAMSubnetDto } from '#lib/types/docker.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+ import { environmentHref } from '#lib/utils/environments.js';
import { formatDateTimeShort } from '#lib/utils/formatting.js';
import { tryCatch } from '#lib/utils/try-catch.js';
@@ -60,7 +61,7 @@
if (data.network?.id) {
const operationResult = await tryCatch(
(async () =>
- networkService.getNetwork(data.network.id, {
+ networkService.getNetworkForEnvironment(data.envId, data.network.id, {
sort: { column: sortCol, direction: sortDir }
}))()
);
@@ -87,6 +88,8 @@
return;
}
+ // The dialog outlives navigation, so it removes the network it was opened for.
+ const target = { id: network.id, environmentId: data.envId };
openConfirmDialog({
title: m.common_remove_title({ resource: m.resource_network() }),
message: m.networks_remove_confirm_message({ name: network?.name ?? shortId }),
@@ -96,7 +99,7 @@
action: async () => {
isRemoving = true;
await handleApiResultWithCallbacks({
- result: await tryCatch(networkService.deleteNetwork(network.id)),
+ result: await tryCatch(networkService.deleteNetwork(target.id, target.environmentId)),
message: m.networks_remove_failed({ name: network?.name ?? shortId }),
setLoadingState: (value) => (isRemoving = value),
onSuccess: async (data) => {
@@ -280,7 +283,10 @@
].filter(Boolean)}
<div class="flex flex-col p-3 sm:flex-row sm:items-center">
<div class="mb-2 w-full font-medium break-all sm:mb-0 sm:w-1/3">
- <a href="/containers/{container.id}" class="flex items-center text-primary hover:underline">
+ <a
+ href={environmentHref(`/containers/${container.id}`, data.envId)}
+ class="flex items-center text-primary hover:underline"
+ >
<ContainersIcon class="mr-1.5 size-3.5 text-muted-foreground" />
{container.name ?? container.Name}
</a>
diff --git a/frontend/src/routes/(app)/networks/[networkId]/+page.ts b/frontend/src/routes/(app)/networks/[networkId]/+page.ts
index 00246ba2d..19a9fe0cf 100644
--- a/frontend/src/routes/(app)/networks/[networkId]/+page.ts
+++ b/frontend/src/routes/(app)/networks/[networkId]/+page.ts
@@ -2,14 +2,14 @@ import { error } from '@sveltejs/kit';
import { queryKeys } from '#lib/query/query-keys.js';
import { networkService } from '#lib/services/network-service.js';
-import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+import { resolveDetailEnvironmentId } from '#lib/utils/environments.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
-export const load: PageLoad = async ({ params, parent }) => {
+export const load: PageLoad = async ({ params, parent, url }) => {
const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const envId = await resolveDetailEnvironmentId(url);
const { networkId } = params;
@@ -25,6 +25,7 @@ export const load: PageLoad = async ({ params, parent }) => {
}
return {
+ envId,
network
};
})()
diff --git a/frontend/src/routes/(app)/networks/components/network-table.svelte b/frontend/src/routes/(app)/networks/components/network-table.svelte
index faaf49670..c2f75d928 100644
--- a/frontend/src/routes/(app)/networks/components/network-table.svelte
+++ b/frontend/src/routes/(app)/networks/components/network-table.svelte
@@ -1,9 +1,47 @@
+<script module lang="ts">
+ import type { NetworkSummaryDto } from '#lib/types/docker.js';
+
+ function ipamValues(item: NetworkSummaryDto, key: 'subnet' | 'gateway'): string[] {
+ return (item.ipam?.config ?? []).map((c) => c[key]).filter((v): v is string => !!v);
+ }
+
+ // A fixed-width digit key that orders like the backend: IPv4 before IPv6, then by address, then by prefix
+ // length. An entry that is not an address sorts after every address.
+ function addressSortKey(value: string): string {
+ const [address = '', prefix = ''] = value.split('/');
+ const octets = address.split('.');
+ let family = '1';
+ let hex = '';
+ if (octets.length === 4 && octets.every((octet) => /^\d{1,3}$/.test(octet))) {
+ hex = octets.map((octet) => Number(octet).toString(16).padStart(2, '0')).join('');
+ } else if (/^[\da-f:]+$/i.test(address)) {
+ const [head = '', tail = ''] = address.split('::');
+ const headGroups = head ? head.split(':') : [];
+ const tailGroups = tail ? tail.split(':') : [];
+ const fill = address.includes('::') ? 8 - headGroups.length - tailGroups.length : 0;
+ family = '2';
+ hex = [...headGroups, ...Array<string>(Math.max(fill, 0)).fill('0'), ...tailGroups].map((g) => g.padStart(4, '0')).join('');
+ }
+ if (!hex) return `z${value}`;
+ return `${family}${BigInt(`0x${hex}`).toString().padStart(39, '0')}${prefix.padStart(3, '0')}`;
+ }
+
+ /** Sort value for a network column whose sort key is not a row field. */
+ export function networkSortValue(network: NetworkSummaryDto, column: string): unknown {
+ // The backend sorts each network's entries before comparing networks, so entry order does not matter.
+ if (column === 'subnet' || column === 'gateway')
+ return ipamValues(network, column).map(addressSortKey).sort().join(' ') || null;
+ return network[column as keyof NetworkSummaryDto];
+ }
+</script>
+
<script lang="ts">
import { goto } from '$app/navigation';
import { toast } from 'svelte-sonner';
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import InUseStatus from '#lib/components/arcane-table/cells/in-use-status.svelte';
+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';
import type { ColumnSpec, BulkAction } from '#lib/components/arcane-table/index.js';
import { UniversalMobileCard } from '#lib/components/arcane-table/index.js';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
@@ -13,16 +51,25 @@
import { DEFAULT_NETWORK_NAMES } from '#lib/constants.js';
import { NetworksIcon, GlobeIcon, InspectIcon, TrashIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
- import { networkService } from '#lib/services/network-service.js';
- import type { NetworkSummaryDto, NetworkUsageCounts } from '#lib/types/docker.js';
- import type { SearchPaginationSortRequest, Paginated } from '#lib/types/shared.js';
+ import { networkService, type NetworksPaginatedResponse } from '#lib/services/network-service.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+ import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { bulkConfirmAndRun } from '#lib/utils/bulk-actions.js';
+ import {
+ environmentHref,
+ fetchAcrossEnvironments,
+ rowKey,
+ type EnvironmentPage,
+ type EnvironmentRow
+ } from '#lib/utils/environments.js';
import { capitalizeFirstLetter } from '#lib/utils/formatting.js';
import { tryCatch } from '#lib/utils/try-catch.js';
type FieldVisibility = Record<string, boolean>;
+ type NetworkRow = EnvironmentRow<NetworkSummaryDto>;
+ type NetworkPage = EnvironmentPage<NetworksPaginatedResponse>;
let {
networks = $bindable(),
@@ -31,10 +78,10 @@
onNetworksChange,
onRefreshData
}: {
- networks: Paginated<NetworkSummaryDto, NetworkUsageCounts>;
+ networks: NetworkPage;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
- onNetworksChange?: (networks: Paginated<NetworkSummaryDto, NetworkUsageCounts>) => void;
+ onNetworksChange?: (networks: NetworkPage) => void;
onRefreshData?: (options: SearchPaginationSortRequest) => Promise<void>;
} = $props();
@@ -50,11 +97,16 @@
}
return;
}
- networks = await networkService.getNetworks(options);
+ networks = await fetchAcrossEnvironments(
+ environmentStore.shown,
+ options,
+ (id, request, config) => networkService.getNetworksForEnvironment(id, request, config),
+ networkSortValue
+ );
onNetworksChange?.(networks);
}
- async function handleDeleteNetwork(id: string, name: string) {
+ async function handleDeleteNetwork(id: string, name: string, environmentId: string) {
const safeName = name?.trim() || m.common_unknown();
if (DEFAULT_NETWORK_NAMES.has(name)) {
toast.error(m.networks_cannot_delete_default({ name: safeName }));
@@ -69,7 +121,7 @@
action: async () => {
isLoading.remove = true;
await handleApiResultWithCallbacks({
- result: await tryCatch(networkService.deleteNetwork(id)),
+ result: await tryCatch(networkService.deleteNetwork(id, environmentId)),
message: m.common_delete_failed({ resource: `${m.resource_network()} "${safeName}"` }),
setLoadingState: (value) => (isLoading.remove = value),
onSuccess: async (data) => {
@@ -86,7 +138,7 @@
}
function handleDeleteSelectedNetworks(ids: string[]) {
- const selectedNetworkList = networks.data.filter((n) => ids.includes(n.id));
+ const selectedNetworkList = networks.data.filter((n) => ids.includes(rowKey(n)));
const defaultNetworks = selectedNetworkList.filter((n) => n.isDefault);
if (defaultNetworks.length > 0) {
@@ -101,7 +153,7 @@
message: m.networks_delete_selected_message({ count: ids.length }),
confirmLabel: m.common_delete(),
destructive: true,
- run: (id) => networkService.deleteNetwork(id),
+ run: (id, environmentId) => networkService.deleteNetwork(id, environmentId),
messages: {
success: (count) => m.common_bulk_delete_success({ count, resource: m.resource_networks_cap() }),
partial: (success, total, failed) =>
@@ -128,7 +180,8 @@
return variantMap[driver] || 'gray';
}
- const columns = [
+ const columns = $derived([
+ ...environmentColumns<NetworkRow>(),
{ accessorKey: 'id', title: m.common_id(), cell: IdCell, hidden: true },
{ accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },
{ accessorKey: 'inUse', title: m.common_status(), sortable: true, cell: StatusCell },
@@ -136,19 +189,19 @@
{ accessorKey: 'scope', title: m.common_scope(), sortable: true, cell: ScopeCell },
{
id: 'subnet',
- accessorFn: (row) => ipamValues(row, 'subnet').join(' '),
+ accessorFn: (row) => networkSortValue(row, 'subnet'),
title: m.common_subnet(),
sortable: true,
cell: SubnetCell
},
{
id: 'gateway',
- accessorFn: (row) => ipamValues(row, 'gateway').join(' '),
+ accessorFn: (row) => networkSortValue(row, 'gateway'),
title: m.common_gateway(),
sortable: true,
cell: GatewayCell
}
- ] satisfies ColumnSpec<NetworkSummaryDto>[];
+ ] satisfies ColumnSpec<NetworkRow>[]);
const mobileFields = [
{ id: 'id', label: m.common_id(), defaultVisible: false },
@@ -159,10 +212,6 @@
{ id: 'gateway', label: m.common_gateway(), defaultVisible: true }
];
- function ipamValues(item: NetworkSummaryDto, key: 'subnet' | 'gateway'): string[] {
- return (item.ipam?.config ?? []).map((c) => c[key]).filter((v): v is string => !!v);
- }
-
const bulkActions = $derived.by<BulkAction[]>(() => [
{
id: 'remove',
@@ -178,15 +227,15 @@
let mobileFieldVisibility = $state<Record<string, boolean>>({});
</script>
-{#snippet NameCell({ item }: { item: NetworkSummaryDto })}
- <a class="font-medium hover:underline" href="/networks/{item.id}">{item.name}</a>
+{#snippet NameCell({ item }: { item: NetworkRow })}
+ <a class="font-medium hover:underline" href={environmentHref(`/networks/${item.id}`, item.environmentId)}>{item.name}</a>
{/snippet}
-{#snippet IdCell({ item }: { item: NetworkSummaryDto })}
+{#snippet IdCell({ item }: { item: NetworkRow })}
<span class="truncate font-mono text-sm">{String(item.id)}</span>
{/snippet}
-{#snippet DriverCell({ item }: { item: NetworkSummaryDto })}
+{#snippet DriverCell({ item }: { item: NetworkRow })}
<Badge
variant={item.driver === 'bridge'
? 'blue'
@@ -201,11 +250,11 @@
>
{/snippet}
-{#snippet ScopeCell({ item }: { item: NetworkSummaryDto })}
+{#snippet ScopeCell({ item }: { item: NetworkRow })}
<Badge variant={item.scope === 'local' ? 'green' : 'amber'} minWidth="20">{capitalizeFirstLetter(item.scope)}</Badge>
{/snippet}
-{#snippet SubnetCell({ item }: { item: NetworkSummaryDto })}
+{#snippet SubnetCell({ item }: { item: NetworkRow })}
{@const subnets = ipamValues(item, 'subnet')}
{#if subnets.length === 0}
<span class="text-muted-foreground">—</span>
@@ -218,7 +267,7 @@
{/if}
{/snippet}
-{#snippet GatewayCell({ item }: { item: NetworkSummaryDto })}
+{#snippet GatewayCell({ item }: { item: NetworkRow })}
{@const gateways = ipamValues(item, 'gateway')}
{#if gateways.length === 0}
<span class="text-muted-foreground">—</span>
@@ -231,7 +280,7 @@
{/if}
{/snippet}
-{#snippet StatusCell({ item }: { item: NetworkSummaryDto })}
+{#snippet StatusCell({ item }: { item: NetworkRow })}
{#if item.isDefault}
<Badge variant="sky" minWidth="20">{m.networks_predefined()}</Badge>
{:else}
@@ -239,23 +288,17 @@
{/if}
{/snippet}
-{#snippet NetworkMobileCardSnippet({
- item,
- mobileFieldVisibility
-}: {
- item: NetworkSummaryDto;
- mobileFieldVisibility: FieldVisibility;
-})}
+{#snippet NetworkMobileCardSnippet({ item, mobileFieldVisibility }: { item: NetworkRow; mobileFieldVisibility: FieldVisibility })}
<UniversalMobileCard
{item}
- icon={(item: NetworkSummaryDto) => ({
+ icon={(item: NetworkRow) => ({
component: NetworksIcon,
variant: item.inUse ? 'emerald' : 'amber'
})}
- title={(item: NetworkSummaryDto) => item.name}
- subtitle={(item: NetworkSummaryDto) => ((mobileFieldVisibility['id'] ?? true) ? item.id : null)}
+ title={(item: NetworkRow) => item.name}
+ subtitle={(item: NetworkRow) => ((mobileFieldVisibility['id'] ?? true) ? item.id : null)}
badges={[
- (item: NetworkSummaryDto) =>
+ (item: NetworkRow) =>
(mobileFieldVisibility['inUse'] ?? true)
? (item.isDefault ?? false) || DEFAULT_NETWORK_NAMES.has(item.name)
? { variant: 'gray', text: m.networks_predefined() }
@@ -267,7 +310,7 @@
fields={[
{
label: m.common_driver(),
- getValue: (item: NetworkSummaryDto) => capitalizeFirstLetter(item.driver),
+ getValue: (item: NetworkRow) => capitalizeFirstLetter(item.driver),
icon: NetworksIcon,
iconVariant: 'gray' as const,
type: 'badge' as const,
@@ -276,7 +319,7 @@
},
{
label: m.common_scope(),
- getValue: (item: NetworkSummaryDto) => capitalizeFirstLetter(item.scope),
+ getValue: (item: NetworkRow) => capitalizeFirstLetter(item.scope),
icon: GlobeIcon,
iconVariant: 'gray' as const,
type: 'badge' as const,
@@ -285,7 +328,7 @@
},
{
label: m.common_subnet(),
- getValue: (item: NetworkSummaryDto) => ipamValues(item, 'subnet').join(', ') || '—',
+ getValue: (item: NetworkRow) => ipamValues(item, 'subnet').join(', ') || '—',
icon: NetworksIcon,
iconVariant: 'gray' as const,
type: 'mono' as const,
@@ -293,7 +336,7 @@
},
{
label: m.common_gateway(),
- getValue: (item: NetworkSummaryDto) => ipamValues(item, 'gateway').join(', ') || '—',
+ getValue: (item: NetworkRow) => ipamValues(item, 'gateway').join(', ') || '—',
icon: GlobeIcon,
iconVariant: 'gray' as const,
type: 'mono' as const,
@@ -301,13 +344,13 @@
}
]}
rowActions={RowActions}
- onclick={() => goto(`/networks/${item.id}`)}
+ onclick={() => goto(environmentHref(`/networks/${item.id}`, item.environmentId))}
/>
{/snippet}
-{#snippet RowActions({ item }: { item: NetworkSummaryDto })}
+{#snippet RowActions({ item }: { item: NetworkRow })}
<RowActionsMenu>
- <DropdownMenu.Item onclick={() => goto(`/networks/${item.id}`)} disabled={isAnyLoading}>
+ <DropdownMenu.Item onclick={() => goto(environmentHref(`/networks/${item.id}`, item.environmentId))} disabled={isAnyLoading}>
<InspectIcon class="size-4" />
{m.common_inspect()}
</DropdownMenu.Item>
@@ -316,7 +359,7 @@
<DropdownMenu.Item
variant="destructive"
- onclick={() => handleDeleteNetwork(item.id, item.name)}
+ onclick={() => handleDeleteNetwork(item.id, item.name, item.environmentId)}
disabled={isAnyLoading || item.isDefault || DEFAULT_NETWORK_NAMES.has(item.name)}
>
<TrashIcon class="size-4" />
diff --git a/frontend/src/routes/(app)/networks/ports/+page.svelte b/frontend/src/routes/(app)/networks/ports/+page.svelte
index 24057ece9..211db1d56 100644
--- a/frontend/src/routes/(app)/networks/ports/+page.svelte
+++ b/frontend/src/routes/(app)/networks/ports/+page.svelte
@@ -1,5 +1,6 @@
<script lang="ts">
import { createQuery } from '@tanstack/svelte-query';
+ import { tick } from 'svelte';
import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';
import { ResourcePageLayout, type ActionButton } from '#lib/layouts/index.js';
@@ -7,6 +8,7 @@
import { queryKeys } from '#lib/query/query-keys.js';
import { portService } from '#lib/services/port-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+ import { fetchAcrossEnvironments } from '#lib/utils/environments.js';
import PortTable from './components/port-table.svelte';
@@ -15,18 +17,27 @@
let requestOptions = $derived(data.portRequestOptions);
let selectedIds = $state<string[]>([]);
- const envId = $derived(environmentStore.selected?.id || '0');
+ const scope = $derived(environmentStore.shownKey);
+ // The load already cached the first page under its key; seeding every key with it would hide other pages and filters.
const portsQuery = createQuery(() => {
- const queryEnvId = envId;
+ const queryScope = scope;
+ const environments = environmentStore.shown;
+ const options = requestOptions;
return {
- queryKey: queryKeys.ports.list(queryEnvId, requestOptions),
- queryFn: () => portService.getPortsForEnvironment(queryEnvId, requestOptions),
- initialData: data.envId === queryEnvId ? data.ports : undefined,
- select: (value) => ({ envId: queryEnvId, value })
+ queryKey: queryKeys.ports.list(queryScope, options),
+ queryFn: () =>
+ fetchAcrossEnvironments(environments, options, (id, request, config) =>
+ portService.getPortsForEnvironment(id, request, config)
+ ),
+ placeholderData: (previous, query) => {
+ if (query?.queryKey[1] === queryScope) return previous;
+ return undefined;
+ },
+ select: (value) => ({ envId: queryScope, value })
};
});
- const ports = $derived(portsQuery.data?.envId === envId ? portsQuery.data.value : null);
+ const ports = $derived(portsQuery.data?.envId === scope ? portsQuery.data.value : null);
useEnvironmentRefresh(() => {
selectedIds = [];
@@ -61,6 +72,9 @@
bind:requestOptions
onRefreshData={async (options) => {
requestOptions = options;
+ // Let the query pick up the new key first; unchanged options (Retry) still refetch.
+ await tick();
+ await portsQuery.refetch({ cancelRefetch: false });
}}
/>
{/if}
diff --git a/frontend/src/routes/(app)/networks/ports/+page.ts b/frontend/src/routes/(app)/networks/ports/+page.ts
index 096b2e188..d6b93717b 100644
--- a/frontend/src/routes/(app)/networks/ports/+page.ts
+++ b/frontend/src/routes/(app)/networks/ports/+page.ts
@@ -1,6 +1,7 @@
import { queryKeys } from '#lib/query/query-keys.js';
import { portService } from '#lib/services/port-service.js';
import { throwPageLoadError } from '#lib/utils/api.js';
+import { fetchAcrossEnvironments } from '#lib/utils/environments.js';
import { resolveListPageLoadContext } from '#lib/utils/tables.js';
import { tryCatch } from '#lib/utils/try-catch.js';
@@ -9,7 +10,8 @@ import type { PageLoad } from './$types';
export const load: PageLoad = async ({ parent }) => {
const {
queryClient,
- envId,
+ environments,
+ scope,
requestOptions: portRequestOptions
} = await resolveListPageLoadContext(parent, 'arcane-ports-table', {
column: 'hostPort',
@@ -20,8 +22,11 @@ export const load: PageLoad = async ({ parent }) => {
const operationResult = await tryCatch(
(async () =>
queryClient.query({
- queryKey: queryKeys.ports.list(envId, portRequestOptions),
- queryFn: () => portService.getPortsForEnvironment(envId, portRequestOptions)
+ queryKey: queryKeys.ports.list(scope, portRequestOptions),
+ queryFn: () =>
+ fetchAcrossEnvironments(environments, portRequestOptions, (id, request, config) =>
+ portService.getPortsForEnvironment(id, request, config)
+ )
}))()
);
if (operationResult.error !== null) {
@@ -33,7 +38,7 @@ export const load: PageLoad = async ({ parent }) => {
}
return {
- envId,
+ scope,
ports,
portRequestOptions
};
diff --git a/frontend/src/routes/(app)/networks/ports/components/port-table.svelte b/frontend/src/routes/(app)/networks/ports/components/port-table.svelte
index 3ea0fb29a..50efae7dd 100644
--- a/frontend/src/routes/(app)/networks/ports/components/port-table.svelte
+++ b/frontend/src/routes/(app)/networks/ports/components/port-table.svelte
@@ -2,14 +2,25 @@
import { goto } from '$app/navigation';
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';
import { UniversalMobileCard } from '#lib/components/arcane-table/index.js';
import type { ColumnSpec, MobileFieldVisibility } from '#lib/components/arcane-table/index.js';
import { Badge } from '#lib/components/ui/badge/index.js';
import { ContainersIcon, ConnectionIcon, GlobeIcon, HashIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
- import { portService } from '#lib/services/port-service.js';
+ import { portService, type PortsPaginatedResponse } from '#lib/services/port-service.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { PortMappingDto } from '#lib/types/docker.js';
- import type { SearchPaginationSortRequest, Paginated } from '#lib/types/shared.js';
+ import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
+ import {
+ environmentHref,
+ fetchAcrossEnvironments,
+ type EnvironmentPage,
+ type EnvironmentRow
+ } from '#lib/utils/environments.js';
+
+ type PortRow = EnvironmentRow<PortMappingDto>;
+ type PortPage = EnvironmentPage<PortsPaginatedResponse>;
let {
ports,
@@ -17,7 +28,7 @@
requestOptions = $bindable(),
onRefreshData
}: {
- ports: Paginated<PortMappingDto>;
+ ports: PortPage;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
onRefreshData?: (options: SearchPaginationSortRequest) => Promise<void>;
@@ -43,22 +54,25 @@
return `${port.containerPort}/${port.protocol}`;
}
- async function refreshPorts(options: SearchPaginationSortRequest = requestOptions): Promise<Paginated<PortMappingDto> | void> {
+ async function refreshPorts(options: SearchPaginationSortRequest = requestOptions): Promise<PortPage | void> {
if (onRefreshData) {
await onRefreshData(options);
return;
}
- return await portService.getPorts(options);
+ return await fetchAcrossEnvironments(environmentStore.shown, options, (id, request, config) =>
+ portService.getPortsForEnvironment(id, request, config)
+ );
}
- const columns = [
+ const columns = $derived([
+ ...environmentColumns<PortRow>(),
{ accessorKey: 'hostPort', title: m.ports_host_port(), sortable: true, cell: HostPortCell },
{ accessorKey: 'containerPort', title: m.ports_container_port(), sortable: true, cell: ContainerPortCell },
{ accessorKey: 'protocol', title: m.common_type(), sortable: true, cell: ProtocolCell },
{ accessorKey: 'containerName', title: m.container(), sortable: true, cell: ContainerCell },
{ accessorKey: 'hostIp', title: m.ports_host_ip(), sortable: true, cell: HostIpCell },
{ accessorKey: 'isPublished', title: m.common_status(), sortable: true, cell: PublishedCell }
- ] satisfies ColumnSpec<PortMappingDto>[];
+ ] satisfies ColumnSpec<PortRow>[]);
const mobileFields = [
{ id: 'hostPort', label: m.ports_host_port(), defaultVisible: true },
@@ -70,43 +84,37 @@
];
</script>
-{#snippet HostPortCell({ item }: { item: PortMappingDto })}
+{#snippet HostPortCell({ item }: { item: PortRow })}
<span class={['font-mono text-sm', { 'text-muted-foreground': !item.isPublished }]}>
{formatHostPort(item)}
</span>
{/snippet}
-{#snippet ContainerPortCell({ item }: { item: PortMappingDto })}
+{#snippet ContainerPortCell({ item }: { item: PortRow })}
<span class="font-mono text-sm">{item.containerPort}</span>
{/snippet}
-{#snippet ProtocolCell({ item }: { item: PortMappingDto })}
+{#snippet ProtocolCell({ item }: { item: PortRow })}
<Badge variant="gray">{item.protocol.toUpperCase()}</Badge>
{/snippet}
-{#snippet ContainerCell({ item }: { item: PortMappingDto })}
- <a class="font-medium hover:underline" href="/containers/{item.containerId}">
+{#snippet ContainerCell({ item }: { item: PortRow })}
+ <a class="font-medium hover:underline" href={environmentHref(`/containers/${item.containerId}`, item.environmentId)}>
{item.containerName}
</a>
{/snippet}
-{#snippet HostIpCell({ item }: { item: PortMappingDto })}
+{#snippet HostIpCell({ item }: { item: PortRow })}
<span class={['font-mono text-sm', { 'text-muted-foreground': !item.isPublished }]}>
{formatHostIp(item)}
</span>
{/snippet}
-{#snippet PublishedCell({ item }: { item: PortMappingDto })}
+{#snippet PublishedCell({ item }: { item: PortRow })}
<Badge variant={item.isPublished ? 'sky' : 'gray'}>{item.isPublished ? m.published() : m.ports_exposed_label()}</Badge>
{/snippet}
-{#snippet PortMobileCardSnippet({
- item,
- mobileFieldVisibility
-}: {
- item: PortMappingDto;
- mobileFieldVisibility: MobileFieldVisibility;
-})}
+{#snippet PortMobileCardSnippet({ item, mobileFieldVisibility }: { item: PortRow; mobileFieldVisibility: MobileFieldVisibility })}
<UniversalMobileCard
{item}
icon={(item: PortMappingDto) => ({
@@ -156,7 +164,7 @@
show: mobileFieldVisibility['containerName'] ?? true
}
]}
- onclick={() => void goto(`/containers/${item.containerId}`)}
+ onclick={() => void goto(environmentHref(`/containers/${item.containerId}`, item.environmentId))}
/>
{/snippet}
diff --git a/frontend/src/routes/(app)/networks/topology/+page.svelte b/frontend/src/routes/(app)/networks/topology/+page.svelte
index bf8c85257..e9d99a216 100644
--- a/frontend/src/routes/(app)/networks/topology/+page.svelte
+++ b/frontend/src/routes/(app)/networks/topology/+page.svelte
@@ -43,7 +43,12 @@
]);
</script>
-<ResourcePageLayout title={m.networks_topology_title()} subtitle={m.networks_topology_subtitle()} {actionButtons}>
+<ResourcePageLayout
+ title={m.networks_topology_title()}
+ subtitle={m.networks_topology_subtitle()}
+ {actionButtons}
+ environmentPicker
+>
{#snippet mainContent()}
{#if topology}
<NetworkDiagram {topology} />
diff --git a/frontend/src/routes/(app)/projects/+page.svelte b/frontend/src/routes/(app)/projects/+page.svelte
index 07253a4b6..a15bef171 100644
--- a/frontend/src/routes/(app)/projects/+page.svelte
+++ b/frontend/src/routes/(app)/projects/+page.svelte
@@ -1,8 +1,8 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { page } from '$app/state';
- import { createMutation, createQuery, keepPreviousData } from '@tanstack/svelte-query';
- import { untrack } from 'svelte';
+ import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
+ import { tick, untrack } from 'svelte';
import { toast } from 'svelte-sonner';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
@@ -18,9 +18,19 @@
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import type { ProjectStatusCounts } from '#lib/types/swarm.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
- import { hasPermission } from '#lib/utils/auth.js';
+ import {
+ acrossEnvironmentsNote,
+ actionEnvironments,
+ fetchAcrossEnvironments,
+ hasShownPermission,
+ listScopes,
+ settleAcrossEnvironments,
+ sumAcrossEnvironments,
+ withFailedEnvironments
+ } from '#lib/utils/environments.js';
import ProjectsTable from './components/projects-table.svelte';
+ import { fetchProjectTags } from './projects-table.helpers';
let { data } = $props();
@@ -41,7 +51,8 @@
let baseProjectRequestOptions = $state(untrack(() => withArchivedFilter(data.projectRequestOptions, data.showArchived)));
let selectedIds = $state<string[]>([]);
let isManualRefreshing = $state(false);
- const envId = $derived(environmentStore.selected?.id || '0');
+ const queryClient = useQueryClient();
+ const scope = $derived(environmentStore.shownKey);
const showArchived = $derived(page.url.searchParams.get('archived') === 'true');
const projectRequestOptions = $derived(withArchivedFilter(baseProjectRequestOptions, showArchived));
const countsFallback: ProjectStatusCounts = {
@@ -51,115 +62,155 @@
archivedProjects: 0
};
+ // The load already cached the first page under its key; seeding every key with it would hide other pages and filters.
const projectsQuery = createQuery(() => {
- const queryEnvId = envId;
+ const queryScope = scope;
+ const environments = environmentStore.shown;
+ const options = projectRequestOptions;
return {
- queryKey: queryKeys.projects.list(queryEnvId, projectRequestOptions),
- queryFn: () => projectService.getProjectsForEnvironment(queryEnvId, projectRequestOptions),
- placeholderData: keepPreviousData,
- initialData: data.envId === queryEnvId ? data.projects : undefined,
- select: (value) => ({ envId: queryEnvId, value }),
+ queryKey: queryKeys.projects.list(queryScope, options),
+ queryFn: () =>
+ fetchAcrossEnvironments(environments, options, (id, request, config) =>
+ projectService.getProjectsForEnvironment(id, request, config)
+ ),
+ placeholderData: (previous, query) => {
+ if (query?.queryKey[1] === queryScope) return previous;
+ return undefined;
+ },
+ select: (value) => ({ envId: queryScope, value }),
refetchOnMount: false
};
});
- let projects = $derived(projectsQuery.data?.envId === envId ? projectsQuery.data.value : null);
+ let projects = $derived(projectsQuery.data?.envId === scope ? projectsQuery.data.value : null);
const projectStatusCountsQuery = createQuery(() => {
- const queryEnvId = envId;
+ const queryScope = scope;
+ const environments = environmentStore.shown;
return {
- queryKey: queryKeys.projects.statusCounts(queryEnvId),
- queryFn: () => projectService.getProjectStatusCountsForEnvironment(queryEnvId),
- initialData: data.envId === queryEnvId ? data.projectStatusCounts : undefined,
- select: (value) => ({ envId: queryEnvId, value }),
+ queryKey: queryKeys.projects.statusCounts(queryScope),
+ queryFn: () =>
+ sumAcrossEnvironments(environments, (id, config) => projectService.getProjectStatusCountsForEnvironment(id, config)),
+ initialData: data.scope === queryScope ? data.projectStatusCounts : undefined,
+ select: (value) => ({ envId: queryScope, value }),
refetchOnMount: false
};
});
const projectTagsQuery = createQuery(() => {
- const queryEnvId = envId;
+ const queryScope = scope;
+ const environments = environmentStore.shown;
return {
- queryKey: queryKeys.projects.tags(queryEnvId),
- queryFn: () => projectService.getProjectTagsForEnvironment(queryEnvId),
- initialData: data.envId === queryEnvId ? data.projectTags : undefined,
- select: (value) => ({ envId: queryEnvId, value }),
+ queryKey: queryKeys.projects.tags(queryScope),
+ queryFn: () => fetchProjectTags(environments),
+ initialData: data.scope === queryScope ? data.projectTags : undefined,
+ select: (value) => ({ envId: queryScope, value }),
refetchOnMount: false
};
});
- const projectTags = $derived(projectTagsQuery.data?.envId === envId ? projectTagsQuery.data.value : []);
+ const projectTags = $derived(projectTagsQuery.data?.envId === scope ? projectTagsQuery.data.value.tags : []);
+ const relatedFailures = $derived(
+ [projectStatusCountsQuery.data, projectTagsQuery.data].flatMap((result) =>
+ result?.envId === scope ? result.value.failedEnvironments : []
+ )
+ );
const resourcesReady = $derived(projects !== null);
+ // Tags change rarely, so a refresh reloads them only after an environment failed to return them.
+ const refetchFailedTags = () =>
+ projectTagsQuery.isError || projectTagsQuery.data?.value.failedEnvironments.length ? projectTagsQuery.refetch() : undefined;
useEnvironmentRefresh(() => {
selectedIds = [];
isManualRefreshing = false;
});
- const checkUpdatesMutation = createMutation(() => ({
- mutationKey: queryKeys.projects.checkUpdates(envId),
- 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(requestedEnvId);
+ async function updateEnvironmentProjects(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(requestedEnvId);
- 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;
- for (const user of img.usedBy ?? []) {
- if (user.type === 'project' && user.id) {
- projectIdsWithUpdates.add(user.id);
- }
+ 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;
+ for (const user of img.usedBy ?? []) {
+ if (user.type === 'project' && user.id) {
+ projectIdsWithUpdates.add(user.id);
}
}
+ }
- if (projectIdsWithUpdates.size === 0) {
- return { updated: 0, activityId: extractActivityId(imageCheckResults) };
- }
+ if (projectIdsWithUpdates.size === 0) {
+ return { updated: 0, activityId: extractActivityId(imageCheckResults) };
+ }
- const allProjects = await projectService.getProjectsForEnvironment(requestedEnvId, {
- pagination: { page: 1, limit: 1000 }
- });
- const projectsToUpdate = allProjects.data.filter((p) => projectIdsWithUpdates.has(p.id));
+ 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(
- projectsToUpdate.map(async (proj) => {
- // deployProject with pullPolicy 'always' already pulls fresh images,
- // so no separate pullProjectImages call is needed.
- await projectService.deployProject(proj.id, 'up', { pullPolicy: 'always' });
- return proj.name;
- })
- );
- const failed = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected');
- if (failed.length > 0) {
- const succeeded = results.length - failed.length;
- throw new Error(`${failed.length} project(s) failed to update (${succeeded} succeeded)`);
- }
+ const results = await Promise.allSettled(
+ projectsToUpdate.map(async (proj) => {
+ // deployProject with pullPolicy 'always' already pulls fresh images,
+ // so no separate pullProjectImages call is needed.
+ await projectService.deployProject(proj.id, 'up', { pullPolicy: 'always' }, requestedEnvId);
+ return proj.name;
+ })
+ );
+ const failed = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected');
+ if (failed.length > 0) {
+ const succeeded = results.length - failed.length;
+ throw new Error(`${failed.length} project(s) failed to update (${succeeded} succeeded)`);
+ }
- return { updated: results.length, activityId: extractActivityId(imageCheckResults) };
+ return { updated: results.length, activityId: extractActivityId(imageCheckResults) };
+ }
+
+ const checkUpdatesMutation = createMutation(() => ({
+ mutationKey: queryKeys.projects.checkUpdates(scope),
+ mutationFn: async (_requestedScope: string) => {
+ const results = await settleAcrossEnvironments(
+ actionEnvironments('image-updates:check', 'projects:deploy'),
+ updateEnvironmentProjects
+ );
+ return {
+ updated: results.reduce((total, result) => total + result.value.updated, 0),
+ activityId: results[0]?.value.activityId,
+ environmentIds: results.map(({ environment }) => environment.id)
+ };
},
- onSuccess: async (result, requestedEnvId) => {
+ onSuccess: async (result, requestedScope) => {
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);
}
- if (requestedEnvId === envId) {
+ // The shown list refetches itself; the affected environments' other cached lists are marked stale.
+ await Promise.all(
+ listScopes(result.environmentIds)
+ .filter((listScope) => listScope !== requestedScope)
+ .flatMap((listScope) => [
+ queryClient.invalidateQueries({ queryKey: ['projects', listScope] }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.projects.statusCounts(listScope) })
+ ])
+ );
+ if (requestedScope === scope) {
await Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch()]);
}
},
- onError: (error, requestedEnvId) => {
+ onError: (error, requestedScope) => {
toast.error(error instanceof Error ? error.message : m.containers_check_updates_failed());
- if (requestedEnvId === envId) {
+ if (requestedScope === scope) {
void Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch()]);
}
}
}));
const projectStatusCounts = $derived(
- projectStatusCountsQuery.data?.envId === envId ? projectStatusCountsQuery.data.value : countsFallback
+ projectStatusCountsQuery.data?.envId === scope ? projectStatusCountsQuery.data.value : countsFallback
);
const totalCompose = $derived(projectStatusCounts.totalProjects);
const runningCompose = $derived(projectStatusCounts.runningProjects);
@@ -170,23 +221,24 @@
function handleCheckForUpdates() {
openConfirmDialog({
title: m.compose_update_projects(),
- message: m.compose_update_projects_confirm_message(),
+ message:
+ `${m.compose_update_projects_confirm_message()} ${acrossEnvironmentsNote(actionEnvironments('image-updates:check', 'projects:deploy'))}`.trim(),
confirm: {
label: m.compose_update_projects(),
destructive: false,
- action: () => checkUpdatesMutation.mutate(envId)
+ action: () => checkUpdatesMutation.mutate(scope)
}
});
}
async function refreshCompose() {
if (isRefreshBlocked) return;
- const requestedEnvId = envId;
+ const requestedScope = scope;
isManualRefreshing = true;
try {
- await Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch()]);
+ await Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch(), refetchFailedTags()]);
} finally {
- if (requestedEnvId === envId) {
+ if (requestedScope === scope) {
isManualRefreshing = false;
}
}
@@ -202,8 +254,8 @@
await goto(`${url.pathname}${url.search}`, { reset: false, replace: true });
}
- const canCreateProject = $derived(hasPermission('projects:create', envId));
- const canDeployProject = $derived(hasPermission('projects:deploy', envId));
+ const canCreateProject = $derived(hasShownPermission('projects:create'));
+ const canDeployProject = $derived(hasShownPermission('projects:deploy'));
const actionButtons: ActionButton[] = $derived.by(() => {
const buttons: ActionButton[] = [];
@@ -282,7 +334,7 @@
{#snippet mainContent()}
{#if projects}
<ProjectsTable
- {projects}
+ projects={withFailedEnvironments(projects, relatedFailures)}
emptyState={projectsEmptyState}
bind:selectedIds
requestOptions={projectRequestOptions}
@@ -290,10 +342,16 @@
availableTags={projectTags}
onToggleArchived={toggleArchived}
onRefreshData={async (options) => {
- const requestedEnvId = envId;
+ const requestedScope = scope;
baseProjectRequestOptions = withArchivedFilter(options, showArchived);
- await Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch()]);
- if (requestedEnvId !== envId) {
+ // Let the query switch to the new options first; the refetch then joins its fetch.
+ await tick();
+ await Promise.all([
+ projectsQuery.refetch({ cancelRefetch: false }),
+ projectStatusCountsQuery.refetch(),
+ refetchFailedTags()
+ ]);
+ if (requestedScope !== scope) {
selectedIds = [];
}
}}
diff --git a/frontend/src/routes/(app)/projects/+page.ts b/frontend/src/routes/(app)/projects/+page.ts
index 34c5f0fb5..9608ba746 100644
--- a/frontend/src/routes/(app)/projects/+page.ts
+++ b/frontend/src/routes/(app)/projects/+page.ts
@@ -3,14 +3,17 @@ import { projectService } from '#lib/services/project-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { throwPageLoadError } from '#lib/utils/api.js';
+import { fetchAcrossEnvironments, sumAcrossEnvironments } from '#lib/utils/environments.js';
import { resolveInitialTableRequest } from '#lib/utils/tables.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
+import { fetchProjectTags } from './projects-table.helpers';
export const load: PageLoad = async ({ parent, url }) => {
const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const environments = await environmentStore.getShownEnvironments();
+ const scope = environmentStore.shownKey;
const showArchived = url.searchParams.get('archived') === 'true';
const projectRequestOptions = resolveInitialTableRequest('arcane-project-table', {
@@ -38,16 +41,20 @@ export const load: PageLoad = async ({ parent, url }) => {
(async () =>
Promise.all([
queryClient.query({
- queryKey: queryKeys.projects.list(envId, projectRequestOptions),
- queryFn: () => projectService.getProjectsForEnvironment(envId, projectRequestOptions)
+ queryKey: queryKeys.projects.list(scope, projectRequestOptions),
+ queryFn: () =>
+ fetchAcrossEnvironments(environments, projectRequestOptions, (id, request, config) =>
+ projectService.getProjectsForEnvironment(id, request, config)
+ )
}),
queryClient.query({
- queryKey: queryKeys.projects.statusCounts(envId),
- queryFn: () => projectService.getProjectStatusCountsForEnvironment(envId)
+ queryKey: queryKeys.projects.statusCounts(scope),
+ queryFn: () =>
+ sumAcrossEnvironments(environments, (id, config) => projectService.getProjectStatusCountsForEnvironment(id, config))
}),
queryClient.query({
- queryKey: queryKeys.projects.tags(envId),
- queryFn: () => projectService.getProjectTagsForEnvironment(envId)
+ queryKey: queryKeys.projects.tags(scope),
+ queryFn: () => fetchProjectTags(environments)
})
]))()
);
@@ -59,5 +66,5 @@ export const load: PageLoad = async ({ parent, url }) => {
[projects, projectStatusCounts, projectTags] = operationResult.data;
}
- return { envId, projects, projectRequestOptions, projectStatusCounts, projectTags, showArchived };
+ return { scope, projects, projectRequestOptions, projectStatusCounts, projectTags, showArchived };
};
diff --git a/frontend/src/routes/(app)/projects/[projectId]/+layout.svelte b/frontend/src/routes/(app)/projects/[projectId]/+layout.svelte
new file mode 100644
index 000000000..ca2993bdf
--- /dev/null
+++ b/frontend/src/routes/(app)/projects/[projectId]/+layout.svelte
@@ -0,0 +1,12 @@
+<script lang="ts">
+ import { page } from '$app/state';
+
+ import type { LayoutProps } from './$types';
+
+ let { children }: LayoutProps = $props();
+</script>
+
+<!-- The page's editors read their project once, so another project or environment gets a fresh page. -->
+{#key `${page.data['envId']}:${page.params.projectId}`}
+ {@render children()}
+{/key}
diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
index 2aa696239..eedf27e7c 100644
--- a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
@@ -26,6 +26,7 @@
import { Switch } from '#lib/components/ui/switch/index.js';
import * as Tabs from '#lib/components/ui/tabs/index.js';
import WorkspaceFileTreePanel from '#lib/components/workspace-file-tree-panel.svelte';
+ import { useEnvironmentSettings } from '#lib/hooks/use-environment-settings.svelte.js';
import { useUrlTab } from '#lib/hooks/use-url-tab.svelte.js';
import {
ArrowLeftIcon,
@@ -53,11 +54,9 @@
import { gitOpsSyncService } from '#lib/services/gitops-sync-service.js';
import { projectService } from '#lib/services/project-service.js';
import { projectWorkspaceService } from '#lib/services/project-workspace-service.js';
- import settingsStore from '#lib/stores/config-store.svelte.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { ProjectEditorLayout } from '#lib/types/auth.js';
import type { ProjectWorkspaceFileChange, ProjectWorkspaceFileContent } from '#lib/types/project-workspace.js';
- import type { IncludeFile, Project, ProjectTagColor, ProjectTagOption } from '#lib/types/swarm.js';
+ import type { IncludeFile, Project, ProjectTagColor } from '#lib/types/swarm.js';
import { cn } from '#lib/utils.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
@@ -70,6 +69,7 @@
type ProjectEditorLayoutMode
} from '#lib/utils/compose-flow.js';
import { getStatusVariant, getThemedIconUrl } from '#lib/utils/docker.js';
+ import { environmentName, listScopes } from '#lib/utils/environments.js';
import { capitalizeFirstLetter } from '#lib/utils/formatting.js';
import { gitOpsComposeEditUrl, gitOpsFileEditUrl, gitOpsProjectUrl } from '#lib/utils/gitops.js';
import { toGitRouteUrl, toSafeHref } from '#lib/utils/navigation.js';
@@ -100,6 +100,7 @@
planProjectWorkspaceFileRename,
validateProjectWorkspaceFileName
} from '../components/project-workspace-utils';
+ import { fetchProjectTags, type ProjectTagOptions } from '../projects-table.helpers';
let { data } = $props();
let projectId = $derived(data.projectId);
@@ -119,7 +120,7 @@
archiving: false
});
- const envId = $derived(environmentStore.selected?.id || '0');
+ const envId = $derived(data.envId);
const canUpdateProject = $derived(hasPermission('projects:update', envId));
const canArchiveProject = $derived(hasPermission('projects:archive', envId));
const canViewProjectLogs = $derived(hasPermission('projects:logs', envId));
@@ -139,7 +140,9 @@
let projectWorkspaceStagedUploadedText = $state<Record<string, string>>({});
let projectWorkspaceFilePromises: Record<string, Promise<IncludeFile | ProjectWorkspaceFileContent> | undefined> = {};
const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));
- const projectWorkspaceMaxFileSizeMb = $derived(settingsStore.current?.projectWorkspaceMaxFileSizeMb ?? 10);
+ // A project from another environment follows that environment's upload limit.
+ const projectSettings = useEnvironmentSettings(() => envId);
+ const projectWorkspaceMaxFileSizeMb = $derived(projectSettings.current?.projectWorkspaceMaxFileSizeMb ?? 10);
const projectDetailQuery = createQuery(() => ({
queryKey: queryKeys.projects.detail(envId, projectId),
@@ -149,20 +152,22 @@
}));
const projectTagsQuery = createQuery(() => ({
queryKey: queryKeys.projects.tags(envId),
- queryFn: () => projectService.getProjectTagsForEnvironment(envId)
+ queryFn: () => fetchProjectTags([{ id: envId, name: environmentName(envId) }])
}));
- const availableProjectTags = $derived(projectTagsQuery.data ?? []);
+ const availableProjectTags = $derived(projectTagsQuery.data?.tags ?? []);
async function handleProjectTagToggle(name: string, attached: boolean, color: ProjectTagColor) {
- const response = await projectService.updateProjectTag(projectId, name, attached, color);
+ const response = await projectService.updateProjectTag(projectId, name, attached, color, envId);
queryClient.setQueryData<Project>(queryKeys.projects.detail(envId, projectId), (current) =>
current ? { ...current, tags: response.tags } : current
);
if (attached) {
- queryClient.setQueryData<ProjectTagOption[]>(queryKeys.projects.tags(envId), (current = []) =>
- current.some((tag) => tag.name === name)
- ? current
- : [...current, { name, color }].sort((a, b) => a.name.localeCompare(b.name))
+ queryClient.setQueryData<ProjectTagOptions>(
+ queryKeys.projects.tags(envId),
+ (current = { tags: [], failedEnvironments: [] }) =>
+ current.tags.some((tag) => tag.name === name)
+ ? current
+ : { ...current, tags: [...current.tags, { name, color }].sort((a, b) => a.name.localeCompare(b.name)) }
);
}
return response.tags;
@@ -635,7 +640,7 @@
}
async function syncProjectQueries(updatedProject: Project) {
- const currentEnvId = envId ?? (await environmentStore.getCurrentEnvironmentId());
+ const currentEnvId = envId;
// The save response is slim (no directory walks), so merge it into the
// cached detail instead of replacing it wholesale.
@@ -644,21 +649,25 @@
(old: Project | undefined) => ({ ...old, ...updatedProject }) as Project
);
await Promise.all([
- queryClient.invalidateQueries({ queryKey: ['projects', currentEnvId] }),
- queryClient.invalidateQueries({ queryKey: queryKeys.projects.statusCounts(currentEnvId) })
+ ...listScopes([currentEnvId]).flatMap((scope) => [
+ queryClient.invalidateQueries({ queryKey: ['projects', scope] }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.projects.statusCounts(scope) })
+ ])
]);
}
const checkProjectUpdatesMutation = createMutation(() => ({
mutationKey: queryKeys.projects.detailCheckUpdates(envId ?? '0', projectId),
- mutationFn: () => projectService.checkUpdates(projectId),
+ mutationFn: () => projectService.checkUpdates(projectId, envId),
onSuccess: async (result) => {
- const currentEnvId = envId ?? (await environmentStore.getCurrentEnvironmentId());
+ const currentEnvId = envId;
summarizeUpdateCheckResult(result);
await Promise.all([
refreshProjectDetails(),
- queryClient.invalidateQueries({ queryKey: ['projects', currentEnvId] }),
- queryClient.invalidateQueries({ queryKey: queryKeys.projects.statusCounts(currentEnvId) })
+ ...listScopes([currentEnvId]).flatMap((scope) => [
+ queryClient.invalidateQueries({ queryKey: ['projects', scope] }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.projects.statusCounts(scope) })
+ ])
]);
},
onError: () => {
@@ -791,7 +800,8 @@
namePayload,
composePayload,
envPayload,
- overridePayload
+ overridePayload,
+ envId
);
rebaseEditorDraft(updatedProject, { preserveProjectWorkspaceContents: true });
await syncProjectQueries(updatedProject);
@@ -833,7 +843,7 @@
isLoading.archiving = true;
try {
const result = await tryCatch(
- archiving ? projectService.archiveProject(project.id) : projectService.unarchiveProject(project.id)
+ archiving ? projectService.archiveProject(project.id, envId) : projectService.unarchiveProject(project.id, envId)
);
await handleApiResultWithCallbacks({
result,
@@ -841,10 +851,12 @@
onSuccess: async () => {
toast.success(archiving ? m.compose_archive_success() : m.compose_unarchive_success());
await refreshProjectDetails();
- const currentEnvId = envId ?? (await environmentStore.getCurrentEnvironmentId());
+ const currentEnvId = envId;
await Promise.all([
- queryClient.invalidateQueries({ queryKey: ['projects', currentEnvId] }),
- queryClient.invalidateQueries({ queryKey: queryKeys.projects.statusCounts(currentEnvId) })
+ ...listScopes([currentEnvId]).flatMap((scope) => [
+ queryClient.invalidateQueries({ queryKey: ['projects', scope] }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.projects.statusCounts(scope) })
+ ])
]);
}
});
@@ -1353,7 +1365,7 @@
async function refreshProjectDetails(options: RefreshProjectDetailsOptions = {}) {
if (!projectId) return;
await handleApiResultWithCallbacks({
- result: await tryCatch(projectService.getProject(projectId)),
+ result: await tryCatch(projectService.getProjectForEnvironment(envId, projectId)),
message: m.common_refresh_failed({ resource: m.project() }),
onSuccess: async (updatedProject) => {
if (options.forceRebaseDraft || !hasChanges) {
@@ -1810,6 +1822,7 @@
<ProjectServicesPanel
services={project.runtimeServices}
{projectId}
+ environmentId={envId}
updateInfoByRef={project.updateInfo?.updateInfoByRef}
onRefresh={() => refreshProjectDetails()}
/>
@@ -1817,7 +1830,7 @@
{#snippet second()}
<div class="flex h-full min-h-0 flex-col overflow-hidden">
{#key project.id}
- <ProjectsLogsPanel projectId={project.id} bind:autoScroll={autoScrollStackLogs} />
+ <ProjectsLogsPanel projectId={project.id} environmentId={envId} bind:autoScroll={autoScrollStackLogs} />
{/key}
</div>
{/snippet}
@@ -1828,6 +1841,7 @@
<ProjectServicesPanel
services={project.runtimeServices}
{projectId}
+ environmentId={envId}
updateInfoByRef={project.updateInfo?.updateInfoByRef}
onRefresh={() => refreshProjectDetails()}
/>
@@ -2165,6 +2179,7 @@
/>
<ProjectUpdateItem
updateInfo={project.updateInfo}
+ environmentId={envId}
onCheck={handleCheckProjectUpdates}
checking={checkProjectUpdatesMutation.isPending}
disabled={!!project.isArchived || composeActionsBlocked}
@@ -2235,6 +2250,7 @@
{#snippet headerActions()}
<ActionButtons
id={project.id}
+ environmentId={envId}
name={project.name}
type="project"
itemState={project.status}
diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.ts b/frontend/src/routes/(app)/projects/[projectId]/+page.ts
index 50e7f0231..71f667ca8 100644
--- a/frontend/src/routes/(app)/projects/[projectId]/+page.ts
+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.ts
@@ -4,8 +4,8 @@ import { queryKeys } from '#lib/query/query-keys.js';
import { projectService } from '#lib/services/project-service.js';
import { projectWorkspaceService } from '#lib/services/project-workspace-service.js';
import { variableService } from '#lib/services/variable-service.js';
-import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { throwPageLoadError } from '#lib/utils/api.js';
+import { resolveDetailEnvironmentId } from '#lib/utils/environments.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
@@ -27,9 +27,9 @@ async function loadGlobalVariables(queryClient: QueryClient) {
});
}
-export const load: PageLoad = async ({ params, parent }) => {
+export const load: PageLoad = async ({ params, parent, url }) => {
const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const envId = await resolveDetailEnvironmentId(url);
type ProjectData = Awaited<ReturnType<typeof projectService.getProjectForEnvironment>>;
@@ -70,6 +70,7 @@ export const load: PageLoad = async ({ params, parent }) => {
};
return {
+ envId,
projectId: params.projectId,
project,
editorState,
diff --git a/frontend/src/routes/(app)/projects/components/project-logs-panel.svelte b/frontend/src/routes/(app)/projects/components/project-logs-panel.svelte
index cc2b1921b..516a82e3b 100644
--- a/frontend/src/routes/(app)/projects/components/project-logs-panel.svelte
+++ b/frontend/src/routes/(app)/projects/components/project-logs-panel.svelte
@@ -9,9 +9,11 @@
let {
projectId,
+ environmentId,
autoScroll = $bindable()
}: {
projectId: string;
+ environmentId: string;
autoScroll: boolean;
} = $props();
@@ -83,6 +85,7 @@
bind:this={viewer}
bind:autoScroll
{projectId}
+ {environmentId}
tailLines={preferences.tailLines}
bind:showParsedJson={preferences.showParsedJson}
showStreamLabels={preferences.showStreamLabels}
diff --git a/frontend/src/routes/(app)/projects/components/project-services-panel.svelte b/frontend/src/routes/(app)/projects/components/project-services-panel.svelte
index 0216652e5..30c9113d2 100644
--- a/frontend/src/routes/(app)/projects/components/project-services-panel.svelte
+++ b/frontend/src/routes/(app)/projects/components/project-services-panel.svelte
@@ -13,7 +13,6 @@
import { StartIcon, StopIcon, RefreshIcon, TrashIcon, InspectIcon, LayersIcon, BoxIcon, HealthIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import { projectService } from '#lib/services/project-service.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { ImageUpdateData } from '#lib/types/docker.js';
import type { RuntimeService } from '#lib/types/swarm.js';
import { cn } from '#lib/utils.js';
@@ -22,22 +21,24 @@
import { hasPermission } from '#lib/utils/auth.js';
import { confirmAndRemoveContainer, runContainerLifecycleAction } from '#lib/utils/container-actions.js';
import { getThemedIconUrl, parseImageRef } from '#lib/utils/docker.js';
+ import { environmentHref } from '#lib/utils/environments.js';
import { tryCatch } from '#lib/utils/try-catch.js';
interface Props {
services?: RuntimeService[];
projectId?: string;
+ environmentId: string;
updateInfoByRef?: Record<string, ImageUpdateData>;
onRefresh?: () => Promise<void>;
}
- let { services = [], projectId, updateInfoByRef = {}, onRefresh }: Props = $props();
+ let { services = [], projectId, environmentId, updateInfoByRef = {}, onRefresh }: Props = $props();
function serviceImageRef(service: RuntimeService): string {
return service.serviceConfig?.image || service.image || '';
}
- const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const currentEnvId = $derived(environmentId);
const canStartContainer = $derived(hasPermission('containers:start', currentEnvId));
const canStopContainer = $derived(hasPermission('containers:stop', currentEnvId));
const canRestartProject = $derived(hasPermission('projects:restart', currentEnvId));
@@ -85,14 +86,15 @@
function getContainerUrl(service: RuntimeService): string {
if (!service.containerId) return '#';
return projectId
- ? `/containers/${service.containerId}?from=project&projectId=${projectId}`
- : `/containers/${service.containerId}`;
+ ? environmentHref(`/containers/${service.containerId}?from=project&projectId=${projectId}`, environmentId)
+ : environmentHref(`/containers/${service.containerId}`, environmentId);
}
async function performContainerAction(action: 'start' | 'stop' | 'restart', id: string) {
await runContainerLifecycleAction({
action,
containerId: id,
+ environmentId,
setStatus: (status) => {
actionStatus[id] = status;
},
@@ -112,7 +114,7 @@
const operationResult = await tryCatch(
(async () => {
await handleApiResultWithCallbacks({
- result: await tryCatch(projectService.restartProject(projectId, [item.name])),
+ result: await tryCatch(projectService.restartProject(projectId, [item.name], environmentId)),
message: m.containers_restart_failed(),
setLoadingState: (value) => {
actionStatus[id] = value ? 'restarting' : '';
@@ -137,6 +139,7 @@
confirmAndRemoveContainer({
containerId: id,
containerName: name,
+ environmentId,
setStatus: (status) => {
actionStatus[id] = status;
},
@@ -185,7 +188,13 @@
{#if serviceImageRef(item)}
{@const imageRef = serviceImageRef(item)}
{@const parsed = parseImageRef(imageRef)}
- <ImageUpdateItem updateInfo={updateInfoByRef[imageRef]} {imageRef} repo={parsed.repo} tag={parsed.tag} />
+ <ImageUpdateItem
+ updateInfo={updateInfoByRef[imageRef]}
+ {imageRef}
+ repo={parsed.repo}
+ tag={parsed.tag}
+ {environmentId}
+ />
{/if}
{#if item.containerId}
<RowActionsMenu triggerClass="size-6 shrink-0 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100">
diff --git a/frontend/src/routes/(app)/projects/components/projects-table.svelte b/frontend/src/routes/(app)/projects/components/projects-table.svelte
index 9c0f92f69..807df96af 100644
--- a/frontend/src/routes/(app)/projects/components/projects-table.svelte
+++ b/frontend/src/routes/(app)/projects/components/projects-table.svelte
@@ -6,6 +6,7 @@
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import ActionMenuItem from '#lib/components/arcane-table/cells/action-menu-item.svelte';
+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';
import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '#lib/components/arcane-table/index.js';
import { UniversalMobileCard } from '#lib/components/arcane-table/index.js';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
@@ -34,6 +35,14 @@
getProjectUpdateTooltip,
getProjectUpdateVariant
} from '#lib/utils/docker.js';
+ import {
+ environmentHref,
+ fetchAcrossEnvironments,
+ hasShownPermission,
+ rowKey,
+ type EnvironmentPage,
+ type EnvironmentRow
+ } from '#lib/utils/environments.js';
import { capitalizeFirstLetter, formatDateTimeShort } from '#lib/utils/formatting.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import { summarizeUpdateCheckResult } from '#lib/utils/update-actions.js';
@@ -41,6 +50,8 @@
import { createProjectActions } from '../projects-table.actions';
import type { ActionStatus } from '../projects-table.helpers';
+ type ProjectRow = EnvironmentRow<Project>;
+
let {
projects = $bindable(),
selectedIds = $bindable(),
@@ -52,7 +63,7 @@
availableTags = [],
emptyState
}: {
- projects: Paginated<Project>;
+ projects: EnvironmentPage<Paginated<Project>>;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
withoutFilters?: boolean;
@@ -79,23 +90,25 @@
await onRefreshData(options);
return;
}
- projects = await projectService.getProjects(options);
+ projects = await fetchAcrossEnvironments(environmentStore.shown, options, (id, request, config) =>
+ projectService.getProjectsForEnvironment(id, request, config)
+ );
}
- async function handleCheckProjectUpdates(project: Project) {
- if (checkingProjectIds[project.id]) {
+ async function handleCheckProjectUpdates(project: ProjectRow) {
+ if (checkingProjectIds[rowKey(project)]) {
return;
}
checkingProjectIds = {
...checkingProjectIds,
- [project.id]: true
+ [rowKey(project)]: true
};
try {
const operationResult = await tryCatch(
(async () => {
- const result = await projectService.checkUpdates(project.id);
+ const result = await projectService.checkUpdates(project.id, project.environmentId);
summarizeUpdateCheckResult(result);
await refreshProjects(requestOptions);
})()
@@ -106,19 +119,19 @@
} finally {
checkingProjectIds = {
...checkingProjectIds,
- [project.id]: false
+ [rowKey(project)]: false
};
}
}
- async function handleTagToggle(project: Project, name: string, attached: boolean, color: ProjectTagColor) {
- const response = await projectService.updateProjectTag(project.id, name, attached, color);
+ async function handleTagToggle(project: ProjectRow, name: string, attached: boolean, color: ProjectTagColor) {
+ const response = await projectService.updateProjectTag(project.id, name, attached, color, project.environmentId);
if (attached && !tagCatalog.some((tag) => tag.name === name)) {
tagCatalog = [...tagCatalog, { name, color }].sort((a, b) => a.name.localeCompare(b.name));
}
projects = {
...projects,
- data: projects.data.map((item) => (item.id === project.id ? { ...item, tags: response.tags } : item))
+ data: projects.data.map((item) => (rowKey(item) === rowKey(project) ? { ...item, tags: response.tags } : item))
};
return response.tags;
}
@@ -137,12 +150,9 @@
}
let mobileFieldVisibility = $state<Record<string, boolean>>({});
- const envId = $derived(environmentStore.selected?.id);
- const currentEnvId = $derived(environmentStore.selected?.id || '0');
- const canUpdateProject = $derived(hasPermission('projects:update', currentEnvId));
- const canDeployProject = $derived(hasPermission('projects:deploy', currentEnvId));
- const canDownProject = $derived(hasPermission('projects:down', currentEnvId));
- const canArchiveProject = $derived(hasPermission('projects:archive', currentEnvId));
+ const canDeployProject = $derived(hasShownPermission('projects:deploy'));
+ const canDownProject = $derived(hasShownPermission('projects:down'));
+ const canArchiveProject = $derived(hasShownPermission('projects:archive'));
const {
performProjectAction,
@@ -159,12 +169,11 @@
selectedIds = next;
},
actionStatus,
- isBulkLoading,
- getEnvId: () => envId
+ isBulkLoading
});
const isAnyLoading = $derived(hasAnyLoadingState(actionStatus, isBulkLoading));
- const selectedProjects = $derived.by(() => (projects?.data ?? []).filter((project) => selectedIds?.includes(project.id)));
+ const selectedProjects = $derived.by(() => (projects?.data ?? []).filter((project) => selectedIds?.includes(rowKey(project))));
const hasRedeployDisabledSelection = $derived.by(() => selectedProjects.some((project) => project.redeployDisabled));
const hasArchivedSelection = $derived.by(() => selectedProjects.some((project) => project.isArchived));
const isProjectArchiveBlocked = (project: Project) =>
@@ -181,6 +190,7 @@
const columns = $derived.by(
() =>
[
+ ...environmentColumns<ProjectRow>(),
{ accessorKey: 'id', title: m.common_id(), hidden: true },
{ accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },
{
@@ -203,7 +213,7 @@
{ accessorKey: 'createdAt', title: m.common_created(), sortable: true, cell: CreatedCell },
{ accessorKey: 'serviceCount', title: m.services(), sortable: true },
{ id: 'label', accessorFn: () => '', title: m.common_labels(), hidden: true }
- ] satisfies ColumnSpec<Project>[]
+ ] satisfies ColumnSpec<ProjectRow>[]
);
const mobileFields = [
@@ -283,7 +293,7 @@
]);
</script>
-{#snippet NameCell({ item }: { item: Project })}
+{#snippet NameCell({ item }: { item: ProjectRow })}
<div class="flex items-center gap-2">
<IconImage
src={getThemedIconUrl(item, mode.current)}
@@ -292,31 +302,31 @@
class="size-6"
containerClass="size-8"
/>
- <a class="font-medium hover:underline" href="/projects/{item.id}">{item.name}</a>
+ <a class="font-medium hover:underline" href={environmentHref(`/projects/${item.id}`, item.environmentId)}>{item.name}</a>
{#if item.isArchived}
<span class="rounded bg-muted px-1.5 py-0.5 text-xs font-medium text-muted-foreground">{m.projects_archived_badge()}</span>
{/if}
</div>
{/snippet}
-{#snippet TagsCell({ item }: { item: Project })}
+{#snippet TagsCell({ item }: { item: ProjectRow })}
<ProjectTagEditor
tags={item.tags ?? []}
availableTags={tagCatalog}
- canEdit={canUpdateProject && !item.isDiscovered}
+ canEdit={hasPermission('projects:update', item.environmentId) && !item.isDiscovered}
onToggle={(name, attached, color) => handleTagToggle(item, name, attached, color)}
/>
{/snippet}
-{#snippet DirectoryCell({ item }: { item: Project })}
+{#snippet DirectoryCell({ item }: { item: ProjectRow })}
<span class="block max-w-88 truncate text-muted-foreground">{item.relativePath ?? item.dirName ?? item.path}</span>
{/snippet}
-{#snippet ProviderCell({ item }: { item: Project })}
+{#snippet ProviderCell({ item }: { item: ProjectRow })}
<div class="flex items-center gap-2">
{#if item.gitOpsManagedBy}
<GitBranchIcon class="size-4" />
- <a class="font-medium hover:underline" href="/environments/{envId}/gitops">
+ <a class="font-medium hover:underline" href="/environments/{item.environmentId}/gitops">
{m.git()}
</a>
{:else}
@@ -334,7 +344,7 @@
</span>
{/snippet}
-{#snippet StatusCell({ item }: { item: Project })}
+{#snippet StatusCell({ item }: { item: ProjectRow })}
{@const statusTooltip = getStatusTooltip(item)}
{#if statusTooltip}
<ArcaneTooltip.Root>
@@ -355,11 +365,12 @@
{/if}
{/snippet}
-{#snippet UpdatesCell({ item }: { item: Project })}
+{#snippet UpdatesCell({ item }: { item: ProjectRow })}
<ProjectUpdateItem
updateInfo={item.updateInfo}
+ environmentId={item.environmentId}
onCheck={() => handleCheckProjectUpdates(item)}
- checking={!!checkingProjectIds[item.id]}
+ checking={!!checkingProjectIds[rowKey(item)]}
disabled={!!item.isArchived || !!item.configurationError?.blocksOperations}
class="mr-2"
/>
@@ -373,21 +384,21 @@
item,
mobileFieldVisibility
}: {
- item: Project;
+ item: ProjectRow;
mobileFieldVisibility: MobileFieldVisibility;
})}
<UniversalMobileCard
{item}
- icon={(item: Project) => ({
+ icon={(item: ProjectRow) => ({
component: FolderOpenIcon,
variant: item.status === 'running' ? 'emerald' : item.status === 'exited' ? 'red' : 'amber',
imageUrl: getThemedIconUrl(item, mode.current) ?? undefined,
alt: item.name
})}
- title={(item: Project) => item.name}
- subtitle={(item: Project) => ((mobileFieldVisibility['id'] ?? true) ? item.id : null)}
+ title={(item: ProjectRow) => item.name}
+ subtitle={(item: ProjectRow) => ((mobileFieldVisibility['id'] ?? true) ? item.id : null)}
badges={[
- (item: Project) =>
+ (item: ProjectRow) =>
(mobileFieldVisibility['status'] ?? true)
? {
variant: getStatusVariant(item.status),
@@ -395,14 +406,14 @@
tooltip: getStatusTooltip(item)
}
: null,
- (item: Project) =>
+ (item: ProjectRow) =>
item.isArchived
? {
variant: 'gray' as const,
text: m.projects_archived_badge()
}
: null,
- (item: Project) =>
+ (item: ProjectRow) =>
(mobileFieldVisibility['updates'] ?? true)
? {
variant: getProjectUpdateVariant(item.updateInfo),
@@ -415,13 +426,13 @@
{
label: m.common_tags(),
type: 'component',
- getValue: (item: Project) => ({ item }),
+ getValue: (item: ProjectRow) => ({ item }),
component: TagsCell,
show: mobileFieldVisibility['tags'] ?? true
},
{
label: m.common_working_directory(),
- getValue: (item: Project) => item.relativePath ?? item.dirName ?? item.path,
+ getValue: (item: ProjectRow) => item.relativePath ?? item.dirName ?? item.path,
icon: FolderOpenIcon,
iconVariant: 'gray' as const,
show: mobileFieldVisibility['directory'] ?? true
@@ -429,7 +440,7 @@
{
label: m.projects_col_provider(),
type: 'component',
- getValue: (item: Project) => ({
+ getValue: (item: ProjectRow) => ({
icon: item.gitOpsManagedBy ? GitBranchIcon : ProjectsIcon,
text: item.gitOpsManagedBy ? m.git() : m.local()
}),
@@ -438,7 +449,7 @@
},
{
label: m.services(),
- getValue: (item: Project) => {
+ getValue: (item: ProjectRow) => {
const serviceCount = item.serviceCount ? Number(item.serviceCount) : (item.services?.length ?? 0);
return `${serviceCount} ${Number(serviceCount) === 1 ? 'service' : 'services'}`;
},
@@ -450,17 +461,18 @@
footer={(mobileFieldVisibility['createdAt'] ?? true) && item.createdAt
? {
label: m.common_created(),
- getValue: (item: Project) => formatDateTimeShort(item.createdAt),
+ getValue: (item: ProjectRow) => formatDateTimeShort(item.createdAt),
icon: CalendarIcon
}
: undefined}
rowActions={RowActions}
- onclick={() => goto(`/projects/${item.id}`)}
+ onclick={() => goto(environmentHref(`/projects/${item.id}`, item.environmentId))}
/>
{/snippet}
-{#snippet RowActions({ item }: { item: Project })}
- {@const status = actionStatus[item.id]}
+{#snippet RowActions({ item }: { item: ProjectRow })}
+ {@const status = actionStatus[rowKey(item)]}
+ {@const envId = item.environmentId}
{@const configurationBlocked = !!item.configurationError?.blocksOperations}
{@const lifecycleDisabled = item.isArchived || isAnyLoading || configurationBlocked}
{@const archivedTitle = configurationBlocked
@@ -469,14 +481,14 @@
? m.projects_archived_badge()
: undefined}
<RowActionsMenu>
- <DropdownMenu.Item onclick={() => goto(`/projects/${item.id}`)} disabled={isAnyLoading}>
+ <DropdownMenu.Item onclick={() => goto(environmentHref(`/projects/${item.id}`, envId))} disabled={isAnyLoading}>
<EditIcon class="size-4" />
{m.common_edit()}
</DropdownMenu.Item>
- {#if item.gitOpsManagedBy && canUpdateProject}
+ {#if item.gitOpsManagedBy && hasPermission('projects:update', envId)}
<ActionMenuItem
- onclick={() => handleSyncFromGit(item.id, item.gitOpsManagedBy!)}
+ onclick={() => handleSyncFromGit(item.id, item.gitOpsManagedBy!, envId)}
disabled={isAnyLoading}
icon={RefreshIcon}
label={m.git_sync_from_git()}
@@ -487,9 +499,9 @@
<DropdownMenu.Separator />
{#if item.status !== 'running'}
- <IfPermitted perm="projects:deploy" envId={currentEnvId}>
+ <IfPermitted perm="projects:deploy" {envId}>
<ActionMenuItem
- onclick={() => performProjectAction('start', item.id)}
+ onclick={() => performProjectAction('start', item.id, envId)}
disabled={lifecycleDisabled}
title={archivedTitle}
icon={StartIcon}
@@ -498,9 +510,9 @@
/>
</IfPermitted>
{:else}
- <IfPermitted perm="projects:down" envId={currentEnvId}>
+ <IfPermitted perm="projects:down" {envId}>
<ActionMenuItem
- onclick={() => performProjectAction('stop', item.id)}
+ onclick={() => performProjectAction('stop', item.id, envId)}
disabled={lifecycleDisabled}
title={archivedTitle}
icon={StopIcon}
@@ -509,9 +521,9 @@
/>
</IfPermitted>
- <IfPermitted perm="projects:restart">
+ <IfPermitted perm="projects:restart" {envId}>
<ActionMenuItem
- onclick={() => performProjectAction('restart', item.id)}
+ onclick={() => performProjectAction('restart', item.id, envId)}
disabled={lifecycleDisabled}
title={archivedTitle}
icon={RestartIcon}
@@ -521,7 +533,7 @@
</IfPermitted>
{/if}
- <IfPermitted perm="projects:deploy" envId={currentEnvId}>
+ <IfPermitted perm="projects:deploy" {envId}>
{#if item.redeployDisabled}
<DropdownMenu.Item disabled title={m.common_redeploy_disabled_arcane_self()}>
<RedeployIcon class="size-4 opacity-50" />
@@ -529,7 +541,7 @@
</DropdownMenu.Item>
{:else}
<ActionMenuItem
- onclick={() => performProjectAction('redeploy', item.id)}
+ onclick={() => performProjectAction('redeploy', item.id, envId)}
disabled={lifecycleDisabled}
title={archivedTitle}
icon={RedeployIcon}
@@ -541,10 +553,10 @@
<DropdownMenu.Separator />
- <IfPermitted perm="projects:archive" envId={currentEnvId}>
+ <IfPermitted perm="projects:archive" {envId}>
{#if item.isArchived}
<ActionMenuItem
- onclick={() => performProjectAction('unarchive', item.id)}
+ onclick={() => performProjectAction('unarchive', item.id, envId)}
disabled={isAnyLoading}
icon={BoxIcon}
label={m.projects_unarchive()}
@@ -552,7 +564,7 @@
/>
{:else}
<ActionMenuItem
- onclick={() => performProjectAction('archive', item.id)}
+ onclick={() => performProjectAction('archive', item.id, envId)}
disabled={isProjectArchiveBlocked(item) || isAnyLoading}
title={isProjectArchiveBlocked(item) ? m.projects_archive_requires_stopped() : undefined}
icon={BoxIcon}
@@ -562,10 +574,10 @@
{/if}
</IfPermitted>
- <IfPermitted perm="projects:delete">
+ <IfPermitted perm="projects:delete" {envId}>
<ActionMenuItem
destructive
- onclick={() => handleDestroyProject(item.id)}
+ onclick={() => handleDestroyProject(item.id, envId)}
disabled={isAnyLoading}
icon={TrashIcon}
label={m.compose_destroy()}
diff --git a/frontend/src/routes/(app)/projects/new/+page.svelte b/frontend/src/routes/(app)/projects/new/+page.svelte
index 564cd223e..a3ba88d2f 100644
--- a/frontend/src/routes/(app)/projects/new/+page.svelte
+++ b/frontend/src/routes/(app)/projects/new/+page.svelte
@@ -12,20 +12,20 @@
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import TemplateSelectionDialog from '#lib/components/dialogs/template-selection-dialog.svelte';
import EditorTabStrip from '#lib/components/editor-tab-strip.svelte';
+ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';
import ProjectTagEditor from '#lib/components/project-tag-editor.svelte';
import ResizableSplit from '#lib/components/resizable-split.svelte';
import * as Alert from '#lib/components/ui/alert/index.js';
import { Switch } from '#lib/components/ui/switch/index.js';
import { WorkspaceDraftState } from '#lib/components/workspace-editor/workspace-draft-state.svelte.js';
import WorkspaceFileTreePanel from '#lib/components/workspace-file-tree-panel.svelte';
+ import { useEnvironmentSettings } from '#lib/hooks/use-environment-settings.svelte.js';
import { ArrowLeftIcon } from '#lib/icons/index.js';
import { AlertIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { containerService } from '#lib/services/container-service.js';
import { projectService } from '#lib/services/project-service.js';
- import settingsStore from '#lib/stores/config-store.svelte.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { ProjectTag } from '#lib/types/swarm.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { extractApiErrorMessage } from '#lib/utils/api.js';
@@ -40,6 +40,7 @@
templateNameSlug,
type ProjectEditorLayoutMode
} from '#lib/utils/compose-flow.js';
+ import { destinationEnvironmentId, environmentHref, environmentName } from '#lib/utils/environments.js';
import { preventDefault, createForm } from '#lib/utils/settings.svelte.js';
import {
getTemplateEditorValidationState,
@@ -61,14 +62,23 @@
planProjectWorkspaceFileRename,
validateProjectWorkspaceFileName
} from '../components/project-workspace-utils';
+ import { fetchProjectTags } from '../projects-table.helpers';
let { data } = $props();
- const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ let pickedEnvironmentId = $state('');
+ // Converted containers default the destination to their environment.
+ const environmentId = $derived(
+ destinationEnvironmentId(pickedEnvironmentId || (data.sourceEnvironmentId ?? ''), 'projects:create')
+ );
+ const currentEnvId = $derived(environmentId);
const canCreateProject = $derived(hasPermission('projects:create', currentEnvId));
- const canDeleteContainers = $derived(hasPermission('containers:delete', currentEnvId));
+ // Originals are removed from their own environment, not the destination.
+ const canDeleteContainers = $derived(hasPermission('containers:delete', data.sourceEnvironmentId ?? currentEnvId));
const sourceContainerIds = $derived(data.sourceContainerIds ?? []);
- const projectWorkspaceMaxFileSizeMb = $derived(settingsStore.current?.projectWorkspaceMaxFileSizeMb ?? 10);
+ // Files are uploaded to the destination, so its limit applies.
+ const destinationSettings = useEnvironmentSettings(() => currentEnvId);
+ const projectWorkspaceMaxFileSizeMb = $derived(destinationSettings.current?.projectWorkspaceMaxFileSizeMb ?? 10);
let ui = $state({
saving: false,
@@ -112,9 +122,9 @@
let newProjectTags = $state<ProjectTag[]>([]);
const projectTagsQuery = createQuery(() => ({
queryKey: queryKeys.projects.tags(currentEnvId),
- queryFn: () => projectService.getProjectTagsForEnvironment(currentEnvId)
+ queryFn: () => fetchProjectTags([{ id: currentEnvId, name: environmentName(currentEnvId) }])
}));
- const availableProjectTags = $derived(projectTagsQuery.data ?? []);
+ const availableProjectTags = $derived(projectTagsQuery.data?.tags ?? []);
let validation = $state({
composeHasErrors: false,
envHasErrors: false,
@@ -201,11 +211,12 @@
// Sync the authoritative compose name into form state at submit time so
// validation and the create payload use it (event-time write, not an effect).
if (composeYamlName) form.setValue('name', composeYamlName);
+ const destination = environmentId;
await submitComposeResourceForm({
validate: () => validateTemplateEditorForm(validationState, form.validate),
setLoading: (value) => (ui.saving = value),
submit: ({ name, composeContent, envContent }) =>
- projectService.createProject(name, composeContent, envContent, workspaceDraft.toDrafts(), newProjectTags),
+ projectService.createProject(name, composeContent, envContent, workspaceDraft.toDrafts(), newProjectTags, destination),
failureMessage: (name) => m.common_create_failed({ resource: `${m.resource_project()} "${name}"` }),
onSuccess: async (project, { name }) => {
toast.success(
@@ -224,7 +235,7 @@
}
}
// fallow-ignore-next-line code-duplication -- create-success handler; navigation target diverges per page
- goto(`/projects/${project.id}`, { refreshAll: true });
+ goto(environmentHref(`/projects/${project.id}`, destination), { refreshAll: true });
}
});
}
@@ -375,7 +386,7 @@
convertLabel={m.compose_convert_from_docker_run()}
onConvert={() => (ui.showConverterDialog = true)}
fromGitLabel={m.git_from_git_repo()}
- onFromGit={async () => goto(`/environments/${await environmentStore.getCurrentEnvironmentId()}/gitops?action=create`)}
+ onFromGit={async () => goto(`/environments/${environmentId}/gitops?action=create`)}
createTemplateLabel={m.templates_create_template()}
createTemplateDisabled={!inputs.name.value ||
!inputs.composeContent.value ||
@@ -398,6 +409,11 @@
<ProjectTagEditor bind:tags={newProjectTags} availableTags={availableProjectTags} canEdit={!ui.saving} class="mt-2" />
</div>
+ <EnvironmentDestinationSelect
+ bind:value={() => environmentId, (value) => (pickedEnvironmentId = value)}
+ permission="projects:create"
+ />
+
{#if templateLoadNotices.length > 0}
<Alert.Root variant="warning" size="sm">
<AlertIcon class="size-4" />
diff --git a/frontend/src/routes/(app)/projects/projects-table.actions.ts b/frontend/src/routes/(app)/projects/projects-table.actions.ts
index 74a855c94..1ee8e9bec 100644
--- a/frontend/src/routes/(app)/projects/projects-table.actions.ts
+++ b/frontend/src/routes/(app)/projects/projects-table.actions.ts
@@ -9,6 +9,7 @@ import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { bulkConfirmAndRun } from '#lib/utils/bulk-actions.js';
+import { rowKey } from '#lib/utils/environments.js';
import type { TableActionConfig, TableBulkActionConfig } from '#lib/utils/table-action-types.js';
import { tryCatch } from '#lib/utils/try-catch.js';
@@ -27,7 +28,6 @@ type ActionDeps = {
setSelectedIds: (next: string[]) => void;
actionStatus: Record<string, ActionStatus>;
isBulkLoading: BulkLoadingState;
- getEnvId: () => string | undefined;
};
type ProjectActionKind = 'start' | 'stop' | 'restart' | 'redeploy' | 'archive' | 'unarchive';
@@ -45,9 +45,9 @@ type DestroyConfirmResult = {
};
type ProjectActions = {
- performProjectAction: (action: ProjectActionKind, id: string) => Promise<void>;
- handleDestroyProject: (id: string) => Promise<void>;
- handleSyncFromGit: (projectId: string, gitOpsSyncId: string) => Promise<void>;
+ performProjectAction: (action: ProjectActionKind, id: string, environmentId: string) => Promise<void>;
+ handleDestroyProject: (id: string, environmentId: string) => Promise<void>;
+ handleSyncFromGit: (projectId: string, gitOpsSyncId: string, environmentId: string) => Promise<void>;
handleBulkUp: (ids: string[]) => Promise<void>;
handleBulkDown: (ids: string[]) => Promise<void>;
handleBulkRedeploy: (ids: string[]) => Promise<void>;
@@ -57,37 +57,38 @@ type ProjectActions = {
const projectActionConfigs: Record<ProjectActionKind, ProjectActionConfig> = {
start: {
status: 'starting',
- run: (id) => projectService.deployProject(id, 'up', deployOptionsStore.takeRequestOptions()),
+ run: (id, environmentId) => projectService.deployProject(id, 'up', deployOptionsStore.takeRequestOptions(), environmentId),
success: () => m.compose_start_success(),
failure: () => m.compose_start_failed()
},
stop: {
status: 'stopping',
- run: (id) => projectService.downProject(id),
+ run: (id, environmentId) => projectService.downProject(id, environmentId),
success: () => m.compose_down_success(),
failure: () => m.compose_stop_failed()
},
restart: {
status: 'restarting',
- run: (id) => projectService.restartProject(id),
+ run: (id, environmentId) => projectService.restartProject(id, undefined, environmentId),
success: () => m.compose_restart_success(),
failure: () => m.compose_restart_failed()
},
redeploy: {
status: 'redeploying',
- run: (id) => projectService.deployProject(id, 'redeploy', deployOptionsStore.takeRequestOptions()),
+ run: (id, environmentId) =>
+ projectService.deployProject(id, 'redeploy', deployOptionsStore.takeRequestOptions(), environmentId),
success: () => m.compose_pull_success(),
failure: () => m.compose_pull_failed()
},
archive: {
status: 'archiving',
- run: (id) => projectService.archiveProject(id),
+ run: (id, environmentId) => projectService.archiveProject(id, environmentId),
success: () => m.compose_archive_success(),
failure: () => m.compose_archive_failed()
},
unarchive: {
status: 'unarchiving',
- run: (id) => projectService.unarchiveProject(id),
+ run: (id, environmentId) => projectService.unarchiveProject(id, environmentId),
success: () => m.compose_unarchive_success(),
failure: () => m.compose_unarchive_failed()
}
@@ -98,20 +99,20 @@ export function createProjectActions({
refreshProjects,
setSelectedIds,
actionStatus,
- isBulkLoading,
- getEnvId
+ isBulkLoading
}: ActionDeps): ProjectActions {
- async function performProjectAction(action: ProjectActionKind, id: string): Promise<void> {
+ async function performProjectAction(action: ProjectActionKind, id: string, environmentId: string): Promise<void> {
+ const key = rowKey({ id, environmentId, environmentTagged: true });
const config = projectActionConfigs[action];
- actionStatus[id] = config.status;
+ actionStatus[key] = config.status;
const operationResult = await tryCatch(
(async () => {
await handleApiResultWithCallbacks({
- result: await tryCatch(config.run(id)),
+ result: await tryCatch(config.run(id, environmentId)),
message: config.failure(),
setLoadingState: (value) => {
- actionStatus[id] = value ? config.status : '';
+ actionStatus[key] = value ? config.status : '';
},
onSuccess: async (data) => {
toast.success(config.success(), activityToastOptions(extractActivityId(data)));
@@ -122,11 +123,12 @@ export function createProjectActions({
);
if (operationResult.error !== null) {
toast.error(m.common_action_failed());
- actionStatus[id] = '';
+ actionStatus[key] = '';
}
}
- async function handleDestroyProject(id: string): Promise<void> {
+ async function handleDestroyProject(id: string, environmentId: string): Promise<void> {
+ const key = rowKey({ id, environmentId, environmentTagged: true });
openConfirmDialog({
title: m.common_confirm_removal_title(),
message: m.compose_confirm_removal_message(),
@@ -142,13 +144,13 @@ export function createProjectActions({
destructive: true,
action: async (result: DestroyConfirmResult) => {
const removeVolumes = !!(result?.checkboxes?.volumes ?? result?.volumes);
- actionStatus[id] = 'destroying';
+ actionStatus[key] = 'destroying';
await handleApiResultWithCallbacks({
- result: await tryCatch(projectService.destroyProject(id, removeVolumes)),
+ result: await tryCatch(projectService.destroyProject(id, removeVolumes, environmentId)),
message: m.compose_destroy_failed(),
setLoadingState: (value) => {
- actionStatus[id] = value ? 'destroying' : '';
+ actionStatus[key] = value ? 'destroying' : '';
},
onSuccess: async (data) => {
toast.success(m.compose_destroy_success(), activityToastOptions(extractActivityId(data)));
@@ -160,18 +162,16 @@ export function createProjectActions({
});
}
- async function handleSyncFromGit(projectId: string, gitOpsSyncId: string): Promise<void> {
- const envId = getEnvId();
- if (!envId) return;
-
- actionStatus[projectId] = 'syncing';
- const result = await tryCatch(gitOpsSyncService.performSync(envId, gitOpsSyncId));
+ async function handleSyncFromGit(projectId: string, gitOpsSyncId: string, environmentId: string): Promise<void> {
+ const key = rowKey({ id: projectId, environmentId, environmentTagged: true });
+ actionStatus[key] = 'syncing';
+ const result = await tryCatch(gitOpsSyncService.performSync(environmentId, gitOpsSyncId));
await handleApiResultWithCallbacks({
result,
message: m.git_sync_failed(),
setLoadingState: (value) => {
- actionStatus[projectId] = value ? 'syncing' : '';
+ actionStatus[key] = value ? 'syncing' : '';
},
onSuccess: async () => {
toast.success(m.git_sync_success());
@@ -189,7 +189,7 @@ export function createProjectActions({
message: config.message(ids.length),
confirmLabel: config.label,
destructive: config.destructive ?? false,
- run: (id) => config.run(id),
+ run: (id, environmentId) => config.run(id, environmentId),
messages: {
success: config.success,
partial: config.partial,
@@ -213,7 +213,8 @@ export function createProjectActions({
message: (count) => m.projects_bulk_up_confirm_message({ count }),
label: m.common_up(),
loadingKey: 'up',
- run: (id) => projectService.deployProject(id, 'up', (deployOptions ??= deployOptionsStore.takeRequestOptions())),
+ run: (id, environmentId) =>
+ projectService.deployProject(id, 'up', (deployOptions ??= deployOptionsStore.takeRequestOptions()), environmentId),
success: (count) => m.projects_bulk_up_success({ count }),
partial: (success, total, failed) => m.projects_bulk_up_partial({ success, total, failed }),
failure: () => m.compose_start_failed()
@@ -226,7 +227,7 @@ export function createProjectActions({
message: (count) => m.projects_bulk_down_confirm_message({ count }),
label: m.common_down(),
loadingKey: 'down',
- run: (id) => projectService.downProject(id),
+ run: (id, environmentId) => projectService.downProject(id, environmentId),
success: (count) => m.projects_bulk_down_success({ count }),
partial: (success, total, failed) => m.projects_bulk_down_partial({ success, total, failed }),
failure: () => m.compose_stop_failed()
@@ -241,7 +242,8 @@ export function createProjectActions({
message: (count) => m.projects_bulk_redeploy_confirm_message({ count }),
label: m.compose_pull_redeploy(),
loadingKey: 'redeploy',
- run: (id) => projectService.deployProject(id, 'redeploy', (deployOptions ??= deployOptionsStore.takeRequestOptions())),
+ run: (id, environmentId) =>
+ projectService.deployProject(id, 'redeploy', (deployOptions ??= deployOptionsStore.takeRequestOptions()), environmentId),
success: (count) => m.projects_bulk_redeploy_success({ count }),
partial: (success, total, failed) => m.projects_bulk_redeploy_partial({ success, total, failed }),
failure: () => m.compose_pull_failed()
@@ -254,7 +256,7 @@ export function createProjectActions({
message: (count) => m.projects_bulk_archive_confirm_message({ count }),
label: m.projects_archive(),
loadingKey: 'archive',
- run: (id) => projectService.archiveProject(id),
+ run: (id, environmentId) => projectService.archiveProject(id, environmentId),
success: (count) => m.projects_bulk_archive_success({ count }),
partial: (success, total, failed) => m.projects_bulk_archive_partial({ success, total, failed }),
failure: () => m.compose_archive_failed()
diff --git a/frontend/src/routes/(app)/projects/projects-table.helpers.ts b/frontend/src/routes/(app)/projects/projects-table.helpers.ts
index cdcc1a350..0b74894fa 100644
--- a/frontend/src/routes/(app)/projects/projects-table.helpers.ts
+++ b/frontend/src/routes/(app)/projects/projects-table.helpers.ts
@@ -1,3 +1,8 @@
+import { projectService } from '#lib/services/project-service.js';
+import type { EnvironmentRef } from '#lib/stores/environment.store.svelte.js';
+import type { ProjectTagOption } from '#lib/types/swarm.js';
+import { collectAcrossEnvironments, type EnvironmentFailure } from '#lib/utils/environments.js';
+
export type ActionStatus =
| 'starting'
| 'stopping'
@@ -8,3 +13,17 @@ export type ActionStatus =
| 'destroying'
| 'syncing'
| '';
+
+export type ProjectTagOptions = { tags: ProjectTagOption[]; failedEnvironments: EnvironmentFailure[] };
+
+/** Tag options from every shown environment, one per name, with the environments that failed. */
+export async function fetchProjectTags(environments: EnvironmentRef[]): Promise<ProjectTagOptions> {
+ const { values, failures } = await collectAcrossEnvironments(environments, (id, config) =>
+ projectService.getProjectTagsForEnvironment(id, config)
+ );
+ const tags = values.flatMap((result) => result.value);
+ return {
+ tags: tags.filter((tag, index) => tags.findIndex((other) => other.name === tag.name) === index),
+ failedEnvironments: failures
+ };
+}
diff --git a/frontend/src/routes/(app)/security/+page.svelte b/frontend/src/routes/(app)/security/+page.svelte
index 1ae0def74..686b4c87d 100644
--- a/frontend/src/routes/(app)/security/+page.svelte
+++ b/frontend/src/routes/(app)/security/+page.svelte
@@ -3,9 +3,11 @@
import { toast } from 'svelte-sonner';
import FeatureDisabled from '#lib/components/features/feature-disabled.svelte';
+ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';
import { EmptyState } from '#lib/components/states/index.js';
import { TabBar, type TabItem } from '#lib/components/tab-bar/index.js';
import * as Tabs from '#lib/components/ui/tabs/index.js';
+ import { TABLE_PAGE_SIZE_ALL } from '#lib/constants/table-pagination.js';
import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';
import { useUrlTab } from '#lib/hooks/use-url-tab.svelte.js';
import { ActivityIcon, ImagesIcon, InspectIcon, ScanIcon, ShieldAlertIcon, ShieldCheckIcon } from '#lib/icons/index.js';
@@ -16,28 +18,34 @@
import { activityStore } from '#lib/stores/activity.store.svelte.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { featureStore } from '#lib/stores/features.store.svelte.js';
- import type { ImagePatchTargetDto } from '#lib/types/docker.js';
- import type { VulnerabilityRiskOverview, VulnerabilityWithImage } from '#lib/types/environment.js';
+ import type { VulnerabilityRiskOverview } from '#lib/types/environment.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import { extractApiErrorMessage, parallelRefresh } from '#lib/utils/api.js';
import { hasPermission } from '#lib/utils/auth.js';
+ import { fetchAcrossEnvironments } from '#lib/utils/environments.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import {
getSeveritySegments,
mapVulnerabilityPage,
mapVulnerabilityRequest,
- withVulnerabilityToggles
+ vulnerabilityEnvironments,
+ vulnerabilityOverviewEnvironment,
+ vulnerabilityOverviewEnvironments,
+ vulnerabilitySortValue,
+ withVulnerabilityToggles,
+ type VulnerabilityRow
} from '#lib/utils/vulnerability.js';
import SecurityOverview from './components/security-overview.svelte';
- import SecurityPatchTable from './components/security-patch-table.svelte';
+ import SecurityPatchTable, { fetchPatchTargets, type PatchTargetPage } from './components/security-patch-table.svelte';
import SecurityVulnerabilityTable from './components/security-vulnerability-table.svelte';
let { data } = $props();
let displayedEnvId = $derived(data.envId);
+ // Rows carry their environment, so they are cleared when the shown environments change too.
+ let displayedShownKey = environmentStore.shownKey;
let overview = $derived<VulnerabilityRiskOverview | null>(data.overview);
- type VulnerabilityRow = VulnerabilityWithImage & { id: string };
let vulnerabilities = $derived<Paginated<VulnerabilityRow>>(data.vulnerabilities);
let requestOptions = $derived<SearchPaginationSortRequest>(data.vulnerabilityRequestOptions);
@@ -69,22 +77,22 @@
let scanPollTimeout: ReturnType<typeof setTimeout> | null = null;
// Set once on destroy so an in-flight poll tick can't re-arm a timer on a dead component.
let destroyed = false;
+ let refreshGeneration = 0;
// Patch targets, loaded when the tab is first opened
- type PatchTargetRow = ImagePatchTargetDto & { id: string };
- let patchTargets = $state<Paginated<PatchTargetRow>>({
+ let patchTargets = $state<PatchTargetPage>({
data: [],
pagination: { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: 20 }
});
let patchRequestOptions = $derived<SearchPaginationSortRequest>(data.patchRequestOptions);
async function loadPatches() {
if (!vulnerabilityManagementEnabled) return;
- const requestedEnvId = currentEnvId;
+ const requestedScope = scopeKey();
const operationResult = await tryCatch(
(async () => {
- const response = await imageService.listPatchTargets(patchRequestOptions);
- if (destroyed || !vulnerabilityManagementEnabled || requestedEnvId !== currentEnvId) return;
- patchTargets = { ...response, data: (response.data ?? []).map((t) => ({ ...t, id: t.imageId })) };
+ const response = await fetchPatchTargets(patchRequestOptions);
+ if (destroyed || !vulnerabilityManagementEnabled || requestedScope !== scopeKey()) return;
+ patchTargets = response;
})()
);
if (operationResult.error !== null) {
@@ -98,13 +106,13 @@
const severityItems = $derived(getSeveritySegments(overview?.summary));
async function refreshOverview() {
- const requestedEnvId = currentEnvId;
- const result = await tryCatch(vulnerabilityService.getRiskOverviewForEnvironment(requestedEnvId));
+ const requestedScope = scopeKey();
+ const result = await tryCatch(vulnerabilityService.getRiskOverviewForEnvironment(overviewEnvironmentId));
if (result.error !== null) {
toast.error(m.common_refresh_failed({ resource: m.security() }), { description: extractApiErrorMessage(result.error) });
return;
}
- if (!destroyed && vulnerabilityManagementEnabled && requestedEnvId === currentEnvId) overview = result.data;
+ if (!destroyed && vulnerabilityManagementEnabled && requestedScope === scopeKey()) overview = result.data;
}
async function showVulnerability(vulnerabilityId: string) {
@@ -122,38 +130,48 @@
// reset drops retained data first so a failed reload leaves the page empty rather than stale.
async function refreshAll(reset = false) {
const requestedEnvId = currentEnvId;
+ const requestedScope = scopeKey();
+ // A newer refresh wins, so an older one finishing last cannot put removed environments back.
+ const generation = ++refreshGeneration;
+ const stillCurrent = () =>
+ !destroyed && vulnerabilityManagementEnabled && requestedScope === scopeKey() && generation === refreshGeneration;
selectedVulnerabilityIds = [];
- if (reset || displayedEnvId !== requestedEnvId) {
+ if (reset || displayedEnvId !== requestedEnvId || displayedShownKey !== environmentStore.shownKey) {
overview = null;
vulnerabilities = { data: [], pagination: { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: 20 } };
patchTargets = { data: [], pagination: { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: 20 } };
displayedEnvId = requestedEnvId;
+ displayedShownKey = environmentStore.shownKey;
}
- await featureStore.refresh(requestedEnvId);
- if (requestedEnvId !== currentEnvId || !vulnerabilityManagementEnabled) return;
+ await Promise.all(environmentStore.shown.map((env) => featureStore.refresh(env.id)));
+ if (!stillCurrent()) return;
const requestForApi = mapVulnerabilityRequest(withVulnerabilityToggles(requestOptions, { showIgnored, fixAvailable }));
await parallelRefresh(
{
overview: {
- fetch: () => vulnerabilityService.getRiskOverviewForEnvironment(requestedEnvId),
+ fetch: () => vulnerabilityService.getRiskOverviewForEnvironment(overviewEnvironmentId),
onSuccess: (data) => {
- if (!destroyed && vulnerabilityManagementEnabled && requestedEnvId === currentEnvId) overview = data;
+ if (stillCurrent()) overview = data;
},
errorMessage: m.common_refresh_failed({ resource: m.security() })
},
vulnerabilities: {
- fetch: () => vulnerabilityService.getAllVulnerabilitiesForEnvironment(requestedEnvId, requestForApi),
+ fetch: () =>
+ fetchAcrossEnvironments(
+ vulnerabilityEnvironments(),
+ requestForApi,
+ (id, request, config) => vulnerabilityService.getAllVulnerabilitiesForEnvironment(id, request, config),
+ vulnerabilitySortValue
+ ),
onSuccess: (data) => {
- if (!destroyed && vulnerabilityManagementEnabled && requestedEnvId === currentEnvId)
- vulnerabilities = mapVulnerabilityPage(data, requestOptions);
+ if (stillCurrent()) vulnerabilities = mapVulnerabilityPage(data, requestOptions);
},
errorMessage: m.common_refresh_failed({ resource: m.vuln_title() })
},
patches: {
- fetch: () => imageService.listPatchTargets(patchRequestOptions),
+ fetch: () => fetchPatchTargets(patchRequestOptions),
onSuccess: (data) => {
- if (!destroyed && vulnerabilityManagementEnabled && requestedEnvId === currentEnvId)
- patchTargets = { ...data, data: (data.data ?? []).map((t: ImagePatchTargetDto) => ({ ...t, id: t.imageId })) };
+ if (stillCurrent()) patchTargets = data;
},
errorMessage: m.common_refresh_failed({ resource: m.patches() })
}
@@ -234,24 +252,29 @@
useEnvironmentRefresh(refreshAll);
onMount(() => {
- let activePatchActivityIds = new Set<string>();
- let observedEnvironmentId: string | undefined;
+ // Activity ID to type for the patches and scans still running.
+ let activeActivities = new Map<string, string>();
+ let observedScope: string | undefined;
return activityStore.subscribeActivities((activities) => {
- const environmentId = environmentStore.selected?.id;
- const active = new Set(
+ // Patches and scans run in each row's own environment, so every shown one is watched.
+ const environmentIds = environmentStore.shown.map((env) => env.id);
+ const active = new Map(
activities
.filter(
(activity) =>
- (activity.sourceEnvironmentId || activity.environmentId || '0') === environmentId &&
+ environmentIds.includes(activity.sourceEnvironmentId || activity.environmentId || '0') &&
(activity.type === 'image_patch' || activity.type === 'vulnerability_scan') &&
(activity.status === 'queued' || activity.status === 'running')
)
- .map((activity) => activity.id)
+ .map((activity) => [activity.id, activity.type] as const)
);
- const finished = observedEnvironmentId === environmentId && [...activePatchActivityIds].some((id) => !active.has(id));
- observedEnvironmentId = environmentId;
- activePatchActivityIds = active;
- if (finished && environmentId && hasPermission('images:read', environmentId)) void loadPatches();
+ const scope = environmentStore.shownKey;
+ const finished = observedScope === scope ? [...activeActivities].filter(([id]) => !active.has(id)) : [];
+ observedScope = scope;
+ activeActivities = active;
+ // Scan polling follows one environment's overview, so with several shown a finished scan refreshes findings.
+ if (environmentIds.length > 1 && finished.some(([, type]) => type === 'vulnerability_scan')) void refreshAll();
+ else if (finished.length > 0 && environmentIds.some((id) => hasPermission('images:read', id))) void loadPatches();
});
});
@@ -263,18 +286,30 @@
async function scanAllImages() {
if (!vulnerabilityManagementEnabled || isLoading.scanningAll) return;
- const requestedEnvId = currentEnvId;
+ const requestedScope = scopeKey();
isLoading.scanningAll = true;
scanProgress = { current: 0, total: 0 };
try {
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 }
- });
+ // Fetch all images with a high limit to get all of them; merged, every environment's whole list.
+ const environments = vulnerabilityEnvironments().filter((env) => hasPermission('vulnerabilities:scan', env.id));
+ const limit = environments.length > 1 ? TABLE_PAGE_SIZE_ALL : 1000;
+ const imagesResponse = await fetchAcrossEnvironments(
+ environments,
+ { pagination: { page: 1, limit } },
+ (id, request, config) => imageService.getImagesForEnvironment(id, request, config)
+ );
const images = imagesResponse.data ?? [];
+ // Environments whose images could not be listed were not scanned.
+ const skipped = imagesResponse.failedEnvironments ?? [];
+ for (const { environment, message } of skipped) {
+ toast.error(m.all_environments_request_failed({ environment: environment.name }), {
+ id: `environment-request-failed-${environment.id}`,
+ description: message
+ });
+ }
if (images.length === 0) {
toast.info(m.security_no_images_to_scan());
@@ -289,14 +324,14 @@
let failed = 0;
for (let i = 0; i < images.length; i += BATCH_SIZE) {
- if (destroyed || !vulnerabilityManagementEnabled || requestedEnvId !== currentEnvId) return;
+ if (destroyed || !vulnerabilityManagementEnabled || requestedScope !== scopeKey()) return;
const batch = images.slice(i, i + BATCH_SIZE);
await Promise.all(
batch.map(async (image) => {
const operationResult = await tryCatch(
(async () => {
- const result = await vulnerabilityService.scanImage(image.id, requestedEnvId);
+ const result = await vulnerabilityService.scanImage(image.id, image.environmentId);
if (result.status === 'completed' || result.status === 'scanning' || result.status === 'pending') {
succeeded++;
} else {
@@ -316,7 +351,9 @@
}
// Show summary toast (scans run in background; this reflects requests started, not completed)
- if (failed === 0) {
+ if (failed === 0 && skipped.length > 0) {
+ toast.warning(m.security_scan_all_success({ count: succeeded }));
+ } else if (failed === 0) {
toast.success(m.security_scan_all_success({ count: succeeded }));
} else if (succeeded === 0) {
toast.error(m.security_scan_all_failed({ count: failed }));
@@ -341,7 +378,10 @@
}
const currentEnvId = $derived(environmentStore.selected?.id || '0');
- const vulnerabilityManagementEnabled = $derived(featureStore.isEnabled('vulnerabilityManagement', currentEnvId));
+ // Reads cover every shown environment, so a result is stale once the selection or the shown set changes.
+ const scopeKey = () => `${currentEnvId}|${environmentStore.shownKey}`;
+ const vulnerabilityManagementEnabled = $derived(vulnerabilityEnvironments().length > 0);
+ const overviewEnvironmentId = $derived(vulnerabilityOverviewEnvironment()?.id ?? currentEnvId);
let wasFeatureEnabled = true;
$effect(() => {
const enabled = vulnerabilityManagementEnabled;
@@ -353,7 +393,9 @@
}
wasFeatureEnabled = enabled;
});
- const canScanVuln = $derived(vulnerabilityManagementEnabled && hasPermission('vulnerabilities:scan', currentEnvId));
+ const canScanVuln = $derived(
+ vulnerabilityManagementEnabled && vulnerabilityEnvironments().some((env) => hasPermission('vulnerabilities:scan', env.id))
+ );
const actionButtons: ActionButton[] = $derived.by(() => {
const buttons: ActionButton[] = [];
@@ -414,6 +456,14 @@
{/if}
{/snippet}
+{#snippet overviewEnvironmentPicker()}
+ {#if environmentStore.shown.length > 1}
+ <div class="mb-3">
+ <EnvironmentDestinationSelect environments={vulnerabilityOverviewEnvironments()} />
+ </div>
+ {/if}
+{/snippet}
+
<ResourcePageLayout
title={m.security()}
subtitle={m.security_subtitle()}
@@ -426,12 +476,14 @@
<Tabs.Root value={activeTab}>
<TabBar items={securityTabItems} value={activeTab} onValueChange={handleTabChange} />
<Tabs.Content value="overview" class="mt-4">
+ {@render overviewEnvironmentPicker()}
{#if overview}
- <SecurityOverview {overview} onSelectVulnerability={showVulnerability} />
+ <SecurityOverview {overview} environmentId={overviewEnvironmentId} onSelectVulnerability={showVulnerability} />
{/if}
</Tabs.Content>
<Tabs.Content value="vulnerabilities" class="mt-4">
{#if overview}
+ {@render overviewEnvironmentPicker()}
<div class="mb-3 flex flex-wrap items-center gap-x-5 gap-y-1.5 text-xs text-muted-foreground">
<span>
{m.security_images_scanned()}:
diff --git a/frontend/src/routes/(app)/security/+page.ts b/frontend/src/routes/(app)/security/+page.ts
index a1ab6a09a..9eb3c70c5 100644
--- a/frontend/src/routes/(app)/security/+page.ts
+++ b/frontend/src/routes/(app)/security/+page.ts
@@ -4,15 +4,23 @@ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { featureStore } from '#lib/stores/features.store.svelte.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { throwPageLoadError } from '#lib/utils/api.js';
+import { fetchAcrossEnvironments } from '#lib/utils/environments.js';
import { resolveInitialTableRequest } from '#lib/utils/tables.js';
import { tryCatch } from '#lib/utils/try-catch.js';
-import { mapVulnerabilityPage, mapVulnerabilityRequest } from '#lib/utils/vulnerability.js';
+import {
+ mapVulnerabilityPage,
+ mapVulnerabilityRequest,
+ vulnerabilityEnvironments,
+ vulnerabilityOverviewEnvironment,
+ vulnerabilitySortValue
+} from '#lib/utils/vulnerability.js';
import type { PageLoad } from './$types';
export const load: PageLoad = async ({ parent }) => {
const { queryClient } = await parent();
const envId = await environmentStore.getCurrentEnvironmentId();
+ const shown = await environmentStore.getShownEnvironments();
const vulnerabilityRequestOptions = resolveInitialTableRequest(
'arcane-security-vuln-table',
@@ -40,8 +48,9 @@ export const load: PageLoad = async ({ parent }) => {
}
} satisfies SearchPaginationSortRequest);
- await featureStore.load(envId);
- if (!featureStore.isEnabled('vulnerabilityManagement', envId)) {
+ await Promise.all([envId, ...shown.map((env) => env.id)].map((id) => featureStore.load(id)));
+ const overviewEnvironment = vulnerabilityOverviewEnvironment();
+ if (!overviewEnvironment) {
return {
envId,
featureDisabled: true,
@@ -60,12 +69,18 @@ export const load: PageLoad = async ({ parent }) => {
(async () =>
Promise.all([
queryClient.query({
- queryKey: queryKeys.vulnerabilities.overviewByEnvironment(envId),
- queryFn: () => vulnerabilityService.getRiskOverviewForEnvironment(envId)
+ queryKey: queryKeys.vulnerabilities.overviewByEnvironment(overviewEnvironment.id),
+ queryFn: () => vulnerabilityService.getRiskOverviewForEnvironment(overviewEnvironment.id)
}),
queryClient.query({
- queryKey: queryKeys.vulnerabilities.allByEnvironment(envId, requestForApi),
- queryFn: () => vulnerabilityService.getAllVulnerabilitiesForEnvironment(envId, requestForApi)
+ queryKey: queryKeys.vulnerabilities.allByEnvironment(environmentStore.shownKey, requestForApi),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ vulnerabilityEnvironments(),
+ requestForApi,
+ (id, request, config) => vulnerabilityService.getAllVulnerabilitiesForEnvironment(id, request, config),
+ vulnerabilitySortValue
+ )
})
]))()
);
diff --git a/frontend/src/routes/(app)/security/components/security-overview.svelte b/frontend/src/routes/(app)/security/components/security-overview.svelte
index 1616f9800..912e1b1ab 100644
--- a/frontend/src/routes/(app)/security/components/security-overview.svelte
+++ b/frontend/src/routes/(app)/security/components/security-overview.svelte
@@ -8,6 +8,7 @@
import { ArrowDownIcon, ArrowUpIcon, InfoIcon, ScanIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import type { VulnerabilityRiskDrivers, VulnerabilityRiskImage, VulnerabilityRiskOverview } from '#lib/types/environment.js';
+ import { environmentHref } from '#lib/utils/environments.js';
import { formatRelativeTime } from '#lib/utils/formatting.js';
import {
getRiskBandDisplay,
@@ -19,10 +20,11 @@
interface Props {
overview: VulnerabilityRiskOverview;
+ environmentId: string;
onSelectVulnerability: (vulnerabilityId: string) => void;
}
- let { overview, onSelectVulnerability }: Props = $props();
+ let { overview, environmentId, onSelectVulnerability }: Props = $props();
let trendDays = $state('30');
let findingRank = $state<'risk' | 'prevalence'>('risk');
@@ -350,7 +352,7 @@
{@const band = getRiskBandDisplay(image.riskBand, image.scoreStatus)}
<li>
<a
- href="/images/{image.imageId}?tab=vulnerabilities"
+ href={environmentHref(`/images/${image.imageId}?tab=vulnerabilities`, environmentId)}
class="-mx-2 grid grid-cols-content-action items-center gap-4 rounded-md px-2 py-3 transition-colors hover:bg-muted/40"
>
<span class="min-w-0 space-y-1">
diff --git a/frontend/src/routes/(app)/security/components/security-patch-table.svelte b/frontend/src/routes/(app)/security/components/security-patch-table.svelte
index 8b9d1fc6b..881fc3037 100644
--- a/frontend/src/routes/(app)/security/components/security-patch-table.svelte
+++ b/frontend/src/routes/(app)/security/components/security-patch-table.svelte
@@ -1,61 +1,88 @@
+<script module lang="ts">
+ import { imageService } from '#lib/services/image-service.js';
+ import type { ImagePatchTargetDto } from '#lib/types/docker.js';
+ import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
+ import {
+ environmentHref,
+ fetchAcrossEnvironments,
+ type EnvironmentFailure,
+ type EnvironmentRow
+ } from '#lib/utils/environments.js';
+ import { vulnerabilityEnvironments } from '#lib/utils/vulnerability.js';
+
+ export type PatchTargetRow = EnvironmentRow<ImagePatchTargetDto> & { id: string };
+ export type PatchTargetPage = Paginated<PatchTargetRow> & { failedEnvironments?: EnvironmentFailure[] };
+
+ /** Patch targets from every shown environment with vulnerability management, keyed by environment and image. */
+ export async function fetchPatchTargets(options: SearchPaginationSortRequest): Promise<PatchTargetPage> {
+ const page = await fetchAcrossEnvironments(
+ vulnerabilityEnvironments(),
+ options,
+ (id, request, config) => imageService.listPatchTargets(request, id, config),
+ // The image column sorts as imageName but the row holds imageRef.
+ (target, column) => (column === 'imageName' ? target.imageRef : target[column as keyof ImagePatchTargetDto])
+ );
+ // The table keys rows by environment and id, so the id is the image's own.
+ return { ...page, data: page.data.map((target) => ({ ...target, id: target.imageId })) };
+ }
+</script>
+
<script lang="ts">
import { toast } from 'svelte-sonner';
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import type { ColumnSpec } from '#lib/components/arcane-table/arcane-table.types.svelte.js';
import UniversalMobileCard from '#lib/components/arcane-table/cards/universal-mobile-card.svelte';
+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
import { Badge } from '#lib/components/ui/badge/index.js';
import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
import MonoCell from '#lib/components/vulnerability/mono-cell.svelte';
import { ShieldCheckIcon, ImagesIcon, ClockIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
- import { imageService } from '#lib/services/image-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
- import { featureStore } from '#lib/stores/features.store.svelte.js';
import userStore from '#lib/stores/user-store.svelte.js';
- import type { ImagePatchTargetDto } from '#lib/types/docker.js';
- import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import { activityToastOptions } from '#lib/utils/activity-toast.js';
import { extractApiErrorMessage } from '#lib/utils/api.js';
import { hasPermission } from '#lib/utils/auth.js';
import { formatDateTimeShort } from '#lib/utils/formatting.js';
import { tryCatch } from '#lib/utils/try-catch.js';
- type PatchTargetRow = ImagePatchTargetDto & { id: string };
-
let {
targets = $bindable(),
requestOptions = $bindable()
}: {
- targets: Paginated<PatchTargetRow>;
+ targets: PatchTargetPage;
requestOptions: SearchPaginationSortRequest;
} = $props();
- const currentEnvId = $derived(environmentStore.selected?.id || '0');
// Track the user store: hasPermission reads it non-reactively, so without
// this the derived would cache a pre-hydration false forever.
const canPatchImage = $derived.by(() => {
userStore.current;
- return featureStore.isEnabled('vulnerabilityManagement', currentEnvId) && hasPermission('images:patch', currentEnvId);
+ return vulnerabilityEnvironments().some((env) => hasPermission('images:patch', env.id));
});
+ // Only the latest request is applied, so a slow response for an earlier filter cannot replace newer rows.
+ let latestRequest = 0;
async function refreshPatchTargets(options: SearchPaginationSortRequest) {
- if (!featureStore.isEnabled('vulnerabilityManagement', currentEnvId)) return targets;
- const requestedEnvId = currentEnvId;
- const response = await imageService.listPatchTargets(options);
- if (!featureStore.isEnabled('vulnerabilityManagement', currentEnvId) || requestedEnvId !== currentEnvId) return targets;
- const mapped = { ...response, data: (response.data ?? []).map((t) => ({ ...t, id: t.imageId })) };
- targets = mapped;
- return mapped;
+ if (vulnerabilityEnvironments().length === 0) return targets;
+ const requestedScope = environmentStore.shownKey;
+ const request = ++latestRequest;
+ const response = await fetchPatchTargets(options);
+ if (vulnerabilityEnvironments().length === 0 || requestedScope !== environmentStore.shownKey || request !== latestRequest) {
+ return targets;
+ }
+ targets = response;
+ return response;
}
async function handlePatchImage(item: PatchTargetRow) {
- if (!canPatchImage) return;
+ if (!hasPermission('images:patch', item.environmentId)) return;
const operationResult = await tryCatch(
(async () => {
// The fixable counts come from the stored scan, so patch from that report.
- const record = await imageService.patchImage(item.imageId, { scanId: item.imageId });
+ const record = await imageService.patchImage(item.imageId, { scanId: item.imageId }, item.environmentId);
toast.info(m.images_patch_started({ patchedRef: record.patchedRef }), activityToastOptions(record.activityId));
await refreshPatchTargets(requestOptions);
})()
@@ -94,6 +121,7 @@
}
const columns = $derived([
+ ...environmentColumns<PatchTargetRow>(),
{ id: 'imageName', accessorKey: 'imageRef', title: m.common_image(), sortable: true, cell: ImageCell },
{ accessorKey: 'fixableCount', title: m.security_fixable(), sortable: true, cell: FixableCell },
{ accessorKey: 'scanTime', title: m.security_last_scanned(), sortable: true, cell: ScannedCell },
@@ -119,7 +147,7 @@
{/snippet}
{#snippet ImageCell({ item }: { item: PatchTargetRow })}
- <a class="truncate text-sm font-medium hover:underline" href="/images/{item.imageId}">
+ <a class="truncate text-sm font-medium hover:underline" href={environmentHref(`/images/${item.imageId}`, item.environmentId)}>
{item.imageRef}
</a>
{/snippet}
@@ -196,7 +224,10 @@
{#snippet rowActions({ item }: { item: PatchTargetRow })}
<RowActionsMenu>
- <DropdownMenu.Item onclick={() => handlePatchImage(item)} disabled={item.localOnly || item.fixableCount === 0}>
+ <DropdownMenu.Item
+ onclick={() => handlePatchImage(item)}
+ disabled={item.localOnly || item.fixableCount === 0 || !hasPermission('images:patch', item.environmentId)}
+ >
<ShieldCheckIcon class="size-4" />
<div class="flex flex-col items-start">
<span>{m.images_patch()}</span>
diff --git a/frontend/src/routes/(app)/security/components/security-vulnerability-table.svelte b/frontend/src/routes/(app)/security/components/security-vulnerability-table.svelte
index b3da9a0ec..8d5d3e744 100644
--- a/frontend/src/routes/(app)/security/components/security-vulnerability-table.svelte
+++ b/frontend/src/routes/(app)/security/components/security-vulnerability-table.svelte
@@ -6,6 +6,7 @@
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import type { BulkAction, ColumnSpec } from '#lib/components/arcane-table/arcane-table.types.svelte.js';
import UniversalMobileCard from '#lib/components/arcane-table/cards/universal-mobile-card.svelte';
+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
// Patching happens on the Patches tab, per image; CVE rows only inspect and ignore.
@@ -30,13 +31,21 @@
import { m } from '#lib/paraglide/messages.js';
import { vulnerabilityService } from '#lib/services/vulnerability-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
- import { featureStore } from '#lib/stores/features.store.svelte.js';
- import type { VulnerabilityWithImage } from '#lib/types/environment.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { hasPermission } from '#lib/utils/auth.js';
import { downloadBlob } from '#lib/utils/browser-download.js';
import { bulkConfirmAndRun, confirmAndRun } from '#lib/utils/bulk-actions.js';
+ import {
+ collectAcrossEnvironments,
+ ENVIRONMENT_FILTER,
+ environmentFilterIds,
+ environmentHref,
+ environmentName,
+ fetchAcrossEnvironments,
+ rowKey,
+ settleAcrossEnvironments
+ } from '#lib/utils/environments.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import {
getSeverityBadgeVariant,
@@ -46,11 +55,12 @@
mapVulnerabilityRequest,
resolveSeverityFilter,
toBulkVulnerabilityFilters,
- withVulnerabilityToggles
+ vulnerabilityEnvironments,
+ vulnerabilitySortValue,
+ withVulnerabilityToggles,
+ type VulnerabilityRow
} from '#lib/utils/vulnerability.js';
- type VulnerabilityRow = VulnerabilityWithImage & { id: string };
-
let {
vulnerabilities = $bindable(),
requestOptions = $bindable(),
@@ -75,10 +85,12 @@
let bulkInFlight = $state(false);
let mounted = true;
- const currentEnvId = $derived(environmentStore.selected?.id || '0');
- const currentEnvName = $derived(environmentStore.selected?.name || currentEnvId);
- const vulnerabilityManagementEnabled = $derived(featureStore.isEnabled('vulnerabilityManagement', currentEnvId));
- const canManageVuln = $derived(vulnerabilityManagementEnabled && hasPermission('vulnerabilities:manage', currentEnvId));
+ const scope = $derived(environmentStore.shownKey);
+ const vulnerabilityManagementEnabled = $derived(vulnerabilityEnvironments().length > 0);
+ const manageEnvironments = $derived(
+ vulnerabilityEnvironments().filter((env) => hasPermission('vulnerabilities:manage', env.id))
+ );
+ const canManageVuln = $derived(manageEnvironments.length > 0);
const matchingCount = $derived(vulnerabilities.pagination?.totalItems ?? vulnerabilities.data.length);
@@ -87,22 +99,22 @@
apply();
return;
}
- const requestedEnvId = currentEnvId;
+ const requestedScope = scope;
openConfirmDialog({
title: m.vuln_load_all_title(),
message: m.vuln_load_all_message({ count: matchingCount }),
confirm: {
label: m.vuln_load_all_confirm(),
action: () => {
- if (!mounted || requestedEnvId !== currentEnvId || !vulnerabilityManagementEnabled) return;
+ if (!mounted || requestedScope !== scope || !vulnerabilityManagementEnabled) return;
apply();
}
}
});
}
- async function reloadFromFirstPage(requestedEnvId: string) {
- if (requestedEnvId !== currentEnvId) return;
+ async function reloadFromFirstPage(requestedScope: string) {
+ if (requestedScope !== scope) return;
// The rows are already changed on the server; clear before refreshing so a failed reload cannot re-submit them.
selectedIds = [];
requestOptions = { ...requestOptions, pagination: { ...(requestOptions.pagination ?? { limit: 20 }), page: 1 } };
@@ -112,13 +124,20 @@
});
}
+ // Confirmations name one environment, and only count several.
+ function confirmEnvironment(environmentIds: string[]): string {
+ const unique = [...new Set(environmentIds)];
+ if (unique.length === 1) return environmentName(unique[0]!);
+ return m.all_environments_count({ count: unique.length });
+ }
+
function handleBulkSelected(ids: string[]) {
if (!canManageVuln) return;
- const requestedEnvId = currentEnvId;
+ const requestedScope = scope;
const restore = showIgnored;
- const rows = new Map(vulnerabilities.data.map((row) => [row.id, row]));
+ const rows = vulnerabilities.data.filter((row) => ids.includes(rowKey(row)));
const count = ids.length;
- const environment = currentEnvName;
+ const environment = confirmEnvironment(rows.map((row) => row.environmentId));
bulkConfirmAndRun({
ids,
title: restore ? m.vuln_bulk_restore_confirm_title({ count }) : m.vuln_bulk_ignore_confirm_title({ count }),
@@ -126,11 +145,11 @@
? m.vuln_bulk_restore_selected_confirm_message({ count, environment })
: m.vuln_bulk_ignore_selected_confirm_message({ count, environment }),
confirmLabel: restore ? m.vuln_bulk_restore() : m.common_ignore(),
- run: async (id) => {
- const row = rows.get(id);
+ run: async (id, environmentId) => {
+ const row = rows.find((candidate) => candidate.id === id && candidate.environmentId === environmentId);
if (!row) return;
if (restore) {
- if (row.ignoreId) await vulnerabilityService.unignoreVulnerability(row.ignoreId, requestedEnvId);
+ if (row.ignoreId) await vulnerabilityService.unignoreVulnerability(row.ignoreId, row.environmentId);
return;
}
await vulnerabilityService.ignoreVulnerability(
@@ -140,7 +159,7 @@
pkgName: row.pkgName || '',
installedVersion: row.installedVersion || ''
},
- requestedEnvId
+ row.environmentId
);
},
messages: {
@@ -153,7 +172,7 @@
},
setLoading: (loading) => (bulkInFlight = loading),
onComplete: async (result) => {
- if (result.success > 0) await reloadFromFirstPage(requestedEnvId);
+ if (result.success > 0) await reloadFromFirstPage(requestedScope);
},
clearSelection: () => (selectedIds = [])
});
@@ -161,11 +180,13 @@
function handleBulkAllMatching() {
if (!canManageVuln) return;
- const requestedEnvId = currentEnvId;
+ const requestedScope = scope;
const restore = showIgnored;
const filters = toBulkVulnerabilityFilters(withVulnerabilityToggles(requestOptions, { showIgnored, fixAvailable }));
const count = matchingCount;
- const environment = currentEnvName;
+ const picked = environmentFilterIds(requestOptions.filters?.[ENVIRONMENT_FILTER]);
+ const environments = manageEnvironments.filter((env) => picked.length === 0 || picked.includes(env.id));
+ const environment = confirmEnvironment(environments.map((env) => env.id));
confirmAndRun({
title: restore ? m.vuln_bulk_restore_confirm_title({ count }) : m.vuln_bulk_ignore_confirm_title({ count }),
message: restore
@@ -173,16 +194,20 @@
: m.vuln_bulk_ignore_all_matching_confirm_message({ count, environment }),
confirmLabel: restore ? m.vuln_bulk_restore() : m.common_ignore(),
setLoading: (loading) => (bulkInFlight = loading),
- run: () =>
- restore
- ? vulnerabilityService.bulkUnignoreVulnerabilities(filters, requestedEnvId)
- : vulnerabilityService.bulkIgnoreVulnerabilities(filters, requestedEnvId),
+ run: async () => {
+ const results = await settleAcrossEnvironments(environments, (id) =>
+ restore
+ ? vulnerabilityService.bulkUnignoreVulnerabilities(filters, id)
+ : vulnerabilityService.bulkIgnoreVulnerabilities(filters, id)
+ );
+ return { affectedCount: results.reduce((total, { value }) => total + value.affectedCount, 0) };
+ },
failureMessage: restore ? m.vuln_bulk_restore_failed() : m.vuln_bulk_ignore_failed(),
onSuccess: async ({ affectedCount }) => {
toast.success(
restore ? m.vuln_bulk_restore_success({ count: affectedCount }) : m.vuln_bulk_ignore_success({ count: affectedCount })
);
- await reloadFromFirstPage(requestedEnvId);
+ await reloadFromFirstPage(requestedScope);
}
});
}
@@ -218,15 +243,15 @@
async function handleUnignoreVulnerability(item: VulnerabilityRow) {
if (!canManageVuln) return;
- const requestedEnvId = currentEnvId;
+ const requestedScope = scope;
const ignoreId = item.ignoreId;
if (!ignoreId) return;
await handleApiResultWithCallbacks({
- result: await tryCatch(vulnerabilityService.unignoreVulnerability(ignoreId, requestedEnvId)),
+ result: await tryCatch(vulnerabilityService.unignoreVulnerability(ignoreId, item.environmentId)),
message: m.vuln_unignore_failed(),
onSuccess: async () => {
toast.success(m.vuln_unignore_success());
- if (requestedEnvId !== currentEnvId) return;
+ if (requestedScope !== scope) return;
await handleApiResultWithCallbacks({
result: await tryCatch(refreshVulnerabilityTable(requestOptions)),
message: m.common_refresh_failed({ resource: m.vuln_title() })
@@ -241,7 +266,7 @@
async function refreshImageNameFilterOptions(options?: SearchPaginationSortRequest): Promise<string[]> {
if (!vulnerabilityManagementEnabled) return [];
- const requestedEnvId = currentEnvId;
+ const requestedScope = scope;
const severity = resolveSeverityFilter(options);
const request: SearchPaginationSortRequest = {
filters: severity ? { severity } : undefined
@@ -249,8 +274,11 @@
const operationResult = await tryCatch(
(async () => {
- const optionsResponse = await vulnerabilityService.getAllVulnerabilityImageOptionsForEnvironment(requestedEnvId, request);
- if (vulnerabilityManagementEnabled && requestedEnvId === currentEnvId) imageNameFilterOptions = optionsResponse;
+ const { values } = await collectAcrossEnvironments(vulnerabilityEnvironments(), (id, config) =>
+ vulnerabilityService.getAllVulnerabilityImageOptionsForEnvironment(id, request, config)
+ );
+ const optionsResponse = [...new Set(values.flatMap((result) => result.value))].sort();
+ if (vulnerabilityManagementEnabled && requestedScope === scope) imageNameFilterOptions = optionsResponse;
return optionsResponse;
})()
);
@@ -261,16 +289,25 @@
return operationResult.error !== null ? imageNameFilterOptions : operationResult.data;
}
+ // Only the latest request is applied, so a slow response for an earlier filter cannot replace newer rows.
+ let latestTableRequest = 0;
async function refreshVulnerabilityTable(options: SearchPaginationSortRequest) {
if (!vulnerabilityManagementEnabled) return vulnerabilities;
- const requestedEnvId = currentEnvId;
+ const requestedScope = scope;
+ const tableRequest = ++latestTableRequest;
const request = mapVulnerabilityRequest(withVulnerabilityToggles(options, { showIgnored, fixAvailable }));
const [response, optionsResponse] = await Promise.all([
- vulnerabilityService.getAllVulnerabilitiesForEnvironment(requestedEnvId, request),
+ fetchAcrossEnvironments(
+ vulnerabilityEnvironments(),
+ request,
+ (id, request, config) => vulnerabilityService.getAllVulnerabilitiesForEnvironment(id, request, config),
+ vulnerabilitySortValue
+ ),
refreshImageNameFilterOptions(request)
]);
- if (!vulnerabilityManagementEnabled || requestedEnvId !== currentEnvId) return vulnerabilities;
+ if (!vulnerabilityManagementEnabled || requestedScope !== scope || tableRequest !== latestTableRequest)
+ return vulnerabilities;
const mapped = mapVulnerabilityPage(response, request);
vulnerabilities = mapped;
// Row ids are page-position keys, so replacing the rows invalidates the selection.
@@ -285,23 +322,28 @@
async function handleExportCsv() {
if (!vulnerabilityManagementEnabled) return;
- const requestedEnvId = currentEnvId;
+ const requestedScope = scope;
const request = mapVulnerabilityRequest(
withVulnerabilityToggles({ ...requestOptions, pagination: undefined }, { showIgnored, fixAvailable })
);
- const operationResult = await tryCatch(vulnerabilityService.exportVulnerabilitiesForEnvironment(requestedEnvId, request));
- if (!mounted || requestedEnvId !== currentEnvId) return;
+ // The table's environment filter is applied here; the export API never receives it.
+ const picked = environmentFilterIds(requestOptions.filters?.[ENVIRONMENT_FILTER]);
+ const environments = vulnerabilityEnvironments().filter((env) => picked.length === 0 || picked.includes(env.id));
+ const operationResult = await tryCatch(
+ settleAcrossEnvironments(environments, (id) => vulnerabilityService.exportVulnerabilitiesForEnvironment(id, request))
+ );
+ if (!mounted || requestedScope !== scope) return;
if (operationResult.error !== null) {
console.error('Failed to export vulnerabilities:', operationResult.error);
toast.error(m.vuln_export_failed());
return;
}
- downloadBlob(operationResult.data.blob, operationResult.data.filename);
+ for (const { value } of operationResult.data) downloadBlob(value.blob, value.filename);
}
async function handleIgnoreVulnerability(item: VulnerabilityRow) {
if (!canManageVuln) return;
- const requestedEnvId = currentEnvId;
+ const requestedScope = scope;
const payload = {
imageId: item.imageId || '',
vulnerabilityId: item.vulnerabilityId || '',
@@ -309,11 +351,11 @@
installedVersion: item.installedVersion || ''
};
await handleApiResultWithCallbacks({
- result: await tryCatch(vulnerabilityService.ignoreVulnerability(payload, requestedEnvId)),
+ result: await tryCatch(vulnerabilityService.ignoreVulnerability(payload, item.environmentId)),
message: m.vuln_ignore_failed(),
onSuccess: async () => {
toast.success(m.vuln_ignore_success({ cve: item.vulnerabilityId }));
- if (requestedEnvId !== currentEnvId) return;
+ if (requestedScope !== scope) return;
await handleApiResultWithCallbacks({
result: await tryCatch(refreshVulnerabilityTable(requestOptions)),
message: m.common_refresh_failed({ resource: m.vuln_title() })
@@ -323,6 +365,7 @@
}
const columns = $derived([
+ ...environmentColumns<VulnerabilityRow>(),
{ accessorKey: 'vulnerabilityId', title: 'CVE', cell: CveCol },
{ accessorKey: 'pkgName', title: m.vuln_package(), cell: PackageCell },
{ id: 'vulnSeverity', accessorKey: 'severity', title: m.events_col_severity(), sortable: true, cell: SeverityCell },
@@ -374,7 +417,7 @@
{/snippet}
{#snippet ImageCell({ item }: { item: VulnerabilityRow })}
- <a class="truncate text-sm font-medium hover:underline" href="/images/{item.imageId}">
+ <a class="truncate text-sm font-medium hover:underline" href={environmentHref(`/images/${item.imageId}`, item.environmentId)}>
{item.imageName || item.imageId}
</a>
{/snippet}
@@ -430,13 +473,14 @@
{#snippet rowActions({ item }: { item: VulnerabilityRow })}
<RowActionsMenu>
+ {@const canManageRow = hasPermission('vulnerabilities:manage', item.environmentId)}
{#if item.ignored}
- <DropdownMenu.Item onclick={() => handleUnignoreVulnerability(item)}>
+ <DropdownMenu.Item onclick={() => handleUnignoreVulnerability(item)} disabled={!canManageRow}>
<EyeOnIcon class="size-4" />
{m.vuln_unignore()}
</DropdownMenu.Item>
{:else}
- <DropdownMenu.Item onclick={() => handleIgnoreVulnerability(item)}>
+ <DropdownMenu.Item onclick={() => handleIgnoreVulnerability(item)} disabled={!canManageRow}>
<EyeOffIcon class="size-4" />
{m.vuln_ignore()}
</DropdownMenu.Item>
diff --git a/frontend/src/routes/(app)/settings/+layout.svelte b/frontend/src/routes/(app)/settings/+layout.svelte
index ccecea419..5be7eb7b0 100644
--- a/frontend/src/routes/(app)/settings/+layout.svelte
+++ b/frontend/src/routes/(app)/settings/+layout.svelte
@@ -9,12 +9,13 @@
import { SettingsIcon, ArrowRightIcon, ArrowLeftIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import settingsStore from '#lib/stores/config-store.svelte.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { SettingsFormContext, SettingsFormState } from '#lib/types/settings-form.js';
import { cn } from '#lib/utils.js';
import type { LayoutProps } from './$types';
- let { children }: LayoutProps = $props();
+ let { children, data }: LayoutProps = $props();
let isSubPage = $derived(page.url.pathname !== '/settings');
let currentPageName = $derived(page.url.pathname.split('/').pop() || 'settings');
@@ -112,7 +113,13 @@
<div>
<div class="w-full max-w-none">
- {@render children()}
+ <!-- Settings forms read their values once, so after an environment switch the page waits for that
+ environment's settings and is then rebuilt with them. -->
+ {#if data.settingsEnvironmentId === environmentStore.selected?.id}
+ {#key data.settingsEnvironmentId}
+ {@render children()}
+ {/key}
+ {/if}
</div>
</div>
</main>
diff --git a/frontend/src/routes/(app)/settings/+layout.ts b/frontend/src/routes/(app)/settings/+layout.ts
index 6378c0847..8336b8623 100644
--- a/frontend/src/routes/(app)/settings/+layout.ts
+++ b/frontend/src/routes/(app)/settings/+layout.ts
@@ -1,4 +1,5 @@
import { settingsService } from '#lib/services/settings-service.js';
+import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { tryCatch } from '#lib/utils/try-catch.js';
export const load = async ({ parent }) => {
@@ -9,6 +10,8 @@ export const load = async ({ parent }) => {
return {
settings,
+ // The root load has selected the environment these settings belong to.
+ settingsEnvironmentId: environmentStore.selected?.id,
oidcStatus
};
})()
diff --git a/frontend/src/routes/(app)/settings/activity/+page.svelte b/frontend/src/routes/(app)/settings/activity/+page.svelte
index d8a4d2c4a..461901c0c 100644
--- a/frontend/src/routes/(app)/settings/activity/+page.svelte
+++ b/frontend/src/routes/(app)/settings/activity/+page.svelte
@@ -45,6 +45,7 @@
icon={ActivityIcon}
pageType="form"
showReadOnlyTag={isReadOnly}
+ environmentPicker
>
{#snippet mainContent()}
<fieldset disabled={isReadOnly} class="relative space-y-8">
diff --git a/frontend/src/routes/(app)/settings/builds/+page.svelte b/frontend/src/routes/(app)/settings/builds/+page.svelte
index 790a63347..04f23263e 100644
--- a/frontend/src/routes/(app)/settings/builds/+page.svelte
+++ b/frontend/src/routes/(app)/settings/builds/+page.svelte
@@ -91,6 +91,7 @@
icon={CodeIcon}
pageType="form"
showReadOnlyTag={isReadOnly}
+ environmentPicker
>
{#snippet mainContent()}
<fieldset disabled={isReadOnly} class="relative space-y-8">
diff --git a/frontend/src/routes/(app)/settings/diagnostics/+page.svelte b/frontend/src/routes/(app)/settings/diagnostics/+page.svelte
index 33c2498f6..aef3208a1 100644
--- a/frontend/src/routes/(app)/settings/diagnostics/+page.svelte
+++ b/frontend/src/routes/(app)/settings/diagnostics/+page.svelte
@@ -18,7 +18,8 @@
ConnectionIcon,
DownloadIcon,
EnvironmentsIcon,
- ArrowDownIcon
+ ArrowDownIcon,
+ LayersIcon
} from '#lib/icons/index.js';
import { SettingsPageLayout } from '#lib/layouts/index.js';
import type { SettingsStatCard } from '#lib/layouts/types.js';
@@ -30,10 +31,11 @@
import { createDiagnosticsWebSocket, type DiagnosticsWebSocket } from '#lib/utils/ws.js';
import DiagnosticActorPanel from './components/diagnostic-actor-panel.svelte';
+ import DiagnosticGoroutinePanel from './components/diagnostic-goroutine-panel.svelte';
import DiagnosticLeakPanel from './components/diagnostic-leak-panel.svelte';
import DiagnosticLogPanel from './components/diagnostic-log-panel.svelte';
- type DiagnosticsTab = 'overview' | 'connections' | 'actors' | 'logs' | 'profiling';
+ type DiagnosticsTab = 'overview' | 'connections' | 'actors' | 'goroutines' | 'logs' | 'profiling';
let diag = $state<Diagnostics | null>(null);
let paused = $state(false);
@@ -121,6 +123,7 @@
badge: totalConnections || undefined
},
{ value: 'actors', label: m.diagnostics_tab_actors(), icon: EnvironmentsIcon },
+ { value: 'goroutines', label: m.goroutines(), icon: LayersIcon },
{ value: 'logs', label: m.common_logs(), icon: ActivityIcon },
{
value: 'profiling',
@@ -503,6 +506,10 @@
<DiagnosticActorPanel />
</Tabs.Content>
+ <Tabs.Content value="goroutines" class="mt-6">
+ <DiagnosticGoroutinePanel />
+ </Tabs.Content>
+
<Tabs.Content value="logs" class="mt-6">
<DiagnosticLogPanel height="min(70vh, 640px)" />
</Tabs.Content>
diff --git a/frontend/src/routes/(app)/settings/diagnostics/components/diagnostic-goroutine-panel.svelte b/frontend/src/routes/(app)/settings/diagnostics/components/diagnostic-goroutine-panel.svelte
new file mode 100644
index 000000000..7f0e5a1b1
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/diagnostics/components/diagnostic-goroutine-panel.svelte
@@ -0,0 +1,137 @@
+<script lang="ts">
+ import { onMount } from 'svelte';
+ import { SvelteSet } from 'svelte/reactivity';
+ import { slide } from 'svelte/transition';
+
+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';
+ import SearchInput from '#lib/components/form/search-input.svelte';
+ import * as Alert from '#lib/components/ui/alert/index.js';
+ import * as Table from '#lib/components/ui/table/index.js';
+ import { ArrowRightIcon } from '#lib/icons/index.js';
+ import { m } from '#lib/paraglide/messages.js';
+ import { diagnosticsService } from '#lib/services/diagnostics-service.js';
+ import { LOCAL_DOCKER_ENVIRONMENT_ID } from '#lib/stores/environment.store.svelte.js';
+ import type { GoroutineGroup, GoroutineProfile } from '#lib/types/diagnostics.js';
+ import { cn } from '#lib/utils.js';
+ import { extractApiErrorMessage } from '#lib/utils/api.js';
+ import { tryCatch } from '#lib/utils/try-catch.js';
+
+ let profile = $state.raw<GoroutineProfile | null>(null);
+ let loading = $state(false);
+ let error = $state<string | null>(null);
+ let query = $state('');
+ const expanded = new SvelteSet<string>();
+
+ // The backend groups by identical stack, so the frames identify a group across refreshes.
+ const groups = $derived(
+ (profile?.groups ?? []).map((group) => ({
+ key: group.frames.map((f) => `${f.function}@${f.file}:${f.line}`).join('|'),
+ group
+ }))
+ );
+
+ const filtered = $derived.by(() => {
+ const q = query.trim().toLowerCase();
+ if (!q) return groups;
+ return groups.filter(({ group }) => matches(group, q));
+ });
+
+ function matches(group: GoroutineGroup, q: string): boolean {
+ return (
+ group.label.toLowerCase().includes(q) ||
+ group.frames.some((f) => f.function.toLowerCase().includes(q) || f.file.toLowerCase().includes(q))
+ );
+ }
+
+ function toggle(key: string) {
+ if (expanded.has(key)) expanded.delete(key);
+ else expanded.add(key);
+ }
+
+ async function load() {
+ loading = true;
+ const result = await tryCatch(diagnosticsService.getGoroutinesForEnvironment(LOCAL_DOCKER_ENVIRONMENT_ID));
+ loading = false;
+ if (result.error !== null) {
+ error = extractApiErrorMessage(result.error);
+ return;
+ }
+ profile = result.data;
+ error = null;
+ }
+
+ onMount(load);
+</script>
+
+<div class="space-y-4">
+ <p class="text-sm text-muted-foreground">{m.diagnostics_goroutines_hint()}</p>
+
+ <div class="flex flex-wrap items-center gap-3">
+ {#if profile}
+ <span class="text-sm font-medium tabular-nums">
+ {m.diagnostics_goroutines_summary({ total: profile.total, groups: profile.groups.length })}
+ </span>
+ {/if}
+ <div class="min-w-48 flex-1">
+ <SearchInput
+ bind:value={query}
+ onClear={() => (query = '')}
+ placeholder={m.diagnostics_goroutines_filter_placeholder()}
+ aria-label={m.common_search()}
+ />
+ </div>
+ <ArcaneButton action="refresh" size="sm" {loading} onclick={load} />
+ </div>
+
+ {#if error}
+ <Alert.Root variant="destructive">
+ <Alert.Title>{m.common_unavailable()}</Alert.Title>
+ <Alert.Description>{error}</Alert.Description>
+ </Alert.Root>
+ {:else if !profile}
+ <p class="py-8 text-sm text-muted-foreground">{m.common_loading()}</p>
+ {:else if filtered.length}
+ <div class="overflow-x-auto">
+ <Table.Root>
+ <Table.Header>
+ <Table.Row variant="static">
+ <Table.Head variant="expander"></Table.Head>
+ <Table.Head>{m.diagnostics_goroutines_count()}</Table.Head>
+ <Table.Head>{m.diagnostics_goroutines_entry_point()}</Table.Head>
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ {#each filtered as { key, group } (key)}
+ {@const open = expanded.has(key)}
+ <Table.Row data-expanded={open ? true : undefined} onclick={() => toggle(key)}>
+ <Table.Cell variant="expander">
+ <ArrowRightIcon
+ class={cn('size-4 text-muted-foreground transition-transform duration-200', open && 'rotate-90')}
+ aria-hidden="true"
+ />
+ </Table.Cell>
+ <Table.Cell><span class="font-semibold tabular-nums">{group.count}</span></Table.Cell>
+ <Table.Cell><span class="font-mono text-xs break-all">{group.label}</span></Table.Cell>
+ </Table.Row>
+ {#if open}
+ <Table.Row variant="detail">
+ <Table.Cell colspan={3} variant="flush">
+ <ol transition:slide={{ duration: 200 }} class="space-y-1.5 px-6 py-4 font-mono text-2xs">
+ {#each group.frames as frame}
+ <li>
+ <div class="break-all">{frame.function}</div>
+ <div class="break-all text-muted-foreground">{frame.file}:{frame.line}</div>
+ </li>
+ {/each}
+ </ol>
+ </Table.Cell>
+ </Table.Row>
+ {/if}
+ {/each}
+ </Table.Body>
+ </Table.Root>
+ </div>
+ {:else}
+ <p class="py-8 text-sm text-muted-foreground">{m.common_no_results_found()}</p>
+ {/if}
+</div>
diff --git a/frontend/src/routes/(app)/settings/notifications/+page.svelte b/frontend/src/routes/(app)/settings/notifications/+page.svelte
index 9667f60d3..76a962237 100644
--- a/frontend/src/routes/(app)/settings/notifications/+page.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/+page.svelte
@@ -258,6 +258,7 @@
icon={NotificationsIcon}
pageType="form"
showReadOnlyTag={isReadOnly}
+ environmentPicker
>
{#snippet mainContent()}
<fieldset disabled={isReadOnly} class="relative w-full min-w-0">
diff --git a/frontend/src/routes/(app)/settings/timeouts/+page.svelte b/frontend/src/routes/(app)/settings/timeouts/+page.svelte
index 46fa2e44f..ca303c2e3 100644
--- a/frontend/src/routes/(app)/settings/timeouts/+page.svelte
+++ b/frontend/src/routes/(app)/settings/timeouts/+page.svelte
@@ -55,6 +55,7 @@
icon={ClockIcon}
pageType="form"
showReadOnlyTag={isReadOnly}
+ environmentPicker
>
{#snippet mainContent()}
<fieldset disabled={isReadOnly} class="relative space-y-8">
diff --git a/frontend/src/routes/(app)/settings/webhooks/+page.svelte b/frontend/src/routes/(app)/settings/webhooks/+page.svelte
index 3f234030e..629bf65c5 100644
--- a/frontend/src/routes/(app)/settings/webhooks/+page.svelte
+++ b/frontend/src/routes/(app)/settings/webhooks/+page.svelte
@@ -74,6 +74,7 @@
icon={GlobeIcon}
pageType="management"
{actionButtons}
+ environmentPicker
>
{#snippet mainContent()}
<WebhookTable
diff --git a/frontend/src/routes/(app)/swarm/cluster/+page.svelte b/frontend/src/routes/(app)/swarm/cluster/+page.svelte
index b41dda79b..163bc3592 100644
--- a/frontend/src/routes/(app)/swarm/cluster/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/cluster/+page.svelte
@@ -359,6 +359,7 @@
class="pb-6"
{actionButtons}
{statCards}
+ environmentPicker
>
{#snippet mainContent()}
<div class="space-y-6 pb-6">
diff --git a/frontend/src/routes/(app)/swarm/nodes/+page.svelte b/frontend/src/routes/(app)/swarm/nodes/+page.svelte
index d7611cbb6..3bde7352d 100644
--- a/frontend/src/routes/(app)/swarm/nodes/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/nodes/+page.svelte
@@ -88,7 +88,7 @@
]);
</script>
-<ResourcePageLayout title={m.nodes()} subtitle={m.swarm_nodes_subtitle()} {actionButtons} {statCards}>
+<ResourcePageLayout title={m.nodes()} subtitle={m.swarm_nodes_subtitle()} {actionButtons} {statCards} environmentPicker>
{#snippet mainContent()}
<div class="space-y-4">
{#if uncoveredNodeCount > 0}
diff --git a/frontend/src/routes/(app)/swarm/services/+page.svelte b/frontend/src/routes/(app)/swarm/services/+page.svelte
index 4208617fa..aee5ab547 100644
--- a/frontend/src/routes/(app)/swarm/services/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/services/+page.svelte
@@ -91,7 +91,7 @@
/>
{/if}
-<ResourcePageLayout title={m.services()} subtitle={m.swarm_services_subtitle()} {actionButtons} {statCards}>
+<ResourcePageLayout title={m.services()} subtitle={m.swarm_services_subtitle()} {actionButtons} {statCards} environmentPicker>
{#snippet mainContent()}
<SwarmServicesTable bind:services bind:requestOptions />
{/snippet}
diff --git a/frontend/src/routes/(app)/swarm/stacks/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/+page.svelte
index 59df585f4..ed82bf915 100644
--- a/frontend/src/routes/(app)/swarm/stacks/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/stacks/+page.svelte
@@ -58,7 +58,13 @@
]);
</script>
-<ResourcePageLayout title={m.swarm_stacks_title()} subtitle={m.swarm_stacks_subtitle()} {actionButtons} {statCards}>
+<ResourcePageLayout
+ title={m.swarm_stacks_title()}
+ subtitle={m.swarm_stacks_subtitle()}
+ {actionButtons}
+ {statCards}
+ environmentPicker
+>
{#snippet mainContent()}
<SwarmStacksTable bind:stacks bind:requestOptions />
{/snippet}
diff --git a/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte
index 9f4b8ebb4..9d9af0853 100644
--- a/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte
@@ -10,6 +10,7 @@
import DockerRunConverterDialog from '#lib/components/compose/docker-run-converter-dialog.svelte';
import TemplateSelectionDialog from '#lib/components/dialogs/template-selection-dialog.svelte';
import EditorTabStrip from '#lib/components/editor-tab-strip.svelte';
+ import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';
import ResizableSplit from '#lib/components/resizable-split.svelte';
import { Checkbox } from '#lib/components/ui/checkbox/index.js';
import { Label } from '#lib/components/ui/label/index.js';
@@ -333,6 +334,7 @@
<form class="flex h-full min-h-0 flex-1 flex-col gap-3 px-2 pb-4 sm:px-6" onsubmit={preventDefault(handleSubmit)}>
{#if !isEditMode}
<div class="flex shrink-0 flex-wrap items-center gap-x-6 gap-y-3 rounded-lg border border-border bg-card px-4 py-3">
+ <EnvironmentDestinationSelect />
<div class="flex items-center gap-2">
<Checkbox
id="swarm-stack-prune"
diff --git a/frontend/src/routes/(app)/swarm/tasks/+page.svelte b/frontend/src/routes/(app)/swarm/tasks/+page.svelte
index dad306d6e..4ad3f53bf 100644
--- a/frontend/src/routes/(app)/swarm/tasks/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/tasks/+page.svelte
@@ -59,6 +59,7 @@
subtitle={nodeId ? m.swarm_tasks_subtitle_node_scoped() : m.swarm_tasks_subtitle()}
{actionButtons}
{statCards}
+ environmentPicker
>
{#snippet mainContent()}
<SwarmTasksTable bind:tasks bind:requestOptions {fetchTasks} />
diff --git a/frontend/src/routes/(app)/updates/+page.svelte b/frontend/src/routes/(app)/updates/+page.svelte
index 053167793..8b0e5e765 100644
--- a/frontend/src/routes/(app)/updates/+page.svelte
+++ b/frontend/src/routes/(app)/updates/+page.svelte
@@ -14,12 +14,14 @@
import { containerService, type ContainerListRequestOptions } from '#lib/services/container-service.js';
import { imageService } from '#lib/services/image-service.js';
import { projectService } from '#lib/services/project-service.js';
- import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+ import { environmentStore, type EnvironmentRef } from '#lib/stores/environment.store.svelte.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { extractApiErrorMessage } from '#lib/utils/api.js';
import { ensureStandaloneContainerUpdatesFilter, ensureUpdatesFilter } from '#lib/utils/docker.js';
+ import { actionEnvironments, fetchAcrossEnvironments, listScopes, settleAcrossEnvironments } from '#lib/utils/environments.js';
import { confirmAndApplyAllUpdates } from '#lib/utils/update-actions.js';
+ import { containerSortValue } from '../containers/container-table.helpers';
import ContainerUpdatesTable from './components/container-updates-table.svelte';
import ProjectUpdatesTable from './components/project-updates-table.svelte';
@@ -28,63 +30,85 @@
let containerRequestOptions = $derived(data.containerRequestOptions as ContainerListRequestOptions);
let projectRequestOptions = $derived(data.projectRequestOptions as SearchPaginationSortRequest);
- const envId = $derived(environmentStore.selected?.id || '0');
+ const scope = $derived(environmentStore.shownKey);
// The page loader already populated these keys, so no initialData is needed.
// Previous rows are kept only within the same environment, and results are
// tagged with their environment so a switch never shows another's rows.
const containersQuery = createQuery(() => {
- const queryEnvId = envId;
+ const queryScope = scope;
+ const environments = environmentStore.shown;
const options = ensureStandaloneContainerUpdatesFilter(containerRequestOptions);
return {
- queryKey: queryKeys.containers.list(queryEnvId, options),
- queryFn: () => containerService.getContainersForEnvironment(queryEnvId, options),
+ queryKey: queryKeys.containers.list(queryScope, options),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ environments,
+ options,
+ (id, request, config) => containerService.getContainersForEnvironment(id, request, config),
+ containerSortValue
+ ),
placeholderData: (previous, query) => {
- if (query?.queryKey[1] === queryEnvId) return previous;
+ if (query?.queryKey[1] === queryScope) return previous;
return undefined;
},
- select: (value) => ({ envId: queryEnvId, value }),
+ select: (value) => ({ envId: queryScope, value }),
refetchOnMount: false
};
});
const projectsQuery = createQuery(() => {
- const queryEnvId = envId;
+ const queryScope = scope;
+ const environments = environmentStore.shown;
const options = ensureUpdatesFilter(projectRequestOptions);
return {
- queryKey: queryKeys.projects.list(queryEnvId, options),
- queryFn: () => projectService.getProjectsForEnvironment(queryEnvId, options),
+ queryKey: queryKeys.projects.list(queryScope, options),
+ queryFn: () =>
+ fetchAcrossEnvironments(environments, options, (id, request, config) =>
+ projectService.getProjectsForEnvironment(id, request, config)
+ ),
placeholderData: (previous, query) => {
- if (query?.queryKey[1] === queryEnvId) return previous;
+ if (query?.queryKey[1] === queryScope) return previous;
return undefined;
},
- select: (value) => ({ envId: queryEnvId, value }),
+ select: (value) => ({ envId: queryScope, value }),
refetchOnMount: false
};
});
- const containers = $derived(containersQuery.data?.envId === envId ? containersQuery.data.value : null);
- const projects = $derived(projectsQuery.data?.envId === envId ? projectsQuery.data.value : null);
+ const containers = $derived(containersQuery.data?.envId === scope ? containersQuery.data.value : null);
+ const projects = $derived(projectsQuery.data?.envId === scope ? projectsQuery.data.value : null);
// Table refreshes write into the cache entry for the environment and request
// they were issued for, so a late response never replaces another
// environment's active table. Failures reject so callers can report them;
// the query's error state also renders inline.
async function refreshContainers(options: ContainerListRequestOptions) {
- const requestedEnvId = envId;
+ const requestedScope = scope;
+ const environments = environmentStore.shown;
const requestedOptions = ensureStandaloneContainerUpdatesFilter(options);
await queryClient.fetchQuery({
- queryKey: queryKeys.containers.list(requestedEnvId, requestedOptions),
- queryFn: () => containerService.getContainersForEnvironment(requestedEnvId, requestedOptions)
+ queryKey: queryKeys.containers.list(requestedScope, requestedOptions),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ environments,
+ requestedOptions,
+ (id, request, config) => containerService.getContainersForEnvironment(id, request, config),
+ containerSortValue
+ )
});
}
async function refreshProjects(options: SearchPaginationSortRequest) {
- const requestedEnvId = envId;
+ const requestedScope = scope;
+ const environments = environmentStore.shown;
const requestedOptions = ensureUpdatesFilter(options);
await queryClient.fetchQuery({
- queryKey: queryKeys.projects.list(requestedEnvId, requestedOptions),
- queryFn: () => projectService.getProjectsForEnvironment(requestedEnvId, requestedOptions)
+ queryKey: queryKeys.projects.list(requestedScope, requestedOptions),
+ queryFn: () =>
+ fetchAcrossEnvironments(environments, requestedOptions, (id, request, config) =>
+ projectService.getProjectsForEnvironment(id, request, config)
+ )
});
}
@@ -92,25 +116,29 @@
// response for this environment. The table refetches its own rows afterwards,
// so other cached lists are only marked stale here.
async function invalidateContainerQueries() {
- const requestedEnvId = envId;
await Promise.all([
- queryClient.invalidateQueries({ queryKey: ['containers', requestedEnvId], refetchType: 'none' }),
- queryClient.invalidateQueries({ queryKey: ['container', requestedEnvId] })
+ ...listScopes(environmentStore.shown.map((env) => env.id)).map((scope) =>
+ queryClient.invalidateQueries({ queryKey: ['containers', scope], refetchType: 'none' })
+ ),
+ ...environmentStore.shown.map((env) => queryClient.invalidateQueries({ queryKey: ['container', env.id] }))
]);
}
const checkUpdatesMutation = createMutation(() => ({
- mutationKey: ['updates', 'check-all', envId],
- mutationFn: (requestedEnvId: string) => imageService.checkAllImages(requestedEnvId),
- onSuccess: async (_result, requestedEnvId) => {
+ mutationKey: ['updates', 'check-all', scope],
+ mutationFn: (environments: EnvironmentRef[]) =>
+ settleAcrossEnvironments(environments, (id) => imageService.checkAllImages(id)),
+ onSuccess: async (_result, environments) => {
toast.success(m.images_update_check_completed());
await Promise.all([
- queryClient.invalidateQueries({ queryKey: ['containers', requestedEnvId] }),
- queryClient.invalidateQueries({ queryKey: ['container', requestedEnvId] }),
- queryClient.invalidateQueries({ queryKey: ['projects', requestedEnvId] }),
- queryClient.invalidateQueries({ queryKey: queryKeys.projects.environment(requestedEnvId) }),
- queryClient.invalidateQueries({ queryKey: ['images', requestedEnvId] }),
- queryClient.invalidateQueries({ queryKey: ['image', requestedEnvId] })
+ ...listScopes(environments.map((env) => env.id)).flatMap((scope) =>
+ ['containers', 'projects', 'images'].map((resource) => queryClient.invalidateQueries({ queryKey: [resource, scope] }))
+ ),
+ ...environments.flatMap((env) => [
+ queryClient.invalidateQueries({ queryKey: ['container', env.id] }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.projects.environment(env.id) }),
+ queryClient.invalidateQueries({ queryKey: ['image', env.id] })
+ ])
]);
},
onError: (error) => {
@@ -173,7 +201,7 @@
action: 'inspect',
label: m.images_check_updates(),
loadingLabel: m.common_action_checking(),
- onclick: () => checkUpdatesMutation.mutate(envId),
+ onclick: () => checkUpdatesMutation.mutate(actionEnvironments('image-updates:check')),
loading: isChecking,
disabled: isChecking
},
@@ -235,7 +263,7 @@
<TabBar items={tabItems} value={effectiveTab} onValueChange={handleTabChange} />
<Tabs.Content value="containers" class="mt-4">
- {#key `${envId}-containers`}
+ {#key `${scope}-containers`}
{#if containersQuery.isError}
<EmptyState
icon={ContainersIcon}
@@ -258,7 +286,7 @@
</Tabs.Content>
<Tabs.Content value="projects" class="mt-4">
- {#key `${envId}-projects`}
+ {#key `${scope}-projects`}
{#if projectsQuery.isError}
<EmptyState
icon={ProjectsIcon}
diff --git a/frontend/src/routes/(app)/updates/+page.ts b/frontend/src/routes/(app)/updates/+page.ts
index 36d72d1a4..1e8019ed3 100644
--- a/frontend/src/routes/(app)/updates/+page.ts
+++ b/frontend/src/routes/(app)/updates/+page.ts
@@ -5,14 +5,17 @@ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { throwPageLoadError } from '#lib/utils/api.js';
import { ensureStandaloneContainerUpdatesFilter, ensureUpdatesFilter } from '#lib/utils/docker.js';
+import { fetchAcrossEnvironments } from '#lib/utils/environments.js';
import { resolveInitialTableRequest } from '#lib/utils/tables.js';
import { tryCatch } from '#lib/utils/try-catch.js';
+import { containerSortValue } from '../containers/container-table.helpers';
import type { PageLoad } from './$types';
export const load: PageLoad = async ({ parent }) => {
const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const environments = await environmentStore.getShownEnvironments();
+ const scope = environmentStore.shownKey;
const containerRequestOptions = ensureStandaloneContainerUpdatesFilter(
resolveInitialTableRequest('arcane-updates-container-table', {
@@ -32,12 +35,21 @@ export const load: PageLoad = async ({ parent }) => {
(async () =>
Promise.all([
queryClient.query({
- queryKey: queryKeys.containers.list(envId, containerRequestOptions),
- queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)
+ queryKey: queryKeys.containers.list(scope, containerRequestOptions),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ environments,
+ containerRequestOptions,
+ (id, request, config) => containerService.getContainersForEnvironment(id, request, config),
+ containerSortValue
+ )
}),
queryClient.query({
- queryKey: queryKeys.projects.list(envId, projectRequestOptions),
- queryFn: () => projectService.getProjectsForEnvironment(envId, projectRequestOptions)
+ queryKey: queryKeys.projects.list(scope, projectRequestOptions),
+ queryFn: () =>
+ fetchAcrossEnvironments(environments, projectRequestOptions, (id, request, config) =>
+ projectService.getProjectsForEnvironment(id, request, config)
+ )
})
]))()
);
diff --git a/frontend/src/routes/(app)/updates/components/container-updates-table.svelte b/frontend/src/routes/(app)/updates/components/container-updates-table.svelte
index 2fa9c34f1..35575a9fd 100644
--- a/frontend/src/routes/(app)/updates/components/container-updates-table.svelte
+++ b/frontend/src/routes/(app)/updates/components/container-updates-table.svelte
@@ -6,6 +6,7 @@
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import CheckedAtCell from '#lib/components/arcane-table/cells/checked-at-cell.svelte';
import DigestCell from '#lib/components/arcane-table/cells/digest-cell.svelte';
+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';
import {
UniversalMobileCard,
type BulkAction,
@@ -32,13 +33,25 @@
import { confirmAndUpdateContainer } from '#lib/utils/container-actions.js';
import { isAutoUpdateLabelDisabled } from '#lib/utils/container-auto-update.js';
import { createContainerUpdateActivityTracker } from '#lib/utils/container-update-activities.js';
+ import {
+ environmentHref,
+ hasShownPermission,
+ listScopes,
+ rowKey,
+ type EnvironmentPage,
+ type EnvironmentRow
+ } from '#lib/utils/environments.js';
import { formatImageUpdateCheckedAt, formatImageUpdateValue } from '#lib/utils/image-updates.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import { getContainerDisplayName } from '../../containers/container-table.helpers';
+ type ContainerRow = EnvironmentRow<ContainerSummaryDto>;
type ContainerUpdateRow = {
id: string;
+ environmentId: string;
+ environmentName: string;
+ environmentTagged: true;
containerId: string;
name: string;
imageRef: string;
@@ -52,11 +65,11 @@
statusAvailable: boolean;
autoUpdateTitle: string;
updateInfo?: ImageUpdateInfoDto;
- container: ContainerSummaryDto;
+ container: ContainerRow;
};
interface Props {
- containers: ContainersPaginatedResponse;
+ containers: EnvironmentPage<ContainersPaginatedResponse>;
requestOptions: SearchPaginationSortRequest;
// Refreshed rows arrive through the `containers` prop once the parent's query updates.
onRefreshData: (options: ContainerListRequestOptions) => Promise<void>;
@@ -72,15 +85,19 @@
let bulkUpdating = $state(false);
let updateTableMounted = false;
const queryClient = useQueryClient();
- const currentEnvironmentId = $derived(environmentStore.selected?.id || '0');
+ const scope = $derived(environmentStore.shownKey);
const updateActivities = createContainerUpdateActivityTracker(
- () => currentEnvironmentId,
+ () => environmentStore.shown.map((env) => env.id),
() => {
if (!updateTableMounted) return;
void refreshRows();
// Compose containers also drive the project update badges.
- void queryClient.invalidateQueries({ queryKey: ['projects', currentEnvironmentId] });
- void queryClient.invalidateQueries({ queryKey: ['project', currentEnvironmentId] });
+ for (const listScope of listScopes(environmentStore.shown.map((env) => env.id))) {
+ void queryClient.invalidateQueries({ queryKey: ['projects', listScope] });
+ }
+ for (const env of environmentStore.shown) {
+ void queryClient.invalidateQueries({ queryKey: ['project', env.id] });
+ }
}
);
onMount(() => {
@@ -92,7 +109,7 @@
};
});
- function mapContainerRow(container: ContainerSummaryDto): ContainerUpdateRow {
+ function mapContainerRow(container: ContainerRow): ContainerUpdateRow {
const name = getContainerDisplayName(container);
const labelControlled = isAutoUpdateLabelDisabled(container.labels);
const statusAvailable = typeof container.autoUpdateEnabled === 'boolean';
@@ -107,6 +124,9 @@
}
return {
id: container.id,
+ environmentId: container.environmentId,
+ environmentName: container.environmentName,
+ environmentTagged: true,
containerId: container.id,
name,
imageRef: container.image,
@@ -127,13 +147,14 @@
data: (containers.data ?? []).map(mapContainerRow)
});
- const columns = [
+ const columns = $derived([
+ ...environmentColumns<ContainerUpdateRow>(),
{ accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },
{ accessorKey: 'imageRef', title: m.common_image(), sortable: true, cell: ImageCell },
{ accessorKey: 'currentValue', title: m.common_current(), sortable: false, cellComponent: DigestCell },
{ accessorKey: 'latestValue', title: m.image_update_latest_label(), sortable: false, cellComponent: DigestCell },
{ accessorKey: 'checkedAt', title: m.common_updated(), sortable: false, cellComponent: CheckedAtCell }
- ] satisfies ColumnSpec<ContainerUpdateRow>[];
+ ] satisfies ColumnSpec<ContainerUpdateRow>[]);
const mobileFields = [
{ id: 'imageRef', label: m.common_image(), defaultVisible: true },
@@ -146,15 +167,15 @@
await onRefreshData(requestOptions as ContainerListRequestOptions);
}
- async function handleUpdateContainer(container: ContainerSummaryDto) {
+ async function handleUpdateContainer(container: ContainerRow) {
const containerName = getContainerDisplayName(container);
confirmAndUpdateContainer({
containerId: container.id,
containerName,
- environmentId: currentEnvironmentId,
+ environmentId: container.environmentId,
setLoading: (loading) => {
- updatingContainerIds = { ...updatingContainerIds, [container.id]: loading };
+ updatingContainerIds = { ...updatingContainerIds, [rowKey(container)]: loading };
},
onRefresh: () => (updateTableMounted ? refreshRows() : undefined),
onAccepted: (activity) => {
@@ -169,9 +190,9 @@
// the new status back.
async function handleToggleAutoUpdate(item: ContainerUpdateRow) {
const enable = item.autoUpdateDisabled;
- togglingAutoUpdateIds = { ...togglingAutoUpdateIds, [item.containerId]: true };
+ togglingAutoUpdateIds = { ...togglingAutoUpdateIds, [rowKey(item)]: true };
try {
- const operationResult = await tryCatch(containerService.setAutoUpdate(item.containerId, enable));
+ const operationResult = await tryCatch(containerService.setAutoUpdate(item.containerId, enable, item.environmentId));
if (operationResult.error !== null) {
toast.error(m.auto_update_failed(), { description: extractApiErrorMessage(operationResult.error) });
return;
@@ -190,41 +211,37 @@
});
}
} finally {
- togglingAutoUpdateIds = { ...togglingAutoUpdateIds, [item.containerId]: false };
+ togglingAutoUpdateIds = { ...togglingAutoUpdateIds, [rowKey(item)]: false };
}
}
function handleBulkUpdate(ids: string[]) {
- const updateEnvironmentId = currentEnvironmentId;
+ const updateScope = scope;
+ const tracksActivities = environmentStore.shown.every((env) => hasPermission('activities:read', env.id));
bulkConfirmAndRun({
ids,
title: m.updates_bulk_update_confirm_title({ count: ids.length }),
message: m.updates_bulk_update_confirm_message({ count: ids.length }),
confirmLabel: m.common_update(),
- run: (id) => containerService.updateContainer(id, updateEnvironmentId),
+ run: (id, environmentId) => containerService.updateContainer(id, environmentId),
messages: {
success: (count) => m.containers_bulk_update_accepted({ count }),
partial: (success, total, failed) => m.containers_bulk_update_accept_partial({ success, total, failed }),
failure: () => m.containers_bulk_update_accept_failed()
},
acceptanceOnly: true,
- activityLink: hasPermission('activities:read', updateEnvironmentId),
+ activityLink: hasShownPermission('activities:read'),
onItemSuccess: (_id, activity) => {
if (updateTableMounted) updateActivities.accept(activity);
},
setLoading: (loading) => (bulkUpdating = loading),
- onComplete: () =>
- updateTableMounted &&
- updateEnvironmentId === currentEnvironmentId &&
- !hasPermission('activities:read', updateEnvironmentId)
- ? refreshRows()
- : undefined,
+ onComplete: () => (updateTableMounted && updateScope === scope && !tracksActivities ? refreshRows() : undefined),
clearSelection: () => (selectedIds = [])
});
}
const bulkActions = $derived<BulkAction[]>(
- hasPermission('containers:autoupdate')
+ hasShownPermission('containers:autoupdate')
? [
{
id: 'update',
@@ -244,7 +261,7 @@
<div class="flex items-center gap-2">
<a
class="font-medium hover:underline {item.autoUpdateDisabled ? 'text-muted-foreground' : ''}"
- href={`/containers/${item.containerId}`}
+ href={environmentHref(`/containers/${item.containerId}`, item.environmentId)}
>
{item.name}
</a>
@@ -265,13 +282,10 @@
{/snippet}
{#snippet RowActions({ item }: { item: ContainerUpdateRow })}
- <IfPermitted perm="containers:autoupdate">
+ <IfPermitted perm="containers:autoupdate" envId={item.environmentId}>
<RowActionsMenu>
- <DropdownMenu.Item
- onclick={() => handleUpdateContainer(item.container)}
- disabled={!!updatingContainerIds[item.containerId]}
- >
- {#if updatingContainerIds[item.containerId]}
+ <DropdownMenu.Item onclick={() => handleUpdateContainer(item.container)} disabled={!!updatingContainerIds[rowKey(item)]}>
+ {#if updatingContainerIds[rowKey(item)]}
<Spinner class="size-4" />
{:else}
<UpdateIcon class="size-4" />
@@ -281,10 +295,10 @@
<DropdownMenu.Item
onclick={() => handleToggleAutoUpdate(item)}
- disabled={item.labelControlled || !item.statusAvailable || !!togglingAutoUpdateIds[item.containerId]}
+ disabled={item.labelControlled || !item.statusAvailable || !!togglingAutoUpdateIds[rowKey(item)]}
title={item.autoUpdateTitle}
>
- {#if togglingAutoUpdateIds[item.containerId]}
+ {#if togglingAutoUpdateIds[rowKey(item)]}
<Spinner class="size-4" />
{:else if item.autoUpdateDisabled}
<EyeOnIcon class="size-4" />
@@ -326,7 +340,7 @@
]}
rowActions={RowActions}
onclick={(item: ContainerUpdateRow) => {
- window.location.href = `/containers/${item.containerId}`;
+ window.location.href = environmentHref(`/containers/${item.containerId}`, item.environmentId);
}}
/>
{/snippet}
diff --git a/frontend/src/routes/(app)/updates/components/project-updates-table.svelte b/frontend/src/routes/(app)/updates/components/project-updates-table.svelte
index 8a974c73e..8004cffad 100644
--- a/frontend/src/routes/(app)/updates/components/project-updates-table.svelte
+++ b/frontend/src/routes/(app)/updates/components/project-updates-table.svelte
@@ -2,6 +2,7 @@
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import CheckedAtCell from '#lib/components/arcane-table/cells/checked-at-cell.svelte';
import DigestCell from '#lib/components/arcane-table/cells/digest-cell.svelte';
+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';
import {
UniversalMobileCard,
type BulkAction,
@@ -16,24 +17,34 @@
import { m } from '#lib/paraglide/messages.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import type { Project } from '#lib/types/swarm.js';
- import { hasPermission } from '#lib/utils/auth.js';
import { bulkConfirmAndRun, confirmAndRun } from '#lib/utils/bulk-actions.js';
+ import {
+ environmentHref,
+ hasShownPermission,
+ rowKey,
+ type EnvironmentPage,
+ type EnvironmentRow
+ } from '#lib/utils/environments.js';
import { formatImageUpdateCheckedAt, formatImageUpdateValue } from '#lib/utils/image-updates.js';
import { applyScopedUpdate, summarizeUpdateResult, throwOnUpdateFailure } from '#lib/utils/update-actions.js';
+ type ProjectRow = EnvironmentRow<Project>;
type ProjectUpdateRow = {
id: string;
+ environmentId: string;
+ environmentName: string;
+ environmentTagged: true;
projectId: string;
name: string;
imageSummary: string;
currentValue: string;
latestValue: string;
checkedAt: string;
- project: Project;
+ project: ProjectRow;
};
interface Props {
- projects: Paginated<Project>;
+ projects: EnvironmentPage<Paginated<Project>>;
requestOptions: SearchPaginationSortRequest;
onRefreshData: (options: SearchPaginationSortRequest) => Promise<void>;
}
@@ -45,7 +56,7 @@
let updatingProjectIds = $state<Record<string, boolean>>({});
let bulkUpdating = $state(false);
- function mapProjectRow(project: Project): ProjectUpdateRow {
+ function mapProjectRow(project: ProjectRow): ProjectUpdateRow {
const updateInfo = project.updateInfo;
const updatedRefs = updateInfo?.updatedImageRefs ?? [];
const summaryRefs = updatedRefs.length > 0 ? updatedRefs : (updateInfo?.imageRefs ?? []);
@@ -78,6 +89,9 @@
return {
id: project.id,
+ environmentId: project.environmentId,
+ environmentName: project.environmentName,
+ environmentTagged: true,
projectId: project.id,
name: project.name,
imageSummary,
@@ -93,13 +107,14 @@
data: (projects.data ?? []).map(mapProjectRow)
});
- const columns = [
+ const columns = $derived([
+ ...environmentColumns<ProjectUpdateRow>(),
{ accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },
{ accessorKey: 'imageSummary', title: m.common_image(), sortable: false, cell: ImageCell },
{ accessorKey: 'currentValue', title: m.common_current(), sortable: false, cellComponent: DigestCell },
{ accessorKey: 'latestValue', title: m.image_update_latest_label(), sortable: false, cellComponent: DigestCell },
{ accessorKey: 'checkedAt', title: m.common_updated(), sortable: false, cellComponent: CheckedAtCell }
- ] satisfies ColumnSpec<ProjectUpdateRow>[];
+ ] satisfies ColumnSpec<ProjectUpdateRow>[]);
const mobileFields = [
{ id: 'imageSummary', label: m.common_image(), defaultVisible: true },
@@ -116,9 +131,9 @@
message: m.updates_update_confirm_message({ name: item.name }),
confirmLabel: m.common_update(),
setLoading: (loading) => {
- updatingProjectIds = { ...updatingProjectIds, [item.projectId]: loading };
+ updatingProjectIds = { ...updatingProjectIds, [rowKey(item)]: loading };
},
- run: () => applyScopedUpdate('project', item.projectId),
+ run: () => applyScopedUpdate('project', item.projectId, item.environmentId),
failureMessage: m.updates_apply_all_failed(),
onSuccess: async (result) => {
summarizeUpdateResult(result);
@@ -133,7 +148,7 @@
title: m.updates_bulk_update_confirm_title({ count: ids.length }),
message: m.updates_bulk_update_confirm_message({ count: ids.length }),
confirmLabel: m.common_update(),
- run: (id) => applyScopedUpdate('project', id).then(throwOnUpdateFailure),
+ run: (id, environmentId) => applyScopedUpdate('project', id, environmentId).then(throwOnUpdateFailure),
messages: {
success: (count) => m.updates_bulk_update_success({ count }),
partial: (success, total, failed) => m.updates_bulk_update_partial({ success, total, failed }),
@@ -146,7 +161,7 @@
}
const bulkActions = $derived<BulkAction[]>(
- hasPermission('image-updates:check')
+ hasShownPermission('image-updates:check')
? [
{
id: 'update',
@@ -166,7 +181,7 @@
{#if item.project.isDiscovered}
<span class="font-medium">{item.name}</span>
{:else}
- <a class="font-medium hover:underline" href={`/projects/${item.projectId}`}>
+ <a class="font-medium hover:underline" href={environmentHref(`/projects/${item.projectId}`, item.environmentId)}>
{item.name}
</a>
{/if}
@@ -182,10 +197,10 @@
{/snippet}
{#snippet RowActions({ item }: { item: ProjectUpdateRow })}
- <IfPermitted perm="image-updates:check">
+ <IfPermitted perm="image-updates:check" envId={item.environmentId}>
<RowActionsMenu>
- <DropdownMenu.Item onclick={() => handleUpdateProject(item)} disabled={!!updatingProjectIds[item.projectId]}>
- {#if updatingProjectIds[item.projectId]}
+ <DropdownMenu.Item onclick={() => handleUpdateProject(item)} disabled={!!updatingProjectIds[rowKey(item)]}>
+ {#if updatingProjectIds[rowKey(item)]}
<Spinner class="size-4" />
{:else}
<UpdateIcon class="size-4" />
@@ -222,7 +237,7 @@
rowActions={RowActions}
onclick={(item: ProjectUpdateRow) => {
if (item.project.isDiscovered) return;
- window.location.href = `/projects/${item.projectId}`;
+ window.location.href = environmentHref(`/projects/${item.projectId}`, item.environmentId);
}}
/>
{/snippet}
diff --git a/frontend/src/routes/(app)/volumes/+page.svelte b/frontend/src/routes/(app)/volumes/+page.svelte
index 9efb6a0d2..872c75629 100644
--- a/frontend/src/routes/(app)/volumes/+page.svelte
+++ b/frontend/src/routes/(app)/volumes/+page.svelte
@@ -11,12 +11,13 @@
import { m } from '#lib/paraglide/messages.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { volumeService } from '#lib/services/volume-service.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { VolumeCreateRequest, VolumeUsageCounts } from '#lib/types/docker.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
- import { hasPermission } from '#lib/utils/auth.js';
+ import { fetchAcrossEnvironments, hasShownPermission } from '#lib/utils/environments.js';
import { ResourceListPageState } from '#lib/utils/resource-list-page.svelte.js';
- import VolumeTable from './components/volume-table.svelte';
+ import VolumeTable, { volumeSortValue } from './components/volume-table.svelte';
let { data } = $props();
const queryClient = useQueryClient();
@@ -24,22 +25,29 @@
const pageState = new ResourceListPageState(untrack(() => data.volumeRequestOptions));
const countsFallback: VolumeUsageCounts = { inuse: 0, unused: 0, total: 0 };
+ // The load already cached the first page under its key; seeding every key with it would hide other pages and filters.
const volumesQuery = createQuery(() => {
- const queryEnvId = pageState.envId;
+ const queryScope = pageState.scope;
+ const environments = environmentStore.shown;
const options = pageState.requestOptions;
return {
- queryKey: queryKeys.volumes.table(queryEnvId, options),
- queryFn: () => volumeService.getVolumesForEnvironment(queryEnvId, options),
+ queryKey: queryKeys.volumes.table(queryScope, options),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ environments,
+ options,
+ (id, request, config) => volumeService.getVolumesForEnvironment(id, request, config),
+ volumeSortValue
+ ),
placeholderData: (previous, query) => {
- if (query?.queryKey[1] === queryEnvId) return previous;
+ if (query?.queryKey[1] === queryScope) return previous;
return undefined;
},
- initialData: data.envId === queryEnvId ? data.volumes : undefined,
- select: (value) => ({ envId: queryEnvId, value })
+ select: (value) => ({ envId: queryScope, value })
};
});
- const resourcesReady = $derived(volumesQuery.data?.envId === pageState.envId);
+ const resourcesReady = $derived(volumesQuery.data?.envId === pageState.scope);
const volumes = $derived(volumesQuery.data?.value ?? data.volumes);
const createVolumeMutation = createMutation(() => ({
@@ -52,8 +60,8 @@
m.common_create_success({ resource: `${m.resource_volume()} "${name}"` }),
activityToastOptions(extractActivityId(data))
);
- if (options.requestedEnvId === pageState.envId) {
- await loadVolumes(pageState.requestOptions, options.requestedEnvId);
+ if (environmentStore.shown.some((env) => env.id === options.requestedEnvId)) {
+ await loadVolumes();
pageState.isCreateDialogOpen = false;
}
},
@@ -68,15 +76,22 @@
pageState.isCreateDialogOpen = false;
});
- async function handleCreate(options: VolumeCreateRequest) {
- await createVolumeMutation.mutateAsync({ options, requestedEnvId: pageState.envId });
+ async function handleCreate(options: VolumeCreateRequest, environmentId: string) {
+ await createVolumeMutation.mutateAsync({ options, requestedEnvId: environmentId });
}
- async function loadVolumes(options = pageState.requestOptions, requestedEnvId = pageState.envId) {
+ async function loadVolumes(options = pageState.requestOptions, requestedScope = pageState.scope) {
+ const environments = environmentStore.shown;
pageState.requestOptions = options;
await queryClient.query({
- queryKey: queryKeys.volumes.table(requestedEnvId, options),
- queryFn: () => volumeService.getVolumesForEnvironment(requestedEnvId, options)
+ queryKey: queryKeys.volumes.table(requestedScope, options),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ environments,
+ options,
+ (id, request, config) => volumeService.getVolumesForEnvironment(id, request, config),
+ volumeSortValue
+ )
});
}
@@ -90,7 +105,7 @@
return countsFallback;
});
- const canCreateVolume = $derived(hasPermission('volumes:create', pageState.envId));
+ const canCreateVolume = $derived(hasShownPermission('volumes:create'));
const actionButtons: ActionButton[] = $derived.by(() => {
const buttons: ActionButton[] = [];
@@ -137,11 +152,11 @@
<ResourcePageLayout title={m.resource_volumes_cap()} subtitle={m.volumes_subtitle()} {actionButtons} {statCards}>
{#snippet mainContent()}
{#if resourcesReady}
- {#key pageState.envId}
+ {#key pageState.scope}
<VolumeTable
bind:volumes={
() => volumes,
- (value) => queryClient.setQueryData(queryKeys.volumes.table(pageState.envId, pageState.requestOptions), value)
+ (value) => queryClient.setQueryData(queryKeys.volumes.table(pageState.scope, pageState.requestOptions), value)
}
bind:selectedIds={pageState.selectedIds}
bind:requestOptions={pageState.requestOptions}
diff --git a/frontend/src/routes/(app)/volumes/+page.ts b/frontend/src/routes/(app)/volumes/+page.ts
index 7a6db17b9..90013d43e 100644
--- a/frontend/src/routes/(app)/volumes/+page.ts
+++ b/frontend/src/routes/(app)/volumes/+page.ts
@@ -2,13 +2,16 @@ import { queryKeys } from '#lib/query/query-keys.js';
import { volumeService } from '#lib/services/volume-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
+import { fetchAcrossEnvironments } from '#lib/utils/environments.js';
import { resolveInitialTableRequest } from '#lib/utils/tables.js';
import type { PageLoad } from './$types';
+import { volumeSortValue } from './components/volume-table.svelte';
export const load: PageLoad = async ({ parent }) => {
const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const environments = await environmentStore.getShownEnvironments();
+ const scope = environmentStore.shownKey;
const volumeRequestOptions = resolveInitialTableRequest(
'arcane-volumes-table',
@@ -27,12 +30,18 @@ export const load: PageLoad = async ({ parent }) => {
// Single API call - counts are included in the response
const volumes = await queryClient.query({
- queryKey: queryKeys.volumes.table(envId, volumeRequestOptions),
- queryFn: () => volumeService.getVolumesForEnvironment(envId, volumeRequestOptions)
+ queryKey: queryKeys.volumes.table(scope, volumeRequestOptions),
+ queryFn: () =>
+ fetchAcrossEnvironments(
+ environments,
+ volumeRequestOptions,
+ (id, request, config) => volumeService.getVolumesForEnvironment(id, request, config),
+ volumeSortValue
+ )
});
return {
- envId,
+ scope,
volumes,
volumeRequestOptions,
// Use counts from the volumes response
diff --git a/frontend/src/routes/(app)/volumes/[volumeName]/+layout.svelte b/frontend/src/routes/(app)/volumes/[volumeName]/+layout.svelte
new file mode 100644
index 000000000..6b09dda5f
--- /dev/null
+++ b/frontend/src/routes/(app)/volumes/[volumeName]/+layout.svelte
@@ -0,0 +1,12 @@
+<script lang="ts">
+ import { page } from '$app/state';
+
+ import type { LayoutProps } from './$types';
+
+ let { children }: LayoutProps = $props();
+</script>
+
+<!-- The page's editors read their volume once, so another volume or environment gets a fresh page. -->
+{#key `${page.data['envId']}:${page.params.volumeName}`}
+ {@render children()}
+{/key}
diff --git a/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte b/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte
index 95e85c19a..79f56f444 100644
--- a/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte
+++ b/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte
@@ -23,6 +23,7 @@
import * as Select from '#lib/components/ui/select/index.js';
import { Spinner } from '#lib/components/ui/spinner/index.js';
import WorkspaceFileTreePanel from '#lib/components/workspace-file-tree-panel.svelte';
+ import { useEnvironmentSettings } from '#lib/hooks/use-environment-settings.svelte.js';
import { useUrlTab } from '#lib/hooks/use-url-tab.svelte.js';
import {
VolumesIcon,
@@ -42,7 +43,6 @@
import { volumeBackupService } from '#lib/services/volume-backup-service.js';
import { volumeService } from '#lib/services/volume-service.js';
import { volumeWorkspaceService } from '#lib/services/volume-workspace-service.js';
- import settingsStore from '#lib/stores/config-store.svelte.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import type { VolumeDetailDto } from '#lib/types/docker.js';
import type { BackupEntry } from '#lib/types/shared.js';
@@ -51,6 +51,7 @@
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { hasPermission } from '#lib/utils/auth.js';
import { composeTreeSplitProps } from '#lib/utils/compose-flow.js';
+ import { environmentHref } from '#lib/utils/environments.js';
import { formatDateTimeShort, truncateString } from '#lib/utils/formatting.js';
import { bytes } from '#lib/utils/formatting.js';
import { tryCatch } from '#lib/utils/try-catch.js';
@@ -78,15 +79,19 @@
let active = true;
let containersDetailed = $derived<{ id: string; name: string }[]>(data.containersDetailed ?? []);
- const backupVolumeName = $derived.by(() => settingsStore.current?.backupVolumeName || 'arcane-backups');
- const isBackupVolume = $derived(volume?.name === backupVolumeName);
+ const currentEnvId = $derived(data.envId);
+ // A volume opened from another environment follows that environment's settings.
+ const environmentSettings = useEnvironmentSettings(() => currentEnvId);
+ const volumeSettings = $derived(environmentSettings.current);
+ // Until the backup volume name is known, the volume cannot be removed.
+ const backupVolumeName = $derived(volumeSettings ? volumeSettings.backupVolumeName || 'arcane-backups' : undefined);
+ const isBackupVolume = $derived(!backupVolumeName || volume?.name === backupVolumeName);
- const currentEnvId = $derived(environmentStore.selected?.id || '0');
const canDeleteVolume = $derived(hasPermission('volumes:delete', currentEnvId));
const canReadVolume = $derived(hasPermission('volumes:read', currentEnvId));
const canUploadVolume = $derived(hasPermission('volumes:upload', currentEnvId));
const canBackupVolume = $derived(hasPermission('volumes:backup', currentEnvId));
- const volumeWorkspaceMaxFileSizeMb = $derived(settingsStore.current?.volumeWorkspaceMaxFileSizeMb ?? 10);
+ const volumeWorkspaceMaxFileSizeMb = $derived(volumeSettings?.volumeWorkspaceMaxFileSizeMb ?? 10);
let isLoading = $state({ remove: false, save: false });
const createdDate = $derived(volume?.createdAt ? formatDateTimeShort(volume.createdAt) : m.common_unknown());
@@ -753,11 +758,13 @@
async function handleRemoveVolumeConfirm(volumeName: string) {
if (!active || !volume) return;
const safeName = volumeName?.trim() || m.common_unknown();
- if (safeName === backupVolumeName) return;
+ if (!backupVolumeName || safeName === backupVolumeName) return;
const message = volume.inUse
? `${m.volumes_remove_confirm_message({ name: safeName })}\n\n${m.volumes_remove_in_use_warning()}`
: m.volumes_remove_confirm_message({ name: safeName });
+ // The dialog outlives navigation, so it removes the volume from the environment it was opened for.
+ const environmentId = currentEnvId;
openConfirmDialog({
title: m.common_remove_title({ resource: m.resource_volume() }),
message,
@@ -767,7 +774,7 @@
action: async () => {
isLoading.remove = true;
await handleApiResultWithCallbacks({
- result: await tryCatch(volumeService.deleteVolume(safeName)),
+ result: await tryCatch(volumeService.deleteVolume(safeName, environmentId)),
message: m.volumes_remove_failed({ name: safeName }),
setLoadingState: (value) => (isLoading.remove = value),
onSuccess: async (data) => {
@@ -822,7 +829,10 @@
{#each containersDetailed as c (c.id)}
<div class="flex flex-col p-3 sm:flex-row sm:items-center">
<div class="mb-2 w-full font-medium break-all sm:mb-0 sm:w-1/3">
- <a href="/containers/{c.id}" class="flex items-center text-primary hover:underline">
+ <a
+ href={environmentHref(`/containers/${c.id}`, currentEnvId)}
+ class="flex items-center text-primary hover:underline"
+ >
<ContainersIcon class="mr-1.5 size-3.5 text-muted-foreground" />
{c.name}
</a>
@@ -844,7 +854,9 @@
{#each volume.containers as id (id)}
<div class="flex items-center justify-between gap-3 p-3">
<code class="font-mono text-sm break-all">{truncateString(id, 48)}</code>
- <a href={`/containers/${id}`} class="text-sm text-primary hover:underline">{m.common_view()}</a>
+ <a href={environmentHref(`/containers/${id}`, currentEnvId)} class="text-sm text-primary hover:underline"
+ >{m.common_view()}</a
+ >
</div>
{/each}
</div>
@@ -1110,7 +1122,12 @@
{@render volumeWorkspace(volume)}
{:else if tab === 'backups'}
{#key `${currentEnvId}:${volume.name}`}
- <BackupList volumeName={volume.name} {hasWorkspaceChanges} onWorkspaceRestored={refreshRestoredVolumeWorkspace} />
+ <BackupList
+ volumeName={volume.name}
+ environmentId={currentEnvId}
+ {hasWorkspaceChanges}
+ onWorkspaceRestored={refreshRestoredVolumeWorkspace}
+ />
{/key}
{/if}
</div>
diff --git a/frontend/src/routes/(app)/volumes/[volumeName]/+page.ts b/frontend/src/routes/(app)/volumes/[volumeName]/+page.ts
index 49815d038..a13a02958 100644
--- a/frontend/src/routes/(app)/volumes/[volumeName]/+page.ts
+++ b/frontend/src/routes/(app)/volumes/[volumeName]/+page.ts
@@ -3,14 +3,14 @@ import { error } from '@sveltejs/kit';
import { queryKeys } from '#lib/query/query-keys.js';
import { containerService } from '#lib/services/container-service.js';
import { volumeService } from '#lib/services/volume-service.js';
-import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+import { resolveDetailEnvironmentId } from '#lib/utils/environments.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
-export const load: PageLoad = async ({ params, parent }) => {
+export const load: PageLoad = async ({ params, parent, url }) => {
const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
+ const envId = await resolveDetailEnvironmentId(url);
const { volumeName } = params;
@@ -46,6 +46,7 @@ export const load: PageLoad = async ({ params, parent }) => {
}
return {
+ envId,
volume,
containersDetailed
};
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 284017e80..83c6a61ee 100644
--- a/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
+++ b/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
@@ -68,15 +68,17 @@
let {
volumeName,
+ environmentId,
hasWorkspaceChanges = false,
onWorkspaceRestored
}: {
volumeName: string;
+ environmentId: string;
hasWorkspaceChanges?: boolean;
onWorkspaceRestored?: () => void | Promise<void>;
} = $props();
- const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const currentEnvId = $derived(environmentId);
const canReadActivities = $derived(hasPermission('activities:read', currentEnvId));
const canBackupVolume = $derived(hasPermission('volumes:backup', currentEnvId));
const canDeleteBackup = $derived(hasPermission('volumes:backup', currentEnvId));
@@ -193,7 +195,7 @@
try {
const operationResult = await tryCatch(
(async () => {
- const result = await volumeBackupService.createBackup(name, request);
+ const result = await volumeBackupService.createBackup(name, request, environmentId);
if (!active || environmentId !== currentEnvId || name !== volumeName) return false;
showS3DestinationDialog = false;
onDemandS3DestinationId = '';
@@ -250,7 +252,7 @@
action: async () => {
const operationResult = await tryCatch(
(async () => {
- const result = await volumeBackupService.deleteBackup(backup.id);
+ const result = await volumeBackupService.deleteBackup(backup.id, currentEnvId);
toast.success(
m.common_delete_success({ resource: m.volumes_workspace_backup() }),
activityToastOptions(extractActivityId(result))
@@ -276,7 +278,7 @@
message: m.volume_backups_remove_selected_message({ count: ids.length }),
confirmLabel: m.common_remove(),
destructive: true,
- run: (id) => volumeBackupService.deleteBackup(id),
+ run: (id) => volumeBackupService.deleteBackup(id, currentEnvId),
messages: {
success: (count) => m.common_bulk_remove_success({ count, resource: m.volumes_backups_title() }),
partial: (success, total, failed) =>
@@ -313,7 +315,7 @@
uploadingBackupId = backup.id;
try {
await runBackupAction(
- () => volumeBackupService.uploadBackup(backup.id, s3DestinationId),
+ () => volumeBackupService.uploadBackup(backup.id, s3DestinationId, currentEnvId),
m.backups_upload_s3_success,
m.backups_upload_s3_failed
);
@@ -328,18 +330,19 @@
selectAllBackupFiles = false;
backupFilesSearch = '';
backupFileProvider = {
- browse: (request) => volumeBackupService.browseBackupFiles(backup.id, request)
+ browse: (request) => volumeBackupService.browseBackupFiles(backup.id, request, environmentId)
};
showRestoreFiles = true;
}
async function handleRestore(backup: BackupEntry) {
const name = volumeName;
+ const environmentId = currentEnvId;
// Check if volume is in use
let usageWarning = '';
const operationResult = await tryCatch(
(async () => {
- const usage = await volumeService.getVolumeUsage(volumeName);
+ const usage = await volumeService.getVolumeUsage(volumeName, environmentId);
if (usage.inUse && usage.containers?.length > 0) {
usageWarning = m.volumes_backup_restore_in_use_warning({ count: usage.containers.length });
}
@@ -360,7 +363,7 @@
destructive: !!usageWarning || hasWorkspaceChanges,
action: () =>
runBackupAction(
- () => volumeBackupService.restoreBackup(name, backup.id),
+ () => volumeBackupService.restoreBackup(name, backup.id, environmentId),
m.volumes_backup_restore_success,
m.common_failed,
() => onWorkspaceRestored?.()
@@ -375,15 +378,18 @@
const name = volumeName;
const backupId = restoreTarget.id;
+ const environmentId = currentEnvId;
const selection = { paths: [...selectedPaths], selectAll: selectAllBackupFiles };
restoringFiles = true;
try {
const operationResult = await tryCatch(
(async () => {
- const result = await volumeBackupService.restoreBackupFiles(name, backupId, {
- ...selection,
- search: selection.selectAll ? backupFilesSearch.trim() : undefined
- });
+ const result = await volumeBackupService.restoreBackupFiles(
+ name,
+ backupId,
+ { ...selection, search: selection.selectAll ? backupFilesSearch.trim() : undefined },
+ environmentId
+ );
await onWorkspaceRestored?.();
toast.success(m.volumes_backup_restore_selection_success(), activityToastOptions(extractActivityId(result)));
showRestoreFiles = false;
@@ -408,7 +414,7 @@
const environmentId = currentEnvId;
const name = volumeName;
const [collection, destinations] = await Promise.all([
- volumeBackupService.getPolicies(name),
+ volumeBackupService.getPolicies(name, environmentId),
canBackupVolume && canListS3Destinations ? tryCatch(s3DestinationService.listAll()) : Promise.resolve(null),
loadData(requestOptions)
]);
@@ -512,7 +518,7 @@
</DropdownMenu.Item>
{/if}
{#if item.format === 'archive' || item.localSnapshotId}
- <DropdownMenu.Item onclick={() => volumeBackupService.downloadBackup(item.id)}>
+ <DropdownMenu.Item onclick={() => volumeBackupService.downloadBackup(item.id, currentEnvId)}>
<DownloadIcon class="size-4" />
{m.templates_download()}
</DropdownMenu.Item>
@@ -528,7 +534,7 @@
</DropdownMenu.Item>
{/each}
{/if}
- <IfPermitted perm="volumes:backup">
+ <IfPermitted perm="volumes:backup" envId={currentEnvId}>
<DropdownMenu.Separator />
<DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)}>
<TrashIcon class="size-4" />
@@ -832,7 +838,7 @@
defaultSchedule="0 0 2 * * *"
showStopContainers
destinations={canListS3Destinations && !s3DestinationsError ? s3Destinations : undefined}
- updatePolicies={async (policies) => (await volumeBackupService.updatePolicies(volumeName, policies)).policies}
+ updatePolicies={async (policies) => (await volumeBackupService.updatePolicies(volumeName, policies, currentEnvId)).policies}
messages={{
saved: m.volume_backup_policy_saved(),
saveFailed: m.volume_backup_policy_save_failed(),
diff --git a/frontend/src/routes/(app)/volumes/components/volume-table.svelte b/frontend/src/routes/(app)/volumes/components/volume-table.svelte
index ab4221c98..85c2dc57a 100644
--- a/frontend/src/routes/(app)/volumes/components/volume-table.svelte
+++ b/frontend/src/routes/(app)/volumes/components/volume-table.svelte
@@ -1,3 +1,13 @@
+<script module lang="ts">
+ import type { VolumeSummaryDto } from '#lib/types/docker.js';
+
+ /** Sort value for a volume column; size falls back to usage data, as the backend sorts it. */
+ export function volumeSortValue(volume: VolumeSummaryDto, column: string): unknown {
+ if (column === 'size') return volume.size || (volume.usageData?.size ?? 0);
+ return volume[column as keyof VolumeSummaryDto];
+ }
+</script>
+
<script lang="ts">
import { goto } from '$app/navigation';
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
@@ -7,6 +17,7 @@
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import InUseStatus from '#lib/components/arcane-table/cells/in-use-status.svelte';
+ import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';
import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '#lib/components/arcane-table/index.js';
import { UniversalMobileCard } from '#lib/components/arcane-table/index.js';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
@@ -16,16 +27,29 @@
import { TrashIcon, InspectIcon, VolumesIcon, CalendarIcon, EditIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import { queryKeys } from '#lib/query/query-keys.js';
- import { volumeService } from '#lib/services/volume-service.js';
+ import { settingsService } from '#lib/services/settings-service.js';
+ import { volumeService, type VolumesPaginatedResponse } from '#lib/services/volume-service.js';
import settingsStore from '#lib/stores/config-store.svelte.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import userStore from '#lib/stores/user-store.svelte.js';
- import type { VolumeSummaryDto, VolumeSizeInfo } from '#lib/types/docker.js';
- import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
+ import type { VolumeSizeInfo } from '#lib/types/docker.js';
+ import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { handleApiResultWithCallbacks, extractApiErrorMessage } from '#lib/utils/api.js';
import { hasPermission } from '#lib/utils/auth.js';
import { bulkConfirmAndRun } from '#lib/utils/bulk-actions.js';
+ import {
+ collectAcrossEnvironments,
+ environmentHref,
+ fetchAcrossEnvironments,
+ hasShownPermission,
+ parseRowKey,
+ rowKey,
+ tagEnvironment,
+ withFailedEnvironments,
+ type EnvironmentPage,
+ type EnvironmentRow
+ } from '#lib/utils/environments.js';
import { formatDateTimeShort, truncateString } from '#lib/utils/formatting.js';
import { bytes } from '#lib/utils/formatting.js';
import { inUseBadge } from '#lib/utils/mobile-card-badges.js';
@@ -33,13 +57,15 @@
import RenameVolumeDialog from './rename-volume-dialog.svelte';
+ type VolumeRow = EnvironmentRow<VolumeSummaryDto>;
+
let {
volumes = $bindable(),
selectedIds = $bindable(),
requestOptions = $bindable(),
onRefreshData
}: {
- volumes: Paginated<VolumeSummaryDto>;
+ volumes: EnvironmentPage<VolumesPaginatedResponse>;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
onRefreshData?: (options: SearchPaginationSortRequest) => Promise<void>;
@@ -49,21 +75,21 @@
removing: false,
renaming: false
});
- let volumeToRename = $state<VolumeSummaryDto | null>(null);
+ let volumeToRename = $state<VolumeRow | null>(null);
let renameDialogOpen = $state(false);
let renameSession = $state(0);
let renameEnvironmentId = $state('0');
- const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const scope = $derived(environmentStore.shownKey);
// Track the user store: hasPermission reads it non-reactively, so without
// this the derived would cache a pre-hydration false forever.
const canDeleteVolume = $derived.by(() => {
userStore.current;
- return hasPermission('volumes:delete', currentEnvId);
+ return hasShownPermission('volumes:delete');
});
const canRenameVolume = $derived.by(() => {
userStore.current;
- return hasPermission('volumes:rename', currentEnvId);
+ return hasShownPermission('volumes:rename');
});
let tablePreferences = $state<{ persistCustomSettings(settings: Record<string, unknown>): void }>();
let customSettings = $state<Record<string, unknown>>({});
@@ -75,11 +101,20 @@
if (onRefreshData) {
await onRefreshData(options);
} else {
- volumes = await volumeService.getVolumes(options);
+ volumes = await fetchAcrossEnvironments(
+ environmentStore.shown,
+ options,
+ (id, request, config) => volumeService.getVolumesForEnvironment(id, request, config),
+ volumeSortValue
+ );
}
if (refreshSizes && sizesEnabled) {
await sizesQuery.refetch({ cancelRefetch: false });
}
+ // A retry also reloads backup volume names an environment failed to return.
+ if (backupVolumeNamesQuery.isError || backupVolumeNamesQuery.data?.failures.length) {
+ await backupVolumeNamesQuery.refetch();
+ }
}
function getCurrentLimit() {
@@ -102,27 +137,63 @@
refreshVolumes(nextOptions);
}
- const backupVolumeName = $derived.by(() => settingsStore.current?.backupVolumeName || 'arcane-backups');
- const isBackupVolumeName = (name?: string) => (name ?? '') === backupVolumeName;
- const isBackupVolume = (item: VolumeSummaryDto) => isBackupVolumeName(item.name);
-
let columnVisibility = $state<ColumnVisibilityState>({});
let tablePreferencesReady = $state(false);
const queryClient = useQueryClient();
+
+ // Each environment names its own backup volume; other shown environments' names come from their settings.
+ const backupVolumeNamesQuery = createQuery(() => {
+ const selectedId = environmentStore.selected?.id;
+ const others = environmentStore.shown.filter((env) => env.id !== selectedId);
+ return {
+ // The selected environment is left out, so it is part of the key.
+ queryKey: queryKeys.volumes.backupVolumeNames(`${scope}|${selectedId}`),
+ queryFn: async () => {
+ const { values, failures } = await collectAcrossEnvironments(others, (id) =>
+ queryClient.ensureQueryData({
+ queryKey: queryKeys.settings.byEnvironment(id),
+ queryFn: () => settingsService.getReadableSettings(id)
+ })
+ );
+ const names = new Map(
+ values.map(({ environment, value }) => [environment.id, value.backupVolumeName || 'arcane-backups'])
+ );
+ return { names, failures };
+ },
+ enabled: others.length > 0,
+ refetchOnWindowFocus: false
+ };
+ });
+ const isBackupVolumeName = (name: string, environmentId = environmentStore.selected?.id) => {
+ if (environmentId === environmentStore.selected?.id) {
+ return name === (settingsStore.current?.backupVolumeName || 'arcane-backups');
+ }
+ // Until another environment's backup volume name is known, none of its volumes can be removed or renamed.
+ const configured = backupVolumeNamesQuery.data?.names.get(environmentId ?? '');
+ return configured === undefined || name === configured;
+ };
+ const isBackupVolume = (item: VolumeRow) => isBackupVolumeName(item.name, item.environmentId);
const sizesEnabled = $derived.by(() => {
userStore.current;
return (
tablePreferencesReady &&
!!environmentStore.selected?.id &&
columnVisibility['size'] !== false &&
- hasPermission('volumes:read', currentEnvId)
+ hasShownPermission('volumes:read')
);
});
const sizesQuery = createQuery(() => {
- const environmentId = currentEnvId;
+ const queryScope = scope;
+ const environments = environmentStore.shown;
return {
- queryKey: queryKeys.volumes.sizes(environmentId),
- queryFn: () => volumeService.getVolumeSizes(environmentId),
+ queryKey: queryKeys.volumes.sizes(queryScope),
+ queryFn: async () => {
+ const { values } = await collectAcrossEnvironments(
+ environments.filter((env) => hasPermission('volumes:read', env.id)),
+ (id, config) => volumeService.getVolumeSizes(id, config)
+ );
+ return values.flatMap(({ environment, value }) => value.map((size) => tagEnvironment(size, environment)));
+ },
enabled: sizesEnabled,
refetchOnWindowFocus: false,
retry: false
@@ -131,7 +202,7 @@
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);
+ for (const size of sizesQuery.data ?? []) sizes.set(rowKey({ ...size, id: size.name }), size);
return sizes;
});
const sizesLoading = $derived(sizesEnabled && sizesQuery.isFetching);
@@ -140,7 +211,7 @@
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.query !== cache.find({ queryKey: queryKeys.volumes.sizes(scope), exact: true })) return;
if (event.action.type === 'success' && sizesEnabled && requestOptions?.sort?.column === 'size') {
void tryCatch(refreshVolumes(requestOptions, false)).then((result) =>
handleApiResultWithCallbacks({ result, message: m.common_refresh_failed({ resource: m.resource_volumes_cap() }) })
@@ -149,9 +220,9 @@
});
});
- async function handleRemoveVolumeConfirm(name: string) {
+ async function handleRemoveVolumeConfirm(name: string, environmentId: string) {
const safeName = name?.trim() || m.common_unknown();
- if (isBackupVolumeName(safeName)) return;
+ if (isBackupVolumeName(safeName, environmentId)) return;
openConfirmDialog({
title: m.common_remove_title({ resource: m.resource_volume() }),
message: m.common_remove_confirm({ resource: `${m.resource_volume()} "${safeName}"` }),
@@ -161,7 +232,7 @@
action: async () => {
isLoading.removing = true;
await handleApiResultWithCallbacks({
- result: await tryCatch(volumeService.deleteVolume(safeName)),
+ result: await tryCatch(volumeService.deleteVolume(safeName, environmentId)),
message: m.common_remove_failed({ resource: `${m.resource_volume()} "${safeName}"` }),
setLoadingState: (value) => (isLoading.removing = value),
onSuccess: async (data) => {
@@ -177,9 +248,9 @@
});
}
- function handleRenameVolume(item: VolumeSummaryDto) {
+ function handleRenameVolume(item: VolumeRow) {
volumeToRename = item;
- renameEnvironmentId = currentEnvId;
+ renameEnvironmentId = item.environmentId;
renameSession += 1;
renameDialogOpen = true;
}
@@ -195,7 +266,7 @@
onSuccess: async (data) => {
toast.success(m.volumes_rename_success({ oldName, newName }), activityToastOptions(extractActivityId(data)));
renameDialogOpen = false;
- if (renameEnvironmentId === currentEnvId) await refreshVolumes();
+ if (environmentStore.shown.some((env) => env.id === renameEnvironmentId)) await refreshVolumes();
}
});
}
@@ -204,7 +275,10 @@
// A volume's id IS its name (backend sets ID: v.Name), so ids can be
// passed to the delete endpoint directly — no per-page name lookup, which
// would break for selections carried across pages.
- const idsToDelete = ids.filter((id) => !isBackupVolumeName(id));
+ const idsToDelete = ids.filter((key) => {
+ const { environmentId, id } = parseRowKey(key);
+ return !isBackupVolumeName(id, environmentId);
+ });
bulkConfirmAndRun({
ids: idsToDelete,
@@ -212,7 +286,7 @@
message: m.volumes_remove_selected_message({ count: idsToDelete.length }),
confirmLabel: m.common_remove(),
destructive: true,
- run: (id) => volumeService.deleteVolume(id),
+ run: (id, environmentId) => volumeService.deleteVolume(id, environmentId),
messages: {
success: (count) => m.common_bulk_remove_success({ count, resource: m.resource_volumes_cap() }),
partial: (success, total, failed) =>
@@ -227,14 +301,15 @@
});
}
- const columns = [
+ const columns = $derived([
+ ...environmentColumns<VolumeRow>(),
{ accessorKey: 'id', title: m.common_id(), hidden: true },
{ accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },
{ accessorKey: 'inUse', title: m.common_status(), sortable: true, cell: StatusCell },
{ accessorKey: 'size', title: m.common_size(), sortable: true, cell: SizeCell },
{ accessorKey: 'createdAt', title: m.common_created(), sortable: true, cell: CreatedCell },
{ accessorKey: 'driver', title: m.common_driver(), sortable: true }
- ] satisfies ColumnSpec<VolumeSummaryDto>[];
+ ] satisfies ColumnSpec<VolumeRow>[]);
const mobileFields = [
{ id: 'id', label: m.common_id(), defaultVisible: false },
@@ -245,7 +320,12 @@
];
// Volume id === name, so the backup-volume filter works on the id directly.
- const deletableSelectedIds = $derived((selectedIds ?? []).filter((id) => !isBackupVolumeName(id)));
+ const deletableSelectedIds = $derived(
+ (selectedIds ?? []).filter((key) => {
+ const { environmentId, id } = parseRowKey(key);
+ return !isBackupVolumeName(id, environmentId);
+ })
+ );
const bulkActions = $derived.by<BulkAction[]>(() => [
{
@@ -262,18 +342,18 @@
let mobileFieldVisibility = $state<Record<string, boolean>>({});
</script>
-{#snippet NameCell({ item }: { item: VolumeSummaryDto })}
- <a class="font-medium hover:underline" href="/volumes/{item.id}" title={item.name}>
+{#snippet NameCell({ item }: { item: VolumeRow })}
+ <a class="font-medium hover:underline" href={environmentHref(`/volumes/${item.id}`, item.environmentId)} title={item.name}>
{truncateString(item.name, 40)}
</a>
{/snippet}
-{#snippet StatusCell({ item }: { item: VolumeSummaryDto })}
+{#snippet StatusCell({ item }: { item: VolumeRow })}
<InUseStatus inUse={item.inUse} />
{/snippet}
-{#snippet SizeCell({ item }: { item: VolumeSummaryDto })}
- {@const sizeInfo = sizesMap.get(item.name)}
+{#snippet SizeCell({ item }: { item: VolumeRow })}
+ {@const sizeInfo = sizesMap.get(rowKey(item))}
{#if sizeInfo && sizeInfo.size >= 0}
<span class="text-sm tabular-nums">{bytes.format(sizeInfo.size)}</span>
{:else if sizesLoading && sizesMap.size === 0}
@@ -305,7 +385,7 @@
item,
mobileFieldVisibility
}: {
- item: VolumeSummaryDto;
+ item: VolumeRow;
mobileFieldVisibility: MobileFieldVisibility;
})}
<UniversalMobileCard
@@ -320,7 +400,7 @@
fields={[
{
label: m.common_driver(),
- getValue: (item: VolumeSummaryDto) => item.driver,
+ getValue: (item: VolumeRow) => item.driver,
icon: VolumesIcon,
iconVariant: 'gray' as const,
show: mobileFieldVisibility['driver'] ?? true
@@ -334,13 +414,13 @@
}
: undefined}
rowActions={RowActions}
- onclick={() => goto(`/volumes/${item.id}`)}
+ onclick={() => goto(environmentHref(`/volumes/${item.id}`, item.environmentId))}
/>
{/snippet}
-{#snippet RowActions({ item }: { item: VolumeSummaryDto })}
+{#snippet RowActions({ item }: { item: VolumeRow })}
<RowActionsMenu>
- <DropdownMenu.Item onclick={() => goto(`/volumes/${item.id}`)}>
+ <DropdownMenu.Item onclick={() => goto(environmentHref(`/volumes/${item.id}`, item.environmentId))}>
<InspectIcon class="size-4" />
{m.common_inspect()}
</DropdownMenu.Item>
@@ -349,7 +429,7 @@
<DropdownMenu.Separator />
{/if}
- {#if canRenameVolume}
+ {#if canRenameVolume && hasPermission('volumes:rename', item.environmentId)}
<DropdownMenu.Item
onclick={() => handleRenameVolume(item)}
disabled={item.inUse || isBackupVolume(item) || isLoading.renaming}
@@ -359,10 +439,10 @@
</DropdownMenu.Item>
{/if}
- {#if canDeleteVolume}
+ {#if canDeleteVolume && hasPermission('volumes:delete', item.environmentId)}
<DropdownMenu.Item
variant="destructive"
- onclick={() => handleRemoveVolumeConfirm(item.name)}
+ onclick={() => handleRemoveVolumeConfirm(item.name, item.environmentId)}
disabled={item.inUse || isBackupVolume(item)}
>
<TrashIcon class="size-4" />
@@ -375,7 +455,7 @@
<ArcaneTable
bind:this={tablePreferences}
persistKey="arcane-volumes-table"
- items={volumes}
+ items={withFailedEnvironments(volumes, backupVolumeNamesQuery.data?.failures)}
bind:requestOptions
bind:selectedIds
bind:mobileFieldVisibility
diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.ts
index 8cade6088..1ff1049a2 100644
--- a/frontend/src/routes/+layout.ts
+++ b/frontend/src/routes/+layout.ts
@@ -1,5 +1,6 @@
import { browser } from '$app/env';
-import { redirect } from '@sveltejs/kit';
+import { navigating, page } from '$app/state';
+import { error, redirect } from '@sveltejs/kit';
import { QueryClient } from '@tanstack/svelte-query';
import { queryKeys } from '#lib/query/query-keys.js';
@@ -18,7 +19,7 @@ import userStore from '#lib/stores/user-store.svelte.js';
import { versionStore } from '#lib/stores/version.store.svelte.js';
import type { PermissionsManifest, User } from '#lib/types/auth.js';
import { isAuthRejectionError } from '#lib/utils/api.js';
-import { getAuthRedirectPath, userHasPermission } from '#lib/utils/auth.js';
+import { getAuthRedirectPath, shownEnvironmentForRoute, userHasPermission } from '#lib/utils/auth.js';
import { getEffectiveLandingPage } from '#lib/utils/navigation.js';
import { setTelemetry } from '#lib/utils/telemetry.js';
import { tryCatch } from '#lib/utils/try-catch.js';
@@ -43,12 +44,25 @@ const queryClient = new QueryClient({
});
let authenticatedUserId: string | null | undefined;
+// Whether a signed-in page has loaded; later loads without a navigation to their path are preloads.
+let opened = false;
function dataOrNull<T>(promise: Promise<T>): Promise<T | null> {
return tryCatch(promise).then((result) => (result.error ? null : result.data));
}
-export const load: LayoutLoad = async ({ url }) => {
+export const load: LayoutLoad = async (event) => {
+ // With several environments shown this load may switch environments for the route, and child loads start
+ // alongside it, so their environment lookups wait until it has chosen.
+ const releaseSelection = environmentStore.shown.length > 1 ? environmentStore.holdSelection() : undefined;
+ try {
+ return await loadRoot(event, releaseSelection);
+ } finally {
+ releaseSelection?.();
+ }
+};
+
+async function loadRoot({ url }: Parameters<LayoutLoad>[0], releaseSelection: (() => void) | undefined) {
// Logout must not wait on, or be triggered by, authenticated requests; preloading runs this too.
if (url.pathname === '/logout') {
return {
@@ -102,6 +116,8 @@ export const load: LayoutLoad = async ({ url }) => {
let permissionsManifest: PermissionsManifest | null = null;
let permissionsManifestLoadFailed = false;
if (user) {
+ const opening = !opened;
+ opened = true;
// Initialize environment store (required for settings service)
const environmentsRequest = tryCatch(environmentManagementService.getEnvironments({ pagination: { page: 1, limit: -1 } }));
const permissionsManifestRequest = dataOrNull(roleService.getPermissionsManifest());
@@ -114,12 +130,34 @@ export const load: LayoutLoad = async ({ url }) => {
await environmentStore.initialize([]);
}
+ // With the preview on, a page only another shown environment allows opens there instead of failing.
+ if (environmentStore.shown.length > 1) {
+ const reachable = shownEnvironmentForRoute(
+ url.pathname,
+ user,
+ environmentStore.selected?.id,
+ await permissionsManifestRequest
+ );
+ const environment = environmentStore.available.find((env) => env.id === reachable?.id);
+ // Switch only when opening, reloading or navigating to the page on screen. A hover preload of another page
+ // must not retarget this one, so it is stopped instead; SvelteKit then drops it and the click loads afresh.
+ const forPageOnScreen = opening || navigating.to?.url.pathname === url.pathname || page.url.pathname === url.pathname;
+ if (environment && !forPageOnScreen) error(403);
+ if (environment) await environmentStore.setEnvironment(environment, { navigate: false });
+ }
+ releaseSelection?.();
+
const settingsRequest = (
userHasPermission(user, 'settings:read') ? dataOrNull(settingsService.getSettings()) : Promise.resolve(null)
).then((loaded) => loaded ?? dataOrNull(settingsService.getPublicSettings(environmentStore.selected?.id ?? '0')));
featureStore.connect(queryClient);
const currentEnvironmentId = await environmentStore.getCurrentEnvironmentId();
const featuresRequest = featureStore.refresh(currentEnvironmentId);
+ // The all environments preview shows navigation for features in any shown environment. The others load
+ // in the background, so an unreachable environment never stalls navigation.
+ for (const env of environmentStore.shown) {
+ if (env.id !== currentEnvironmentId) void featureStore.load(env.id);
+ }
// Optional discovery: skip it without swarm:read and never toast a denial.
const swarmStatusRequest = userHasPermission(user, 'swarm:read', currentEnvironmentId)
? dataOrNull(swarmService.getSwarmStatus(currentEnvironmentId, { suppressAccessDeniedToast: true }))
@@ -182,4 +220,4 @@ export const load: LayoutLoad = async ({ url }) => {
queryClient,
swarmEnabled
};
-};
+}
diff --git a/tests/spec/all-environments.spec.ts b/tests/spec/all-environments.spec.ts
new file mode 100644
index 000000000..a5a27fec5
--- /dev/null
+++ b/tests/spec/all-environments.spec.ts
@@ -0,0 +1,228 @@
+import { test, expect, type Page } from '../fixtures/test.fixture';
+
+const remoteEnvironment = {
+ id: 'remote-preview-test',
+ name: 'Remote Preview',
+ apiUrl: 'https://remote-preview.example.invalid',
+ status: 'online',
+ enabled: true,
+ isEdge: false
+};
+
+const remoteContainer = {
+ id: 'remote-preview-container',
+ names: ['/remote-preview-web'],
+ image: 'nginx:latest',
+ imageId: 'sha256:remote-preview',
+ command: 'nginx',
+ created: Math.floor(Date.now() / 1000),
+ state: 'exited',
+ status: 'Exited (0)',
+ labels: {},
+ ports: [],
+ mounts: [],
+ networkSettings: { networks: {} }
+};
+
+function paginated<T>(data: T[], counts?: Record<string, number>) {
+ return {
+ success: true,
+ data,
+ counts,
+ pagination: {
+ totalPages: 1,
+ totalItems: data.length,
+ currentPage: 1,
+ itemsPerPage: 20,
+ grandTotalItems: data.length
+ }
+ };
+}
+
+type Preferences = Record<string, unknown>;
+
+// Serves the signed-in user with these preferences without saving them, so other specs keep the defaults.
+async function withPreferences(page: Page, preferences: () => Preferences) {
+ await page.route(/\/api\/auth\/me(?:\?.*)?$/, async (route) => {
+ const response = await route.fetch();
+ const body = await response.json();
+ body.data.preferences = { ...body.data.preferences, ...preferences() };
+ await route.fulfill({ response, json: body });
+ });
+}
+
+async function enablePreview(page: Page) {
+ await withPreferences(page, () => ({ allEnvironmentsPreview: true }));
+}
+
+// Lists the real local environment plus a mocked remote one, and keeps the live stream from replacing that list.
+async function mockRemoteEnvironment(page: Page) {
+ const local = await page.request.get('/api/environments/0');
+ const localEnvironment = (await local.json()).data;
+ await page.route(/\/api\/stream(?:\?.*)?$/, (route) => route.abort());
+ await page.route(/\/api\/environments(?:\?.*)?$/, (route) =>
+ route.fulfill({ json: paginated([localEnvironment, remoteEnvironment]) })
+ );
+ await page.route(
+ new RegExp(`/api/environments/${remoteEnvironment.id}/containers(?:\\?.*)?$`),
+ (route) =>
+ route.fulfill({
+ json: paginated([remoteContainer], {
+ runningContainers: 0,
+ stoppedContainers: 1,
+ totalContainers: 1
+ })
+ })
+ );
+}
+
+test.describe('All environments preview', () => {
+ test('the preview toggle is saved to the user preferences', async ({ page }) => {
+ let saved: Preferences = {};
+ await withPreferences(page, () => saved);
+ await page.route(/\/api\/auth\/me\/profile(?:\?.*)?$/, async (route) => {
+ saved = { ...saved, ...route.request().postDataJSON().preferences };
+ const me = await (await page.request.get('/api/auth/me')).json();
+ await route.fulfill({
+ json: {
+ success: true,
+ data: { ...me.data, preferences: { ...me.data.preferences, ...saved } }
+ }
+ });
+ });
+
+ await page.goto('/account?tab=previews');
+ const toggle = page.getByRole('switch', { name: 'All environments (preview)' });
+ await expect(toggle).not.toBeChecked();
+
+ await toggle.click();
+ await expect(toggle).toBeChecked();
+ expect(saved.allEnvironmentsPreview).toBe(true);
+
+ await page.reload();
+ await expect(page.getByRole('switch', { name: 'All environments (preview)' })).toBeChecked();
+ });
+
+ test('lists rows from every environment and links details to their environment', async ({
+ page
+ }) => {
+ await enablePreview(page);
+ await mockRemoteEnvironment(page);
+
+ await page.goto('/containers');
+
+ await expect(
+ page.getByRole('columnheader', { name: 'Environment', exact: true })
+ ).toBeVisible();
+ const remoteRow = page.getByRole('row').filter({ hasText: 'remote-preview-web' });
+ await expect(remoteRow).toContainText(remoteEnvironment.name);
+ await expect(remoteRow.getByRole('link', { name: 'remote-preview-web' })).toHaveAttribute(
+ 'href',
+ `/containers/${remoteContainer.id}?env=${remoteEnvironment.id}`
+ );
+ });
+
+ test('the environment filter queries only the picked environments', async ({ page }) => {
+ await enablePreview(page);
+ await mockRemoteEnvironment(page);
+
+ await page.goto('/containers');
+ await expect(page.getByRole('row').filter({ hasText: 'remote-preview-web' })).toBeVisible();
+
+ const listRequests: string[] = [];
+ page.on('request', (request) => {
+ if (/\/api\/environments\/[^/]+\/containers(?:\?.*)?$/.test(request.url()))
+ listRequests.push(request.url());
+ });
+ await page.getByTestId('facet-environment-trigger').click();
+ await page.getByTestId(`facet-environment-option-${remoteEnvironment.id}`).click();
+
+ await expect.poll(() => listRequests.length).toBeGreaterThan(0);
+ expect(
+ listRequests.every((url) => url.includes(`/api/environments/${remoteEnvironment.id}/`))
+ ).toBe(true);
+ expect(listRequests.some((url) => /[?&]environment=/.test(url))).toBe(false);
+ await expect(page.getByRole('row').filter({ hasText: 'remote-preview-web' })).toBeVisible();
+ });
+
+ test('a failed environment is named inline and can be retried', async ({ page }) => {
+ await enablePreview(page);
+ await mockRemoteEnvironment(page);
+ let remoteAvailable = false;
+ await page.route(
+ new RegExp(`/api/environments/${remoteEnvironment.id}/containers(?:\\?.*)?$`),
+ (route) =>
+ remoteAvailable
+ ? route.fallback()
+ : route.fulfill({ status: 500, json: { success: false, error: 'remote unavailable' } })
+ );
+
+ await page.goto('/containers');
+ const alert = page.getByRole('alert').filter({ hasText: remoteEnvironment.name });
+ await expect(alert).toBeVisible();
+ await expect(page.getByRole('row').filter({ hasText: 'remote-preview-web' })).toHaveCount(0);
+
+ remoteAvailable = true;
+ await alert.getByRole('button', { name: 'Retry', exact: true }).click();
+
+ await expect(page.getByRole('row').filter({ hasText: 'remote-preview-web' })).toBeVisible();
+ await expect(alert).toHaveCount(0);
+ });
+
+ test('page-wide confirmations count environments without listing them', async ({ page }) => {
+ await enablePreview(page);
+ await mockRemoteEnvironment(page);
+
+ await page.goto('/projects');
+ await page
+ .getByRole('button', { name: 'Update Projects', exact: true })
+ .filter({ visible: true })
+ .first()
+ .click();
+
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toContainText('This runs on all 2 environments.');
+ await expect(dialog).not.toContainText(remoteEnvironment.name);
+ await dialog.getByRole('button', { name: 'Cancel', exact: true }).click();
+ });
+
+ test('sorting by environment orders rows without sending the sort to environments', async ({
+ page
+ }) => {
+ await enablePreview(page);
+ await mockRemoteEnvironment(page);
+ const listRequests: string[] = [];
+ page.on('request', (request) => {
+ if (/\/api\/environments\/[^/]+\/containers(?:\?.*)?$/.test(request.url()))
+ listRequests.push(request.url());
+ });
+
+ await page.goto('/containers');
+ await expect(page.getByRole('row').filter({ hasText: 'remote-preview-web' })).toBeVisible();
+ await page
+ .getByRole('columnheader', { name: 'Environment', exact: true })
+ .getByRole('button')
+ .click();
+ await page.getByRole('menuitem', { name: 'Desc', exact: true }).click();
+
+ await expect(page.getByRole('row').nth(1)).toContainText(remoteEnvironment.name);
+ expect(listRequests.some((url) => /[?&]sort=environment/.test(url))).toBe(false);
+ });
+
+ test('the dot label style shows the environment name on hover', async ({ page }) => {
+ await withPreferences(page, () => ({
+ allEnvironmentsPreview: true,
+ environmentLabelStyle: 'dot'
+ }));
+ await mockRemoteEnvironment(page);
+
+ await page.goto('/containers');
+ const remoteRow = page.getByRole('row').filter({ hasText: 'remote-preview-web' });
+ await expect(remoteRow).toBeVisible();
+ await expect(remoteRow).not.toContainText(remoteEnvironment.name);
+
+ await remoteRow.getByLabel(remoteEnvironment.name).hover();
+ // The row shows only the dot, so the visible name is the tooltip.
+ await expect(page.getByText(remoteEnvironment.name, { exact: true })).toBeVisible();
+ });
+});
diff --git a/types/system/diagnostics.go b/types/system/diagnostics.go
index 299a56d6b..28f721e4d 100644
--- a/types/system/diagnostics.go
+++ b/types/system/diagnostics.go
@@ -52,6 +52,29 @@ type GoroutineLeakReport struct {
ScannedAt time.Time `json:"scannedAt"`
}
+// GoroutineProfile groups the live goroutines by identical stack, largest group first.
+type GoroutineProfile struct {
+ Total int `json:"total"`
+ Groups []GoroutineGroup `json:"groups"`
+ CapturedAt time.Time `json:"capturedAt"`
+}
+
+// GoroutineGroup is a set of goroutines that share one stack.
+type GoroutineGroup struct {
+ Count int `json:"count"`
+ // Label is the outermost non-runtime function, usually the goroutine's entry point.
+ Label string `json:"label"`
+ // Frames lists the stack innermost first.
+ Frames []GoroutineFrame `json:"frames"`
+}
+
+// GoroutineFrame is one stack frame of a goroutine group.
+type GoroutineFrame struct {
+ Function string `json:"function"`
+ File string `json:"file"`
+ Line int `json:"line"`
+}
+
// MemoryInfo is the subset of runtime.MemStats surfaced in diagnostics. All
// byte counts are raw bytes.
type MemoryInfo struct {
diff --git a/types/user/user.go b/types/user/user.go
index d4cb8a889..a08184bae 100644
--- a/types/user/user.go
+++ b/types/user/user.go
@@ -27,6 +27,10 @@ type Preferences struct {
MobileNavigationShowLabels *bool `json:"mobileNavigationShowLabels,omitempty" doc:"Show text labels in mobile navigation"`
DefaultLandingPage *string `json:"defaultLandingPage,omitempty" doc:"Route opened after signing in"`
DefaultProjectEditorLayout *string `json:"defaultProjectEditorLayout,omitempty" enum:"auto,classic,tree" doc:"Initial layout of the project editor; auto keeps workspace detection"`
+ AllEnvironmentsPreview *bool `json:"allEnvironmentsPreview,omitempty" doc:"Preview: resource lists show and act on every enabled environment"`
+ // A pointer so the merge-only preferences update replaces the whole map.
+ EnvironmentColors *map[string]string `json:"environmentColors,omitempty" doc:"Environment label color by environment ID"`
+ EnvironmentLabelStyle *string `json:"environmentLabelStyle,omitempty" enum:"name,dot" doc:"How resource lists label environments"`
}
// CreateUser represents the request body for creating a new user.