Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
chore: add bigger coverage of e2e tests (#3789)
Kyle Mendell4a2f9ff46428
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex dbe9d138f..1b461aecd 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -234,12 +234,15 @@ jobs:- name: sqlitecompose_file: setup/compose.yamlport: 3000+ playwright_projects: --project=chromium --project=mobile-chromium --project=tablet-chromium --project=firefox --project=accessibility- name: postgrescompose_file: setup/compose-postgres.yamlport: 3001+ playwright_projects: --project=chromium- name: proxycompose_file: setup/compose-proxy.yamlport: 3002+ playwright_projects: --project=chromiumsteps:- name: Checkout codeuses: actions/checkout@v7@@ -280,7 +283,7 @@ jobs:run: just deps install tests- name: Run Playwright E2E tests- run: vp -C tests exec playwright test --project=chromium+ run: vp -C tests exec playwright test ${{ matrix.database.playwright_projects }}env:COMPOSE_FILE: ${{ matrix.database.compose_file }}BASE_URL: http://localhost:${{ matrix.database.port }}diff --git a/.gitignore b/.gitignoreindex a1a0602d6..ef0e41f67 100644--- a/.gitignore+++ b/.gitignore@@ -45,6 +45,9 @@ tests/test-results/*tests/.report/*tests/.auth/tests/.bin/+tests/setup/projects/*+!tests/setup/projects/test-project-static/+!tests/setup/projects/test-project-static/**backend/test-results/cli/test-results/types/test-results/diff --git a/Justfile b/Justfileindex 17847e09e..6e1013697 100644--- a/Justfile+++ b/Justfile@@ -417,9 +417,9 @@ _deps-install-tests:vp -C tests install# --with-deps shells out to apt-get, so skip it on non-Debian systemsif command -v apt-get >/dev/null 2>&1; then \- vp -C tests exec playwright install --with-deps chromium; \+ vp -C tests exec playwright install --with-deps chromium firefox; \else \- vp -C tests exec playwright install chromium; \+ vp -C tests exec playwright install chromium firefox; \fi# Install backend Go dependenciesdiff --git a/frontend/src/lib/components/arcane-button/arcane-button.svelte b/frontend/src/lib/components/arcane-button/arcane-button.svelteindex 20ea0c6b9..8200f006b 100644--- a/frontend/src/lib/components/arcane-button/arcane-button.svelte+++ b/frontend/src/lib/components/arcane-button/arcane-button.svelte@@ -65,6 +65,8 @@onclick,onClickPromise,class: className,+ role,+ 'aria-label': ariaLabel,children,...rest}: ArcaneButtonProps = $props();@@ -86,10 +88,10 @@href={href && !disabled ? href : undefined}disabled={href ? undefined : disabled || loading}aria-disabled={href ? disabled : undefined}- role={href && disabled ? 'link' : undefined}+ role={href && disabled ? 'link' : role}tabindex={href && disabled ? -1 : tabindex}class={cn('relative', arcaneButtonVariants({ tone: tone ?? config.tone, size, hoverEffect }), className)}- aria-label={children ? undefined : isIconOnlyButton ? displayLabel : undefined}+ aria-label={ariaLabel ?? (children ? undefined : isIconOnlyButton ? displayLabel : undefined)}bind:this={ref}onclick={async (e: any) => {onclick?.(e);diff --git a/frontend/src/lib/components/containers/container-form/container-form-state.ts b/frontend/src/lib/components/containers/container-form/container-form-state.tsindex 48df6cc8e..99f1375fc 100644--- a/frontend/src/lib/components/containers/container-form/container-form-state.ts+++ b/frontend/src/lib/components/containers/container-form/container-form-state.ts@@ -220,7 +220,7 @@ export function rowsFromEditConfig(cfg: ContainerEditConfigDto): ContainerFormRofor (const binding of bindings) {rows.ports.push({hostIp: binding.hostIp ?? '',- hostPort: binding.hostPort,+ hostPort: binding.hostPort ?? '',containerPort: portPart ?? '',protocol: protocolPart === 'udp' ? 'udp' : 'tcp'});diff --git a/frontend/src/lib/components/error.svelte b/frontend/src/lib/components/error.svelteindex bbff73535..245a44cc4 100644--- a/frontend/src/lib/components/error.svelte+++ b/frontend/src/lib/components/error.svelte@@ -78,7 +78,7 @@<Empty.Media variant="icon"><ErrorNotFoundIcon class="size-20 text-destructive" aria-hidden="true" /></Empty.Media>- <Empty.Title>{isConnectionError ? connectionErrorTitle : title}</Empty.Title>+ <Empty.Title role="heading" aria-level={1}>{isConnectionError ? connectionErrorTitle : title}</Empty.Title><Empty.Description>{isConnectionError ? connectionErrorMessage : message} - {status}</Empty.Description></Empty.Header><Empty.Content>diff --git a/frontend/src/lib/components/form/searchable-select.svelte b/frontend/src/lib/components/form/searchable-select.svelteindex e98c36984..e5f762bee 100644--- a/frontend/src/lib/components/form/searchable-select.svelte+++ b/frontend/src/lib/components/form/searchable-select.svelte@@ -20,7 +20,7 @@let {items,- value = $bindable(''),+ value = $bindable(),displayText,onSelect,oninput,@@ -141,9 +141,9 @@{action}tone={resolvedTone}{size}+ {...props}role="combobox"aria-expanded={open}- {...props}{disabled}id={triggerId}class={cn(@@ -194,6 +194,7 @@class={cn(itemClass)}onSelect={() => {if (item.disabled) return;+ if (value !== undefined) value = item.value;onSelect?.(item.value);closeAndFocusTrigger();}}diff --git a/frontend/src/lib/types/docker.ts b/frontend/src/lib/types/docker.tsindex 964021c48..d1f768bea 100644--- a/frontend/src/lib/types/docker.ts+++ b/frontend/src/lib/types/docker.ts@@ -18,7 +18,7 @@ export interface BaseContainer {export interface PortBinding {hostIp?: string;- hostPort: string;+ hostPort?: string;}export interface RestartPolicy {diff --git a/frontend/src/lib/utils/auth.ts b/frontend/src/lib/utils/auth.tsindex eca5f1ff4..47cc8cbe8 100644--- a/frontend/src/lib/utils/auth.ts+++ b/frontend/src/lib/utils/auth.ts@@ -49,7 +49,8 @@ const PROTECTED_PREFIXES = ['/updates'];-const UNAUTHENTICATED_ONLY_PREFIXES = ['/login', '/oidc/login', '/oidc/callback', '/auth/oidc/callback', '/img', '/favicon.ico'];+const UNAUTHENTICATED_ONLY_PREFIXES = ['/login', '/oidc/login', '/img', '/favicon.ico'];+const AUTH_CALLBACK_PREFIXES = ['/oidc/callback', '/auth/oidc/callback'];function isUserGlobalAdmin(user: User): boolean {if (typeof user.isGlobalAdmin === 'boolean') return user.isGlobalAdmin;@@ -62,6 +63,13 @@ export function userIsGlobalAdmin(user: User | null | undefined): boolean {return !!user && isUserGlobalAdmin(user);}+export function userHasPermission(user: User | null | undefined, permission: string, envId?: string): boolean {+ if (!user?.permissionsByEnv) return false;+ const global = user.permissionsByEnv[GLOBAL_SCOPE] ?? [];+ if (global.includes(SUDO_PERMISSION) || global.includes(permission)) return true;+ return envId ? (user.permissionsByEnv[envId] ?? []).includes(permission) : false;+}+function isAdminOnlyRoute(path: string): boolean {return path === '/settings/roles/new' || /^\/settings\/roles\/[^/]+/.test(path);}@@ -104,6 +112,10 @@ export function getAuthRedirectPath(return isSignedIn ? landingPath : '/login';}+ if (matchesAny(path, AUTH_CALLBACK_PREFIXES)) {+ return null;+ }+if (!isSignedIn && matchesAny(path, PROTECTED_PREFIXES)) {return '/login';}diff --git a/frontend/src/routes/(app)/containers/+page.svelte b/frontend/src/routes/(app)/containers/+page.svelteindex 4314ba0bd..76866e42e 100644--- a/frontend/src/routes/(app)/containers/+page.svelte+++ b/frontend/src/routes/(app)/containers/+page.svelte@@ -103,6 +103,9 @@}};requestOptions = nextOptions;+ if (!hasPermission('containers:list', envId)) {+ return;+ }return refreshContainers(buildRequestOptions(nextOptions), envId);}@@ -116,17 +119,20 @@const containerStatusCounts = $derived(resourcesReady ? (containers.counts ?? countsFallback) : countsFallback);+ const canCreateContainers = $derived(hasPermission('containers:create', envId));const canAutoUpdate = $derived(hasPermission('containers:autoupdate', envId));const actionButtons: ActionButton[] = $derived([- {- id: 'create',- action: 'create',- label: m.common_create_button({ resource: m.container() }),- onclick: () => goto('/containers/new'),- disabled: !resourcesReady- },+ canCreateContainers+ ? {+ id: 'create',+ action: 'create',+ label: m.common_create_button({ resource: m.container() }),+ onclick: () => goto('/containers/new'),+ disabled: !resourcesReady+ }+ : null,canAutoUpdate? {id: 'check-updates',diff --git a/frontend/src/routes/(app)/containers/[containerId]/edit/+page.ts b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.tsindex f56336bb4..bfaf1a092 100644--- a/frontend/src/routes/(app)/containers/[containerId]/edit/+page.ts+++ b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.ts@@ -1,16 +1,16 @@import type { PageLoad } from './$types';import { redirect } from '@sveltejs/kit';import { environmentStore } from '#lib/stores/environment.store.svelte';-import { hasPermission } from '#lib/utils/auth';+import { userHasPermission } from '#lib/utils/auth';import { containerService } from '#lib/services/container-service';import { queryKeys } from '#lib/query/query-keys';export const load: PageLoad = async ({ params, parent }) => {- const { queryClient } = await parent();+ const { queryClient, user } = await parent();const envId = await environmentStore.getCurrentEnvironmentId();const containerId = params.containerId;- if (!hasPermission('containers:edit', envId)) {+ if (!userHasPermission(user, 'containers:edit', envId)) {redirect(302, `/containers/${containerId}`);}diff --git a/frontend/src/routes/(app)/containers/container-table.svelte b/frontend/src/routes/(app)/containers/container-table.svelteindex 327a4c323..1e62aa918 100644--- a/frontend/src/routes/(app)/containers/container-table.svelte+++ b/frontend/src/routes/(app)/containers/container-table.svelte@@ -194,6 +194,11 @@const resourcesCurrent = $derived(environmentId === currentEnvId);const canUpdateContainers = $derived(hasPermission('containers:autoupdate', currentEnvId));const canEditContainers = $derived(hasPermission('containers:edit', currentEnvId));+ const canStartContainers = $derived(hasPermission('containers:start', currentEnvId));+ const canStopContainers = $derived(hasPermission('containers:stop', currentEnvId));+ const canRestartContainers = $derived(hasPermission('containers:restart', currentEnvId));+ const canRedeployContainers = $derived(hasPermission('containers:redeploy', currentEnvId));+ const canDeleteContainers = $derived(hasPermission('containers:delete', currentEnvId));const canKillContainers = $derived(hasPermission('containers:kill', currentEnvId));const canPauseContainers = $derived(hasPermission('containers:pause', currentEnvId));const canConvertToCompose = $derived(@@ -316,42 +321,58 @@];const bulkActions = $derived.by<BulkAction[]>(() => [- {- id: 'start',- label: m.containers_bulk_start({ count: selectedIds?.length ?? 0 }),- action: 'start',- onClick: handleBulkStart,- loading: isBulkLoading.start,- disabled: !resourcesCurrent || isAnyLoading,- icon: StartIcon- },- {- id: 'stop',- label: m.containers_bulk_stop({ count: selectedIds?.length ?? 0 }),- action: 'stop',- onClick: handleBulkStop,- loading: isBulkLoading.stop,- disabled: !resourcesCurrent || isAnyLoading,- icon: StopIcon- },- {- id: 'restart',- label: m.containers_bulk_restart({ count: selectedIds?.length ?? 0 }),- action: 'restart',- onClick: handleBulkRestart,- loading: isBulkLoading.restart,- disabled: !resourcesCurrent || isAnyLoading,- icon: RefreshIcon- },- {- id: 'remove',- label: m.containers_bulk_remove({ count: selectedIds?.length ?? 0 }),- action: 'remove',- onClick: handleBulkRemove,- loading: isBulkLoading.remove,- disabled: !resourcesCurrent || isAnyLoading,- icon: TrashIcon- },+ ...(canStartContainers+ ? [+ {+ id: 'start',+ label: m.containers_bulk_start({ count: selectedIds?.length ?? 0 }),+ action: 'start' as const,+ onClick: handleBulkStart,+ loading: isBulkLoading.start,+ disabled: !resourcesCurrent || isAnyLoading,+ icon: StartIcon+ }+ ]+ : []),+ ...(canStopContainers+ ? [+ {+ id: 'stop',+ label: m.containers_bulk_stop({ count: selectedIds?.length ?? 0 }),+ action: 'stop' as const,+ onClick: handleBulkStop,+ loading: isBulkLoading.stop,+ disabled: !resourcesCurrent || isAnyLoading,+ icon: StopIcon+ }+ ]+ : []),+ ...(canRestartContainers+ ? [+ {+ id: 'restart',+ label: m.containers_bulk_restart({ count: selectedIds?.length ?? 0 }),+ action: 'restart' as const,+ onClick: handleBulkRestart,+ loading: isBulkLoading.restart,+ disabled: !resourcesCurrent || isAnyLoading,+ icon: RefreshIcon+ }+ ]+ : []),+ ...(canDeleteContainers+ ? [+ {+ id: 'remove',+ label: m.containers_bulk_remove({ count: selectedIds?.length ?? 0 }),+ action: 'remove' as const,+ onClick: handleBulkRemove,+ loading: isBulkLoading.remove,+ disabled: !resourcesCurrent || isAnyLoading,+ icon: TrashIcon+ }+ ]+ : []),...(canConvertToCompose? [{@@ -456,7 +477,7 @@<Badge variant={getStateBadgeVariant(item.state)} minWidth="20">{getContainerStatusLabel(item.state)}</Badge>{/if}<div class="flex items-center gap-1">- {#if !status && item.state !== 'running'}+ {#if !status && item.state !== 'running' && canStartContainers}<ArcaneButtonaction="base"tone="outline"@@ -467,7 +488,7 @@icon={StartIcon}title={m.common_start()}/>- {:else if !status && item.state === 'running'}+ {:else if !status && item.state === 'running' && canStopContainers}<ArcaneButtonaction="base"tone="outline"@@ -705,7 +726,7 @@{m.common_unpause()}</DropdownMenu.Item>{/if}- {:else if item.state !== 'running'}+ {:else if item.state !== 'running' && canStartContainers}<DropdownMenu.Itemonclick={() => performContainerAction('start', item.id)}disabled={status === 'starting' || isAnyLoading}@@ -717,22 +738,26 @@{/if}{m.common_start()}</DropdownMenu.Item>- {:else}- <ContainerActionMenuItem- icon={StopIcon}- label={m.common_stop()}- onclick={() => performContainerAction('stop', item.id)}- loading={status === 'stopping'}- disabled={status === 'stopping' || isAnyLoading}- />+ {:else if item.state === 'running'}+ {#if canStopContainers}+ <ContainerActionMenuItem+ icon={StopIcon}+ label={m.common_stop()}+ onclick={() => performContainerAction('stop', item.id)}+ loading={status === 'stopping'}+ disabled={status === 'stopping' || isAnyLoading}+ />+ {/if}- <ContainerActionMenuItem- icon={RefreshIcon}- label={m.common_restart()}- onclick={() => performContainerAction('restart', item.id)}- loading={status === 'restarting'}- disabled={status === 'restarting' || isAnyLoading}- />+ {#if canRestartContainers}+ <ContainerActionMenuItem+ icon={RefreshIcon}+ label={m.common_restart()}+ onclick={() => performContainerAction('restart', item.id)}+ loading={status === 'restarting'}+ disabled={status === 'restarting' || isAnyLoading}+ />+ {/if}{#if canPauseContainers}<DropdownMenu.Item@@ -756,32 +781,36 @@</DropdownMenu.Item>{/if}- {#if item.redeployDisabled}- <DropdownMenu.Item disabled title={m.common_redeploy_disabled_arcane_self()}>- <RedeployIcon class="size-4 opacity-50" />- {m.common_redeploy()}- </DropdownMenu.Item>- {:else}- <DropdownMenu.Item onclick={() => handleRedeployContainer(item)} disabled={status === 'redeploying' || isAnyLoading}>- {#if status === 'redeploying'}- <Spinner class="size-4" />- {:else}- <RedeployIcon class="size-4" />- {/if}- {m.common_redeploy()}- </DropdownMenu.Item>+ {#if canRedeployContainers}+ {#if item.redeployDisabled}+ <DropdownMenu.Item disabled title={m.common_redeploy_disabled_arcane_self()}>+ <RedeployIcon class="size-4 opacity-50" />+ {m.common_redeploy()}+ </DropdownMenu.Item>+ {:else}+ <DropdownMenu.Item onclick={() => handleRedeployContainer(item)} disabled={status === 'redeploying' || isAnyLoading}>+ {#if status === 'redeploying'}+ <Spinner class="size-4" />+ {:else}+ <RedeployIcon class="size-4" />+ {/if}+ {m.common_redeploy()}+ </DropdownMenu.Item>+ {/if}{/if}<DropdownMenu.Separator />- <ContainerActionMenuItem- icon={TrashIcon}- label={m.common_remove()}- onclick={() => handleRemoveContainer(item.id, getContainerDisplayName(item))}- loading={status === 'removing'}- disabled={status === 'removing' || isAnyLoading}- destructive- />+ {#if canDeleteContainers}+ <ContainerActionMenuItem+ icon={TrashIcon}+ label={m.common_remove()}+ onclick={() => handleRemoveContainer(item.id, getContainerDisplayName(item))}+ loading={status === 'removing'}+ disabled={status === 'removing' || isAnyLoading}+ destructive+ />+ {/if}</RowActionsMenu>{/if}{/snippet}diff --git a/frontend/src/routes/(app)/containers/new/+page.ts b/frontend/src/routes/(app)/containers/new/+page.tsindex 561dded0b..6a7e88a3a 100644--- a/frontend/src/routes/(app)/containers/new/+page.ts+++ b/frontend/src/routes/(app)/containers/new/+page.ts@@ -1,11 +1,12 @@import type { PageLoad } from './$types';import { redirect } from '@sveltejs/kit';import { environmentStore } from '#lib/stores/environment.store.svelte';-import { hasPermission } from '#lib/utils/auth';+import { userHasPermission } from '#lib/utils/auth';-export const load: PageLoad = async () => {+export const load: PageLoad = async ({ parent }) => {+ const { user } = await parent();const envId = await environmentStore.getCurrentEnvironmentId();- if (!hasPermission('containers:create', envId)) {+ if (!userHasPermission(user, 'containers:create', envId)) {redirect(302, '/containers');}diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelteindex 9748074bf..bb1f505e9 100644--- a/frontend/src/routes/+layout.svelte+++ b/frontend/src/routes/+layout.svelte@@ -57,35 +57,35 @@<svelte:head><title>{pageTitle}</title></svelte:head>-<div class={cn('flex min-h-dvh flex-col', 'bg-transparent')}>- {#if !settings && data.user}- <Error message={m.error_occurred()} showButton={true} />- {:else}- <Tooltip.Provider>- <QueryClientProvider client={data.queryClient}>+<QueryClientProvider client={data.queryClient}>+ <div class={cn('flex min-h-dvh flex-col', 'bg-transparent')}>+ {#if !settings && data.user}+ <Error message={m.error_occurred()} showButton={true} />+ {:else}+ <Tooltip.Provider>{@render children()}<FirstLoginPasswordDialog open={showPasswordChangeDialog} onSuccess={handlePasswordChangeSuccess} />{#if dev}<SvelteQueryDevtools />{/if}- </QueryClientProvider>- </Tooltip.Provider>- {/if}-</div>+ </Tooltip.Provider>+ {/if}+ </div>-<ModeWatcher disableTransitions={false} />-<Toaster- position={isMobile.current || isTablet.current ? 'top-center' : 'bottom-right'}- toastOptions={{- classes: {- toast: 'border border-primary/30!',- title: 'text-foreground',- description: 'text-muted-foreground',- actionButton: 'bg-primary text-primary-foreground hover:bg-primary/90',- cancelButton: 'bg-muted text-muted-foreground hover:bg-muted/80',- closeButton: 'text-muted-foreground hover:text-foreground'- }- }}-/>-<ConfirmDialog />-<LoadingIndicator active={isNavigating} thickness="h-1.5" />+ <ModeWatcher disableTransitions={false} />+ <Toaster+ position={isMobile.current || isTablet.current ? 'top-center' : 'bottom-right'}+ toastOptions={{+ classes: {+ toast: 'border border-primary/30!',+ title: 'text-foreground',+ description: 'text-muted-foreground',+ actionButton: 'bg-primary text-primary-foreground hover:bg-primary/90',+ cancelButton: 'bg-muted text-muted-foreground hover:bg-muted/80',+ closeButton: 'text-muted-foreground hover:text-foreground'+ }+ }}+ />+ <ConfirmDialog />+ <LoadingIndicator active={isNavigating} thickness="h-1.5" />+</QueryClientProvider>diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.tsindex ceedd4f3c..5b6a0f5e2 100644--- a/frontend/src/routes/+layout.ts+++ b/frontend/src/routes/+layout.ts@@ -15,6 +15,10 @@ import { authService } from '#lib/services/auth-service';import { tryCatch } from '#lib/utils/api';import { QueryClient } from '@tanstack/svelte-query';import { queryKeys } from '#lib/query/query-keys';+import { redirect } from '@sveltejs/kit';+import { getAuthRedirectPath, userHasPermission } from '#lib/utils/auth';+import { getEffectiveLandingPage } from '#lib/utils/navigation';+import type { LayoutLoad } from './$types';export const ssr = false;@@ -33,7 +37,7 @@ const queryClient = new QueryClient({let authenticatedUserId: string | null | undefined;-export const load = async () => {+export const load: LayoutLoad = async ({ url }) => {const versionInformationRequest = versionService.getVersionInformation();const autoLoginConfigRequest = browser? queryClient.fetchQuery({@@ -87,8 +91,11 @@ export const load = async () => {await environmentStore.initialize([]);}+ const settingsRequest = userHasPermission(user, 'settings:read')+ ? settingsService.getSettings().catch(() => settingsService.getPublicSettings().catch(() => null))+ : settingsService.getPublicSettings().catch(() => null);const [loadedSettings, loadedSwarmStatus, loadedPermissionsManifest] = await Promise.all([- settingsService.getSettings().catch(() => null),+ settingsRequest,swarmService.getSwarmStatus().catch(() => null),permissionsManifestRequest]);@@ -150,6 +157,18 @@ export const load = async () => {};} catch {}+ const redirectPath = getAuthRedirectPath(+ url.pathname,+ user,+ environmentStore.selected?.id || '0',+ permissionsManifest,+ permissionsManifestLoadFailed,+ getEffectiveLandingPage()+ );+ if (redirectPath && redirectPath !== url.pathname) {+ throw redirect(302, redirectPath);+ }+return {user,settings,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex cd9ffddc8..6e4302d05 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -295,6 +295,9 @@ importers:tests:devDependencies:+ '@axe-core/playwright':+ specifier: ^4.13.0+ version: 4.13.0([email protected])'@playwright/test':specifier: ^1.62.1version: 1.62.1@@ -330,6 +333,11 @@ packages:resolution: {integrity: sha512-93Z1N+BQNXysodoicpOIyNh2drHfz/CTf9nnT0FEx72GJcIiwgydD7tGAr78j41LsYn3hlRn+LdGPuBLn1Bl8Q==}engines: {node: ^22.13.0 || >=24.0.0}+ '@axe-core/[email protected]':+ resolution: {integrity: sha512-6YLx+kxXu5GJceG4ozFg+33a2EMTdjYwWGloJ3sb9Kta5pp+ZNS53uxGVog5JetIY8s++P5UrtX+cri+u0VAVg==}+ peerDependencies:+ playwright-core: '>= 1.0.0'+'@babel/[email protected]':resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==}engines: {node: '>=6.9.0'}@@ -2192,6 +2200,10 @@ packages:resolution: {integrity: sha512-P4w9o2dqARji6P7MHprklbfiArZAWvo07yW7qs3pdljb3BWr12FIB7W+p0zJiuiVsUpRO0iZn1kFFcpPegg0tQ==}+ resolution: {integrity: sha512-UzGt8zg7Ny8djbYMhxl2zuEevVa7r2gJjYY5Lwr1xM7+XU2nd6CkIWFTVcCIbAP63vSz71NaVyyuSk9lHKcy0A==}+ engines: {node: '>=4'}+resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==}engines: {node: '>= 0.4'}@@ -3608,6 +3620,11 @@ snapshots:is-potential-custom-element-name: 1.0.1lru-cache: 11.5.2+ '@axe-core/[email protected]([email protected])':+ dependencies:+ axe-core: 4.13.0+ playwright-core: 1.62.1+'@babel/[email protected]':dependencies:'@babel/helper-validator-identifier': 7.29.7@@ -4739,24 +4756,24 @@ snapshots:validator: 13.15.35optional: true- '@vitest/[email protected](@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))':+ '@vitest/[email protected](@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:'@testing-library/dom': 10.4.1'@testing-library/user-event': 14.6.3(@testing-library/[email protected])- '@vitest/browser': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))- vitest: 4.1.11(@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ '@vitest/browser': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ vitest: 4.1.11(@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])transitivePeerDependencies:- bufferutil- msw- utf-8-validate- vite- '@vitest/[email protected](@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))':+ '@vitest/[email protected](@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:'@testing-library/dom': 10.4.1'@testing-library/user-event': 14.6.3(@testing-library/[email protected])- '@vitest/browser': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))- vitest: 4.1.11(@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ '@vitest/browser': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ vitest: 4.1.11(@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])transitivePeerDependencies:- bufferutil- msw@@ -4775,7 +4792,7 @@ snapshots:- utf-8-validate- vite- '@vitest/[email protected](@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))':+ '@vitest/[email protected](@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:'@blazediff/core': 1.9.1'@vitest/mocker': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))@@ -4784,7 +4801,7 @@ snapshots:pngjs: 7.0.0sirv: 3.0.2tinyrainbow: 3.1.1- vitest: 4.1.11(@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ vitest: 4.1.11(@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])ws: 8.21.1transitivePeerDependencies:- bufferutil@@ -4792,7 +4809,7 @@ snapshots:- utf-8-validate- vite- '@vitest/[email protected](@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))':+ '@vitest/[email protected](@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:'@blazediff/core': 1.9.1'@vitest/mocker': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -4801,7 +4818,7 @@ snapshots:pngjs: 7.0.0sirv: 3.0.2tinyrainbow: 3.1.1- vitest: 4.1.11(@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ vitest: 4.1.11(@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])ws: 8.21.1transitivePeerDependencies:- bufferutil@@ -5125,6 +5142,8 @@ snapshots:stubborn-fs: 2.0.0when-exit: 2.1.5+ [email protected]: {}+@@ -6524,8 +6543,8 @@ snapshots:dependencies:'@oxc-project/types': 0.146.0'@oxlint/plugins': 1.79.0- '@vitest/browser': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))- '@vitest/browser-preview': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))+ '@vitest/browser': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ '@vitest/browser-preview': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@vitest/expect': 4.1.11'@vitest/mocker': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))'@vitest/pretty-format': 4.1.11@@ -6537,7 +6556,7 @@ snapshots:oxfmt: 0.64.0([email protected])([email protected](@types/[email protected])(@typescript/[email protected])(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))oxlint: 1.79.0([email protected])([email protected](@types/[email protected])(@typescript/[email protected])(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))oxlint-tsgolint: 7.0.2001- vitest: 4.1.11(@types/[email protected])(@vitest/[email protected](@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ vitest: 4.1.11(@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])optionalDependencies:'@voidzero-dev/vite-plus-darwin-arm64': 0.3.0'@voidzero-dev/vite-plus-darwin-x64': 0.3.0@@ -6582,8 +6601,8 @@ snapshots:dependencies:'@oxc-project/types': 0.146.0'@oxlint/plugins': 1.79.0- '@vitest/browser': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))- '@vitest/browser-preview': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))+ '@vitest/browser': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ '@vitest/browser-preview': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@vitest/expect': 4.1.11'@vitest/mocker': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@vitest/pretty-format': 4.1.11@@ -6595,7 +6614,7 @@ snapshots:oxfmt: 0.64.0([email protected])([email protected](@types/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))oxlint: 1.79.0([email protected])([email protected](@types/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))oxlint-tsgolint: 7.0.2001- vitest: 4.1.11(@types/[email protected])(@vitest/[email protected](@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ vitest: 4.1.11(@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])optionalDependencies:'@voidzero-dev/vite-plus-darwin-arm64': 0.3.0'@voidzero-dev/vite-plus-darwin-x64': 0.3.0@@ -6698,7 +6717,7 @@ snapshots:optionalDependencies:vite: '@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected])'- [email protected](@types/[email protected])(@vitest/[email protected](@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]):+ [email protected](@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]):dependencies:'@vitest/expect': 4.1.11'@vitest/mocker': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))@@ -6722,12 +6741,12 @@ snapshots:why-is-node-running: 2.3.0optionalDependencies:'@types/node': 26.3.0- '@vitest/browser-preview': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ '@vitest/browser-preview': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])(@typescript/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])jsdom: 30.0.1transitivePeerDependencies:- msw- [email protected](@types/[email protected])(@vitest/[email protected](@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]):+ [email protected](@types/[email protected])(@vitest/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]):dependencies:'@vitest/expect': 4.1.11'@vitest/mocker': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -6751,7 +6770,7 @@ snapshots:why-is-node-running: 2.3.0optionalDependencies:'@types/node': 26.3.0- '@vitest/browser-preview': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ '@vitest/browser-preview': 4.1.11(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])jsdom: 30.0.1transitivePeerDependencies:- mswdiff --git a/tests/fixtures/test.fixture.ts b/tests/fixtures/test.fixture.tsnew file mode 100644index 000000000..b5860bc78--- /dev/null+++ b/tests/fixtures/test.fixture.ts@@ -0,0 +1,119 @@+import { expect, test as base } from '@playwright/test';+import type { Page, Request } from '@playwright/test';++const NETWORK_CHANGE_ERROR = 'net::ERR_NETWORK_CHANGED';+const DYNAMIC_IMPORT_ERROR = 'Failed to fetch dynamically imported module:';+const NETWORK_CHANGE_MATCH_WINDOW_MS = 1000;++export type PageErrorRecord = {+ url: string;+ name: string;+ message: string;+ stack?: string;+ timestamp: number;+};++type PageErrorFixtures = {+ pageErrorGuard: {+ allow: (matcher: string | RegExp) => void;+ };+};++function pageErrorMatches(error: PageErrorRecord, matcher: string | RegExp): boolean {+ const value = `${error.name}: ${error.message}`;+ return typeof matcher === 'string'+ ? value.includes(matcher)+ : new RegExp(matcher.source, matcher.flags).test(value);+}++function dynamicImportWasInterruptedByNetworkChange(+ error: PageErrorRecord,+ networkChangeTimestamps: number[]+): boolean {+ return (+ error.message.includes(DYNAMIC_IMPORT_ERROR) &&+ networkChangeTimestamps.some(+ (timestamp) => Math.abs(error.timestamp - timestamp) <= NETWORK_CHANGE_MATCH_WINDOW_MS+ )+ );+}++export function installPageErrorCollector(page: Page) {+ const errors: PageErrorRecord[] = [];+ const record = (error: Error) => {+ errors.push({+ url: page.url(),+ name: error.name,+ message: error.message,+ stack: error.stack,+ timestamp: Date.now()+ });+ };++ page.on('pageerror', record);++ return {+ errors,+ stop: () => page.off('pageerror', record)+ };+}++export function formatPageErrors(pageErrors: PageErrorRecord[]): string {+ return pageErrors+ .map((error, index) => {+ const stack = error.stack ? `\n${error.stack}` : '';+ return `${index + 1}. ${error.name}: ${error.message}\nURL: ${error.url}${stack}`;+ })+ .join('\n\n');+}++export const test = base.extend<PageErrorFixtures>({+ pageErrorGuard: [+ async ({ page }, use, testInfo) => {+ const collector = installPageErrorCollector(page);+ const allowed: Array<string | RegExp> = [];+ const networkChangeTimestamps: number[] = [];+ const recordNetworkChange = (request: Request) => {+ if (request.failure()?.errorText === NETWORK_CHANGE_ERROR) {+ networkChangeTimestamps.push(Date.now());+ }+ };+ page.on('requestfailed', recordNetworkChange);++ try {+ await use({ allow: (matcher) => allowed.push(matcher) });+ } finally {+ collector.stop();+ page.off('requestfailed', recordNetworkChange);+ const unexpected = collector.errors.filter((error) => {+ if (allowed.some((matcher) => pageErrorMatches(error, matcher))) return false;+ return !dynamicImportWasInterruptedByNetworkChange(error, networkChangeTimestamps);+ });++ if (unexpected.length > 0) {+ const details = formatPageErrors(unexpected);++ await testInfo.attach('unexpected-page-errors', {+ body: details,+ contentType: 'text/plain'+ });++ throw new Error(`Unexpected pageerror event(s):\n\n${details}`);+ }+ }+ },+ { auto: true }+ ]+});++export { expect };+export type {+ APIResponse,+ Browser,+ BrowserContext,+ Locator,+ Page,+ Request,+ Response,+ Route+} from '@playwright/test';diff --git a/tests/package.json b/tests/package.jsonindex ba7fd4757..ffb285d82 100644--- a/tests/package.json+++ b/tests/package.json@@ -9,6 +9,7 @@"test": "playwright test"},"devDependencies": {+ "@axe-core/playwright": "^4.13.0","@playwright/test": "^1.62.1","@types/node": "^26.3.0","typescript": "^6.0.3",diff --git a/tests/playwright.config.ts b/tests/playwright.config.tsindex 57492883e..6733f9225 100644--- a/tests/playwright.config.ts+++ b/tests/playwright.config.ts@@ -2,13 +2,20 @@ import { defineConfig, devices } from '@playwright/test';const baseURL = process.env.BASE_URL || 'http://localhost:3000';const ciJunitOutputFile = process.env.PLAYWRIGHT_JUNIT_OUTPUT_FILE || 'test-results/junit.xml';+const configuredWorkers = process.env.PLAYWRIGHT_WORKERS;+const workers =+ configuredWorkers && Number.isInteger(Number(configuredWorkers))+ ? Number(configuredWorkers)+ : configuredWorkers || (process.env.CI ? 1 : 2);export default defineConfig({testDir: '.',- fullyParallel: true,+ fullyParallel: false,forbidOnly: !!process.env.CI,+ failOnFlakyTests: !!process.env.CI,retries: process.env.CI ? 2 : 0,- workers: 1,+ retryStrategy: 'isolated',+ workers,globalSetup: './setup/global-setup',globalTeardown: './setup/global-teardown',reporter: process.env.CI@@ -34,11 +41,11 @@ export default defineConfig({projects: [{name: 'auth-setup',- testMatch: /setup\/auth\.setup\.ts/+ testMatch: '**/setup/auth.setup.ts'},{name: 'gitops-setup',- testMatch: /setup\/gitops\.setup\.ts/,+ testMatch: '**/setup/gitops.setup.ts',use: { storageState: '.auth/login.json' },dependencies: ['auth-setup']},@@ -46,11 +53,51 @@ export default defineConfig({name: 'chromium',use: { ...devices['Desktop Chrome'], storageState: '.auth/login.json' },dependencies: ['auth-setup', 'gitops-setup'],- testMatch: /spec\/(?!cli\.).*\.spec\.ts/+ testMatch: '**/spec/*.spec.ts',+ testIgnore: [+ '**/spec/cli.spec.ts',+ '**/spec/responsive-browser.spec.ts',+ '**/spec/accessibility-check.spec.ts'+ ]+ },+ {+ name: 'mobile-chromium',+ use: { ...devices['Pixel 7'], storageState: '.auth/login.json' },+ dependencies: ['auth-setup'],+ testMatch: '**/spec/responsive-browser.spec.ts'+ },+ {+ name: 'tablet-chromium',+ use: {+ ...devices['Desktop Chrome'],+ viewport: { width: 900, height: 1180 },+ 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/+ },+ {+ name: 'accessibility',+ use: {+ ...devices['Desktop Chrome'],+ storageState: { cookies: [], origins: [] }+ },+ dependencies: ['auth-setup'],+ testMatch: '**/spec/accessibility-check.spec.ts'},{name: 'cli',- testMatch: /spec\/cli\.spec\.ts/+ testMatch: '**/spec/cli.spec.ts'}]});diff --git a/tests/setup/auth.setup.ts b/tests/setup/auth.setup.tsindex 643cd8b7b..9d9634e66 100644--- a/tests/setup/auth.setup.ts+++ b/tests/setup/auth.setup.ts@@ -1,4 +1,4 @@-import { test as setup } from '@playwright/test';+import { test as setup } from '../fixtures/test.fixture';import authUtil from '../utils/auth.util';const authFile = '.auth/login.json';diff --git a/tests/setup/compose-postgres.yaml b/tests/setup/compose-postgres.yamlindex 7a6ae1d5a..bd19141ac 100644--- a/tests/setup/compose-postgres.yaml+++ b/tests/setup/compose-postgres.yaml@@ -35,11 +35,13 @@ services:environment:- ENVIRONMENT=testing- APP_ENV=test+ - APP_URL=http://localhost:3001- PUID=65532- PGID=65532- DATABASE_URL=postgres://arcane:arcane_test_password@postgres:5432/arcane_test?sslmode=disable- ENCRYPTION_KEY=3JDIgolks2tJ9ymm1AdqzlYMWu0DUWyt- JWT_SECRET=your-super-secret-jwt-key-change-this-in-production+ - TRUSTED_PROXIES=172.16.0.0/12,192.168.0.0/16- ADMIN_STATIC_API_KEY=${E2E_ADMIN_STATIC_API_KEY:-}volumes:- /var/run/docker.sock:/var/run/docker.sockdiff --git a/tests/setup/compose-proxy.yaml b/tests/setup/compose-proxy.yamlindex b308392a7..1a3b9b15f 100644--- a/tests/setup/compose-proxy.yaml+++ b/tests/setup/compose-proxy.yaml@@ -15,34 +15,71 @@ services:retries: 15docker-socket-proxy:- image: tecnativa/docker-socket-proxy:latest+ image: wollomatic/socket-proxy:1.13.1container_name: arcane-docker-proxy-test- environment:- - EVENTS=1- - PING=1- - VERSION=1- - AUTH=0- - SECRETS=0- - POST=1- - BUILD=0- - COMMIT=0- - CONFIGS=0- - CONTAINERS=1- - DISTRIBUTION=0- - EXEC=1- - IMAGES=1- - INFO=1- - NETWORKS=1- - NODES=0- - PLUGINS=0- - SERVICES=0- - SESSION=0- - SWARM=0- - SYSTEM=0- - TASKS=0- - VOLUMES=1+ user: '0:0'+ command:+ - '-listenip=0.0.0.0'+ - '-allowfrom=arcane'+ - '-allowhealthcheck'+ - '-allowGET=(/v[\d.]+)?/_ping'+ - '-allowGET=(/v[\d.]+)?/events(/.*)?'+ - '-allowGET=(/v[\d.]+)?/version'+ - '-allowGET=(/v[\d.]+)?/containers(/.*)?'+ - '-allowGET=(/v[\d.]+)?/exec(/.*)?'+ - '-allowGET=(/v[\d.]+)?/images(/.*)?'+ - '-allowGET=(/v[\d.]+)?/info(/.*)?'+ - '-allowGET=(/v[\d.]+)?/networks(/.*)?'+ - '-allowGET=(/v[\d.]+)?/volumes(/.*)?'+ - '-allowHEAD=(/v[\d.]+)?/_ping'+ - '-allowHEAD=(/v[\d.]+)?/events(/.*)?'+ - '-allowHEAD=(/v[\d.]+)?/version'+ - '-allowHEAD=(/v[\d.]+)?/containers(/.*)?'+ - '-allowHEAD=(/v[\d.]+)?/exec(/.*)?'+ - '-allowHEAD=(/v[\d.]+)?/images(/.*)?'+ - '-allowHEAD=(/v[\d.]+)?/info(/.*)?'+ - '-allowHEAD=(/v[\d.]+)?/networks(/.*)?'+ - '-allowHEAD=(/v[\d.]+)?/volumes(/.*)?'+ - '-allowPOST=(/v[\d.]+)?/_ping'+ - '-allowPOST=(/v[\d.]+)?/events(/.*)?'+ - '-allowPOST=(/v[\d.]+)?/version'+ - '-allowPOST=(/v[\d.]+)?/containers(/.*)?'+ - '-allowPOST=(/v[\d.]+)?/exec(/.*)?'+ - '-allowPOST=(/v[\d.]+)?/images(/.*)?'+ - '-allowPOST=(/v[\d.]+)?/info(/.*)?'+ - '-allowPOST=(/v[\d.]+)?/networks(/.*)?'+ - '-allowPOST=(/v[\d.]+)?/volumes(/.*)?'+ - '-allowPOST=(/v[\d.]+)?/commit'+ - '-allowPUT=(/v[\d.]+)?/_ping'+ - '-allowPUT=(/v[\d.]+)?/events(/.*)?'+ - '-allowPUT=(/v[\d.]+)?/version'+ - '-allowPUT=(/v[\d.]+)?/containers(/.*)?'+ - '-allowPUT=(/v[\d.]+)?/exec(/.*)?'+ - '-allowPUT=(/v[\d.]+)?/images(/.*)?'+ - '-allowPUT=(/v[\d.]+)?/info(/.*)?'+ - '-allowPUT=(/v[\d.]+)?/networks(/.*)?'+ - '-allowPUT=(/v[\d.]+)?/volumes(/.*)?'+ - '-allowDELETE=(/v[\d.]+)?/_ping'+ - '-allowDELETE=(/v[\d.]+)?/events(/.*)?'+ - '-allowDELETE=(/v[\d.]+)?/version'+ - '-allowDELETE=(/v[\d.]+)?/containers(/.*)?'+ - '-allowDELETE=(/v[\d.]+)?/exec(/.*)?'+ - '-allowDELETE=(/v[\d.]+)?/images(/.*)?'+ - '-allowDELETE=(/v[\d.]+)?/info(/.*)?'+ - '-allowDELETE=(/v[\d.]+)?/networks(/.*)?'+ - '-allowDELETE=(/v[\d.]+)?/volumes(/.*)?'volumes:- /var/run/docker.sock:/var/run/docker.sock:ro+ read_only: true+ cap_drop:+ - ALL+ security_opt:+ - no-new-privileges:true+ healthcheck:+ test: ['CMD', './healthcheck']+ interval: 2s+ timeout: 5s+ retries: 15restart: unless-stoppedarcane:@@ -54,10 +91,12 @@ services:environment:- ENVIRONMENT=testing- APP_ENV=test+ - APP_URL=http://localhost:${E2E_PROXY_PORT:-3002}- PUID=65532- PGID=65532- ENCRYPTION_KEY=3JDIgolks2tJ9ymm1AdqzlYMWu0DUWyt- JWT_SECRET=your-super-secret-jwt-key-change-this-in-production+ - TRUSTED_PROXIES=172.16.0.0/12,192.168.0.0/16- ADMIN_STATIC_API_KEY=${E2E_ADMIN_STATIC_API_KEY:-}- DOCKER_HOST=tcp://docker-socket-proxy:2375volumes:@@ -65,7 +104,7 @@ services:- ./projects:/app/data/projectsdepends_on:docker-socket-proxy:- condition: service_started+ condition: service_healthyminio:condition: service_healthybuild:diff --git a/tests/setup/compose.yaml b/tests/setup/compose.yamlindex 7f7ab14a7..7aaf357f6 100644--- a/tests/setup/compose.yaml+++ b/tests/setup/compose.yaml@@ -21,10 +21,12 @@ services:environment:- ENVIRONMENT=testing- APP_ENV=test+ - APP_URL=http://localhost:3000- PUID=65532- PGID=65532- ENCRYPTION_KEY=3JDIgolks2tJ9ymm1AdqzlYMWu0DUWyt- JWT_SECRET=your-super-secret-jwt-key-change-this-in-production+ - TRUSTED_PROXIES=172.16.0.0/12,192.168.0.0/16- ADMIN_STATIC_API_KEY=${E2E_ADMIN_STATIC_API_KEY:-}volumes:- /var/run/docker.sock:/var/run/docker.sockdiff --git a/tests/setup/gitops.setup.ts b/tests/setup/gitops.setup.tsindex 8f5e51a18..e3b15b4b4 100644--- a/tests/setup/gitops.setup.ts+++ b/tests/setup/gitops.setup.ts@@ -1,186 +1,168 @@-import { test as setup, expect } from '@playwright/test';--/**- * GitOps Test Setup- *- * This setup:- * 1. Registers a Git repository in Arcane (GitHub)- * 2. Configures Arcane to sync from this repository- */+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';--setup('create gitops sync in arcane', async ({ page }) => {- console.log('Creating GitOps sync configuration in Arcane...');-- // Step 1: Create a Git Repository in Arcane pointing to GitHub- await page.goto('/customize/git-repositories');- await page.waitForLoadState('load');-- // Check if test repo already exists- const existingRepo = page.getByRole('cell', { name: GITOPS_REPO_NAME });- if ((await existingRepo.count()) === 0) {- console.log('Creating Git repository in Arcane...');-- // Click Add Repository button- const addRepoButton = page.getByRole('button', { name: /Add.*Repository/i });- await addRepoButton.click();-- // Wait for dialog- const dialog = page.getByRole('dialog');- await expect(dialog).toBeVisible();-- // Fill repository form - use specific labels to avoid ambiguity- await dialog.getByRole('textbox', { name: /Repository Name/i }).fill(GITOPS_REPO_NAME);- await dialog.getByRole('textbox', { name: /Repository URL/i }).fill(GITOPS_REPO_URL);-- // Select "None" for auth type (public repo) - click the auth type dropdown- const authTrigger = dialog.locator('#authType');- if ((await authTrigger.count()) > 0) {- await authTrigger.click();- await page.waitForTimeout(300);- const noneOption = page.getByRole('option', { name: /None|No Auth/i });- if ((await noneOption.count()) > 0) {- await noneOption.click();- } else {- await page.keyboard.press('Escape');- }- }-- // Submit the form- const submitButton = dialog.getByRole('button', { name: /Add Repository/i });- await submitButton.click();-- // Wait for success or error- await page.waitForTimeout(2000);- const successToast = page.getByText(/created|success/i);- if ((await successToast.count()) > 0) {- console.log('Git repository created successfully in Arcane');- } else {- console.log('Repository may already exist or creation had issues, continuing...');- }- } else {- console.log('Git repository already exists in Arcane');- }-- // Step 2: Create GitOps Sync- await page.goto('/environments/0/gitops');- await page.waitForLoadState('load');-- // Check if sync already exists- const existingSync = page.getByRole('cell', { name: GITOPS_SYNC_NAME });- if ((await existingSync.count()) === 0) {- console.log('Creating GitOps sync...');-- // Click Add Sync button- const addSyncButton = page.getByRole('button', { name: /Add.*Sync/i });- await addSyncButton.click();-- // Wait for dialog- const dialog = page.getByRole('dialog');- await expect(dialog).toBeVisible();-- // Wait for dialog content to load- await page.waitForTimeout(1000);-- // Fill sync form - Name field (use specific selector)- const nameInput = dialog.getByRole('textbox', { name: /Sync Name/i });- await nameInput.fill(GITOPS_SYNC_NAME);-- // Select repository from dropdown- const repoTrigger = dialog.locator('#repository, [id*="repository"]').first();- if ((await repoTrigger.count()) > 0) {- await repoTrigger.click();- await page.waitForTimeout(300);- const repoOption = page.getByRole('option', { name: GITOPS_REPO_NAME });- if ((await repoOption.count()) > 0) {- await repoOption.click();- }- }-- // Wait for branches to load- await page.waitForTimeout(2000);-- // Select or enter branch- const branchTrigger = dialog.locator('#branch, [id*="branch"]').first();- if ((await branchTrigger.count()) > 0) {- const isSelect = (await branchTrigger.getAttribute('role')) === 'combobox';- if (isSelect) {- await branchTrigger.click();- await page.waitForTimeout(300);- const mainOption = page.getByRole('option', { name: new RegExp(GITOPS_REPO_BRANCH, 'i') });- if ((await mainOption.count()) > 0) {- await mainOption.click();- } else {- await page.keyboard.press('Escape');- }- }- }-- // Enter compose path- const composePathInput = dialog.getByPlaceholder(/docker-compose|compose/i);- if ((await composePathInput.count()) > 0) {- await composePathInput.fill(GITOPS_COMPOSE_PATH);- }-- // Disable auto-sync for tests- const autoSyncSwitch = dialog.locator('#autoSyncSwitch');- if ((await autoSyncSwitch.count()) > 0) {- const isChecked = await autoSyncSwitch.getAttribute('data-state');- if (isChecked === 'checked') {- await autoSyncSwitch.click();+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'+ );+}++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]}- }-- // Submit the form- const submitButton = dialog- .getByRole('button', { name: /Add.*Sync|Create/i })- .filter({ hasNotText: /Cancel/ });- await submitButton.click();-- // Wait for result- await page.waitForTimeout(3000);- console.log('GitOps sync configuration created');- } else {- console.log('GitOps sync already exists');- }-- // Step 3: Trigger initial sync to create the managed project- console.log('Triggering initial sync...');- await page.reload();- await page.waitForLoadState('load');-- // Find the sync row and trigger sync- const syncRow = page.locator('tr').filter({ hasText: GITOPS_SYNC_NAME }).first();- if ((await syncRow.count()) > 0) {- // Look for sync button or menu- const syncButton = syncRow.getByRole('button', { name: /Sync|Sync Now/i });- const menuButton = syncRow.getByRole('button', { name: /menu|actions|Open menu/i });-- if ((await syncButton.count()) > 0) {- await syncButton.click();- } else if ((await menuButton.count()) > 0) {- await syncRow.hover();- await menuButton.click();- await page.waitForTimeout(300);- const syncMenuItem = page.getByRole('menuitem', { name: /Sync/i });- if ((await syncMenuItem.count()) > 0) {- await syncMenuItem.click();- }- }+ )+ .toEqual({ status: 'success', hasProject: true, hasCommit: true, error: null });- // Wait for sync to complete- await page.waitForTimeout(5000);- console.log('Initial sync triggered');- }+ const projects = await getProjects(page);+ const project = projects.find((candidate) => candidate.id === sync.projectId);- // Verify project was created- await page.goto('/projects');- await page.waitForLoadState('load');- await page.waitForTimeout(2000);+ 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);- console.log('GitOps test setup complete!');+ 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);++ await page.goto('/projects');+ await expect(page.getByRole('link', { name: GITOPS_PROJECT_NAME, exact: true })).toBeVisible();});diff --git a/tests/spec/accessibility-check.spec.ts b/tests/spec/accessibility-check.spec.tsnew file mode 100644index 000000000..f8a6a5f04--- /dev/null+++ b/tests/spec/accessibility-check.spec.ts@@ -0,0 +1,62 @@+import AxeBuilder from '@axe-core/playwright';+import { expect, test, type Page } from '../fixtures/test.fixture';+import authUtil from '../utils/auth.util';++type AxeViolation = Awaited<ReturnType<AxeBuilder['analyze']>>['violations'][number];++function formatViolations(violations: AxeViolation[]): string {+ return violations+ .map((violation) => {+ const targets = violation.nodes.map((node) => node.target.join(' > ')).join(', ');+ return `${violation.id} (${violation.impact ?? 'unknown'}): ${targets}`;+ })+ .join('\n');+}++async function expectNoSeriousAccessibilityViolations(page: Page, label: string, include?: string) {+ let builder = new AxeBuilder({ page })+ .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])+ .disableRules(['color-contrast', 'html-lang-valid']);+ if (include) {+ await expect(page.locator(include)).toBeVisible();+ builder = builder.include(include);+ }++ const results = await builder.analyze();+ const violations = results.violations.filter(+ (violation) => violation.impact === 'critical' || violation.impact === 'serious'+ );++ expect(violations, `${label}\n${formatViolations(violations)}`).toEqual([]);+}++test('login and representative authenticated surfaces pass the accessibility checks', async ({+ page+}) => {+ test.setTimeout(120_000);++ await page.goto('/login');+ await expect(page).toHaveTitle(/Arcane/);+ await expectNoSeriousAccessibilityViolations(page, 'Login page');++ await page.getByLabel('Username').fill('arcane');+ await page.getByLabel('Password').fill(authUtil.TEST_PASSWORD);+ await page.getByRole('button', { name: 'Sign in to Arcane', exact: true }).click();+ await expect(page).toHaveURL('/dashboard');+ await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();+ await expectNoSeriousAccessibilityViolations(page, 'Dashboard', 'main');++ await page.goto('/networks');+ await expect(page.getByRole('heading', { name: 'Networks', level: 1 })).toBeVisible();+ await expectNoSeriousAccessibilityViolations(page, 'Networks table', 'main');++ await page.goto('/containers/new');+ await expect(page.getByRole('heading', { name: 'Create Container' })).toBeVisible();+ await expectNoSeriousAccessibilityViolations(page, 'New container form', 'main');++ await page.goto('/networks');+ await expect(page.getByRole('heading', { name: 'Networks', level: 1 })).toBeVisible();+ await page.getByRole('button', { name: 'Create Network' }).first().click();+ await expect(page.getByRole('dialog')).toBeVisible();+ await expectNoSeriousAccessibilityViolations(page, 'Create network dialog', '[role="dialog"]');+});diff --git a/tests/spec/account.spec.ts b/tests/spec/account.spec.tsnew file mode 100644index 000000000..4c53a456b--- /dev/null+++ b/tests/spec/account.spec.ts@@ -0,0 +1,495 @@+import { fileURLToPath } from 'node:url';+import {+ expect,+ formatPageErrors,+ installPageErrorCollector,+ test,+ type BrowserContext,+ type Page+} from '../fixtures/test.fixture';+import { readApiData } from '../utils/fetch.util';++const AVATAR_PATH = fileURLToPath(+ new URL('../../backend/resources/images/icon-128x128.png', import.meta.url)+);++type UserPreferences = {+ themeMode?: 'light' | 'dark' | 'system';+ keyboardShortcutsEnabled?: boolean;+ mobileNavigationMode?: 'floating' | 'docked';+ defaultLandingPage?: string;+};++type AccountUser = {+ id: string;+ username: string;+ displayName?: string;+ email?: string;+ avatarUrl?: string;+ timeFormat: 'auto' | '12h' | '24h';+ preferences?: UserPreferences;+};++type PersonalApiKey = {+ id: string;+ name: string;+ key: string;+};++type Passkey = {+ id: string;+ name: string;+};++async function login(page: Page, username: string, password: string, expectedPath = '/dashboard') {+ await page.goto('/login');+ await page.getByLabel('Username', { exact: true }).fill(username);+ await page.getByLabel('Password', { exact: true }).fill(password);+ await page.getByRole('button', { name: 'Sign in to Arcane', exact: true }).click();+ await expect(page).toHaveURL(expectedPath);+ await expect(page.locator('main').first()).toBeVisible();+}++async function waitForProfileUpdate(page: Page, action: () => Promise<void>) {+ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'PUT' &&+ new URL(response.url()).pathname === '/api/auth/me/profile'+ );+ await action();+ return responsePromise;+}++test('manages an isolated account, preferences, credentials, and sessions', async ({+ browser,+ page+}, testInfo) => {+ test.setTimeout(180_000);++ const suffix = Date.now().toString(36);+ const username = `e2e-account-${suffix}`;+ const initialPassword = 'E2e-account-initial-123!';+ const updatedPassword = 'E2e-account-updated-456!';+ const displayName = `Account Journey ${suffix}`;+ const email = `${username}@example.test`;+ const keyName = `account-key-${suffix}`;+ let user: AccountUser | null = null;+ let accountContext: BrowserContext | null = null;++ try {+ user = await readApiData<AccountUser>(+ await page.request.post('/api/users', {+ data: {+ username,+ password: initialPassword,+ displayName: 'Account Journey Initial',+ email: `${username}[email protected]`+ }+ }),+ `Create account user ${username}`+ );+ await readApiData<unknown[]>(+ await page.request.put(`/api/users/${user.id}/role-assignments`, {+ data: { assignments: [{ roleId: 'role_viewer' }] }+ }),+ `Assign Viewer role to ${username}`+ );++ accountContext = await browser.newContext({+ baseURL: String(testInfo.project.use.baseURL),+ storageState: { cookies: [], origins: [] },+ extraHTTPHeaders: { 'X-Forwarded-For': '198.18.0.1' }+ });+ const accountPage = await accountContext.newPage();+ accountPage.setDefaultTimeout(12_000);+ const pageErrors = installPageErrorCollector(accountPage);++ try {+ await login(accountPage, username, initialPassword);+ await accountPage.goto('/account');+ await expect(accountPage.getByRole('heading', { name: 'Account', level: 1 })).toBeVisible();++ await accountPage.getByLabel('Display Name', { exact: true }).fill(displayName);+ await accountPage.getByLabel('Email', { exact: true }).fill(email);+ const profileResponse = await waitForProfileUpdate(accountPage, () =>+ accountPage.getByRole('button', { name: 'Save profile', exact: true }).click()+ );+ const updatedProfile = await readApiData<AccountUser>(+ profileResponse,+ 'Update account profile'+ );+ expect(updatedProfile).toMatchObject({ displayName, email });++ await accountPage.getByLabel('Display Name', { exact: true }).fill('Unsaved account name');+ await accountPage.getByRole('button', { name: 'Reset', exact: true }).click();+ await expect(accountPage.getByLabel('Display Name', { exact: true })).toHaveValue(+ displayName+ );++ await accountPage.locator('#account-avatar-cropper').setInputFiles(AVATAR_PATH);+ const cropDialog = accountPage+ .getByRole('dialog')+ .filter({ has: accountPage.getByRole('heading', { name: 'Crop profile picture' }) });+ await expect(cropDialog).toBeVisible();+ const avatarUploadResponsePromise = accountPage.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/auth/me/avatar'+ );+ await cropDialog.getByRole('button', { name: 'Crop photo', exact: true }).click();+ const avatarUser = await readApiData<AccountUser>(+ await avatarUploadResponsePromise,+ 'Upload account avatar'+ );+ expect(avatarUser.avatarUrl).toBeTruthy();++ const profileSection = accountPage+ .locator('section')+ .filter({ has: accountPage.getByRole('heading', { name: 'Profile', exact: true }) });+ const avatarDeleteResponsePromise = accountPage.waitForResponse(+ (response) =>+ response.request().method() === 'DELETE' &&+ new URL(response.url()).pathname === '/api/auth/me/avatar'+ );+ await profileSection.getByRole('button', { name: 'Remove', exact: true }).click();+ const avatarRemovedUser = await readApiData<AccountUser>(+ await avatarDeleteResponsePromise,+ 'Remove account avatar'+ );+ expect(avatarRemovedUser.avatarUrl).toBeFalsy();++ await accountPage.getByRole('button', { name: 'New key', exact: true }).click();+ const keyDialog = accountPage.getByRole('dialog', { name: 'Create API Key' });+ await keyDialog.getByLabel('Name', { exact: true }).fill(keyName);+ await keyDialog.getByLabel('Description', { exact: true }).fill('Account browser journey');+ const keyCreateResponsePromise = accountPage.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/auth/me/api-keys'+ );+ await keyDialog.getByRole('button', { name: 'Create API Key', exact: true }).click();+ const createdKey = await readApiData<PersonalApiKey>(+ await keyCreateResponsePromise,+ 'Create personal API key'+ );+ expect(createdKey.name).toBe(keyName);+ expect(createdKey.key).toBeTruthy();+ await accountPage.getByRole('button', { name: "I've saved it", exact: true }).click();++ const keyRow = accountPage.locator('li').filter({ hasText: keyName });+ await expect(keyRow).toBeVisible();+ await keyRow.getByRole('button', { name: 'Delete', exact: true }).click();+ const keyDeleteResponsePromise = accountPage.waitForResponse(+ (response) =>+ response.request().method() === 'DELETE' &&+ new URL(response.url()).pathname === `/api/auth/me/api-keys/${createdKey.id}`+ );+ await accountPage+ .getByRole('dialog')+ .getByRole('button', { name: 'Delete', exact: true })+ .click();+ expect((await keyDeleteResponsePromise).ok()).toBe(true);+ await expect(keyRow).toHaveCount(0);++ await accountPage.getByRole('tab', { name: 'Preferences', exact: true }).click();+ await expect(accountPage).toHaveURL('/account?tab=preferences');+ const original = await readApiData<AccountUser>(+ await accountPage.request.get('/api/auth/me'),+ 'Get account preferences'+ );++ const timeFormat = original.timeFormat === '24h' ? '12h' : '24h';+ const timeFormatLabel = timeFormat === '24h' ? '24-hour' : '12-hour';+ const timeFormatResponse = await waitForProfileUpdate(accountPage, async () => {+ await accountPage.locator('#accountTimeFormatPicker').click();+ await accountPage.getByRole('option', { name: timeFormatLabel, exact: true }).click();+ });+ expect(timeFormatResponse.request().postDataJSON()).toEqual({ timeFormat });++ const themeMode = original.preferences?.themeMode === 'dark' ? 'light' : 'dark';+ const themeLabel = themeMode === 'dark' ? 'Dark' : 'Light';+ const themeResponse = await waitForProfileUpdate(accountPage, () =>+ accountPage.getByRole('button', { name: themeLabel, exact: true }).click()+ );+ expect(themeResponse.request().postDataJSON()).toEqual({ preferences: { themeMode } });++ const landingPage =+ original.preferences?.defaultLandingPage === '/containers' ? '/dashboard' : '/containers';+ const landingLabel = landingPage === '/containers' ? 'Containers' : 'Dashboard';+ const landingResponse = await waitForProfileUpdate(accountPage, async () => {+ await accountPage.locator('#account-default-landing-page').click();+ await accountPage.getByRole('option', { name: landingLabel, exact: true }).click();+ });+ expect(landingResponse.request().postDataJSON()).toEqual({+ preferences: { defaultLandingPage: landingPage }+ });++ const keyboardShortcutsEnabled = !(original.preferences?.keyboardShortcutsEnabled ?? true);+ const keyboardResponse = await waitForProfileUpdate(accountPage, () =>+ accountPage.locator('#account-keyboard-shortcuts').click()+ );+ expect(keyboardResponse.request().postDataJSON()).toEqual({+ preferences: { keyboardShortcutsEnabled }+ });++ const mobileNavigationMode =+ original.preferences?.mobileNavigationMode === 'docked' ? 'floating' : 'docked';+ const mobileNavigationLabel = mobileNavigationMode === 'docked' ? 'Docked' : 'Floating';+ const mobileNavigationResponse = await waitForProfileUpdate(accountPage, () =>+ accountPage.getByRole('button', { name: mobileNavigationLabel, exact: true }).click()+ );+ expect(mobileNavigationResponse.request().postDataJSON()).toEqual({+ preferences: { mobileNavigationMode }+ });++ const persisted = await readApiData<AccountUser>(+ await accountPage.request.get('/api/auth/me'),+ 'Verify persisted account preferences'+ );+ expect(persisted).toMatchObject({+ timeFormat,+ preferences: {+ themeMode,+ defaultLandingPage: landingPage,+ keyboardShortcutsEnabled,+ mobileNavigationMode+ }+ });++ await accountPage.reload();+ await expect(accountPage.locator('#account-keyboard-shortcuts')).toHaveAttribute(+ 'data-state',+ keyboardShortcutsEnabled ? 'checked' : 'unchecked'+ );+ await expect(+ accountPage.getByRole('button', { name: mobileNavigationLabel, exact: true })+ ).toHaveAttribute('aria-pressed', 'true');++ await accountPage.getByRole('tab', { name: 'Account', exact: true }).click();+ const logoutOtherResponsePromise = accountPage.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/auth/sessions/logout-all'+ );+ await accountPage+ .getByRole('button', { name: 'Sign out other sessions', exact: true })+ .click();+ expect((await logoutOtherResponsePromise).ok()).toBe(true);++ await accountPage.getByLabel('Current password', { exact: true }).fill(initialPassword);+ await accountPage.getByLabel('New password', { exact: true }).fill(updatedPassword);+ await accountPage.getByLabel('Confirm new password', { exact: true }).fill(updatedPassword);+ const passwordResponsePromise = accountPage.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/auth/password'+ );+ await accountPage.getByRole('button', { name: 'Update password', exact: true }).click();+ expect((await passwordResponsePromise).ok()).toBe(true);++ const dangerZone = accountPage+ .locator('section')+ .filter({ has: accountPage.getByRole('heading', { name: 'Danger zone', exact: true }) });+ await dangerZone.getByRole('button', { name: 'Log out', exact: true }).click();+ await expect(accountPage).toHaveURL('/login');+ await login(accountPage, username, updatedPassword, landingPage);+ } finally {+ pageErrors.stop();+ expect(+ pageErrors.errors,+ `Account journey page errors:\n${formatPageErrors(pageErrors.errors)}`+ ).toEqual([]);+ }+ } finally {+ await accountContext?.close();+ if (user) {+ await page.request.delete(`/api/users/${user.id}`).catch(() => undefined);+ }+ }+});++test('registers, renames, authenticates with, and removes a passkey with MFA', async ({+ browser,+ page+}, testInfo) => {+ test.setTimeout(180_000);++ const suffix = Date.now().toString(36);+ const username = `e2e-passkey-${suffix}`;+ const password = 'E2e-passkey-user-123!';+ const renamedPasskey = `Virtual authenticator ${suffix}`;+ let user: AccountUser | null = null;+ let passkeyContext: BrowserContext | null = null;++ try {+ user = await readApiData<AccountUser>(+ await page.request.post('/api/users', {+ data: {+ username,+ password,+ displayName: 'Passkey Browser User',+ email: `${username}@example.test`+ }+ }),+ `Create passkey user ${username}`+ );+ await readApiData<unknown[]>(+ await page.request.put(`/api/users/${user.id}/role-assignments`, {+ data: { assignments: [{ roleId: 'role_viewer' }] }+ }),+ `Assign Viewer role to ${username}`+ );++ const webAuthnURL = new URL(String(testInfo.project.use.baseURL));+ webAuthnURL.hostname = 'localhost';+ passkeyContext = await browser.newContext({+ baseURL: webAuthnURL.origin,+ storageState: { cookies: [], origins: [] },+ extraHTTPHeaders: { 'X-Forwarded-For': '198.18.0.1' }+ });+ const passkeyPage = await passkeyContext.newPage();+ passkeyPage.setDefaultTimeout(15_000);+ const cdp = await passkeyContext.newCDPSession(passkeyPage);+ await cdp.send('WebAuthn.enable');+ const { authenticatorId } = await cdp.send('WebAuthn.addVirtualAuthenticator', {+ options: {+ protocol: 'ctap2',+ transport: 'internal',+ hasResidentKey: true,+ hasUserVerification: true,+ isUserVerified: true,+ automaticPresenceSimulation: true+ }+ });+ const pageErrors = installPageErrorCollector(passkeyPage);++ try {+ await login(passkeyPage, username, password);+ await passkeyPage.goto('/account');+ const addPasskeyButton = passkeyPage.getByRole('button', {+ name: 'Add passkey',+ exact: true+ });+ await expect(addPasskeyButton).toBeEnabled();+ const registrationResponsePromise = passkeyPage.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/auth/me/passkeys/register/finish'+ );+ await addPasskeyButton.click();+ const registered = await readApiData<Passkey>(+ await registrationResponsePromise,+ 'Register virtual passkey'+ );+ const passkeyRow = passkeyPage.locator('li').filter({ hasText: registered.name });+ await expect(passkeyRow).toBeVisible();++ await passkeyRow.getByRole('button', { name: 'Rename', exact: true }).click();+ await passkeyPage.getByRole('textbox', { name: 'Name', exact: true }).fill(renamedPasskey);+ await passkeyPage.getByRole('button', { name: 'Save', exact: true }).click();+ const stepUpDialog = passkeyPage.getByRole('dialog', { name: 'Confirm your identity' });+ await expect(stepUpDialog).toBeVisible();+ await stepUpDialog+ .getByPlaceholder('Enter your current password', { exact: true })+ .fill(password);+ const renameResponsePromise = passkeyPage.waitForResponse(+ (response) =>+ response.request().method() === 'PUT' &&+ new URL(response.url()).pathname === `/api/auth/me/passkeys/${registered.id}`+ );+ await stepUpDialog+ .getByRole('button', { name: 'Continue with password', exact: true })+ .click();+ const renamed = await readApiData<Passkey>(+ await renameResponsePromise,+ 'Rename virtual passkey'+ );+ expect(renamed.name).toBe(renamedPasskey);+ const renamedRow = passkeyPage.locator('li').filter({ hasText: renamedPasskey });+ await expect(renamedRow).toBeVisible();++ await passkeyPage.getByRole('button', { name: 'Enable MFA', exact: true }).click();+ const mfaDialog = passkeyPage.getByRole('dialog', { name: 'Passkey MFA' });+ await expect(mfaDialog).toBeVisible();+ const mfaEnableResponsePromise = passkeyPage.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/auth/me/mfa/enable'+ );+ await mfaDialog.getByRole('button', { name: 'Enable MFA', exact: true }).click();+ const recovery = await readApiData<{ codes: string[] }>(+ await mfaEnableResponsePromise,+ 'Enable passkey MFA'+ );+ expect(recovery.codes).toHaveLength(10);+ const recoveryCodes = passkeyPage+ .getByRole('heading', { name: 'Recovery codes', exact: true })+ .locator('..')+ .getByRole('listitem');+ await expect(recoveryCodes).toHaveCount(10);+ await passkeyPage.getByRole('button', { name: "I've saved it", exact: true }).click();++ const dangerZone = passkeyPage+ .locator('section')+ .filter({ has: passkeyPage.getByRole('heading', { name: 'Danger zone', exact: true }) });+ await dangerZone.getByRole('button', { name: 'Log out', exact: true }).click();+ await expect(passkeyPage).toHaveURL('/login');++ await passkeyPage.getByRole('button', { name: 'Passkey', exact: true }).click();+ const usePasskeyButton = passkeyPage.getByRole('button', {+ name: 'Use passkey',+ exact: true+ });+ if (await usePasskeyButton.isVisible().catch(() => false)) {+ await usePasskeyButton.click();+ }+ await expect(passkeyPage).toHaveURL('/dashboard');+ await expect(passkeyPage.locator('main').first()).toBeVisible();++ await passkeyPage.goto('/account');+ await passkeyPage.getByRole('button', { name: 'Disable MFA', exact: true }).click();+ const disableDialog = passkeyPage.getByRole('dialog', { name: 'Disable passkey MFA' });+ await expect(disableDialog).toBeVisible();+ await disableDialog.getByRole('button', { name: 'Disable MFA', exact: true }).click();+ const disableStepUp = passkeyPage.getByRole('dialog', { name: 'Confirm your identity' });+ await expect(disableStepUp).toBeVisible();+ const mfaDisableResponsePromise = passkeyPage.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/auth/me/mfa/disable'+ );+ await disableStepUp+ .getByRole('button', { name: 'Continue with passkey', exact: true })+ .click();+ expect((await mfaDisableResponsePromise).ok()).toBe(true);+ await expect(+ passkeyPage.getByRole('button', { name: 'Enable MFA', exact: true })+ ).toBeVisible();++ const finalPasskeyRow = passkeyPage.locator('li').filter({ hasText: renamedPasskey });+ await finalPasskeyRow.getByRole('button', { name: 'Delete', exact: true }).click();+ const deleteDialog = passkeyPage.getByRole('dialog', { name: 'Delete passkey' });+ const passkeyDeleteResponsePromise = passkeyPage.waitForResponse(+ (response) =>+ response.request().method() === 'DELETE' &&+ new URL(response.url()).pathname === `/api/auth/me/passkeys/${registered.id}`+ );+ await deleteDialog.getByRole('button', { name: 'Delete', exact: true }).click();+ expect((await passkeyDeleteResponsePromise).ok()).toBe(true);+ await expect(finalPasskeyRow).toHaveCount(0);+ } finally {+ pageErrors.stop();+ expect(+ pageErrors.errors,+ `Passkey journey page errors:\n${formatPageErrors(pageErrors.errors)}`+ ).toEqual([]);+ await cdp.send('WebAuthn.removeVirtualAuthenticator', { authenticatorId });+ await cdp.send('WebAuthn.disable');+ }+ } finally {+ await passkeyContext?.close();+ if (user) {+ await page.request.delete(`/api/users/${user.id}`).catch(() => undefined);+ }+ }+});diff --git a/tests/spec/activity-center.spec.ts b/tests/spec/activity-center.spec.tsindex 715c12b5e..294a1be4e 100644--- a/tests/spec/activity-center.spec.ts+++ b/tests/spec/activity-center.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Locator, type Page, type Route } from '@playwright/test';+import { test, expect, type Locator, type Page, type Route } from '../fixtures/test.fixture';type MockEnvironment = {id: string;diff --git a/tests/spec/api-keys.spec.ts b/tests/spec/api-keys.spec.tsindex 8c2d729ae..dcb225bd6 100644--- a/tests/spec/api-keys.spec.ts+++ b/tests/spec/api-keys.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';import { createTestApiKeys, deleteTestApiKeys } from '../utils/playwright.util';import { openRowActionsMenu } from '../utils/table-actions.util';diff --git a/tests/spec/backup-file-picker.spec.ts b/tests/spec/backup-file-picker.spec.tsindex 2830be5fc..9063b0358 100644--- a/tests/spec/backup-file-picker.spec.ts+++ b/tests/spec/backup-file-picker.spec.ts@@ -1,4 +1,4 @@-import { expect, test, type Locator, type Page, type Route } from '@playwright/test';+import { expect, test, type Locator, type Page, type Route } from '../fixtures/test.fixture';const VOLUME_NAME = 'backup-picker-e2e';const BACKUP_ID = 'backup-picker-snapshot';diff --git a/tests/spec/builds.spec.ts b/tests/spec/builds.spec.tsindex 8462988a2..3ae709a99 100644--- a/tests/spec/builds.spec.ts+++ b/tests/spec/builds.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Locator, type Page } from '@playwright/test';+import { test, expect, type Locator, type Page } from '../fixtures/test.fixture';const ROUTES = {page: '/images/builds'diff --git a/tests/spec/cli.spec.ts b/tests/spec/cli.spec.tsindex 9c3503529..378cc26b2 100644--- a/tests/spec/cli.spec.ts+++ b/tests/spec/cli.spec.ts@@ -38,7 +38,7 @@ type FederatedAuthOutput = {persisted: boolean;};-type JsonSmokeCommand = {+type JsonReadOnlyCommand = {name: string;args: string[];expectation: (value: unknown) => void;@@ -109,7 +109,7 @@ function expectJsonValue(value: unknown): void {expect(value === null || typeof value === 'object' || Array.isArray(value)).toBe(true);}-const readOnlyJsonSmokeCommands: JsonSmokeCommand[] = [+const readOnlyJsonCommands: JsonReadOnlyCommand[] = [{name: 'images list',args: ['--output', 'json', 'images', 'list', '--limit', '5'],@@ -526,7 +526,7 @@ test.describe('arcane-cli e2e', () => {});});- for (const command of readOnlyJsonSmokeCommands) {+ for (const command of readOnlyJsonCommands) {test(`${command.name} returns JSON`, async () => {await withConfig(async (config) => {const result = await runCommandJSON<unknown>(config.configPath, command.args);diff --git a/tests/spec/container-grouped-pagination.spec.ts b/tests/spec/container-grouped-pagination.spec.tsindex f7763b601..ad284cc99 100644--- a/tests/spec/container-grouped-pagination.spec.ts+++ b/tests/spec/container-grouped-pagination.spec.ts@@ -1,4 +1,4 @@-import { expect, test } from '@playwright/test';+import { expect, test } from '../fixtures/test.fixture';type MockContainer = {id: string;@@ -66,6 +66,7 @@ function buildContainersResponse(containers: MockContainer[], start: number, limtest('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');diff --git a/tests/spec/container-lifecycle.spec.ts b/tests/spec/container-lifecycle.spec.tsnew file mode 100644index 000000000..71d9ffba1--- /dev/null+++ b/tests/spec/container-lifecycle.spec.ts@@ -0,0 +1,743 @@+import { expect, test, type Locator, type Page, type Response } from '../fixtures/test.fixture';+import { readApiData } from '../utils/fetch.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()}`+ );+ }+}++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();+}++async function runSimpleContainerAction(+ page: Page,+ containerId: string,+ pathAction: string,+ buttonName: string,+ expectedActivityType: string+) {+ 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 page+ .getByRole('button', { name: buttonName, exact: true })+ .filter({ visible: true })+ .first()+ .click();+ 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+) {+ 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}`+ );+ 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) {+ 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) {+ 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+ .poll(async () => Object.keys((await getContainer(page, containerId)).networkSettings.networks))+ .not.toContain(networkName);+}++async function commitContainer(+ page: Page,+ containerId: string,+ containerName: string,+ repository: string+) {+ const floatingHeader = page+ .locator('div.fixed')+ .filter({ has: page.getByText(containerName, { exact: true }) });+ const commitButton = (await floatingHeader.isVisible())+ ? floatingHeader.getByRole('button', { name: 'Commit', exact: true })+ : page.getByRole('button', { name: 'Commit', exact: true }).filter({ visible: true }).first();+ await commitButton.click();+ const dialog = page.getByRole('dialog', { name: `Commit "${containerName}"` });+ 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');++ 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;+ expect(request.postDataJSON()).toMatchObject({+ repository,+ tag: 'e2e',+ comment: 'Playwright lifecycle snapshot',+ author: 'Arcane Playwright'+ });+ const result = await readApiData<CommitResult>(+ await responsePromise,+ `Commit container ${containerId}`+ );+ expect(result.id).toMatch(/^sha256:/);+ await expect(dialog).toBeHidden();+ return result;+}++async function editContainerThroughUI(page: Page, containerId: string, newContainerName: string) {+ const floatingEditLink = page+ .locator('div.fixed')+ .getByRole('link', { name: 'Edit', exact: true });+ const editLink = (await floatingEditLink.isVisible())+ ? floatingEditLink+ : page.getByRole('link', { name: 'Edit', exact: true }).filter({ visible: true }).first();+ await editLink.click();+ await expect(page).toHaveURL(`/containers/${containerId}/edit`);+ await expect(page.getByText('Applying changes recreates this container.')).toBeVisible();++ 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}`+ );+ 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) {+ await page+ .getByRole('button', { name: 'Redeploy', exact: true })+ .filter({ visible: true })+ .first()+ .click();+ 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}`+ );+ 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) {+ const generateResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/environments/0/containers/generate-compose'+ );+ const floatingConvertLink = page+ .locator('div.fixed')+ .getByRole('link', { name: 'Convert to Compose', exact: true });+ const convertLink = (await floatingConvertLink.isVisible())+ ? floatingConvertLink+ : page+ .getByRole('link', { name: 'Convert to Compose', exact: true })+ .filter({ visible: true })+ .first();+ await convertLink.click();+ 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}`+ );+ await expect(page).toHaveURL((url) => url.pathname === `/projects/${project.id}`);+ return project;+}++async function killContainerThroughUI(page: Page, containerId: string, containerName: string) {+ await page+ .getByRole('button', { name: 'Kill', exact: true })+ .filter({ visible: true })+ .first()+ .click();+ 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) {+ await page+ .getByRole('button', { name: 'Remove', exact: true })+ .filter({ visible: true })+ .first()+ .click();+ 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 }) => {+ 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;+ let convertedProjectId: string | null = null;+ let originalExperimentalSetting = 'false';++ try {+ 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 }>;+ originalExperimentalSetting =+ settings.find((setting) => setting.key === 'experimentalFeaturesEnabled')?.value ?? 'false';+ 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+ );+ 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+ );+ 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);+ 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);+ currentContainerId = redeployed.id;+ await expectContainerMissing(page, preRedeployId);+ await expectContainerStatus(page, currentContainerId, 'running');++ const convertedProject = await convertContainerToProject(+ page,+ currentContainerId,+ editedContainerName+ );+ convertedProjectId = convertedProject.id;+ 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;+ } finally {+ if (convertedProjectId) {+ await page.request+ .delete(`/api/environments/0/projects/${convertedProjectId}/destroy`, {+ data: { removeVolumes: false }+ })+ .catch(() => undefined);+ }+ if (currentContainerId) {+ await page.request+ .delete(`/api/environments/0/containers/${currentContainerId}?force=true&volumes=false`)+ .catch(() => undefined);+ }+ if (committedImageId) {+ await page.request+ .delete(`/api/environments/0/images/${encodeURIComponent(committedImageId)}?force=true`)+ .catch(() => undefined);+ }+ for (const networkName of [secondaryNetworkName, primaryNetworkName]) {+ await page.request+ .delete(`/api/environments/0/networks/${encodeURIComponent(networkName)}`)+ .catch(() => undefined);+ }+ await page.request+ .delete(`/api/environments/0/volumes/${encodeURIComponent(volumeName)}?force=true`)+ .catch(() => undefined);+ await updateExperimentalFeatures(page, originalExperimentalSetting).catch(() => undefined);+ }+});diff --git a/tests/spec/containers.spec.ts b/tests/spec/containers.spec.tsindex 1c50b490f..369bcf833 100644--- a/tests/spec/containers.spec.ts+++ b/tests/spec/containers.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';import { fetchContainersWithRetry, type Paginated } from '../utils/fetch.util';import { ContainerSummary } from 'types/containers.type';import { openRowActionsMenu } from '../utils/table-actions.util';@@ -370,3 +370,21 @@ test.describe('Containers Page network IP addresses', () => {await expect(row).toContainText('172.20.0.10');});});++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');+ });+});diff --git a/tests/spec/converter.spec.ts b/tests/spec/converter.spec.tsindex 1c927ab27..ade4814fc 100644--- a/tests/spec/converter.spec.ts+++ b/tests/spec/converter.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';type ConvertResponse = {success: boolean;diff --git a/tests/spec/customization.spec.ts b/tests/spec/customization.spec.tsnew file mode 100644index 000000000..c1de0c428--- /dev/null+++ b/tests/spec/customization.spec.ts@@ -0,0 +1,373 @@+import { expect, test, type Locator, type Page } from '../fixtures/test.fixture';+import { 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 setCodeMirrorValue(page: Page, editor: Locator, text: string) {+ const content = editor.locator('.cm-content').first();+ await expect(content).toBeVisible();+ await content.click({ position: { x: 10, y: 10 } });+ await content.press('ControlOrMeta+A');+ await page.keyboard.insertText(text);+}++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 expect(dialog).toBeVisible();+ 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 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(page, composeEditor, 'services:\n broken: [\n');+ await setCodeMirrorValue(page, envEditor, 'NOT VALID ENV');+ await expect(page.getByRole('button', { name: 'Create Template', exact: true })).toBeDisabled();++ await setCodeMirrorValue(page, composeEditor, composeContent);+ await setCodeMirrorValue(page, 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 page.request.delete(`/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 page.request+ .delete(`/api/environments/0/projects/${projectId}/destroy`, {+ data: { removeVolumes: false }+ })+ .catch(() => undefined);+ }+ if (templateId) {+ await page.request.delete(`/api/templates/${templateId}`).catch(() => undefined);+ }+ const variables = await listVariables(page).catch(() => []);+ for (const variable of variables.filter((candidate) => candidate.key.endsWith(suffix))) {+ await page.request.delete(`/api/variables/${variable.id}`).catch(() => undefined);+ }+ }+});diff --git a/tests/spec/dashboard-system-stats.spec.ts b/tests/spec/dashboard-system-stats.spec.tsindex 207d5a236..813f0e1a2 100644--- a/tests/spec/dashboard-system-stats.spec.ts+++ b/tests/spec/dashboard-system-stats.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';const defaultDashboardPath = '/dashboard';diff --git a/tests/spec/diagnostics-logs.spec.ts b/tests/spec/diagnostics-logs.spec.tsindex a907ecf61..5989dba15 100644--- a/tests/spec/diagnostics-logs.spec.ts+++ b/tests/spec/diagnostics-logs.spec.ts@@ -1,4 +1,4 @@-import { expect, test, type Page } from '@playwright/test';+import { expect, test, type Page } from '../fixtures/test.fixture';const duplicateLogEntry = {time: '2026-07-25T02:00:00.000Z',diff --git a/tests/spec/docker-runtime-identity.spec.ts b/tests/spec/docker-runtime-identity.spec.tsindex cb7701990..9fb7c580c 100644--- a/tests/spec/docker-runtime-identity.spec.ts+++ b/tests/spec/docker-runtime-identity.spec.ts@@ -1,4 +1,4 @@-import { test, expect } from '@playwright/test';+import { test, expect } from '../fixtures/test.fixture';import { execFileSync } from 'node:child_process';import fs from 'node:fs';import os from 'node:os';@@ -8,6 +8,57 @@ const IMAGE = process.env.ARCANE_RUNTIME_TEST_IMAGE || 'arcane:playwright-tests'const HELPER_IMAGE =process.env.ARCANE_RUNTIME_HELPER_IMAGE || 'public.ecr.aws/docker/library/alpine:3.20';const HEALTH_PATH = '/api/health';+const SOCKET_PROXY_IMAGE = 'wollomatic/socket-proxy:1.13.1';+const SOCKET_PROXY_ARGUMENTS = [+ '-listenip=0.0.0.0',+ '-allowfrom=0.0.0.0/0',+ '-allowGET=(/v[\\d.]+)?/_ping',+ '-allowGET=(/v[\\d.]+)?/events(/.*)?',+ '-allowGET=(/v[\\d.]+)?/version',+ '-allowGET=(/v[\\d.]+)?/containers(/.*)?',+ '-allowGET=(/v[\\d.]+)?/exec(/.*)?',+ '-allowGET=(/v[\\d.]+)?/images(/.*)?',+ '-allowGET=(/v[\\d.]+)?/info(/.*)?',+ '-allowGET=(/v[\\d.]+)?/networks(/.*)?',+ '-allowGET=(/v[\\d.]+)?/volumes(/.*)?',+ '-allowHEAD=(/v[\\d.]+)?/_ping',+ '-allowHEAD=(/v[\\d.]+)?/events(/.*)?',+ '-allowHEAD=(/v[\\d.]+)?/version',+ '-allowHEAD=(/v[\\d.]+)?/containers(/.*)?',+ '-allowHEAD=(/v[\\d.]+)?/exec(/.*)?',+ '-allowHEAD=(/v[\\d.]+)?/images(/.*)?',+ '-allowHEAD=(/v[\\d.]+)?/info(/.*)?',+ '-allowHEAD=(/v[\\d.]+)?/networks(/.*)?',+ '-allowHEAD=(/v[\\d.]+)?/volumes(/.*)?',+ '-allowPOST=(/v[\\d.]+)?/_ping',+ '-allowPOST=(/v[\\d.]+)?/events(/.*)?',+ '-allowPOST=(/v[\\d.]+)?/version',+ '-allowPOST=(/v[\\d.]+)?/containers(/.*)?',+ '-allowPOST=(/v[\\d.]+)?/exec(/.*)?',+ '-allowPOST=(/v[\\d.]+)?/images(/.*)?',+ '-allowPOST=(/v[\\d.]+)?/info(/.*)?',+ '-allowPOST=(/v[\\d.]+)?/networks(/.*)?',+ '-allowPOST=(/v[\\d.]+)?/volumes(/.*)?',+ '-allowPOST=(/v[\\d.]+)?/commit',+ '-allowPUT=(/v[\\d.]+)?/_ping',+ '-allowPUT=(/v[\\d.]+)?/events(/.*)?',+ '-allowPUT=(/v[\\d.]+)?/version',+ '-allowPUT=(/v[\\d.]+)?/containers(/.*)?',+ '-allowPUT=(/v[\\d.]+)?/exec(/.*)?',+ '-allowPUT=(/v[\\d.]+)?/images(/.*)?',+ '-allowPUT=(/v[\\d.]+)?/info(/.*)?',+ '-allowPUT=(/v[\\d.]+)?/networks(/.*)?',+ '-allowPUT=(/v[\\d.]+)?/volumes(/.*)?',+ '-allowDELETE=(/v[\\d.]+)?/_ping',+ '-allowDELETE=(/v[\\d.]+)?/events(/.*)?',+ '-allowDELETE=(/v[\\d.]+)?/version',+ '-allowDELETE=(/v[\\d.]+)?/containers(/.*)?',+ '-allowDELETE=(/v[\\d.]+)?/exec(/.*)?',+ '-allowDELETE=(/v[\\d.]+)?/images(/.*)?',+ '-allowDELETE=(/v[\\d.]+)?/info(/.*)?',+ '-allowDELETE=(/v[\\d.]+)?/networks(/.*)?',+ '-allowDELETE=(/v[\\d.]+)?/volumes(/.*)?'+];function docker(args: string[], options?: { stdio?: 'pipe' | 'inherit' }) {const output = execFileSync('docker', args, {@@ -83,6 +134,33 @@ function dockerLogs(container: string) {return docker(['logs', container]);}+function dockerProxyRequest(network: string, proxy: string, path: string) {+ return docker([+ 'run',+ '--rm',+ '--network',+ network,+ HELPER_IMAGE,+ 'wget',+ '-qO-',+ `http://${proxy}:2375${path}`+ ]);+}++function dockerProxyStatus(network: string, proxy: string, path: string) {+ const url = `http://${proxy}:2375${path}`;+ return docker([+ 'run',+ '--rm',+ '--network',+ network,+ HELPER_IMAGE,+ 'sh',+ '-lc',+ `wget -S -O /dev/null ${shellQuote(url)} 2>&1 | sed -n 's/.*HTTP\\/[0-9.]* \\([0-9][0-9][0-9]\\).*/\\1/p' | tail -n 1`+ ]);+}+function dockerFileStat(volumePath: string, filePath: string) {return docker(['run',@@ -421,31 +499,20 @@ test.describe.serial('Docker runtime identity', () => {proxyName,'--network',networkName,- '-e',- 'EVENTS=1',- '-e',- 'PING=1',- '-e',- 'VERSION=1',- '-e',- 'AUTH=0',- '-e',- 'POST=1',- '-e',- 'CONTAINERS=1',- '-e',- 'IMAGES=1',- '-e',- 'INFO=1',- '-e',- 'NETWORKS=1',- '-e',- 'VOLUMES=1',+ '--user',+ '0:0','-v','/var/run/docker.sock:/var/run/docker.sock:ro',- 'tecnativa/docker-socket-proxy:latest'+ SOCKET_PROXY_IMAGE,+ ...SOCKET_PROXY_ARGUMENTS]);- await new Promise((resolve) => setTimeout(resolve, 2_000));+ await expect+ .poll(() => dockerProxyRequest(networkName, proxyName, '/version'), {+ timeout: 30_000,+ intervals: [500, 1_000, 2_000]+ })+ .toContain('ApiVersion');+ expect(dockerProxyStatus(networkName, proxyName, '/v1.51/swarm')).toBe('403');dockerRunContainer([...defaultRunArgs(containerName, dataVolume),diff --git a/tests/spec/edge-agent.spec.ts b/tests/spec/edge-agent.spec.tsindex 840c9fac8..0ae69967f 100644--- a/tests/spec/edge-agent.spec.ts+++ b/tests/spec/edge-agent.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';const ROUTES = {environments: '/environments'diff --git a/tests/spec/environment-settings.spec.ts b/tests/spec/environment-settings.spec.tsindex c0e0f9f24..e0d4e2782 100644--- a/tests/spec/environment-settings.spec.ts+++ b/tests/spec/environment-settings.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Locator, type Page } from '@playwright/test';+import { test, expect, type Locator, type Page } from '../fixtures/test.fixture';const LOCAL_ENV_ID = '0';const NAME_PLACEHOLDER = 'My Lab Server';@@ -118,9 +118,6 @@ test.describe('Environment Settings UI', () => {await page.reload();await expect(dockerTab).toHaveAttribute('data-state', 'active');- await page.goBack();- await expect(page).toHaveURL(/\/settings$/);-await page.goto(`/environments/${LOCAL_ENV_ID}?source=e2e&tab=invalid#tab-state`);await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('storage');const canonicalUrl = new URL(page.url());@@ -136,19 +133,23 @@ test.describe('Environment Settings UI', () => {test.setTimeout(120_000); // 120 seconds timeout for this lengthy UI workflowconst envName = `settings-ui-${Date.now().toString().slice(-5)}`;const updatedName = `${envName}-updated`;+ let environmentId = '';try {await createDirectEnvironmentViaUI(page, envName);await page.getByRole('button', { name: envName, exact: true }).click();await expect(page).toHaveURL(/\/environments\/[^/?]+\?tab=[a-z]+$/);- const environmentId = new URL(page.url()).pathname.split('/').pop()!;+ environmentId = new URL(page.url()).pathname.split('/').pop()!;await renameEnvironmentInHeader(page, updatedName);await saveAndWaitForPut(page, `/api/environments/${environmentId}`);await page.reload();await expect(environmentTitleButton(page)).toHaveText(updatedName);} finally {+ if (environmentId) {+ await page.request.delete(`/api/environments/${environmentId}`).catch(() => undefined);+ }await deleteEnvironmentViaUI(page, updatedName);await deleteEnvironmentViaUI(page, envName);}diff --git a/tests/spec/environment-switch-isolation.spec.ts b/tests/spec/environment-switch-isolation.spec.tsindex f6a46eb9a..ba1c6f131 100644--- a/tests/spec/environment-switch-isolation.spec.ts+++ b/tests/spec/environment-switch-isolation.spec.ts@@ -1,4 +1,4 @@-import { expect, test, type Page, type Route } from '@playwright/test';+import { expect, test, type Page, type Route } from '../fixtures/test.fixture';const localEnvironment = {id: '0',@@ -189,7 +189,11 @@ test.describe('Environment switch isolation', () => {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 }) => {+ test('does not restore local rows when the remote request fails', async ({+ page,+ pageErrorGuard+ }) => {+ pageErrorGuard.allow('remote unavailable');await mockEnvironmentCatalog(page);await page.context()diff --git a/tests/spec/image-updates.spec.ts b/tests/spec/image-updates.spec.tsindex 1b5731810..d0cedf806 100644--- a/tests/spec/image-updates.spec.ts+++ b/tests/spec/image-updates.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Locator, type Page } from '@playwright/test';+import { test, expect, type Locator, type Page } from '../fixtures/test.fixture';import { fetchImagesWithRetry } from '../utils/fetch.util';const ROUTES = {diff --git a/tests/spec/images.spec.ts b/tests/spec/images.spec.tsindex a6f672616..6a48908cf 100644--- a/tests/spec/images.spec.ts+++ b/tests/spec/images.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';import { fetchImageCountsWithRetry, fetchImagesWithRetry } from '../utils/fetch.util';import { ImageUsageCounts } from 'types/image.type';import { openRowActionsMenu } from '../utils/table-actions.util';@@ -147,13 +147,28 @@ test.describe('Images Page', () => {test('should align /images/counts with usage derived from /images list', async ({ page }) => {await navigateToImages(page);- const allImages = await fetchAllImagesForUsage(page);- const derivedInUse = allImages.filter((img) => !!img.inUse).length;- const derivedUnused = allImages.length - derivedInUse;-- expect(imageCounts.totalImages).toBe(allImages.length);- expect(imageCounts.imagesInuse).toBe(derivedInUse);- expect(imageCounts.imagesUnused).toBe(derivedUnused);+ 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 });});test('should display the image table when images exist', async ({ page }) => {diff --git a/tests/spec/network.spec.ts b/tests/spec/network.spec.tsindex 7c84f9ad9..b59bd15a5 100644--- a/tests/spec/network.spec.ts+++ b/tests/spec/network.spec.ts@@ -1,21 +1,32 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';import { fetchNetworksCountsWithRetry } from '../utils/fetch.util';+import authUtil from '../utils/auth.util';async function navigateToNetworks(page: Page) {await page.goto('/networks');await page.waitForLoadState('load');+ await expect(page.getByRole('heading', { level: 1, name: 'Networks' })).toBeVisible();+}++async function ensureAuthenticated(page: Page) {+ const currentUserResponse = await page.request.get('/api/auth/me');+ if (!currentUserResponse.ok()) {+ await authUtil.login(page);+ await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();+ }}test.beforeEach(async ({ page }) => {+ await ensureAuthenticated(page);await navigateToNetworks(page);});async function createNetworkViaUI(page: Page, networkName: string) {- await navigateToNetworks(page);await page.getByRole('button', { name: 'Create Network' }).first().click();- await expect(page.getByRole('dialog')).toBeVisible();- await expect(page.getByRole('heading', { name: 'Create New Network' })).toBeVisible();- await page.getByLabel('Network Name *').fill(networkName);+ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();+ await expect(dialog.getByRole('heading', { name: 'Create New Network' })).toBeVisible();+ await dialog.getByLabel('Network Name *').fill(networkName);const createRequest = page.waitForResponse((response) => {@@ -26,7 +37,7 @@ async function createNetworkViaUI(page: Page, networkName: string) {{ timeout: 15000 });- await page.getByRole('dialog').getByRole('button', { name: 'Create Network' }).click();+ await dialog.getByRole('button', { name: 'Create Network' }).click();const createResponse = await createRequest;const responseBody = await createResponse.json().catch(() => undefined);if (!createResponse.ok()) {@@ -35,11 +46,14 @@ async function createNetworkViaUI(page: Page, networkName: string) {`Failed to create network ${networkName}: ${createResponse.status()} ${responseText}`);}+ await expect(dialog).toBeHidden();+ await expect(page.getByText(networkName, { exact: true }).first()).toBeVisible();return responseBody?.data?.id ?? networkName;}async function createNetworkViaApi(page: Page, networkName: string) {+ await page.goto('about:blank');const response = await page.request.post('/api/environments/0/networks', {data: {name: networkName,@@ -77,6 +91,7 @@ async function findNetworkRow(page: Page, networkName: string, maxRetries = 10)}async function removeNetworkViaApi(page: Page, networkName: string) {+ await page.goto('about:blank');await page.request.delete(`/api/environments/0/networks/${encodeURIComponent(networkName)}`).catch(() => undefined);@@ -115,7 +130,7 @@ test.describe('Networks Page', () => {}});- test('Open Create Network sheet', async ({ page }) => {+ test('@cross-browser creates and removes a network through the UI', async ({ page }) => {const networkName = `test-network-${Date.now()}`;try {const networkId = await createNetworkViaUI(page, networkName);@@ -123,6 +138,21 @@ test.describe('Networks Page', () => {`/api/environments/0/networks/${encodeURIComponent(networkId)}`);expect(response.ok()).toBe(true);++ await page.goto(`/networks/${encodeURIComponent(networkId)}`);+ await expect(page.getByRole('heading', { name: networkName, level: 1 })).toBeVisible();+ await page.getByRole('button', { name: 'Remove', exact: true }).click();+ await page.getByRole('dialog').getByRole('button', { name: 'Remove', exact: true }).click();+ await expect(page).toHaveURL('/networks');+ await expect(page.getByRole('heading', { name: 'Networks', level: 1 })).toBeVisible();+ await expect+ .poll(async () => {+ const removed = await page.request.get(+ `/api/environments/0/networks/${encodeURIComponent(networkId)}`+ );+ return removed.status();+ })+ .toBe(404);} finally {await removeNetworkViaApi(page, networkName);}diff --git a/tests/spec/project.spec.ts b/tests/spec/project.spec.tsindex cfe00813b..255a69075 100644--- a/tests/spec/project.spec.ts+++ b/tests/spec/project.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Locator, type Page, type Response } from '@playwright/test';+import { test, expect, type Locator, type Page, type Response } from '../fixtures/test.fixture';import { fetchProjectCountsWithRetry, fetchProjectsWithRetry } from '../utils/fetch.util';import type { Activity } from '../types/activity.type';import { Project, ProjectStatusCounts } from 'types/project.type';@@ -285,15 +285,19 @@ let projectCounts: ProjectStatusCounts = {archivedProjects: 0};+function getRequiredGitOpsProject(): Project & { id: string } {+ const project = realProjects.find((candidate) => candidate.gitOpsManagedBy);+ expect(project, 'GitOps setup must provide a managed project').toBeDefined();+ expect(project!.id, 'GitOps setup project must have an ID').toBeTruthy();+ return project as Project & { id: string };+}+test.beforeEach(async ({ page }) => {await navigateToProjects(page);- try {- realProjects = await fetchProjectsWithRetry(page);- projectCounts = await fetchProjectCountsWithRetry(page);- } catch (error) {- realProjects = [];- }+ realProjects = await fetchProjectsWithRetry(page);+ projectCounts = await fetchProjectCountsWithRetry(page);+ expect(realProjects.length, 'Project setup must provide at least one project').toBeGreaterThan(0);});test.describe('Projects Page', () => {@@ -1013,17 +1017,14 @@ test.describe('New Compose Project Page', () => {test.describe('GitOps Managed Project', () => {test('should navigate back to gitops when opened from the git syncs page', async ({ page }) => {- const gitOpsProject = realProjects.find((project) => project.gitOpsManagedBy);- test.skip(!gitOpsProject, 'No GitOps project links found');+ const gitOpsProject = getRequiredGitOpsProject();await page.goto('/environments/0/gitops');await page.waitForLoadState('load');- const projectLink = page.getByRole('link', {- name: gitOpsProject!.name,- exact: true- });+ const projectLink = page.locator(`a[href^='/projects/${gitOpsProject.id}?from=gitops']`);+ await expect(projectLink).toBeVisible();await projectLink.click();await page.waitForURL(/\/projects\/.+/, { timeout: 10000 });@@ -1036,10 +1037,9 @@ test.describe('GitOps Managed Project', () => {});test('should show read-only alert when project is GitOps managed', async ({ page }) => {- const gitOpsProject = realProjects.find((p) => p.gitOpsManagedBy);- test.skip(!gitOpsProject, 'No GitOps-managed projects found');+ const gitOpsProject = getRequiredGitOpsProject();- await page.goto(`/projects/${gitOpsProject!.id}`);+ await page.goto(`/projects/${gitOpsProject.id}`);await page.waitForLoadState('load');// Navigate to Configuration tab@@ -1058,10 +1058,9 @@ test.describe('GitOps Managed Project', () => {});test('should display Sync from Git button when GitOps managed', async ({ page }) => {- const gitOpsProject = realProjects.find((p) => p.gitOpsManagedBy);- test.skip(!gitOpsProject, 'No GitOps-managed projects found');+ const gitOpsProject = getRequiredGitOpsProject();- await page.goto(`/projects/${gitOpsProject!.id}`);+ await page.goto(`/projects/${gitOpsProject.id}`);await page.waitForLoadState('load');const configTab = page.getByRole('tab', { name: 'Configuration', exact: true });@@ -1073,34 +1072,33 @@ test.describe('GitOps Managed Project', () => {});test('should show last sync commit when GitOps managed', async ({ page }) => {- const gitOpsProject = realProjects.find((p) => p.gitOpsManagedBy && p.lastSyncCommit);- test.skip(!gitOpsProject, 'No GitOps-managed projects with sync commit found');+ const gitOpsProject = getRequiredGitOpsProject();+ const projectDetail = await fetchProjectDetail(page, gitOpsProject.id);+ expect(projectDetail?.lastSyncCommit, 'GitOps setup must record a sync commit').toBeTruthy();- await page.goto(`/projects/${gitOpsProject!.id}`);+ await page.goto(`/projects/${gitOpsProject.id}`);await page.waitForLoadState('load');// The commit hash should be visible somewhere on the page- const commitHash = gitOpsProject!.lastSyncCommit!.substring(0, 7);+ const commitHash = projectDetail!.lastSyncCommit!.substring(0, 7);await expect(page.getByText(commitHash)).toBeVisible();});test('should disable name editing when GitOps managed', async ({ page }) => {- const gitOpsProject = realProjects.find((p) => p.gitOpsManagedBy);- test.skip(!gitOpsProject, 'No GitOps-managed projects found');+ const gitOpsProject = getRequiredGitOpsProject();- await page.goto(`/projects/${gitOpsProject!.id}`);+ await page.goto(`/projects/${gitOpsProject.id}`);await page.waitForLoadState('load');// The name button should be disabled for GitOps-managed projects- const nameButton = page.getByRole('button', { name: gitOpsProject!.name });+ const nameButton = page.getByRole('button', { name: gitOpsProject.name });await expect(nameButton).toBeDisabled();});test('should have compose editor in read-only mode when GitOps managed', async ({ page }) => {- const gitOpsProject = realProjects.find((p) => p.gitOpsManagedBy);- test.skip(!gitOpsProject, 'No GitOps-managed projects found');+ const gitOpsProject = getRequiredGitOpsProject();- await page.goto(`/projects/${gitOpsProject!.id}`);+ await page.goto(`/projects/${gitOpsProject.id}`);await page.waitForLoadState('load');const configTab = page.getByRole('tab', { name: 'Configuration', exact: true });@@ -1119,10 +1117,9 @@ test.describe('GitOps Managed Project', () => {test('should allow editing env editor when GitOps managed in classic and tree view', async ({page}) => {- const gitOpsProject = realProjects.find((p) => p.gitOpsManagedBy);- test.skip(!gitOpsProject, 'No GitOps-managed projects found');+ const gitOpsProject = getRequiredGitOpsProject();- await page.goto(`/projects/${gitOpsProject!.id}`);+ await page.goto(`/projects/${gitOpsProject.id}`);await page.waitForLoadState('load');const configTab = page.getByRole('tab', { name: 'Configuration', exact: true });diff --git a/tests/spec/rbac.spec.ts b/tests/spec/rbac.spec.tsnew file mode 100644index 000000000..9a360527e--- /dev/null+++ b/tests/spec/rbac.spec.ts@@ -0,0 +1,511 @@+import {+ expect,+ formatPageErrors,+ installPageErrorCollector,+ test,+ type BrowserContext,+ type Page+} from '../fixtures/test.fixture';+import { readApiData } from '../utils/fetch.util';+import { openRowActionsMenu } from '../utils/table-actions.util';++type TestRole = {+ id: string;+ name: string;+ description?: string;+ permissions: string[];+ builtIn: boolean;+};++type TestUser = {+ id: string;+ username: string;+ displayName?: string;+ permissionsByEnv: Record<string, string[]>;+};++type TestEnvironment = {+ id: string;+ name: string;+ apiUrl: string;+ enabled: boolean;+};++async function selectPermission(page: Page, permission: string) {+ const search = page.getByPlaceholder('Filter permissions…');+ await search.fill(permission);+ const checkbox = page.locator(`[id="perm-${permission}"]`);+ await expect(checkbox).toBeVisible();+ await checkbox.click();+}++async function createRoleThroughUI(page: Page, name: string, permissions: string[]) {+ await page.goto('/settings/roles/new');+ await page.getByLabel('Name', { exact: true }).fill(name);+ await page+ .getByLabel('Description', { exact: true })+ .fill('Playwright environment-scoped reader');++ for (const permission of permissions) {+ await selectPermission(page, permission);+ }++ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' && new URL(response.url()).pathname === '/api/roles'+ );+ await page+ .locator('form')+ .getByRole('button', { name: /Create Role/ })+ .click();+ const role = await readApiData<TestRole>(await responsePromise, `Create role ${name}`);+ await expect(page).toHaveURL('/settings/roles');+ return role;+}++async function editRoleThroughUI(page: Page, role: TestRole) {+ await page.goto('/settings/roles');+ await page.getByPlaceholder('Search…').fill(role.name);+ const row = page.getByRole('row').filter({ hasText: role.name });+ const menu = await openRowActionsMenu(page, row);+ await menu.getByRole('menuitem', { name: 'Edit', exact: true }).click();++ await expect(page).toHaveURL(`/settings/roles/${role.id}`);+ await page+ .getByLabel('Description', { exact: true })+ .fill('Updated by the Playwright RBAC journey');++ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'PUT' &&+ new URL(response.url()).pathname === `/api/roles/${role.id}`+ );+ await page.getByRole('button', { name: 'Save changes', exact: true }).click();+ const updated = await readApiData<TestRole>(await responsePromise, `Update role ${role.name}`);+ await expect(page).toHaveURL('/settings/roles');+ expect(updated.description).toBe('Updated by the Playwright RBAC journey');+}++async function cloneViewerRoleThroughUI(page: Page) {+ await page.goto('/settings/roles/role_viewer');+ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' && new URL(response.url()).pathname === '/api/roles'+ );+ await page.getByRole('button', { name: 'Clone as custom role', exact: true }).click();+ const cloned = await readApiData<TestRole>(await responsePromise, 'Clone the Viewer role');+ await expect(page).toHaveURL(`/settings/roles/${cloned.id}`);+ expect(cloned.builtIn).toBe(false);+ expect(cloned.permissions.length).toBeGreaterThan(0);+ return cloned;+}++async function selectUserAssignment(+ page: Page,+ dialog: ReturnType<Page['getByRole']>,+ index: number,+ environmentName: string,+ roleName: string+) {+ const environmentSelect = dialog+ .getByRole('button', { name: 'Environment', exact: true })+ .nth(index);+ await environmentSelect.click();+ await page.getByRole('option', { name: environmentName, exact: true }).click();++ const roleSelect = dialog.getByRole('button', { name: 'Role', exact: true }).nth(index);+ await roleSelect.click();+ await page.getByRole('option').filter({ hasText: roleName }).click();+}++async function createRestrictedUserThroughUI(+ page: Page,+ username: string,+ password: string,+ localEnvironmentName: string,+ localRoleName: string,+ remoteEnvironmentName: string,+ remoteRoleName: string+) {+ await page.goto('/settings/users');+ await page.getByRole('button', { name: 'Create User', exact: true }).click();+ const dialog = page.getByRole('dialog', { name: 'Create New User' });+ await expect(dialog).toBeVisible();++ await dialog.getByLabel('Username', { exact: true }).fill(username);+ await dialog.getByLabel('Password *', { exact: true }).fill(password);+ await dialog.getByLabel('Display Name', { exact: true }).fill('Scoped Browser User');+ await dialog.getByLabel('Email', { exact: true }).fill(`${username}@example.test`);++ await dialog.getByRole('button', { name: 'Add assignment', exact: true }).click();+ await selectUserAssignment(page, dialog, 0, localEnvironmentName, localRoleName);+ await dialog.getByRole('button', { name: 'Add assignment', exact: true }).click();+ await selectUserAssignment(page, dialog, 1, remoteEnvironmentName, remoteRoleName);++ const createResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' && new URL(response.url()).pathname === '/api/users'+ );+ const assignmentsResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'PUT' &&+ /^\/api\/users\/[^/]+\/role-assignments$/.test(new URL(response.url()).pathname)+ );+ await dialog.getByRole('button', { name: 'Create User', exact: true }).click();++ const user = await readApiData<TestUser>(await createResponsePromise, `Create user ${username}`);+ await readApiData<unknown[]>(await assignmentsResponsePromise, `Assign roles to ${username}`);+ await expect(dialog).toBeHidden();+ return user;+}++async function editUserThroughUI(page: Page, user: TestUser) {+ await page.goto('/settings/users');+ await page.getByPlaceholder('Search…').fill(user.username);+ const row = page.getByRole('row').filter({ hasText: user.username });+ const menu = await openRowActionsMenu(page, row);+ await menu.getByRole('menuitem', { name: 'Edit', exact: true }).click();++ const dialog = page.getByRole('dialog', { name: 'Edit User' });+ await expect(dialog).toBeVisible();+ await dialog.getByLabel('Display Name', { exact: true }).fill('Scoped Browser User Updated');++ const updateResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'PUT' &&+ new URL(response.url()).pathname === `/api/users/${user.id}`+ );+ const assignmentsResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'PUT' &&+ new URL(response.url()).pathname === `/api/users/${user.id}/role-assignments`+ );+ await dialog.getByRole('button', { name: 'Save Changes', exact: true }).click();++ const updated = await readApiData<TestUser>(+ await updateResponsePromise,+ `Update user ${user.username}`+ );+ await readApiData<unknown[]>(+ await assignmentsResponsePromise,+ `Retain roles for ${user.username}`+ );+ await expect(dialog).toBeHidden();+ expect(updated.displayName).toBe('Scoped Browser User Updated');+}++async function loginAs(page: Page, username: string, password: string, expectedPath: string) {+ await page.goto('/login');+ await page.getByLabel('Username').fill(username);+ await page.getByLabel('Password').fill(password);+ await page.getByRole('button', { name: 'Sign in to Arcane', exact: true }).click();+ await expect(page).toHaveURL(expectedPath, { timeout: 15_000 });+}++async function deleteUserThroughUI(page: Page, user: TestUser) {+ await page.goto('/settings/users');+ await page.getByPlaceholder('Search…').fill(user.username);+ const row = page.getByRole('row').filter({ hasText: user.username });+ const menu = await openRowActionsMenu(page, row);+ await menu.getByRole('menuitem', { name: 'Delete', exact: true }).click();++ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'DELETE' &&+ new URL(response.url()).pathname === `/api/users/${user.id}`+ );+ await page.getByRole('dialog').getByRole('button', { name: 'Delete', exact: true }).click();+ await readApiData<{ message: string }>(await responsePromise, `Delete user ${user.username}`);+ await expect(row).toHaveCount(0);+}++async function deleteRoleThroughUI(page: Page, role: TestRole) {+ await page.goto('/settings/roles');+ await page.getByPlaceholder('Search…').fill(role.name);+ const row = page.getByRole('row').filter({ hasText: role.name });+ const menu = await openRowActionsMenu(page, row);+ await menu.getByRole('menuitem', { name: 'Delete', exact: true }).click();++ const responsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'DELETE' &&+ new URL(response.url()).pathname === `/api/roles/${role.id}`+ );+ await page.getByRole('dialog').getByRole('button', { name: 'Delete', exact: true }).click();+ await readApiData<{ message: string }>(await responsePromise, `Delete role ${role.name}`);+ await expect(row).toHaveCount(0);+}++test('administers scoped identities and enforces their browser access immediately', async ({+ browser,+ page+}, testInfo) => {+ test.setTimeout(180_000);+ page.setDefaultTimeout(10_000);+ page.setDefaultNavigationTimeout(15_000);++ const suffix = Date.now().toString(36);+ const localRoleName = `E2E Container Reader ${suffix}`;+ const remoteRoleName = `E2E Project Reader ${suffix}`;+ const remoteEnvironmentName = `E2E Scoped Remote ${suffix}`;+ const username = `e2e-scoped-${suffix}`;+ const noAccessUsername = `e2e-no-access-${suffix}`;+ const password = 'E2e-RBAC-user-123!';++ let localRole: TestRole | null = null;+ let remoteRole: TestRole | null = null;+ let clonedRole: TestRole | null = null;+ let remoteEnvironment: TestEnvironment | null = null;+ let restrictedUser: TestUser | null = null;+ let noAccessUser: TestUser | null = null;+ let restrictedContext: BrowserContext | null = null;+ let noAccessContext: BrowserContext | null = null;++ try {+ const localEnvironment = await readApiData<TestEnvironment>(+ await page.request.get('/api/environments/0'),+ 'Get local environment'+ );++ localRole = await createRoleThroughUI(page, localRoleName, [+ 'containers:list',+ 'containers:read'+ ]);+ await editRoleThroughUI(page, localRole);+ clonedRole = await cloneViewerRoleThroughUI(page);++ remoteRole = await readApiData<TestRole>(+ await page.request.post('/api/roles', {+ data: {+ name: remoteRoleName,+ description: 'Playwright remote project reader',+ permissions: ['projects:list', 'projects:read']+ }+ }),+ `Create role ${remoteRoleName}`+ );++ remoteEnvironment = await readApiData<TestEnvironment>(+ await page.request.post('/api/environments', {+ data: {+ name: remoteEnvironmentName,+ apiUrl: 'http://rbac-remote.invalid:3552',+ enabled: true,+ isEdge: false+ }+ }),+ `Create environment ${remoteEnvironmentName}`+ );++ restrictedUser = await createRestrictedUserThroughUI(+ page,+ username,+ password,+ localEnvironment.name,+ localRole.name,+ remoteEnvironment.name,+ remoteRole.name+ );+ await editUserThroughUI(page, restrictedUser);++ noAccessUser = await readApiData<TestUser>(+ await page.request.post('/api/users', {+ data: {+ username: noAccessUsername,+ password,+ displayName: 'No Access Browser User'+ }+ }),+ `Create user ${noAccessUsername}`+ );++ const baseURL = String(testInfo.project.use.baseURL);+ restrictedContext = await browser.newContext({+ baseURL,+ storageState: { cookies: [], origins: [] }+ });+ const remoteID = remoteEnvironment.id;+ await restrictedContext.route(`**/api/environments/${remoteID}/projects**`, async (route) => {+ const pathname = new URL(route.request().url()).pathname;+ if (pathname.endsWith('/counts')) {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: {+ runningProjects: 0,+ stoppedProjects: 0,+ totalProjects: 0,+ archivedProjects: 0+ }+ })+ });+ return;+ }++ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ success: true,+ data: [],+ counts: {+ runningProjects: 0,+ stoppedProjects: 0,+ totalProjects: 0,+ archivedProjects: 0+ },+ pagination: {+ currentPage: 1,+ totalPages: 0,+ totalItems: 0,+ itemsPerPage: 20+ }+ })+ });+ });+ await restrictedContext.route(`**/api/environments/${remoteID}/settings`, async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ success: true, data: {} })+ });+ });++ const restrictedPage = await restrictedContext.newPage();+ restrictedPage.setDefaultTimeout(10_000);+ const restrictedErrors = installPageErrorCollector(restrictedPage);+ try {+ await loginAs(restrictedPage, username, password, '/containers');++ await expect(+ restrictedPage.getByRole('link', { name: 'Containers', exact: true })+ ).toBeVisible();+ await expect(restrictedPage.getByRole('link', { name: 'Projects', exact: true })).toHaveCount(+ 0+ );+ await expect(+ restrictedPage.getByRole('link', { name: 'Dashboard', exact: true })+ ).toHaveCount(0);+ await expect(restrictedPage.getByRole('link', { name: 'Settings', exact: true })).toHaveCount(+ 0+ );+ await expect(+ restrictedPage.getByRole('button', { name: 'Create Container', exact: true })+ ).toHaveCount(0);++ const containerRow = restrictedPage+ .getByRole('row')+ .filter({ has: restrictedPage.getByRole('button', { name: 'Open menu', exact: true }) })+ .first();+ const containerMenu = await openRowActionsMenu(restrictedPage, containerRow);+ await expect(+ containerMenu.getByRole('menuitem', { name: 'Inspect', exact: true })+ ).toBeVisible();+ for (const action of ['Start', 'Stop', 'Restart', 'Remove']) {+ await expect(+ containerMenu.getByRole('menuitem', { name: action, exact: true })+ ).toHaveCount(0);+ }+ await restrictedPage.keyboard.press('Escape');++ await restrictedPage.goto('/settings/backups');+ await expect(restrictedPage).toHaveURL('/containers');+ await restrictedPage.goto('/projects');+ await expect(restrictedPage).toHaveURL('/containers');++ const currentUser = await readApiData<TestUser>(+ await restrictedPage.request.get('/api/auth/me'),+ 'Get restricted current user'+ );+ expect(currentUser.permissionsByEnv['0']).toEqual(+ expect.arrayContaining(['containers:list', 'containers:read'])+ );+ expect(currentUser.permissionsByEnv[remoteID]).toEqual(+ expect.arrayContaining(['projects:list', 'projects:read'])+ );+ expect(currentUser.permissionsByEnv.global ?? []).toEqual([]);++ await restrictedPage+ .getByRole('button')+ .filter({ hasText: localEnvironment.name })+ .first()+ .click();+ const environmentDialog = restrictedPage.getByRole('dialog', {+ name: 'Select Environment'+ });+ await expect(environmentDialog).toBeVisible();+ await environmentDialog+ .getByRole('button')+ .filter({ hasText: remoteEnvironment.name })+ .first()+ .click();++ await expect(restrictedPage).toHaveURL('/projects');+ await expect(+ restrictedPage.getByRole('link', { name: 'Projects', exact: true })+ ).toBeVisible();+ await expect(+ restrictedPage.getByRole('link', { name: 'Containers', exact: true })+ ).toHaveCount(0);+ } finally {+ restrictedErrors.stop();+ expect(+ restrictedErrors.errors,+ `Restricted user page errors:\n${formatPageErrors(restrictedErrors.errors)}`+ ).toEqual([]);+ }++ noAccessContext = await browser.newContext({+ baseURL,+ storageState: { cookies: [], origins: [] }+ });+ const noAccessPage = await noAccessContext.newPage();+ noAccessPage.setDefaultTimeout(10_000);+ const noAccessErrors = installPageErrorCollector(noAccessPage);+ try {+ await loginAs(noAccessPage, noAccessUsername, password, '/no-access');+ await expect(+ noAccessPage.getByRole('heading', { name: "You don't have access to anything yet" })+ ).toBeVisible();+ await expect(noAccessPage.getByRole('link')).toHaveCount(0);+ } finally {+ noAccessErrors.stop();+ expect(+ noAccessErrors.errors,+ `No-access user page errors:\n${formatPageErrors(noAccessErrors.errors)}`+ ).toEqual([]);+ }++ await restrictedContext.close();+ restrictedContext = null;+ await noAccessContext.close();+ noAccessContext = null;++ await deleteUserThroughUI(page, restrictedUser);+ restrictedUser = null;+ await deleteRoleThroughUI(page, clonedRole);+ clonedRole = null;+ await deleteRoleThroughUI(page, localRole);+ localRole = null;+ } finally {+ await restrictedContext?.close();+ await noAccessContext?.close();++ if (restrictedUser) {+ await page.request.delete(`/api/users/${restrictedUser.id}`).catch(() => undefined);+ }+ if (noAccessUser) {+ await page.request.delete(`/api/users/${noAccessUser.id}`).catch(() => undefined);+ }+ for (const role of [clonedRole, localRole, remoteRole]) {+ if (role) {+ await page.request.delete(`/api/roles/${role.id}`).catch(() => undefined);+ }+ }+ if (remoteEnvironment) {+ await page.request.delete(`/api/environments/${remoteEnvironment.id}`).catch(() => undefined);+ }+ }+});diff --git a/tests/spec/registries.spec.ts b/tests/spec/registries.spec.tsindex 5711db707..8a6ca74c3 100644--- a/tests/spec/registries.spec.ts+++ b/tests/spec/registries.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';import { openRowActionsMenu } from '../utils/table-actions.util';const route = '/customize/registries';diff --git a/tests/spec/responsive-browser.spec.ts b/tests/spec/responsive-browser.spec.tsnew file mode 100644index 000000000..4b1452574--- /dev/null+++ b/tests/spec/responsive-browser.spec.ts@@ -0,0 +1,51 @@+import { expect, test } from '../fixtures/test.fixture';++test('navigation matches the configured mobile or tablet viewport', async ({ page }, testInfo) => {+ await page.goto('/dashboard');++ if (testInfo.project.name === 'mobile-chromium') {+ await expect(page.getByTestId(/mobile-(floating|docked)-nav/)).toBeVisible();+ await expect(page.locator('[data-slot="sidebar"]')).toHaveCount(0);++ await page.getByTestId('mobile-nav-open').click();+ const navigationSheet = page.getByTestId('mobile-nav-sheet');+ await expect(navigationSheet).toBeVisible();+ await navigationSheet.getByRole('link', { name: 'Containers', exact: true }).click();+ await expect(page).toHaveURL('/containers');+ await expect(page.getByTestId(/mobile-(floating|docked)-nav/)).toBeVisible();+ } else {+ const sidebar = page.locator('[data-slot="sidebar"]');+ await expect(sidebar).toBeVisible();+ await expect(sidebar).toHaveAttribute('data-state', 'collapsed');+ await expect(page.getByTestId(/mobile-(floating|docked)-nav/)).toHaveCount(0);++ await page.locator('a[href="/containers"]').filter({ visible: true }).first().click();+ await expect(page).toHaveURL('/containers');+ await expect(sidebar).toHaveAttribute('data-state', 'collapsed');+ }++ expect(+ await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth),+ 'The app shell must not introduce horizontal document overflow'+ ).toBe(true);+});++test('resource dialog stays usable in the configured viewport', async ({ page }) => {+ await page.goto('/networks');+ const createButton = page.getByRole('button', { name: 'Create Network', exact: true }).first();+ if (await createButton.isVisible().catch(() => false)) {+ await createButton.click();+ } else {+ await page.getByRole('button', { name: 'More actions', exact: true }).click();+ await page.getByRole('menuitem', { name: 'Create Network', exact: true }).click();+ }++ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();+ await expect(dialog.getByRole('heading', { name: 'Create New Network' })).toBeVisible();+ await expect(dialog.getByLabel('Network Name *')).toBeInViewport();+ await expect(dialog.getByRole('button', { name: 'Create Network' })).toBeInViewport();++ await dialog.getByRole('button', { name: 'Cancel' }).click();+ await expect(dialog).toBeHidden();+});diff --git a/tests/spec/route-mount.spec.ts b/tests/spec/route-mount.spec.tsnew file mode 100644index 000000000..5cbab7e6e--- /dev/null+++ b/tests/spec/route-mount.spec.ts@@ -0,0 +1,79 @@+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/s3-backups.spec.ts b/tests/spec/s3-backups.spec.tsindex 1295a7425..06e6830a0 100644--- a/tests/spec/s3-backups.spec.ts+++ b/tests/spec/s3-backups.spec.ts@@ -1,4 +1,5 @@-import { test, expect, type Page } from '@playwright/test';+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.@@ -176,6 +177,100 @@ async function createBackupViaApi(}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 {diff --git a/tests/spec/security.spec.ts b/tests/spec/security.spec.tsindex fd39f6d9b..572b3c420 100644--- a/tests/spec/security.spec.ts+++ b/tests/spec/security.spec.ts@@ -1,4 +1,5 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';+import { openRowActionsMenu } from '../utils/table-actions.util';const ROUTES = {page: '/security',@@ -10,6 +11,18 @@ async function navigateToSecurity(page: Page) {await page.waitForLoadState('load');}+function paginated<T>(data: T[]) {+ return {+ data,+ pagination: {+ totalPages: data.length > 0 ? 1 : 0,+ totalItems: data.length,+ currentPage: 1,+ itemsPerPage: 20+ }+ };+}+test.describe('Security Page', () => {test('redirects the old vulnerabilities URL to the security page', async ({ page }) => {await page.goto(ROUTES.legacyVulnerabilities);@@ -45,4 +58,242 @@ test.describe('Security Page', () => {expect(response.ok()).toBeTruthy();await expect(page.getByRole('switch', { name: 'Show ignored' })).toBeChecked();});++ test('reports a partial failure when starting scans for every image', async ({ page }) => {+ await navigateToSecurity(page);++ const scanRequests: string[] = [];+ await page.route(/\/api\/environments\/0\/images(?:\?.*)?$/, async (route) => {+ const requestUrl = new URL(route.request().url());+ expect(requestUrl.searchParams.get('limit')).toBe('1000');+ await route.fulfill({+ json: paginated([+ { id: 'scan-success', repoTags: ['example/success:latest'] },+ { id: 'scan-failure', repoTags: ['example/failure:latest'] }+ ])+ });+ });+ await page.route(+ /\/api\/environments\/0\/images\/([^/]+)\/vulnerabilities\/scan$/,+ async (route) => {+ const imageId = new URL(route.request().url()).pathname.split('/').at(-3);+ if (!imageId) throw new Error('Scan request did not include an image ID');+ scanRequests.push(imageId);++ if (imageId === 'scan-failure') {+ await route.fulfill({ status: 500, json: { message: 'scanner unavailable' } });+ return;+ }++ await route.fulfill({+ json: {+ success: true,+ data: {+ imageId,+ imageName: 'example/success:latest',+ scanTime: new Date().toISOString(),+ status: 'scanning',+ activityId: 'scan-activity'+ }+ }+ });+ }+ );++ await page.getByRole('button', { name: 'Scan all images', exact: true }).click();++ await expect(+ page.getByText('Started 1 scans; 1 failed to start', { exact: true })+ ).toBeVisible();+ expect(scanRequests.sort()).toEqual(['scan-failure', 'scan-success']);+ });++ test('ignores and restores a vulnerability from the row actions', async ({ page }) => {+ const vulnerability = {+ vulnerabilityId: 'CVE-2026-4242',+ pkgName: 'openssl',+ installedVersion: '3.0.0',+ fixedVersion: '3.0.1',+ severity: 'HIGH',+ imageId: 'security-image',+ imageName: 'example/security:latest'+ };+ let ignored = false;+ let ignorePayload: unknown;+ let unignoreRequestCount = 0;++ await page.route(/\/api\/environments\/0\/vulnerabilities\/summary$/, async (route) => {+ await route.fulfill({+ json: {+ success: true,+ data: {+ totalImages: 1,+ scannedImages: 1,+ summary: { critical: 0, high: 1, medium: 0, low: 0, unknown: 0, total: 1 }+ }+ }+ });+ });+ await page.route(/\/api\/environments\/0\/vulnerabilities\/all(?:\?.*)?$/, async (route) => {+ const showIgnored = new URL(route.request().url()).searchParams.get('ignored') === 'true';+ const rows =+ ignored === showIgnored+ ? [{ ...vulnerability, ignored, ignoreId: ignored ? 'ignore-1' : undefined }]+ : [];+ await route.fulfill({ json: paginated(rows) });+ });+ await page.route(+ /\/api\/environments\/0\/vulnerabilities\/image-options(?:\?.*)?$/,+ async (route) => {+ await route.fulfill({ json: { success: true, data: [vulnerability.imageName] } });+ }+ );+ await page.route(/\/api\/environments\/0\/images\/patch-targets(?:\?.*)?$/, async (route) => {+ await route.fulfill({ json: paginated([]) });+ });+ await page.route(/\/api\/environments\/0\/vulnerabilities\/ignore$/, async (route) => {+ ignorePayload = route.request().postDataJSON();+ ignored = true;+ await route.fulfill({+ json: {+ success: true,+ data: { id: 'ignore-1', ...vulnerability }+ }+ });+ });+ await page.route(+ /\/api\/environments\/0\/vulnerabilities\/ignore\/ignore-1$/,+ async (route) => {+ expect(route.request().method()).toBe('DELETE');+ unignoreRequestCount += 1;+ ignored = false;+ await route.fulfill({ status: 204 });+ }+ );++ await navigateToSecurity(page);++ let vulnerabilityRow = page.getByRole('row').filter({ hasText: vulnerability.vulnerabilityId });+ let menu = await openRowActionsMenu(page, vulnerabilityRow);+ await menu.getByRole('menuitem', { name: 'Ignore vulnerability' }).click();++ await expect(+ page.getByText(`Ignored ${vulnerability.vulnerabilityId}`, { exact: true })+ ).toBeVisible();+ await expect(vulnerabilityRow).toHaveCount(0);+ expect(ignorePayload).toEqual({+ imageId: vulnerability.imageId,+ vulnerabilityId: vulnerability.vulnerabilityId,+ pkgName: vulnerability.pkgName,+ installedVersion: vulnerability.installedVersion+ });++ await page.getByRole('switch', { name: 'Show ignored' }).click();+ vulnerabilityRow = page.getByRole('row').filter({ hasText: vulnerability.vulnerabilityId });+ await expect(vulnerabilityRow.getByText('Ignored', { exact: true })).toBeVisible();+ menu = await openRowActionsMenu(page, vulnerabilityRow);+ await menu.getByRole('menuitem', { name: 'Unignore', exact: true }).click();++ await expect(page.getByText('Vulnerability unignored', { exact: true })).toBeVisible();+ await expect(vulnerabilityRow).toHaveCount(0);+ expect(unignoreRequestCount).toBe(1);+ });++ test('starts a valid image patch and explains disabled patch actions', async ({ page }) => {+ const now = new Date().toISOString();+ let patchPayload: unknown;+ let patchStarted = false;+ const targets = () => [+ {+ imageId: 'remote-image',+ imageRef: 'example/remote:latest',+ fixableCount: 2,+ totalCount: 4,+ scanTime: now,+ ...(patchStarted+ ? {+ lastPatch: {+ id: 'patch-record',+ environmentId: '0',+ originalImageId: 'remote-image',+ originalRef: 'example/remote:latest',+ patchedRef: 'example/remote:arcane-patched',+ mode: 'buildkit',+ status: 'running',+ activityId: 'patch-activity',+ createdAt: now+ }+ }+ : {})+ },+ {+ imageId: 'local-image',+ imageRef: 'example/local:latest',+ fixableCount: 1,+ totalCount: 1,+ scanTime: now,+ localOnly: true+ },+ {+ imageId: 'clean-image',+ imageRef: 'example/clean:latest',+ fixableCount: 0,+ totalCount: 3,+ scanTime: now+ }+ ];++ await page.route(/\/api\/environments\/0\/images\/patch-targets(?:\?.*)?$/, async (route) => {+ await route.fulfill({ json: paginated(targets()) });+ });+ await page.route(/\/api\/environments\/0\/images\/remote-image\/patch$/, async (route) => {+ patchPayload = route.request().postDataJSON();+ patchStarted = true;+ await route.fulfill({+ json: {+ success: true,+ data: {+ id: 'patch-record',+ environmentId: '0',+ originalImageId: 'remote-image',+ originalRef: 'example/remote:latest',+ patchedRef: 'example/remote:arcane-patched',+ mode: 'buildkit',+ status: 'running',+ activityId: 'patch-activity',+ createdAt: now+ }+ }+ });+ });++ await navigateToSecurity(page);+ await page.getByRole('tab', { name: 'Patches', exact: true }).click();++ const localRow = page.getByRole('row').filter({ hasText: 'example/local:latest' });+ let menu = await openRowActionsMenu(page, localRow);+ await expect(menu.getByRole('menuitem', { name: /Patch/ })).toBeDisabled();+ await expect(+ menu.getByText('Locally built image — rebuild it to update its packages')+ ).toBeVisible();+ await page.keyboard.press('Escape');++ const cleanRow = page.getByRole('row').filter({ hasText: 'example/clean:latest' });+ menu = await openRowActionsMenu(page, cleanRow);+ await expect(menu.getByRole('menuitem', { name: /Patch/ })).toBeDisabled();+ await expect(menu.getByText('The last scan found no fixable vulnerabilities')).toBeVisible();+ await page.keyboard.press('Escape');++ const remoteRow = page.getByRole('row').filter({ hasText: 'example/remote:latest' });+ menu = await openRowActionsMenu(page, remoteRow);+ await menu.getByRole('menuitem', { name: 'Patch', exact: true }).click();++ await expect(+ page.getByText('Patching image; the result will be tagged example/remote:arcane-patched', {+ exact: true+ })+ ).toBeVisible();+ expect(patchPayload).toEqual({ scanId: 'remote-image' });+ await expect(remoteRow.getByText('Running', { exact: true })).toBeVisible();+ });});diff --git a/tests/spec/settings-notifications.spec.ts b/tests/spec/settings-notifications.spec.tsindex 9dd3f38a2..a45295287 100644--- a/tests/spec/settings-notifications.spec.ts+++ b/tests/spec/settings-notifications.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';test.describe('Notification settings', () => {const openProviderTab = async (page: Page, name: string) => {diff --git a/tests/spec/swarm-ui.spec.ts b/tests/spec/swarm-ui.spec.tsindex 6875d31db..3c07d1559 100644--- a/tests/spec/swarm-ui.spec.ts+++ b/tests/spec/swarm-ui.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';async function mockConfigs(page: Page) {await page.route('**/api/environments/*/swarm/configs', async (route) => {diff --git a/tests/spec/system-upgrade.spec.ts b/tests/spec/system-upgrade.spec.tsindex 05cb0ec4e..bfc4d91b7 100644--- a/tests/spec/system-upgrade.spec.ts+++ b/tests/spec/system-upgrade.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Page, type Route } from '@playwright/test';+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';diff --git a/tests/spec/system-volume-backups.spec.ts b/tests/spec/system-volume-backups.spec.tsindex 611266847..5f12d7da0 100644--- a/tests/spec/system-volume-backups.spec.ts+++ b/tests/spec/system-volume-backups.spec.ts@@ -1,4 +1,4 @@-import { expect, test, type Page } from '@playwright/test';+import { expect, test, type Page } from '../fixtures/test.fixture';type ManagementType = 'system' | 'volume';diff --git a/tests/spec/token-refresh.spec.ts b/tests/spec/token-refresh.spec.tsindex 038cda9f4..0d733603a 100644--- a/tests/spec/token-refresh.spec.ts+++ b/tests/spec/token-refresh.spec.ts@@ -1,4 +1,5 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';+import authUtil from '../utils/auth.util';const REFRESH_TOKEN_KEY = 'arcane_refresh_token';const TOKEN_EXPIRY_KEY = 'arcane_token_expiry';@@ -84,7 +85,51 @@ async function mockRefreshSuccess(page: Page, delayMs = 0): Promise<() => numberreturn () => callCount;}+test('signed-in OIDC callbacks reach the callback exchange', async ({ page }) => {+ let callbackPayload: { code: string; state: string } | undefined;+ await page.route(/\/api\/oidc\/callback$/, async (route) => {+ callbackPayload = route.request().postDataJSON() as { code: string; state: string };+ await route.fulfill({+ status: 400,+ contentType: 'application/json',+ body: JSON.stringify({ success: false, message: 'Callback exchange reached' })+ });+ });++ await page.goto('/oidc/callback?code=callback-code&state=callback-state');++ await expect+ .poll(() => callbackPayload)+ .toEqual({+ code: 'callback-code',+ state: 'callback-state'+ });+ await expect(page).toHaveURL(/\/oidc\/callback\?/);+});+test.describe('Token refresh behaviour', () => {+ test('@cross-browser rejects invalid credentials and accepts the configured admin password', async ({+ page+ }) => {+ await page.context().clearCookies();+ await page.goto('/login');+ await page.getByLabel('Username').fill('arcane');+ await page.getByLabel('Password').fill('not-the-admin-password');+ await page.getByRole('button', { name: 'Sign in to Arcane', exact: true }).click();++ await expect(+ page.getByRole('alert').filter({ hasText: 'Invalid username or password' })+ ).toBeVisible();++ await page.getByLabel('Password').fill(authUtil.TEST_PASSWORD);+ await page.getByRole('button', { name: 'Sign in to Arcane', exact: true }).click();+ await expect(page).toHaveURL('/dashboard');+ await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();+ await expect(+ page.locator('main').getByText('Dashboard', { exact: true }).first()+ ).toBeVisible();+ });+test('version mismatch 401 on /auth/me during page load is silently recovered', async ({page}) => {diff --git a/tests/spec/updates.spec.ts b/tests/spec/updates.spec.tsindex bc4156332..ba4828933 100644--- a/tests/spec/updates.spec.ts+++ b/tests/spec/updates.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';const UPDATES_ROUTE = '/updates';diff --git a/tests/spec/volumes.spec.ts b/tests/spec/volumes.spec.tsindex 067d4cf40..56092ada8 100644--- a/tests/spec/volumes.spec.ts+++ b/tests/spec/volumes.spec.ts@@ -1,4 +1,4 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from '../fixtures/test.fixture';import { fetchVolumeCountsWithRetry } from '../utils/fetch.util';import { VolumeUsageCounts } from 'types/volumes.type';import { openRowActionsMenu } from '../utils/table-actions.util';@@ -261,6 +261,8 @@ test.describe('Volumes Page', () => {try {await createVolumeViaApi(page, sourceName);await page.goto('/volumes');+ const search = page.getByPlaceholder('Search…');+ await search.fill(sourceName);const row = page.getByRole('row')@@ -285,6 +287,7 @@ test.describe('Volumes Page', () => {const response = await renameRequest;expect(response.ok(), await response.text()).toBe(true);+ await search.fill(targetName);await expect(page.getByRole('link', { name: targetName, exact: true })).toBeVisible();expect((diff --git a/tests/utils/fetch.util.ts b/tests/utils/fetch.util.tsindex 366a8d6de..4878a74dd 100644--- a/tests/utils/fetch.util.ts+++ b/tests/utils/fetch.util.ts@@ -8,6 +8,34 @@ import { ApiKey } from 'types/api-key.type';export type Paginated<T> = { data: T[]; pagination?: { totalItems?: number } };+type JsonResponse = {+ ok(): boolean;+ status(): number;+ text(): Promise<string>;+};++export async function readApiData<T>(response: JsonResponse, action: string): Promise<T> {+ const responseText = await response.text();+ let parsed: unknown;++ try {+ parsed = JSON.parse(responseText);+ } catch {+ throw new Error(`${action} returned non-JSON response ${response.status()}: ${responseText}`);+ }++ if (typeof parsed !== 'object' || parsed === null) {+ throw new Error(`${action} returned an invalid response ${response.status()}: ${responseText}`);+ }++ const payload = parsed as { success?: boolean; data?: T };+ if (!response.ok() || payload.success === false || !('data' in payload)) {+ throw new Error(`${action} failed with ${response.status()}: ${responseText}`);+ }++ return payload.data as T;+}+async function retry<T>(fn: () => Promise<T>, maxRetries: number, delayMs = 1000): Promise<T> {let attempt = 0;while (true) {