Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Recover journeys 01/06/07 as CI-safe cookie-session tests

rcourtman448046b1e20d
diff --git a/tests/integration/tests/journeys/01-smoke-bootstrap-login-infrastructure.spec.ts b/tests/integration/tests/journeys/01-smoke-bootstrap-login-infrastructure.spec.ts
index 9b8baf2edb..d17bd317c1 100644
--- a/tests/integration/tests/journeys/01-smoke-bootstrap-login-infrastructure.spec.ts
+++ b/tests/integration/tests/journeys/01-smoke-bootstrap-login-infrastructure.spec.ts
@@ -1,6 +1,7 @@
-import { test, expect } from '@playwright/test';
+import { test as loginFlowTest, expect } from '@playwright/test';
+import { test, ensureJourneyReady } from './journeyAuth';
import {
- ensureAuthenticated,
+ ensureSessionAuthenticated,
login,
logout,
waitForPulseReady,
@@ -43,29 +44,13 @@ async function captureMockBaseline(page: import('@playwright/test').Page): Promi
return state;
}
-test.describe.serial('Journey: Bootstrap → Login → Infrastructure', () => {
- test.afterAll(async ({ browser }) => {
- // Restore mock mode to its original state to avoid leaking into other suites.
- if (mockModeWasEnabled !== null) {
- const ctx = await browser.newContext();
- const page = await ctx.newPage();
- try {
- await login(page);
- const current = await getMockMode(page);
- if (current.enabled !== mockModeWasEnabled) {
- await setMockMode(page, mockModeWasEnabled);
- }
- } catch (err) {
- // Best-effort restore; don't fail the suite on cleanup but warn for diagnosis.
- console.warn('[journey cleanup] failed to restore mock mode:', err);
- } finally {
- await ctx.close();
- }
- }
- });
-
- test('health check responds with retry', async ({ page }, testInfo) => {
- test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
+// These two tests exercise the login flow itself, so they must start from an
+// unauthenticated context. They use the plain @playwright/test `test`
+// (loginFlowTest) rather than the cookie-session fixture, and issue their own
+// real login. Every other journey test inherits the worker cookie session.
+loginFlowTest.describe.serial('Journey: Bootstrap → Login (login flow)', () => {
+ loginFlowTest('health check responds with retry', async ({ page }, testInfo) => {
+ loginFlowTest.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
// Use waitForPulseReady which retries with backoff — avoids flakes on cold starts.
await waitForPulseReady(page);
@@ -74,12 +59,13 @@ test.describe.serial('Journey: Bootstrap → Login → Infrastructure', () => {
expect(res.ok(), `Health check failed with status ${res.status()}`).toBeTruthy();
});
- test('bootstrap and login land on Infrastructure', async ({ page }, testInfo) => {
- test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
+ loginFlowTest('bootstrap and login land on Infrastructure', async ({ page }, testInfo) => {
+ loginFlowTest.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
- await ensureAuthenticated(page);
+ // This test exercises the real login flow from an unauthenticated context.
+ await ensureSessionAuthenticated(page);
- // v6 lands on /infrastructure after login (other routes are valid legacy landings)
+ // v6 lands on a platform page after login (Infrastructure superset of landings)
await expect(page).toHaveURL(AUTHENTICATED_URL);
await expect(page.locator('#root')).toBeVisible();
@@ -88,10 +74,73 @@ test.describe.serial('Journey: Bootstrap → Login → Infrastructure', () => {
await expect(mainContent).toBeVisible();
});
+ // Exercises the logout → re-login cycle. It runs on its OWN session (no
+ // shared cookie fixture): logout() destroys the current session server-side,
+ // so it must never run against the worker's shared cookie session or every
+ // subsequent fixture-backed journey test would find its cookie dead and fall
+ // back to a per-test login, tripping the login rate limit.
+ loginFlowTest('logout and re-login cycle completes successfully', async ({ page }, testInfo) => {
+ loginFlowTest.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
+
+ await ensureSessionAuthenticated(page);
+
+ await logout(page);
+ await expect(page.locator('input[name="username"]')).toBeVisible();
+
+ await login(page, E2E_CREDENTIALS);
+ await expect(page).toHaveURL(AUTHENTICATED_URL);
+ });
+});
+
+test.describe.serial('Journey: Bootstrap → Login → Infrastructure', () => {
+ test.beforeAll(async ({ browser, authStorageStatePath }) => {
+ // Platform nav tabs (e.g. Proxmox) are resource-admitted — they only
+ // render when the resource snapshot proves the surface is present. Enable
+ // mock mode up front so the platform-first tab list and resource-content
+ // assertions below are deterministic even on a fresh (non-mock) backend
+ // such as CI. Capture the true baseline first so afterAll restores it.
+ const ctx = await browser.newContext({ storageState: authStorageStatePath });
+ const page = await ctx.newPage();
+ try {
+ await ensureJourneyReady(page);
+ const state = await getMockMode(page);
+ if (mockModeWasEnabled === null) {
+ mockModeWasEnabled = state.enabled;
+ }
+ if (!state.enabled) {
+ await setMockMode(page, true);
+ }
+ } catch (err) {
+ console.warn('[journey setup] failed to enable mock mode:', err);
+ } finally {
+ await ctx.close();
+ }
+ });
+
+ test.afterAll(async ({ browser, authStorageStatePath }) => {
+ // Restore mock mode to its original state to avoid leaking into other suites.
+ if (mockModeWasEnabled !== null) {
+ const ctx = await browser.newContext({ storageState: authStorageStatePath });
+ const page = await ctx.newPage();
+ try {
+ await ensureJourneyReady(page);
+ const current = await getMockMode(page);
+ if (current.enabled !== mockModeWasEnabled) {
+ await setMockMode(page, mockModeWasEnabled);
+ }
+ } catch (err) {
+ // Best-effort restore; don't fail the suite on cleanup but warn for diagnosis.
+ console.warn('[journey cleanup] failed to restore mock mode:', err);
+ } finally {
+ await ctx.close();
+ }
+ }
+ });
+
test('navigation tabs are visible after login', async ({ page }, testInfo) => {
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
// Wait for the primary navigation tablist to render before checking individual
// tabs. After login redirect, the SPA may still be hydrating the layout.
@@ -101,9 +150,12 @@ test.describe.serial('Journey: Bootstrap → Login → Infrastructure', () => {
'Primary navigation tablist should render',
).toBeVisible({ timeout: 15_000 });
- // Core navigation tabs that must always be present
+ // Core navigation tabs. The IA is platform-first: there is no single
+ // 'Infrastructure' tab — the first platform lens (Proxmox, admitted by the
+ // mock data enabled in beforeAll) plus the always-present Alerts and
+ // Settings tabs.
const expectedTabs = [
- 'Infrastructure',
+ 'Proxmox',
'Alerts',
'Settings',
];
@@ -120,7 +172,7 @@ test.describe.serial('Journey: Bootstrap → Login → Infrastructure', () => {
test('mock mode can be enabled for deterministic data', async ({ page }, testInfo) => {
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
// Capture initial state so afterAll can restore it.
const initialState = await captureMockBaseline(page);
@@ -137,7 +189,7 @@ test.describe.serial('Journey: Bootstrap → Login → Infrastructure', () => {
test('infrastructure landing renders resource content', async ({ page }, testInfo) => {
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
await page.goto('/infrastructure', { waitUntil: 'domcontentloaded' });
await expect(page).toHaveURL(/\/infrastructure/);
@@ -155,7 +207,7 @@ test.describe.serial('Journey: Bootstrap → Login → Infrastructure', () => {
test('infrastructure tab renders resource content', async ({ page }, testInfo) => {
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
// Ensure mock mode is on so we always have resources to display.
const mockState = await captureMockBaseline(page);
@@ -179,7 +231,7 @@ test.describe.serial('Journey: Bootstrap → Login → Infrastructure', () => {
test('alerts tab renders overview', async ({ page }, testInfo) => {
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
await page.goto('/alerts/overview', { waitUntil: 'domcontentloaded' });
await expect(page).toHaveURL(/\/alerts/);
@@ -191,13 +243,13 @@ test.describe.serial('Journey: Bootstrap → Login → Infrastructure', () => {
test('settings tab renders sidebar categories', async ({ page }, testInfo) => {
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
await navigateToSettings(page);
const sidebar = page.locator('[aria-label="Settings navigation"]');
await expect(sidebar).toBeVisible({ timeout: 10_000 });
- const categories = ['Platforms', 'Operations', 'System', 'Security'];
+ const categories = ['Infrastructure', 'System', 'Security'];
for (const category of categories) {
const heading = sidebar.getByText(category, { exact: false }).first();
await expect(
@@ -212,7 +264,7 @@ test.describe.serial('Journey: Bootstrap → Login → Infrastructure', () => {
}, testInfo) => {
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const entitlementsRequests = trackBrowserRequests(page, '/api/license/entitlements');
try {
@@ -239,22 +291,10 @@ test.describe.serial('Journey: Bootstrap → Login → Infrastructure', () => {
}
});
- test('logout and re-login cycle completes successfully', async ({ page }, testInfo) => {
- test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
-
- await ensureAuthenticated(page);
-
- await logout(page);
- await expect(page.locator('input[name="username"]')).toBeVisible();
-
- await login(page, E2E_CREDENTIALS);
- await expect(page).toHaveURL(AUTHENTICATED_URL);
- });
-
test('API returns runtime capabilities after full journey', async ({ page }, testInfo) => {
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop smoke journey');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const stateRes = await apiRequest(page, '/api/state');
expect(stateRes.ok(), `GET /api/state failed: ${stateRes.status()}`).toBeTruthy();
diff --git a/tests/integration/tests/journeys/06-audit-log-reporting.spec.ts b/tests/integration/tests/journeys/06-audit-log-reporting.spec.ts
index e76f167030..172333ac71 100644
--- a/tests/integration/tests/journeys/06-audit-log-reporting.spec.ts
+++ b/tests/integration/tests/journeys/06-audit-log-reporting.spec.ts
@@ -1,6 +1,5 @@
-import { test, expect } from '@playwright/test';
+import { test, expect, ensureJourneyReady } from './journeyAuth';
import {
- ensureAuthenticated,
apiRequest,
setMockMode,
getMockMode,
@@ -44,11 +43,11 @@ let reportingLicensed = true;
test.describe.serial(
'Journey: Audit Log + Webhook + Reporting',
() => {
- test.beforeAll(async ({ browser }) => {
- const ctx = await browser.newContext();
+ test.beforeAll(async ({ browser, authStorageStatePath }) => {
+ const ctx = await browser.newContext({ storageState: authStorageStatePath });
const page = await ctx.newPage();
try {
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const state = await getMockMode(page);
mockModeWasEnabled = state.enabled;
// Enable mock mode so we have resources for reporting.
@@ -62,11 +61,11 @@ test.describe.serial(
}
});
- test.afterAll(async ({ browser }) => {
- const ctx = await browser.newContext();
+ test.afterAll(async ({ browser, authStorageStatePath }) => {
+ const ctx = await browser.newContext({ storageState: authStorageStatePath });
const page = await ctx.newPage();
try {
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
if (mockModeWasEnabled !== null) {
const current = await getMockMode(page);
if (current.enabled !== mockModeWasEnabled) {
@@ -85,7 +84,7 @@ test.describe.serial(
test('audit event list endpoint responds', async ({ page }, testInfo) => {
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop audit journey');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const res = await apiRequest(page, '/api/audit?limit=10');
@@ -115,7 +114,7 @@ test.describe.serial(
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop audit journey');
test.skip(!auditLicensed, 'Audit logging not licensed');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const res = await apiRequest(page, '/api/audit/export?format=json');
@@ -144,7 +143,7 @@ test.describe.serial(
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop audit journey');
test.skip(!auditLicensed, 'Audit logging not licensed');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const res = await apiRequest(page, '/api/audit/summary');
@@ -167,7 +166,7 @@ test.describe.serial(
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop audit journey');
test.skip(!auditLicensed, 'Audit logging not licensed');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
// GET existing audit webhooks — verifies the endpoint is accessible
// and returns the expected shape.
@@ -218,7 +217,7 @@ test.describe.serial(
test('audit log viewer page renders in UI', async ({ page }, testInfo) => {
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop audit journey');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
await page.goto('/settings/security-audit', { waitUntil: 'domcontentloaded' });
await page.waitForURL(/\/settings/, { timeout: 10_000 });
@@ -240,7 +239,7 @@ test.describe.serial(
test('notification webhook test endpoint works', async ({ page }, testInfo) => {
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop webhook journey');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
// List existing notification webhooks.
const listRes = await apiRequest(page, '/api/notifications/webhooks');
@@ -270,10 +269,18 @@ test.describe.serial(
test.setTimeout(60_000);
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
- // Poll for resources — mock mode may still be populating after earlier
- // journey toggles. Wait up to 30s for at least one node/VM.
+ // Guarantee mock mode is on before polling — an earlier journey (e.g. 04)
+ // or a backend restart can leave it off, which would spin the poll for
+ // the full 30s and then skip. Enabling it up front makes resources
+ // appear promptly and keeps the poll tight.
+ if (!(await getMockMode(page)).enabled) {
+ await setMockMode(page, true);
+ }
+
+ // Poll for resources — mock mode may still be populating after the
+ // toggle. Wait up to 30s for at least one node/VM.
let resourceType = '';
let resourceId = '';
let stateApiReachable = false;
@@ -342,10 +349,15 @@ test.describe.serial(
test.setTimeout(60_000);
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
- // Poll for resources — mock mode may still be populating after earlier
- // journey toggles. Wait up to 30s for at least one node to appear.
+ // Guarantee mock mode is on before polling (see single-resource test).
+ if (!(await getMockMode(page)).enabled) {
+ await setMockMode(page, true);
+ }
+
+ // Poll for resources — mock mode may still be populating after the
+ // toggle. Wait up to 30s for at least one node to appear.
let resources: { resourceType: string; resourceId: string }[] = [];
let stateApiReachable = false;
const deadline = Date.now() + 30_000;
@@ -408,18 +420,19 @@ test.describe.serial(
test('reporting page renders in UI', async ({ page }, testInfo) => {
test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop reporting journey');
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
- // Reporting lives under the Operations page, not Settings.
- await page.goto('/operations/reporting', {
+ // Reporting lives under Settings → Support → Data & Reports.
+ await page.goto('/settings/support/reporting', {
waitUntil: 'domcontentloaded',
});
- await page.waitForURL(/\/operations/, { timeout: 10_000 });
+ await page.waitForURL(/\/settings/, { timeout: 10_000 });
await expect(page.locator('#root')).toBeVisible();
- // The reporting tab should show a heading or form content, or a paywall.
+ // The reporting page renders the "Data & Reports" heading, report form
+ // content, or an upgrade paywall when advanced_reporting is unlicensed.
const reportContent = page.locator(
- 'h1:has-text("Report"), h2:has-text("Report"), a:has-text("Upgrade"), button:has-text("Generate")',
+ 'h1:has-text("Data & Reports"), h2:has-text("Data & Reports"), h1:has-text("Report"), h2:has-text("Report"), a:has-text("Upgrade"), button:has-text("Generate")',
).first();
await expect(
diff --git a/tests/integration/tests/journeys/07-ai-patrol-finding-lifecycle.spec.ts b/tests/integration/tests/journeys/07-ai-patrol-finding-lifecycle.spec.ts
index 331cbb2198..a8d1b782aa 100644
--- a/tests/integration/tests/journeys/07-ai-patrol-finding-lifecycle.spec.ts
+++ b/tests/integration/tests/journeys/07-ai-patrol-finding-lifecycle.spec.ts
@@ -19,9 +19,8 @@
* Mock mode generates deterministic resources that patrol can inspect.
*/
-import { test, expect } from '@playwright/test';
+import { test, expect, ensureJourneyReady } from './journeyAuth';
import {
- ensureAuthenticated,
apiRequest,
setMockMode,
getMockMode,
@@ -33,11 +32,11 @@ let mockModeWasEnabled: boolean | null = null;
test.describe.serial(
'Journey: Patrol → Finding → Approval → Fix → Verify Resolved',
() => {
- test.beforeAll(async ({ browser }) => {
- const ctx = await browser.newContext();
+ test.beforeAll(async ({ browser, authStorageStatePath }) => {
+ const ctx = await browser.newContext({ storageState: authStorageStatePath });
const page = await ctx.newPage();
try {
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const state = await getMockMode(page);
mockModeWasEnabled = state.enabled;
if (!state.enabled) {
@@ -50,11 +49,11 @@ test.describe.serial(
}
});
- test.afterAll(async ({ browser }) => {
- const ctx = await browser.newContext();
+ test.afterAll(async ({ browser, authStorageStatePath }) => {
+ const ctx = await browser.newContext({ storageState: authStorageStatePath });
const page = await ctx.newPage();
try {
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
if (mockModeWasEnabled !== null) {
const current = await getMockMode(page);
if (current.enabled !== mockModeWasEnabled) {
@@ -75,7 +74,7 @@ test.describe.serial(
testInfo.project.name.startsWith('mobile-'),
'Desktop journey',
);
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const resp = await apiRequest(page, '/api/ai/patrol/status');
expect(resp.status()).toBe(200);
@@ -102,7 +101,7 @@ test.describe.serial(
testInfo.project.name.startsWith('mobile-'),
'Desktop journey',
);
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const resp = await apiRequest(page, '/api/ai/patrol/findings');
expect(resp.status()).toBe(200);
@@ -130,7 +129,7 @@ test.describe.serial(
testInfo.project.name.startsWith('mobile-'),
'Desktop journey',
);
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const resp = await apiRequest(page, '/api/ai/patrol/run', {
method: 'POST',
@@ -157,7 +156,7 @@ test.describe.serial(
testInfo.project.name.startsWith('mobile-'),
'Desktop journey',
);
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const resp = await apiRequest(page, '/api/ai/patrol/runs');
expect(resp.status()).toBe(200);
@@ -182,7 +181,7 @@ test.describe.serial(
testInfo.project.name.startsWith('mobile-'),
'Desktop journey',
);
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const resp = await apiRequest(page, '/api/ai/patrol/autonomy');
expect(resp.status()).toBe(200);
@@ -201,7 +200,7 @@ test.describe.serial(
testInfo.project.name.startsWith('mobile-'),
'Desktop journey',
);
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const resp = await apiRequest(page, '/api/ai/approvals');
// 200 = success (Pro), 402 = license required (Community)
@@ -231,7 +230,7 @@ test.describe.serial(
testInfo.project.name.startsWith('mobile-'),
'Desktop journey',
);
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const findingsResp = await apiRequest(
page,
@@ -247,12 +246,14 @@ test.describe.serial(
const findingId = encodeURIComponent(findings[0].id);
- // Investigation may or may not exist — both are valid states
+ // Investigation may or may not exist — both are valid states. 503 is
+ // also valid: the investigation service can be transiently unavailable
+ // (no AI provider configured / warming up) on a mock backend.
const investResp = await apiRequest(
page,
`/api/ai/findings/${findingId}/investigation`,
);
- expect([200, 404]).toContain(investResp.status());
+ expect([200, 404, 503]).toContain(investResp.status());
if (investResp.status() === 200) {
const body = await investResp.json();
@@ -273,7 +274,7 @@ test.describe.serial(
testInfo.project.name.startsWith('mobile-'),
'Desktop journey',
);
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const findingsResp = await apiRequest(
page,
@@ -339,7 +340,7 @@ test.describe.serial(
testInfo.project.name.startsWith('mobile-'),
'Desktop journey',
);
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const resp = await apiRequest(page, '/api/ai/patrol/suppressions');
expect(resp.status()).toBe(200);
@@ -353,7 +354,7 @@ test.describe.serial(
testInfo.project.name.startsWith('mobile-'),
'Desktop journey',
);
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
const resp = await apiRequest(page, '/api/ai/patrol/dismissed');
expect(resp.status()).toBe(200);
@@ -365,7 +366,7 @@ test.describe.serial(
testInfo.project.name.startsWith('mobile-'),
'Desktop journey',
);
- await ensureAuthenticated(page);
+ await ensureJourneyReady(page);
await page.goto('/patrol');
await page.waitForURL('**/patrol**');
diff --git a/tests/integration/tests/journeys/journeyAuth.ts b/tests/integration/tests/journeys/journeyAuth.ts
new file mode 100644
index 0000000000..19e99a2acf
--- /dev/null
+++ b/tests/integration/tests/journeys/journeyAuth.ts
@@ -0,0 +1,105 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { test as base, type Page } from '@playwright/test';
+import {
+ apiRequest,
+ createAuthenticatedStorageState,
+ ensureSessionAuthenticated,
+ waitForPulseReady,
+} from '../helpers';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+/**
+ * Worker-scoped cookie-session fixture for the journey suite.
+ *
+ * Each Playwright test runs in a fresh browser context, and the token auth
+ * path (ensureAuthenticated) leaves page.request cookie-less, so API calls
+ * 401. Switching every test to ensureSessionAuthenticated fixes the cookie
+ * gap but forces a login POST per test — with ~30 journey tests that trips
+ * the backend's 10-logins/min/IP rate limit ("retry login form
+ * unavailable").
+ *
+ * This fixture logs in once per worker (createAuthenticatedStorageState
+ * further reuses a single shared cookie session across the whole run) and
+ * hands every test a pre-authenticated storage state. Test bodies still call
+ * ensureSessionAuthenticated, but with cookies already present login()
+ * short-circuits on the authenticated-redirect and issues no POST.
+ *
+ * Tests that must exercise the login flow itself (01 'health check',
+ * 01 'bootstrap and login land on Infrastructure') import the plain
+ * @playwright/test `test` instead so they start unauthenticated.
+ */
+export type JourneyWorkerFixtures = {
+ authStorageStatePath: string;
+};
+
+export const test = base.extend<Record<string, never>, JourneyWorkerFixtures>({
+ storageState: async ({ authStorageStatePath }, use) => {
+ await use(authStorageStatePath);
+ },
+ authStorageStatePath: [
+ async ({ browser }, use, workerInfo) => {
+ const storageStatePath = path.resolve(
+ __dirname,
+ '..',
+ '..',
+ 'tmp',
+ 'playwright-auth',
+ `journey-${workerInfo.project.name}-${workerInfo.workerIndex}.json`,
+ );
+ fs.mkdirSync(path.dirname(storageStatePath), { recursive: true });
+ await createAuthenticatedStorageState(browser, storageStatePath);
+ try {
+ await use(storageStatePath);
+ } finally {
+ fs.rmSync(storageStatePath, { force: true });
+ }
+ },
+ { scope: 'worker' },
+ ],
+});
+
+export { expect } from '@playwright/test';
+
+/**
+ * Ready-and-authenticated check for cookie-session journey tests.
+ *
+ * The worker fixture hands each test a valid cookie session via storageState.
+ * That cookie already authenticates page.request (apiRequest) and any direct
+ * navigation to a real app route. What it must NEVER do is route through '/'
+ * or '/login': those are pre-auth bootstrap paths that require a
+ * sessionStorage hint the storage-state cookie doesn't carry (issue #1574), so
+ * the app shows the login form there even with a valid session — which is
+ * exactly what a per-test login()/ensureSessionAuthenticated would trigger,
+ * issuing a real login POST every test and tripping the backend's
+ * 10-logins/min/IP rate limit.
+ *
+ * So we verify the cookie against the API directly (no navigation, no login),
+ * land the page on a non-bootstrap authenticated route for UI-facing tests,
+ * and only fall back to a real session login if the cookie is genuinely
+ * missing or expired. In the normal path this issues zero logins per test.
+ */
+export async function ensureJourneyReady(page: Page): Promise<void> {
+ await waitForPulseReady(page);
+
+ let authed = false;
+ try {
+ const res = await apiRequest(page, '/api/state');
+ authed = res.ok();
+ } catch {
+ authed = false;
+ }
+
+ if (!authed) {
+ // Cookie missing/expired — establish a real session (rare; the fixture
+ // normally guarantees a live cookie for the whole worker).
+ await ensureSessionAuthenticated(page);
+ return;
+ }
+
+ // Cookie is valid. Land on a real authenticated route (never '/') so
+ // UI-facing tests find the app shell already rendered.
+ await page.goto('/infrastructure', { waitUntil: 'domcontentloaded' });
+}