Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

84.3 KB
Raw Blame
import assert from 'node:assert/strict';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import process from 'node:process';
import { inspect } from 'node:util';
import { chromium } from 'playwright';

import { assertNoAxeViolations } from './accessibility/axe.mjs';
import { startAssetFaultProxy } from './asset-fault-proxy.mjs';
import { observeBrowserDiagnostics, waitForRenderedMedia, withBrowserNavigation } from './browser-validation.mjs';
import { MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME } from './mock-backend-fixtures.mjs';
import { startMockBackend } from './mock-backend.mjs';
import { killPreview, spawnPreview } from './preview-server.mjs';

const root = resolve(import.meta.dirname, '..');
const port = Number(process.env.INVOKEAI_ACCESSIBILITY_PORT ?? 4178);
const origin = `http://127.0.0.1:${String(port)}`;
const backendPort = Number(process.env.INVOKEAI_ACCESSIBILITY_BACKEND_PORT ?? 4179);
const backendOrigin = `http://127.0.0.1:${String(backendPort)}`;
const representativeProjectPath = '/#/app?project=fixture-project-001';
const requestedJourney = process.env.INVOKEAI_ACCESSIBILITY_JOURNEY;

const waitForPreview = async () => {
  const deadline = Date.now() + 20_000;

  while (Date.now() < deadline) {
    try {
      const response = await fetch(origin);

      if (response.ok) {
        return;
      }
    } catch {
      // Preview is still starting.
    }

    await new Promise((resolveWait) => {
      setTimeout(resolveWait, 100);
    });
  }

  throw new Error(`Vite preview did not become ready at ${origin}.`);
};

const waitForSettledDocument = async (page) => {
  await page.evaluate(async () => {
    await document.fonts.ready;
    // Wait for animations to finish before contrast audits. Keep this serialized helper aligned with
    // settleAnimations.testing.ts.
    await Promise.allSettled(
      document
        .getAnimations({ subtree: true })
        .filter((animation) => {
          const timing = animation.effect?.getComputedTiming();
          const duration = typeof timing?.duration === 'number' ? timing.duration : 0;

          // A spinner, a shimmering skeleton, or a paused animation never finishes.
          return (
            timing?.iterations !== Infinity &&
            Number.isFinite(duration) &&
            animation.playbackRate !== 0 &&
            animation.playState !== 'paused'
          );
        })
        .map((animation) => animation.finished)
    );
    await new Promise((resolveFrame) => {
      requestAnimationFrame(() => requestAnimationFrame(resolveFrame));
    });
  });
};

const openRepresentativePage = async (browser, path, viewport = { height: 1_000, width: 1_440 }, themeId) => {
  const resetResponse = await fetch(`${backendOrigin}/__reset?profile=representative`, { method: 'POST' });

  if (!resetResponse.ok) {
    throw new Error(`Could not reset representative backend: ${resetResponse.status}.`);
  }

  if (themeId) {
    const response = await fetch(
      `${backendOrigin}/api/v1/client_state/default/set_by_key?key=webv2%3Aworkbench-settings`,
      {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(JSON.stringify({ betaNoticeAcknowledged: true, whatsNewSeenVersion: 'fixture', themeId })),
      }
    );
    assert.ok(response.ok, `Could not set ${themeId} accessibility fixture theme.`);
  }

  const context = await browser.newContext({
    colorScheme: themeId === 'light' ? 'light' : 'dark',
    reducedMotion: 'reduce',
    viewport,
  });
  const page = await context.newPage();
  const pageErrors = [];
  const consoleErrors = [];
  await observeBrowserDiagnostics(page, {
    onError: (event) => {
      pageErrors.push(new Error(JSON.stringify(event)));
      if (event.kind === 'console') {
        consoleErrors.push(event.message);
      }
    },
  });

  await page.goto(`${origin}${path}`, { waitUntil: 'domcontentloaded' });

  return { consoleErrors, context, page, pageErrors };
};

const waitForHome = async (page) => {
  await page.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();
  await page.getByRole('link', { exact: true, name: 'Open Fixture Project 001' }).waitFor();
  await page.getByText('Generate from text', { exact: true }).waitFor();
};

/** Use the level-2 library heading; the shell has a hidden level-1 heading with the same name. */
const waitForProjects = async (page) => {
  await page.getByRole('heading', { exact: true, level: 2, name: 'Projects' }).waitFor();
  await page.getByRole('link', { exact: true, name: 'Open Fixture Project 001' }).waitFor();
};

const waitForModels = async (page) => {
  await page.getByLabel('Model library', { exact: true }).waitFor();
  await page.getByText('Fixture Model 001', { exact: true }).waitFor();
};

const waitForNodes = async (page) => {
  await page.getByRole('textbox', { exact: true, name: 'Search node packs' }).waitFor();
  await page.getByText('fixture-pack-01', { exact: true }).waitFor();
};

const presetStrip = (page) => page.getByRole('tablist', { exact: true, name: 'Layout preset' });

const waitForWorkbench = async (page) => {
  await page.getByRole('main', { exact: true, name: 'Fixture Project 001' }).waitFor();
  await presetStrip(page).waitFor();
  await waitForRenderedMedia(page);
};

const BUILT_IN_BOTTOM_WIDGETS = [
  'Autosave',
  'Gallery',
  'Notifications',
  'Queue status',
  'Server Status',
  'Shortcuts',
  'Workflow',
];
const centerViewTrigger = (page, label) => page.getByRole('button', { exact: true, name: `Center view: ${label}` });

const selectLayoutPreset = async (page, preset, centerView) => {
  // Custom presets and Workflow tabs can share prefixes.
  const name = new RegExp(`^${preset}(, unsaved changes)?$`);
  const strip = presetStrip(page);
  const selected = strip.getByRole('tab', { name, selected: true });

  if ((await selected.count()) === 0) {
    await strip.getByRole('tab', { name }).click();
  }

  await selected.waitFor();
  await centerViewTrigger(page, centerView).waitFor();
};

const centerRegion = (page) => page.getByRole('region', { exact: true, name: 'Center view' });

const selectCenterView = async (page, from, to) => {
  await centerViewTrigger(page, from).click();
  await page.getByRole('menuitemradio', { exact: true, name: to }).click();
  await centerViewTrigger(page, to).waitFor();
};

const surfaces = [
  {
    id: 'launchpad-home-representative',
    path: '/#/',
    ready: waitForHome,
  },
  {
    id: 'launchpad-projects-representative',
    path: '/#/projects',
    ready: waitForProjects,
  },
  {
    id: 'launchpad-preferences-intermediates-representative',
    path: '/#/projects',
    ready: async (page) => {
      await page
        .getByRole('navigation', { exact: true, name: 'Launchpad sections' })
        .getByRole('link', { exact: true, name: 'Preferences' })
        .click();
      await page
        .getByRole('list', { exact: true, name: 'Settings section' })
        .getByRole('button', { exact: true, name: 'Intermediates' })
        .click();
      await page.getByRole('heading', { exact: true, level: 2, name: 'Intermediates' }).waitFor();
      await page.getByRole('textbox', { exact: true, name: 'Search projects' }).waitFor();
      await page.getByRole('checkbox', { exact: true, name: 'Select Fixture Project 001' }).waitFor();
    },
    representative: true,
  },
  {
    id: 'launchpad-fonts-empty',
    path: '/#/fonts',
    ready: async (page) => {
      await page.getByRole('textbox', { exact: true, name: 'Search fonts' }).waitFor();
      await page.getByText('No fonts available', { exact: true }).waitFor();
    },
  },
  {
    id: 'launchpad-models-representative',
    path: '/#/models',
    ready: waitForModels,
  },
  {
    id: 'launchpad-nodes-representative',
    path: '/#/nodes',
    ready: waitForNodes,
  },
  {
    id: 'workbench-default-representative',
    path: representativeProjectPath,
    ready: async (page) => {
      await waitForWorkbench(page);
      await centerViewTrigger(page, 'Preview').waitFor();
    },
  },
  {
    id: 'workbench-canvas-representative',
    path: representativeProjectPath,
    ready: async (page) => {
      await waitForWorkbench(page);
      await selectLayoutPreset(page, 'Edit', 'Canvas');
      await waitForRenderedMedia(page, { canvas: true });
      await page.getByRole('tab', { exact: true, name: 'Properties', selected: true }).waitFor();
      await page.getByRole('tabpanel').getByRole('group', { exact: true, name: 'Layer' }).waitFor();
    },
  },
  {
    id: 'workbench-canvas-first-spline-focus',
    path: representativeProjectPath,
    ready: async (page) => {
      await waitForWorkbench(page);
      await selectLayoutPreset(page, 'Edit', 'Canvas');
      await waitForRenderedMedia(page, { canvas: true });
      const spline = page.getByRole('button', { exact: true, name: 'Spline Edit' });
      await spline.waitFor();
      assert.equal(await spline.getAttribute('aria-pressed'), 'false');

      const surface = page.locator('[data-canvas-surface]');
      await surface.focus();
      const original = await surface.elementHandle();
      try {
        assert.equal(await original.evaluate((element) => document.activeElement === element), true);
        await page.keyboard.press('s');
        await page.getByRole('button', { exact: true, name: 'Spline Edit', pressed: true }).waitFor();
        assert.equal(
          await original.evaluate((element) => element.isConnected && document.activeElement === element),
          true,
          'The first Spline shortcut must preserve the original focused Canvas surface.'
        );
      } finally {
        await original.dispose();
      }
    },
  },
  {
    id: 'workbench-canvas-control-layer',
    path: representativeProjectPath,
    ready: async (page) => {
      const seeded = await fetch(`${backendOrigin}/__models`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ set: 'control-sdxl' }),
      });
      assert.ok(seeded.ok, `Could not seed control models: ${String(seeded.status)}.`);
      await withBrowserNavigation(page, () => page.reload({ waitUntil: 'domcontentloaded' }));
      await waitForWorkbench(page);
      await selectLayoutPreset(page, 'Edit', 'Canvas');
      await waitForRenderedMedia(page, { canvas: true });
      // The seeded control models are SDXL, so switch to an SDXL main.
      await page.getByText('Fixture Model 001', { exact: true }).click();
      const search = page.getByRole('combobox', { name: /^Search / });
      await search.fill('Fixture Model 006');
      await page.getByRole('option', { name: /Fixture Model 006(?!\d)/ }).click();
      await search.waitFor({ state: 'hidden' });
      await page.getByText('Fixture Model 006', { exact: true }).waitFor();
      await page.getByRole('button', { exact: true, name: 'Add layer' }).click();
      await page.getByRole('menuitem', { exact: true, name: 'Control layer' }).click();
      const type = page.getByRole('combobox', { exact: true, name: 'Type' });
      await type.waitFor();
      await page.getByRole('note').filter({ hasText: 'Add an image' }).waitFor();
      await waitForSettledDocument(page);
      await assertNoAxeViolations(page, 'workbench-canvas-control-layer-untyped');
      await type.click();
      await page.getByRole('option', { name: /^Depth/ }).click();
      await page
        .getByRole('combobox', { exact: true, name: 'Model' })
        .filter({ hasText: 'Choose a depth model' })
        .waitFor();
    },
  },
  {
    id: 'workbench-gallery-representative',
    path: representativeProjectPath,
    ready: async (page) => {
      await waitForWorkbench(page);
      await selectLayoutPreset(page, 'Compose', 'Preview');
      await selectCenterView(page, 'Preview', 'Gallery');
      await centerRegion(page).locator('button:not([aria-expanded])').filter({ hasText: 'Uncategorized' }).click();
      await centerRegion(page).getByRole('list', { exact: true, name: 'Gallery items' }).waitFor();
    },
  },
  {
    id: 'workbench-workflow-representative',
    path: representativeProjectPath,
    ready: async (page) => {
      await waitForWorkbench(page);
      await selectLayoutPreset(page, 'Workflow', 'Workflow');
      await page.getByText('Fixture Node 001', { exact: true }).waitFor();
      // Pan the y=0 fixture clear of the floating toolbar before measuring targets.
      const pane = await page.locator('.react-flow__pane').boundingBox();
      assert.ok(pane);
      const x = pane.x + pane.width / 2;
      const y = pane.y + 160;
      await page.mouse.move(x, y);
      await page.mouse.down();
      await page.mouse.move(x, y + 64, { steps: 4 });
      await page.mouse.up();
      await page
        .locator('[data-id="fixture-workflow-node-001"]')
        .getByRole('button', { name: 'Collapse node' })
        .click({ trial: true });
    },
  },
];

const runAxeSurface = async (browser, surface) => {
  const { context, page, pageErrors } = await openRepresentativePage(browser, surface.path);

  try {
    await surface.ready(page);
    await waitForSettledDocument(page);
    await assertNoAxeViolations(page, surface.id);

    if (pageErrors.length > 0) {
      throw new AggregateError(pageErrors, `${surface.id} raised uncaught browser errors.`);
    }

    return { id: surface.id, status: 'passed' };
  } catch (error) {
    const artifactDir = resolve(root, 'artifacts/accessibility');
    await mkdir(artifactDir, { recursive: true })
      .then(() => page.screenshot({ path: resolve(artifactDir, `${surface.id}.png`) }))
      .catch(() => undefined);
    throw error;
  } finally {
    await context.close();
  }
};

/** Poll focus because roving tabindex and focus restoration run after the initiating key event. */
const expectFocused = async (locator, message) => {
  const deadline = Date.now() + 5_000;

  for (;;) {
    if (await locator.evaluate((element) => element === document.activeElement)) {
      return;
    }

    if (Date.now() >= deadline) {
      const activeElement = await locator.page().evaluate(() => {
        const active = document.activeElement;

        return active instanceof HTMLElement
          ? {
              ariaLabel: active.getAttribute('aria-label'),
              role: active.getAttribute('role'),
              tagName: active.tagName,
              text: active.innerText.slice(0, 200),
            }
          : null;
      });
      assert.fail(`${message} Active element: ${JSON.stringify(activeElement)}.`);
    }

    await new Promise((resolveWait) => {
      setTimeout(resolveWait, 25);
    });
  }
};

const runShortcutGuideJourney = async (browser) => {
  for (const themeId of ['classic', 'light']) {
    const { context, page, pageErrors } = await openRepresentativePage(
      browser,
      representativeProjectPath,
      undefined,
      themeId
    );
    try {
      await waitForWorkbench(page);
      await page.waitForFunction((theme) => document.documentElement.dataset.theme === theme, themeId);
      await selectLayoutPreset(page, 'Edit', 'Canvas');
      await waitForRenderedMedia(page, { canvas: true });
      const viewTool = page
        .getByRole('toolbar', { exact: true, name: 'Tools' })
        .getByRole('button', { exact: true, name: 'Pan' });
      await viewTool.click();
      const guide = page.locator('footer').getByRole('button', { exact: true, name: 'Shortcuts' });
      await guide.waitFor();
      await waitForSettledDocument(page);
      await assertNoAxeViolations(page, `shortcuts-${themeId}-compact`, { include: ['footer [data-shortcut-guide]'] });
      await guide.focus();
      await guide.press('Enter');
      const popup = page
        .getByRole('dialog')
        .filter({ has: page.getByRole('button', { exact: true, name: 'Keyboard shortcut settings' }) });
      await popup.waitFor();
      await waitForSettledDocument(page);
      await assertNoAxeViolations(page, `shortcuts-${themeId}-expanded`, {
        include: ['[data-scope="popover"][data-part="content"][data-state="open"][data-workbench-focus-preserve]'],
      });
      await popup.getByRole('button', { exact: true, name: 'Keyboard shortcut settings' }).press('Escape');
      await popup.waitFor({ state: 'hidden' });
      await expectFocused(viewTool, 'Closing the guide should restore its editing origin.');
      if (pageErrors.length > 0) {
        throw new AggregateError(pageErrors, `shortcuts-${themeId} raised uncaught browser errors.`);
      }
    } catch (error) {
      const directory = resolve(root, 'artifacts/accessibility');
      await mkdir(directory, { recursive: true });
      await page.screenshot({ path: resolve(directory, `shortcuts-${themeId}.png`) }).catch(() => undefined);
      throw error;
    } finally {
      await context.close();
    }
  }
  return { id: 'workbench-shortcuts', status: 'passed' };
};

/** Every built-in status-bar chip's name must lead with its widget label. */
const runStatusBarNamesJourney = async (browser) => {
  const { context, page, pageErrors } = await openRepresentativePage(browser, representativeProjectPath);
  const id = 'workbench-status-bar-names';

  try {
    await waitForWorkbench(page);
    const footer = page.locator('footer');
    await footer.getByRole('button', { exact: true, name: 'Status bar widgets' }).click();
    const menu = page.getByRole('menu');
    await menu.waitFor();
    const items = menu.getByRole('menuitemcheckbox');

    for (let index = 0; index < (await items.count()); index++) {
      const item = items.nth(index);

      if (
        (await item.getAttribute('aria-checked')) === 'false' &&
        (await item.getAttribute('aria-disabled')) !== 'true'
      ) {
        await item.click();
        await page.waitForFunction(
          (element) => element.getAttribute('aria-checked') === 'true',
          await item.elementHandle()
        );
      }
    }

    // Read while the menu is open; its items leave the page with it.
    const itemLabels = [];
    const labels = [];

    for (let index = 0; index < (await items.count()); index++) {
      // Item text only: a failed widget's row also carries a "Failed" note.
      const label = ((await items.nth(index).locator('[data-part="item-text"]').textContent()) ?? '').trim();
      itemLabels.push(label);
      if ((await items.nth(index).getAttribute('aria-checked')) === 'true') {
        labels.push(label);
      }
    }

    await page.keyboard.press('Escape');
    await menu.waitFor({ state: 'hidden' });
    // A chip still loading its view is named "Loading <label>" by its busy status fallback.
    await page.waitForFunction(() => document.querySelector('footer [aria-busy="true"]') === null);
    await waitForSettledDocument(page);
    const chips = footer.locator('[data-status-bar-widget] > [role="button"]');
    const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

    assert.deepEqual(
      itemLabels.toSorted(),
      BUILT_IN_BOTTOM_WIDGETS.toSorted(),
      'The bottom widget menu must list every built-in bottom widget.'
    );
    assert.equal(
      labels.length,
      itemLabels.length,
      `Every bottom widget the menu lists must be enabled; got ${JSON.stringify(labels)}.`
    );
    assert.equal(await chips.count(), labels.length, 'Each enabled bottom widget must render one status-bar chip.');

    for (const label of labels) {
      const named = footer.getByRole('button', { name: new RegExp(`^${escapeRegExp(label)}(?:$|[\\s:])`) });
      assert.equal(
        await chips.and(named).count(),
        1,
        `Exactly one status-bar chip's name must start with "${label}"; chips: ${(await chips.allInnerTexts()).join(' | ')}.`
      );
    }

    await assertNoAxeViolations(page, id, { include: ['footer'] });

    if (pageErrors.length > 0) {
      throw new AggregateError(pageErrors, `${id} raised uncaught browser errors.`);
    }
  } catch (error) {
    const directory = resolve(root, 'artifacts/accessibility');
    await mkdir(directory, { recursive: true });
    await page.screenshot({ path: resolve(directory, `${id}.png`) }).catch(() => undefined);
    throw error;
  } finally {
    await context.close();
  }

  return { id: 'workbench-status-bar-names', status: 'passed' };
};

const runKeyboardJourney = async (browser) => {
  const { context, page, pageErrors } = await openRepresentativePage(browser, '/#/');

  try {
    await waitForHome(page);

    const rail = page.getByRole('navigation', { exact: true, name: 'Launchpad sections' });
    const projectsLink = rail.getByRole('link', { exact: true, name: 'Projects' });
    const nodesLink = rail.getByRole('link', { exact: true, name: 'Nodes' });
    const modelsLink = rail.getByRole('link', { exact: true, name: 'Models' });

    const railLinkTops = await rail
      .getByRole('link')
      .evaluateAll((links) => links.map((link) => link.getBoundingClientRect().top));
    assert.deepEqual(
      railLinkTops,
      [...railLinkTops].sort((a, b) => a - b),
      'Launchpad rail links must follow their visual order.'
    );

    await modelsLink.focus();
    await modelsLink.press('Enter');
    await waitForModels(page);
    assert.match(page.url(), /#\/models$/);
    assert.equal(await modelsLink.getAttribute('aria-current'), 'page');
    await modelsLink.press('Tab');
    await expectFocused(nodesLink, 'Tab should move focus from Models to Nodes.');
    await nodesLink.press('Enter');
    await waitForNodes(page);
    assert.match(page.url(), /#\/nodes$/);
    assert.equal(await nodesLink.getAttribute('aria-current'), 'page');
    assert.equal(await modelsLink.getAttribute('aria-current'), null);

    const paletteTrigger = page.getByRole('button', { exact: true, name: 'Command palette' });

    await paletteTrigger.click();
    const paletteDialog = page.getByRole('dialog', { exact: true, name: 'Command palette' });
    const paletteInput = page.getByRole('combobox', { exact: true, name: 'Search commands and settings' });

    await paletteDialog.waitFor();
    await expectFocused(paletteInput, 'Opening the command palette should focus its search field.');
    await paletteInput.press('Escape');
    await paletteDialog.waitFor({ state: 'hidden' });
    await expectFocused(paletteTrigger, 'Closing the command palette should restore focus to its trigger.');

    await projectsLink.focus();
    await projectsLink.press('Enter');
    await waitForProjects(page);

    const projectLink = page.getByRole('link', { exact: true, name: 'Open Fixture Project 001' });

    await projectLink.focus();
    await projectLink.press('Enter');
    await waitForWorkbench(page);

    const previewTrigger = centerViewTrigger(page, 'Preview');

    await previewTrigger.focus();
    await previewTrigger.press('ControlOrMeta+k');
    await paletteDialog.waitFor();
    await expectFocused(paletteInput, 'Opening the Workbench palette should focus its search field.');
    await paletteInput.press('Escape');
    await paletteDialog.waitFor({ state: 'hidden' });
    await expectFocused(previewTrigger, 'Closing the Workbench palette should restore the keyboard origin.');

    await previewTrigger.press('Enter');

    const previewItem = page.getByRole('menuitemradio', { exact: true, name: 'Preview' });
    const galleryItem = page.getByRole('menuitemradio', { exact: true, name: 'Gallery' });
    const centerViewMenu = page.getByRole('menu');

    await galleryItem.waitFor();
    assert.equal(await previewItem.getAttribute('aria-checked'), 'true');
    await expectFocused(centerViewMenu, 'Opening the center view menu should focus its composite.');
    assert.equal(await centerViewMenu.getAttribute('aria-activedescendant'), await previewItem.getAttribute('id'));
    await centerViewMenu.press('ArrowDown');
    assert.equal(await centerViewMenu.getAttribute('aria-activedescendant'), await galleryItem.getAttribute('id'));
    await centerViewMenu.press('Enter');
    const galleryTrigger = centerViewTrigger(page, 'Gallery');
    await galleryTrigger.waitFor();
    await expectFocused(galleryTrigger, 'Selecting a center view should restore focus to the view selector.');

    if (pageErrors.length > 0) {
      throw new AggregateError(pageErrors, 'keyboard-critical-journey raised uncaught browser errors.');
    }

    return { id: 'keyboard-critical-journey', status: 'passed' };
  } finally {
    await context.close();
  }
};

const runResponsiveTopbarJourney = async (browser) => {
  const { context, page, pageErrors } = await openRepresentativePage(browser, representativeProjectPath, {
    height: 900,
    width: 1_024,
  });
  const id = 'workbench-topbar-responsive';

  try {
    await waitForWorkbench(page);
    // The representative fixture has exactly 167 pending outputs; connection state may change its label.
    await page
      .locator('header')
      .getByRole('button', { name: /^167 (?:images remaining|items waiting for the connection)\. Open queue$/ })
      .waitFor();

    for (const width of [1_024, 900]) {
      await page.setViewportSize({ height: 900, width });
      await waitForSettledDocument(page);

      const metrics = await page.locator('header').evaluate((header) => {
        const bounds = header.getBoundingClientRect();
        const zones = [...header.children].map((element) => element.getBoundingClientRect());
        const centerZone = zones[1];

        return {
          centerOffset: Math.abs(bounds.left + bounds.width / 2 - (centerZone.left + centerZone.width / 2)),
          clientWidth: header.clientWidth,
          controlsInsideHeader: [...header.querySelectorAll('button')].every((button) => {
            const controlBounds = button.getBoundingClientRect();

            return controlBounds.left >= bounds.left && controlBounds.right <= bounds.right;
          }),
          scrollWidth: header.scrollWidth,
          zonesDoNotOverlap: zones.every((zone, index) => index === 0 || zones[index - 1].right <= zone.left),
        };
      });

      assert.equal(metrics.scrollWidth, metrics.clientWidth, `The topbar must not overflow at ${width}px.`);
      const documentHeights = await page.evaluate(() => ({
        clientHeight: document.documentElement.clientHeight,
        scrollHeight: document.documentElement.scrollHeight,
      }));
      assert.equal(
        documentHeights.scrollHeight,
        documentHeights.clientHeight,
        `The workbench must not scroll the document at ${width}px.`
      );
      assert.equal(metrics.controlsInsideHeader, true, `Every topbar control must remain visible at ${width}px.`);
      assert.equal(metrics.zonesDoNotOverlap, true, `Topbar zones must not overlap at ${width}px.`);
      assert.ok(
        metrics.centerOffset <= 0.5,
        `The preset strip must be centered at ${width}px (offset: ${metrics.centerOffset.toFixed(2)}px).`
      );
    }

    if (pageErrors.length > 0) {
      throw new AggregateError(pageErrors, `${id} raised uncaught browser errors.`);
    }

    return { id, status: 'passed' };
  } finally {
    await context.close();
  }
};

const runTopbarMenuJourney = async (browser) => {
  const { context, page, pageErrors } = await openRepresentativePage(browser, representativeProjectPath);
  const id = 'workbench-topbar-menus';

  try {
    await waitForWorkbench(page);

    await centerViewTrigger(page, 'Preview').click();
    await page.getByRole('menuitem', { exact: true, name: 'Workflow' }).click();
    await centerViewTrigger(page, 'Workflow').waitFor();
    await selectCenterView(page, 'Workflow', 'Preview');

    const leftWidgetRail = page.getByRole('navigation', { exact: true, name: 'Left rail' });
    const upscaleWidget = leftWidgetRail.getByRole('button', { exact: true, name: 'Upscale' });
    await upscaleWidget.click({ button: 'right' });
    await page.getByRole('menuitem', { exact: true, name: 'Remove Upscale' }).click();
    assert.equal(await upscaleWidget.count(), 0);
    const activeLeftWidget = leftWidgetRail.getByRole('button', { pressed: true });
    const activeLeftWidgetName = await activeLeftWidget.getAttribute('aria-label');
    assert.ok(activeLeftWidgetName);

    assert.equal(await page.locator('[data-routing-control]').count(), 0);
    const invokeButton = page.getByRole('button', { name: /^Invoke(?: · \d+ issues?)?$/ });
    const invokeCard = page.locator('[data-scope="popover"][data-part="content"][data-state="open"]');
    const routingLockIndicator = invokeButton.locator('[data-routing-lock-indicator]');
    const invokeBoundsBeforeLock = await invokeButton.boundingBox();
    assert.ok(invokeBoundsBeforeLock);
    const invokeBlocked = (await invokeButton.getAttribute('data-blocked')) !== null;
    const expectedInvokeExpanded = (expanded) => (invokeBlocked ? String(expanded) : null);
    assert.equal(await invokeButton.getAttribute('aria-haspopup'), invokeBlocked ? 'dialog' : null);
    assert.equal(await invokeButton.getAttribute('aria-expanded'), expectedInvokeExpanded(false));
    assert.ok(
      ((await invokeButton.getAttribute('aria-keyshortcuts')) ?? '').split(' ').includes('ArrowDown'),
      'Invoke must list ArrowDown, its keyboard way into the card, among its shortcuts.'
    );
    const invokeDescription = () =>
      invokeButton.evaluate((button) =>
        (button.getAttribute('aria-describedby') ?? '')
          .split(/\s+/)
          .filter(Boolean)
          .map((descriptionId) => document.getElementById(descriptionId)?.textContent?.trim() ?? '')
          .join(' ')
      );
    const routeDescriptionPattern = (locked) =>
      new RegExp(`^\\S+ to \\S+${locked ? ', route locked' : ''}\\. Down Arrow opens the route\\.`);
    assert.match(await invokeDescription(), routeDescriptionPattern(false));
    assert.equal(await routingLockIndicator.count(), 0);

    await invokeButton.hover();
    await invokeCard.getByText('Source', { exact: true }).waitFor();
    await invokeCard.getByText('Destination', { exact: true }).waitFor();
    assert.equal(await invokeButton.getAttribute('aria-expanded'), expectedInvokeExpanded(false));
    await page.mouse.move(0, 0);
    await invokeCard.waitFor({ state: 'hidden' });

    await invokeButton.focus();
    await page.keyboard.press('ArrowDown');
    await invokeCard.waitFor();
    assert.equal(await invokeButton.getAttribute('aria-expanded'), expectedInvokeExpanded(true));
    assert.equal(await invokeButton.getAttribute('aria-controls'), await invokeCard.getAttribute('id'));
    assert.equal(
      await page.getByRole('dialog', { name: /^(?:Add to queue|Unable to queue|Preparing generation…)$/ }).count(),
      1,
      'The open Invoke card must be named by its title.'
    );
    await invokeCard.locator(':focus').waitFor();
    await waitForSettledDocument(page);
    await assertNoAxeViolations(page, `${id}:invoke-card`, {
      include: ['[data-scope="popover"][data-part="content"]'],
    });

    const lockRouting = invokeCard.getByRole('button', { exact: true, name: 'Lock routing' });
    assert.equal(await lockRouting.getAttribute('aria-pressed'), 'false');
    await lockRouting.click();
    await invokeCard.locator('[data-routing-lock][aria-pressed="true"]').waitFor();
    await routingLockIndicator.waitFor();
    const invokeBoundsLocked = await invokeButton.boundingBox();
    assert.ok(invokeBoundsLocked);
    assert.equal(invokeBoundsLocked.width, invokeBoundsBeforeLock.width);
    assert.equal(invokeBoundsLocked.x, invokeBoundsBeforeLock.x);
    assert.match(await invokeDescription(), routeDescriptionPattern(true));
    await lockRouting.click();
    await invokeCard.locator('[data-routing-lock][aria-pressed="false"]').waitFor();
    assert.equal(await routingLockIndicator.count(), 0);
    assert.ok(await invokeCard.isVisible(), 'Toggling the lock should keep the card open.');

    const sourceGroup = invokeCard.getByRole('radiogroup', { exact: true, name: 'Source' });
    assert.equal(await sourceGroup.getByText('Upscale', { exact: true }).count(), 0);
    await sourceGroup.getByText('Generate', { exact: true }).click();
    await sourceGroup.locator('input[value="generate"]:checked').waitFor({ state: 'attached' });
    assert.ok(await invokeCard.isVisible(), 'Switching the source should keep the card open.');
    await centerViewTrigger(page, 'Preview').waitFor();
    assert.equal(await upscaleWidget.count(), 0);
    assert.equal(await activeLeftWidget.getAttribute('aria-label'), activeLeftWidgetName);
    await page.keyboard.press('Escape');
    await invokeCard.waitFor({ state: 'hidden' });
    await expectFocused(invokeButton, 'Closing the Invoke card should return focus to Invoke.');

    const appMenuButton = page.getByRole('button', { exact: true, name: 'Open menu' });
    await appMenuButton.click();
    const appMenu = page.getByRole('menu', { exact: true, name: 'Open menu' });
    const launchpadItem = appMenu.getByRole('menuitem', { exact: true, name: 'Launchpad' });
    const settingsItem = appMenu.getByRole('menuitem', { exact: true, name: 'Settings' });
    const commandPaletteItem = appMenu.getByRole('menuitem', { exact: true, name: 'Command palette' });
    const whatsNewItem = page.getByRole('menuitem', { exact: true, name: "What's New in Invoke" });
    const documentationItem = page.getByRole('menuitem', { exact: true, name: 'Documentation' });
    const discordItem = page.getByRole('menuitem', { exact: true, name: 'Discord' });
    const donationItem = appMenu.getByRole('menuitem', { exact: true, name: 'Donate to Invoke' });
    await launchpadItem.waitFor();
    await commandPaletteItem.waitFor();
    await settingsItem.waitFor();
    assert.equal(await settingsItem.getAttribute('aria-keyshortcuts'), 'Control+,');
    assert.equal(await commandPaletteItem.getAttribute('aria-keyshortcuts'), 'Control+K');
    await whatsNewItem.waitFor();
    await documentationItem.waitFor();
    await discordItem.waitFor();
    await donationItem.waitFor();
    assert.equal(await donationItem.getAttribute('href'), 'https://github.com/sponsors/invoke-ai');
    assert.equal(await donationItem.getAttribute('target'), '_blank');

    const footerMetrics = await appMenu.evaluate((menu) => {
      const menuBounds = menu.getBoundingClientRect();
      const items = [...menu.querySelectorAll('[role="menuitem"]')];
      const footerValues = ['whats-new', 'documentation', 'discord'];
      const footerItems = items.filter((item) => footerValues.includes(item.getAttribute('data-value')));
      const leadingItems = items.filter((item) =>
        ['launchpad', 'settings', 'command-palette'].includes(item.getAttribute('data-value'))
      );
      const fits = (bounds) => bounds.left >= menuBounds.left && bounds.right <= menuBounds.right;

      return {
        footerCount: footerItems.length,
        itemsFit: footerItems.every((item) => {
          const bounds = item.getBoundingClientRect();

          return fits(bounds) && bounds.width <= 32.5;
        }),
        leadingRowsFit: leadingItems.every((item) => {
          const bounds = item.getBoundingClientRect();
          const label = item.querySelector('[data-part="item-text"]')?.getBoundingClientRect();

          return fits(bounds) && bounds.width > 32.5 && label !== undefined && label.right <= bounds.right;
        }),
        menuClientWidth: menu.clientWidth,
        menuScrollWidth: menu.scrollWidth,
      };
    });
    assert.equal(footerMetrics.footerCount, 3);
    assert.equal(footerMetrics.itemsFit, true);
    assert.equal(footerMetrics.leadingRowsFit, true);
    assert.equal(footerMetrics.menuScrollWidth, footerMetrics.menuClientWidth);

    await expectFocused(appMenu, 'Opening the app menu should focus its composite.');
    assert.equal(await appMenu.locator('[role="menuitem"][data-highlighted]').count(), 0);
    await new Promise((resolveWait) => {
      setTimeout(resolveWait, 750);
    });
    assert.equal(
      await page.getByRole('tooltip', { name: /^(?:What's New in Invoke|Documentation|Discord)$/ }).count(),
      0
    );

    const menuItemValues = await appMenu.evaluate((menu) =>
      [...menu.querySelectorAll('[role="menuitem"]')].map((item) => item.getAttribute('data-value'))
    );
    assert.deepEqual(menuItemValues.slice(0, 3), ['launchpad', 'settings', 'command-palette']);
    assert.deepEqual(menuItemValues.slice(menuItemValues.indexOf('queue')), [
      'queue',
      'widgets',
      'donate',
      'whats-new',
      'documentation',
      'discord',
    ]);
    const queueItem = appMenu.locator('[role="menuitem"][data-value="queue"]');
    const widgetsItem = appMenu.locator('[role="menuitem"][data-value="widgets"]');

    await appMenu.press('End');
    assert.equal(await appMenu.getAttribute('aria-activedescendant'), await discordItem.getAttribute('id'));
    for (const item of [documentationItem, whatsNewItem, donationItem, widgetsItem, queueItem]) {
      await appMenu.press('ArrowUp');
      assert.equal(await appMenu.getAttribute('aria-activedescendant'), await item.getAttribute('id'));
    }
    await appMenu.press('Home');
    assert.equal(await appMenu.getAttribute('aria-activedescendant'), await launchpadItem.getAttribute('id'));
    await appMenu.press('ArrowDown');
    assert.equal(await appMenu.getAttribute('aria-activedescendant'), await settingsItem.getAttribute('id'));
    await appMenu.press('ArrowDown');
    assert.equal(await appMenu.getAttribute('aria-activedescendant'), await commandPaletteItem.getAttribute('id'));

    // Each opens from the keyboard and closes back to the menu's button: the item that opened it is gone by then.
    await appMenu.press('Enter');
    const paletteDialog = page.getByRole('dialog', { exact: true, name: 'Command palette' });
    await paletteDialog.waitFor();
    await expectFocused(
      page.getByRole('combobox', { exact: true, name: 'Search commands and settings' }),
      'Opening the command palette from the app menu should focus its search field.'
    );
    await page.keyboard.press('Escape');
    await paletteDialog.waitFor({ state: 'hidden' });
    await expectFocused(appMenuButton, 'Closing the command palette should return focus to the app menu button.');

    await appMenuButton.press('Enter');
    await launchpadItem.waitFor();
    // Keys pressed before the reopened menu holds focus are lost.
    await expectFocused(appMenu, 'Reopening the app menu from the keyboard should focus its composite.');
    await appMenu.press('Home');
    await appMenu.press('ArrowDown');
    assert.equal(await appMenu.getAttribute('aria-activedescendant'), await settingsItem.getAttribute('id'));
    await appMenu.press('Enter');
    const settingsDialog = page.getByRole('dialog', { name: /^Settings:/ });
    await settingsDialog.waitFor();
    await waitForSettledDocument(page);
    await page.keyboard.press('Escape');
    await settingsDialog.waitFor({ state: 'hidden' });
    await expectFocused(appMenuButton, 'Closing Settings should return focus to the app menu button.');

    const projectSwitcher = page.getByRole('button', { name: /^Switch project\./ });
    await projectSwitcher.click();
    await page.getByRole('menuitem', { exact: true, name: 'New project' }).click();
    await page.getByRole('main', { name: /^Project Name #\d+$/ }).waitFor();

    await projectSwitcher.click();
    const openProjects = page.getByRole('menuitemradio');
    assert.ok((await openProjects.count()) >= 2);
    assert.equal(await page.getByRole('menuitemradio', { checked: true }).count(), 1);

    const textOffsets = await openProjects.evaluateAll((items) =>
      items.map((item) => item.querySelector('[data-part="item-text"]')?.getBoundingClientRect().left ?? null)
    );
    assert.equal(
      textOffsets.every((offset) => offset !== null),
      true
    );
    assert.ok(Math.max(...textOffsets) - Math.min(...textOffsets) <= 0.5);

    const otherProject = page.getByRole('menuitemradio', { checked: false }).first();
    const otherProjectName = (await otherProject.locator('[data-part="item-text"]').textContent())?.trim();
    assert.ok(otherProjectName);
    await otherProject.click();
    await page.getByRole('main', { exact: true, name: otherProjectName }).waitFor();

    const customPresetNames = ['Custom One', 'Custom Two', 'Custom Three', 'Custom Four', 'Custom Five', 'Custom Six'];
    for (const presetName of customPresetNames) {
      await page.getByRole('button', { exact: true, name: 'Save this layout as a new preset' }).click();
      const savePresetDialog = page.getByRole('dialog', { exact: true, name: 'Save as new preset' });
      await savePresetDialog.getByRole('textbox', { exact: true, name: 'Preset name' }).fill(presetName);
      await savePresetDialog.getByRole('button', { exact: true, name: 'Save preset' }).click();
      await savePresetDialog.waitFor({ state: 'hidden' });
    }
    for (const presetName of customPresetNames) {
      await page.getByRole('tab', { exact: true, name: presetName }).waitFor();
    }
    assert.equal(await page.getByRole('button', { name: /^More layout presets/ }).count(), 0);
    const presetScroller = page.locator('[data-layout-preset-scroll]');
    await presetScroller.waitFor();
    const presetScrollerMetrics = await presetScroller.evaluate((scroller) => ({
      clientWidth: scroller.clientWidth,
      scrollWidth: scroller.scrollWidth,
    }));
    assert.ok(presetScrollerMetrics.scrollWidth > presetScrollerMetrics.clientWidth);
    const savePresetButton = page.getByRole('button', { exact: true, name: 'Save this layout as a new preset' });
    const [scrollerBounds, savePresetBounds] = await Promise.all([
      presetScroller.boundingBox(),
      savePresetButton.boundingBox(),
    ]);
    assert.ok(scrollerBounds);
    assert.ok(savePresetBounds);
    assert.ok(savePresetBounds.x >= scrollerBounds.x + scrollerBounds.width);
    assert.ok(savePresetBounds.x + savePresetBounds.width <= 1_440);
    const horizontalScroll = await presetScroller.evaluate(async (scroller) => {
      scroller.scrollLeft = scroller.scrollWidth;
      await new Promise((resolveFrame) => {
        requestAnimationFrame(resolveFrame);
      });

      return scroller.scrollLeft;
    });
    assert.ok(horizontalScroll > 0);
    const presetLayoutMetrics = await page.getByRole('banner').evaluate((header) => ({
      clientWidth: header.clientWidth,
      scrollWidth: header.scrollWidth,
    }));
    assert.equal(presetLayoutMetrics.scrollWidth, presetLayoutMetrics.clientWidth);

    await page.getByRole('tab', { name: /^Edit(?:, unsaved changes)?$/ }).click({ button: 'right' });
    const switchLayout = page.getByRole('menuitem', { exact: true, name: 'Switch to this layout' });
    await switchLayout.waitFor();
    assert.equal(await switchLayout.locator('svg.lucide-check').count(), 0);
    assert.equal(await switchLayout.locator('svg.lucide-arrow-right').count(), 1);

    if (pageErrors.length > 0) {
      throw new AggregateError(pageErrors, `${id} raised uncaught browser errors.`);
    }

    return { id, status: 'passed' };
  } finally {
    await context.close();
  }
};

const runVideoPreviewJourney = async (browser) => {
  const { consoleErrors, context, page, pageErrors } = await openRepresentativePage(browser, representativeProjectPath);
  const id = 'workbench-video-preview-representative';

  try {
    await waitForWorkbench(page);
    await selectLayoutPreset(page, 'Compose', 'Preview');

    const rightPanel = page.getByRole('complementary', { exact: true, name: 'right widget panel' });
    await rightPanel.locator('button:not([aria-expanded])').filter({ hasText: 'Uncategorized' }).click();
    const gallery = rightPanel.getByRole('list', { exact: true, name: 'Gallery items' });
    const selectVideoName = `Select video ${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}, duration 0:01, for preview`;
    const selectVideo = rightPanel.getByRole('button', { exact: true, name: selectVideoName });
    // Tile badges sit outside the bordered image box; the panel-wide lookup covers the starred strip and main list.
    const videoTile = rightPanel
      .getByRole('listitem')
      .filter({ has: page.getByRole('button', { exact: true, name: selectVideoName }) });

    try {
      await gallery.waitFor();
    } catch (error) {
      const bodyText = (await page.locator('body').innerText()).slice(0, 4_000);
      throw new Error(
        `${error instanceof Error ? error.message : String(error)}\nPage errors: ${pageErrors.map(String).join('\n')}\nConsole errors: ${consoleErrors.join('\n')}\nBody:\n${bodyText}`
      );
    }
    await selectVideo.waitFor();
    await selectVideo.focus();
    await expectFocused(selectVideo, 'The video gallery item must be keyboard focusable.');
    assert.equal(await videoTile.locator('svg.lucide-play').getAttribute('aria-hidden'), 'true');
    await selectVideo.press('Enter');

    const player = centerRegion(page).getByRole('group', {
      exact: true,
      name: `Video ${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}`,
    });
    const video = player.locator('video');

    try {
      await video.waitFor();
    } catch (error) {
      const bodyText = (await page.locator('body').innerText()).slice(0, 4_000);
      throw new Error(
        `${error instanceof Error ? error.message : String(error)}\nPage errors: ${pageErrors.map(String).join('\n')}\nConsole errors: ${consoleErrors.join('\n')}\nBody:\n${bodyText}`
      );
    }
    assert.equal(await video.getAttribute('controls'), null);
    assert.equal(await video.getAttribute('playsinline'), '');
    assert.match((await video.getAttribute('poster')) ?? '', /fixture-video-001\.mp4\/thumbnail$/);
    assert.equal(await video.getAttribute('draggable'), null);

    const play = player.locator('button[aria-label="Play"]:not([disabled])');
    await play.waitFor();
    assert.notEqual(await play.getAttribute('tabindex'), '-1');
    await play.focus();
    await expectFocused(play, 'The video player Play control must be keyboard focusable.');
    await page.keyboard.press('Space');
    await page.waitForFunction((element) => !element.paused, await video.elementHandle());
    const pause = player.getByRole('button', { exact: true, name: 'Pause' });
    await expectFocused(pause, 'The video player must keep focus on its play control while playing.');
    await page.keyboard.press('Space');
    await page.waitForFunction((element) => element.paused, await video.elementHandle());
    const seek = player.getByRole('slider', { exact: true, name: 'Seek' });
    assert.notEqual(await seek.getAttribute('tabindex'), '-1');
    assert.equal(await player.getByRole('button', { exact: true, name: 'Loop' }).isEnabled(), true);
    // A wide bar shows the volume slider; a narrow one opens it from a volume button.
    const volume = player
      .getByRole('slider', { exact: true, name: 'Volume' })
      .or(player.getByRole('button', { exact: true, name: 'Volume' }));
    assert.equal(await volume.isEnabled(), true);

    const details = page
      .locator('[data-hotkey-widget-region="center"][data-hotkey-widget-type-id="preview"]')
      .getByRole('button', { exact: true, name: 'Details' });
    await details.focus();
    await expectFocused(details, 'The preview Details toggle must be keyboard focusable.');
    await details.press('Enter');
    await page.getByText(/Duration 0:01/).waitFor();
    await waitForSettledDocument(page);

    // Generated media has no caption track, so only this video surface disables axe's caption rule.
    await assertNoAxeViolations(page, id, { rules: { 'video-caption': { enabled: false } } });

    if (pageErrors.length > 0) {
      throw new AggregateError(pageErrors, `${id} raised uncaught browser errors.`);
    }

    return { id, status: 'passed' };
  } finally {
    await context.close();
  }
};

/** Mounted-node identity alone cannot detect state loss. */
const runKeepAliveStateJourney = async (browser) => {
  const { context, page, pageErrors } = await openRepresentativePage(browser, representativeProjectPath);
  const id = 'workbench-keep-alive-state';

  /** Clipped text is not scroll state; filmstrips may overflow only horizontally. */
  const SCROLLER_QUERY = `(element) => [...element.querySelectorAll('*')].filter((node) => {
    const style = getComputedStyle(node);
    const scrollsY = (style.overflowY === 'auto' || style.overflowY === 'scroll') && node.scrollHeight > node.clientHeight + 40;
    const scrollsX = (style.overflowX === 'auto' || style.overflowX === 'scroll') && node.scrollWidth > node.clientWidth + 40;
    return scrollsY || scrollsX;
  })`;

  const readScrollOffsets = (panel) =>
    panel.evaluate(
      new Function(
        'element',
        `return (${SCROLLER_QUERY})(element).map((node) => ({ left: Math.round(node.scrollLeft), top: Math.round(node.scrollTop) }));`
      )
    );

  const scrollAll = (panel, offset) =>
    panel.evaluate(
      new Function(
        'element',
        'target',
        `const scrollers = (${SCROLLER_QUERY})(element);
         for (const scroller of scrollers) {
           scroller.scrollTop = target;
           scroller.scrollLeft = target;
         }
         return scrollers.map((scroller) => ({ left: Math.round(scroller.scrollLeft), top: Math.round(scroller.scrollTop) }));`
      ),
      offset
    );

  try {
    await waitForWorkbench(page);
    await selectLayoutPreset(page, 'Compose', 'Preview');

    const rightPanel = page.getByRole('complementary', { exact: true, name: 'right widget panel' });
    await rightPanel.locator('button:not([aria-expanded])').filter({ hasText: 'Uncategorized' }).click();
    const galleryItems = rightPanel.getByRole('list', { exact: true, name: 'Gallery items' });
    await galleryItems.waitFor();

    await galleryItems
      .locator('[data-gallery-section="regular"]')
      .getByRole('button', { name: /for preview$/ })
      .first()
      .click();

    const leftPanel = page.getByRole('complementary', { exact: true, name: 'left widget panel' });
    const scrolledLeftOffsets = await scrollAll(leftPanel, 400);
    const scrolledOffsets = await scrollAll(rightPanel, 600);
    assert.ok(
      scrolledOffsets.length >= 2 && scrolledOffsets.every(({ left, top }) => top > 0 || left > 0),
      `The representative gallery must have scrollable boards and items; got ${JSON.stringify(scrolledOffsets)}.`
    );

    // Filmstrip overflow arrives with its own board-scoped fetch.
    const centerPanel = centerRegion(page);
    await page.waitForFunction(
      () => {
        const region = [...document.querySelectorAll('[role="region"]')].find(
          (node) => node.getAttribute('aria-label') === 'Center view'
        );

        return region
          ? [...region.querySelectorAll('*')].some((node) => {
              const style = getComputedStyle(node);
              return (
                (style.overflowX === 'auto' || style.overflowX === 'scroll') && node.scrollWidth > node.clientWidth + 40
              );
            })
          : false;
      },
      undefined,
      { timeout: 10_000 }
    );
    const scrolledCenterOffsets = await scrollAll(centerPanel, 300);
    assert.ok(
      scrolledCenterOffsets.some(({ left }) => left > 0),
      `The representative preview filmstrip must scroll horizontally; got ${JSON.stringify(scrolledCenterOffsets)}.`
    );
    await waitForSettledDocument(page);

    await selectLayoutPreset(page, 'Edit', 'Canvas');
    await waitForRenderedMedia(page, { canvas: true });

    const zoomTrigger = page.getByRole('button', { name: /^Zoom \d+%$/ });
    await zoomTrigger.click();
    await page.getByRole('menuitem', { exact: true, name: '200%' }).click();
    await waitForSettledDocument(page);
    assert.equal((await zoomTrigger.textContent())?.trim(), '200%', 'The zoom control must report the chosen zoom.');

    await selectLayoutPreset(page, 'Workflow', 'Workflow');
    await waitForSettledDocument(page);
    await selectLayoutPreset(page, 'Edit', 'Canvas');
    await waitForRenderedMedia(page, { canvas: true });
    await waitForSettledDocument(page);

    assert.equal(
      (await zoomTrigger.textContent())?.trim(),
      '200%',
      'Returning to a layout must keep the canvas viewport, not refit it.'
    );

    await selectLayoutPreset(page, 'Compose', 'Preview');
    await galleryItems.waitFor();
    await waitForSettledDocument(page);

    assert.deepEqual(
      await readScrollOffsets(rightPanel),
      scrolledOffsets,
      'Returning to a layout must keep the gallery scrolled where the user left it.'
    );
    assert.deepEqual(
      await readScrollOffsets(leftPanel),
      scrolledLeftOffsets,
      'Returning to a layout must keep a panel body scrolled where the user left it.'
    );
    assert.deepEqual(
      await readScrollOffsets(centerPanel),
      scrolledCenterOffsets,
      'Returning to a layout must keep the preview filmstrip scrolled where the user left it.'
    );

    if (pageErrors.length > 0) {
      throw new AggregateError(pageErrors, `${id} raised uncaught browser errors.`);
    }

    return { id, status: 'passed' };
  } finally {
    await context.close();
  }
};

const LAYERS_PANEL_SCOPE = { include: ['[data-hotkey-widget-type-id="layers"]'] };

const runLayersPanesJourney = async (browser) => {
  const { context, page, pageErrors } = await openRepresentativePage(browser, representativeProjectPath);

  try {
    await waitForWorkbench(page);
    await selectLayoutPreset(page, 'Edit', 'Canvas');
    await waitForRenderedMedia(page, { canvas: true });
    const propertiesTab = page.getByRole('tab', { exact: true, name: 'Properties' });
    await propertiesTab.waitFor();

    const tools = page.getByRole('toolbar', { exact: true, name: 'Tools' });
    await tools.getByRole('button', { exact: true, name: 'Brush' }).click();
    await page
      .getByRole('tabpanel', { exact: true, name: 'Properties' })
      .getByRole('slider', { exact: true, name: 'Brush size' })
      .waitFor();
    await tools.getByRole('button', { exact: true, name: 'Pan' }).click();
    await page.getByRole('tabpanel', { exact: true, name: 'Properties' }).waitFor();

    await page.getByRole('tab', { exact: true, name: 'Overview' }).click();
    await page.getByRole('button', { exact: true, name: 'Pan the canvas view' }).waitFor();
    await page.getByRole('tab', { exact: true, name: 'History' }).click();
    await page.getByRole('tabpanel', { exact: true, name: 'History' }).waitFor();
    await page.getByRole('tab', { exact: true, name: 'Swatches' }).click();
    await page.getByRole('tabpanel', { exact: true, name: 'Swatches' }).waitFor();

    await waitForSettledDocument(page);
    // Scope this audit to Layers so unrelated lazy generation panels cannot change its result.
    await assertNoAxeViolations(page, 'workbench-layers-panes', LAYERS_PANEL_SCOPE);

    const overviewTab = page.getByRole('tab', { exact: true, name: 'Overview' });
    await overviewTab.focus();
    await overviewTab.press('ArrowLeft');
    const transformTab = page.getByRole('tab', { exact: true, name: 'Transform' });
    await expectFocused(transformTab, 'ArrowLeft should move focus from Overview to Transform.');
    await transformTab.press('Enter');
    await page.getByRole('tabpanel', { exact: true, name: 'Transform' }).waitFor();
    assert.equal(await transformTab.getAttribute('aria-selected'), 'true');

    await waitForSettledDocument(page);
    await assertNoAxeViolations(page, 'workbench-layers-panes:transform', LAYERS_PANEL_SCOPE);

    if (pageErrors.length > 0) {
      throw new AggregateError(pageErrors, 'workbench-layers-panes raised uncaught browser errors.');
    }

    return { id: 'workbench-layers-panes', status: 'passed' };
  } finally {
    await context.close();
  }
};

const runFloatingWindowJourney = async (browser) => {
  const { context, page, pageErrors } = await openRepresentativePage(browser, representativeProjectPath);
  const id = 'workbench-floating-window';

  try {
    await waitForWorkbench(page);
    await selectLayoutPreset(page, 'Video', 'Preview');

    const rail = page.getByRole('navigation', { exact: true, name: 'Right rail' });
    const center = centerRegion(page);
    const floatingWindow = page.locator('[data-hotkey-widget-region="floating"]');
    const marker = rail.getByRole('button', { exact: true, name: 'Preview, floating window' });
    const floatPreviewFromRail = async () => {
      await rail.getByRole('button', { exact: true, name: 'Right panel widgets' }).click();
      await page.getByRole('menuitemcheckbox', { exact: true, name: 'Preview' }).click();
      await page.keyboard.press('Escape');
      await page.getByRole('button', { exact: true, name: 'Float Window' }).click();
      await floatingWindow.waitFor();
      await marker.waitFor();
    };
    const focusedRegion = () =>
      page.evaluate(() => document.activeElement?.closest('[data-focus-region]')?.getAttribute('data-focus-region'));
    const waitForActiveWindow = () =>
      page.waitForFunction(() => {
        const active = document.activeElement?.closest('[data-floating-window]');

        return active !== null && active !== undefined && active.getAttribute('data-highlighted') === 'true';
      });
    const waitForFocusedRegion = (region) =>
      page.waitForFunction(
        (expected) =>
          document.activeElement?.closest('[data-focus-region]')?.getAttribute('data-focus-region') === expected,
        region
      );

    await floatPreviewFromRail();
    await waitForActiveWindow();
    await center.getByText('Preview is in a floating window', { exact: true }).waitFor();
    await waitForSettledDocument(page);
    await assertNoAxeViolations(page, `${id}:floating`);

    const width = async () => Math.round((await floatingWindow.boundingBox()).width);
    const left = async () => Math.round((await floatingWindow.boundingBox()).x);
    const windowedWidth = await width();
    await floatingWindow.getByRole('separator', { exact: true, name: 'Resize window' }).focus();
    await page.keyboard.press('ArrowRight');
    await page.waitForFunction(
      ([selector, expected]) => Math.round(document.querySelector(selector).getBoundingClientRect().width) === expected,
      ['[data-hotkey-widget-region="floating"]', windowedWidth + 16]
    );
    const windowedLeft = await left();
    await floatingWindow.getByLabel('Move Preview window', { exact: true }).focus();
    await page.keyboard.press('ArrowRight');
    await page.waitForFunction(
      ([selector, expected]) => Math.round(document.querySelector(selector).getBoundingClientRect().left) === expected,
      ['[data-hotkey-widget-region="floating"]', windowedLeft + 16]
    );

    await floatingWindow.getByRole('button', { exact: true, name: 'Maximize' }).click();
    await floatingWindow.getByRole('button', { exact: true, name: 'Restore' }).waitFor();
    await waitForSettledDocument(page);
    await assertNoAxeViolations(page, `${id}:maximized`);
    await floatingWindow.getByRole('button', { exact: true, name: 'Restore' }).click();
    assert.equal(await width(), windowedWidth + 16, 'Restore must return to the windowed size.');
    await floatingWindow.getByRole('button', { exact: true, name: 'Collapse' }).click();
    await floatingWindow.getByRole('button', { exact: true, name: 'Expand' }).waitFor();
    await waitForSettledDocument(page);
    await assertNoAxeViolations(page, `${id}:collapsed`);
    await floatingWindow.getByRole('button', { exact: true, name: 'Expand' }).click();
    await floatingWindow.getByRole('button', { exact: true, name: 'Collapse' }).waitFor();

    await marker.focus();
    await page.keyboard.press('Enter');
    assert.equal(await floatingWindow.count(), 1, 'Activating the marker must keep the window floating.');
    await waitForActiveWindow();

    await marker.click({ button: 'right' });
    assert.deepEqual(await page.getByRole('menuitem').allInnerTexts(), ['Dock to right panel', 'Remove Preview']);
    await page.getByRole('menuitem', { exact: true, name: 'Remove Preview' }).click();
    await centerViewTrigger(page, 'Preview').waitFor();
    await floatingWindow.waitFor({ state: 'detached' });
    assert.equal(await marker.count(), 0, 'Removing the window must free its rail slot.');
    await waitForFocusedRegion('center');

    await floatPreviewFromRail();
    await waitForActiveWindow();
    await center.getByRole('button', { exact: true, name: 'Dock to right panel' }).click();
    await centerViewTrigger(page, 'Preview').waitFor();
    await floatingWindow.waitFor({ state: 'detached' });
    await rail.getByRole('button', { exact: true, name: 'Preview' }).waitFor();
    await waitForFocusedRegion('center');
    assert.equal(await focusedRegion(), 'center');

    await page.getByRole('button', { exact: true, name: 'Float Window' }).click();
    await floatingWindow.waitFor();
    await waitForActiveWindow();
    await floatingWindow.getByRole('button', { exact: true, name: 'Dock to right panel' }).click();
    await floatingWindow.waitFor({ state: 'detached' });
    await waitForFocusedRegion('right');

    await page.getByRole('button', { exact: true, name: 'Float Window' }).click();
    await floatingWindow.waitFor();
    await waitForActiveWindow();
    await marker.focus();
    await page.keyboard.press('Shift+F10');
    await page.getByRole('menuitem', { exact: true, name: 'Dock to right panel' }).click();
    await floatingWindow.waitFor({ state: 'detached' });
    await waitForFocusedRegion('right');
    await waitForSettledDocument(page);
    await assertNoAxeViolations(page, `${id}:docked`);

    const floatImageMapFrom = async (widgetRail, menuName) => {
      await widgetRail.getByRole('button', { exact: true, name: menuName }).click();
      await page.getByRole('menuitemcheckbox', { exact: true, name: 'Image Map' }).click();
      await page.keyboard.press('Escape');
      await page.getByRole('button', { exact: true, name: 'Float Window' }).click();
      await floatingWindow.waitFor();
      await waitForActiveWindow();
    };
    const removeImageMapFrom = async (widgetRail, focusedRegionAfter) => {
      await widgetRail.getByRole('button', { exact: true, name: 'Image Map, floating window' }).focus();
      await page.keyboard.press('Shift+F10');
      await page.waitForFunction(() => Boolean(document.activeElement?.closest('[role="menu"]')));
      await page.keyboard.press('End');
      await page.keyboard.press('Enter');
      await floatingWindow.waitFor({ state: 'detached' });
      await waitForFocusedRegion(focusedRegionAfter);
    };

    await floatImageMapFrom(rail, 'Right panel widgets');
    await removeImageMapFrom(rail, 'right');

    await floatImageMapFrom(rail, 'Right panel widgets');
    await rail.getByRole('button', { pressed: true }).click();
    await page.getByRole('complementary', { exact: true, name: 'right widget panel' }).waitFor({ state: 'detached' });
    await removeImageMapFrom(rail, 'center');

    const leftRail = page.getByRole('navigation', { exact: true, name: 'Left rail' });
    for (const name of ['Video', 'Upscale']) {
      await leftRail.getByRole('button', { exact: true, name }).click({ button: 'right' });
      await page.getByRole('menuitem', { exact: true, name: `Remove ${name}` }).click();
    }
    await floatImageMapFrom(leftRail, 'Left panel widgets');
    await page.getByRole('complementary', { exact: true, name: 'left widget panel' }).waitFor({ state: 'detached' });
    await removeImageMapFrom(leftRail, 'center');

    await floatImageMapFrom(leftRail, 'Left panel widgets');
    await leftRail.getByRole('button', { exact: true, name: 'Left panel widgets' }).click();
    await page.getByRole('menuitemcheckbox', { exact: true, name: 'Image Map' }).click();
    await floatingWindow.waitFor({ state: 'detached' });
    // A focus move would have landed within a frame of the removal.
    await page.evaluate(
      () =>
        new Promise((resolve) => {
          requestAnimationFrame(() => requestAnimationFrame(resolve));
        })
    );
    assert.equal(
      await page.evaluate(() => Boolean(document.activeElement?.closest('[role="menu"]'))),
      true,
      'Removing a window from the enable menu must leave focus in that menu.'
    );
    await page.keyboard.press('Escape');

    if (pageErrors.length > 0) {
      throw new AggregateError(pageErrors, `${id} raised uncaught browser errors.`);
    }

    return { id, status: 'passed' };
  } finally {
    await context.close();
  }
};

const SETTINGS_DIALOG_SCOPE = { include: ['[data-scope="dialog"][data-part="content"]'] };

const runSettingsJourney = async (browser) => {
  const { context, page, pageErrors } = await openRepresentativePage(browser, representativeProjectPath);
  const id = 'workbench-settings';

  try {
    await waitForWorkbench(page);
    const gear = page.getByRole('button', { exact: true, name: 'Gallery settings' });
    await gear.click();
    // Wait for lazy settings controls; their arrival moves the footer's click target.
    await page.getByRole('slider', { exact: true, name: 'Image size' }).waitFor();
    await waitForSettledDocument(page);
    await page.getByRole('button', { exact: true, name: 'All Gallery settings…' }).click();
    const dialog = page.getByRole('dialog', { name: /^Settings:/ });
    await dialog.waitFor();
    const navigation = dialog.getByRole('navigation', { exact: true, name: 'Settings' });
    const sectionNames = await navigation.getByRole('button').allTextContents();
    assert.equal(
      sectionNames.length,
      15,
      'All application, project, widget, and system sections must be discoverable.'
    );
    assert(sectionNames.includes('Intermediates'), 'Intermediates settings must be discoverable.');
    for (const name of sectionNames) {
      await navigation.getByRole('button', { exact: true, name }).click();
      await page.getByRole('dialog', { exact: true, name: `Settings: ${name}` }).waitFor();
      await page.waitForLoadState('networkidle');
      await waitForSettledDocument(page);
      await assertNoAxeViolations(page, `${id}:${name}`, SETTINGS_DIALOG_SCOPE);
    }

    const search = dialog.getByRole('textbox', { exact: true, name: 'Search settings…' });
    await search.focus();
    await search.pressSequentially('numeric attention');
    const numericAttention = dialog.getByRole('checkbox', { exact: true, name: 'Prefer numeric attention style' });
    await numericAttention.waitFor();
    await expectFocused(search, 'Filtering settings should keep keyboard focus in search.');
    await numericAttention.focus();
    await numericAttention.press('Space');
    assert.equal(await numericAttention.isChecked(), true);
    await waitForSettledDocument(page);
    await assertNoAxeViolations(page, `${id}:search`, SETTINGS_DIALOG_SCOPE);
    await dialog.getByRole('button', { exact: true, name: 'Show in section' }).click();
    await expectFocused(numericAttention, 'Revealing a setting should focus its control.');
    await page.keyboard.press('Escape');
    await dialog.waitFor({ state: 'hidden' });
    await expectFocused(gear, 'Closing settings should return focus to its widget gear.');

    await gear.press('Enter');
    const popover = page.locator('[data-scope="popover"][data-part="content"][data-state="open"]');
    await popover.waitFor();
    await waitForSettledDocument(page);
    // Quick settings are nonmodal; scan their popup independently of the workbench behind it.
    await assertNoAxeViolations(page, `${id}:quick`, { include: ['[data-scope="popover"][data-part="content"]'] });
    await page.keyboard.press('Escape');
    await popover.waitFor({ state: 'hidden' });
    await expectFocused(gear, 'Closing quick settings should restore focus to its widget gear.');

    if (pageErrors.length > 0) {
      throw new AggregateError(pageErrors, `${id} raised uncaught browser errors.`);
    }
    return { id, status: 'passed' };
  } catch (error) {
    const directory = resolve(root, 'artifacts/accessibility');
    await mkdir(directory, { recursive: true })
      .then(async () => {
        await writeFile(resolve(directory, `${id}.txt`), `${inspect(error, { depth: null, colors: false })}\n`);
        await page.screenshot({ path: resolve(directory, `${id}.png`) });
      })
      .catch((artifactError) => process.stderr.write(`Could not capture ${id}: ${String(artifactError)}\n`));
    throw error;
  } finally {
    await context.close();
  }
};

const runHiddenMaintenanceJourney = async (browser) => {
  const id = 'launchpad-hidden-maintenance';
  for (const outcome of ['success', 'error']) {
    const { context, page } = await openRepresentativePage(browser, '/#/');
    let finish = () => {};
    let started = () => {};
    const executing = new Promise((resolveStarted) => {
      started = resolveStarted;
    });
    const pending = new Promise((resolvePending) => {
      finish = resolvePending;
    });
    let previews = 0;
    let mutations = 0;
    await page.route('**/api/v1/app/gallery/maintenance/preview', (route) => {
      previews += 1;
      return route.fulfill({
        status: 200,
        json: {
          operation: 'archive_untracked',
          fingerprint: 'a'.repeat(64),
          examined_count: 12,
          affected_count: 2,
          skipped_count: 0,
          error_count: 0,
          errors: [],
          archive_path: '/fixture/gallery-archive',
        },
      });
    });
    await page.route('**/api/v1/app/gallery/maintenance/archive-untracked', async (route) => {
      mutations += 1;
      started();
      await pending;
      await route.fulfill(
        outcome === 'error'
          ? { status: 500, json: { detail: 'Fixture maintenance failure' } }
          : {
              status: 200,
              json: {
                operation: 'archive_untracked',
                status: 'completed',
                examined_count: 12,
                skipped_count: 0,
                failed_count: 0,
                records_removed: 0,
                images_archived: 2,
                thumbnails_archived: 0,
                thumbnails_regenerated: 0,
                archive_path: '/fixture/gallery-archive',
                backup_path: '/fixture/gallery-backup.sqlite',
                errors: [],
              },
            }
      );
    });
    try {
      await waitForHome(page);
      await page.evaluate(() => {
        location.hash = '/preferences/workspace';
      });
      const action = page.getByRole('button', { name: 'Archive untracked files', exact: true });
      await action.click();
      const dialog = page.getByRole('alertdialog');
      await dialog.getByRole('button', { name: 'Archive untracked files', exact: true }).click();
      await executing;
      await page.goBack();
      await waitForHome(page);
      const settled = page.waitForResponse((response) =>
        response.url().endsWith('/api/v1/app/gallery/maintenance/archive-untracked')
      );
      finish();
      await (await settled).finished();
      await page.goForward();
      await page
        .getByText(outcome === 'success' ? 'Gallery maintenance completed.' : 'Fixture maintenance failure', {
          exact: true,
        })
        .waitFor();
      await page.getByRole('alertdialog').waitFor({ state: 'hidden' });
      assert.equal(await action.isEnabled(), true, 'Hidden completion must release the running state.');
      assert.equal(previews, 1);
      assert.equal(mutations, 1, 'History navigation must never repeat destructive execution.');
      await waitForSettledDocument(page);
      await assertNoAxeViolations(page, `${id}:${outcome}`);
    } finally {
      finish();
      await context.close();
    }
  }
  return {
    id,
    status: 'passed',
    hiddenOutcomes: ['success', 'error'],
    navigation: 'browser Back/Forward while modal',
    mutationsPerOperation: 1,
  };
};

const runNativeWidgetRecoveryJourney = async (browser, failures, activeWorker = false) => {
  const id = activeWorker
    ? 'workbench-native-import-active-worker-recovery'
    : failures === 1
      ? 'workbench-native-import-recovery'
      : 'workbench-native-import-repeated-recovery';
  await fetch(`${backendOrigin}/__reset?profile=representative`, { method: 'POST' });
  const manifest = JSON.parse(await readFile(resolve(root, 'dist/.vite/manifest.json'), 'utf8'));
  const chunk = manifest['src/workbench/widgets/preview/implementation.ts'].file;
  const proxy = activeWorker ? await startAssetFaultProxy(origin, chunk, failures) : null;
  const context = await browser.newContext({
    viewport: { width: 1440, height: 1000 },
    reducedMotion: 'reduce',
    ...(activeWorker ? {} : { serviceWorkers: 'block' }),
  });
  const page = await context.newPage();
  let remainingFailures = failures;
  const requests = proxy?.requests ?? [];
  const workerResponses = [];
  page.on('response', (response) => {
    if (new URL(response.url()).pathname === `/${chunk}`) {
      workerResponses.push({ status: response.status(), fromServiceWorker: response.fromServiceWorker() });
    }
  });
  if (!activeWorker) {
    await page.route(`**/${chunk}`, async (route) => {
      const blocked = remainingFailures-- > 0;
      requests.push(blocked ? 503 : 200);
      if (blocked) {
        await route.fulfill({ status: 503, contentType: 'text/javascript', body: 'Temporary module outage' });
      } else {
        await route.continue();
      }
    });
  }
  try {
    if (activeWorker) {
      await page.goto(proxy.origin);
      await page.evaluate(async () => {
        await navigator.serviceWorker.ready;
        if (!navigator.serviceWorker.controller) {
          await new Promise((resolveController) => {
            navigator.serviceWorker.addEventListener('controllerchange', resolveController, { once: true });
          });
        }
      });
      assert.equal(await page.evaluate(() => navigator.serviceWorker.controller.state), 'activated');
      assert.equal(await page.evaluate(() => new URL(navigator.serviceWorker.controller.scriptURL).pathname), '/sw.js');
      assert.deepEqual(requests, [], 'The lazy target must not already be cached before the fault.');
    }
    await page.goto(`${proxy?.origin ?? origin}${representativeProjectPath}`);
    await waitForWorkbench(page);
    let canvasUndoName;
    if (failures > 1) {
      await selectLayoutPreset(page, 'Edit', 'Canvas');
      await page.getByRole('button', { name: 'Add layer', exact: true }).click();
      await page.getByRole('menuitem', { name: 'Raster layer', exact: true }).click();
      const undo = page.getByRole('button', { name: /^Undo: / });
      await undo.waitFor();
      canvasUndoName = await undo.getAttribute('aria-label');
      assert.equal(await undo.isEnabled(), true);
    }
    await selectLayoutPreset(page, 'Compose', 'Preview');
    const card = centerRegion(page).locator('[data-testid="widget-failure"]');
    await card.getByRole('button', { name: 'Retry', exact: true }).waitFor();
    assert.deepEqual(requests, [503]);
    await waitForSettledDocument(page);
    await assertNoAxeViolations(page, `${id}:failed`);
    const output = resolve(root, 'artifacts/accessibility');
    await mkdir(output, { recursive: true });
    await page.screenshot({ path: resolve(output, `${id}-failed.png`) });
    const before = await page.evaluate(() => performance.timeOrigin);
    const draft = 'Native import recovery keeps this held prompt';
    const prompt = page.getByLabel('Positive prompt', { exact: true });
    await prompt.fill(draft);
    const unsaved = await fetch(`${backendOrigin}/api/v1/projects/fixture-project-001`).then((response) =>
      response.json()
    );
    assert.equal(JSON.stringify(unsaved).includes(draft), false, 'The field must not already be saved before Retry.');
    const retry = card.getByRole('button', { name: 'Retry', exact: true });
    await retry.focus();
    await retry.press('Enter');
    if (failures > 1) {
      const reload = card.getByRole('button', { name: 'Reload editor', exact: true });
      await reload.waitFor();
      assert.equal(
        await page.evaluate(() => performance.timeOrigin),
        before,
        'Ordinary Retry must keep the document and its undo histories.'
      );
      await reload.click();
      const dialog = page.getByRole('alertdialog', { name: 'Reload the editor?' });
      await dialog.waitFor();
      assert.match(await dialog.textContent(), /ALL open projects.*Canvas undo and per-workflow edit histories/);
      await waitForSettledDocument(page);
      await assertNoAxeViolations(page, `${id}:confirmation`);
      await page.screenshot({ path: resolve(output, `${id}-confirmation.png`) });
      await dialog.getByRole('button', { name: 'Cancel', exact: true }).click();
      assert.equal(await page.evaluate(() => performance.timeOrigin), before);
      assert.equal(await prompt.inputValue(), draft);
      await selectLayoutPreset(page, 'Edit', 'Canvas');
      const retainedUndo = page.getByRole('button', { name: canvasUndoName, exact: true });
      assert.equal(await retainedUndo.isEnabled(), true, 'Cancel must retain real Canvas undo, across layout hiding.');
      await selectLayoutPreset(page, 'Compose', 'Preview');
      // A new held draft proves confirmation saves the current editor, not just the earlier Retry's checkpoint.
      await prompt.fill(`${draft} after cancel`);
      const beforeConfirm = await fetch(`${backendOrigin}/api/v1/projects/fixture-project-001`).then((response) =>
        response.json()
      );
      assert.equal(JSON.stringify(beforeConfirm).includes(`${draft} after cancel`), false);
      await reload.click();
      await dialog.getByRole('button', { name: 'Reload editor', exact: true }).click();
      await page.waitForFunction((previous) => performance.timeOrigin > previous, before);
    }
    await waitForWorkbench(page);
    await centerViewTrigger(page, 'Preview').waitFor();
    await page
      .locator('[data-hotkey-widget-region="center"][data-hotkey-widget-type-id="preview"]')
      .getByRole('button', { name: /^Auto-switch:/ })
      .waitFor();
    await centerRegion(page).locator('[data-widget-loading]').waitFor({ state: 'detached' });
    await centerRegion(page).locator('[data-testid="widget-failure"]').waitFor({ state: 'detached' });
    await page.getByLabel('Positive prompt', { exact: true }).waitFor();
    assert.equal(
      await page.getByLabel('Positive prompt', { exact: true }).inputValue(),
      failures > 1 ? `${draft} after cancel` : draft
    );
    assert.deepEqual(requests, [...Array(failures).fill(503), 200]);
    if (activeWorker) {
      assert.deepEqual(
        workerResponses,
        requests.map((status) => ({ status, fromServiceWorker: true }))
      );
      assert.equal(await page.evaluate(() => navigator.serviceWorker.controller.state), 'activated');
      await page.waitForFunction(
        async (asset) => !!(await caches.match(new URL(asset, location.origin).href, { cacheName: 'invokeai-assets' })),
        chunk
      );
    }
    await waitForSettledDocument(page);
    await assertNoAxeViolations(page, `${id}:recovered`);
    await page.screenshot({ path: resolve(output, `${id}-recovered.png`) });
    return {
      id,
      status: 'passed',
      requests,
      chromiumVersion: browser.version(),
      freshDocument: await page.evaluate((previous) => performance.timeOrigin > previous, before),
      draftInitiallyUnsaved: true,
      promptPreserved: true,
      ...(failures > 1 ? { canvasUndoRetainedOnCancel: true } : {}),
      ...(activeWorker ? { workerResponses, workerActiveBeforeFault: true, recoveredAssetCached: true } : {}),
    };
  } finally {
    await context.close();
    await proxy?.close();
  }
};

const runNativeUsersRecoveryJourney = async (browser) => {
  const id = 'launchpad-users-native-import-recovery';
  await fetch(`${backendOrigin}/__reset?profile=representative`, { method: 'POST' });
  await fetch(`${backendOrigin}/__faults`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ intermediatesCaller: 'multiuser-admin' }),
  });
  const manifest = JSON.parse(await readFile(resolve(root, 'dist/.vite/manifest.json'), 'utf8'));
  const chunk = manifest['src/features/identity/ui/UsersPage.tsx'].file;
  const context = await browser.newContext({
    viewport: { width: 1440, height: 1000 },
    reducedMotion: 'reduce',
    serviceWorkers: 'block',
  });
  const page = await context.newPage();
  let blocked = true;
  const requests = [];
  await page.route('**/api/v1/auth/users', (route) =>
    route.fulfill({ status: 200, contentType: 'application/json', body: '[]' })
  );
  await page.route(`**/${chunk}`, async (route) => {
    requests.push(blocked ? 503 : 200);
    if (blocked) {
      await route.fulfill({ status: 503, contentType: 'text/javascript', body: 'Temporary module outage' });
    } else {
      await route.continue();
    }
  });
  try {
    await page.goto(origin);
    await page.getByLabel('Email', { exact: true }).fill('[email protected]');
    await page.getByLabel('Password', { exact: true }).fill('fixture-password');
    await page.getByRole('button', { name: 'Sign in', exact: true }).click();
    await page.getByRole('link', { name: 'Users', exact: true }).waitFor();
    assert.deepEqual(requests, [], 'Home must not request user management.');
    await page.getByRole('link', { name: 'Users', exact: true }).click();
    await page.getByText('Unable to load users', { exact: true }).waitFor();
    await assertNoAxeViolations(page, `${id}:failed`);
    const before = await page.evaluate(() => performance.timeOrigin);
    blocked = false;
    await page.getByRole('button', { name: 'Retry', exact: true }).press('Enter');
    await page.waitForFunction((previous) => performance.timeOrigin > previous, before);
    await page.getByText('0 accounts in this workspace.', { exact: true }).waitFor();
    assert.deepEqual(requests, [503, 200]);
    await page.getByRole('button', { name: 'Add user', exact: true }).click();
    await page.getByRole('dialog').waitFor();
    await waitForSettledDocument(page);
    await assertNoAxeViolations(page, `${id}:recovered`);
    return { id, status: 'passed', requests, coldHomeManagementRequests: 0, freshDocument: true };
  } finally {
    await context.close();
  }
};

const mockBackend = await startMockBackend(backendPort, { profile: 'representative' });
const preview = spawnPreview({
  cwd: root,
  env: { ...process.env, INVOKEAI_DEV_BACKEND: backendOrigin },
  port,
  stdio: ['ignore', 'pipe', 'pipe'],
});
let previewError = '';
let browser = null;

preview.stderr.on('data', (chunk) => {
  previewError += String(chunk);
});

try {
  await waitForPreview();
  browser = await chromium.launch({ headless: true });
  const reports = [];

  for (const surface of surfaces.filter(({ id }) => !requestedJourney || id === requestedJourney)) {
    reports.push(await runAxeSurface(browser, surface));
  }

  if (!requestedJourney || requestedJourney === 'keyboard-critical-journey') {
    reports.push(await runKeyboardJourney(browser));
  }
  if (!requestedJourney || requestedJourney === 'workbench-shortcuts') {
    reports.push(await runShortcutGuideJourney(browser));
  }
  if (!requestedJourney || requestedJourney === 'workbench-status-bar-names') {
    reports.push(await runStatusBarNamesJourney(browser));
  }
  if (!requestedJourney || requestedJourney === 'workbench-topbar-responsive') {
    reports.push(await runResponsiveTopbarJourney(browser));
  }
  if (!requestedJourney || requestedJourney === 'workbench-topbar-menus') {
    reports.push(await runTopbarMenuJourney(browser));
  }
  if (!requestedJourney || requestedJourney === 'workbench-video-preview-representative') {
    reports.push(await runVideoPreviewJourney(browser));
  }
  if (!requestedJourney || requestedJourney === 'workbench-keep-alive-state') {
    reports.push(await runKeepAliveStateJourney(browser));
  }
  if (!requestedJourney || requestedJourney === 'workbench-layers-panes') {
    reports.push(await runLayersPanesJourney(browser));
  }
  if (!requestedJourney || requestedJourney === 'workbench-floating-window') {
    reports.push(await runFloatingWindowJourney(browser));
  }
  if (!requestedJourney || requestedJourney === 'workbench-settings') {
    reports.push(await runSettingsJourney(browser));
  }
  if (!requestedJourney || requestedJourney === 'workbench-native-import-recovery') {
    reports.push(await runNativeWidgetRecoveryJourney(browser, 1));
  }
  if (!requestedJourney || requestedJourney === 'workbench-native-import-repeated-recovery') {
    reports.push(await runNativeWidgetRecoveryJourney(browser, 2));
  }
  if (!requestedJourney || requestedJourney === 'workbench-native-import-active-worker-recovery') {
    reports.push(await runNativeWidgetRecoveryJourney(browser, 2, true));
  }
  if (!requestedJourney || requestedJourney === 'launchpad-users-native-import-recovery') {
    reports.push(await runNativeUsersRecoveryJourney(browser));
  }
  if (!requestedJourney || requestedJourney === 'launchpad-hidden-maintenance') {
    reports.push(await runHiddenMaintenanceJourney(browser));
  }
  if (reports.length === 0) {
    throw new Error(`Unknown accessibility journey ${JSON.stringify(requestedJourney)}.`);
  }
  process.stdout.write(`${JSON.stringify({ profile: 'representative', reports }, null, 2)}\n`);
} catch (error) {
  const failure = `${inspect(error, { depth: null, colors: false })}${previewError ? `\n${previewError}` : ''}`;
  const directory = resolve(root, 'artifacts/accessibility');
  await mkdir(directory, { recursive: true })
    .then(() => writeFile(resolve(directory, 'failure.txt'), `${failure}\n`))
    .catch((artifactError) =>
      process.stderr.write(`Could not capture accessibility failure: ${String(artifactError)}\n`)
    );
  throw new Error(failure);
} finally {
  await browser?.close();

  if (preview.pid) {
    try {
      killPreview(preview.pid, 'SIGTERM');
    } catch {
      // Preview may already have exited after a startup failure.
    }
  }

  await mockBackend.close();
}