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
Make release dry-run diagnostics fail closed (#1758)
rcourtmanb92893351d15
diff --git a/.github/workflows/release-dry-run.yml b/.github/workflows/release-dry-run.ymlindex 8bd9847e2d..8a4579d3d5 100644--- a/.github/workflows/release-dry-run.yml+++ b/.github/workflows/release-dry-run.yml@@ -316,7 +316,10 @@ jobs:timeout 60 sh -c 'until curl -fsS http://localhost:7655/api/health > /dev/null; do sleep 2; done'echo "Running Playwright diagnostics..."- npx playwright test tests/00-diagnostic.spec.ts --reporter=list+ mkdir -p diagnostic-evidence+ set -o pipefail+ npx playwright test tests/00-diagnostic.spec.ts --project=chromium --retries=0 --reporter=list \+ 2>&1 | tee diagnostic-evidence/playwright-diagnostic.logecho "Running update API route smoke check..."STATUS=$(curl -s -o /tmp/update-status.json -w "%{http_code}" http://localhost:7655/api/updates/status || true)@@ -331,13 +334,31 @@ jobs:;;esac- docker compose -f docker-compose.test.yml down -v+ - name: Collect integration diagnostic runtime evidence+ if: always()+ working-directory: tests/integration+ run: |+ mkdir -p diagnostic-evidence+ docker compose -f docker-compose.test.yml ps --all \+ > diagnostic-evidence/docker-compose-ps.txt 2>&1 || true+ docker compose -f docker-compose.test.yml logs --no-color \+ > diagnostic-evidence/docker-compose.log 2>&1 || true- name: Cleanup integration environmentif: always()working-directory: tests/integrationrun: docker compose -f docker-compose.test.yml down -v || true+ - name: Upload integration diagnostic evidence+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: release-dry-run-integration-diagnostics+ path: |+ tests/integration/diagnostic-evidence/+ tests/integration/test-results/+ if-no-files-found: error+- name: Write rehearsal summaryif: always()env:diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.ymlindex 39e9b7b882..bfeb14bbb9 100644--- a/.github/workflows/test-e2e.yml+++ b/.github/workflows/test-e2e.yml@@ -58,6 +58,10 @@ jobs:working-directory: tests/integrationrun: npm run check:e2e-tiers+ - name: Validate stable failure reporting+ working-directory: tests/integration+ run: node --test scripts/report-stable-e2e-failures.test.mjs+e2e:name: Playwright Core E2E (shard ${{ matrix.shard }}/8)needs: tier-selection@@ -123,6 +127,16 @@ jobs:PULSE_MULTI_TENANT_ENABLED: "true"run: npm test -- --shard=${{ matrix.shard }}/8+ # Playwright's report artifacts preserve the full forensic record, but+ # artifact bodies and job logs require an authenticated GitHub session.+ # Project the bounded failed testcase identity into ordinary check+ # annotations so a red stable gate is diagnosable from the API without+ # rerunning, demoting, or skipping the failure.+ - name: Report stable-tier failures+ if: ${{ !cancelled() && steps.stable.outcome == 'failure' }}+ working-directory: tests/integration+ run: node scripts/report-stable-e2e-failures.mjs test-results/junit.xml+# Runs even when the stable tier failed (its data still counts toward# promotion), but not when the stable tier was skipped — that means the# environment never came up and every probation spec would fail on it.diff --git a/scripts/release_control/internal/release_preflight_test.py b/scripts/release_control/internal/release_preflight_test.pyindex bfbb34594c..75eed74194 100755--- a/scripts/release_control/internal/release_preflight_test.py+++ b/scripts/release_control/internal/release_preflight_test.py@@ -93,6 +93,113 @@ class ReleasePreflightTest(unittest.TestCase):self.assertIn("--if-configured", release)self.assertIn('PULSE_E2E_DIAGNOSTIC: "1"', workflow)+ def assert_release_dry_run_diagnostic_contract(+ self, workflow: str, diagnostic: str+ ) -> None:+ installed_browser = re.search(+ r"npx playwright install --with-deps ([a-z-]+)", workflow+ )+ diagnostic_step = re.search(+ r" - name: Run integration diagnostics\n(?P<body>.*?)(?=\n - name:)",+ workflow,+ flags=re.DOTALL,+ )+ self.assertIsNotNone(diagnostic_step)+ step_body = diagnostic_step.group("body")+ diagnostic_command = re.search(+ r"npx playwright test tests/00-diagnostic\.spec\.ts (?P<args>[^\n]+)",+ step_body,+ )+ self.assertIsNotNone(installed_browser)+ self.assertIsNotNone(diagnostic_command)+ self.assertIn('PULSE_E2E_DIAGNOSTIC: "1"', step_body)+ self.assertLess(+ step_body.index("set -o pipefail"),+ step_body.index("npx playwright test tests/00-diagnostic.spec.ts"),+ )+ self.assertIn("2>&1 | tee diagnostic-evidence/playwright-diagnostic.log", step_body)+ selected_browser = re.search(+ r"--project(?:=|\s+)([a-z-]+)", diagnostic_command.group("args")+ )+ self.assertIsNotNone(+ selected_browser,+ "release diagnostic must select the one browser installed by the job",+ )+ self.assertEqual(selected_browser.group(1), installed_browser.group(1))+ self.assertIn("--retries=0", diagnostic_command.group("args"))++ self.assertRegex(+ diagnostic,+ r"test\.describe\.configure\(\{\s*retries:\s*0\s*\}\);",+ )+ self.assertIn("test.setTimeout(120_000)", diagnostic)++ for required_diagnostic in (+ "API readiness failed:",+ "dependencies.monitor",+ "dependencies.scheduler",+ "dependencies.websocket",+ "/api/security/status",+ "hasAuthentication",+ "Rendered UI readiness failed:",+ "Pulse app shell did not render within 20s",+ "effectiveRenderedOpacity",+ "stayed transparent",+ "Pulse Setup Wizard",+ "Paste your bootstrap token",+ "diagnostic-evidence",+ "release-dry-run-rendered-readiness-chromium.png",+ "testInfo.attach(",+ "DIAGNOSTIC EVIDENCE ERROR:",+ "if (!readinessFailed)",+ ):+ self.assertIn(required_diagnostic, diagnostic)++ self.assertIn("Collect integration diagnostic runtime evidence", workflow)+ self.assertIn("Upload integration diagnostic evidence", workflow)+ self.assertIn("if-no-files-found: error", workflow)+ self.assertIn("tests/integration/test-results/", workflow)+ self.assertNotIn("expect(true).toBe(true)", diagnostic)+ self.assertNotIn("await page.waitForTimeout(3000)", diagnostic)++ def test_release_dry_run_diagnostic_contract(self) -> None:+ workflow = (ROOT / ".github/workflows/release-dry-run.yml").read_text()+ diagnostic = (+ ROOT / "tests/integration/tests/00-diagnostic.spec.ts"+ ).read_text()++ self.assert_release_dry_run_diagnostic_contract(workflow, diagnostic)++ legacy_workflow = workflow.replace(+ " --project=chromium --retries=0", "", 1+ )+ with self.assertRaises(AssertionError):+ self.assert_release_dry_run_diagnostic_contract(+ legacy_workflow, diagnostic+ )++ retrying_diagnostic = diagnostic.replace(+ "test.describe.configure({ retries: 0 });", "", 1+ )+ with self.assertRaises(AssertionError):+ self.assert_release_dry_run_diagnostic_contract(+ workflow, retrying_diagnostic+ )++ unconditional_pass = f"{diagnostic}\nexpect(true).toBe(true);\n"+ with self.assertRaises(AssertionError):+ self.assert_release_dry_run_diagnostic_contract(+ workflow, unconditional_pass+ )++ evidence_failure_ignored = diagnostic.replace(+ "if (!readinessFailed) {", "if (false) {", 1+ )+ with self.assertRaises(AssertionError):+ self.assert_release_dry_run_diagnostic_contract(+ workflow, evidence_failure_ignored+ )+def test_worker_has_no_publication_or_signing_authority(self) -> None:worker = (ROOT / "scripts/release-preflight-worker.sh").read_text()runner = (ROOT / "scripts/run-release-preflight.sh").read_text()diff --git a/tests/integration/scripts/report-stable-e2e-failures.mjs b/tests/integration/scripts/report-stable-e2e-failures.mjsnew file mode 100644index 0000000000..e8d26f09cd--- /dev/null+++ b/tests/integration/scripts/report-stable-e2e-failures.mjs@@ -0,0 +1,119 @@+#!/usr/bin/env node++import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const decodeXml = (value) =>+ value+ .replaceAll('"', '"')+ .replaceAll(''', "'")+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replaceAll('&', '&');++const attribute = (source, name) => {+ const match = source.match(new RegExp(`\\b${name}="([^"]*)"`));+ return match ? decodeXml(match[1]) : '';+};++const stripCdata = (value) =>+ decodeXml(value.replace(/^<!\[CDATA\[/, '').replace(/\]\]>$/, ''));++const compactFailure = (value) => {+ const lines = stripCdata(value)+ .replace(/\u001b\[[0-9;]*m/g, '')+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(Boolean);+ const plain =+ lines.find((line) =>+ /^(?:[A-Za-z]*Error:|Error:|Timeout \d|Timed out|Expected |Received )/.test(+ line,+ ),+ ) || lines.find((line) => !line.startsWith('at '));+ return (plain || 'Playwright reported a stable-tier failure').slice(0, 1200);+};++const sourceFile = (classname) => {+ const normalized = classname.replaceAll('\\', '/');+ const match = normalized.match(+ /(?:^| › )((?:journeys\/)?[^ ›]+\.spec\.ts)(?: › |$)/,+ );+ return match ? `tests/integration/tests/${match[1]}` : '';+};++export const parseFailedTestcases = (xml) => {+ const failures = [];+ const testcasePattern = /<testcase\b([^>]*?)(?<!\/)>([\s\S]*?)<\/testcase>/g;+ for (const testcase of xml.matchAll(testcasePattern)) {+ const body = testcase[2];+ const failure = body.match(/<(?:failure|error)\b([^>]*)>([\s\S]*?)<\/(?:failure|error)>/);+ if (!failure) continue;++ const classname = attribute(testcase[1], 'classname');+ const name = attribute(testcase[1], 'name') || 'Unnamed Playwright test';+ const bodyMessage = compactFailure(failure[2]);+ const summaryMessage = attribute(failure[1], 'message');+ const message = /^(?:[A-Za-z]*Error:|Error:|Timeout \d|Timed out|Expected |Received )/.test(+ bodyMessage,+ )+ ? bodyMessage+ : summaryMessage || bodyMessage;+ failures.push({+ file: sourceFile(classname),+ message: compactFailure(message),+ name,+ });+ }+ return failures;+};++const escapeCommandData = (value) =>+ value.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A');++const escapeCommandProperty = (value) =>+ escapeCommandData(value).replaceAll(':', '%3A').replaceAll(',', '%2C');++export const githubAnnotations = (failures) => {+ if (failures.length === 0) {+ return [+ '::error title=Stable E2E failure details unavailable::' ++ 'The stable step failed without a testcase failure in JUnit XML; inspect the retained Playwright report and runtime logs.',+ ];+ }++ return failures.map(({ file, message, name }) => {+ const properties = [+ file ? `file=${escapeCommandProperty(file)}` : '',+ `title=${escapeCommandProperty(`Stable E2E failure: ${name}`)}`,+ ]+ .filter(Boolean)+ .join(',');+ return `::error ${properties}::${escapeCommandData(message)}`;+ });+};++const isMain =+ process.argv[1] &&+ path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));++if (isMain) {+ const reportPath = path.resolve(process.argv[2] || 'test-results/junit.xml');+ let xml;+ try {+ xml = fs.readFileSync(reportPath, 'utf8');+ } catch (error) {+ console.log(+ '::error title=Stable E2E JUnit report unavailable::' ++ escapeCommandData(`Could not read ${reportPath}: ${error.message}`),+ );+ process.exit(0);+ }++ const failures = parseFailedTestcases(xml);+ console.log(`Stable E2E JUnit failures: ${failures.length}`);+ for (const annotation of githubAnnotations(failures)) {+ console.log(annotation);+ }+}diff --git a/tests/integration/scripts/report-stable-e2e-failures.test.mjs b/tests/integration/scripts/report-stable-e2e-failures.test.mjsnew file mode 100644index 0000000000..7f5ae1b339--- /dev/null+++ b/tests/integration/scripts/report-stable-e2e-failures.test.mjs@@ -0,0 +1,57 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import {+ githubAnnotations,+ parseFailedTestcases,+} from './report-stable-e2e-failures.mjs';++test('extracts failed and errored Playwright testcases without reporting passes', () => {+ const xml = `<?xml version="1.0"?>+ <testsuites>+ <testcase name="passes" classname="chromium › 63-pbs-active-tasks.spec.ts › PBS active tasks" />+ <testcase name="shows a running task" classname="chromium › 63-pbs-active-tasks.spec.ts › PBS active tasks">+ <failure message="63-pbs-active-tasks.spec.ts:83:3 shows a running task"><![CDATA[[chromium] › stable test+ Error: Expected "running" but received "stopped"]]></failure>+ </testcase>+ <testcase name="loads history" classname="chromium › journeys/07-audit-log-resilience.spec.ts › audit log">+ <error><![CDATA[[31mTimeout 10000ms exceeded[39m+ at tests/journeys/07-audit-log-resilience.spec.ts:30:1]]></error>+ </testcase>+ </testsuites>`;++ assert.deepEqual(parseFailedTestcases(xml), [+ {+ file: 'tests/integration/tests/63-pbs-active-tasks.spec.ts',+ message: 'Error: Expected "running" but received "stopped"',+ name: 'shows a running task',+ },+ {+ file: 'tests/integration/tests/journeys/07-audit-log-resilience.spec.ts',+ message: 'Timeout 10000ms exceeded',+ name: 'loads history',+ },+ ]);+});++test('emits bounded GitHub annotations with command escaping', () => {+ assert.deepEqual(+ githubAnnotations([+ {+ file: 'tests/integration/tests/example.spec.ts',+ message: 'expected 100%, got 0%\nsecond line',+ name: 'renders: cards, tables',+ },+ ]),+ [+ '::error file=tests/integration/tests/example.spec.ts,title=Stable E2E failure%3A renders%3A cards%2C tables::expected 100%25, got 0%25%0Asecond line',+ ],+ );+});++test('keeps a failed stable step observable when JUnit has no testcase failure', () => {+ assert.match(+ githubAnnotations([])[0],+ /^::error title=Stable E2E failure details unavailable::/,+ );+});diff --git a/tests/integration/tests/00-diagnostic.spec.ts b/tests/integration/tests/00-diagnostic.spec.tsindex b026fd05e9..23b0272b0b 100644--- a/tests/integration/tests/00-diagnostic.spec.ts+++ b/tests/integration/tests/00-diagnostic.spec.ts@@ -1,139 +1,349 @@/**- * Diagnostic test to understand why login is failing+ * Fail-closed API and rendered-UI readiness diagnostic for release rehearsals.*/-import { test, expect, type Page } from '@playwright/test';-import { waitForPulseReady } from './helpers';+import fs from "node:fs/promises";+import path from "node:path";++import { test, expect, type Locator, type Page } from "@playwright/test";+import { waitForAppShell, waitForPulseReady } from "./helpers";++type HealthPayload = {+ status?: unknown;+ dependencies?: {+ monitor?: unknown;+ scheduler?: unknown;+ websocket?: unknown;+ };+};++type SecurityStatusPayload = {+ hasAuthentication?: unknown;+ hideLocalLogin?: unknown;+ ssoProviders?: Array<{+ name?: unknown;+ displayName?: unknown;+ }>;+};const truthy = (value: string | undefined) => {if (!value) return false;- return ['1', 'true', 'yes', 'on'].includes(value.trim().toLowerCase());+ return ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());};-const gotoWithHealthRetry = async (page: Page, url: string, attempts = 3): Promise<void> => {+const compact = (value: string, limit = 1000): string =>+ value.replace(/\s+/g, " ").trim().slice(0, limit);++const errorMessage = (error: unknown): string =>+ error instanceof Error ? error.message : String(error);++const effectiveRenderedOpacity = (locator: Locator): Promise<number> =>+ locator.evaluate((element) => {+ let opacity = 1;+ for (+ let current: Element | null = element;+ current;+ current = current.parentElement+ ) {+ const style = window.getComputedStyle(current);+ if (style.display === "none" || style.visibility !== "visible") {+ return 0;+ }+ opacity *= Number.parseFloat(style.opacity || "1");+ }+ return opacity;+ });++const gotoWithHealthRetry = async (+ page: Page,+ url: string,+ attempts = 3,+): Promise<void> => {let lastError: unknown = null;for (let attempt = 1; attempt <= attempts; attempt++) {try {await waitForPulseReady(page, 30_000);- await page.goto(url);+ await page.goto(url, { waitUntil: "domcontentloaded" });return;} catch (error) {lastError = error;if (attempt === attempts) {- throw error;+ break;}- console.log(`Navigation attempt ${attempt} failed, retrying...`);+ console.log(+ `Navigation attempt ${attempt}/${attempts} failed: ${errorMessage(error)}; retrying...`,+ );await page.waitForTimeout(1_000);}}- throw lastError ?? new Error(`Failed to navigate to ${url}`);+ throw new Error(+ `Rendered UI readiness failed: could not navigate to ${url} after ${attempts} attempts: ${errorMessage(lastError)}`,+ );};-test.describe('Login Diagnostic', () => {+test.describe("Release readiness diagnostic", () => {+ // A readiness failure must remain red. CI's general retry policy is useful+ // for the wider suite but would let a flaky release preflight pass.+ test.describe.configure({ retries: 0 });+test.skip(!truthy(process.env.PULSE_E2E_DIAGNOSTIC),- 'Set PULSE_E2E_DIAGNOSTIC=1 to enable verbose login diagnostics',+ "Set PULSE_E2E_DIAGNOSTIC=1 to enable release readiness diagnostics",);- test('diagnose login page and API access', async ({ page }) => {- // Capture all console messages including errors- page.on('console', msg => {- const type = msg.type();- const text = msg.text();- if (type === 'error') {- console.log('BROWSER ERROR:', text);- } else if (type === 'warning') {- console.log('BROWSER WARNING:', text);- } else {- console.log('BROWSER CONSOLE:', text);+ test("API and browser shell are genuinely ready", async ({+ page,+ }, testInfo) => {+ test.setTimeout(120_000);++ const consoleErrors: string[] = [];+ const pageErrors: string[] = [];+ const requestFailures: string[] = [];++ page.on("console", (message) => {+ const text = `${message.type().toUpperCase()}: ${message.text()}`;+ console.log(`BROWSER ${text}`);+ if (message.type() === "error") {+ consoleErrors.push(text);}});-- // Capture page errors- page.on('pageerror', err => {- console.log('PAGE ERROR:', err.message);- console.log('Stack:', err.stack);+ page.on("pageerror", (error) => {+ const text = errorMessage(error);+ pageErrors.push(text);+ console.log(`PAGE ERROR: ${text}`);});-- // Track network requests- page.on('request', req => {- console.log('REQUEST:', req.method(), req.url());+ page.on("requestfailed", (request) => {+ const text = `${request.method()} ${request.url()}: ${request.failure()?.errorText ?? "unknown failure"}`;+ requestFailures.push(text);+ console.log(`REQUEST FAILED: ${text}`);});- page.on('response', async res => {- console.log('RESPONSE:', res.status(), res.url());- if (res.url().includes('/api/security/status')) {- try {- const body = await res.json();- console.log('SECURITY STATUS RESPONSE:', JSON.stringify(body, null, 2));- } catch (e) {- console.log('Failed to parse response:', e);- }- }- });+ let renderedSurface = "unknown";+ let healthBody = "";+ let securityBody = "";+ let readinessFailed = false;+ try {+ await waitForPulseReady(page, 30_000).catch((error) => {+ throw new Error(+ `API readiness failed: GET /api/health did not become reachable within 30s: ${errorMessage(error)}`,+ );+ });- console.log('\n=== Navigating to login page ===');- await gotoWithHealthRetry(page, '/');- console.log('Page loaded');+ const healthResponse = await page.request+ .get("/api/health")+ .catch((error) => {+ throw new Error(+ `API readiness failed: GET /api/health could not complete: ${errorMessage(error)}`,+ );+ });+ healthBody = await healthResponse.text();+ expect(+ healthResponse.status(),+ `API readiness failed: GET /api/health returned HTTP ${healthResponse.status()}; body=${compact(healthBody)}`,+ ).toBe(200);- // Wait a bit for any async operations- await page.waitForTimeout(3000);+ let healthPayload: HealthPayload;+ try {+ healthPayload = JSON.parse(healthBody) as HealthPayload;+ } catch (error) {+ throw new Error(+ `API readiness failed: GET /api/health returned invalid JSON: ${errorMessage(error)}; body=${compact(healthBody)}`,+ );+ }+ const dependencies = healthPayload.dependencies ?? {};+ expect(+ healthPayload.status,+ `API readiness failed: health status was ${JSON.stringify(healthPayload.status)}; body=${compact(healthBody)}`,+ ).toBe("healthy");+ expect(+ dependencies.monitor,+ `API readiness failed: dependencies.monitor was not ready; body=${compact(healthBody)}`,+ ).toBe(true);+ expect(+ dependencies.scheduler,+ `API readiness failed: dependencies.scheduler was not ready; body=${compact(healthBody)}`,+ ).toBe(true);+ expect(+ dependencies.websocket,+ `API readiness failed: dependencies.websocket was not ready; body=${compact(healthBody)}`,+ ).toBe(true);+ console.log(`API readiness passed: ${compact(healthBody)}`);- console.log('\n=== Checking page state ===');- const url = page.url();- console.log('Current URL:', url);+ await gotoWithHealthRetry(page, "/");+ await waitForAppShell(page, 20_000).catch((error) => {+ throw new Error(+ `Rendered UI readiness failed: Pulse app shell did not render within 20s: ${errorMessage(error)}`,+ );+ });- // Check what's actually on the page- const bodyText = await page.locator('body').textContent();- console.log('Page text content:', bodyText?.substring(0, 500));+ const root = page.locator("#root");+ await expect(+ root,+ `Rendered UI readiness failed: #root was not visible at ${page.url()}`,+ ).toBeVisible();+ await expect+ .poll(() => root.evaluate((element) => element.children.length), {+ message: `Rendered UI readiness failed: #root stayed empty at ${page.url()}`,+ timeout: 20_000,+ })+ .toBeGreaterThan(0);- // Check the actual DOM structure- const bodyHTML = await page.locator('body').innerHTML();- console.log('Page HTML structure:', bodyHTML.substring(0, 1000));+ const securityProbe = await page.evaluate(async () => {+ try {+ const response = await fetch("/api/security/status", {+ cache: "no-store",+ credentials: "same-origin",+ });+ return {+ body: await response.text(),+ ok: response.ok,+ status: response.status,+ };+ } catch (error) {+ return {+ body: "",+ error: error instanceof Error ? error.message : String(error),+ ok: false,+ status: 0,+ };+ }+ });+ securityBody = securityProbe.body;+ expect(+ securityProbe.ok,+ `API readiness failed: browser GET /api/security/status returned HTTP ${securityProbe.status}` ++ `${securityProbe.error ? ` error=${securityProbe.error}` : ""}; body=${compact(securityBody)}`,+ ).toBe(true);- // Check for various elements- const usernameField = page.locator('input[name="username"]');- const usernameVisible = await usernameField.isVisible().catch(() => false);- console.log('Username field visible:', usernameVisible);+ let securityPayload: SecurityStatusPayload;+ try {+ securityPayload = JSON.parse(securityBody) as SecurityStatusPayload;+ } catch (error) {+ throw new Error(+ `API readiness failed: browser GET /api/security/status returned invalid JSON: ${errorMessage(error)}; body=${compact(securityBody)}`,+ );+ }+ expect(+ typeof securityPayload.hasAuthentication,+ `API readiness failed: /api/security/status hasAuthentication was not boolean; body=${compact(securityBody)}`,+ ).toBe("boolean");- const setupHeading = page.locator('h1, h2').filter({ hasText: /setup|bootstrap|getting started/i });- const setupVisible = await setupHeading.isVisible().catch(() => false);- console.log('Setup/bootstrap heading visible:', setupVisible);+ const welcomeHeading = page.getByRole("heading", {+ name: "Welcome to Pulse",+ });+ await expect(+ welcomeHeading,+ `Rendered UI readiness failed: the Pulse welcome heading was not visible at ${page.url()}`,+ ).toBeVisible();- const loginHeading = page.locator('h1, h2').filter({ hasText: /login|sign in/i });- const loginVisible = await loginHeading.isVisible().catch(() => false);- console.log('Login heading visible:', loginVisible);+ let renderedSurfaceControl: Locator;+ if (securityPayload.hasAuthentication === false) {+ renderedSurface = "first-run setup wizard";+ await expect(+ page.getByRole("main", { name: "Pulse Setup Wizard" }),+ `Rendered UI readiness failed: security status requires first-run setup, but the setup wizard was not visible; body=${compact(securityBody)}`,+ ).toBeVisible();+ await expect(+ page.getByPlaceholder("Paste your bootstrap token"),+ `Rendered UI readiness failed: the setup wizard did not render its bootstrap-token control; body=${compact(securityBody)}`,+ ).toBeVisible();+ renderedSurfaceControl = page.getByPlaceholder(+ "Paste your bootstrap token",+ );+ } else if (securityPayload.hideLocalLogin !== true) {+ renderedSurface = "local login";+ await expect(+ page.getByLabel("Username"),+ `Rendered UI readiness failed: authentication is configured, but the username control was not visible; body=${compact(securityBody)}`,+ ).toBeVisible();+ await expect(page.getByLabel("Password")).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Sign in to Pulse" }),+ ).toBeVisible();+ renderedSurfaceControl = page.getByRole("button", {+ name: "Sign in to Pulse",+ });+ } else {+ renderedSurface = "SSO login";+ const providers = (securityPayload.ssoProviders ?? [])+ .map((provider) =>+ String(provider.displayName || provider.name || "").trim(),+ )+ .filter(Boolean);+ expect(+ providers.length,+ `Rendered UI readiness failed: local login is hidden but /api/security/status advertised no SSO provider; body=${compact(securityBody)}`,+ ).toBeGreaterThan(0);+ await expect(+ page.getByRole("button", { name: `Continue with ${providers[0]}` }),+ `Rendered UI readiness failed: SSO provider ${JSON.stringify(providers[0])} was not rendered; body=${compact(securityBody)}`,+ ).toBeVisible();+ renderedSurfaceControl = page.getByRole("button", {+ name: `Continue with ${providers[0]}`,+ });+ }- // Take screenshot- await page.screenshot({ path: 'test-results/login-diagnostic.png', fullPage: true });- console.log('Screenshot saved to test-results/login-diagnostic.png');+ await expect+ .poll(() => effectiveRenderedOpacity(renderedSurfaceControl), {+ message: `Rendered UI readiness failed: ${renderedSurface} control or an ancestor stayed transparent`,+ timeout: 10_000,+ })+ .toBeGreaterThan(0.99);+ const renderedControlBounds = await renderedSurfaceControl.boundingBox();+ expect(+ (renderedControlBounds?.width ?? 0) *+ (renderedControlBounds?.height ?? 0),+ `Rendered UI readiness failed: ${renderedSurface} control had no rendered area`,+ ).toBeGreaterThan(0);- console.log('\n=== Fetching API from browser context ===');- const apiResponse = await page.evaluate(async () => {+ expect(+ pageErrors,+ `Rendered UI readiness failed: uncaught page errors were observed: ${JSON.stringify(pageErrors)}`,+ ).toEqual([]);+ console.log(+ `Rendered UI readiness passed: surface=${renderedSurface}; url=${page.url()}; consoleErrors=${consoleErrors.length}; requestFailures=${requestFailures.length}`,+ );+ } catch (error) {+ readinessFailed = true;+ const appState = await page+ .evaluate(() => {+ const root = document.getElementById("root");+ return {+ bodyText: document.body?.innerText?.slice(0, 800) ?? "",+ rootChildren: root?.children.length ?? 0,+ rootText: root?.textContent?.slice(0, 800) ?? "",+ url: window.location.href,+ };+ })+ .catch((stateError) => ({+ stateError: errorMessage(stateError),+ url: page.url(),+ }));+ throw new Error(+ `${errorMessage(error)}; appState=${JSON.stringify(appState)}; healthBody=${compact(healthBody)}; ` ++ `securityBody=${compact(securityBody)}; pageErrors=${JSON.stringify(pageErrors)}; ` ++ `consoleErrors=${JSON.stringify(consoleErrors.slice(-10))}; requestFailures=${JSON.stringify(requestFailures.slice(-10))}`,+ );+ } finally {try {- const res = await fetch('/api/security/status');- const data = await res.json();- return { ok: res.ok, status: res.status, data };- } catch (err) {- return { error: String(err) };+ const evidenceDirectory = path.resolve("diagnostic-evidence");+ await fs.mkdir(evidenceDirectory, { recursive: true });+ const evidencePath = path.join(+ evidenceDirectory,+ "release-dry-run-rendered-readiness-chromium.png",+ );+ await page.screenshot({ fullPage: true, path: evidencePath });+ await testInfo.attach("release-dry-run-rendered-readiness-chromium", {+ path: evidencePath,+ contentType: "image/png",+ });+ } catch (attachmentError) {+ const evidenceError = `DIAGNOSTIC EVIDENCE ERROR: could not retain rendered UI screenshot: ${errorMessage(attachmentError)}`;+ console.error(evidenceError);+ if (!readinessFailed) {+ throw new Error(evidenceError);+ }}- });- console.log('Browser fetch result:', JSON.stringify(apiResponse, null, 2));-- console.log('\n=== Checking if app attempted to mount ===');- const appState = await page.evaluate(() => {- const root = document.getElementById('root');- return {- rootExists: !!root,- rootChildren: root?.children.length || 0,- rootHTML: root?.innerHTML || '',- hasScriptTag: !!document.querySelector('script[src*="index"]'),- scriptLoaded: (window as any).__PULSE_APP_LOADED__ || false,- };- });- console.log('App mount state:', JSON.stringify(appState, null, 2));-- // This test always passes - it's just for diagnostics- expect(true).toBe(true);+ }});});