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.

fix(frontend): preserve edits and validate browser lifecycles (#10165)

Josh Corbettfa5621ef8558
diff --git a/.github/AGENTS.md b/.github/AGENTS.md
index a69a6372b2..ce7f4cf336 100644
--- a/.github/AGENTS.md
+++ b/.github/AGENTS.md
@@ -4,7 +4,7 @@
- Keep PR, main-push, merge-group, manual-dispatch, reusable-workflow events. `github.base_ref` is not always set outside PRs.
- Change detection must include workflows and relevant shared actions/config. Test-only and tooling-only changes must trigger owning checks.
- Keep tool versions, lockfiles, reproducible installs, hardware/platform matrices, pinned action revisions.
-- Prefer package completion commands over duplicating them in YAML. Webv2 `pnpm check:release`: install Chromium and required Linux dependencies first.
+- Prefer package completion commands over duplicating them in YAML. Webv2 `pnpm check:release`: install locked Chromium, Firefox, WebKit and required Linux dependencies first. Completion includes the three-engine lifecycle smoke and reuses its performance build.
- Keep failure diagnostics with `always()` where fitting. Generated review/performance artifacts stay out of Git.
- Hooks must match CI's Ruff version and config. Validation never rewrites formatting.
- Workflow changes neither configure hosted branch protection nor install local hooks. Verify before claiming either.
diff --git a/.github/workflows/frontend-tests.yml b/.github/workflows/frontend-tests.yml
index b4e6b25fbd..3369287cff 100644
--- a/.github/workflows/frontend-tests.yml
+++ b/.github/workflows/frontend-tests.yml
@@ -45,7 +45,7 @@ concurrency:
jobs:
frontend-webv2-tests:
runs-on: blacksmith-4vcpu-ubuntu-2404
- timeout-minutes: 20 # Includes browser suites, performance sampling, project files, and accessibility.
+ timeout-minutes: 30 # Completion reached 19 minutes; allow 3-engine smoke and cold exact-base measurements.
defaults:
run:
working-directory: invokeai/frontend/webv2
@@ -71,9 +71,9 @@ jobs:
with:
working-directory: invokeai/frontend/webv2
- - name: install Chromium
+ - name: install smoke browsers
if: ${{ steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true }}
- run: 'pnpm exec playwright install --with-deps chromium'
+ run: 'pnpm exec playwright install --with-deps chromium firefox webkit'
shell: bash
# A pull request into main, or a merge group, is compared with the base branch's
@@ -196,4 +196,5 @@ jobs:
invokeai/frontend/webv2/artifacts/architecture
invokeai/frontend/webv2/artifacts/architecture-performance
invokeai/frontend/webv2/artifacts/accessibility
+ invokeai/frontend/webv2/artifacts/browser-smoke
if-no-files-found: ignore
diff --git a/docs/src/content/docs/development/Process/release-process.mdx b/docs/src/content/docs/development/Process/release-process.mdx
index c6b22730fb..92285cc6e9 100644
--- a/docs/src/content/docs/development/Process/release-process.mdx
+++ b/docs/src/content/docs/development/Process/release-process.mdx
@@ -62,7 +62,7 @@ Next, these jobs run and must pass. They are the same jobs that are run for ever
- **`python-tests`**: runs `pytest` on matrix of platforms
- **`python-checks`**: runs `ruff` (format and lint)
-- **`frontend-tests`**: runs webv2's `check:release`, including unit/browser tests, performance, project-file, and accessibility gates
+- **`frontend-tests`**: runs webv2's `check:release`, including unit/browser tests, performance, project-file, accessibility, and Chromium/Firefox/WebKit lifecycle gates
- **`frontend-checks`**: runs webv2 formatting, Oxc lint, TypeScript, architecture checks, and its production build
PRs also run **`openapi-checks`** and **`typegen-checks`** against the shared `invokeai/frontend/api` package to detect backend contract drift. Legacy webv1 lint/tests remain local commands.
diff --git a/invokeai/frontend/webv2/AGENTS.md b/invokeai/frontend/webv2/AGENTS.md
index 56294cdba0..b02e4ca56d 100644
--- a/invokeai/frontend/webv2/AGENTS.md
+++ b/invokeai/frontend/webv2/AGENTS.md
@@ -43,21 +43,22 @@ No Python backend: `pnpm dev:mock` serves the app against the in-repo mock backe
- Preserve disposal, bounded memory, account transitions, responsive input. Never update goldens/baselines to hide regressions.
- Run pnpm from this directory: Corepack picks pnpm's version from the current directory, so `pnpm -C` from the repo root can get the wrong one. Install: `pnpm install --frozen-lockfile`.
-| Change/check | Command |
-| ------------------------------------- | --------------------------------------------------------------------- |
-| Formatting, lint, types, architecture | `pnpm lint` |
-| Focused behavior | `pnpm test <test-path>` or `pnpm test:browser <browser-test-path>` |
-| Unit, Chromium, mock-backend fixtures | `pnpm test:all` |
-| Architecture and browser performance | `pnpm test:performance:architecture` ([guide](performance/README.md)) |
-| Project-file integration | `pnpm test:project-files` |
-| Accessibility in a fresh build | `pnpm test:accessibility` |
-| Milestone/release completion | `pnpm check:release` |
-
-- Missing Chromium: `pnpm exec playwright install chromium` (`--with-deps` in Linux CI).
+| Change/check | Command |
+| --------------------------------------- | --------------------------------------------------------------------- |
+| Formatting, lint, types, architecture | `pnpm lint` |
+| Focused behavior | `pnpm test <test-path>` or `pnpm test:browser <browser-test-path>` |
+| Unit, Chromium, mock-backend fixtures | `pnpm test:all` |
+| Architecture and browser performance | `pnpm test:performance:architecture` ([guide](performance/README.md)) |
+| Project-file integration | `pnpm test:project-files` |
+| Three-engine lifecycle in a fresh build | `pnpm test:browser:smoke` |
+| Accessibility in a fresh build | `pnpm test:accessibility` |
+| Milestone/release completion | `pnpm check:release` |
+
+- Missing engines for completion: `pnpm exec playwright install chromium firefox webkit` (`--with-deps` in Linux CI).
- Colocate tests: unit `*.test.ts`/`*.test.tsx`, browser `*.browser.test.ts`/`*.browser.test.tsx`.
- Use real IndexedDB, Web Locks, focus, pointer, rendering where mocks cannot prove correctness.
- Droppable enabled only after drag start: drag through dnd-kit mouse sensors with `dragWithMouse` (`@platform/browser/mouseDrag.testing`). Single-jump drags such as `userEvent.dragAndDrop` miss it.
Unit tests cache transformed modules between runs in ignored `node_modules/.vitest-cache`.
-Focused checks during development. `check:release` before code-milestone readiness: lint, all tests, architecture performance/build, project-file journeys, accessibility. CI splits completion between `lint:code` and `check:release:tests`; together they run each gate once. Routine browser performance checks take two resource observations per fixture; `test:performance:browser:profile` and baseline updates use full timing sampling. Docs-only changes: formatting and link review, no application tests. Architecture inventories and performance reports stay in ignored `artifacts/`, never committed.
+Focused checks during development. `check:release` before code-milestone readiness: lint, all tests, architecture performance/build, project-file journeys, accessibility, three-engine lifecycle smoke. CI splits completion between `lint:code` and `check:release:tests`; together they run each gate once. Routine browser performance checks take two resource observations per fixture; `test:performance:browser:profile` and baseline updates use full timing sampling. Docs-only changes: formatting and link review, no application tests. Architecture inventories and performance reports stay in ignored `artifacts/`, never committed.
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index 6a50b29a31..86c38464e6 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -12,7 +12,7 @@
"build": "pnpm run lint && vite build",
"check:architecture": "pnpm run lint:code && pnpm run test:all && pnpm run architecture:inventory && pnpm run test:performance:architecture && pnpm run test:project-files:browser",
"check:release": "pnpm run lint:code && pnpm run check:release:tests",
- "check:release:tests": "pnpm run test:all && pnpm run architecture:inventory && pnpm run test:performance:architecture && pnpm run test:project-files:browser && pnpm run test:accessibility:browser",
+ "check:release:tests": "pnpm run test:all && pnpm run architecture:inventory && pnpm run test:performance:architecture && pnpm run test:project-files:browser && pnpm run test:accessibility:browser && pnpm run test:browser:smoke:browser",
"dev": "vite dev",
"dev:host": "vite dev --host",
"dev:mock": "node scripts/dev-mock.mjs",
@@ -35,8 +35,10 @@
"test:accessibility:build": "vite build",
"test:all": "pnpm run test && pnpm run test:browser && pnpm run test:fixtures",
"test:browser": "vitest run --config vitest.browser.config.mts",
+ "test:browser:smoke": "vite build && pnpm run test:browser:smoke:browser",
+ "test:browser:smoke:browser": "node scripts/run-browser-smoke.mjs",
"test:browser:update-goldens": "CANVAS_GOLDEN_UPDATE=1 vitest run --config vitest.browser.config.mts src/workbench/canvas-engine/render/golden",
- "test:fixtures": "node --test scripts/mock-backend-fixtures.test.mjs scripts/preview-server.test.mjs scripts/run-project-file-journey.test.mjs scripts/locale-assets-plugin.test.mjs scripts/export-graphs.test.mjs scripts/asset-fault-proxy.test.mjs",
+ "test:fixtures": "node --test scripts/mock-backend-fixtures.test.mjs scripts/preview-server.test.mjs scripts/run-project-file-journey.test.mjs scripts/locale-assets-plugin.test.mjs scripts/export-graphs.test.mjs scripts/asset-fault-proxy.test.mjs scripts/browser-validation.test.mjs",
"test:performance:architecture": "pnpm run test:performance:build && pnpm run test:performance:browser",
"test:performance:browser": "node scripts/measure-architecture-performance.mjs",
"test:performance:browser:profile": "node scripts/measure-architecture-performance.mjs --profile",
diff --git a/invokeai/frontend/webv2/performance/README.md b/invokeai/frontend/webv2/performance/README.md
index 720ff9128f..408485143f 100644
--- a/invokeai/frontend/webv2/performance/README.md
+++ b/invokeai/frontend/webv2/performance/README.md
@@ -31,6 +31,7 @@ Reference modes:
## Running
+- CI’s 30-minute job timeout covers completion, including the three-engine lifecycle smoke and cold exact-base measurements; completion has already reached about 19 minutes.
- CI splits `check:release` between `lint:code` in the checks job and `check:release:tests` in the tests job. Architecture tests run in the complete unit suite; inventories are generated once and the performance build serves all subsequent browser journeys.
- `check:release` stops at the first failing gate; later gates did not run. In CI logs the failure sits at the tail, after passing test summaries.
- Browser gate binds ports 4176 and 4177 (`INVOKEAI_PERFORMANCE_PORT`, `INVOKEAI_PERFORMANCE_BACKEND_PORT`). One performance gate per machine, nothing else building or testing.
@@ -77,6 +78,89 @@ Failures name an owner and a remediation ticket: structural work that would reti
| `finish-queue-ownership` | Importers of `@features/queue` |
| `define-gallery-feature` | Importers of `./GalleryWidgetView` |
+## Render validity and sustained interaction evidence
+
+Nominal browser journeys distinguish implementation mount marks from usable content. Visible images must finish
+`decode()`; the representative Canvas journey also waits for fixture pixels on the Canvas surface and a painted
+layer thumbnail. Mock full images are deterministic PNGs matching their DTO dimensions; thumbnails preserve aspect
+ratio within 256 pixels, without upscaling. Their encoding differs from the backend's WEBP thumbnails. Generation
+is capped at 4096 pixels per dimension and the shared dimension cache at 32 entries. Fixture tests verify PNG CRCs,
+inflated scanlines and dimensions, including a 4096-square image. Corrupt bytes are used only in negative tests.
+
+The shared journey diagnostics reject uncaught errors, console errors, HTTP failures and failed requests. Only the
+mock's `/ws/socket.io/?…transport=polling` 404 is expected. Canceled Queue status polls are normal owner teardown;
+HTTP failures for that endpoint still fail. Lifecycle/fault journeys declare their other expected failures locally.
+Browser reports keep API media requests and decoded dimensions separate from static-resource byte accounting.
+Failures retain diagnostics, screenshots and the existing diagnostic traces under `artifacts/architecture-performance`.
+
+Both routine resource observations and full profiles run a bounded Gallery quick-settings workload after startup and return-switch measurements on the
+representative Compose fixture: one warmup and six open/change/close cycles per routine observation or scored profile sample. Every cycle arms the pinned Chakra presence owner’s native `exitcomplete` event before closing, waits at most five seconds for it, then polls React removal for at most 250 ms before reporting actual retained counts. Persistent DOM is still rejected by the zero-retention bound. Animation-finished promises alone do not establish presence completion.
+Retained popover count must be zero; the runner fails immediately on a retained portal instead of waiting it away.
+Routine resource observations also run this bounded correctness phase, independently of report-only timing.
+DOM nodes, Canvas elements and request counts are diagnostic observations, not universal lifetime bounds. The
+report includes every cycle, interaction min/median/p95/max and observed long-task distributions. Long tasks cover
+the interaction phase, including its warmup, and interaction latency includes automation overhead; neither is an INP measurement. Failure
+artifacts preserve the workload context. The workload is intentionally hard-coded to Gallery quick settings; other owners need their own journey before extending coverage.
+
+Sustained reports name the runner, engine version, platform, workload and sample policy. Timing distributions remain report-only; portal retirement is enforced:
+`browser-baseline.json` still requires 20 stable runs on a designated runner before timing enforcement. Local runs
+cannot satisfy that calibration policy. Existing byte ceilings, timing sampling and goldens are unchanged.
+
+## Browser lifecycle smoke
+
+`pnpm test:browser:smoke` creates a fresh production build, then uses the existing project-file preview/backend lifecycle.
+`check:release` runs `test:browser:smoke:browser` after its shared performance build, so completion and CI build once.
+Use the raw `:browser` command only when the build is known current. Install engines using the locked package:
+`pnpm exec playwright install --with-deps chromium firefox webkit`. Ports default to 4180/4181; override
+`INVOKEAI_PROJECT_FILE_PORT` and `INVOKEAI_PROJECT_FILE_BACKEND_PORT` for an isolated focused run.
+
+The required localhost capabilities are IndexedDB and Web Locks. Each engine holds the initial fixture migration PUT before server dispatch, makes a new held prompt edit, and
+leaves for a neutral same-origin document immediately. Before any editor can reconcile it, the suite proves the
+committed journal has the new marker while the staged draft, held PUT bodies and server do not. Reopening must
+recover that marker. Each engine also verifies actual Canvas and layer-thumbnail fixture pixels, rejects an opaque
+checker-only thumbnail and empty Canvas, holds native animation-end delivery to prove retirement waits for the owner’s exit event, defers actual owner DOM removal by 100 ms to exercise the bounded React-removal grace, and injects retained portal DOM into the real sustained-workload collector.
+Engines must give duplicated tabs separate live editor sessions, release a closed tab's session lock, preserve edits
+across route re-entry after Launchpad owner/media readiness (all mounted cover images finish decoding), advance keyboard focus, and disable copy controls with an explanation when clipboard is
+unavailable. This is targeted current-engine coverage, with no minimum-version support promise. Missing engines or
+required capabilities fail the command and are reported, rather than skipped. Every engine is attempted, even after
+another fails. Reports, failure screenshots and traces live in `artifacts/browser-smoke` and CI uploads them.
+
+A new held prompt is made immediately before history navigation. History return records the real `pageshow.persisted` result and, where exposed, `notRestoredReasons`. A reload is
+reported as such; it does not establish BFCache restoration. Playwright WebKit is not actual Safari verification,
+and says nothing about every Apple platform. The documented Chromium unload guarantee remains scoped to Chromium;
+other engine results are evidence for the tested engine/build/platform only, not a broader durability guarantee.
+
+The smoke context blocks service workers so its same-origin idle HTML document and fault probes cannot be bypassed
+by the PWA navigation cache. This suite exercises real IndexedDB and Web Locks; service-worker cache behavior is
+outside its coverage. The noncanceling unload checkpoint runs before `pagehide` because WebKit can discard an
+IndexedDB journal transaction started in `pagehide`, even after explicit commit. A `beforeunload` listener can reduce
+Firefox BFCache eligibility; restoring from the cache is reported only when the engine actually does so.
+
+Document-navigation cancellation expectations are shared by smoke and release journeys. They apply only inside an
+explicitly owned navigation through DOMContentLoaded, on the same origin's `/api/` requests or mock Socket.IO polling.
+All engines may cancel old-document reads and writes; WebKit may instead emit its exact native Fetch/XMLHttpRequest
+access-control-denial message. A canceled mutation is teardown evidence, never evidence of a successful save: the
+held-edit scenario separately proves journal-only recovery. HTTP 4xx/5xx responses, non-abort failures, cross-origin
+requests, asset failures, live-document mutations and unrelated runtime/console errors remain critical. Queue reader
+cancellations during route re-entry are limited to its actual read interface: status, current, next and item IDs (GET),
+then bounded item hydration (`items_by_ids`, read-only POST). Queue status GET cancellation is also recognized at the
+shared observer because that owner's polling read retires during ordinary in-document switches. Only the concrete project-switch actions in
+`measureProjectSwitch` retire already pending same-origin `GET /api/v1/gallery/items/` request identities: Query cancels the
+old project's listing when its last observer leaves, including after HTTP 200 while the body is pending. These snapshots
+cover the switch to a temporary project and return to the original project; requests started during either action,
+setup/autosave reads, live-page aborts, other endpoints/methods and
+HTTP failures (including a later aborted error body) remain critical. The fault probes
+use independent strict diagnostics and separately assert that request and runtime failures reached the validator.
+
+Image readiness bounds native decoding within the same readiness timeout and retries a legitimately changed image
+source. An explicit owner selector includes every cover, even below the fold. It requires visible decoded images by default, or representative fixture pixels from both Canvas
+owners in Canvas mode. Empty fixtures explicitly opt out of image requirements after their owner semantic-ready
+assertion. An early capturing image-error listener remembers failed images even when an owner's `onError` removes
+them. The smoke proves both corrupt-visible and corrupt-removed image failures, independently of console errors.
+
+Accessibility runner failures retain nested aggregate diagnostics in `artifacts/accessibility/failure.txt`; the
+settings journey also captures its failing page as text and a screenshot before the browser context closes.
+
## Workflow-library scaling fixture
The mock backend accepts `POST /__workflow-library` with JSON `{"scenario":"large"}`. This opt-in workload replaces library records with 1,000 user workflows, each containing 40 integer nodes; normal route fixtures and resource budgets are unchanged. Scenarios `empty`, `failed-page`, `slow-detail`, and `changed-revision` respectively empty the library, fail page 2 once (retry succeeds), delay detail reads by 300 ms, and advance each record's revision on its first detail read. `POST /__reset` restores ordinary fixtures. `GET /__workflow-requests` records list/detail requests since seeding.
diff --git a/invokeai/frontend/webv2/scripts/browser-smoke-expectations.mjs b/invokeai/frontend/webv2/scripts/browser-smoke-expectations.mjs
new file mode 100644
index 0000000000..09aa18d236
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/browser-smoke-expectations.mjs
@@ -0,0 +1,53 @@
+// Queue's POST hydration is a read; commands are deliberately outside owner-remount cancellation.
+const queueReadMethods = new Map([
+ ['/api/v1/queue/default/status', 'GET'],
+ ['/api/v1/queue/default/current', 'GET'],
+ ['/api/v1/queue/default/next', 'GET'],
+ ['/api/v1/queue/default/item_ids', 'GET'],
+ ['/api/v1/queue/default/items_by_ids', 'POST'],
+]);
+export const isQueueReadRequest = (event, origin) => {
+ const url = new URL(event.url);
+ const method = queueReadMethods.get(url.pathname);
+ return method !== undefined && url.origin === origin && method === event.method;
+};
+
+/** Explicit document exit can cancel reads and writes. Recovery must separately prove abandoned writes survive. */
+export const isExpectedDocumentUnload = (event, { navigating, origin }) => {
+ if (!navigating || event.kind === 'response' || event.responseStatus >= 400) {
+ return false;
+ }
+ let url;
+ if (event.kind === 'requestfailed' && /(?:ERR_ABORTED|NS_BINDING_ABORTED|cancelled)/i.test(event.message)) {
+ url = new URL(event.url);
+ } else if (event.kind === 'pageerror') {
+ const match = /^(?:Fetch API|XMLHttpRequest) cannot load (https?:\/\/\S+) due to access control checks\.$/.exec(
+ event.message.split('\n', 1)[0]
+ );
+ if (!match) {
+ return false;
+ }
+ url = new URL(match[1]);
+ } else {
+ return false;
+ }
+ return (
+ url.origin === origin &&
+ (url.pathname.startsWith('/api/') ||
+ (url.pathname === '/ws/socket.io/' && url.searchParams.get('transport') === 'polling'))
+ );
+};
+
+/** Leaving the observed project retires its Gallery page reader, including a response whose body is still pending. */
+export const isExpectedGalleryProjectSwitchAbort = (event, { origin }) => {
+ if (
+ event.kind !== 'requestfailed' ||
+ event.method !== 'GET' ||
+ event.responseStatus >= 400 ||
+ !/(?:ERR_ABORTED|NS_BINDING_ABORTED|cancelled)/i.test(event.message)
+ ) {
+ return false;
+ }
+ const url = new URL(event.url);
+ return url.origin === origin && url.pathname === '/api/v1/gallery/items/';
+};
diff --git a/invokeai/frontend/webv2/scripts/browser-validation.mjs b/invokeai/frontend/webv2/scripts/browser-validation.mjs
new file mode 100644
index 0000000000..bbb243a0a6
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/browser-validation.mjs
@@ -0,0 +1,390 @@
+import { isExpectedDocumentUnload, isExpectedGalleryProjectSwitchAbort } from './browser-smoke-expectations.mjs';
+
+const navigations = new WeakMap();
+
+/** Scope natural cancellation to an explicitly owned document transition, through DOMContentLoaded only. */
+export const withBrowserNavigation = async (page, action) => {
+ navigations.set(page, { navigating: true, origin: new URL(page.url()).origin });
+ try {
+ return await action();
+ } finally {
+ navigations.delete(page);
+ }
+};
+
+const installMediaFailures = () => {
+ window.__browserMediaFailures = [];
+ window.addEventListener(
+ 'error',
+ (event) => {
+ if (event.target instanceof HTMLImageElement) {
+ const url = event.target.currentSrc || event.target.src;
+ window.__browserMediaFailures.push(url);
+ void window.__recordBrowserMediaFailure(url).catch(() => {});
+ }
+ },
+ true
+ );
+};
+
+/** Strict nominal-journey diagnostics; expected failures are scenario-local predicates. */
+export const observeBrowserDiagnostics = async (page, { expected = () => false, onError = () => {} } = {}) => {
+ const errors = [];
+ const media = [];
+ const responseStatuses = new WeakMap();
+ const pendingConsoleDetails = new Set();
+ const pendingGalleryReads = new Set();
+ const retiredGalleryReads = new WeakSet();
+ page.on('request', (request) => {
+ const url = new URL(request.url());
+ if (
+ request.method?.() === 'GET' &&
+ url.origin === new URL(page.url?.() ?? request.url()).origin &&
+ url.pathname === '/api/v1/gallery/items/'
+ ) {
+ pendingGalleryReads.add(request);
+ }
+ });
+ page.on('requestfinished', (request) => {
+ pendingGalleryReads.delete(request);
+ retiredGalleryReads.delete(request);
+ });
+ page.once('close', () => pendingGalleryReads.clear());
+ const socket404 = (url, status) => {
+ const parsed = new URL(url);
+ return parsed.pathname === '/ws/socket.io/' && parsed.searchParams.get('transport') === 'polling' && status === 404;
+ };
+ const record = (event) => {
+ if (!expected(event) && !isExpectedDocumentUnload(event, navigations.get(page) ?? {})) {
+ errors.push(event);
+ onError(event);
+ }
+ };
+ await page.exposeBinding?.('__recordBrowserMediaFailure', (_source, url) =>
+ record({ kind: 'media', url, message: `Image failed to decode: ${url}` })
+ );
+ await page.addInitScript?.(installMediaFailures);
+ page.on('pageerror', (error) => record({ kind: 'pageerror', message: error.stack ?? error.message }));
+ page.on('console', (message) => {
+ if (message.type() !== 'error') {
+ return;
+ }
+ const url = message.location().url;
+ if (url && socket404(url, 404) && /(?:404|Not Found)/.test(message.text())) {
+ return;
+ }
+ const event = { kind: 'console', url, message: message.text() };
+ record(event);
+ // Firefox labels Error objects only as "Error"; retain the actionable message and stack before navigation.
+ const details = Promise.all(
+ (message.args?.() ?? []).map((argument) =>
+ argument
+ .evaluate((value) =>
+ value && typeof value.message === 'string'
+ ? { name: value.name, message: value.message, stack: value.stack }
+ : null
+ )
+ .catch(() => null)
+ )
+ ).then((arguments_) => {
+ event.arguments = arguments_.filter(Boolean);
+ });
+ pendingConsoleDetails.add(details);
+ void details.finally(() => pendingConsoleDetails.delete(details));
+ });
+ page.on('requestfailed', (request) => {
+ // This read is explicitly canceled by Queue's owner on retirement, even within one document.
+ const url = new URL(request.url());
+ if (
+ url.origin === new URL(page.url?.() ?? request.url()).origin &&
+ url.pathname === '/api/v1/queue/default/status' &&
+ request.method?.() === 'GET' &&
+ !(responseStatuses.get(request) >= 400) &&
+ /(?:ERR_ABORTED|NS_BINDING_ABORTED|cancelled)/i.test(request.failure()?.errorText ?? '')
+ ) {
+ return;
+ }
+ const event = {
+ kind: 'requestfailed',
+ url: request.url(),
+ method: request.method?.(),
+ message: request.failure()?.errorText,
+ responseStatus: responseStatuses.get(request),
+ };
+ if (
+ !retiredGalleryReads.has(request) ||
+ !isExpectedGalleryProjectSwitchAbort(event, { origin: new URL(page.url()).origin })
+ ) {
+ record(event);
+ }
+ pendingGalleryReads.delete(request);
+ retiredGalleryReads.delete(request);
+ });
+ page.on('response', (response) => {
+ const request = response.request?.();
+ if (request) {
+ responseStatuses.set(request, response.status());
+ }
+ const url = response.url();
+ if (/\/api\/v1\/(images|videos)\/i\/.*\/(full|thumbnail)/.test(url)) {
+ media.push({ url, status: response.status() });
+ }
+ if (response.status() >= 400 && !socket404(url, response.status())) {
+ record({ kind: 'response', url, status: response.status() });
+ }
+ });
+ return {
+ errors,
+ media,
+ /** Only readers already pending before this switch action retire; new-project reads remain strict. */
+ withGalleryProjectSwitch(action) {
+ for (const request of pendingGalleryReads) {
+ retiredGalleryReads.add(request);
+ }
+ return action();
+ },
+ async assertHealthy() {
+ await Promise.all(pendingConsoleDetails);
+ if (errors.length) {
+ throw new Error(`Unexpected browser diagnostics:\n${JSON.stringify(errors, null, 2)}`);
+ }
+ },
+ };
+};
+
+/** Mount marks are separate: decode the selected images and verify pixels within one bounded readiness wait. */
+export const waitForRenderedMedia = async (
+ page,
+ { canvas = false, requireImage = !canvas, allImagesSelector, timeout = 20_000 } = {}
+) => {
+ const deadline = Date.now() + timeout;
+ // Playwright returns a promise's false result without repolling; reselect interrupted sources within one deadline.
+ while (Date.now() < deadline) {
+ const result = await page.waitForFunction(
+ ({ canvasRequired, imageRequired, allImagesSelector }) => {
+ const checkFailures = () => {
+ if (window.__browserMediaFailures?.length) {
+ throw new Error(
+ `Media failed to decode (including removed images): ${window.__browserMediaFailures.join(', ')}`
+ );
+ }
+ };
+ checkFailures();
+ const visible = (element) => element.checkVisibility() && element.getBoundingClientRect().width > 0;
+ // An owner selector includes its below-fold and hidden images, not just the visible document surface.
+ const selectImages = () =>
+ allImagesSelector ? [...document.querySelectorAll(allImagesSelector)] : [...document.images].filter(visible);
+ const images = selectImages();
+ if (imageRequired && images.length === 0) {
+ return false;
+ }
+ if (images.some((image) => !image.complete)) {
+ return false;
+ }
+ const broken = images.find((image) => image.naturalWidth === 0);
+ if (broken) {
+ throw new Error(`Media failed to decode: ${broken.currentSrc || broken.src}`);
+ }
+ const hasPixels = (selector) =>
+ [...document.querySelectorAll(selector)].filter(visible).some((surface) => {
+ if (!surface.width || !surface.height) {
+ return false;
+ }
+ const pixels = surface.getContext('2d')?.getImageData(0, 0, surface.width, surface.height).data;
+ if (!pixels) {
+ return false;
+ }
+ for (let i = 0; i < pixels.length; i += 4) {
+ if (
+ pixels[i + 3] > 0 &&
+ pixels[i + 2] === 128 &&
+ ((pixels[i] === 64 && pixels[i + 1] === 160) || (pixels[i] === 192 && pixels[i + 1] === 80))
+ ) {
+ return true;
+ }
+ }
+ return false;
+ });
+ if (
+ canvasRequired &&
+ !(
+ hasPixels('[data-hotkey-widget-type-id="canvas"] canvas') &&
+ hasPixels('[data-hotkey-widget-type-id="layers"] [data-layer-row-id] canvas')
+ )
+ ) {
+ return false;
+ }
+ const sources = images.map((image) => ({
+ image,
+ src: image.src,
+ currentSrc: image.currentSrc,
+ srcset: image.srcset,
+ sizes: image.sizes,
+ }));
+ const unchanged = ({ image, src, currentSrc, srcset, sizes }) =>
+ image.isConnected &&
+ image.src === src &&
+ image.currentSrc === currentSrc &&
+ image.srcset === srcset &&
+ image.sizes === sizes;
+ return (async () => {
+ try {
+ await Promise.all(images.map((image) => image.decode()));
+ } catch (error) {
+ checkFailures();
+ if (sources.some((source) => !unchanged(source))) {
+ return false;
+ }
+ throw new Error(`Media failed to decode: ${String(error)}`);
+ }
+ checkFailures();
+ const currentImages = selectImages();
+ if (
+ sources.some((source) => !unchanged(source)) ||
+ currentImages.length !== images.length ||
+ currentImages.some((image, index) => image !== images[index])
+ ) {
+ return false;
+ }
+ return {
+ images: images.map((image) => ({
+ url: image.currentSrc,
+ width: image.naturalWidth,
+ height: image.naturalHeight,
+ })),
+ canvasPixelsVerified: canvasRequired,
+ };
+ })();
+ },
+ { canvasRequired: canvas, imageRequired: requireImage, allImagesSelector },
+ { timeout: Math.max(1, deadline - Date.now()) }
+ );
+ try {
+ const media = await result.jsonValue();
+ if (media) {
+ return media;
+ }
+ } finally {
+ await result.dispose();
+ }
+ }
+ throw new Error(`Timeout ${timeout}ms exceeded waiting for rendered media.`);
+};
+
+export const assertRetirement = (samples, bounds) => {
+ for (const [key, maximum] of Object.entries(bounds)) {
+ if (samples.some((sample) => sample[key] > maximum)) {
+ throw new Error(`Retained ${key} exceeded ${maximum}: ${samples.map((sample) => sample[key]).join(', ')}`);
+ }
+ if (samples.length >= 4 && samples.every((sample, index) => index === 0 || sample[key] > samples[index - 1][key])) {
+ throw new Error(`Monotonic retained ${key} growth: ${samples.map((sample) => sample[key]).join(', ')}`);
+ }
+ }
+};
+
+export const distribution = (values) => {
+ const sorted = [...values].sort((a, b) => a - b);
+ return {
+ count: sorted.length,
+ min: sorted[0] ?? 0,
+ median: sorted[Math.floor(sorted.length / 2)] ?? 0,
+ p95: sorted[Math.max(0, Math.ceil(sorted.length * 0.95) - 1)] ?? 0,
+ max: sorted.at(-1) ?? 0,
+ };
+};
+
+/** Warm one quick-settings popover, then six complete open/interact/close cycles. Portals must retire each time. */
+export const runSustainedWorkload = async (page) => {
+ const gear = page.getByRole('button', { exact: true, name: 'Gallery settings' });
+ const requests = [];
+ const onRequest = (request) => requests.push(request.url());
+ page.on('request', onRequest);
+ const samples = [];
+ let currentCycle;
+ const ownedPopoverIds = [];
+ const longTaskStart = await page.evaluate(() => window.__architectureLongTasks?.length ?? 0);
+ try {
+ for (let cycle = 0; cycle < 7; cycle += 1) {
+ const start = performance.now();
+ await gear.click();
+ await page.getByRole('slider', { exact: true, name: 'Image size' }).waitFor();
+ const popupId = await page
+ .getByRole('slider', { exact: true, name: 'Image size' })
+ .evaluate((element) => element.closest('[data-scope="popover"][data-part="content"]').id);
+ if (!popupId) {
+ throw new Error('Quick settings popover has no identity.');
+ }
+ if (!ownedPopoverIds.includes(popupId)) {
+ ownedPopoverIds.push(popupId);
+ }
+ await page.getByRole('slider', { exact: true, name: 'Image size' }).focus();
+ await page.keyboard.press(cycle % 2 ? 'ArrowLeft' : 'ArrowRight');
+ // Chakra presence waits for native animationend; animation.finished can resolve before that owner transition.
+ const exitState = await page.evaluateHandle((id) => {
+ const state = { completed: false };
+ const content = document.getElementById(id);
+ const onExit = () => {
+ state.completed = true;
+ };
+ content.addEventListener('exitcomplete', onExit, { once: true });
+ state.cleanup = () => content.removeEventListener('exitcomplete', onExit);
+ return state;
+ }, popupId);
+ currentCycle = { cycle, popoverId: popupId, phase: 'waiting-for-exit' };
+ try {
+ await page.keyboard.press('Escape');
+ await page.waitForFunction((state) => state.completed, exitState, { timeout: 5000 });
+ } finally {
+ // A retired document can invalidate handles; cleanup must preserve the original journey failure.
+ await exitState.evaluate((state) => state.cleanup()).catch(() => {});
+ await exitState.dispose().catch(() => {});
+ }
+ // Presence completes before React's removal commit; allow a short grace, then report actual retained DOM.
+ const retained = await page.evaluate(async (ids) => {
+ const deadline = performance.now() + 250;
+ while (ids.some((id) => document.getElementById(id))) {
+ const remaining = deadline - performance.now();
+ if (remaining <= 0) {
+ break;
+ }
+ await new Promise((resolve) => {
+ setTimeout(resolve, Math.min(16, remaining));
+ });
+ }
+ return {
+ domNodes: document.querySelectorAll('*').length,
+ popovers: ids.filter((id) => document.getElementById(id)).length,
+ canvases: document.querySelectorAll('canvas').length,
+ };
+ }, ownedPopoverIds);
+ currentCycle = {
+ ...retained,
+ cycle,
+ popoverId: popupId,
+ latencyMs: performance.now() - start,
+ requests: requests.length,
+ };
+ assertRetirement([currentCycle], { popovers: 0 });
+ if (cycle > 0) {
+ samples.push(currentCycle);
+ }
+ }
+ assertRetirement(samples, { popovers: 0 });
+ return {
+ workload: 'gallery-quick-settings',
+ warmups: 1,
+ cycles: 6,
+ samples,
+ interactionMs: distribution(samples.map((sample) => sample.latencyMs)),
+ longTasksMs: distribution(
+ await page.evaluate((start) => (window.__architectureLongTasks ?? []).slice(start), longTaskStart)
+ ),
+ timingEnforced: false,
+ };
+ } catch (error) {
+ error.sustained = { workload: 'gallery-quick-settings', samples, failedCycle: currentCycle };
+ throw error;
+ } finally {
+ page.off('request', onRequest);
+ }
+};
diff --git a/invokeai/frontend/webv2/scripts/browser-validation.test.mjs b/invokeai/frontend/webv2/scripts/browser-validation.test.mjs
new file mode 100644
index 0000000000..dc0401d8a0
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/browser-validation.test.mjs
@@ -0,0 +1,325 @@
+import assert from 'node:assert/strict';
+import { EventEmitter } from 'node:events';
+import test from 'node:test';
+import { crc32, inflateSync } from 'node:zlib';
+
+import {
+ isExpectedDocumentUnload,
+ isQueueReadRequest,
+ isExpectedGalleryProjectSwitchAbort,
+} from './browser-smoke-expectations.mjs';
+import {
+ assertRetirement,
+ distribution,
+ observeBrowserDiagnostics,
+ withBrowserNavigation,
+} from './browser-validation.mjs';
+import { createMockBackendFixture } from './mock-backend-fixtures.mjs';
+import { startMockBackend } from './mock-backend.mjs';
+import { fixturePng, mediaDimensions } from './mock-media.mjs';
+
+const decodePng = (bytes, width, height) => {
+ assert.equal(bytes.subarray(0, 8).toString('hex'), '89504e470d0a1a0a');
+ const idat = [];
+ for (let offset = 8; offset < bytes.length;) {
+ const size = bytes.readUInt32BE(offset);
+ const type = bytes.toString('ascii', offset + 4, offset + 8);
+ const data = bytes.subarray(offset + 8, offset + 8 + size);
+ assert.equal(
+ bytes.readUInt32BE(offset + 8 + size),
+ crc32(bytes.subarray(offset + 4, offset + 8 + size)),
+ `${type} CRC`
+ );
+ if (type === 'IHDR') {
+ assert.equal(data.readUInt32BE(0), width);
+ assert.equal(data.readUInt32BE(4), height);
+ assert.equal(data[8], 8);
+ assert.equal(data[9], 2);
+ }
+ if (type === 'IDAT') {
+ idat.push(data);
+ }
+ offset += size + 12;
+ }
+ const pixels = inflateSync(Buffer.concat(idat));
+ assert.equal(pixels.length, (width * 3 + 1) * height);
+ assert.deepEqual([...pixels.subarray(0, 4)], [0, 64, 160, 128]);
+ for (let y = 0; y < height; y += 1) {
+ assert.equal(pixels[y * (width * 3 + 1)], 0);
+ }
+};
+
+test('seeded media routes carry decodable PNG pixels at metadata and aspect-preserving thumbnail dimensions', async () => {
+ const fixture = createMockBackendFixture('representative');
+ const backend = await startMockBackend(0, { profile: 'representative' });
+ try {
+ // Every distinct seeded dimension, rather than downloading 1000 identical-size fixtures.
+ const dimensions = new Map(fixture.images.map((image) => [`${image.width}x${image.height}`, image]));
+ const thumbnails = {
+ '512x512': [256, 256],
+ '576x576': [256, 256],
+ '640x640': [256, 256],
+ '704x512': [256, 186],
+ '512x576': [228, 256],
+ '576x640': [230, 256],
+ '640x512': [256, 205],
+ '704x576': [256, 209],
+ '512x640': [205, 256],
+ '576x512': [256, 228],
+ '640x576': [256, 230],
+ '704x640': [256, 233],
+ };
+ for (const image of dimensions.values()) {
+ for (const variant of ['full', 'thumbnail']) {
+ const response = await fetch(`${backend.origin}/api/v1/images/i/${image.image_name}/${variant}`);
+ assert.equal(response.status, 200);
+ assert.equal(response.headers.get('content-type'), 'image/png');
+ const [width, height] =
+ variant === 'thumbnail' ? thumbnails[`${image.width}x${image.height}`] : [image.width, image.height];
+ decodePng(Buffer.from(await response.arrayBuffer()), width, height);
+ }
+ }
+ decodePng(fixturePng(4096, 4096), 4096, 4096);
+ const corrupt = Buffer.from(fixturePng(64, 64));
+ corrupt[45] ^= 1;
+ assert.throws(() => decodePng(corrupt, 64, 64), /CRC/);
+ assert.throws(() => fixturePng(8192, 1), /dimensions/);
+ assert.deepEqual(mediaDimensions({ width: 832, height: 480 }, true), { width: 256, height: 148 });
+ } finally {
+ await backend.close();
+ }
+});
+
+test('nominal diagnostics attribute only the mock socket 404 and reject failed media, HTTP and runtime errors', async () => {
+ const page = new EventEmitter();
+ const diagnostics = await observeBrowserDiagnostics(page);
+ const response = (url, status) => ({ url: () => url, status: () => status });
+ page.emit('response', response('http://localhost/ws/socket.io/?transport=polling', 404));
+ await diagnostics.assertHealthy();
+ page.emit('response', response('http://localhost/api/v1/images/i/bad/full', 500));
+ page.emit('requestfailed', {
+ url: () => 'http://localhost/assets/app.js',
+ failure: () => ({ errorText: 'connection refused' }),
+ });
+ page.emit('pageerror', new Error('raster failed'));
+ page.emit('console', {
+ type: () => 'error',
+ location: () => ({ url: 'http://localhost/app.js' }),
+ text: () => 'decode failed',
+ });
+ assert.equal(diagnostics.errors.length, 4);
+ assert.equal(diagnostics.media.length, 1);
+ await assert.rejects(() => diagnostics.assertHealthy(), /decode failed/);
+});
+
+test('retirement checks detect induced retained portals and sustained growth while allowing a stable plateau', () => {
+ assertRetirement([{ portals: 0 }, { portals: 0 }], { portals: 0 });
+ assert.throws(() => assertRetirement([{ portals: 0 }, { portals: 1 }], { portals: 0 }), /Retained portals/);
+ assert.throws(
+ () =>
+ assertRetirement(
+ [1, 2, 3, 4].map((portals) => ({ portals })),
+ { portals: 10 }
+ ),
+ /Monotonic/
+ );
+ assert.deepEqual(distribution([4, 1, 3, 2]), { count: 4, min: 1, median: 3, p95: 4, max: 4 });
+});
+
+test('diagnostics await Error argument extraction when Firefox console text loses the error message', async () => {
+ const page = new EventEmitter();
+ const diagnostics = await observeBrowserDiagnostics(page);
+ let release;
+ const available = new Promise((resolve) => {
+ release = resolve;
+ });
+ page.emit('console', {
+ type: () => 'error',
+ location: () => ({ url: 'http://localhost/assets/vendor.js' }),
+ text: () => 'Error',
+ args: () => [
+ {
+ evaluate: async (extract) => {
+ await available;
+ return extract(new Error('authentication unavailable'));
+ },
+ },
+ ],
+ });
+ const assertion = assert.rejects(() => diagnostics.assertHealthy(), /authentication unavailable/);
+ release();
+ await assertion;
+ assert.equal(diagnostics.errors[0].arguments[0].name, 'Error');
+});
+
+test('document teardown is same-origin and active only; real failures and live mutations stay critical', async () => {
+ const phase = { navigating: true, origin: 'http://localhost:4180' };
+ const canceled = {
+ kind: 'requestfailed',
+ method: 'PUT',
+ url: `${phase.origin}/api/v1/projects/p/workspace`,
+ message: 'net::ERR_ABORTED',
+ };
+ const native = {
+ kind: 'pageerror',
+ message: `Fetch API cannot load ${phase.origin}/api/v1/new-read due to access control checks.`,
+ };
+ assert.equal(isExpectedDocumentUnload(canceled, phase), true);
+ assert.equal(isExpectedDocumentUnload(native, phase), true);
+ for (const event of [
+ { ...canceled, message: 'connection refused' },
+ { ...canceled, responseStatus: 500 },
+ { ...canceled, kind: 'response', status: 500 },
+ { ...canceled, url: 'http://foreign/api/v1/projects/p/workspace' },
+ { ...canceled, url: `${phase.origin}/assets/app.js` },
+ { ...native, kind: 'console' },
+ { ...native, message: 'Unexpected runtime error' },
+ ]) {
+ assert.equal(isExpectedDocumentUnload(event, phase), false);
+ }
+ assert.equal(isExpectedDocumentUnload(canceled, { ...phase, navigating: false }), false);
+ assert.equal(isExpectedDocumentUnload(native, { ...phase, navigating: false }), false);
+ const page = new EventEmitter();
+ const diagnostics = await observeBrowserDiagnostics(page, {
+ expected: (event) => isExpectedDocumentUnload(event, phase),
+ });
+ page.emit('pageerror', { message: native.message, stack: native.message });
+ await diagnostics.assertHealthy();
+ page.emit('response', { url: () => canceled.url, status: () => 500 });
+ await assert.rejects(() => diagnostics.assertHealthy(), /500/);
+});
+
+test('socket polling teardown excludes websocket, cross-origin and live-page failures', async () => {
+ const phase = { navigating: true, origin: 'http://localhost:4180' };
+ const pollingUrl = `${phase.origin}/ws/socket.io/?EIO=4&transport=polling&t=1`;
+ const canceled = { kind: 'requestfailed', method: 'GET', url: pollingUrl, message: 'net::ERR_ABORTED' };
+ const native = {
+ kind: 'pageerror',
+ message: `XMLHttpRequest cannot load ${pollingUrl} due to access control checks.`,
+ };
+ for (const event of [canceled, native]) {
+ assert.equal(isExpectedDocumentUnload(event, phase), true);
+ assert.equal(isExpectedDocumentUnload(event, { ...phase, navigating: false }), false);
+ }
+ for (const url of [pollingUrl.replace('polling', 'websocket'), pollingUrl.replace('localhost', 'foreign')]) {
+ assert.equal(isExpectedDocumentUnload({ ...canceled, url }, phase), false);
+ assert.equal(
+ isExpectedDocumentUnload({ ...native, message: native.message.replace(pollingUrl, url) }, phase),
+ false
+ );
+ }
+ const page = new EventEmitter();
+ const diagnostics = await observeBrowserDiagnostics(page, {
+ expected: (event) => isExpectedDocumentUnload(event, phase),
+ });
+ const request = { url: () => pollingUrl, method: () => 'GET', failure: () => ({ errorText: canceled.message }) };
+ page.emit('requestfailed', request);
+ page.emit('pageerror', { message: native.message, stack: native.message });
+ await diagnostics.assertHealthy();
+ page.emit('response', { url: () => pollingUrl, status: () => 500 });
+ await assert.rejects(() => diagnostics.assertHealthy(), /500/);
+ phase.navigating = false;
+ page.emit('requestfailed', request);
+ page.emit('pageerror', { message: native.message, stack: native.message });
+ assert.equal(diagnostics.errors.length, 3, 'The HTTP failure and both live-page errors remain fatal');
+});
+
+test('Queue owner cancellation includes its read methods and excludes commands, cross-origin requests and wrong methods', () => {
+ const origin = 'http://localhost:4180';
+ for (const [operation, method] of [
+ ['status', 'GET'],
+ ['current', 'GET'],
+ ['next', 'GET'],
+ ['item_ids', 'GET'],
+ ['items_by_ids', 'POST'],
+ ]) {
+ const url = `${origin}/api/v1/queue/default/${operation}`;
+ assert.equal(isQueueReadRequest({ method, url }, origin), true);
+ assert.equal(isQueueReadRequest({ method: method === 'GET' ? 'POST' : 'GET', url }, origin), false);
+ assert.equal(isQueueReadRequest({ method, url: url.replace('localhost', 'foreign') }, origin), false);
+ }
+ assert.equal(
+ isQueueReadRequest({ method: 'POST', url: `${origin}/api/v1/queue/default/enqueue_batch` }, origin),
+ false
+ );
+ assert.equal(isQueueReadRequest({ url: `${origin}/api/v1/queue/default/unexpected` }, origin), false);
+});
+
+test('natural navigation scopes cancellation to the owned transition and retires the expectation afterwards', async () => {
+ const page = new EventEmitter();
+ page.url = () => 'http://localhost:4180/#/app';
+ const diagnostics = await observeBrowserDiagnostics(page);
+ const cancellation = () =>
+ page.emit('requestfailed', {
+ url: () => 'http://localhost:4180/api/v1/projects/p/workspace',
+ method: () => 'PUT',
+ failure: () => ({ errorText: 'net::ERR_ABORTED' }),
+ });
+ await withBrowserNavigation(page, () => {
+ cancellation();
+ });
+ await diagnostics.assertHealthy();
+ cancellation();
+ await assert.rejects(() => diagnostics.assertHealthy(), /workspace/);
+});
+
+test('Gallery project-switch cancellation is an exact same-origin read expectation, never a live-page or HTTP waiver', async () => {
+ const phase = { origin: 'http://localhost:4180' };
+ const url = `${phase.origin}/api/v1/gallery/items/?board_id=fixture-project-board-01&offset=0`;
+ const aborted = { kind: 'requestfailed', method: 'GET', url, responseStatus: 200, message: 'net::ERR_ABORTED' };
+ assert.equal(isExpectedGalleryProjectSwitchAbort(aborted, phase), true);
+ for (const event of [
+ { ...aborted, url: url.replace('localhost', 'foreign') },
+ { ...aborted, url: `${phase.origin}/api/v1/gallery/items/location` },
+ { ...aborted, url: `${phase.origin}/api/v1/gallery/items/names` },
+ { ...aborted, url: `${phase.origin}/api/v1/images/i/broken/thumbnail` },
+ { ...aborted, url: `${phase.origin}/assets/app.js` },
+ { ...aborted, method: 'POST' },
+ { ...aborted, method: 'PUT' },
+ { ...aborted, message: 'net::ERR_CONNECTION_REFUSED' },
+ { ...aborted, responseStatus: 404 },
+ { ...aborted, responseStatus: 500 },
+ { ...aborted, kind: 'response', status: 500 },
+ { ...aborted, kind: 'pageerror' },
+ ]) {
+ assert.equal(isExpectedGalleryProjectSwitchAbort(event, phase), false);
+ }
+ const page = new EventEmitter();
+ page.url = () => phase.origin;
+ const diagnostics = await observeBrowserDiagnostics(page);
+ const request = () => ({ url: () => url, method: () => 'GET', failure: () => ({ errorText: 'net::ERR_ABORTED' }) });
+ const retired = request();
+ page.emit('request', retired);
+ page.emit('response', { url: () => url, status: () => 200, request: () => retired });
+ await diagnostics.withGalleryProjectSwitch(() => {
+ const newProject = request();
+ page.emit('request', newProject);
+ page.emit('requestfailed', newProject);
+ });
+ assert.equal(diagnostics.errors.length, 1, 'A new request with the very same URL must remain fatal');
+ // The retired request's body cancellation can be delivered after the switch action has completed.
+ page.emit('requestfailed', retired);
+ assert.equal(diagnostics.errors.length, 1);
+ for (const phase of ['setup', 'first autosave', 'live project']) {
+ const live = request();
+ page.emit('request', live);
+ page.emit('requestfailed', live);
+ assert.equal(diagnostics.errors.at(-1).message, 'net::ERR_ABORTED', `${phase} reads are strict`);
+ }
+ const finished = request();
+ page.emit('request', finished);
+ await diagnostics.withGalleryProjectSwitch(() => {});
+ page.emit('requestfinished', finished);
+ page.emit('requestfailed', finished);
+ const failed = request();
+ page.emit('request', failed);
+ await diagnostics.withGalleryProjectSwitch(() => {
+ page.emit('response', { url: () => url, status: () => 500, request: () => failed });
+ page.emit('requestfailed', failed);
+ });
+ assert.equal(diagnostics.errors.length, 7, 'New, setup, autosave, live, settled and HTTP failures stay fatal');
+ await assert.rejects(
+ () => diagnostics.assertHealthy(),
+ (error) => error.message.includes('500') && error.message.includes('ERR_ABORTED')
+ );
+});
diff --git a/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs b/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs
index db8c46b325..948c51e013 100644
--- a/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs
+++ b/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs
@@ -3,6 +3,7 @@ import { dirname, resolve } from 'node:path';
import process from 'node:process';
import { chromium } from 'playwright';
+import { observeBrowserDiagnostics, waitForRenderedMedia, runSustainedWorkload } from './browser-validation.mjs';
import { startMockBackend } from './mock-backend.mjs';
import {
BROWSER_RESOURCE_METRIC_KEYS,
@@ -340,8 +341,9 @@ const runSample = async (browser, fixture, sample) => {
await context.tracing.start({ screenshots: true, snapshots: true, sources: true });
}
+ const page = await context.newPage();
+ const diagnostics = await observeBrowserDiagnostics(page);
try {
- const page = await context.newPage();
await page.addInitScript(() => {
window.__architectureLongTasks = [];
new PerformanceObserver((list) => {
@@ -492,7 +494,9 @@ const runSample = async (browser, fixture, sample) => {
response.request().method() === 'POST' && new URL(response.url()).pathname === '/api/v1/projects/',
{ timeout: 10_000 }
);
- await page.getByRole('menuitem', { exact: true, name: /new project/i }).click();
+ await diagnostics.withGalleryProjectSwitch(() =>
+ page.getByRole('menuitem', { exact: true, name: /new project/i }).click()
+ );
await page.waitForFunction(
(name) => document.querySelector('button[aria-label^="Switch project."]')?.textContent?.trim() !== name,
originalProjectName
@@ -545,7 +549,7 @@ const runSample = async (browser, fixture, sample) => {
readyMarkName: projectSwitchReadyMark,
}
);
- await originalProject.click();
+ await diagnostics.withGalleryProjectSwitch(() => originalProject.click());
await waitForSemanticMark(page, projectSwitchReadyMark);
projectSwitchMs = await page.evaluate(
({ interactionMarkName, readyMarkName }) => {
@@ -562,13 +566,43 @@ const runSample = async (browser, fixture, sample) => {
await waitForWidgetRequests(fixture, scripts);
const routeReadyMs = await waitForSemanticMark(page, fixture.readyMark);
+ const renderedMedia = await waitForRenderedMedia(page, {
+ canvas: fixture.id === 'editor-canvas' && fixture.stateProfile === 'representative',
+ requireImage: fixture.stateProfile === 'representative' && ['launchpad', 'editor-minimal'].includes(fixture.id),
+ });
const resources = await resourceCollector.settle();
const activatedResources = resources.filter((resource) => activatedResourcePaths.has(resource.path));
const timing = await getTiming(page);
const scriptSourceOwners = getScriptSourceOwners(scripts);
const layoutReturnSwitchMs = await measureLayoutReturnSwitch(page, fixture);
+ const sustained =
+ (mode === 'resources' || sample.kind === 'scored') &&
+ fixture.id === 'editor-minimal' &&
+ fixture.stateProfile === 'representative'
+ ? await runSustainedWorkload(page)
+ : null;
+ await diagnostics.assertHealthy();
+ if (sustained) {
+ await mkdir(dirname(artifactPath), { recursive: true });
+ await writeFile(
+ resolve(dirname(artifactPath), `sustained-${sample.index}.json`),
+ JSON.stringify(
+ {
+ runner: process.env.GITHUB_RUNNER_NAME ?? process.env.RUNNER_NAME ?? 'local-unconfigured',
+ platform: process.platform,
+ browser: browser.version(),
+ renderedMedia,
+ mediaRequests: diagnostics.media,
+ sustained,
+ },
+ null,
+ 2
+ )
+ );
+ }
return {
+ media: { renderedMedia, requests: diagnostics.media },
activatedResources: summarizeBrowserResources(activatedResources),
profileCounts: profile.counts,
resources: summarizeBrowserResources(resources),
@@ -583,6 +617,27 @@ const runSample = async (browser, fixture, sample) => {
},
tracePath: sample.kind === 'trace' ? tracePath : null,
};
+ } catch (error) {
+ await mkdir(dirname(artifactPath), { recursive: true });
+ const failurePath = resolve(
+ dirname(artifactPath),
+ `failure-${fixture.id}-${fixture.stateProfile}-${sample.kind}-${sample.index}`
+ );
+ await writeFile(
+ `${failurePath}.json`,
+ JSON.stringify(
+ {
+ error: String(error),
+ diagnostics: diagnostics.errors,
+ media: diagnostics.media,
+ sustained: error.sustained ?? null,
+ },
+ null,
+ 2
+ )
+ );
+ await page.screenshot({ path: `${failurePath}.png`, fullPage: true }).catch(() => {});
+ throw error;
} finally {
if (sample.kind === 'trace') {
await context.tracing.stop({ path: tracePath });
@@ -645,6 +700,7 @@ try {
}
routeReports.push({
...summarizeBrowserSamples(observedSamples, mode),
+ mediaObservations: observedSamples.map((sample) => sample.media),
id: fixture.id,
owner: fixture.owner,
readyMark: fixture.readyMark,
diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
index 5044d4c76e..0dcc3c5b02 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
@@ -2405,6 +2405,30 @@ test('wildcards are stateful: create, rename, delete one, and delete a batch of
}
});
+test('settings read routes provide usable vocabulary and dependency information', async () => {
+ const backend = await startMockBackend(0, { profile: 'representative' });
+ try {
+ const vocabulary = await fetch(`${backend.origin}/api/v1/image_map/vocab`);
+ assert.equal(vocabulary.status, 200);
+ assert.deepEqual(await vocabulary.json(), {
+ terms: ['architectural study', 'watercolor'],
+ state: 'ready',
+ error: null,
+ max_terms: 500,
+ max_term_length: 64,
+ });
+ const dependencies = await fetch(`${backend.origin}/api/v1/app/app_deps`);
+ assert.equal(dependencies.status, 200);
+ const versions = await dependencies.json();
+ assert.equal(versions.CUDA, 'N/A');
+ const version = await fetch(`${backend.origin}/api/v1/app/version`).then((response) => response.json());
+ assert.equal(versions.invokeai, version.version, 'About dependency information must identify the served app');
+ assert.ok(Object.values(versions).every((value) => typeof value === 'string'));
+ } finally {
+ await backend.close();
+ }
+});
+
test('image PATCH adopts an intermediate as hidden durable Canvas pixels on every read', async () => {
await withRepresentativeBackend(async (backend) => {
const form = new FormData();
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index e9439d4a0b..cef60939c2 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -15,6 +15,7 @@ import {
MOCK_BACKEND_FIXED_EPOCH,
MODEL_SEED_SETS,
} from './mock-backend-fixtures.mjs';
+import { fixturePng, mediaDimensions } from './mock-media.mjs';
import { createWorkingMemoryMock, WORKING_MEMORY_SCENARIOS } from './mock-working-memory.mjs';
/** The canvas schema every mock project declares; the real server keeps the same floor per record. */
@@ -62,10 +63,6 @@ const writtenRecordOf = ({ workspace, ...project }) => ({
/** In-memory test backend; no Socket.IO. POST /__reset restores the startup profile unless ?profile= overrides it. */
const FIXED_EPOCH_MS = Date.parse(MOCK_BACKEND_FIXED_EPOCH);
-const TINY_PNG = Buffer.from(
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAF/gL+XcX1WQAAAABJRU5ErkJggg==',
- 'base64'
-);
const FIXTURE_VIDEO = readFileSync(resolve(import.meta.dirname, 'mock-assets/fixture-video.mp4'));
const FIXTURE_VIDEO_POSTER = readFileSync(resolve(import.meta.dirname, 'mock-assets/fixture-video.webp'));
// Share the backend-pinned capabilities fixture to keep journey payloads aligned with the real API.
@@ -1287,13 +1284,15 @@ const writeJson = (response, status, value) => {
response.end(body);
};
-const writePng = (response) => {
+const writePng = (response, image, thumbnail) => {
+ const { width, height } = mediaDimensions(image, thumbnail);
+ const bytes = fixturePng(width, height);
response.writeHead(200, {
'cache-control': 'public, max-age=3600',
- 'content-length': TINY_PNG.length,
+ 'content-length': bytes.length,
'content-type': 'image/png',
});
- response.end(TINY_PNG);
+ response.end(bytes);
};
const writeBinary = (response, status, body, headers) => {
@@ -1581,6 +1580,16 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'empt
});
}
+ if (method === 'GET' && path === '/api/v1/image_map/vocab') {
+ return json(200, {
+ terms: ['architectural study', 'watercolor'],
+ state: 'ready',
+ error: null,
+ max_terms: 500,
+ max_term_length: 64,
+ });
+ }
+
if (method === 'POST' && path === '/api/v1/image_map/refresh') {
return json(200, { enqueued: true });
}
@@ -1589,6 +1598,10 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'empt
return json(200, { version: MOCK_APP_VERSION });
}
+ if (method === 'GET' && path === '/api/v1/app/app_deps') {
+ return json(200, { CUDA: 'N/A', invokeai: MOCK_APP_VERSION });
+ }
+
if (method === 'GET' && path === '/api/v1/app/frontend_config') {
return json(200, { show_donation_link: true });
}
@@ -3125,7 +3138,10 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'empt
if (method === 'GET' && imageAssetMatch) {
const imageName = decodeURIComponent(imageAssetMatch[1]);
- return state.images.has(imageName) ? writePng(response) : json(404, { detail: 'Image not found' });
+ const image = state.images.get(imageName);
+ return image
+ ? writePng(response, image, imageAssetMatch[2] === 'thumbnail')
+ : json(404, { detail: 'Image not found' });
}
const imageWorkflowMatch = /^\/api\/v1\/images\/i\/([^/]+)\/workflow$/.exec(path);
diff --git a/invokeai/frontend/webv2/scripts/mock-media.mjs b/invokeai/frontend/webv2/scripts/mock-media.mjs
new file mode 100644
index 0000000000..6fa5f282b3
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/mock-media.mjs
@@ -0,0 +1,58 @@
+import { crc32, deflateSync } from 'node:zlib';
+
+// PNG truecolour, filter 0. A finite palette of dimensions is shared by all seeded images.
+const cache = new Map();
+const chunk = (type, data) => {
+ const body = Buffer.concat([Buffer.from(type), data]);
+ const result = Buffer.alloc(body.length + 8);
+ result.writeUInt32BE(data.length);
+ body.copy(result, 4);
+ result.writeUInt32BE(crc32(body), result.length - 4);
+ return result;
+};
+export const mediaDimensions = ({ width, height }, thumbnail = false) => {
+ const scale = thumbnail ? Math.min(1, 256 / width, 256 / height) : 1;
+ return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
+};
+export const fixturePng = (width, height) => {
+ if (
+ !Number.isInteger(width) ||
+ !Number.isInteger(height) ||
+ width < 1 ||
+ height < 1 ||
+ width > 4096 ||
+ height > 4096
+ ) {
+ throw new Error(`Invalid fixture image dimensions: ${width}x${height}`);
+ }
+ const key = `${width}x${height}`;
+ if (cache.has(key)) {
+ return cache.get(key);
+ }
+ const header = Buffer.alloc(13);
+ header.writeUInt32BE(width);
+ header.writeUInt32BE(height, 4);
+ header[8] = 8;
+ header[9] = 2;
+ const pixels = Buffer.alloc((width * 3 + 1) * height);
+ for (let y = 0; y < height; y += 1) {
+ for (let x = 0; x < width; x += 1) {
+ const offset = y * (width * 3 + 1) + 1 + x * 3;
+ const light = (Math.floor(x / 32) + Math.floor(y / 32)) % 2 === 0;
+ pixels[offset] = light ? 64 : 192;
+ pixels[offset + 1] = light ? 160 : 80;
+ pixels[offset + 2] = 128;
+ }
+ }
+ const bytes = Buffer.concat([
+ Buffer.from('89504e470d0a1a0a', 'hex'),
+ chunk('IHDR', header),
+ chunk('IDAT', deflateSync(pixels)),
+ chunk('IEND', Buffer.alloc(0)),
+ ]);
+ // Dynamic uploads may introduce dimensions; never retain an unbounded test-server cache.
+ if (cache.size < 32) {
+ cache.set(key, bytes);
+ }
+ return bytes;
+};
diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
index 77636e9f3e..13e1f36072 100644
--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
@@ -1,11 +1,13 @@
import assert from 'node:assert/strict';
-import { mkdir, readFile } from 'node:fs/promises';
+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';
@@ -95,13 +97,15 @@ const openRepresentativePage = async (browser, path, viewport = { height: 1_000,
const page = await context.newPage();
const pageErrors = [];
const consoleErrors = [];
-
- page.on('pageerror', (error) => pageErrors.push(error));
- page.on('console', (message) => {
- if (message.type() === 'error') {
- consoleErrors.push(message.text());
- }
+ 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 };
@@ -135,6 +139,7 @@ const presetStrip = (page) => page.getByRole('tablist', { exact: true, name: 'La
const waitForWorkbench = async (page) => {
await page.getByRole('main', { exact: true, name: 'Fixture Project 001' }).waitFor();
await presetStrip(page).waitFor();
+ await waitForRenderedMedia(page);
};
/** Every built-in widget the status bar can hold, by its menu label (manifests allowing the `bottom` region). */
@@ -235,6 +240,7 @@ const surfaces = [
ready: async (page) => {
await waitForWorkbench(page);
await selectLayoutPreset(page, 'Edit', 'Canvas');
+ await waitForRenderedMedia(page, { canvas: true });
// The Layers panel's Properties pane is the canvas's settings surface; the journey must scan it, not a fallback.
await page.getByRole('tab', { exact: true, name: 'Properties', selected: true }).waitFor();
await page.getByRole('tabpanel').getByRole('group', { exact: true, name: 'Layer' }).waitFor();
@@ -251,9 +257,10 @@ const surfaces = [
body: JSON.stringify({ set: 'control-sdxl' }),
});
assert.ok(seeded.ok, `Could not seed control models: ${String(seeded.status)}.`);
- await page.reload({ waitUntil: 'domcontentloaded' });
+ await withBrowserNavigation(page, () => page.reload({ waitUntil: 'domcontentloaded' }));
await waitForWorkbench(page);
await selectLayoutPreset(page, 'Edit', 'Canvas');
+ await waitForRenderedMedia(page, { canvas: true });
// The representative main model is SD 1.x; the seeded control models are SDXL, so switch to an SDXL main
// (Fixture Model 006) through the Generate panel's model picker.
await page.getByText('Fixture Model 001', { exact: true }).click();
@@ -383,6 +390,7 @@ const runShortcutGuideJourney = async (browser) => {
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: 'View' });
@@ -613,10 +621,10 @@ const runResponsiveTopbarJourney = async (browser) => {
try {
await waitForWorkbench(page);
- // The representative queue is populated; measure the hydrated counter rather than its transient idle state.
+ // The representative fixture has exactly 167 pending outputs; connection state may change its label.
await page
.locator('header')
- .getByRole('button', { name: /^[1-9]\d* (images? remaining|items? waiting for the connection)\. Open queue$/ })
+ .getByRole('button', { name: /^167 (?:images remaining|items waiting for the connection)\. Open queue$/ })
.waitFor();
for (const width of [1_024, 900]) {
@@ -1129,6 +1137,7 @@ const runKeepAliveStateJourney = async (browser) => {
await waitForSettledDocument(page);
await selectLayoutPreset(page, 'Edit', 'Canvas');
+ await waitForRenderedMedia(page, { canvas: true });
const zoomTrigger = page.getByRole('button', { name: /^Zoom \d+%$/ });
await zoomTrigger.click();
@@ -1140,6 +1149,7 @@ const runKeepAliveStateJourney = async (browser) => {
await selectLayoutPreset(page, 'Workflow', 'Workflow');
await waitForSettledDocument(page);
await selectLayoutPreset(page, 'Edit', 'Canvas');
+ await waitForRenderedMedia(page, { canvas: true });
await waitForSettledDocument(page);
assert.equal(
@@ -1190,6 +1200,7 @@ const runLayersPanesJourney = async (browser) => {
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();
@@ -1491,6 +1502,15 @@ const runSettingsJourney = async (browser) => {
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();
}
@@ -1884,9 +1904,14 @@ try {
}
process.stdout.write(`${JSON.stringify({ profile: 'representative', reports }, null, 2)}\n`);
} catch (error) {
- throw new Error(
- `${error instanceof Error ? (error.stack ?? error.message) : String(error)}${previewError ? `\n${previewError}` : ''}`
- );
+ 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();
diff --git a/invokeai/frontend/webv2/scripts/run-browser-smoke.mjs b/invokeai/frontend/webv2/scripts/run-browser-smoke.mjs
new file mode 100644
index 0000000000..2fde7935bc
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/run-browser-smoke.mjs
@@ -0,0 +1,560 @@
+import assert from 'node:assert/strict';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import process from 'node:process';
+import { chromium, firefox, webkit } from 'playwright';
+import { expect } from 'playwright/test';
+
+import { isExpectedDocumentUnload, isQueueReadRequest } from './browser-smoke-expectations.mjs';
+import { observeBrowserDiagnostics, waitForRenderedMedia, runSustainedWorkload } from './browser-validation.mjs';
+import { fixturePng } from './mock-media.mjs';
+import { executeProjectFileJourney } from './run-project-file-journey.mjs';
+
+const artifacts = resolve(import.meta.dirname, '../artifacts/browser-smoke');
+const origin = `http://127.0.0.1:${process.env.INVOKEAI_PROJECT_FILE_PORT ?? 4180}`;
+const path = '/#/app?project=fixture-project-002';
+const sessionKey = 'invokeai:v7:webv2:editor-session';
+const lockPrefix = `${sessionKey}:`;
+await mkdir(artifacts, { recursive: true });
+const reports = [];
+for (const [engine, type] of Object.entries({ chromium, firefox, webkit })) {
+ const report = {
+ engine,
+ platform: `${process.platform}/${process.arch}`,
+ status: 'unavailable',
+ safari: 'Real Safari and Apple platforms are not verified by Playwright WebKit.',
+ };
+ try {
+ await executeProjectFileJourney({
+ dependencies: {
+ launchBrowser: async ({ timeoutMs }) => {
+ const browser = await type.launch({
+ headless: true,
+ timeout: timeoutMs,
+ ...(engine === 'chromium' ? { ignoreDefaultArgs: ['--disable-back-forward-cache'] } : {}),
+ });
+ report.version = browser.version();
+ return browser;
+ },
+ runRoundTrip: async ({ browser, contexts, backend }) => {
+ const context = await browser.newContext({
+ // PWA navigation caching would bypass the scenario-local idle HTML route and boot another editor.
+ serviceWorkers: 'block',
+ viewport: { width: 1440, height: 1000 },
+ });
+ contexts.add(context);
+ await context.tracing.start({ screenshots: true, snapshots: true, sources: true });
+ // A real same-origin document works in every engine; a manifest navigation downloads in Firefox.
+ await context.route('**/__browser-smoke-idle', (route) =>
+ route.fulfill({ contentType: 'text/html', body: '<!doctype html><title>Browser smoke idle</title>' })
+ );
+ const page = await context.newPage();
+ let navigating = false;
+ let changingEditorRoute = false;
+ const diagnostics = await observeBrowserDiagnostics(page, {
+ expected: (event) =>
+ isExpectedDocumentUnload(event, { navigating, origin }) ||
+ (event.kind === 'requestfailed' &&
+ /(?:ERR_ABORTED|NS_BINDING_ABORTED|cancelled)/i.test(event.message) &&
+ changingEditorRoute &&
+ isQueueReadRequest(event, origin)),
+ });
+ const navigate = async (action) => {
+ navigating = true;
+ try {
+ return await action();
+ } finally {
+ navigating = false;
+ }
+ };
+ await context.addInitScript((applicationOrigin) => {
+ if (location.origin !== applicationOrigin) {
+ return;
+ }
+ Object.defineProperty(Navigator.prototype, 'clipboard', { configurable: true, get: () => undefined });
+ window.addEventListener('pageshow', (event) =>
+ sessionStorage.setItem(
+ 'smoke:pageshow',
+ JSON.stringify({
+ persisted: event.persisted,
+ reasons: performance.getEntriesByType('navigation')[0]?.notRestoredReasons ?? null,
+ })
+ )
+ );
+ }, origin);
+ const prompt = page.getByRole('combobox', { exact: true, name: 'Positive prompt' });
+ const open = async () => {
+ const current = new URL(page.url());
+ const action = () => page.goto(`${origin}${path}`, { waitUntil: 'domcontentloaded' });
+ if (current.origin !== origin || current.pathname !== '/') {
+ await navigate(action);
+ } else {
+ await action();
+ }
+ await prompt.waitFor();
+ };
+ try {
+ report.status = 'failed';
+ // The legacy fixture's initial split save stages B before its PUT. Keep it in flight through unload.
+ const initialSaveStarted = page.waitForRequest(
+ (request) =>
+ request.method() === 'PUT' && new URL(request.url()).pathname.startsWith('/api/v1/projects/'),
+ { timeout: 20_000 }
+ );
+ // Setup can fail before the later await; retain its rejection without abandoning an unhandled waiter.
+ void initialSaveStarted.catch(() => {});
+ const heldPuts = [];
+ const holdSaves = (route) => {
+ if (route.request().method() !== 'PUT') {
+ return route.fallback();
+ }
+ heldPuts.push(route.request().postData());
+ return new Promise(() => {});
+ };
+ await page.route('**/api/v1/projects/**', holdSaves);
+ await open();
+ report.capabilities = await page.evaluate(() => ({
+ webLocks: Boolean(navigator.locks),
+ indexedDB: Boolean(globalThis.indexedDB),
+ }));
+ if (!report.capabilities.webLocks || !report.capabilities.indexedDB) {
+ report.status = 'unsupported';
+ throw new Error('Required Web Locks and IndexedDB must exist on localhost');
+ }
+ await waitForRenderedMedia(page);
+ await initialSaveStarted;
+ // No blur/debounce/save wait after A: the actual unload must checkpoint the held field over B.
+ let marker = `smoke held prompt ${engine}`;
+ await prompt.fill(marker);
+ await navigate(() => page.goto(`${origin}/__browser-smoke-idle`, { waitUntil: 'domcontentloaded' }));
+ const recovery = await page.evaluate(async (needle) => {
+ const result = { journal: [], drafts: [] };
+ for (const { name } of await indexedDB.databases()) {
+ const kind = name.startsWith('invokeai:v7:webv2:unload-journal')
+ ? 'journal'
+ : name.startsWith('invokeai:v7:webv2:workbench')
+ ? 'drafts'
+ : null;
+ if (!kind) {
+ continue;
+ }
+ const db = await new Promise((resolve, reject) => {
+ const request = indexedDB.open(name);
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error);
+ });
+ try {
+ const store = kind === 'journal' ? 'entries' : 'draftBodies';
+ if (!db.objectStoreNames.contains(store)) {
+ continue;
+ }
+ const records = await new Promise((resolve, reject) => {
+ const request = db.transaction(store).objectStore(store).getAll();
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error);
+ });
+ result[kind].push(
+ ...records.map((record) => ({
+ projectId: record.projectId,
+ hasMarker: record.documentJson.includes(needle),
+ }))
+ );
+ } finally {
+ db.close();
+ }
+ }
+ return result;
+ }, marker);
+ assert.ok(
+ recovery.journal.some((entry) => entry.hasMarker),
+ 'Committed journal must contain A'
+ );
+ assert.ok(
+ recovery.drafts.some((entry) => entry.projectId === 'fixture-project-002' && !entry.hasMarker),
+ 'The initial save must have staged old B'
+ );
+ assert.ok(!recovery.drafts.some((entry) => entry.hasMarker), 'Staged B must not explain A recovery');
+ assert.ok(heldPuts.length && heldPuts.every((body) => !body.includes(marker)), 'Only old B reached PUT');
+ const server = await fetch(
+ `${backend.origin}/api/v1/projects/fixture-project-002?max_canvas_schema_version=4&max_document_schema_version=4`
+ );
+ assert.ok(server.ok);
+ assert.ok(!(await server.text()).includes(marker), 'Server must not explain A recovery');
+ report.journalAttribution = recovery;
+ await page.unroute('**/api/v1/projects/**', holdSaves);
+ await open();
+ await expect(prompt, 'Journal-only held field must survive actual unload').toHaveValue(marker);
+ report.heldFieldRecovery = 'passed';
+ // Canvas and layer thumbnails must contain fixture colour, in all three engines.
+ await page
+ .getByRole('tablist', { exact: true, name: 'Layout preset' })
+ .getByRole('tab', { name: /^Edit(, unsaved changes)?$/ })
+ .click();
+ await waitForRenderedMedia(page, { canvas: true });
+ report.canvasPainting = 'passed';
+ await page
+ .getByRole('tablist', { exact: true, name: 'Layout preset' })
+ .getByRole('tab', { name: /^Compose(, unsaved changes)?$/ })
+ .click();
+ // Hold native exit delivery after the browser finishes its animation: presence still owns the popup.
+ await page.getByRole('button', { exact: true, name: 'Gallery settings' }).evaluate((trigger) => {
+ const removeChild = Node.prototype.removeChild;
+ const delayedRemoval = { deferred: false, removed: false };
+ let galleryContent;
+ let pendingRemoval;
+ window.__delayedPopoverRemoval = delayedRemoval;
+ window.__restorePopoverRemoval = () => {
+ Node.prototype.removeChild = removeChild;
+ if (pendingRemoval) {
+ clearTimeout(pendingRemoval.timer);
+ pendingRemoval.finish();
+ }
+ };
+ Node.prototype.removeChild = function (child) {
+ if (galleryContent && child.contains(galleryContent)) {
+ Node.prototype.removeChild = removeChild;
+ delayedRemoval.deferred = true;
+ const parent = this;
+ const finish = () => {
+ if (child.parentNode === parent) {
+ removeChild.call(parent, child);
+ }
+ delayedRemoval.removed = !child.isConnected;
+ pendingRemoval = null;
+ };
+ pendingRemoval = { finish, timer: setTimeout(finish, 100) };
+ return child;
+ }
+ return removeChild.call(this, child);
+ };
+ window.__heldPopoverEnds = [];
+ window.__holdPopoverEnd = (event) => {
+ if (
+ event.target.id === trigger.getAttribute('aria-controls') &&
+ event.target.matches?.('[data-scope="popover"][data-part="content"][data-state="closed"]')
+ ) {
+ galleryContent = event.target;
+ event.stopImmediatePropagation();
+ window.__heldPopoverEnds.push({
+ target: event.target,
+ animationName: event.animationName,
+ elapsedTime: event.elapsedTime,
+ });
+ }
+ };
+ document.addEventListener('animationend', window.__holdPopoverEnd, true);
+ });
+ let workloadSettled = false;
+ const workload = runSustainedWorkload(page);
+ void workload.then(
+ () => {
+ workloadSettled = true;
+ },
+ () => {
+ workloadSettled = true;
+ }
+ );
+ try {
+ try {
+ await Promise.race([
+ workload,
+ page.waitForFunction(() => window.__heldPopoverEnds.length > 0, null, { timeout: 10_000 }),
+ ]);
+ // Keep the owner event withheld across rendering turns, beyond the old animation-snapshot sampler.
+ await page.evaluate(async () => {
+ for (let frame = 0; frame < 4; frame += 1) {
+ await new Promise((resolve) => {
+ requestAnimationFrame(resolve);
+ });
+ }
+ });
+ assert.equal(workloadSettled, false, 'Retirement must wait for the owner exit event');
+ } finally {
+ await page
+ .evaluate(() => {
+ document.removeEventListener('animationend', window.__holdPopoverEnd, true);
+ for (const { target, animationName, elapsedTime } of window.__heldPopoverEnds) {
+ target.dispatchEvent(
+ new AnimationEvent('animationend', { animationName, elapsedTime, bubbles: true })
+ );
+ }
+ delete window.__heldPopoverEnds;
+ delete window.__holdPopoverEnd;
+ })
+ .catch(() => {});
+ }
+ report.sustained = await workload;
+ assert.ok(
+ await page.evaluate(
+ () => window.__delayedPopoverRemoval.deferred && window.__delayedPopoverRemoval.removed
+ ),
+ 'The actual owner removal must cross the grace period'
+ );
+ report.delayedRemovalProbe = 'passed';
+ } finally {
+ await page
+ .evaluate(() => {
+ window.__restorePopoverRemoval();
+ delete window.__restorePopoverRemoval;
+ delete window.__delayedPopoverRemoval;
+ })
+ .catch(() => {});
+ }
+ report.delayedExitProbe = 'passed';
+ // Inject retained owner DOM into the real collector/runner, rather than fabricated counts.
+ await page.evaluate(() => {
+ window.__retentionProbe = new MutationObserver((records) => {
+ for (const record of records) {
+ for (const node of record.removedNodes) {
+ if (!(node instanceof HTMLElement)) {
+ continue;
+ }
+ const popup = node.matches('[data-scope="popover"][data-part="content"]')
+ ? node
+ : node.querySelector('[data-scope="popover"][data-part="content"]');
+ if (popup?.id) {
+ const retained = popup.cloneNode(true);
+ retained.hidden = true;
+ retained.dataset.retentionProbe = 'true';
+ document.body.append(retained);
+ }
+ }
+ }
+ });
+ window.__retentionProbe.observe(document.body, { childList: true, subtree: true });
+ });
+ await assert.rejects(() => runSustainedWorkload(page), /Retained popovers/);
+ await page.evaluate(() => {
+ window.__retentionProbe.disconnect();
+ document.querySelectorAll('[data-retention-probe]').forEach((node) => node.remove());
+ });
+ report.retentionFaultProbe = 'passed';
+ const firstSession = await page.evaluate((key) => sessionStorage.getItem(key), sessionKey);
+ assert.ok(firstSession);
+ // A duplicated tab starts with the same persisted identity; actual product code must take a new lock.
+ const competitor = await context.newPage();
+ const competingDiagnostics = await observeBrowserDiagnostics(competitor);
+ await competitor.goto(`${origin}/__browser-smoke-idle`);
+ await competitor.evaluate(({ key, value }) => sessionStorage.setItem(key, value), {
+ key: sessionKey,
+ value: firstSession,
+ });
+ await competitor.goto(`${origin}${path}`);
+ await competitor.getByRole('combobox', { exact: true, name: 'Positive prompt' }).waitFor();
+ const secondSession = await competitor.evaluate((key) => sessionStorage.getItem(key), sessionKey);
+ assert.notEqual(secondSession, firstSession, 'Competing editor must not steal a live editor session');
+ const held = await competitor.evaluate(async () =>
+ (await navigator.locks.query()).held.map((lock) => lock.name)
+ );
+ assert.ok(held.includes(`${lockPrefix}${firstSession}`));
+ assert.ok(held.includes(`${lockPrefix}${secondSession}`));
+ await competingDiagnostics.assertHealthy();
+ await competitor.close();
+ await page.waitForFunction(
+ async (name) => !(await navigator.locks.query()).held.some((lock) => lock.name === name),
+ `${lockPrefix}${secondSession}`
+ );
+ report.competingTabs = 'passed';
+ marker = `smoke route exit ${engine}`;
+ await prompt.fill(marker);
+ changingEditorRoute = true;
+ try {
+ await page.getByRole('button', { exact: true, name: 'Open menu' }).click();
+ await page.getByRole('menuitem', { exact: true, name: 'Launchpad' }).click();
+ await page.waitForURL(/#\/$/);
+ // Cards appear after the library and cover index load; finish even below-fold cover reads before leaving.
+ await page.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();
+ await page.getByRole('link', { exact: true, name: 'Open Fixture Project 001' }).waitFor();
+ await waitForRenderedMedia(page, { allImagesSelector: 'main img' });
+ await open();
+ await expect(prompt, 'Route exit/re-entry must keep the edit').toHaveValue(marker);
+ await prompt.focus();
+ await page.keyboard.press('Tab');
+ assert.equal(
+ await prompt.evaluate(
+ (element) => document.activeElement !== element && document.activeElement !== document.body
+ ),
+ true,
+ 'Keyboard focus must advance to a control'
+ );
+ report.routeAndFocus = 'passed';
+ } finally {
+ changingEditorRoute = false;
+ }
+ // Clipboard capability is absent rather than permission-denied: product copy controls must explain it.
+ changingEditorRoute = true;
+ try {
+ await page.goto(`${origin}/#/nodes`);
+ } finally {
+ changingEditorRoute = false;
+ }
+ const copy = page.getByRole('button', { exact: true, name: 'Copy path' });
+ await copy.waitFor();
+ assert.equal(await copy.getAttribute('aria-disabled'), 'true');
+ await copy.hover();
+ await page.getByRole('tooltip').filter({ hasText: 'Copying needs HTTPS or localhost' }).waitFor();
+ report.clipboardUnavailable = 'passed';
+ await open();
+ marker = `smoke dirty history ${engine}`;
+ await prompt.fill(marker);
+ await navigate(() => page.goto(`${origin}/__browser-smoke-idle`));
+ await navigate(() => page.goBack({ waitUntil: 'domcontentloaded' }));
+ await prompt.waitFor();
+ await expect(prompt, 'History restoration must keep the edit').toHaveValue(marker);
+ report.bfcache = await page.evaluate(() => JSON.parse(sessionStorage.getItem('smoke:pageshow')));
+ report.bfcache.reason = report.bfcache.persisted
+ ? 'Actual BFCache restoration tested'
+ : (report.bfcache.reasons ??
+ 'Engine did not enter BFCache; detailed eligibility API unavailable. History reload tested.');
+ if (report.bfcache.persisted) {
+ marker = `smoke restored edit ${engine}`;
+ await prompt.fill(marker);
+ await navigate(() => page.reload({ waitUntil: 'domcontentloaded' }));
+ await prompt.waitFor();
+ await expect(prompt, 'Restored editor must still save held edits').toHaveValue(marker);
+ }
+ // Fault probes use their own document and diagnostics: nominal application errors never get waived.
+ const probe = await context.newPage();
+ await probe.goto(`${origin}/__browser-smoke-idle`);
+ const faultDiagnostics = await observeBrowserDiagnostics(probe);
+ await probe.route('**/valid-media-probe', (route) =>
+ route.fulfill({ contentType: 'image/png', body: fixturePng(4096, 4096) })
+ );
+ await probe.setContent(
+ `<img alt="Large fixture" style="width:64px;height:64px" src="${origin}/valid-media-probe">`
+ );
+ const decoded = await waitForRenderedMedia(probe, { requireImage: true });
+ assert.equal(decoded.images[0].width, 4096);
+ assert.equal(decoded.images[0].height, 4096);
+ report.largeMediaDecode = 'passed';
+ // Cover readiness includes below-fold owners and bounds a decode that never settles.
+ const smallCover = `data:image/png;base64,${fixturePng(32, 48).toString('base64')}`;
+ const changedCover = `data:image/png;base64,${fixturePng(48, 32).toString('base64')}`;
+ await probe.setContent(
+ `<main><img id="cover" src="${smallCover}"><img id="below-fold" style="margin-top:200vh" src="${smallCover}"></main>`
+ );
+ await probe.evaluate(() => {
+ document.querySelector('#below-fold').decode = () => new Promise(() => {});
+ });
+ await assert.rejects(
+ () => waitForRenderedMedia(probe, { allImagesSelector: 'main img', timeout: 250 }),
+ /Timeout/
+ );
+ await probe.evaluate(() => {
+ delete document.querySelector('#below-fold').decode;
+ });
+ assert.equal((await waitForRenderedMedia(probe, { allImagesSelector: 'main img' })).images.length, 2);
+ report.boundedCoverDecode = 'passed';
+ // Trigger the browser's native decode interruption by changing its source while decode is pending.
+ await probe.evaluate((source) => {
+ const image = document.querySelector('#cover');
+ const decode = image.decode.bind(image);
+ let changed = false;
+ image.decode = () => {
+ const decoded = decode();
+ if (!changed) {
+ changed = true;
+ image.src = source;
+ }
+ return decoded;
+ };
+ }, changedCover);
+ const changed = await waitForRenderedMedia(probe, { allImagesSelector: 'main img' });
+ assert.equal(changed.images[0].width, 48);
+ assert.equal(changed.images[0].height, 32);
+ report.changingCoverDecode = 'passed';
+
+ await probe.route('**/critical-probe', (route) => route.abort('failed'));
+ const failedRequest = probe.waitForEvent('requestfailed');
+ await probe.evaluate(() => fetch('/critical-probe').catch(() => {}));
+ await failedRequest;
+ const runtimeError = probe.waitForEvent('pageerror');
+ await probe.evaluate(() =>
+ setTimeout(() => {
+ throw new Error('intentional runtime probe');
+ }, 0)
+ );
+ await runtimeError;
+ await probe.setContent('<img alt="Corrupt probe" src="data:image/png;base64,aW52YWxpZA==">');
+ await assert.rejects(() => waitForRenderedMedia(probe, { requireImage: true }), /decode/);
+ await assert.rejects(
+ () => faultDiagnostics.assertHealthy(),
+ (error) =>
+ error.message.includes('critical-probe') && error.message.includes('intentional runtime probe'),
+ 'The validator must reject both the critical request and the runtime failure'
+ );
+ // Removed-on-error media and checker-only thumbnails are false-green regressions.
+ await probe.route('**/removed-media-probe', (route) =>
+ route.fulfill({
+ contentType: 'text/html',
+ body: '<img onerror="this.remove()" alt="Removed corrupt" src="data:image/png;base64,aW52YWxpZA==">',
+ })
+ );
+ await probe.goto(`${origin}/removed-media-probe`);
+ await assert.rejects(() => waitForRenderedMedia(probe, { timeout: 1000 }), /decode/);
+ await probe.goto(`${origin}/__browser-smoke-idle`);
+ await assert.rejects(() => waitForRenderedMedia(probe, { timeout: 250 }), /Timeout/);
+ await probe.setContent(
+ '<div data-hotkey-widget-type-id="canvas"><canvas width="16" height="16"></canvas></div><div data-hotkey-widget-type-id="layers"><canvas aria-label="Overview" width="16" height="16"></canvas><div data-layer-row-id="probe-row"><canvas width="16" height="16"></canvas></div></div>'
+ );
+ await probe.evaluate(() => {
+ const [surface, overview, layer] = document.querySelectorAll('canvas');
+ for (const painted of [surface, overview]) {
+ painted.getContext('2d').fillStyle = 'rgb(64, 160, 128)';
+ painted.getContext('2d').fillRect(0, 0, 16, 16);
+ }
+ layer.getContext('2d').fillStyle = '#ccc';
+ layer.getContext('2d').fillRect(0, 0, 16, 16);
+ });
+ await assert.rejects(
+ () => waitForRenderedMedia(probe, { canvas: true, requireImage: false, timeout: 250 }),
+ /Timeout/
+ );
+ await probe.evaluate(() => (document.querySelector('[data-layer-row-id="probe-row"] canvas').width = 16));
+ await assert.rejects(
+ () => waitForRenderedMedia(probe, { canvas: true, requireImage: false, timeout: 250 }),
+ /Timeout/
+ );
+ await probe.evaluate(() => {
+ const layer = document.querySelector('[data-layer-row-id="probe-row"] canvas');
+ layer.getContext('2d').fillStyle = 'rgb(64, 160, 128)';
+ layer.getContext('2d').fillRect(0, 0, 16, 16);
+ });
+ await waitForRenderedMedia(probe, { canvas: true, requireImage: false });
+ await probe.evaluate(
+ () => (document.querySelector('[data-hotkey-widget-type-id="canvas"] canvas').width = 16)
+ );
+ await assert.rejects(
+ () => waitForRenderedMedia(probe, { canvas: true, requireImage: false, timeout: 250 }),
+ /Timeout/
+ );
+ await probe.close();
+ report.validationFaultProbes = 'passed';
+ await diagnostics.assertHealthy();
+ assert.equal(report.heldFieldRecovery, 'passed', report.heldFieldRecoveryError);
+ report.status = 'passed';
+ } catch (error) {
+ await page
+ .screenshot({ path: resolve(artifacts, `${engine}-failure.png`), fullPage: true })
+ .catch(() => {});
+ report.diagnostics = diagnostics.errors;
+ report.sustained = error.sustained ?? report.sustained;
+ throw error;
+ } finally {
+ await context.tracing.stop({ path: resolve(artifacts, `${engine}.zip`) });
+ await context.close();
+ contexts.delete(context);
+ }
+ },
+ },
+ });
+ } catch (error) {
+ report.error = error.stack ?? String(error);
+ }
+ reports.push(report);
+ await writeFile(resolve(artifacts, 'report.json'), `${JSON.stringify(reports, null, 2)}\n`);
+}
+process.stdout.write(`${JSON.stringify(reports, null, 2)}\n`);
+if (reports.some((report) => report.status !== 'passed')) {
+ process.exitCode = 1;
+}
diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs
index 2cc00a07b8..96940da55c 100644
--- a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs
+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs
@@ -8,6 +8,7 @@ import process from 'node:process';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
+import { observeBrowserDiagnostics, waitForRenderedMedia, withBrowserNavigation } from './browser-validation.mjs';
import {
collectCanvasLeaves,
MOCK_BACKEND_PROFILE_COUNTS,
@@ -79,36 +80,23 @@ const waitForPreview = async (getPreviewExit) => {
throw new Error(`Vite preview did not become ready at ${origin}.`);
};
-const observeBrowserErrors = (page, phase, errors) => {
- page.on('pageerror', (error) => {
- errors.push(new Error(`${phase} page error: ${error.stack ?? error.message}`));
- });
- page.on('console', (message) => {
- if (message.type() === 'error') {
- const location = message.location();
-
- // The HTTP-only mock has no Socket.IO; ignore only its expected transport 404.
- if (
- location.url.includes('/ws/socket.io/') &&
- message.text().includes('the server responded with a status of 404')
- ) {
- return;
- }
-
- // Import probes archived video names; this 404 triggers restoration.
- if (
+export const observeBrowserErrors = async (page, phase, errors) => {
+ await observeBrowserDiagnostics(page, {
+ onError: (event) => errors.push(new Error(`${phase}: ${JSON.stringify(event)}`)),
+ expected: (event) => {
+ // Import probes an archived video DTO before restoring its binary under a new identity.
+ return (
phase.endsWith('import') &&
- location.url &&
- new URL(location.url).pathname === `/api/v1/videos/i/${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}` &&
- message.text().includes('the server responded with a status of 404')
- ) {
- return;
- }
-
- const where = location.url ? ` (${location.url}:${String(location.lineNumber)})` : '';
-
- errors.push(new Error(`${phase} console error${where}: ${message.text()}`));
- }
+ event.url &&
+ new URL(event.url).pathname === `/api/v1/videos/i/${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}` &&
+ (event.status === 404 ||
+ (event.kind === 'console' && /404/.test(event.message)) ||
+ // The existence probe explicitly cancels an unread missing-response body before restoring the archive.
+ (event.kind === 'requestfailed' &&
+ [403, 404].includes(event.responseStatus) &&
+ /^(?:net::)?ERR_ABORTED$/.test(event.message)))
+ );
+ },
});
};
@@ -280,7 +268,7 @@ const importArchive = async ({ archivePath, browser, contexts, errors, phase })
contexts.add(context);
const page = await context.newPage();
- observeBrowserErrors(page, phase, errors);
+ await observeBrowserErrors(page, phase, errors);
await page.goto(`${origin}/#/`, { waitUntil: 'domcontentloaded' });
await page.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();
@@ -290,6 +278,7 @@ const importArchive = async ({ archivePath, browser, contexts, errors, phase })
await (await chooserPromise).setFiles(archivePath);
await page.waitForURL(/#\/app$/);
await page.getByRole('main', { exact: true, name: sourceProjectName }).waitFor();
+ await waitForRenderedMedia(page);
return { context, page };
};
@@ -309,7 +298,7 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectory
contexts.add(exportContext);
const exportPage = await exportContext.newPage();
- observeBrowserErrors(exportPage, 'export', errors);
+ await observeBrowserErrors(exportPage, 'export', errors);
await exportPage.goto(`${origin}${sourceProjectPath}`, { waitUntil: 'domcontentloaded' });
await exportPage.getByRole('main', { exact: true, name: sourceProjectName }).waitFor();
@@ -528,7 +517,7 @@ const runDuplication = async ({ browser, contexts, errors, imported, importedBoa
contexts.add(context);
const page = await context.newPage();
- observeBrowserErrors(page, 'duplicate', errors);
+ await observeBrowserErrors(page, 'duplicate', errors);
// Enter through Home so authentication settles before opening the library.
await page.goto(`${origin}/#/`, { waitUntil: 'domcontentloaded' });
await page.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();
@@ -624,7 +613,7 @@ const runWorkflowCollection = async ({ browser, contexts, errors, imported }) =>
contexts.add(context);
const page = await context.newPage();
- observeBrowserErrors(page, 'workflow-collection', errors);
+ await observeBrowserErrors(page, 'workflow-collection', errors);
await page.goto(`${origin}/#/`, { waitUntil: 'domcontentloaded' });
await page.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();
await page.goto(`${origin}/#/app?project=${encodeURIComponent(projectId)}`, { waitUntil: 'domcontentloaded' });
@@ -741,7 +730,7 @@ const runWorkflowCollection = async ({ browser, contexts, errors, imported }) =>
assert.equal(record.workspace.data.workflows.activeWorkflowId, record.data.workflows.entries[1].document.id);
// Restart: both workflows and the active selection come back from the server.
- await page.reload({ waitUntil: 'domcontentloaded' });
+ await withBrowserNavigation(page, () => page.reload({ waitUntil: 'domcontentloaded' }));
await page.getByRole('main', { exact: true, name: imported.name }).waitFor();
await selectLayoutPreset(page, 'Workflow', 'Workflow');
assert.equal(await currentWorkflowName(), 'Journey Saved');
@@ -801,7 +790,7 @@ const runUnloadRecovery = async ({ browser, contexts, errors, imported }) => {
const context = await browser.newContext();
contexts.add(context);
const page = await context.newPage();
- observeBrowserErrors(page, 'unload recovery', errors);
+ await observeBrowserErrors(page, 'unload recovery', errors);
const main = page.getByRole('main', { exact: true, name: imported.name });
const workflowName = page.getByRole('button', { name: /^Open this project's workflows\. Current workflow: / });
const dialog = page.getByRole('dialog', { exact: true, name: 'Workflows' });
@@ -824,7 +813,9 @@ const runUnloadRecovery = async ({ browser, contexts, errors, imported }) => {
const holdProjectSaves = (route) => (route.request().method() === 'PUT' ? new Promise(() => {}) : route.fallback());
await page.route('**/api/v1/projects/**', holdProjectSaves);
await rename('Unload navigate');
- await page.goto(`${origin}/manifest.webmanifest`, { waitUntil: 'domcontentloaded' });
+ await withBrowserNavigation(page, () =>
+ page.goto(`${origin}/manifest.webmanifest`, { waitUntil: 'domcontentloaded' })
+ );
assert.equal(await isRecoverable(page, 'Unload navigate'), true, 'browser recovery holds the rename after unload');
await page.unroute('**/api/v1/projects/**', holdProjectSaves);
await openEditor();
@@ -832,7 +823,7 @@ const runUnloadRecovery = async ({ browser, contexts, errors, imported }) => {
// Reloading the editor.
await rename('Unload reload');
- await page.reload({ waitUntil: 'domcontentloaded' });
+ await withBrowserNavigation(page, () => page.reload({ waitUntil: 'domcontentloaded' }));
await main.waitFor();
assert.equal(await currentWorkflowName(), 'Unload reload');
@@ -844,7 +835,7 @@ const runUnloadRecovery = async ({ browser, contexts, errors, imported }) => {
await page.getByRole('button', { exact: true, name: 'Open menu' }).click();
await page.getByRole('menuitem', { exact: true, name: 'Launchpad' }).click();
await page.waitForURL(/#\/$/);
- await page.reload({ waitUntil: 'domcontentloaded' });
+ await withBrowserNavigation(page, () => page.reload({ waitUntil: 'domcontentloaded' }));
await page.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();
await openEditor();
assert.equal(await currentWorkflowName(), 'Unload home');
@@ -968,7 +959,7 @@ const runSecondOrigin = async ({ browser, contexts, errors, imported, importedBo
const requests = [];
page.on('request', (request) => requests.push({ method: request.method(), url: request.url() }));
- observeBrowserErrors(page, 'second origin', errors);
+ await observeBrowserErrors(page, 'second origin', errors);
await page.goto(`${secondOrigin}/#/app?project=${encodeURIComponent(imported.project_id)}`, {
waitUntil: 'domcontentloaded',
});
@@ -1035,7 +1026,7 @@ const runPlainHttp = async ({ browser, contexts, errors }) => {
contexts.add(context);
const page = await context.newPage();
- observeBrowserErrors(page, 'plain HTTP', errors);
+ await observeBrowserErrors(page, 'plain HTTP', errors);
await page.goto(`${plainHttpOrigin}/#/projects`, { waitUntil: 'domcontentloaded' });
assert.equal(await page.evaluate(() => window.isSecureContext), false);
@@ -1065,7 +1056,7 @@ const runPlainHttp = async ({ browser, contexts, errors }) => {
// Dismissed, the notice stays dismissed on this origin.
await notice.getByRole('button', { exact: true, name: 'Dismiss' }).click();
await notice.waitFor({ state: 'detached' });
- await page.reload({ waitUntil: 'domcontentloaded' });
+ await withBrowserNavigation(page, () => page.reload({ waitUntil: 'domcontentloaded' }));
await page
.getByRole('link', { exact: true, name: `Open ${sourceProjectName}` })
.first()
diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.test.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.test.mjs
index b6e217b876..d6be3a2dee 100644
--- a/invokeai/frontend/webv2/scripts/run-project-file-journey.test.mjs
+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.test.mjs
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import test from 'node:test';
-import { executeProjectFileJourney } from './run-project-file-journey.mjs';
+import { executeProjectFileJourney, observeBrowserErrors } from './run-project-file-journey.mjs';
const delay = (durationMs) =>
new Promise((resolve) => {
@@ -166,3 +166,24 @@ test('a browser error raised during teardown prevents a success result', async (
assert.equal(events.at(-1), 'temp:remove');
});
+
+test('import waives only a missing archived video probe body cancellation after that request received its expected response', async () => {
+ const page = new EventEmitter();
+ const errors = [];
+ await observeBrowserErrors(page, 'import', errors);
+ const url = 'http://localhost/api/v1/videos/i/fixture-video-001.mp4';
+ const request = (target, errorText) => ({
+ url: () => target,
+ failure: () => ({ errorText }),
+ });
+ const missing = request(url, 'net::ERR_ABORTED');
+ page.emit('requestfailed', missing);
+ assert.equal(errors.length, 1, 'An abort without a known missing response remains critical');
+ page.emit('response', { url: () => url, status: () => 404, request: () => missing });
+ page.emit('requestfailed', missing);
+ assert.equal(errors.length, 1);
+ page.emit('requestfailed', request(url, 'net::ERR_ABORTED'));
+ page.emit('requestfailed', request(url, 'net::ERR_CONNECTION_REFUSED'));
+ page.emit('requestfailed', request(`${url}/full`, 'net::ERR_ABORTED'));
+ assert.equal(errors.length, 4, 'Another request, transport failure and media-content cancellation remain critical');
+});
diff --git a/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts b/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts
index 4e4f431a29..fc701dc75e 100644
--- a/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts
@@ -120,6 +120,7 @@ describe('architecture workflow', () => {
/scripts\/measure-architecture-performance.mjs$/,
/scripts\/run-project-file-journey.mjs$/,
/scripts\/run-accessibility-journeys.mjs$/,
+ /scripts\/run-browser-smoke.mjs$/,
];
for (const [name, commands] of [
['local release', expand('pnpm check:release')],
diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.browser.test.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.browser.test.ts
index d622f302ee..ed8db7aef6 100644
--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.browser.test.ts
@@ -1,10 +1,46 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { browserPageLifecycle } from './persistenceRuntime';
const unload = (): boolean => !window.dispatchEvent(new Event('beforeunload', { cancelable: true }));
describe('browser page lifecycle', () => {
+ it('checkpoints before pagehide without prompting, and removes every lifecycle listener on disposal', () => {
+ const checkpoints: string[] = [];
+ let signal = 'beforeunload';
+ let visibility: DocumentVisibilityState = 'visible';
+ const visibilityState = vi.spyOn(document, 'visibilityState', 'get').mockImplementation(() => visibility);
+ const unsubscribe = browserPageLifecycle.subscribeHidden(() => checkpoints.push(signal));
+ const unsubscribeUnload = browserPageLifecycle.subscribeBeforeUnload(() => {
+ checkpoints.push(signal);
+ return false;
+ });
+ try {
+ expect(unload()).toBe(false);
+ expect(checkpoints).toEqual(['beforeunload']);
+ signal = 'pagehide';
+ window.dispatchEvent(new Event('pagehide'));
+ expect(checkpoints).toEqual(['beforeunload', 'pagehide']);
+ signal = 'hidden';
+ document.dispatchEvent(new Event('visibilitychange'));
+ expect(checkpoints).toEqual(['beforeunload', 'pagehide']);
+ visibility = 'hidden';
+ document.dispatchEvent(new Event('visibilitychange'));
+ expect(checkpoints).toEqual(['beforeunload', 'pagehide', 'hidden']);
+ unsubscribe();
+ unsubscribeUnload();
+ signal = 'after disposal';
+ expect(unload()).toBe(false);
+ window.dispatchEvent(new Event('pagehide'));
+ document.dispatchEvent(new Event('visibilitychange'));
+ expect(checkpoints).toEqual(['beforeunload', 'pagehide', 'hidden']);
+ } finally {
+ unsubscribe();
+ unsubscribeUnload();
+ visibilityState.mockRestore();
+ }
+ });
+
it('cancels `beforeunload`, so the browser asks, only while the runtime says leaving would lose changes', () => {
let wouldLose = false;
const unsubscribe = browserPageLifecycle.subscribeBeforeUnload(() => wouldLose);
diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts
index 1bdd604d8d..adfce1e385 100644
--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts
@@ -153,11 +153,9 @@ const createPersistence = (load: WorkbenchPersistencePort['loadWorkbench']) => {
let pending = false;
let closedSession = false;
let unloadWouldLose = false;
- let unloadAtRisk = false;
const sessionReopenedListeners = new Set<() => void>();
const persistence: WorkbenchPersistencePort = {
hasChangesUnloadWouldLose: () => unloadWouldLose,
- isUnloadAtRisk: () => unloadAtRisk,
hasClosedSession: () => closedSession,
hasPendingChanges: () => pending,
journalBeforeUnload: vi.fn(() => ({ kind: 'nothing-to-journal' as const })),
@@ -183,10 +181,6 @@ const createPersistence = (load: WorkbenchPersistencePort['loadWorkbench']) => {
setPending(next: boolean) {
pending = next;
},
- /** Local recovery could lose an edit (a project too large for the journal is open, or storage is failing). */
- setUnloadAtRisk(next: boolean) {
- unloadAtRisk = next;
- },
/** What local recovery reports after the latest journal: an unsaved document it could not take. */
setUnloadWouldLose(next: boolean) {
unloadWouldLose = next;
@@ -1334,7 +1328,7 @@ describe('Workbench persistence runtime unload journal', () => {
return journaledNames;
};
- it('journals committed drafts before the hidden-page save, including a revision whose save is in flight', async () => {
+ it('journals held drafts before saving once across repeated unload and hidden checkpoints, including an in-flight save', async () => {
const page = createPage();
const draft = createHeldDraft();
const { aggregate, clock, persistence } = await startLoaded({ commitDrafts: draft.commit, page: page.port });
@@ -1345,10 +1339,12 @@ describe('Workbench persistence runtime unload journal', () => {
expect(journaledNames).toEqual([]);
draft.held.name = 'Typed just before hiding';
+ expect(page.beforeUnload()).toBe(false);
+ // Before unload, pagehide and becoming hidden checkpoint the same revision.
page.hide();
- // Unloading fires both `pagehide` and becoming hidden; the second has nothing new to journal.
page.hide();
expect(journaledNames).toEqual(['Typed just before hiding']);
+ expect(savedNames(persistence)).toEqual(['Typed just before hiding']);
expect(vi.mocked(persistence.journalBeforeUnload!).mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(persistence.saveWorkbench).mock.invocationCallOrder[0]!
);
@@ -1491,34 +1487,17 @@ describe('Workbench persistence runtime unload prompt', () => {
return journaledNames;
};
- it('listens for unloads only while local recovery reports a risk', async () => {
+ it('checkpoints on every unload and asks when journaling fails outright', async () => {
const page = createPage();
- const loaded = await startLoaded({ page: page.port });
- const { aggregate, clock, persistence, setUnloadAtRisk } = loaded;
- expect(page.isListeningBeforeUnload).toBe(false);
-
- // A project too large for the journal opens, say: the next persisted revision registers the listener.
- setUnloadAtRisk(true);
- aggregate.edit('Opened a large project');
+ const { aggregate, persistence } = await startLoaded({ page: page.port });
expect(page.isListeningBeforeUnload).toBe(true);
-
- // The save that settles it finds the risk gone (the project closed, or storage recovered).
- const save = deferred<WorkbenchSaveResult>();
- vi.mocked(persistence.saveWorkbench).mockImplementationOnce(() => save.promise);
- clock.runAll();
- setUnloadAtRisk(false);
- save.resolve(saveResult(aggregate.state));
- await flushPromises();
- expect(page.isListeningBeforeUnload).toBe(false);
-
- // A journal that fails outright leaves nothing known about recovery, so it listens until one succeeds.
+ expect(page.beforeUnload()).toBe(false);
persistence.journalBeforeUnload = vi.fn(() => {
throw new Error('storage gone');
});
aggregate.edit('Unjournaled');
- page.hide();
- expect(page.isListeningBeforeUnload).toBe(true);
expect(page.beforeUnload()).toBe(true);
+ expect(savedNames(persistence)).toEqual(['Unjournaled']);
});
it('asks only when the journal could not take the unsaved revision, journaling it first', async () => {
@@ -1528,7 +1507,6 @@ describe('Workbench persistence runtime unload prompt', () => {
const { aggregate, clock, persistence } = loaded;
draft.held.commitTo = aggregate;
const journaledNames = journalTo(loaded);
- loaded.setUnloadAtRisk(true);
aggregate.edit('At risk');
clock.runAll();
await flushPromises();
@@ -1538,6 +1516,8 @@ describe('Workbench persistence runtime unload prompt', () => {
expect(journaledNames).toEqual([]);
// An ordinary edit, still held in a debounced field: the journal keeps it, so leaving needs no prompt.
+ const save = deferred<WorkbenchSaveResult>();
+ vi.mocked(persistence.saveWorkbench).mockImplementationOnce(() => save.promise);
draft.held.name = 'Typed';
expect(page.beforeUnload()).toBe(false);
expect(journaledNames).toEqual(['Typed']);
@@ -1547,24 +1527,21 @@ describe('Workbench persistence runtime unload prompt', () => {
// Asked again (the user stayed, then left once more) without journaling the same revision twice.
expect(page.beforeUnload()).toBe(true);
// The unload that follows has nothing new to journal.
- const save = deferred<WorkbenchSaveResult>();
- vi.mocked(persistence.saveWorkbench).mockImplementationOnce(() => save.promise);
page.hide();
expect(journaledNames).toEqual(['Typed', tooLarge]);
// Once the server has it, nothing is left to lose.
save.resolve(saveResult(aggregate.state));
+ await vi.waitFor(() => expect(savedNames(persistence)).toEqual(['At risk', 'Typed', tooLarge]));
await flushPromises();
- clock.runAll();
expect(page.beforeUnload()).toBe(false);
});
- it('never listens before loading, while the session is closed, or after the account lifetime ended', async () => {
+ it('does not checkpoint or prompt before load, while closed, or after its account lifetime ended', async () => {
const page = createPage();
const aggregate = createAggregate();
const load = deferred<HydratedWorkbenchSnapshot | null>();
const fake = createPersistence(() => load.promise);
- fake.setUnloadAtRisk(true);
fake.setUnloadWouldLose(true);
const controller = new AbortController();
const runtime = createWorkbenchPersistenceRuntime({
@@ -1576,7 +1553,9 @@ describe('Workbench persistence runtime unload prompt', () => {
});
runtime.start();
aggregate.edit('While loading');
- expect(page.isListeningBeforeUnload).toBe(false);
+ expect(page.beforeUnload()).toBe(false);
+ expect(fake.persistence.journalBeforeUnload).not.toHaveBeenCalled();
+ expect(fake.persistence.saveWorkbench).not.toHaveBeenCalled();
load.resolve(null);
await flushPromises();
@@ -1585,9 +1564,12 @@ describe('Workbench persistence runtime unload prompt', () => {
fake.setClosedSession(true);
expect(page.beforeUnload()).toBe(false);
aggregate.edit('Closed');
- expect(page.isListeningBeforeUnload).toBe(false);
+ expect(page.beforeUnload()).toBe(false);
+ expect(fake.persistence.journalBeforeUnload).not.toHaveBeenCalled();
+ expect(fake.persistence.saveWorkbench).not.toHaveBeenCalled();
fake.reopenSession();
expect(page.beforeUnload()).toBe(true);
+ expect(fake.persistence.journalBeforeUnload).toHaveBeenCalledOnce();
controller.abort();
expect(page.isListeningBeforeUnload).toBe(false);
@@ -1598,7 +1580,6 @@ describe('Workbench persistence runtime unload prompt', () => {
const loaded = await startLoaded({ page: page.port });
const { aggregate, persistence, runtime } = loaded;
const journaledNames = journalTo(loaded);
- loaded.setUnloadAtRisk(true);
const checkpointSave = deferred<WorkbenchSaveResult>();
vi.mocked(persistence.saveWorkbench).mockImplementationOnce(() => checkpointSave.promise);
aggregate.edit(tooLarge);
@@ -1618,7 +1599,6 @@ describe('Workbench persistence runtime unload prompt', () => {
it('stops listening when the exit checkpoint settles', async () => {
const page = createPage();
const loaded = await startLoaded({ page: page.port });
- loaded.setUnloadAtRisk(true);
loaded.aggregate.edit('Left the editor');
expect(page.isListeningBeforeUnload).toBe(true);
diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts
index b60f0141ab..abe24b65df 100644
--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts
+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts
@@ -46,8 +46,6 @@ export interface WorkbenchPersistencePort {
journalBeforeUnload(state: WorkbenchState): UnloadJournalOutcome;
/** Whether unloading now would lose unsaved changes local recovery cannot hold, as of the last journal. */
hasChangesUnloadWouldLose(): boolean;
- /** Whether an unload could lose an edit at all; the unload prompt is registered only while it could. */
- isUnloadAtRisk(state: WorkbenchState): boolean;
loadWorkbench(options?: WorkbenchLoadOptions): Promise<HydratedWorkbenchSnapshot | null>;
saveWorkbench(state: WorkbenchState): Promise<WorkbenchSaveResult>;
}
@@ -59,8 +57,9 @@ export interface PersistenceClock {
/** Signals the moments a page may stop running script without further notice. */
export interface PageLifecyclePort {
- /** Asks before the page unloads; a true answer has the browser offer to stay, with its own wording. */
+ /** Checkpoints before unload; a true answer has the browser offer to stay, with its own wording. */
subscribeBeforeUnload(shouldPrompt: () => boolean): () => void;
+ /** Checkpoints on hidden/pagehide; the callback must tolerate repeated signals. */
subscribeHidden(listener: () => void): () => void;
}
@@ -107,7 +106,7 @@ const browserClock: PersistenceClock = {
setTimeout: (callback, delayMs) => window.setTimeout(callback, delayMs),
};
-/** `pagehide` and becoming hidden; hidden is often the last event a backgrounded or discarded page receives. */
+/** Checkpoint before WebKit starts tearing IndexedDB down; hidden still covers pages that are later discarded. */
export const browserPageLifecycle: PageLifecyclePort = {
subscribeBeforeUnload: (shouldPrompt) => {
const listener = (event: BeforeUnloadEvent): void => {
@@ -197,12 +196,9 @@ export const createWorkbenchPersistenceRuntime = ({
let previousExitWait: Promise<void> | null = null;
let unsubscribeAggregate: (() => void) | null = null;
let unsubscribePage: (() => void) | null = null;
- /** The unload decision of the editor, or of its exit checkpoint; none once neither can write. */
- let unloadPrompt: (() => boolean) | null = null;
let unsubscribeBeforeUnload: (() => void) | null = null;
/** The last journal failed unexpectedly, so nothing tells what it holds. */
let hasJournalFailed = false;
- let unloadRiskRevision: number | null = null;
let unsubscribeSessionReopened: (() => void) | null = null;
const isStopped = (): boolean => disposed || exiting;
@@ -352,7 +348,6 @@ export const createWorkbenchPersistenceRuntime = ({
isSaveInFlight = false;
inFlightRevision = null;
inFlightSave = null;
- syncUnloadPrompt();
const queuedRequireCurrentRevision = queuedSaveRequireCurrentRevision;
queuedSaveRequireCurrentRevision = null;
@@ -399,10 +394,9 @@ export const createWorkbenchPersistenceRuntime = ({
/**
* The only write that can land while the page unloads: a save first stages through fenced IndexedDB round trips that
- * an unloading page never finishes. The journal is reconciled into local recovery on the next load. False when the
- * journal failed unexpectedly, so nothing tells what it holds.
+ * an unloading page never finishes. The journal is reconciled into local recovery on the next load.
*/
- const journalBeforeUnload = (): boolean => {
+ const journalBeforeUnload = (): void => {
const revision = aggregate.getPersistedRevision();
if (
disposed ||
@@ -411,7 +405,7 @@ export const createWorkbenchPersistenceRuntime = ({
revision === lastSavedRevision ||
revision === journaledRevision
) {
- return true;
+ return;
}
try {
const outcome = persistence.journalBeforeUnload(aggregate.getState());
@@ -420,7 +414,7 @@ export const createWorkbenchPersistenceRuntime = ({
message: 'Unsaved changes could not be journaled for recovery before the page was hidden.',
name: 'persistence.unload-journal-unavailable',
});
- return true;
+ return;
}
journaledRevision = revision;
if (outcome.kind === 'journaled') {
@@ -446,7 +440,6 @@ export const createWorkbenchPersistenceRuntime = ({
});
}
hasJournalFailed = false;
- return true;
} catch (error) {
logger.warn({
error,
@@ -454,45 +447,19 @@ export const createWorkbenchPersistenceRuntime = ({
name: 'persistence.unload-journal-unavailable',
});
hasJournalFailed = true;
- return false;
- } finally {
- syncUnloadPrompt();
}
};
/**
- * Keeps `beforeunload` registered only while an unload could lose an edit, as a listener alone can cost the page its
- * back/forward cache in some browsers. Rechecked whenever its inputs change: a persisted revision, a save or journal
- * settling, the session reopening, the editor leaving.
- */
- const syncUnloadPrompt = (): void => {
- unloadRiskRevision = aggregate.getPersistedRevision();
- const isAtRisk =
- unloadPrompt !== null &&
- !disposed &&
- hasLoaded &&
- !persistence.hasClosedSession() &&
- (hasJournalFailed || persistence.isUnloadAtRisk(aggregate.getState()));
- if (isAtRisk && !unsubscribeBeforeUnload) {
- unsubscribeBeforeUnload = page?.subscribeBeforeUnload(() => unloadPrompt?.() ?? false) ?? null;
- } else if (!isAtRisk && unsubscribeBeforeUnload) {
- unsubscribeBeforeUnload();
- unsubscribeBeforeUnload = null;
- }
- };
-
- /**
- * Journals what `pagehide` would (unloading fires `beforeunload` first), then whether the unload would lose an unsaved
- * revision the journal could not take. An ordinary edit the journal holds never prompts.
+ * Answers from the checkpoint's journal, without serializing again. An ordinary edit the journal holds never prompts.
*/
const wouldUnloadLoseChanges = (): boolean => {
if (disposed || !hasLoaded || persistence.hasClosedSession()) {
return false;
}
- const isJournalKnown = journalBeforeUnload();
return (
aggregate.getPersistedRevision() !== lastSavedRevision &&
- (!isJournalKnown || persistence.hasChangesUnloadWouldLose())
+ (hasJournalFailed || persistence.hasChangesUnloadWouldLose())
);
};
@@ -500,7 +467,7 @@ export const createWorkbenchPersistenceRuntime = ({
if (isStopped() || !hasLoaded || persistence.hasClosedSession()) {
return false;
}
- commitPendingDrafts();
+ saveBeforeHidden();
return wouldUnloadLoseChanges();
};
@@ -531,9 +498,6 @@ export const createWorkbenchPersistenceRuntime = ({
if (isStopped()) {
return;
}
- if (aggregate.getPersistedRevision() !== unloadRiskRevision) {
- syncUnloadPrompt();
- }
const connectionStatus = aggregate.getState().backendConnection.status;
if (connectionStatus !== previousConnectionStatus) {
previousConnectionStatus = connectionStatus;
@@ -620,7 +584,6 @@ export const createWorkbenchPersistenceRuntime = ({
}
if (!isStopped() && loadGeneration === generation) {
hasLoaded = true;
- syncUnloadPrompt();
aggregate.reportLoadAvailable();
aggregate.setHasHydrated(true);
publish({ error: null, phase: 'idle' });
@@ -629,7 +592,6 @@ export const createWorkbenchPersistenceRuntime = ({
};
const onSessionReopened = (): void => {
- syncUnloadPrompt();
const held = saveHeldByClosedSession;
saveHeldByClosedSession = null;
if (held !== null && !isStopped()) {
@@ -645,8 +607,8 @@ export const createWorkbenchPersistenceRuntime = ({
unsubscribeAggregate = null;
unsubscribePage?.();
unsubscribePage = null;
- unloadPrompt = null;
- syncUnloadPrompt();
+ unsubscribeBeforeUnload?.();
+ unsubscribeBeforeUnload = null;
unsubscribeSessionReopened?.();
unsubscribeSessionReopened = null;
snapshot = { error: null, phase: 'disposed' };
@@ -687,7 +649,7 @@ export const createWorkbenchPersistenceRuntime = ({
}
lastExitRevision = revision;
try {
- const result = await persistence.saveWorkbench(aggregate.getState()).finally(syncUnloadPrompt);
+ const result = await persistence.saveWorkbench(aggregate.getState());
if (result.error || result.shouldRetry) {
logger.warn({
context: {
@@ -780,8 +742,14 @@ export const createWorkbenchPersistenceRuntime = ({
journalBeforeUnload();
}
}) ?? null;
- unloadPrompt = wouldUnloadLoseChanges;
- syncUnloadPrompt();
+ unsubscribeBeforeUnload =
+ page?.subscribeBeforeUnload(() => {
+ if (isSuperseded) {
+ return false;
+ }
+ journalBeforeUnload();
+ return wouldUnloadLoseChanges();
+ }) ?? null;
const settled = checkpoint(beforeCapture, () => isSuperseded).finally(() => {
unsubscribeExitPage?.();
dispose();
@@ -791,8 +759,8 @@ export const createWorkbenchPersistenceRuntime = ({
supersede: () => {
isSuperseded = true;
// A superseded checkpoint gave its unsaved revision up already; the newer editor guards its own.
- unloadPrompt = null;
- syncUnloadPrompt();
+ unsubscribeBeforeUnload?.();
+ unsubscribeBeforeUnload = null;
},
};
return exitHandle;
@@ -820,7 +788,7 @@ export const createWorkbenchPersistenceRuntime = ({
signal?.addEventListener('abort', dispose, { once: true });
unsubscribeAggregate = aggregate.subscribe(onAggregateChange);
unsubscribePage = page?.subscribeHidden(saveBeforeHidden) ?? null;
- unloadPrompt = promptBeforeUnload;
+ unsubscribeBeforeUnload = page?.subscribeBeforeUnload(promptBeforeUnload) ?? null;
unsubscribeSessionReopened = persistence.subscribeSessionReopened(onSessionReopened);
void load();
},
diff --git a/invokeai/frontend/webv2/src/workbench/projects/README.md b/invokeai/frontend/webv2/src/workbench/projects/README.md
index a68011c73f..e2d722a29a 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/README.md
+++ b/invokeai/frontend/webv2/src/workbench/projects/README.md
@@ -34,6 +34,22 @@ Workflow reads the active workflow through the App-composed port and edits, publ
Workbench persistence is scoped to one mounted Workbench and its account lifetime. `createWorkbenchPersistenceRuntime` owns hydration ordering, debounced autosave, hidden-page saves, revision/generation checks, conflict application, reconnect replay, status publication, exit checkpoint, without importing React. `createSyncedWorkbenchPersistence` builds local/remote project sync state for one mounted Workbench; no process-wide maps, sets, flags, or caches hold that state. It also owns the unload journal: runtime asks it, via its persistence port, to journal unsaved state synchronously when page is hidden or unloads, and its load reconciles the journal into the draft store under the draft store's fencing rules. `WorkbenchProvider` constructs these lifetimes, starts the runtime and ends it with its exit checkpoint through the mount lifecycle adapter, and selects aggregate hydration state. Checkpoint and persistence lease outlive the unmount until it settles. Provider also hands the checkpoint to the account lifetime's next editor through a module-level map keyed by account scope; that editor loads after it, waiting at most 10 seconds; the tab's editor session is reference-counted across the two. Project transition commands commit pending editor drafts themselves, so callers do not flush before creating, opening, switching, or closing a project.
+Save, project-flush and server-identity requests capture the current journal identity before queuing. A distinct held edit journaled
+after that intent cannot be superseded by the older request's stage or retired as an undo; it stays pending while
+older acknowledgements may rebase it. A journal of the same document can still be covered by the save, and an
+explicit later save or undo can replace an already existing journal. Retiring a journal keeps only its session and
+generation as intent metadata for the owner lifetime: an older queued undo must remain fenced even if another save
+has already staged or acknowledged the redone document and removed its journal. This metadata retains no document
+payload and resets with workbench load or terminal clear; it tracks the same resolved project identities as the writer generations.
+Returning to a document already in recovery also advances this intent, even though the checkpoint only retires an
+older journal. That journal's payload cannot authorize an older queued request; its physical identity stays separate
+so the next save can still write its settled mark if the blind deletion failed. A different in-flight stage can
+replace the current recovery document, so a checkpoint of that document still writes a payload journal until the
+stage settles. Matching physical journal bytes skip a checkpoint only while that entry still names the current
+intent; a failed retirement leaves the newer intent authoritative even if storage still holds older bytes. Sharing a pending stage's
+generation likewise requires that it is still the writer's latest issued generation. An undo-retired journal is never
+rewritten by an older acknowledgement's rebase.
+
Project record reads, content/workspace writes, and project deletion have a 150-second request deadline, including response-body consumption. This allows the server's 120-second maximum request upload duration plus 30 seconds for processing and the response, so supported large documents can save over slower connections. Client-state reads have a 30-second deadline. Cancellation aborts the request and ends the wait, with timer/listener cleanup on every settlement. Uploads and model operations have no universal deadline; an import’s project creation uses these project budgets. Busy project writes admit at most nine attempts within 125 seconds; every started attempt gets its full 150 seconds, so a late admitted attempt may finish about 275 seconds after the operation began. A project request that stalls releases the serialized save queue, so later edits and project switches in the same mounted editor can save once any following session write settles. Dirty drafts remain pending on unavailable reconciliation; normal autosave retry/status policy applies, without parallel writes.
A deadline does not prove a write failed. Creates repeat their reserved identity only within the write admission budget and reconcile matching content; absence after unanswered attempts never authorizes cleanup. Content/workspace timeouts use revision/content reconciliation: acknowledge held bytes, retry unchanged or previously sent server state once at its revision, or report divergence. Unanswered state survives that retry, so a late commit followed by a revision conflict does not invent a competing writer. An inconclusive read or exhausted unanswered retry leaves the draft pending. Undo to previously acknowledged bytes still sends revision-fenced writes for any half with an unanswered different body. A read holding the desired bytes at a strictly newer revision also proves the fence; an unchanged revision cannot prove that older body will not commit later. Whole documents retain the same sent-body evidence. A reconciled create applies its server board assignment and refreshes board lists.
@@ -48,7 +64,7 @@ Widget module recovery (`projects/reloadWorkbench.ts`) prepares a fresh document
- Account-owned IndexedDB stores only unacknowledged project drafts, unload journal entries, active queue runs, receipt acknowledgements, bounded recall values. Clean server documents not mirrored. Journal has its own database, deleted with the workbench database by account cleanup and by clearing workspace data.
- Draft generations fence acknowledgements. Draft writer ownership and cross-tab notifications stop one editor overwriting another editor's unacknowledged work.
-- **Unload journal.** Staging a draft takes fenced read-then-write transactions, which an unloading page never finishes. So when page is hidden or unloads, before save starts, each open project whose document is not what next load would restore (its durably staged draft, or without one the acknowledged server copy) is written as one blind, explicitly committed IndexedDB write. Own database because Chromium drops such a write at unload while a read-write transaction of the same database is still open, which a stage in flight is. Entry carries account, project, lineage (an editor session, possibly another tab's that the session blob handed on), editor session of the page that wrote it, writer, base revisions and canvas schema floor, and a draft generation: above everything the writer staged or journaled before, or equal to a still-in-flight stage of the same document. A writer's generations never restart while its page lives, even when a project is closed and reopened. Each write also deletes the writer's lower generations for the lineage, so at most one entry per lineage and writer, however long saves cannot be acknowledged.
+- **Unload journal.** Staging a draft takes fenced read-then-write transactions, which an unloading page never finishes. So when page is hidden or unloads, before save starts, each open project whose document is not what next load would restore (its durably staged draft, or without one the acknowledged server copy) is written as one blind, explicitly committed IndexedDB write. Own database because Chromium drops such a write at unload while a read-write transaction of the same database is still open, which a stage in flight is. Entry carries account, project, lineage (an editor session, possibly another tab's that the session blob handed on), editor session of the page that wrote it, writer, base revisions and canvas schema floor, and a draft generation: above everything the writer staged or journaled before, or equal to a still-in-flight stage of the same document while its generation is still the writer's latest issued generation and its journal identity is live. A redo after retirement or settlement gets a fresh generation, so an older queued undo cannot retire it. A writer's generations never restart while its page lives, even when a project is closed and reopened. Each write also deletes the writer's lower generations for the lineage, so at most one entry per lineage and writer, however long saves cannot be acknowledged.
- **Settled mark.** A lineage's writer claim records the generation through which its writer settled its journal: everything it acknowledged, discarded, or holds in recovery. Acknowledgement and draft deletion write it in the same transaction that settles or deletes the draft; a document back to what recovery holds (an undo, say) writes it on its next save, and claims the lineage for the writer if it has none. Optional claim field, so earlier claims read as settled nothing and workbench database stays at version 4; an earlier writer's mark is ignored. It tells "never staged" from "acknowledged and moved on" once an acknowledgement deleted the draft, so an entry whose deletion failed, or that another tab reconciles at the moment of acknowledgement, can never come back.
- Next load of the account reconciles every entry, in pages, before any writer claims a lineage. Entry becomes its lineage's next draft only where its writer could still have staged it: lineage unclaimed or still claimed by that writer, writer has not settled that far, and lineage holds no generation at or above the entry's. It keeps the stored draft's conflict, schema refusal, copy reservation, and base revision, as staging does, then goes through usual load rules, so a server revision the base no longer matches surfaces as conflict. One exception: when the entry replaced a staged draft whose document the server now holds exactly (its save arrived, its answer did not), the draft is rebased onto that revision, as the late answer would have done, instead of conflicting with the writer's own save. Entry discarded when another writer adopted, reclaimed, or retargeted the lineage, when its writer settled it, when lineage already holds it or something newer, when it belongs to another account, or when its record schema is unknown or it is damaged. Draft written before entry removed, so a crash between leaves an entry the next pass discards as superseded.
- Another tab's load reconciles only entries of pages that are gone. Page proves it still runs by its editor session's Web Lock, held until its last editor releases it or the page unloads or crashes; an entry whose writing page (the editor session it names, not the lineage it is written under) another page still holds is left in place (a merely hidden tab still writes its lineages, and staging its entry elsewhere would hand that tab's unsaved edit to another tab, where an undo could never retire it). Entry written before it named its page counts as a gone page's. Hidden page settles the entry with its own saves, or next load after it is gone recovers it. Browser that keeps a page holding its session in the back/forward cache keeps the lock held, so the entry waits until the page is restored (and saves) or evicted; one that evicts such pages (Chromium today) releases the lock, and the entry is recovered as a gone page's. Reload of same tab reclaims its session, retrying up to half a second (five retries 100 ms apart) while old document lets go, then reconciles its own entries. Two cases fall outside it. If old document holds the lock longer, reload takes a fresh session, its own entries and staged drafts count as a running page's on that load, and a later load recovers them once old document is gone. Duplicated tab waits the same half second before taking its own session; if the original reloads within it, the duplicate can take the original's session instead and then takes the original's entries and staged drafts, while reloaded original takes a fresh session. Staged drafts follow same rule: a load does not adopt, auto-open, or offer for recovery a draft whose lineage is named after another running page's session, and editor route does not count it. Draft records its lineage, not the page staging it, so it is judged by the session that lineage is named after: a lineage isolated for an unopenable draft names no page and is adopted as before. A lineage the session blob hands on (today only isolated ones) is not judged at all: loading page claims its handed-on lineage directly, whether or not the page staging it still runs. Without Web Locks (plain-HTTP deployment, say) liveness cannot be told, so every entry is reconciled and every draft adopted as before. Hidden event during save-as-new journals the source project: if page goes away before the copy exists, edit is recovered into the conflicted source and retried copy keeps its reserved document; once copy exists, source lineage has moved, so entry is discarded and copy is never written from it.
@@ -69,9 +85,9 @@ Navigation never blocked in the app; local capture of committed state is the con
- **Account changes.** Ended account lifetime abandons its checkpoint: nothing of the old account is written afterwards.
- **Re-entry.** Remounted editor of same account loads only after previous checkpoint settled and its persistence closed, so it never hydrates an older snapshot and two editors never write at once. Provider keeps that handoff per account lifetime, keyed by its scope, so another account never waits on it.
- **Re-entry after 10 seconds.** New editor loads anyway. Previous checkpoint is superseded: starts no further write and gives up its project mutation locks. If it still had an unsaved revision, it logs that the revision was not written. Staging happens inside the persistence queue, so while a request stalls nothing newer than the save before it reaches local recovery; edits committed after that are lost in this case, before any unload, so no unload prompt can keep them. A tab closed during the wait instead journals them through the exit checkpoint (above), and is prompted as an editor is. A project request still pending at the handoff keeps its own 150-second deadline and is cancelled when that expires; an unconditional client-state write has no deadline (above). Until it settles, or tab closes, superseded persistence keeps its draft-store connection and its hold on the tab's editor session. New editor holds the same session, which stays locked to this tab until its last holder releases it. Late write is fenced like another tab's, by draft-writer claims and revision conflicts.
-- **Hidden pages.** On `pagehide` and when page becomes hidden, runtime commits drafts editors still hold (the draft registry), writes the unload journal for an unsaved revision (including one whose save is in flight), then saves it at once instead of after autosave debounce. Committing a draft leaves control's value, caret and focus as they were. Revision whose save failed, or one already being saved, is not sent again; while session is closed nothing is committed, journaled, or saved. Save is asynchronous, so it completes when the hidden page keeps running (switching tabs or apps, minimising, or entering back/forward cache), and its acknowledgement retires the journal. It cannot complete while page unloads (reload, closing tab, navigating away), so across an unload the journal is what survives: next load of the account recovers the edit as a pending draft and saves it. Tab restored from back/forward cache writes through the same account-scope, draft-writer, and revision checks as every other write.
-- **Unload prompt.** A `beforeunload` listener is registered only while an unload could lose an edit (`isUnloadAtRisk`), since a listener alone can cost the page its back/forward cache in some browsers: open documents that together exceed the journal budget (sized as a save or the journal last serialized them, or as loaded until then), local recovery failing for an open project (storage full or unavailable), the journal unavailable at load or for its last write, or a last journal that failed outright. The runtime rechecks on each persisted revision, settled save or journal, session reopen, and exit; healthy storage with projects inside the budget registers nothing. A document that grows past the budget after its last serialization is caught by its next save, not before. While registered, `beforeunload` (which comes before `pagehide`) commits held drafts and writes the unload journal (the later events find it written), and asks the browser to confirm leaving (its own generic wording) only when an unsaved revision would not survive the unload: a project the journal skipped for its budget, an edit it could not write, or one journaled for a project whose local recovery is failing, in each case until a stage succeeds or the server acknowledges the revision. `hasChangesUnloadWouldLose` answers from what that journal recorded, without serializing again. An ordinary edit the journal holds never prompts, nor does anything while the session is closed, before load, after the account lifetime ended, or for an exit checkpoint a newer editor superseded; an exit checkpoint still saving keeps the editor's listener rules. A journal write that aborts after starting (storage filling during the unload) cannot be known in time and does not prompt.
-- **What is and is not guaranteed.** In Chromium, an ordinary reload, tab close, or navigation away right after an edit keeps the edit, including one still held in a debounced field: journal write is committed before the handler returns and the browser finishes it. Nothing guaranteed when browser or OS is killed, crashes, or loses power before the write reaches disk (transaction uses default, relaxed durability), when a page is discarded without a `pagehide` or hidden event (edit made after last hidden event is lost), for projects over the journal budget, or when browser storage is unavailable or full; those last two bring up the unload prompt while they hold an unsaved revision, so leaving anyway is the user's choice. Undo made just before page goes away is retired by the same kind of blind write and can be lost the same way: then the undone edit comes back on next load, silently when server revision has not moved. Other browsers follow same IndexedDB rules but are not verified to finish a committed write during unload.
+- **Hidden pages and unload checkpoints.** On `beforeunload`, `pagehide`, and when the page becomes hidden, runtime commits drafts editors still hold (the draft registry), writes the unload journal for an unsaved revision (including one whose save is in flight), then saves it at once instead of after autosave debounce. Committing a draft leaves control's value, caret and focus as they were. Revision whose save failed, or one already being saved, is not sent again; while session is closed nothing is committed, journaled, or saved. Save is asynchronous, so it completes when the hidden page keeps running (switching tabs or apps, minimising, or entering back/forward cache), and its acknowledgement retires the journal. It cannot complete while page unloads (reload, closing tab, navigating away), so across an unload the journal is what survives: next load of the account recovers the edit as a pending draft and saves it. Tab restored from back/forward cache writes through the same account-scope, draft-writer, and revision checks as every other write.
+- **Unload prompt.** One `beforeunload` listener commits held drafts, writes the journal, starts the save, then asks the browser to confirm leaving (its own generic wording) only when an unsaved revision would not survive the unload: a project the journal skipped for its budget, an edit it could not write, or one journaled for a project whose local recovery is failing, in each case until a stage succeeds or the server acknowledges the revision. `hasChangesUnloadWouldLose` answers from what that journal recorded, without serializing again. The early checkpoint is necessary because WebKit can discard even an explicitly committed IndexedDB write started later in `pagehide`. This always registered listener can reduce back/forward-cache eligibility in engines such as Firefox; the smoke report records actual restoration rather than promising eligibility. An ordinary edit the journal holds never prompts, nor does anything while the session is closed, before load, after the account lifetime ended, or for an exit checkpoint a newer editor superseded; an exit checkpoint still saving keeps its listener until it settles. A journal write that aborts after starting (storage filling during the unload) cannot be known in time and does not prompt.
+- **What is and is not guaranteed.** In Chromium, an ordinary reload, tab close, or navigation away right after an edit keeps the edit, including one still held in a debounced field: journal write is committed before the handler returns and the browser finishes it. Nothing guaranteed when browser or OS is killed, crashes, or loses power before the write reaches disk (transaction uses default, relaxed durability), when a page is discarded without a `pagehide` or hidden event (edit made after last hidden event is lost), for projects over the journal budget, or when browser storage is unavailable or full; those last two bring up the unload prompt while they hold an unsaved revision, so leaving anyway is the user's choice. Undo made just before page goes away is retired by the same kind of blind write and can be lost the same way: then the undone edit comes back on next load, silently when server revision has not moved. The targeted smoke also verifies held-field reload recovery in the locked Firefox and Playwright WebKit builds on the recorded platform; this does not establish the same guarantee for every browser version, real Safari, or other Apple platforms.
- **Journal side effects.** Entry kept for a damaged lineage or full storage reports degraded local recovery for its project on every load that keeps it, even when that project is not opened in the session. Editor route counts any project with an entry of a gone page (or of this page, by the session it persisted) as one that would open, so with an empty session such an entry, or one reconciliation will discard, opens the editor instead of Home; an entry or staged draft of another still-running page does not, since editor would leave it alone.
- **Project transitions.** Creating, opening, switching, and closing projects commit pending editor drafts the moment open or active projects change, so an edit typed while a caller awaited hydration or a close push lands on the project it was typed in. Close can require the version it pushed; drafts that change the project refuse it, and close flow pushes again.
@@ -107,6 +123,12 @@ A build that predates these fields would strip them on load and lose the origina
Run `pnpm lint`, `pnpm test`, `pnpm test:browser`, and `pnpm run test:performance:build` from webv2. Queue receipt tests also cover backend admission, account isolation, project deletion, partial acceptance, idempotent retries. Browser tests exercise real IndexedDB transactions and Web Locks.
+`pnpm test:browser:smoke` exercises held-prompt reload recovery, duplicated-tab editor-session lock ownership and
+release, and route exit/re-entry against real storage in Chromium, Firefox and Playwright WebKit. It records actual
+BFCache entry separately from history reload. See the package [performance guide](../../../performance/README.md)
+for capabilities, artifacts and limits. These smoke results do not expand the Chromium unload guarantee above to
+all browser versions, real Safari, crashes or storage failure.
+
## Image and queue metadata recall
Canvas generation captures its document after paint persistence, together with its detached generation composites. Image `canvas_v3_metadata` version 1 holds that authored document, portable control-model identities and Canvas settings, without project identity, staging, undo history or stored media URLs. Controls that ran are pinned to the resolved model, kind, weight and schedule; the core metadata's `control_layers`, `controlnets` and `t2iAdapters` describe the executed composites. The queue recall cache keeps the same canvas record beside Generate values under its existing account and byte limits. Manual Save Canvas records the exported document and authored Canvas and common Generate settings, model, prompts, concepts and reference images, labelled `metadata_source: canvas_save`; it records neither an executed seed nor a generation mode. Its destination follows the Gallery settings at click time. After paint persistence and export, metadata is captured synchronously from the originating project only if its document is still the one exported, so settings edits during the save are recorded with the unchanged document. A changed document, a closed project or an expired account prevents upload.
diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
index 573825f81f..5e79148b9c 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
@@ -4541,62 +4541,6 @@ describe('unload journal', () => {
expect(service.hasChangesUnloadWouldLose()).toBe(false);
});
- it('is at risk while open documents together exceed the journal budget, from load on', async () => {
- const api = createApi();
- const over = projectOfSize(PROJECT_UNLOAD_JOURNAL_MAX_BYTES + 1);
- openSession(api, over);
- const service = createService(captureAccountScope(), api);
- const loaded = await service.loadWorkbench();
- // Nothing journaled or saved yet: the loaded document alone is too large for the journal.
- expect(service.isUnloadAtRisk(loaded.state)).toBe(true);
- expect(service.hasChangesUnloadWouldLose()).toBe(false);
- expect(service.isUnloadAtRisk(stateWith([]))).toBe(false);
-
- const small = createDraftProject([over]);
- const half = projectOfSize(PROJECT_UNLOAD_JOURNAL_MAX_BYTES / 2 + 1, [over, small]);
- const otherHalf = projectOfSize(PROJECT_UNLOAD_JOURNAL_MAX_BYTES / 2 + 1, [over, small, half]);
- await service.saveWorkbench(stateWith([small, half]));
- expect(service.isUnloadAtRisk(stateWith([small, half]))).toBe(false);
- // Each fits on its own; together they do not.
- await service.saveWorkbench(stateWith([small, half, otherHalf]));
- expect(service.isUnloadAtRisk(stateWith([small, half, otherHalf]))).toBe(true);
-
- await service.persistEmptySession(stateWith([small, half, otherHalf]));
- expect(service.isUnloadAtRisk(stateWith([small, half, otherHalf]))).toBe(false);
- });
-
- it('is at risk while local recovery fails for an open project or the journal is unavailable', async () => {
- const backing = createMemoryProjectDraftStore();
- let isFull = true;
- const full: ProjectDraftStore = {
- ...backing,
- get availability() {
- return backing.availability;
- },
- stage: (input) => (isFull ? Promise.resolve({ kind: 'quota' }) : backing.stage(input)),
- };
- const service = createService(captureAccountScope(), createApi(), full);
- const loaded = await service.loadWorkbench();
- expect(service.isUnloadAtRisk(loaded.state)).toBe(false);
- const edited = stateWith([{ ...loaded.state.projects[0]!, name: 'Typed while storage is full' }]);
- await service.saveWorkbench(edited);
- expect(service.isUnloadAtRisk(edited)).toBe(true);
- isFull = false;
- await service.saveWorkbench(stateWith([{ ...edited.projects[0]!, name: 'Storage freed up' }]));
- expect(service.isUnloadAtRisk(edited)).toBe(false);
-
- const withoutJournal: ProjectDraftStore = {
- ...backing,
- get availability() {
- return backing.availability;
- },
- journalBeforeUnload: () => ({ kind: 'unavailable' }),
- reconcileUnloadJournal: () => Promise.resolve({ kind: 'unavailable' }),
- };
- const other = createService(captureAccountScope(), createApi(), withoutJournal);
- expect(other.isUnloadAtRisk((await other.loadWorkbench()).state)).toBe(true);
- });
-
it('counts nothing for a closed session, an ended account lifetime, or a project being deleted', async () => {
const api = createApi();
const service = createService(captureAccountScope(), api);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts
index 9562e20c50..6b810a7524 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts
@@ -537,12 +537,6 @@ export interface DurableSyncedWorkbenchPersistence {
* that project's local recovery is failing (storage full or unavailable). Synchronous and cheap, for `beforeunload`.
*/
hasChangesUnloadWouldLose(): boolean;
- /**
- * True while an unload could lose an edit, before any journal of it: what `hasChangesUnloadWouldLose` reports, or
- * open documents that together exceed the journal budget (as last serialized or loaded), local recovery failing for
- * an open project, or the journal unavailable. Synchronous and cheap, for keeping the unload prompt registered.
- */
- isUnloadAtRisk(state: WorkbenchState): boolean;
hasPendingChanges(): boolean;
hydrateProjectFromServer(projectId: string, projectName?: string): Promise<ProjectLoadResult>;
loadWorkbench(options?: { createNew?: boolean; openProjectId?: string }): Promise<DurableHydratedWorkbenchSnapshot>;
@@ -705,15 +699,13 @@ export const createDurableSyncedWorkbenchPersistence = (
const localDraftFailures = new Set<string>();
/** Documents this writer journaled and has not yet seen acknowledged, by resolved project id. */
const journaledDocuments = new Map<string, ProjectUnloadJournalEntry>();
+ /** Journal retirement intents still fence older queued requests, without retaining acknowledged document bytes. */
+ const retiredJournalIntents = new Map<string, JournalIdentity>();
/**
* Unsaved documents the last unload journal could not write, by resolved project id, with the generation a stage must
* exceed to hold that document (or a newer one) in local recovery.
*/
const unjournaledDocuments = new Map<string, number>();
- /** Each project's document size as a save or the journal last serialized it, by resolved project id. */
- const serializedDocumentBytes = new Map<string, number>();
- /** The journal could not be reconciled at load, or its last write could not start. */
- let isJournalUnavailable = false;
/**
* Projects whose journal record no longer stands for a stored entry, so its document is journaled again: retired at
* a hidden event (the record stays, so the next save writes the settled mark), or being settled right now.
@@ -1083,10 +1075,37 @@ export const createDurableSyncedWorkbenchPersistence = (
}
};
- const createProjectSavePlan = (inputProject: Project) => {
+ type JournalIdentity = Pick<ProjectUnloadJournalEntry, 'editorSessionId' | 'generation'>;
+ const captureJournalIdentity = (projectId: string): JournalIdentity | undefined => {
+ const resolvedProjectId = resolveProjectId(projectId);
+ const journal = journaledDocuments.get(resolvedProjectId);
+ const retired = retiredJournalIntents.get(resolvedProjectId);
+ if (retired && (!journal || retired.generation > journal.generation)) {
+ return retired;
+ }
+ return journal ? { editorSessionId: journal.editorSessionId, generation: journal.generation } : undefined;
+ };
+ const isSameJournal = (journal: JournalIdentity, expected: JournalIdentity | undefined): boolean =>
+ journal.editorSessionId === expected?.editorSessionId && journal.generation === expected?.generation;
+ const isSupersededByJournal = (
+ projectId: string,
+ documentJson: string,
+ expected: JournalIdentity | undefined
+ ): boolean => {
+ const journal = journaledDocuments.get(projectId);
+ const current = captureJournalIdentity(projectId);
+ return (
+ current !== undefined &&
+ !isSameJournal(current, expected) &&
+ (journal && isSameJournal(journal, current) && !retiredJournalProjectIds.has(projectId)
+ ? journal.documentJson !== documentJson
+ : !isInRecovery(projectId, documentJson))
+ );
+ };
+
+ const createProjectSavePlan = (inputProject: Project, journalAtRequest: JournalIdentity | undefined) => {
const project = resolveInputProject(inputProject);
const serialized = serializeProjectDocumentV3Json(project);
- serializedDocumentBytes.set(project.id, serialized.byteSize);
const entry = syncEntries.get(project.id);
const existingDraft = volatileDrafts.get(project.id);
// A conflicted or refused project pushes nothing until resolved, so its upgrade waits too.
@@ -1105,16 +1124,23 @@ export const createDurableSyncedWorkbenchPersistence = (
pendingProjectIds.has(project.id) ||
conflicts.has(project.id) ||
schemaRefusals.has(project.id);
- return { existingDraft, needsPush, needsStage, project, serialized };
+ return { existingDraft, journalAtRequest, needsPush, needsStage, project, serialized };
};
type ProjectSavePlan = ReturnType<typeof createProjectSavePlan>;
const stageProject = async (
project: Project,
- serialized: ReturnType<typeof serializeProjectDocumentV3Json> = serializeProjectDocumentV3Json(project)
+ serialized: ReturnType<typeof serializeProjectDocumentV3Json>,
+ journalAtRequest: JournalIdentity | undefined
) => {
const store = await getDraftStore();
const session = await getEditorSessionForService();
+ // An old queued request must not allocate a generation above a later held edit's journal.
+ if (isSupersededByJournal(project.id, serialized.documentJson, journalAtRequest)) {
+ pendingProjectIds.add(project.id);
+ hasPending = true;
+ return null;
+ }
if (serialized.byteSize > PROJECT_DOCUMENT_MAX_BYTES) {
pendingProjectIds.add(project.id);
hasPending = true;
@@ -1201,6 +1227,12 @@ export const createDurableSyncedWorkbenchPersistence = (
// The lineage now holds this generation, which supersedes the writer's journal through it.
const journaled = journaledDocuments.get(project.id);
if (journaled && journaled.generation <= generation && journaled.editorSessionId === draftInput.editorSessionId) {
+ if ((retiredJournalIntents.get(project.id)?.generation ?? 0) < journaled.generation) {
+ retiredJournalIntents.set(project.id, {
+ editorSessionId: journaled.editorSessionId,
+ generation: journaled.generation,
+ });
+ }
journaledDocuments.delete(project.id);
retiredJournalProjectIds.delete(project.id);
await store.discardUnloadJournal(project.id, journaled.editorSessionId, writerToken, journaled.generation);
@@ -1250,6 +1282,7 @@ export const createDurableSyncedWorkbenchPersistence = (
await settleJournaledDocument(project.id, store);
} else if (
journaled &&
+ !retiredJournalProjectIds.has(project.id) &&
journaled.editorSessionId === editorSessionId &&
(journaled.baseRevision !== acknowledged.revision ||
(journaled.baseWorkspaceRevision ?? null) !== acknowledged.workspaceRevision)
@@ -1378,7 +1411,7 @@ export const createDurableSyncedWorkbenchPersistence = (
const pushStagedProject = async (
project: Project,
- staged: Awaited<ReturnType<typeof stageProject>>
+ staged: NonNullable<Awaited<ReturnType<typeof stageProject>>>
): Promise<ProjectPushOutcome> => {
assertNotCleared();
assertOwner();
@@ -1487,7 +1520,7 @@ export const createDurableSyncedWorkbenchPersistence = (
volatileDrafts.set(project.id, withBases(volatile, bases));
}
const journaled = journaledDocuments.get(project.id);
- if (journaled && journaled.editorSessionId === editorSessionId) {
+ if (journaled && !retiredJournalProjectIds.has(project.id) && journaled.editorSessionId === editorSessionId) {
const rebased = { ...journaled, ...bases };
const write = store.journalBeforeUnload({ entries: [rebased], retired: [] });
if (write.kind === 'started' && (await write.written) && journaledDocuments.get(project.id) === journaled) {
@@ -1878,15 +1911,22 @@ export const createDurableSyncedWorkbenchPersistence = (
plan: ProjectSavePlan,
staged?: Awaited<ReturnType<typeof stageProject>>
): Promise<ProjectPushOutcome> => {
- // The document went back to what recovery holds (an undo, say): the journal of a later state must not return.
- if (journaledDocuments.has(plan.project.id) && isInRecovery(plan.project.id, plan.serialized.documentJson)) {
- await settleJournaledDocument(plan.project.id, await getDraftStore());
- }
if (deletedProjectIds.has(plan.project.id)) {
// A pending push that the deletion overtook would otherwise keep every later save pending.
pendingProjectIds.delete(plan.project.id);
return { documentJson: plan.serialized.documentJson, kind: 'superseded' };
}
+ if (isSupersededByJournal(plan.project.id, plan.serialized.documentJson, plan.journalAtRequest)) {
+ pendingProjectIds.add(plan.project.id);
+ hasPending = true;
+ return { documentJson: plan.serialized.documentJson, kind: 'unsynced' };
+ }
+ // Only an undo requested after this journal, or the same document already in recovery, can retire it.
+ // Capture the target before the store await; a later hidden edit is a different intent.
+ const journalToRetire = journaledDocuments.get(plan.project.id);
+ if (journalToRetire && isInRecovery(plan.project.id, plan.serialized.documentJson)) {
+ await settleJournaledDocument(plan.project.id, await getDraftStore(), journalToRetire);
+ }
if (!plan.needsPush) {
return { documentJson: plan.serialized.documentJson, kind: 'acknowledged' };
}
@@ -1898,9 +1938,18 @@ export const createDurableSyncedWorkbenchPersistence = (
return { documentJson: plan.serialized.documentJson, kind: 'conflicted' };
}
if (plan.needsStage) {
- return pushStagedProject(plan.project, staged ?? (await stageProject(plan.project, plan.serialized)));
+ const capture = staged ?? (await stageProject(plan.project, plan.serialized, plan.journalAtRequest));
+ return capture
+ ? pushStagedProject(plan.project, capture)
+ : { documentJson: plan.serialized.documentJson, kind: 'unsynced' };
}
if (!plan.existingDraft) {
+ // A superseded request can leave only a pending marker; an explicit undo owes no write to the server.
+ if (syncEntries.get(plan.project.id)?.pushedDoc === plan.serialized.documentJson) {
+ pendingProjectIds.delete(plan.project.id);
+ recomputeHasPending();
+ return { documentJson: plan.serialized.documentJson, kind: 'acknowledged' };
+ }
return { documentJson: plan.serialized.documentJson, kind: 'unsynced' };
}
const store = await getDraftStore();
@@ -1912,8 +1961,10 @@ export const createDurableSyncedWorkbenchPersistence = (
});
};
- const pushProject = (inputProject: Project): Promise<ProjectPushOutcome> =>
- pushProjectPlan(createProjectSavePlan(inputProject));
+ const pushProject = (
+ inputProject: Project,
+ journalAtRequest: JournalIdentity | undefined
+ ): Promise<ProjectPushOutcome> => pushProjectPlan(createProjectSavePlan(inputProject, journalAtRequest));
const getRecoverableDraftSummaries = () =>
[...unopenableDrafts.values()]
@@ -2078,9 +2129,14 @@ export const createDurableSyncedWorkbenchPersistence = (
/**
* What the next load would restore for a project is exactly `documentJson`: its newest staged draft when it has one
- * (and that stage was durable), otherwise the acknowledged server document.
+ * (and that stage was durable), otherwise the acknowledged server document. A different in-flight stage can replace
+ * either, so the journal must still cover this document until that stage settles.
*/
const isInRecovery = (projectId: string, documentJson: string): boolean => {
+ const staging = stagingDocuments.get(projectId);
+ if (staging && staging.documentJson !== documentJson) {
+ return false;
+ }
const volatile = volatileDrafts.get(projectId);
return volatile
? volatile.documentJson === documentJson && !localDraftFailures.has(projectDraftFailureKey(projectId))
@@ -2090,11 +2146,16 @@ export const createDurableSyncedWorkbenchPersistence = (
/**
* Settles this writer's journal of a project in its lineage's claim (the mark makes a deletion that fails moot), then
* deletes it. The record is kept, for a later retry, until the mark commits. A fenced lineage needs no mark: its
- * entries are discarded anyway. False while the journal could still come back.
+ * entries are discarded anyway. False while the targeted journal could still come back; a replacement belongs to
+ * a newer intent and is left untouched.
*/
- const settleJournaledDocument = async (projectId: string, store: ProjectDraftStore): Promise<boolean> => {
+ const settleJournaledDocument = async (
+ projectId: string,
+ store: ProjectDraftStore,
+ expected?: JournalIdentity
+ ): Promise<boolean> => {
const journaled = journaledDocuments.get(projectId);
- if (!journaled) {
+ if (!journaled || (expected && !isSameJournal(journaled, expected))) {
return true;
}
settlingJournalProjectIds.add(projectId);
@@ -2114,6 +2175,12 @@ export const createDurableSyncedWorkbenchPersistence = (
}
// A hidden event meanwhile journaled a newer generation, which this settlement does not cover.
if (journaledDocuments.get(projectId) === journaled) {
+ if ((retiredJournalIntents.get(projectId)?.generation ?? 0) < journaled.generation) {
+ retiredJournalIntents.set(projectId, {
+ editorSessionId: journaled.editorSessionId,
+ generation: journaled.generation,
+ });
+ }
journaledDocuments.delete(projectId);
retiredJournalProjectIds.delete(projectId);
}
@@ -2180,7 +2247,14 @@ export const createDurableSyncedWorkbenchPersistence = (
conflicts.delete(projectId);
schemaRefusals.delete(projectId);
volatileDrafts.set(projectId, resumed.draft);
- const staged = await stageProject(merged.project);
+ const staged = await stageProject(
+ merged.project,
+ serializeProjectDocumentV3Json(merged.project),
+ captureJournalIdentity(projectId)
+ );
+ if (!staged) {
+ throw new Error('The project changed while its workspace was being recovered. Retry with the current project.');
+ }
const rebased = await store.rebaseDraft(projectId, editorSessionId, writerToken, staged.generation, {
baseMinimumCanvasSchemaVersion: record.minimum_canvas_schema_version,
baseRevision: record.revision,
@@ -2531,6 +2605,7 @@ export const createDurableSyncedWorkbenchPersistence = (
serverDeletedProjectIds.clear();
volatileDrafts.clear();
generations.clear();
+ retiredJournalIntents.clear();
draftEditorSessionIds.clear();
unopenableDrafts.clear();
localDraftFailures.clear();
@@ -2651,6 +2726,7 @@ export const createDurableSyncedWorkbenchPersistence = (
}
}),
ensureProjectOnServer: (project) => {
+ const journalAtRequest = captureJournalIdentity(project.id);
const assertProjectIdentityCurrent = () => {
assertNotCleared();
assertOwner();
@@ -2680,7 +2756,7 @@ export const createDurableSyncedWorkbenchPersistence = (
ensure = enqueue(async () => {
assertProjectIdentityCurrent();
if (!syncEntries.has(project.id)) {
- assertProjectFlushed(await pushProject(project));
+ assertProjectFlushed(await pushProject(project, journalAtRequest));
}
}).then(
() => {
@@ -2701,7 +2777,8 @@ export const createDurableSyncedWorkbenchPersistence = (
if (isTerminallyCleared) {
return Promise.reject(new Error('Workbench persistence was cleared and must be reloaded.'));
}
- return enqueue(() => pushProject(project));
+ const journalAtRequest = captureJournalIdentity(project.id);
+ return enqueue(() => pushProject(project, journalAtRequest));
},
getProjectDraftDocument: async (projectId) => {
const { draft } = await requireDraft(projectId);
@@ -2715,31 +2792,6 @@ export const createDurableSyncedWorkbenchPersistence = (
hasClosedSession: () => isSessionClosed,
hasPendingChanges: () => hasPending,
hasChangesUnloadWouldLose: () => isJournalWritable() && hasJournalLoss(),
- isUnloadAtRisk: (state) => {
- if (!isJournalWritable()) {
- return false;
- }
- if (isJournalUnavailable || hasJournalLoss()) {
- return true;
- }
- let openBytes = 0;
- for (const inputProject of state.projects) {
- const projectId = resolveProjectId(inputProject.id);
- if (deletedProjectIds.has(projectId)) {
- continue;
- }
- if (localDraftFailures.has(projectDraftFailureKey(projectId))) {
- return true;
- }
- // Until a save serializes it, a loaded document's length: never more than its UTF-8 size.
- openBytes +=
- serializedDocumentBytes.get(projectId) ??
- volatileDrafts.get(projectId)?.documentByteSize ??
- syncEntries.get(projectId)?.pushedDoc.length ??
- 0;
- }
- return openBytes > PROJECT_UNLOAD_JOURNAL_MAX_BYTES;
- },
journalBeforeUnload: (state) => {
const target = unloadJournalTarget;
if (!target || !isJournalWritable() || owner.accountId === null) {
@@ -2758,25 +2810,44 @@ export const createDurableSyncedWorkbenchPersistence = (
continue;
}
const serialized = serializeProjectDocumentV3Json(project);
- serializedDocumentBytes.set(project.id, serialized.byteSize);
const journaled = journaledDocuments.get(project.id);
+ const journalIntent = captureJournalIdentity(project.id);
const isJournalStored = !retiredJournalProjectIds.has(project.id) && !settlingJournalProjectIds.has(project.id);
- if (serialized.documentJson === journaled?.documentJson && isJournalStored) {
+ if (
+ journaled &&
+ serialized.documentJson === journaled.documentJson &&
+ isJournalStored &&
+ isSameJournal(journaled, journalIntent)
+ ) {
continue;
}
if (isInRecovery(project.id, serialized.documentJson)) {
// Back to what recovery holds: the journal of a later state must not come back as a newer draft. The record
// stays, so the next save also settles it, should this blind deletion be lost.
- if (journaled && isJournalStored) {
- retired.push([project.id, journaled.editorSessionId, writerToken, journaled.generation]);
+ if (journaled) {
+ // Recovery may already hold a redo while its PUT waits: this checkpoint supersedes the journal's intent,
+ // even though it writes no new payload. Keep the physical entry's identity for later durable settlement.
+ if (isSameJournal(journaled, journalIntent)) {
+ const generation = nextGeneration(project.id);
+ issuedGenerations.set(project.id, generation);
+ retiredJournalIntents.set(project.id, { editorSessionId: journaled.editorSessionId, generation });
+ }
+ if (isJournalStored) {
+ retired.push([project.id, journaled.editorSessionId, writerToken, journaled.generation]);
+ }
}
continue;
}
// A stage of this very document that is still in flight shares its generation: whichever lands first, the
- // lineage ends with one copy, and the acknowledgement of that stage also settles the journal.
+ // lineage ends with one copy, and the acknowledgement of that stage also settles the journal. A later
+ // checkpoint or retirement advances the writer's generation, so an older stage must not lend its identity.
const staging = stagingDocuments.get(project.id);
const generation =
- staging?.documentJson === serialized.documentJson ? staging.generation : nextGeneration(project.id);
+ staging?.documentJson === serialized.documentJson &&
+ isJournalStored &&
+ staging.generation === issuedGenerations.get(project.id)
+ ? staging.generation
+ : nextGeneration(project.id);
if (serialized.byteSize > remainingBytes) {
skippedOversizedProjectIds.push(project.id);
unjournaledDocuments.set(project.id, generation - 1);
@@ -2810,7 +2881,6 @@ export const createDurableSyncedWorkbenchPersistence = (
: { kind: 'nothing-to-journal' };
}
const write = target.store.journalBeforeUnload({ entries, retired });
- isJournalUnavailable = write.kind !== 'started';
if (write.kind !== 'started') {
for (const entry of entries) {
unjournaledDocuments.set(entry.projectId, entry.generation - 1);
@@ -2936,9 +3006,8 @@ export const createDurableSyncedWorkbenchPersistence = (
projectResolutionFences.clear();
draftEditorSessionIds.clear();
journaledDocuments.clear();
+ retiredJournalIntents.clear();
unjournaledDocuments.clear();
- serializedDocumentBytes.clear();
- isJournalUnavailable = reconciledJournal.kind === 'unavailable';
retiredJournalProjectIds.clear();
settlingJournalProjectIds.clear();
localDraftFailures.clear();
@@ -3512,7 +3581,10 @@ export const createDurableSyncedWorkbenchPersistence = (
owned.draft.documentJson !== currentDocument.documentJson &&
owned.draft.generation <= invocationGeneration
) {
- await stageProject(inputProject, currentDocument);
+ const staged = await stageProject(inputProject, currentDocument, captureJournalIdentity(projectId));
+ if (!staged) {
+ throw new Error('The project changed while its copy was being prepared. Retry with the current project.');
+ }
owned = await requireDraft(projectId);
}
const { editorSessionId, store } = owned;
@@ -3880,16 +3952,20 @@ export const createDurableSyncedWorkbenchPersistence = (
}
assertOwner();
lastKnownState = applyProjectResolutionFences(state);
+ // Fence against journals created while this request waits in the queue or stages its snapshot.
+ const journalsAtRequest = new Map(
+ state.projects.map((project) => [resolveProjectId(project.id), captureJournalIdentity(project.id)] as const)
+ );
const capture = mapConcurrent(
state.projects.filter((project) => copyCaptureProjectIds.has(project.id)),
2,
async (inputProject) => {
- const plan = createProjectSavePlan(inputProject);
+ const plan = createProjectSavePlan(inputProject, journalsAtRequest.get(resolveProjectId(inputProject.id)));
if (!plan.needsStage) {
return;
}
try {
- await stageProject(plan.project, plan.serialized);
+ await stageProject(plan.project, plan.serialized, plan.journalAtRequest);
} catch {
return;
}
@@ -3901,14 +3977,19 @@ export const createDurableSyncedWorkbenchPersistence = (
assertOwner();
hasPending = sessionSavePending;
const currentState = lastKnownState ?? state;
- const plans = currentState.projects.map(createProjectSavePlan);
+ const plans = currentState.projects.map((project) =>
+ createProjectSavePlan(project, journalsAtRequest.get(resolveProjectId(project.id)))
+ );
const stagedProjects = new Map<string, Awaited<ReturnType<typeof stageProject>>>();
await mapConcurrent(plans, 2, async (plan) => {
if (!plan.needsStage || deletedProjectIds.has(plan.project.id)) {
return;
}
try {
- stagedProjects.set(plan.project.id, await stageProject(plan.project, plan.serialized));
+ stagedProjects.set(
+ plan.project.id,
+ await stageProject(plan.project, plan.serialized, plan.journalAtRequest)
+ );
} catch {
return;
}
diff --git a/invokeai/frontend/webv2/src/workbench/projects/unloadJournal.scenarios.ts b/invokeai/frontend/webv2/src/workbench/projects/unloadJournal.scenarios.ts
index 626625d84e..8e2b491b67 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/unloadJournal.scenarios.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/unloadJournal.scenarios.ts
@@ -2,6 +2,7 @@ import type { Project, WorkbenchState } from '@workbench/projectContracts';
import { createUuid } from '@platform/browser/randomUuid';
import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';
+import { RequestDeadlineError } from '@platform/transport/http';
import {
createDraftProject,
createInitialWorkbenchState,
@@ -536,6 +537,271 @@ export const testUnloadJournalScenarios = (createStore: () => Promise<ProjectDra
expect(recovered.state.projects).toMatchObject([{ id: project.id, name: 'Typed, undone, redone' }]);
});
+ it('keeps a redo journal distinct from the undo queued while its original stage is in flight', async () => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ const redone = named(loaded.state, 'Typed, undone, redone during stage');
+ const stage = store.stage;
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let started!: () => void;
+ const staging = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ store.stage = async (input) => {
+ const result = await stage(input);
+ started();
+ await gate;
+ return result;
+ };
+ const saving = tab.saveWorkbench(redone);
+ await staging;
+ tab.journalBeforeUnload(redone);
+ tab.journalBeforeUnload(loaded.state);
+ const undoing = tab.saveWorkbench(loaded.state);
+ tab.journalBeforeUnload(redone);
+ store.stage = stage;
+ release();
+ await Promise.all([saving, undoing]);
+ expect(serverName()).toBe(redone.projects[0]!.name);
+
+ // A normal save after the same-document acknowledgement must clear the superseded undo's pending marker.
+ await expect(tab.saveWorkbench(redone)).resolves.toMatchObject({ hasPendingChanges: false, shouldRetry: false });
+ // A new explicit undo captures the retired intent and is allowed to replace it.
+ await expect(tab.saveWorkbench(loaded.state)).resolves.toMatchObject({
+ hasPendingChanges: false,
+ shouldRetry: false,
+ });
+ expect(serverName()).toBe(project.name);
+ await expect(tab.saveWorkbench(redone)).resolves.toMatchObject({ hasPendingChanges: false, shouldRetry: false });
+ const reloaded = openTab();
+ const recovered = await reloaded.loadWorkbench();
+ expect(recovered.conflicts).toEqual([]);
+ expect(recovered.state.projects).toMatchObject([{ id: project.id, name: redone.projects[0]!.name }]);
+ });
+
+ it('fences a queued undo flush when redo retires its journal into an already staged document', async () => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ const redone = named(loaded.state, 'Durably staged redo');
+ const undone = named(loaded.state, 'Undo queued before redo');
+ let release!: () => void;
+ server.gate = new Promise((resolve) => {
+ release = resolve;
+ });
+ const saving = tab.saveWorkbench(redone);
+ await vi.waitFor(() => expect(server.updates).toBe(1));
+ // The PUT is held after staging; this redo is already safe in the draft store.
+ const staged = await store.get(project.id, 'tab-a');
+ expect(staged.kind).toBe('found');
+ if (staged.kind === 'found') {
+ expect(JSON.parse(staged.draft.documentJson)).toMatchObject({ name: 'Durably staged redo' });
+ }
+ tab.journalBeforeUnload(undone);
+ const staleFlush = tab.flushProjectToServer(undone.projects[0]!);
+ tab.journalBeforeUnload(redone);
+ server.gate = null;
+ release();
+ await saving;
+ await expect(staleFlush).resolves.toMatchObject({ kind: 'unsynced' });
+ expect(serverName()).toBe('Durably staged redo');
+ expect(server.updates).toBe(1);
+ await expect(store.listForProject(project.id)).resolves.toMatchObject({ items: [] });
+
+ // Even a lost blind retirement must be made durable by the next ordinary save of the recovery document.
+ failEveryJournalDeletion();
+ await expect(tab.saveWorkbench(redone)).resolves.toMatchObject({ hasPendingChanges: false, shouldRetry: false });
+ failEveryJournalDeletion();
+ const reloaded = openTab();
+ const recovered = await reloaded.loadWorkbench();
+ expect(recovered.conflicts).toEqual([]);
+ expect(recovered.state.projects).toMatchObject([{ id: project.id, name: 'Durably staged redo' }]);
+ await expect(reloaded.saveWorkbench(undone)).resolves.toMatchObject({ hasPendingChanges: false });
+ expect(serverName()).toBe('Undo queued before redo');
+ await expect(reloaded.saveWorkbench(redone)).resolves.toMatchObject({ hasPendingChanges: false });
+ expect(serverName()).toBe('Durably staged redo');
+ });
+
+ it.each(['unavailable', 'aborted'] as const)(
+ 'renews a checkpoint matching the physical journal after its retirement was %s',
+ async (failure) => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ const staged = named(loaded.state, 'Staged before retirement');
+ const latest = named(loaded.state, 'Latest after storage recovered');
+ let release!: () => void;
+ server.gate = new Promise((resolve) => {
+ release = resolve;
+ });
+ const saving = tab.saveWorkbench(staged);
+ await vi.waitFor(() => expect(server.updates).toBe(1));
+ const firstJournal = tab.journalBeforeUnload(latest);
+ expect(firstJournal.kind).toBe('journaled');
+ if (firstJournal.kind === 'journaled') {
+ expect(await firstJournal.written).toBe(true);
+ }
+ const journal = store.journalBeforeUnload;
+ store.journalBeforeUnload = () =>
+ failure === 'unavailable' ? { kind: 'unavailable' } : { kind: 'started', written: Promise.resolve(false) };
+ const retirement = tab.journalBeforeUnload(staged);
+ expect(retirement.kind).toBe(failure === 'unavailable' ? 'unavailable' : 'journaled');
+ if (retirement.kind === 'journaled') {
+ expect(await retirement.written).toBe(false);
+ }
+ store.journalBeforeUnload = journal;
+ const staleFlush = tab.flushProjectToServer(staged.projects[0]!);
+ // Storage now works; the old physical bytes are a new intent after the attempted retirement.
+ const checkpoint = tab.journalBeforeUnload(latest);
+ server.gate = null;
+ release();
+ await saving;
+ await expect(staleFlush).resolves.toMatchObject({ kind: 'unsynced' });
+ expect(checkpoint).toMatchObject({ kind: 'journaled', projectIds: [project.id] });
+ if (checkpoint.kind === 'journaled') {
+ expect(await checkpoint.written).toBe(true);
+ }
+ expect(server.updates).toBe(1);
+ const reloaded = openTab();
+ const recovered = await reloaded.loadWorkbench();
+ expect(recovered.conflicts).toEqual([]);
+ expect(recovered.state.projects).toMatchObject([{ id: project.id, name: 'Latest after storage recovered' }]);
+ await expect(reloaded.saveWorkbench(recovered.state)).resolves.toMatchObject({ hasPendingChanges: false });
+ expect(serverName()).toBe('Latest after storage recovered');
+ }
+ );
+
+ it('journals the latest checkpoint above an older same-document stage and intervening journal', async () => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ const latest = named(loaded.state, 'Latest matches the pending stage');
+ const intervening = named(loaded.state, 'Intervening checkpoint');
+ const stage = store.stage;
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let started!: () => void;
+ const staging = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ store.stage = async (input) => {
+ const result = await stage(input);
+ started();
+ await gate;
+ return result;
+ };
+ const saving = tab.flushProjectToServer(latest.projects[0]!);
+ await staging;
+ tab.journalBeforeUnload(intervening);
+ const checkpoint = tab.journalBeforeUnload(latest);
+ store.stage = stage;
+ release();
+ await saving;
+ expect(checkpoint).toMatchObject({ kind: 'journaled', projectIds: [project.id] });
+ if (checkpoint.kind === 'journaled') {
+ expect(await checkpoint.written).toBe(true);
+ }
+ const reloaded = openTab();
+ const recovered = await reloaded.loadWorkbench();
+ expect(recovered.conflicts).toEqual([]);
+ expect(recovered.state.projects).toMatchObject([{ id: project.id, name: 'Latest matches the pending stage' }]);
+ await expect(reloaded.saveWorkbench(recovered.state)).resolves.toMatchObject({ hasPendingChanges: false });
+ expect(serverName()).toBe('Latest matches the pending stage');
+ });
+
+ it('keeps a redo in recovery while a different document finishes staging', async () => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ const redone = named(loaded.state, 'Acknowledged redo');
+ const undone = named(loaded.state, 'Undo staging during redo');
+ await tab.saveWorkbench(redone);
+ tab.journalBeforeUnload(undone);
+ const stage = store.stage;
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let started!: () => void;
+ const staging = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ store.stage = async (input) => {
+ const result = await stage(input);
+ started();
+ await gate;
+ return result;
+ };
+ const undoing = tab.flushProjectToServer(undone.projects[0]!);
+ await staging;
+ tab.journalBeforeUnload(redone);
+ store.stage = stage;
+ release();
+ await undoing;
+
+ // There is no later save before unload: the checkpoint must itself preserve the redo over the finishing stage.
+ const reloaded = openTab();
+ const recovered = await reloaded.loadWorkbench();
+ expect(recovered.conflicts).toEqual([]);
+ expect(recovered.state.projects).toMatchObject([{ id: project.id, name: 'Acknowledged redo' }]);
+ await expect(reloaded.saveWorkbench(recovered.state)).resolves.toMatchObject({ hasPendingChanges: false });
+ expect(serverName()).toBe('Acknowledged redo');
+ });
+
+ it('fences a queued undo flush while a recovery-only redo settles its old journal', async () => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ const redone = named(loaded.state, 'Already saved redo');
+ const undone = named(loaded.state, 'Undo captured before settlement');
+ await tab.saveWorkbench(redone);
+ tab.journalBeforeUnload(undone);
+ let release!: () => void;
+ settleGate = new Promise((resolve) => {
+ release = resolve;
+ });
+ const settling = tab.flushProjectToServer(redone.projects[0]!);
+ await vi.waitFor(() => expect(settlesStarted).toBe(1));
+ const staleFlush = tab.flushProjectToServer(undone.projects[0]!);
+ tab.journalBeforeUnload(redone);
+ settleGate = null;
+ release();
+ await expect(settling).resolves.toMatchObject({ kind: 'acknowledged' });
+ await expect(staleFlush).resolves.toMatchObject({ kind: 'unsynced' });
+ expect(serverName()).toBe('Already saved redo');
+ expect(server.updates).toBe(1);
+ const recovered = await openTab().loadWorkbench();
+ expect(recovered.conflicts).toEqual([]);
+ expect(recovered.state.projects).toMatchObject([{ id: project.id, name: 'Already saved redo' }]);
+ });
+
+ it.each(['content', 'content and workspace'] as const)(
+ 'does not rewrite an undo-retired journal when older %s acknowledges',
+ async (halves) => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ const content = named(loaded.state, 'Saved before the undo');
+ const saved = halves === 'content' ? content : prompted(content, 'Saved workspace before the undo');
+ let release!: () => void;
+ server.gate = new Promise((resolve) => {
+ release = resolve;
+ });
+ const saving = tab.saveWorkbench(saved);
+ await vi.waitFor(() => expect(server.updates).toBe(1));
+ tab.journalBeforeUnload(named(loaded.state, 'Typed, then undone'));
+ tab.journalBeforeUnload(saved);
+ server.gate = null;
+ release();
+ await saving;
+
+ const recovered = await openTab().loadWorkbench();
+ expect(recovered.conflicts).toEqual([]);
+ expect(serializeProjectDocumentV3(recovered.state.projects[0]!)).toEqual(
+ serializeProjectDocumentV3(saved.projects[0]!)
+ );
+ }
+ );
+
it('journals an edit redone while its earlier journal was being settled', async () => {
const tab = openTab();
const loaded = await tab.loadWorkbench();
@@ -557,6 +823,130 @@ export const testUnloadJournalScenarios = (createStore: () => Promise<ProjectDra
expect(recovered.state.projects).toMatchObject([{ id: project.id, name: 'Typed, undone, redone' }]);
});
+ it('keeps the latest journal and workspace conflict when the recovered merge cannot be staged', async () => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ const remote = prompted(loaded.state, 'Workspace saved elsewhere');
+ const record = server.records.get(project.id)!;
+ const workspace = splitProjectDocument(serializeProjectDocumentV3(remote.projects[0]!)).workspace;
+ server.records.set(project.id, {
+ ...record,
+ workspace: { data: workspace as unknown as Record<string, unknown>, revision: 2, updated_at: now },
+ });
+ const local = prompted(loaded.state, 'Workspace edited here');
+ await expect(tab.saveWorkbench(local)).resolves.toMatchObject({ conflicts: [{ half: 'workspace' }] });
+ const stage = store.stage;
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let started!: () => void;
+ const staging = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ store.stage = async () => {
+ started();
+ await gate;
+ return { kind: 'fenced' };
+ };
+ const resolving = tab.resolveConflictUseServer(project.id);
+ const rejected = expect(resolving).rejects.toMatchObject({
+ name: 'ProjectDraftWriteRejectedError',
+ reason: 'fenced',
+ });
+ await staging;
+ // The existing conflict was resumed successfully before the merge's stage failed.
+ await expect(store.get(project.id, 'tab-a')).resolves.toMatchObject({ draft: { state: 'dirty' } });
+ const latest = named(local, 'Typed while workspace recovery waited');
+ const journal = tab.journalBeforeUnload(latest);
+ expect(journal.kind).toBe('journaled');
+ if (journal.kind === 'journaled') {
+ expect(await journal.written).toBe(true);
+ }
+ store.stage = stage;
+ release();
+ await rejected;
+ expect(server.updates).toBe(0);
+ expect(server.workspaceUpdates).toBe(1);
+ expect(server.creates).toBe(0);
+ expect(server.records.get(project.id)?.workspace).toMatchObject({
+ data: { promptHistory: [{ positivePrompt: 'Workspace saved elsewhere' }] },
+ revision: 2,
+ });
+ await expect(store.get(project.id, 'tab-a')).resolves.toMatchObject({ draft: { state: 'conflict' } });
+ expect(getProjectSyncSnapshot().projects[project.id]?.conflict).toMatchObject({ half: 'workspace' });
+
+ const reloaded = openTab();
+ const recovered = await reloaded.loadWorkbench();
+ expect(recovered.conflicts).toMatchObject([{ half: 'workspace' }]);
+ expect(recovered.state.projects).toMatchObject([{ name: 'Typed while workspace recovery waited' }]);
+ const retried = await reloaded.resolveConflictUseServer(project.id);
+ expect(retried.status).toBe('loaded');
+ if (retried.status !== 'loaded') {
+ throw new Error('Expected workspace recovery to remain available.');
+ }
+ reloaded.acknowledgeProjectResolution(project.id);
+ await expect(reloaded.saveWorkbench(stateWith([retried.project]))).resolves.toMatchObject({
+ conflicts: [],
+ hasPendingChanges: false,
+ });
+ expect(serverName()).toBe('Typed while workspace recovery waited');
+ expect(retried.project.promptHistory).toEqual(remote.projects[0]!.promptHistory);
+ });
+
+ it('keeps the latest journal and source conflict when preparing a copy is fenced', async () => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ saveElsewhere('Saved elsewhere', 2);
+ const local = named(loaded.state, 'Conflicted local edit');
+ await expect(tab.saveWorkbench(local)).resolves.toMatchObject({ conflicts: [{ kind: 'revision' }] });
+ const stage = store.stage;
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let started!: () => void;
+ const staging = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ store.stage = async () => {
+ started();
+ await gate;
+ return { kind: 'fenced' };
+ };
+ const copying = tab.resolveConflictSaveAsNew(named(local, 'Edit selected for copying').projects[0]!);
+ const rejected = expect(copying).rejects.toMatchObject({
+ name: 'ProjectDraftWriteRejectedError',
+ reason: 'fenced',
+ });
+ await staging;
+ const latest = named(local, 'Typed while copy preparation waited');
+ const journal = tab.journalBeforeUnload(latest);
+ expect(journal.kind).toBe('journaled');
+ if (journal.kind === 'journaled') {
+ expect(await journal.written).toBe(true);
+ }
+ store.stage = stage;
+ release();
+ await rejected;
+ expect(copiesStarted).toBe(0);
+ expect(server.creates).toBe(0);
+ expect(serverName()).toBe('Saved elsewhere');
+ expect(server.updates).toBe(1);
+ await expect(store.get(project.id, 'tab-a')).resolves.toMatchObject({ draft: { state: 'conflict' } });
+ expect(getProjectSyncSnapshot().projects[project.id]?.conflict).toMatchObject({ kind: 'revision' });
+
+ const reloaded = openTab();
+ const recovered = await reloaded.loadWorkbench();
+ expect(recovered.conflicts).toMatchObject([{ kind: 'revision' }]);
+ expect(recovered.state.projects).toMatchObject([{ name: 'Typed while copy preparation waited' }]);
+ const retried = await reloaded.resolveConflictSaveAsNew(recovered.state.projects[0]!);
+ expect(copiesStarted).toBe(1);
+ expect(server.creates).toBe(1);
+ expect(server.records.get(retried.targetProjectId)?.data.name).toBe('Typed while copy preparation waited (copy)');
+ expect(serverName()).toBe('Saved elsewhere');
+ });
+
describe('a hidden event during save-as-new', () => {
const startCopy = async () => {
const tab = openTab();
@@ -655,6 +1045,266 @@ export const testUnloadJournalScenarios = (createStore: () => Promise<ProjectDra
expect(server.records.get(project.id)).toMatchObject({ name: 'Saved', revision: 2 });
});
+ it('keeps an edit journaled while an older save is still staging before its push begins', async () => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ const stage = store.stage;
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let started!: () => void;
+ const staged = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ store.stage = async (input) => {
+ const result = await stage(input);
+ started();
+ await gate;
+ return result;
+ };
+ const saving = tab.saveWorkbench(prompted(loaded.state, 'Captured before the edit'));
+ await staged;
+ try {
+ const journal = tab.journalBeforeUnload(prompted(loaded.state, 'Held edit during stage'));
+ expect(journal.kind).toBe('journaled');
+ if (journal.kind === 'journaled') {
+ expect(await journal.written).toBe(true);
+ }
+ } finally {
+ store.stage = stage;
+ release();
+ }
+ await saving;
+
+ const recovered = await openTab().loadWorkbench();
+ expect(recovered.conflicts).toEqual([]);
+ expect(recovered.state.projects).toMatchObject([
+ { id: project.id, promptHistory: [{ positivePrompt: 'Held edit during stage' }] },
+ ]);
+ });
+
+ it.each(['workbench save', 'project flush'] as const)(
+ 'keeps a newer held edit when an older %s was queued before its journal',
+ async (request) => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ let release!: () => void;
+ server.gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const first = tab.saveWorkbench(prompted(loaded.state, 'First save'));
+ await vi.waitFor(() => expect(server.workspaceUpdates).toBe(1));
+ const queuedState = prompted(loaded.state, 'Queued before the edit');
+ const queued =
+ request === 'workbench save'
+ ? tab.saveWorkbench(queuedState)
+ : tab.flushProjectToServer(queuedState.projects[0]!);
+ try {
+ const journal = tab.journalBeforeUnload(prompted(loaded.state, 'Held edit after queueing'));
+ expect(journal.kind).toBe('journaled');
+ if (journal.kind === 'journaled') {
+ expect(await journal.written).toBe(true);
+ }
+ } finally {
+ server.gate = null;
+ release();
+ }
+ await Promise.all([first, queued]);
+
+ const recovered = await openTab().loadWorkbench();
+ expect(recovered.conflicts).toEqual([]);
+ expect(recovered.state.projects).toMatchObject([
+ { id: project.id, promptHistory: [{ positivePrompt: 'Held edit after queueing' }] },
+ ]);
+ }
+ );
+
+ it.each(['workbench save', 'project flush'] as const)(
+ 'acknowledges an undo after a journal superseded an older %s before staging',
+ async (request) => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ const older = prompted(loaded.state, 'Captured before the held edit');
+ const saving =
+ request === 'workbench save' ? tab.saveWorkbench(older) : tab.flushProjectToServer(older.projects[0]!);
+ const journal = tab.journalBeforeUnload(prompted(loaded.state, 'Held edit, then undone'));
+ expect(journal.kind).toBe('journaled');
+ if (journal.kind === 'journaled') {
+ expect(await journal.written).toBe(true);
+ }
+ await expect(saving).resolves.toMatchObject(
+ request === 'project flush' ? { kind: 'unsynced' } : { shouldRetry: true }
+ );
+ await expect(store.listForProject(project.id)).resolves.toMatchObject({ items: [] });
+
+ // The explicit undo is already what the server holds, so it owes neither a draft nor a push.
+ await expect(tab.saveWorkbench(loaded.state)).resolves.toMatchObject({
+ hasPendingChanges: false,
+ shouldRetry: false,
+ });
+ await expect(tab.flushProjectToServer(loaded.state.projects[0]!)).resolves.toMatchObject({
+ kind: 'acknowledged',
+ });
+ await tab.persistEmptySession(loaded.state);
+ failEveryJournalDeletion();
+ const recovered = await openTab().loadWorkbench();
+ expect(recovered.state.projects.map(({ id }) => id)).not.toContain(project.id);
+ expect(server.workspaceUpdates).toBe(0);
+ }
+ );
+
+ it('does not create an upload identity from a snapshot superseded by a held edit', async () => {
+ const tab = openTab();
+ await tab.loadWorkbench();
+ const draft = createDraftProject([project]);
+ const ensuring = tab.ensureProjectOnServer(draft);
+ const rejected = expect(ensuring).rejects.toMatchObject({ reason: 'unsynced' });
+ const newer = stateWith([{ ...draft, name: 'Held before creation' }]);
+ const journal = tab.journalBeforeUnload(newer);
+ expect(journal.kind).toBe('journaled');
+ if (journal.kind === 'journaled') {
+ expect(await journal.written).toBe(true);
+ }
+ await rejected;
+ expect(server.creates).toBe(0);
+ expect(server.records.has(draft.id)).toBe(false);
+
+ // Autosave of the newer intent creates its identity; upload retries can then use it immediately.
+ await expect(tab.saveWorkbench(newer)).resolves.toMatchObject({ hasPendingChanges: false });
+ await expect(tab.ensureProjectOnServer(draft)).resolves.toBeUndefined();
+ failEveryJournalDeletion();
+ const recovered = await openTab().loadWorkbench();
+ expect(recovered.conflicts).toEqual([]);
+ expect(recovered.state.projects).toMatchObject([{ id: draft.id, name: 'Held before creation' }]);
+ expect(server.creates).toBe(1);
+ });
+
+ it.each(['content', 'workspace'] as const)(
+ 'saves a newer journaled %s after an older save acknowledges without reviving either journal',
+ async (half) => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ const edit = half === 'content' ? named : prompted;
+ let release!: () => void;
+ server.gate = new Promise((resolve) => {
+ release = resolve;
+ });
+ const older = tab.saveWorkbench(edit(loaded.state, 'Older save'));
+ await vi.waitFor(() => expect(half === 'content' ? server.updates : server.workspaceUpdates).toBe(1));
+ const latest = edit(loaded.state, 'Newer held edit');
+ tab.journalBeforeUnload(latest);
+ const newer = tab.saveWorkbench(latest);
+ server.gate = null;
+ release();
+ await older;
+ await expect(newer).resolves.toMatchObject({ hasPendingChanges: false, shouldRetry: false });
+ const record = server.records.get(project.id)!;
+ expect(half === 'content' ? record.name : record.workspace?.data.promptHistory).toEqual(
+ half === 'content' ? 'Newer held edit' : [{ negativePrompt: null, positivePrompt: 'Newer held edit' }]
+ );
+ expect(half === 'content' ? record.revision : record.workspace?.revision).toBe(3);
+ failEveryJournalDeletion();
+ const recovered = await openTab().loadWorkbench();
+ expect(recovered.conflicts).toEqual([]);
+ expect(serializeProjectDocumentV3(recovered.state.projects[0]!)).toEqual(
+ serializeProjectDocumentV3(latest.projects[0]!)
+ );
+ await expect(store.listForProject(project.id)).resolves.toMatchObject({ items: [] });
+ }
+ );
+
+ it('finishes a save when the same document is journaled during its asynchronous setup', async () => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ const edited = prompted(loaded.state, 'The same held edit');
+ const saving = tab.saveWorkbench(edited);
+ const journal = tab.journalBeforeUnload(edited);
+ expect(journal.kind).toBe('journaled');
+ if (journal.kind === 'journaled') {
+ expect(await journal.written).toBe(true);
+ }
+ const result = await saving;
+ expect(result.hasPendingChanges).toBe(false);
+ expect(result.shouldRetry).toBe(false);
+ expect(await store.peekUnloadJournalProjectIds(1)).toMatchObject({ kind: 'available', projectIds: [] });
+ const recovered = await openTab().loadWorkbench();
+ expect(recovered.state.projects).toMatchObject([
+ { id: project.id, promptHistory: [{ positivePrompt: 'The same held edit' }] },
+ ]);
+ });
+
+ it.each(['content', 'workspace'] as const)(
+ 'keeps a newer journal across timeout reconciliation of older %s and fences its queued undo',
+ async (half) => {
+ const tab = openTab();
+ const loaded = await tab.loadWorkbench();
+ const edit = half === 'content' ? named : prompted;
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let started!: () => void;
+ const committed = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const timeOutAfterCommit = async (): Promise<never> => {
+ started();
+ await gate;
+ throw new RequestDeadlineError();
+ };
+ let restore: () => void;
+ if (half === 'content') {
+ const update = api.updateProject;
+ api.updateProject = async (...args) => {
+ await update(...args);
+ return timeOutAfterCommit();
+ };
+ restore = () => {
+ api.updateProject = update;
+ };
+ } else {
+ const update = api.saveProjectWorkspace;
+ api.saveProjectWorkspace = async (...args) => {
+ await update(...args);
+ return timeOutAfterCommit();
+ };
+ restore = () => {
+ api.saveProjectWorkspace = update;
+ };
+ }
+ const saving = tab.saveWorkbench(edit(loaded.state, 'Committed before its response timed out'));
+ await committed;
+ const undoing = tab.flushProjectToServer(loaded.state.projects[0]!);
+ const latest = edit(loaded.state, 'Newer held edit during timeout');
+ const journal = tab.journalBeforeUnload(latest);
+ expect(journal.kind).toBe('journaled');
+ if (journal.kind === 'journaled') {
+ expect(await journal.written).toBe(true);
+ }
+ restore();
+ release();
+ await expect(saving).resolves.toMatchObject({ conflicts: [], shouldRetry: false });
+ await expect(undoing).resolves.toMatchObject({ kind: 'unsynced' });
+ expect(half === 'content' ? server.updates : server.workspaceUpdates).toBe(1);
+
+ const reloaded = openTab();
+ const recovered = await reloaded.loadWorkbench();
+ expect(recovered.conflicts).toEqual([]);
+ expect(serializeProjectDocumentV3(recovered.state.projects[0]!)).toEqual(
+ serializeProjectDocumentV3(latest.projects[0]!)
+ );
+ await expect(reloaded.saveWorkbench(recovered.state)).resolves.toMatchObject({ hasPendingChanges: false });
+ const saved = server.records.get(project.id)!;
+ expect(half === 'content' ? saved.name : saved.workspace?.data.promptHistory).toEqual(
+ half === 'content'
+ ? 'Newer held edit during timeout'
+ : [{ negativePrompt: null, positivePrompt: 'Newer held edit during timeout' }]
+ );
+ expect(half === 'content' ? saved.revision : saved.workspace?.revision).toBe(3);
+ }
+ );
+
it('keeps a newer journal across an older acknowledgement, rebased onto it', async () => {
const tab = openTab();
const loaded = await tab.loadWorkbench();