Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Align first-session onboarding handoff
rcourtmanfdcbf0f2d30e
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex dd85d77a9c..d75c87d5ae 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -884,8 +884,10 @@ profile and assignment columns, but embedded table framing must route throughinto Add infrastructure instead of repeating competing install or dashboardCTAs across multiple sections. Once the first monitored system isalready connected, that same surface must pivot its primary CTA and headline- to `/` so the operator is sent to the dashboard rather than being told to- connect the first source again. While the first source is still pending,+ to `/settings/infrastructure` so the operator returns to the shared+ infrastructure workspace rather than being told to connect the first source+ again or being sent through a generic home/dashboard completion. While the+ first source is still pending,that same completion narrative must describe Add infrastructure as theplace where the operator chooses platform API inventory, Pulse Agenttelemetry, or both. If the operator selects the direct agent path from that@@ -2726,6 +2728,13 @@ setup: RC-proof and helpers must treat direct navigation into`/settings/infrastructure?add=pick` as the canonical completion path, ratherthan assuming an agent-only install landing or the legacy dashboard-onlylanding still defines successful wizard completion.+For already-connected completion states, the `Open Infrastructure` action must+return through the shared infrastructure workspace route+`/settings/infrastructure`, not the root app shell or a dashboard alias. The+source-picker and agent-install actions remain the explicit first-source+handoffs at `/settings/infrastructure?add=pick` and+`/settings/infrastructure?add=agent`, so setup-completion tests must assert the+route helpers rather than allowing a generic home-route completion.That same `SetupCompletionPanel` boundary must also stay on the direct`setup-completion-source-picker-surface` proof path, rather than relying onlyon shared helper coverage or downstream install tests to catch lifecycle driftdiff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.mdindex ef24dfc0e8..ab696ceb75 100644--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md@@ -414,6 +414,13 @@ server-side update execution surfaces.Infrastructure landing path rather than the retired `/dashboard` route, andany helper changes that rely on hot-dev browser/backend behavior must keep amanaged-runtime recovery proof updated in the same slice.+ When those helpers complete first-run setup, they must preserve the API token+ emitted through the setup handoff and write it back to the managed runtime+ state before later authenticated entry attempts. Stale configured tokens may+ be discarded after backend auth failure, but reset and re-entry must still+ use backend-owned dev reset, admin-bypass, session-login, or token-auth paths+ instead of deleting runtime files, rebuilding bootstrap state, or accepting+ the retired dashboard route as proof of authentication.8. Keep root-level Playwright wrapper routing on the canonical managed browsertruth. `playwright.config.ts`, `tests/integration/playwright.config.ts`,and `tests/integration/tests/runtime-defaults.ts` must resolve the same@@ -936,6 +943,11 @@ helper coverage that demonstrates browser-shell request tracking remainstrustworthy when the same test also performs direct health or security-statusAPI probes, and that authenticated bootstrap does not fall back to the retiredDashboard route.+That proof pack must also cover first-session helper re-entry under the managed+runtime: after the dev reset route drives the live setup wizard to Add+infrastructure, the helper must persist the current primary API token into the+runtime-state file and use that token for a later authenticated browser entry+instead of depending on leftover session storage or a dashboard redirect.`scripts/hot-dev-bg.sh` must also supervise `scripts/hot-dev.sh` in an isolatedchild session so an unexpected owner-process death cannot leave orphanedwatchers or health monitors behind. When the supervisor replaces the manageddiff --git a/frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx b/frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsxindex 7697cb3754..f963661abe 100644--- a/frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx+++ b/frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx@@ -5,7 +5,10 @@ import { apiFetchJSON } from '@/utils/apiClient';import { getPulseBaseUrl } from '@/utils/url';import type { State } from '@/types/api';import type { Resource } from '@/types/resource';-import { buildInfrastructureOnboardingPath } from '@/components/Settings/infrastructureWorkspaceModel';+import {+ buildInfrastructureOnboardingPath,+ buildInfrastructureWorkspacePath,+} from '@/components/Settings/infrastructureWorkspaceModel';import type { WizardState } from '../SetupWizard';import {buildSetupCompletionConnectedSystems,@@ -35,6 +38,7 @@ const SOURCE_STRATEGY_OPTIONS = [const ADD_INFRASTRUCTURE_PATH = buildInfrastructureOnboardingPath('pick');const AGENT_INSTALL_PATH = buildInfrastructureOnboardingPath('agent');+const INFRASTRUCTURE_WORKSPACE_PATH = buildInfrastructureWorkspacePath();export const SetupCompletionPanel: Component<CompleteStepProps> = (props) => {const [copied, setCopied] = createSignal<'password' | 'admin-token' | null>(null);@@ -155,7 +159,7 @@ Keep these credentials secure!};const handleOpenInfrastructure = () => {- props.onComplete('/');+ props.onComplete(INFRASTRUCTURE_WORKSPACE_PATH);};const completionViewModel = createMemo(() => buildSetupCompletionViewModel(connectedSystems()));diff --git a/frontend-modern/src/components/SetupWizard/__tests__/SetupCompletionPanel.guardrails.test.ts b/frontend-modern/src/components/SetupWizard/__tests__/SetupCompletionPanel.guardrails.test.tsindex d363cddf44..4f36b4eea4 100644--- a/frontend-modern/src/components/SetupWizard/__tests__/SetupCompletionPanel.guardrails.test.ts+++ b/frontend-modern/src/components/SetupWizard/__tests__/SetupCompletionPanel.guardrails.test.ts@@ -11,12 +11,18 @@ describe('SetupCompletionPanel guardrails', () => {expect(setupCompletionPanelSource).toContain("const AGENT_INSTALL_PATH = buildInfrastructureOnboardingPath('agent');",);+ expect(setupCompletionPanelSource).toContain(+ 'const INFRASTRUCTURE_WORKSPACE_PATH = buildInfrastructureWorkspacePath();',+ );expect(setupCompletionPanelSource).toContain('Add infrastructure');expect(setupCompletionPanelSource).toContain('Install Pulse Agent');expect(setupCompletionPanelSource).toContain('Credentials you must save now');expect(setupCompletionPanelSource).toContain('Shown during setup');expect(setupCompletionPanelSource).toContain('props.onComplete(ADD_INFRASTRUCTURE_PATH);');expect(setupCompletionPanelSource).toContain('props.onComplete(AGENT_INSTALL_PATH);');+ expect(setupCompletionPanelSource).toContain(+ 'props.onComplete(INFRASTRUCTURE_WORKSPACE_PATH);',+ );expect(setupCompletionPanelSource).toContain('Use Add infrastructure to choose a platform API, Pulse Agent, or both',);@@ -54,7 +60,9 @@ describe('SetupCompletionPanel guardrails', () => {);expect(setupCompletionPanelSource).not.toContain("title: 'What happens next'");expect(setupCompletionPanelSource).not.toContain("title: 'Open Add infrastructure'");- expect(setupCompletionPanelSource).not.toContain("title: 'Save the source and confirm coverage'");+ expect(setupCompletionPanelSource).not.toContain(+ "title: 'Save the source and confirm coverage'",+ );expect(setupCompletionPanelSource).not.toContain('What to expect');expect(setupCompletionPanelSource).not.toContain('First system first');expect(setupCompletionPanelSource).not.toContain('Smart Auto-Detection');diff --git a/frontend-modern/src/components/SetupWizard/__tests__/SetupCompletionPanel.test.tsx b/frontend-modern/src/components/SetupWizard/__tests__/SetupCompletionPanel.test.tsxindex 81dd8bc437..7c8e8b3a34 100644--- a/frontend-modern/src/components/SetupWizard/__tests__/SetupCompletionPanel.test.tsx+++ b/frontend-modern/src/components/SetupWizard/__tests__/SetupCompletionPanel.test.tsx@@ -86,9 +86,7 @@ describe('SetupCompletionPanel', () => {expect(screen.getByText('Platform API')).toBeInTheDocument();expect(screen.getByText('Use both')).toBeInTheDocument();expect(- screen.getByText(- 'Inventory and health from Proxmox, TrueNAS, VMware, PBS, or PMG.',- ),+ screen.getByText('Inventory and health from Proxmox, TrueNAS, VMware, PBS, or PMG.'),).toBeInTheDocument();expect(screen.getByText(@@ -205,7 +203,9 @@ describe('SetupCompletionPanel', () => {'Add infrastructure stays available for more Pulse Agent systems or platform API inventory when a platform manages the estate.',),).toBeInTheDocument();- expect(screen.getAllByRole('button', { name: 'Open Infrastructure' }).length).toBeGreaterThan(0);+ expect(screen.getAllByRole('button', { name: 'Open Infrastructure' }).length).toBeGreaterThan(+ 0,+ );expect(screen.getAllByRole('button', { name: 'Add infrastructure' }).length).toBeGreaterThan(0);expect(screen.queryByRole('button', { name: 'Install Pulse Agent' })).not.toBeInTheDocument();@@ -216,7 +216,7 @@ describe('SetupCompletionPanel', () => {fireEvent.click(within(nextStepCard as HTMLElement).getByRole('button', { name: 'Open Infrastructure' }),);- expect(onComplete).toHaveBeenCalledWith('/');+ expect(onComplete).toHaveBeenCalledWith('/settings/infrastructure');});it('keeps add infrastructure available for API-backed starts after the first system connects', async () => {diff --git a/tests/integration/tests/11-first-session.spec.ts b/tests/integration/tests/11-first-session.spec.tsindex 625755dbb8..30b25eed98 100644--- a/tests/integration/tests/11-first-session.spec.ts+++ b/tests/integration/tests/11-first-session.spec.ts@@ -1,11 +1,10 @@-import { test, expect } from '@playwright/test';+import { test, expect } from "@playwright/test";import {- ensureAuthenticated,ensureFirstRunExperience,navigateToSettings,apiRequest,trackBrowserRequests,-} from './helpers';+} from "./helpers";/*** Dedicated first-session E2E test covering the full journey:@@ -13,7 +12,7 @@ import {** This satisfies L8 score-8 criteria: "Dedicated first-session E2E test* (wizard → settings discovery)" while also keeping the setup-completion- * surface on real browser proof for both host-install and API-backed starts.+ * surface on real browser proof for both source-picker and agent-managed starts.** The opening test in this file forces the backend into deterministic* first-run state through the dev/test reset route, then completes the real@@ -27,56 +26,103 @@ type RuntimeCapabilitiesPayload = {/** Selector for the settings sidebar (div with aria-label, not a nav element). */const SETTINGS_SIDEBAR = '[aria-label="Settings navigation"]';-test.describe.serial('First-session experience', () => {- test('wizard completes and lands on infrastructure operations', async ({ page }, testInfo) => {- test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop-only first-session coverage');+test.describe.serial("First-session experience", () => {+ test("wizard completes and lands on Add infrastructure source picker", async ({+ page,+ }, testInfo) => {+ test.skip(+ testInfo.project.name.startsWith("mobile-"),+ "Desktop-only first-session coverage",+ );await ensureFirstRunExperience(page);- // First-run security now hands off directly into the Infrastructure Operations install flow.- await expect(page).toHaveURL(/\/settings\/infrastructure\/install/);+ await expect(page).toHaveURL(/\/settings\/infrastructure\?add=pick$/);+ await expect(+ page.getByText("Connected systems", { exact: true }),+ ).toBeVisible();+ const addDialog = page.getByRole("dialog", { name: "Add infrastructure" });+ await expect(addDialog).toBeVisible();+ await expect(+ addDialog.getByText("Choose how Pulse should connect"),+ ).toBeVisible();+ await expect(+ addDialog.getByRole("button", { name: /Install Pulse Agent/i }),+ ).toBeVisible();await expect(- page.getByRole('heading', { name: 'Infrastructure Operations', exact: true }).first(),+ addDialog.getByRole("button", { name: /Detect API platform/i }),).toBeVisible();- await expect(page.locator('#root')).toBeVisible();+ await expect(page.locator("#root")).toBeVisible();// The main content area should be rendered (not stuck on a spinner/blank).- const mainContent = page.locator('main, [role="main"], #root > div').first();+ const mainContent = page+ .locator('main, [role="main"], #root > div')+ .first();await expect(mainContent).toBeVisible();++ await page+ .getByRole("button", {+ name: "Close add infrastructure dialog",+ exact: true,+ })+ .click();+ await expect(page).toHaveURL(/\/settings\/infrastructure$/);});- test('wizard completion can hand off API-backed starts into platform connections', async ({+ test("wizard completion can hand off directly to Pulse Agent install", async ({page,}, testInfo) => {- test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop-only first-session coverage');+ test.skip(+ testInfo.project.name.startsWith("mobile-"),+ "Desktop-only first-session coverage",+ );- await ensureFirstRunExperience(page, { completionTarget: 'platforms' });+ await ensureFirstRunExperience(page, { completionTarget: "agent" });- await expect(page).toHaveURL(/\/settings\/infrastructure\/platforms/);+ await expect(page).toHaveURL(/\/settings\/infrastructure\?add=agent$/);await expect(- page.getByRole('heading', { name: 'Infrastructure Operations', exact: true }).first(),+ page.getByText("Connected systems", { exact: true }),+ ).toBeVisible();+ const agentDialog = page.getByRole("dialog", { name: "Add Pulse Agent" });+ await expect(agentDialog).toBeVisible();+ await expect(+ agentDialog.getByRole("heading", { name: "Install on a host" }),+ ).toBeVisible();+ await expect(+ agentDialog.getByText(+ "This is the Pulse Agent handoff from first-run setup inside Add infrastructure.",+ ),).toBeVisible();- await expect(page.getByRole('tab', { name: 'Platform connections' })).toHaveAttribute(- 'aria-selected',- 'true',- );- await expect(page.getByText('TrueNAS', { exact: false }).first()).toBeVisible();});- test('shell shows key navigation elements', async ({ page }, testInfo) => {- test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop-only first-session coverage');+ test("shell shows key navigation elements", async ({ page }, testInfo) => {+ test.skip(+ testInfo.project.name.startsWith("mobile-"),+ "Desktop-only first-session coverage",+ );- await ensureAuthenticated(page);+ await ensureFirstRunExperience(page);// The Settings tab is rendered as a div[role="tab"] in the top utility bar.- const settingsTab = page.locator('[role="tab"]').filter({ hasText: 'Settings' }).first();- await expect(settingsTab, 'Settings tab should be visible in the top nav bar').toBeVisible();+ const settingsTab = page+ .locator('[role="tab"]')+ .filter({ hasText: "Settings" })+ .first();+ await expect(+ settingsTab,+ "Settings tab should be visible in the top nav bar",+ ).toBeVisible();});- test('settings discovery - all top-level categories render', async ({ page }, testInfo) => {- test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop-only first-session coverage');+ test("settings discovery - all top-level categories render", async ({+ page,+ }, testInfo) => {+ test.skip(+ testInfo.project.name.startsWith("mobile-"),+ "Desktop-only first-session coverage",+ );- await ensureAuthenticated(page);+ await ensureFirstRunExperience(page);await navigateToSettings(page);// The settings sidebar (div[aria-label="Settings navigation"]) lists category@@ -85,9 +131,9 @@ test.describe.serial('First-session experience', () => {const sidebar = page.locator(SETTINGS_SIDEBAR);await expect(sidebar).toBeVisible({ timeout: 10_000 });- const requiredCategories = ['Infrastructure', 'System', 'Security'];- if (process.env.PULSE_MULTI_TENANT_ENABLED === 'true') {- requiredCategories.splice(1, 0, 'Organization');+ const requiredCategories = ["Infrastructure", "System", "Security"];+ if (process.env.PULSE_MULTI_TENANT_ENABLED === "true") {+ requiredCategories.splice(1, 0, "Organization");}for (const category of requiredCategories) {@@ -99,25 +145,28 @@ test.describe.serial('First-session experience', () => {}});- test('settings panels load without errors', async ({ page }, testInfo) => {- test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop-only first-session coverage');+ test("settings panels load without errors", async ({ page }, testInfo) => {+ test.skip(+ testInfo.project.name.startsWith("mobile-"),+ "Desktop-only first-session coverage",+ );- await ensureAuthenticated(page);+ await ensureFirstRunExperience(page);// Visit a selection of key settings routes and verify the page renders// without console errors or blank screens.const keyRoutes = [- '/settings/system-general',- '/settings/system-updates',- '/settings/security-overview',- '/settings/security-auth',- '/settings/system-pro',+ "/settings/system-general",+ "/settings/system-updates",+ "/settings/security-overview",+ "/settings/security-auth",+ "/settings/system-pro",] as const;const consoleErrors: string[] = [];const aiRequests = trackBrowserRequests(page, /\/api\/ai(\/|$)/);- page.on('console', (msg) => {- if (msg.type() === 'error') {+ page.on("console", (msg) => {+ if (msg.type() === "error") {consoleErrors.push(msg.text());}});@@ -127,16 +176,17 @@ test.describe.serial('First-session experience', () => {consoleErrors.length = 0;aiRequests.clear();- await page.goto(route, { waitUntil: 'domcontentloaded' });+ await page.goto(route, { waitUntil: "domcontentloaded" });await page.waitForURL(/\/settings/, { timeout: 10_000 });- await expect(page.locator('#root')).toBeVisible();+ await expect(page.locator("#root")).toBeVisible();// Wait for the panel content to render. Scope to the settings content// area (everything after the sidebar) to avoid matching sidebar labels.// Fall back to a page-wide heading if the content area locator doesn't// match — some layouts render headings differently.- const panelHeading = page.locator('h1, h2, h3, [role="heading"]')- .filter({ hasNotText: 'Settings' })+ const panelHeading = page+ .locator('h1, h2, h3, [role="heading"]')+ .filter({ hasNotText: "Settings" }).first();await expect(panelHeading,@@ -147,22 +197,22 @@ test.describe.serial('First-session experience', () => {expect(aiRequests.count(),- `Non-AI settings route ${route} should not bootstrap AI endpoints: ${aiRequests.urls().join(', ')}`,+ `Non-AI settings route ${route} should not bootstrap AI endpoints: ${aiRequests.urls().join(", ")}`,).toBe(0);// Filter out benign console noise.const realErrors = consoleErrors.filter((e) =>- !e.includes('Download the React DevTools') &&- !e.includes('Warning:') &&- !e.includes('favicon') &&- !e.includes('ERR_CONNECTION_REFUSED') &&- !e.includes('net::'),+ !e.includes("Download the React DevTools") &&+ !e.includes("Warning:") &&+ !e.includes("favicon") &&+ !e.includes("ERR_CONNECTION_REFUSED") &&+ !e.includes("net::"),);expect(realErrors.length,- `Unexpected console errors on ${route}: ${realErrors.join('; ')}`,+ `Unexpected console errors on ${route}: ${realErrors.join("; ")}`,).toBe(0);}} finally {@@ -170,34 +220,46 @@ test.describe.serial('First-session experience', () => {}});- test('gated panels do not flash unlocked content before license loads', async ({+ test("gated panels do not flash unlocked content before license loads", async ({page,}, testInfo) => {- test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop-only first-session coverage');+ test.skip(+ testInfo.project.name.startsWith("mobile-"),+ "Desktop-only first-session coverage",+ );- await ensureAuthenticated(page);+ await ensureFirstRunExperience(page);// Query runtime capabilities to check feature access per-route without// depending on billing-only entitlements.- const runtimeRes = await apiRequest(page, '/api/license/runtime-capabilities');+ const runtimeRes = await apiRequest(+ page,+ "/api/license/runtime-capabilities",+ );expect(runtimeRes.ok()).toBeTruthy();- const runtimeCapabilities = (await runtimeRes.json()) as RuntimeCapabilitiesPayload;+ const runtimeCapabilities =+ (await runtimeRes.json()) as RuntimeCapabilitiesPayload;const features = new Set(runtimeCapabilities.capabilities || []);- const entitlementsRequests = trackBrowserRequests(page, '/api/license/entitlements');+ const entitlementsRequests = trackBrowserRequests(+ page,+ "/api/license/entitlements",+ );// Gated routes with their required feature. Gating is feature-based, not// tier-based — e.g. a "relay" tier has the relay feature but not// advanced_reporting or audit_logging.const gatedRoutes = [- { route: '/operations/reporting', feature: 'advanced_reporting' },- { route: '/settings/security-webhooks', feature: 'audit_logging' },- { route: '/settings/system-relay', feature: 'relay' },+ { route: "/operations/reporting", feature: "advanced_reporting" },+ { route: "/settings/security-webhooks", feature: "audit_logging" },+ { route: "/settings/system-relay", feature: "relay" },] as const;try {for (const { route, feature } of gatedRoutes) {const hasFeature = features.has(feature);- const routePattern = route.startsWith('/operations/') ? /\/operations/ : /\/settings/;+ const routePattern = route.startsWith("/operations/")+ ? /\/operations/+ : /\/settings/;if (!hasFeature) {// Install a MutationObserver via addInitScript BEFORE navigating so it@@ -205,7 +267,8 @@ test.describe.serial('First-session experience', () => {// flash before the paywall renders (flash-of-unlocked-content).await page.addInitScript(() => {(window as any).__pulseFlashDetected = false;- const SELECTOR = 'form input:not([type="search"]), form textarea, form select';+ const SELECTOR =+ 'form input:not([type="search"]), form textarea, form select';const checkForFlash = () => {const els = document.querySelectorAll(SELECTOR);@@ -231,9 +294,9 @@ test.describe.serial('First-session experience', () => {setTimeout(() => observer.disconnect(), 5000);});- await page.goto(route, { waitUntil: 'domcontentloaded' });+ await page.goto(route, { waitUntil: "domcontentloaded" });await page.waitForURL(routePattern, { timeout: 10_000 });- await expect(page.locator('#root')).toBeVisible();+ await expect(page.locator("#root")).toBeVisible();// Wait for the page to settle, then read the observer result.await page.waitForTimeout(2_000);@@ -247,9 +310,11 @@ test.describe.serial('First-session experience', () => {).toBe(false);// Paywall indicator should be visible.- const paywallIndicator = page.locator(- 'text=/Upgrade|Pro Feature|Requires Pro|Requires Relay|Start.*Trial/i',- ).first();+ const paywallIndicator = page+ .locator(+ "text=/Upgrade|Pro Feature|Requires Pro|Requires Relay|Start.*Trial/i",+ )+ .first();const isPaywallVisible = await paywallIndicator.isVisible({ timeout: 5_000 }).catch(() => false);@@ -258,14 +323,14 @@ test.describe.serial('First-session experience', () => {`Gated route ${route} (feature=${feature}) should show paywall when feature is not available`,).toBeTruthy();} else {- await page.goto(route, { waitUntil: 'domcontentloaded' });+ await page.goto(route, { waitUntil: "domcontentloaded" });await page.waitForURL(routePattern, { timeout: 10_000 });- await expect(page.locator('#root')).toBeVisible();+ await expect(page.locator("#root")).toBeVisible();// Licensed for this feature — the full panel content should render.const panelContent = page- .locator('h1, h2, h3, label, form')- .filter({ hasNotText: 'Settings' })+ .locator("h1, h2, h3, label, form")+ .filter({ hasNotText: "Settings" }).first();await expect(panelContent,@@ -278,28 +343,35 @@ test.describe.serial('First-session experience', () => {entitlementsRequests.stop();expect(requestedURLs,- 'Non-billing gated routes must not trigger billing entitlements reads in the browser shell',+ "Non-billing gated routes must not trigger billing entitlements reads in the browser shell",).toEqual([]);}});- test('Pro license panel is discoverable from settings', async ({ page }, testInfo) => {- test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop-only first-session coverage');+ test("Pro license panel is discoverable from settings", async ({+ page,+ }, testInfo) => {+ test.skip(+ testInfo.project.name.startsWith("mobile-"),+ "Desktop-only first-session coverage",+ );- await ensureAuthenticated(page);- await page.goto('/settings/system-pro', { waitUntil: 'domcontentloaded' });+ await ensureFirstRunExperience(page);+ await page.goto("/settings/system-pro", { waitUntil: "domcontentloaded" });await page.waitForURL(/\/settings/, { timeout: 10_000 });// The Pro panel should always render — either showing license details// (if licensed) or the activation/trial UI (if on free tier).// Scope assertions to content that is specific to the license panel,// not the sidebar label "Pulse Pro".- const licenseContent = page.locator(- 'text=/Current License|Activate|License Key|Start.*Trial|Subscription|Free Tier/i',- ).first();+ const licenseContent = page+ .locator(+ "text=/Current License|Activate|License Key|Start.*Trial|Subscription|Free Tier/i",+ )+ .first();await expect(licenseContent,- 'Pro license panel should show license-specific content (not just sidebar label)',+ "Pro license panel should show license-specific content (not just sidebar label)",).toBeVisible({ timeout: 10_000 });});});diff --git a/tests/integration/tests/16-dev-runtime-recovery.spec.ts b/tests/integration/tests/16-dev-runtime-recovery.spec.tsindex 94efd8d291..e9cb285882 100644--- a/tests/integration/tests/16-dev-runtime-recovery.spec.ts+++ b/tests/integration/tests/16-dev-runtime-recovery.spec.ts@@ -1,6 +1,11 @@import { expect, test } from '@playwright/test';-import { ensureAuthenticated, trackBrowserRequests } from './helpers';+import {+ ensureAuthenticated,+ ensureFirstRunExperience,+ trackBrowserRequests,+} from './helpers';+import { readRuntimeState } from './runtime-defaults';import {killManagedDevRuntimeOwnerProcess,restartManagedDevRuntimeBackend,@@ -43,6 +48,29 @@ test.describe.serial('Managed dev runtime recovery', () => {}});+ test('first-session helper preserves managed runtime auth after dev reset', async ({+ page,+ }, testInfo) => {+ test.setTimeout(120_000);+ test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop-only managed dev runtime coverage');+ test.skip(!truthy(process.env.PULSE_E2E_USE_HOT_DEV), 'Runs only against the managed hot-dev runtime');++ await ensureFirstRunExperience(page);+ await expect(page).toHaveURL(/\/settings\/infrastructure\?add=pick$/);+ await expect(page.getByRole('dialog', { name: 'Add infrastructure' })).toBeVisible();++ expect(+ String(readRuntimeState()?.primaryAPIToken || '').trim().length,+ 'expected first-session helper to persist the handoff API token to runtime state',+ ).toBeGreaterThan(0);++ await page.evaluate(() => {+ window.sessionStorage.removeItem('pulse_auth');+ });+ await ensureAuthenticated(page);+ await expect(page).not.toHaveURL(/\/dashboard(?:[/?#]|$)/);+ });+test('browser shell distinguishes stream-only reconnect from total backend loss', async ({page,}, testInfo) => {diff --git a/tests/integration/tests/30-setup-platform-connections-handoff.spec.ts b/tests/integration/tests/30-setup-platform-connections-handoff.spec.tsindex 41029f1350..f36b7bf9b6 100644--- a/tests/integration/tests/30-setup-platform-connections-handoff.spec.ts+++ b/tests/integration/tests/30-setup-platform-connections-handoff.spec.ts@@ -1,49 +1,75 @@-import { test, expect } from '@playwright/test';+import { test, expect } from "@playwright/test";+import { ensureAuthenticated } from "./helpers";-test.describe('Setup completion platform connections handoff', () => {- test('preview exposes Platform connections as the API-backed first-run alternative', async ({+test.describe("Setup completion Add infrastructure handoff", () => {+ test("preview exposes Add infrastructure as the canonical first source choice", async ({page,}) => {- await page.goto('/preview/setup-complete', { waitUntil: 'domcontentloaded' });+ await ensureAuthenticated(page);+ await page.goto("/preview/setup-complete", {+ waitUntil: "domcontentloaded",+ });- await expect(page.getByText('What happens next')).toBeVisible();- await expect(page.getByRole('button', { name: 'Open Infrastructure Install' })).toBeVisible();- await expect(page.getByRole('button', { name: 'Open Platform connections' })).toBeVisible();+ await expect(+ page.getByText("Choose your first infrastructure source"),+ ).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Add infrastructure", exact: true }),+ ).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Install Pulse Agent" }),+ ).toBeVisible();await expect(page.getByText(- 'If the first system is API-backed, use Platform connections instead of starting with host install.',+ "Start with a platform API when a platform manages the estate. Install Pulse Agent when the system itself should report node-local telemetry.",),).toBeVisible();- await page.getByRole('button', { name: 'Open Platform connections' }).click();- await page.waitForURL(/\/settings\/infrastructure\/platforms$/, { timeout: 15_000 });+ await page+ .getByRole("button", { name: "Add infrastructure", exact: true })+ .click();+ await page.waitForURL(/\/settings\/infrastructure\?add=pick$/, {+ timeout: 15_000,+ });+ const addDialog = page.getByRole("dialog", { name: "Add infrastructure" });+ await expect(addDialog).toBeVisible();+ await expect(+ addDialog.getByText("Choose how Pulse should connect"),+ ).toBeVisible();+ await expect(+ addDialog.getByRole("button", { name: /Detect API platform/i }),+ ).toBeVisible();await expect(- page.getByRole('heading', { name: 'Infrastructure Operations', exact: true }),+ addDialog.getByRole("button", { name: /Install Pulse Agent/i }),).toBeVisible();- await expect(page.getByRole('tab', { name: 'Platform connections' })).toHaveAttribute(- 'aria-selected',- 'true',- );});- test('preview exposes the VMware-connected continuation scenario through platform connections', async ({+ test("preview exposes the VMware-connected continuation scenario through Infrastructure", async ({page,}) => {- await page.goto('/preview/setup-complete?scenario=vmware-api-backed', {- waitUntil: 'domcontentloaded',+ await ensureAuthenticated(page);+ await page.goto("/preview/setup-complete?scenario=vmware-api-backed", {+ waitUntil: "domcontentloaded",});await expect(- page.getByRole('heading', { name: 'First monitored system connected', exact: true }),+ page.getByRole("heading", {+ name: "First monitored system connected",+ exact: true,+ }),+ ).toBeVisible();+ await expect(page.getByText("VMware vSphere")).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Open Infrastructure" }),+ ).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Add infrastructure", exact: true }),).toBeVisible();- await expect(page.getByText('VMware vSphere')).toBeVisible();- await expect(page.getByRole('button', { name: 'Open Platform connections' })).toBeVisible();- await page.getByRole('button', { name: 'Open Platform connections' }).click();- await page.waitForURL(/\/settings\/infrastructure\/platforms$/, { timeout: 15_000 });- await expect(page.getByRole('tab', { name: 'Platform connections' })).toHaveAttribute(- 'aria-selected',- 'true',- );+ await page.getByRole("button", { name: "Open Infrastructure" }).click();+ await page.waitForURL(/\/settings\/infrastructure$/, { timeout: 15_000 });+ await expect(+ page.getByText("Connected systems", { exact: true }),+ ).toBeVisible();});});diff --git a/tests/integration/tests/62-runtime-home-onboarding-contract.spec.ts b/tests/integration/tests/62-runtime-home-onboarding-contract.spec.tsindex 6aff451fd6..d5289834ef 100644--- a/tests/integration/tests/62-runtime-home-onboarding-contract.spec.ts+++ b/tests/integration/tests/62-runtime-home-onboarding-contract.spec.ts@@ -2,7 +2,10 @@ import fs from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";import { test as base, expect } from "@playwright/test";-import { createAuthenticatedStorageState } from "./helpers";+import {+ createAuthenticatedStorageState,+ ensureAuthenticated,+} from "./helpers";const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -42,6 +45,7 @@ test.describe("runtime-home onboarding contract", () => {test("opens the agent install handoff on the shared infrastructure workspace", async ({page,}) => {+ await ensureAuthenticated(page);await page.goto("/settings/infrastructure?add=agent", {waitUntil: "domcontentloaded",});@@ -78,6 +82,7 @@ test.describe("runtime-home onboarding contract", () => {test("opens the platform-pick handoff on the shared infrastructure workspace", async ({page,}) => {+ await ensureAuthenticated(page);await page.goto("/settings/infrastructure?add=pick", {waitUntil: "domcontentloaded",});@@ -104,6 +109,7 @@ test.describe("runtime-home onboarding contract", () => {test("normalizes legacy platform-management paths back to the inventory workspace", async ({page,}) => {+ await ensureAuthenticated(page);await page.goto("/settings/infrastructure/platforms/truenas", {waitUntil: "domcontentloaded",});@@ -116,7 +122,7 @@ test.describe("runtime-home onboarding contract", () => {}),).toBeVisible();await expect(- page.getByText("Infrastructure systems", { exact: true }),+ page.getByText("Connected systems", { exact: true }),).toBeVisible();await expect(page.getByRole("button", { name: /Probe API endpoint/i }),diff --git a/tests/integration/tests/68-infrastructure-onboarding.spec.ts b/tests/integration/tests/68-infrastructure-onboarding.spec.tsindex 3cdad5aed7..51a81f69e5 100644--- a/tests/integration/tests/68-infrastructure-onboarding.spec.ts+++ b/tests/integration/tests/68-infrastructure-onboarding.spec.ts@@ -2,7 +2,10 @@ import fs from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";import { expect, test as base, type Page } from "@playwright/test";-import { createAuthenticatedStorageState } from "./helpers";+import {+ createAuthenticatedStorageState,+ ensureAuthenticated,+} from "./helpers";const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -64,6 +67,7 @@ async function stubConnectionsList(page: Page): Promise<void> {async function prepareOnboardingPage(page: Page): Promise<void> {await stubConnectionsList(page);+ await ensureAuthenticated(page);}async function scrollToBottom(page: Page): Promise<void> {@@ -181,7 +185,7 @@ test.describe("Infrastructure onboarding", () => {});await expect(- page.getByText("Infrastructure systems", { exact: true }),+ page.getByText("Connected systems", { exact: true }),).toBeVisible();await expect(page.getByRole("button", { name: /Run discovery/i }),@@ -192,12 +196,12 @@ test.describe("Infrastructure onboarding", () => {await expect(page.getByRole("button", { name: /Discovery settings/i }),).toBeVisible();- await expect(- page.getByText("VMware vCenter", { exact: true }),- ).toHaveCount(0);- await expect(- page.getByText("TrueNAS SCALE", { exact: true }),- ).toHaveCount(0);+ await expect(page.getByText("VMware vCenter", { exact: true })).toHaveCount(+ 0,+ );+ await expect(page.getByText("TrueNAS SCALE", { exact: true })).toHaveCount(+ 0,+ );await expect(page.getByText("Proxmox VE", { exact: true })).toBeVisible();await expect(page.getByText("Standalone hosts", { exact: true }),@@ -282,7 +286,7 @@ test.describe("Infrastructure onboarding", () => {});await expect(- page.getByText("Infrastructure systems", { exact: true }),+ page.getByText("Connected systems", { exact: true }),).toBeVisible();await expect(page.getByRole("dialog")).toBeVisible();await expect(@@ -476,7 +480,7 @@ test.describe("Infrastructure onboarding", () => {timeout: 15_000,});await expect(- page.getByText("Infrastructure systems", { exact: true }),+ page.getByText("Connected systems", { exact: true }),).toBeVisible();await expect(page.getByText("Pulse Agent", { exact: true })).toBeVisible();await expect(diff --git a/tests/integration/tests/helpers.ts b/tests/integration/tests/helpers.tsindex 3b397a6caa..b97ac4c539 100644--- a/tests/integration/tests/helpers.ts+++ b/tests/integration/tests/helpers.ts@@ -1,8 +1,10 @@+import fs from "node:fs";import { Browser, Page, Request, expect } from "@playwright/test";import {preferredBrowserBaseURL,preferredPlaywrightRouteBaseURL,readRuntimeState,+ runtimeStatePath,} from "./runtime-defaults";const runtimePrimaryAPIToken = (): string => {@@ -12,6 +14,9 @@ const runtimePrimaryAPIToken = (): string => {: "";};+const configuredPrimaryAPIToken = (): string =>+ runtimePrimaryAPIToken() || process.env.PULSE_E2E_PRIMARY_API_TOKEN || "";+/*** Default admin credentials for testing*/@@ -27,12 +32,44 @@ const DEFAULT_E2E_BOOTSTRAP_TOKEN =export const E2E_CREDENTIALS = {bootstrapToken:process.env.PULSE_E2E_BOOTSTRAP_TOKEN || DEFAULT_E2E_BOOTSTRAP_TOKEN,- primaryApiToken:- process.env.PULSE_E2E_PRIMARY_API_TOKEN || runtimePrimaryAPIToken(),+ primaryApiToken: configuredPrimaryAPIToken(),username: process.env.PULSE_E2E_USERNAME || ADMIN_CREDENTIALS.username,password: process.env.PULSE_E2E_PASSWORD || ADMIN_CREDENTIALS.password,};+const SETUP_HANDOFF_STORAGE_KEY = "pulse_setup_handoff";+let ignoreConfiguredPrimaryAPIToken = false;++const currentPrimaryAPIToken = (): string =>+ String(+ E2E_CREDENTIALS.primaryApiToken ||+ (ignoreConfiguredPrimaryAPIToken ? "" : configuredPrimaryAPIToken()),+ ).trim();++const rememberPrimaryAPIToken = (token: unknown) => {+ const nextToken = String(token || "").trim();+ if (nextToken) {+ E2E_CREDENTIALS.primaryApiToken = nextToken;+ ignoreConfiguredPrimaryAPIToken = false;+ persistRuntimePrimaryAPIToken(nextToken);+ }+};++const persistRuntimePrimaryAPIToken = (token: string) => {+ try {+ const runtimePath = runtimeStatePath();+ const currentState = readRuntimeState() || {};+ fs.writeFileSync(+ runtimePath,+ `${JSON.stringify({ ...currentState, primaryAPIToken: token }, null, 2)}\n`,+ "utf8",+ );+ } catch {+ // Runtime-state persistence is a managed-local optimization. In plain+ // Playwright runs the in-process credential update is still sufficient.+ }+};+async function waitForAppShell(page: Page, timeoutMs = 20_000) {await page.waitForLoadState("domcontentloaded");@@ -97,23 +134,29 @@ type ResetFirstRunResponse = {bootstrapToken?: string;};-type SetupCompletionTarget = "install" | "platforms" | "none";+type SetupCompletionTarget = "sources" | "agent" | "none";type CompleteSetupWizardOptions = {completionTarget?: SetupCompletionTarget;};+type CompleteSetupWizardResult = {+ apiToken?: string;+};++const AUTHENTICATED_URL = /\/(proxmox|nodes|hosts|docker|infrastructure)/;+const SETUP_COMPLETION_HANDOFFS: Record<Exclude<SetupCompletionTarget, "none">,{ buttonName: string; urlPattern: RegExp }> = {- install: {- buttonName: "Open Infrastructure Install",- urlPattern: /\/settings\/infrastructure\/install/,+ sources: {+ buttonName: "Add infrastructure",+ urlPattern: /\/settings\/infrastructure\?add=pick$/,},- platforms: {- buttonName: "Open Platform connections",- urlPattern: /\/settings\/infrastructure\/platforms/,+ agent: {+ buttonName: "Install Pulse Agent",+ urlPattern: /\/settings\/infrastructure\?add=agent$/,},};@@ -121,8 +164,8 @@ async function completeSetupWizard(page: Page,bootstrapToken: string,options: CompleteSetupWizardOptions = {},-) {- const completionTarget = options.completionTarget ?? "install";+): Promise<CompleteSetupWizardResult> {+ const completionTarget = options.completionTarget ?? "sources";if (!bootstrapToken) {throw new Error("Pulse requires first-run setup but no bootstrap token is available",@@ -136,14 +179,14 @@ async function completeSetupWizard(await expect(wizard).toBeVisible();const completionHeading = wizard.getByRole("heading", {- name: /install your first monitored host|first monitored host connected/i,+ name: /choose your first infrastructure source|first monitored system connected/i,});- const openInstallWorkspaceButton = wizard.getByRole("button", {- name: "Open Infrastructure Install",+ const addInfrastructureButton = wizard.getByRole("button", {+ name: "Add infrastructure",exact: true,});- const openPlatformConnectionsButton = wizard.getByRole("button", {- name: "Open Platform connections",+ const installPulseAgentButton = wizard.getByRole("button", {+ name: "Install Pulse Agent",exact: true,});const securePulseHeading = wizard.getByText("Secure Pulse");@@ -168,19 +211,17 @@ async function completeSetupWizard((await completionHeading.isVisible({ timeout: 100 }).catch(() => false)) ||- (await openInstallWorkspaceButton+ (await addInfrastructureButton.isVisible({ timeout: 100 }).catch(() => false)) ||- (await openPlatformConnectionsButton+ (await installPulseAgentButton.isVisible({ timeout: 100 }).catch(() => false))) {return "completion";}if (- await securePulseHeading- .isVisible({ timeout: 100 })- .catch(() => false)+ await securePulseHeading.isVisible({ timeout: 100 }).catch(() => false)) {return "security";}@@ -238,10 +279,10 @@ async function completeSetupWizard((await completionHeading.isVisible({ timeout: 250 }).catch(() => false)) ||- (await openInstallWorkspaceButton+ (await addInfrastructureButton.isVisible({ timeout: 250 }).catch(() => false)) ||- (await openPlatformConnectionsButton+ (await installPulseAgentButton.isVisible({ timeout: 250 }).catch(() => false))) {@@ -276,18 +317,20 @@ async function completeSetupWizard((await completionHeading.isVisible({ timeout: 250 }).catch(() => false)) ||- (await openInstallWorkspaceButton+ (await addInfrastructureButton.isVisible({ timeout: 250 }).catch(() => false)) ||- (await openPlatformConnectionsButton+ (await installPulseAgentButton.isVisible({ timeout: 250 }).catch(() => false))) {return "complete";}if (- completionTarget === "install" &&- SETUP_COMPLETION_HANDOFFS.install.urlPattern.test(page.url())+ completionTarget !== "none" &&+ SETUP_COMPLETION_HANDOFFS[completionTarget].urlPattern.test(+ page.url(),+ )) {return "handoff";}@@ -322,7 +365,7 @@ async function completeSetupWizard(if (!completionAction.urlPattern.test(page.url())) {throw new Error(- `Setup wizard completion did not hand off to ${completionAction.buttonName}: ${page.url()}`,+ `Setup wizard completion did not hand off through ${completionAction.buttonName}: ${page.url()}`,);}} else if (onCompleteStep) {@@ -336,6 +379,23 @@ async function completeSetupWizard(}await page.waitForLoadState("domcontentloaded");++ const apiToken = await page+ .evaluate((storageKey) => {+ try {+ const raw = window.sessionStorage.getItem(storageKey);+ if (!raw) return "";+ const payload = JSON.parse(raw) as { apiToken?: unknown };+ return typeof payload.apiToken === "string"+ ? payload.apiToken.trim()+ : "";+ } catch {+ return "";+ }+ }, SETUP_HANDOFF_STORAGE_KEY)+ .catch(() => "");++ return { apiToken: apiToken || undefined };}export async function getSecurityStatus(page: Page): Promise<SecurityStatus> {@@ -352,41 +412,77 @@ export async function maybeCompleteSetupWizard(page: Page) {return;}- await completeSetupWizard(page, E2E_CREDENTIALS.bootstrapToken);+ const setup = await completeSetupWizard(page, E2E_CREDENTIALS.bootstrapToken);+ rememberPrimaryAPIToken(setup.apiToken);}-export async function ensureFirstRunExperience(+async function resetFirstRunState(page: Page,- options: CompleteSetupWizardOptions = {},-) {- await waitForPulseReady(page);- const completionTarget = options.completionTarget ?? "install";-- let bootstrapToken = E2E_CREDENTIALS.bootstrapToken;- const security = await getSecurityStatus(page);- let resetRes = await apiRequest(page, "/api/security/dev/reset-first-run", {- method: "POST",- headers: E2E_CREDENTIALS.primaryApiToken- ? { "X-API-Token": E2E_CREDENTIALS.primaryApiToken }- : undefined,- });- if (- resetRes.status() === 401 &&- !E2E_CREDENTIALS.primaryApiToken &&- security.hasAuthentication !== false- ) {- await login(page);- resetRes = await apiRequest(page, "/api/security/dev/reset-first-run", {+ security: SecurityStatus,+): Promise<ResetFirstRunResponse> {+ const resetPath = "/api/security/dev/reset-first-run";+ const reset = (headers?: Record<string, string>) =>+ apiRequest(page, resetPath, {method: "POST",+ headers,});+ const isAuthFailure = (status: number) => status === 401 || status === 403;++ const primaryToken = currentPrimaryAPIToken();+ if (primaryToken) {+ const tokenRes = await reset({ "X-API-Token": primaryToken });+ if (tokenRes.ok()) {+ return (await tokenRes.json()) as ResetFirstRunResponse;+ }+ if (!isAuthFailure(tokenRes.status())) {+ throw new Error(+ `Failed to reset first-run state: ${tokenRes.status()} ${await tokenRes.text()}`,+ );+ }++ // The reset route intentionally clears API tokens. A configured static+ // token can therefore be valid for the first reset and stale for later+ // first-session tests in the same managed runtime.+ E2E_CREDENTIALS.primaryApiToken = "";+ ignoreConfiguredPrimaryAPIToken = true;}- if (!resetRes.ok()) {++ const bypassRes = await reset({ "X-Admin-Bypass": "true" });+ if (bypassRes.ok()) {+ return (await bypassRes.json()) as ResetFirstRunResponse;+ }+ if (!isAuthFailure(bypassRes.status())) {throw new Error(- `Failed to reset first-run state: ${resetRes.status()} ${await resetRes.text()}`,+ `Failed to reset first-run state: ${bypassRes.status()} ${await bypassRes.text()}`,);}- const payload = (await resetRes.json()) as ResetFirstRunResponse;+ if (security.hasAuthentication !== false) {+ await login(page);+ const sessionRes = await reset();+ if (sessionRes.ok()) {+ return (await sessionRes.json()) as ResetFirstRunResponse;+ }+ throw new Error(+ `Failed to reset first-run state after login fallback: ${sessionRes.status()} ${await sessionRes.text()}`,+ );+ }++ throw new Error(+ `Failed to reset first-run state: ${bypassRes.status()} ${await bypassRes.text()}`,+ );+}++export async function ensureFirstRunExperience(+ page: Page,+ options: CompleteSetupWizardOptions = {},+) {+ await waitForPulseReady(page);+ const completionTarget = options.completionTarget ?? "sources";++ let bootstrapToken = E2E_CREDENTIALS.bootstrapToken;+ const security = await getSecurityStatus(page);+ const payload = await resetFirstRunState(page, security);bootstrapToken = String(payload.bootstrapToken || "").trim();if (bootstrapToken === "") {throw new Error(@@ -394,15 +490,18 @@ export async function ensureFirstRunExperience();}- await completeSetupWizard(page, bootstrapToken, { completionTarget });+ const setup = await completeSetupWizard(page, bootstrapToken, {+ completionTarget,+ });+ rememberPrimaryAPIToken(setup.apiToken);const firstRunLandingPattern =- completionTarget === "platforms"- ? SETUP_COMPLETION_HANDOFFS.platforms.urlPattern- : /\/(settings\/infrastructure\/install|proxmox|nodes|hosts|docker|infrastructure)/;+ completionTarget === "none"+ ? /\/(settings\/infrastructure|proxmox|nodes|hosts|docker|infrastructure)/+ : SETUP_COMPLETION_HANDOFFS[completionTarget].urlPattern;if (!firstRunLandingPattern.test(page.url())) {- if (completionTarget === "platforms") {+ if (completionTarget !== "none") {throw new Error(- `First-run setup did not reach Platform connections: ${page.url()}`,+ `First-run setup did not reach ${SETUP_COMPLETION_HANDOFFS[completionTarget].buttonName}: ${page.url()}`,);}await login(page);@@ -428,8 +527,6 @@ export async function login(page: Page, credentials = E2E_CREDENTIALS) {await page.goto("/");await waitForAppShell(page);- const authenticatedURL =- /\/(proxmox|nodes|hosts|docker|infrastructure)/;const usernameInput = page.locator('input[name="username"]');const state = await Promise.race([@@ -438,7 +535,7 @@ export async function login(page: Page, credentials = E2E_CREDENTIALS) {.then(() => "login").catch(() => undefined),page- .waitForURL(authenticatedURL, { timeout: 15_000 })+ .waitForURL(AUTHENTICATED_URL, { timeout: 15_000 }).then(() => "authenticated").catch(() => undefined),]);@@ -471,7 +568,7 @@ export async function login(page: Page, credentials = E2E_CREDENTIALS) {.poll(async () => {const url = page.url();- if (authenticatedURL.test(url)) {+ if (AUTHENTICATED_URL.test(url)) {return "authenticated";}@@ -503,13 +600,48 @@ export async function login(page: Page, credentials = E2E_CREDENTIALS) {.toBe("authenticated");}+async function authenticateWithPrimaryAPIToken(page: Page): Promise<boolean> {+ const token = currentPrimaryAPIToken();+ if (!token) {+ return false;+ }++ await page.goto(`/?token=${encodeURIComponent(token)}`, {+ waitUntil: "domcontentloaded",+ });+ await waitForAppShell(page);++ const state = await Promise.race([+ page+ .waitForURL(AUTHENTICATED_URL, { timeout: 10_000 })+ .then(() => "authenticated")+ .catch(() => undefined),+ page+ .locator('input[name="username"]')+ .waitFor({ state: "visible", timeout: 10_000 })+ .then(() => "login")+ .catch(() => undefined),+ ]);++ if (state === "authenticated") {+ return true;+ }++ await page+ .evaluate(() => {+ window.sessionStorage.removeItem("pulse_auth");+ })+ .catch(() => {});+ return false;+}+export async function ensureAuthenticated(page: Page) {await waitForPulseReady(page);await maybeCompleteSetupWizard(page);- await login(page);- await expect(page).toHaveURL(- /\/(proxmox|nodes|hosts|docker|infrastructure)/,- );+ if (!(await authenticateWithPrimaryAPIToken(page))) {+ await login(page);+ }+ await expect(page).toHaveURL(AUTHENTICATED_URL);}export async function createAuthenticatedStorageState(