Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
chore: fix test setup and remove stale tests (#4240)
Kyle Mendell29de5be38aec
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a91e978f9..8894016a2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -254,7 +254,7 @@ jobs:- name: sqlitecompose_file: setup/compose.yamlport: 3000- playwright_projects: --project=chromium --project=mobile-chromium --project=tablet-chromium --project=firefox --project=accessibility+ playwright_projects: --project=chromium --project=mobile-chromium --project=tablet-chromium --project=accessibility- name: postgrescompose_file: setup/compose-postgres.yamlport: 3001diff --git a/Justfile b/Justfileindex 3b64d5211..ef14db841 100644--- a/Justfile+++ b/Justfile@@ -420,7 +420,7 @@ _deps-install-frontend:[group('deps')]_deps-install-tests:vp -C tests install- vp -C tests exec playwright install --with-deps chromium firefox+ vp -C tests exec playwright install --with-deps chromium# Install backend Go dependencies[group('deps')]diff --git a/backend/internal/bootstrap/playwright_router_bootstrap.go b/backend/internal/bootstrap/playwright_router_bootstrap.goindex da4a8fab4..3057eab3b 100644--- a/backend/internal/bootstrap/playwright_router_bootstrap.go+++ b/backend/internal/bootstrap/playwright_router_bootstrap.go@@ -15,12 +15,12 @@ func init() {func(apiGroup *echo.Group, deps api.HandlerDeps) {apiKeyService := deps.ApiKey.Service()userService := deps.User.Service()- if apiKeyService == nil || userService == nil || deps.Federated == nil {+ if apiKeyService == nil || userService == nil || deps.Federated == nil || deps.GitRepository.Service() == nil || deps.GitOpsSync.Service() == nil || deps.Project.Service() == nil {slog.Warn("Playwright service not available, skipping playwright routes")return}- playwrightService := playwright.NewPlaywrightService(apiKeyService, userService)+ playwrightService := playwright.NewPlaywrightService(apiKeyService, userService, deps.GitRepository.Service(), deps.GitOpsSync.Service(), deps.Project.Service())playwright.SetupRoutes(apiGroup, playwrightService, deps.Federated)slog.Info("Playwright routes registered for E2E testing")},diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex b392b83c1..e395876ed 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -43,19 +43,12 @@ var loggerSkipPatterns = []string{"GET /api/environments/*/ws/containers/*/terminal","GET /api/environments/*/ws/projects/*/logs","GET /api/environments/*/ws/system/stats",- // Long-lived aggregate streams. The access log only fires when the stream- // ends, so it reports the full connection lifetime as request latency —- // which reads as a multi-minute hung request. The handlers log their own- // termination instead."GET /api/stream","GET /_app/*","GET /img","GET /api/health","HEAD /api/health",- // Static branding / PWA assets — browsers re-request these frequently- // and the logs add no signal."GET /api/app-images/*",- // Chunked uploads: a large file logs one line per chunk otherwise."PUT /api/environments/*/uploads/*/*/chunks/*",}diff --git a/backend/internal/playwright/gitops.go b/backend/internal/playwright/gitops.gonew file mode 100644index 000000000..aa4e55870--- /dev/null+++ b/backend/internal/playwright/gitops.go@@ -0,0 +1,131 @@+//go:build playwright++package playwright++import (+ "context"+ "time"++ "emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/project"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"+ gitopstypes "github.com/getarcaneapp/arcane/types/v2/gitops"+ projecttypes "github.com/getarcaneapp/arcane/types/v2/project"+)++const (+ testRepositoryNameInternal = "gitsyncs-test-repo"+ testRepositoryURLInternal = "https://github.com/getarcaneapp/gitsyncs.git"+ testSyncNameInternal = "gitops-test-sync"+ testProjectNameInternal = "gitops-test-project"+ testBranchInternal = "main"+ testComposePathInternal = "compose-test-repo/compose.yaml"+)++// CreateTestGitOpsProject seeds the suite prerequisite through the real GitOps services.+func (ps *PlaywrightService) CreateTestGitOpsProject(ctx context.Context) error {+ ctx, cancel := context.WithTimeout(ctx, 90*time.Second)+ defer cancel()+ actor, err := ps.userService.GetUserByUsername(ctx, "arcane")+ if err != nil {+ return errors.WrapIf(err, "failed to get arcane user")+ }+ repositoryID, err := ps.ensureTestRepositoryInternal(ctx, *actor)+ if err != nil {+ return err+ }+ sync, created, err := ps.ensureTestSyncInternal(ctx, repositoryID, *actor)+ if err != nil {+ return err+ }+ // CreateSync already ran the initial sync; retry only if it failed.+ if !created || sync.LastSyncStatus == nil || *sync.LastSyncStatus != "success" || sync.LastSyncError != nil {+ result, err := ps.syncService.PerformSync(ctx, "0", sync.ID, *actor)+ if err != nil {+ return errors.WrapIf(err, "failed to sync GitOps test project")+ }+ if !result.Success {+ return errors.Errorf("GitOps test sync failed: %s", result.Message)+ }+ sync, err = ps.syncService.GetSyncByID(ctx, "0", sync.ID)+ if err != nil {+ return err+ }+ }+ if sync.ProjectID == nil || sync.LastSyncCommit == nil || *sync.LastSyncCommit == "" || sync.LastSyncStatus == nil || *sync.LastSyncStatus != "success" || sync.LastSyncError != nil {+ return errors.New("GitOps test sync did not bind a managed project and commit")+ }+ details, err := ps.projectService.GetProjectDetails(ctx, *sync.ProjectID, projecttypes.DetailsOptions{})+ if err != nil {+ return errors.WrapIf(err, "failed to verify GitOps test project")+ }+ if details.Name != testProjectNameInternal || details.GitOpsManagedBy == nil || *details.GitOpsManagedBy != sync.ID || details.LastSyncCommit == nil || *details.LastSyncCommit != *sync.LastSyncCommit {+ return errors.New("GitOps test project does not match its managed sync")+ }+ return nil+}++func (ps *PlaywrightService) ensureTestRepositoryInternal(ctx context.Context, actor common.User) (string, error) {+ params := pagination.QueryParams{Search: testRepositoryNameInternal, Limit: 100}+ repositories, _, err := ps.repositoryService.GetRepositoriesPaginated(ctx, params)+ if err != nil {+ return "", err+ }+ repositoryID := ""+ for _, repository := range repositories {+ if repository.Name != testRepositoryNameInternal {+ continue+ }+ updated, err := ps.repositoryService.UpdateRepository(ctx, repository.ID, gitopstypes.UpdateRepositoryRequest{+ Name: new(testRepositoryNameInternal), URL: new(testRepositoryURLInternal), AuthType: new("none"), Enabled: new(true),+ }, actor)+ if err != nil {+ return "", err+ }+ repositoryID = updated.ID+ break+ }+ if repositoryID == "" {+ created, err := ps.repositoryService.CreateRepository(ctx, gitopstypes.CreateRepositoryRequest{+ Name: testRepositoryNameInternal, URL: testRepositoryURLInternal, AuthType: "none", Enabled: new(true),+ }, actor)+ if err != nil {+ return "", err+ }+ repositoryID = created.ID+ }+ if err := ps.repositoryService.TestConnection(ctx, repositoryID, testBranchInternal, actor); err != nil {+ return "", errors.WrapIf(err, "failed to connect to GitOps test repository")+ }+ return repositoryID, nil+}++func (ps *PlaywrightService) ensureTestSyncInternal(ctx context.Context, repositoryID string, actor common.User) (*project.GitOpsSync, bool, error) {+ params := pagination.QueryParams{Search: testSyncNameInternal, Limit: 100}+ syncs, _, _, err := ps.syncService.GetSyncsPaginated(ctx, "0", params)+ if err != nil {+ return nil, false, err+ }+ for _, sync := range syncs {+ if sync.Name != testSyncNameInternal {+ continue+ }+ updated, err := ps.syncService.UpdateSync(ctx, "0", sync.ID, gitopstypes.UpdateSyncRequest{+ Name: new(testSyncNameInternal), RepositoryID: new(repositoryID), Branch: new(testBranchInternal), ComposePath: new(testComposePathInternal),+ TargetType: new("project"), ProjectName: new(testProjectNameInternal), AutoSync: new(false), SyncDirectory: new(false), PullImageAfterSync: new(false), RedeployAfterSync: new(false),+ }, actor)+ if err != nil {+ return nil, false, err+ }+ return updated, false, nil+ }+ created, err := ps.syncService.CreateSync(ctx, "0", gitopstypes.CreateSyncRequest{+ Name: testSyncNameInternal, RepositoryID: repositoryID, Branch: testBranchInternal, ComposePath: testComposePathInternal,+ TargetType: "project", ProjectName: testProjectNameInternal, AutoSync: new(false), SyncDirectory: new(false), PullImageAfterSync: new(false), RedeployAfterSync: new(false),+ }, actor)+ if err != nil {+ return nil, false, err+ }+ return created, true, nil+}diff --git a/backend/internal/playwright/handler.go b/backend/internal/playwright/handler.goindex dfa274587..9da784152 100644--- a/backend/internal/playwright/handler.go+++ b/backend/internal/playwright/handler.go@@ -31,6 +31,7 @@ func SetupRoutes(api *echo.Group, service *PlaywrightService, federatedService *group := api.Group("/playwright")handler := &playwrightHandlerInternal{service: service, federated: federatedService}+ group.POST("/create-test-gitops-project", handler.createTestGitOpsProjectInternal)group.POST("/create-test-api-keys", handler.createTestAPIKeysInternal)group.POST("/delete-test-api-keys", handler.deleteTestAPIKeysInternal)group.POST("/create-test-federated-credential", handler.createTestFederatedCredentialInternal)@@ -78,3 +79,10 @@ func (h *playwrightHandlerInternal) createTestFederatedCredentialInternal(c *echreturn c.JSON(http.StatusCreated, map[string]any{"credential": map[string]string{"id": credentialID}})}++func (h *playwrightHandlerInternal) createTestGitOpsProjectInternal(c *echo.Context) error {+ if err := h.service.CreateTestGitOpsProject(c.Request().Context()); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]any{"error": err.Error()})+ }+ return c.NoContent(http.StatusNoContent)+}diff --git a/backend/internal/playwright/service.go b/backend/internal/playwright/service.goindex 767b4562f..5927a6f33 100644--- a/backend/internal/playwright/service.go+++ b/backend/internal/playwright/service.go@@ -9,6 +9,9 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/apikey"+ "github.com/getarcaneapp/arcane/backend/v2/internal/gitops"+ "github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"+ "github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -16,14 +19,20 @@ import ()type PlaywrightService struct {- apiKeyService *apikey.ApiKeyService- userService *user.UserService+ apiKeyService *apikey.ApiKeyService+ userService *user.UserService+ repositoryService *gitrepo.GitRepositoryService+ syncService *gitops.GitOpsSyncService+ projectService *project.ProjectService}-func NewPlaywrightService(apiKeyService *apikey.ApiKeyService, userService *user.UserService) *PlaywrightService {+func NewPlaywrightService(apiKeyService *apikey.ApiKeyService, userService *user.UserService, repositoryService *gitrepo.GitRepositoryService, syncService *gitops.GitOpsSyncService, projectService *project.ProjectService) *PlaywrightService {return &PlaywrightService{- apiKeyService: apiKeyService,- userService: userService,+ apiKeyService: apiKeyService,+ userService: userService,+ repositoryService: repositoryService,+ syncService: syncService,+ projectService: projectService,}}@@ -71,13 +80,9 @@ func (ps *PlaywrightService) DeleteAllTestApiKeys(ctx context.Context) error {// Get all API keys with test prefixparams := pagination.QueryParams{- SearchQuery: pagination.SearchQuery{- Search: "test-api-key",- },- Params: pagination.Params{- Start: 0,- Limit: 1000,- },+ Search: "test-api-key",+ Start: 0,+ Limit: 1000,}apiKeys, _, err := ps.apiKeyService.ListApiKeys(ctx, params)diff --git a/backend/pkg/utils/handlerutil/remote_proxy.go b/backend/pkg/utils/handlerutil/remote_proxy.goindex 6279612c6..015f8da98 100644--- a/backend/pkg/utils/handlerutil/remote_proxy.go+++ b/backend/pkg/utils/handlerutil/remote_proxy.go@@ -4,6 +4,7 @@ import ("context""encoding/json/v2"stderrors "errors"+ "net/http""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"@@ -51,6 +52,9 @@ func TranslateRemoteProxyError(err error) error {}if statusErr, ok := stderrors.AsType[*remenv.StatusError](err); ok {+ if statusErr.StatusCode == http.StatusUnauthorized {+ return huma.Error502BadGateway("Remote environment rejected the manager's credentials")+ }return huma.NewError(statusErr.StatusCode, "environment returned error: "+string(statusErr.Body), nil)}diff --git a/frontend/src/routes/(app)/customize/templates/[id]/+page.svelte b/frontend/src/routes/(app)/customize/templates/[id]/+page.svelteindex 9a27ca2a4..9c91e2c0f 100644--- a/frontend/src/routes/(app)/customize/templates/[id]/+page.svelte+++ b/frontend/src/routes/(app)/customize/templates/[id]/+page.svelte@@ -12,6 +12,8 @@import IfPermitted from '#lib/components/if-permitted.svelte';import { goto, refreshAll } from '$app/navigation';import { m } from '#lib/paraglide/messages.js';+ import { useQueryClient } from '@tanstack/svelte-query';+ import { queryKeys } from '#lib/query/query-keys.js';import { templateService } from '#lib/services/template-service.js';import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';import { toast } from 'svelte-sonner';@@ -38,6 +40,7 @@} from '#lib/icons/index.js';let { data } = $props();+ const queryClient = useQueryClient();let template = $derived(data.templateData.template);let services = $derived(data.templateData.services);@@ -106,6 +109,10 @@originalDescription = validated.description ?? '';originalCompose = validated.composeContent;originalEnv = validated.envContent ?? '';+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: queryKeys.templates.content(template.id) }),+ queryClient.invalidateQueries({ queryKey: queryKeys.templates.all })+ ]);await refreshAll();}});@@ -151,6 +158,10 @@if (downloadedTemplate?.id) {await goto(`/customize/templates/${downloadedTemplate.id}`, { replaceState: true });} else {+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: queryKeys.templates.content(template.id) }),+ queryClient.invalidateQueries({ queryKey: queryKeys.templates.all })+ ]);await refreshAll();}})()diff --git a/frontend/src/routes/(app)/images/+page.svelte b/frontend/src/routes/(app)/images/+page.svelteindex f11d6acde..0e47c89f9 100644--- a/frontend/src/routes/(app)/images/+page.svelte+++ b/frontend/src/routes/(app)/images/+page.svelte@@ -202,11 +202,13 @@await Promise.all([queryClient.query({queryKey: queryKeys.images.list(requestedEnvId, options),- queryFn: () => imageService.getImagesForEnvironment(requestedEnvId, options)+ queryFn: () => imageService.getImagesForEnvironment(requestedEnvId, options),+ staleTime: 0}),queryClient.query({queryKey: queryKeys.images.usageCounts(requestedEnvId),- queryFn: () => imageService.getImageUsageCountsForEnvironment(requestedEnvId)+ queryFn: () => imageService.getImageUsageCountsForEnvironment(requestedEnvId),+ staleTime: 0})]);}diff --git a/frontend/src/routes/(app)/images/builds/+page.svelte b/frontend/src/routes/(app)/images/builds/+page.svelteindex b2d097253..7b088f668 100644--- a/frontend/src/routes/(app)/images/builds/+page.svelte+++ b/frontend/src/routes/(app)/images/builds/+page.svelte@@ -55,10 +55,18 @@const providerOptions = $derived.by<BuildProviderOption[]>(() => {const options: BuildProviderOption[] = [- { label: m.local_docker(), value: 'local', description: m.local_docker_description() }+ {+ label: m.local_docker(),+ value: 'local',+ description: m.local_docker_description()+ }];if (depotAvailable) {- options.push({ label: m.depot(), value: 'depot', description: m.depot_description() });+ options.push({+ label: m.depot(),+ value: 'depot',+ description: m.depot_description()+ });}return options;});@@ -163,6 +171,7 @@const registriesQuery = createQuery(() => ({queryKey: queryKeys.containerRegistries.list(registryRequestOptions),enabled: isPushMode,+ staleTime: 0,queryFn: () => containerRegistryService.getRegistries(registryRequestOptions)}));@@ -184,7 +193,10 @@const selectedRegistry = $derived(registries.find((registry) => registry.id === inputs.registryId.value));const repositoryOptions = $derived<SelectOption[]>(- (selectedRegistry?.repositoryNames ?? []).map((name) => ({ label: name, value: name }))+ (selectedRegistry?.repositoryNames ?? []).map((name) => ({+ label: name,+ value: name+ })));const fullImageReference = $derived(@@ -193,7 +205,10 @@: '');- type ImageBuildRequest = { envId: string; provider: 'local' | 'depot' } & Pick<+ type ImageBuildRequest = {+ envId: string;+ provider: 'local' | 'depot';+ } & Pick<ImageBuildRecord,| 'contextDir'| 'dockerfile'@@ -312,7 +327,9 @@appendLog(m.build_completed());},onSettled: async (_data, _error, variables) => {- await queryClient.invalidateQueries({ queryKey: queryKeys.images.builds(variables.envId) });+ await queryClient.invalidateQueries({+ queryKey: queryKeys.images.builds(variables.envId)+ });}}));@@ -572,7 +589,10 @@const operationResult = await tryCatch((async () => {const resolvedEnvId = await environmentStore.getCurrentEnvironmentId();- await buildMutation.mutateAsync({ envId: resolvedEnvId, ...payload });+ await buildMutation.mutateAsync({+ envId: resolvedEnvId,+ ...payload+ });toast.success(m.build_completed());})());@@ -702,59 +722,69 @@{#if isDesktop}<ResourceDetailLayout title={m.build_workspace()} subtitle={m.manual_build_workspace_subtitle()}>- <Tabs.Root value={mainTab} onValueChange={mainUrlTab.select} class="flex h-(--height-screen-inset-12) flex-col">- <Tabs.List class="mb-3 flex w-fit">- <Tabs.Trigger value="build">- {m.build_workspace()}- </Tabs.Trigger>- <Tabs.Trigger value="history">- {m.build_history()}- </Tabs.Trigger>- </Tabs.List>-- <Tabs.Content value="build" class="min-h-0 flex-1">- <div class="relative flex h-full">- <ResizableSplit- class="flex h-full w-full gap-3"- firstClass="h-full"- secondClass="h-full"- minSize={300}- minSecondSize={520}- defaultRatio={0.28}- handleSize={10}- handleClass="bg-muted-foreground/50 rounded-full"- allowCollapse={true}- persistKey="arcane.build.workspace.split"- >- {#snippet first()}- {@render workspaceCard()}- {/snippet}- {#snippet second()}- <Card.Root class="flex h-full flex-col overflow-hidden">- {@render rightPanel()}- </Card.Root>- {/snippet}- </ResizableSplit>- </div>- </Tabs.Content>+ <div class="h-screen-inset-12">+ <Tabs.Root value={mainTab} onValueChange={mainUrlTab.select} class="flex h-full flex-col">+ <Tabs.List class="mb-3 flex w-fit">+ <Tabs.Trigger value="build">+ {m.build_workspace()}+ </Tabs.Trigger>+ <Tabs.Trigger value="history">+ {m.build_history()}+ </Tabs.Trigger>+ </Tabs.List>- <Tabs.Content value="history" class="min-h-0 flex-1">- <Card.Root class="flex h-full flex-col overflow-hidden">- {@render historyContent()}- </Card.Root>- </Tabs.Content>- </Tabs.Root>+ <Tabs.Content value="build" class="min-h-0 flex-1">+ <div class="relative flex h-full">+ <ResizableSplit+ class="flex h-full w-full gap-3"+ firstClass="h-full"+ secondClass="h-full"+ minSize={300}+ minSecondSize={520}+ defaultRatio={0.28}+ handleSize={10}+ handleClass="bg-muted-foreground/50 rounded-full"+ allowCollapse={true}+ persistKey="arcane.build.workspace.split"+ >+ {#snippet first()}+ {@render workspaceCard()}+ {/snippet}+ {#snippet second()}+ <Card.Root class="flex h-full flex-col overflow-hidden">+ {@render rightPanel()}+ </Card.Root>+ {/snippet}+ </ResizableSplit>+ </div>+ </Tabs.Content>++ <Tabs.Content value="history" class="min-h-0 flex-1">+ <Card.Root class="flex h-full flex-col overflow-hidden">+ {@render historyContent()}+ </Card.Root>+ </Tabs.Content>+ </Tabs.Root>+ </div></ResourceDetailLayout>{:else}<TabbedPageLayout tabItems={mainTabItems} selectedTab={mainTab} onTabChange={onMainTabChange} class="min-h-screen-inset-10">{#snippet headerInfo()}<div class="flex flex-col gap-1">{#if mainTab === 'history'}- <h1 class="text-2xl font-semibold tracking-tight">{m.builds()}</h1>- <p class="text-sm text-muted-foreground">{m.build_output()}</p>+ <h1 class="text-2xl font-semibold tracking-tight">+ {m.builds()}+ </h1>+ <p class="text-sm text-muted-foreground">+ {m.build_output()}+ </p>{:else}- <h1 class="text-2xl font-semibold tracking-tight">{m.build_workspace()}</h1>- <p class="text-sm text-muted-foreground">{m.manual_build_workspace_subtitle()}</p>+ <h1 class="text-2xl font-semibold tracking-tight">+ {m.build_workspace()}+ </h1>+ <p class="text-sm text-muted-foreground">+ {m.manual_build_workspace_subtitle()}+ </p>{/if}</div>{/snippet}@@ -776,8 +806,12 @@>{#snippet headerInfo()}<div class="flex flex-col gap-1">- <h2 class="text-lg font-semibold">{m.build_workspace()}</h2>- <p class="text-xs text-muted-foreground">{m.manual_build_workspace_subtitle()}</p>+ <h2 class="text-lg font-semibold">+ {m.build_workspace()}+ </h2>+ <p class="text-xs text-muted-foreground">+ {m.manual_build_workspace_subtitle()}+ </p></div>{/snippet}{#snippet headerActions()}diff --git a/frontend/src/routes/(app)/networks/+page.svelte b/frontend/src/routes/(app)/networks/+page.svelteindex ea01abac1..615451452 100644--- a/frontend/src/routes/(app)/networks/+page.svelte+++ b/frontend/src/routes/(app)/networks/+page.svelte@@ -73,7 +73,8 @@pageState.requestOptions = options;await queryClient.query({queryKey: queryKeys.networks.list(requestedEnvId, options),- queryFn: () => networkService.getNetworksForEnvironment(requestedEnvId, options)+ queryFn: () => networkService.getNetworksForEnvironment(requestedEnvId, options),+ staleTime: 0});}diff --git a/tests/playwright.config.ts b/tests/playwright.config.tsindex 405b5aca0..2909581b5 100644--- a/tests/playwright.config.ts+++ b/tests/playwright.config.ts@@ -14,7 +14,7 @@ export default defineConfig({forbidOnly: !!process.env.CI,failOnFlakyTests: !!process.env.CI,retries: process.env.CI ? 2 : 0,- retryStrategy: 'isolated',+ retryStrategy: 'immediate',globalTimeout: process.env.CI ? 35 * 60 * 1000 : 0,maxFailures: process.env.CI ? 20 : 0,workers,@@ -22,6 +22,7 @@ export default defineConfig({globalTeardown: './setup/global-teardown',reporter: process.env.CI? [+ ['./utils/compose-reporter.ts'],['html', { outputFolder: '.report' }],['github'],[@@ -33,7 +34,11 @@ export default defineConfig({}]]- : [['line'], ['html', { open: 'never', outputFolder: '.report' }]],+ : [+ ['./utils/compose-reporter.ts'],+ ['line'],+ ['html', { open: 'never', outputFolder: '.report' }]+ ],use: {baseURL,serviceWorkers: 'block',@@ -59,15 +64,15 @@ export default defineConfig({testMatch: '**/spec/*.spec.ts',testIgnore: ['**/spec/cli.spec.ts',- '**/spec/responsive-browser.spec.ts',- '**/spec/accessibility-check.spec.ts'+ '**/spec/responsive.spec.ts',+ '**/spec/accessibility.spec.ts']},{name: 'mobile-chromium',use: { ...devices['Pixel 7'], storageState: '.auth/login.json' },dependencies: ['auth-setup'],- testMatch: '**/spec/responsive-browser.spec.ts'+ testMatch: '**/spec/responsive.spec.ts'},{name: 'tablet-chromium',@@ -77,17 +82,7 @@ export default defineConfig({storageState: '.auth/login.json'},dependencies: ['auth-setup'],- testMatch: '**/spec/responsive-browser.spec.ts'- },- {- name: 'firefox',- use: {- ...devices['Desktop Firefox'],- storageState: { cookies: [], origins: [] }- },- dependencies: ['auth-setup'],- testMatch: ['**/spec/token-refresh.spec.ts', '**/spec/network.spec.ts'],- grep: /@cross-browser/+ testMatch: '**/spec/responsive.spec.ts'},{name: 'accessibility',@@ -96,7 +91,7 @@ export default defineConfig({storageState: { cookies: [], origins: [] }},dependencies: ['auth-setup'],- testMatch: '**/spec/accessibility-check.spec.ts'+ testMatch: '**/spec/accessibility.spec.ts'},{name: 'cli',diff --git a/tests/setup/gitops.setup.ts b/tests/setup/gitops.setup.tsindex e3b15b4b4..891166a1d 100644--- a/tests/setup/gitops.setup.ts+++ b/tests/setup/gitops.setup.ts@@ -1,168 +1,11 @@-import { expect, test as setup, type Page } from '../fixtures/test.fixture';-import { readApiData } from '../utils/fetch.util';--const GITOPS_REPO_NAME = 'gitsyncs-test-repo';-const GITOPS_REPO_URL = 'https://github.com/getarcaneapp/gitsyncs.git';-const GITOPS_REPO_BRANCH = 'main';-const GITOPS_COMPOSE_PATH = 'compose-test-repo/compose.yaml';-const GITOPS_SYNC_NAME = 'gitops-test-sync';-const GITOPS_PROJECT_NAME = 'gitops-test-project';--type GitRepository = {- id: string;- name: string;- url: string;- authType: string;- enabled: boolean;-};--type GitOpsSync = {- id: string;- name: string;- projectId?: string;- projectName: string;- lastSyncStatus?: string;- lastSyncError?: string;- lastSyncCommit?: string;-};--type GitOpsProject = {- id: string;- name: string;- gitOpsManagedBy?: string;- lastSyncCommit?: string;-};--async function listRepositories(page: Page): Promise<GitRepository[]> {- const response = await page.request.get(- `/api/customize/git-repositories?search=${encodeURIComponent(GITOPS_REPO_NAME)}&start=0&limit=100`- );- return readApiData<GitRepository[]>(response, 'List Git repositories');-}--async function ensureRepository(page: Page): Promise<GitRepository> {- const existing = (await listRepositories(page)).find(- (repository) => repository.name === GITOPS_REPO_NAME- );- const body = {- name: GITOPS_REPO_NAME,- url: GITOPS_REPO_URL,- authType: 'none',- enabled: true- };-- const repository = existing- ? await readApiData<GitRepository>(- await page.request.put(`/api/customize/git-repositories/${existing.id}`, { data: body }),- 'Update GitOps test repository'- )- : await readApiData<GitRepository>(- await page.request.post('/api/customize/git-repositories', { data: body }),- 'Create GitOps test repository'- );-- await readApiData<{ message: string }>(- await page.request.post(- `/api/customize/git-repositories/${repository.id}/test?branch=${encodeURIComponent(GITOPS_REPO_BRANCH)}`- ),- 'Test GitOps repository connection'- );-- return repository;-}--async function listSyncs(page: Page): Promise<GitOpsSync[]> {- const response = await page.request.get(- `/api/environments/0/gitops-syncs?search=${encodeURIComponent(GITOPS_SYNC_NAME)}&start=0&limit=100`- );- return readApiData<GitOpsSync[]>(response, 'List GitOps syncs');-}--async function ensureSync(page: Page, repositoryId: string): Promise<GitOpsSync> {- const existing = (await listSyncs(page)).find((sync) => sync.name === GITOPS_SYNC_NAME);- const body = {- name: GITOPS_SYNC_NAME,- repositoryId,- branch: GITOPS_REPO_BRANCH,- composePath: GITOPS_COMPOSE_PATH,- targetType: 'project',- projectName: GITOPS_PROJECT_NAME,- autoSync: false,- syncDirectory: false,- pullImageAfterSync: false,- redeployAfterSync: false- };-- return existing- ? readApiData<GitOpsSync>(- await page.request.put(`/api/environments/0/gitops-syncs/${existing.id}`, {- data: body- }),- 'Update GitOps test sync'- )- : readApiData<GitOpsSync>(- await page.request.post('/api/environments/0/gitops-syncs', { data: body }),- 'Create GitOps test sync'- );-}--async function getSync(page: Page, syncId: string): Promise<GitOpsSync> {- return readApiData<GitOpsSync>(- await page.request.get(`/api/environments/0/gitops-syncs/${syncId}`),- 'Get GitOps test sync'- );-}--async function getProjects(page: Page): Promise<GitOpsProject[]> {- return readApiData<GitOpsProject[]>(- await page.request.get('/api/environments/0/projects?start=0&limit=100'),- 'List projects after GitOps sync'- );-}+import { expect, test as setup } from '../fixtures/test.fixture';setup('create and verify the GitOps project prerequisite', async ({ page }) => {setup.setTimeout(120_000);-- const repository = await ensureRepository(page);- let sync = await ensureSync(page, repository.id);-- await readApiData<{ success: boolean; message: string }>(- await page.request.post(`/api/environments/0/gitops-syncs/${sync.id}/sync`),- 'Run GitOps test sync'- );-- await expect- .poll(- async () => {- sync = await getSync(page, sync.id);- return {- status: sync.lastSyncStatus,- hasProject: Boolean(sync.projectId),- hasCommit: Boolean(sync.lastSyncCommit),- error: sync.lastSyncError ?? null- };- },- {- message: 'Expected GitOps sync to bind a managed project and commit',- timeout: 60_000,- intervals: [500, 1_000, 2_000]- }- )- .toEqual({ status: 'success', hasProject: true, hasCommit: true, error: null });-- const projects = await getProjects(page);- const project = projects.find((candidate) => candidate.id === sync.projectId);-- expect(project, 'Expected the GitOps sync project to exist in the projects API').toBeDefined();- expect(project!.name).toBe(GITOPS_PROJECT_NAME);- expect(project!.gitOpsManagedBy).toBe(sync.id);-- const projectDetail = await readApiData<GitOpsProject>(- await page.request.get(`/api/environments/0/projects/${project!.id}`),- 'Get GitOps managed project details'- );- expect(projectDetail.lastSyncCommit).toBe(sync.lastSyncCommit);-+ const response = await page.request.post('/api/playwright/create-test-gitops-project', {+ timeout: 100_000+ });+ expect(response.status(), await response.text()).toBe(204);await page.goto('/projects');- await expect(page.getByRole('link', { name: GITOPS_PROJECT_NAME, exact: true })).toBeVisible();+ await expect(page.getByRole('link', { name: 'gitops-test-project', exact: true })).toBeVisible();});diff --git a/tests/setup/global-setup.ts b/tests/setup/global-setup.tsindex cfc90e79d..732f3e7f4 100644--- a/tests/setup/global-setup.ts+++ b/tests/setup/global-setup.ts@@ -16,7 +16,8 @@ export function captureComposeDiagnostics(composeFile: string) {try {const output = execFileSync('docker', ['compose', '-f', composeFile, ...args], {encoding: 'utf8',- maxBuffer: 32 * 1024 * 1024+ maxBuffer: 32 * 1024 * 1024,+ timeout: 10_000});fs.writeFileSync(path.join(directory, `${name}.txt`), output);} catch (error) {@@ -57,6 +58,9 @@ function ensureProjectsDirIsContainerWritable(projectsDir: string) {}async function globalSetup() {+ process.env.ARCANE_E2E_COMPOSE_FILE = process.env.COMPOSE_FILE+ ? path.resolve(__dirname, '..', process.env.COMPOSE_FILE)+ : path.resolve(__dirname, 'compose.yaml');console.log('\nStarting global setup...');const composeFile = process.env.COMPOSE_FILE@@ -111,7 +115,7 @@ async function globalSetup() {console.log('Server is ready!');break;}- } catch (e) {+ } catch {// Ignore connection errors}attempts++;diff --git a/tests/setup/global-teardown.ts b/tests/setup/global-teardown.tsindex b6136c5bb..ff22f3b6b 100644--- a/tests/setup/global-teardown.ts+++ b/tests/setup/global-teardown.ts@@ -20,7 +20,10 @@ async function globalTeardown() {// 1. Stop and remove Docker containerstry {console.log('Stopping Docker containers...');- execFileSync('docker', ['compose', '-f', composeFile, 'down', '-v'], { stdio: 'inherit' });+ execFileSync('docker', ['compose', '-f', composeFile, 'down', '-v'], {+ stdio: 'inherit',+ timeout: 60_000+ });console.log('Docker containers stopped and volumes removed.');} catch (error) {failures.push(error);@@ -42,8 +45,12 @@ async function globalTeardown() {if (fs.lstatSync(itemPath).isDirectory()) {try {fs.rmSync(itemPath, { recursive: true, force: true });- } catch (err: any) {- if (err.code === 'EACCES' || err.code === 'EPERM') {+ } catch (err) {+ if (+ err instanceof Error &&+ 'code' in err &&+ (err.code === 'EACCES' || err.code === 'EPERM')+ ) {// Arcane container creates files as root, fallback to docker to remove themexecFileSync('docker',@@ -59,7 +66,7 @@ async function globalTeardown() {'--',item],- { stdio: 'inherit' }+ { stdio: 'inherit', timeout: 30_000 });} else {throw err;diff --git a/tests/spec/accessibility-check.spec.ts b/tests/spec/accessibility.spec.tssimilarity index 100%rename from tests/spec/accessibility-check.spec.tsrename to tests/spec/accessibility.spec.tsdiff --git a/tests/spec/activity-center.spec.ts b/tests/spec/activities.spec.tssimilarity index 100%rename from tests/spec/activity-center.spec.tsrename to tests/spec/activities.spec.tsdiff --git a/tests/spec/api-keys.spec.ts b/tests/spec/api-keys.spec.tsdeleted file mode 100644index d7999e03e..000000000--- a/tests/spec/api-keys.spec.ts+++ /dev/null@@ -1,255 +0,0 @@-import { test, expect, type Page } from '../fixtures/test.fixture';-import { createTestApiKeys, deleteTestApiKeys, waitForDialogReady } from '../utils/playwright.util';-import { fetchApiKeysWithRetry } from '../utils/fetch.util';-import { openRowActionsMenu } from '../utils/table-actions.util';--const API_KEYS_ROUTE = '/settings/api-keys';--async function navigateToApiKeys(page: Page) {- await page.goto(API_KEYS_ROUTE);- await page.waitForLoadState('load');-}--test.describe('API Keys Page', () => {- // Each test starts with its own required keys.- test.beforeEach(async () => {- await createTestApiKeys(3);- });-- // Remove fixture keys before the next test.- test.afterEach(async ({ page }) => {- await deleteTestApiKeys();- await expect- .poll(- async () =>- (await fetchApiKeysWithRetry(page)).data.filter((key) =>- key.name.startsWith('test-api-key-')- ).length- )- .toBe(0);- });-- test('should display the API keys page title and description', async ({ page }) => {- await navigateToApiKeys(page);- await expect(page.getByRole('heading', { name: 'API Keys', level: 1 })).toBeVisible();- await expect(- page.getByText('Manage API keys for programmatic access to Arcane').first()- ).toBeVisible();- });-- test('should open Create API Key sheet', async ({ page }) => {- await navigateToApiKeys(page);-- await page.getByRole('button', { name: 'Create API Key' }).click();- await expect(page.getByRole('dialog')).toBeVisible();- await expect(page.getByText('Create API Key').first()).toBeVisible();- });-- test('should validate required fields when creating API key', async ({ page }) => {- await navigateToApiKeys(page);-- await page.getByRole('button', { name: 'Create API Key' }).click();- const dialog = page.getByRole('dialog');- await expect(dialog).toBeVisible();-- // Try to submit without filling required name field- await dialog.getByRole('button', { name: 'Create API Key', exact: true }).click();-- // Should show validation error for name field- await expect(dialog.getByText('Name is required', { exact: true })).toBeVisible();- });-- test('should create a new API key and show the key dialog', async ({ page }) => {- await navigateToApiKeys(page);-- await page.getByRole('button', { name: 'Create API Key' }).click();- const createDialog = page.getByRole('dialog');- await waitForDialogReady(createDialog);-- const apiKeyName = `test-api-key-created-${Date.now()}`;-- // Fill in the name field- await createDialog.getByLabel('Name', { exact: true }).fill(apiKeyName);-- // Optionally fill description- const descInput = createDialog.getByLabel('Description', { exact: true });- await descInput.fill('E2E test API key');-- // Select at least one permission (form requires min 1)- await createDialog- .getByPlaceholder('Filter permissions…', { exact: true })- .fill('containers:list');- await createDialog.getByRole('checkbox', { name: 'Select all' }).check();-- // Submit the form- await createDialog.getByRole('button', { name: 'Create API Key', exact: true }).click();-- // Should show success toast- await expect(- page- .getByRole('region', { name: 'Notifications alt+T', exact: true })- .getByRole('listitem')- .first()- ).toBeVisible({ timeout: 10000 });-- // Should show the API key reveal dialog- await expect(page.getByText('API Key Created')).toBeVisible();- await expect(- page.getByText("Copy your API key now. You won't be able to see it again!", {- exact: true- })- ).toBeVisible();-- // The key should be visible in a code/snippet element- await expect(page.locator('code').first()).toBeVisible();-- // Close the dialog- await page.getByRole('button', { name: 'Done' }).click();-- // The new key should appear in the table- await expect(- page.getByRole('row').filter({ has: page.getByText(apiKeyName, { exact: true }) })- ).toBeVisible();- });-- test('should open edit dialog from row actions', async ({ page }) => {- await navigateToApiKeys(page);-- const firstRow = page- .getByRole('row')- .filter({ has: page.getByRole('button', { name: 'Open menu', exact: true }) })- .first();- await expect(firstRow).toBeVisible();-- const menu = await openRowActionsMenu(page, firstRow);- await menu.getByRole('menuitem', { name: 'Edit' }).click();-- await expect(page.getByRole('dialog')).toBeVisible();- await expect(page.getByText('Edit API Key')).toBeVisible();-- // Close the dialog- await page.keyboard.press('Escape');- });-- test('should open delete confirmation dialog from row actions', async ({ page }) => {- await navigateToApiKeys(page);-- const firstRow = page- .getByRole('row')- .filter({ has: page.getByRole('button', { name: 'Open menu', exact: true }) })- .first();- await expect(firstRow).toBeVisible();-- const menu = await openRowActionsMenu(page, firstRow);- await menu.getByRole('menuitem', { name: 'Delete' }).click();-- // Should show confirmation dialog- const confirmationDialog = page.getByRole('dialog');- await expect(- confirmationDialog.getByRole('heading', { name: 'Delete API Key', exact: false })- ).toBeVisible();- await expect(- confirmationDialog.getByText('Are you sure you want to delete the API key', {- exact: false- })- ).toBeVisible();-- // Cancel the deletion- await page.getByRole('button', { name: 'Cancel' }).click();- });-- test('should delete an API key', async ({ page }) => {- // First create a key to delete- await navigateToApiKeys(page);-- await page.getByRole('button', { name: 'Create API Key' }).click();- const createDialog = page.getByRole('dialog');-- const apiKeyName = `test-api-key-delete-${Date.now()}`;- await createDialog.getByLabel('Name', { exact: true }).fill(apiKeyName);-- // Select at least one permission (form requires min 1)- await createDialog- .getByPlaceholder('Filter permissions…', { exact: true })- .fill('containers:list');- await createDialog.getByRole('checkbox', { name: 'Select all' }).check();-- await createDialog.getByRole('button', { name: 'Create API Key', exact: true }).click();-- // Wait for creation success and close reveal dialog- const createdDialog = page.getByRole('dialog', { name: 'API Key Created' });- await expect(createdDialog).toBeVisible({ timeout: 10000 });- await createdDialog.getByRole('button', { name: 'Done' }).click();-- await expect(createdDialog).toBeHidden();-- // Now delete the key- const keyRow = page- .getByRole('row')- .filter({ has: page.getByText(apiKeyName, { exact: true }) });- await expect(keyRow).toBeVisible();-- const menu = await openRowActionsMenu(page, keyRow);- await menu.getByRole('menuitem', { name: 'Delete' }).click();-- // Confirm deletion- await expect(- page.getByRole('heading', { name: `Delete API Key "${apiKeyName}"?`, exact: true })- ).toBeVisible();- await page.getByRole('button', { name: 'Delete' }).click();-- // Should show success toast for deletion- await expect(- page.getByText(`API key "${apiKeyName}" deleted successfully`, { exact: true })- ).toBeVisible({ timeout: 10000 });-- // Key should no longer be in the table- await expect(keyRow).toBeHidden();- });-- test('should select multiple API keys and show bulk delete option', async ({ page }) => {- await navigateToApiKeys(page);-- // Select first two checkboxes- const checkboxes = page- .getByRole('row')- .filter({ has: page.getByRole('button', { name: 'Open menu', exact: true }) })- .getByRole('checkbox');- await expect(checkboxes.nth(1)).toBeVisible();-- await checkboxes.nth(0).check();- await checkboxes.nth(1).check();-- // Remove Selected button should appear- const removeSelectedBtn = page.getByRole('button', {- name: 'Remove Selected (2)',- exact: true- });- await expect(removeSelectedBtn).toBeVisible();-- // Click it to open confirmation- await removeSelectedBtn.click();-- // Should show bulk delete confirmation- await expect(- page.getByRole('heading', { name: 'Delete 2 API Key(s)?', exact: true })- ).toBeVisible();-- // Cancel- await page.getByRole('button', { name: 'Cancel' }).click();- });-- test('should display correct status badges for active keys', async ({ page }) => {- await navigateToApiKeys(page);-- // Check if Active badge is visible- await expect(page.getByText('Active', { exact: true }).first()).toBeVisible();- });-- test('should display "Never" for keys without expiration', async ({ page }) => {- await navigateToApiKeys(page);-- // Test keys created without expiration should show "Never"- await expect(page.getByText('Never', { exact: true }).first()).toBeVisible();- });-});diff --git a/tests/spec/token-refresh.spec.ts b/tests/spec/auth.spec.tssimilarity index 96%rename from tests/spec/token-refresh.spec.tsrename to tests/spec/auth.spec.tsindex 979ee98cc..1bb8aca52 100644--- a/tests/spec/token-refresh.spec.ts+++ b/tests/spec/auth.spec.ts@@ -105,12 +105,10 @@ test('signed-in OIDC callbacks reach the callback exchange', async ({ page }) =>});test.describe('Token refresh behaviour', () => {- test('@cross-browser shows useful login errors and accepts the configured admin password', async ({- page- }, testInfo) => {- // Keep each browser's login attempts in its own rate-limit bucket.+ test('shows useful login errors and accepts the configured admin password', async ({ page }) => {+ // Keep login error checks in their own rate-limit bucket.await page.setExtraHTTPHeaders({- 'X-Forwarded-For': testInfo.project.name === 'firefox' ? '198.18.0.2' : '198.18.0.3'+ 'X-Forwarded-For': '198.18.0.3'});await page.context().clearCookies();let gatewayFailurePending = true;diff --git a/tests/spec/backup-file-picker.spec.ts b/tests/spec/backup-file-picker.spec.tsdeleted file mode 100644index f715eb885..000000000--- a/tests/spec/backup-file-picker.spec.ts+++ /dev/null@@ -1,875 +0,0 @@-import { expect, test, type Page, type Route } from '../fixtures/test.fixture';-import { setCodeMirrorValue } from '../utils/playwright.util';--const VOLUME_NAME = 'backup-picker-e2e';-const BACKUP_ID = 'backup-picker-snapshot';-const SYSTEM_BACKUP_ID = 'system-picker-id';-const PROJECT_ID = 'backup-picker-project';--type BrowseRequest = {- path: string;- search: string;- start: number;- limit: string | null;-};--type BrowseHandler = (request: BrowseRequest, route: Route) => Promise<void>;--type BackupFileEntry = {- path: string;- name: string;- isDirectory: boolean;-};--function response(data: unknown) {- return { success: true, data };-}--function browseResponse(data: BackupFileEntry[], totalItems = data.length, start = 0, limit = 20) {- return {- success: true,- data,- pagination: {- totalPages: Math.max(1, Math.ceil(totalItems / limit)),- totalItems,- currentPage: Math.floor(start / limit) + 1,- itemsPerPage: limit,- grandTotalItems: totalItems- }- };-}--async function mockAppShell(page: Page) {- await page.addInitScript(() => localStorage.removeItem('selectedEnvironmentId'));- await page.route(/\/api\/auth\/me$/, async (route) => {- await route.fulfill({- json: response({- id: 'backup-picker-admin',- username: 'arcane',- roleAssignments: [],- permissionsByEnv: { global: ['*'] },- isGlobalAdmin: true,- createdAt: new Date().toISOString()- })- });- });- await page.route(/\/api\/auth\/auto-login-config$/, async (route) => {- await route.fulfill({ json: response({ enabled: false }) });- });- await page.route(/\/api\/environments(?:\?.*)?$/, async (route) => {- await route.fulfill({- json: {- success: true,- data: [- { id: '0', name: 'Local', apiUrl: '', status: 'online', enabled: true, isEdge: false }- ],- pagination: { currentPage: 1, totalPages: 1, totalItems: 1, itemsPerPage: 1000 }- }- });- });- await page.route(/\/api\/environments\/0\/settings$/, async (route) => {- await route.fulfill({ json: {} });- });- await page.route(/\/api\/environments\/0\/swarm\/status$/, async (route) => {- await route.fulfill({ json: response({ enabled: false }) });- });- await page.route(/\/api\/oidc\/status$/, async (route) => {- await route.fulfill({- json: response({- envForced: false,- envConfigured: false,- mergeAccounts: false,- providerName: '',- providerLogoUrl: ''- })- });- });- await page.route(/\/api\/roles\/available-permissions$/, async (route) => {- await route.fulfill({ status: 503, json: { message: 'not needed for global admin' } });- });- await page.route(/\/api\/app-version$/, async (route) => {- await route.fulfill({- json: { currentVersion: 'e2e', displayVersion: 'e2e', enabledFeatures: [] }- });- });- await page.route(/\/api\/stream(?:\?.*)?$/, async (route) => {- await route.fulfill({ contentType: 'application/x-json-stream', body: '' });- });- await page.route(/\/api\/backups\/s3(?:\?.*)?$/, async (route) => {- await route.fulfill({ json: response([]) });- });- await page.route(/\/api\/backups\/s3\/options$/, async (route) => {- await route.fulfill({ json: response([]) });- });-}--async function mockVolumeBackupPage(page: Page, browse: BrowseHandler) {- const encodedVolume = encodeURIComponent(VOLUME_NAME);- await mockAppShell(page);- await page.route(new RegExp(`/api/environments/0/volumes/${encodedVolume}$`), async (route) => {- await route.fulfill({- json: response({- id: VOLUME_NAME,- name: VOLUME_NAME,- driver: 'local',- mountpoint: `/var/lib/docker/volumes/${VOLUME_NAME}/_data`,- scope: 'local',- options: null,- labels: {},- createdAt: new Date().toISOString(),- inUse: false,- containers: [],- size: 0- })- });- });- await page.route(- new RegExp(`/api/environments/0/volumes/${encodedVolume}/backup-policy$`),- async (route) => {- await route.fulfill({ json: response({ policies: [], s3Available: false }) });- }- );- await page.route(- new RegExp(`/api/environments/0/volumes/${encodedVolume}/backups(?:\\?.*)?$`),- async (route) => {- await route.fulfill({- json: {- success: true,- data: [- {- id: BACKUP_ID,- volumeName: VOLUME_NAME,- size: 1024,- createdAt: new Date().toISOString(),- status: 'succeeded',- trigger: 'manual',- destination: 'local',- format: 'rustic',- localSnapshotId: 'snapshot'- }- ],- pagination: { currentPage: 1, totalPages: 1, totalItems: 1, itemsPerPage: 10 }- }- });- }- );- await page.route(- new RegExp(`/api/environments/0/volumes/backups/${BACKUP_ID}/files/browse(?:\\?.*)?$`),- async (route) => {- const url = new URL(route.request().url());- await browse(- {- path: url.searchParams.get('path') ?? '',- search: url.searchParams.get('search') ?? '',- start: Number(url.searchParams.get('start') ?? 0),- limit: url.searchParams.get('limit')- },- route- );- }- );-- await page.goto(`/volumes/${encodedVolume}?tab=backups`);- await openVolumeRestoreFilesDialog(page);-}--type VolumeWorkspaceRestoreState = {- content: string;- restoredContent: string;- revision: number;- failRestore: boolean;- workspaceRequests: number;- fileRequests: number;- restoreBodies: Array<Record<string, unknown>>;- fullRestoreRequests: number;-};--async function mockVolumeWorkspaceRestore(page: Page, state: VolumeWorkspaceRestoreState) {- const encodedVolume = encodeURIComponent(VOLUME_NAME);- await page.route(- new RegExp(`/api/environments/0/volumes/${encodedVolume}/workspace$`),- async (route) => {- state.workspaceRequests += 1;- await route.fulfill({- json: response({- files: [- {- path: '/workspace.txt',- relativePath: 'workspace.txt',- name: 'workspace.txt',- isDirectory: false,- size: state.content.length,- mode: '-rw-r--r--',- isSymlink: false,- editable: true- }- ],- fileTreeRevision: `revision-${state.revision}`,- fileTreeTruncated: false- })- });- }- );- await page.route(- new RegExp(`/api/environments/0/volumes/${encodedVolume}/workspace/file(?:\\?.*)?$`),- async (route) => {- state.fileRequests += 1;- await route.fulfill({- json: response({- path: '/workspace.txt',- relativePath: 'workspace.txt',- name: 'workspace.txt',- size: state.content.length,- mimeType: 'text/plain',- content: state.content,- editable: true- })- });- }- );- await page.route(- new RegExp(`/api/environments/0/volumes/${encodedVolume}/backups/${BACKUP_ID}/restore-files$`),- async (route) => {- state.restoreBodies.push(route.request().postDataJSON() as Record<string, unknown>);- if (state.failRestore) {- await route.fulfill({ status: 500, json: { success: false, message: 'restore failed' } });- return;- }- state.content = state.restoredContent;- state.revision += 1;- await route.fulfill({ json: response({ message: 'restored' }) });- }- );- await page.route(- new RegExp(`/api/environments/0/volumes/${encodedVolume}/backups/${BACKUP_ID}/restore$`),- async (route) => {- state.fullRestoreRequests += 1;- state.content = state.restoredContent;- state.revision += 1;- await route.fulfill({ json: response({ message: 'restored' }) });- }- );- await page.route(- new RegExp(`/api/environments/0/volumes/${encodedVolume}/usage$`),- async (route) => {- await route.fulfill({ json: response({ inUse: false, containers: [] }) });- }- );-}--async function openVolumeRestoreFilesDialog(page: Page) {- await page.getByRole('tab', { name: 'Backups', exact: true }).click();- await expect(page.getByText(BACKUP_ID, { exact: true }).first()).toBeVisible();- const backupRow = page.getByRole('row').filter({ hasText: BACKUP_ID }).first();- await backupRow.getByRole('button', { name: 'Open menu' }).click();- await page.getByRole('menuitem', { name: 'Restore files' }).click();- await expect(page.getByRole('dialog', { name: 'Restore files' })).toBeVisible();-}--async function selectVolumeRestoreFile(page: Page) {- const dialog = page.getByRole('dialog', { name: 'Restore files' });- await dialog.locator('[data-path="workspace.txt"]').getByRole('checkbox').click();- return dialog;-}--async function openVolumeWorkspaceEditor(page: Page) {- await page.getByRole('tab', { name: 'Workspace', exact: true }).click();- await page- .locator('[data-path="workspace.txt"]')- .getByRole('button', { name: 'workspace.txt', exact: true })- .first()- .click();- const editor = page.locator('.arcane-code-editor .cm-content').first();- await expect(editor).toBeVisible();- return editor;-}--async function mockProjectWorkspacePage(- page: Page,- workspaceState: () => { content: string; revision: number }-) {- const encodedProject = encodeURIComponent(PROJECT_ID);- await mockAppShell(page);- await page.route(/\/api\/variables(?:\?.*)?$/, async (route) => {- await route.fulfill({ json: response([]) });- });- await page.route(/\/api\/environments\/0\/projects\/tags$/, async (route) => {- await route.fulfill({ json: response([]) });- });- await page.route(- new RegExp(`/api/environments/0/projects/${encodedProject}/workspace$`),- async (route) => {- const state = workspaceState();- await route.fulfill({- json: response({- files: [- {- path: `/projects/${PROJECT_ID}/workspace.txt`,- relativePath: 'workspace.txt',- name: 'workspace.txt',- isDirectory: false,- size: state.content.length,- mode: '-rw-r--r--',- isSymlink: false,- editable: true- }- ],- fileTreeRevision: `revision-${state.revision}`,- fileTreeTruncated: false- })- });- }- );- await page.route(- new RegExp(`/api/environments/0/projects/${encodedProject}/workspace/file(?:\\?.*)?$`),- async (route) => {- const state = workspaceState();- await route.fulfill({- json: response({- path: `/projects/${PROJECT_ID}/workspace.txt`,- relativePath: 'workspace.txt',- name: 'workspace.txt',- size: state.content.length,- mimeType: 'text/plain',- content: state.content,- editable: true- })- });- }- );- await page.route(- new RegExp(`/api/environments/0/projects/${encodedProject}(?:/(compose|runtime|updates))?$`),- async (route) => {- const section = new URL(route.request().url()).pathname.split('/').at(-1);- const project = {- id: PROJECT_ID,- name: PROJECT_ID,- path: `/projects/${PROJECT_ID}`,- dirName: PROJECT_ID,- status: 'stopped',- serviceCount: 0,- runningCount: 0,- isArchived: false,- hasBuildDirective: false,- createdAt: new Date().toISOString(),- updatedAt: new Date().toISOString(),- tags: [],- services: [],- runtimeServices: [],- includeFiles: []- };-- if (section === 'compose') {- await route.fulfill({- json: response({- ...project,- composeContent: 'services: {}\n',- envContent: '',- overrideContent: '',- composeFileName: 'compose.yaml'- })- });- return;- }-- await route.fulfill({ json: response(project) });- }- );-}--async function mockSystemBackupPage(- page: Page,- browse: (request: BrowseRequest, body: Record<string, unknown>, route: Route) => Promise<void>,- restore: (body: Record<string, unknown>, route: Route) => Promise<void>,- openPage = true-) {- await mockAppShell(page);- await page.route(/\/api\/backups\/history(?:\?.*)?$/, async (route) => {- await route.fulfill({- json: {- success: true,- data: [- {- id: SYSTEM_BACKUP_ID,- size: 2048,- createdAt: new Date().toISOString(),- status: 'succeeded',- trigger: 'manual',- destination: 'local',- localSnapshotId: 'system-snapshot',- type: 'system',- resourceType: 'system',- resourceName: 'Arcane system'- }- ],- pagination: { currentPage: 1, totalPages: 1, totalItems: 1, itemsPerPage: 20 }- }- });- });- await page.route(/\/api\/backups\/policies$/, async (route) => {- await route.fulfill({ json: response({ policies: [], recoveryKeyStored: true }) });- });- await page.route(- new RegExp(`/api/backups/${SYSTEM_BACKUP_ID}/files/browse(?:\\?.*)?$`),- async (route) => {- const url = new URL(route.request().url());- await browse(- {- path: url.searchParams.get('path') ?? '',- search: url.searchParams.get('search') ?? '',- start: Number(url.searchParams.get('start') ?? 0),- limit: url.searchParams.get('limit')- },- route.request().postDataJSON() as Record<string, unknown>,- route- );- }- );- await page.route(new RegExp(`/api/backups/${SYSTEM_BACKUP_ID}/restore-files$`), async (route) => {- await restore(route.request().postDataJSON() as Record<string, unknown>, route);- });- if (!openPage) return;-- await page.goto('/settings/backups');- await openSystemRestoreDialog(page);-}--async function openSystemRestoreDialog(page: Page) {- await expect(page.getByText(SYSTEM_BACKUP_ID, { exact: false }).first()).toBeVisible();- const backupRow = page.getByRole('row').filter({ hasText: SYSTEM_BACKUP_ID }).first();- await backupRow.getByRole('button', { name: 'Open menu' }).click();- await page.getByRole('menuitem', { name: 'Restore files' }).click();- await expect(page.getByRole('dialog', { name: 'Restore files' })).toBeVisible();-}--async function navigateInApp(page: Page, path: string) {- await page.evaluate((targetPath) => {- const link = document.createElement('a');- link.href = targetPath;- document.body.append(link);- link.click();- link.remove();- }, path);- await page.waitForURL((url) => url.pathname === path.split('?')[0]);-}--function rootEntries(count: number) {- return Array.from({ length: count }, (_, index) =>- index === 0- ? { path: 'folder', name: 'folder', isDirectory: true }- : {- path: `file-${index.toString().padStart(5, '0')}.txt`,- name: `file-${index.toString().padStart(5, '0')}.txt`,- isDirectory: false- }- );-}--test.describe('Backup file picker', () => {- test('refreshes clean volume workspace files after restore', async ({ page }) => {- const state: VolumeWorkspaceRestoreState = {- content: 'before restore',- restoredContent: 'after restore',- revision: 1,- failRestore: false,- workspaceRequests: 0,- fileRequests: 0,- restoreBodies: [],- fullRestoreRequests: 0- };- await mockVolumeWorkspaceRestore(page, state);-- await mockVolumeBackupPage(page, async (_request, route) => {- await route.fulfill({- json: browseResponse([{ path: 'workspace.txt', name: 'workspace.txt', isDirectory: false }])- });- });-- await page.keyboard.press('Escape');- const editor = await openVolumeWorkspaceEditor(page);- await expect(editor).toContainText('before restore');-- await openVolumeRestoreFilesDialog(page);- const dialog = await selectVolumeRestoreFile(page);- await expect(dialog).not.toContainText('discard all unsaved text and staged file operations');- await dialog.getByRole('button', { name: 'Restore files' }).click();- await expect.poll(() => state.restoreBodies.length).toBe(1);- expect(state.restoreBodies[0]).toEqual({- paths: ['workspace.txt'],- selectAll: false- });- await expect(dialog).not.toBeVisible();- const workspaceRequestsAfterRestore = state.workspaceRequests;- await page.getByRole('tab', { name: 'Workspace', exact: true }).click();-- await expect(editor).toContainText('after restore');- await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(0);- expect(workspaceRequestsAfterRestore).toBeGreaterThanOrEqual(2);- expect(state.workspaceRequests).toBe(workspaceRequestsAfterRestore);- expect(state.fileRequests).toBeGreaterThanOrEqual(2);- });-- test('warns before discarding volume workspace changes', async ({ page }) => {- const state: VolumeWorkspaceRestoreState = {- content: 'before restore',- restoredContent: 'after restore',- revision: 1,- failRestore: false,- workspaceRequests: 0,- fileRequests: 0,- restoreBodies: [],- fullRestoreRequests: 0- };- await mockVolumeWorkspaceRestore(page, state);- await mockVolumeBackupPage(page, async (_request, route) => {- await route.fulfill({- json: browseResponse([{ path: 'workspace.txt', name: 'workspace.txt', isDirectory: false }])- });- });-- await page.keyboard.press('Escape');- const editor = await openVolumeWorkspaceEditor(page);- await setCodeMirrorValue(editor, 'local draft');- await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(1);-- await openVolumeRestoreFilesDialog(page);- let restoreDialog = await selectVolumeRestoreFile(page);- await expect(restoreDialog).toContainText(- 'discard all unsaved text and staged file operations'- );- await restoreDialog.getByRole('button', { name: 'Cancel', exact: true }).click();- await expect(restoreDialog).not.toBeVisible();- expect(state.restoreBodies).toHaveLength(0);-- await page.getByRole('tab', { name: 'Workspace', exact: true }).click();- await expect(editor).toContainText('local draft');- await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(1);-- state.failRestore = true;- await openVolumeRestoreFilesDialog(page);- restoreDialog = await selectVolumeRestoreFile(page);- await expect(restoreDialog).toContainText(- 'discard all unsaved text and staged file operations'- );- await restoreDialog.getByRole('button', { name: 'Restore files' }).click();- await expect.poll(() => state.restoreBodies.length).toBe(1);- await restoreDialog.getByRole('button', { name: 'Cancel', exact: true }).click();- await expect(restoreDialog).not.toBeVisible();-- await page.getByRole('tab', { name: 'Workspace', exact: true }).click();- await expect(editor).toContainText('local draft');- await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(1);-- state.failRestore = false;- await openVolumeRestoreFilesDialog(page);- restoreDialog = await selectVolumeRestoreFile(page);- await expect(restoreDialog).toContainText(- 'discard all unsaved text and staged file operations'- );- await restoreDialog.getByRole('button', { name: 'Restore files' }).click();- await expect.poll(() => state.restoreBodies.length).toBe(2);- await expect(restoreDialog).not.toBeVisible();-- await page.getByRole('tab', { name: 'Workspace', exact: true }).click();- await expect(editor).toContainText('after restore');- await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(0);- });-- test('warns before a full volume restore discards workspace changes', async ({ page }) => {- const state: VolumeWorkspaceRestoreState = {- content: 'before restore',- restoredContent: 'after restore',- revision: 1,- failRestore: false,- workspaceRequests: 0,- fileRequests: 0,- restoreBodies: [],- fullRestoreRequests: 0- };- await mockVolumeWorkspaceRestore(page, state);- await mockVolumeBackupPage(page, async (_request, route) => {- await route.fulfill({- json: browseResponse([{ path: 'workspace.txt', name: 'workspace.txt', isDirectory: false }])- });- });-- await page.keyboard.press('Escape');- const editor = await openVolumeWorkspaceEditor(page);- await setCodeMirrorValue(editor, 'local draft');- await page.getByRole('tab', { name: 'Backups', exact: true }).click();- const backupRow = page.getByRole('row').filter({ hasText: BACKUP_ID }).first();- await backupRow.getByRole('button', { name: 'Open menu' }).click();- await page.getByRole('menuitem', { name: 'Restore', exact: true }).click();-- const confirmDialog = page.getByRole('dialog', { name: 'Restore Volume' });- await expect(confirmDialog).toContainText(- 'discard all unsaved text and staged file operations'- );- await confirmDialog.getByRole('button', { name: 'Cancel', exact: true }).click();- await expect(confirmDialog).not.toBeVisible();- expect(state.fullRestoreRequests).toBe(0);-- await page.getByRole('tab', { name: 'Workspace', exact: true }).click();- await expect(editor).toContainText('local draft');- await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(1);- });-- test('refreshes clean project workspace files after a system restore', async ({ page }) => {- const workspaceState = { content: 'before restore', revision: 1 };- const restoreBodies: Array<Record<string, unknown>> = [];- await mockProjectWorkspacePage(page, () => workspaceState);-- await page.goto(`/projects/${PROJECT_ID}?tab=compose`);- await page- .locator('[data-path="workspace.txt"]')- .getByRole('button', { name: 'workspace.txt', exact: true })- .first()- .click();- const editor = page.locator('.arcane-code-editor .cm-content').first();- await expect(editor).toContainText('before restore');-- await mockSystemBackupPage(- page,- async (_request, _body, route) => {- await route.fulfill({- json: browseResponse([- {- path: `${PROJECT_ID}/workspace.txt`,- name: 'workspace.txt',- isDirectory: false- }- ])- });- },- async (body, route) => {- restoreBodies.push(body);- workspaceState.content = 'after restore';- workspaceState.revision += 1;- await route.fulfill({ json: response({ message: 'restored' }) });- },- false- );- await navigateInApp(page, '/settings/backups');- await openSystemRestoreDialog(page);-- const dialog = page.getByRole('dialog', { name: 'Restore files' });- await dialog.locator(`[data-path="${PROJECT_ID}/workspace.txt"]`).getByRole('checkbox').click();- await dialog.getByRole('button', { name: 'Restore files' }).click();- await expect.poll(() => restoreBodies.length).toBe(1);-- await navigateInApp(page, `/projects/${PROJECT_ID}?tab=compose`);- await page- .locator('[data-path="workspace.txt"]')- .getByRole('button', { name: 'workspace.txt', exact: true })- .first()- .click();- await expect(editor).toContainText('after restore');- await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(0);- });-- test('loads folders lazily, walks continuation pages, retains rows on retry, and bounds mounted rows', async ({- page- }) => {- const requests: BrowseRequest[] = [];- let continuationAttempts = 0;- await mockVolumeBackupPage(page, async (request, route) => {- requests.push(request);- if (request.path === 'folder/nested') {- await route.fulfill({- json: browseResponse([- { path: 'folder/nested/grandchild.txt', name: 'grandchild.txt', isDirectory: false }- ])- });- return;- }- if (request.path === 'folder') {- await route.fulfill({- json: browseResponse([- { path: 'folder/nested', name: 'nested', isDirectory: true },- { path: 'folder/child.txt', name: 'child.txt', isDirectory: false }- ])- });- return;- }- if (request.start === 20) {- continuationAttempts += 1;- if (continuationAttempts === 1) {- await route.fulfill({ status: 500, json: { message: 'interrupted' } });- return;- }- await route.fulfill({- json: browseResponse([{ path: 'last.txt', name: 'last.txt', isDirectory: false }], 21, 20)- });- return;- }- await route.fulfill({ json: browseResponse(rootEntries(20), 21) });- });-- await expect.poll(() => requests.length).toBe(1);- expect(requests[0]).toMatchObject({ path: '', search: '', start: 0, limit: null });- const tree = page.locator('[data-backup-file-tree]');- await expect(tree.locator('[data-path="folder"]')).toBeVisible();- expect(await tree.locator('[data-path]').count()).toBeLessThan(40);-- await tree- .locator('[data-path="folder"]')- .getByRole('button', { name: 'Expand folder' })- .click();- await expect.poll(() => requests.filter((request) => request.path === 'folder').length).toBe(1);- await expect(tree.locator('[data-path="folder/child.txt"]')).toBeVisible();- await tree- .locator('[data-path="folder/nested"]')- .getByRole('button', { name: 'Expand nested' })- .click();- await expect- .poll(() => requests.filter((request) => request.path === 'folder/nested').length)- .toBe(1);- await expect(tree.locator('[data-path="folder/nested/grandchild.txt"]')).toBeVisible();-- await tree.evaluate((element) => {- element.scrollTop = element.scrollHeight;- element.dispatchEvent(new Event('scroll'));- });- await expect(page.getByText('The remaining backup files could not be loaded.')).toBeVisible();- expect(await tree.locator('[data-path]').count()).toBeLessThan(40);- await tree.evaluate((element) => {- element.scrollTop = 0;- element.dispatchEvent(new Event('scroll'));- });- await expect(tree.locator('[data-path="folder"]')).toBeVisible();- await tree.evaluate((element) => {- element.scrollTop = element.scrollHeight;- element.dispatchEvent(new Event('scroll'));- });- await expect(page.getByText('The remaining backup files could not be loaded.')).toBeVisible();- await page.getByRole('button', { name: 'Retry' }).click();- await expect.poll(() => continuationAttempts).toBe(2);- await expect(tree.locator('[data-path="last.txt"]')).toBeVisible();- });-- test('supports folder coverage, indeterminate state, global selection, and search-scoped selection', async ({- page- }) => {- const restoreBodies: Array<Record<string, unknown>> = [];- await page.route(- new RegExp(`/api/environments/0/volumes/${VOLUME_NAME}/backups/${BACKUP_ID}/restore-files$`),- async (route) => {- restoreBodies.push(route.request().postDataJSON() as Record<string, unknown>);- await route.fulfill({ json: response({ message: 'restored' }) });- }- );- await mockVolumeBackupPage(page, async (request, route) => {- if (request.search) {- await route.fulfill({- json: browseResponse([- {- path: `folder/${request.search}.txt`,- name: `${request.search}.txt`,- isDirectory: false- }- ])- });- return;- }- if (request.path === 'folder') {- await route.fulfill({- json: browseResponse([- { path: 'folder/a.txt', name: 'a.txt', isDirectory: false },- { path: 'folder/b.txt', name: 'b.txt', isDirectory: false }- ])- });- return;- }- await route.fulfill({- json: browseResponse([- { path: 'folder', name: 'folder', isDirectory: true },- { path: 'root.txt', name: 'root.txt', isDirectory: false }- ])- });- });-- const dialog = page.getByRole('dialog', { name: 'Restore files' });- const folder = dialog.locator('[data-path="folder"]');- await folder.getByRole('button', { name: 'Expand folder' }).click();- const child = dialog.locator('[data-path="folder/a.txt"]');- await child.getByRole('checkbox').click();- await expect(folder.getByRole('checkbox')).toHaveAttribute('data-state', 'indeterminate');- await folder.getByRole('checkbox').click();- await expect(child.getByRole('checkbox')).toBeDisabled();- await expect(child.getByRole('checkbox')).toBeChecked();-- await dialog.getByRole('button', { name: 'Clear' }).click();- await dialog.getByRole('button', { name: 'Select all' }).click();- await expect(dialog.locator('[data-path="root.txt"]').getByRole('checkbox')).toBeDisabled();- await dialog.getByRole('button', { name: 'Restore files' }).click();- await expect.poll(() => restoreBodies.length).toBe(1);- expect(restoreBodies[0]).toEqual({ paths: [], selectAll: true, search: '' });-- await mockVolumeBackupPage(page, async (request, route) => {- if (request.search) {- await route.fulfill({- json: browseResponse([- {- path: `folder/${request.search}.txt`,- name: `${request.search}.txt`,- isDirectory: false- }- ])- });- return;- }- await route.fulfill({ json: browseResponse(rootEntries(2)) });- });- const reopened = page.getByRole('dialog', { name: 'Restore files' });- await reopened.getByPlaceholder('Search files').fill('match');- await expect(reopened.locator('[data-path="folder/match.txt"]')).toBeVisible();- await reopened.getByRole('button', { name: 'Select all search matches' }).click();- await reopened.getByPlaceholder('Search files').fill('changed');- await expect(reopened.getByRole('button', { name: 'Restore files' })).toBeDisabled();- });-- test('keeps a synthetic 100,000-entry result bounded to the viewport', async ({ page }) => {- await mockVolumeBackupPage(page, async (_request, route) => {- await route.fulfill({ json: browseResponse(rootEntries(100_000), 100_000, 0, 100_000) });- });- const tree = page.locator('[data-backup-file-tree]');- await expect(tree.locator('[data-path="folder"]')).toBeVisible();- expect(await tree.locator('[data-path]').count()).toBeLessThan(40);- await tree.evaluate((element) => {- element.scrollTop = element.scrollHeight / 2;- element.dispatchEvent(new Event('scroll'));- });- await expect.poll(() => tree.locator('[data-path]').count()).toBeLessThan(40);- });-- test('uses the same provider selection contract in the system backup dialog', async ({- page- }) => {- const browseRequests: BrowseRequest[] = [];- const browseBodies: Array<Record<string, unknown>> = [];- const restoreBodies: Array<Record<string, unknown>> = [];- await mockSystemBackupPage(- page,- async (request, body, route) => {- browseRequests.push(request);- browseBodies.push(body);- await route.fulfill({- json: browseResponse([{ path: 'project', name: 'project', isDirectory: true }])- });- },- async (body, route) => {- restoreBodies.push(body);- await route.fulfill({ json: response({ message: 'restored' }) });- }- );-- await expect.poll(() => browseBodies.length).toBe(1);- expect(browseBodies[0]).toEqual({ recoveryKey: '' });- expect(browseRequests[0]).toMatchObject({ path: '', search: '', start: 0, limit: null });- const dialog = page.getByRole('dialog', { name: 'Restore files' });- await dialog.getByRole('button', { name: 'Select all' }).click();- await dialog.getByRole('button', { name: 'Restore files' }).click();- await expect.poll(() => restoreBodies.length).toBe(1);- expect(restoreBodies[0]).toEqual({ recoveryKey: '', paths: [], selectAll: true, search: '' });- });-});diff --git a/tests/spec/backups.spec.ts b/tests/spec/backups.spec.tsnew file mode 100644index 000000000..e4ee7e41b--- /dev/null+++ b/tests/spec/backups.spec.ts@@ -0,0 +1,1641 @@+import { expect, test, type Page, type Route } from '../fixtures/test.fixture';+import { setCodeMirrorValue } from '../utils/playwright.util';+import { removeApiResource, readApiData } from '../utils/fetch.util';+import { openRowActionsMenu } from '../utils/table-actions.util';+import { type Activity } from '../../frontend/src/lib/types/activity.type';++test.describe('Workspace restore', () => {+ const VOLUME_NAME = 'backup-picker-e2e';+ const BACKUP_ID = 'backup-picker-snapshot';+ const SYSTEM_BACKUP_ID = 'system-picker-id';+ const PROJECT_ID = 'backup-picker-project';++ type BrowseRequest = {+ path: string;+ search: string;+ start: number;+ limit: string | null;+ };++ type BrowseHandler = (request: BrowseRequest, route: Route) => Promise<void>;++ type BackupFileEntry = {+ path: string;+ name: string;+ isDirectory: boolean;+ };++ function response(data: unknown) {+ return { success: true, data };+ }++ function browseResponse(+ data: BackupFileEntry[],+ totalItems = data.length,+ start = 0,+ limit = 20+ ) {+ return {+ success: true,+ data,+ pagination: {+ totalPages: Math.max(1, Math.ceil(totalItems / limit)),+ totalItems,+ currentPage: Math.floor(start / limit) + 1,+ itemsPerPage: limit,+ grandTotalItems: totalItems+ }+ };+ }++ async function mockAppShell(page: Page) {+ await page.addInitScript(() => localStorage.removeItem('selectedEnvironmentId'));+ await page.route(/\/api\/auth\/me$/, async (route) => {+ await route.fulfill({+ json: response({+ id: 'backup-picker-admin',+ username: 'arcane',+ roleAssignments: [],+ permissionsByEnv: { global: ['*'] },+ isGlobalAdmin: true,+ createdAt: new Date().toISOString()+ })+ });+ });+ await page.route(/\/api\/auth\/auto-login-config$/, async (route) => {+ await route.fulfill({ json: response({ enabled: false }) });+ });+ await page.route(/\/api\/environments(?:\?.*)?$/, async (route) => {+ await route.fulfill({+ json: {+ success: true,+ data: [+ { id: '0', name: 'Local', apiUrl: '', status: 'online', enabled: true, isEdge: false }+ ],+ pagination: { currentPage: 1, totalPages: 1, totalItems: 1, itemsPerPage: 1000 }+ }+ });+ });+ await page.route(/\/api\/environments\/0\/settings$/, async (route) => {+ await route.fulfill({ json: {} });+ });+ await page.route(/\/api\/environments\/0\/swarm\/status$/, async (route) => {+ await route.fulfill({ json: response({ enabled: false }) });+ });+ await page.route(/\/api\/oidc\/status$/, async (route) => {+ await route.fulfill({+ json: response({+ envForced: false,+ envConfigured: false,+ mergeAccounts: false,+ providerName: '',+ providerLogoUrl: ''+ })+ });+ });+ await page.route(/\/api\/roles\/available-permissions$/, async (route) => {+ await route.fulfill({ status: 503, json: { message: 'not needed for global admin' } });+ });+ await page.route(/\/api\/app-version$/, async (route) => {+ await route.fulfill({+ json: { currentVersion: 'e2e', displayVersion: 'e2e', enabledFeatures: [] }+ });+ });+ await page.route(/\/api\/stream(?:\?.*)?$/, async (route) => {+ await route.fulfill({ contentType: 'application/x-json-stream', body: '' });+ });+ await page.route(/\/api\/backups\/s3(?:\?.*)?$/, async (route) => {+ await route.fulfill({ json: response([]) });+ });+ await page.route(/\/api\/backups\/s3\/options$/, async (route) => {+ await route.fulfill({ json: response([]) });+ });+ }++ async function mockVolumeBackupPage(page: Page, browse: BrowseHandler) {+ const encodedVolume = encodeURIComponent(VOLUME_NAME);+ await mockAppShell(page);+ await page.route(new RegExp(`/api/environments/0/volumes/${encodedVolume}$`), async (route) => {+ await route.fulfill({+ json: response({+ id: VOLUME_NAME,+ name: VOLUME_NAME,+ driver: 'local',+ mountpoint: `/var/lib/docker/volumes/${VOLUME_NAME}/_data`,+ scope: 'local',+ options: null,+ labels: {},+ createdAt: new Date().toISOString(),+ inUse: false,+ containers: [],+ size: 0+ })+ });+ });+ await page.route(+ new RegExp(`/api/environments/0/volumes/${encodedVolume}/backup-policy$`),+ async (route) => {+ await route.fulfill({ json: response({ policies: [], s3Available: false }) });+ }+ );+ await page.route(+ new RegExp(`/api/environments/0/volumes/${encodedVolume}/backups(?:\\?.*)?$`),+ async (route) => {+ await route.fulfill({+ json: {+ success: true,+ data: [+ {+ id: BACKUP_ID,+ volumeName: VOLUME_NAME,+ size: 1024,+ createdAt: new Date().toISOString(),+ status: 'succeeded',+ trigger: 'manual',+ destination: 'local',+ format: 'rustic',+ localSnapshotId: 'snapshot'+ }+ ],+ pagination: { currentPage: 1, totalPages: 1, totalItems: 1, itemsPerPage: 10 }+ }+ });+ }+ );+ await page.route(+ new RegExp(`/api/environments/0/volumes/backups/${BACKUP_ID}/files/browse(?:\\?.*)?$`),+ async (route) => {+ const url = new URL(route.request().url());+ await browse(+ {+ path: url.searchParams.get('path') ?? '',+ search: url.searchParams.get('search') ?? '',+ start: Number(url.searchParams.get('start') ?? 0),+ limit: url.searchParams.get('limit')+ },+ route+ );+ }+ );++ await page.goto(`/volumes/${encodedVolume}?tab=backups`);+ await openVolumeRestoreFilesDialog(page);+ }++ type VolumeWorkspaceRestoreState = {+ content: string;+ restoredContent: string;+ revision: number;+ failRestore: boolean;+ workspaceRequests: number;+ fileRequests: number;+ restoreBodies: Array<Record<string, unknown>>;+ fullRestoreRequests: number;+ };++ async function mockVolumeWorkspaceRestore(page: Page, state: VolumeWorkspaceRestoreState) {+ const encodedVolume = encodeURIComponent(VOLUME_NAME);+ await page.route(+ new RegExp(`/api/environments/0/volumes/${encodedVolume}/workspace$`),+ async (route) => {+ state.workspaceRequests += 1;+ await route.fulfill({+ json: response({+ files: [+ {+ path: '/workspace.txt',+ relativePath: 'workspace.txt',+ name: 'workspace.txt',+ isDirectory: false,+ size: state.content.length,+ mode: '-rw-r--r--',+ isSymlink: false,+ editable: true+ }+ ],+ fileTreeRevision: `revision-${state.revision}`,+ fileTreeTruncated: false+ })+ });+ }+ );+ await page.route(+ new RegExp(`/api/environments/0/volumes/${encodedVolume}/workspace/file(?:\\?.*)?$`),+ async (route) => {+ state.fileRequests += 1;+ await route.fulfill({+ json: response({+ path: '/workspace.txt',+ relativePath: 'workspace.txt',+ name: 'workspace.txt',+ size: state.content.length,+ mimeType: 'text/plain',+ content: state.content,+ editable: true+ })+ });+ }+ );+ await page.route(+ new RegExp(+ `/api/environments/0/volumes/${encodedVolume}/backups/${BACKUP_ID}/restore-files$`+ ),+ async (route) => {+ state.restoreBodies.push(route.request().postDataJSON() as Record<string, unknown>);+ if (state.failRestore) {+ await route.fulfill({ status: 500, json: { success: false, message: 'restore failed' } });+ return;+ }+ state.content = state.restoredContent;+ state.revision += 1;+ await route.fulfill({ json: response({ message: 'restored' }) });+ }+ );+ await page.route(+ new RegExp(`/api/environments/0/volumes/${encodedVolume}/backups/${BACKUP_ID}/restore$`),+ async (route) => {+ state.fullRestoreRequests += 1;+ state.content = state.restoredContent;+ state.revision += 1;+ await route.fulfill({ json: response({ message: 'restored' }) });+ }+ );+ await page.route(+ new RegExp(`/api/environments/0/volumes/${encodedVolume}/usage$`),+ async (route) => {+ await route.fulfill({ json: response({ inUse: false, containers: [] }) });+ }+ );+ }++ async function openVolumeRestoreFilesDialog(page: Page) {+ await page.getByRole('tab', { name: 'Backups', exact: true }).click();+ await expect(page.getByText(BACKUP_ID, { exact: true }).first()).toBeVisible();+ const backupRow = page.getByRole('row').filter({ hasText: BACKUP_ID }).first();+ await backupRow.getByRole('button', { name: 'Open menu' }).click();+ await page.getByRole('menuitem', { name: 'Restore files' }).click();+ await expect(page.getByRole('dialog', { name: 'Restore files' })).toBeVisible();+ }++ async function selectVolumeRestoreFile(page: Page) {+ const dialog = page.getByRole('dialog', { name: 'Restore files' });+ await dialog.locator('[data-path="workspace.txt"]').getByRole('checkbox').click();+ return dialog;+ }++ async function openVolumeWorkspaceEditor(page: Page) {+ await page.getByRole('tab', { name: 'Workspace', exact: true }).click();+ await page+ .locator('[data-path="workspace.txt"]')+ .getByRole('button', { name: 'workspace.txt', exact: true })+ .first()+ .click();+ const editor = page.locator('.arcane-code-editor .cm-content').first();+ await expect(editor).toBeVisible();+ return editor;+ }++ async function mockProjectWorkspacePage(+ page: Page,+ workspaceState: () => { content: string; revision: number }+ ) {+ const encodedProject = encodeURIComponent(PROJECT_ID);+ await mockAppShell(page);+ await page.route(/\/api\/variables(?:\?.*)?$/, async (route) => {+ await route.fulfill({ json: response([]) });+ });+ await page.route(/\/api\/environments\/0\/projects\/tags$/, async (route) => {+ await route.fulfill({ json: response([]) });+ });+ await page.route(+ new RegExp(`/api/environments/0/projects/${encodedProject}/workspace$`),+ async (route) => {+ const state = workspaceState();+ await route.fulfill({+ json: response({+ files: [+ {+ path: `/projects/${PROJECT_ID}/workspace.txt`,+ relativePath: 'workspace.txt',+ name: 'workspace.txt',+ isDirectory: false,+ size: state.content.length,+ mode: '-rw-r--r--',+ isSymlink: false,+ editable: true+ }+ ],+ fileTreeRevision: `revision-${state.revision}`,+ fileTreeTruncated: false+ })+ });+ }+ );+ await page.route(+ new RegExp(`/api/environments/0/projects/${encodedProject}/workspace/file(?:\\?.*)?$`),+ async (route) => {+ const state = workspaceState();+ await route.fulfill({+ json: response({+ path: `/projects/${PROJECT_ID}/workspace.txt`,+ relativePath: 'workspace.txt',+ name: 'workspace.txt',+ size: state.content.length,+ mimeType: 'text/plain',+ content: state.content,+ editable: true+ })+ });+ }+ );+ await page.route(+ new RegExp(`/api/environments/0/projects/${encodedProject}(?:/(compose|runtime|updates))?$`),+ async (route) => {+ const section = new URL(route.request().url()).pathname.split('/').at(-1);+ const project = {+ id: PROJECT_ID,+ name: PROJECT_ID,+ path: `/projects/${PROJECT_ID}`,+ dirName: PROJECT_ID,+ status: 'stopped',+ serviceCount: 0,+ runningCount: 0,+ isArchived: false,+ hasBuildDirective: false,+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ tags: [],+ services: [],+ runtimeServices: [],+ includeFiles: []+ };++ if (section === 'compose') {+ await route.fulfill({+ json: response({+ ...project,+ composeContent: 'services: {}\n',+ envContent: '',+ overrideContent: '',+ composeFileName: 'compose.yaml'+ })+ });+ return;+ }++ await route.fulfill({ json: response(project) });+ }+ );+ }++ async function mockSystemBackupPage(+ page: Page,+ browse: (request: BrowseRequest, body: Record<string, unknown>, route: Route) => Promise<void>,+ restore: (body: Record<string, unknown>, route: Route) => Promise<void>,+ openPage = true+ ) {+ await mockAppShell(page);+ await page.route(/\/api\/backups\/history(?:\?.*)?$/, async (route) => {+ await route.fulfill({+ json: {+ success: true,+ data: [+ {+ id: SYSTEM_BACKUP_ID,+ size: 2048,+ createdAt: new Date().toISOString(),+ status: 'succeeded',+ trigger: 'manual',+ destination: 'local',+ localSnapshotId: 'system-snapshot',+ type: 'system',+ resourceType: 'system',+ resourceName: 'Arcane system'+ }+ ],+ pagination: { currentPage: 1, totalPages: 1, totalItems: 1, itemsPerPage: 20 }+ }+ });+ });+ await page.route(/\/api\/backups\/policies$/, async (route) => {+ await route.fulfill({ json: response({ policies: [], recoveryKeyStored: true }) });+ });+ await page.route(+ new RegExp(`/api/backups/${SYSTEM_BACKUP_ID}/files/browse(?:\\?.*)?$`),+ async (route) => {+ const url = new URL(route.request().url());+ await browse(+ {+ path: url.searchParams.get('path') ?? '',+ search: url.searchParams.get('search') ?? '',+ start: Number(url.searchParams.get('start') ?? 0),+ limit: url.searchParams.get('limit')+ },+ route.request().postDataJSON() as Record<string, unknown>,+ route+ );+ }+ );+ await page.route(+ new RegExp(`/api/backups/${SYSTEM_BACKUP_ID}/restore-files$`),+ async (route) => {+ await restore(route.request().postDataJSON() as Record<string, unknown>, route);+ }+ );+ if (!openPage) return;++ await page.goto('/settings/backups');+ await openSystemRestoreDialog(page);+ }++ async function openSystemRestoreDialog(page: Page) {+ await expect(page.getByText(SYSTEM_BACKUP_ID, { exact: false }).first()).toBeVisible();+ const backupRow = page.getByRole('row').filter({ hasText: SYSTEM_BACKUP_ID }).first();+ await backupRow.getByRole('button', { name: 'Open menu' }).click();+ await page.getByRole('menuitem', { name: 'Restore files' }).click();+ await expect(page.getByRole('dialog', { name: 'Restore files' })).toBeVisible();+ }++ async function navigateInApp(page: Page, path: string) {+ await page.evaluate((targetPath) => {+ const link = document.createElement('a');+ link.href = targetPath;+ document.body.append(link);+ link.click();+ link.remove();+ }, path);+ await page.waitForURL((url) => url.pathname === path.split('?')[0]);+ }++ function rootEntries(count: number) {+ return Array.from({ length: count }, (_, index) =>+ index === 0+ ? { path: 'folder', name: 'folder', isDirectory: true }+ : {+ path: `file-${index.toString().padStart(5, '0')}.txt`,+ name: `file-${index.toString().padStart(5, '0')}.txt`,+ isDirectory: false+ }+ );+ }++ test.describe('Backup file picker', () => {+ test('refreshes clean volume workspace files after restore', async ({ page }) => {+ const state: VolumeWorkspaceRestoreState = {+ content: 'before restore',+ restoredContent: 'after restore',+ revision: 1,+ failRestore: false,+ workspaceRequests: 0,+ fileRequests: 0,+ restoreBodies: [],+ fullRestoreRequests: 0+ };+ await mockVolumeWorkspaceRestore(page, state);++ await mockVolumeBackupPage(page, async (_request, route) => {+ await route.fulfill({+ json: browseResponse([+ { path: 'workspace.txt', name: 'workspace.txt', isDirectory: false }+ ])+ });+ });++ await page.keyboard.press('Escape');+ const editor = await openVolumeWorkspaceEditor(page);+ await expect(editor).toContainText('before restore');++ await openVolumeRestoreFilesDialog(page);+ const dialog = await selectVolumeRestoreFile(page);+ await expect(dialog).not.toContainText('discard all unsaved text and staged file operations');+ await dialog.getByRole('button', { name: 'Restore files' }).click();+ await expect.poll(() => state.restoreBodies.length).toBe(1);+ expect(state.restoreBodies[0]).toEqual({+ paths: ['workspace.txt'],+ selectAll: false+ });+ await expect(dialog).not.toBeVisible();+ const workspaceRequestsAfterRestore = state.workspaceRequests;+ await page.getByRole('tab', { name: 'Workspace', exact: true }).click();++ await expect(editor).toContainText('after restore');+ await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(0);+ expect(workspaceRequestsAfterRestore).toBeGreaterThanOrEqual(2);+ expect(state.workspaceRequests).toBe(workspaceRequestsAfterRestore);+ expect(state.fileRequests).toBeGreaterThanOrEqual(2);+ });++ test('warns before discarding volume workspace changes', async ({ page }) => {+ const state: VolumeWorkspaceRestoreState = {+ content: 'before restore',+ restoredContent: 'after restore',+ revision: 1,+ failRestore: false,+ workspaceRequests: 0,+ fileRequests: 0,+ restoreBodies: [],+ fullRestoreRequests: 0+ };+ await mockVolumeWorkspaceRestore(page, state);+ await mockVolumeBackupPage(page, async (_request, route) => {+ await route.fulfill({+ json: browseResponse([+ { path: 'workspace.txt', name: 'workspace.txt', isDirectory: false }+ ])+ });+ });++ await page.keyboard.press('Escape');+ const editor = await openVolumeWorkspaceEditor(page);+ await setCodeMirrorValue(editor, 'local draft');+ await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(1);++ await openVolumeRestoreFilesDialog(page);+ let restoreDialog = await selectVolumeRestoreFile(page);+ await expect(restoreDialog).toContainText(+ 'discard all unsaved text and staged file operations'+ );+ await restoreDialog.getByRole('button', { name: 'Cancel', exact: true }).click();+ await expect(restoreDialog).not.toBeVisible();+ expect(state.restoreBodies).toHaveLength(0);++ await page.getByRole('tab', { name: 'Workspace', exact: true }).click();+ await expect(editor).toContainText('local draft');+ await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(1);++ state.failRestore = true;+ await openVolumeRestoreFilesDialog(page);+ restoreDialog = await selectVolumeRestoreFile(page);+ await expect(restoreDialog).toContainText(+ 'discard all unsaved text and staged file operations'+ );+ await restoreDialog.getByRole('button', { name: 'Restore files' }).click();+ await expect.poll(() => state.restoreBodies.length).toBe(1);+ await restoreDialog.getByRole('button', { name: 'Cancel', exact: true }).click();+ await expect(restoreDialog).not.toBeVisible();++ await page.getByRole('tab', { name: 'Workspace', exact: true }).click();+ await expect(editor).toContainText('local draft');+ await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(1);++ state.failRestore = false;+ await openVolumeRestoreFilesDialog(page);+ restoreDialog = await selectVolumeRestoreFile(page);+ await expect(restoreDialog).toContainText(+ 'discard all unsaved text and staged file operations'+ );+ await restoreDialog.getByRole('button', { name: 'Restore files' }).click();+ await expect.poll(() => state.restoreBodies.length).toBe(2);+ await expect(restoreDialog).not.toBeVisible();++ await page.getByRole('tab', { name: 'Workspace', exact: true }).click();+ await expect(editor).toContainText('after restore');+ await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(0);+ });++ test('warns before a full volume restore discards workspace changes', async ({ page }) => {+ const state: VolumeWorkspaceRestoreState = {+ content: 'before restore',+ restoredContent: 'after restore',+ revision: 1,+ failRestore: false,+ workspaceRequests: 0,+ fileRequests: 0,+ restoreBodies: [],+ fullRestoreRequests: 0+ };+ await mockVolumeWorkspaceRestore(page, state);+ await mockVolumeBackupPage(page, async (_request, route) => {+ await route.fulfill({+ json: browseResponse([+ { path: 'workspace.txt', name: 'workspace.txt', isDirectory: false }+ ])+ });+ });++ await page.keyboard.press('Escape');+ const editor = await openVolumeWorkspaceEditor(page);+ await setCodeMirrorValue(editor, 'local draft');+ await page.getByRole('tab', { name: 'Backups', exact: true }).click();+ const backupRow = page.getByRole('row').filter({ hasText: BACKUP_ID }).first();+ await backupRow.getByRole('button', { name: 'Open menu' }).click();+ await page.getByRole('menuitem', { name: 'Restore', exact: true }).click();++ const confirmDialog = page.getByRole('dialog', { name: 'Restore Volume' });+ await expect(confirmDialog).toContainText(+ 'discard all unsaved text and staged file operations'+ );+ await confirmDialog.getByRole('button', { name: 'Cancel', exact: true }).click();+ await expect(confirmDialog).not.toBeVisible();+ expect(state.fullRestoreRequests).toBe(0);++ await page.getByRole('tab', { name: 'Workspace', exact: true }).click();+ await expect(editor).toContainText('local draft');+ await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(1);+ });++ test('refreshes clean project workspace files after a system restore', async ({ page }) => {+ const workspaceState = { content: 'before restore', revision: 1 };+ const restoreBodies: Array<Record<string, unknown>> = [];+ await mockProjectWorkspacePage(page, () => workspaceState);++ await page.goto(`/projects/${PROJECT_ID}?tab=compose`);+ await page+ .locator('[data-path="workspace.txt"]')+ .getByRole('button', { name: 'workspace.txt', exact: true })+ .first()+ .click();+ const editor = page.locator('.arcane-code-editor .cm-content').first();+ await expect(editor).toContainText('before restore');++ await mockSystemBackupPage(+ page,+ async (_request, _body, route) => {+ await route.fulfill({+ json: browseResponse([+ {+ path: `${PROJECT_ID}/workspace.txt`,+ name: 'workspace.txt',+ isDirectory: false+ }+ ])+ });+ },+ async (body, route) => {+ restoreBodies.push(body);+ workspaceState.content = 'after restore';+ workspaceState.revision += 1;+ await route.fulfill({ json: response({ message: 'restored' }) });+ },+ false+ );+ await navigateInApp(page, '/settings/backups');+ await openSystemRestoreDialog(page);++ const dialog = page.getByRole('dialog', { name: 'Restore files' });+ await dialog+ .locator(`[data-path="${PROJECT_ID}/workspace.txt"]`)+ .getByRole('checkbox')+ .click();+ await dialog.getByRole('button', { name: 'Restore files' }).click();+ await expect.poll(() => restoreBodies.length).toBe(1);++ await navigateInApp(page, `/projects/${PROJECT_ID}?tab=compose`);+ await page+ .locator('[data-path="workspace.txt"]')+ .getByRole('button', { name: 'workspace.txt', exact: true })+ .first()+ .click();+ await expect(editor).toContainText('after restore');+ await expect(page.getByRole('img', { name: 'Unsaved changes' })).toHaveCount(0);+ });++ test('loads folders lazily, walks continuation pages, retains rows on retry, and bounds mounted rows', async ({+ page+ }) => {+ const requests: BrowseRequest[] = [];+ let continuationAttempts = 0;+ await mockVolumeBackupPage(page, async (request, route) => {+ requests.push(request);+ if (request.path === 'folder/nested') {+ await route.fulfill({+ json: browseResponse([+ { path: 'folder/nested/grandchild.txt', name: 'grandchild.txt', isDirectory: false }+ ])+ });+ return;+ }+ if (request.path === 'folder') {+ await route.fulfill({+ json: browseResponse([+ { path: 'folder/nested', name: 'nested', isDirectory: true },+ { path: 'folder/child.txt', name: 'child.txt', isDirectory: false }+ ])+ });+ return;+ }+ if (request.start === 20) {+ continuationAttempts += 1;+ if (continuationAttempts === 1) {+ await route.fulfill({ status: 500, json: { message: 'interrupted' } });+ return;+ }+ await route.fulfill({+ json: browseResponse(+ [{ path: 'last.txt', name: 'last.txt', isDirectory: false }],+ 21,+ 20+ )+ });+ return;+ }+ await route.fulfill({ json: browseResponse(rootEntries(20), 21) });+ });++ await expect.poll(() => requests.length).toBe(1);+ expect(requests[0]).toMatchObject({ path: '', search: '', start: 0, limit: null });+ const tree = page.locator('[data-backup-file-tree]');+ await expect(tree.locator('[data-path="folder"]')).toBeVisible();+ expect(await tree.locator('[data-path]').count()).toBeLessThan(40);++ await tree+ .locator('[data-path="folder"]')+ .getByRole('button', { name: 'Expand folder' })+ .click();+ await expect+ .poll(() => requests.filter((request) => request.path === 'folder').length)+ .toBe(1);+ await expect(tree.locator('[data-path="folder/child.txt"]')).toBeVisible();+ await tree+ .locator('[data-path="folder/nested"]')+ .getByRole('button', { name: 'Expand nested' })+ .click();+ await expect+ .poll(() => requests.filter((request) => request.path === 'folder/nested').length)+ .toBe(1);+ await expect(tree.locator('[data-path="folder/nested/grandchild.txt"]')).toBeVisible();++ await tree.evaluate((element) => {+ element.scrollTop = element.scrollHeight;+ element.dispatchEvent(new Event('scroll'));+ });+ await expect(page.getByText('The remaining backup files could not be loaded.')).toBeVisible();+ expect(await tree.locator('[data-path]').count()).toBeLessThan(40);+ await tree.evaluate((element) => {+ element.scrollTop = 0;+ element.dispatchEvent(new Event('scroll'));+ });+ await expect(tree.locator('[data-path="folder"]')).toBeVisible();+ await tree.evaluate((element) => {+ element.scrollTop = element.scrollHeight;+ element.dispatchEvent(new Event('scroll'));+ });+ await expect(page.getByText('The remaining backup files could not be loaded.')).toBeVisible();+ await page.getByRole('button', { name: 'Retry' }).click();+ await expect.poll(() => continuationAttempts).toBe(2);+ await expect(tree.locator('[data-path="last.txt"]')).toBeVisible();+ });++ test('supports folder coverage, indeterminate state, global selection, and search-scoped selection', async ({+ page+ }) => {+ const restoreBodies: Array<Record<string, unknown>> = [];+ await page.route(+ new RegExp(+ `/api/environments/0/volumes/${VOLUME_NAME}/backups/${BACKUP_ID}/restore-files$`+ ),+ async (route) => {+ restoreBodies.push(route.request().postDataJSON() as Record<string, unknown>);+ await route.fulfill({ json: response({ message: 'restored' }) });+ }+ );+ await mockVolumeBackupPage(page, async (request, route) => {+ if (request.search) {+ await route.fulfill({+ json: browseResponse([+ {+ path: `folder/${request.search}.txt`,+ name: `${request.search}.txt`,+ isDirectory: false+ }+ ])+ });+ return;+ }+ if (request.path === 'folder') {+ await route.fulfill({+ json: browseResponse([+ { path: 'folder/a.txt', name: 'a.txt', isDirectory: false },+ { path: 'folder/b.txt', name: 'b.txt', isDirectory: false }+ ])+ });+ return;+ }+ await route.fulfill({+ json: browseResponse([+ { path: 'folder', name: 'folder', isDirectory: true },+ { path: 'root.txt', name: 'root.txt', isDirectory: false }+ ])+ });+ });++ const dialog = page.getByRole('dialog', { name: 'Restore files' });+ const folder = dialog.locator('[data-path="folder"]');+ await folder.getByRole('button', { name: 'Expand folder' }).click();+ const child = dialog.locator('[data-path="folder/a.txt"]');+ await child.getByRole('checkbox').click();+ await expect(folder.getByRole('checkbox')).toHaveAttribute('data-state', 'indeterminate');+ await folder.getByRole('checkbox').click();+ await expect(child.getByRole('checkbox')).toBeDisabled();+ await expect(child.getByRole('checkbox')).toBeChecked();++ await dialog.getByRole('button', { name: 'Clear' }).click();+ await dialog.getByRole('button', { name: 'Select all' }).click();+ await expect(dialog.locator('[data-path="root.txt"]').getByRole('checkbox')).toBeDisabled();+ await dialog.getByRole('button', { name: 'Restore files' }).click();+ await expect.poll(() => restoreBodies.length).toBe(1);+ expect(restoreBodies[0]).toEqual({ paths: [], selectAll: true, search: '' });++ await mockVolumeBackupPage(page, async (request, route) => {+ if (request.search) {+ await route.fulfill({+ json: browseResponse([+ {+ path: `folder/${request.search}.txt`,+ name: `${request.search}.txt`,+ isDirectory: false+ }+ ])+ });+ return;+ }+ await route.fulfill({ json: browseResponse(rootEntries(2)) });+ });+ const reopened = page.getByRole('dialog', { name: 'Restore files' });+ await reopened.getByPlaceholder('Search files').fill('match');+ await expect(reopened.locator('[data-path="folder/match.txt"]')).toBeVisible();+ await reopened.getByRole('button', { name: 'Select all search matches' }).click();+ await reopened.getByPlaceholder('Search files').fill('changed');+ await expect(reopened.getByRole('button', { name: 'Restore files' })).toBeDisabled();+ });++ test('keeps a synthetic 100,000-entry result bounded to the viewport', async ({ page }) => {+ await mockVolumeBackupPage(page, async (_request, route) => {+ await route.fulfill({ json: browseResponse(rootEntries(100_000), 100_000, 0, 100_000) });+ });+ const tree = page.locator('[data-backup-file-tree]');+ await expect(tree.locator('[data-path="folder"]')).toBeVisible();+ expect(await tree.locator('[data-path]').count()).toBeLessThan(40);+ await tree.evaluate((element) => {+ element.scrollTop = element.scrollHeight / 2;+ element.dispatchEvent(new Event('scroll'));+ });+ await expect.poll(() => tree.locator('[data-path]').count()).toBeLessThan(40);+ });++ test('uses the same provider selection contract in the system backup dialog', async ({+ page+ }) => {+ const browseRequests: BrowseRequest[] = [];+ const browseBodies: Array<Record<string, unknown>> = [];+ const restoreBodies: Array<Record<string, unknown>> = [];+ await mockSystemBackupPage(+ page,+ async (request, body, route) => {+ browseRequests.push(request);+ browseBodies.push(body);+ await route.fulfill({+ json: browseResponse([{ path: 'project', name: 'project', isDirectory: true }])+ });+ },+ async (body, route) => {+ restoreBodies.push(body);+ await route.fulfill({ json: response({ message: 'restored' }) });+ }+ );++ await expect.poll(() => browseBodies.length).toBe(1);+ expect(browseBodies[0]).toEqual({ recoveryKey: '' });+ expect(browseRequests[0]).toMatchObject({ path: '', search: '', start: 0, limit: null });+ const dialog = page.getByRole('dialog', { name: 'Restore files' });+ await dialog.getByRole('button', { name: 'Select all' }).click();+ await dialog.getByRole('button', { name: 'Restore files' }).click();+ await expect.poll(() => restoreBodies.length).toBe(1);+ expect(restoreBodies[0]).toEqual({ recoveryKey: '', paths: [], selectAll: true, search: '' });+ });+ });+});++test.describe('S3 storage', () => {+ // The MinIO sidecar in the compose stack. Arcane reaches it over the compose+ // network, and so must the Rustic helper container it starts for each backup.+ const S3_ENDPOINT = process.env.E2E_S3_ENDPOINT ?? 'http://minio:9000';+ const S3_BUCKET = process.env.E2E_S3_BUCKET ?? 'arcane-backups';+ const S3_ACCESS_KEY_ID = process.env.E2E_S3_ACCESS_KEY_ID ?? 'arcane-test';+ const S3_SECRET_ACCESS_KEY = process.env.E2E_S3_SECRET_ACCESS_KEY ?? 'arcane-test-secret';++ type S3Destination = { id: string; name: string; bucket: string; secretConfigured: boolean };+ type BackupEntry = {+ id: string;+ status: string;+ destination: string;+ format: string;+ remoteSnapshotId?: string;+ localSnapshotId?: string;+ error?: string;+ };++ function destinationPayload(overrides: Record<string, unknown> = {}) {+ return {+ name: `e2e-minio-${Date.now()}`,+ endpoint: S3_ENDPOINT,+ bucket: S3_BUCKET,+ region: '',+ accessKeyId: S3_ACCESS_KEY_ID,+ secretAccessKey: S3_SECRET_ACCESS_KEY,+ prefix: `e2e/${Date.now()}`,+ useSsl: false,+ forcePathStyle: true,+ ...overrides+ };+ }++ async function createDestinationViaApi(+ page: Page,+ overrides: Record<string, unknown> = {}+ ): Promise<S3Destination> {+ const response = await page.request.post('/api/backups/s3', {+ data: destinationPayload(overrides)+ });+ if (!response.ok()) {+ throw new Error(+ `Failed to create S3 destination: ${response.status()} ${await response.text()}`+ );+ }+ return (await response.json()) as S3Destination;+ }++ async function deleteDestinationViaApi(page: Page, destinationId: string) {+ await removeApiResource(page, `/api/backups/s3/${destinationId}`);+ }++ async function createVolumeViaApi(page: Page, volumeName: string) {+ const response = await page.request.post('/api/environments/0/volumes', {+ data: { name: volumeName, driver: 'local' }+ });+ if (!response.ok()) {+ throw new Error(`Failed to create volume ${volumeName}: ${response.status()}`);+ }+ }++ async function removeVolumeViaApi(page: Page, volumeName: string) {+ await removeApiResource(+ page,+ `/api/environments/0/volumes/${encodeURIComponent(volumeName)}?force=true`+ );+ }++ async function getVolumeWorkspaceRevision(page: Page, volumeName: string) {+ const response = await page.request.get(+ `/api/environments/0/volumes/${encodeURIComponent(volumeName)}/workspace`+ );+ if (!response.ok()) {+ throw new Error(+ `Failed to read ${volumeName} workspace: ${response.status()} ${await response.text()}`+ );+ }+ const body = await response.json();+ return body.data.fileTreeRevision as string;+ }++ async function writeVolumeFile(+ page: Page,+ volumeName: string,+ fileName: string,+ content: string,+ operation: 'create_file' | 'update_file' = 'create_file'+ ) {+ const fileTreeRevision = await getVolumeWorkspaceRevision(page, volumeName);+ const response = await page.request.put(+ `/api/environments/0/volumes/${encodeURIComponent(volumeName)}/workspace`,+ {+ multipart: {+ manifest: JSON.stringify({+ fileTreeRevision,+ fileChanges: [{ operation, relativePath: fileName, uploadIndex: 0 }]+ }),+ files: { name: fileName, mimeType: 'text/plain', buffer: Buffer.from(content) }+ }+ }+ );+ if (!response.ok()) {+ throw new Error(+ `Failed to upload ${fileName}: ${response.status()} ${await response.text()}`+ );+ }+ }++ async function readVolumeFile(page: Page, volumeName: string, filePath: string) {+ const relativePath = filePath.replace(/^\/+/, '');+ const response = await page.request.get(+ `/api/environments/0/volumes/${encodeURIComponent(volumeName)}/workspace/file?relativePath=${encodeURIComponent(relativePath)}`+ );+ const data = await readApiData<{ content: string }>(response, `Read volume file ${filePath}`);+ expect(typeof data.content).toBe('string');+ return data.content;+ }++ async function listBackups(page: Page, volumeName: string): Promise<BackupEntry[]> {+ const backups = await readApiData<BackupEntry[]>(+ await page.request.get(+ `/api/environments/0/volumes/${encodeURIComponent(volumeName)}/backups`+ ),+ `List backups for ${volumeName}`+ );+ expect(Array.isArray(backups)).toBe(true);+ return backups;+ }++ // Backups run Rustic in a helper container, so the request returns before the+ // snapshot finishes. Poll the record until it leaves the running state.+ async function waitForBackup(page: Page, volumeName: string, backupId: string) {+ let last: BackupEntry | undefined;+ await expect+ .poll(+ async () => {+ last = (await listBackups(page, volumeName)).find((entry) => entry.id === backupId);+ return last?.status ?? 'missing';+ },+ { timeout: 180000, intervals: [2000] }+ )+ .not.toBe('running');+ expect(last?.status, `backup failed: ${last?.error ?? 'unknown error'}`).toBe('succeeded');+ return last as BackupEntry;+ }++ // Deleting a destination also verifies that no managed environment still+ // references it, and is refused when one cannot be reached. Other specs create+ // environments, so the release path depends on what is registered right now.+ async function countRemoteEnvironments(page: Page) {+ const response = await page.request.get('/api/environments');+ if (!response.ok()) {+ return 0;+ }+ const body = await response.json();+ const environments = (body?.data ?? []) as { id: string }[];+ return environments.filter((environment) => environment.id !== '0').length;+ }++ async function createBackupViaApi(+ page: Page,+ volumeName: string,+ data: Record<string, unknown>+ ): Promise<BackupEntry> {+ const response = await page.request.post(+ `/api/environments/0/volumes/${encodeURIComponent(volumeName)}/backups`,+ { data, timeout: 180000 }+ );+ if (!response.ok()) {+ throw new Error(`Failed to create backup: ${response.status()} ${await response.text()}`);+ }+ const body = await response.json();+ return body.data as BackupEntry;+ }++ test.describe('S3 Backups', () => {+ test('creates, tests, edits, and deletes a destination through settings', async ({ page }) => {+ test.setTimeout(120_000);+ const suffix = Date.now();+ const name = `e2e-minio-ui-${suffix}`;+ const updatedName = `${name}-updated`;+ let destinationId: string | undefined;++ try {+ await page.goto('/settings/backups/s3');+ await page.getByRole('button', { name: 'Add destination', exact: true }).click();++ let dialog = page.getByRole('dialog');+ await expect(dialog.getByRole('heading', { name: 'Add S3 destination' })).toBeVisible();+ await dialog.getByLabel('Name', { exact: true }).fill(name);+ await dialog.getByLabel('Endpoint', { exact: true }).fill(S3_ENDPOINT);+ await dialog.getByLabel('Bucket', { exact: true }).fill(S3_BUCKET);+ await dialog.getByLabel('Access key ID', { exact: true }).fill(S3_ACCESS_KEY_ID);+ await dialog.getByLabel('Secret access key', { exact: true }).fill(S3_SECRET_ACCESS_KEY);+ await dialog.getByLabel('Path prefix', { exact: true }).fill(`e2e/ui/${suffix}`);++ const sslSwitch = dialog.getByRole('switch', { name: 'Use SSL', exact: true });+ if (await sslSwitch.isChecked()) await sslSwitch.click();++ await dialog.getByRole('button', { name: 'Test Connection', exact: true }).click();+ await expect(+ page.getByText(`Connection to ${name} succeeded`, { exact: true })+ ).toBeVisible();+ await expect(+ page.getByText('Connection verified. You can now save this destination.')+ ).toBeVisible();+ await dialog.getByRole('button', { name: 'Add S3 destination', exact: true }).click();++ await expect(page.getByText(`Created ${name}`, { exact: true })).toBeVisible();+ let destinationRow = page.getByRole('row').filter({ hasText: name });+ await expect(destinationRow).toBeVisible();++ const listResponse = await page.request.get('/api/backups/s3?start=0&limit=100');+ expect(listResponse.status(), await listResponse.text()).toBe(200);+ const destinations = (await listResponse.json()).data as S3Destination[];+ destinationId = destinations.find((destination) => destination.name === name)?.id;+ expect(destinationId).toBeTruthy();++ let menu = await openRowActionsMenu(page, destinationRow);+ await menu.getByRole('menuitem', { name: 'Test Connection', exact: true }).click();+ await expect(+ page.getByText(`Connection to ${name} succeeded`, { exact: true }).last()+ ).toBeVisible();++ menu = await openRowActionsMenu(page, destinationRow);+ await menu.getByRole('menuitem', { name: 'Edit', exact: true }).click();+ dialog = page.getByRole('dialog');+ await expect(dialog.getByRole('heading', { name: 'Edit S3 destination' })).toBeVisible();+ await dialog.getByLabel('Name', { exact: true }).fill(updatedName);+ await dialog.getByLabel('Path prefix', { exact: true }).fill(`e2e/ui/${suffix}/updated`);+ await dialog.getByRole('button', { name: 'Test Connection', exact: true }).click();+ await expect(+ page.getByText(`Connection to ${updatedName} succeeded`, { exact: true })+ ).toBeVisible();+ await dialog.getByRole('button', { name: 'Save Changes', exact: true }).click();++ await expect(page.getByText(`Updated ${updatedName}`, { exact: true })).toBeVisible();+ destinationRow = page.getByRole('row').filter({ hasText: updatedName });+ await expect(destinationRow).toBeVisible();+ await expect+ .poll(() => countRemoteEnvironments(page), {+ message: 'Expected temporary remote environments to be removed before S3 deletion',+ timeout: 90_000,+ intervals: [1_000, 2_000]+ })+ .toBe(0);++ menu = await openRowActionsMenu(page, destinationRow);+ await menu.getByRole('menuitem', { name: 'Delete', exact: true }).click();+ const confirmDialog = page.getByRole('dialog', { name: `Delete ${updatedName}` });+ await expect(+ confirmDialog.getByRole('heading', { name: `Delete ${updatedName}` })+ ).toBeVisible();+ const deleteResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'DELETE' &&+ new URL(response.url()).pathname === `/api/backups/s3/${destinationId}`+ );+ await confirmDialog.getByRole('button', { name: 'Delete', exact: true }).click();+ const deleteResponse = await deleteResponsePromise;+ expect(deleteResponse.ok(), await deleteResponse.text()).toBe(true);++ await expect(page.getByText(`Deleted ${updatedName}`, { exact: true })).toBeVisible();+ await expect(destinationRow).toHaveCount(0);+ destinationId = undefined;+ } finally {+ if (destinationId) await deleteDestinationViaApi(page, destinationId);+ }+ });++ test('creates a destination and verifies connectivity against MinIO', async ({ page }) => {+ const destination = await createDestinationViaApi(page);+ try {+ expect(destination.bucket).toBe(S3_BUCKET);+ expect(destination.secretConfigured).toBe(true);++ // Uploads, downloads, and deletes a probe object in the bucket.+ const test = await page.request.post(`/api/backups/s3/${destination.id}/test`);+ expect(test.status(), await test.text()).toBe(200);+ } finally {+ await deleteDestinationViaApi(page, destination.id);+ }+ });++ test('refuses the stored secret once connection settings change', async ({ page }) => {+ const destination = await createDestinationViaApi(page);+ try {+ const withoutSecret = await page.request.put(`/api/backups/s3/${destination.id}`, {+ data: destinationPayload({+ name: destination.name,+ bucket: 'someone-elses-bucket',+ secretAccessKey: ''+ })+ });+ expect(withoutSecret.status()).toBe(400);+ expect(await withoutSecret.text()).toContain('re-enter the secret access key');++ // The same edit is accepted once the secret is supplied again.+ const withSecret = await page.request.put(`/api/backups/s3/${destination.id}`, {+ data: destinationPayload({ name: destination.name, prefix: `e2e/${Date.now()}-moved` })+ });+ expect(withSecret.status(), await withSecret.text()).toBe(200);+ } finally {+ await deleteDestinationViaApi(page, destination.id);+ }+ });++ test('backs a volume up to S3 and restores it from the bucket', async ({ page }) => {+ test.setTimeout(300000);++ const volumeName = `e2e-s3-backup-${Date.now()}`;+ const fileContent = `arcane-e2e-${Date.now()}`;+ const destination = await createDestinationViaApi(page);+ let backupId: string | undefined;++ try {+ await createVolumeViaApi(page, volumeName);+ await writeVolumeFile(page, volumeName, 'payload.txt', fileContent);+ expect(await readVolumeFile(page, volumeName, '/payload.txt')).toBe(fileContent);++ const created = await createBackupViaApi(page, volumeName, {+ destination: 's3',+ s3DestinationId: destination.id+ });+ backupId = created.id;+ const backup = await waitForBackup(page, volumeName, created.id);++ expect(backup.destination).toBe('s3');+ expect(backup.format).toBe('rustic');+ expect(backup.remoteSnapshotId, 'no snapshot was recorded in S3').toBeTruthy();+ expect(backup.localSnapshotId ?? '').toBe('');++ // Rustic can only list these paths by reading the repository back out+ // of the bucket, so this proves the snapshot really landed in MinIO.+ const files = await page.request.get(+ `/api/environments/0/volumes/backups/${created.id}/files`+ );+ expect(files.status(), await files.text()).toBe(200);+ expect(JSON.stringify((await files.json())?.data ?? [])).toContain('payload.txt');++ const replacementContent = 'x'.repeat(fileContent.length);+ await writeVolumeFile(page, volumeName, 'payload.txt', replacementContent, 'update_file');+ expect(await readVolumeFile(page, volumeName, '/payload.txt')).toBe(replacementContent);++ const restore = await page.request.post(+ `/api/environments/0/volumes/${encodeURIComponent(volumeName)}/backups/${created.id}/restore`,+ { data: {}, timeout: 180000 }+ );+ expect(restore.status(), await restore.text()).toBe(200);+ expect(await readVolumeFile(page, volumeName, '/payload.txt')).toBe(fileContent);+ } finally {+ if (backupId) {+ await removeApiResource(page, `/api/environments/0/volumes/backups/${backupId}`);+ }+ await removeVolumeViaApi(page, volumeName);+ await deleteDestinationViaApi(page, destination.id);+ }+ });++ test('blocks deleting a destination a backup still references', async ({ page }) => {+ test.setTimeout(300000);++ const volumeName = `e2e-s3-inuse-${Date.now()}`;+ const destination = await createDestinationViaApi(page);+ let backupId: string | undefined;++ try {+ await createVolumeViaApi(page, volumeName);+ await writeVolumeFile(page, volumeName, 'payload.txt', 'in-use');++ const created = await createBackupViaApi(page, volumeName, {+ destination: 's3',+ s3DestinationId: destination.id+ });+ backupId = created.id;+ await waitForBackup(page, volumeName, created.id);++ const blocked = await page.request.delete(`/api/backups/s3/${destination.id}`);+ expect(blocked.status()).toBe(409);++ const removed = await page.request.delete(+ `/api/environments/0/volumes/backups/${created.id}`+ );+ expect(removed.ok(), await removed.text()).toBe(true);+ backupId = undefined;++ const remoteEnvironments = await countRemoteEnvironments(page);+ const allowed = await page.request.delete(`/api/backups/s3/${destination.id}`);+ if (remoteEnvironments === 0) {+ expect(allowed.status(), await allowed.text()).toBe(200);+ } else {+ // A registered environment that cannot be checked keeps the+ // destination, so the local reference is no longer the blocker.+ expect([200, 409]).toContain(allowed.status());+ }+ } finally {+ if (backupId) {+ await removeApiResource(page, `/api/environments/0/volumes/backups/${backupId}`);+ }+ await removeVolumeViaApi(page, volumeName);+ await deleteDestinationViaApi(page, destination.id);+ }+ });+ });+});++test.describe('System and volume restore', () => {+ type ManagementType = 'system' | 'volume';++ type SystemVolumeBackupPolicy = {+ id: string;+ enabled: boolean;+ schedule: string;+ retentionCount: number;+ stopContainers: boolean;+ localEnabled: boolean;+ s3Enabled: boolean;+ selectionMode: 'all' | 'allowlist' | 'blocklist';+ volumeNames: string[];+ ignoreAnonymous: boolean;+ };++ type SystemVolumeBackupPolicyCollection = { policies: SystemVolumeBackupPolicy[] };++ type HistoryEntry = {+ id: string;+ size: number;+ createdAt: string;+ status: string;+ trigger: string;+ destination: string;+ format: string;+ policyId?: string;+ type: ManagementType;+ resourceType: 'system' | 'volume';+ resourceName: string;+ };++ const defaultPolicy: SystemVolumeBackupPolicy = {+ id: 'volume-nightly',+ enabled: false,+ schedule: '0 0 2 * * *',+ retentionCount: 7,+ stopContainers: false,+ localEnabled: true,+ s3Enabled: false,+ selectionMode: 'all',+ volumeNames: [],+ ignoreAnonymous: true+ };++ function paginated<T>(data: T[]) {+ return {+ data,+ pagination: {+ currentPage: 1,+ totalPages: data.length > 0 ? 1 : 0,+ totalItems: data.length,+ itemsPerPage: 20+ }+ };+ }++ function historyEntry(resourceName: string, type: ManagementType): HistoryEntry {+ return {+ id: `${type}-${resourceName}`,+ size: 1024,+ createdAt: new Date().toISOString(),+ status: 'succeeded',+ trigger: type === 'system' ? 'scheduled' : 'manual',+ destination: 'local',+ format: 'rustic',+ policyId: type === 'system' ? 'system-volume:test' : undefined,+ type,+ resourceType: 'volume',+ resourceName+ };+ }++ async function createVolumeViaApi(page: Page, volumeName: string) {+ const response = await page.request.post('/api/environments/0/volumes', {+ data: { name: volumeName, driver: 'local' }+ });+ expect(response.ok(), await response.text()).toBeTruthy();+ }++ async function removeVolumeViaApi(page: Page, volumeName: string) {+ await removeApiResource(+ page,+ `/api/environments/0/volumes/${encodeURIComponent(volumeName)}?force=true`+ );+ }++ async function mockSystemBackupPage(+ page: Page,+ collection: SystemVolumeBackupPolicyCollection,+ options: { name: string; anonymous: boolean; available: boolean }[],+ history: HistoryEntry[] = []+ ) {+ let savedCollection = structuredClone(collection);+ const runRequests: unknown[] = [];+ const activities: Activity[] = [];+ await page.route('**/api/environments/0/activities?**', (route) => {+ const status = new URL(route.request().url()).searchParams.get('status');+ return route.fulfill({+ json: paginated(activities.filter((activity) => !status || activity.status === status))+ });+ });++ await page.route('**/api/backups/volumes/config', async (route) => {+ if (route.request().method() === 'PUT') {+ const input = (await route.request().postDataJSON()) as {+ policies: SystemVolumeBackupPolicy[];+ };+ savedCollection = {+ policies: input.policies.map((policy, index) => ({+ ...policy,+ id: policy.id || `volume-created-${index}`+ }))+ };+ }+ await route.fulfill({ json: savedCollection });+ });+ await page.route('**/api/backups/policies', async (route) => {+ await route.fulfill({+ json: {+ policies: [+ {+ id: 'system-nightly',+ enabled: true,+ schedule: '0 0 3 * * *',+ retentionCount: 7,+ localEnabled: true,+ s3Enabled: false+ }+ ],+ recoveryKeyStored: true+ }+ });+ });+ await page.route('**/api/backups/volumes/options', (route) => route.fulfill({ json: options }));+ await page.route('**/api/backups/volumes/run', async (route) => {+ runRequests.push(await route.request().postDataJSON());+ const now = new Date().toISOString();+ const activity: Activity = {+ id: `system-volume-run-${runRequests.length}`,+ environmentId: '0',+ type: 'resource_action',+ status: 'running',+ metadata: { action: 'run_system_volume_backups' },+ startedAt: now,+ createdAt: now+ };+ activities.push(activity);+ return route.fulfill({ status: 202, json: { activityId: activity.id, status: 'running' } });+ });+ await page.route('**/api/backups/history**', (route) => {+ const type = new URL(route.request().url()).searchParams.get('type');+ const rows =+ type === 'system' || type === 'volume'+ ? history.filter((row) => row.type === type)+ : history;+ return route.fulfill({ json: paginated(rows) });+ });++ return {+ savedCollection: () => savedCollection,+ runRequests: () => runRequests,+ completeRun: () => {+ const activity = activities.at(-1);+ if (!activity) throw new Error('No backup run was accepted');+ activity.status = 'success';+ activity.endedAt = new Date().toISOString();+ activity.metadata = {+ ...activity.metadata,+ matched: 2,+ succeeded: 1,+ failed: 0,+ skipped: 1,+ failures: []+ };+ history.push({+ ...historyEntry('completed-batch-volume', 'system'),+ id: activity.id,+ trigger: 'manual'+ });+ }+ };+ }++ test.describe('System-managed volume backups', () => {+ test('creates multiple volume schedules and runs a saved schedule', async ({ page }) => {+ const liveName = `e2e-live-volume-${Date.now()}`;+ const anonymousName = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';+ const unavailableName = 'deleted-volume';+ const mock = await mockSystemBackupPage(+ page,+ {+ policies: [+ {+ ...defaultPolicy,+ enabled: false,+ selectionMode: 'allowlist',+ volumeNames: [unavailableName]+ }+ ]+ },+ [+ { name: liveName, anonymous: false, available: true },+ { name: anonymousName, anonymous: true, available: true },+ { name: unavailableName, anonymous: false, available: false }+ ]+ );++ await page.goto('/settings/backups');+ const systemCard = page.getByTestId('backup-policy-system-system-nightly');+ const volumeCard = page.getByTestId('backup-policy-volume-volume-nightly');+ await expect(systemCard.getByText('System')).toHaveClass(/(^|\s)text-purple(\s|$)/);+ await expect(volumeCard.getByText('Volume')).toHaveClass(/(^|\s)text-purple(\s|$)/);+ await volumeCard.getByRole('button', { name: 'Edit Schedule' }).click();+ const dialog = page.getByRole('dialog', { name: 'Edit Schedule' });++ await expect(dialog.getByText(unavailableName)).toBeVisible();+ await expect(dialog.getByText('Unavailable', { exact: true })).toBeVisible();+ await expect(dialog.getByText('Anonymous', { exact: true })).toBeVisible();+ await dialog.getByLabel('Volume selection').click();+ await page.getByRole('option', { name: 'Blocklist' }).click();+ await expect(dialog.getByLabel('Volume selection')).toContainText('Blocklist');+ await expect(dialog.getByText('Excluded volumes')).toBeVisible();+ await dialog.locator('label').filter({ hasText: liveName }).getByRole('checkbox').click();+ await dialog.getByRole('button', { name: 'Save' }).click();+ await expect(dialog).toBeHidden();+ expect(mock.savedCollection().policies[0]?.volumeNames).toEqual([unavailableName, liveName]);++ await page.getByRole('button', { name: 'Create', exact: true }).click();+ await page.getByRole('menuitem', { name: 'Schedule' }).click();+ const createSchedule = page.getByRole('dialog', { name: 'Create schedule' });+ await createSchedule.getByLabel('Backup type').click();+ await page.getByRole('option', { name: 'Volume' }).click();+ await createSchedule.getByLabel('Schedule', { exact: true }).fill('0 30 4 * * *');+ await createSchedule.getByRole('button', { name: 'Save' }).click();+ await expect(createSchedule).toBeHidden();+ expect(mock.savedCollection().policies).toHaveLength(2);+ await expect(page.getByText('Volume', { exact: true })).toHaveCount(2);++ await page.getByRole('button', { name: 'Create', exact: true }).click();+ await page.getByRole('menuitem', { name: 'Backup' }).click();+ const createBackup = page.getByRole('dialog', { name: 'Create Backup' });+ const runningBackup = page.getByRole('alert').filter({ hasText: 'Backup in progress' });+ await createBackup.getByLabel('Backup type').click();+ await page.getByRole('option', { name: 'Volume' }).click();+ await createBackup.getByLabel('Backup configuration').click();+ await page.getByRole('option', { name: '0 0 2 * * *' }).click();+ await createBackup.getByRole('button', { name: 'Create Backup' }).click();+ await expect(createBackup).toBeHidden();+ await expect(page.getByText('Backup started', { exact: true })).toBeVisible();+ await expect(runningBackup).toBeVisible();+ await page.getByRole('button', { name: 'Create', exact: true }).click();+ await expect(page.getByRole('menuitem', { name: 'Backup', exact: true })).toBeDisabled();+ await page.keyboard.press('Escape');+ await page.reload();+ await expect(runningBackup).toBeVisible();+ mock.completeRun();+ await expect(runningBackup).toBeHidden({+ timeout: 15000+ });+ await expect(page.getByRole('table').getByText('completed-batch-volume')).toBeVisible();+ expect(mock.runRequests()).toContainEqual({ policyId: 'volume-nightly' });++ await page.getByRole('button', { name: 'Create', exact: true }).click();+ await page.getByRole('menuitem', { name: 'Backup' }).click();+ const customBackup = page.getByRole('dialog', { name: 'Create Backup' });+ await customBackup.getByLabel('Backup type').click();+ await page.getByRole('option', { name: 'Volume' }).click();+ await customBackup.getByLabel('Volume selection').click();+ await page.getByRole('option', { name: 'Allowlist' }).click();+ await customBackup+ .locator('label')+ .filter({ hasText: liveName })+ .getByRole('checkbox')+ .click();+ await customBackup.getByRole('button', { name: 'Create Backup' }).click();+ await expect(customBackup).toBeHidden();+ await expect(runningBackup).toBeVisible();+ expect(mock.runRequests()).toContainEqual({+ custom: {+ destination: 'local',+ s3DestinationId: '',+ stopContainers: false,+ selectionMode: 'allowlist',+ volumeNames: [liveName],+ ignoreAnonymous: true+ }+ });+ });++ test('filters unified history and opens the owning volume backup tab', async ({ page }) => {+ const volumeName = `e2e-system-history-${Date.now()}`;+ await createVolumeViaApi(page, volumeName);+ try {+ await mockSystemBackupPage(+ page,+ { policies: [] },+ [],+ [historyEntry('central-volume', 'system'), historyEntry(volumeName, 'volume')]+ );+ await page.goto('/settings/backups');++ await page.getByTestId('facet-type-trigger').click();+ await page.getByTestId('facet-type-option-system').click();+ const historyTable = page.getByRole('table');+ await expect(historyTable.getByText('central-volume')).toBeVisible();+ await expect(historyTable.getByText(volumeName)).toHaveCount(0);++ await page.getByTestId('facet-type-option-system').click();+ await page.getByTestId('facet-type-option-volume').click();+ await expect(historyTable.getByText(volumeName)).toBeVisible();+ await expect(historyTable.getByText('central-volume')).toHaveCount(0);++ await page.keyboard.press('Escape');+ const row = page.getByRole('row').filter({ hasText: volumeName });+ await row.getByRole('button', { name: 'Open menu' }).click();+ await page.getByRole('menuitem', { name: 'Open volume backups' }).click();+ await expect(page).toHaveURL(+ new RegExp(`/volumes/${encodeURIComponent(volumeName)}\\?tab=backups`)+ );+ } finally {+ await removeVolumeViaApi(page, volumeName);+ }+ });+ });+});diff --git a/tests/spec/container-grouped-pagination.spec.ts b/tests/spec/container-grouped-pagination.spec.tsdeleted file mode 100644index 3a403ff4a..000000000--- a/tests/spec/container-grouped-pagination.spec.ts+++ /dev/null@@ -1,343 +0,0 @@-import { expect, test, type Page } from '../fixtures/test.fixture';--type MockContainer = {- id: string;- names: string[];- image: string;- imageId: string;- command: string;- created: number;- labels: Record<string, string>;- state: string;- status: string;- ports: [];- hostConfig: { networkMode: string };- networkSettings: { networks: Record<string, unknown> };- mounts: [];-};--function createContainer(- id: string,- name: string,- project: string,- created: number-): MockContainer {- return {- id,- names: [`/${name}`],- image: `${project || 'misc'}:latest`,- imageId: `image-${id}`,- command: '',- created,- labels: project ? { 'com.docker.compose.project': project } : {},- state: 'running',- status: 'Up 5 minutes',- ports: [],- hostConfig: { networkMode: 'default' },- networkSettings: { networks: {} },- mounts: []- };-}--function buildContainersResponse(containers: MockContainer[], start: number, limit: number) {- const safeLimit = limit > 0 ? limit : containers.length;- const pageItems = limit === -1 ? containers : containers.slice(start, start + safeLimit);- const currentPage = limit > 0 ? Math.floor(start / safeLimit) + 1 : 1;- const totalPages = limit > 0 ? Math.max(1, Math.ceil(containers.length / safeLimit)) : 1;- const itemsPerPage = limit === -1 ? containers.length : safeLimit;-- return {- success: true,- data: pageItems,- counts: {- runningContainers: containers.length,- stoppedContainers: 0,- totalContainers: containers.length- },- pagination: {- totalPages,- totalItems: containers.length,- currentPage,- itemsPerPage,- grandTotalItems: containers.length- }- };-}--test('grouped containers do not split the same project across pages', async ({ page, context }) => {- await page.addInitScript(() => {- localStorage.removeItem('selectedEnvironmentId');- localStorage.removeItem('arcane-container-table');- localStorage.setItem('container-groups-collapsed', JSON.stringify({ immich: false }));- localStorage.removeItem('collapsible-cards-expanded');- });-- let groupedMockPayload:- | {- groups: Array<{ groupName: string; items: MockContainer[] }>;- }- | undefined;-- const otherContainers = Array.from({ length: 18 }, (_, index) => {- const project = `other-${index + 1}`;- return createContainer(`other-${index + 1}`, `${project}-service`, project, 1_000 - index);- });-- const immichContainers = [- createContainer('immich-1', 'immich-server', 'immich', 900),- createContainer('immich-2', 'immich-machine-learning', 'immich', 899),- createContainer('immich-3', 'immich-redis', 'immich', 898),- createContainer('immich-4', 'immich-postgres', 'immich', 897)- ];-- const allContainers = [...otherContainers, ...immichContainers];-- await context.route('**/containers**', async (route) => {- if (route.request().method() !== 'GET') {- await route.continue();- return;- }-- const url = new URL(route.request().url());- if (!/^\/api\/environments\/[^/]+\/containers$/.test(url.pathname)) {- await route.continue();- return;- }-- const start = Number(url.searchParams.get('start') ?? '0');- const limit = Number(url.searchParams.get('limit') ?? '20');- const groupBy = url.searchParams.get('groupBy');-- if (groupBy === 'project') {- groupedMockPayload = {- groups: [- {- groupName: 'immich',- items: immichContainers- },- ...otherContainers.slice(0, 18).map((container, index) => ({- groupName: `other-${index + 1}`,- items: [container]- }))- ]- };-- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({- success: true,- data: [...immichContainers, ...otherContainers.slice(0, 18)],- groups: groupedMockPayload.groups,- counts: {- runningContainers: allContainers.length,- stoppedContainers: 0,- totalContainers: allContainers.length- },- pagination: {- totalPages: 1,- totalItems: allContainers.length,- currentPage: 1,- itemsPerPage: 20,- grandTotalItems: allContainers.length- }- })- });- return;- }-- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify(buildContainersResponse(allContainers, start, limit))- });- });-- await page.goto('/containers');- await page.waitForLoadState('load');-- await page.setViewportSize({ width: 1440, height: 900 });-- await page.getByRole('button', { name: 'View' }).click();- await page.getByRole('menuitemcheckbox', { name: 'Group by Project' }).click();- await page.keyboard.press('Escape');-- await expect- .poll(- () =>- groupedMockPayload?.groups.find((group) => group.groupName === 'immich')?.items.length ?? 0- )- .toBe(4);-- const immichGroupRow = page- .locator('table tbody tr')- .filter({ has: page.getByText('immich', { exact: true }) });-- await expect(immichGroupRow).toHaveCount(1);- await expect(immichGroupRow).toContainText('immich');- await expect(immichGroupRow).toContainText('(4)');-- await expect(page.getByRole('link', { name: 'immich-server', exact: true })).toBeVisible();- await expect(- page.getByRole('link', { name: 'immich-machine-learning', exact: true })- ).toBeVisible();- await expect(page.getByRole('link', { name: 'immich-redis', exact: true })).toBeVisible();- await expect(page.getByRole('link', { name: 'immich-postgres', exact: true })).toBeVisible();-});--type MockGroup = { groupName: string; items: MockContainer[] };--async function mockGroupedContainers(page: Page, groups: MockGroup[]) {- const allContainers = groups.flatMap((group) => group.items);- await page.context().route('**/containers**', async (route) => {- const url = new URL(route.request().url());- if (- route.request().method() !== 'GET' ||- !/^\/api\/environments\/[^/]+\/containers$/.test(url.pathname)- ) {- await route.continue();- return;- }- const response = buildContainersResponse(allContainers, 0, -1);- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify(- url.searchParams.get('groupBy') === 'project' ? { ...response, groups } : response- )- });- });-}--function containerRow(page: Page, name: string) {- return page.getByRole('row').filter({ has: page.getByRole('link', { name, exact: true }) });-}--function groupRow(page: Page, groupName: string) {- return page.locator('table tbody tr').filter({ has: page.getByText(groupName, { exact: true }) });-}--async function expectContainersSelected(page: Page, names: string[], selected: boolean) {- for (const name of names) {- await expect(containerRow(page, name).getByRole('checkbox')).toHaveAttribute(- 'aria-checked',- selected ? 'true' : 'false'- );- }-}--async function openGroupedContainers(page: Page, collapsed: Record<string, boolean>) {- await page.addInitScript((collapsedState) => {- localStorage.removeItem('selectedEnvironmentId');- localStorage.removeItem('arcane-container-table');- localStorage.setItem('container-groups-collapsed', JSON.stringify(collapsedState));- localStorage.removeItem('collapsible-cards-expanded');- }, collapsed);-- const groups: MockGroup[] = [- {- groupName: 'immich',- items: [- createContainer('immich-1', 'immich-server', 'immich', 900),- createContainer('immich-2', 'immich-machine-learning', 'immich', 899),- createContainer('immich-3', 'immich-redis', 'immich', 898),- createContainer('immich-4', 'immich-postgres', 'immich', 897)- ]- },- { groupName: 'alpha', items: [createContainer('alpha-1', 'alpha-service', 'alpha', 800)] },- {- groupName: 'beta',- items: [- createContainer('beta-1', 'beta-web', 'beta', 700),- createContainer('beta-2', 'beta-db', 'beta', 699)- ]- },- { groupName: 'gamma', items: [createContainer('gamma-1', 'gamma-service', 'gamma', 600)] }- ];- await mockGroupedContainers(page, groups);- await page.setViewportSize({ width: 1440, height: 900 });- await page.goto('/containers');- await page.waitForLoadState('load');- await page.getByRole('button', { name: 'View' }).click();- await page.getByRole('menuitemcheckbox', { name: 'Group by Project' }).click();- await page.keyboard.press('Escape');- await expect(groupRow(page, 'immich')).toContainText('(4)');- await expect(page.getByRole('link', { name: 'immich-server', exact: true })).toBeVisible();-}--test.describe('grouped shift-select', () => {- test('ranges follow group order and skip collapsed groups', async ({ page }) => {- await openGroupedContainers(page, { immich: false, alpha: false, gamma: false });- await expect(page.getByRole('link', { name: 'beta-web', exact: true })).toHaveCount(0);-- await containerRow(page, 'immich-machine-learning').getByRole('checkbox').click();- await containerRow(page, 'gamma-service')- .getByRole('checkbox')- .click({ modifiers: ['Shift'] });-- await expectContainersSelected(- page,- [- 'immich-machine-learning',- 'immich-redis',- 'immich-postgres',- 'alpha-service',- 'gamma-service'- ],- true- );- await expectContainersSelected(page, ['immich-server'], false);- await expect(groupRow(page, 'beta').getByRole('checkbox')).toHaveAttribute(- 'aria-checked',- 'false'- );- await expect(groupRow(page, 'alpha').getByRole('checkbox')).toHaveAttribute(- 'aria-checked',- 'true'- );- await expect(groupRow(page, 'immich').getByRole('checkbox')).toHaveAttribute(- 'aria-checked',- 'mixed'- );- await expect(page.getByRole('button', { name: 'Stop (5)', exact: true })).toBeVisible();-- await groupRow(page, 'beta').click();- await expect(page.getByRole('link', { name: 'beta-web', exact: true })).toBeVisible();- await expectContainersSelected(page, ['beta-web', 'beta-db'], false);- });-- test('expanded groups are included and group or collapse changes reset the anchor', async ({- page- }) => {- await openGroupedContainers(page, { immich: false, alpha: false, beta: false });-- await containerRow(page, 'immich-postgres').getByRole('checkbox').click();- await containerRow(page, 'beta-db')- .getByRole('checkbox')- .click({ modifiers: ['Shift'] });- await expectContainersSelected(- page,- ['immich-postgres', 'alpha-service', 'beta-web', 'beta-db'],- true- );- await expectContainersSelected(page, ['immich-server', 'immich-redis'], false);-- await groupRow(page, 'alpha').getByRole('checkbox').click();- await expectContainersSelected(page, ['alpha-service'], false);- await containerRow(page, 'immich-server')- .getByRole('checkbox')- .click({ modifiers: ['Shift'] });- await expectContainersSelected(page, ['immich-server'], true);- await expectContainersSelected(page, ['immich-machine-learning', 'immich-redis'], false);-- await containerRow(page, 'immich-machine-learning').getByRole('checkbox').click();- await groupRow(page, 'alpha').click();- await expect(page.getByRole('link', { name: 'alpha-service', exact: true })).toHaveCount(0);- await containerRow(page, 'beta-db')- .getByRole('checkbox')- .click({ modifiers: ['Shift'] });- await expectContainersSelected(page, ['immich-machine-learning', 'beta-web'], true);- await expectContainersSelected(page, ['immich-redis', 'beta-db'], false);- await expect(page.getByRole('button', { name: 'Stop (4)', exact: true })).toBeVisible();- });-});diff --git a/tests/spec/container-lifecycle.spec.ts b/tests/spec/container-lifecycle.spec.tsdeleted file mode 100644index 50d01c211..000000000--- a/tests/spec/container-lifecycle.spec.ts+++ /dev/null@@ -1,809 +0,0 @@-import { expect, test, type Locator, type Page, type Response } from '../fixtures/test.fixture';-import { readApiData, removeApiResource } from '../utils/fetch.util';-import { waitForDialogReady } from '../utils/playwright.util';--const TEST_IMAGE = 'public.ecr.aws/docker/library/busybox:1.37';--type CreatedContainer = {- id: string;- name: string;- image: string;- status: string;-};--type ContainerDetails = {- id: string;- name: string;- image: string;- activityId?: string;- state: {- status: string;- running: boolean;- };- config: {- env?: string[];- cmd?: string[];- workingDir?: string;- healthcheck?: {- test?: string[];- interval?: number;- timeout?: number;- retries?: number;- };- };- hostConfig: {- restartPolicy?: string;- };- networkSettings: {- networks: Record<string, { aliases?: string[] }>;- };- mounts: Array<{- type: string;- name?: string;- source: string;- destination: string;- }>;- ports: Array<{- privatePort: number;- publicPort?: number;- type: string;- }>;- labels?: Record<string, string>;-};--type ActivityDetail = {- activity: {- id: string;- type: string;- status: string;- error?: string;- };-};--type ActionResult = {- message?: string;- activityId?: string;-};--type CommitResult = {- id: string;-};--type CreatedProject = {- id: string;- name: string;-};--type ContainerCreatePayload = {- name: string;- image: string;- cmd?: string[];- workingDir?: string;- env?: string[];- labels?: Record<string, string>;- healthcheck?: {- test?: string[];- interval?: number;- timeout?: number;- retries?: number;- };- hostConfig?: {- binds?: string[];- portBindings?: Record<string, Array<{ hostIp?: string; hostPort?: string }>>;- restartPolicy?: { name: string; maximumRetryCount?: number };- };- networkingConfig?: {- endpointsConfig?: Record<string, { aliases?: string[] }>;- };-};--async function updateExperimentalFeatures(page: Page, enabled: string) {- const response = await page.request.put('/api/environments/0/settings', {- data: { experimentalFeaturesEnabled: enabled }- });- if (!response.ok()) {- throw new Error(- `Update experimentalFeaturesEnabled failed with ${response.status()}: ${await response.text()}`- );- }- const settingsResponse = await page.request.get('/api/environments/0/settings');- expect(settingsResponse.ok(), 'Read back experimental feature setting').toBe(true);- const settings = (await settingsResponse.json()) as Array<{ key: string; value: string }>;- expect(settings).toContainEqual(- expect.objectContaining({ key: 'experimentalFeaturesEnabled', value: enabled })- );-}--async function getContainer(page: Page, containerId: string): Promise<ContainerDetails> {- return readApiData<ContainerDetails>(- await page.request.get(`/api/environments/0/containers/${containerId}`),- `Get container ${containerId}`- );-}--async function expectContainerStatus(page: Page, containerId: string, status: string) {- await expect- .poll(async () => (await getContainer(page, containerId)).state.status, {- message: `Expected container ${containerId} to reach ${status}`,- timeout: 20_000- })- .toBe(status);-}--async function expectContainerMissing(page: Page, containerId: string) {- await expect- .poll(- async () =>- (await page.request.get(`/api/environments/0/containers/${containerId}`)).status(),- { message: `Expected container ${containerId} to be removed`, timeout: 20_000 }- )- .toBe(404);-}--async function expectActivitySucceeded(page: Page, activityId: string, expectedType: string) {- await expect- .poll(- async () => {- const detail = await readApiData<ActivityDetail>(- await page.request.get(`/api/environments/0/activities/${activityId}`),- `Get activity ${activityId}`- );- return detail.activity.status;- },- { message: `Expected ${expectedType} activity ${activityId} to succeed`, timeout: 20_000 }- )- .toBe('success');- const detail = await readApiData<ActivityDetail>(- await page.request.get(`/api/environments/0/activities/${activityId}`),- `Get completed activity ${activityId}`- );- expect(detail.activity.type).toBe(expectedType);- expect(detail.activity.error).toBeFalsy();-}--// Header actions render inline or inside the "More actions" menu depending on placement.-async function clickHeaderAction(page: Page, name: string) {- const header = page.locator('[data-tabs-root] > :not([inert])');- const inline = header- .getByRole('button', { name, exact: true })- .or(header.getByRole('link', { name, exact: true }))- .filter({ visible: true })- .first();- const menuTrigger = header- .getByRole('button', { name: 'More actions', exact: true })- .filter({ visible: true })- .first();- const inlineVisible = await inline- .waitFor({ state: 'visible', timeout: 5_000 })- .then(() => true)- .catch(() => false);- if (inlineVisible) {- await inline.click();- return;- }- await menuTrigger.click();- await page.getByRole('menuitem', { name, exact: true }).click();-}--async function runSimpleContainerAction(- page: Page,- containerId: string,- pathAction: string,- buttonName: string,- expectedActivityType: string-) {- return test.step(`${buttonName} container`, async () => {- const responseTimeout = pathAction === 'stop' ? 120_000 : 60_000;- const matchesActionRequest = (url: string, method: string) => {- const pathname = new URL(url).pathname.replace(/\/$/, '');- return method === 'POST' && pathname.endsWith(`/containers/${containerId}/${pathAction}`);- };- const requestPromise = page.waitForRequest(- (request) => matchesActionRequest(request.url(), request.method()),- { timeout: 30_000 }- );- const responsePromise = page.waitForResponse(- (response) => matchesActionRequest(response.url(), response.request().method()),- { timeout: responseTimeout }- );- await clickHeaderAction(page, buttonName);- await requestPromise;- const result = await readApiData<ActionResult>(- await responsePromise,- `${buttonName} container ${containerId}`- );- expect(result.activityId, `${buttonName} must return an activity ID`).toBeTruthy();- await expectActivitySucceeded(page, result.activityId!, expectedActivityType);- });-}--async function selectSearchableOption(page: Page, scope: Locator, option: string) {- await scope.getByRole('combobox').filter({ visible: true }).first().click();- await page.getByRole('option', { name: option, exact: true }).click();-}--function formGroup(page: Page, heading: string) {- return page- .locator('div.space-y-4')- .filter({ has: page.getByRole('heading', { name: heading, exact: true }) })- .first();-}--async function createContainerThroughUI(- page: Page,- containerName: string,- volumeName: string,- networkName: string,- containerIds: Set<string>-) {- return test.step('Create container', async () => {- await page.goto('/containers/new');- await page.getByRole('button', { name: 'Create Container', exact: true }).click();- await expect(page.getByText('Container name is required', { exact: true })).toBeVisible();- await expect(page.getByText('Image is required', { exact: true })).toBeVisible();-- await page.getByLabel('Container Name *', { exact: true }).fill(containerName);- await page.getByLabel('Image *', { exact: true }).fill(TEST_IMAGE);- await page.getByLabel('Command', { exact: true }).fill('sleep 3600');- await page.getByLabel('Working Directory', { exact: true }).fill('/tmp');-- await page.getByRole('tab', { name: 'Environment', exact: true }).click();- const environmentGroup = formGroup(page, 'Environment Variables');- await environmentGroup.getByRole('button', { name: 'Add', exact: true }).click();- await environmentGroup.getByPlaceholder('KEY').fill('E2E_VALUE');- await environmentGroup.getByPlaceholder('value').fill('initial');-- const labelsGroup = formGroup(page, 'Labels');- await labelsGroup.getByRole('button', { name: 'Add', exact: true }).click();- await labelsGroup.getByPlaceholder('com.example.key').fill('arcane.e2e');- await labelsGroup.getByPlaceholder('value').fill('container-lifecycle');-- await page.getByRole('tab', { name: 'Ports', exact: true }).click();- await page.getByRole('button', { name: 'Add', exact: true }).click();- await page.getByPlaceholder('0.0.0.0').fill('127.0.0.1');- await page.getByPlaceholder('80', { exact: true }).fill('8080');-- await page.getByRole('tab', { name: 'Volumes', exact: true }).click();- await page.getByRole('button', { name: 'Add Volume Mount', exact: true }).click();- await selectSearchableOption(page, page.getByRole('tabpanel'), volumeName);- await page.getByPlaceholder('Container path').fill('/data');-- await page.getByRole('tab', { name: 'Networks', exact: true }).click();- await page.getByRole('button', { name: 'Add', exact: true }).click();- await selectSearchableOption(page, page.getByRole('tabpanel'), networkName);- await page.getByPlaceholder('Aliases').fill('lifecycle-alias');-- await page.getByRole('tab', { name: 'Advanced', exact: true }).click();- await page.locator('#restart-policy').click();- await page.getByRole('option', { name: 'On Failure', exact: true }).click();- await page.getByLabel('Maximum Retries', { exact: true }).fill('3');- await page.locator('#health-mode').click();- await page.getByRole('option', { name: 'Custom', exact: true }).click();- await page.getByLabel('Test Command', { exact: true }).fill('test "$E2E_VALUE" = "initial"');- await page.getByLabel('Interval (s)', { exact: true }).fill('2');- await page.getByLabel('Timeout (s)', { exact: true }).fill('1');- await page.getByLabel('Retries', { exact: true }).fill('2');-- const requestPromise = page.waitForRequest(- (request) =>- request.method() === 'POST' &&- new URL(request.url()).pathname === '/api/environments/0/containers'- );- const responsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === '/api/environments/0/containers'- );- await page.getByRole('button', { name: 'Create Container', exact: true }).click();-- const request = await requestPromise;- const payload = request.postDataJSON() as ContainerCreatePayload;- const created = await readApiData<CreatedContainer>(- await responsePromise,- `Create container ${containerName}`- );- containerIds.add(created.id);- await expect(page).toHaveURL((url) => url.pathname === `/containers/${created.id}`);-- expect(payload).toMatchObject({- name: containerName,- image: TEST_IMAGE,- cmd: ['sleep', '3600'],- workingDir: '/tmp',- env: ['E2E_VALUE=initial'],- labels: { 'arcane.e2e': 'container-lifecycle' },- healthcheck: {- test: ['CMD-SHELL', 'test "$E2E_VALUE" = "initial"'],- interval: 2,- timeout: 1,- retries: 2- },- hostConfig: {- binds: [`${volumeName}:/data`],- portBindings: {- '8080/tcp': [{ hostIp: '127.0.0.1', hostPort: '' }]- },- restartPolicy: { name: 'on-failure', maximumRetryCount: 3 }- },- networkingConfig: {- endpointsConfig: {- [networkName]: { aliases: ['lifecycle-alias'] }- }- }- });-- return created;- });-}--async function verifyShell(page: Page, marker: string) {- return test.step('Verify shell and volume', async () => {- await page.getByRole('tab', { name: 'Shell', exact: true }).click();- await expect(page.getByText('Live', { exact: true })).toBeVisible({ timeout: 15_000 });-- const terminal = page.locator('.terminal-container');- const input = terminal.locator('textarea.xterm-helper-textarea');- await expect(input).toBeAttached();- await input.pressSequentially(- `echo ${marker}-$E2E_VALUE && echo volume-ok > /data/e2e-marker && cat /data/e2e-marker`,- { delay: 5 }- );- await input.press('Enter');- await expect(terminal.locator('.xterm-rows')).toContainText(`${marker}-initial`, {- timeout: 15_000- });- await expect(terminal.locator('.xterm-rows')).toContainText('volume-ok');- });-}--async function connectAndDisconnectNetwork(page: Page, containerId: string, networkName: string) {- return test.step('Connect and disconnect network', async () => {- await page.getByRole('tab', { name: 'Networks', exact: true }).click();- const connectSection = page.locator('div').filter({- has: page.getByRole('heading', { name: 'Connect to network', exact: true })- });- await selectSearchableOption(page, connectSection, networkName);- await connectSection.getByPlaceholder('Aliases').fill('attached-live');-- const connectResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- /\/api\/environments\/0\/networks\/[^/]+\/connect$/.test(new URL(response.url()).pathname)- );- await connectSection.getByRole('button', { name: 'Connect', exact: true }).click();- expect((await connectResponsePromise).ok()).toBe(true);- await expect- .poll(async () =>- Object.keys((await getContainer(page, containerId)).networkSettings.networks)- )- .toContain(networkName);-- const networkCard = page- .locator('[data-slot="card"]')- .filter({ has: page.getByText(networkName, { exact: true }) })- .filter({ has: page.getByRole('button', { name: 'Disconnect', exact: true }) })- .last();- await networkCard.getByRole('button', { name: 'Disconnect', exact: true }).click();- const disconnectResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- /\/api\/environments\/0\/networks\/[^/]+\/disconnect$/.test(- new URL(response.url()).pathname- )- );- await page.getByRole('dialog').getByRole('button', { name: 'Disconnect', exact: true }).click();- expect((await disconnectResponsePromise).ok()).toBe(true);- await expect(page.getByRole('dialog')).toBeHidden();- await expect(page.locator('[data-dialog-overlay]')).toHaveCount(0);- await expect- .poll(async () =>- Object.keys((await getContainer(page, containerId)).networkSettings.networks)- )- .not.toContain(networkName);- });-}--async function commitContainer(- page: Page,- containerId: string,- containerName: string,- repository: string,- imageIds: Set<string>-) {- return test.step('Commit image', async () => {- await clickHeaderAction(page, 'Commit');- const dialog = page.getByRole('dialog', { name: `Commit "${containerName}"` });- await waitForDialogReady(dialog);- await expect(dialog.locator('#repository')).toBeFocused();- await dialog.locator('#repository').fill(repository);- await dialog.locator('#tag').fill('e2e');- await dialog.getByLabel('Description', { exact: true }).fill('Playwright lifecycle snapshot');- await dialog.getByLabel('Author', { exact: true }).fill('Arcane Playwright');- await expect(dialog.locator('#repository')).toHaveValue(repository);- await expect(dialog.locator('#tag')).toHaveValue('e2e');- await expect(dialog.getByLabel('Description', { exact: true })).toHaveValue(- 'Playwright lifecycle snapshot'- );- await expect(dialog.getByLabel('Author', { exact: true })).toHaveValue('Arcane Playwright');-- const requestPromise = page.waitForRequest(- (request) =>- request.method() === 'POST' &&- new URL(request.url()).pathname === `/api/environments/0/containers/${containerId}/commit`- );- const responsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === `/api/environments/0/containers/${containerId}/commit`- );- await dialog.getByRole('button', { name: 'Commit', exact: true }).click();- const request = await requestPromise;- const result = await readApiData<CommitResult>(- await responsePromise,- `Commit container ${containerId}`- );- imageIds.add(result.id);- expect(request.postDataJSON()).toMatchObject({- repository,- tag: 'e2e',- comment: 'Playwright lifecycle snapshot',- author: 'Arcane Playwright'- });- expect(result.id).toMatch(/^sha256:/);- await expect(dialog).toBeHidden();- return result;- });-}--async function editContainerThroughUI(- page: Page,- containerId: string,- newContainerName: string,- containerIds: Set<string>-) {- return test.step('Edit and recreate container', async () => {- await clickHeaderAction(page, 'Edit');- await expect(page).toHaveURL(`/containers/${containerId}/edit`);- await expect(page.getByText('Applying changes recreates this container.')).toBeVisible();- await expect(page.getByLabel('Container Name *', { exact: true })).toHaveValue(- newContainerName.replace(/-edited$/, '')- );- await expect(page.getByLabel('Command', { exact: true })).toHaveValue('sleep 3600');-- await page.getByLabel('Container Name *', { exact: true }).fill(newContainerName);- await page.getByLabel('Command', { exact: true }).fill('sleep 7200');- await page.getByRole('tab', { name: 'Environment', exact: true }).click();- const environmentGroup = formGroup(page, 'Environment Variables');- const environmentKeys = environmentGroup.getByPlaceholder('KEY');- const customEnvironmentIndex = await environmentKeys.evaluateAll((inputs) =>- inputs.findIndex((input) => (input as HTMLInputElement).value === 'E2E_VALUE')- );- expect(customEnvironmentIndex).toBeGreaterThanOrEqual(0);- const customEnvironmentRow = environmentKeys.nth(customEnvironmentIndex).locator('..');- await customEnvironmentRow.getByPlaceholder('value').fill('edited');-- const responsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === `/api/environments/0/containers/${containerId}/edit`,- { timeout: 60_000 }- );- await page.getByRole('button', { name: 'Save', exact: true }).click();- const dialog = page.getByRole('dialog', { name: 'Recreate container?' });- await dialog.getByRole('button', { name: 'Save', exact: true }).click();- const edited = await readApiData<ContainerDetails>(- await responsePromise,- `Edit container ${containerId}`- );- containerIds.add(edited.id);- await expect(page).toHaveURL((url) => url.pathname === `/containers/${edited.id}`);- expect(edited.id).not.toBe(containerId);- expect(edited.activityId).toBeTruthy();- await expectActivitySucceeded(page, edited.activityId!, 'container_edit');- return edited;- });-}--async function redeployContainerThroughUI(- page: Page,- containerId: string,- containerIds: Set<string>-) {- return test.step('Redeploy container', async () => {- await clickHeaderAction(page, 'Redeploy');- const dialog = page.getByRole('dialog');- const responsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname ===- `/api/environments/0/containers/${containerId}/redeploy`,- { timeout: 60_000 }- );- await dialog.getByRole('button', { name: 'Redeploy', exact: true }).click();- const redeployed = await readApiData<ContainerDetails>(- await responsePromise,- `Redeploy container ${containerId}`- );- containerIds.add(redeployed.id);- await expect(page).toHaveURL((url) => url.pathname === `/containers/${redeployed.id}`);- expect(redeployed.id).not.toBe(containerId);- expect(redeployed.activityId).toBeTruthy();- await expectActivitySucceeded(page, redeployed.activityId!, 'container_redeploy');- return redeployed;- });-}--async function convertContainerToProject(- page: Page,- containerId: string,- containerName: string,- projectIds: Set<string>-) {- return test.step('Convert to Compose', async () => {- const generateResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === '/api/environments/0/containers/generate-compose'- );- await clickHeaderAction(page, 'Convert to Compose');- const generated = await readApiData<{ composeContent: string }>(- await generateResponsePromise,- `Generate Compose for ${containerId}`- );- expect(generated.composeContent).toContain(containerName);- await expect(page).toHaveURL(`/projects/new?fromContainers=${containerId}&fromEnv=0`);- await expect(page.locator('.cm-editor').first()).toContainText(containerName);-- const createButton = page.locator('button[data-action="create"]');- await expect(createButton).toBeEnabled({ timeout: 15_000 });- const responsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === '/api/environments/0/projects'- );- await createButton.click();- const dialog = page.getByRole('dialog');- await expect(- dialog.getByLabel('Remove original container(s) after creation')- ).not.toBeChecked();- await dialog.getByRole('button', { name: 'Create Project', exact: true }).click();- const project = await readApiData<CreatedProject>(- await responsePromise,- `Create converted project for ${containerId}`- );- projectIds.add(project.id);- await expect(page).toHaveURL((url) => url.pathname === `/projects/${project.id}`);- return project;- });-}--async function killContainerThroughUI(page: Page, containerId: string, containerName: string) {- return test.step('Kill container', async () => {- await clickHeaderAction(page, 'Kill');- const dialog = page.getByRole('dialog', { name: `Kill "${containerName}"` });- const responsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === `/api/environments/0/containers/${containerId}/kill`- );- await dialog.getByRole('button', { name: 'Kill container', exact: true }).click();- const result = await readApiData<ActionResult>(- await responsePromise,- `Kill container ${containerId}`- );- expect(result.activityId).toBeTruthy();- await expectActivitySucceeded(page, result.activityId!, 'container_kill');- });-}--async function removeContainerThroughUI(page: Page, containerId: string) {- return test.step('Remove container', async () => {- await clickHeaderAction(page, 'Remove');- const responsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'DELETE' &&- new URL(response.url()).pathname === `/api/environments/0/containers/${containerId}`- );- await page.getByRole('dialog').getByRole('button', { name: 'Remove', exact: true }).click();- const result = await readApiData<ActionResult>(- await responsePromise,- `Remove container ${containerId}`- );- expect(result.activityId).toBeTruthy();- await expectActivitySucceeded(page, result.activityId!, 'container_delete');- await expect(page).toHaveURL('/containers');- });-}--test('creates, mutates, converts, and removes a standalone container', async ({- page,- registerCleanup-}) => {- test.setTimeout(300_000);- page.setDefaultTimeout(15_000);- page.setDefaultNavigationTimeout(20_000);-- const suffix = Date.now().toString(36);- const containerName = `e2e-container-${suffix}`;- const editedContainerName = `${containerName}-edited`;- const volumeName = `e2e-volume-${suffix}`;- const primaryNetworkName = `e2e-network-primary-${suffix}`;- const secondaryNetworkName = `e2e-network-secondary-${suffix}`;- const committedRepository = `arcane-e2e/${containerName}`;- let currentContainerId: string | null = null;- let committedImageId: string | null = null;- const containerIds = new Set<string>();- const imageIds = new Set<string>();- const projectIds = new Set<string>();- let settingsChanged = false;- let originalExperimentalSetting = 'false';-- registerCleanup(async () => {- for (const id of projectIds)- await removeApiResource(page, `/api/environments/0/projects/${id}/destroy`, {- data: { removeVolumes: false }- });- for (const id of containerIds)- await removeApiResource(- page,- `/api/environments/0/containers/${id}?force=true&volumes=false`- );- for (const id of imageIds)- await removeApiResource(- page,- `/api/environments/0/images/${encodeURIComponent(id)}?force=true`- );- for (const name of [secondaryNetworkName, primaryNetworkName])- await removeApiResource(page, `/api/environments/0/networks/${encodeURIComponent(name)}`);- await removeApiResource(- page,- `/api/environments/0/volumes/${encodeURIComponent(volumeName)}?force=true`- );- if (settingsChanged) await updateExperimentalFeatures(page, originalExperimentalSetting);- });-- const settingsResponse = await page.request.get('/api/environments/0/settings');- if (!settingsResponse.ok()) {- throw new Error(`Get settings failed with ${settingsResponse.status()}`);- }- const settings = (await settingsResponse.json()) as Array<{ key: string; value: string }>;- const experimentalSetting = settings.find(- (setting) => setting.key === 'experimentalFeaturesEnabled'- );- expect(experimentalSetting, 'Experimental feature setting must be present').toBeDefined();- originalExperimentalSetting = experimentalSetting!.value;- settingsChanged = true;- await updateExperimentalFeatures(page, 'true');-- await readApiData(- await page.request.post('/api/environments/0/volumes', {- data: { name: volumeName, driver: 'local' }- }),- `Create volume ${volumeName}`- );- for (const networkName of [primaryNetworkName, secondaryNetworkName]) {- await readApiData(- await page.request.post('/api/environments/0/networks', {- data: { name: networkName, options: { driver: 'bridge' } }- }),- `Create network ${networkName}`- );- }-- const created = await createContainerThroughUI(- page,- containerName,- volumeName,- primaryNetworkName,- containerIds- );- currentContainerId = created.id;-- let details = await getContainer(page, currentContainerId);- expect(details.name).toBe(containerName);- expect(details.image).toBe(TEST_IMAGE);- expect(details.state.status).toBe('running');- expect(details.config.cmd).toEqual(['sleep', '3600']);- expect(details.config.workingDir).toBe('/tmp');- expect(details.config.env).toContain('E2E_VALUE=initial');- expect(details.config.healthcheck?.test).toEqual(['CMD-SHELL', 'test "$E2E_VALUE" = "initial"']);- expect(details.config.healthcheck?.interval).toBe(2_000_000_000);- expect(details.hostConfig.restartPolicy).toBe('on-failure');- expect(details.labels?.['arcane.e2e']).toBe('container-lifecycle');- expect(details.ports.some((port) => port.privatePort === 8080 && port.type === 'tcp')).toBe(true);- expect(details.mounts).toEqual(- expect.arrayContaining([- expect.objectContaining({ type: 'volume', name: volumeName, destination: '/data' })- ])- );- expect(details.networkSettings.networks[primaryNetworkName]?.aliases).toContain(- 'lifecycle-alias'- );-- await verifyShell(page, `shell-${suffix}`);- await page.getByRole('tab', { name: 'Overview', exact: true }).click();-- await runSimpleContainerAction(page, currentContainerId, 'pause', 'Pause', 'container_pause');- await expectContainerStatus(page, currentContainerId, 'paused');- await runSimpleContainerAction(- page,- currentContainerId,- 'unpause',- 'Unpause',- 'container_unpause'- );- await expectContainerStatus(page, currentContainerId, 'running');- await runSimpleContainerAction(- page,- currentContainerId,- 'restart',- 'Restart',- 'container_restart'- );- await expectContainerStatus(page, currentContainerId, 'running');- await runSimpleContainerAction(page, currentContainerId, 'stop', 'Stop', 'container_stop');- await expectContainerStatus(page, currentContainerId, 'exited');- await runSimpleContainerAction(page, currentContainerId, 'start', 'Start', 'container_start');- await expectContainerStatus(page, currentContainerId, 'running');-- await connectAndDisconnectNetwork(page, currentContainerId, secondaryNetworkName);-- const commit = await commitContainer(- page,- currentContainerId,- containerName,- committedRepository,- imageIds- );- committedImageId = commit.id;- const committedImageResponse = await page.request.get(- `/api/environments/0/images/${encodeURIComponent(committedImageId)}`- );- expect(committedImageResponse.ok()).toBe(true);-- const oldContainerId = currentContainerId;- const edited = await editContainerThroughUI(- page,- currentContainerId,- editedContainerName,- containerIds- );- currentContainerId = edited.id;- await expectContainerMissing(page, oldContainerId);- details = await getContainer(page, currentContainerId);- expect(details.name).toBe(editedContainerName);- expect(details.config.cmd).toEqual(['sleep', '7200']);- expect(details.config.env).toContain('E2E_VALUE=edited');- expect(details.mounts.some((mount) => mount.name === volumeName)).toBe(true);- expect(details.ports.some((port) => port.privatePort === 8080)).toBe(true);- expect(details.networkSettings.networks).toHaveProperty(primaryNetworkName);-- const preRedeployId = currentContainerId;- const redeployed = await redeployContainerThroughUI(page, currentContainerId, containerIds);- currentContainerId = redeployed.id;- await expectContainerMissing(page, preRedeployId);- await expectContainerStatus(page, currentContainerId, 'running');-- const convertedProject = await convertContainerToProject(- page,- currentContainerId,- editedContainerName,- projectIds- );- expect(projectIds.has(convertedProject.id)).toBe(true);- expect(- (await page.request.get(`/api/environments/0/containers/${currentContainerId}`)).ok()- ).toBe(true);-- await page.goto(`/containers/${currentContainerId}`);- await killContainerThroughUI(page, currentContainerId, editedContainerName);- await expectContainerStatus(page, currentContainerId, 'exited');- await runSimpleContainerAction(page, currentContainerId, 'start', 'Start', 'container_start');- await expectContainerStatus(page, currentContainerId, 'running');- await runSimpleContainerAction(page, currentContainerId, 'stop', 'Stop', 'container_stop');- await expectContainerStatus(page, currentContainerId, 'exited');-- await removeContainerThroughUI(page, currentContainerId);- await expectContainerMissing(page, currentContainerId);- currentContainerId = null;-});diff --git a/tests/spec/container-resource-sort.spec.ts b/tests/spec/container-resource-sort.spec.tsdeleted file mode 100644index b13c633d1..000000000--- a/tests/spec/container-resource-sort.spec.ts+++ /dev/null@@ -1,319 +0,0 @@-import { expect, test, type Page } from '../fixtures/test.fixture';--type MockSample = {- cpuPercent: number;- memoryUsageBytes: number;- memoryLimitBytes: number;- sampleTime: string;-};--type MockContainer = {- id: string;- names: string[];- image: string;- imageId: string;- command: string;- created: number;- labels: Record<string, string>;- state: string;- status: string;- ports: [];- hostConfig: { networkMode: string };- networkSettings: { networks: Record<string, unknown> };- mounts: [];- resourceSample?: MockSample | null;-};--const MiB = 1024 * 1024;-const GiB = 1024 * MiB;--function createSortContainer(- id: string,- created: number,- sample: MockSample | null-): MockContainer {- return {- id,- names: [`/${id}`],- image: 'misc:latest',- imageId: `image-${id}`,- command: '',- created,- labels: {},- state: 'running',- status: 'Up 5 minutes',- ports: [],- hostConfig: { networkMode: 'default' },- networkSettings: { networks: {} },- mounts: [],- resourceSample: sample- };-}--function sample(- cpuPercent: number,- memoryUsageBytes: number,- memoryLimitBytes: number-): MockSample {- return { cpuPercent, memoryUsageBytes, memoryLimitBytes, sampleTime: new Date().toISOString() };-}--// Default order is created desc: small, high-percent, big-bytes, broken.-// Memory-bytes desc: big-bytes (3GiB), high-percent (800MiB), small (100MiB), broken.-// Memory-percent desc would put high-percent (80%) first: the two orders differ.-function basicFixtures() {- return [- createSortContainer('small', 400, sample(5, 100 * MiB, 8 * GiB)),- createSortContainer('high-percent', 300, sample(50, 800 * MiB, 1 * GiB)),- createSortContainer('big-bytes', 200, sample(10, 3 * GiB, 4 * GiB)),- createSortContainer('broken', 100, null)- ];-}--// Twelve fixtures in created-desc order so page size 10 leaves the two-// heaviest containers off the default first page: they enter it once sorted-// by memory desc.-function pagedFixtures() {- const items: MockContainer[] = [];- for (let i = 0; i < 10; i++) {- items.push(createSortContainer(`filler-${i}`, 20 - i, sample(i, (10 + i) * MiB, 8 * GiB)));- }- items.push(createSortContainer('offpage-heavy2', 2, sample(2, 4 * GiB, 8 * GiB)));- items.push(createSortContainer('offpage-heavy', 1, sample(1, 5 * GiB, 8 * GiB)));- return items;-}--type Scenario = {- supported: boolean;- fixtures: () => MockContainer[];- failList?: boolean;- requests: string[];-};--function installContainersMock(page: Page, scenario: Scenario) {- return page.context().route('**/containers**', async (route) => {- if (route.request().method() !== 'GET') {- await route.continue();- return;- }- const url = new URL(route.request().url());- if (!/^\/api\/environments\/[^/]+\/containers$/.test(url.pathname)) {- await route.continue();- return;- }- if (scenario.failList) {- await route.fulfill({- status: 500,- contentType: 'application/json',- body: JSON.stringify({ success: false, data: { error: 'daemon exploded' } })- });- return;- }-- scenario.requests.push(url.search);- const sort = url.searchParams.get('sort') ?? '';- const order = url.searchParams.get('order') ?? 'asc';- const start = Number(url.searchParams.get('start') ?? '0');- const limit = Number(url.searchParams.get('limit') ?? '20');-- let items = scenario.fixtures();- const valueOf = (c: MockContainer) => {- if (!c.resourceSample) return null;- return sort === 'cpuUsage' ? c.resourceSample.cpuPercent : c.resourceSample.memoryUsageBytes;- };- if (sort === 'cpuUsage' || sort === 'memoryUsage') {- items = [...items].sort((a, b) => {- const va = valueOf(a);- const vb = valueOf(b);- if (va === null && vb === null) return a.id.localeCompare(b.id);- if (va === null) return 1;- if (vb === null) return -1;- if (va === vb) return a.id.localeCompare(b.id);- return order === 'desc' ? vb - va : va - vb;- });- }-- const safeLimit = limit > 0 ? limit : items.length;- const pageItems = items.slice(start, start + safeLimit);-- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({- success: true,- data: pageItems,- counts: {- runningContainers: items.length,- stoppedContainers: 0,- totalContainers: items.length- },- pagination: {- totalPages: Math.max(1, Math.ceil(items.length / safeLimit)),- totalItems: items.length,- currentPage: Math.floor(start / safeLimit) + 1,- itemsPerPage: safeLimit,- grandTotalItems: items.length- },- ...(scenario.supported ? { resourceSortSupported: true } : {})- })- });- });-}--async function openContainers(page: Page) {- await page.addInitScript(() => {- localStorage.removeItem('selectedEnvironmentId');- localStorage.removeItem('arcane-container-table');- });- await page.goto('/containers');- await page.waitForLoadState('load');- await page.setViewportSize({ width: 1440, height: 900 });-}--function rowIds(page: Page) {- return page- .getByRole('row')- .filter({ has: page.locator('a[href^="/containers/"]') })- .locator('a[href^="/containers/"]')- .evaluateAll((els) => els.map((el) => el.getAttribute('href')?.split('/').pop() ?? ''));-}--async function setPageSize(page: Page, size: string) {- // The rows-per-page control is a bits-ui Select trigger, which renders as a plain- // button rather than a combobox.- await page.locator('[data-slot="select-trigger"]').filter({ visible: true }).first().click();- await page.getByRole('option', { name: size, exact: true }).click();-}--async function sortByHeader(page: Page, name: string, direction: 'asc' | 'desc') {- // The sortable header button opens a menu; the direction is chosen from it.- await page.getByRole('columnheader', { name, exact: true }).getByRole('button').click();- await page- .getByRole('menuitem', { name: direction === 'desc' ? 'Desc' : 'Asc', exact: true })- .click();-}--test('memory sort orders globally by bytes and renders matching samples', async ({ page }) => {- const scenario: Scenario = { supported: true, fixtures: basicFixtures, requests: [] };- await installContainersMock(page, scenario);- await openContainers(page);-- await expect(page.getByRole('row').filter({ hasText: 'small' }).first()).toBeVisible();-- await sortByHeader(page, 'Memory Usage', 'desc');-- await expect- .poll(() => rowIds(page), { timeout: 10000 })- .toEqual(['big-bytes', 'high-percent', 'small', 'broken']);-- const bigBytesRow = page- .getByRole('row')- .filter({ has: page.getByRole('link', { name: 'big-bytes' }) });- await expect(bigBytesRow.getByText('10.0%')).toBeVisible();- await expect(bigBytesRow.getByText('3 GB', { exact: true })).toBeVisible();-- const brokenRow = page- .getByRole('row')- .filter({ has: page.getByRole('link', { name: 'broken' }) });- // Both the CPU and memory cells fall back to the unavailable label.- await expect(brokenRow.getByText('Unavailable', { exact: true })).toHaveCount(2);-});--test('sorted refresh pulls off-page containers into the first page', async ({ page }) => {- const scenario: Scenario = { supported: true, fixtures: pagedFixtures, requests: [] };- await installContainersMock(page, scenario);- await openContainers(page);-- await setPageSize(page, '10');- await expect- .poll(() => rowIds(page), { timeout: 10000 })- .toEqual([- 'filler-0',- 'filler-1',- 'filler-2',- 'filler-3',- 'filler-4',- 'filler-5',- 'filler-6',- 'filler-7',- 'filler-8',- 'filler-9'- ]);-- await sortByHeader(page, 'Memory Usage', 'desc');-- await expect- .poll(() => rowIds(page), { timeout: 10000 })- .toEqual([- 'offpage-heavy',- 'offpage-heavy2',- 'filler-9',- 'filler-8',- 'filler-7',- 'filler-6',- 'filler-5',- 'filler-4',- 'filler-3',- 'filler-2'- ]);-});--test('resource sort polls, suspends in background tabs, and surfaces failures', async ({- page-}) => {- test.setTimeout(60000);- await page.clock.install();- const scenario: Scenario = { supported: true, fixtures: basicFixtures, requests: [] };- await installContainersMock(page, scenario);- await openContainers(page);-- await sortByHeader(page, 'CPU Usage', 'desc');- await expect- .poll(() => rowIds(page), { timeout: 10000 })- .toEqual(['high-percent', 'big-bytes', 'small', 'broken']);-- const initialRequests = scenario.requests.filter((q) => q.includes('sort=cpuUsage')).length;- await expect- .poll(() => scenario.requests.filter((q) => q.includes('sort=cpuUsage')).length, {- timeout: 15000- })- .toBeGreaterThan(initialRequests);-- await page.evaluate(() => {- Object.defineProperty(document, 'hidden', { value: true, configurable: true });- document.dispatchEvent(new Event('visibilitychange'));- });- const frozen = scenario.requests.length;- await page.clock.runFor(6500);- expect(scenario.requests.length).toBe(frozen);-- await page.evaluate(() => {- Object.defineProperty(document, 'hidden', { value: false, configurable: true });- document.dispatchEvent(new Event('visibilitychange'));- });- await expect.poll(() => scenario.requests.length, { timeout: 10000 }).toBeGreaterThan(frozen);-- scenario.failList = true;- await expect(page.getByText('Automatic refresh failed: daemon exploded')).toBeVisible({- timeout: 15000- });-- scenario.failList = false;- await expect(page.getByText('Automatic refresh failed: daemon exploded')).toBeHidden({- timeout: 15000- });-});--test('older agents disable resource sorting with an upgrade explanation', async ({ page }) => {- const scenario: Scenario = { supported: false, fixtures: basicFixtures, requests: [] };- await installContainersMock(page, scenario);- await openContainers(page);-- await expect(page.getByText('needs a newer agent for this environment')).toBeVisible();- await expect(- page.getByRole('columnheader', { name: 'Memory Usage', exact: true }).getByRole('button')- ).toHaveCount(0);- await expect(- page.getByRole('columnheader', { name: 'CPU Usage', exact: true }).getByRole('button')- ).toHaveCount(0);-});diff --git a/tests/spec/containers.spec.ts b/tests/spec/containers.spec.tsindex e254f13e0..5adb6a11a 100644--- a/tests/spec/containers.spec.ts+++ b/tests/spec/containers.spec.ts@@ -1,369 +1,1591 @@import { stat } from 'node:fs/promises';-import { test, expect, type Page } from '../fixtures/test.fixture';+import { test, expect, type Page, type Locator, type Response } from '../fixtures/test.fixture';import { readApiData, removeApiResource, type Paginated } from '../utils/fetch.util';-import { ContainerSummary } from 'types/containers.type';+import { ContainerSummary } from '../types/containers.type';import { openRowActionsMenu } from '../utils/table-actions.util';+import { waitForDialogReady } from '../utils/playwright.util';++test.describe('Management', () => {+ const CONTAINERS_ROUTE = '/containers';++ const structuredContainerLog = {+ level: 'stdout',+ message: JSON.stringify({+ level: 'info',+ message: 'structured container log marker',+ request_id: 'request-3415'+ }),+ timestamp: '2026-07-27T23:08:37.000Z'+ };++ async function mockContainerLogsWebSocket(page: Page) {+ await page.addInitScript(() => {+ localStorage.setItem('arcane_log_json_parsing_v3', 'false');+ localStorage.setItem('arcane_log_auto_start', 'false');+ });+ await page.routeWebSocket(+ /\/api\/environments\/[^/]+\/ws\/containers\/[^/]+\/logs(?:\?.*)?$/,+ (socket) => socket.send(JSON.stringify(structuredContainerLog))+ );+ }-const CONTAINERS_ROUTE = '/containers';--const structuredContainerLog = {- level: 'stdout',- message: JSON.stringify({- level: 'info',- message: 'structured container log marker',- request_id: 'request-3415'- }),- timestamp: '2026-07-27T23:08:37.000Z'-};--async function mockContainerLogsWebSocket(page: Page) {- await page.addInitScript((logEntry) => {- localStorage.setItem('arcane_log_json_parsing_v3', 'false');- localStorage.setItem('arcane_log_auto_start', 'false');-- const browserWindow = globalThis as typeof globalThis & {- WebSocket: any;- EventTarget: any;- Event: any;- MessageEvent: any;- CloseEvent: any;- };+ async function navigateToContainers(page: Page) {+ await page.goto(CONTAINERS_ROUTE);+ await page.waitForLoadState('load');+ }++ let containersData: Paginated<ContainerSummary> = { data: [], pagination: { totalItems: 0 } };++ const fixtureContainerIds = new Set<string>();++ test.describe('Containers Page', () => {+ test.beforeEach(async ({ page }) => {+ containersData = { data: [] };+ for (const state of ['running', 'exited']) {+ const name = `e2e-list-${state}-${Date.now()}`;+ const container = await readApiData<{ id: string }>(+ await page.request.post('/api/environments/0/containers', {+ data: {+ name,+ image: 'public.ecr.aws/docker/library/busybox:1.37',+ cmd: state === 'running' ? ['sleep', '3600'] : ['true']+ }+ }),+ `Create ${state} container fixture`+ );+ fixtureContainerIds.add(container.id);+ await expect+ .poll(+ async () =>+ (+ await readApiData<{ state: { status: string } }>(+ await page.request.get(`/api/environments/0/containers/${container.id}`),+ 'Read fixture state'+ )+ ).state.status+ )+ .toBe(state);+ containersData.data.push({ id: container.id, names: [name], state });+ }+ await navigateToContainers(page);+ });- const NativeWebSocket = browserWindow.WebSocket;- const containerLogsPathPattern =- /\/api\/environments\/[^/]+\/ws\/containers\/[^/]+\/logs(?:\?.*)?$/;-- class MockContainerLogsWebSocket extends browserWindow.EventTarget {- static CONNECTING = 0;- static OPEN = 1;- static CLOSING = 2;- static CLOSED = 3;-- url: string;- readyState = MockContainerLogsWebSocket.CONNECTING;- bufferedAmount = 0;- extensions = '';- protocol = '';- binaryType = 'blob';- onopen: ((event: unknown) => void) | null = null;- onmessage: ((event: unknown) => void) | null = null;- onerror: ((event: unknown) => void) | null = null;- onclose: ((event: unknown) => void) | null = null;-- constructor(url: string | URL) {- super();- this.url = String(url);-- queueMicrotask(() => {- if (this.readyState !== MockContainerLogsWebSocket.CONNECTING) return;-- this.readyState = MockContainerLogsWebSocket.OPEN;-- const openEvent = new browserWindow.Event('open');- this.dispatchEvent(openEvent);- this.onopen?.(openEvent);-- const messageEvent = new browserWindow.MessageEvent('message', {- data: JSON.stringify(logEntry)- });-- this.dispatchEvent(messageEvent);- this.onmessage?.(messageEvent);- });+ test.afterEach(async ({ page }) => {+ for (const id of fixtureContainerIds) {+ await removeApiResource(+ page,+ `/api/environments/0/containers/${id}?force=true&volumes=false`+ );}+ fixtureContainerIds.clear();+ });- send(_data?: string | ArrayBufferLike | Blob | ArrayBufferView) {}+ test('should display stat cards with correct counts', async ({ page }) => {+ // Aggregate counts can exceed the current page and must not depend on other workers' containers.+ const counts = { totalContainers: 37, runningContainers: 23, stoppedContainers: 14 };+ await page.route(+ (url) => /^\/api\/environments\/[^/]+\/containers$/.test(url.pathname),+ async (route) => {+ const response = await route.fetch();+ const body = (await response.json()) as Record<string, unknown>;+ await route.fulfill({ response, json: { ...body, counts } });+ }+ );- close(code = 1000, reason = '') {- if (this.readyState === MockContainerLogsWebSocket.CLOSED) return;+ await navigateToContainers(page);+ await expect(+ page.getByText(`${counts.totalContainers} Total`, { exact: true })+ ).toBeVisible();+ await expect(+ page.getByText(`${counts.runningContainers} Running`, { exact: true })+ ).toBeVisible();+ await expect(+ page.getByText(`${counts.stoppedContainers} Stopped`, { exact: true })+ ).toBeVisible();+ });- this.readyState = MockContainerLogsWebSocket.CLOSED;+ test('should navigate to container details on Inspect', async ({ page }) => {+ expect(containersData.data.length, 'No containers available').toBeGreaterThan(0);+ await navigateToContainers(page);- const closeEvent = new browserWindow.CloseEvent('close', {- code,- reason,- wasClean: true- });+ const firstRow = page+ .getByRole('row')+ .filter({ has: page.getByRole('button', { name: 'Open menu', exact: true }) })+ .first();+ const menu = await openRowActionsMenu(page, firstRow);+ await menu.getByRole('menuitem', { name: 'Inspect', exact: true }).click();- this.dispatchEvent(closeEvent);- this.onclose?.(closeEvent);- }- }+ await expect(page).toHaveURL(/\/containers\/.+/);+ await expect(page.getByRole('tab', { name: 'Overview', exact: true })).toBeVisible();+ await expect(page.getByRole('heading', { name: 'Runtime', exact: true })).toBeVisible();+ });- const PatchedWebSocket = function (- this: unknown,- url: string | URL,- protocols?: string | string[]- ) {- const urlString = String(url);+ test('should show live CPU and memory monitors on the logs tab for running containers', async ({+ page+ }) => {+ const running = containersData.data.find((c) => c.state === 'running');+ expect(running, 'No running container available').toBeDefined();- if (containerLogsPathPattern.test(urlString)) {- return new MockContainerLogsWebSocket(urlString);- }+ await page.goto(`/containers/${running!.id}`);+ await page.waitForLoadState('load');- return protocols === undefined- ? new NativeWebSocket(url)- : new NativeWebSocket(url, protocols);- } as unknown as typeof WebSocket;-- Object.defineProperties(PatchedWebSocket, {- CONNECTING: { value: NativeWebSocket.CONNECTING },- OPEN: { value: NativeWebSocket.OPEN },- CLOSING: { value: NativeWebSocket.CLOSING },- CLOSED: { value: NativeWebSocket.CLOSED }- });-- PatchedWebSocket.prototype = NativeWebSocket.prototype;- browserWindow.WebSocket = PatchedWebSocket;- }, structuredContainerLog);-}--async function navigateToContainers(page: Page) {- await page.goto(CONTAINERS_ROUTE);- await page.waitForLoadState('load');-}--let containersData: Paginated<ContainerSummary> = { data: [], pagination: { totalItems: 0 } };--const fixtureContainerIds = new Set<string>();--test.describe('Containers Page', () => {- test.beforeEach(async ({ page }) => {- containersData = { data: [] };- for (const state of ['running', 'exited']) {- const name = `e2e-list-${state}-${Date.now()}`;- const container = await readApiData<{ id: string }>(- await page.request.post('/api/environments/0/containers', {- data: {- name,- image: 'public.ecr.aws/docker/library/busybox:1.37',- cmd: state === 'running' ? ['sleep', '3600'] : ['true']- }- }),- `Create ${state} container fixture`- );- fixtureContainerIds.add(container.id);+ await page.getByRole('tab', { name: 'Logs' }).click();++ await expect(page.getByTestId('container-log-cpu-monitor')).toBeVisible();+ await expect(page.getByTestId('container-log-memory-monitor')).toBeVisible();+ await expect(page.getByTestId('container-log-cpu-monitor')).not.toContainText('N/A');+ await expect(page.getByTestId('container-log-memory-monitor')).not.toContainText('N/A');+ });++ test('keeps the parsed log toggle synchronized when structured logs are detected', async ({+ page+ }) => {+ const running = containersData.data.find((container) => container.state === 'running');+ expect(running, 'No running container available').toBeDefined();++ await mockContainerLogsWebSocket(page);+ await page.goto(`/containers/${running!.id}`);+ await page.waitForLoadState('load');+ await page.getByRole('tab', { name: 'Logs' }).click();++ const parsedModeToggle = page.locator('#parsed-log-mode-toggle:visible');+ await expect(parsedModeToggle).toHaveAttribute('aria-checked', 'false');++ await page.getByRole('button', { name: 'Start', exact: true }).first().click();++ await expect(+ page.getByText('structured container log marker', { exact: true }).filter({ visible: true })+ ).toBeVisible();+ await expect(parsedModeToggle).toHaveAttribute('aria-checked', 'true');await expect- .poll(- async () =>- (- await readApiData<{ state: { status: string } }>(- await page.request.get(`/api/environments/0/containers/${container.id}`),- 'Read fixture state'- )- ).state.status- )- .toBe(state);- containersData.data.push({ id: container.id, names: [name], state });- }- await navigateToContainers(page);+ .poll(() => page.evaluate(() => localStorage.getItem('arcane_log_json_parsing_v3')))+ .toBe('false');+ });++ test('should show non-live fallback monitors on the logs tab for stopped containers', async ({+ page+ }) => {+ const stopped = containersData.data.find((c) => c.state !== 'running');+ expect(stopped, 'No stopped container available').toBeDefined();++ await page.goto(`/containers/${stopped!.id}`);+ await page.waitForLoadState('load');++ await page.getByRole('tab', { name: 'Logs' }).click();++ await expect(page.getByTestId('container-log-cpu-monitor')).toBeVisible();+ await expect(page.getByTestId('container-log-memory-monitor')).toBeVisible();+ await expect(page.getByTestId('container-log-cpu-monitor')).toContainText('N/A');+ await expect(page.getByTestId('container-log-memory-monitor')).toContainText('N/A');+ });++ test('downloads the full log history from the logs tab', async ({ page }, testInfo) => {+ const running = containersData.data.find((c) => c.state === 'running');+ expect(running, 'No running container available').toBeDefined();++ await page.goto(`/containers/${running!.id}`);+ await page.waitForLoadState('load');++ await page.getByRole('tab', { name: 'Logs' }).click();++ const downloadPromise = page.waitForEvent('download');+ await page+ .getByRole('button', { name: 'Download', exact: true })+ .filter({ visible: true })+ .click();+ const download = await downloadPromise;+ expect(download.suggestedFilename()).toBe(`container-${running!.id.slice(0, 12)}-logs.log`);+ const downloadPath = testInfo.outputPath(download.suggestedFilename());+ await download.saveAs(downloadPath);+ expect((await stat(downloadPath)).isFile()).toBe(true);+ });++ test('should show correct actions based on container state (without changing state)', async ({+ page+ }) => {+ const running = containersData.data.find((c) => c.state === 'running');+ const stopped = containersData.data.find((c) => c.state !== 'running');++ await navigateToContainers(page);++ expect(running, 'Running container fixture must exist').toBeDefined();+ expect(stopped, 'Stopped container fixture must exist').toBeDefined();+ const runningName = running!.names?.[0]?.replace(/^\/+/, '') ?? running!.id;+ const runningRow = page+ .getByRole('row')+ .filter({ has: page.getByRole('link', { name: runningName, exact: true }) });+ const runningMenu = await openRowActionsMenu(page, runningRow);+ await expect(+ runningMenu.getByRole('menuitem', { name: 'Restart', exact: true })+ ).toBeVisible();+ await expect(runningMenu.getByRole('menuitem', { name: 'Stop', exact: true })).toBeVisible();+ await page.keyboard.press('Escape');++ const stoppedName = stopped!.names?.[0]?.replace(/^\/+/, '') ?? stopped!.id;+ const stoppedRow = page+ .getByRole('row')+ .filter({ has: page.getByRole('link', { name: stoppedName, exact: true }) });+ const stoppedMenu = await openRowActionsMenu(page, stoppedRow);+ await expect(stoppedMenu.getByRole('menuitem', { name: 'Start', exact: true })).toBeVisible();+ await page.keyboard.press('Escape');+ });++ test('should open the Remove dialog from row actions and allow cancel', async ({ page }) => {+ expect(containersData.data.length, 'No containers available').toBeGreaterThan(0);+ const container = containersData.data[0];++ await navigateToContainers(page);++ const containerName = container.names?.[0]?.replace(/^\/+/, '') ?? container.id;+ const row = page+ .getByRole('row')+ .filter({ has: page.getByRole('link', { name: containerName, exact: true }) });+ const menu = await openRowActionsMenu(page, row);+ await menu.getByRole('menuitem', { name: 'Remove', exact: true }).click();++ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();+ await expect(+ dialog.getByRole('heading', { name: 'Confirm Container Removal', exact: true })+ ).toBeVisible();++ await page.getByRole('button', { name: 'Cancel' }).click();+ await expect(dialog).toBeHidden();+ });});- test.afterEach(async ({ page }) => {- for (const id of fixtureContainerIds) {- await removeApiResource(- page,- `/api/environments/0/containers/${id}?force=true&volumes=false`- );- }- fixtureContainerIds.clear();+ test.describe('Containers Page network IP addresses', () => {+ test('should show every network IP address for a multi-network container', async ({+ page,+ context+ }) => {+ await page.addInitScript(() => {+ localStorage.removeItem('arcane-container-table');+ });++ await context.route('**/api/environments/*/containers**', async (route) => {+ if (route.request().method() !== 'GET') {+ await route.continue();+ return;+ }++ const url = new URL(route.request().url());+ if (!/^\/api\/environments\/[^/]+\/containers$/.test(url.pathname)) {+ await route.continue();+ return;+ }++ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: [+ {+ id: 'wordpress-multi-network',+ names: ['/wordpress'],+ image: 'wordpress:latest',+ imageId: 'sha256:wordpress',+ command: 'apache2-foreground',+ created: 1_700_000_000,+ labels: {},+ state: 'running',+ status: 'Up 5 minutes',+ ports: [],+ hostConfig: { networkMode: 'default' },+ networkSettings: {+ networks: {+ proxy: { ipAddress: '172.20.0.10' },+ private: { ipAddress: '10.10.0.5' }+ }+ },+ mounts: []+ }+ ],+ counts: {+ runningContainers: 1,+ stoppedContainers: 0,+ totalContainers: 1+ },+ pagination: {+ totalPages: 1,+ totalItems: 1,+ currentPage: 1,+ itemsPerPage: 20,+ grandTotalItems: 1+ }+ })+ });+ });++ await navigateToContainers(page);++ const row = page.getByRole('row').filter({+ has: page.getByRole('link', { name: 'wordpress', exact: true })+ });++ await expect(row).toContainText('10.10.0.5');+ await expect(row).toContainText('172.20.0.10');+ });});- test('should display the containers page title and description', async ({ page }) => {- await navigateToContainers(page);- await expect(page.getByRole('heading', { name: 'Containers', level: 1 })).toBeVisible();- await expect(page.getByText('View and Manage your Containers').first()).toBeVisible();+ test.describe('Container form', () => {+ test('adds and removes container capabilities without retaining the previous selection', async ({+ page+ }) => {+ await page.goto('/containers/new');+ await page.getByRole('tab', { name: 'Advanced', exact: true }).click();++ const capAdd = page.getByText('Add capabilities', { exact: true }).locator('..');+ const selector = capAdd.getByRole('combobox');+ await selector.click();+ await page.getByRole('option', { name: 'NET_ADMIN', exact: true }).click();++ const badge = capAdd.locator('[data-slot="badge"]').filter({ hasText: 'NET_ADMIN' });+ await expect(badge).toBeVisible();+ await badge.getByRole('button').click();+ await expect(badge).toHaveCount(0);+ await expect(selector).toContainText('Select an option');+ });});+});- test('should display stat cards with correct counts', async ({ page }) => {- // Aggregate counts can exceed the current page and must not depend on other workers' containers.- const counts = { totalContainers: 37, runningContainers: 23, stoppedContainers: 14 };- await page.route(- (url) => /^\/api\/environments\/[^/]+\/containers$/.test(url.pathname),- async (route) => {- const response = await route.fetch();- const body = (await response.json()) as Record<string, unknown>;- await route.fulfill({ response, json: { ...body, counts } });- }+test.describe('Lifecycle', () => {+ const TEST_IMAGE = 'public.ecr.aws/docker/library/busybox:1.37';++ type CreatedContainer = {+ id: string;+ name: string;+ image: string;+ status: string;+ };++ type ContainerDetails = {+ id: string;+ name: string;+ image: string;+ activityId?: string;+ state: {+ status: string;+ running: boolean;+ };+ config: {+ env?: string[];+ cmd?: string[];+ workingDir?: string;+ healthcheck?: {+ test?: string[];+ interval?: number;+ timeout?: number;+ retries?: number;+ };+ };+ hostConfig: {+ restartPolicy?: string;+ };+ networkSettings: {+ networks: Record<string, { aliases?: string[] }>;+ };+ mounts: Array<{+ type: string;+ name?: string;+ source: string;+ destination: string;+ }>;+ ports: Array<{+ privatePort: number;+ publicPort?: number;+ type: string;+ }>;+ labels?: Record<string, string>;+ };++ type ActivityDetail = {+ activity: {+ id: string;+ type: string;+ status: string;+ error?: string;+ };+ };++ type ActionResult = {+ message?: string;+ activityId?: string;+ };++ type CommitResult = {+ id: string;+ };++ type CreatedProject = {+ id: string;+ name: string;+ };++ type ContainerCreatePayload = {+ name: string;+ image: string;+ cmd?: string[];+ workingDir?: string;+ env?: string[];+ labels?: Record<string, string>;+ healthcheck?: {+ test?: string[];+ interval?: number;+ timeout?: number;+ retries?: number;+ };+ hostConfig?: {+ binds?: string[];+ portBindings?: Record<string, Array<{ hostIp?: string; hostPort?: string }>>;+ restartPolicy?: { name: string; maximumRetryCount?: number };+ };+ networkingConfig?: {+ endpointsConfig?: Record<string, { aliases?: string[] }>;+ };+ };++ async function updateExperimentalFeatures(page: Page, enabled: string) {+ const response = await page.request.put('/api/environments/0/settings', {+ data: { experimentalFeaturesEnabled: enabled }+ });+ if (!response.ok()) {+ throw new Error(+ `Update experimentalFeaturesEnabled failed with ${response.status()}: ${await response.text()}`+ );+ }+ const settingsResponse = await page.request.get('/api/environments/0/settings');+ expect(settingsResponse.ok(), 'Read back experimental feature setting').toBe(true);+ const settings = (await settingsResponse.json()) as Array<{ key: string; value: string }>;+ expect(settings).toContainEqual(+ expect.objectContaining({ key: 'experimentalFeaturesEnabled', value: enabled }));+ }- await navigateToContainers(page);- await expect(page.getByText(`${counts.totalContainers} Total`, { exact: true })).toBeVisible();- await expect(- page.getByText(`${counts.runningContainers} Running`, { exact: true })- ).toBeVisible();- await expect(- page.getByText(`${counts.stoppedContainers} Stopped`, { exact: true })- ).toBeVisible();- });+ async function getContainer(page: Page, containerId: string): Promise<ContainerDetails> {+ return readApiData<ContainerDetails>(+ await page.request.get(`/api/environments/0/containers/${containerId}`),+ `Get container ${containerId}`+ );+ }- test('should display the container table with columns', async ({ page }) => {- await navigateToContainers(page);- await expect(page.getByRole('table')).toBeVisible();- await expect(page.getByRole('button', { name: 'Name' })).toBeVisible();- await expect(page.getByRole('button', { name: 'Image', exact: true })).toBeVisible();- await expect(page.getByRole('button', { name: 'State' })).toBeVisible();- await expect(page.getByRole('button', { name: 'Created' })).toBeVisible();- });+ async function expectContainerStatus(page: Page, containerId: string, status: string) {+ await expect+ .poll(async () => (await getContainer(page, containerId)).state.status, {+ message: `Expected container ${containerId} to reach ${status}`,+ timeout: 20_000+ })+ .toBe(status);+ }++ async function expectContainerMissing(page: Page, containerId: string) {+ await expect+ .poll(+ async () =>+ (await page.request.get(`/api/environments/0/containers/${containerId}`)).status(),+ { message: `Expected container ${containerId} to be removed`, timeout: 20_000 }+ )+ .toBe(404);+ }++ async function expectActivitySucceeded(page: Page, activityId: string, expectedType: string) {+ await expect+ .poll(+ async () => {+ const detail = await readApiData<ActivityDetail>(+ await page.request.get(`/api/environments/0/activities/${activityId}`),+ `Get activity ${activityId}`+ );+ return detail.activity.status;+ },+ { message: `Expected ${expectedType} activity ${activityId} to succeed`, timeout: 20_000 }+ )+ .toBe('success');+ const detail = await readApiData<ActivityDetail>(+ await page.request.get(`/api/environments/0/activities/${activityId}`),+ `Get completed activity ${activityId}`+ );+ expect(detail.activity.type).toBe(expectedType);+ expect(detail.activity.error).toBeFalsy();+ }++ // Header actions render inline or inside the "More actions" menu depending on placement.+ async function clickHeaderAction(page: Page, name: string) {+ const header = page.locator('[data-tabs-root] > :not([inert])');+ const inline = header+ .getByRole('button', { name, exact: true })+ .or(header.getByRole('link', { name, exact: true }))+ .filter({ visible: true })+ .first();+ const menuTrigger = header+ .getByRole('button', { name: 'More actions', exact: true })+ .filter({ visible: true })+ .first();+ const inlineVisible = await inline+ .waitFor({ state: 'visible', timeout: 5_000 })+ .then(() => true)+ .catch(() => false);+ if (inlineVisible) {+ await inline.click();+ return;+ }+ await menuTrigger.click();+ await page.getByRole('menuitem', { name, exact: true }).click();+ }++ async function runSimpleContainerAction(+ page: Page,+ containerId: string,+ pathAction: string,+ buttonName: string,+ expectedActivityType: string+ ) {+ return test.step(`${buttonName} container`, async () => {+ const responseTimeout = pathAction === 'stop' ? 120_000 : 60_000;+ const matchesActionRequest = (url: string, method: string) => {+ const pathname = new URL(url).pathname.replace(/\/$/, '');+ return method === 'POST' && pathname.endsWith(`/containers/${containerId}/${pathAction}`);+ };+ const requestPromise = page.waitForRequest(+ (request) => matchesActionRequest(request.url(), request.method()),+ { timeout: 30_000 }+ );+ const responsePromise = page.waitForResponse(+ (response) => matchesActionRequest(response.url(), response.request().method()),+ { timeout: responseTimeout }+ );+ await clickHeaderAction(page, buttonName);+ await requestPromise;+ const result = await readApiData<ActionResult>(+ await responsePromise,+ `${buttonName} container ${containerId}`+ );+ expect(result.activityId, `${buttonName} must return an activity ID`).toBeTruthy();+ await expectActivitySucceeded(page, result.activityId!, expectedActivityType);+ });+ }- test('should navigate to container details on Inspect', async ({ page }) => {- expect(containersData.data.length, 'No containers available').toBeGreaterThan(0);- await navigateToContainers(page);+ async function selectSearchableOption(page: Page, scope: Locator, option: string) {+ await scope.getByRole('combobox').filter({ visible: true }).first().click();+ await page.getByRole('option', { name: option, exact: true }).click();+ }- const firstRow = page- .getByRole('row')- .filter({ has: page.getByRole('button', { name: 'Open menu', exact: true }) })+ function formGroup(page: Page, heading: string) {+ return page+ .locator('div.space-y-4')+ .filter({ has: page.getByRole('heading', { name: heading, exact: true }) }).first();- const menu = await openRowActionsMenu(page, firstRow);- await menu.getByRole('menuitem', { name: 'Inspect', exact: true }).click();+ }++ async function createContainerThroughUI(+ page: Page,+ containerName: string,+ volumeName: string,+ networkName: string,+ containerIds: Set<string>+ ) {+ return test.step('Create container', async () => {+ await page.goto('/containers/new');+ await page.getByRole('button', { name: 'Create Container', exact: true }).click();+ await expect(page.getByText('Container name is required', { exact: true })).toBeVisible();+ await expect(page.getByText('Image is required', { exact: true })).toBeVisible();++ await page.getByLabel('Container Name *', { exact: true }).fill(containerName);+ await page.getByLabel('Image *', { exact: true }).fill(TEST_IMAGE);+ await page.getByLabel('Command', { exact: true }).fill('sleep 3600');+ await page.getByLabel('Working Directory', { exact: true }).fill('/tmp');++ await page.getByRole('tab', { name: 'Environment', exact: true }).click();+ const environmentGroup = formGroup(page, 'Environment Variables');+ await environmentGroup.getByRole('button', { name: 'Add', exact: true }).click();+ await environmentGroup.getByPlaceholder('KEY').fill('E2E_VALUE');+ await environmentGroup.getByPlaceholder('value').fill('initial');++ const labelsGroup = formGroup(page, 'Labels');+ await labelsGroup.getByRole('button', { name: 'Add', exact: true }).click();+ await labelsGroup.getByPlaceholder('com.example.key').fill('arcane.e2e');+ await labelsGroup.getByPlaceholder('value').fill('container-lifecycle');++ await page.getByRole('tab', { name: 'Ports', exact: true }).click();+ await page.getByRole('button', { name: 'Add', exact: true }).click();+ await page.getByPlaceholder('0.0.0.0').fill('127.0.0.1');+ await page.getByPlaceholder('80', { exact: true }).fill('8080');++ await page.getByRole('tab', { name: 'Volumes', exact: true }).click();+ await page.getByRole('button', { name: 'Add Volume Mount', exact: true }).click();+ await selectSearchableOption(page, page.getByRole('tabpanel'), volumeName);+ await page.getByPlaceholder('Container path').fill('/data');++ await page.getByRole('tab', { name: 'Networks', exact: true }).click();+ await page.getByRole('button', { name: 'Add', exact: true }).click();+ await selectSearchableOption(page, page.getByRole('tabpanel'), networkName);+ await page.getByPlaceholder('Aliases').fill('lifecycle-alias');++ await page.getByRole('tab', { name: 'Advanced', exact: true }).click();+ await page.locator('#restart-policy').click();+ await page.getByRole('option', { name: 'On Failure', exact: true }).click();+ await page.getByLabel('Maximum Retries', { exact: true }).fill('3');+ await page.locator('#health-mode').click();+ await page.getByRole('option', { name: 'Custom', exact: true }).click();+ await page.getByLabel('Test Command', { exact: true }).fill('test "$E2E_VALUE" = "initial"');+ await page.getByLabel('Interval (s)', { exact: true }).fill('2');+ await page.getByLabel('Timeout (s)', { exact: true }).fill('1');+ await page.getByLabel('Retries', { exact: true }).fill('2');++ const requestPromise = page.waitForRequest(+ (request) =>+ request.method() === 'POST' &&+ new URL(request.url()).pathname === '/api/environments/0/containers'+ );+ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/environments/0/containers'+ );+ await page.getByRole('button', { name: 'Create Container', exact: true }).click();- await expect(page).toHaveURL(/\/containers\/.+/);- await expect(page.getByRole('tab', { name: 'Overview', exact: true })).toBeVisible();- await expect(page.getByRole('heading', { name: 'Runtime', exact: true })).toBeVisible();- });+ const request = await requestPromise;+ const payload = request.postDataJSON() as ContainerCreatePayload;+ const created = await readApiData<CreatedContainer>(+ await responsePromise,+ `Create container ${containerName}`+ );+ containerIds.add(created.id);+ await expect(page).toHaveURL((url) => url.pathname === `/containers/${created.id}`);++ expect(payload).toMatchObject({+ name: containerName,+ image: TEST_IMAGE,+ cmd: ['sleep', '3600'],+ workingDir: '/tmp',+ env: ['E2E_VALUE=initial'],+ labels: { 'arcane.e2e': 'container-lifecycle' },+ healthcheck: {+ test: ['CMD-SHELL', 'test "$E2E_VALUE" = "initial"'],+ interval: 2,+ timeout: 1,+ retries: 2+ },+ hostConfig: {+ binds: [`${volumeName}:/data`],+ portBindings: {+ '8080/tcp': [{ hostIp: '127.0.0.1', hostPort: '' }]+ },+ restartPolicy: { name: 'on-failure', maximumRetryCount: 3 }+ },+ networkingConfig: {+ endpointsConfig: {+ [networkName]: { aliases: ['lifecycle-alias'] }+ }+ }+ });- test('should show live CPU and memory monitors on the logs tab for running containers', async ({- page+ return created;+ });+ }++ async function verifyShell(page: Page, marker: string) {+ return test.step('Verify shell and volume', async () => {+ await page.getByRole('tab', { name: 'Shell', exact: true }).click();+ await expect(page.getByText('Live', { exact: true })).toBeVisible({ timeout: 15_000 });++ const terminal = page.locator('.terminal-container');+ const input = terminal.locator('textarea.xterm-helper-textarea');+ await expect(input).toBeAttached();+ await input.pressSequentially(+ `echo ${marker}-$E2E_VALUE && echo volume-ok > /data/e2e-marker && cat /data/e2e-marker`,+ { delay: 5 }+ );+ await input.press('Enter');+ await expect(terminal.locator('.xterm-rows')).toContainText(`${marker}-initial`, {+ timeout: 15_000+ });+ await expect(terminal.locator('.xterm-rows')).toContainText('volume-ok');+ });+ }++ async function connectAndDisconnectNetwork(page: Page, containerId: string, networkName: string) {+ return test.step('Connect and disconnect network', async () => {+ await page.getByRole('tab', { name: 'Networks', exact: true }).click();+ const connectSection = page.locator('div').filter({+ has: page.getByRole('heading', { name: 'Connect to network', exact: true })+ });+ await selectSearchableOption(page, connectSection, networkName);+ await connectSection.getByPlaceholder('Aliases').fill('attached-live');++ const connectResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ /\/api\/environments\/0\/networks\/[^/]+\/connect$/.test(new URL(response.url()).pathname)+ );+ await connectSection.getByRole('button', { name: 'Connect', exact: true }).click();+ expect((await connectResponsePromise).ok()).toBe(true);+ await expect+ .poll(async () =>+ Object.keys((await getContainer(page, containerId)).networkSettings.networks)+ )+ .toContain(networkName);++ const networkCard = page+ .locator('[data-slot="card"]')+ .filter({ has: page.getByText(networkName, { exact: true }) })+ .filter({ has: page.getByRole('button', { name: 'Disconnect', exact: true }) })+ .last();+ await networkCard.getByRole('button', { name: 'Disconnect', exact: true }).click();+ const disconnectResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ /\/api\/environments\/0\/networks\/[^/]+\/disconnect$/.test(+ new URL(response.url()).pathname+ )+ );+ await page+ .getByRole('dialog')+ .getByRole('button', { name: 'Disconnect', exact: true })+ .click();+ expect((await disconnectResponsePromise).ok()).toBe(true);+ await expect(page.getByRole('dialog')).toBeHidden();+ await expect(page.locator('[data-dialog-overlay]')).toHaveCount(0);+ await expect+ .poll(async () =>+ Object.keys((await getContainer(page, containerId)).networkSettings.networks)+ )+ .not.toContain(networkName);+ });+ }++ async function commitContainer(+ page: Page,+ containerId: string,+ containerName: string,+ repository: string,+ imageIds: Set<string>+ ) {+ return test.step('Commit image', async () => {+ await clickHeaderAction(page, 'Commit');+ const dialog = page.getByRole('dialog', { name: `Commit "${containerName}"` });+ await waitForDialogReady(dialog);+ await expect(dialog.locator('#repository')).toBeFocused();+ await dialog.locator('#repository').fill(repository);+ await dialog.locator('#tag').fill('e2e');+ await dialog.getByLabel('Description', { exact: true }).fill('Playwright lifecycle snapshot');+ await dialog.getByLabel('Author', { exact: true }).fill('Arcane Playwright');+ await expect(dialog.locator('#repository')).toHaveValue(repository);+ await expect(dialog.locator('#tag')).toHaveValue('e2e');+ await expect(dialog.getByLabel('Description', { exact: true })).toHaveValue(+ 'Playwright lifecycle snapshot'+ );+ await expect(dialog.getByLabel('Author', { exact: true })).toHaveValue('Arcane Playwright');++ const requestPromise = page.waitForRequest(+ (request) =>+ request.method() === 'POST' &&+ new URL(request.url()).pathname === `/api/environments/0/containers/${containerId}/commit`+ );+ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname ===+ `/api/environments/0/containers/${containerId}/commit`+ );+ await dialog.getByRole('button', { name: 'Commit', exact: true }).click();+ const request = await requestPromise;+ const result = await readApiData<CommitResult>(+ await responsePromise,+ `Commit container ${containerId}`+ );+ imageIds.add(result.id);+ expect(request.postDataJSON()).toMatchObject({+ repository,+ tag: 'e2e',+ comment: 'Playwright lifecycle snapshot',+ author: 'Arcane Playwright'+ });+ expect(result.id).toMatch(/^sha256:/);+ await expect(dialog).toBeHidden();+ return result;+ });+ }++ async function editContainerThroughUI(+ page: Page,+ containerId: string,+ newContainerName: string,+ containerIds: Set<string>+ ) {+ return test.step('Edit and recreate container', async () => {+ await clickHeaderAction(page, 'Edit');+ await expect(page).toHaveURL(`/containers/${containerId}/edit`);+ await expect(page.getByText('Applying changes recreates this container.')).toBeVisible();+ await expect(page.getByLabel('Container Name *', { exact: true })).toHaveValue(+ newContainerName.replace(/-edited$/, '')+ );+ await expect(page.getByLabel('Command', { exact: true })).toHaveValue('sleep 3600');++ await page.getByLabel('Container Name *', { exact: true }).fill(newContainerName);+ await page.getByLabel('Command', { exact: true }).fill('sleep 7200');+ await page.getByRole('tab', { name: 'Environment', exact: true }).click();+ const environmentGroup = formGroup(page, 'Environment Variables');+ const environmentKeys = environmentGroup.getByPlaceholder('KEY');+ const customEnvironmentIndex = await environmentKeys.evaluateAll((inputs) =>+ inputs.findIndex((input) => (input as HTMLInputElement).value === 'E2E_VALUE')+ );+ expect(customEnvironmentIndex).toBeGreaterThanOrEqual(0);+ const customEnvironmentRow = environmentKeys.nth(customEnvironmentIndex).locator('..');+ await customEnvironmentRow.getByPlaceholder('value').fill('edited');++ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === `/api/environments/0/containers/${containerId}/edit`,+ { timeout: 60_000 }+ );+ await page.getByRole('button', { name: 'Save', exact: true }).click();+ const dialog = page.getByRole('dialog', { name: 'Recreate container?' });+ await dialog.getByRole('button', { name: 'Save', exact: true }).click();+ const edited = await readApiData<ContainerDetails>(+ await responsePromise,+ `Edit container ${containerId}`+ );+ containerIds.add(edited.id);+ await expect(page).toHaveURL((url) => url.pathname === `/containers/${edited.id}`);+ expect(edited.id).not.toBe(containerId);+ expect(edited.activityId).toBeTruthy();+ await expectActivitySucceeded(page, edited.activityId!, 'container_edit');+ return edited;+ });+ }++ async function redeployContainerThroughUI(+ page: Page,+ containerId: string,+ containerIds: Set<string>+ ) {+ return test.step('Redeploy container', async () => {+ await clickHeaderAction(page, 'Redeploy');+ const dialog = page.getByRole('dialog');+ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname ===+ `/api/environments/0/containers/${containerId}/redeploy`,+ { timeout: 60_000 }+ );+ await dialog.getByRole('button', { name: 'Redeploy', exact: true }).click();+ const redeployed = await readApiData<ContainerDetails>(+ await responsePromise,+ `Redeploy container ${containerId}`+ );+ containerIds.add(redeployed.id);+ await expect(page).toHaveURL((url) => url.pathname === `/containers/${redeployed.id}`);+ expect(redeployed.id).not.toBe(containerId);+ expect(redeployed.activityId).toBeTruthy();+ await expectActivitySucceeded(page, redeployed.activityId!, 'container_redeploy');+ return redeployed;+ });+ }++ async function convertContainerToProject(+ page: Page,+ containerId: string,+ containerName: string,+ projectIds: Set<string>+ ) {+ return test.step('Convert to Compose', async () => {+ const generateResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/environments/0/containers/generate-compose'+ );+ await clickHeaderAction(page, 'Convert to Compose');+ const generated = await readApiData<{ composeContent: string }>(+ await generateResponsePromise,+ `Generate Compose for ${containerId}`+ );+ expect(generated.composeContent).toContain(containerName);+ await expect(page).toHaveURL(`/projects/new?fromContainers=${containerId}&fromEnv=0`);+ await expect(page.locator('.cm-editor').first()).toContainText(containerName);++ const createButton = page.locator('button[data-action="create"]');+ await expect(createButton).toBeEnabled({ timeout: 15_000 });+ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/environments/0/projects'+ );+ await createButton.click();+ const dialog = page.getByRole('dialog');+ await expect(+ dialog.getByLabel('Remove original container(s) after creation')+ ).not.toBeChecked();+ await dialog.getByRole('button', { name: 'Create Project', exact: true }).click();+ const project = await readApiData<CreatedProject>(+ await responsePromise,+ `Create converted project for ${containerId}`+ );+ projectIds.add(project.id);+ await expect(page).toHaveURL((url) => url.pathname === `/projects/${project.id}`);+ return project;+ });+ }++ async function killContainerThroughUI(page: Page, containerId: string, containerName: string) {+ return test.step('Kill container', async () => {+ await clickHeaderAction(page, 'Kill');+ const dialog = page.getByRole('dialog', { name: `Kill "${containerName}"` });+ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === `/api/environments/0/containers/${containerId}/kill`+ );+ await dialog.getByRole('button', { name: 'Kill container', exact: true }).click();+ const result = await readApiData<ActionResult>(+ await responsePromise,+ `Kill container ${containerId}`+ );+ expect(result.activityId).toBeTruthy();+ await expectActivitySucceeded(page, result.activityId!, 'container_kill');+ });+ }++ async function removeContainerThroughUI(page: Page, containerId: string) {+ return test.step('Remove container', async () => {+ await clickHeaderAction(page, 'Remove');+ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'DELETE' &&+ new URL(response.url()).pathname === `/api/environments/0/containers/${containerId}`+ );+ await page.getByRole('dialog').getByRole('button', { name: 'Remove', exact: true }).click();+ const result = await readApiData<ActionResult>(+ await responsePromise,+ `Remove container ${containerId}`+ );+ expect(result.activityId).toBeTruthy();+ await expectActivitySucceeded(page, result.activityId!, 'container_delete');+ await expect(page).toHaveURL('/containers');+ });+ }++ test('creates, mutates, converts, and removes a standalone container', async ({+ page,+ registerCleanup}) => {- const running = containersData.data.find((c) => c.state === 'running');- expect(running, 'No running container available').toBeDefined();+ test.setTimeout(300_000);+ page.setDefaultTimeout(15_000);+ page.setDefaultNavigationTimeout(20_000);++ const suffix = Date.now().toString(36);+ const containerName = `e2e-container-${suffix}`;+ const editedContainerName = `${containerName}-edited`;+ const volumeName = `e2e-volume-${suffix}`;+ const primaryNetworkName = `e2e-network-primary-${suffix}`;+ const secondaryNetworkName = `e2e-network-secondary-${suffix}`;+ const committedRepository = `arcane-e2e/${containerName}`;+ let currentContainerId: string | null = null;+ let committedImageId: string | null = null;+ const containerIds = new Set<string>();+ const imageIds = new Set<string>();+ const projectIds = new Set<string>();+ let settingsChanged = false;+ let originalExperimentalSetting = 'false';++ registerCleanup(async () => {+ for (const id of projectIds)+ await removeApiResource(page, `/api/environments/0/projects/${id}/destroy`, {+ data: { removeVolumes: false }+ });+ for (const id of containerIds)+ await removeApiResource(+ page,+ `/api/environments/0/containers/${id}?force=true&volumes=false`+ );+ for (const id of imageIds)+ await removeApiResource(+ page,+ `/api/environments/0/images/${encodeURIComponent(id)}?force=true`+ );+ for (const name of [secondaryNetworkName, primaryNetworkName])+ await removeApiResource(page, `/api/environments/0/networks/${encodeURIComponent(name)}`);+ await removeApiResource(+ page,+ `/api/environments/0/volumes/${encodeURIComponent(volumeName)}?force=true`+ );+ if (settingsChanged) await updateExperimentalFeatures(page, originalExperimentalSetting);+ });- await page.goto(`/containers/${running!.id}`);- await page.waitForLoadState('load');+ const settingsResponse = await page.request.get('/api/environments/0/settings');+ if (!settingsResponse.ok()) {+ throw new Error(`Get settings failed with ${settingsResponse.status()}`);+ }+ const settings = (await settingsResponse.json()) as Array<{ key: string; value: string }>;+ const experimentalSetting = settings.find(+ (setting) => setting.key === 'experimentalFeaturesEnabled'+ );+ expect(experimentalSetting, 'Experimental feature setting must be present').toBeDefined();+ originalExperimentalSetting = experimentalSetting!.value;+ settingsChanged = true;+ await updateExperimentalFeatures(page, 'true');++ await readApiData(+ await page.request.post('/api/environments/0/volumes', {+ data: { name: volumeName, driver: 'local' }+ }),+ `Create volume ${volumeName}`+ );+ for (const networkName of [primaryNetworkName, secondaryNetworkName]) {+ await readApiData(+ await page.request.post('/api/environments/0/networks', {+ data: { name: networkName, options: { driver: 'bridge' } }+ }),+ `Create network ${networkName}`+ );+ }- await page.getByRole('tab', { name: 'Logs' }).click();+ const created = await createContainerThroughUI(+ page,+ containerName,+ volumeName,+ primaryNetworkName,+ containerIds+ );+ currentContainerId = created.id;++ let details = await getContainer(page, currentContainerId);+ expect(details.name).toBe(containerName);+ expect(details.image).toBe(TEST_IMAGE);+ expect(details.state.status).toBe('running');+ expect(details.config.cmd).toEqual(['sleep', '3600']);+ expect(details.config.workingDir).toBe('/tmp');+ expect(details.config.env).toContain('E2E_VALUE=initial');+ expect(details.config.healthcheck?.test).toEqual([+ 'CMD-SHELL',+ 'test "$E2E_VALUE" = "initial"'+ ]);+ expect(details.config.healthcheck?.interval).toBe(2_000_000_000);+ expect(details.hostConfig.restartPolicy).toBe('on-failure');+ expect(details.labels?.['arcane.e2e']).toBe('container-lifecycle');+ expect(details.ports.some((port) => port.privatePort === 8080 && port.type === 'tcp')).toBe(+ true+ );+ expect(details.mounts).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ type: 'volume', name: volumeName, destination: '/data' })+ ])+ );+ expect(details.networkSettings.networks[primaryNetworkName]?.aliases).toContain(+ 'lifecycle-alias'+ );- await expect(page.getByTestId('container-log-cpu-monitor')).toBeVisible();- await expect(page.getByTestId('container-log-memory-monitor')).toBeVisible();- await expect(page.getByTestId('container-log-cpu-monitor')).not.toContainText('N/A');- await expect(page.getByTestId('container-log-memory-monitor')).not.toContainText('N/A');+ await verifyShell(page, `shell-${suffix}`);+ await page.getByRole('tab', { name: 'Overview', exact: true }).click();++ await runSimpleContainerAction(page, currentContainerId, 'pause', 'Pause', 'container_pause');+ await expectContainerStatus(page, currentContainerId, 'paused');+ await runSimpleContainerAction(+ page,+ currentContainerId,+ 'unpause',+ 'Unpause',+ 'container_unpause'+ );+ await expectContainerStatus(page, currentContainerId, 'running');+ await runSimpleContainerAction(+ page,+ currentContainerId,+ 'restart',+ 'Restart',+ 'container_restart'+ );+ await expectContainerStatus(page, currentContainerId, 'running');+ await runSimpleContainerAction(page, currentContainerId, 'stop', 'Stop', 'container_stop');+ await expectContainerStatus(page, currentContainerId, 'exited');+ await runSimpleContainerAction(page, currentContainerId, 'start', 'Start', 'container_start');+ await expectContainerStatus(page, currentContainerId, 'running');++ await connectAndDisconnectNetwork(page, currentContainerId, secondaryNetworkName);++ const commit = await commitContainer(+ page,+ currentContainerId,+ containerName,+ committedRepository,+ imageIds+ );+ committedImageId = commit.id;+ const committedImageResponse = await page.request.get(+ `/api/environments/0/images/${encodeURIComponent(committedImageId)}`+ );+ expect(committedImageResponse.ok()).toBe(true);++ const oldContainerId = currentContainerId;+ const edited = await editContainerThroughUI(+ page,+ currentContainerId,+ editedContainerName,+ containerIds+ );+ currentContainerId = edited.id;+ await expectContainerMissing(page, oldContainerId);+ details = await getContainer(page, currentContainerId);+ expect(details.name).toBe(editedContainerName);+ expect(details.config.cmd).toEqual(['sleep', '7200']);+ expect(details.config.env).toContain('E2E_VALUE=edited');+ expect(details.mounts.some((mount) => mount.name === volumeName)).toBe(true);+ expect(details.ports.some((port) => port.privatePort === 8080)).toBe(true);+ expect(details.networkSettings.networks).toHaveProperty(primaryNetworkName);++ const preRedeployId = currentContainerId;+ const redeployed = await redeployContainerThroughUI(page, currentContainerId, containerIds);+ currentContainerId = redeployed.id;+ await expectContainerMissing(page, preRedeployId);+ await expectContainerStatus(page, currentContainerId, 'running');++ const convertedProject = await convertContainerToProject(+ page,+ currentContainerId,+ editedContainerName,+ projectIds+ );+ expect(projectIds.has(convertedProject.id)).toBe(true);+ expect(+ (await page.request.get(`/api/environments/0/containers/${currentContainerId}`)).ok()+ ).toBe(true);++ await page.goto(`/containers/${currentContainerId}`);+ await killContainerThroughUI(page, currentContainerId, editedContainerName);+ await expectContainerStatus(page, currentContainerId, 'exited');+ await runSimpleContainerAction(page, currentContainerId, 'start', 'Start', 'container_start');+ await expectContainerStatus(page, currentContainerId, 'running');+ await runSimpleContainerAction(page, currentContainerId, 'stop', 'Stop', 'container_stop');+ await expectContainerStatus(page, currentContainerId, 'exited');++ await removeContainerThroughUI(page, currentContainerId);+ await expectContainerMissing(page, currentContainerId);+ currentContainerId = null;});+});- test('keeps the parsed log toggle synchronized when structured logs are detected', async ({- page- }) => {- const running = containersData.data.find((container) => container.state === 'running');- expect(running, 'No running container available').toBeDefined();+test.describe('Resource sorting', () => {+ type MockSample = {+ cpuPercent: number;+ memoryUsageBytes: number;+ memoryLimitBytes: number;+ sampleTime: string;+ };++ type MockContainer = {+ id: string;+ names: string[];+ image: string;+ imageId: string;+ command: string;+ created: number;+ labels: Record<string, string>;+ state: string;+ status: string;+ ports: [];+ hostConfig: { networkMode: string };+ networkSettings: { networks: Record<string, unknown> };+ mounts: [];+ resourceSample?: MockSample | null;+ };++ const MiB = 1024 * 1024;+ const GiB = 1024 * MiB;++ function createSortContainer(+ id: string,+ created: number,+ sample: MockSample | null+ ): MockContainer {+ return {+ id,+ names: [`/${id}`],+ image: 'misc:latest',+ imageId: `image-${id}`,+ command: '',+ created,+ labels: {},+ state: 'running',+ status: 'Up 5 minutes',+ ports: [],+ hostConfig: { networkMode: 'default' },+ networkSettings: { networks: {} },+ mounts: [],+ resourceSample: sample+ };+ }++ function sample(+ cpuPercent: number,+ memoryUsageBytes: number,+ memoryLimitBytes: number+ ): MockSample {+ return { cpuPercent, memoryUsageBytes, memoryLimitBytes, sampleTime: new Date().toISOString() };+ }++ // Default order is created desc: small, high-percent, big-bytes, broken.+ // Memory-bytes desc: big-bytes (3GiB), high-percent (800MiB), small (100MiB), broken.+ // Memory-percent desc would put high-percent (80%) first: the two orders differ.+ function basicFixtures() {+ return [+ createSortContainer('small', 400, sample(5, 100 * MiB, 8 * GiB)),+ createSortContainer('high-percent', 300, sample(50, 800 * MiB, 1 * GiB)),+ createSortContainer('big-bytes', 200, sample(10, 3 * GiB, 4 * GiB)),+ createSortContainer('broken', 100, null)+ ];+ }++ // Twelve fixtures in created-desc order so page size 10 leaves the two+ // heaviest containers off the default first page: they enter it once sorted+ // by memory desc.+ function pagedFixtures() {+ const items: MockContainer[] = [];+ for (let i = 0; i < 10; i++) {+ items.push(createSortContainer(`filler-${i}`, 20 - i, sample(i, (10 + i) * MiB, 8 * GiB)));+ }+ items.push(createSortContainer('offpage-heavy2', 2, sample(2, 4 * GiB, 8 * GiB)));+ items.push(createSortContainer('offpage-heavy', 1, sample(1, 5 * GiB, 8 * GiB)));+ return items;+ }++ type Scenario = {+ supported: boolean;+ fixtures: () => MockContainer[];+ failList?: boolean;+ requests: string[];+ };++ function installContainersMock(page: Page, scenario: Scenario) {+ return page.context().route('**/containers**', async (route) => {+ if (route.request().method() !== 'GET') {+ await route.continue();+ return;+ }+ const url = new URL(route.request().url());+ if (!/^\/api\/environments\/[^/]+\/containers$/.test(url.pathname)) {+ await route.continue();+ return;+ }+ if (scenario.failList) {+ await route.fulfill({+ status: 500,+ contentType: 'application/json',+ body: JSON.stringify({ success: false, data: { error: 'daemon exploded' } })+ });+ return;+ }- await mockContainerLogsWebSocket(page);- await page.goto(`/containers/${running!.id}`);+ scenario.requests.push(url.search);+ const sort = url.searchParams.get('sort') ?? '';+ const order = url.searchParams.get('order') ?? 'asc';+ const start = Number(url.searchParams.get('start') ?? '0');+ const limit = Number(url.searchParams.get('limit') ?? '20');++ let items = scenario.fixtures();+ const valueOf = (c: MockContainer) => {+ if (!c.resourceSample) return null;+ return sort === 'cpuUsage'+ ? c.resourceSample.cpuPercent+ : c.resourceSample.memoryUsageBytes;+ };+ if (sort === 'cpuUsage' || sort === 'memoryUsage') {+ items = [...items].sort((a, b) => {+ const va = valueOf(a);+ const vb = valueOf(b);+ if (va === null && vb === null) return a.id.localeCompare(b.id);+ if (va === null) return 1;+ if (vb === null) return -1;+ if (va === vb) return a.id.localeCompare(b.id);+ return order === 'desc' ? vb - va : va - vb;+ });+ }++ const safeLimit = limit > 0 ? limit : items.length;+ const pageItems = items.slice(start, start + safeLimit);++ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: pageItems,+ counts: {+ runningContainers: items.length,+ stoppedContainers: 0,+ totalContainers: items.length+ },+ pagination: {+ totalPages: Math.max(1, Math.ceil(items.length / safeLimit)),+ totalItems: items.length,+ currentPage: Math.floor(start / safeLimit) + 1,+ itemsPerPage: safeLimit,+ grandTotalItems: items.length+ },+ ...(scenario.supported ? { resourceSortSupported: true } : {})+ })+ });+ });+ }++ async function openContainers(page: Page) {+ await page.addInitScript(() => {+ localStorage.removeItem('selectedEnvironmentId');+ localStorage.removeItem('arcane-container-table');+ });+ await page.goto('/containers');await page.waitForLoadState('load');- await page.getByRole('tab', { name: 'Logs' }).click();+ await page.setViewportSize({ width: 1440, height: 900 });+ }- const parsedModeToggle = page.locator('#parsed-log-mode-toggle:visible');- await expect(parsedModeToggle).toHaveAttribute('aria-checked', 'false');+ function rowIds(page: Page) {+ return page+ .getByRole('row')+ .filter({ has: page.locator('a[href^="/containers/"]') })+ .locator('a[href^="/containers/"]')+ .evaluateAll((els) => els.map((el) => el.getAttribute('href')?.split('/').pop() ?? ''));+ }++ async function setPageSize(page: Page, size: string) {+ // The rows-per-page control is a bits-ui Select trigger, which renders as a plain+ // button rather than a combobox.+ await page.locator('[data-slot="select-trigger"]').filter({ visible: true }).first().click();+ await page.getByRole('option', { name: size, exact: true }).click();+ }++ async function sortByHeader(page: Page, name: string, direction: 'asc' | 'desc') {+ // The sortable header button opens a menu; the direction is chosen from it.+ await page.getByRole('columnheader', { name, exact: true }).getByRole('button').click();+ await page+ .getByRole('menuitem', { name: direction === 'desc' ? 'Desc' : 'Asc', exact: true })+ .click();+ }- await page.getByRole('button', { name: 'Start', exact: true }).first().click();+ test('memory sort orders globally by bytes and renders matching samples', async ({ page }) => {+ const scenario: Scenario = { supported: true, fixtures: basicFixtures, requests: [] };+ await installContainersMock(page, scenario);+ await openContainers(page);- await expect(- page.getByText('structured container log marker', { exact: true }).filter({ visible: true })- ).toBeVisible();- await expect(parsedModeToggle).toHaveAttribute('aria-checked', 'true');- await expect- .poll(() => page.evaluate(() => localStorage.getItem('arcane_log_json_parsing_v3')))- .toBe('false');- });+ await expect(page.getByRole('row').filter({ hasText: 'small' }).first()).toBeVisible();- test('should show non-live fallback monitors on the logs tab for stopped containers', async ({- page- }) => {- const stopped = containersData.data.find((c) => c.state !== 'running');- expect(stopped, 'No stopped container available').toBeDefined();+ await sortByHeader(page, 'Memory Usage', 'desc');- await page.goto(`/containers/${stopped!.id}`);- await page.waitForLoadState('load');+ await expect+ .poll(() => rowIds(page), { timeout: 10000 })+ .toEqual(['big-bytes', 'high-percent', 'small', 'broken']);- await page.getByRole('tab', { name: 'Logs' }).click();+ const bigBytesRow = page+ .getByRole('row')+ .filter({ has: page.getByRole('link', { name: 'big-bytes' }) });+ await expect(bigBytesRow.getByText('10.0%')).toBeVisible();+ await expect(bigBytesRow.getByText('3 GB', { exact: true })).toBeVisible();- await expect(page.getByTestId('container-log-cpu-monitor')).toBeVisible();- await expect(page.getByTestId('container-log-memory-monitor')).toBeVisible();- await expect(page.getByTestId('container-log-cpu-monitor')).toContainText('N/A');- await expect(page.getByTestId('container-log-memory-monitor')).toContainText('N/A');+ const brokenRow = page+ .getByRole('row')+ .filter({ has: page.getByRole('link', { name: 'broken' }) });+ // Both the CPU and memory cells fall back to the unavailable label.+ await expect(brokenRow.getByText('Unavailable', { exact: true })).toHaveCount(2);});- test('downloads the full log history from the logs tab', async ({ page }, testInfo) => {- const running = containersData.data.find((c) => c.state === 'running');- expect(running, 'No running container available').toBeDefined();-- await page.goto(`/containers/${running!.id}`);- await page.waitForLoadState('load');+ test('sorted refresh pulls off-page containers into the first page', async ({ page }) => {+ const scenario: Scenario = { supported: true, fixtures: pagedFixtures, requests: [] };+ await installContainersMock(page, scenario);+ await openContainers(page);- await page.getByRole('tab', { name: 'Logs' }).click();+ await setPageSize(page, '10');+ await expect+ .poll(() => rowIds(page), { timeout: 10000 })+ .toEqual([+ 'filler-0',+ 'filler-1',+ 'filler-2',+ 'filler-3',+ 'filler-4',+ 'filler-5',+ 'filler-6',+ 'filler-7',+ 'filler-8',+ 'filler-9'+ ]);++ await sortByHeader(page, 'Memory Usage', 'desc');- const downloadPromise = page.waitForEvent('download');- await page- .getByRole('button', { name: 'Download', exact: true })- .filter({ visible: true })- .click();- const download = await downloadPromise;- expect(download.suggestedFilename()).toBe(`container-${running!.id.slice(0, 12)}-logs.log`);- const downloadPath = testInfo.outputPath(download.suggestedFilename());- await download.saveAs(downloadPath);- expect((await stat(downloadPath)).isFile()).toBe(true);+ await expect+ .poll(() => rowIds(page), { timeout: 10000 })+ .toEqual([+ 'offpage-heavy',+ 'offpage-heavy2',+ 'filler-9',+ 'filler-8',+ 'filler-7',+ 'filler-6',+ 'filler-5',+ 'filler-4',+ 'filler-3',+ 'filler-2'+ ]);});- test('should show correct actions based on container state (without changing state)', async ({+ test('resource sort polls, suspends in background tabs, and surfaces failures', async ({page}) => {- const running = containersData.data.find((c) => c.state === 'running');- const stopped = containersData.data.find((c) => c.state !== 'running');+ test.setTimeout(60000);+ await page.clock.install();+ const scenario: Scenario = { supported: true, fixtures: basicFixtures, requests: [] };+ await installContainersMock(page, scenario);+ await openContainers(page);- await navigateToContainers(page);+ await sortByHeader(page, 'CPU Usage', 'desc');+ await expect+ .poll(() => rowIds(page), { timeout: 10000 })+ .toEqual(['high-percent', 'big-bytes', 'small', 'broken']);- expect(running, 'Running container fixture must exist').toBeDefined();- expect(stopped, 'Stopped container fixture must exist').toBeDefined();- const runningName = running!.names?.[0]?.replace(/^\/+/, '') ?? running!.id;- const runningRow = page- .getByRole('row')- .filter({ has: page.getByRole('link', { name: runningName, exact: true }) });- const runningMenu = await openRowActionsMenu(page, runningRow);- await expect(runningMenu.getByRole('menuitem', { name: 'Restart', exact: true })).toBeVisible();- await expect(runningMenu.getByRole('menuitem', { name: 'Stop', exact: true })).toBeVisible();- await page.keyboard.press('Escape');+ const initialRequests = scenario.requests.filter((q) => q.includes('sort=cpuUsage')).length;+ await expect+ .poll(() => scenario.requests.filter((q) => q.includes('sort=cpuUsage')).length, {+ timeout: 15000+ })+ .toBeGreaterThan(initialRequests);++ await page.evaluate(() => {+ Object.defineProperty(document, 'hidden', { value: true, configurable: true });+ document.dispatchEvent(new Event('visibilitychange'));+ });+ const frozen = scenario.requests.length;+ await page.clock.runFor(6500);+ expect(scenario.requests.length).toBe(frozen);- const stoppedName = stopped!.names?.[0]?.replace(/^\/+/, '') ?? stopped!.id;- const stoppedRow = page- .getByRole('row')- .filter({ has: page.getByRole('link', { name: stoppedName, exact: true }) });- const stoppedMenu = await openRowActionsMenu(page, stoppedRow);- await expect(stoppedMenu.getByRole('menuitem', { name: 'Start', exact: true })).toBeVisible();- await page.keyboard.press('Escape');- });+ await page.evaluate(() => {+ Object.defineProperty(document, 'hidden', { value: false, configurable: true });+ document.dispatchEvent(new Event('visibilitychange'));+ });+ await expect.poll(() => scenario.requests.length, { timeout: 10000 }).toBeGreaterThan(frozen);- test('should open the Remove dialog from row actions and allow cancel', async ({ page }) => {- expect(containersData.data.length, 'No containers available').toBeGreaterThan(0);- const any = containersData.data[0];+ scenario.failList = true;+ await expect(page.getByText('Automatic refresh failed: daemon exploded')).toBeVisible({+ timeout: 15000+ });- await navigateToContainers(page);+ scenario.failList = false;+ await expect(page.getByText('Automatic refresh failed: daemon exploded')).toBeHidden({+ timeout: 15000+ });+ });- const containerName = any.names?.[0]?.replace(/^\/+/, '') ?? any.id;- const row = page- .getByRole('row')- .filter({ has: page.getByRole('link', { name: containerName, exact: true }) });- const menu = await openRowActionsMenu(page, row);- await menu.getByRole('menuitem', { name: 'Remove', exact: true }).click();+ test('older agents disable resource sorting with an upgrade explanation', async ({ page }) => {+ const scenario: Scenario = { supported: false, fixtures: basicFixtures, requests: [] };+ await installContainersMock(page, scenario);+ await openContainers(page);- const dialog = page.getByRole('dialog');- await expect(dialog).toBeVisible();+ await expect(page.getByText('needs a newer agent for this environment')).toBeVisible();await expect(- dialog.getByRole('heading', { name: 'Confirm Container Removal', exact: true })- ).toBeVisible();-- await page.getByRole('button', { name: 'Cancel' }).click();- await expect(dialog).toBeHidden();+ page.getByRole('columnheader', { name: 'Memory Usage', exact: true }).getByRole('button')+ ).toHaveCount(0);+ await expect(+ page.getByRole('columnheader', { name: 'CPU Usage', exact: true }).getByRole('button')+ ).toHaveCount(0);});});-test.describe('Containers Page network IP addresses', () => {- test('should show every network IP address for a multi-network container', async ({+test.describe('Project grouping', () => {+ type MockContainer = {+ id: string;+ names: string[];+ image: string;+ imageId: string;+ command: string;+ created: number;+ labels: Record<string, string>;+ state: string;+ status: string;+ ports: [];+ hostConfig: { networkMode: string };+ networkSettings: { networks: Record<string, unknown> };+ mounts: [];+ };++ function createContainer(+ id: string,+ name: string,+ project: string,+ created: number+ ): MockContainer {+ return {+ id,+ names: [`/${name}`],+ image: `${project || 'misc'}:latest`,+ imageId: `image-${id}`,+ command: '',+ created,+ labels: project ? { 'com.docker.compose.project': project } : {},+ state: 'running',+ status: 'Up 5 minutes',+ ports: [],+ hostConfig: { networkMode: 'default' },+ networkSettings: { networks: {} },+ mounts: []+ };+ }++ function buildContainersResponse(containers: MockContainer[], start: number, limit: number) {+ const safeLimit = limit > 0 ? limit : containers.length;+ const pageItems = limit === -1 ? containers : containers.slice(start, start + safeLimit);+ const currentPage = limit > 0 ? Math.floor(start / safeLimit) + 1 : 1;+ const totalPages = limit > 0 ? Math.max(1, Math.ceil(containers.length / safeLimit)) : 1;+ const itemsPerPage = limit === -1 ? containers.length : safeLimit;++ return {+ success: true,+ data: pageItems,+ counts: {+ runningContainers: containers.length,+ stoppedContainers: 0,+ totalContainers: containers.length+ },+ pagination: {+ totalPages,+ totalItems: containers.length,+ currentPage,+ itemsPerPage,+ grandTotalItems: containers.length+ }+ };+ }++ test('grouped containers do not split the same project across pages', async ({page,context}) => {await page.addInitScript(() => {+ localStorage.removeItem('selectedEnvironmentId');localStorage.removeItem('arcane-container-table');+ localStorage.setItem('container-groups-collapsed', JSON.stringify({ immich: false }));+ localStorage.removeItem('collapsible-cards-expanded');});- await context.route('**/api/environments/*/containers**', async (route) => {+ let groupedMockPayload:+ | {+ groups: Array<{ groupName: string; items: MockContainer[] }>;+ }+ | undefined;++ const otherContainers = Array.from({ length: 18 }, (_, index) => {+ const project = `other-${index + 1}`;+ return createContainer(`other-${index + 1}`, `${project}-service`, project, 1_000 - index);+ });++ const immichContainers = [+ createContainer('immich-1', 'immich-server', 'immich', 900),+ createContainer('immich-2', 'immich-machine-learning', 'immich', 899),+ createContainer('immich-3', 'immich-redis', 'immich', 898),+ createContainer('immich-4', 'immich-postgres', 'immich', 897)+ ];++ const allContainers = [...otherContainers, ...immichContainers];++ await context.route('**/containers**', async (route) => {if (route.request().method() !== 'GET') {await route.continue();return;@@ -375,74 +1597,244 @@ test.describe('Containers Page network IP addresses', () => {return;}+ const start = Number(url.searchParams.get('start') ?? '0');+ const limit = Number(url.searchParams.get('limit') ?? '20');+ const groupBy = url.searchParams.get('groupBy');++ if (groupBy === 'project') {+ groupedMockPayload = {+ groups: [+ {+ groupName: 'immich',+ items: immichContainers+ },+ ...otherContainers.slice(0, 18).map((container, index) => ({+ groupName: `other-${index + 1}`,+ items: [container]+ }))+ ]+ };++ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: [...immichContainers, ...otherContainers.slice(0, 18)],+ groups: groupedMockPayload.groups,+ counts: {+ runningContainers: allContainers.length,+ stoppedContainers: 0,+ totalContainers: allContainers.length+ },+ pagination: {+ totalPages: 1,+ totalItems: allContainers.length,+ currentPage: 1,+ itemsPerPage: 20,+ grandTotalItems: allContainers.length+ }+ })+ });+ return;+ }+await route.fulfill({status: 200,contentType: 'application/json',- body: JSON.stringify({- success: true,- data: [- {- id: 'wordpress-multi-network',- names: ['/wordpress'],- image: 'wordpress:latest',- imageId: 'sha256:wordpress',- command: 'apache2-foreground',- created: 1_700_000_000,- labels: {},- state: 'running',- status: 'Up 5 minutes',- ports: [],- hostConfig: { networkMode: 'default' },- networkSettings: {- networks: {- proxy: { ipAddress: '172.20.0.10' },- private: { ipAddress: '10.10.0.5' }- }- },- mounts: []- }- ],- counts: {- runningContainers: 1,- stoppedContainers: 0,- totalContainers: 1- },- pagination: {- totalPages: 1,- totalItems: 1,- currentPage: 1,- itemsPerPage: 20,- grandTotalItems: 1- }- })+ body: JSON.stringify(buildContainersResponse(allContainers, start, limit))});});- await navigateToContainers(page);+ await page.goto('/containers');+ await page.waitForLoadState('load');- const row = page.getByRole('row').filter({- has: page.getByRole('link', { name: 'wordpress', exact: true })- });+ await page.setViewportSize({ width: 1440, height: 900 });- await expect(row).toContainText('10.10.0.5');- await expect(row).toContainText('172.20.0.10');+ await page.getByRole('button', { name: 'View' }).click();+ await page.getByRole('menuitemcheckbox', { name: 'Group by Project' }).click();+ await page.keyboard.press('Escape');++ await expect+ .poll(+ () =>+ groupedMockPayload?.groups.find((group) => group.groupName === 'immich')?.items.length ??+ 0+ )+ .toBe(4);++ const immichGroupRow = page+ .locator('table tbody tr')+ .filter({ has: page.getByText('immich', { exact: true }) });++ await expect(immichGroupRow).toHaveCount(1);+ await expect(immichGroupRow).toContainText('immich');+ await expect(immichGroupRow).toContainText('(4)');++ await expect(page.getByRole('link', { name: 'immich-server', exact: true })).toBeVisible();+ await expect(+ page.getByRole('link', { name: 'immich-machine-learning', exact: true })+ ).toBeVisible();+ await expect(page.getByRole('link', { name: 'immich-redis', exact: true })).toBeVisible();+ await expect(page.getByRole('link', { name: 'immich-postgres', exact: true })).toBeVisible();});-});-test.describe('Container form', () => {- test('capability selectors remain stateless when value is not bound', async ({ page }) => {- await page.goto('/containers/new');- await page.getByRole('tab', { name: 'Advanced', exact: true }).click();-- const capAdd = page.getByText('Add capabilities', { exact: true }).locator('..');- const selector = capAdd.getByRole('combobox');- await selector.click();- await page.getByRole('option', { name: 'NET_ADMIN', exact: true }).click();-- const badge = capAdd.locator('[data-slot="badge"]').filter({ hasText: 'NET_ADMIN' });- await expect(badge).toBeVisible();- await badge.getByRole('button').click();- await expect(badge).toHaveCount(0);- await expect(selector).toContainText('Select an option');+ type MockGroup = { groupName: string; items: MockContainer[] };++ async function mockGroupedContainers(page: Page, groups: MockGroup[]) {+ const allContainers = groups.flatMap((group) => group.items);+ await page.context().route('**/containers**', async (route) => {+ const url = new URL(route.request().url());+ if (+ route.request().method() !== 'GET' ||+ !/^\/api\/environments\/[^/]+\/containers$/.test(url.pathname)+ ) {+ await route.continue();+ return;+ }+ const response = buildContainersResponse(allContainers, 0, -1);+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(+ url.searchParams.get('groupBy') === 'project' ? { ...response, groups } : response+ )+ });+ });+ }++ function containerRow(page: Page, name: string) {+ return page.getByRole('row').filter({ has: page.getByRole('link', { name, exact: true }) });+ }++ function groupRow(page: Page, groupName: string) {+ return page+ .locator('table tbody tr')+ .filter({ has: page.getByText(groupName, { exact: true }) });+ }++ async function expectContainersSelected(page: Page, names: string[], selected: boolean) {+ for (const name of names) {+ await expect(containerRow(page, name).getByRole('checkbox')).toHaveAttribute(+ 'aria-checked',+ selected ? 'true' : 'false'+ );+ }+ }++ async function openGroupedContainers(page: Page, collapsed: Record<string, boolean>) {+ await page.addInitScript((collapsedState) => {+ localStorage.removeItem('selectedEnvironmentId');+ localStorage.removeItem('arcane-container-table');+ localStorage.setItem('container-groups-collapsed', JSON.stringify(collapsedState));+ localStorage.removeItem('collapsible-cards-expanded');+ }, collapsed);++ const groups: MockGroup[] = [+ {+ groupName: 'immich',+ items: [+ createContainer('immich-1', 'immich-server', 'immich', 900),+ createContainer('immich-2', 'immich-machine-learning', 'immich', 899),+ createContainer('immich-3', 'immich-redis', 'immich', 898),+ createContainer('immich-4', 'immich-postgres', 'immich', 897)+ ]+ },+ { groupName: 'alpha', items: [createContainer('alpha-1', 'alpha-service', 'alpha', 800)] },+ {+ groupName: 'beta',+ items: [+ createContainer('beta-1', 'beta-web', 'beta', 700),+ createContainer('beta-2', 'beta-db', 'beta', 699)+ ]+ },+ { groupName: 'gamma', items: [createContainer('gamma-1', 'gamma-service', 'gamma', 600)] }+ ];+ await mockGroupedContainers(page, groups);+ await page.setViewportSize({ width: 1440, height: 900 });+ await page.goto('/containers');+ await page.waitForLoadState('load');+ await page.getByRole('button', { name: 'View' }).click();+ await page.getByRole('menuitemcheckbox', { name: 'Group by Project' }).click();+ await page.keyboard.press('Escape');+ await expect(groupRow(page, 'immich')).toContainText('(4)');+ await expect(page.getByRole('link', { name: 'immich-server', exact: true })).toBeVisible();+ }++ test.describe('grouped shift-select', () => {+ test('ranges follow group order and skip collapsed groups', async ({ page }) => {+ await openGroupedContainers(page, { immich: false, alpha: false, gamma: false });+ await expect(page.getByRole('link', { name: 'beta-web', exact: true })).toHaveCount(0);++ await containerRow(page, 'immich-machine-learning').getByRole('checkbox').click();+ await containerRow(page, 'gamma-service')+ .getByRole('checkbox')+ .click({ modifiers: ['Shift'] });++ await expectContainersSelected(+ page,+ [+ 'immich-machine-learning',+ 'immich-redis',+ 'immich-postgres',+ 'alpha-service',+ 'gamma-service'+ ],+ true+ );+ await expectContainersSelected(page, ['immich-server'], false);+ await expect(groupRow(page, 'beta').getByRole('checkbox')).toHaveAttribute(+ 'aria-checked',+ 'false'+ );+ await expect(groupRow(page, 'alpha').getByRole('checkbox')).toHaveAttribute(+ 'aria-checked',+ 'true'+ );+ await expect(groupRow(page, 'immich').getByRole('checkbox')).toHaveAttribute(+ 'aria-checked',+ 'mixed'+ );+ await expect(page.getByRole('button', { name: 'Stop (5)', exact: true })).toBeVisible();++ await groupRow(page, 'beta').click();+ await expect(page.getByRole('link', { name: 'beta-web', exact: true })).toBeVisible();+ await expectContainersSelected(page, ['beta-web', 'beta-db'], false);+ });++ test('expanded groups are included and group or collapse changes reset the anchor', async ({+ page+ }) => {+ await openGroupedContainers(page, { immich: false, alpha: false, beta: false });++ await containerRow(page, 'immich-postgres').getByRole('checkbox').click();+ await containerRow(page, 'beta-db')+ .getByRole('checkbox')+ .click({ modifiers: ['Shift'] });+ await expectContainersSelected(+ page,+ ['immich-postgres', 'alpha-service', 'beta-web', 'beta-db'],+ true+ );+ await expectContainersSelected(page, ['immich-server', 'immich-redis'], false);++ await groupRow(page, 'alpha').getByRole('checkbox').click();+ await expectContainersSelected(page, ['alpha-service'], false);+ await containerRow(page, 'immich-server')+ .getByRole('checkbox')+ .click({ modifiers: ['Shift'] });+ await expectContainersSelected(page, ['immich-server'], true);+ await expectContainersSelected(page, ['immich-machine-learning', 'immich-redis'], false);++ await containerRow(page, 'immich-machine-learning').getByRole('checkbox').click();+ await groupRow(page, 'alpha').click();+ await expect(page.getByRole('link', { name: 'alpha-service', exact: true })).toHaveCount(0);+ await containerRow(page, 'beta-db')+ .getByRole('checkbox')+ .click({ modifiers: ['Shift'] });+ await expectContainersSelected(page, ['immich-machine-learning', 'beta-web'], true);+ await expectContainersSelected(page, ['immich-redis', 'beta-db'], false);+ await expect(page.getByRole('button', { name: 'Stop (4)', exact: true })).toBeVisible();+ });});});diff --git a/tests/spec/customization.spec.ts b/tests/spec/customization.spec.tsdeleted file mode 100644index 3b994fd1d..000000000--- a/tests/spec/customization.spec.ts+++ /dev/null@@ -1,369 +0,0 @@-import { setCodeMirrorValue, waitForDialogReady } from '../utils/playwright.util';-import { expect, test, type Page } from '../fixtures/test.fixture';-import { removeApiResource, readApiData } from '../utils/fetch.util';-import { openRowActionsMenu } from '../utils/table-actions.util';--type GlobalVariable = {- id: string;- key: string;- value: string;- isSecret: boolean;- allEnvironments: boolean;- environmentIds: string[];-};--type VariableMutation = {- variable?: GlobalVariable;-};--type Template = {- id: string;- name: string;- description: string;-};--type Project = {- id: string;- name: string;- status?: string;- runtimeServices?: Array<{ containerId?: string; containerName?: string }>;-};--type ContainerDetails = {- id: string;- config: { env?: string[] };-};--async function listVariables(page: Page): Promise<GlobalVariable[]> {- return readApiData<GlobalVariable[]>(- await page.request.get('/api/variables'),- 'List global variables'- );-}--function variableRow(page: Page, key: string) {- return page.getByRole('row').filter({ has: page.getByText(key, { exact: true }) });-}--async function openVariableSheet(page: Page) {- await page.getByRole('button', { name: 'Add Variable', exact: true }).click();- const dialog = page.getByRole('dialog', { name: 'Create Variable' });- await waitForDialogReady(dialog);- return dialog;-}--async function createSingleVariable(- page: Page,- key: string,- value: string,- isSecret = false-): Promise<GlobalVariable> {- const dialog = await openVariableSheet(page);- await dialog.locator('#variable-key').fill(key);- await dialog.locator('#variable-value').fill(value);- if (isSecret) await dialog.locator('#variable-secret').click();-- const responsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === '/api/variables'- );- await dialog.getByRole('button', { name: 'Add Variable', exact: true }).click();- const result = await readApiData<VariableMutation>(- await responsePromise,- `Create global variable ${key}`- );- expect(result.variable).toBeDefined();- await expect(dialog).toBeHidden();- return result.variable!;-}--async function getProject(page: Page, projectId: string): Promise<Project> {- return readApiData<Project>(- await page.request.get(`/api/environments/0/projects/${projectId}`),- `Get project ${projectId}`- );-}--test('manages variables and deploys an edited template with real substitution', async ({- page-}) => {- test.setTimeout(240_000);- page.setDefaultTimeout(15_000);-- const suffix = Date.now().toString(36).toUpperCase();- const publicKey = `E2E_TEMPLATE_VALUE_${suffix}`;- const publicValue = `resolved-${suffix.toLowerCase()}`;- const secretKey = `E2E_TEMPLATE_SECRET_${suffix}`;- const secretValue = `secret-${suffix.toLowerCase()}`;- const bulkKeyOne = `E2E_BULK_ONE_${suffix}`;- const bulkKeyTwo = `E2E_BULK_TWO_${suffix}`;- const templateName = `E2E Variable Template ${suffix}`;- const updatedTemplateName = `${templateName} Updated`;- const projectName = `e2e-variable-project-${suffix.toLowerCase()}`;- const containerName = `e2e-variable-container-${suffix.toLowerCase()}`;- let templateId: string | null = null;- let projectId: string | null = null;-- const composeContent = [- 'services:',- ' verifier:',- ' image: public.ecr.aws/docker/library/busybox:1.37',- ` container_name: ${containerName}`,- ' command:',- ' - sh',- ' - -c',- ' - test "$' + publicKey + '" = "' + publicValue + '" && sleep 3600',- ' environment:',- ` ${publicKey}: \${${publicKey}}`,- ''- ].join('\n');-- try {- const localEnvironment = await readApiData<{ id: string; name: string }>(- await page.request.get('/api/environments/0'),- 'Get local environment for variable scope'- );-- await page.goto('/customize/variables');- const publicVariable = await createSingleVariable(page, publicKey, publicValue);- expect(publicVariable).toMatchObject({- key: publicKey,- value: publicValue,- isSecret: false,- allEnvironments: true- });- await expect(variableRow(page, publicKey)).toContainText(publicValue);-- const secretVariable = await createSingleVariable(page, secretKey, secretValue, true);- expect(secretVariable).toMatchObject({ key: secretKey, value: '', isSecret: true });- const secretRow = variableRow(page, secretKey);- await expect(secretRow).toContainText('••••••••');- await expect(secretRow).not.toContainText(secretValue);-- const bulkDialog = await openVariableSheet(page);- await bulkDialog.getByRole('button', { name: 'Paste .env', exact: true }).click();- await bulkDialog- .getByLabel('Paste .env content', { exact: true })- .fill(`${bulkKeyOne}=first\n${bulkKeyTwo}=second`);- await bulkDialog.getByRole('radio', { name: /Specific Environments/ }).click();- const environmentOption = bulkDialog- .locator('label')- .filter({ hasText: localEnvironment.name });- await environmentOption.getByRole('switch').click();- await bulkDialog.getByRole('button', { name: 'Add Variable', exact: true }).click();- await expect(bulkDialog).toBeHidden();- await expect(variableRow(page, bulkKeyOne)).toBeVisible();- await expect(variableRow(page, bulkKeyTwo)).toBeVisible();-- let variables = await listVariables(page);- for (const key of [bulkKeyOne, bulkKeyTwo]) {- const variable = variables.find((candidate) => candidate.key === key);- expect(variable).toMatchObject({- allEnvironments: false,- environmentIds: ['0']- });- }-- const editableRow = variableRow(page, bulkKeyOne);- const editMenu = await openRowActionsMenu(page, editableRow);- await editMenu.getByRole('menuitem', { name: 'Edit', exact: true }).click();- const editDialog = page.getByRole('dialog', { name: 'Edit Variable' });- await waitForDialogReady(editDialog);- await editDialog.locator('#variable-value').fill('first-edited');- const editResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'PUT' &&- /^\/api\/variables\/[^/]+$/.test(new URL(response.url()).pathname)- );- await editDialog.getByRole('button', { name: 'Save Changes', exact: true }).click();- expect((await editResponsePromise).ok()).toBe(true);- await expect(editableRow).toContainText('first-edited');-- const secretMenu = await openRowActionsMenu(page, secretRow);- await secretMenu.getByRole('menuitem', { name: 'Delete', exact: true }).click();- const secretDeleteResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'DELETE' &&- new URL(response.url()).pathname === `/api/variables/${secretVariable.id}`- );- await page.getByRole('dialog').getByRole('button', { name: 'Delete', exact: true }).click();- expect((await secretDeleteResponsePromise).ok()).toBe(true);- await expect(secretRow).toHaveCount(0);-- const syncResults = await readApiData<- Array<{ environmentId: string; status: 'synced' | 'pending' | 'error'; error?: string }>- >(await page.request.post('/api/variables/sync'), 'Synchronize global variables');- expect(syncResults).toEqual(- expect.arrayContaining([expect.objectContaining({ environmentId: '0', status: 'synced' })])- );-- await page.goto('/customize/templates/create');- await page.getByRole('button', { name: 'e.g. My Nginx Project', exact: true }).click();- const templateNameInput = page- .getByPlaceholder('e.g. My Nginx Project', { exact: true })- .filter({ visible: true });- await templateNameInput.fill(templateName);- await templateNameInput.press('Enter');- await page- .getByLabel('Description', { exact: true })- .fill('Created by the customization browser journey');-- const editors = page.locator('.cm-editor').filter({ visible: true });- const composeEditor = editors.first();- const envEditor = editors.nth(1);- await setCodeMirrorValue(composeEditor, 'services:\n broken: [\n');- await setCodeMirrorValue(envEditor, 'NOT VALID ENV');- await expect(page.getByRole('button', { name: 'Create Template', exact: true })).toBeDisabled();-- await setCodeMirrorValue(composeEditor, composeContent);- await setCodeMirrorValue(envEditor, 'TEMPLATE_LOCAL=value\n');- const createTemplateButton = page.getByRole('button', { name: 'Create Template', exact: true });- await expect(createTemplateButton).toBeEnabled({ timeout: 20_000 });- const templateCreateResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === '/api/templates'- );- await createTemplateButton.click();- const template = await readApiData<Template>(- await templateCreateResponsePromise,- `Create template ${templateName}`- );- templateId = template.id;- await expect(page).toHaveURL(`/customize/templates/${template.id}`);-- await page.getByRole('button', { name: templateName, exact: true }).click();- const editTemplateNameInput = page- .getByPlaceholder('e.g. My Nginx Project', { exact: true })- .filter({ visible: true });- await editTemplateNameInput.fill(updatedTemplateName);- await editTemplateNameInput.press('Enter');- await page.getByLabel('Description', { exact: true }).fill('Updated customization template');- const templateUpdateResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'PUT' &&- new URL(response.url()).pathname === `/api/templates/${template.id}`- );- await page.getByRole('button', { name: 'Save', exact: true }).click();- const updatedTemplate = await readApiData<Template>(- await templateUpdateResponsePromise,- `Update template ${template.id}`- );- expect(updatedTemplate).toMatchObject({- name: updatedTemplateName,- description: 'Updated customization template'- });-- await page.getByRole('button', { name: 'Open menu', exact: true }).click();- await page.getByRole('menuitem', { name: 'Create Project', exact: true }).click();- await expect(page).toHaveURL(`/projects/new?templateId=${template.id}`);- const projectNameButton = page.getByRole('button', {- name: updatedTemplateName- .toLowerCase()- .replace(/[^a-z0-9]+/g, '-')- .replace(/^-|-$/g, ''),- exact: true- });- await projectNameButton.click();- const projectNameInput = page- .getByPlaceholder('My New Project', { exact: true })- .filter({ visible: true });- await projectNameInput.fill(projectName);- await projectNameInput.press('Enter');- await expect(page.locator('.cm-editor').filter({ visible: true }).first()).toContainText(- publicKey- );-- const createProjectButton = page.locator('button[data-action="create"]');- await expect(createProjectButton).toBeEnabled({ timeout: 20_000 });- const projectCreateResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === '/api/environments/0/projects'- );- await createProjectButton.click();- const project = await readApiData<Project>(- await projectCreateResponsePromise,- `Create project from template ${template.id}`- );- projectId = project.id;- await expect(page).toHaveURL((url) => url.pathname === `/projects/${project.id}`);-- const deployResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === `/api/environments/0/projects/${project.id}/up`,- { timeout: 30_000 }- );- await page- .getByRole('button', { name: 'Up', exact: true })- .filter({ visible: true })- .first()- .click();- expect((await deployResponsePromise).ok()).toBe(true);- await expect- .poll(async () => (await getProject(page, project.id)).status, { timeout: 60_000 })- .toBe('running');-- let containerId = '';- await expect- .poll(- async () => {- const runtime = await readApiData<Project>(- await page.request.get(`/api/environments/0/projects/${project.id}/runtime`),- `Get runtime services for ${project.id}`- );- containerId =- runtime.runtimeServices?.find((service) => service.containerName === containerName)- ?.containerId ?? '';- return containerId;- },- { timeout: 30_000 }- )- .not.toBe('');- const container = await readApiData<ContainerDetails>(- await page.request.get(`/api/environments/0/containers/${containerId}`),- `Inspect substituted container ${containerId}`- );- expect(container.config.env).toContain(`${publicKey}=${publicValue}`);-- await removeApiResource(page, `/api/environments/0/projects/${project.id}/destroy`, {- data: { removeVolumes: false }- });- projectId = null;-- await page.goto(`/customize/templates/${template.id}`);- await page.getByRole('button', { name: 'Open menu', exact: true }).click();- await page.getByRole('menuitem', { name: 'Delete Template', exact: true }).click();- const templateDeleteResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'DELETE' &&- new URL(response.url()).pathname === `/api/templates/${template.id}`- );- await page- .getByRole('dialog')- .getByRole('button', { name: 'Delete Template', exact: true })- .click();- expect((await templateDeleteResponsePromise).ok()).toBe(true);- await expect(page).toHaveURL((url) => url.pathname === '/customize/templates');- templateId = null;- } finally {- if (projectId) {- await removeApiResource(page, `/api/environments/0/projects/${projectId}/destroy`, {- data: { removeVolumes: false }- });- }- if (templateId) {- await removeApiResource(page, `/api/templates/${templateId}`);- }- try {- const variables = await listVariables(page);- for (const variable of variables.filter((candidate) => candidate.key.endsWith(suffix))) {- await removeApiResource(page, `/api/variables/${variable.id}`);- }- } catch (error) {- expect.soft(false, `Clean up variables: ${String(error)}`).toBe(true);- }- }-});diff --git a/tests/spec/customize.spec.ts b/tests/spec/customize.spec.tsnew file mode 100644index 000000000..ebca3d666--- /dev/null+++ b/tests/spec/customize.spec.ts@@ -0,0 +1,609 @@+import { setCodeMirrorValue, waitForDialogReady } from '../utils/playwright.util';+import { expect, test, type Page } from '../fixtures/test.fixture';+import { removeApiResource, readApiData } from '../utils/fetch.util';+import { openRowActionsMenu } from '../utils/table-actions.util';++test.describe('Templates', () => {+ type GlobalVariable = {+ id: string;+ key: string;+ value: string;+ isSecret: boolean;+ allEnvironments: boolean;+ environmentIds: string[];+ };++ type VariableMutation = {+ variable?: GlobalVariable;+ };++ type Template = {+ id: string;+ name: string;+ description: string;+ };++ type Project = {+ id: string;+ name: string;+ status?: string;+ runtimeServices?: Array<{ containerId?: string; containerName?: string }>;+ };++ type ContainerDetails = {+ id: string;+ config: { env?: string[] };+ };++ async function listVariables(page: Page): Promise<GlobalVariable[]> {+ return readApiData<GlobalVariable[]>(+ await page.request.get('/api/variables'),+ 'List global variables'+ );+ }++ function variableRow(page: Page, key: string) {+ return page.getByRole('row').filter({ has: page.getByText(key, { exact: true }) });+ }++ async function openVariableSheet(page: Page) {+ await page.getByRole('button', { name: 'Add Variable', exact: true }).click();+ const dialog = page.getByRole('dialog', { name: 'Create Variable' });+ await waitForDialogReady(dialog);+ return dialog;+ }++ async function createSingleVariable(+ page: Page,+ key: string,+ value: string,+ isSecret = false+ ): Promise<GlobalVariable> {+ const dialog = await openVariableSheet(page);+ await dialog.locator('#variable-key').fill(key);+ await dialog.locator('#variable-value').fill(value);+ if (isSecret) await dialog.locator('#variable-secret').click();++ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/variables'+ );+ await dialog.getByRole('button', { name: 'Add Variable', exact: true }).click();+ const result = await readApiData<VariableMutation>(+ await responsePromise,+ `Create global variable ${key}`+ );+ expect(result.variable).toBeDefined();+ await expect(dialog).toBeHidden();+ return result.variable!;+ }++ async function getProject(page: Page, projectId: string): Promise<Project> {+ return readApiData<Project>(+ await page.request.get(`/api/environments/0/projects/${projectId}`),+ `Get project ${projectId}`+ );+ }++ test('manages variables and deploys an edited template with real substitution', async ({+ page+ }) => {+ test.setTimeout(240_000);+ page.setDefaultTimeout(15_000);++ const suffix = Date.now().toString(36).toUpperCase();+ const publicKey = `E2E_TEMPLATE_VALUE_${suffix}`;+ const publicValue = `resolved-${suffix.toLowerCase()}`;+ const secretKey = `E2E_TEMPLATE_SECRET_${suffix}`;+ const secretValue = `secret-${suffix.toLowerCase()}`;+ const bulkKeyOne = `E2E_BULK_ONE_${suffix}`;+ const bulkKeyTwo = `E2E_BULK_TWO_${suffix}`;+ const templateName = `E2E Variable Template ${suffix}`;+ const updatedTemplateName = `${templateName} Updated`;+ const projectName = `e2e-variable-project-${suffix.toLowerCase()}`;+ const containerName = `e2e-variable-container-${suffix.toLowerCase()}`;+ let templateId: string | null = null;+ let projectId: string | null = null;++ const composeContent = [+ 'services:',+ ' verifier:',+ ' image: public.ecr.aws/docker/library/busybox:1.37',+ ` container_name: ${containerName}`,+ ' command:',+ ' - sh',+ ' - -c',+ ' - test "$' + publicKey + '" = "' + publicValue + '" && sleep 3600',+ ' environment:',+ ` ${publicKey}: \${${publicKey}}`,+ ''+ ].join('\n');++ try {+ const localEnvironment = await readApiData<{ id: string; name: string }>(+ await page.request.get('/api/environments/0'),+ 'Get local environment for variable scope'+ );++ await page.goto('/customize/variables');+ const publicVariable = await createSingleVariable(page, publicKey, publicValue);+ expect(publicVariable).toMatchObject({+ key: publicKey,+ value: publicValue,+ isSecret: false,+ allEnvironments: true+ });+ await expect(variableRow(page, publicKey)).toContainText(publicValue);++ const secretVariable = await createSingleVariable(page, secretKey, secretValue, true);+ expect(secretVariable).toMatchObject({ key: secretKey, value: '', isSecret: true });+ const secretRow = variableRow(page, secretKey);+ await expect(secretRow).toContainText('••••••••');+ await expect(secretRow).not.toContainText(secretValue);++ const bulkDialog = await openVariableSheet(page);+ await bulkDialog.getByRole('button', { name: 'Paste .env', exact: true }).click();+ await bulkDialog+ .getByLabel('Paste .env content', { exact: true })+ .fill(`${bulkKeyOne}=first\n${bulkKeyTwo}=second`);+ await bulkDialog.getByRole('radio', { name: /Specific Environments/ }).click();+ const environmentOption = bulkDialog+ .locator('label')+ .filter({ hasText: localEnvironment.name });+ await environmentOption.getByRole('switch').click();+ await bulkDialog.getByRole('button', { name: 'Add Variable', exact: true }).click();+ await expect(bulkDialog).toBeHidden();+ await expect(variableRow(page, bulkKeyOne)).toBeVisible();+ await expect(variableRow(page, bulkKeyTwo)).toBeVisible();++ let variables = await listVariables(page);+ for (const key of [bulkKeyOne, bulkKeyTwo]) {+ const variable = variables.find((candidate) => candidate.key === key);+ expect(variable).toMatchObject({+ allEnvironments: false,+ environmentIds: ['0']+ });+ }++ const editableRow = variableRow(page, bulkKeyOne);+ const editMenu = await openRowActionsMenu(page, editableRow);+ await editMenu.getByRole('menuitem', { name: 'Edit', exact: true }).click();+ const editDialog = page.getByRole('dialog', { name: 'Edit Variable' });+ await waitForDialogReady(editDialog);+ await editDialog.locator('#variable-value').fill('first-edited');+ const editResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'PUT' &&+ /^\/api\/variables\/[^/]+$/.test(new URL(response.url()).pathname)+ );+ await editDialog.getByRole('button', { name: 'Save Changes', exact: true }).click();+ expect((await editResponsePromise).ok()).toBe(true);+ await expect(editableRow).toContainText('first-edited');++ const secretMenu = await openRowActionsMenu(page, secretRow);+ await secretMenu.getByRole('menuitem', { name: 'Delete', exact: true }).click();+ const secretDeleteResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'DELETE' &&+ new URL(response.url()).pathname === `/api/variables/${secretVariable.id}`+ );+ await page.getByRole('dialog').getByRole('button', { name: 'Delete', exact: true }).click();+ expect((await secretDeleteResponsePromise).ok()).toBe(true);+ await expect(secretRow).toHaveCount(0);++ const syncResults = await readApiData<+ Array<{ environmentId: string; status: 'synced' | 'pending' | 'error'; error?: string }>+ >(await page.request.post('/api/variables/sync'), 'Synchronize global variables');+ expect(syncResults).toEqual(+ expect.arrayContaining([expect.objectContaining({ environmentId: '0', status: 'synced' })])+ );++ await page.goto('/customize/templates/create');+ await page.getByRole('button', { name: 'e.g. My Nginx Project', exact: true }).click();+ const templateNameInput = page+ .getByPlaceholder('e.g. My Nginx Project', { exact: true })+ .filter({ visible: true });+ await templateNameInput.fill(templateName);+ await templateNameInput.press('Enter');+ await page+ .getByLabel('Description', { exact: true })+ .fill('Created by the customization browser journey');++ const editors = page.locator('.cm-editor').filter({ visible: true });+ const composeEditor = editors.first();+ const envEditor = editors.nth(1);+ await setCodeMirrorValue(composeEditor, 'services:\n broken: [\n');+ await setCodeMirrorValue(envEditor, 'NOT VALID ENV');+ await expect(+ page.getByRole('button', { name: 'Create Template', exact: true })+ ).toBeDisabled();++ await setCodeMirrorValue(composeEditor, composeContent);+ await setCodeMirrorValue(envEditor, 'TEMPLATE_LOCAL=value\n');+ const createTemplateButton = page.getByRole('button', {+ name: 'Create Template',+ exact: true+ });+ await expect(createTemplateButton).toBeEnabled({ timeout: 20_000 });+ const templateCreateResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/templates'+ );+ await createTemplateButton.click();+ const template = await readApiData<Template>(+ await templateCreateResponsePromise,+ `Create template ${templateName}`+ );+ templateId = template.id;+ await expect(page).toHaveURL(`/customize/templates/${template.id}`);++ await page.getByRole('button', { name: templateName, exact: true }).click();+ const editTemplateNameInput = page+ .getByPlaceholder('e.g. My Nginx Project', { exact: true })+ .filter({ visible: true });+ await editTemplateNameInput.fill(updatedTemplateName);+ await editTemplateNameInput.press('Enter');+ await page.getByLabel('Description', { exact: true }).fill('Updated customization template');+ const templateUpdateResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'PUT' &&+ new URL(response.url()).pathname === `/api/templates/${template.id}`+ );+ await page.getByRole('button', { name: 'Save', exact: true }).click();+ const updatedTemplate = await readApiData<Template>(+ await templateUpdateResponsePromise,+ `Update template ${template.id}`+ );+ expect(updatedTemplate).toMatchObject({+ name: updatedTemplateName,+ description: 'Updated customization template'+ });++ await page.getByRole('button', { name: 'Open menu', exact: true }).click();+ await page.getByRole('menuitem', { name: 'Create Project', exact: true }).click();+ await expect(page).toHaveURL(`/projects/new?templateId=${template.id}`);+ const projectNameButton = page.getByRole('button', {+ name: updatedTemplateName+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-|-$/g, ''),+ exact: true+ });+ await projectNameButton.click();+ const projectNameInput = page+ .getByPlaceholder('My New Project', { exact: true })+ .filter({ visible: true });+ await projectNameInput.fill(projectName);+ await projectNameInput.press('Enter');+ await expect(page.locator('.cm-editor').filter({ visible: true }).first()).toContainText(+ publicKey+ );++ const createProjectButton = page.locator('button[data-action="create"]');+ await expect(createProjectButton).toBeEnabled({ timeout: 20_000 });+ const projectCreateResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/environments/0/projects'+ );+ await createProjectButton.click();+ const project = await readApiData<Project>(+ await projectCreateResponsePromise,+ `Create project from template ${template.id}`+ );+ projectId = project.id;+ await expect(page).toHaveURL((url) => url.pathname === `/projects/${project.id}`);++ const deployResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === `/api/environments/0/projects/${project.id}/up`,+ { timeout: 30_000 }+ );+ await page+ .getByRole('button', { name: 'Up', exact: true })+ .filter({ visible: true })+ .first()+ .click();+ expect((await deployResponsePromise).ok()).toBe(true);+ await expect+ .poll(async () => (await getProject(page, project.id)).status, { timeout: 60_000 })+ .toBe('running');++ let containerId = '';+ await expect+ .poll(+ async () => {+ const runtime = await readApiData<Project>(+ await page.request.get(`/api/environments/0/projects/${project.id}/runtime`),+ `Get runtime services for ${project.id}`+ );+ containerId =+ runtime.runtimeServices?.find((service) => service.containerName === containerName)+ ?.containerId ?? '';+ return containerId;+ },+ { timeout: 30_000 }+ )+ .not.toBe('');+ const container = await readApiData<ContainerDetails>(+ await page.request.get(`/api/environments/0/containers/${containerId}`),+ `Inspect substituted container ${containerId}`+ );+ expect(container.config.env).toContain(`${publicKey}=${publicValue}`);++ await removeApiResource(page, `/api/environments/0/projects/${project.id}/destroy`, {+ data: { removeVolumes: false }+ });+ projectId = null;++ await page.goto(`/customize/templates/${template.id}`);+ await page.getByRole('button', { name: 'Open menu', exact: true }).click();+ await page.getByRole('menuitem', { name: 'Delete Template', exact: true }).click();+ const templateDeleteResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'DELETE' &&+ new URL(response.url()).pathname === `/api/templates/${template.id}`+ );+ await page+ .getByRole('dialog')+ .getByRole('button', { name: 'Delete Template', exact: true })+ .click();+ expect((await templateDeleteResponsePromise).ok()).toBe(true);+ await expect(page).toHaveURL((url) => url.pathname === '/customize/templates');+ templateId = null;+ } finally {+ if (projectId) {+ await removeApiResource(page, `/api/environments/0/projects/${projectId}/destroy`, {+ data: { removeVolumes: false }+ });+ }+ if (templateId) {+ await removeApiResource(page, `/api/templates/${templateId}`);+ }+ try {+ const variables = await listVariables(page);+ for (const variable of variables.filter((candidate) => candidate.key.endsWith(suffix))) {+ await removeApiResource(page, `/api/variables/${variable.id}`);+ }+ } catch (error) {+ expect.soft(false, `Clean up variables: ${String(error)}`).toBe(true);+ }+ }+ });+});++test.describe('Registries', () => {+ const route = '/customize/registries';+ const TOKEN = process.env.REGISTRY_TEST_TOKEN ?? 'e2e-token';+ const pullUsageRoute = /\/api\/container-registries\/pull-usage(?:\?|$)/;+ const registryListRoute = /\/api\/container-registries(?:\?|$)/;++ async function mockRegistryList(page: Page, registryId = 'dockerhub-registry') {+ await page.context().route(registryListRoute, async (route) => {+ if (route.request().method() !== 'GET') {+ await route.fallback();+ return;+ }++ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: [+ {+ id: registryId,+ url: 'docker.io',+ username: 'docker-user',+ description: 'Docker Hub test registry',+ insecure: false,+ enabled: true,+ registryType: 'generic',+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString()+ }+ ],+ pagination: {+ totalPages: 1,+ totalItems: 1,+ currentPage: 1,+ itemsPerPage: 20,+ grandTotalItems: 1+ }+ })+ });+ });+ }++ async function mockRegistryPullUsage(+ page: Page,+ options: { registryId?: string; remaining?: number; limit?: number; observedPulls?: number }+ ) {+ const registryId = options.registryId ?? 'dockerhub-registry';+ await page.context().route(pullUsageRoute, async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: {+ registries: [+ {+ registryId,+ provider: 'dockerhub',+ registry: 'docker.io',+ displayName: 'Docker Hub',+ repository: 'ratelimitpreview/test',+ ...(options.limit === undefined ? {} : { limit: options.limit }),+ ...(options.remaining === undefined ? {} : { remaining: options.remaining }),+ observedPulls: options.observedPulls ?? 0,+ authMethod: 'credential',+ authUsername: 'docker-user',+ checkedAt: new Date().toISOString()+ }+ ]+ }+ })+ });+ });+ }++ test.describe('Container Registries', () => {+ const registryIds = new Set<string>();+ test.afterEach(async ({ page }) => {+ for (const id of registryIds)+ await removeApiResource(page, `/api/container-registries/${id}`);+ registryIds.clear();+ });+ test.beforeEach(async ({ page }) => {+ await page.goto(route);+ await page.waitForLoadState('load');+ });++ test('should display title and subtitle, and refresh', async ({ page }) => {+ await expect(+ page.getByRole('heading', { name: 'Container Registries', level: 1 })+ ).toBeVisible();+ await expect(+ page+ .getByText(+ 'Configure access credentials for private Docker registries and container repositories'+ )+ .first()+ ).toBeVisible();++ await page.getByRole('button', { name: 'Refresh' }).click();+ await expect(+ page+ .getByRole('region', { name: 'Notifications alt+T', exact: true })+ .getByRole('listitem')+ .filter({ hasText: 'Registries Refreshed!' })+ ).toBeVisible({ timeout: 10000 });+ });++ test('should open Add Registry dialog and validate required fields', async ({ page }) => {+ await page.getByRole('button', { name: 'Add Registry' }).click();++ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();++ // Submit without URL -> expect validation error+ await dialog.getByRole('button', { name: 'Add Registry', exact: true }).click();+ await expect(dialog.getByText('Registry URL is required', { exact: true })).toBeVisible();++ // Close dialog+ await page.keyboard.press('Escape');+ await expect(dialog).toBeHidden();+ });++ test('should display registry pull limit usage when headers are available', async ({+ page+ }) => {+ await mockRegistryList(page);+ await mockRegistryPullUsage(page, { remaining: 76, limit: 100, observedPulls: 4 });+ await page.goto(route);+ await page.waitForLoadState('load');++ const table = page.getByRole('table');+ await expect(table.getByText('Pull Usage')).toBeVisible();+ await expect(table.getByText('76/100')).toBeVisible();+ });++ test('should display observed pull count when registry limit headers are unavailable', async ({+ page+ }) => {+ await mockRegistryList(page);+ await mockRegistryPullUsage(page, { observedPulls: 4 });+ await page.goto(route);+ await page.waitForLoadState('load');++ const table = page.getByRole('table');+ await expect(table.getByText('Pull Usage')).toBeVisible();+ await expect(table.getByText('4 pulls')).toBeVisible();+ });++ test('should create, test, edit, and delete a registry', async ({ page }) => {+ // Create+ await page.getByRole('button', { name: 'Add Registry' }).click();+ const dialog = page.getByRole('dialog');+ await waitForDialogReady(dialog);++ const url = `e2e.example.com-${Date.now()}`;++ // URL+ await dialog.getByLabel('Registry URL', { exact: true }).fill(url);+ // Username (frontend requires it)+ await dialog.getByLabel('Username', { exact: true }).fill('e2e');+ // Token (backend needs it to avoid 400)+ const tokenInput = dialog.getByLabel('Token', { exact: true });+ await tokenInput.fill(TOKEN);++ // Optional description+ const desc = dialog.getByLabel('Description', { exact: true });+ await desc.fill('E2E test registry');++ const createdPromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/container-registries'+ );+ await dialog.getByRole('button', { name: 'Add Registry', exact: true }).click();++ const created = await readApiData<{ id: string }>(await createdPromise, 'Create registry');+ registryIds.add(created.id);++ // Creation complete when dialog closes+ await expect(dialog).toBeHidden({ timeout: 10000 });++ // Row should appear+ const row = page+ .getByRole('row')+ .filter({ has: page.getByText(url, { exact: true }) })+ .first();+ await expect(row).toBeVisible();++ // Test Connection (accept either success or failure toast)+ const menu = await openRowActionsMenu(page, row);+ await menu.getByRole('menuitem', { name: 'Test Connection' }).click();+ });++ test('should open Remove Selected dialog and cancel (no mutation)', async ({ page }) => {+ const registry = await readApiData<{ id: string }>(+ await page.request.post('/api/container-registries', {+ data: {+ url: `e2e-select-${Date.now()}.example.com`,+ username: 'e2e',+ token: TOKEN,+ description: '',+ insecure: false,+ enabled: true,+ registryType: 'generic',+ repositoryNames: [],+ awsAccessKeyId: '',+ awsSecretAccessKey: '',+ awsRegion: ''+ }+ }),+ 'Create registry selection fixture'+ );+ registryIds.add(registry.id);+ await page.goto(route);+ const firstRowCheckbox = page+ .getByRole('row')+ .filter({ has: page.getByRole('button', { name: 'Open menu', exact: true }) })+ .getByRole('checkbox')+ .first();+ await firstRowCheckbox.check();+ await page.getByRole('button', { name: 'Remove Selected (1)', exact: true }).click();+ const confirm = page.getByRole('dialog');+ await expect(+ confirm.getByRole('heading', { name: 'Remove 1 Registry(ies)', exact: true })+ ).toBeVisible();+ await confirm.getByRole('button', { name: 'Cancel', exact: true }).click();+ await expect(confirm).toBeHidden();+ });+ });+});diff --git a/tests/spec/dashboard-system-stats.spec.ts b/tests/spec/dashboard-system-stats.spec.tsdeleted file mode 100644index e22b28934..000000000--- a/tests/spec/dashboard-system-stats.spec.ts+++ /dev/null@@ -1,392 +0,0 @@-import { test, expect, type Page } from '../fixtures/test.fixture';--const defaultDashboardPath = '/dashboard';--const mockedStats = {- cpuUsage: 12.3,- memoryUsage: 512 * 1024 * 1024,- memoryTotal: 1024 * 1024 * 1024,- diskUsage: 256 * 1024 * 1024,- diskTotal: 1024 * 1024 * 1024,- cpuCount: 7,- architecture: 'amd64',- platform: 'linux',- hostname: 'edge-client',- gpuCount: 0,- gpus: []-};--type StatsMockOptions = {- deliverAfterMs?: number;- failConnections?: boolean;- closeAfterMessage?: boolean;-};--async function mockDashboardStatsWebSocket(page: Page, options: StatsMockOptions = {}) {- await page.addInitScript(- ({ statsPayload, options }) => {- const browserWindow = globalThis as typeof globalThis & {- WebSocket: any;- EventTarget: any;- Event: any;- MessageEvent: any;- CloseEvent: any;- __arcaneStatsMock: { failConnections: boolean };- };- browserWindow.__arcaneStatsMock = { failConnections: options.failConnections ?? false };- const NativeWebSocket = browserWindow.WebSocket;- const statsPathPattern = /\/api\/environments\/[^/]+\/ws\/system\/stats(?:\?.*)?$/;-- class MockStatsWebSocket extends browserWindow.EventTarget {- static CONNECTING = 0;- static OPEN = 1;- static CLOSING = 2;- static CLOSED = 3;-- url: string;- readyState = MockStatsWebSocket.CONNECTING;- bufferedAmount = 0;- extensions = '';- protocol = '';- binaryType = 'blob';- onopen: ((event: unknown) => void) | null = null;- onmessage: ((event: unknown) => void) | null = null;- onerror: ((event: unknown) => void) | null = null;- onclose: ((event: unknown) => void) | null = null;-- constructor(url: string | URL) {- super();- this.url = String(url);-- if (browserWindow.__arcaneStatsMock.failConnections) {- queueMicrotask(() => {- if (this.readyState !== MockStatsWebSocket.CONNECTING) return;- const errorEvent = new browserWindow.Event('error');- this.dispatchEvent(errorEvent);- this.onerror?.(errorEvent);- this.close(1006, '');- });- return;- }-- const deliver = () => {- if (this.readyState !== MockStatsWebSocket.CONNECTING) return;- this.readyState = MockStatsWebSocket.OPEN;- const openEvent = new browserWindow.Event('open');- this.dispatchEvent(openEvent);- this.onopen?.(openEvent);-- const messageEvent = new browserWindow.MessageEvent('message', {- data: JSON.stringify(statsPayload)- });- this.dispatchEvent(messageEvent);- this.onmessage?.(messageEvent);-- if (options.closeAfterMessage) {- browserWindow.__arcaneStatsMock.failConnections = true;- this.close(1006, '');- }- };-- if (options.deliverAfterMs) {- setTimeout(deliver, options.deliverAfterMs);- } else {- queueMicrotask(deliver);- }- }-- send(_data?: string | ArrayBufferLike | Blob | ArrayBufferView) {}-- close(code = 1000, reason = '') {- if (this.readyState === MockStatsWebSocket.CLOSED) return;- this.readyState = MockStatsWebSocket.CLOSED;- const closeEvent = new browserWindow.CloseEvent('close', {- code,- reason,- wasClean: true- });- this.dispatchEvent(closeEvent);- this.onclose?.(closeEvent);- }- }-- const PatchedWebSocket = function (- this: unknown,- url: string | URL,- protocols?: string | string[]- ) {- const urlString = String(url);- if (statsPathPattern.test(urlString)) {- return new MockStatsWebSocket(urlString);- }- return protocols === undefined- ? new NativeWebSocket(url)- : new NativeWebSocket(url, protocols);- } as unknown as typeof WebSocket;-- Object.defineProperties(PatchedWebSocket, {- CONNECTING: { value: NativeWebSocket.CONNECTING },- OPEN: { value: NativeWebSocket.OPEN },- CLOSING: { value: NativeWebSocket.CLOSING },- CLOSED: { value: NativeWebSocket.CLOSED }- });- PatchedWebSocket.prototype = NativeWebSocket.prototype;-- browserWindow.WebSocket = PatchedWebSocket;- },- { statsPayload: mockedStats, options }- );-}--async function allowStatsConnections(page: Page) {- await page.evaluate(() => {- (- globalThis as typeof globalThis & { __arcaneStatsMock: { failConnections: boolean } }- ).__arcaneStatsMock.failConnections = false;- });-}--async function mockInputCapabilities(page: Page, hoverNone: boolean, maxTouchPoints: number) {- await page.addInitScript(- ({ hoverNone, maxTouchPoints }) => {- Object.defineProperty(navigator, 'maxTouchPoints', {- configurable: true,- get: () => maxTouchPoints- });-- const nativeMatchMedia = window.matchMedia.bind(window);- window.matchMedia = (query: string) => {- if (query !== '(hover: none)') {- return nativeMatchMedia(query);- }-- return {- matches: hoverNone,- media: query,- onchange: null,- addEventListener: () => undefined,- removeEventListener: () => undefined,- addListener: () => undefined,- removeListener: () => undefined,- dispatchEvent: () => true- } as MediaQueryList;- };- },- { hoverNone, maxTouchPoints }- );-}--function collectDashboardRequestPaths(page: Page): string[] {- const requestPaths: string[] = [];-- page.on('request', (request) => {- const pathname = new URL(request.url()).pathname;- if (- pathname === '/api/stream' ||- pathname.startsWith('/api/environments/') ||- pathname.startsWith('/api/dashboard/')- ) {- requestPaths.push(pathname);- }- });-- return requestPaths;-}--function countMatchingRequests(paths: string[], pattern: RegExp): number {- return paths.filter((path) => pattern.test(path)).length;-}--// Environment cards expose everything but "Use" through a row actions menu.-async function openEnvironmentActionsMenu(page: Page) {- const trigger = page- .locator('main')- .getByRole('button', { name: 'Open menu', exact: true })- .first();- await expect(trigger).toBeVisible();- await trigger.click();- const menu = page.getByRole('menu').filter({ visible: true }).last();- await expect(menu).toBeVisible();- return menu;-}--test.describe('Dashboard system stats websocket', () => {- test('renders metrics from the system stats websocket stream', async ({ page }) => {- await mockDashboardStatsWebSocket(page);-- await page.goto(defaultDashboardPath);- await page.waitForLoadState('load');-- await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();- await expect(page.getByText('12.3%', { exact: true })).toBeVisible();- await expect(page.getByText('50.0%', { exact: true })).toBeVisible();- await expect(page.getByText('25.0%', { exact: true })).toBeVisible();- await expect(page.getByText('7 CPUs', { exact: true })).toBeVisible();- await expect(page.getByText('512 MB / 1 GB', { exact: true })).toBeVisible();- await expect(page.getByText('256 MB / 1 GB', { exact: true })).toBeVisible();- await expect(page.locator('main').getByText('Local Docker', { exact: true })).toBeVisible();- });-- test('keeps skeletons until the deadline when the stream opens without a sample', async ({- page- }) => {- await page.clock.install();- await mockDashboardStatsWebSocket(page, { deliverAfterMs: 12_000 });-- await page.goto(defaultDashboardPath);- await page.waitForLoadState('load');- await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();-- await page.clock.runFor(5_000);- await expect(page.getByText('Live stats unavailable', { exact: true })).toHaveCount(0);- await expect(page.getByText('12.3%', { exact: true })).toHaveCount(0);-- await page.clock.runFor(5_000);- await expect(page.getByText('Live stats unavailable', { exact: true })).toBeVisible();- await expect(page.getByText('12.3%', { exact: true })).toHaveCount(0);-- await page.clock.runFor(2_000);- await expect(page.getByText('12.3%', { exact: true })).toBeVisible();- await expect(page.getByText('Live stats unavailable', { exact: true })).toHaveCount(0);- });-- test('shows unavailable metrics on connection failure and recovers on refresh', async ({- page- }) => {- await mockDashboardStatsWebSocket(page, { failConnections: true });-- await page.goto(defaultDashboardPath);- await page.waitForLoadState('load');- await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();-- await expect(page.getByText('Live stats unavailable', { exact: true })).toBeVisible();- await expect(page.getByText('12.3%', { exact: true })).toHaveCount(0);-- await allowStatsConnections(page);- await page.getByRole('button', { name: 'Refresh', exact: true }).click();-- await expect(page.getByText('12.3%', { exact: true })).toBeVisible();- await expect(page.getByText('Live stats unavailable', { exact: true })).toHaveCount(0);- });-- test('keeps the last sample and flags it stale after the stream disconnects', async ({- page- }) => {- await mockDashboardStatsWebSocket(page, { closeAfterMessage: true });-- await page.goto(defaultDashboardPath);- await page.waitForLoadState('load');- await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();-- await expect(page.getByText('12.3%', { exact: true })).toBeVisible();- await expect(page.getByText("Live stats aren't updating", { exact: true })).toBeVisible();- });-- test('loads dashboard content without eagerly loading docker info', async ({ page }) => {- await mockDashboardStatsWebSocket(page);- const requestPaths = collectDashboardRequestPaths(page);-- await page.goto(defaultDashboardPath);- await page.waitForLoadState('load');- await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();-- await expect.poll(() => requestPaths).toContain('/api/stream');-- expect(- countMatchingRequests(requestPaths, /\/api\/environments\/[^/]+\/system\/docker\/info$/)- ).toBe(0);- });-- test('lazy loads docker info when the inspect dialog opens and reuses the cached result', async ({- page- }) => {- await mockDashboardStatsWebSocket(page);- const requestPaths = collectDashboardRequestPaths(page);-- await page.goto(defaultDashboardPath);- await page.waitForLoadState('load');- await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();-- expect(- countMatchingRequests(requestPaths, /\/api\/environments\/[^/]+\/system\/docker\/info$/)- ).toBe(0);-- await openEnvironmentActionsMenu(page).then((menu) =>- menu.getByRole('menuitem', { name: 'Inspect', exact: true }).click()- );- await expect(page.getByRole('dialog')).toBeVisible();- await expect- .poll(() =>- countMatchingRequests(requestPaths, /\/api\/environments\/[^/]+\/system\/docker\/info$/)- )- .toBe(1);-- await page.getByRole('button', { name: 'Close', exact: true }).click();- await expect(page.getByRole('dialog')).not.toBeVisible();-- await openEnvironmentActionsMenu(page).then((menu) =>- menu.getByRole('menuitem', { name: 'Inspect', exact: true }).click()- );- await page.waitForTimeout(300);-- expect(- countMatchingRequests(requestPaths, /\/api\/environments\/[^/]+\/system\/docker\/info$/)- ).toBe(1);- });-});--test.describe('Dashboard environment actions', () => {- test('exposes secondary environment actions through the row menu', async ({ page }) => {- await mockInputCapabilities(page, false, 5);- await mockDashboardStatsWebSocket(page);-- await page.goto(defaultDashboardPath);- await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();-- const menu = await openEnvironmentActionsMenu(page);- await expect(menu.getByRole('menuitem', { name: 'View Details', exact: true })).toBeVisible();- await expect(menu.getByRole('menuitem', { name: 'Inspect', exact: true })).toBeVisible();- });-- test('keeps the use action and the menu trigger keyboard reachable', async ({ page }) => {- await mockInputCapabilities(page, false, 0);- await mockDashboardStatsWebSocket(page);-- await page.goto(defaultDashboardPath);- await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();-- const useButton = page- .locator('main')- .getByRole('button', { name: 'Current', exact: true })- .first();- const menuTrigger = page- .locator('main')- .getByRole('button', { name: 'Open menu', exact: true })- .first();- await expect(useButton).toBeVisible();- await expect(menuTrigger).toBeVisible();-- await menuTrigger.focus();- await expect(menuTrigger).toBeFocused();-- const focusShadow = await menuTrigger.evaluate(- (element) => getComputedStyle(element).boxShadow- );- expect(focusShadow).not.toBe('none');- });-- test('disables the use action for the environment already in use', async ({ page }) => {- await mockInputCapabilities(page, true, 5);- await mockDashboardStatsWebSocket(page);-- await page.goto(defaultDashboardPath);- await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();-- const currentButton = page- .locator('main')- .getByRole('button', { name: 'Current', exact: true })- .first();- await expect(currentButton).toBeVisible();- await expect(currentButton).toBeDisabled();- });-});diff --git a/tests/spec/dashboard.spec.ts b/tests/spec/dashboard.spec.tsnew file mode 100644index 000000000..9bf34556f--- /dev/null+++ b/tests/spec/dashboard.spec.ts@@ -0,0 +1,204 @@+import type { WebSocketRoute } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';++const defaultDashboardPath = '/dashboard';++const mockedStats = {+ cpuUsage: 12.3,+ memoryUsage: 512 * 1024 * 1024,+ memoryTotal: 1024 * 1024 * 1024,+ diskUsage: 256 * 1024 * 1024,+ diskTotal: 1024 * 1024 * 1024,+ cpuCount: 7,+ architecture: 'amd64',+ platform: 'linux',+ hostname: 'edge-client',+ gpuCount: 0,+ gpus: []+};++async function mockDashboardStatsWebSocket(+ page: Page,+ { delaySample = false, failConnections = false, closeAfterMessage = false } = {}+) {+ const pendingSockets: WebSocketRoute[] = [];+ await page.routeWebSocket(/\/api\/environments\/[^/]+\/ws\/system\/stats(?:\?.*)?$/, (socket) => {+ if (failConnections) {+ socket.close({ code: 1011, reason: 'Stats unavailable' });+ return;+ }+ if (delaySample) {+ pendingSockets.push(socket);+ return;+ }+ socket.send(JSON.stringify(mockedStats));+ if (closeAfterMessage) {+ failConnections = true;+ socket.close({ code: 1011, reason: 'Stats unavailable' });+ }+ });+ return {+ allowConnections() {+ failConnections = false;+ },+ deliverSample() {+ for (const socket of pendingSockets) socket.send(JSON.stringify(mockedStats));+ pendingSockets.length = 0;+ }+ };+}++// Environment cards expose everything but "Use" through a row actions menu.+async function openEnvironmentActionsMenu(page: Page) {+ const trigger = page+ .locator('main')+ .getByRole('button', { name: 'Open menu', exact: true })+ .first();+ await expect(trigger).toBeVisible();+ await trigger.click();+ const menu = page.getByRole('menu').filter({ visible: true }).last();+ await expect(menu).toBeVisible();+ return menu;+}++test.describe('Dashboard system stats websocket', () => {+ test('renders metrics from the system stats websocket stream', async ({ page }) => {+ await mockDashboardStatsWebSocket(page);++ await page.goto(defaultDashboardPath);+ await page.waitForLoadState('load');++ await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();+ await expect(page.getByText('12.3%', { exact: true })).toBeVisible();+ await expect(page.getByText('50.0%', { exact: true })).toBeVisible();+ await expect(page.getByText('25.0%', { exact: true })).toBeVisible();+ await expect(page.getByText('7 CPUs', { exact: true })).toBeVisible();+ await expect(page.getByText('512 MB / 1 GB', { exact: true })).toBeVisible();+ await expect(page.getByText('256 MB / 1 GB', { exact: true })).toBeVisible();+ await expect(page.locator('main').getByText('Local Docker', { exact: true })).toBeVisible();+ });++ test('keeps skeletons until the deadline when the stream opens without a sample', async ({+ page+ }) => {+ await page.clock.install();+ const stats = await mockDashboardStatsWebSocket(page, { delaySample: true });++ await page.goto(defaultDashboardPath);+ await page.waitForLoadState('load');+ await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();++ await page.clock.runFor(5_000);+ await expect(page.getByText('Live stats unavailable', { exact: true })).toHaveCount(0);+ await expect(page.getByText('12.3%', { exact: true })).toHaveCount(0);++ await page.clock.runFor(5_000);+ await expect(page.getByText('Live stats unavailable', { exact: true })).toBeVisible();+ await expect(page.getByText('12.3%', { exact: true })).toHaveCount(0);++ stats.deliverSample();+ await expect(page.getByText('12.3%', { exact: true })).toBeVisible();+ await expect(page.getByText('Live stats unavailable', { exact: true })).toHaveCount(0);+ });++ test('shows unavailable metrics on connection failure and recovers on refresh', async ({+ page+ }) => {+ const stats = await mockDashboardStatsWebSocket(page, { failConnections: true });++ await page.goto(defaultDashboardPath);+ await page.waitForLoadState('load');+ await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();++ await expect(page.getByText('Live stats unavailable', { exact: true })).toBeVisible();+ await expect(page.getByText('12.3%', { exact: true })).toHaveCount(0);++ stats.allowConnections();+ await page.getByRole('button', { name: 'Refresh', exact: true }).click();++ await expect(page.getByText('12.3%', { exact: true })).toBeVisible();+ await expect(page.getByText('Live stats unavailable', { exact: true })).toHaveCount(0);+ });++ test('keeps the last sample and flags it stale after the stream disconnects', async ({+ page+ }) => {+ await mockDashboardStatsWebSocket(page, { closeAfterMessage: true });++ await page.goto(defaultDashboardPath);+ await page.waitForLoadState('load');+ await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();++ await expect(page.getByText('12.3%', { exact: true })).toBeVisible();+ await expect(page.getByText("Live stats aren't updating", { exact: true })).toBeVisible();+ });++ test('inspects Docker engine information and can reopen the dialog', async ({ page }) => {+ await mockDashboardStatsWebSocket(page);+ await page.goto(defaultDashboardPath);+ const info = await page.request.get('/api/environments/0/system/docker/info');+ expect(info.ok()).toBe(true);+ const data = await info.json();+ for (let attempt = 0; attempt < 2; attempt += 1) {+ const menu = await openEnvironmentActionsMenu(page);+ await menu.getByRole('menuitem', { name: 'Inspect', exact: true }).click();+ const dialog = page.getByRole('dialog');+ await expect(dialog.getByText(data.ServerVersion, { exact: true })).toBeVisible();+ await dialog.getByRole('button', { name: 'Close', exact: true }).click();+ await expect(dialog).toBeHidden();+ }+ });+});++test.describe('Dashboard environment actions', () => {+ test('opens environment details through the row menu', async ({ page }) => {+ await mockDashboardStatsWebSocket(page);++ await page.goto(defaultDashboardPath);+ await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();++ const menu = await openEnvironmentActionsMenu(page);+ await menu.getByRole('menuitem', { name: 'View Details', exact: true }).click();+ await expect(page).toHaveURL(/\/environments\/0(?:\?.*)?$/);+ });++ test('keeps the use action and the menu trigger keyboard reachable', async ({ page }) => {+ await mockDashboardStatsWebSocket(page);++ await page.goto(defaultDashboardPath);+ await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();++ const useButton = page+ .locator('main')+ .getByRole('button', { name: 'Current', exact: true })+ .first();+ const menuTrigger = page+ .locator('main')+ .getByRole('button', { name: 'Open menu', exact: true })+ .first();+ await expect(useButton).toBeVisible();+ await expect(menuTrigger).toBeVisible();++ await menuTrigger.focus();+ await expect(menuTrigger).toBeFocused();++ await page.keyboard.press('Enter');+ await expect(page.getByRole('menu')).toBeVisible();+ await page.keyboard.press('Escape');+ await expect(menuTrigger).toBeFocused();+ });++ test('disables the use action for the environment already in use', async ({ page }) => {+ await mockDashboardStatsWebSocket(page);++ await page.goto(defaultDashboardPath);+ await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();++ const currentButton = page+ .locator('main')+ .getByRole('button', { name: 'Current', exact: true })+ .first();+ await expect(currentButton).toBeVisible();+ await expect(currentButton).toBeDisabled();+ });+});diff --git a/tests/spec/diagnostics-logs.spec.ts b/tests/spec/diagnostics-logs.spec.tsdeleted file mode 100644index 5989dba15..000000000--- a/tests/spec/diagnostics-logs.spec.ts+++ /dev/null@@ -1,134 +0,0 @@-import { expect, test, type Page } from '../fixtures/test.fixture';--const duplicateLogEntry = {- time: '2026-07-25T02:00:00.000Z',- level: 'INFO',- message: 'duplicate diagnostic entry'-};--async function mockDiagnosticsLogsWebSocket(page: Page) {- await page.addInitScript((logEntry) => {- const browserWindow = globalThis as typeof globalThis & {- WebSocket: any;- EventTarget: any;- Event: any;- MessageEvent: any;- CloseEvent: any;- };-- const NativeWebSocket = browserWindow.WebSocket;- const diagnosticsLogsPathPattern = /\/api\/diagnostics\/logs\/stream(?:\?.*)?$/;-- class MockDiagnosticsLogsWebSocket extends browserWindow.EventTarget {- static CONNECTING = 0;- static OPEN = 1;- static CLOSING = 2;- static CLOSED = 3;-- url: string;- readyState = MockDiagnosticsLogsWebSocket.CONNECTING;- bufferedAmount = 0;- extensions = '';- protocol = '';- binaryType = 'blob';- onopen: ((event: unknown) => void) | null = null;- onmessage: ((event: unknown) => void) | null = null;- onerror: ((event: unknown) => void) | null = null;- onclose: ((event: unknown) => void) | null = null;-- constructor(url: string | URL) {- super();- this.url = String(url);-- queueMicrotask(() => {- if (this.readyState !== MockDiagnosticsLogsWebSocket.CONNECTING) return;-- this.readyState = MockDiagnosticsLogsWebSocket.OPEN;-- const openEvent = new browserWindow.Event('open');- this.dispatchEvent(openEvent);- this.onopen?.(openEvent);-- for (let index = 0; index < 2; index += 1) {- const messageEvent = new browserWindow.MessageEvent('message', {- data: JSON.stringify(logEntry)- });-- this.dispatchEvent(messageEvent);- this.onmessage?.(messageEvent);- }- });- }-- send(_data?: string | ArrayBufferLike | Blob | ArrayBufferView) {}-- close(code = 1000, reason = '') {- if (this.readyState === MockDiagnosticsLogsWebSocket.CLOSED) return;-- this.readyState = MockDiagnosticsLogsWebSocket.CLOSED;-- const closeEvent = new browserWindow.CloseEvent('close', {- code,- reason,- wasClean: true- });-- this.dispatchEvent(closeEvent);- this.onclose?.(closeEvent);- }- }-- const PatchedWebSocket = function (- this: unknown,- url: string | URL,- protocols?: string | string[]- ) {- const urlString = String(url);-- if (diagnosticsLogsPathPattern.test(urlString)) {- return new MockDiagnosticsLogsWebSocket(urlString);- }-- return protocols === undefined- ? new NativeWebSocket(url)- : new NativeWebSocket(url, protocols);- } as unknown as typeof WebSocket;-- Object.defineProperties(PatchedWebSocket, {- CONNECTING: { value: NativeWebSocket.CONNECTING },- OPEN: { value: NativeWebSocket.OPEN },- CLOSING: { value: NativeWebSocket.CLOSING },- CLOSED: { value: NativeWebSocket.CLOSED }- });-- PatchedWebSocket.prototype = NativeWebSocket.prototype;- browserWindow.WebSocket = PatchedWebSocket;- }, duplicateLogEntry);-}--test.describe('Diagnostics logs', () => {- test('renders identical log entries without duplicate-key failure', async ({ page }) => {- await mockDiagnosticsLogsWebSocket(page);-- const pageErrors: Error[] = [];- let recentLogsRequests = 0;-- page.on('pageerror', (error) => pageErrors.push(error));- page.on('request', (request) => {- const url = new URL(request.url());-- if (url.pathname === '/api/diagnostics/logs') {- recentLogsRequests += 1;- }- });-- await page.goto('/settings/diagnostics?tab=logs');- await page.waitForLoadState('domcontentloaded');-- await expect(page).toHaveURL(/\/settings\/diagnostics/);- await expect(page.getByText('duplicate diagnostic entry', { exact: true })).toHaveCount(2);-- expect(recentLogsRequests).toBe(0);- expect(pageErrors.map((error) => error.message).join('\n')).not.toContain('each_key_duplicate');- });-});diff --git a/tests/spec/edge-agent.spec.ts b/tests/spec/edge-agent.spec.tsdeleted file mode 100644index f039808a6..000000000--- a/tests/spec/edge-agent.spec.ts+++ /dev/null@@ -1,163 +0,0 @@-import { removeApiResource } from '../utils/fetch.util';-import { test, expect, type Page } from '../fixtures/test.fixture';--const ROUTES = {- environments: '/environments'-};--async function openNewEnvironmentSheet(page: Page) {- await page.goto(ROUTES.environments);- await page.waitForLoadState('load');-- const addButton = page.getByRole('button', { name: 'Add Environment', exact: true });- await expect(addButton).toBeVisible();- await addButton.click();-- await expect(page.getByText('Create New Agent Environment')).toBeVisible();-}--async function switchToEdgeMode(page: Page) {- await page.getByRole('tab', { name: 'Edge', exact: true }).click();- await expect(page.getByText('Agent connects outbound to the manager.')).toBeVisible();-}--test.describe('Edge Agent Environment', () => {- test('should display the edge agent form', async ({ page }) => {- await openNewEnvironmentSheet(page);-- await switchToEdgeMode(page);-- await expect(page.getByPlaceholder('Remote Docker Host')).toBeVisible();- await expect(- page.getByRole('button', { name: 'Generate Agent Configuration', exact: true })- ).toBeVisible();- });-- test('should switch between direct and edge connection modes', async ({ page }) => {- await openNewEnvironmentSheet(page);-- await expect(page.locator('#new-agent-api-url')).toBeVisible();- await expect(page.getByPlaceholder('Remote Docker Host')).toBeHidden();-- await switchToEdgeMode(page);- await expect(page.locator('#new-agent-api-url')).toBeHidden();- await expect(page.getByPlaceholder('Remote Docker Host')).toBeVisible();-- await page.getByRole('tab', { name: 'Direct', exact: true }).click();- await expect(page.locator('#new-agent-api-url')).toBeVisible();- await expect(page.getByPlaceholder('Remote Docker Host')).toBeHidden();- });-- test('should validate required fields for edge and direct modes', async ({ page }) => {- await openNewEnvironmentSheet(page);- let createRequests = 0;-- await page.route('**/api/environments', async (route) => {- if (route.request().method() === 'POST') {- createRequests += 1;- }- await route.continue();- });-- // Direct mode: missing name and URL- await page.getByRole('button', { name: 'Generate Agent Configuration', exact: true }).click();- await expect.poll(() => createRequests).toBe(0);-- // Edge mode: missing name- await switchToEdgeMode(page);- await page.getByRole('button', { name: 'Generate Agent Configuration', exact: true }).click();- await expect.poll(() => createRequests).toBe(0);- });-- test('should create an edge agent environment and show deployment snippets', async ({ page }) => {- const environmentName = `edge-agent-${Date.now().toString().slice(-6)}`;- let createdEnvironmentId: string | null = null;- const agentSettingsRequests: string[] = [];- page.on('request', (request) => {- if (!createdEnvironmentId) return;- const pathname = new URL(request.url()).pathname;- if (- pathname === `/api/environments/${createdEnvironmentId}/settings` ||- pathname === `/api/environments/${createdEnvironmentId}/settings/public`- ) {- agentSettingsRequests.push(pathname);- }- });-- await page.route('**/api/environments', async (route) => {- if (route.request().method() === 'POST') {- const response = await route.fetch();- const body = await response.text();- try {- const parsed = JSON.parse(body);- createdEnvironmentId = parsed?.data?.id ?? parsed?.id ?? null;- } catch {- createdEnvironmentId = createdEnvironmentId ?? null;- }-- await route.fulfill({- status: response.status(),- headers: response.headers(),- body- });- return;- }-- await route.continue();- });-- try {- await openNewEnvironmentSheet(page);- await switchToEdgeMode(page);-- await page.getByPlaceholder('Remote Docker Host').fill(environmentName);- const submitButton = page.getByRole('button', {- name: 'Generate Agent Configuration',- exact: true- });- await submitButton.click();-- const sheetTitle = page.locator('[data-slot="sheet-title"]');- await expect(sheetTitle).toContainText('Environment Created');- await expect(- page.getByText('Edge agent - connects outbound to manager', { exact: true })- ).toBeVisible();- await expect(page.getByText('API Key', { exact: true })).toBeVisible();- await expect(page.getByText('Docker Run Command', { exact: true })).toBeVisible();- await expect(page.getByText('Docker Compose', { exact: true })).toBeVisible();-- const snippetBlocks = page.locator('pre code').filter({ hasText: 'EDGE_AGENT=true' });- await expect(snippetBlocks.first()).toBeVisible();-- const dockerRunSnippet = snippetBlocks.first();- await expect(dockerRunSnippet).toContainText('arcane-edge-agent');- await expect(dockerRunSnippet).not.toContainText('-p 3553:3553');-- await page.getByRole('button', { name: 'Done', exact: true }).click();-- await expect(page.getByRole('button', { name: environmentName, exact: true })).toBeVisible();- const environmentRow = page.locator('tr').filter({- has: page.getByRole('button', { name: environmentName, exact: true })- });- await expect(environmentRow.getByText('edge://edge-agent-').first()).toBeVisible();- await expect(environmentRow.getByText('Edge', { exact: true })).toBeVisible();-- await page.getByRole('button', { name: environmentName, exact: true }).click();- if (createdEnvironmentId) {- await expect(page).toHaveURL(new RegExp(`/environments/${createdEnvironmentId}`));- }-- await expect(page.getByTitle('API URL', { exact: true })).toHaveText(/edge:\/\/edge-agent-/);- await expect(page.getByText('Edge', { exact: true }).first()).toBeVisible();- await expect(page.getByText('Live Tunnel', { exact: true })).toBeVisible();- await expect(- page.getByRole('tab', { name: 'Connection & Edge', exact: true })- ).toHaveAttribute('data-state', 'active');- expect(agentSettingsRequests).toEqual([]);- } finally {- if (createdEnvironmentId) {- await removeApiResource(page, `/api/environments/${createdEnvironmentId}`);- }- }- });-});diff --git a/tests/spec/environment-settings.spec.ts b/tests/spec/environment-settings.spec.tsdeleted file mode 100644index 0135784dc..000000000--- a/tests/spec/environment-settings.spec.ts+++ /dev/null@@ -1,604 +0,0 @@-import { waitForDialogReady } from '../utils/playwright.util';-import { removeApiResource } from '../utils/fetch.util';-import { test, expect, type Locator, type Page, type Request } from '../fixtures/test.fixture';--const LOCAL_ENV_ID = '0';-const NAME_PLACEHOLDER = 'My Lab Server';--async function openEnvironment(page: Page, environmentId: string) {- await page.goto(`/environments/${environmentId}`);- await page.waitForLoadState('load');- await expect(environmentTitleButton(page)).toBeVisible();- await expect(page.getByRole('button', { name: 'Save', exact: true }).first()).toBeVisible();-}--function environmentTitleButton(page: Page) {- return page.locator('h1 button').first();-}--async function renameEnvironmentInHeader(page: Page, newName: string) {- await environmentTitleButton(page).click();- const nameInput = page.getByPlaceholder(NAME_PLACEHOLDER);- await expect(nameInput).toBeVisible();- await nameInput.fill(newName);- await nameInput.press('Enter');- await expect(environmentTitleButton(page)).toHaveText(newName);-}--async function createDirectEnvironmentViaUI(- page: Page,- environmentName: string,- environmentIds: Set<string>-) {- await page.goto('/environments');- await page.waitForLoadState('load');-- await page.getByRole('button', { name: 'Add Environment', exact: true }).click();- await expect(page.getByText('Create New Agent Environment')).toBeVisible();-- const dialog = page.getByRole('dialog');- await waitForDialogReady(dialog);- await dialog.getByLabel('Name', { exact: true }).fill(environmentName);- await dialog.getByLabel('Agent Address', { exact: true }).fill('localhost:3552');- const createResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === '/api/environments'- );- await page.getByRole('button', { name: 'Generate Agent Configuration', exact: true }).click();- const createResponse = await createResponsePromise;- expect(createResponse.ok(), 'Create direct environment').toBeTruthy();- const created: { data: { id: string; apiKey?: string } } = await createResponse.json();- environmentIds.add(created.data.id);- expect(created.data.id).toBeTruthy();- if (!created.data.apiKey) throw new Error('New agent environment did not return an API key');-- await expect(- page.getByRole('heading', { name: 'Environment Created Successfully', exact: true })- ).toBeVisible();- await page.getByRole('button', { name: 'Done', exact: true }).click();- await expect(page.getByRole('button', { name: environmentName, exact: true })).toBeVisible();- return { id: created.data.id, apiKey: created.data.apiKey };-}--async function removeCreatedEnvironments(- page: Page,- environmentIds: Set<string>,- environmentName: string-) {- // A login redirect can swallow the create response, so also match by name.- const response = await page.request.get('/api/environments?start=0&limit=1000');- if (response.ok()) {- const { data }: { data: Array<{ id: string; name: string }> } = await response.json();- for (const env of data) if (env.name.startsWith(environmentName)) environmentIds.add(env.id);- }- for (const id of environmentIds) await removeApiResource(page, `/api/environments/${id}`);-}--async function openLocalEnvironment(page: Page) {- await openEnvironment(page, LOCAL_ENV_ID);-}--async function saveAndWaitForPut(page: Page, expectedPath: string) {- const saveButton = page.getByRole('button', { name: 'Save', exact: true }).first();- await expect(saveButton).toBeEnabled();-- const responsePromise = page.waitForResponse((response) => {- const request = response.request();- if (request.method() !== 'PUT') return false;- const url = new URL(response.url());- return url.pathname === expectedPath;- });-- await saveButton.click();- const response = await responsePromise;- expect(response.ok(), `Expected successful PUT to ${expectedPath}`).toBeTruthy();- await expect(saveButton).toBeDisabled({ timeout: 10000 });- return response.request();-}--async function selectSettingOption(page: Page, trigger: Locator, optionText: string) {- await expect(trigger).toBeVisible();- await trigger.click();- const option = page.getByRole('option').filter({ hasText: optionText }).first();- await expect(option).toBeVisible();- await option.click();-}--test.describe('Environment Settings UI', () => {- test.describe.configure({ mode: 'serial' });- const settingKeys = new Set([- 'baseServerUrl',- 'followProjectSymlinks',- 'defaultDeployPullPolicy',- 'trivyNetwork',- 'trivyResourceLimitsEnabled',- 'trivyMemoryLimitMb',- 'trivyCpuLimit'- ]);- let originalSettings: Record<string, string> = {};- test.beforeEach(async ({ page }) => {- originalSettings = {};- const response = await page.request.get(`/api/environments/${LOCAL_ENV_ID}/settings`);- expect(response.ok(), 'Read original environment settings').toBe(true);- const settings: Array<{ key: string; value: string }> = await response.json();- expect(Array.isArray(settings)).toBe(true);- originalSettings = Object.fromEntries(- settings- .filter((setting) => settingKeys.has(setting.key))- .map((setting) => [setting.key, setting.value])- );- });- test.afterEach(async ({ page }) => {- if (Object.keys(originalSettings).length === 0) return;- try {- const currentResponse = await page.request.get(`/api/environments/${LOCAL_ENV_ID}/settings`);- expect(currentResponse.ok()).toBe(true);- const current: Array<{ key: string; value: string }> = await currentResponse.json();- const changed = Object.fromEntries(- Object.entries(originalSettings).filter(- ([key, value]) => current.find((setting) => setting.key === key)?.value !== value- )- );- if (Object.keys(changed).length === 0) return;- const response = await page.request.put(`/api/environments/${LOCAL_ENV_ID}/settings`, {- data: changed- });- expect(- response.ok(),- `Restore environment settings: ${response.status()} ${await response.text()}`- ).toBe(true);- const restoredResponse = await page.request.get(`/api/environments/${LOCAL_ENV_ID}/settings`);- expect(restoredResponse.ok()).toBe(true);- const restored: Array<{ key: string; value: string }> = await restoredResponse.json();- expect(- Object.fromEntries(- restored- .filter((setting) => settingKeys.has(setting.key))- .map((setting) => [setting.key, setting.value])- )- ).toEqual(originalSettings);- } catch (error) {- expect.soft(false, `Restore environment settings: ${String(error)}`).toBe(true);- }- });-- test('should keep primary tabs selectable and restore them from the URL', async ({ page }) => {- await page.goto('/settings');- await page.waitForLoadState('load');-- const jobScheduleCategory = page.getByRole('button').filter({ hasText: 'Automations' }).first();- await expect(jobScheduleCategory).toBeVisible();- await jobScheduleCategory.click();-- await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('jobs');- await expect(page.getByRole('tab', { name: 'Automations', exact: true })).toHaveAttribute(- 'data-state',- 'active'- );-- const storageTab = page.getByRole('tab', { name: 'Storage & Limits', exact: true });- await storageTab.click();- await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('storage');- await expect(storageTab).toHaveAttribute('data-state', 'active');-- const dockerTab = page.getByRole('tab', { name: 'Docker Settings', exact: true });- await dockerTab.click();- await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('docker');- await page.reload();- await expect(dockerTab).toHaveAttribute('data-state', 'active');-- await page.goto(`/environments/${LOCAL_ENV_ID}?source=e2e&tab=invalid#tab-state`);- await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('features');- const canonicalUrl = new URL(page.url());- expect(canonicalUrl.searchParams.get('source')).toBe('e2e');- expect(canonicalUrl.hash).toBe('#tab-state');- await expect(page.getByRole('tab', { name: 'Features', exact: true })).toHaveAttribute(- 'data-state',- 'active'- );- await expect(page.getByRole('heading', { name: 'Features', exact: true })).toBeVisible();- await expect(- page.getByRole('switch', { name: 'Vulnerability management', exact: true })- ).toBeVisible();- });-- test('should update and save environment details', async ({ page }) => {- test.setTimeout(120_000); // 120 seconds timeout for this lengthy UI workflow- const envName = `settings-ui-${Date.now().toString().slice(-5)}`;- const updatedName = `${envName}-updated`;- const environmentIds = new Set<string>();-- try {- const { id: environmentId, apiKey } = await createDirectEnvironmentViaUI(- page,- envName,- environmentIds- );- const environmentPath = `/api/environments/${environmentId}`;- await page.getByRole('button', { name: envName, exact: true }).click();- await expect(page).toHaveURL(/\/environments\/[^/?]+\?tab=[a-z]+$/);-- const apiUrlButton = page.getByTitle('API URL', { exact: true });- const originalApiUrl = (await apiUrlButton.textContent())!.trim();- const updatedApiUrl = originalApiUrl.replace(':3552', ':3553');- expect(updatedApiUrl).not.toBe(originalApiUrl);-- await renameEnvironmentInHeader(page, updatedName);- const nameRequest = await saveAndWaitForPut(page, environmentPath);- expect(nameRequest.postDataJSON()).not.toHaveProperty('accessToken');-- await page.reload();- await expect(environmentTitleButton(page)).toHaveText(updatedName);-- await apiUrlButton.click();- await page.locator('#api-url').fill(updatedApiUrl);- await page.locator('#api-url').press('Tab');- const tokenInput = page.getByLabel('Agent access token', { exact: true });- await expect(tokenInput).toBeVisible();- await expect(tokenInput).toHaveAttribute('type', 'password');- await expect(tokenInput).toHaveValue('');-- const rejectedResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'PUT' &&- new URL(response.url()).pathname === environmentPath- );- await page.getByRole('button', { name: 'Save', exact: true }).first().click();- const rejectedResponse = await rejectedResponsePromise;- expect(rejectedResponse.status()).toBe(400);- expect(rejectedResponse.request().postDataJSON()).not.toHaveProperty('accessToken');- await expect(- page.getByText('Changing environment API URL requires re-entering the accessToken')- ).toBeVisible();- const afterRejection = await page.request.get(environmentPath);- expect(afterRejection.ok()).toBe(true);- expect(((await afterRejection.json()) as { data: { apiUrl: string } }).data.apiUrl).toBe(- originalApiUrl- );-- await tokenInput.fill(apiKey);- await apiUrlButton.click();- await page.locator('#api-url').fill(`${updatedApiUrl}/changed`);- await page.locator('#api-url').press('Tab');- await expect(tokenInput).toHaveValue('');- await apiUrlButton.click();- await page.locator('#api-url').fill(updatedApiUrl);- await page.locator('#api-url').press('Tab');- await tokenInput.fill(apiKey);- await page.route(`**${environmentPath}`, async (route) => {- if (route.request().method() !== 'PUT') return route.continue();- await route.fulfill({- status: 503,- contentType: 'application/problem+json',- body: JSON.stringify({ detail: 'Temporary update failure' })- });- });- const failedResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'PUT' &&- new URL(response.url()).pathname === environmentPath- );- await page.getByRole('button', { name: 'Save', exact: true }).first().click();- expect((await failedResponsePromise).status()).toBe(503);- await expect(page.getByText('Temporary update failure')).toBeVisible();- expect((await tokenInput.inputValue()) === apiKey).toBe(true);- await page.unroute(`**${environmentPath}`);-- const updateRequest = await saveAndWaitForPut(page, environmentPath);- const updatePayload = updateRequest.postDataJSON() as Record<string, unknown>;- expect(updatePayload.apiUrl).toBe(updatedApiUrl);- expect(updatePayload.accessToken === apiKey).toBe(true);- await expect(tokenInput).toBeHidden();- await apiUrlButton.click();- await page.locator('#api-url').fill(`${updatedApiUrl}/another`);- await page.locator('#api-url').press('Tab');- await expect(tokenInput).toHaveValue('');- await apiUrlButton.click();- await page.locator('#api-url').press('Escape');- await expect(apiUrlButton).toHaveText(updatedApiUrl);- await expect(tokenInput).toBeHidden();-- await page.reload();- await expect(apiUrlButton).toHaveText(updatedApiUrl);- await expect(tokenInput).toBeHidden();- await renameEnvironmentInHeader(page, `${updatedName}-again`);- const secondNameRequest = await saveAndWaitForPut(page, environmentPath);- expect(secondNameRequest.postDataJSON()).not.toHaveProperty('accessToken');- } finally {- await removeCreatedEnvironments(page, environmentIds, envName);- }- });-- test('should update and save the base server URL in Docker settings', async ({ page }) => {- await openLocalEnvironment(page);- await expect(page.getByLabel('Agent access token', { exact: true })).toBeHidden();- await page.getByRole('tab', { name: 'Docker Settings', exact: true }).click();-- const baseServerUrlInput = page.locator('#base-server-url');- await expect(baseServerUrlInput).toBeVisible();-- const originalBaseServerUrl = await baseServerUrlInput.inputValue();- const updatedBaseServerUrl = originalBaseServerUrl.endsWith('/e2e')- ? `${originalBaseServerUrl}-2`- : `${originalBaseServerUrl}/e2e`;-- try {- await baseServerUrlInput.fill(updatedBaseServerUrl);- await expect(baseServerUrlInput).toHaveValue(updatedBaseServerUrl);- const settingsRequest = await saveAndWaitForPut(- page,- `/api/environments/${LOCAL_ENV_ID}/settings`- );- expect(settingsRequest.postDataJSON()).not.toHaveProperty('accessToken');-- await page.reload();- await page.getByRole('tab', { name: 'Docker Settings', exact: true }).click();- await expect(page.locator('#base-server-url')).toHaveValue(updatedBaseServerUrl, {- timeout: 15000- });- } finally {- if (!page.isClosed()) {- await page.getByRole('tab', { name: 'Docker Settings', exact: true }).click();- const currentValue = await page.locator('#base-server-url').inputValue();- if (currentValue !== originalBaseServerUrl) {- await page.locator('#base-server-url').fill(originalBaseServerUrl);- await saveAndWaitForPut(page, `/api/environments/${LOCAL_ENV_ID}/settings`);- }- }- }- });-- test('should update and save the follow project symlinks setting from Storage & Limits', async ({- page- }) => {- await openLocalEnvironment(page);- await page.getByRole('tab', { name: 'Storage & Limits', exact: true }).click();-- const followProjectSymlinksSwitch = page.locator('#follow-project-symlinks');- await expect(followProjectSymlinksSwitch).toBeVisible();-- const originalChecked =- (await followProjectSymlinksSwitch.getAttribute('aria-checked')) === 'true';- const updatedChecked = !originalChecked;-- try {- await followProjectSymlinksSwitch.click();- await expect(followProjectSymlinksSwitch).toHaveAttribute(- 'aria-checked',- String(updatedChecked)- );-- const saveButton = page.getByRole('button', { name: 'Save', exact: true }).first();- await expect(saveButton).toBeEnabled();-- const responsePromise = page.waitForResponse((response) => {- const request = response.request();- if (request.method() !== 'PUT') return false;- const url = new URL(response.url());- return url.pathname === `/api/environments/${LOCAL_ENV_ID}/settings`;- });-- await saveButton.click();- const response = await responsePromise;- expect(response.ok()).toBeTruthy();-- await page.reload();- await page.getByRole('tab', { name: 'Storage & Limits', exact: true }).click();- await expect(page.locator('#follow-project-symlinks')).toHaveAttribute(- 'aria-checked',- String(updatedChecked)- );- } finally {- if (!page.isClosed()) {- await page.getByRole('tab', { name: 'Storage & Limits', exact: true }).click();- const currentChecked =- (await page.locator('#follow-project-symlinks').getAttribute('aria-checked')) === 'true';- if (currentChecked !== originalChecked) {- await page.locator('#follow-project-symlinks').click();- await saveAndWaitForPut(page, `/api/environments/${LOCAL_ENV_ID}/settings`);- }- }- }- });-- test('should reset unsaved environment detail changes', async ({ page }) => {- const envName = `settings-reset-${Date.now().toString().slice(-5)}`;- const environmentIds = new Set<string>();- try {- const { id: environmentId, apiKey } = await createDirectEnvironmentViaUI(- page,- envName,- environmentIds- );- await openEnvironment(page, environmentId);- const titleButton = environmentTitleButton(page);- const apiUrlButton = page.getByTitle('API URL', { exact: true });- const originalApiUrl = (await apiUrlButton.textContent())!.trim();- await renameEnvironmentInHeader(page, `${envName}-pending`);- await apiUrlButton.click();- await page.locator('#api-url').fill(originalApiUrl.replace(':3552', ':3553'));- await page.locator('#api-url').press('Tab');- const tokenInput = page.getByLabel('Agent access token', { exact: true });- await tokenInput.fill(apiKey);-- const saveButton = page.getByRole('button', { name: 'Save', exact: true }).first();- const resetButton = page.getByRole('button', { name: 'Reset', exact: true }).first();- await expect(saveButton).toBeEnabled();- await expect(resetButton).toBeVisible();- await resetButton.click();- await expect(titleButton).toHaveText(envName);- await expect(apiUrlButton).toHaveText(originalApiUrl);- await expect(tokenInput).toBeHidden();- await expect(saveButton).toBeDisabled();-- await apiUrlButton.click();- await page.locator('#api-url').fill(originalApiUrl.replace(':3552', ':3553'));- await page.locator('#api-url').press('Tab');- await expect(tokenInput).toHaveValue('');- await tokenInput.fill(apiKey);- await page.getByRole('button', { name: 'Back to Environments', exact: true }).click();- await expect(page).toHaveURL(/\/environments$/);- await expect(page.getByRole('heading', { name: 'Environments', exact: true })).toBeVisible();- await page.getByRole('button', { name: envName, exact: true }).click();- await expect(page).toHaveURL(new RegExp(`/environments/${environmentId}(?:\\?|$)`));- await expect(environmentTitleButton(page)).toHaveText(envName);- await apiUrlButton.click();- await page.locator('#api-url').fill(originalApiUrl.replace(':3552', ':3553'));- await page.locator('#api-url').press('Tab');- await expect(tokenInput).toHaveValue('');- } finally {- await removeCreatedEnvironments(page, environmentIds, envName);- }- });-- test('should update and save the default deploy pull policy in Docker settings', async ({- page- }) => {- await openLocalEnvironment(page);-- const dockerTab = page.getByRole('tab', { name: 'Docker Settings', exact: true });- await dockerTab.click();- const pullPolicyTrigger = page.locator('#defaultDeployPullPolicy');- await expect(pullPolicyTrigger).toBeVisible();-- const originalValue = (await pullPolicyTrigger.textContent())?.trim() || 'Missing';- const updatedValue = originalValue.includes('Always') ? 'Never' : 'Always';-- try {- await selectSettingOption(page, pullPolicyTrigger, updatedValue);- await expect(pullPolicyTrigger).toContainText(updatedValue);- await saveAndWaitForPut(page, `/api/environments/${LOCAL_ENV_ID}/settings`);-- await page.reload();- await page.getByRole('tab', { name: 'Docker Settings', exact: true }).click();- await expect(page.locator('#defaultDeployPullPolicy')).toContainText(updatedValue, {- timeout: 15000- });- } finally {- if (!page.isClosed()) {- await page.getByRole('tab', { name: 'Docker Settings', exact: true }).click();- const currentValue = (- (await page.locator('#defaultDeployPullPolicy').textContent()) || ''- ).trim();- if (!currentValue.includes(originalValue)) {- await selectSettingOption(page, page.locator('#defaultDeployPullPolicy'), originalValue);- await saveAndWaitForPut(page, `/api/environments/${LOCAL_ENV_ID}/settings`);- }- }- }- });-- test('should save decimal trivy CPU limits and reject negative values', async ({ page }) => {- test.setTimeout(120_000);- const settingsPath = `/api/environments/${LOCAL_ENV_ID}/settings`;- const settingsResponse = await page.request.get(settingsPath);- expect(settingsResponse.ok()).toBeTruthy();- const settings = (await settingsResponse.json()) as Array<{ key: string; value: string }>;- const originalSettings = Object.fromEntries(- settings- .filter(({ key }) =>- ['trivyResourceLimitsEnabled', 'trivyCpuLimit', 'trivyMemoryLimitMb'].includes(key)- )- .map(({ key, value }) => [key, value])- );- expect(Object.keys(originalSettings)).toHaveLength(3);-- try {- await openLocalEnvironment(page);- await page.getByRole('tab', { name: 'Security', exact: true }).click();- await page.locator('#trivyResourceLimitsEnabledSwitch').setChecked(true);- const cpuInput = page.getByRole('spinbutton', { name: 'CPU Limit (cores)', exact: true });- await expect(cpuInput).toHaveAttribute('min', '0');- await expect(cpuInput).toHaveAttribute('step', 'any');-- const values = ['0.5', '1.5', '2.5', '0.25', '1', '0'];- if ((await cpuInput.inputValue()) === values[0]) values.reverse();-- for (const value of values) {- await cpuInput.fill(value);- expect(await cpuInput.evaluate((input: HTMLInputElement) => input.validity.valid)).toBe(- true- );- const requestPromise = page.waitForRequest(- (request) =>- request.method() === 'PUT' && new URL(request.url()).pathname === settingsPath- );- await saveAndWaitForPut(page, settingsPath);- const payload = (await requestPromise).postDataJSON() as Record<string, unknown>;- expect(payload.trivyCpuLimit).toBe(value);- expect(payload.trivyResourceLimitsEnabled).toBe('true');- await page.reload();- await page.getByRole('tab', { name: 'Security', exact: true }).click();- await expect(cpuInput).toHaveValue(value);- }-- const writes: Request[] = [];- const recordWrite = (request: Request) => {- if (request.method() === 'PUT' && new URL(request.url()).pathname === settingsPath) {- writes.push(request);- }- };- page.on('request', recordWrite);- try {- await cpuInput.fill('-0.5');- await page.getByRole('button', { name: 'Save', exact: true }).first().click();- await expect(- page.getByText('Please check the form for errors.', { exact: true })- ).toBeVisible();- expect(writes).toHaveLength(0);- await page.reload();- await page.getByRole('tab', { name: 'Security', exact: true }).click();- await expect(cpuInput).toHaveValue(values[values.length - 1]);- } finally {- page.off('request', recordWrite);- }- } finally {- const restored = await page.request.put(settingsPath, { data: originalSettings });- expect(restored.ok()).toBeTruthy();- }- });-- test('should update and save the trivy network mode including auto', async ({ page }) => {- await openLocalEnvironment(page);- await page.getByRole('tab', { name: 'Security', exact: true }).click();-- const trivyNetworkTrigger = page.locator('#trivyNetwork');- await expect(trivyNetworkTrigger).toBeVisible();-- const originalValue = ((await trivyNetworkTrigger.textContent()) || '').trim();- const updatedValue = originalValue.includes('bridge') ? 'Auto' : 'bridge';-- try {- await selectSettingOption(page, trivyNetworkTrigger, updatedValue);- await expect(trivyNetworkTrigger).toContainText(updatedValue);-- const saveButton = page.getByRole('button', { name: 'Save', exact: true }).first();- await expect(saveButton).toBeEnabled();-- const responsePromise = page.waitForResponse((response) => {- const request = response.request();- if (request.method() !== 'PUT') return false;- const url = new URL(response.url());- return url.pathname === `/api/environments/${LOCAL_ENV_ID}/settings`;- });-- await saveButton.click();- const response = await responsePromise;- expect(response.ok()).toBeTruthy();-- await page.reload();- await page.getByRole('tab', { name: 'Security', exact: true }).click();- await expect(page.locator('#trivyNetwork')).toContainText(updatedValue);- } finally {- if (!page.isClosed()) {- await page.getByRole('tab', { name: 'Security', exact: true }).click();- const currentValue = ((await page.locator('#trivyNetwork').textContent()) || '').trim();- if (!currentValue.includes(originalValue)) {- await selectSettingOption(page, page.locator('#trivyNetwork'), originalValue);- await saveAndWaitForPut(page, `/api/environments/${LOCAL_ENV_ID}/settings`);- }- }- }- });-});diff --git a/tests/spec/environment-switch-isolation.spec.ts b/tests/spec/environment-switch-isolation.spec.tsdeleted file mode 100644index a97d12b2e..000000000--- a/tests/spec/environment-switch-isolation.spec.ts+++ /dev/null@@ -1,291 +0,0 @@-import { expect, test, type Page, type Route } from '../fixtures/test.fixture';--const localEnvironment = {- id: '0',- name: 'Local Test',- apiUrl: 'unix:///var/run/docker.sock',- status: 'online',- enabled: true,- isEdge: false-};--const remoteEnvironment = {- id: 'remote-switch-test',- name: 'Remote Test',- apiUrl: 'https://remote.example.invalid',- status: 'online',- enabled: true,- isEdge: false-};--function paginated<T>(data: T[]) {- return {- success: true,- data,- counts: {- runningContainers: data.length,- stoppedContainers: 0,- totalContainers: data.length- },- pagination: {- totalPages: 1,- totalItems: data.length,- currentPage: 1,- itemsPerPage: 20,- grandTotalItems: data.length- }- };-}--function containerSummary(id: string, name: string) {- return {- id,- names: [`/${name}`],- image: 'nginx:latest',- imageId: `sha256:${id}`,- command: 'nginx',- created: 1_700_000_000,- labels: {},- state: 'running',- status: 'Up 5 minutes',- ports: [],- hostConfig: { networkMode: 'default' },- networkSettings: { networks: {} },- mounts: []- };-}--function containerDetails(id: string, name: string) {- return {- id,- name,- image: 'nginx:latest',- imageId: `sha256:${id}`,- created: '2026-01-01T00:00:00Z',- state: {- status: 'running',- running: true,- startedAt: '2026-01-01T00:00:00Z',- finishedAt: ''- },- config: {},- hostConfig: { networkMode: 'default' },- networkSettings: { networks: {} },- ports: [],- mounts: [],- labels: {},- redeployDisabled: false- };-}--async function mockEnvironmentCatalog(page: Page) {- await page.addInitScript(() => {- localStorage.removeItem('selectedEnvironmentId');- localStorage.removeItem('arcane-container-table');- });- await page.context().route(/\/api\/environments(?:\?.*)?$/, async (route) => {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify(paginated([localEnvironment, remoteEnvironment]))- });- });- await page.context().route(/\/api\/stream(?:\?.*)?$/, async (route) => {- const channels = new URL(route.request().url()).searchParams.get('channels')?.split(',') ?? [];- const timestamp = new Date().toISOString();- await route.fulfill({- status: 200,- contentType: 'application/x-json-stream',- body: channels.includes('environments')- ? `${JSON.stringify({- channel: 'environments',- environment: {- type: 'snapshot',- environments: [localEnvironment, remoteEnvironment],- timestamp- },- timestamp- })}\n`- : ''- });- });- await page- .context()- .route(/\/api\/environments\/(?:0|remote-switch-test)\/settings$/, async (route) => {- if (route.request().method() !== 'GET') {- await route.continue();- return;- }- await route.fulfill({ status: 200, contentType: 'application/json', body: '{}' });- });-}--async function selectRemoteEnvironment(page: Page) {- await page.getByRole('button').filter({ hasText: localEnvironment.name }).first().click();- const dialog = page.getByRole('dialog', { name: 'Select Environment' });- await expect(dialog).toBeVisible();- await dialog.getByRole('button').filter({ hasText: remoteEnvironment.name }).first().click();-}--test.describe('Environment switch isolation', () => {- test('clears local rows and stats targets while the remote response is delayed', async ({- page- }) => {- let releaseRemote!: () => void;- const remoteGate = new Promise<void>((resolve) => {- releaseRemote = resolve;- });- let markRemoteStarted!: () => void;- const remoteStarted = new Promise<void>((resolve) => {- markRemoteStarted = resolve;- });- let remoteMarked = false;- const websocketPaths: string[] = [];-- await mockEnvironmentCatalog(page);- await page- .context()- .route(/\/api\/environments\/[^/]+\/containers(?:\?.*)?$/, async (route: Route) => {- const pathname = new URL(route.request().url()).pathname;- if (pathname === '/api/environments/remote-switch-test/containers') {- if (!remoteMarked) {- remoteMarked = true;- markRemoteStarted();- }- await remoteGate;- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify(paginated([containerSummary('remote-b-id', 'remote-b-container')]))- });- return;- }- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify(paginated([containerSummary('local-a-id', 'local-a-container')]))- });- });- page.on('websocket', (socket) => websocketPaths.push(new URL(socket.url()).pathname));-- await page.goto('/containers');- await expect(page.getByRole('link', { name: 'local-a-container', exact: true })).toBeVisible();-- try {- await selectRemoteEnvironment(page);- await remoteStarted;- await expect(page.getByRole('link', { name: 'local-a-container', exact: true })).toHaveCount(- 0- );- await page.waitForTimeout(200);- expect(websocketPaths).not.toContain(- '/api/environments/remote-switch-test/ws/containers/local-a-id/stats'- );- } finally {- releaseRemote();- }-- await expect(page.getByRole('link', { name: 'remote-b-container', exact: true })).toBeVisible();- await expect(page.getByRole('link', { name: 'local-a-container', exact: true })).toHaveCount(0);- });-- test('does not restore local rows when the remote request fails', async ({- page,- pageErrorGuard- }) => {- pageErrorGuard.allow('remote unavailable');- await mockEnvironmentCatalog(page);- await page- .context()- .route(/\/api\/environments\/[^/]+\/containers(?:\?.*)?$/, async (route: Route) => {- const pathname = new URL(route.request().url()).pathname;- if (pathname === '/api/environments/remote-switch-test/containers') {- await route.fulfill({- status: 503,- contentType: 'application/json',- body: JSON.stringify({ success: false, message: 'remote unavailable' })- });- return;- }- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify(paginated([containerSummary('local-a-id', 'local-a-container')]))- });- });-- await page.goto('/containers');- await expect(page.getByRole('link', { name: 'local-a-container', exact: true })).toBeVisible();- const failedRemoteRequest = page.waitForResponse((response) => {- return (- new URL(response.url()).pathname === '/api/environments/remote-switch-test/containers' &&- response.status() === 503- );- });- await selectRemoteEnvironment(page);- await failedRemoteRequest;- await expect(page.getByRole('link', { name: 'local-a-container', exact: true })).toHaveCount(0);- });-- test('remounts same-route details and navigates to the unwrapped redeployed container id', async ({- page- }) => {- await page.addInitScript(() => localStorage.removeItem('selectedEnvironmentId'));- const detailsById = {- 'route-a': containerDetails('route-a', 'Route A Container'),- 'route-b': containerDetails('route-b', 'Route B Container'),- 'route-redeployed': containerDetails('route-redeployed', 'Redeployed Container')- };-- await page.context().route(/\/api\/environments\/0\/settings$/, async (route) => {- await route.fulfill({ status: 200, contentType: 'application/json', body: '{}' });- });- await page.context().route(/\/api\/environments\/0\/containers\/([^/?]+)$/, async (route) => {- const id = decodeURIComponent(new URL(route.request().url()).pathname.split('/').pop() ?? '');- const details = detailsById[id as keyof typeof detailsById];- await route.fulfill({- status: details ? 200 : 404,- contentType: 'application/json',- body: JSON.stringify(- details ? { success: true, data: details } : { success: false, message: 'not found' }- )- });- });- await page- .context()- .route(/\/api\/environments\/0\/containers\/route-b\/redeploy$/, async (route) => {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({ success: true, data: detailsById['route-redeployed'] })- });- });-- await page.goto('/containers/route-a');- await expect(page.getByRole('heading', { name: 'Route A Container' })).toBeVisible();- await page.getByRole('tab', { name: 'Logs' }).click();- await expect(page.getByRole('tab', { name: 'Logs' })).toHaveAttribute('aria-selected', 'true');-- await page.evaluate(() => {- const link = document.createElement('a');- link.id = 'same-route-navigation';- link.href = '/containers/route-b';- link.textContent = 'navigate';- document.body.append(link);- });- await page.locator('#same-route-navigation').click();- await expect(page).toHaveURL('/containers/route-b?tab=overview');- await expect(page.getByRole('heading', { name: 'Route B Container' })).toBeVisible();- await expect(page.getByRole('tab', { name: 'Overview' })).toHaveAttribute(- 'aria-selected',- 'true'- );-- await page.getByRole('button', { name: 'More actions', exact: true }).click();- await page.getByRole('menuitem', { name: 'Redeploy', exact: true }).click();- const dialog = page.getByRole('dialog');- await dialog.getByRole('button', { name: 'Redeploy', exact: true }).click();- await expect(page).toHaveURL('/containers/route-redeployed?tab=overview');- await expect(page.getByRole('heading', { name: 'Redeployed Container' })).toBeVisible();- });-});diff --git a/tests/spec/environments.spec.ts b/tests/spec/environments.spec.tsnew file mode 100644index 000000000..b83a10b18--- /dev/null+++ b/tests/spec/environments.spec.ts@@ -0,0 +1,1077 @@+import { waitForDialogReady } from '../utils/playwright.util';+import { removeCreatedEnvironments, readApiData } from '../utils/fetch.util';+import {+ test,+ expect,+ type Locator,+ type Page,+ type Request,+ type Route+} from '../fixtures/test.fixture';++test.describe('Settings', () => {+ const LOCAL_ENV_ID = '0';+ const NAME_PLACEHOLDER = 'My Lab Server';++ async function openEnvironment(page: Page, environmentId: string) {+ await page.goto(`/environments/${environmentId}`);+ await page.waitForLoadState('load');+ await expect(environmentTitleButton(page)).toBeVisible();+ await expect(page.getByRole('button', { name: 'Save', exact: true }).first()).toBeVisible();+ }++ function environmentTitleButton(page: Page) {+ return page.locator('h1 button').first();+ }++ async function renameEnvironmentInHeader(page: Page, newName: string) {+ await environmentTitleButton(page).click();+ const nameInput = page.getByPlaceholder(NAME_PLACEHOLDER);+ await expect(nameInput).toBeVisible();+ await nameInput.fill(newName);+ await nameInput.press('Enter');+ await expect(environmentTitleButton(page)).toHaveText(newName);+ }++ async function createDirectEnvironmentViaUI(+ page: Page,+ environmentName: string,+ environmentIds: Set<string>+ ) {+ await page.goto('/environments');+ await page.waitForLoadState('load');++ await page.getByRole('button', { name: 'Add Environment', exact: true }).click();+ await expect(page.getByText('Create New Agent Environment')).toBeVisible();++ const dialog = page.getByRole('dialog');+ await waitForDialogReady(dialog);+ await dialog.getByLabel('Name', { exact: true }).fill(environmentName);+ await dialog.getByLabel('Agent Address', { exact: true }).fill('localhost:3552');+ const createResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/environments'+ );+ await page.getByRole('button', { name: 'Generate Agent Configuration', exact: true }).click();+ const createResponse = await createResponsePromise;+ expect(createResponse.ok(), 'Create direct environment').toBeTruthy();+ const created: { data: { id: string; apiKey?: string } } = await createResponse.json();+ environmentIds.add(created.data.id);+ expect(created.data.id).toBeTruthy();+ if (!created.data.apiKey) throw new Error('New agent environment did not return an API key');++ await expect(+ page.getByRole('heading', { name: 'Environment Created Successfully', exact: true })+ ).toBeVisible();+ await page.getByRole('button', { name: 'Done', exact: true }).click();+ await expect(page.getByRole('button', { name: environmentName, exact: true })).toBeVisible();+ return { id: created.data.id, apiKey: created.data.apiKey };+ }++ async function openLocalEnvironment(page: Page) {+ await openEnvironment(page, LOCAL_ENV_ID);+ }++ async function saveAndWaitForPut(page: Page, expectedPath: string) {+ const saveButton = page.getByRole('button', { name: 'Save', exact: true }).first();+ await expect(saveButton).toBeEnabled();++ const responsePromise = page.waitForResponse((response) => {+ const request = response.request();+ if (request.method() !== 'PUT') return false;+ const url = new URL(response.url());+ return url.pathname === expectedPath;+ });++ await saveButton.click();+ const response = await responsePromise;+ expect(response.ok(), `Expected successful PUT to ${expectedPath}`).toBeTruthy();+ await expect(saveButton).toBeDisabled({ timeout: 10000 });+ return response.request();+ }++ async function selectSettingOption(page: Page, trigger: Locator, optionText: string) {+ await expect(trigger).toBeVisible();+ await trigger.click();+ const option = page.getByRole('option').filter({ hasText: optionText }).first();+ await expect(option).toBeVisible();+ await option.click();+ }++ test.describe('Environment Settings UI', () => {+ test.describe.configure({ mode: 'serial' });+ const settingKeys = new Set([+ 'baseServerUrl',+ 'followProjectSymlinks',+ 'defaultDeployPullPolicy',+ 'trivyNetwork',+ 'trivyResourceLimitsEnabled',+ 'trivyMemoryLimitMb',+ 'trivyCpuLimit'+ ]);+ let originalSettings: Record<string, string> = {};+ test.beforeEach(async ({ page }) => {+ originalSettings = {};+ const response = await page.request.get(`/api/environments/${LOCAL_ENV_ID}/settings`);+ expect(response.ok(), 'Read original environment settings').toBe(true);+ const settings: Array<{ key: string; value: string }> = await response.json();+ expect(Array.isArray(settings)).toBe(true);+ originalSettings = Object.fromEntries(+ settings+ .filter((setting) => settingKeys.has(setting.key))+ .map((setting) => [setting.key, setting.value])+ );+ });+ test.afterEach(async ({ page }) => {+ if (Object.keys(originalSettings).length === 0) return;+ try {+ const currentResponse = await page.request.get(+ `/api/environments/${LOCAL_ENV_ID}/settings`+ );+ expect(currentResponse.ok()).toBe(true);+ const current: Array<{ key: string; value: string }> = await currentResponse.json();+ const changed = Object.fromEntries(+ Object.entries(originalSettings).filter(+ ([key, value]) => current.find((setting) => setting.key === key)?.value !== value+ )+ );+ if (Object.keys(changed).length === 0) return;+ const response = await page.request.put(`/api/environments/${LOCAL_ENV_ID}/settings`, {+ data: changed+ });+ expect(+ response.ok(),+ `Restore environment settings: ${response.status()} ${await response.text()}`+ ).toBe(true);+ const restoredResponse = await page.request.get(+ `/api/environments/${LOCAL_ENV_ID}/settings`+ );+ expect(restoredResponse.ok()).toBe(true);+ const restored: Array<{ key: string; value: string }> = await restoredResponse.json();+ expect(+ Object.fromEntries(+ restored+ .filter((setting) => settingKeys.has(setting.key))+ .map((setting) => [setting.key, setting.value])+ )+ ).toEqual(originalSettings);+ } catch (error) {+ expect.soft(false, `Restore environment settings: ${String(error)}`).toBe(true);+ }+ });++ test('should keep primary tabs selectable and restore them from the URL', async ({ page }) => {+ await page.goto('/settings');+ await page.waitForLoadState('load');++ const jobScheduleCategory = page+ .getByRole('button')+ .filter({ hasText: 'Automations' })+ .first();+ await expect(jobScheduleCategory).toBeVisible();+ await jobScheduleCategory.click();++ await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('jobs');+ await expect(page.getByRole('tab', { name: 'Automations', exact: true })).toHaveAttribute(+ 'data-state',+ 'active'+ );++ const storageTab = page.getByRole('tab', { name: 'Storage & Limits', exact: true });+ await storageTab.click();+ await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('storage');+ await expect(storageTab).toHaveAttribute('data-state', 'active');++ const dockerTab = page.getByRole('tab', { name: 'Docker Settings', exact: true });+ await dockerTab.click();+ await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('docker');+ await page.reload();+ await expect(dockerTab).toHaveAttribute('data-state', 'active');++ await page.goto(`/environments/${LOCAL_ENV_ID}?source=e2e&tab=invalid#tab-state`);+ await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('features');+ const canonicalUrl = new URL(page.url());+ expect(canonicalUrl.searchParams.get('source')).toBe('e2e');+ expect(canonicalUrl.hash).toBe('#tab-state');+ await expect(page.getByRole('tab', { name: 'Features', exact: true })).toHaveAttribute(+ 'data-state',+ 'active'+ );+ await expect(page.getByRole('heading', { name: 'Features', exact: true })).toBeVisible();+ await expect(+ page.getByRole('switch', { name: 'Vulnerability management', exact: true })+ ).toBeVisible();+ });++ test('should update and save environment details', async ({ page, registerCleanup }) => {+ test.setTimeout(120_000); // 120 seconds timeout for this lengthy UI workflow+ const envName = `settings-ui-${Date.now().toString().slice(-5)}`;+ const updatedName = `${envName}-updated`;+ const activityStatuses = new Map<string, number>();+ page.on('response', (response) => {+ const match = new URL(response.url()).pathname.match(+ /^\/api\/environments\/([^/]+)\/activities$/+ );+ if (match) activityStatuses.set(match[1], response.status());+ });+ const environmentIds = new Set<string>();++ registerCleanup(() => removeCreatedEnvironments(page, environmentIds, envName));+ const { id: environmentId, apiKey } = await createDirectEnvironmentViaUI(+ page,+ envName,+ environmentIds+ );+ const environmentPath = `/api/environments/${environmentId}`;+ await expect.poll(() => activityStatuses.get(environmentId)).toBe(502);+ expect((await page.request.get('/api/auth/me', { timeout: 5_000 })).status()).toBe(200);+ await expect(page).toHaveURL('/environments');+ await page.getByRole('button', { name: 'Open activity center' }).first().click();+ const activityCenter = page.getByRole('dialog', { name: 'Activity Center' });+ await expect(+ activityCenter.getByText(`Could not load activity from ${envName}`, { exact: true })+ ).toBeVisible();+ await page.keyboard.press('Escape');+ await expect(activityCenter).toBeHidden();+ await page.getByRole('button', { name: envName, exact: true }).click();+ await expect(page).toHaveURL(/\/environments\/[^/?]+\?tab=[a-z]+$/);++ const apiUrlButton = page.getByTitle('API URL', { exact: true });+ const originalApiUrl = (await apiUrlButton.textContent())!.trim();+ const updatedApiUrl = originalApiUrl.replace(':3552', ':3553');+ expect(updatedApiUrl).not.toBe(originalApiUrl);++ await renameEnvironmentInHeader(page, updatedName);+ const nameRequest = await saveAndWaitForPut(page, environmentPath);+ expect(nameRequest.postDataJSON()).not.toHaveProperty('accessToken');++ await page.reload();+ await expect(environmentTitleButton(page)).toHaveText(updatedName);++ await apiUrlButton.click();+ await page.locator('#api-url').fill(updatedApiUrl);+ await page.locator('#api-url').press('Tab');+ const tokenInput = page.getByLabel('Agent access token', { exact: true });+ await expect(tokenInput).toBeVisible();+ await expect(tokenInput).toHaveAttribute('type', 'password');+ await expect(tokenInput).toHaveValue('');++ const rejectedResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'PUT' &&+ new URL(response.url()).pathname === environmentPath+ );+ await page.getByRole('button', { name: 'Save', exact: true }).first().click();+ const rejectedResponse = await rejectedResponsePromise;+ expect(rejectedResponse.status()).toBe(400);+ expect(rejectedResponse.request().postDataJSON()).not.toHaveProperty('accessToken');+ await expect(+ page.getByText('Changing environment API URL requires re-entering the accessToken')+ ).toBeVisible();+ const afterRejection = await page.request.get(environmentPath);+ expect(afterRejection.ok()).toBe(true);+ expect(((await afterRejection.json()) as { data: { apiUrl: string } }).data.apiUrl).toBe(+ originalApiUrl+ );++ await tokenInput.fill(apiKey);+ await apiUrlButton.click();+ await page.locator('#api-url').fill(`${updatedApiUrl}/changed`);+ await page.locator('#api-url').press('Tab');+ await expect(tokenInput).toHaveValue('');+ await apiUrlButton.click();+ await page.locator('#api-url').fill(updatedApiUrl);+ await page.locator('#api-url').press('Tab');+ await tokenInput.fill(apiKey);+ await page.route(`**${environmentPath}`, async (route) => {+ if (route.request().method() !== 'PUT') return route.continue();+ await route.fulfill({+ status: 503,+ contentType: 'application/problem+json',+ body: JSON.stringify({ detail: 'Temporary update failure' })+ });+ });+ const failedResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'PUT' &&+ new URL(response.url()).pathname === environmentPath+ );+ await page.getByRole('button', { name: 'Save', exact: true }).first().click();+ expect((await failedResponsePromise).status()).toBe(503);+ await expect(page.getByText('Temporary update failure')).toBeVisible();+ expect((await tokenInput.inputValue()) === apiKey).toBe(true);+ await page.unroute(`**${environmentPath}`);++ const updateRequest = await saveAndWaitForPut(page, environmentPath);+ const updatePayload = updateRequest.postDataJSON() as Record<string, unknown>;+ expect(updatePayload.apiUrl).toBe(updatedApiUrl);+ expect(updatePayload.accessToken === apiKey).toBe(true);+ await expect(tokenInput).toBeHidden();+ await apiUrlButton.click();+ await page.locator('#api-url').fill(`${updatedApiUrl}/another`);+ await page.locator('#api-url').press('Tab');+ await expect(tokenInput).toHaveValue('');+ await apiUrlButton.click();+ await page.locator('#api-url').press('Escape');+ await expect(apiUrlButton).toHaveText(updatedApiUrl);+ await expect(tokenInput).toBeHidden();++ await page.reload();+ await expect(apiUrlButton).toHaveText(updatedApiUrl);+ await expect(tokenInput).toBeHidden();+ await renameEnvironmentInHeader(page, `${updatedName}-again`);+ const secondNameRequest = await saveAndWaitForPut(page, environmentPath);+ expect(secondNameRequest.postDataJSON()).not.toHaveProperty('accessToken');+ });++ test('should update and save the base server URL in Docker settings', async ({ page }) => {+ await openLocalEnvironment(page);+ await expect(page.getByLabel('Agent access token', { exact: true })).toBeHidden();+ await page.getByRole('tab', { name: 'Docker Settings', exact: true }).click();++ const baseServerUrlInput = page.locator('#base-server-url');+ await expect(baseServerUrlInput).toBeVisible();++ const originalBaseServerUrl = await baseServerUrlInput.inputValue();+ const updatedBaseServerUrl = originalBaseServerUrl.endsWith('/e2e')+ ? `${originalBaseServerUrl}-2`+ : `${originalBaseServerUrl}/e2e`;++ try {+ await baseServerUrlInput.fill(updatedBaseServerUrl);+ await expect(baseServerUrlInput).toHaveValue(updatedBaseServerUrl);+ const settingsRequest = await saveAndWaitForPut(+ page,+ `/api/environments/${LOCAL_ENV_ID}/settings`+ );+ expect(settingsRequest.postDataJSON()).not.toHaveProperty('accessToken');++ await page.reload();+ await page.getByRole('tab', { name: 'Docker Settings', exact: true }).click();+ await expect(page.locator('#base-server-url')).toHaveValue(updatedBaseServerUrl, {+ timeout: 15000+ });+ } finally {+ if (!page.isClosed()) {+ await page.getByRole('tab', { name: 'Docker Settings', exact: true }).click();+ const currentValue = await page.locator('#base-server-url').inputValue();+ if (currentValue !== originalBaseServerUrl) {+ await page.locator('#base-server-url').fill(originalBaseServerUrl);+ await saveAndWaitForPut(page, `/api/environments/${LOCAL_ENV_ID}/settings`);+ }+ }+ }+ });++ test('should update and save the follow project symlinks setting from Storage & Limits', async ({+ page+ }) => {+ await openLocalEnvironment(page);+ await page.getByRole('tab', { name: 'Storage & Limits', exact: true }).click();++ const followProjectSymlinksSwitch = page.locator('#follow-project-symlinks');+ await expect(followProjectSymlinksSwitch).toBeVisible();++ const originalChecked =+ (await followProjectSymlinksSwitch.getAttribute('aria-checked')) === 'true';+ const updatedChecked = !originalChecked;++ try {+ await followProjectSymlinksSwitch.click();+ await expect(followProjectSymlinksSwitch).toHaveAttribute(+ 'aria-checked',+ String(updatedChecked)+ );++ const saveButton = page.getByRole('button', { name: 'Save', exact: true }).first();+ await expect(saveButton).toBeEnabled();++ const responsePromise = page.waitForResponse((response) => {+ const request = response.request();+ if (request.method() !== 'PUT') return false;+ const url = new URL(response.url());+ return url.pathname === `/api/environments/${LOCAL_ENV_ID}/settings`;+ });++ await saveButton.click();+ const response = await responsePromise;+ expect(response.ok()).toBeTruthy();++ await page.reload();+ await page.getByRole('tab', { name: 'Storage & Limits', exact: true }).click();+ await expect(page.locator('#follow-project-symlinks')).toHaveAttribute(+ 'aria-checked',+ String(updatedChecked)+ );+ } finally {+ if (!page.isClosed()) {+ await page.getByRole('tab', { name: 'Storage & Limits', exact: true }).click();+ const currentChecked =+ (await page.locator('#follow-project-symlinks').getAttribute('aria-checked')) ===+ 'true';+ if (currentChecked !== originalChecked) {+ await page.locator('#follow-project-symlinks').click();+ await saveAndWaitForPut(page, `/api/environments/${LOCAL_ENV_ID}/settings`);+ }+ }+ }+ });++ test('should reset unsaved environment detail changes', async ({ page, registerCleanup }) => {+ const envName = `settings-reset-${Date.now().toString().slice(-5)}`;+ const environmentIds = new Set<string>();+ registerCleanup(() => removeCreatedEnvironments(page, environmentIds, envName));+ const { id: environmentId, apiKey } = await createDirectEnvironmentViaUI(+ page,+ envName,+ environmentIds+ );+ await openEnvironment(page, environmentId);+ const titleButton = environmentTitleButton(page);+ const apiUrlButton = page.getByTitle('API URL', { exact: true });+ const originalApiUrl = (await apiUrlButton.textContent())!.trim();+ await renameEnvironmentInHeader(page, `${envName}-pending`);+ await apiUrlButton.click();+ await page.locator('#api-url').fill(originalApiUrl.replace(':3552', ':3553'));+ await page.locator('#api-url').press('Tab');+ const tokenInput = page.getByLabel('Agent access token', { exact: true });+ await tokenInput.fill(apiKey);++ const saveButton = page.getByRole('button', { name: 'Save', exact: true }).first();+ const resetButton = page.getByRole('button', { name: 'Reset', exact: true }).first();+ await expect(saveButton).toBeEnabled();+ await expect(resetButton).toBeVisible();+ await resetButton.click();+ await expect(titleButton).toHaveText(envName);+ await expect(apiUrlButton).toHaveText(originalApiUrl);+ await expect(tokenInput).toBeHidden();+ await expect(saveButton).toBeDisabled();++ await apiUrlButton.click();+ await page.locator('#api-url').fill(originalApiUrl.replace(':3552', ':3553'));+ await page.locator('#api-url').press('Tab');+ await expect(tokenInput).toHaveValue('');+ await tokenInput.fill(apiKey);+ await page.getByRole('button', { name: 'Back to Environments', exact: true }).click();+ await expect(page).toHaveURL(/\/environments$/);+ await expect(page.getByRole('heading', { name: 'Environments', exact: true })).toBeVisible();+ await page.getByRole('button', { name: envName, exact: true }).click();+ await expect(page).toHaveURL(new RegExp(`/environments/${environmentId}(?:\\?|$)`));+ await expect(environmentTitleButton(page)).toHaveText(envName);+ await apiUrlButton.click();+ await page.locator('#api-url').fill(originalApiUrl.replace(':3552', ':3553'));+ await page.locator('#api-url').press('Tab');+ await expect(tokenInput).toHaveValue('');+ });++ test('should update and save the default deploy pull policy in Docker settings', async ({+ page+ }) => {+ await openLocalEnvironment(page);++ const dockerTab = page.getByRole('tab', { name: 'Docker Settings', exact: true });+ await dockerTab.click();+ const pullPolicyTrigger = page.locator('#defaultDeployPullPolicy');+ await expect(pullPolicyTrigger).toBeVisible();++ const originalValue = (await pullPolicyTrigger.textContent())?.trim() || 'Missing';+ const updatedValue = originalValue.includes('Always') ? 'Never' : 'Always';++ try {+ await selectSettingOption(page, pullPolicyTrigger, updatedValue);+ await expect(pullPolicyTrigger).toContainText(updatedValue);+ await saveAndWaitForPut(page, `/api/environments/${LOCAL_ENV_ID}/settings`);++ await page.reload();+ await page.getByRole('tab', { name: 'Docker Settings', exact: true }).click();+ await expect(page.locator('#defaultDeployPullPolicy')).toContainText(updatedValue, {+ timeout: 15000+ });+ } finally {+ if (!page.isClosed()) {+ await page.getByRole('tab', { name: 'Docker Settings', exact: true }).click();+ const currentValue = (+ (await page.locator('#defaultDeployPullPolicy').textContent()) || ''+ ).trim();+ if (!currentValue.includes(originalValue)) {+ await selectSettingOption(+ page,+ page.locator('#defaultDeployPullPolicy'),+ originalValue+ );+ await saveAndWaitForPut(page, `/api/environments/${LOCAL_ENV_ID}/settings`);+ }+ }+ }+ });++ test('should save decimal trivy CPU limits and reject negative values', async ({ page }) => {+ test.setTimeout(120_000);+ const settingsPath = `/api/environments/${LOCAL_ENV_ID}/settings`;+ const settingsResponse = await page.request.get(settingsPath);+ expect(settingsResponse.ok()).toBeTruthy();+ const settings = (await settingsResponse.json()) as Array<{ key: string; value: string }>;+ const originalSettings = Object.fromEntries(+ settings+ .filter(({ key }) =>+ ['trivyResourceLimitsEnabled', 'trivyCpuLimit', 'trivyMemoryLimitMb'].includes(key)+ )+ .map(({ key, value }) => [key, value])+ );+ expect(Object.keys(originalSettings)).toHaveLength(3);++ try {+ await openLocalEnvironment(page);+ await page.getByRole('tab', { name: 'Security', exact: true }).click();+ await page.locator('#trivyResourceLimitsEnabledSwitch').setChecked(true);+ const cpuInput = page.getByRole('spinbutton', { name: 'CPU Limit (cores)', exact: true });+ await expect(cpuInput).toHaveAttribute('min', '0');+ await expect(cpuInput).toHaveAttribute('step', 'any');++ const values = ['0.5', '1.5', '2.5', '0.25', '1', '0'];+ if ((await cpuInput.inputValue()) === values[0]) values.reverse();++ for (const value of values) {+ await cpuInput.fill(value);+ expect(await cpuInput.evaluate((input: HTMLInputElement) => input.validity.valid)).toBe(+ true+ );+ const requestPromise = page.waitForRequest(+ (request) =>+ request.method() === 'PUT' && new URL(request.url()).pathname === settingsPath+ );+ await saveAndWaitForPut(page, settingsPath);+ const payload = (await requestPromise).postDataJSON() as Record<string, unknown>;+ expect(payload.trivyCpuLimit).toBe(value);+ expect(payload.trivyResourceLimitsEnabled).toBe('true');+ await page.reload();+ await page.getByRole('tab', { name: 'Security', exact: true }).click();+ await expect(cpuInput).toHaveValue(value);+ }++ const writes: Request[] = [];+ const recordWrite = (request: Request) => {+ if (request.method() === 'PUT' && new URL(request.url()).pathname === settingsPath) {+ writes.push(request);+ }+ };+ page.on('request', recordWrite);+ try {+ await cpuInput.fill('-0.5');+ await page.getByRole('button', { name: 'Save', exact: true }).first().click();+ await expect(+ page.getByText('Please check the form for errors.', { exact: true })+ ).toBeVisible();+ expect(writes).toHaveLength(0);+ await page.reload();+ await page.getByRole('tab', { name: 'Security', exact: true }).click();+ await expect(cpuInput).toHaveValue(values[values.length - 1]);+ } finally {+ page.off('request', recordWrite);+ }+ } finally {+ const restored = await page.request.put(settingsPath, { data: originalSettings });+ expect(restored.ok()).toBeTruthy();+ }+ });++ test('should update and save the trivy network mode including auto', async ({ page }) => {+ await openLocalEnvironment(page);+ await page.getByRole('tab', { name: 'Security', exact: true }).click();++ const trivyNetworkTrigger = page.locator('#trivyNetwork');+ await expect(trivyNetworkTrigger).toBeVisible();++ const originalValue = ((await trivyNetworkTrigger.textContent()) || '').trim();+ const updatedValue = originalValue.includes('bridge') ? 'Auto' : 'bridge';++ try {+ await selectSettingOption(page, trivyNetworkTrigger, updatedValue);+ await expect(trivyNetworkTrigger).toContainText(updatedValue);++ const saveButton = page.getByRole('button', { name: 'Save', exact: true }).first();+ await expect(saveButton).toBeEnabled();++ const responsePromise = page.waitForResponse((response) => {+ const request = response.request();+ if (request.method() !== 'PUT') return false;+ const url = new URL(response.url());+ return url.pathname === `/api/environments/${LOCAL_ENV_ID}/settings`;+ });++ await saveButton.click();+ const response = await responsePromise;+ expect(response.ok()).toBeTruthy();++ await page.reload();+ await page.getByRole('tab', { name: 'Security', exact: true }).click();+ await expect(page.locator('#trivyNetwork')).toContainText(updatedValue);+ } finally {+ if (!page.isClosed()) {+ await page.getByRole('tab', { name: 'Security', exact: true }).click();+ const currentValue = ((await page.locator('#trivyNetwork').textContent()) || '').trim();+ if (!currentValue.includes(originalValue)) {+ await selectSettingOption(page, page.locator('#trivyNetwork'), originalValue);+ await saveAndWaitForPut(page, `/api/environments/${LOCAL_ENV_ID}/settings`);+ }+ }+ }+ });+ });+});++test.describe('Switching', () => {+ const localEnvironment = {+ id: '0',+ name: 'Local Test',+ apiUrl: 'unix:///var/run/docker.sock',+ status: 'online',+ enabled: true,+ isEdge: false+ };++ const remoteEnvironment = {+ id: 'remote-switch-test',+ name: 'Remote Test',+ apiUrl: 'https://remote.example.invalid',+ status: 'online',+ enabled: true,+ isEdge: false+ };++ function paginated<T>(data: T[]) {+ return {+ success: true,+ data,+ counts: {+ runningContainers: data.length,+ stoppedContainers: 0,+ totalContainers: data.length+ },+ pagination: {+ totalPages: 1,+ totalItems: data.length,+ currentPage: 1,+ itemsPerPage: 20,+ grandTotalItems: data.length+ }+ };+ }++ function containerSummary(id: string, name: string) {+ return {+ id,+ names: [`/${name}`],+ image: 'nginx:latest',+ imageId: `sha256:${id}`,+ command: 'nginx',+ created: 1_700_000_000,+ labels: {},+ state: 'running',+ status: 'Up 5 minutes',+ ports: [],+ hostConfig: { networkMode: 'default' },+ networkSettings: { networks: {} },+ mounts: []+ };+ }++ function containerDetails(id: string, name: string) {+ return {+ id,+ name,+ image: 'nginx:latest',+ imageId: `sha256:${id}`,+ created: '2026-01-01T00:00:00Z',+ state: {+ status: 'running',+ running: true,+ startedAt: '2026-01-01T00:00:00Z',+ finishedAt: ''+ },+ config: {},+ hostConfig: { networkMode: 'default' },+ networkSettings: { networks: {} },+ ports: [],+ mounts: [],+ labels: {},+ redeployDisabled: false+ };+ }++ async function mockEnvironmentCatalog(page: Page) {+ await page.addInitScript(() => {+ localStorage.removeItem('selectedEnvironmentId');+ localStorage.removeItem('arcane-container-table');+ });+ await page.context().route(/\/api\/environments(?:\?.*)?$/, async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(paginated([localEnvironment, remoteEnvironment]))+ });+ });+ await page.context().route(/\/api\/stream(?:\?.*)?$/, async (route) => {+ const channels =+ new URL(route.request().url()).searchParams.get('channels')?.split(',') ?? [];+ const timestamp = new Date().toISOString();+ await route.fulfill({+ status: 200,+ contentType: 'application/x-json-stream',+ body: channels.includes('environments')+ ? `${JSON.stringify({+ channel: 'environments',+ environment: {+ type: 'snapshot',+ environments: [localEnvironment, remoteEnvironment],+ timestamp+ },+ timestamp+ })}\n`+ : ''+ });+ });+ await page+ .context()+ .route(/\/api\/environments\/(?:0|remote-switch-test)\/settings$/, async (route) => {+ if (route.request().method() !== 'GET') {+ await route.continue();+ return;+ }+ await route.fulfill({ status: 200, contentType: 'application/json', body: '{}' });+ });+ }++ async function selectRemoteEnvironment(page: Page) {+ await page.getByRole('button').filter({ hasText: localEnvironment.name }).first().click();+ const dialog = page.getByRole('dialog', { name: 'Select Environment' });+ await expect(dialog).toBeVisible();+ await dialog.getByRole('button').filter({ hasText: remoteEnvironment.name }).first().click();+ }++ test.describe('Environment switch isolation', () => {+ test('clears local rows and stats targets while the remote response is delayed', async ({+ page+ }) => {+ let releaseRemote!: () => void;+ const remoteGate = new Promise<void>((resolve) => {+ releaseRemote = resolve;+ });+ let markRemoteStarted!: () => void;+ const remoteStarted = new Promise<void>((resolve) => {+ markRemoteStarted = resolve;+ });+ let remoteMarked = false;+ const websocketPaths: string[] = [];++ await mockEnvironmentCatalog(page);+ await page+ .context()+ .route(/\/api\/environments\/[^/]+\/containers(?:\?.*)?$/, async (route: Route) => {+ const pathname = new URL(route.request().url()).pathname;+ if (pathname === '/api/environments/remote-switch-test/containers') {+ if (!remoteMarked) {+ remoteMarked = true;+ markRemoteStarted();+ }+ await remoteGate;+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(+ paginated([containerSummary('remote-b-id', 'remote-b-container')])+ )+ });+ return;+ }+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(paginated([containerSummary('local-a-id', 'local-a-container')]))+ });+ });+ page.on('websocket', (socket) => websocketPaths.push(new URL(socket.url()).pathname));++ await page.goto('/containers');+ await expect(+ page.getByRole('link', { name: 'local-a-container', exact: true })+ ).toBeVisible();++ try {+ await selectRemoteEnvironment(page);+ await remoteStarted;+ await expect(+ page.getByRole('link', { name: 'local-a-container', exact: true })+ ).toHaveCount(0);+ await page.waitForTimeout(200);+ expect(websocketPaths).not.toContain(+ '/api/environments/remote-switch-test/ws/containers/local-a-id/stats'+ );+ } finally {+ releaseRemote();+ }++ await expect(+ page.getByRole('link', { name: 'remote-b-container', exact: true })+ ).toBeVisible();+ await expect(page.getByRole('link', { name: 'local-a-container', exact: true })).toHaveCount(+ 0+ );+ });++ test('does not restore local rows when the remote request fails', async ({+ page,+ pageErrorGuard+ }) => {+ pageErrorGuard.allow('remote unavailable');+ await mockEnvironmentCatalog(page);+ await page+ .context()+ .route(/\/api\/environments\/[^/]+\/containers(?:\?.*)?$/, async (route: Route) => {+ const pathname = new URL(route.request().url()).pathname;+ if (pathname === '/api/environments/remote-switch-test/containers') {+ await route.fulfill({+ status: 503,+ contentType: 'application/json',+ body: JSON.stringify({ success: false, message: 'remote unavailable' })+ });+ return;+ }+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(paginated([containerSummary('local-a-id', 'local-a-container')]))+ });+ });++ await page.goto('/containers');+ await expect(+ page.getByRole('link', { name: 'local-a-container', exact: true })+ ).toBeVisible();+ const failedRemoteRequest = page.waitForResponse((response) => {+ return (+ new URL(response.url()).pathname === '/api/environments/remote-switch-test/containers' &&+ response.status() === 503+ );+ });+ await selectRemoteEnvironment(page);+ await failedRemoteRequest;+ await expect(page.getByRole('link', { name: 'local-a-container', exact: true })).toHaveCount(+ 0+ );+ });++ test('remounts same-route details and navigates to the unwrapped redeployed container id', async ({+ page+ }) => {+ await page.addInitScript(() => localStorage.removeItem('selectedEnvironmentId'));+ const detailsById = {+ 'route-a': containerDetails('route-a', 'Route A Container'),+ 'route-b': containerDetails('route-b', 'Route B Container'),+ 'route-redeployed': containerDetails('route-redeployed', 'Redeployed Container')+ };++ await page.context().route(/\/api\/environments\/0\/settings$/, async (route) => {+ await route.fulfill({ status: 200, contentType: 'application/json', body: '{}' });+ });+ await page.context().route(/\/api\/environments\/0\/containers\/([^/?]+)$/, async (route) => {+ const id = decodeURIComponent(+ new URL(route.request().url()).pathname.split('/').pop() ?? ''+ );+ const details = detailsById[id as keyof typeof detailsById];+ await route.fulfill({+ status: details ? 200 : 404,+ contentType: 'application/json',+ body: JSON.stringify(+ details ? { success: true, data: details } : { success: false, message: 'not found' }+ )+ });+ });+ await page+ .context()+ .route(/\/api\/environments\/0\/containers\/route-b\/redeploy$/, async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ success: true, data: detailsById['route-redeployed'] })+ });+ });++ await page.goto('/containers/route-a');+ await expect(page.getByRole('heading', { name: 'Route A Container' })).toBeVisible();+ await page.getByRole('tab', { name: 'Logs' }).click();+ await expect(page.getByRole('tab', { name: 'Logs' })).toHaveAttribute(+ 'aria-selected',+ 'true'+ );++ await page.evaluate(() => {+ const link = document.createElement('a');+ link.id = 'same-route-navigation';+ link.href = '/containers/route-b';+ link.textContent = 'navigate';+ document.body.append(link);+ });+ await page.locator('#same-route-navigation').click();+ await expect(page).toHaveURL('/containers/route-b?tab=overview');+ await expect(page.getByRole('heading', { name: 'Route B Container' })).toBeVisible();+ await expect(page.getByRole('tab', { name: 'Overview' })).toHaveAttribute(+ 'aria-selected',+ 'true'+ );++ await page.getByRole('button', { name: 'More actions', exact: true }).click();+ await page.getByRole('menuitem', { name: 'Redeploy', exact: true }).click();+ const dialog = page.getByRole('dialog');+ await dialog.getByRole('button', { name: 'Redeploy', exact: true }).click();+ await expect(page).toHaveURL('/containers/route-redeployed?tab=overview');+ await expect(page.getByRole('heading', { name: 'Redeployed Container' })).toBeVisible();+ });+ });+});++test.describe('Edge agents', () => {+ const ROUTES = {+ environments: '/environments'+ };++ async function openNewEnvironmentSheet(page: Page) {+ await page.goto(ROUTES.environments);+ await page.waitForLoadState('load');++ const addButton = page.getByRole('button', { name: 'Add Environment', exact: true });+ await expect(addButton).toBeVisible();+ await addButton.click();++ await expect(page.getByText('Create New Agent Environment')).toBeVisible();+ }++ async function switchToEdgeMode(page: Page) {+ await page.getByRole('tab', { name: 'Edge', exact: true }).click();+ await expect(page.getByText('Agent connects outbound to the manager.')).toBeVisible();+ }++ test.describe('Edge Agent Environment', () => {+ test('should switch between direct and edge connection modes', async ({ page }) => {+ await openNewEnvironmentSheet(page);++ await expect(page.locator('#new-agent-api-url')).toBeVisible();+ await expect(page.getByPlaceholder('Remote Docker Host')).toBeHidden();++ await switchToEdgeMode(page);+ await expect(page.locator('#new-agent-api-url')).toBeHidden();+ await expect(page.getByPlaceholder('Remote Docker Host')).toBeVisible();++ await page.getByRole('tab', { name: 'Direct', exact: true }).click();+ await expect(page.locator('#new-agent-api-url')).toBeVisible();+ await expect(page.getByPlaceholder('Remote Docker Host')).toBeHidden();+ });++ test('should validate required fields for edge and direct modes', async ({ page }) => {+ await openNewEnvironmentSheet(page);+ let createRequests = 0;++ await page.route('**/api/environments', async (route) => {+ if (route.request().method() === 'POST') {+ createRequests += 1;+ }+ await route.continue();+ });++ // Direct mode: missing name and URL+ await page.getByRole('button', { name: 'Generate Agent Configuration', exact: true }).click();+ await expect.poll(() => createRequests).toBe(0);++ // Edge mode: missing name+ await switchToEdgeMode(page);+ await page.getByRole('button', { name: 'Generate Agent Configuration', exact: true }).click();+ await expect.poll(() => createRequests).toBe(0);+ });++ test('should create an edge agent environment and show deployment snippets', async ({+ page,+ registerCleanup+ }) => {+ const environmentName = `edge-agent-${Date.now().toString().slice(-6)}`;+ let createdEnvironmentId: string | null = null;+ const environmentIds = new Set<string>();+ registerCleanup(() => removeCreatedEnvironments(page, environmentIds, environmentName));+ const agentSettingsRequests: string[] = [];+ page.on('request', (request) => {+ if (!createdEnvironmentId) return;+ const pathname = new URL(request.url()).pathname;+ if (+ pathname === `/api/environments/${createdEnvironmentId}/settings` ||+ pathname === `/api/environments/${createdEnvironmentId}/settings/public`+ ) {+ agentSettingsRequests.push(pathname);+ }+ });++ await page.route('**/api/environments', async (route) => {+ if (route.request().method() === 'POST') {+ const response = await route.fetch();+ const environment = await readApiData<{ id: string }>(+ response,+ 'Create edge environment'+ );+ createdEnvironmentId = environment.id;+ environmentIds.add(environment.id);+ await route.fulfill({ response });+ return;+ }++ await route.continue();+ });++ await openNewEnvironmentSheet(page);+ await switchToEdgeMode(page);++ await page.getByPlaceholder('Remote Docker Host').fill(environmentName);+ const submitButton = page.getByRole('button', {+ name: 'Generate Agent Configuration',+ exact: true+ });+ await submitButton.click();++ const sheetTitle = page.locator('[data-slot="sheet-title"]');+ await expect(sheetTitle).toContainText('Environment Created');+ await expect(+ page.getByText('Edge agent - connects outbound to manager', { exact: true })+ ).toBeVisible();+ await expect(page.getByText('API Key', { exact: true })).toBeVisible();+ await expect(page.getByText('Docker Run Command', { exact: true })).toBeVisible();+ await expect(page.getByText('Docker Compose', { exact: true })).toBeVisible();++ const snippetBlocks = page.locator('pre code').filter({ hasText: 'EDGE_AGENT=true' });+ await expect(snippetBlocks.first()).toBeVisible();++ const dockerRunSnippet = snippetBlocks.first();+ await expect(dockerRunSnippet).toContainText('arcane-edge-agent');+ await expect(dockerRunSnippet).not.toContainText('-p 3553:3553');++ await page.getByRole('button', { name: 'Done', exact: true }).click();++ await expect(page.getByRole('button', { name: environmentName, exact: true })).toBeVisible();+ const environmentRow = page.locator('tr').filter({+ has: page.getByRole('button', { name: environmentName, exact: true })+ });+ await expect(environmentRow.getByText('edge://edge-agent-').first()).toBeVisible();+ await expect(environmentRow.getByText('Edge', { exact: true })).toBeVisible();++ await page.getByRole('button', { name: environmentName, exact: true }).click();+ if (createdEnvironmentId) {+ await expect(page).toHaveURL(new RegExp(`/environments/${createdEnvironmentId}`));+ }++ await expect(page.getByTitle('API URL', { exact: true })).toHaveText(/edge:\/\/edge-agent-/);+ await expect(page.getByText('Edge', { exact: true }).first()).toBeVisible();+ await expect(page.getByText('Live Tunnel', { exact: true })).toBeVisible();+ await expect(+ page.getByRole('tab', { name: 'Connection & Edge', exact: true })+ ).toHaveAttribute('data-state', 'active');+ expect(agentSettingsRequests).toEqual([]);+ });+ });+});diff --git a/tests/spec/image-updates.spec.ts b/tests/spec/image-updates.spec.tsdeleted file mode 100644index 74a20e451..000000000--- a/tests/spec/image-updates.spec.ts+++ /dev/null@@ -1,381 +0,0 @@-import { test, expect, type Locator, type Page } from '../fixtures/test.fixture';-import { fetchImagesWithRetry, readList } from '../utils/fetch.util';--const ROUTES = {- page: '/images',- apiImageUpdatesCheckBatch: '/api/environments/0/image-updates/check-batch',- apiImageUpdatesCheckAll: '/api/environments/0/image-updates/check-all',- apiImageUpdatesSummary: '/api/environments/0/image-updates/summary'-};--const TEST_IMAGE_REFS = {- nginx: 'public.ecr.aws/nginx/nginx:stable-alpine',- alpine: 'public.ecr.aws/docker/library/alpine:3.20',- busybox: 'public.ecr.aws/docker/library/busybox:1.37'-};--interface BatchUpdateResponse {- success: boolean;- data: Record<- string,- {- hasUpdate: boolean;- updateType: string;- currentVersion?: string;- latestVersion?: string;- currentDigest?: string;- latestDigest?: string;- checkTime: string;- responseTimeMs: number;- error?: string;- authMethod?: string;- authUsername?: string;- authRegistry?: string;- usedCredential?: boolean;- }- >;-}--interface UpdateSummary {- success: boolean;- data: {- totalImages: number;- imagesWithUpdates: number;- digestUpdates: number;- errorsCount: number;- };-}--async function navigateToImages(page: Page) {- await page.goto(ROUTES.page);- await page.waitForLoadState('load');-}--async function fetchImagesTotal(page: Page, updatesFilter?: string): Promise<number> {- const params = new URLSearchParams({ start: '0', limit: '1' });- if (updatesFilter) {- params.set('updates', updatesFilter);- }-- const result = await readList(- await page.request.get(`/api/environments/0/images?${params.toString()}`),- 'List filtered images'- );- expect(result.pagination?.totalItems, 'Image list must include a total').toBeDefined();- return result.pagination!.totalItems!;-}--async function getCheckUpdatesAction(page: Page): Promise<Locator> {- await expect(page.getByRole('heading', { name: 'Images', exact: true })).toBeVisible();-- const directButton = page- .getByRole('button', { name: 'Check Updates', exact: true })- .filter({ visible: true })- .first();-- const menuTrigger = page- .getByRole('button', { name: 'More actions' })- .filter({ visible: true })- .first();- await expect(directButton.or(menuTrigger).first()).toBeVisible();- if (await directButton.isVisible()) return directButton;-- await menuTrigger.click();-- const menu = page.getByRole('menu').filter({ visible: true }).last();- await expect(menu).toBeVisible();- const menuItem = menu.getByRole('menuitem', { name: 'Check Updates', exact: true }).first();- await expect(menuItem).toBeVisible();- return menuItem;-}--async function openImageUpdateCard(page: Page, trigger: Locator): Promise<Locator> {- const usesTouchPopover = await page.evaluate(() => window.matchMedia('(hover: none)').matches);- if (usesTouchPopover) {- await trigger.click();- } else {- await trigger.hover();- }-- const content = page.locator('[data-open="true"]').filter({ visible: true }).last();- await expect(content).toBeVisible();- return content;-}--let realImages: any[] = [];--test.beforeEach(async ({ page }) => {- await navigateToImages(page);-- realImages = await fetchImagesWithRetry(page);-});--test.describe('Image Update UI - Check All Updates Button', () => {- test('should display the Check Updates button on images page', async ({ page }) => {- await navigateToImages(page);-- const checkUpdatesButton = await getCheckUpdatesAction(page);- await expect(checkUpdatesButton).toBeVisible();- });-- test('should trigger bulk update check when clicking Check Updates button', async ({ page }) => {- await page.route(`**${ROUTES.apiImageUpdatesCheckAll}`, async (route) => {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({ success: true, data: {} })- });- });- await navigateToImages(page);-- const checkUpdatesButton = await getCheckUpdatesAction(page);- await expect(checkUpdatesButton).toBeVisible();-- const checkAllResponsePromise = page.waitForResponse((response) => {- const request = response.request();- if (request.method() !== 'POST') return false;- return new URL(response.url()).pathname === ROUTES.apiImageUpdatesCheckAll;- });-- await checkUpdatesButton.click();-- const checkAllResponse = await checkAllResponsePromise;- expect(checkAllResponse.ok()).toBeTruthy();-- // Eventually a success or completion toast should appear- await expect(- page.getByRole('region', { name: 'Notifications alt+T', exact: true }).getByRole('listitem')- ).toBeVisible({ timeout: 60000 });- });-});--test.describe('Image Update UI - Individual Image Update Check via Hover Card', () => {- test('should display update status icons in the images table', async ({ page }) => {- expect(realImages.length, 'No images available').toBeGreaterThan(0);-- await navigateToImages(page);-- // Wait for the table to load- await expect(page.getByRole('table')).toBeVisible();-- // Check that image rows exist- const rows = page.getByRole('table').getByRole('row');- await expect(rows.nth(1)).toBeVisible();- });-- test('should show hover card tooltip when hovering over update status icon', async ({ page }) => {- expect(realImages.length, 'No images available').toBeGreaterThan(0);-- await navigateToImages(page);-- // Wait for images table- await expect(page.getByRole('table')).toBeVisible();-- // Find the first row's update status area (the Updates column)- const firstRow = page- .getByRole('row')- .filter({ has: page.getByTestId('image-update-trigger') })- .first();- await expect(firstRow).toBeVisible();-- // Look for the update status icon trigger element (Tooltip.Trigger wraps a span)- const updateStatusTrigger = firstRow.getByTestId('image-update-trigger').first();- await openImageUpdateCard(page, updateStatusTrigger);- });-- test('should allow triggering individual image update check from hover card', async ({- page- }) => {- expect(realImages.length, 'No images available').toBeGreaterThan(0);-- const fixtures = await readList<{ id: string; repoTags: string[] }>(- await page.request.get('/api/environments/0/images', {- params: { search: TEST_IMAGE_REFS.busybox }- }),- 'Find BusyBox fixture'- );- const testImage = fixtures.data.find((image) =>- image.repoTags?.includes(TEST_IMAGE_REFS.busybox)- );- expect(testImage, 'BusyBox fixture must be present').toBeDefined();- await navigateToImages(page);- const filteredImagesResponse = page.waitForResponse((response) => {- const url = new URL(response.url());- return (- response.request().method() === 'GET' &&- url.pathname === '/api/environments/0/images' &&- url.searchParams.get('search') === testImage!.id- );- });- await page.getByPlaceholder('Search…').first().fill(testImage!.id);- const filteredResponse = await filteredImagesResponse;- expect(filteredResponse.ok()).toBe(true);- await filteredResponse.finished();- await expect(page.getByRole('table').locator('tbody tr')).toHaveCount(1);- const row = page- .getByRole('row')- .filter({ has: page.locator(`a[href="/images/${testImage!.id}"]`) });- const trigger = row.getByTestId('image-update-trigger');- await expect(trigger).toBeVisible();- const responsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- decodeURIComponent(new URL(response.url()).pathname) ===- `/api/environments/0/image-updates/check/${testImage!.id}`- );- if (await trigger.evaluate((element) => element.tagName === 'BUTTON')) {- await trigger.click();- } else {- const updateCard = await openImageUpdateCard(page, trigger);- await updateCard.getByRole('button', { name: 'Re-check Updates', exact: true }).click();- }- expect((await responsePromise).ok()).toBe(true);- await expect(page.locator('li[data-sonner-toast]').first()).toBeVisible();- });-});--test.describe('Image Update API Endpoints', () => {- test('should check batch image updates via API', async ({ page }) => {- const imageRefs = [TEST_IMAGE_REFS.nginx, TEST_IMAGE_REFS.alpine];-- const res = await page.request.post(ROUTES.apiImageUpdatesCheckBatch, {- data: {- imageRefs- }- });-- expect(res.status()).toBe(200);-- const json = (await res.json()) as BatchUpdateResponse;- expect(json.success).toBe(true);- expect(json.data).toBeDefined();- expect(typeof json.data).toBe('object');- });-- test('should check all images for updates via API', async ({ page }) => {- const res = await page.request.post(ROUTES.apiImageUpdatesCheckAll, {- data: {}- });-- expect(res.status()).toBe(200);-- const json = (await res.json()) as BatchUpdateResponse;- expect(json.success).toBe(true);- expect(json.data).toBeDefined();- });-- test('should get update summary via API', async ({ page }) => {- const res = await page.request.get(ROUTES.apiImageUpdatesSummary);-- expect(res.status()).toBe(200);-- const json = (await res.json()) as UpdateSummary;- expect(json.success).toBe(true);- expect(json.data).toBeDefined();- expect(typeof json.data.totalImages).toBe('number');- expect(typeof json.data.imagesWithUpdates).toBe('number');- expect(typeof json.data.digestUpdates).toBe('number');- expect(typeof json.data.errorsCount).toBe('number');-- const [imagesTotal, hasUpdateTotal] = await Promise.all([- fetchImagesTotal(page),- fetchImagesTotal(page, 'has_update')- ]);-- expect(json.data.totalImages).toBe(imagesTotal);- expect(json.data.imagesWithUpdates).toBe(hasUpdateTotal);- });-});--test.describe('Image Update UI Integration', () => {- test('should display update status icon in images table', async ({ page }) => {- expect(realImages.length, 'No images available').toBeGreaterThan(0);-- await navigateToImages(page);-- // Wait for the table to load- await expect(page.getByRole('table')).toBeVisible();-- // Check that image rows exist- const rows = page.getByRole('table').getByRole('row');- await expect(rows.nth(1)).toBeVisible();- });-- test('should display update information in image detail page', async ({ page }) => {- expect(realImages.length, 'No images available').toBeGreaterThan(0);-- const testImage = realImages.find(- (img) => img.repoTags?.[0] && !img.repoTags[0].includes('<none>')- );- expect(testImage, 'No suitable image found').toBeTruthy();-- // Navigate to image detail- await page.goto(`/images/${encodeURIComponent(testImage.id)}`);- await page.waitForLoadState('load');-- // The detail page should load- await expect(page.getByRole('heading').first()).toBeVisible({- timeout: 10000- });- });-});--test.describe('Batch Update Checks', () => {- test('should handle empty batch request', async ({ page }) => {- const res = await page.request.post(ROUTES.apiImageUpdatesCheckBatch, {- data: {- imageRefs: []- }- });-- expect(res.status()).toBe(200);-- const json = (await res.json()) as BatchUpdateResponse;- expect(json.success).toBe(true);- expect(Object.keys(json.data).length).toBe(0);- });-- test('should return results for each image in batch', async ({ page }) => {- const imageRefs = [TEST_IMAGE_REFS.nginx, TEST_IMAGE_REFS.alpine, TEST_IMAGE_REFS.busybox];-- const res = await page.request.post(ROUTES.apiImageUpdatesCheckBatch, {- data: {- imageRefs- }- });-- expect(res.status()).toBe(200);-- const json = (await res.json()) as BatchUpdateResponse;- expect(json.success).toBe(true);-- // Each requested image should have a result- for (const ref of imageRefs) {- expect(json.data[ref]).toBeDefined();- }- });-- test('should handle mixed valid and invalid images in batch', async ({ page }) => {- const imageRefs = [TEST_IMAGE_REFS.nginx, 'invalid-registry.example.com/nonexistent:latest'];-- const res = await page.request.post(ROUTES.apiImageUpdatesCheckBatch, {- data: {- imageRefs- }- });-- expect(res.status()).toBe(200);-- const json = (await res.json()) as BatchUpdateResponse;- expect(json.success).toBe(true);-- // The Public ECR image should succeed.- expect(json.data[TEST_IMAGE_REFS.nginx]).toBeDefined();-- // Invalid image should have an error- const invalidResult = json.data['invalid-registry.example.com/nonexistent:latest'];- if (invalidResult) {- expect(invalidResult.error || invalidResult.hasUpdate === false).toBeTruthy();- }- });-});diff --git a/tests/spec/images.spec.ts b/tests/spec/images.spec.tsindex e4c590c95..b76c378c5 100644--- a/tests/spec/images.spec.ts+++ b/tests/spec/images.spec.ts@@ -1,585 +1,814 @@-import { test, expect, type Page } from '../fixtures/test.fixture';+import { test, expect, type Page, type Locator } from '../fixtures/test.fixture';import {fetchImageCountsWithRetry,fetchImagesWithRetry,readApiData,readList} from '../utils/fetch.util';-import { ImageUsageCounts } from 'types/image.type';+import {+ ImageSummary,+ ImageUsageCounts,+ type ImageUpdateInfo,+ type ImageUpdateSummary+} from '../types/image.type';import { openRowActionsMenu } from '../utils/table-actions.util';import { waitForDialogReady } from '../utils/playwright.util';-const ROUTES = {- page: '/images',- apiImages: '/api/environments/0/images'-};--async function navigateToImages(page: Page) {- await page.goto(ROUTES.page);- await page.waitForLoadState('load');-}--function getImageRows(page: Page) {- return page- .getByRole('row')- .filter({ has: page.getByRole('checkbox', { name: 'Select row', exact: true }) });-}--async function mockImageDeleteFlow(page: Page, failFirst = false) {- const state = {- deleteRequestCount: 0,- imageListRequestCount: 0,- usageCountRequestCount: 0,- inFlight: 0,- maxInFlight: 0,- deletedIds: new Set<string>()+test.describe('Management', () => {+ const ROUTES = {+ page: '/images',+ apiImages: '/api/environments/0/images'};- await page.route('**/api/environments/0/images**', async (route) => {- const request = route.request();- const url = new URL(request.url());-- if (request.method() === 'DELETE' && url.pathname.startsWith(`${ROUTES.apiImages}/`)) {- state.deleteRequestCount += 1;- state.inFlight += 1;- state.maxInFlight = Math.max(state.maxInFlight, state.inFlight);- const imageId = decodeURIComponent(url.pathname.slice(`${ROUTES.apiImages}/`.length));- const shouldFail = failFirst && state.deleteRequestCount === 1;-- await new Promise((resolve) => setTimeout(resolve, 50));- state.inFlight -= 1;- if (!shouldFail) state.deletedIds.add(imageId);-- await route.fulfill({- status: shouldFail ? 500 : 200,- contentType: 'application/json',- body: JSON.stringify(- shouldFail- ? { success: false, message: 'mock delete failure' }- : { success: true, data: { message: 'Image removed successfully' } }- )- });- return;- }+ async function navigateToImages(page: Page) {+ await page.goto(ROUTES.page);+ await page.waitForLoadState('load');+ }++ function getImageRows(page: Page) {+ return page+ .getByRole('row')+ .filter({ has: page.getByRole('checkbox', { name: 'Select row', exact: true }) });+ }++ async function mockImageDeleteFlow(page: Page, failFirst = false) {+ const state = {+ deleteRequestCount: 0,+ imageListRequestCount: 0,+ usageCountRequestCount: 0,+ inFlight: 0,+ maxInFlight: 0,+ deletedIds: new Set<string>()+ };++ await page.route('**/api/environments/0/images**', async (route) => {+ const request = route.request();+ const url = new URL(request.url());++ if (request.method() === 'DELETE' && url.pathname.startsWith(`${ROUTES.apiImages}/`)) {+ state.deleteRequestCount += 1;+ state.inFlight += 1;+ state.maxInFlight = Math.max(state.maxInFlight, state.inFlight);+ const imageId = decodeURIComponent(url.pathname.slice(`${ROUTES.apiImages}/`.length));+ const shouldFail = failFirst && state.deleteRequestCount === 1;++ await new Promise((resolve) => setTimeout(resolve, 50));+ state.inFlight -= 1;+ if (!shouldFail) state.deletedIds.add(imageId);++ await route.fulfill({+ status: shouldFail ? 500 : 200,+ contentType: 'application/json',+ body: JSON.stringify(+ shouldFail+ ? { success: false, message: 'mock delete failure' }+ : { success: true, data: { message: 'Image removed successfully' } }+ )+ });+ return;+ }- if (request.method() === 'GET' && url.pathname === ROUTES.apiImages) {- state.imageListRequestCount += 1;- const response = await route.fetch();- const body = await response.json();- if (Array.isArray(body?.data)) {- body.data = body.data.filter((image: { id: string }) => !state.deletedIds.has(image.id));- if (body.pagination?.totalItems !== undefined) {- body.pagination.totalItems = Math.max(- 0,- Number(body.pagination.totalItems) - state.deletedIds.size- );+ if (request.method() === 'GET' && url.pathname === ROUTES.apiImages) {+ state.imageListRequestCount += 1;+ const response = await route.fetch();+ const body = await response.json();+ if (Array.isArray(body?.data)) {+ body.data = body.data.filter((image: { id: string }) => !state.deletedIds.has(image.id));+ if (body.pagination?.totalItems !== undefined) {+ body.pagination.totalItems = Math.max(+ 0,+ Number(body.pagination.totalItems) - state.deletedIds.size+ );+ }}+ await route.fulfill({ response, body: JSON.stringify(body) });+ return;}- await route.fulfill({ response, body: JSON.stringify(body) });- return;- }- if (request.method() === 'GET' && url.pathname === `${ROUTES.apiImages}/counts`) {- state.usageCountRequestCount += 1;- }+ if (request.method() === 'GET' && url.pathname === `${ROUTES.apiImages}/counts`) {+ state.usageCountRequestCount += 1;+ }- await route.continue();- });+ await route.continue();+ });- return state;-}+ return state;+ }-async function fetchAllImagesForUsage(page: Page): Promise<Record<string, unknown>[]> {- const limit = 200;- let start = 0;- const all: Record<string, unknown>[] = [];+ async function fetchAllImagesForUsage(page: Page): Promise<Record<string, unknown>[]> {+ const limit = 200;+ let start = 0;+ const all: Record<string, unknown>[] = [];- while (true) {- const { data, pagination } = await readList<Record<string, unknown>>(- await page.request.get(`${ROUTES.apiImages}?start=${start}&limit=${limit}`),- 'List images for usage'- );- all.push(...data);- expect(pagination?.totalItems, 'Image list must include a total').toBeDefined();- const totalItems = pagination!.totalItems!;- if (data.length === 0 || all.length >= totalItems) {- break;+ while (true) {+ const { data, pagination } = await readList<Record<string, unknown>>(+ await page.request.get(`${ROUTES.apiImages}?start=${start}&limit=${limit}`),+ 'List images for usage'+ );+ all.push(...data);+ expect(pagination?.totalItems, 'Image list must include a total').toBeDefined();+ const totalItems = pagination!.totalItems!;+ if (data.length === 0 || all.length >= totalItems) {+ break;+ }++ start += limit;}- start += limit;+ return all;}- return all;-}--async function mockPinnedImageFlow(page: Page) {- const digest = `sha256:${'8c8ff37a'.padEnd(64, '0')}`;- const alternateDigest = `sha256:${'9d9aa48b'.padEnd(64, '1')}`;- const repository = 'registry.example.com:5000/team/syncthing';- const pinnedReference = `${repository}:2.1.3@${digest}`;- const alternateReference = `${repository}:stable@${alternateDigest}`;- const imageId = `sha256:${'abc123'.padEnd(64, '0')}`;- const image = {- id: imageId,- repoTags: [],- repoDigests: [`${repository}@${digest}`],- pinnedReferences: [pinnedReference, alternateReference],- created: 1_725_000_000,- size: 123_456,- virtualSize: 123_456,- labels: null,- inUse: true,- usedBy: [{ type: 'container', name: 'syncthing', id: 'container-syncthing' }],- repo: repository,- tag: '<none>'- };+ async function mockPinnedImageFlow(page: Page) {+ const digest = `sha256:${'8c8ff37a'.padEnd(64, '0')}`;+ const alternateDigest = `sha256:${'9d9aa48b'.padEnd(64, '1')}`;+ const repository = 'registry.example.com:5000/team/syncthing';+ const pinnedReference = `${repository}:2.1.3@${digest}`;+ const alternateReference = `${repository}:stable@${alternateDigest}`;+ const imageId = `sha256:${'abc123'.padEnd(64, '0')}`;+ const image = {+ id: imageId,+ repoTags: [],+ repoDigests: [`${repository}@${digest}`],+ pinnedReferences: [pinnedReference, alternateReference],+ created: 1_725_000_000,+ size: 123_456,+ virtualSize: 123_456,+ labels: null,+ inUse: true,+ usedBy: [{ type: 'container', name: 'syncthing', id: 'container-syncthing' }],+ repo: repository,+ tag: '<none>'+ };++ await page.route('**/api/environments/0/images**', async (route) => {+ const request = route.request();+ const url = new URL(request.url());+ if (request.method() !== 'GET') {+ await route.continue();+ return;+ }++ if (url.pathname === ROUTES.apiImages) {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: [image],+ pagination: {+ totalPages: 1,+ totalItems: 1,+ currentPage: 1,+ itemsPerPage: 20,+ grandTotalItems: 1+ }+ })+ });+ return;+ }++ if (url.pathname === `${ROUTES.apiImages}/counts`) {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: { imagesInuse: 1, imagesUnused: 0, totalImages: 1, totalImageSize: image.size }+ })+ });+ return;+ }++ if (decodeURIComponent(url.pathname) === `${ROUTES.apiImages}/${imageId}`) {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: {+ ...image,+ created: '2026-09-04T00:00:00Z',+ comment: '',+ author: '',+ config: {},+ architecture: 'amd64',+ os: 'linux',+ graphDriver: { data: null, name: 'overlay2' },+ rootFs: { type: 'layers', layers: [] },+ metadata: { lastTagTime: '' },+ descriptor: { mediaType: '', digest, size: image.size }+ }+ })+ });+ return;+ }- await page.route('**/api/environments/0/images**', async (route) => {- const request = route.request();- const url = new URL(request.url());- if (request.method() !== 'GET') {await route.continue();- return;- }+ });++ return { imageId, repository, pinnedReference, alternateReference };+ }- if (url.pathname === ROUTES.apiImages) {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({- success: true,- data: [image],- pagination: {- totalPages: 1,- totalItems: 1,- currentPage: 1,- itemsPerPage: 20,- grandTotalItems: 1+ let realImages: ImageSummary[] = [];+ let imageCounts: ImageUsageCounts = {+ imagesInuse: 0,+ imagesUnused: 0,+ totalImages: 0,+ totalImageSize: 0+ };++ test.beforeEach(async ({ page }) => {+ await navigateToImages(page);++ realImages = await fetchImagesWithRetry(page);+ imageCounts = await fetchImageCountsWithRetry(page);+ });++ test.describe('Images Page', () => {+ test('should display stats cards with correct counts and size', async ({ page }) => {+ await navigateToImages(page);++ await expect(page.getByText(`${imageCounts.totalImages} Total Images`)).toBeVisible();+ await expect(page.getByText('Total Size', { exact: true })).toBeVisible();+ });++ test('should align /images/counts with usage derived from /images list', async ({ page }) => {+ await navigateToImages(page);++ await expect+ .poll(+ async () => {+ const [allImages, counts] = await Promise.all([+ fetchAllImagesForUsage(page),+ fetchImageCountsWithRetry(page)+ ]);+ const derivedInUse = allImages.filter((image) => !!image.inUse).length;+ return {+ totalDifference: counts.totalImages - allImages.length,+ inUseDifference: counts.imagesInuse - derivedInUse,+ unusedDifference: counts.imagesUnused - (allImages.length - derivedInUse)+ };+ },+ {+ message:+ 'Expected image usage counts and the image list to describe the same Docker state',+ timeout: 30_000,+ intervals: [500, 1_000, 2_000]}- })- });- return;- }+ )+ .toEqual({ totalDifference: 0, inUseDifference: 0, unusedDifference: 0 });+ });++ test('should display full pinned references without enabling tag actions', async ({ page }) => {+ const { imageId, repository, pinnedReference, alternateReference } =+ await mockPinnedImageFlow(page);+ await page.reload();- if (url.pathname === `${ROUTES.apiImages}/counts`) {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({- success: true,- data: { imagesInuse: 1, imagesUnused: 0, totalImages: 1, totalImageSize: image.size }- })+ const row = page.getByRole('row').filter({+ has: page.getByRole('link', { name: repository, exact: true })});- return;- }+ await expect(row.getByText(pinnedReference, { exact: true })).toBeVisible();++ const overflow = row.getByText('+1', { exact: true });+ await overflow.hover();+ await expect(page.getByText(alternateReference, { exact: true })).toBeVisible();++ const menu = await openRowActionsMenu(page, row);+ await expect(menu.getByRole('menuitem', { name: 'Pull', exact: true })).toBeDisabled();+ await expect(menu.getByRole('menuitem', { name: 'Patch', exact: true })).toBeDisabled();+ await page.keyboard.press('Escape');++ await row.getByRole('link', { name: repository, exact: true }).click();+ await expect+ .poll(() => decodeURIComponent(new URL(page.url()).pathname))+ .toBe(`/images/${imageId}`);+ await expect(page.getByRole('heading', { name: pinnedReference, exact: true })).toBeVisible();+ await expect(page.getByText('Pinned References', { exact: true })).toBeVisible();+ await expect(page.getByText(pinnedReference, { exact: true }).last()).toBeVisible();+ await expect(page.getByText(alternateReference, { exact: true }).last()).toBeVisible();+ await expect(page.getByRole('button', { name: 'Patch', exact: true })).toHaveCount(0);+ });++ test('should navigate to image details on inspect click', async ({ page }) => {+ await navigateToImages(page);++ const firstRow = page+ .getByRole('row')+ .filter({ has: page.getByRole('button', { name: 'Open menu', exact: true }) })+ .first();+ const menu = await openRowActionsMenu(page, firstRow);+ await menu.getByRole('menuitem', { name: 'Inspect' }).click();+ });++ test('should pull image from dropdown menu', async ({ page }) => {+ test.setTimeout(90_000);+ const reference = 'public.ecr.aws/docker/library/busybox:1.37';+ const fixtures = await readList<{ id: string }>(+ await page.request.get(ROUTES.apiImages, { params: { search: reference } }),+ 'Find image pull fixture'+ );+ expect(fixtures.data).toHaveLength(1);+ await navigateToImages(page);+ await page.getByPlaceholder('Search…').first().fill(fixtures.data[0].id);++ const row = page+ .getByRole('row')+ .filter({ has: page.locator(`a[href="/images/${fixtures.data[0].id}"]`) });+ const menu = await openRowActionsMenu(page, row);+ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === `${ROUTES.apiImages}/pull`+ );+ await menu.getByRole('menuitem', { name: 'Pull' }).click();+ const response = await responsePromise;+ expect(response.ok(), 'Pull fixture image').toBe(true);+ const frames = (await response.text())+ .trim()+ .split('\n')+ .map(+ (line) =>+ JSON.parse(line) as {+ activityId?: string;+ done?: boolean;+ error?: unknown;+ }+ );+ expect(frames.some((frame) => frame.error)).toBe(false);+ expect(frames).toContainEqual(expect.objectContaining({ done: true }));+ const activityId = frames.find((frame) => frame.activityId)?.activityId;+ expect(activityId).toBeTruthy();+ await expect(+ page+ .getByRole('region', { name: 'Notifications alt+T', exact: true })+ .getByRole('listitem')+ .filter({ hasText: `Image ${reference} pulled successfully` })+ ).toBeVisible();+ await expect+ .poll(+ async () => {+ const detail = await readApiData<{ activity: { status: string } }>(+ await page.request.get(`/api/environments/0/activities/${activityId}`),+ 'Get image pull activity'+ );+ return detail.activity.status;+ },+ { timeout: 60_000 }+ )+ .toBe('success');+ });- if (decodeURIComponent(url.pathname) === `${ROUTES.apiImages}/${imageId}`) {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({- success: true,- data: {- ...image,- created: '2026-09-04T00:00:00Z',- comment: '',- author: '',- config: {},- architecture: 'amd64',- os: 'linux',- graphDriver: { data: null, name: 'overlay2' },- rootFs: { type: 'layers', layers: [] },- metadata: { lastTagTime: '' },- descriptor: { mediaType: '', digest, size: image.size }+ test('should call remove API on row action remove click and confirmation', async ({ page }) => {+ expect(realImages.length, 'No images available for remove API test').toBeGreaterThan(0);+ await navigateToImages(page);++ const removableImage = realImages.find((image) => image.repo && image.repo !== '<none>');+ if (!removableImage) throw new Error('No removable images available');+ const removePath = `/api/environments/0/images/${removableImage.id}`;++ let removeRequestCount = 0;+ await page.route(+ (url) => decodeURIComponent(url.pathname) === removePath,+ async (route) => {+ if (route.request().method() !== 'DELETE') {+ await route.continue();+ return;}- })- });- return;- }- await route.continue();- });+ removeRequestCount += 1;+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: { message: 'Image removed successfully' }+ })+ });+ }+ );- return { imageId, repository, pinnedReference, alternateReference };-}+ // The API list and the UI use different sorting, so the selected image may be on another page.+ const search = page.getByRole('textbox', { name: 'Search…', exact: true });+ await search.fill(removableImage.id);+ await search.press('Enter');-let realImages: any[] = [];-let imageCounts: ImageUsageCounts = {- imagesInuse: 0,- imagesUnused: 0,- totalImages: 0,- totalImageSize: 0-};+ const imageRow = getImageRows(page).filter({+ has: page.locator(`a[href="/images/${removableImage.id}"]`)+ });+ const menu = await openRowActionsMenu(page, imageRow);+ await menu.getByRole('menuitem', { name: 'Remove', exact: true }).click();++ const dialog = page.getByRole('dialog', { name: 'Remove image', exact: true });+ await expect(dialog).toBeVisible();+ // The post-remove refresh goes through queryClient.fetchQuery, which joins an+ // already in-flight background refetch instead of issuing a new request, so+ // asserting on fresh network calls here races under parallel load. The bulk+ // removal tests below cover the refresh path with stubbed list/count endpoints.+ await dialog.getByRole('button', { name: 'Remove', exact: true }).click();+ await expect.poll(() => removeRequestCount).toBe(1);++ await expect(+ page.getByRole('region', { name: 'Notifications alt+T', exact: true }).getByRole('listitem')+ ).toBeVisible();+ });-test.beforeEach(async ({ page }) => {- await navigateToImages(page);+ test('should remove selected images sequentially and refresh the list and usage counts', async ({+ page+ }) => {+ expect(+ realImages.length,+ 'At least two images are required for bulk remove test'+ ).toBeGreaterThanOrEqual(2);+ await navigateToImages(page);++ const rows = getImageRows(page);+ await expect(rows.nth(1)).toBeVisible();+ const initialRowCount = await rows.count();+ const mock = await mockImageDeleteFlow(page);++ await rows.nth(0).getByRole('checkbox', { name: 'Select row', exact: true }).check();+ await rows.nth(1).getByRole('checkbox', { name: 'Select row', exact: true }).check();+ await expect(+ page.getByRole('button', { name: 'Remove Selected (2)', exact: true })+ ).toBeVisible();+ await page.getByRole('button', { name: 'Remove Selected (2)', exact: true }).click();++ const dialog = page.getByRole('dialog');+ await dialog.getByRole('button', { name: 'Remove', exact: true }).click();++ await expect.poll(() => mock.deleteRequestCount).toBe(2);+ expect(mock.maxInFlight).toBe(1);+ await expect(+ page+ .getByRole('region', { name: 'Notifications alt+T', exact: true })+ .getByRole('listitem')+ .filter({ hasText: '2 images removed successfully' })+ ).toBeVisible();+ await expect.poll(() => getImageRows(page).count()).toBe(initialRowCount - 2);+ await expect(page.getByRole('button', { name: /^Remove Selected/ })).toHaveCount(0);+ });- realImages = await fetchImagesWithRetry(page);- imageCounts = await fetchImageCountsWithRetry(page);-});+ test('should continue bulk removal after a failed image and refresh successful results', async ({+ page+ }) => {+ expect(+ realImages.length,+ 'At least two images are required for bulk remove test'+ ).toBeGreaterThanOrEqual(2);+ await navigateToImages(page);++ const rows = getImageRows(page);+ await expect(rows.nth(1)).toBeVisible();+ const initialRowCount = await rows.count();+ const mock = await mockImageDeleteFlow(page, true);++ await rows.nth(0).getByRole('checkbox', { name: 'Select row', exact: true }).check();+ await rows.nth(1).getByRole('checkbox', { name: 'Select row', exact: true }).check();+ await page.getByRole('button', { name: 'Remove Selected (2)', exact: true }).click();++ const dialog = page.getByRole('dialog');+ await dialog.getByRole('button', { name: 'Remove', exact: true }).click();++ await expect.poll(() => mock.deleteRequestCount).toBe(2);+ expect(mock.maxInFlight).toBe(1);+ await expect(+ page+ .getByRole('region', { name: 'Notifications alt+T', exact: true })+ .getByRole('listitem')+ .filter({ hasText: 'Removed 1 of 2' })+ ).toBeVisible();+ await expect.poll(() => getImageRows(page).count()).toBe(initialRowCount - 1);+ await expect(page.getByRole('button', { name: /^Remove Selected/ })).toHaveCount(0);+ });-test.describe('Images Page', () => {- test('should display the images page title and description', async ({ page }) => {- await navigateToImages(page);+ test('should call prune API on prune click and confirmation', async ({ page }) => {+ await navigateToImages(page);++ let pruneButton = page.getByRole('button', { name: 'Prune Unused' });+ await expect(+ pruneButton+ .or(page.getByRole('button', { name: 'More actions' }))+ .filter({ visible: true })+ .first()+ ).toBeVisible();+ const isDirectlyVisible = await pruneButton.isVisible();++ if (!isDirectlyVisible) {+ await page.getByRole('button', { name: 'More actions' }).click();+ pruneButton = page.getByRole('menuitem', { name: 'Prune Unused' });+ }- await expect(page.getByRole('heading', { name: 'Images', level: 1 })).toBeVisible();- await expect(page.getByText('View and Manage your Container images').first()).toBeVisible();- });+ await pruneButton.click();- test('should display stats cards with correct counts and size', async ({ page }) => {- await navigateToImages(page);+ const dialog = page.getByRole('dialog');+ await expect(+ dialog.getByRole('heading', { name: 'Prune Unused Images', exact: true })+ ).toBeVisible();+ const pruneResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/environments/0/images/prune'+ );+ await dialog.getByRole('button', { name: 'Prune Images', exact: true }).click();+ await readApiData<Record<string, unknown>>(+ await pruneResponsePromise,+ 'Prune dangling images'+ );- await expect(page.getByText(`${imageCounts.totalImages} Total Images`)).toBeVisible();- await expect(page.getByText('Total Size', { exact: true })).toBeVisible();- });+ await expect(+ page+ .getByRole('region', { name: 'Notifications alt+T', exact: true })+ .getByRole('listitem')+ .filter({ hasText: 'pruned' })+ ).toBeVisible({+ timeout: 10000+ });+ });- test('should align /images/counts with usage derived from /images list', async ({ page }) => {- await navigateToImages(page);+ test('should pull image via form', async ({ page }) => {+ test.setTimeout(180_000); // Pulling images can take a long time on CI- await expect- .poll(- async () => {- const [allImages, counts] = await Promise.all([- fetchAllImagesForUsage(page),- fetchImageCountsWithRetry(page)- ]);- const derivedInUse = allImages.filter((image) => !!image.inUse).length;- return {- totalDifference: counts.totalImages - allImages.length,- inUseDifference: counts.imagesInuse - derivedInUse,- unusedDifference: counts.imagesUnused - (allImages.length - derivedInUse)- };- },- {- message:- 'Expected image usage counts and the image list to describe the same Docker state',- timeout: 30_000,- intervals: [500, 1_000, 2_000]- }- )- .toEqual({ totalDifference: 0, inUseDifference: 0, unusedDifference: 0 });- });+ await navigateToImages(page);- test('should display the image table when images exist', async ({ page }) => {- await navigateToImages(page);+ await page.getByRole('button', { name: 'Pull Image' }).click();+ const dialogHeading = page.getByRole('heading', { name: 'Pull Image' });+ await expect(dialogHeading).toBeVisible();+ await waitForDialogReady(page.getByRole('dialog'));- await expect(page.getByRole('table')).toBeVisible();- await expect(page.getByRole('button', { name: 'Repository' })).toBeVisible();- });+ await page+ .getByRole('textbox', { name: 'Image Name *' })+ .fill('public.ecr.aws/docker/library/alpine');+ await page.getByRole('textbox', { name: 'Tag' }).fill('3.20');+ await expect(page.getByRole('textbox', { name: 'Image Name *' })).toHaveValue(+ 'public.ecr.aws/docker/library/alpine'+ );+ await expect(page.getByRole('textbox', { name: 'Tag' })).toHaveValue('3.20');- test('should display full pinned references without enabling tag actions', async ({ page }) => {- const { imageId, repository, pinnedReference, alternateReference } =- await mockPinnedImageFlow(page);- await page.reload();+ await page.getByRole('button', { name: 'Pull', exact: true }).click();- const row = page.getByRole('row').filter({- has: page.getByRole('link', { name: repository, exact: true })+ await expect(dialogHeading).toBeHidden({ timeout: 120_000 });});- await expect(row.getByText(pinnedReference, { exact: true })).toBeVisible();-- const overflow = row.getByText('+1', { exact: true });- await overflow.hover();- await expect(page.getByText(alternateReference, { exact: true })).toBeVisible();-- const menu = await openRowActionsMenu(page, row);- await expect(menu.getByRole('menuitem', { name: 'Pull', exact: true })).toBeDisabled();- await expect(menu.getByRole('menuitem', { name: 'Patch', exact: true })).toBeDisabled();- await page.keyboard.press('Escape');-- await row.getByRole('link', { name: repository, exact: true }).click();- await expect- .poll(() => decodeURIComponent(new URL(page.url()).pathname))- .toBe(`/images/${imageId}`);- await expect(page.getByRole('heading', { name: pinnedReference, exact: true })).toBeVisible();- await expect(page.getByText('Pinned References', { exact: true })).toBeVisible();- await expect(page.getByText(pinnedReference, { exact: true }).last()).toBeVisible();- await expect(page.getByText(alternateReference, { exact: true }).last()).toBeVisible();- await expect(page.getByRole('button', { name: 'Patch', exact: true })).toHaveCount(0);});+});- test('should open the Pull Image dialog', async ({ page }) => {- await navigateToImages(page);- await page.getByRole('button', { name: 'Pull Image' }).click();- await expect(page.getByRole('heading', { name: 'Pull Image', exact: true })).toBeVisible();- });+test.describe('Update checks', () => {+ const ROUTES = {+ page: '/images',+ apiImageUpdatesCheckBatch: '/api/environments/0/image-updates/check-batch',+ apiImageUpdatesCheckAll: '/api/environments/0/image-updates/check-all',+ apiImageUpdatesSummary: '/api/environments/0/image-updates/summary'+ };- test('should open the Prune Unused Images dialog', async ({ page }) => {- await navigateToImages(page);+ const TEST_IMAGE_REFS = {+ nginx: 'public.ecr.aws/nginx/nginx:stable-alpine',+ alpine: 'public.ecr.aws/docker/library/alpine:3.20',+ busybox: 'public.ecr.aws/docker/library/busybox:1.37'+ };++ async function navigateToImages(page: Page) {+ await page.goto(ROUTES.page);+ await page.waitForLoadState('load');+ }- let pruneButton = page.getByRole('button', { name: 'Prune Unused' });- await expect(- pruneButton- .or(page.getByRole('button', { name: 'More actions' }))- .filter({ visible: true })- .first()- ).toBeVisible();- const isDirectlyVisible = await pruneButton.isVisible();-- if (!isDirectlyVisible) {- await page.getByRole('button', { name: 'More actions' }).click();- pruneButton = page.getByRole('menuitem', { name: 'Prune Unused' });+ async function fetchImagesTotal(page: Page, updatesFilter?: string): Promise<number> {+ const params = new URLSearchParams({ start: '0', limit: '1' });+ if (updatesFilter) {+ params.set('updates', updatesFilter);}- await pruneButton.click();- await expect(- page.getByRole('heading', { name: 'Prune Unused Images', exact: true })- ).toBeVisible();- });+ const result = await readList(+ await page.request.get(`/api/environments/0/images?${params.toString()}`),+ 'List filtered images'+ );+ const total = result.pagination?.totalItems;+ if (total === undefined) throw new Error('Image list must include a total');+ return total;+ }- test('should navigate to image details on inspect click', async ({ page }) => {- await navigateToImages(page);+ async function getCheckUpdatesAction(page: Page): Promise<Locator> {+ await expect(page.getByRole('heading', { name: 'Images', exact: true })).toBeVisible();- const firstRow = page- .getByRole('row')- .filter({ has: page.getByRole('button', { name: 'Open menu', exact: true }) })+ const directButton = page+ .getByRole('button', { name: 'Check Updates', exact: true })+ .filter({ visible: true }).first();- const menu = await openRowActionsMenu(page, firstRow);- await menu.getByRole('menuitem', { name: 'Inspect' }).click();- });- test('should pull image from dropdown menu', async ({ page }) => {- test.setTimeout(90_000);- const reference = 'public.ecr.aws/docker/library/busybox:1.37';- const fixtures = await readList<{ id: string }>(- await page.request.get(ROUTES.apiImages, { params: { search: reference } }),- 'Find image pull fixture'- );- expect(fixtures.data).toHaveLength(1);- await navigateToImages(page);- await page.getByPlaceholder('Search…').first().fill(fixtures.data[0].id);+ const menuTrigger = page+ .getByRole('button', { name: 'More actions' })+ .filter({ visible: true })+ .first();+ await expect(directButton.or(menuTrigger).first()).toBeVisible();+ if (await directButton.isVisible()) return directButton;- const row = page- .getByRole('row')- .filter({ has: page.locator(`a[href="/images/${fixtures.data[0].id}"]`) });- const menu = await openRowActionsMenu(page, row);- const responsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === `${ROUTES.apiImages}/pull`- );- await menu.getByRole('menuitem', { name: 'Pull' }).click();- const response = await responsePromise;- expect(response.ok(), 'Pull fixture image').toBe(true);- const frames = (await response.text())- .trim()- .split('\n')- .map(- (line) =>- JSON.parse(line) as {- activityId?: string;- done?: boolean;- error?: unknown;- }- );- expect(frames.some((frame) => frame.error)).toBe(false);- expect(frames).toContainEqual(expect.objectContaining({ done: true }));- const activityId = frames.find((frame) => frame.activityId)?.activityId;- expect(activityId).toBeTruthy();- await expect(- page- .getByRole('region', { name: 'Notifications alt+T', exact: true })- .getByRole('listitem')- .filter({ hasText: `Image ${reference} pulled successfully` })- ).toBeVisible();- await expect- .poll(- async () => {- const detail = await readApiData<{ activity: { status: string } }>(- await page.request.get(`/api/environments/0/activities/${activityId}`),- 'Get image pull activity'- );- return detail.activity.status;- },- { timeout: 60_000 }- )- .toBe('success');- });+ await menuTrigger.click();- test('should call remove API on row action remove click and confirmation', async ({ page }) => {- expect(realImages.length, 'No images available for remove API test').toBeGreaterThan(0);+ const menu = page.getByRole('menu').filter({ visible: true }).last();+ await expect(menu).toBeVisible();+ const menuItem = menu.getByRole('menuitem', { name: 'Check Updates', exact: true }).first();+ await expect(menuItem).toBeVisible();+ return menuItem;+ }++ async function openImageUpdateCard(page: Page, trigger: Locator): Promise<Locator> {+ const usesTouchPopover = await page.evaluate(() => window.matchMedia('(hover: none)').matches);+ if (usesTouchPopover) {+ await trigger.click();+ } else {+ await trigger.hover();+ }++ const content = page.locator('[data-open="true"]').filter({ visible: true }).last();+ await expect(content).toBeVisible();+ return content;+ }++ let realImages: ImageSummary[] = [];++ test.beforeEach(async ({ page }) => {await navigateToImages(page);- const removableImage = realImages.find((image) => image.repo && image.repo !== '<none>');- expect(removableImage, 'No removable images available').toBeTruthy();- const removePath = `/api/environments/0/images/${removableImage.id}`;-- let removeRequestCount = 0;- await page.route(- (url) => decodeURIComponent(url.pathname) === removePath,- async (route) => {- if (route.request().method() !== 'DELETE') {- await route.continue();- return;- }+ realImages = await fetchImagesWithRetry(page);+ });- removeRequestCount += 1;+ test.describe('Image Update UI - Check All Updates Button', () => {+ test('should trigger bulk update check when clicking Check Updates button', async ({+ page+ }) => {+ await page.route(`**${ROUTES.apiImageUpdatesCheckAll}`, async (route) => {await route.fulfill({status: 200,contentType: 'application/json',- body: JSON.stringify({- success: true,- data: { message: 'Image removed successfully' }- })+ body: JSON.stringify({ success: true, data: {} })});- }- );+ });+ await navigateToImages(page);++ const checkUpdatesButton = await getCheckUpdatesAction(page);+ await expect(checkUpdatesButton).toBeVisible();++ const checkAllResponsePromise = page.waitForResponse((response) => {+ const request = response.request();+ if (request.method() !== 'POST') return false;+ return new URL(response.url()).pathname === ROUTES.apiImageUpdatesCheckAll;+ });++ await checkUpdatesButton.click();- // The API list and the UI use different sorting, so the selected image may be on another page.- const search = page.getByRole('textbox', { name: 'Search…', exact: true });- await search.fill(removableImage.id);- await search.press('Enter');+ const checkAllResponse = await checkAllResponsePromise;+ expect(checkAllResponse.ok()).toBeTruthy();- const imageRow = getImageRows(page).filter({- has: page.locator(`a[href="/images/${removableImage.id}"]`)+ // Eventually a success or completion toast should appear+ await expect(+ page.getByRole('region', { name: 'Notifications alt+T', exact: true }).getByRole('listitem')+ ).toBeVisible({ timeout: 60000 });});- const menu = await openRowActionsMenu(page, imageRow);- await menu.getByRole('menuitem', { name: 'Remove', exact: true }).click();-- const dialog = page.getByRole('dialog', { name: 'Remove image', exact: true });- await expect(dialog).toBeVisible();- // The post-remove refresh goes through queryClient.fetchQuery, which joins an- // already in-flight background refetch instead of issuing a new request, so- // asserting on fresh network calls here races under parallel load. The bulk- // removal tests below cover the refresh path with stubbed list/count endpoints.- await dialog.getByRole('button', { name: 'Remove', exact: true }).click();- await expect.poll(() => removeRequestCount).toBe(1);-- await expect(- page.getByRole('region', { name: 'Notifications alt+T', exact: true }).getByRole('listitem')- ).toBeVisible();});- test('should remove selected images sequentially and refresh the list and usage counts', async ({- page- }) => {- expect(- realImages.length,- 'At least two images are required for bulk remove test'- ).toBeGreaterThanOrEqual(2);- await navigateToImages(page);+ test.describe('Image Update UI - Individual Image Update Check via Hover Card', () => {+ test('should show hover card tooltip when hovering over update status icon', async ({+ page+ }) => {+ expect(realImages.length, 'No images available').toBeGreaterThan(0);++ await navigateToImages(page);- const rows = getImageRows(page);- await expect(rows.nth(1)).toBeVisible();- const initialRowCount = await rows.count();- const mock = await mockImageDeleteFlow(page);+ // Wait for images table+ await expect(page.getByRole('table')).toBeVisible();- await rows.nth(0).getByRole('checkbox', { name: 'Select row', exact: true }).check();- await rows.nth(1).getByRole('checkbox', { name: 'Select row', exact: true }).check();- await expect(- page.getByRole('button', { name: 'Remove Selected (2)', exact: true })- ).toBeVisible();- await page.getByRole('button', { name: 'Remove Selected (2)', exact: true }).click();+ // Find the first row's update status area (the Updates column)+ const firstRow = page+ .getByRole('row')+ .filter({ has: page.getByTestId('image-update-trigger') })+ .first();+ await expect(firstRow).toBeVisible();- const dialog = page.getByRole('dialog');- await dialog.getByRole('button', { name: 'Remove', exact: true }).click();+ // Look for the update status icon trigger element (Tooltip.Trigger wraps a span)+ const updateStatusTrigger = firstRow.getByTestId('image-update-trigger').first();+ await openImageUpdateCard(page, updateStatusTrigger);+ });- await expect.poll(() => mock.deleteRequestCount).toBe(2);- expect(mock.maxInFlight).toBe(1);- await expect(+ test('should allow triggering individual image update check from hover card', async ({page- .getByRole('region', { name: 'Notifications alt+T', exact: true })- .getByRole('listitem')- .filter({ hasText: '2 images removed successfully' })- ).toBeVisible();- await expect.poll(() => getImageRows(page).count()).toBe(initialRowCount - 2);- await expect(page.getByRole('button', { name: /^Remove Selected/ })).toHaveCount(0);+ }) => {+ expect(realImages.length, 'No images available').toBeGreaterThan(0);++ const fixtures = await readList<{ id: string; repoTags: string[] }>(+ await page.request.get('/api/environments/0/images', {+ params: { search: TEST_IMAGE_REFS.busybox }+ }),+ 'Find BusyBox fixture'+ );+ const testImage = fixtures.data.find((image) =>+ image.repoTags?.includes(TEST_IMAGE_REFS.busybox)+ );+ if (!testImage) throw new Error('BusyBox fixture must be present');+ await navigateToImages(page);+ const filteredImagesResponse = page.waitForResponse((response) => {+ const url = new URL(response.url());+ return (+ response.request().method() === 'GET' &&+ url.pathname === '/api/environments/0/images' &&+ url.searchParams.get('search') === testImage.id+ );+ });+ await page.getByPlaceholder('Search…').first().fill(testImage.id);+ const filteredResponse = await filteredImagesResponse;+ expect(filteredResponse.ok()).toBe(true);+ await filteredResponse.finished();+ await expect(page.getByRole('table').locator('tbody tr')).toHaveCount(1);+ const row = page+ .getByRole('row')+ .filter({ has: page.locator(`a[href="/images/${testImage.id}"]`) });+ const trigger = row.getByTestId('image-update-trigger');+ await expect(trigger).toBeVisible();+ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ decodeURIComponent(new URL(response.url()).pathname) ===+ `/api/environments/0/image-updates/check/${testImage.id}`+ );+ if (await trigger.evaluate((element) => element.tagName === 'BUTTON')) {+ await trigger.click();+ } else {+ const updateCard = await openImageUpdateCard(page, trigger);+ await updateCard.getByRole('button', { name: 'Re-check Updates', exact: true }).click();+ }+ expect((await responsePromise).ok()).toBe(true);+ await expect(page.locator('li[data-sonner-toast]').first()).toBeVisible();+ });});- test('should continue bulk removal after a failed image and refresh successful results', async ({- page- }) => {- expect(- realImages.length,- 'At least two images are required for bulk remove test'- ).toBeGreaterThanOrEqual(2);- await navigateToImages(page);+ test.describe('Image Update API Endpoints', () => {+ test('should get update summary via API', async ({ page }) => {+ const res = await page.request.get(ROUTES.apiImageUpdatesSummary);- const rows = getImageRows(page);- await expect(rows.nth(1)).toBeVisible();- const initialRowCount = await rows.count();- const mock = await mockImageDeleteFlow(page, true);+ expect(res.status()).toBe(200);- await rows.nth(0).getByRole('checkbox', { name: 'Select row', exact: true }).check();- await rows.nth(1).getByRole('checkbox', { name: 'Select row', exact: true }).check();- await page.getByRole('button', { name: 'Remove Selected (2)', exact: true }).click();+ const json = await readApiData<ImageUpdateSummary>(res, 'Get image update summary');- const dialog = page.getByRole('dialog');- await dialog.getByRole('button', { name: 'Remove', exact: true }).click();+ const [imagesTotal, hasUpdateTotal] = await Promise.all([+ fetchImagesTotal(page),+ fetchImagesTotal(page, 'has_update')+ ]);- await expect.poll(() => mock.deleteRequestCount).toBe(2);- expect(mock.maxInFlight).toBe(1);- await expect(- page- .getByRole('region', { name: 'Notifications alt+T', exact: true })- .getByRole('listitem')- .filter({ hasText: 'Removed 1 of 2' })- ).toBeVisible();- await expect.poll(() => getImageRows(page).count()).toBe(initialRowCount - 1);- await expect(page.getByRole('button', { name: /^Remove Selected/ })).toHaveCount(0);+ expect(json.totalImages).toBe(imagesTotal);+ expect(json.imagesWithUpdates).toBe(hasUpdateTotal);+ });});- test('should call prune API on prune click and confirmation', async ({ page }) => {- await navigateToImages(page);+ test.describe('Batch Update Checks', () => {+ test('should handle empty batch request', async ({ page }) => {+ const res = await page.request.post(ROUTES.apiImageUpdatesCheckBatch, {+ data: {+ imageRefs: []+ }+ });- let pruneButton = page.getByRole('button', { name: 'Prune Unused' });- await expect(- pruneButton- .or(page.getByRole('button', { name: 'More actions' }))- .filter({ visible: true })- .first()- ).toBeVisible();- const isDirectlyVisible = await pruneButton.isVisible();-- if (!isDirectlyVisible) {- await page.getByRole('button', { name: 'More actions' }).click();- pruneButton = page.getByRole('menuitem', { name: 'Prune Unused' });- }+ expect(res.status()).toBe(200);- await pruneButton.click();+ const json = await readApiData<Record<string, ImageUpdateInfo>>(res, 'Check image updates');- const dialog = page.getByRole('dialog');- await expect(- dialog.getByRole('heading', { name: 'Prune Unused Images', exact: true })- ).toBeVisible();- const pruneResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === '/api/environments/0/images/prune'- );- await dialog.getByRole('button', { name: 'Prune Images', exact: true }).click();- await readApiData<Record<string, unknown>>(await pruneResponsePromise, 'Prune dangling images');+ expect(Object.keys(json).length).toBe(0);+ });- await expect(- page- .getByRole('region', { name: 'Notifications alt+T', exact: true })- .getByRole('listitem')- .filter({ hasText: 'pruned' })- ).toBeVisible({- timeout: 10000+ test('should return results for each image in batch', async ({ page }) => {+ const imageRefs = [TEST_IMAGE_REFS.nginx, TEST_IMAGE_REFS.alpine, TEST_IMAGE_REFS.busybox];++ const res = await page.request.post(ROUTES.apiImageUpdatesCheckBatch, {+ data: {+ imageRefs+ }+ });++ expect(res.status()).toBe(200);++ const json = await readApiData<Record<string, ImageUpdateInfo>>(res, 'Check image updates');++ // Each requested image should have a result+ for (const ref of imageRefs) {+ expect(json[ref]).toBeDefined();+ }});- });- test('should pull image via form', async ({ page }) => {- test.setTimeout(180_000); // Pulling images can take a long time on CI+ test('should handle mixed valid and invalid images in batch', async ({ page }) => {+ const imageRefs = [TEST_IMAGE_REFS.nginx, 'invalid-registry.example.com/nonexistent:latest'];- await navigateToImages(page);+ const res = await page.request.post(ROUTES.apiImageUpdatesCheckBatch, {+ data: {+ imageRefs+ }+ });- await page.getByRole('button', { name: 'Pull Image' }).click();- const dialogHeading = page.getByRole('heading', { name: 'Pull Image' });- await expect(dialogHeading).toBeVisible();- await waitForDialogReady(page.getByRole('dialog'));-- await page- .getByRole('textbox', { name: 'Image Name *' })- .fill('public.ecr.aws/docker/library/alpine');- await page.getByRole('textbox', { name: 'Tag' }).fill('3.20');- await expect(page.getByRole('textbox', { name: 'Image Name *' })).toHaveValue(- 'public.ecr.aws/docker/library/alpine'- );- await expect(page.getByRole('textbox', { name: 'Tag' })).toHaveValue('3.20');+ expect(res.status()).toBe(200);- await page.getByRole('button', { name: 'Pull', exact: true }).click();+ const json = await readApiData<Record<string, ImageUpdateInfo>>(res, 'Check image updates');- await expect(dialogHeading).toBeHidden({ timeout: 120_000 });+ // The Public ECR image should succeed.+ expect(json[TEST_IMAGE_REFS.nginx]).toBeDefined();++ // Invalid image should have an error+ const invalidResult = json['invalid-registry.example.com/nonexistent:latest'];+ expect(invalidResult.error).toBeTruthy();+ });});});diff --git a/tests/spec/network.spec.ts b/tests/spec/networks.spec.tssimilarity index 90%rename from tests/spec/network.spec.tsrename to tests/spec/networks.spec.tsindex dbba11445..e14e279d6 100644--- a/tests/spec/network.spec.ts+++ b/tests/spec/networks.spec.ts@@ -88,24 +88,9 @@ async function createNetworkViaApi(page: Page, networkName: string) {}}-async function findNetworkRow(page: Page, networkName: string) {- await page.getByPlaceholder('Search…').first().fill(networkName);- const row = page.getByRole('row').filter({- has: page.getByRole('link', { name: networkName, exact: true })- });- await expect(row).toBeVisible();- return row;-}-test.describe('Networks Page', () => {test.describe.configure({ mode: 'serial' });- test('Page renders with heading and subtitle', async ({ page }) => {- await navigateToNetworks(page);- await expect(page.getByRole('heading', { level: 1, name: 'Networks' })).toBeVisible();- await expect(page.getByText('Manage your Docker networks').first()).toBeVisible();- });-test('Stat cards show correct counts', async ({ page }) => {await navigateToNetworks(page);@@ -116,24 +101,7 @@ test.describe('Networks Page', () => {await expect(page.getByText(`${counts.unused} Unused Networks`)).toBeVisible();});- test('Table displays when networks exist, else empty state', async ({ page }) => {- const networkName = `e2e-table-network-${Date.now()}`;- await navigateToNetworks(page);- try {- await createNetworkViaApi(page, networkName);- await navigateToNetworks(page);- await expect(page.getByRole('table')).toBeVisible();- await expect(page.getByRole('button', { name: 'Name' })).toBeVisible();- await expect(await findNetworkRow(page, networkName)).toBeVisible();- } finally {- await removeApiResource(- page,- `/api/environments/0/networks/${encodeURIComponent(networkName)}`- );- }- });-- test('@cross-browser creates and removes a network through the UI', async ({ page }) => {+ test('creates and removes a network through the UI', async ({ page }) => {const networkName = `test-network-${Date.now()}`;try {const networkId = await createNetworkViaUI(page, networkName);diff --git a/tests/spec/rbac.spec.ts b/tests/spec/permissions.spec.tssimilarity index 100%rename from tests/spec/rbac.spec.tsrename to tests/spec/permissions.spec.tsdiff --git a/tests/spec/project.spec.ts b/tests/spec/projects.spec.tssimilarity index 93%rename from tests/spec/project.spec.tsrename to tests/spec/projects.spec.tsindex 7e1df107f..8beb996e4 100644--- a/tests/spec/project.spec.ts+++ b/tests/spec/projects.spec.ts@@ -301,11 +301,6 @@ test.beforeEach(async ({ page, registerCleanup }) => {});test.describe('Projects Page', () => {- test('should display the main heading and description', async ({ page }) => {- await expect(page.getByRole('heading', { name: 'Projects', level: 1 })).toBeVisible();- await expect(page.getByText('View and Manage Compose Projects')).toBeVisible();- });-test('should display summary cards with correct counts', async ({ page }) => {await expect(page.getByText(`${projectCounts.totalProjects} Total Projects`, {@@ -329,38 +324,6 @@ test.describe('Projects Page', () => {).toBeVisible();});- test('should display projects list', async ({ page }) => {- await expect(page.getByRole('table')).toBeVisible();- });-- test('should display the updates column', async ({ page }) => {- await expect(page.getByRole('columnheader', { name: 'Updates' })).toBeVisible();- });-- test('should show project actions menu', async ({ page }) => {- expect(realProjects.length, 'No projects available for actions menu test').toBeGreaterThan(0);-- await page.waitForLoadState('load');- const firstRow = page- .getByRole('row')- .filter({ has: page.getByRole('button', { name: 'Open menu', exact: true }) })- .first();- const menu = await openRowActionsMenu(page, firstRow);-- await expect(menu.getByRole('menuitem', { name: 'Edit' })).toBeVisible();- // Check for at least one of the state action buttons (Up/Down/Restart)- const upItem = menu.getByRole('menuitem', { name: 'Up', exact: true });- const downItem = menu.getByRole('menuitem', { name: 'Down', exact: true });- const restartItem = menu.getByRole('menuitem', {- name: 'Restart',- exact: true- });- await expect(upItem.or(downItem).or(restartItem).first()).toBeVisible();- await expect(menu.getByRole('menuitem', { name: 'Pull & Redeploy' })).toBeVisible();- await expect(menu.getByRole('menuitem', { name: 'Archive' })).toBeVisible();- await expect(menu.getByRole('menuitem', { name: 'Destroy' })).toBeVisible();- });-test('should archive and unarchive a stopped project from the projects page', async ({page}) => {@@ -480,12 +443,6 @@ test.describe('New Compose Project Page', () => {await page.waitForLoadState('load');});- test('should display the create project form', async ({ page }) => {- await expect(page.getByRole('button', { name: 'My New Project' })).toBeVisible();- await expect(page.getByRole('heading', { name: 'Docker Compose File' })).toBeVisible();- await expect(page.getByRole('heading', { name: 'Environment (.env)' })).toBeVisible();- });-test('should preserve YAML indentation when pressing Enter in compose editor', async ({page}) => {@@ -513,10 +470,6 @@ test.describe('New Compose Project Page', () => {await page.getByRole('textbox', { name: 'My New Project' }).press('Enter');});- test('should have a head title', async ({ page }) => {- await expect(page).toHaveTitle('Arcane | Projects | My New Project');- });-test('should enable Create Project after entering a valid name', async ({ page }) => {const observedErrors: string[] = [];page.on('pageerror', (err) => observedErrors.push(String(err?.message ?? err)));@@ -649,7 +602,7 @@ test.describe('New Compose Project Page', () => {await page.waitForURL(/\/projects\/.+/, { timeout: 10000 });if (createdProjectId) {- await expect(page).toHaveURL(new RegExp(`/projects/${createdProjectId}`));+ await expect(page).toHaveURL(new RegExp(`/projects/${String(createdProjectId)}`));} else {await expect(page).toHaveURL(new RegExp(`/projects/[a-f0-9\\-]{36}`));}@@ -1225,22 +1178,6 @@ test.describe('Project Detail Page', () => {await expect(page.getByRole('tab', { name: 'Logs', exact: true })).toHaveCount(0);});- test('should display tabs navigation', async ({ page }) => {- expect(realProjects.length, 'No projects available for navigation test').toBeGreaterThan(0);- const firstProject = realProjects[0];- await page.goto(`/projects/${firstProject.id || firstProject.name}`);- await page.waitForLoadState('load');-- await expect(- page.getByRole('tab', {- name: `Services ${firstProject.serviceCount ?? 0}`,- exact: true- })- ).toBeVisible();- await expect(page.getByRole('tab', { name: 'Configuration', exact: true })).toBeVisible();- await expect(page.getByRole('tab', { name: 'Logs', exact: true })).toHaveCount(0);- });-test('should check updates for the current project without deploying it', async ({ page }) => {const projectName = `test-project-update-check-${Date.now()}`;const projectID = await createProjectViaUI(page, projectName);@@ -1286,31 +1223,6 @@ test.describe('Project Detail Page', () => {expect(updaterRunRequests).toBe(0);});- test('should display services tab content', async ({ page }) => {- expect(realProjects.length, 'No projects available for services test').toBeGreaterThan(0);-- const projectWithServices =- realProjects.find((p) => (p.serviceCount ?? 0) > 0) ?? realProjects[0]!;- await page.goto(`/projects/${projectWithServices.id || projectWithServices.name}`);- await page.waitForLoadState('load');-- await page- .getByRole('tab', {- name: `Services ${projectWithServices.serviceCount ?? 0}`,- exact: true- })- .click();-- const nginxService = page.getByRole('heading', { name: 'nginx', exact: true });- const emptyState = page.getByText('No services found for this project', { exact: true });-- const serviceStatus = page- .getByText('Running', { exact: true })- .or(page.getByText('Stopped', { exact: true }))- .or(page.getByText('Unknown', { exact: true }));- await expect(nginxService.or(serviceStatus).or(emptyState).first()).toBeVisible();- });-test('should display the configured service port host IP', async ({ page }) => {test.slow();@@ -1697,7 +1609,7 @@ test.describe('Project Detail Page', () => {const targetProject = realProjects[0];await page.routeWebSocket('**/api/environments/*/ws/projects/*/logs**', (ws) => {- ws.close({ code: 1013, reason: 'forced failure' });+ void ws.close({ code: 1013, reason: 'forced failure' });});await page.goto(`/projects/${targetProject.id || targetProject.name}?tab=services`);diff --git a/tests/spec/registries.spec.ts b/tests/spec/registries.spec.tsdeleted file mode 100644index 9fa726bf5..000000000--- a/tests/spec/registries.spec.ts+++ /dev/null@@ -1,232 +0,0 @@-import { readApiData, removeApiResource } from '../utils/fetch.util';-import { waitForDialogReady } from '../utils/playwright.util';-import { test, expect, type Page } from '../fixtures/test.fixture';-import { openRowActionsMenu } from '../utils/table-actions.util';--const route = '/customize/registries';-const TOKEN = process.env.REGISTRY_TEST_TOKEN ?? 'e2e-token';-const pullUsageRoute = /\/api\/container-registries\/pull-usage(?:\?|$)/;-const registryListRoute = /\/api\/container-registries(?:\?|$)/;--async function mockRegistryList(page: Page, registryId = 'dockerhub-registry') {- await page.context().route(registryListRoute, async (route) => {- if (route.request().method() !== 'GET') {- await route.fallback();- return;- }-- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({- success: true,- data: [- {- id: registryId,- url: 'docker.io',- username: 'docker-user',- description: 'Docker Hub test registry',- insecure: false,- enabled: true,- registryType: 'generic',- createdAt: new Date().toISOString(),- updatedAt: new Date().toISOString()- }- ],- pagination: {- totalPages: 1,- totalItems: 1,- currentPage: 1,- itemsPerPage: 20,- grandTotalItems: 1- }- })- });- });-}--async function mockRegistryPullUsage(- page: Page,- options: { registryId?: string; remaining?: number; limit?: number; observedPulls?: number }-) {- const registryId = options.registryId ?? 'dockerhub-registry';- await page.context().route(pullUsageRoute, async (route) => {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({- success: true,- data: {- registries: [- {- registryId,- provider: 'dockerhub',- registry: 'docker.io',- displayName: 'Docker Hub',- repository: 'ratelimitpreview/test',- ...(options.limit === undefined ? {} : { limit: options.limit }),- ...(options.remaining === undefined ? {} : { remaining: options.remaining }),- observedPulls: options.observedPulls ?? 0,- authMethod: 'credential',- authUsername: 'docker-user',- checkedAt: new Date().toISOString()- }- ]- }- })- });- });-}--test.describe('Container Registries', () => {- const registryIds = new Set<string>();- test.afterEach(async ({ page }) => {- for (const id of registryIds) await removeApiResource(page, `/api/container-registries/${id}`);- registryIds.clear();- });- test.beforeEach(async ({ page }) => {- await page.goto(route);- await page.waitForLoadState('load');- });-- test('should display title and subtitle, and refresh', async ({ page }) => {- await expect(- page.getByRole('heading', { name: 'Container Registries', level: 1 })- ).toBeVisible();- await expect(- page- .getByText(- 'Configure access credentials for private Docker registries and container repositories'- )- .first()- ).toBeVisible();-- await page.getByRole('button', { name: 'Refresh' }).click();- await expect(- page- .getByRole('region', { name: 'Notifications alt+T', exact: true })- .getByRole('listitem')- .filter({ hasText: 'Registries Refreshed!' })- ).toBeVisible({ timeout: 10000 });- });-- test('should open Add Registry dialog and validate required fields', async ({ page }) => {- await page.getByRole('button', { name: 'Add Registry' }).click();-- const dialog = page.getByRole('dialog');- await expect(dialog).toBeVisible();-- // Submit without URL -> expect validation error- await dialog.getByRole('button', { name: 'Add Registry', exact: true }).click();- await expect(dialog.getByText('Registry URL is required', { exact: true })).toBeVisible();-- // Close dialog- await page.keyboard.press('Escape');- await expect(dialog).toBeHidden();- });-- test('should display registry pull limit usage when headers are available', async ({ page }) => {- await mockRegistryList(page);- await mockRegistryPullUsage(page, { remaining: 76, limit: 100, observedPulls: 4 });- await page.goto(route);- await page.waitForLoadState('load');-- const table = page.getByRole('table');- await expect(table.getByText('Pull Usage')).toBeVisible();- await expect(table.getByText('76/100')).toBeVisible();- });-- test('should display observed pull count when registry limit headers are unavailable', async ({- page- }) => {- await mockRegistryList(page);- await mockRegistryPullUsage(page, { observedPulls: 4 });- await page.goto(route);- await page.waitForLoadState('load');-- const table = page.getByRole('table');- await expect(table.getByText('Pull Usage')).toBeVisible();- await expect(table.getByText('4 pulls')).toBeVisible();- });-- test('should create, test, edit, and delete a registry', async ({ page }) => {- // Create- await page.getByRole('button', { name: 'Add Registry' }).click();- const dialog = page.getByRole('dialog');- await waitForDialogReady(dialog);-- const url = `e2e.example.com-${Date.now()}`;-- // URL- await dialog.getByLabel('Registry URL', { exact: true }).fill(url);- // Username (frontend requires it)- await dialog.getByLabel('Username', { exact: true }).fill('e2e');- // Token (backend needs it to avoid 400)- const tokenInput = dialog.getByLabel('Token', { exact: true });- await tokenInput.fill(TOKEN);-- // Optional description- const desc = dialog.getByLabel('Description', { exact: true });- await desc.fill('E2E test registry');-- const createdPromise = page.waitForResponse(- (response) =>- response.request().method() === 'POST' &&- new URL(response.url()).pathname === '/api/container-registries'- );- await dialog.getByRole('button', { name: 'Add Registry', exact: true }).click();-- const created = await readApiData<{ id: string }>(await createdPromise, 'Create registry');- registryIds.add(created.id);-- // Creation complete when dialog closes- await expect(dialog).toBeHidden({ timeout: 10000 });-- // Row should appear- const row = page- .getByRole('row')- .filter({ has: page.getByText(url, { exact: true }) })- .first();- await expect(row).toBeVisible();-- // Test Connection (accept either success or failure toast)- const menu = await openRowActionsMenu(page, row);- await menu.getByRole('menuitem', { name: 'Test Connection' }).click();- });-- test('should open Remove Selected dialog and cancel (no mutation)', async ({ page }) => {- const registry = await readApiData<{ id: string }>(- await page.request.post('/api/container-registries', {- data: {- url: `e2e-select-${Date.now()}.example.com`,- username: 'e2e',- token: TOKEN,- description: '',- insecure: false,- enabled: true,- registryType: 'generic',- repositoryNames: [],- awsAccessKeyId: '',- awsSecretAccessKey: '',- awsRegion: ''- }- }),- 'Create registry selection fixture'- );- registryIds.add(registry.id);- await page.goto(route);- const firstRowCheckbox = page- .getByRole('row')- .filter({ has: page.getByRole('button', { name: 'Open menu', exact: true }) })- .getByRole('checkbox')- .first();- await firstRowCheckbox.check();- await page.getByRole('button', { name: 'Remove Selected (1)', exact: true }).click();- const confirm = page.getByRole('dialog');- await expect(- confirm.getByRole('heading', { name: 'Remove 1 Registry(ies)', exact: true })- ).toBeVisible();- await confirm.getByRole('button', { name: 'Cancel', exact: true }).click();- await expect(confirm).toBeHidden();- });-});diff --git a/tests/spec/responsive-browser.spec.ts b/tests/spec/responsive.spec.tssimilarity index 100%rename from tests/spec/responsive-browser.spec.tsrename to tests/spec/responsive.spec.tsdiff --git a/tests/spec/route-mount.spec.ts b/tests/spec/route-mount.spec.tsdeleted file mode 100644index 5cbab7e6e..000000000--- a/tests/spec/route-mount.spec.ts+++ /dev/null@@ -1,79 +0,0 @@-import { expect, test } from '../fixtures/test.fixture';--const AUTHENTICATED_ROUTES = [- '/account',- '/containers',- '/containers/new',- '/customize',- '/customize/git-repositories',- '/customize/registries',- '/customize/templates',- '/customize/templates/create',- '/customize/templates/default',- '/customize/variables',- '/dashboard',- '/environments',- '/environments/0',- '/environments/0/gitops',- '/events',- '/images',- '/images/builds',- '/networks',- '/networks/ports',- '/networks/topology',- '/no-access',- '/projects',- '/projects/new',- '/security',- '/settings',- '/settings/activity',- '/settings/api-keys',- '/settings/authentication',- '/settings/backups',- '/settings/backups/s3',- '/settings/builds',- '/settings/diagnostics',- '/settings/notifications',- '/settings/roles',- '/settings/roles/new',- '/settings/timeouts',- '/settings/users',- '/settings/webhooks',- '/swarm/cluster',- '/updates',- '/volumes'-] as const;--const LEGACY_REDIRECTS = [- { from: '/ports?search=8080', to: '/networks/ports?search=8080' },- { from: '/images/vulnerabilities?tab=ignored', to: '/security?tab=vulnerabilities' },- { from: '/settings/jobs', to: '/environments/0?tab=jobs' }-] as const;--test.describe('authenticated route mounts', () => {- for (const route of AUTHENTICATED_ROUTES) {- test(`${route} mounts without the application error view`, async ({ page }) => {- const response = await page.goto(route);-- expect(response, `Expected ${route} to return a document response`).not.toBeNull();- expect(response!.status(), `Expected ${route} not to return a server error`).toBeLessThan(- 500- );- await expect(page.locator('main').first()).toBeVisible();- await expect(page.getByText('Something went wrong', { exact: true })).toHaveCount(0);- await expect(- page.getByText('Unable to connect to local Docker daemon', { exact: true })- ).toHaveCount(0);- await expect(page.getByText(/^Unable to connect to remote environment /)).toHaveCount(0);- });- }-});--test.describe('legacy route redirects', () => {- for (const { from, to } of LEGACY_REDIRECTS) {- test(`${from} redirects to ${to}`, async ({ page }) => {- await page.goto(from);- await expect(page).toHaveURL(to);- });- }-});diff --git a/tests/spec/docker-runtime-identity.spec.ts b/tests/spec/runtime.spec.tssimilarity index 100%rename from tests/spec/docker-runtime-identity.spec.tsrename to tests/spec/runtime.spec.tsdiff --git a/tests/spec/s3-backups.spec.ts b/tests/spec/s3-backups.spec.tsdeleted file mode 100644index ba540825d..000000000--- a/tests/spec/s3-backups.spec.ts+++ /dev/null@@ -1,404 +0,0 @@-import { removeApiResource, readApiData } from '../utils/fetch.util';-import { test, expect, type Page } from '../fixtures/test.fixture';-import { openRowActionsMenu } from '../utils/table-actions.util';--// The MinIO sidecar in the compose stack. Arcane reaches it over the compose-// network, and so must the Rustic helper container it starts for each backup.-const S3_ENDPOINT = process.env.E2E_S3_ENDPOINT ?? 'http://minio:9000';-const S3_BUCKET = process.env.E2E_S3_BUCKET ?? 'arcane-backups';-const S3_ACCESS_KEY_ID = process.env.E2E_S3_ACCESS_KEY_ID ?? 'arcane-test';-const S3_SECRET_ACCESS_KEY = process.env.E2E_S3_SECRET_ACCESS_KEY ?? 'arcane-test-secret';--type S3Destination = { id: string; name: string; bucket: string; secretConfigured: boolean };-type BackupEntry = {- id: string;- status: string;- destination: string;- format: string;- remoteSnapshotId?: string;- localSnapshotId?: string;- error?: string;-};--function destinationPayload(overrides: Record<string, unknown> = {}) {- return {- name: `e2e-minio-${Date.now()}`,- endpoint: S3_ENDPOINT,- bucket: S3_BUCKET,- region: '',- accessKeyId: S3_ACCESS_KEY_ID,- secretAccessKey: S3_SECRET_ACCESS_KEY,- prefix: `e2e/${Date.now()}`,- useSsl: false,- forcePathStyle: true,- ...overrides- };-}--async function createDestinationViaApi(- page: Page,- overrides: Record<string, unknown> = {}-): Promise<S3Destination> {- const response = await page.request.post('/api/backups/s3', {- data: destinationPayload(overrides)- });- if (!response.ok()) {- throw new Error(- `Failed to create S3 destination: ${response.status()} ${await response.text()}`- );- }- return (await response.json()) as S3Destination;-}--async function deleteDestinationViaApi(page: Page, destinationId: string) {- await removeApiResource(page, `/api/backups/s3/${destinationId}`);-}--async function createVolumeViaApi(page: Page, volumeName: string) {- const response = await page.request.post('/api/environments/0/volumes', {- data: { name: volumeName, driver: 'local' }- });- if (!response.ok()) {- throw new Error(`Failed to create volume ${volumeName}: ${response.status()}`);- }-}--async function removeVolumeViaApi(page: Page, volumeName: string) {- await removeApiResource(- page,- `/api/environments/0/volumes/${encodeURIComponent(volumeName)}?force=true`- );-}--async function getVolumeWorkspaceRevision(page: Page, volumeName: string) {- const response = await page.request.get(- `/api/environments/0/volumes/${encodeURIComponent(volumeName)}/workspace`- );- if (!response.ok()) {- throw new Error(- `Failed to read ${volumeName} workspace: ${response.status()} ${await response.text()}`- );- }- const body = await response.json();- return body.data.fileTreeRevision as string;-}--async function writeVolumeFile(- page: Page,- volumeName: string,- fileName: string,- content: string,- operation: 'create_file' | 'update_file' = 'create_file'-) {- const fileTreeRevision = await getVolumeWorkspaceRevision(page, volumeName);- const response = await page.request.put(- `/api/environments/0/volumes/${encodeURIComponent(volumeName)}/workspace`,- {- multipart: {- manifest: JSON.stringify({- fileTreeRevision,- fileChanges: [{ operation, relativePath: fileName, uploadIndex: 0 }]- }),- files: { name: fileName, mimeType: 'text/plain', buffer: Buffer.from(content) }- }- }- );- if (!response.ok()) {- throw new Error(`Failed to upload ${fileName}: ${response.status()} ${await response.text()}`);- }-}--async function readVolumeFile(page: Page, volumeName: string, filePath: string) {- const relativePath = filePath.replace(/^\/+/, '');- const response = await page.request.get(- `/api/environments/0/volumes/${encodeURIComponent(volumeName)}/workspace/file?relativePath=${encodeURIComponent(relativePath)}`- );- const data = await readApiData<{ content: string }>(response, `Read volume file ${filePath}`);- expect(typeof data.content).toBe('string');- return data.content;-}--async function listBackups(page: Page, volumeName: string): Promise<BackupEntry[]> {- const backups = await readApiData<BackupEntry[]>(- await page.request.get(`/api/environments/0/volumes/${encodeURIComponent(volumeName)}/backups`),- `List backups for ${volumeName}`- );- expect(Array.isArray(backups)).toBe(true);- return backups;-}--// Backups run Rustic in a helper container, so the request returns before the-// snapshot finishes. Poll the record until it leaves the running state.-async function waitForBackup(page: Page, volumeName: string, backupId: string) {- let last: BackupEntry | undefined;- await expect- .poll(- async () => {- last = (await listBackups(page, volumeName)).find((entry) => entry.id === backupId);- return last?.status ?? 'missing';- },- { timeout: 180000, intervals: [2000] }- )- .not.toBe('running');- expect(last?.status, `backup failed: ${last?.error ?? 'unknown error'}`).toBe('succeeded');- return last as BackupEntry;-}--// Deleting a destination also verifies that no managed environment still-// references it, and is refused when one cannot be reached. Other specs create-// environments, so the release path depends on what is registered right now.-async function countRemoteEnvironments(page: Page) {- const response = await page.request.get('/api/environments');- if (!response.ok()) {- return 0;- }- const body = await response.json();- const environments = (body?.data ?? []) as { id: string }[];- return environments.filter((environment) => environment.id !== '0').length;-}--async function createBackupViaApi(- page: Page,- volumeName: string,- data: Record<string, unknown>-): Promise<BackupEntry> {- const response = await page.request.post(- `/api/environments/0/volumes/${encodeURIComponent(volumeName)}/backups`,- { data, timeout: 180000 }- );- if (!response.ok()) {- throw new Error(`Failed to create backup: ${response.status()} ${await response.text()}`);- }- const body = await response.json();- return body.data as BackupEntry;-}--test.describe('S3 Backups', () => {- test('creates, tests, edits, and deletes a destination through settings', async ({ page }) => {- test.setTimeout(120_000);- const suffix = Date.now();- const name = `e2e-minio-ui-${suffix}`;- const updatedName = `${name}-updated`;- let destinationId: string | undefined;-- try {- await page.goto('/settings/backups/s3');- await page.getByRole('button', { name: 'Add destination', exact: true }).click();-- let dialog = page.getByRole('dialog');- await expect(dialog.getByRole('heading', { name: 'Add S3 destination' })).toBeVisible();- await dialog.getByLabel('Name', { exact: true }).fill(name);- await dialog.getByLabel('Endpoint', { exact: true }).fill(S3_ENDPOINT);- await dialog.getByLabel('Bucket', { exact: true }).fill(S3_BUCKET);- await dialog.getByLabel('Access key ID', { exact: true }).fill(S3_ACCESS_KEY_ID);- await dialog.getByLabel('Secret access key', { exact: true }).fill(S3_SECRET_ACCESS_KEY);- await dialog.getByLabel('Path prefix', { exact: true }).fill(`e2e/ui/${suffix}`);-- const sslSwitch = dialog.getByRole('switch', { name: 'Use SSL', exact: true });- if (await sslSwitch.isChecked()) await sslSwitch.click();-- await dialog.getByRole('button', { name: 'Test Connection', exact: true }).click();- await expect(- page.getByText(`Connection to ${name} succeeded`, { exact: true })- ).toBeVisible();- await expect(- page.getByText('Connection verified. You can now save this destination.')- ).toBeVisible();- await dialog.getByRole('button', { name: 'Add S3 destination', exact: true }).click();-- await expect(page.getByText(`Created ${name}`, { exact: true })).toBeVisible();- let destinationRow = page.getByRole('row').filter({ hasText: name });- await expect(destinationRow).toBeVisible();-- const listResponse = await page.request.get('/api/backups/s3?start=0&limit=100');- expect(listResponse.status(), await listResponse.text()).toBe(200);- const destinations = (await listResponse.json()).data as S3Destination[];- destinationId = destinations.find((destination) => destination.name === name)?.id;- expect(destinationId).toBeTruthy();-- let menu = await openRowActionsMenu(page, destinationRow);- await menu.getByRole('menuitem', { name: 'Test Connection', exact: true }).click();- await expect(- page.getByText(`Connection to ${name} succeeded`, { exact: true }).last()- ).toBeVisible();-- menu = await openRowActionsMenu(page, destinationRow);- await menu.getByRole('menuitem', { name: 'Edit', exact: true }).click();- dialog = page.getByRole('dialog');- await expect(dialog.getByRole('heading', { name: 'Edit S3 destination' })).toBeVisible();- await dialog.getByLabel('Name', { exact: true }).fill(updatedName);- await dialog.getByLabel('Path prefix', { exact: true }).fill(`e2e/ui/${suffix}/updated`);- await dialog.getByRole('button', { name: 'Test Connection', exact: true }).click();- await expect(- page.getByText(`Connection to ${updatedName} succeeded`, { exact: true })- ).toBeVisible();- await dialog.getByRole('button', { name: 'Save Changes', exact: true }).click();-- await expect(page.getByText(`Updated ${updatedName}`, { exact: true })).toBeVisible();- destinationRow = page.getByRole('row').filter({ hasText: updatedName });- await expect(destinationRow).toBeVisible();- await expect- .poll(() => countRemoteEnvironments(page), {- message: 'Expected temporary remote environments to be removed before S3 deletion',- timeout: 90_000,- intervals: [1_000, 2_000]- })- .toBe(0);-- menu = await openRowActionsMenu(page, destinationRow);- await menu.getByRole('menuitem', { name: 'Delete', exact: true }).click();- const confirmDialog = page.getByRole('dialog', { name: `Delete ${updatedName}` });- await expect(- confirmDialog.getByRole('heading', { name: `Delete ${updatedName}` })- ).toBeVisible();- const deleteResponsePromise = page.waitForResponse(- (response) =>- response.request().method() === 'DELETE' &&- new URL(response.url()).pathname === `/api/backups/s3/${destinationId}`- );- await confirmDialog.getByRole('button', { name: 'Delete', exact: true }).click();- const deleteResponse = await deleteResponsePromise;- expect(deleteResponse.ok(), await deleteResponse.text()).toBe(true);-- await expect(page.getByText(`Deleted ${updatedName}`, { exact: true })).toBeVisible();- await expect(destinationRow).toHaveCount(0);- destinationId = undefined;- } finally {- if (destinationId) await deleteDestinationViaApi(page, destinationId);- }- });-- test('creates a destination and verifies connectivity against MinIO', async ({ page }) => {- const destination = await createDestinationViaApi(page);- try {- expect(destination.bucket).toBe(S3_BUCKET);- expect(destination.secretConfigured).toBe(true);-- // Uploads, downloads, and deletes a probe object in the bucket.- const test = await page.request.post(`/api/backups/s3/${destination.id}/test`);- expect(test.status(), await test.text()).toBe(200);- } finally {- await deleteDestinationViaApi(page, destination.id);- }- });-- test('refuses the stored secret once connection settings change', async ({ page }) => {- const destination = await createDestinationViaApi(page);- try {- const withoutSecret = await page.request.put(`/api/backups/s3/${destination.id}`, {- data: destinationPayload({- name: destination.name,- bucket: 'someone-elses-bucket',- secretAccessKey: ''- })- });- expect(withoutSecret.status()).toBe(400);- expect(await withoutSecret.text()).toContain('re-enter the secret access key');-- // The same edit is accepted once the secret is supplied again.- const withSecret = await page.request.put(`/api/backups/s3/${destination.id}`, {- data: destinationPayload({ name: destination.name, prefix: `e2e/${Date.now()}-moved` })- });- expect(withSecret.status(), await withSecret.text()).toBe(200);- } finally {- await deleteDestinationViaApi(page, destination.id);- }- });-- test('backs a volume up to S3 and restores it from the bucket', async ({ page }) => {- test.setTimeout(300000);-- const volumeName = `e2e-s3-backup-${Date.now()}`;- const fileContent = `arcane-e2e-${Date.now()}`;- const destination = await createDestinationViaApi(page);- let backupId: string | undefined;-- try {- await createVolumeViaApi(page, volumeName);- await writeVolumeFile(page, volumeName, 'payload.txt', fileContent);- expect(await readVolumeFile(page, volumeName, '/payload.txt')).toBe(fileContent);-- const created = await createBackupViaApi(page, volumeName, {- destination: 's3',- s3DestinationId: destination.id- });- backupId = created.id;- const backup = await waitForBackup(page, volumeName, created.id);-- expect(backup.destination).toBe('s3');- expect(backup.format).toBe('rustic');- expect(backup.remoteSnapshotId, 'no snapshot was recorded in S3').toBeTruthy();- expect(backup.localSnapshotId ?? '').toBe('');-- // Rustic can only list these paths by reading the repository back out- // of the bucket, so this proves the snapshot really landed in MinIO.- const files = await page.request.get(- `/api/environments/0/volumes/backups/${created.id}/files`- );- expect(files.status(), await files.text()).toBe(200);- expect(JSON.stringify((await files.json())?.data ?? [])).toContain('payload.txt');-- const replacementContent = 'x'.repeat(fileContent.length);- await writeVolumeFile(page, volumeName, 'payload.txt', replacementContent, 'update_file');- expect(await readVolumeFile(page, volumeName, '/payload.txt')).toBe(replacementContent);-- const restore = await page.request.post(- `/api/environments/0/volumes/${encodeURIComponent(volumeName)}/backups/${created.id}/restore`,- { data: {}, timeout: 180000 }- );- expect(restore.status(), await restore.text()).toBe(200);- expect(await readVolumeFile(page, volumeName, '/payload.txt')).toBe(fileContent);- } finally {- if (backupId) {- await removeApiResource(page, `/api/environments/0/volumes/backups/${backupId}`);- }- await removeVolumeViaApi(page, volumeName);- await deleteDestinationViaApi(page, destination.id);- }- });-- test('blocks deleting a destination a backup still references', async ({ page }) => {- test.setTimeout(300000);-- const volumeName = `e2e-s3-inuse-${Date.now()}`;- const destination = await createDestinationViaApi(page);- let backupId: string | undefined;-- try {- await createVolumeViaApi(page, volumeName);- await writeVolumeFile(page, volumeName, 'payload.txt', 'in-use');-- const created = await createBackupViaApi(page, volumeName, {- destination: 's3',- s3DestinationId: destination.id- });- backupId = created.id;- await waitForBackup(page, volumeName, created.id);-- const blocked = await page.request.delete(`/api/backups/s3/${destination.id}`);- expect(blocked.status()).toBe(409);-- const removed = await page.request.delete(- `/api/environments/0/volumes/backups/${created.id}`- );- expect(removed.ok(), await removed.text()).toBe(true);- backupId = undefined;-- const remoteEnvironments = await countRemoteEnvironments(page);- const allowed = await page.request.delete(`/api/backups/s3/${destination.id}`);- if (remoteEnvironments === 0) {- expect(allowed.status(), await allowed.text()).toBe(200);- } else {- // A registered environment that cannot be checked keeps the- // destination, so the local reference is no longer the blocker.- expect([200, 409]).toContain(allowed.status());- }- } finally {- if (backupId) {- await removeApiResource(page, `/api/environments/0/volumes/backups/${backupId}`);- }- await removeVolumeViaApi(page, volumeName);- await deleteDestinationViaApi(page, destination.id);- }- });-});diff --git a/tests/spec/settings-notifications.spec.ts b/tests/spec/settings-notifications.spec.tsdeleted file mode 100644index ef269de6b..000000000--- a/tests/spec/settings-notifications.spec.ts+++ /dev/null@@ -1,495 +0,0 @@-import { test, expect, type Page } from '../fixtures/test.fixture';--test.describe('Notification settings', () => {- const openProviderTab = async (page: Page, name: string) => {- const tab = page.getByRole('tab', { name });- await tab.scrollIntoViewIfNeeded();- await expect(tab).toBeVisible();- await tab.click();- await expect(page.getByRole('tabpanel').filter({ visible: true })).toBeVisible();- };-- const enableCurrentProvider = async (page: Page) => {- const providerPanel = page.getByRole('tabpanel').filter({ visible: true });- const toggle = providerPanel.getByRole('switch').first();- await expect(toggle).toBeVisible();- await toggle.click();- await expect(providerPanel.locator('[data-dropdown-menu-trigger]')).toBeVisible({- timeout: 10000- });- };-- const openTestMenu = async (page: Page) => {- const trigger = page- .getByRole('tabpanel')- .filter({ visible: true })- .locator('[data-dropdown-menu-trigger]');- await expect(trigger).toBeVisible({ timeout: 10000 });- await trigger.click();- };-- // Shared setup for all notification tests- const setupNotificationTest = async (- page: Page,- provider: string,- options: {- failProviders?: ReadonlySet<string>;- initialSettings?: Array<Record<string, unknown>>;- } = {}- ) => {- const observedErrors: string[] = [];-- page.on('pageerror', (err) => {- observedErrors.push(String(err?.message ?? err));- });-- page.on('console', (msg) => {- if (msg.type() === 'error') {- observedErrors.push(msg.text());- }- });-- let saveEndpointCalled = false;- let testEndpointCalled = false;- const attemptedProviders: string[] = [];- const savedProviders: string[] = [];- // Saved settings are kept in memory and served back on GET so that a- // reload round-trips them through the form like the real backend would.- const persistedSettings: Array<Record<string, unknown>> = [...(options.initialSettings ?? [])];- const savedPayloads: Array<Record<string, unknown>> = [];-- await page.route('**/api/environments/*/notifications/settings', async (route) => {- const req = route.request();- if (req.method() === 'GET') {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify(persistedSettings)- });- return;- }-- if (req.method() === 'POST') {- saveEndpointCalled = true;- const saved = req.postDataJSON() as Record<string, unknown>;- const savedProvider = String(saved.provider ?? '');- attemptedProviders.push(savedProvider);- savedPayloads.push(saved);- if (options.failProviders?.has(savedProvider)) {- await route.fulfill({- status: 500,- contentType: 'application/json',- body: JSON.stringify({ error: `${savedProvider} save failed` })- });- return;- }- savedProviders.push(savedProvider);- const index = persistedSettings.findIndex((s) => s.provider === saved.provider);- if (index >= 0) {- persistedSettings[index] = saved;- } else {- persistedSettings.push(saved);- }- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify(saved)- });- return;- }-- await route.continue();- });-- // Stub the specific test endpoint- await page.route(`**/api/environments/*/notifications/test/${provider}**`, async (route) => {- testEndpointCalled = true;- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({ success: true })- });- });-- await page.goto('/settings/notifications');- await page.waitForLoadState('load');- await expect(page.getByRole('tab', { name: 'Email' })).toBeVisible();-- return {- getErrorCheck: () => {- const stateUnsafe = observedErrors.filter((e) => e.includes('state_unsafe_mutation'));- expect(- stateUnsafe,- `Unexpected state_unsafe_mutation errors: ${stateUnsafe.join('\n')}`- ).toHaveLength(0);- },- wasTestEndpointCalled: () => testEndpointCalled,- wasSaveEndpointCalled: () => saveEndpointCalled,- getAttemptedProviders: () => [...attemptedProviders],- getSavedProviders: () => [...savedProviders],- getSavedPayloads: () => [...savedPayloads]- };- };-- const telegramSettings = (chatIds: string[]) => ({- provider: 'telegram',- enabled: true,- config: {- chatIds,- preview: true,- notification: true,- title: '',- events: {- image_update: true,- container_update: true,- vulnerability_found: true,- prune_report: true,- auto_heal: true- }- }- });-- const telegramChatIds = (payload: Record<string, unknown>) =>- (payload.config as { chatIds: string[] }).chatIds;-- const telegramRow = (page: Page, index: number) => ({- chatId: page.locator(`#telegram-chat-id-${index}`),- topicId: page.locator(`#telegram-topic-id-${index}`)- });-- test('saves only changed providers and retains failed providers as dirty', async ({ page }) => {- const { getAttemptedProviders, getSavedProviders } = await setupNotificationTest(- page,- 'discord',- {- failProviders: new Set(['email'])- }- );-- await openProviderTab(page, 'Discord');- await enableCurrentProvider(page);- await page.getByPlaceholder('Enter webhook ID').fill('123456789');- await page.getByPlaceholder('Enter webhook token').fill('abc-def-ghi');-- await openProviderTab(page, 'Email');- await enableCurrentProvider(page);- await page.getByPlaceholder('smtp.example.com').fill('smtp.example.com');- await page.getByPlaceholder('[email protected]').fill('[email protected]');-- const saveButton = page.getByRole('button', { name: 'Save', exact: true });- await saveButton.click();- await expect.poll(getAttemptedProviders).toEqual(['email', 'discord']);- await expect.poll(getSavedProviders).toEqual(['discord']);- await expect(page.getByText(/Failed to save Email settings:/)).toBeVisible();- await expect(saveButton).toBeEnabled();-- await saveButton.click();- await expect.poll(getAttemptedProviders).toEqual(['email', 'discord', 'email']);- });-- test('should persist the selected provider tab in the URL', async ({ page }) => {- await setupNotificationTest(page, 'discord');- await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('email');-- await openProviderTab(page, 'Discord');- await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('discord');-- await page.reload();- await expect(page.getByRole('tab', { name: 'Discord' })).toHaveAttribute(- 'data-state',- 'active'- );- await expect(page.getByRole('tabpanel', { name: 'Discord', exact: true })).toBeVisible();- });-- test('should allow testing email notifications without state_unsafe_mutation errors', async ({- page- }) => {- const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'email');-- await openProviderTab(page, 'Email');- await enableCurrentProvider(page);-- // Fill fields- await page.getByPlaceholder('smtp.example.com').fill('smtp.example.com');- await page.getByPlaceholder('[email protected]').fill('[email protected]');-- // Trigger test- await openTestMenu(page);- await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();-- // Handle Save & Test if needed- const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });- await saveAndTestButton.click();-- await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);- getErrorCheck();- });-- test('should allow testing discord notifications', async ({ page }) => {- const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'discord');-- await openProviderTab(page, 'Discord');- await enableCurrentProvider(page);-- // Discord split fields- await page.getByPlaceholder('Enter webhook ID').fill('123456789');- await page.getByPlaceholder('Enter webhook token').fill('abc-def-ghi');-- await openTestMenu(page);- await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();-- const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });- await saveAndTestButton.click();-- await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);- getErrorCheck();- });-- test('should allow testing slack notifications', async ({ page }) => {- const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'slack');-- await openProviderTab(page, 'Slack');- await enableCurrentProvider(page);-- // Slack OAuth token (xoxb- or xoxp- format)- await page- .getByPlaceholder('xoxb-... or xoxp-...')- .fill('xoxb-123456789012-1234567890123-abcdefghijklmnopqrstuvwx');-- await openTestMenu(page);- await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();-- const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });- await saveAndTestButton.click();-- await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);- getErrorCheck();- });-- test('should allow testing telegram notifications', async ({ page }) => {- const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'telegram');-- await openProviderTab(page, 'Telegram');- await enableCurrentProvider(page);-- // Telegram fields (placeholders are hardcoded in component)- await page- .getByPlaceholder('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11')- .fill('123456:TEST-TOKEN');- await telegramRow(page, 0).chatId.fill('123456789');-- await openTestMenu(page);- await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();-- const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });- await saveAndTestButton.click();-- await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);- getErrorCheck();- });-- test('loads, edits and saves telegram topic destinations', async ({ page }) => {- const { getSavedPayloads, wasSaveEndpointCalled } = await setupNotificationTest(- page,- 'telegram',- {- initialSettings: [telegramSettings(['@channel', '-1001234567890:42'])]- }- );-- await openProviderTab(page, 'Telegram');- const saveButton = page.getByRole('button', { name: 'Save', exact: true });- const panel = page.getByRole('tabpanel').filter({ visible: true });-- // Existing chats and chatId:topicId entries load into separate fields.- await expect(telegramRow(page, 0).chatId).toHaveValue('@channel');- await expect(telegramRow(page, 0).topicId).toHaveValue('');- await expect(telegramRow(page, 1).chatId).toHaveValue('-1001234567890');- await expect(telegramRow(page, 1).topicId).toHaveValue('42');- await expect(saveButton).toBeDisabled();-- // A second topic in the same group plus a plain chat.- await panel.getByRole('button', { name: 'Add destination' }).click();- await telegramRow(page, 2).chatId.fill(' -1001234567890 ');- await telegramRow(page, 2).topicId.fill(' 7 ');- await panel.getByRole('button', { name: 'Add destination' }).click();- await telegramRow(page, 3).chatId.fill('123456789');- await expect(saveButton).toBeEnabled();-- // The redacted bot token stays blank and does not block saving.- await expect(page.getByPlaceholder('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11')).toHaveValue(- ''- );- await saveButton.click();- await expect.poll(wasSaveEndpointCalled).toBe(true);- expect(telegramChatIds(getSavedPayloads()[0])).toEqual([- '@channel',- '-1001234567890:42',- '-1001234567890:7',- '123456789'- ]);- await expect(saveButton).toBeDisabled();-- // Saved destinations round-trip through a reload.- await page.reload();- await openProviderTab(page, 'Telegram');- await expect(telegramRow(page, 3).chatId).toHaveValue('123456789');- await expect(telegramRow(page, 2).topicId).toHaveValue('7');-- // Clearing a topic marks the form dirty and Reset restores the baseline.- await telegramRow(page, 1).topicId.fill('');- await expect(saveButton).toBeEnabled();- await page.getByRole('button', { name: 'Reset', exact: true }).click();- await expect(telegramRow(page, 1).topicId).toHaveValue('42');- await expect(saveButton).toBeDisabled();-- // Removing a row saves the remaining destinations in order.- await panel.getByRole('button', { name: 'Remove' }).nth(1).click();- await expect(telegramRow(page, 1).topicId).toHaveValue('7');- await saveButton.click();- await expect.poll(() => getSavedPayloads().length).toBe(2);- expect(telegramChatIds(getSavedPayloads()[1])).toEqual([- '@channel',- '-1001234567890:7',- '123456789'- ]);- });-- test('rejects invalid telegram destinations before saving or testing', async ({ page }) => {- const { wasSaveEndpointCalled, wasTestEndpointCalled } = await setupNotificationTest(- page,- 'telegram'- );-- await openProviderTab(page, 'Telegram');- await enableCurrentProvider(page);- await page- .getByPlaceholder('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11')- .fill('123456:TEST-TOKEN');-- const saveButton = page.getByRole('button', { name: 'Save', exact: true });- const panel = page.getByRole('tabpanel').filter({ visible: true });-- // Non-numeric and non-positive topics are rejected.- await telegramRow(page, 0).chatId.fill('-1001234567890');- await telegramRow(page, 0).topicId.fill('abc');- await expect(panel.getByText('Topic ID must be a positive whole number')).toBeVisible();- await saveButton.click();- await expect(page.getByText('Please check the form for errors').first()).toBeVisible();- expect(wasSaveEndpointCalled()).toBe(false);-- await telegramRow(page, 0).topicId.fill('0');- await expect(panel.getByText('Topic ID must be a positive whole number')).toBeVisible();-- // A topic without a chat is incomplete.- await telegramRow(page, 0).topicId.fill('5');- await telegramRow(page, 0).chatId.fill('');- await expect(panel.getByText('This field is required')).toBeVisible();-- // A colon in the chat field is not accepted as an inline topic.- await telegramRow(page, 0).chatId.fill('-1001234567890:5');- await expect(panel.getByText(/Chat ID cannot contain a colon/)).toBeVisible();-- // Save & Test is blocked while the form is invalid.- await openTestMenu(page);- await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();- await page.getByRole('button', { name: 'Save & Test', exact: true }).click();- await expect(page.getByText('Please check the form for errors').first()).toBeVisible();- expect(wasSaveEndpointCalled()).toBe(false);- expect(wasTestEndpointCalled()).toBe(false);-- // Fixing the row lets the save go through.- await telegramRow(page, 0).chatId.fill('-1001234567890');- await expect(panel.getByText(/Chat ID cannot contain a colon/)).toHaveCount(0);- await saveButton.click();- await expect.poll(wasSaveEndpointCalled).toBe(true);- });-- test('should allow testing generic webhook notifications', async ({ page }) => {- const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'generic');-- await openProviderTab(page, 'Generic');- await enableCurrentProvider(page);-- await page.getByPlaceholder('https://example.com/webhook').fill('https://example.com/webhook');-- await openTestMenu(page);- await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();-- const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });- await saveAndTestButton.click();-- await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);- getErrorCheck();- });-- test('should allow configuring a custom generic webhook payload template', async ({ page }) => {- const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'generic');-- await openProviderTab(page, 'Generic');- await enableCurrentProvider(page);-- await page.getByPlaceholder('https://example.com/webhook').fill('https://example.com/webhook');-- const template = '{"receiveIdType":"chat_id","msgType":"text","text":"{{.message}}"}';- await page.locator('#generic-payload-template').fill(template);-- await openTestMenu(page);- await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();-- const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });- await saveAndTestButton.click();-- await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);- getErrorCheck();-- // The template must survive a reload, proving it round-trips through the- // save path and back into the form.- await page.reload();- await openProviderTab(page, 'Generic');- await expect(page.locator('#generic-payload-template')).toHaveValue(template);- });-- test('should allow testing signal notifications', async ({ page }) => {- const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'signal');-- await openProviderTab(page, 'Signal');- await enableCurrentProvider(page);-- await page.getByPlaceholder('localhost').fill('signal-api.example.com');- await page.getByPlaceholder('8080').fill('8080');- await page.locator('#signal-token').fill('signal-test-token');- await page.locator('#signal-source').fill('+1234567890');- await page.locator('#signal-recipients').fill('+1987654321');-- await openTestMenu(page);- await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();-- await page.getByRole('button', { name: 'Save & Test', exact: true }).click();-- await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);- getErrorCheck();- });-- test('should allow testing ntfy notifications', async ({ page }) => {- const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'ntfy');-- await openProviderTab(page, 'Ntfy');- await enableCurrentProvider(page);-- await page.getByPlaceholder('ntfy.sh').fill('ntfy.sh');- await page.getByPlaceholder('my-updates').fill('arcane-updates');-- await openTestMenu(page);- await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();-- const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });- await saveAndTestButton.click();-- await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);- getErrorCheck();- });-});diff --git a/tests/spec/settings.spec.ts b/tests/spec/settings.spec.tsnew file mode 100644index 000000000..cd34a30e6--- /dev/null+++ b/tests/spec/settings.spec.ts@@ -0,0 +1,713 @@+import { test, expect, type Page } from '../fixtures/test.fixture';+import { createTestApiKeys, deleteTestApiKeys, waitForDialogReady } from '../utils/playwright.util';+import { fetchApiKeysWithRetry } from '../utils/fetch.util';+import { openRowActionsMenu } from '../utils/table-actions.util';++test.describe('API keys', () => {+ const API_KEYS_ROUTE = '/settings/api-keys';++ async function navigateToApiKeys(page: Page) {+ await page.goto(API_KEYS_ROUTE);+ await page.waitForLoadState('load');+ }++ test.describe('API Keys Page', () => {+ // Each test starts with its own required keys.+ test.beforeEach(async () => {+ await createTestApiKeys(3);+ });++ // Remove fixture keys before the next test.+ test.afterEach(async ({ page }) => {+ await deleteTestApiKeys();+ await expect+ .poll(+ async () =>+ (await fetchApiKeysWithRetry(page)).data.filter((key) =>+ key.name.startsWith('test-api-key-')+ ).length+ )+ .toBe(0);+ });++ test('should validate required fields when creating API key', async ({ page }) => {+ await navigateToApiKeys(page);++ await page.getByRole('button', { name: 'Create API Key' }).click();+ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();++ // Try to submit without filling required name field+ await dialog.getByRole('button', { name: 'Create API Key', exact: true }).click();++ // Should show validation error for name field+ await expect(dialog.getByText('Name is required', { exact: true })).toBeVisible();+ });++ test('should create a new API key and show the key dialog', async ({ page }) => {+ await navigateToApiKeys(page);++ await page.getByRole('button', { name: 'Create API Key' }).click();+ const createDialog = page.getByRole('dialog');+ await waitForDialogReady(createDialog);++ const apiKeyName = `test-api-key-created-${Date.now()}`;++ // Fill in the name field+ await createDialog.getByLabel('Name', { exact: true }).fill(apiKeyName);++ // Optionally fill description+ const descInput = createDialog.getByLabel('Description', { exact: true });+ await descInput.fill('E2E test API key');++ // Select at least one permission (form requires min 1)+ await createDialog+ .getByPlaceholder('Filter permissions…', { exact: true })+ .fill('containers:list');+ await createDialog.getByRole('checkbox', { name: 'Select all' }).check();++ // Submit the form+ await createDialog.getByRole('button', { name: 'Create API Key', exact: true }).click();++ // Should show success toast+ await expect(+ page+ .getByRole('region', { name: 'Notifications alt+T', exact: true })+ .getByRole('listitem')+ .first()+ ).toBeVisible({ timeout: 10000 });++ // Should show the API key reveal dialog+ await expect(page.getByText('API Key Created')).toBeVisible();+ await expect(+ page.getByText("Copy your API key now. You won't be able to see it again!", {+ exact: true+ })+ ).toBeVisible();++ // The key should be visible in a code/snippet element+ await expect(page.locator('code').first()).toBeVisible();++ // Close the dialog+ await page.getByRole('button', { name: 'Done' }).click();++ // The new key should appear in the table+ await expect(+ page.getByRole('row').filter({ has: page.getByText(apiKeyName, { exact: true }) })+ ).toBeVisible();+ });++ test('should delete an API key', async ({ page }) => {+ // First create a key to delete+ await navigateToApiKeys(page);++ await page.getByRole('button', { name: 'Create API Key' }).click();+ const createDialog = page.getByRole('dialog');++ const apiKeyName = `test-api-key-delete-${Date.now()}`;+ await createDialog.getByLabel('Name', { exact: true }).fill(apiKeyName);++ // Select at least one permission (form requires min 1)+ await createDialog+ .getByPlaceholder('Filter permissions…', { exact: true })+ .fill('containers:list');+ await createDialog.getByRole('checkbox', { name: 'Select all' }).check();++ await createDialog.getByRole('button', { name: 'Create API Key', exact: true }).click();++ // Wait for creation success and close reveal dialog+ const createdDialog = page.getByRole('dialog', { name: 'API Key Created' });+ await expect(createdDialog).toBeVisible({ timeout: 10000 });+ await createdDialog.getByRole('button', { name: 'Done' }).click();++ await expect(createdDialog).toBeHidden();++ // Now delete the key+ const keyRow = page+ .getByRole('row')+ .filter({ has: page.getByText(apiKeyName, { exact: true }) });+ await expect(keyRow).toBeVisible();++ const menu = await openRowActionsMenu(page, keyRow);+ await menu.getByRole('menuitem', { name: 'Delete' }).click();++ // Confirm deletion+ await expect(+ page.getByRole('heading', { name: `Delete API Key "${apiKeyName}"?`, exact: true })+ ).toBeVisible();+ await page.getByRole('button', { name: 'Delete' }).click();++ // Should show success toast for deletion+ await expect(+ page.getByText(`API key "${apiKeyName}" deleted successfully`, { exact: true })+ ).toBeVisible({ timeout: 10000 });++ // Key should no longer be in the table+ await expect(keyRow).toBeHidden();+ });++ test('should select multiple API keys and show bulk delete option', async ({ page }) => {+ await navigateToApiKeys(page);++ // Select first two checkboxes+ const checkboxes = page+ .getByRole('row')+ .filter({ has: page.getByRole('button', { name: 'Open menu', exact: true }) })+ .getByRole('checkbox');+ await expect(checkboxes.nth(1)).toBeVisible();++ await checkboxes.nth(0).check();+ await checkboxes.nth(1).check();++ // Remove Selected button should appear+ const removeSelectedBtn = page.getByRole('button', {+ name: 'Remove Selected (2)',+ exact: true+ });+ await expect(removeSelectedBtn).toBeVisible();++ // Click it to open confirmation+ await removeSelectedBtn.click();++ // Should show bulk delete confirmation+ await expect(+ page.getByRole('heading', { name: 'Delete 2 API Key(s)?', exact: true })+ ).toBeVisible();++ // Cancel+ await page.getByRole('button', { name: 'Cancel' }).click();+ });+ });+});++test.describe('Diagnostics', () => {+ const duplicateLogEntry = {+ time: '2026-07-25T02:00:00.000Z',+ level: 'INFO',+ message: 'duplicate diagnostic entry'+ };++ async function mockDiagnosticsLogsWebSocket(page: Page) {+ await page.routeWebSocket(/\/api\/diagnostics\/logs\/stream(?:\?.*)?$/, (socket) => {+ socket.send(JSON.stringify(duplicateLogEntry));+ socket.send(JSON.stringify(duplicateLogEntry));+ });+ }++ test.describe('Diagnostics logs', () => {+ test('renders repeated entries from the live diagnostic log stream', async ({ page }) => {+ await mockDiagnosticsLogsWebSocket(page);++ await page.goto('/settings/diagnostics?tab=logs');+ await page.waitForLoadState('domcontentloaded');++ await expect(page).toHaveURL(/\/settings\/diagnostics/);+ await expect(page.getByText('duplicate diagnostic entry', { exact: true })).toHaveCount(2);+ });+ });+});++test.describe('Notifications', () => {+ test.describe('Notification settings', () => {+ const openProviderTab = async (page: Page, name: string) => {+ const tab = page.getByRole('tab', { name });+ await tab.scrollIntoViewIfNeeded();+ await expect(tab).toBeVisible();+ await tab.click();+ await expect(page.getByRole('tabpanel').filter({ visible: true })).toBeVisible();+ };++ const enableCurrentProvider = async (page: Page) => {+ const providerPanel = page.getByRole('tabpanel').filter({ visible: true });+ const toggle = providerPanel.getByRole('switch').first();+ await expect(toggle).toBeVisible();+ await toggle.click();+ await expect(providerPanel.locator('[data-dropdown-menu-trigger]')).toBeVisible({+ timeout: 10000+ });+ };++ const openTestMenu = async (page: Page) => {+ const trigger = page+ .getByRole('tabpanel')+ .filter({ visible: true })+ .locator('[data-dropdown-menu-trigger]');+ await expect(trigger).toBeVisible({ timeout: 10000 });+ await trigger.click();+ };++ // Shared setup for all notification tests+ const setupNotificationTest = async (+ page: Page,+ provider: string,+ options: {+ failProviders?: ReadonlySet<string>;+ initialSettings?: Array<Record<string, unknown>>;+ } = {}+ ) => {+ const observedErrors: string[] = [];++ page.on('pageerror', (err) => {+ observedErrors.push(String(err?.message ?? err));+ });++ page.on('console', (msg) => {+ if (msg.type() === 'error') {+ observedErrors.push(msg.text());+ }+ });++ let saveEndpointCalled = false;+ let testEndpointCalled = false;+ const attemptedProviders: string[] = [];+ const savedProviders: string[] = [];+ // Saved settings are kept in memory and served back on GET so that a+ // reload round-trips them through the form like the real backend would.+ const persistedSettings: Array<Record<string, unknown>> = [+ ...(options.initialSettings ?? [])+ ];+ const savedPayloads: Array<Record<string, unknown>> = [];++ await page.route('**/api/environments/*/notifications/settings', async (route) => {+ const req = route.request();+ if (req.method() === 'GET') {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(persistedSettings)+ });+ return;+ }++ if (req.method() === 'POST') {+ saveEndpointCalled = true;+ const saved = req.postDataJSON() as Record<string, unknown>;+ const savedProvider = String(saved.provider ?? '');+ attemptedProviders.push(savedProvider);+ savedPayloads.push(saved);+ if (options.failProviders?.has(savedProvider)) {+ await route.fulfill({+ status: 500,+ contentType: 'application/json',+ body: JSON.stringify({ error: `${savedProvider} save failed` })+ });+ return;+ }+ savedProviders.push(savedProvider);+ const index = persistedSettings.findIndex((s) => s.provider === saved.provider);+ if (index >= 0) {+ persistedSettings[index] = saved;+ } else {+ persistedSettings.push(saved);+ }+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(saved)+ });+ return;+ }++ await route.continue();+ });++ // Stub the specific test endpoint+ await page.route(`**/api/environments/*/notifications/test/${provider}**`, async (route) => {+ testEndpointCalled = true;+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ success: true })+ });+ });++ await page.goto('/settings/notifications');+ await page.waitForLoadState('load');+ await expect(page.getByRole('tab', { name: 'Email' })).toBeVisible();++ return {+ getErrorCheck: () => {+ const stateUnsafe = observedErrors.filter((e) => e.includes('state_unsafe_mutation'));+ expect(+ stateUnsafe,+ `Unexpected state_unsafe_mutation errors: ${stateUnsafe.join('\n')}`+ ).toHaveLength(0);+ },+ wasTestEndpointCalled: () => testEndpointCalled,+ wasSaveEndpointCalled: () => saveEndpointCalled,+ getAttemptedProviders: () => [...attemptedProviders],+ getSavedProviders: () => [...savedProviders],+ getSavedPayloads: () => [...savedPayloads]+ };+ };++ const telegramSettings = (chatIds: string[]) => ({+ provider: 'telegram',+ enabled: true,+ config: {+ chatIds,+ preview: true,+ notification: true,+ title: '',+ events: {+ image_update: true,+ container_update: true,+ vulnerability_found: true,+ prune_report: true,+ auto_heal: true+ }+ }+ });++ const telegramChatIds = (payload: Record<string, unknown>) =>+ (payload.config as { chatIds: string[] }).chatIds;++ const telegramRow = (page: Page, index: number) => ({+ chatId: page.locator(`#telegram-chat-id-${index}`),+ topicId: page.locator(`#telegram-topic-id-${index}`)+ });++ test('saves only changed providers and retains failed providers as dirty', async ({ page }) => {+ const { getAttemptedProviders, getSavedProviders } = await setupNotificationTest(+ page,+ 'discord',+ {+ failProviders: new Set(['email'])+ }+ );++ await openProviderTab(page, 'Discord');+ await enableCurrentProvider(page);+ await page.getByPlaceholder('Enter webhook ID').fill('123456789');+ await page.getByPlaceholder('Enter webhook token').fill('abc-def-ghi');++ await openProviderTab(page, 'Email');+ await enableCurrentProvider(page);+ await page.getByPlaceholder('smtp.example.com').fill('smtp.example.com');+ await page.getByPlaceholder('[email protected]').fill('[email protected]');++ const saveButton = page.getByRole('button', { name: 'Save', exact: true });+ await saveButton.click();+ await expect.poll(getAttemptedProviders).toEqual(['email', 'discord']);+ await expect.poll(getSavedProviders).toEqual(['discord']);+ await expect(page.getByText(/Failed to save Email settings:/)).toBeVisible();+ await expect(saveButton).toBeEnabled();++ await saveButton.click();+ await expect.poll(getAttemptedProviders).toEqual(['email', 'discord', 'email']);+ });++ test('should persist the selected provider tab in the URL', async ({ page }) => {+ await setupNotificationTest(page, 'discord');+ await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('email');++ await openProviderTab(page, 'Discord');+ await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('discord');++ await page.reload();+ await expect(page.getByRole('tab', { name: 'Discord' })).toHaveAttribute(+ 'data-state',+ 'active'+ );+ await expect(page.getByRole('tabpanel', { name: 'Discord', exact: true })).toBeVisible();+ });++ test('should allow testing email notifications without state_unsafe_mutation errors', async ({+ page+ }) => {+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'email');++ await openProviderTab(page, 'Email');+ await enableCurrentProvider(page);++ // Fill fields+ await page.getByPlaceholder('smtp.example.com').fill('smtp.example.com');+ await page.getByPlaceholder('[email protected]').fill('[email protected]');++ // Trigger test+ await openTestMenu(page);+ await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();++ // Handle Save & Test if needed+ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });+ await saveAndTestButton.click();++ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);+ getErrorCheck();+ });++ test('should allow testing discord notifications', async ({ page }) => {+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'discord');++ await openProviderTab(page, 'Discord');+ await enableCurrentProvider(page);++ // Discord split fields+ await page.getByPlaceholder('Enter webhook ID').fill('123456789');+ await page.getByPlaceholder('Enter webhook token').fill('abc-def-ghi');++ await openTestMenu(page);+ await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();++ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });+ await saveAndTestButton.click();++ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);+ getErrorCheck();+ });++ test('should allow testing slack notifications', async ({ page }) => {+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'slack');++ await openProviderTab(page, 'Slack');+ await enableCurrentProvider(page);++ // Slack OAuth token (xoxb- or xoxp- format)+ await page+ .getByPlaceholder('xoxb-... or xoxp-...')+ .fill('xoxb-123456789012-1234567890123-abcdefghijklmnopqrstuvwx');++ await openTestMenu(page);+ await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();++ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });+ await saveAndTestButton.click();++ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);+ getErrorCheck();+ });++ test('should allow testing telegram notifications', async ({ page }) => {+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(+ page,+ 'telegram'+ );++ await openProviderTab(page, 'Telegram');+ await enableCurrentProvider(page);++ // Telegram fields (placeholders are hardcoded in component)+ await page+ .getByPlaceholder('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11')+ .fill('123456:TEST-TOKEN');+ await telegramRow(page, 0).chatId.fill('123456789');++ await openTestMenu(page);+ await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();++ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });+ await saveAndTestButton.click();++ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);+ getErrorCheck();+ });++ test('loads, edits and saves telegram topic destinations', async ({ page }) => {+ const { getSavedPayloads, wasSaveEndpointCalled } = await setupNotificationTest(+ page,+ 'telegram',+ {+ initialSettings: [telegramSettings(['@channel', '-1001234567890:42'])]+ }+ );++ await openProviderTab(page, 'Telegram');+ const saveButton = page.getByRole('button', { name: 'Save', exact: true });+ const panel = page.getByRole('tabpanel').filter({ visible: true });++ // Existing chats and chatId:topicId entries load into separate fields.+ await expect(telegramRow(page, 0).chatId).toHaveValue('@channel');+ await expect(telegramRow(page, 0).topicId).toHaveValue('');+ await expect(telegramRow(page, 1).chatId).toHaveValue('-1001234567890');+ await expect(telegramRow(page, 1).topicId).toHaveValue('42');+ await expect(saveButton).toBeDisabled();++ // A second topic in the same group plus a plain chat.+ await panel.getByRole('button', { name: 'Add destination' }).click();+ await telegramRow(page, 2).chatId.fill(' -1001234567890 ');+ await telegramRow(page, 2).topicId.fill(' 7 ');+ await panel.getByRole('button', { name: 'Add destination' }).click();+ await telegramRow(page, 3).chatId.fill('123456789');+ await expect(saveButton).toBeEnabled();++ // The redacted bot token stays blank and does not block saving.+ await expect(page.getByPlaceholder('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11')).toHaveValue(+ ''+ );+ await saveButton.click();+ await expect.poll(wasSaveEndpointCalled).toBe(true);+ expect(telegramChatIds(getSavedPayloads()[0])).toEqual([+ '@channel',+ '-1001234567890:42',+ '-1001234567890:7',+ '123456789'+ ]);+ await expect(saveButton).toBeDisabled();++ // Saved destinations round-trip through a reload.+ await page.reload();+ await openProviderTab(page, 'Telegram');+ await expect(telegramRow(page, 3).chatId).toHaveValue('123456789');+ await expect(telegramRow(page, 2).topicId).toHaveValue('7');++ // Clearing a topic marks the form dirty and Reset restores the baseline.+ await telegramRow(page, 1).topicId.fill('');+ await expect(saveButton).toBeEnabled();+ await page.getByRole('button', { name: 'Reset', exact: true }).click();+ await expect(telegramRow(page, 1).topicId).toHaveValue('42');+ await expect(saveButton).toBeDisabled();++ // Removing a row saves the remaining destinations in order.+ await panel.getByRole('button', { name: 'Remove' }).nth(1).click();+ await expect(telegramRow(page, 1).topicId).toHaveValue('7');+ await saveButton.click();+ await expect.poll(() => getSavedPayloads().length).toBe(2);+ expect(telegramChatIds(getSavedPayloads()[1])).toEqual([+ '@channel',+ '-1001234567890:7',+ '123456789'+ ]);+ });++ test('rejects invalid telegram destinations before saving or testing', async ({ page }) => {+ const { wasSaveEndpointCalled, wasTestEndpointCalled } = await setupNotificationTest(+ page,+ 'telegram'+ );++ await openProviderTab(page, 'Telegram');+ await enableCurrentProvider(page);+ await page+ .getByPlaceholder('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11')+ .fill('123456:TEST-TOKEN');++ const saveButton = page.getByRole('button', { name: 'Save', exact: true });+ const panel = page.getByRole('tabpanel').filter({ visible: true });++ // Non-numeric and non-positive topics are rejected.+ await telegramRow(page, 0).chatId.fill('-1001234567890');+ await telegramRow(page, 0).topicId.fill('abc');+ await expect(panel.getByText('Topic ID must be a positive whole number')).toBeVisible();+ await saveButton.click();+ await expect(page.getByText('Please check the form for errors').first()).toBeVisible();+ expect(wasSaveEndpointCalled()).toBe(false);++ await telegramRow(page, 0).topicId.fill('0');+ await expect(panel.getByText('Topic ID must be a positive whole number')).toBeVisible();++ // A topic without a chat is incomplete.+ await telegramRow(page, 0).topicId.fill('5');+ await telegramRow(page, 0).chatId.fill('');+ await expect(panel.getByText('This field is required')).toBeVisible();++ // A colon in the chat field is not accepted as an inline topic.+ await telegramRow(page, 0).chatId.fill('-1001234567890:5');+ await expect(panel.getByText(/Chat ID cannot contain a colon/)).toBeVisible();++ // Save & Test is blocked while the form is invalid.+ await openTestMenu(page);+ await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();+ await page.getByRole('button', { name: 'Save & Test', exact: true }).click();+ await expect(page.getByText('Please check the form for errors').first()).toBeVisible();+ expect(wasSaveEndpointCalled()).toBe(false);+ expect(wasTestEndpointCalled()).toBe(false);++ // Fixing the row lets the save go through.+ await telegramRow(page, 0).chatId.fill('-1001234567890');+ await expect(panel.getByText(/Chat ID cannot contain a colon/)).toHaveCount(0);+ await saveButton.click();+ await expect.poll(wasSaveEndpointCalled).toBe(true);+ });++ test('should allow testing generic webhook notifications', async ({ page }) => {+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'generic');++ await openProviderTab(page, 'Generic');+ await enableCurrentProvider(page);++ await page+ .getByPlaceholder('https://example.com/webhook')+ .fill('https://example.com/webhook');++ await openTestMenu(page);+ await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();++ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });+ await saveAndTestButton.click();++ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);+ getErrorCheck();+ });++ test('should allow configuring a custom generic webhook payload template', async ({ page }) => {+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'generic');++ await openProviderTab(page, 'Generic');+ await enableCurrentProvider(page);++ await page+ .getByPlaceholder('https://example.com/webhook')+ .fill('https://example.com/webhook');++ const template = '{"receiveIdType":"chat_id","msgType":"text","text":"{{.message}}"}';+ await page.locator('#generic-payload-template').fill(template);++ await openTestMenu(page);+ await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();++ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });+ await saveAndTestButton.click();++ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);+ getErrorCheck();++ // The template must survive a reload, proving it round-trips through the+ // save path and back into the form.+ await page.reload();+ await openProviderTab(page, 'Generic');+ await expect(page.locator('#generic-payload-template')).toHaveValue(template);+ });++ test('should allow testing signal notifications', async ({ page }) => {+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'signal');++ await openProviderTab(page, 'Signal');+ await enableCurrentProvider(page);++ await page.getByPlaceholder('localhost').fill('signal-api.example.com');+ await page.getByPlaceholder('8080').fill('8080');+ await page.locator('#signal-token').fill('signal-test-token');+ await page.locator('#signal-source').fill('+1234567890');+ await page.locator('#signal-recipients').fill('+1987654321');++ await openTestMenu(page);+ await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();++ await page.getByRole('button', { name: 'Save & Test', exact: true }).click();++ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);+ getErrorCheck();+ });++ test('should allow testing ntfy notifications', async ({ page }) => {+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'ntfy');++ await openProviderTab(page, 'Ntfy');+ await enableCurrentProvider(page);++ await page.getByPlaceholder('ntfy.sh').fill('ntfy.sh');+ await page.getByPlaceholder('my-updates').fill('arcane-updates');++ await openTestMenu(page);+ await page.getByRole('menuitem', { name: 'Simple', exact: true }).click();++ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });+ await saveAndTestButton.click();++ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);+ getErrorCheck();+ });+ });+});diff --git a/tests/spec/swarm-ui.spec.ts b/tests/spec/swarm-ui.spec.tsdeleted file mode 100644index 3c07d1559..000000000--- a/tests/spec/swarm-ui.spec.ts+++ /dev/null@@ -1,114 +0,0 @@-import { test, expect, type Page } from '../fixtures/test.fixture';--async function mockConfigs(page: Page) {- await page.route('**/api/environments/*/swarm/configs', async (route) => {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({- success: true,- data: []- })- });- });-}--async function mockSecrets(page: Page) {- await page.route('**/api/environments/*/swarm/secrets', async (route) => {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({- success: true,- data: []- })- });- });-}--test.describe('Swarm UI', () => {- test('cluster page renders correct lifecycle controls for current swarm state', async ({- page- }) => {- const swarmInfoResponsePromise = page.waitForResponse('**/api/environments/*/swarm/info');- await page.goto('/swarm/cluster');- await page.waitForLoadState('load');- const swarmInfoResponse = await swarmInfoResponsePromise;-- await expect(page.getByRole('heading', { name: 'Cluster', level: 1 })).toBeVisible();-- const initializeCard = page- .locator('[data-slot="card-title"]')- .filter({ hasText: 'Initialize Cluster' });- if (swarmInfoResponse.ok()) {- await expect(page.getByRole('button', { name: 'Actions' })).toBeVisible();- await expect(page.getByText('Initialize Cluster')).toHaveCount(0);- await expect(page.getByText('Join Existing Cluster')).toHaveCount(0);- await page.getByRole('button', { name: 'Actions' }).click();- await expect(page.getByText('Unlock / Leave')).toBeVisible();- await expect(page.getByRole('button', { name: 'Leave Cluster' })).toBeVisible();- } else {- await expect(initializeCard).toBeVisible();- await expect(page.getByText('Join Existing Cluster')).toBeVisible();- await expect(page.getByText('Choose how to set up this engine')).toBeVisible();- await expect(- page.locator('[data-slot="card-title"]').filter({ hasText: 'Cluster Status' })- ).toHaveCount(0);- await expect(- page.locator('[data-slot="card-title"]').filter({ hasText: 'Join Tokens' })- ).toHaveCount(0);- await expect(- page.locator('[data-slot="card-title"]').filter({ hasText: 'Update Swarm Spec' })- ).toHaveCount(0);-- const initializeRoot = initializeCard.locator('xpath=ancestor::*[@data-slot="card"]');- const joinRoot = page- .locator('[data-slot="card-title"]')- .filter({ hasText: 'Join Existing Cluster' })- .locator('xpath=ancestor::*[@data-slot="card"]');- const [initializeBox, joinBox] = await Promise.all([- initializeRoot.boundingBox(),- joinRoot.boundingBox()- ]);- expect(initializeBox?.y).toBe(joinBox?.y);- expect(initializeBox?.height).toBe(joinBox?.height);-- await expect(page.getByPlaceholder('Remote manager addrs (comma separated)')).toBeVisible();- await expect(page.getByPlaceholder('Listen address (optional)').first()).toBeHidden();- await page.getByText('Advanced settings').first().click();- await expect(page.getByPlaceholder('Listen address (optional)').first()).toBeVisible();- await expect(page.getByRole('button', { name: 'Initialize' })).toBeVisible();- await expect(page.getByRole('button', { name: 'Join' })).toBeVisible();- }- });-- test('configs page renders name/data fields and empty state', async ({ page }) => {- await mockConfigs(page);- await page.goto('/swarm/configs');- await page.waitForLoadState('load');-- await expect(page.getByRole('heading', { name: 'Configs', level: 1 })).toBeVisible();- await expect(- page.locator('[data-slot="card-title"]').filter({ hasText: 'Create Config' })- ).toBeVisible();- await expect(page.getByPlaceholder('Config name')).toBeVisible();- await expect(page.getByPlaceholder('Config data')).toBeVisible();- await expect(page.getByRole('button', { name: 'Create Config' })).toBeVisible();- await expect(page.getByText('No configs found.')).toBeVisible();- });-- test('secrets page renders name/data fields and empty state', async ({ page }) => {- await mockSecrets(page);- await page.goto('/swarm/secrets');- await page.waitForLoadState('load');-- await expect(page.getByRole('heading', { name: 'Secrets', level: 1 })).toBeVisible();- await expect(- page.locator('[data-slot="card-title"]').filter({ hasText: 'Create Secret' })- ).toBeVisible();- await expect(page.getByPlaceholder('Secret name')).toBeVisible();- await expect(page.getByPlaceholder('Secret data')).toBeVisible();- await expect(page.getByRole('button', { name: 'Create Secret' })).toBeVisible();- await expect(page.getByText('No secrets found.')).toBeVisible();- });-});diff --git a/tests/spec/swarm.spec.ts b/tests/spec/swarm.spec.tsnew file mode 100644index 000000000..0970e7cbe--- /dev/null+++ b/tests/spec/swarm.spec.ts@@ -0,0 +1,46 @@+import { test, expect } from '../fixtures/test.fixture';++test.describe('Swarm UI', () => {+ test('cluster page renders correct lifecycle controls for current swarm state', async ({+ page+ }) => {+ const swarmInfoResponsePromise = page.waitForResponse('**/api/environments/*/swarm/info');+ await page.goto('/swarm/cluster');+ await page.waitForLoadState('load');+ const swarmInfoResponse = await swarmInfoResponsePromise;++ await expect(page.getByRole('heading', { name: 'Cluster', level: 1 })).toBeVisible();++ const initializeCard = page+ .locator('[data-slot="card-title"]')+ .filter({ hasText: 'Initialize Cluster' });+ if (swarmInfoResponse.ok()) {+ await expect(page.getByRole('button', { name: 'Actions' })).toBeVisible();+ await expect(page.getByText('Initialize Cluster')).toHaveCount(0);+ await expect(page.getByText('Join Existing Cluster')).toHaveCount(0);+ await page.getByRole('button', { name: 'Actions' }).click();+ await expect(page.getByText('Unlock / Leave')).toBeVisible();+ await expect(page.getByRole('button', { name: 'Leave Cluster' })).toBeVisible();+ } else {+ await expect(initializeCard).toBeVisible();+ await expect(page.getByText('Join Existing Cluster')).toBeVisible();+ await expect(page.getByText('Choose how to set up this engine')).toBeVisible();+ await expect(+ page.locator('[data-slot="card-title"]').filter({ hasText: 'Cluster Status' })+ ).toHaveCount(0);+ await expect(+ page.locator('[data-slot="card-title"]').filter({ hasText: 'Join Tokens' })+ ).toHaveCount(0);+ await expect(+ page.locator('[data-slot="card-title"]').filter({ hasText: 'Update Swarm Spec' })+ ).toHaveCount(0);++ await expect(page.getByPlaceholder('Remote manager addrs (comma separated)')).toBeVisible();+ await expect(page.getByPlaceholder('Listen address (optional)').first()).toBeHidden();+ await page.getByText('Advanced settings').first().click();+ await expect(page.getByPlaceholder('Listen address (optional)').first()).toBeVisible();+ await expect(page.getByRole('button', { name: 'Initialize' })).toBeVisible();+ await expect(page.getByRole('button', { name: 'Join' })).toBeVisible();+ }+ });+});diff --git a/tests/spec/system-upgrade.spec.ts b/tests/spec/system-upgrade.spec.tsdeleted file mode 100644index 2e0005ab1..000000000--- a/tests/spec/system-upgrade.spec.ts+++ /dev/null@@ -1,635 +0,0 @@-import { test, expect, type Page, type Route } from '../fixtures/test.fixture';--const REFRESH_TOKEN_KEY = 'arcane_refresh_token';-const TOKEN_EXPIRY_KEY = 'arcane_token_expiry';-const REFRESH_COOKIE = 'arcane_refresh_test=complete';-const reloadCounts = new WeakMap<Page, number>();--type ManagerStatus = 'updated' | 'failed' | 'updating';-type JobStatus = 'running' | 'completed' | 'failed';--function updateAllJob(status: JobStatus, managerStatus: ManagerStatus) {- return {- id: 'playwright-update-all',- status,- results: [- {- environmentId: '0',- environmentName: 'Manager',- status: managerStatus,- ...(managerStatus === 'failed' ? { error: 'Manager update failed' } : {})- }- ],- createdAt: new Date().toISOString(),- ...(status === 'completed' || status === 'failed'- ? { completedAt: new Date().toISOString() }- : {})- };-}--function versionInfo(currentVersion: string, newestVersion = '2.0.0') {- return {- currentVersion,- displayVersion: `v${currentVersion}`,- revision: currentVersion === newestVersion ? 'new-revision' : 'old-revision',- shortRevision: currentVersion === newestVersion ? 'new-rev' : 'old-rev',- goVersion: 'go-test',- nodeVersion: 'node-test',- svelteKitVersion: 'svelte-test',- isSemverVersion: true,- newestVersion,- updateAvailable: currentVersion !== newestVersion- };-}--function dashboardSnapshot() {- const pagination = { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: 20 };- return {- containers: {- data: [],- pagination,- counts: { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 }- },- images: { data: [], pagination },- imageUsageCounts: { imagesInuse: 0, imagesUnused: 0, totalImages: 0, totalImageSize: 0 },- actionItems: { items: [] },- settings: {},- versionInfo: versionInfo('1.0.0')- };-}--function registerReloadCounter(page: Page) {- reloadCounts.set(page, 0);- page.on('domcontentloaded', () => {- reloadCounts.set(page, (reloadCounts.get(page) ?? 0) + 1);- });-}--async function registerTokenSeeding(page: Page) {- await page.addInitScript(- ({ tokenKey, expiryKey }: { tokenKey: string; expiryKey: string }) => {- if (!sessionStorage.getItem(tokenKey)) {- sessionStorage.setItem(tokenKey, 'playwright-test-refresh-token');- sessionStorage.setItem(expiryKey, new Date(Date.now() + 3_600_000).toISOString());- }- },- { tokenKey: REFRESH_TOKEN_KEY, expiryKey: TOKEN_EXPIRY_KEY }- );-}--async function fulfillJob(route: Route, status: JobStatus, managerStatus: ManagerStatus) {- await route.fulfill({- status: route.request().method() === 'POST' ? 202 : 200,- contentType: 'application/json',- body: JSON.stringify({ success: true, data: updateAllJob(status, managerStatus) })- });-}--async function openAndConfirmUpdateAll(page: Page) {- await page.getByRole('button', { name: 'Update All', exact: true }).first().click();- const dialog = page.getByRole('dialog');- await expect(dialog.getByRole('heading', { name: 'Update all environments' })).toBeVisible();- await dialog.getByRole('button', { name: 'Update All', exact: true }).click();-}--function currentReloadCount(page: Page) {- return reloadCounts.get(page) ?? 0;-}--// Huma renders errors as RFC 7807 problem documents; the dialog surfaces `detail`.-async function fulfillProblem(route: Route, status: number, detail: string) {- await route.fulfill({- status,- contentType: 'application/problem+json',- body: JSON.stringify({ title: 'Error', status, detail })- });-}--test.describe('Update All startup', () => {- const CONFLICT_DETAIL = 'an update-all job is already in progress';-- test('a failed start surfaces the API error and returns to the confirm step', async ({- page- }) => {- let statusCalls = 0;- await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {- await fulfillProblem(route, 500, 'Failed to initiate upgrade: pull access denied');- });- await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {- statusCalls++;- await fulfillJob(route, 'running', 'updating');- });-- await page.goto('/environments');- await openAndConfirmUpdateAll(page);-- const toast = page- .locator('li[data-sonner-toast]')- .filter({ hasText: 'Failed to start update all' });- await expect(toast).toBeVisible({ timeout: 10_000 });- await expect(toast).toContainText('pull access denied');-- // Back at the confirm step, ready for another attempt — and no polling started.- const dialog = page.getByRole('dialog');- await expect(dialog.getByRole('heading', { name: 'Update all environments' })).toBeVisible();- await expect(dialog.getByRole('button', { name: 'Update All', exact: true })).toBeVisible();- expect(statusCalls).toBe(0);- });-- test('a 409 conflict adopts the active job and follows it to completion', async ({ page }) => {- let startCalls = 0;- let statusCalls = 0;- await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {- startCalls++;- await fulfillProblem(route, 409, CONFLICT_DETAIL);- });- await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {- statusCalls++;- // First read (adoption) reports the job still running; the poll completes it.- if (statusCalls === 1) {- await fulfillJob(route, 'running', 'updating');- return;- }- await fulfillJob(route, 'completed', 'updated');- });-- await page.goto('/environments');- await openAndConfirmUpdateAll(page);-- const dialog = page.getByRole('dialog');- await expect(dialog.getByRole('heading', { name: 'All environments processed' })).toBeVisible({- timeout: 10_000- });- await expect(dialog.getByText('1 of 1', { exact: true })).toBeVisible();- await expect(page.locator('li[data-sonner-toast]')).toHaveCount(0);- // The conflict is never retried; the existing job is tracked instead.- expect(startCalls).toBe(1);- expect(statusCalls).toBeGreaterThanOrEqual(2);- });-- test('a 409 conflict without an active job reports the conflict and does not retry', async ({- page- }) => {- await page.clock.install();- let startCalls = 0;- let statusCalls = 0;- await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {- startCalls++;- await fulfillProblem(route, 409, CONFLICT_DETAIL);- });- await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {- statusCalls++;- // The guard tripped but the latest job is already terminal: nothing to adopt.- await fulfillJob(route, 'completed', 'updated');- });-- await page.goto('/environments');- await openAndConfirmUpdateAll(page);-- const toast = page- .locator('li[data-sonner-toast]')- .filter({ hasText: 'Failed to start update all' });- await expect(toast).toBeVisible({ timeout: 10_000 });- await expect(toast).toContainText(CONFLICT_DETAIL);-- const dialog = page.getByRole('dialog');- await expect(dialog.getByRole('heading', { name: 'Update all environments' })).toBeVisible();-- // Wait past one poll interval to prove neither polling nor a retry kicked in.- // The three status reads are the persistence-window grace, not polling.- await page.clock.runFor(4_000);- expect(startCalls).toBe(1);- expect(statusCalls).toBe(3);- });-- test('a 409 conflict adopts a job that is persisted shortly after the conflict', async ({- page- }) => {- let statusCalls = 0;- await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {- await fulfillProblem(route, 409, CONFLICT_DETAIL);- });- await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {- statusCalls++;- // The winning client's job row does not exist yet on the first read.- if (statusCalls === 1) {- await fulfillProblem(route, 404, 'no update-all job found');- return;- }- await fulfillJob(- route,- statusCalls === 2 ? 'running' : 'completed',- statusCalls === 2 ? 'updating' : 'updated'- );- });-- await page.goto('/environments');- await openAndConfirmUpdateAll(page);-- const dialog = page.getByRole('dialog');- await expect(dialog.getByRole('heading', { name: 'All environments processed' })).toBeVisible({- timeout: 10_000- });- await expect(page.locator('li[data-sonner-toast]')).toHaveCount(0);- });-- test('closing the dialog during a pending start ignores the late response', async ({ page }) => {- await page.clock.install();- let releaseStart!: () => void;- const startReleased = new Promise<void>((resolve) => {- releaseStart = resolve;- });- let statusCalls = 0;- await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {- await startReleased;- await fulfillJob(route, 'running', 'updating');- });- await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {- statusCalls++;- await fulfillJob(route, 'running', 'updating');- });-- await page.goto('/environments');- await openAndConfirmUpdateAll(page);-- const dialog = page.getByRole('dialog');- await expect(dialog.getByRole('heading', { name: 'Updating environments…' })).toBeVisible();- await dialog.getByRole('button', { name: 'Close', exact: true }).first().click();- await expect(dialog).toBeHidden();-- // The start response arrives after closure: it must not reopen or start polling.- releaseStart();- await page.clock.runFor(4_000);- await expect(dialog).toBeHidden();- expect(statusCalls).toBe(0);- await expect(page.locator('li[data-sonner-toast]')).toHaveCount(0);- });-});--test.describe('Manager self-update recovery', () => {- test('Update All keeps the manager result visible and refreshes without a document reload', async ({- page- }) => {- registerReloadCounter(page);- await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {- await fulfillJob(route, 'running', 'updating');- });- await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {- await fulfillJob(route, 'completed', 'updated');- });-- await page.goto('/environments');- await openAndConfirmUpdateAll(page);-- // The finished result stays on screen instead of the page being yanked away.- const dialog = page.getByRole('dialog');- await expect(dialog.getByRole('heading', { name: 'All environments processed' })).toBeVisible({- timeout: 10_000- });- // A hard reload here would re-run every load function while the agents are still- // reconnecting, briefly rendering the whole fleet as offline.- await expect.poll(() => currentReloadCount(page)).toBe(1);-- // Closing refreshes through SvelteKit, which reloads data but not the document.- await dialog.getByRole('button', { name: 'Close', exact: true }).first().click();- await expect(dialog).toBeHidden();- await expect.poll(() => currentReloadCount(page)).toBe(1);- await expect(page).toHaveURL('/environments');- });-- test('Update All leaves failed manager results visible without reloading', async ({ page }) => {- registerReloadCounter(page);- await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {- await fulfillJob(route, 'running', 'updating');- });- await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {- await fulfillJob(route, 'failed', 'failed');- });-- await page.goto('/environments');- await openAndConfirmUpdateAll(page);-- await expect(page.getByRole('heading', { name: 'Update all failed' })).toBeVisible({- timeout: 10_000- });- await expect(page.getByText('Manager update failed')).toBeVisible();- await expect.poll(() => currentReloadCount(page)).toBe(1);- });-- test('the single-manager flow reloads immediately after version verification', async ({- page- }) => {- registerReloadCounter(page);- const snapshot = dashboardSnapshot();- let upgradeTriggered = false;-- await page.route(/\/api\/stream(?:\?.*)?$/, async (route) => {- const channels =- new URL(route.request().url()).searchParams.get('channels')?.split(',') ?? [];- const timestamp = new Date().toISOString();- await route.fulfill({- status: 200,- contentType: 'application/x-json-stream',- body: channels.includes('dashboard')- ? `${JSON.stringify({- channel: 'dashboard',- dashboard: { type: 'snapshot', environmentId: '0', snapshot, timestamp },- timestamp- })}\n`- : ''- });- });- await page.route(/\/api\/environments\/0\/dashboard(?:\?.*)?$/, async (route) => {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({ success: true, data: snapshot })- });- });- await page.route(/\/api\/environments\/0\/system\/upgrade\/check$/, async (route) => {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({ canUpgrade: true, error: false, message: '' })- });- });- await page.route(/\/api\/environments\/0\/system\/upgrade$/, async (route) => {- upgradeTriggered = true;- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({ success: true, message: 'Upgrade started' })- });- });- await page.route(/\/api\/health$/, async (route) => {- await route.fulfill({ status: 200, body: '' });- });- await page.route(/\/api\/app-version$/, async (route) => {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify(versionInfo(upgradeTriggered ? '2.0.0' : '1.0.0'))- });- });-- const dashboardUpgradeCheck = page.waitForResponse((response) => {- return (- new URL(response.url()).pathname === '/api/environments/0/system/upgrade/check' &&- response.status() === 200- );- });- await page.goto('/dashboard');- await dashboardUpgradeCheck;- const versionBadge = page.locator('main').getByRole('button', { name: 'v1.0.0', exact: true });- await expect(versionBadge).toBeVisible();- await versionBadge.hover();- const upgradeButton = page.getByRole('button', { name: 'Update to 2.0.0', exact: true });- await expect(upgradeButton).toBeVisible();- await upgradeButton.click();- const dialog = page.getByRole('dialog');- await dialog.getByRole('button', { name: 'Update to 2.0.0', exact: true }).click();-- await expect.poll(() => currentReloadCount(page), { timeout: 10_000 }).toBe(2);- await expect(page).toHaveURL('/dashboard');- });-- test('status and activity 401s share one refresh before the upgrade reload', async ({ page }) => {- await page.clock.install();- registerReloadCounter(page);- await registerTokenSeeding(page);-- let releaseActivity!: () => void;- const activityRelease = new Promise<void>((resolve) => {- releaseActivity = resolve;- });- await page.route(/\/api\/stream(?:\?.*)?$/, async (route) => {- const channels =- new URL(route.request().url()).searchParams.get('channels')?.split(',') ?? [];- if (!channels.includes('activities')) {- await route.fulfill({- status: 200,- contentType: 'application/x-json-stream',- body: ''- });- return;- }- await activityRelease;- if (route.request().headers()['cookie']?.includes(REFRESH_COOKIE)) {- const timestamp = new Date().toISOString();- await route.fulfill({- status: 200,- contentType: 'application/x-json-stream',- body: `${JSON.stringify({- channel: 'activities',- activity: { type: 'snapshot', environmentId: '0', activities: [], timestamp },- timestamp- })}\n`- });- return;- }- await route.fulfill({- status: 401,- contentType: 'application/json',- body: JSON.stringify({ message: 'Application has been updated. Refreshing session.' })- });- });-- let refreshCalls = 0;- let releaseRefresh!: () => void;- const refreshReleased = new Promise<void>((resolve) => {- releaseRefresh = resolve;- });- await page.route(/\/api\/auth\/refresh$/, async (route) => {- refreshCalls++;- await refreshReleased;- await route.fulfill({- status: 200,- headers: {- 'content-type': 'application/json',- 'set-cookie': `${REFRESH_COOKIE}; Path=/; SameSite=Lax`- },- body: JSON.stringify({- success: true,- data: {- token: 'mocked-access-token',- refreshToken: 'mocked-refresh-token',- expiresAt: new Date(Date.now() + 3_600_000).toISOString()- }- })- });- });-- await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {- await fulfillJob(route, 'running', 'updating');- });- await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {- if (route.request().headers()['cookie']?.includes(REFRESH_COOKIE)) {- await fulfillJob(route, 'completed', 'updated');- return;- }- await route.fulfill({- status: 401,- contentType: 'application/json',- body: JSON.stringify({ message: 'Application has been updated. Refreshing session.' })- });- });-- try {- await page.goto('/environments');- const statusUnauthorized = page.waitForResponse((response) => {- return (- new URL(response.url()).pathname === '/api/environments/0/system/upgrade/all/status' &&- response.status() === 401- );- });- await openAndConfirmUpdateAll(page);- releaseActivity();- await expect.poll(() => refreshCalls).toBe(1);- await page.clock.runFor(3500);- const statusResponse = await statusUnauthorized;- await statusResponse.finished();- // Queue this after the response event so its 401 handler has joined the- // in-flight refresh before that refresh is released.- await page.evaluate(() => undefined);- expect(refreshCalls).toBe(1);- releaseRefresh();-- await expect.poll(() => currentReloadCount(page), { timeout: 15_000 }).toBe(2);- expect(refreshCalls).toBe(1);- await expect(page).toHaveURL('/environments');- } finally {- releaseActivity();- releaseRefresh();- }- });-- test('a transient refresh failure keeps the token and recovers on the next poll', async ({- page- }) => {- registerReloadCounter(page);- await registerTokenSeeding(page);-- let refreshCalls = 0;- await page.route(/\/api\/auth\/refresh$/, async (route) => {- refreshCalls++;- if (refreshCalls === 1) {- await route.abort('connectionfailed');- return;- }- await route.fulfill({- status: 200,- headers: {- 'content-type': 'application/json',- 'set-cookie': `${REFRESH_COOKIE}; Path=/; SameSite=Lax`- },- body: JSON.stringify({- success: true,- data: {- token: 'mocked-access-token',- refreshToken: 'mocked-refresh-token',- expiresAt: new Date(Date.now() + 3_600_000).toISOString()- }- })- });- });-- await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {- await fulfillJob(route, 'running', 'updating');- });- await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {- await route.fulfill({- status: 401,- contentType: 'application/json',- body: JSON.stringify({ message: 'Application has been updated. Refreshing session.' })- });- });-- await page.goto('/environments');- await openAndConfirmUpdateAll(page);-- await expect.poll(() => refreshCalls, { timeout: 10_000 }).toBe(1);- await expect- .poll(() => page.evaluate((key: string) => sessionStorage.getItem(key), REFRESH_TOKEN_KEY))- .toBe('playwright-test-refresh-token');- await expect.poll(() => currentReloadCount(page), { timeout: 15_000 }).toBe(2);- expect(refreshCalls).toBe(2);- });-- test('a rejected refresh during an upgrade redirects to login instead of polling', async ({- page- }) => {- await registerTokenSeeding(page);- let refreshCalls = 0;-- await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {- await fulfillJob(route, 'running', 'updating');- });- await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {- await route.fulfill({- status: 401,- contentType: 'application/json',- body: JSON.stringify({ message: 'Application has been updated. Refreshing session.' })- });- });-- await page.goto('/environments');- await openAndConfirmUpdateAll(page);- await page.route(/\/api\/auth\/refresh$/, async (route) => {- refreshCalls++;- await route.fulfill({- status: 401,- contentType: 'application/json',- body: JSON.stringify({ message: 'Invalid or expired refresh token' })- });- });- await page.route(/\/api\/auth\/me$/, async (route) => {- await route.fulfill({- status: 401,- contentType: 'application/json',- body: JSON.stringify({ message: 'Authentication required' })- });- });-- await page.waitForURL(/\/login(?:\?|$)/, { timeout: 10_000 });- expect(refreshCalls).toBe(1);- await expect(- page.getByRole('button', { name: 'Sign in to Arcane', exact: true })- ).toBeVisible();- });-- test('a missing refresh token during an upgrade redirects to login instead of polling', async ({- page- }) => {- let refreshCalls = 0;- await page.route(/\/api\/auth\/refresh$/, async (route) => {- refreshCalls++;- await route.continue();- });- await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {- await fulfillJob(route, 'running', 'updating');- });- await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {- await route.fulfill({- status: 401,- contentType: 'application/json',- body: JSON.stringify({ message: 'Application has been updated. Refreshing session.' })- });- });-- await page.goto('/environments');- await openAndConfirmUpdateAll(page);- await page.route(/\/api\/auth\/me$/, async (route) => {- await route.fulfill({- status: 401,- contentType: 'application/json',- body: JSON.stringify({ message: 'Authentication required' })- });- });-- await page.waitForURL(/\/login(?:\?|$)/, { timeout: 10_000 });- expect(refreshCalls).toBe(0);- await expect(- page.getByRole('button', { name: 'Sign in to Arcane', exact: true })- ).toBeVisible();- });-});diff --git a/tests/spec/system-volume-backups.spec.ts b/tests/spec/system-volume-backups.spec.tsdeleted file mode 100644index 94ea5ca89..000000000--- a/tests/spec/system-volume-backups.spec.ts+++ /dev/null@@ -1,322 +0,0 @@-import { removeApiResource } from '../utils/fetch.util';-import { expect, test, type Page } from '../fixtures/test.fixture';-import type { Activity } from '../../frontend/src/lib/types/activity.type';--type ManagementType = 'system' | 'volume';--type SystemVolumeBackupPolicy = {- id: string;- enabled: boolean;- schedule: string;- retentionCount: number;- stopContainers: boolean;- localEnabled: boolean;- s3Enabled: boolean;- selectionMode: 'all' | 'allowlist' | 'blocklist';- volumeNames: string[];- ignoreAnonymous: boolean;-};--type SystemVolumeBackupPolicyCollection = { policies: SystemVolumeBackupPolicy[] };--type HistoryEntry = {- id: string;- size: number;- createdAt: string;- status: string;- trigger: string;- destination: string;- format: string;- policyId?: string;- type: ManagementType;- resourceType: 'system' | 'volume';- resourceName: string;-};--const defaultPolicy: SystemVolumeBackupPolicy = {- id: 'volume-nightly',- enabled: false,- schedule: '0 0 2 * * *',- retentionCount: 7,- stopContainers: false,- localEnabled: true,- s3Enabled: false,- selectionMode: 'all',- volumeNames: [],- ignoreAnonymous: true-};--function paginated<T>(data: T[]) {- return {- data,- pagination: {- currentPage: 1,- totalPages: data.length > 0 ? 1 : 0,- totalItems: data.length,- itemsPerPage: 20- }- };-}--function historyEntry(resourceName: string, type: ManagementType): HistoryEntry {- return {- id: `${type}-${resourceName}`,- size: 1024,- createdAt: new Date().toISOString(),- status: 'succeeded',- trigger: type === 'system' ? 'scheduled' : 'manual',- destination: 'local',- format: 'rustic',- policyId: type === 'system' ? 'system-volume:test' : undefined,- type,- resourceType: 'volume',- resourceName- };-}--async function createVolumeViaApi(page: Page, volumeName: string) {- const response = await page.request.post('/api/environments/0/volumes', {- data: { name: volumeName, driver: 'local' }- });- expect(response.ok(), await response.text()).toBeTruthy();-}--async function removeVolumeViaApi(page: Page, volumeName: string) {- await removeApiResource(- page,- `/api/environments/0/volumes/${encodeURIComponent(volumeName)}?force=true`- );-}--async function mockSystemBackupPage(- page: Page,- collection: SystemVolumeBackupPolicyCollection,- options: { name: string; anonymous: boolean; available: boolean }[],- history: HistoryEntry[] = []-) {- let savedCollection = structuredClone(collection);- const runRequests: unknown[] = [];- const activities: Activity[] = [];- await page.route('**/api/environments/0/activities?**', (route) => {- const status = new URL(route.request().url()).searchParams.get('status');- return route.fulfill({- json: paginated(activities.filter((activity) => !status || activity.status === status))- });- });-- await page.route('**/api/backups/volumes/config', async (route) => {- if (route.request().method() === 'PUT') {- const input = (await route.request().postDataJSON()) as {- policies: SystemVolumeBackupPolicy[];- };- savedCollection = {- policies: input.policies.map((policy, index) => ({- ...policy,- id: policy.id || `volume-created-${index}`- }))- };- }- await route.fulfill({ json: savedCollection });- });- await page.route('**/api/backups/policies', async (route) => {- await route.fulfill({- json: {- policies: [- {- id: 'system-nightly',- enabled: true,- schedule: '0 0 3 * * *',- retentionCount: 7,- localEnabled: true,- s3Enabled: false- }- ],- recoveryKeyStored: true- }- });- });- await page.route('**/api/backups/volumes/options', (route) => route.fulfill({ json: options }));- await page.route('**/api/backups/volumes/run', async (route) => {- runRequests.push(await route.request().postDataJSON());- const now = new Date().toISOString();- const activity: Activity = {- id: `system-volume-run-${runRequests.length}`,- environmentId: '0',- type: 'resource_action',- status: 'running',- metadata: { action: 'run_system_volume_backups' },- startedAt: now,- createdAt: now- };- activities.push(activity);- return route.fulfill({ status: 202, json: { activityId: activity.id, status: 'running' } });- });- await page.route('**/api/backups/history**', (route) => {- const type = new URL(route.request().url()).searchParams.get('type');- const rows =- type === 'system' || type === 'volume' ? history.filter((row) => row.type === type) : history;- return route.fulfill({ json: paginated(rows) });- });-- return {- savedCollection: () => savedCollection,- runRequests: () => runRequests,- completeRun: () => {- const activity = activities.at(-1);- if (!activity) throw new Error('No backup run was accepted');- activity.status = 'success';- activity.endedAt = new Date().toISOString();- activity.metadata = {- ...activity.metadata,- matched: 2,- succeeded: 1,- failed: 0,- skipped: 1,- failures: []- };- history.push({- ...historyEntry('completed-batch-volume', 'system'),- id: activity.id,- trigger: 'manual'- });- }- };-}--test.describe('System-managed volume backups', () => {- test('creates multiple volume schedules and runs a saved schedule', async ({ page }) => {- const liveName = `e2e-live-volume-${Date.now()}`;- const anonymousName = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';- const unavailableName = 'deleted-volume';- const mock = await mockSystemBackupPage(- page,- {- policies: [- {- ...defaultPolicy,- enabled: false,- selectionMode: 'allowlist',- volumeNames: [unavailableName]- }- ]- },- [- { name: liveName, anonymous: false, available: true },- { name: anonymousName, anonymous: true, available: true },- { name: unavailableName, anonymous: false, available: false }- ]- );-- await page.goto('/settings/backups');- const systemCard = page.getByTestId('backup-policy-system-system-nightly');- const volumeCard = page.getByTestId('backup-policy-volume-volume-nightly');- await expect(systemCard.getByText('System')).toHaveClass(/(^|\s)text-purple(\s|$)/);- await expect(volumeCard.getByText('Volume')).toHaveClass(/(^|\s)text-purple(\s|$)/);- await volumeCard.getByRole('button', { name: 'Edit Schedule' }).click();- const dialog = page.getByRole('dialog', { name: 'Edit Schedule' });-- await expect(dialog.getByText(unavailableName)).toBeVisible();- await expect(dialog.getByText('Unavailable', { exact: true })).toBeVisible();- await expect(dialog.getByText('Anonymous', { exact: true })).toBeVisible();- await dialog.getByLabel('Volume selection').click();- await page.getByRole('option', { name: 'Blocklist' }).click();- await expect(dialog.getByLabel('Volume selection')).toContainText('Blocklist');- await expect(dialog.getByText('Excluded volumes')).toBeVisible();- await dialog.locator('label').filter({ hasText: liveName }).getByRole('checkbox').click();- await dialog.getByRole('button', { name: 'Save' }).click();- await expect(dialog).toBeHidden();- expect(mock.savedCollection().policies[0]?.volumeNames).toEqual([unavailableName, liveName]);-- await page.getByRole('button', { name: 'Create', exact: true }).click();- await page.getByRole('menuitem', { name: 'Schedule' }).click();- const createSchedule = page.getByRole('dialog', { name: 'Create schedule' });- await createSchedule.getByLabel('Backup type').click();- await page.getByRole('option', { name: 'Volume' }).click();- await createSchedule.getByLabel('Schedule', { exact: true }).fill('0 30 4 * * *');- await createSchedule.getByRole('button', { name: 'Save' }).click();- await expect(createSchedule).toBeHidden();- expect(mock.savedCollection().policies).toHaveLength(2);- await expect(page.getByText('Volume', { exact: true })).toHaveCount(2);-- await page.getByRole('button', { name: 'Create', exact: true }).click();- await page.getByRole('menuitem', { name: 'Backup' }).click();- const createBackup = page.getByRole('dialog', { name: 'Create Backup' });- const runningBackup = page.getByRole('alert').filter({ hasText: 'Backup in progress' });- await createBackup.getByLabel('Backup type').click();- await page.getByRole('option', { name: 'Volume' }).click();- await createBackup.getByLabel('Backup configuration').click();- await page.getByRole('option', { name: '0 0 2 * * *' }).click();- await createBackup.getByRole('button', { name: 'Create Backup' }).click();- await expect(createBackup).toBeHidden();- await expect(page.getByText('Backup started', { exact: true })).toBeVisible();- await expect(runningBackup).toBeVisible();- await page.getByRole('button', { name: 'Create', exact: true }).click();- await expect(page.getByRole('menuitem', { name: 'Backup', exact: true })).toBeDisabled();- await page.keyboard.press('Escape');- await page.reload();- await expect(runningBackup).toBeVisible();- mock.completeRun();- await expect(runningBackup).toBeHidden({- timeout: 15000- });- await expect(page.getByRole('table').getByText('completed-batch-volume')).toBeVisible();- expect(mock.runRequests()).toContainEqual({ policyId: 'volume-nightly' });-- await page.getByRole('button', { name: 'Create', exact: true }).click();- await page.getByRole('menuitem', { name: 'Backup' }).click();- const customBackup = page.getByRole('dialog', { name: 'Create Backup' });- await customBackup.getByLabel('Backup type').click();- await page.getByRole('option', { name: 'Volume' }).click();- await customBackup.getByLabel('Volume selection').click();- await page.getByRole('option', { name: 'Allowlist' }).click();- await customBackup.locator('label').filter({ hasText: liveName }).getByRole('checkbox').click();- await customBackup.getByRole('button', { name: 'Create Backup' }).click();- await expect(customBackup).toBeHidden();- await expect(runningBackup).toBeVisible();- expect(mock.runRequests()).toContainEqual({- custom: {- destination: 'local',- s3DestinationId: '',- stopContainers: false,- selectionMode: 'allowlist',- volumeNames: [liveName],- ignoreAnonymous: true- }- });- });-- test('filters unified history and opens the owning volume backup tab', async ({ page }) => {- const volumeName = `e2e-system-history-${Date.now()}`;- await createVolumeViaApi(page, volumeName);- try {- await mockSystemBackupPage(- page,- { policies: [] },- [],- [historyEntry('central-volume', 'system'), historyEntry(volumeName, 'volume')]- );- await page.goto('/settings/backups');-- await page.getByTestId('facet-type-trigger').click();- await page.getByTestId('facet-type-option-system').click();- const historyTable = page.getByRole('table');- await expect(historyTable.getByText('central-volume')).toBeVisible();- await expect(historyTable.getByText(volumeName)).toHaveCount(0);-- await page.getByTestId('facet-type-option-system').click();- await page.getByTestId('facet-type-option-volume').click();- await expect(historyTable.getByText(volumeName)).toBeVisible();- await expect(historyTable.getByText('central-volume')).toHaveCount(0);-- await page.keyboard.press('Escape');- const row = page.getByRole('row').filter({ hasText: volumeName });- await row.getByRole('button', { name: 'Open menu' }).click();- await page.getByRole('menuitem', { name: 'Open volume backups' }).click();- await expect(page).toHaveURL(- new RegExp(`/volumes/${encodeURIComponent(volumeName)}\\?tab=backups`)- );- } finally {- await removeVolumeViaApi(page, volumeName);- }- });-});diff --git a/tests/spec/updates.spec.ts b/tests/spec/updates.spec.tsindex ad6c31abc..150e2950d 100644--- a/tests/spec/updates.spec.ts+++ b/tests/spec/updates.spec.ts@@ -1,355 +1,1010 @@import { test, expect, type Page, type Route } from '../fixtures/test.fixture';import { openRowActionsMenu } from '../utils/table-actions.util';-const UPDATES_ROUTE = '/updates';-const CONTAINER_UPDATE_ROUTE = /\/api\/environments\/0\/containers\/[^/]+\/update\?async=true$/;-const CONTAINER_LIST_ROUTE = /\/api\/environments\/0\/containers(?:\?.*)?$/;--const CONTAINERS = [- {- id: 'update-row-a',- name: 'updates-alpha',- image: 'public.ecr.aws/docker/library/alpine:3.20',- ignored: false- },- {- id: 'update-row-b',- name: 'updates-beta',- image: 'public.ecr.aws/docker/library/busybox:1.37',- ignored: false- },- {- // Excluded from auto-update (`autoUpdateEnabled: false`): automatic runs- // skip it, but a user may still update it explicitly (#4123).- id: 'update-row-c',- name: 'updates-gamma',- image: 'public.ecr.aws/docker/library/nginx:1.27',- ignored: true- }-];-const IGNORED_CONTAINER = CONTAINERS.find((container) => container.ignored)!;--function containerWithUpdate(container: (typeof CONTAINERS)[number]) {- return {- id: container.id,- names: [`/${container.name}`],- image: container.image,- imageId: `sha256:${container.id}`,- command: 'sleep',- created: 1_700_000_000,- labels: {},- autoUpdateEnabled: !container.ignored,- state: 'running',- status: 'Up 2 hours',- ports: [],- hostConfig: { networkMode: 'bridge' },- networkSettings: { networks: {} },- mounts: [],- updateInfo: {- hasUpdate: true,- updateType: 'digest',- currentVersion: '1.0',- latestVersion: '1.0',- currentDigest: 'sha256:aaa',- latestDigest: 'sha256:bbb',- checkTime: new Date().toISOString(),- responseTimeMs: 12+test.describe('Container updates', () => {+ const UPDATES_ROUTE = '/updates';+ const CONTAINER_UPDATE_ROUTE = /\/api\/environments\/0\/containers\/[^/]+\/update\?async=true$/;+ const CONTAINER_LIST_ROUTE = /\/api\/environments\/0\/containers(?:\?.*)?$/;++ const CONTAINERS = [+ {+ id: 'update-row-a',+ name: 'updates-alpha',+ image: 'public.ecr.aws/docker/library/alpine:3.20',+ ignored: false+ },+ {+ id: 'update-row-b',+ name: 'updates-beta',+ image: 'public.ecr.aws/docker/library/busybox:1.37',+ ignored: false+ },+ {+ // Excluded from auto-update (`autoUpdateEnabled: false`): automatic runs+ // skip it, but a user may still update it explicitly (#4123).+ id: 'update-row-c',+ name: 'updates-gamma',+ image: 'public.ecr.aws/docker/library/nginx:1.27',+ ignored: true}+ ];+ const IGNORED_CONTAINER = CONTAINERS.find((container) => container.ignored)!;++ function containerWithUpdate(container: (typeof CONTAINERS)[number]) {+ return {+ id: container.id,+ names: [`/${container.name}`],+ image: container.image,+ imageId: `sha256:${container.id}`,+ command: 'sleep',+ created: 1_700_000_000,+ labels: {},+ autoUpdateEnabled: !container.ignored,+ state: 'running',+ status: 'Up 2 hours',+ ports: [],+ hostConfig: { networkMode: 'bridge' },+ networkSettings: { networks: {} },+ mounts: [],+ updateInfo: {+ hasUpdate: true,+ updateType: 'digest',+ currentVersion: '1.0',+ latestVersion: '1.0',+ currentDigest: 'sha256:aaa',+ latestDigest: 'sha256:bbb',+ checkTime: new Date().toISOString(),+ responseTimeMs: 12+ }+ };+ }++ const TAG_UPDATE_PROJECT = {+ id: 'update-project-tag',+ name: 'updates-tag-project',+ imageRef: 'public.ecr.aws/docker/library/redis:7'};-}--const TAG_UPDATE_PROJECT = {- id: 'update-project-tag',- name: 'updates-tag-project',- imageRef: 'public.ecr.aws/docker/library/redis:7'-};--/** Serves one project whose tag moved to a new version while the tag's digest stayed the same. */-async function stubProjectWithTagUpdate(page: Page) {- const checkTime = new Date().toISOString();- await page.route(/\/api\/environments\/0\/projects(?:\?.*)?$/, async (route) => {- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({- success: true,- data: [- {- id: TAG_UPDATE_PROJECT.id,- name: TAG_UPDATE_PROJECT.name,- path: `/projects/${TAG_UPDATE_PROJECT.name}`,- status: 'running',- runningCount: '1',- serviceCount: '1',- createdAt: checkTime,- updatedAt: checkTime,- updateInfo: {- status: 'has_update',- hasUpdate: true,- imageCount: 1,- checkedImageCount: 1,- imagesWithUpdates: 1,- imagesNotPulled: 0,- errorCount: 0,- imageRefs: [TAG_UPDATE_PROJECT.imageRef],- updatedImageRefs: [TAG_UPDATE_PROJECT.imageRef],- updateInfoByRef: {- [TAG_UPDATE_PROJECT.imageRef]: {- hasUpdate: true,- updateType: 'tag',- currentVersion: '7.2.4',- latestVersion: '7.4.1',- currentDigest: 'sha256:same-digest',- latestDigest: 'sha256:same-digest',- checkTime,- responseTimeMs: 12,- error: ''- }- },- lastCheckedAt: checkTime++ /** Serves one project whose tag moved to a new version while the tag's digest stayed the same. */+ async function stubProjectWithTagUpdate(page: Page) {+ const checkTime = new Date().toISOString();+ await page.route(/\/api\/environments\/0\/projects(?:\?.*)?$/, async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: [+ {+ id: TAG_UPDATE_PROJECT.id,+ name: TAG_UPDATE_PROJECT.name,+ path: `/projects/${TAG_UPDATE_PROJECT.name}`,+ status: 'running',+ runningCount: '1',+ serviceCount: '1',+ createdAt: checkTime,+ updatedAt: checkTime,+ updateInfo: {+ status: 'has_update',+ hasUpdate: true,+ imageCount: 1,+ checkedImageCount: 1,+ imagesWithUpdates: 1,+ imagesNotPulled: 0,+ errorCount: 0,+ imageRefs: [TAG_UPDATE_PROJECT.imageRef],+ updatedImageRefs: [TAG_UPDATE_PROJECT.imageRef],+ updateInfoByRef: {+ [TAG_UPDATE_PROJECT.imageRef]: {+ hasUpdate: true,+ updateType: 'tag',+ currentVersion: '7.2.4',+ latestVersion: '7.4.1',+ currentDigest: 'sha256:same-digest',+ latestDigest: 'sha256:same-digest',+ checkTime,+ responseTimeMs: 12,+ error: ''+ }+ },+ lastCheckedAt: checkTime+ }}- }- ],- pagination: { totalItems: 1, totalPages: 1, currentPage: 1, itemsPerPage: 20 }- })+ ],+ pagination: { totalItems: 1, totalPages: 1, currentPage: 1, itemsPerPage: 20 }+ })+ });});- });-}+ }-/** Serves the update-pending containers so the tab always has selectable rows; returns the number of list fetches so far. */-async function stubContainersWithUpdates(page: Page) {- const fetches = { count: 0 };- await page.route(CONTAINER_LIST_ROUTE, async (route) => {- fetches.count++;- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({- success: true,- data: CONTAINERS.map(containerWithUpdate),- pagination: {- totalItems: CONTAINERS.length,- totalPages: 1,- currentPage: 1,- itemsPerPage: 100- }- })+ /** Serves the update-pending containers so the tab always has selectable rows; returns the number of list fetches so far. */+ async function stubContainersWithUpdates(page: Page) {+ const fetches = { count: 0 };+ await page.route(CONTAINER_LIST_ROUTE, async (route) => {+ fetches.count++;+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: CONTAINERS.map(containerWithUpdate),+ pagination: {+ totalItems: CONTAINERS.length,+ totalPages: 1,+ currentPage: 1,+ itemsPerPage: 100+ }+ })+ });});- });- return fetches;-}--type ContainerUpdateOutcome =- | { kind: 'updated' }- | { kind: 'skipped'; reason: string }- | { kind: 'failed'; error: string }- | { kind: 'request-error'; error: string };--/** Answers `POST .../containers/{id}/update` per container and records which ids were requested. */-async function stubContainerUpdates(page: Page, outcomes: Record<string, ContainerUpdateOutcome>) {- const requested: string[] = [];- await page.route(CONTAINER_UPDATE_ROUTE, async (route: Route) => {- const containerId = new URL(route.request().url()).pathname.split('/').at(-2)!;- requested.push(containerId);- const outcome = outcomes[containerId] ?? { kind: 'updated' };- if (outcome.kind === 'request-error') {+ return fetches;+ }++ type ContainerUpdateOutcome =+ | { kind: 'updated' }+ | { kind: 'skipped'; reason: string }+ | { kind: 'failed'; error: string }+ | { kind: 'request-error'; error: string };++ /** Answers `POST .../containers/{id}/update` per container and records which ids were requested. */+ async function stubContainerUpdates(+ page: Page,+ outcomes: Record<string, ContainerUpdateOutcome>+ ) {+ const requested: string[] = [];+ await page.route(CONTAINER_UPDATE_ROUTE, async (route: Route) => {+ const containerId = new URL(route.request().url()).pathname.split('/').at(-2)!;+ requested.push(containerId);+ const outcome = outcomes[containerId] ?? { kind: 'updated' };+ if (outcome.kind === 'request-error') {+ await route.fulfill({+ status: 500,+ contentType: 'application/json',+ json: { success: false, error: outcome.error }+ });+ return;+ }+ const container = CONTAINERS.find((candidate) => candidate.id === containerId)!;+ const now = new Date().toISOString();+ const data = {+ id: `update-activity-${requested.length}`,+ environmentId: '0',+ sourceEnvironmentId: '0',+ type: 'auto_update',+ status: 'queued',+ resourceType: 'container',+ resourceId: containerId,+ resourceName: container.name,+ createdAt: now,+ startedAt: now+ };await route.fulfill({- status: 500,+ status: 202,contentType: 'application/json',- json: { success: false, error: outcome.error }+ json: { success: true, data }});- return;- }- const container = CONTAINERS.find((candidate) => candidate.id === containerId)!;- const now = new Date().toISOString();- const data = {- id: `update-activity-${requested.length}`,- environmentId: '0',- sourceEnvironmentId: '0',- type: 'auto_update',- status: 'queued',- resourceType: 'container',- resourceId: containerId,- resourceName: container.name,- createdAt: now,- startedAt: now- };- await route.fulfill({- status: 202,- contentType: 'application/json',- json: { success: true, data }});- });- return requested;-}+ return requested;+ }-function containerRow(page: Page, container: (typeof CONTAINERS)[number]) {- return page.getByRole('row').filter({ hasText: container.name });-}+ function containerRow(page: Page, container: (typeof CONTAINERS)[number]) {+ return page.getByRole('row').filter({ hasText: container.name });+ }-async function selectAllContainerRows(page: Page) {- for (const container of CONTAINERS) {- await containerRow(page, container).getByRole('checkbox', { name: 'Select row' }).check();+ async function selectAllContainerRows(page: Page) {+ for (const container of CONTAINERS) {+ await containerRow(page, container).getByRole('checkbox', { name: 'Select row' }).check();+ }}-}--async function confirmBulkUpdate(page: Page) {- await page.getByRole('button', { name: `Update (${CONTAINERS.length})`, exact: true }).click();- const dialog = page.getByRole('dialog');- await expect(dialog).toBeVisible();- await dialog.getByRole('button', { name: 'Update', exact: true }).click();-}--/** Runs the row-level "Update Container" action for one container through its confirm dialog. */-async function updateContainerFromRow(page: Page, container: (typeof CONTAINERS)[number]) {- const menu = await openRowActionsMenu(page, containerRow(page, container));- await menu.getByRole('menuitem', { name: 'Update Container', exact: true }).click();- const dialog = page.getByRole('dialog');- await expect(dialog).toBeVisible();- await dialog.getByRole('button', { name: 'Update Container', exact: true }).click();-}--test.describe('Updates Page Project Rows', () => {- test('shows the versions behind a tag update even when the digest is unchanged', async ({- page- }) => {- await stubContainersWithUpdates(page);- await stubProjectWithTagUpdate(page);-- await page.goto(`${UPDATES_ROUTE}?tab=projects`);- await page.waitForLoadState('load');-- const row = page.getByRole('row').filter({ hasText: TAG_UPDATE_PROJECT.name });- await expect(row.getByText('7.2.4', { exact: true })).toBeVisible();- await expect(row.getByText('7.4.1', { exact: true })).toBeVisible();- await expect(row.getByText('sha256:same-digest')).toHaveCount(0);++ async function confirmBulkUpdate(page: Page) {+ await page.getByRole('button', { name: `Update (${CONTAINERS.length})`, exact: true }).click();+ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();+ await dialog.getByRole('button', { name: 'Update', exact: true }).click();+ }++ /** Runs the row-level "Update Container" action for one container through its confirm dialog. */+ async function updateContainerFromRow(page: Page, container: (typeof CONTAINERS)[number]) {+ const menu = await openRowActionsMenu(page, containerRow(page, container));+ await menu.getByRole('menuitem', { name: 'Update Container', exact: true }).click();+ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();+ await dialog.getByRole('button', { name: 'Update Container', exact: true }).click();+ }++ test.describe('Updates Page Project Rows', () => {+ test('shows the versions behind a tag update even when the digest is unchanged', async ({+ page+ }) => {+ await stubContainersWithUpdates(page);+ await stubProjectWithTagUpdate(page);++ await page.goto(`${UPDATES_ROUTE}?tab=projects`);+ await page.waitForLoadState('load');++ const row = page.getByRole('row').filter({ hasText: TAG_UPDATE_PROJECT.name });+ await expect(row.getByText('7.2.4', { exact: true })).toBeVisible();+ await expect(row.getByText('7.4.1', { exact: true })).toBeVisible();+ await expect(row.getByText('sha256:same-digest')).toHaveCount(0);+ });});-});-test.describe('Updates Page Actions', () => {- test('accepts updates for the selected container rows, including one with automatic updates disabled', async ({- page- }) => {- await stubContainersWithUpdates(page);- const requested = await stubContainerUpdates(page, {});-- await page.goto(UPDATES_ROUTE);- await page.waitForLoadState('load');- await expect(- containerRow(page, IGNORED_CONTAINER).getByText('Automatic updates disabled', { exact: true })- ).toBeVisible();-- await selectAllContainerRows(page);- await confirmBulkUpdate(page);-- await expect(- page.getByText(`Started updates for ${CONTAINERS.length} container(s)`)- ).toBeVisible({- timeout: 15_000+ test.describe('Updates Page Actions', () => {+ test('accepts updates for the selected container rows, including one with automatic updates disabled', async ({+ page+ }) => {+ await stubContainersWithUpdates(page);+ const requested = await stubContainerUpdates(page, {});++ await page.goto(UPDATES_ROUTE);+ await page.waitForLoadState('load');+ await expect(+ containerRow(page, IGNORED_CONTAINER).getByText('Automatic updates disabled', {+ exact: true+ })+ ).toBeVisible();++ await selectAllContainerRows(page);+ await confirmBulkUpdate(page);++ await expect(+ page.getByText(`Started updates for ${CONTAINERS.length} container(s)`)+ ).toBeVisible({+ timeout: 15_000+ });+ expect(requested.sort()).toEqual(CONTAINERS.map((c) => c.id).sort());+ for (const container of CONTAINERS) {+ await expect(+ containerRow(page, container).getByRole('checkbox', { name: 'Select row' })+ ).not.toBeChecked();+ }});- expect(requested.sort()).toEqual(CONTAINERS.map((c) => c.id).sort());- for (const container of CONTAINERS) {++ test('counts submission failures separately from later update outcomes', async ({ page }) => {+ await stubContainersWithUpdates(page);+ const [alpha, beta] = CONTAINERS;+ const requested = await stubContainerUpdates(page, {+ [beta.id]: { kind: 'failed', error: 'pull failed: registry unreachable' },+ [IGNORED_CONTAINER.id]: { kind: 'request-error', error: 'executor unavailable' }+ });++ await page.goto(UPDATES_ROUTE);+ await page.waitForLoadState('load');++ await selectAllContainerRows(page);+ await confirmBulkUpdate(page);+await expect(- containerRow(page, container).getByRole('checkbox', { name: 'Select row' })- ).not.toBeChecked();- }- });+ page.getByText(`Started 2 of ${CONTAINERS.length} container update(s). 1 could not start.`)+ ).toBeVisible({+ timeout: 15_000+ });+ await expect(page.getByText(`Updated ${CONTAINERS.length} resource(s)`)).toHaveCount(0);+ expect(requested.sort()).toEqual([alpha.id, beta.id, IGNORED_CONTAINER.id].sort());+ });++ test('row update acknowledges acceptance and reports submission errors', async ({ page }) => {+ await stubContainersWithUpdates(page);+ const outcomes: Record<string, ContainerUpdateOutcome> = {+ [IGNORED_CONTAINER.id]: { kind: 'skipped', reason: 'immutable image reference' }+ };+ const requested = await stubContainerUpdates(page, outcomes);- test('counts submission failures separately from later update outcomes', async ({ page }) => {- await stubContainersWithUpdates(page);- const [alpha, beta] = CONTAINERS;- const requested = await stubContainerUpdates(page, {- [beta.id]: { kind: 'failed', error: 'pull failed: registry unreachable' },- [IGNORED_CONTAINER.id]: { kind: 'request-error', error: 'executor unavailable' }+ await page.goto(UPDATES_ROUTE);+ await page.waitForLoadState('load');++ await updateContainerFromRow(page, IGNORED_CONTAINER);+ await expect(+ page.getByText(`Update started for container "${IGNORED_CONTAINER.name}"`)+ ).toBeVisible({+ timeout: 15_000+ });+ await expect(page.getByText('immutable image reference')).toHaveCount(0);+ await expect(page.getByText('Up to Date')).toHaveCount(0);+ expect(requested).toEqual([IGNORED_CONTAINER.id]);++ outcomes[IGNORED_CONTAINER.id] = {+ kind: 'request-error',+ error: 'pull failed: registry unreachable'+ };+ await updateContainerFromRow(page, IGNORED_CONTAINER);+ await expect(+ page.getByText(+ `Could not confirm the update request for container "${IGNORED_CONTAINER.name}"`+ )+ ).toBeVisible({+ timeout: 15_000+ });+ await expect(page.getByText('pull failed: registry unreachable')).toBeVisible();+ expect(requested).toEqual([IGNORED_CONTAINER.id, IGNORED_CONTAINER.id]);++ // The action is usable again after both outcomes: loading state was cleared.+ const menu = await openRowActionsMenu(page, containerRow(page, IGNORED_CONTAINER));+ await expect(+ menu.getByRole('menuitem', { name: 'Update Container', exact: true })+ ).toBeEnabled();+ await page.keyboard.press('Escape');});- await page.goto(UPDATES_ROUTE);- await page.waitForLoadState('load');+ test('Update All confirms before dispatching a host-wide updater run', async ({ page }) => {+ await stubContainersWithUpdates(page);++ let runs = 0;+ await page.route(/\/api\/environments\/0\/updater\/run$/, async (route) => {+ runs++;+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: { checked: 2, updated: 2, skipped: 0, failed: 0, items: [], duration: '2s' }+ })+ });+ });++ await page.goto(UPDATES_ROUTE);+ await page.waitForLoadState('load');++ await page.getByRole('button', { name: 'Update All', exact: true }).click();++ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();+ await expect(dialog.getByText(/every pending update on this host/i)).toBeVisible();+ expect(runs).toBe(0);- await selectAllContainerRows(page);- await confirmBulkUpdate(page);+ await dialog.getByRole('button', { name: 'Update All', exact: true }).click();- await expect(- page.getByText(`Started 2 of ${CONTAINERS.length} container update(s). 1 could not start.`)- ).toBeVisible({- timeout: 15_000+ await expect(page.getByText('Applied 2 update(s)')).toBeVisible({ timeout: 15_000 });+ expect(runs).toBe(1);});- await expect(page.getByText(`Updated ${CONTAINERS.length} resource(s)`)).toHaveCount(0);- expect(requested.sort()).toEqual([alpha.id, beta.id, IGNORED_CONTAINER.id].sort());});+});- test('row update acknowledges acceptance and reports submission errors', async ({ page }) => {- await stubContainersWithUpdates(page);- const outcomes: Record<string, ContainerUpdateOutcome> = {- [IGNORED_CONTAINER.id]: { kind: 'skipped', reason: 'immutable image reference' }+test.describe('Arcane upgrades', () => {+ const REFRESH_TOKEN_KEY = 'arcane_refresh_token';+ const TOKEN_EXPIRY_KEY = 'arcane_token_expiry';+ const REFRESH_COOKIE = 'arcane_refresh_test=complete';+ const reloadCounts = new WeakMap<Page, number>();++ type ManagerStatus = 'updated' | 'failed' | 'updating';+ type JobStatus = 'running' | 'completed' | 'failed';++ function updateAllJob(status: JobStatus, managerStatus: ManagerStatus) {+ return {+ id: 'playwright-update-all',+ status,+ results: [+ {+ environmentId: '0',+ environmentName: 'Manager',+ status: managerStatus,+ ...(managerStatus === 'failed' ? { error: 'Manager update failed' } : {})+ }+ ],+ createdAt: new Date().toISOString(),+ ...(status === 'completed' || status === 'failed'+ ? { completedAt: new Date().toISOString() }+ : {})};- const requested = await stubContainerUpdates(page, outcomes);+ }- await page.goto(UPDATES_ROUTE);- await page.waitForLoadState('load');+ function versionInfo(currentVersion: string, newestVersion = '2.0.0') {+ return {+ currentVersion,+ displayVersion: `v${currentVersion}`,+ revision: currentVersion === newestVersion ? 'new-revision' : 'old-revision',+ shortRevision: currentVersion === newestVersion ? 'new-rev' : 'old-rev',+ goVersion: 'go-test',+ nodeVersion: 'node-test',+ svelteKitVersion: 'svelte-test',+ isSemverVersion: true,+ newestVersion,+ updateAvailable: currentVersion !== newestVersion+ };+ }++ function dashboardSnapshot() {+ const pagination = { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: 20 };+ return {+ containers: {+ data: [],+ pagination,+ counts: { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 }+ },+ images: { data: [], pagination },+ imageUsageCounts: { imagesInuse: 0, imagesUnused: 0, totalImages: 0, totalImageSize: 0 },+ actionItems: { items: [] },+ settings: {},+ versionInfo: versionInfo('1.0.0')+ };+ }- await updateContainerFromRow(page, IGNORED_CONTAINER);- await expect(- page.getByText(`Update started for container "${IGNORED_CONTAINER.name}"`)- ).toBeVisible({- timeout: 15_000+ function registerReloadCounter(page: Page) {+ reloadCounts.set(page, 0);+ page.on('domcontentloaded', () => {+ reloadCounts.set(page, (reloadCounts.get(page) ?? 0) + 1);});- await expect(page.getByText('immutable image reference')).toHaveCount(0);- await expect(page.getByText('Up to Date')).toHaveCount(0);- expect(requested).toEqual([IGNORED_CONTAINER.id]);+ }- outcomes[IGNORED_CONTAINER.id] = {- kind: 'request-error',- error: 'pull failed: registry unreachable'- };- await updateContainerFromRow(page, IGNORED_CONTAINER);- await expect(- page.getByText(- `Could not confirm the update request for container "${IGNORED_CONTAINER.name}"`- )- ).toBeVisible({- timeout: 15_000+ async function registerTokenSeeding(page: Page) {+ await page.addInitScript(+ ({ tokenKey, expiryKey }: { tokenKey: string; expiryKey: string }) => {+ if (!sessionStorage.getItem(tokenKey)) {+ sessionStorage.setItem(tokenKey, 'playwright-test-refresh-token');+ sessionStorage.setItem(expiryKey, new Date(Date.now() + 3_600_000).toISOString());+ }+ },+ { tokenKey: REFRESH_TOKEN_KEY, expiryKey: TOKEN_EXPIRY_KEY }+ );+ }++ async function fulfillJob(route: Route, status: JobStatus, managerStatus: ManagerStatus) {+ await route.fulfill({+ status: route.request().method() === 'POST' ? 202 : 200,+ contentType: 'application/json',+ body: JSON.stringify({ success: true, data: updateAllJob(status, managerStatus) })+ });+ }++ async function openAndConfirmUpdateAll(page: Page) {+ await page.getByRole('button', { name: 'Update All', exact: true }).first().click();+ const dialog = page.getByRole('dialog');+ await expect(dialog.getByRole('heading', { name: 'Update all environments' })).toBeVisible();+ await dialog.getByRole('button', { name: 'Update All', exact: true }).click();+ }++ function currentReloadCount(page: Page) {+ return reloadCounts.get(page) ?? 0;+ }++ // Huma renders errors as RFC 7807 problem documents; the dialog surfaces `detail`.+ async function fulfillProblem(route: Route, status: number, detail: string) {+ await route.fulfill({+ status,+ contentType: 'application/problem+json',+ body: JSON.stringify({ title: 'Error', status, detail })+ });+ }++ test.describe('Update All startup', () => {+ const CONFLICT_DETAIL = 'an update-all job is already in progress';++ test('a failed start surfaces the API error and returns to the confirm step', async ({+ page+ }) => {+ let statusCalls = 0;+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {+ await fulfillProblem(route, 500, 'Failed to initiate upgrade: pull access denied');+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {+ statusCalls++;+ await fulfillJob(route, 'running', 'updating');+ });++ await page.goto('/environments');+ await openAndConfirmUpdateAll(page);++ const toast = page+ .locator('li[data-sonner-toast]')+ .filter({ hasText: 'Failed to start update all' });+ await expect(toast).toBeVisible({ timeout: 10_000 });+ await expect(toast).toContainText('pull access denied');++ // Back at the confirm step, ready for another attempt — and no polling started.+ const dialog = page.getByRole('dialog');+ await expect(dialog.getByRole('heading', { name: 'Update all environments' })).toBeVisible();+ await expect(dialog.getByRole('button', { name: 'Update All', exact: true })).toBeVisible();+ expect(statusCalls).toBe(0);+ });++ test('a 409 conflict adopts the active job and follows it to completion', async ({ page }) => {+ let startCalls = 0;+ let statusCalls = 0;+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {+ startCalls++;+ await fulfillProblem(route, 409, CONFLICT_DETAIL);+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {+ statusCalls++;+ // First read (adoption) reports the job still running; the poll completes it.+ if (statusCalls === 1) {+ await fulfillJob(route, 'running', 'updating');+ return;+ }+ await fulfillJob(route, 'completed', 'updated');+ });++ await page.goto('/environments');+ await openAndConfirmUpdateAll(page);++ const dialog = page.getByRole('dialog');+ await expect(dialog.getByRole('heading', { name: 'All environments processed' })).toBeVisible(+ {+ timeout: 10_000+ }+ );+ await expect(dialog.getByText('1 of 1', { exact: true })).toBeVisible();+ await expect(page.locator('li[data-sonner-toast]')).toHaveCount(0);+ // The conflict is never retried; the existing job is tracked instead.+ expect(startCalls).toBe(1);+ expect(statusCalls).toBeGreaterThanOrEqual(2);+ });++ test('a 409 conflict without an active job reports the conflict and does not retry', async ({+ page+ }) => {+ await page.clock.install();+ let startCalls = 0;+ let statusCalls = 0;+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {+ startCalls++;+ await fulfillProblem(route, 409, CONFLICT_DETAIL);+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {+ statusCalls++;+ // The guard tripped but the latest job is already terminal: nothing to adopt.+ await fulfillJob(route, 'completed', 'updated');+ });++ await page.goto('/environments');+ await openAndConfirmUpdateAll(page);++ const toast = page+ .locator('li[data-sonner-toast]')+ .filter({ hasText: 'Failed to start update all' });+ await expect(toast).toBeVisible({ timeout: 10_000 });+ await expect(toast).toContainText(CONFLICT_DETAIL);++ const dialog = page.getByRole('dialog');+ await expect(dialog.getByRole('heading', { name: 'Update all environments' })).toBeVisible();++ // Wait past one poll interval to prove neither polling nor a retry kicked in.+ // The three status reads are the persistence-window grace, not polling.+ await page.clock.runFor(4_000);+ expect(startCalls).toBe(1);+ expect(statusCalls).toBe(3);+ });++ test('a 409 conflict adopts a job that is persisted shortly after the conflict', async ({+ page+ }) => {+ let statusCalls = 0;+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {+ await fulfillProblem(route, 409, CONFLICT_DETAIL);+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {+ statusCalls++;+ // The winning client's job row does not exist yet on the first read.+ if (statusCalls === 1) {+ await fulfillProblem(route, 404, 'no update-all job found');+ return;+ }+ await fulfillJob(+ route,+ statusCalls === 2 ? 'running' : 'completed',+ statusCalls === 2 ? 'updating' : 'updated'+ );+ });++ await page.goto('/environments');+ await openAndConfirmUpdateAll(page);++ const dialog = page.getByRole('dialog');+ await expect(dialog.getByRole('heading', { name: 'All environments processed' })).toBeVisible(+ {+ timeout: 10_000+ }+ );+ await expect(page.locator('li[data-sonner-toast]')).toHaveCount(0);+ });++ test('closing the dialog during a pending start ignores the late response', async ({+ page+ }) => {+ await page.clock.install();+ let releaseStart!: () => void;+ const startReleased = new Promise<void>((resolve) => {+ releaseStart = resolve;+ });+ let statusCalls = 0;+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {+ await startReleased;+ await fulfillJob(route, 'running', 'updating');+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {+ statusCalls++;+ await fulfillJob(route, 'running', 'updating');+ });++ await page.goto('/environments');+ await openAndConfirmUpdateAll(page);++ const dialog = page.getByRole('dialog');+ await expect(dialog.getByRole('heading', { name: 'Updating environments…' })).toBeVisible();+ await dialog.getByRole('button', { name: 'Close', exact: true }).first().click();+ await expect(dialog).toBeHidden();++ // The start response arrives after closure: it must not reopen or start polling.+ releaseStart();+ await page.clock.runFor(4_000);+ await expect(dialog).toBeHidden();+ expect(statusCalls).toBe(0);+ await expect(page.locator('li[data-sonner-toast]')).toHaveCount(0);});- await expect(page.getByText('pull failed: registry unreachable')).toBeVisible();- expect(requested).toEqual([IGNORED_CONTAINER.id, IGNORED_CONTAINER.id]);-- // The action is usable again after both outcomes: loading state was cleared.- const menu = await openRowActionsMenu(page, containerRow(page, IGNORED_CONTAINER));- await expect(- menu.getByRole('menuitem', { name: 'Update Container', exact: true })- ).toBeEnabled();- await page.keyboard.press('Escape');});- test('Update All confirms before dispatching a host-wide updater run', async ({ page }) => {- await stubContainersWithUpdates(page);+ test.describe('Manager self-update recovery', () => {+ test('Update All keeps the manager result visible and refreshes without a document reload', async ({+ page+ }) => {+ registerReloadCounter(page);+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {+ await fulfillJob(route, 'running', 'updating');+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {+ await fulfillJob(route, 'completed', 'updated');+ });- let runs = 0;- await page.route(/\/api\/environments\/0\/updater\/run$/, async (route) => {- runs++;- await route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify({- success: true,- data: { checked: 2, updated: 2, skipped: 0, failed: 0, items: [], duration: '2s' }- })+ await page.goto('/environments');+ await openAndConfirmUpdateAll(page);++ // The finished result stays on screen instead of the page being yanked away.+ const dialog = page.getByRole('dialog');+ await expect(dialog.getByRole('heading', { name: 'All environments processed' })).toBeVisible(+ {+ timeout: 10_000+ }+ );+ // A hard reload here would re-run every load function while the agents are still+ // reconnecting, briefly rendering the whole fleet as offline.+ await expect.poll(() => currentReloadCount(page)).toBe(1);++ // Closing refreshes through SvelteKit, which reloads data but not the document.+ await dialog.getByRole('button', { name: 'Close', exact: true }).first().click();+ await expect(dialog).toBeHidden();+ await expect.poll(() => currentReloadCount(page)).toBe(1);+ await expect(page).toHaveURL('/environments');+ });++ test('Update All leaves failed manager results visible without reloading', async ({ page }) => {+ registerReloadCounter(page);+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {+ await fulfillJob(route, 'running', 'updating');+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {+ await fulfillJob(route, 'failed', 'failed');+ });++ await page.goto('/environments');+ await openAndConfirmUpdateAll(page);++ await expect(page.getByRole('heading', { name: 'Update all failed' })).toBeVisible({+ timeout: 10_000});+ await expect(page.getByText('Manager update failed')).toBeVisible();+ await expect.poll(() => currentReloadCount(page)).toBe(1);});- await page.goto(UPDATES_ROUTE);- await page.waitForLoadState('load');+ test('the single-manager flow reloads immediately after version verification', async ({+ page+ }) => {+ registerReloadCounter(page);+ const snapshot = dashboardSnapshot();+ let upgradeTriggered = false;++ await page.route(/\/api\/stream(?:\?.*)?$/, async (route) => {+ const channels =+ new URL(route.request().url()).searchParams.get('channels')?.split(',') ?? [];+ const timestamp = new Date().toISOString();+ await route.fulfill({+ status: 200,+ contentType: 'application/x-json-stream',+ body: channels.includes('dashboard')+ ? `${JSON.stringify({+ channel: 'dashboard',+ dashboard: { type: 'snapshot', environmentId: '0', snapshot, timestamp },+ timestamp+ })}\n`+ : ''+ });+ });+ await page.route(/\/api\/environments\/0\/dashboard(?:\?.*)?$/, async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ success: true, data: snapshot })+ });+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade\/check$/, async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ canUpgrade: true, error: false, message: '' })+ });+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade$/, async (route) => {+ upgradeTriggered = true;+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ success: true, message: 'Upgrade started' })+ });+ });+ await page.route(/\/api\/health$/, async (route) => {+ await route.fulfill({ status: 200, body: '' });+ });+ await page.route(/\/api\/app-version$/, async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(versionInfo(upgradeTriggered ? '2.0.0' : '1.0.0'))+ });+ });- await page.getByRole('button', { name: 'Update All', exact: true }).click();+ const dashboardUpgradeCheck = page.waitForResponse((response) => {+ return (+ new URL(response.url()).pathname === '/api/environments/0/system/upgrade/check' &&+ response.status() === 200+ );+ });+ await page.goto('/dashboard');+ await dashboardUpgradeCheck;+ const versionBadge = page+ .locator('main')+ .getByRole('button', { name: 'v1.0.0', exact: true });+ await expect(versionBadge).toBeVisible();+ await versionBadge.hover();+ const upgradeButton = page.getByRole('button', { name: 'Update to 2.0.0', exact: true });+ await expect(upgradeButton).toBeVisible();+ await upgradeButton.click();+ const dialog = page.getByRole('dialog');+ await dialog.getByRole('button', { name: 'Update to 2.0.0', exact: true }).click();++ await expect.poll(() => currentReloadCount(page), { timeout: 10_000 }).toBe(2);+ await expect(page).toHaveURL('/dashboard');+ });- const dialog = page.getByRole('dialog');- await expect(dialog).toBeVisible();- await expect(dialog.getByText(/every pending update on this host/i)).toBeVisible();- expect(runs).toBe(0);+ test('status and activity 401s share one refresh before the upgrade reload', async ({+ page+ }) => {+ await page.clock.install();+ registerReloadCounter(page);+ await registerTokenSeeding(page);- await dialog.getByRole('button', { name: 'Update All', exact: true }).click();+ let releaseActivity!: () => void;+ const activityRelease = new Promise<void>((resolve) => {+ releaseActivity = resolve;+ });+ await page.route(/\/api\/stream(?:\?.*)?$/, async (route) => {+ const channels =+ new URL(route.request().url()).searchParams.get('channels')?.split(',') ?? [];+ if (!channels.includes('activities')) {+ await route.fulfill({+ status: 200,+ contentType: 'application/x-json-stream',+ body: ''+ });+ return;+ }+ await activityRelease;+ if (route.request().headers()['cookie']?.includes(REFRESH_COOKIE)) {+ const timestamp = new Date().toISOString();+ await route.fulfill({+ status: 200,+ contentType: 'application/x-json-stream',+ body: `${JSON.stringify({+ channel: 'activities',+ activity: { type: 'snapshot', environmentId: '0', activities: [], timestamp },+ timestamp+ })}\n`+ });+ return;+ }+ await route.fulfill({+ status: 401,+ contentType: 'application/json',+ body: JSON.stringify({ message: 'Application has been updated. Refreshing session.' })+ });+ });++ let refreshCalls = 0;+ let releaseRefresh!: () => void;+ const refreshReleased = new Promise<void>((resolve) => {+ releaseRefresh = resolve;+ });+ await page.route(/\/api\/auth\/refresh$/, async (route) => {+ refreshCalls++;+ await refreshReleased;+ await route.fulfill({+ status: 200,+ headers: {+ 'content-type': 'application/json',+ 'set-cookie': `${REFRESH_COOKIE}; Path=/; SameSite=Lax`+ },+ body: JSON.stringify({+ success: true,+ data: {+ token: 'mocked-access-token',+ refreshToken: 'mocked-refresh-token',+ expiresAt: new Date(Date.now() + 3_600_000).toISOString()+ }+ })+ });+ });++ await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {+ await fulfillJob(route, 'running', 'updating');+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {+ if (route.request().headers()['cookie']?.includes(REFRESH_COOKIE)) {+ await fulfillJob(route, 'completed', 'updated');+ return;+ }+ await route.fulfill({+ status: 401,+ contentType: 'application/json',+ body: JSON.stringify({ message: 'Application has been updated. Refreshing session.' })+ });+ });++ try {+ await page.goto('/environments');+ const statusUnauthorized = page.waitForResponse((response) => {+ return (+ new URL(response.url()).pathname === '/api/environments/0/system/upgrade/all/status' &&+ response.status() === 401+ );+ });+ await openAndConfirmUpdateAll(page);+ releaseActivity();+ await expect.poll(() => refreshCalls).toBe(1);+ await page.clock.runFor(3500);+ const statusResponse = await statusUnauthorized;+ await statusResponse.finished();+ // Queue this after the response event so its 401 handler has joined the+ // in-flight refresh before that refresh is released.+ await page.evaluate(() => undefined);+ expect(refreshCalls).toBe(1);+ releaseRefresh();++ await expect.poll(() => currentReloadCount(page), { timeout: 15_000 }).toBe(2);+ expect(refreshCalls).toBe(1);+ await expect(page).toHaveURL('/environments');+ } finally {+ releaseActivity();+ releaseRefresh();+ }+ });++ test('a transient refresh failure keeps the token and recovers on the next poll', async ({+ page+ }) => {+ registerReloadCounter(page);+ await registerTokenSeeding(page);++ let refreshCalls = 0;+ await page.route(/\/api\/auth\/refresh$/, async (route) => {+ refreshCalls++;+ if (refreshCalls === 1) {+ await route.abort('connectionfailed');+ return;+ }+ await route.fulfill({+ status: 200,+ headers: {+ 'content-type': 'application/json',+ 'set-cookie': `${REFRESH_COOKIE}; Path=/; SameSite=Lax`+ },+ body: JSON.stringify({+ success: true,+ data: {+ token: 'mocked-access-token',+ refreshToken: 'mocked-refresh-token',+ expiresAt: new Date(Date.now() + 3_600_000).toISOString()+ }+ })+ });+ });++ await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {+ await fulfillJob(route, 'running', 'updating');+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {+ await route.fulfill({+ status: 401,+ contentType: 'application/json',+ body: JSON.stringify({ message: 'Application has been updated. Refreshing session.' })+ });+ });++ await page.goto('/environments');+ await openAndConfirmUpdateAll(page);- await expect(page.getByText('Applied 2 update(s)')).toBeVisible({ timeout: 15_000 });- expect(runs).toBe(1);+ await expect.poll(() => refreshCalls, { timeout: 10_000 }).toBe(1);+ await expect+ .poll(() => page.evaluate((key: string) => sessionStorage.getItem(key), REFRESH_TOKEN_KEY))+ .toBe('playwright-test-refresh-token');+ await expect.poll(() => currentReloadCount(page), { timeout: 15_000 }).toBe(2);+ expect(refreshCalls).toBe(2);+ });++ test('a rejected refresh during an upgrade redirects to login instead of polling', async ({+ page+ }) => {+ await registerTokenSeeding(page);+ let refreshCalls = 0;++ await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {+ await fulfillJob(route, 'running', 'updating');+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {+ await route.fulfill({+ status: 401,+ contentType: 'application/json',+ body: JSON.stringify({ message: 'Application has been updated. Refreshing session.' })+ });+ });++ await page.goto('/environments');+ await openAndConfirmUpdateAll(page);+ await page.route(/\/api\/auth\/refresh$/, async (route) => {+ refreshCalls++;+ await route.fulfill({+ status: 401,+ contentType: 'application/json',+ body: JSON.stringify({ message: 'Invalid or expired refresh token' })+ });+ });+ await page.route(/\/api\/auth\/me$/, async (route) => {+ await route.fulfill({+ status: 401,+ contentType: 'application/json',+ body: JSON.stringify({ message: 'Authentication required' })+ });+ });++ await page.waitForURL(/\/login(?:\?|$)/, { timeout: 10_000 });+ expect(refreshCalls).toBe(1);+ await expect(+ page.getByRole('button', { name: 'Sign in to Arcane', exact: true })+ ).toBeVisible();+ });++ test('a missing refresh token during an upgrade redirects to login instead of polling', async ({+ page+ }) => {+ let refreshCalls = 0;+ await page.route(/\/api\/auth\/refresh$/, async (route) => {+ refreshCalls++;+ await route.continue();+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all$/, async (route) => {+ await fulfillJob(route, 'running', 'updating');+ });+ await page.route(/\/api\/environments\/0\/system\/upgrade\/all\/status$/, async (route) => {+ await route.fulfill({+ status: 401,+ contentType: 'application/json',+ body: JSON.stringify({ message: 'Application has been updated. Refreshing session.' })+ });+ });++ await page.goto('/environments');+ await openAndConfirmUpdateAll(page);+ await page.route(/\/api\/auth\/me$/, async (route) => {+ await route.fulfill({+ status: 401,+ contentType: 'application/json',+ body: JSON.stringify({ message: 'Authentication required' })+ });+ });++ await page.waitForURL(/\/login(?:\?|$)/, { timeout: 10_000 });+ expect(refreshCalls).toBe(0);+ await expect(+ page.getByRole('button', { name: 'Sign in to Arcane', exact: true })+ ).toBeVisible();+ });});});diff --git a/tests/spec/volumes.spec.ts b/tests/spec/volumes.spec.tsindex 2b50a888a..1b38b31b9 100644--- a/tests/spec/volumes.spec.ts+++ b/tests/spec/volumes.spec.ts@@ -92,25 +92,6 @@ async function gotoVolumeDetail(page: Page, volumeName: string) {await expect(page.getByRole('heading', { level: 1, name: volumeName })).toBeVisible();}-function facetIds(title: string) {- const key = title.toLowerCase();- return {- triggerId: `facet-${key}-trigger`,- contentId: `facet-${key}-content`- };-}--async function ensureFacetOpen(page: Page, title: string) {- const { triggerId, contentId } = facetIds(title);- const trigger = page.getByTestId(triggerId).first();- const content = page.getByTestId(contentId).first();-- await expect(trigger).toBeVisible();- if ((await trigger.getAttribute('data-state')) !== 'open') await trigger.click();- await content.waitFor({ state: 'visible' });- return { trigger, content };-}-test.describe('Volumes Page', () => {test('Persisted Size sort does not block navigation', async ({ page, context }) => {await page.goto('/dashboard');@@ -191,13 +172,6 @@ test.describe('Volumes Page', () => {expect(sizeRequests).toBe(0);});- test('Volume Page Display', async ({ page }) => {- await page.goto('/volumes');-- await expect(page.getByRole('heading', { name: 'Volumes', level: 1 })).toBeVisible();- await expect(page.getByText('Manage your Docker volumes').first()).toBeVisible();- });-test('Correct Volume Stat Card Counts', async ({ page }) => {await page.goto('/volumes');await page.waitForLoadState('load');@@ -205,20 +179,6 @@ test.describe('Volumes Page', () => {await expect(page.getByText(`${volumeCount.total} Total Volumes`)).toBeVisible();});- test('Create Volume Sheet Opens', async ({ page }) => {- await openCreateVolumeSheet(page);- await expect(page.getByText('Create New Volume')).toBeVisible();- });-- test('Display Volume Filters', async ({ page }) => {- await page.goto('/volumes');- await page.waitForLoadState('load');-- const { content } = await ensureFacetOpen(page, 'Usage');- await expect(content.getByRole('option', { name: 'In Use' })).toBeVisible();- await expect(content.getByRole('option', { name: 'Unused' })).toBeVisible();- });-test('Inspect Volume', async ({ page }) => {const volumeName = `e2e-inspect-volume-${Date.now()}`;@@ -365,7 +325,7 @@ function volumesPage(volumes: MockVolume[], url: URL) {const cmp =typeof av === 'number' && typeof bv === 'number'? av - bv- : String(av).localeCompare(String(bv));+ : JSON.stringify(av ?? '').localeCompare(JSON.stringify(bv ?? ''));return order === 'desc' ? -cmp : cmp;});const data = limit === -1 ? sorted : sorted.slice(start, start + limit);diff --git a/tests/types/image.type.ts b/tests/types/image.type.tsindex 359d89d42..ef4442463 100644--- a/tests/types/image.type.ts+++ b/tests/types/image.type.ts@@ -1,3 +1,10 @@+export interface ImageSummary {+ id: string;+ repo: string;+ repoTags: string[];+ inUse: boolean;+}+export interface ImageUsageCounts {imagesInuse: number;imagesUnused: number;diff --git a/tests/utils/compose-reporter.ts b/tests/utils/compose-reporter.tsnew file mode 100644index 000000000..aff7b91d3--- /dev/null+++ b/tests/utils/compose-reporter.ts@@ -0,0 +1,26 @@+import type { Reporter, TestCase, TestError, TestResult } from '@playwright/test/reporter';+import { captureComposeDiagnostics } from '../setup/global-setup';++export default class ComposeReporter implements Reporter {+ private capturedFailure = false;++ onTestEnd(test: TestCase, result: TestResult) {+ if (+ result.status === test.expectedStatus ||+ result.status === 'skipped' ||+ this.capturedFailure+ )+ return;+ this.capturedFailure = true;+ this.capture();+ }++ onError(_error: TestError) {+ this.capture();+ }++ private capture() {+ const composeFile = process.env.ARCANE_E2E_COMPOSE_FILE;+ if (composeFile) captureComposeDiagnostics(composeFile);+ }+}diff --git a/tests/utils/fetch.util.ts b/tests/utils/fetch.util.tsindex 733d25a1e..fc0c1101a 100644--- a/tests/utils/fetch.util.ts+++ b/tests/utils/fetch.util.ts@@ -1,6 +1,6 @@import { expect, test, type APIRequestContext, type Page } from '@playwright/test';import { ContainerSummary } from 'types/containers.type';-import { ImageUsageCounts } from 'types/image.type';+import { ImageSummary, ImageUsageCounts } from 'types/image.type';import { NetworkSummary, NetworkUsageCounts } from 'types/networks.type';import { Project, ProjectStatusCounts } from 'types/project.type';import { VolumeUsageCounts } from 'types/volumes.type';@@ -141,14 +141,11 @@ export async function fetchNetworksWithRetry();}-export async function fetchImagesWithRetry(- page: Page,- maxRetries = 3-): Promise<Record<string, unknown>[]> {+export async function fetchImagesWithRetry(page: Page, maxRetries = 3): Promise<ImageSummary[]> {return retry(async () =>(- await readList<Record<string, unknown>>(+ await readList<ImageSummary>(await page.request.get('/api/environments/0/images'),'List images')@@ -293,3 +290,32 @@ export async function removeApiResource(expect.soft(false, `DELETE ${path}: ${String(error)}`).toBe(true);}}++export async function removeCreatedEnvironments(+ page: Page,+ environmentIds: Set<string>,+ environmentName: string+) {+ // Find the resource by name if the test timed out before receiving its ID.+ if (environmentIds.size === 0) {+ const response = await page.request.get('/api/environments?start=0&limit=1000', {+ timeout: 5_000+ });+ expect(response.ok(), 'Find environments left by interrupted creation').toBe(true);+ const { data }: { data: Array<{ id: string; name: string }> } = await response.json();+ for (const env of data) if (env.name.startsWith(environmentName)) environmentIds.add(env.id);+ }+ for (const id of environmentIds) {+ await removeApiResource(page, `/api/environments/${id}`, { timeout: 5_000 });+ await expect+ .poll(+ async () =>+ (await page.request.get(`/api/environments/${id}`, { timeout: 5_000 })).status(),+ {+ message: `Environment ${id} must be removed`,+ timeout: 10_000+ }+ )+ .toBe(404);+ }+}