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.

test(a11y): gate representative journeys

joshistoast5c5417c13638
diff --git a/invokeai/frontend/webv2/.oxlintrc.json b/invokeai/frontend/webv2/.oxlintrc.json
index aba3b3877a..b0cc5d578e 100644
--- a/invokeai/frontend/webv2/.oxlintrc.json
+++ b/invokeai/frontend/webv2/.oxlintrc.json
@@ -1,6 +1,6 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
- "plugins": ["typescript", "react", "import", "unicorn", "oxc", "react-perf", "eslint"],
+ "plugins": ["typescript", "react", "import", "unicorn", "oxc", "react-perf", "jsx-a11y", "eslint"],
"categories": {
"correctness": "error"
},
@@ -57,6 +57,13 @@
"react-hooks/exhaustive-deps": "error",
"react-hooks/rules-of-hooks": "error",
+ // Invoke's Chakra/Ark composites deliberately use ARIA listbox, option,
+ // separator, and status semantics on polymorphic primitives. Replacing
+ // those primitives with the rule's suggested native tags would break the
+ // owning composite's keyboard/focus contract; Axe journeys validate the
+ // resulting accessibility tree instead.
+ "jsx-a11y/prefer-tag-over-role": "off",
+
"react-perf/jsx-no-new-object-as-prop": [
"error",
{
@@ -113,6 +120,42 @@
"vitest/require-mock-type-parameters": "off"
},
+ "overrides": [
+ {
+ // These are focus-managed entry points. Autofocus is intentional and
+ // scoped to an opened dialog, an auth screen, or an inline rename so
+ // keyboard users land on the only immediate task.
+ "files": [
+ "src/features/gallery/ui/GalleryBoardMenu.tsx",
+ "src/features/identity/ui/LoginScreen.tsx",
+ "src/features/identity/ui/SetupScreen.tsx",
+ "src/features/identity/ui/UserFormDialog.tsx",
+ "src/features/workflow/ui/editor/AddNodeDialog.tsx",
+ "src/features/workflow/ui/editor/InvocationFlowNode.tsx",
+ "src/platform/ui/RenameDialog.tsx",
+ "src/workbench/palette/CommandPaletteDialog.tsx",
+ "src/workbench/widgets/layers/LayerListItem.tsx"
+ ],
+ "rules": {
+ "jsx-a11y/no-autofocus": "off"
+ }
+ },
+ {
+ // Oxlint cannot see the focusable DOM produced by Chakra Button/Input/
+ // Menu primitives. Palette options are the other intentional case:
+ // focus stays on their aria-activedescendant combobox by design.
+ "files": [
+ "src/features/models/ui/components/ModelSelect.tsx",
+ "src/features/models/ui/shared/ModelFilterMenu.tsx",
+ "src/features/workflow/ui/editor/AddNodeDialog.tsx",
+ "src/workbench/palette/CommandPaletteDialog.tsx",
+ "src/workbench/palette/CommandPaletteRows.tsx"
+ ],
+ "rules": {
+ "jsx-a11y/interactive-supports-focus": "off"
+ }
+ }
+ ],
"env": {
"browser": true,
"builtin": true,
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index d22b5932e5..47d980e35f 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -15,13 +15,17 @@
"i18n:report": "node scripts/i18n-report.mjs",
"i18n:report:verbose": "node scripts/i18n-report.mjs --verbose",
"lint": "pnpm run format:check && pnpm run lint:oxc && pnpm run lint:tsc && pnpm run architecture:check",
- "lint:oxc": "oxlint --react-plugin --import-plugin --deny-warnings .",
- "lint:oxc:fix": "oxlint --react-plugin --import-plugin --fix .",
+ "lint:oxc": "oxlint --react-plugin --import-plugin --jsx-a11y-plugin --deny-warnings .",
+ "lint:oxc:fix": "oxlint --react-plugin --import-plugin --jsx-a11y-plugin --fix .",
"lint:tsc": "tsc --noEmit",
"preview": "vite preview",
"test": "vitest run --config vitest.config.mts",
- "test:all": "pnpm run test && pnpm run test:browser",
+ "test:accessibility": "pnpm run test:accessibility:build && pnpm run test:accessibility:browser",
+ "test:accessibility:browser": "node scripts/run-accessibility-journeys.mjs",
+ "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:fixtures": "node --test scripts/mock-backend-fixtures.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:update-baseline": "node scripts/measure-architecture-performance.mjs --update-baseline",
@@ -63,6 +67,7 @@
"@types/use-sync-external-store": "^1.5.0",
"@vitejs/plugin-react": "^6.0.3",
"@vitest/browser-playwright": "4.1.10",
+ "axe-core": "^4.12.1",
"babel-plugin-react-compiler": "^1.0.0",
"oxfmt": "^0.59.0",
"oxlint": "^1.74.0",
diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yaml
index 15a719d98c..d0d5c9e9fc 100644
--- a/invokeai/frontend/webv2/pnpm-lock.yaml
+++ b/invokeai/frontend/webv2/pnpm-lock.yaml
@@ -108,6 +108,9 @@ importers:
'@vitest/browser-playwright':
specifier: 4.1.10
+ axe-core:
+ specifier: ^4.12.1
+ version: 4.12.1
babel-plugin-react-compiler:
specifier: ^1.0.0
version: 1.0.0
@@ -1373,6 +1376,10 @@ packages:
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-s7iGf5GaVMxEG0ENN9x+xTr7GFZCb1ZP/1uATUpCEK2X78nDB3RwbtFCo9pGAf9ru+VwoQ464DkaLEeRM08wJA==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-Cg7TFGpIr01vOQNODXOOaGz2NpCU5gl8x1qJFbb6hbZxR7XrcE2vtbAsTAbJ7/xwJtUuJEw8K8Zr/AE0LHlesg==}
engines: {node: '>=10', npm: '>=6'}
@@ -3534,6 +3541,8 @@ snapshots:
+
dependencies:
'@babel/runtime': 7.29.7
diff --git a/invokeai/frontend/webv2/scripts/accessibility/axe.mjs b/invokeai/frontend/webv2/scripts/accessibility/axe.mjs
new file mode 100644
index 0000000000..5f43868be2
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/accessibility/axe.mjs
@@ -0,0 +1,69 @@
+import { createRequire } from 'node:module';
+
+const require = createRequire(import.meta.url);
+const axeScriptPath = require.resolve('axe-core/axe.min.js');
+
+export const WCAG_RELEASE_TAGS = Object.freeze(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22a', 'wcag22aa']);
+
+export const injectAxe = async (page) => {
+ const isLoaded = await page.evaluate(() => typeof window.axe?.run === 'function');
+
+ if (!isLoaded) {
+ await page.addScriptTag({ path: axeScriptPath });
+ }
+};
+
+export const runAxe = async (page, { exclude = [], include = [], runOnly = WCAG_RELEASE_TAGS, rules = {} } = {}) => {
+ await injectAxe(page);
+
+ return page.evaluate(
+ ({ excludeSelectors, includeSelectors, ruleConfiguration, tags }) => {
+ const context =
+ includeSelectors.length > 0 || excludeSelectors.length > 0
+ ? {
+ exclude: excludeSelectors.map((selector) => [selector]),
+ include: (includeSelectors.length > 0 ? includeSelectors : ['html']).map((selector) => [selector]),
+ }
+ : document;
+
+ return window.axe.run(context, {
+ resultTypes: ['violations'],
+ rules: ruleConfiguration,
+ runOnly: { type: 'tag', values: tags },
+ });
+ },
+ {
+ excludeSelectors: exclude,
+ includeSelectors: include,
+ ruleConfiguration: rules,
+ tags: runOnly,
+ }
+ );
+};
+
+const formatNode = (node) => {
+ const target = node.target.join(' ');
+ const summary = node.failureSummary?.replaceAll(/\s+/g, ' ').trim();
+ const html = node.html.replaceAll(/\s+/g, ' ').trim();
+
+ return [` ${target}`, ` ${html}`, summary ? ` ${summary}` : null].filter(Boolean).join('\n');
+};
+
+export const formatAxeViolations = (surface, violations) =>
+ [
+ `${surface} has ${violations.length} Axe violation${violations.length === 1 ? '' : 's'}:`,
+ ...violations.flatMap((violation) => [
+ ` [${violation.impact ?? 'unknown'}] ${violation.id}: ${violation.help} (${violation.helpUrl})`,
+ ...violation.nodes.map(formatNode),
+ ]),
+ ].join('\n');
+
+export const assertNoAxeViolations = async (page, surface, options) => {
+ const results = await runAxe(page, options);
+
+ if (results.violations.length > 0) {
+ throw new Error(formatAxeViolations(surface, results.violations));
+ }
+
+ return results;
+};
diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
new file mode 100644
index 0000000000..44053e0021
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
@@ -0,0 +1,517 @@
+/**
+ * Deterministic synthetic data for browser release and performance journeys.
+ *
+ * Keep this module free of browser and server dependencies: harnesses can
+ * import the same builders to validate their workload without starting HTTP.
+ * Every generated value is derived from an index and a fixed epoch, so resets
+ * are byte-identical and checked-in baselines never depend on wall-clock time.
+ */
+
+export const MOCK_BACKEND_PROFILE_NAMES = Object.freeze(['empty', 'representative']);
+
+export const MOCK_BACKEND_PROFILE_COUNTS = Object.freeze({
+ empty: Object.freeze({
+ images: 0,
+ layers: 0,
+ models: 0,
+ nodes: 0,
+ projects: 0,
+ queueItems: 0,
+ workflowNodes: 0,
+ }),
+ representative: Object.freeze({
+ images: 1_000,
+ layers: 64,
+ models: 100,
+ nodes: 100,
+ projects: 40,
+ queueItems: 500,
+ workflowNodes: 100,
+ }),
+});
+
+export const MOCK_BACKEND_FIXED_EPOCH = '2026-01-15T12:00:00.000Z';
+
+const FIXED_EPOCH_MS = Date.parse(MOCK_BACKEND_FIXED_EPOCH);
+const range = (length, build) => Array.from({ length }, (_, index) => build(index));
+const ordinal = (index, width = 3) => String(index + 1).padStart(width, '0');
+const timestampAt = (index) => new Date(FIXED_EPOCH_MS - index * 60_000).toISOString();
+
+export const isMockBackendProfileName = (value) => MOCK_BACKEND_PROFILE_NAMES.includes(value);
+
+export const assertMockBackendProfileName = (value) => {
+ if (!isMockBackendProfileName(value)) {
+ throw new TypeError(
+ `Unknown mock-backend profile ${JSON.stringify(value)}. Expected one of ${MOCK_BACKEND_PROFILE_NAMES.join(', ')}.`
+ );
+ }
+
+ return value;
+};
+
+const createImages = (count) =>
+ range(count, (index) => {
+ const id = ordinal(index, 4);
+ const imageName = `fixture-image-${id}.png`;
+ const boardIndex = index % 10;
+ const imageCategory = index % 10 === 0 ? 'control' : 'general';
+
+ return {
+ board_id: index % 8 === 0 ? null : `fixture-board-${ordinal(boardIndex, 2)}`,
+ created_at: timestampAt(index),
+ height: 512 + (index % 3) * 64,
+ image_category: imageCategory,
+ image_name: imageName,
+ image_url: `/api/v1/images/i/${imageName}/full`,
+ is_intermediate: false,
+ starred: index % 11 === 0,
+ thumbnail_url: `/api/v1/images/i/${imageName}/thumbnail`,
+ width: 512 + (index % 4) * 64,
+ };
+ });
+
+const createBoards = (images) =>
+ range(10, (index) => {
+ const boardId = `fixture-board-${ordinal(index, 2)}`;
+ const boardImages = images.filter((image) => image.board_id === boardId);
+
+ return {
+ archived: false,
+ asset_count: boardImages.filter((image) => image.image_category !== 'general').length,
+ board_id: boardId,
+ board_name: `Fixture Board ${ordinal(index, 2)}`,
+ cover_image_name: boardImages[0]?.image_name ?? null,
+ created_at: timestampAt(index * 10),
+ image_count: boardImages.filter((image) => image.image_category === 'general').length,
+ owner_username: null,
+ };
+ });
+
+const QUEUE_STATUSES = ['pending', 'waiting', 'in_progress', 'completed', 'failed', 'canceled'];
+
+const createQueueItems = (count) =>
+ range(count, (index) => {
+ const itemId = index + 1;
+ const status = QUEUE_STATUSES[index % QUEUE_STATUSES.length];
+ const createdAt = timestampAt(index);
+ const isSettled = status === 'completed' || status === 'failed' || status === 'canceled';
+
+ return {
+ batch_id: `fixture-batch-${ordinal(Math.floor(index / 4), 3)}`,
+ completed_at: isSettled ? createdAt : null,
+ created_at: createdAt,
+ destination: index % 2 === 0 ? 'gallery' : 'canvas',
+ error_message: status === 'failed' ? 'Synthetic fixture failure' : null,
+ error_traceback: null,
+ error_type: status === 'failed' ? 'FixtureError' : null,
+ field_values: [
+ {
+ field_name: 'prompt',
+ node_path: 'fixture_prompt',
+ value: `Representative prompt ${itemId}`,
+ },
+ ],
+ item_id: itemId,
+ origin: `webv2:fixture-project-${ordinal(index % 40, 3)}:generate`,
+ retried_from_item_id: null,
+ session: { prepared_source_mapping: {}, results: {} },
+ session_id: `fixture-session-${ordinal(index, 4)}`,
+ started_at: status === 'pending' || status === 'waiting' ? null : createdAt,
+ status,
+ updated_at: createdAt,
+ user_display_name: 'Fixture User',
+ user_email: '[email protected]',
+ user_id: 'fixture-user',
+ };
+ });
+
+const MODEL_BASES = ['sd-1', 'sdxl', 'flux', 'flux2', 'qwen-image'];
+const MODEL_TYPES = ['main', 'lora', 'controlnet', 'vae', 'embedding'];
+
+const createModels = (count) =>
+ range(count, (index) => {
+ const id = ordinal(index);
+ const type = MODEL_TYPES[index % MODEL_TYPES.length];
+
+ return {
+ base: MODEL_BASES[index % MODEL_BASES.length],
+ cover_image: null,
+ default_settings: type === 'main' ? { cfg_scale: 7, height: 1024, steps: 30, width: 1024 } : null,
+ description: `Deterministic representative ${type} model ${id}.`,
+ file_size: 512_000_000 + index * 1_024,
+ format: type === 'embedding' ? 'embedding_file' : 'checkpoint',
+ hash: `fixture-hash-${id}`,
+ key: `fixture-model-${id}`,
+ name: `Fixture Model ${id}`,
+ path: `fixtures/models/fixture-model-${id}.safetensors`,
+ source: `fixtures/models/fixture-model-${id}.safetensors`,
+ source_type: 'path',
+ source_url: null,
+ trigger_phrases: type === 'lora' ? [`fixture-style-${id}`] : null,
+ type,
+ };
+ });
+
+const createNodePacks = (nodeCount) =>
+ range(Math.ceil(nodeCount / 5), (packIndex) => {
+ const firstNodeIndex = packIndex * 5;
+ const nodeTypes = range(Math.min(5, nodeCount - firstNodeIndex), (nodeOffset) => {
+ const nodeIndex = firstNodeIndex + nodeOffset;
+
+ return `mock_node_${ordinal(nodeIndex)}`;
+ });
+
+ return {
+ name: `fixture-pack-${ordinal(packIndex, 2)}`,
+ node_count: nodeTypes.length,
+ node_types: nodeTypes,
+ path: `/opt/invokeai/nodes/fixture-pack-${ordinal(packIndex, 2)}`,
+ };
+ });
+
+const createOpenApiDocument = (nodeCount) => {
+ const outputSchema = {
+ class: 'output',
+ properties: {
+ type: { const: 'fixture_output', default: 'fixture_output' },
+ value: { field_kind: 'output', title: 'Value', type: 'string' },
+ },
+ type: 'object',
+ };
+ const invocationSchemas = Object.fromEntries(
+ range(nodeCount, (index) => {
+ const id = ordinal(index);
+ const type = `mock_node_${id}`;
+
+ return [
+ `FixtureNode${id}Invocation`,
+ {
+ category: `fixture-${(index % 5) + 1}`,
+ class: 'invocation',
+ classification: 'stable',
+ description: `Synthetic invocation template ${id}.`,
+ node_pack: `fixture-pack-${ordinal(Math.floor(index / 5), 2)}`,
+ output: { $ref: '#/components/schemas/FixtureOutput' },
+ properties: {
+ prompt: {
+ default: '',
+ field_kind: 'input',
+ input: 'direct',
+ orig_required: false,
+ title: 'Prompt',
+ type: 'string',
+ ui_hidden: false,
+ },
+ type: { const: type, default: type, title: 'type' },
+ use_cache: { default: true, field_kind: 'internal', type: 'boolean' },
+ },
+ tags: ['fixture'],
+ title: `Fixture Node ${id}`,
+ type: 'object',
+ version: '1.0.0',
+ },
+ ];
+ })
+ );
+
+ return {
+ components: { schemas: { FixtureOutput: outputSchema, ...invocationSchemas } },
+ info: { title: 'InvokeAI deterministic mock', version: '1.0.0' },
+ openapi: '3.1.0',
+ paths: {},
+ };
+};
+
+const createWorkflowNodes = (count) =>
+ range(count, (index) => {
+ const id = ordinal(index);
+
+ return {
+ data: {
+ inputs: { prompt: { label: '', name: 'prompt', value: `Fixture node ${id}` } },
+ isIntermediate: true,
+ isOpen: true,
+ label: `Fixture Node ${id}`,
+ nodePack: `fixture-pack-${ordinal(Math.floor(index / 5), 2)}`,
+ notes: '',
+ type: `mock_node_${id}`,
+ useCache: true,
+ version: '1.0.0',
+ },
+ id: `fixture-workflow-node-${id}`,
+ position: { x: (index % 10) * 320, y: Math.floor(index / 10) * 240 },
+ type: 'invocation',
+ };
+ });
+
+const createCanvasLayers = (count) =>
+ range(count, (index) => {
+ const id = ordinal(index);
+ const imageName = `fixture-image-${ordinal(index, 4)}.png`;
+
+ return {
+ blendMode: 'normal',
+ id: `fixture-layer-${id}`,
+ isEnabled: true,
+ isLocked: false,
+ name: `Fixture Layer ${id}`,
+ opacity: 1,
+ source: {
+ image: { height: 512, imageName, width: 512 },
+ type: 'image',
+ },
+ transform: {
+ rotation: 0,
+ scaleX: 1,
+ scaleY: 1,
+ x: (index % 8) * 32,
+ y: Math.floor(index / 8) * 32,
+ },
+ type: 'raster',
+ };
+ });
+
+const createProjectDocument = ({ index, layers = [], workflowNodes = [] }) => {
+ const id = `fixture-project-${ordinal(index, 3)}`;
+ const graphId = `${id}-graph`;
+ const formRootId = `${graphId}-form-root`;
+
+ return {
+ canvas: {
+ document: {
+ background: 'transparent',
+ bbox: { height: 1024, width: 1024, x: 0, y: 0 },
+ height: 1024,
+ layers,
+ selectedLayerId: layers[0]?.id ?? null,
+ version: 2,
+ width: 1024,
+ },
+ documentRevision: 0,
+ snapshots: [],
+ stagingArea: {
+ areThumbnailsVisible: true,
+ autoSwitchMode: 'off',
+ isVisible: false,
+ pendingImageIds: [],
+ pendingImages: [],
+ selectedImageIndex: 0,
+ },
+ version: 2,
+ },
+ events: [],
+ graphHistory: [],
+ id,
+ invocation: {
+ destination: 'gallery',
+ destinationLocked: false,
+ sourceId: workflowNodes.length > 0 ? 'workflow' : 'generate',
+ sourceLocked: false,
+ },
+ layout: {
+ centerViewId: 'preview',
+ panels: { isBottomOpen: false, isLeftOpen: true, isRightOpen: true },
+ presetId: 'canvas-default',
+ },
+ name: `Fixture Project ${ordinal(index, 3)}`,
+ promptHistory: [],
+ projectGraph: {
+ author: 'InvokeAI',
+ contact: '',
+ description: index === 0 ? 'Representative 100-node workflow.' : '',
+ edges: [],
+ form: {
+ elements: {
+ [formRootId]: {
+ data: { children: [], layout: 'column' },
+ id: formRootId,
+ type: 'container',
+ },
+ },
+ rootElementId: formRootId,
+ },
+ id: graphId,
+ name: index === 0 ? 'Representative Workflow' : 'Empty Workflow',
+ nodes: workflowNodes,
+ notes: '',
+ tags: 'fixture',
+ updatedAt: timestampAt(index),
+ version: 2,
+ workflowVersion: '1.0.0',
+ },
+ queue: { items: [] },
+ settings: {},
+ widgetGraphs: {},
+ };
+};
+
+const createProjects = (count, workflowNodeCount, layerCount) =>
+ range(count, (index) => {
+ const data = createProjectDocument({
+ index,
+ layers: index === 0 ? createCanvasLayers(layerCount) : [],
+ workflowNodes: index === 0 ? createWorkflowNodes(workflowNodeCount) : [],
+ });
+ const timestamp = timestampAt(index);
+
+ return {
+ created_at: timestamp,
+ data,
+ name: data.name,
+ project_id: data.id,
+ revision: 1,
+ updated_at: timestamp,
+ };
+ });
+
+const createWorkflows = (count) =>
+ range(count, (index) => {
+ const id = ordinal(index);
+
+ return {
+ category: index % 4 === 0 ? 'default' : 'user',
+ created_at: timestampAt(index),
+ description: `Synthetic workflow library entry ${id}.`,
+ name: `Fixture Workflow ${id}`,
+ opened_at: index % 3 === 0 ? timestampAt(index) : null,
+ tags: 'fixture,representative',
+ thumbnail_url: null,
+ updated_at: timestampAt(index),
+ workflow: {
+ author: 'InvokeAI',
+ contact: '',
+ description: `Synthetic workflow library entry ${id}.`,
+ edges: [],
+ exposedFields: [],
+ form: { elements: {}, rootElementId: '' },
+ meta: { category: 'user', version: '3.0.0' },
+ name: `Fixture Workflow ${id}`,
+ nodes: [],
+ notes: '',
+ tags: 'fixture',
+ version: '3.0.0',
+ workflowVersion: '1.0.0',
+ },
+ workflow_id: `fixture-workflow-${id}`,
+ };
+ });
+
+const createEmptyFixture = () => ({
+ boards: [],
+ images: [],
+ models: [],
+ nodeCatalog: { custom_nodes_path: '/opt/invokeai/nodes', node_packs: [] },
+ openApiDocument: createOpenApiDocument(0),
+ profile: 'empty',
+ projects: [],
+ queueItems: [],
+ workflows: [],
+});
+
+const createRepresentativeFixture = () => {
+ const counts = MOCK_BACKEND_PROFILE_COUNTS.representative;
+ const images = createImages(counts.images);
+
+ return {
+ boards: createBoards(images),
+ images,
+ models: createModels(counts.models),
+ nodeCatalog: {
+ custom_nodes_path: '/opt/invokeai/nodes',
+ node_packs: createNodePacks(counts.nodes),
+ },
+ openApiDocument: createOpenApiDocument(counts.nodes),
+ profile: 'representative',
+ projects: createProjects(counts.projects, counts.workflowNodes, counts.layers),
+ queueItems: createQueueItems(counts.queueItems),
+ workflows: createWorkflows(100),
+ };
+};
+
+export const createMockBackendFixture = (profile = 'empty') => {
+ assertMockBackendProfileName(profile);
+
+ return profile === 'representative' ? createRepresentativeFixture() : createEmptyFixture();
+};
+
+const countInvocationSchemas = (fixture) =>
+ Object.values(fixture.openApiDocument?.components?.schemas ?? {}).filter((schema) => schema?.class === 'invocation')
+ .length;
+
+export const getMockBackendFixtureCounts = (fixture) => ({
+ images: fixture.images.length,
+ layers: fixture.projects[0]?.data?.canvas?.document?.layers?.length ?? 0,
+ models: fixture.models.length,
+ nodes: countInvocationSchemas(fixture),
+ projects: fixture.projects.length,
+ queueItems: fixture.queueItems.length,
+ workflowNodes: fixture.projects[0]?.data?.projectGraph?.nodes?.length ?? 0,
+});
+
+const findDuplicates = (values) => {
+ const seen = new Set();
+ const duplicates = new Set();
+
+ for (const value of values) {
+ if (seen.has(value)) {
+ duplicates.add(value);
+ }
+ seen.add(value);
+ }
+
+ return [...duplicates];
+};
+
+export const validateMockBackendFixture = (fixture) => {
+ const failures = [];
+
+ if (!isMockBackendProfileName(fixture?.profile)) {
+ failures.push(`fixture.profile must be one of ${MOCK_BACKEND_PROFILE_NAMES.join(', ')}`);
+ return failures;
+ }
+
+ const expected = MOCK_BACKEND_PROFILE_COUNTS[fixture.profile];
+ const received = getMockBackendFixtureCounts(fixture);
+
+ for (const [name, expectedCount] of Object.entries(expected)) {
+ if (received[name] !== expectedCount) {
+ failures.push(`${fixture.profile}.${name}: expected ${expectedCount}, received ${received[name]}`);
+ }
+ }
+
+ const identities = [
+ ['image names', fixture.images.map((image) => image.image_name)],
+ ['model keys', fixture.models.map((model) => model.key)],
+ ['project ids', fixture.projects.map((project) => project.project_id)],
+ ['queue item ids', fixture.queueItems.map((item) => item.item_id)],
+ ];
+
+ for (const [label, values] of identities) {
+ const duplicates = findDuplicates(values);
+
+ if (duplicates.length > 0) {
+ failures.push(`${label} must be unique; duplicated ${duplicates.join(', ')}`);
+ }
+ }
+
+ const nodeTypes = fixture.nodeCatalog.node_packs.flatMap((pack) => pack.node_types);
+ const invocationTypes = Object.values(fixture.openApiDocument.components.schemas)
+ .filter((schema) => schema?.class === 'invocation')
+ .map((schema) => schema.properties?.type?.const);
+
+ if (JSON.stringify(nodeTypes) !== JSON.stringify(invocationTypes)) {
+ failures.push('custom-node catalog types and OpenAPI invocation types must match in deterministic order');
+ }
+
+ return failures;
+};
+
+export const assertMockBackendFixture = (fixture) => {
+ const failures = validateMockBackendFixture(fixture);
+
+ if (failures.length > 0) {
+ throw new Error(`Invalid mock-backend fixture:\n- ${failures.join('\n- ')}`);
+ }
+
+ return fixture;
+};
diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
new file mode 100644
index 0000000000..bf0e70e44f
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
@@ -0,0 +1,109 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import {
+ assertMockBackendFixture,
+ createMockBackendFixture,
+ getMockBackendFixtureCounts,
+ MOCK_BACKEND_PROFILE_COUNTS,
+ MOCK_BACKEND_PROFILE_NAMES,
+ validateMockBackendFixture,
+} from './mock-backend-fixtures.mjs';
+import { startMockBackend } from './mock-backend.mjs';
+
+test('empty and representative fixtures have exact, distinct workloads', () => {
+ for (const profile of MOCK_BACKEND_PROFILE_NAMES) {
+ const fixture = assertMockBackendFixture(createMockBackendFixture(profile));
+
+ assert.deepEqual(getMockBackendFixtureCounts(fixture), MOCK_BACKEND_PROFILE_COUNTS[profile]);
+ assert.deepEqual(validateMockBackendFixture(fixture), []);
+ }
+
+ assert.notDeepEqual(createMockBackendFixture('empty'), createMockBackendFixture('representative'));
+});
+
+test('fixture generation is byte-deterministic', () => {
+ for (const profile of MOCK_BACKEND_PROFILE_NAMES) {
+ assert.equal(JSON.stringify(createMockBackendFixture(profile)), JSON.stringify(createMockBackendFixture(profile)));
+ }
+});
+
+test('representative fixtures keep node discovery and heavy project data coherent', () => {
+ const fixture = createMockBackendFixture('representative');
+ const catalogTypes = fixture.nodeCatalog.node_packs.flatMap((pack) => pack.node_types);
+ const invocationTypes = Object.values(fixture.openApiDocument.components.schemas)
+ .filter((schema) => schema.class === 'invocation')
+ .map((schema) => schema.properties.type.const);
+ const project = fixture.projects[0];
+
+ assert.deepEqual(catalogTypes, invocationTypes);
+ assert.deepEqual(
+ project.data.projectGraph.nodes.map((node) => node.data.type),
+ invocationTypes
+ );
+ assert.equal(project.data.canvas.document.layers.length, MOCK_BACKEND_PROFILE_COUNTS.representative.layers);
+ assert.equal(new Set(project.data.canvas.document.layers.map((layer) => layer.id)).size, 64);
+});
+
+test('the HTTP reset contract selects profiles explicitly and restores the startup profile by default', async () => {
+ const backend = await startMockBackend(0, { profile: 'empty' });
+
+ try {
+ const readJson = async (path, init) => {
+ const response = await fetch(`${backend.origin}${path}`, init);
+
+ assert.equal(response.ok, true, `${init?.method ?? 'GET'} ${path} returned ${response.status}`);
+
+ return response.json();
+ };
+
+ assert.deepEqual(await readJson('/__profile'), {
+ counts: MOCK_BACKEND_PROFILE_COUNTS.empty,
+ ok: true,
+ profile: 'empty',
+ });
+
+ assert.deepEqual(await readJson('/__reset?profile=representative', { method: 'POST' }), {
+ counts: MOCK_BACKEND_PROFILE_COUNTS.representative,
+ ok: true,
+ profile: 'representative',
+ });
+
+ const [images, itemIds, models, nodeCatalog, openApi, projects] = await Promise.all([
+ readJson('/api/v1/images/?limit=17&offset=0'),
+ readJson('/api/v1/queue/default/item_ids'),
+ readJson('/api/v2/models/'),
+ readJson('/api/v2/custom_nodes/'),
+ readJson('/openapi.json'),
+ readJson('/api/v1/projects/'),
+ ]);
+
+ assert.equal(images.items.length, 17);
+ assert.equal(images.total, 1_000);
+ assert.equal(itemIds.item_ids.length, 500);
+ assert.equal(models.models.length, 100);
+ assert.equal(nodeCatalog.node_packs.flatMap((pack) => pack.node_types).length, 100);
+ assert.equal(
+ Object.values(openApi.components.schemas).filter((schema) => schema.class === 'invocation').length,
+ 100
+ );
+ assert.equal(projects.length, 40);
+
+ assert.deepEqual(await readJson('/__reset', { method: 'POST' }), {
+ counts: MOCK_BACKEND_PROFILE_COUNTS.empty,
+ ok: true,
+ profile: 'empty',
+ });
+
+ assert.deepEqual(
+ await readJson('/__reset', {
+ body: JSON.stringify({ profile: 'representative' }),
+ headers: { 'content-type': 'application/json' },
+ method: 'POST',
+ }),
+ { counts: MOCK_BACKEND_PROFILE_COUNTS.representative, ok: true, profile: 'representative' }
+ );
+ } finally {
+ await backend.close();
+ }
+});
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 895848e1a8..4e752c7b81 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -1,22 +1,56 @@
import { createServer } from 'node:http';
+import {
+ assertMockBackendFixture,
+ assertMockBackendProfileName,
+ createMockBackendFixture,
+ getMockBackendFixtureCounts,
+ MOCK_BACKEND_FIXED_EPOCH,
+} from './mock-backend-fixtures.mjs';
+
/**
- * Disposable in-memory backend for the browser performance measurement.
- * Serves just enough of the InvokeAI REST surface for the measured routes to
- * boot deterministically: stateful projects + client-state KV, and stable
- * empty responses for the read models (queue, models, gallery, workflows).
- * `POST /__reset` wipes all state so every sample starts from byte-identical
- * backend state. No socket.io server is provided; the app measures as
- * disconnected, which is deterministic.
+ * Disposable in-memory InvokeAI backend for browser release/performance tests.
+ *
+ * `empty` and `representative` are explicit workload profiles. A reset without
+ * a profile restores the profile selected at server startup; callers may switch
+ * deterministically with `POST /__reset?profile=representative`. No socket.io
+ * server is provided, so realtime transport remains stably disconnected.
*/
-const createState = () => ({
- clientState: new Map(),
- nextProjectNumber: 1,
- projects: new Map(),
-});
+const FIXED_EPOCH_MS = Date.parse(MOCK_BACKEND_FIXED_EPOCH);
+const TINY_PNG = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAF/gL+XcX1WQAAAABJRU5ErkJggg==',
+ 'base64'
+);
+
+const clone = (value) => structuredClone(value);
-const timestamp = () => new Date().toISOString().replace('T', ' ').replace('Z', '');
+const createState = (profile) => {
+ const fixture = assertMockBackendFixture(createMockBackendFixture(profile));
+
+ return {
+ boards: new Map(fixture.boards.map((board) => [board.board_id, clone(board)])),
+ clientState: new Map(),
+ images: new Map(fixture.images.map((image) => [image.image_name, clone(image)])),
+ models: new Map(fixture.models.map((model) => [model.key, clone(model)])),
+ mutationClock: 0,
+ nextProjectNumber: fixture.projects.length + 1,
+ nodeCatalog: clone(fixture.nodeCatalog),
+ openApiDocument: clone(fixture.openApiDocument),
+ profile,
+ projects: new Map(fixture.projects.map((project) => [project.project_id, clone(project)])),
+ queueItems: new Map(fixture.queueItems.map((item) => [item.item_id, clone(item)])),
+ workflows: new Map(fixture.workflows.map((workflow) => [workflow.workflow_id, clone(workflow)])),
+ };
+};
+
+const timestamp = (state) => {
+ const value = new Date(FIXED_EPOCH_MS + state.mutationClock * 1_000).toISOString();
+
+ state.mutationClock += 1;
+
+ return value;
+};
const summaryOf = (project) => ({
created_at: project.created_at,
@@ -29,144 +63,485 @@ const summaryOf = (project) => ({
const readBody = (request) =>
new Promise((resolve, reject) => {
const chunks = [];
+
request.on('data', (chunk) => chunks.push(chunk));
request.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
request.on('error', reject);
});
-export const startMockBackend = async (port) => {
- let state = createState();
+const readJsonBody = async (request, fallback = {}) => {
+ const body = await readBody(request);
+
+ return body ? JSON.parse(body) : fallback;
+};
+
+const invocationNodeCount = (state) =>
+ Object.values(state.openApiDocument.components?.schemas ?? {}).filter((schema) => schema?.class === 'invocation')
+ .length;
+
+const getStateCounts = (state) => ({
+ images: state.images.size,
+ layers: state.projects.values().next().value?.data?.canvas?.document?.layers?.length ?? 0,
+ models: state.models.size,
+ nodes: invocationNodeCount(state),
+ projects: state.projects.size,
+ queueItems: state.queueItems.size,
+ workflowNodes: state.projects.values().next().value?.data?.projectGraph?.nodes?.length ?? 0,
+});
+
+const getProfileInfo = (state) => ({
+ counts: getStateCounts(state),
+ profile: state.profile,
+});
+
+const queueItemsForScope = (state, url) => {
+ const originPrefix = url.searchParams.get('origin_prefix');
+ const items = [...state.queueItems.values()];
+
+ return originPrefix ? items.filter((item) => item.origin?.startsWith(originPrefix)) : items;
+};
+
+const queueStatus = (items) => {
+ const count = (status) => items.filter((item) => item.status === status).length;
+
+ return {
+ canceled: count('canceled'),
+ completed: count('completed'),
+ failed: count('failed'),
+ in_progress: count('in_progress'),
+ pending: count('pending'),
+ queue_id: 'default',
+ total: items.length,
+ waiting: count('waiting'),
+ };
+};
+
+const getRequestedCategories = (url) => {
+ const values = url.searchParams.getAll('categories');
+
+ return values.flatMap((value) => value.split(',')).filter(Boolean);
+};
+
+const listImages = (state, url) => {
+ const boardId = url.searchParams.get('board_id');
+ const categories = getRequestedCategories(url);
+ const createdFrom = url.searchParams.get('created_from');
+ const createdTo = url.searchParams.get('created_to');
+ const orderDir = url.searchParams.get('order_dir')?.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
+ const searchTerm = url.searchParams.get('search_term')?.trim().toLocaleLowerCase() ?? '';
+ const starredFirst = url.searchParams.get('starred_first') === 'true';
+ const offset = Math.max(0, Number(url.searchParams.get('offset') ?? 0) || 0);
+ const limit = Math.max(0, Number(url.searchParams.get('limit') ?? 100) || 0);
+ let items = [...state.images.values()].filter((image) => {
+ if (image.is_intermediate) {
+ return false;
+ }
+ if (boardId && boardId !== 'all') {
+ if (boardId === 'none' ? image.board_id !== null : image.board_id !== boardId) {
+ return false;
+ }
+ }
+ if (categories.length > 0 && !categories.includes(image.image_category)) {
+ return false;
+ }
+ if (createdFrom && image.created_at.slice(0, 10) < createdFrom) {
+ return false;
+ }
+ if (createdTo && image.created_at.slice(0, 10) > createdTo) {
+ return false;
+ }
+
+ return !searchTerm || image.image_name.toLocaleLowerCase().includes(searchTerm);
+ });
+
+ items.sort((left, right) => {
+ if (starredFirst && Boolean(left.starred) !== Boolean(right.starred)) {
+ return left.starred ? -1 : 1;
+ }
+
+ return orderDir === 'ASC'
+ ? left.created_at.localeCompare(right.created_at)
+ : right.created_at.localeCompare(left.created_at);
+ });
+
+ const total = items.length;
+ items = limit === 0 ? [] : items.slice(offset, offset + limit);
+
+ return { items, limit, offset, total };
+};
+
+const listVirtualDateBoards = (state) => {
+ const groups = new Map();
+
+ for (const image of state.images.values()) {
+ const date = image.created_at.slice(0, 10);
+ const group = groups.get(date) ?? [];
+
+ group.push(image);
+ groups.set(date, group);
+ }
+
+ return [...groups.entries()]
+ .sort(([left], [right]) => right.localeCompare(left))
+ .map(([date, images]) => ({
+ asset_count: images.filter((image) => image.image_category !== 'general').length,
+ board_name: date,
+ cover_image_name: images[0]?.image_name ?? null,
+ date,
+ image_count: images.filter((image) => image.image_category === 'general').length,
+ virtual_board_id: `by_date:${date}`,
+ }));
+};
+
+const writeJson = (response, status, value) => {
+ const body = JSON.stringify(value ?? null);
+
+ response.writeHead(status, {
+ 'cache-control': 'no-store',
+ 'content-length': Buffer.byteLength(body),
+ 'content-type': 'application/json',
+ });
+ response.end(body);
+};
+
+const writePng = (response) => {
+ response.writeHead(200, {
+ 'cache-control': 'public, max-age=3600',
+ 'content-length': TINY_PNG.length,
+ 'content-type': 'image/png',
+ });
+ response.end(TINY_PNG);
+};
+
+export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
+ const initialProfile = assertMockBackendProfileName(profile);
+ let state = createState(initialProfile);
const server = createServer(async (request, response) => {
- const url = new URL(request.url, `http://127.0.0.1:${port}`);
+ const url = new URL(request.url, `http://127.0.0.1:${String(port)}`);
const path = url.pathname;
const method = request.method ?? 'GET';
+ const json = (status, value) => writeJson(response, status, value);
- const json = (status, value) => {
- const body = JSON.stringify(value ?? null);
- response.writeHead(status, { 'content-type': 'application/json' });
- response.end(body);
- };
+ try {
+ if (method === 'GET' && (path === '/__health' || path === '/__profile')) {
+ return json(200, { ok: true, ...getProfileInfo(state) });
+ }
- if (method === 'POST' && path === '/__reset') {
- state = createState();
- return json(200, { ok: true });
- }
+ if (method === 'POST' && path === '/__reset') {
+ const body = await readJsonBody(request);
+ const requestedProfile = url.searchParams.get('profile') ?? body.profile ?? initialProfile;
+
+ try {
+ state = createState(assertMockBackendProfileName(requestedProfile));
+ } catch (error) {
+ return json(400, { detail: error instanceof Error ? error.message : String(error) });
+ }
- if (path === '/api/v1/projects/' || path === '/api/v1/projects') {
- if (method === 'GET') {
- return json(200, [...state.projects.values()].map(summaryOf));
- }
- if (method === 'POST') {
- const requested = JSON.parse((await readBody(request)) || '{}');
- if (requested.project_id && state.projects.has(requested.project_id)) {
- return json(409, { detail: 'Project already exists' });
- }
- const now = timestamp();
- const project = {
- created_at: now,
- data: requested.data ?? {},
- name: requested.name ?? `Project Name #${state.nextProjectNumber}`,
- project_id: requested.project_id ?? `mock-project-${state.nextProjectNumber}`,
- revision: 1,
- updated_at: now,
- };
- state.nextProjectNumber += 1;
- state.projects.set(project.project_id, project);
- return json(200, project);
+ return json(200, { ok: true, ...getProfileInfo(state) });
}
- }
- const projectMatch = /^\/api\/v1\/projects\/([^/]+)$/.exec(path);
- if (projectMatch) {
- const projectId = decodeURIComponent(projectMatch[1]);
- const project = state.projects.get(projectId);
- if (method === 'GET') {
- return project ? json(200, project) : json(404, { detail: 'Project not found' });
+ if (method === 'GET' && path === '/openapi.json') {
+ return json(200, state.openApiDocument);
}
- if (method === 'PUT') {
- if (!project) {
- return json(404, { detail: 'Project not found' });
+
+ if (method === 'GET' && path === '/api/v1/auth/status') {
+ return json(200, {
+ admin_email: null,
+ multiuser_enabled: false,
+ setup_required: false,
+ strict_password_checking: false,
+ });
+ }
+
+ if (method === 'GET' && path === '/api/v1/app/version') {
+ return json(200, { version: 'fixture' });
+ }
+
+ if (path.startsWith('/api/v1/app/external_providers')) {
+ return json(200, []);
+ }
+
+ if (path === '/api/v1/projects/' || path === '/api/v1/projects') {
+ if (method === 'GET') {
+ return json(200, [...state.projects.values()].map(summaryOf));
}
- const requested = JSON.parse((await readBody(request)) || '{}');
- if (requested.expected_revision !== undefined && requested.expected_revision !== project.revision) {
- return json(409, { detail: 'Revision conflict' });
+ if (method === 'POST') {
+ const requested = await readJsonBody(request);
+
+ if (requested.project_id && state.projects.has(requested.project_id)) {
+ return json(409, { detail: 'Project already exists' });
+ }
+
+ const now = timestamp(state);
+ const projectNumber = state.nextProjectNumber;
+ const project = {
+ created_at: now,
+ data: requested.data ?? {},
+ name: requested.name ?? `Project Name #${projectNumber}`,
+ project_id: requested.project_id ?? `mock-project-${projectNumber}`,
+ revision: 1,
+ updated_at: now,
+ };
+
+ state.nextProjectNumber += 1;
+ state.projects.set(project.project_id, project);
+
+ return json(200, project);
}
- project.data = requested.data ?? project.data;
- project.name = requested.name ?? project.name;
- project.revision += 1;
- project.updated_at = timestamp();
- return json(200, project);
- }
- if (method === 'DELETE') {
- state.projects.delete(projectId);
- return json(200, { ok: true });
}
- }
- if (path.startsWith('/api/v1/client_state/')) {
- const key = url.searchParams.get('key') ?? '';
- if (path.endsWith('/get_by_key')) {
- return json(200, state.clientState.get(key) ?? null);
+ const projectMatch = /^\/api\/v1\/projects\/([^/]+)$/.exec(path);
+ if (projectMatch) {
+ const projectId = decodeURIComponent(projectMatch[1]);
+ const project = state.projects.get(projectId);
+
+ if (method === 'GET') {
+ return project ? json(200, project) : json(404, { detail: 'Project not found' });
+ }
+ if (method === 'PUT') {
+ if (!project) {
+ return json(404, { detail: 'Project not found' });
+ }
+
+ const requested = await readJsonBody(request);
+
+ if (requested.expected_revision !== undefined && requested.expected_revision !== project.revision) {
+ return json(409, { detail: 'Revision conflict' });
+ }
+
+ project.data = requested.data ?? project.data;
+ project.name = requested.name ?? project.name;
+ project.revision += 1;
+ project.updated_at = timestamp(state);
+
+ return json(200, project);
+ }
+ if (method === 'DELETE') {
+ state.projects.delete(projectId);
+ return json(200, { ok: true });
+ }
}
- if (path.endsWith('/set_by_key')) {
- const value = JSON.parse((await readBody(request)) || 'null');
- state.clientState.set(key, value);
- return json(200, value);
+
+ if (path.startsWith('/api/v1/client_state/')) {
+ const key = url.searchParams.get('key') ?? '';
+
+ if (path.endsWith('/get_by_key')) {
+ return json(200, state.clientState.get(key) ?? null);
+ }
+ if (path.endsWith('/set_by_key')) {
+ const value = await readJsonBody(request, null);
+
+ state.clientState.set(key, value);
+ return json(200, value);
+ }
+ if (path.endsWith('/delete_by_key')) {
+ state.clientState.delete(key);
+ return json(200, { ok: true });
+ }
}
- if (path.endsWith('/delete_by_key')) {
- state.clientState.delete(key);
- return json(200, { ok: true });
+
+ const queueItemMatch = /^\/api\/v1\/queue\/[^/]+\/i\/(\d+)$/.exec(path);
+ if (queueItemMatch) {
+ const itemId = Number(queueItemMatch[1]);
+ const item = state.queueItems.get(itemId);
+
+ if (method === 'GET') {
+ return item ? json(200, item) : json(404, { detail: 'Queue item not found' });
+ }
+ if (method === 'DELETE') {
+ state.queueItems.delete(itemId);
+ return json(200, { ok: true });
+ }
}
- }
- const queueMatch = /^\/api\/v1\/queue\/[^/]+\/(.+)$/.exec(path);
- if (queueMatch) {
- const action = queueMatch[1];
- if (action === 'status') {
- return json(200, {
- processor: { is_processing: false, is_started: true },
- queue: { canceled: 0, completed: 0, failed: 0, in_progress: 0, pending: 0, queue_id: 'default', total: 0 },
- });
+ const queueMatch = /^\/api\/v1\/queue\/[^/]+\/(.+)$/.exec(path);
+ if (queueMatch) {
+ const action = queueMatch[1];
+ const scopedItems = queueItemsForScope(state, url);
+
+ if (action === 'status') {
+ return json(200, {
+ processor: { is_processing: scopedItems.some((item) => item.status === 'in_progress'), is_started: true },
+ queue: queueStatus(scopedItems),
+ });
+ }
+ if (action === 'current') {
+ return json(200, scopedItems.find((item) => item.status === 'in_progress') ?? null);
+ }
+ if (action === 'next') {
+ return json(200, scopedItems.find((item) => item.status === 'pending' || item.status === 'waiting') ?? null);
+ }
+ if (action === 'list_all') {
+ return json(200, scopedItems);
+ }
+ if (action === 'items_by_ids') {
+ const body = await readJsonBody(request);
+ const ids = Array.isArray(body.item_ids) ? new Set(body.item_ids) : new Set();
+
+ return json(
+ 200,
+ scopedItems.filter((item) => ids.has(item.item_id))
+ );
+ }
+ if (action === 'item_ids' || action === 'list') {
+ const descending = url.searchParams.get('order_dir')?.toUpperCase() !== 'ASC';
+ const itemIds = scopedItems.map((item) => item.item_id).sort((left, right) => left - right);
+
+ if (descending) {
+ itemIds.reverse();
+ }
+
+ return json(200, { item_ids: itemIds, total_count: itemIds.length });
+ }
+ if (action === 'clear' && method === 'PUT') {
+ state.queueItems.clear();
+ return json(200, { deleted: true });
+ }
+ if (action === 'prune' && method === 'PUT') {
+ for (const item of state.queueItems.values()) {
+ if (item.status === 'completed' || item.status === 'failed' || item.status === 'canceled') {
+ state.queueItems.delete(item.item_id);
+ }
+ }
+ return json(200, { deleted: true });
+ }
+
+ return json(200, null);
}
- if (action === 'current' || action === 'next') {
+
+ if (method === 'GET' && path === '/api/v2/models/stats') {
return json(200, null);
}
- if (action === 'list_all' || action === 'items_by_ids') {
+ if (method === 'GET' && path === '/api/v2/models/missing') {
+ return json(200, { models: [] });
+ }
+ if (method === 'GET' && path === '/api/v2/models/models_dir') {
+ return json(200, '/opt/invokeai/models');
+ }
+ if (method === 'GET' && path === '/api/v2/models/install') {
return json(200, []);
}
- if (action === 'list') {
- return json(200, { item_ids: [], total_count: 0 });
+ if (method === 'GET' && path === '/api/v2/models/starter_models') {
+ return json(200, { starter_bundles: {}, starter_models: [] });
+ }
+ if (method === 'GET' && path === '/api/v2/models/hf_login') {
+ return json(200, 'unknown');
+ }
+ if (method === 'GET' && path === '/api/v2/models/sync/orphaned') {
+ return json(200, []);
}
- return json(200, null);
- }
- if (path.startsWith('/api/v2/models/stats')) {
- return json(200, null);
- }
- if (path.startsWith('/api/v2/models')) {
- return json(200, { models: [] });
- }
- if (path.startsWith('/api/v1/model_relationships')) {
- return json(200, []);
- }
- if (path.startsWith('/api/v1/app/external_providers')) {
- return json(200, []);
- }
- if (path.startsWith('/api/v1/virtual_boards/by_date')) {
- return json(200, []);
- }
- if (path.startsWith('/api/v1/images/images_by_names')) {
- return json(200, []);
- }
- if (path.startsWith('/api/v1/workflows')) {
- return json(200, { items: [], total: 0 });
- }
- if (path.startsWith('/api/v2/custom_nodes')) {
- return json(200, []);
- }
+ const modelMatch = /^\/api\/v2\/models\/i\/([^/]+)$/.exec(path);
+ if (modelMatch) {
+ const key = decodeURIComponent(modelMatch[1]);
+ const model = state.models.get(key);
+
+ return model ? json(200, model) : json(404, { detail: 'Model not found' });
+ }
+
+ if (method === 'GET' && (path === '/api/v2/models' || path === '/api/v2/models/')) {
+ return json(200, { models: [...state.models.values()] });
+ }
+
+ if (path.startsWith('/api/v1/model_relationships')) {
+ return json(200, []);
+ }
+
+ if (method === 'GET' && (path === '/api/v2/custom_nodes' || path === '/api/v2/custom_nodes/')) {
+ return json(200, state.nodeCatalog);
+ }
+
+ if (method === 'GET' && (path === '/api/v1/boards' || path === '/api/v1/boards/')) {
+ return json(200, [...state.boards.values()]);
+ }
+
+ if (method === 'GET' && path === '/api/v1/virtual_boards/by_date') {
+ return json(200, listVirtualDateBoards(state));
+ }
+
+ const virtualBoardNamesMatch = /^\/api\/v1\/virtual_boards\/by_date\/([^/]+)\/image_names$/.exec(path);
+ if (method === 'GET' && virtualBoardNamesMatch) {
+ const date = decodeURIComponent(virtualBoardNamesMatch[1]);
+ const imageNames = [...state.images.values()]
+ .filter((image) => image.created_at.startsWith(date))
+ .map((image) => image.image_name);
+
+ return json(200, { image_names: imageNames, total_count: imageNames.length });
+ }
+
+ if (method === 'POST' && path === '/api/v1/images/images_by_names') {
+ const body = await readJsonBody(request);
+ const names = Array.isArray(body.image_names) ? body.image_names : [];
+
+ return json(
+ 200,
+ names.flatMap((name) => (state.images.has(name) ? [state.images.get(name)] : []))
+ );
+ }
+
+ if (method === 'GET' && (path === '/api/v1/images' || path === '/api/v1/images/')) {
+ return json(200, listImages(state, url));
+ }
- return json(404, { detail: `No mock for ${method} ${path}` });
+ const imageAssetMatch = /^\/api\/v1\/images\/i\/([^/]+)\/(full|thumbnail)$/.exec(path);
+ if (method === 'GET' && imageAssetMatch) {
+ const imageName = decodeURIComponent(imageAssetMatch[1]);
+
+ return state.images.has(imageName) ? writePng(response) : json(404, { detail: 'Image not found' });
+ }
+
+ const imageMetadataMatch = /^\/api\/v1\/images\/i\/([^/]+)\/metadata$/.exec(path);
+ if (method === 'GET' && imageMetadataMatch) {
+ return json(200, {});
+ }
+
+ const imageMatch = /^\/api\/v1\/images\/i\/([^/]+)$/.exec(path);
+ if (imageMatch) {
+ const imageName = decodeURIComponent(imageMatch[1]);
+ const image = state.images.get(imageName);
+
+ return image ? json(200, image) : json(404, { detail: 'Image not found' });
+ }
+
+ const workflowMatch = /^\/api\/v1\/workflows\/i\/([^/]+)(?:\/opened_at)?$/.exec(path);
+ if (workflowMatch) {
+ const workflowId = decodeURIComponent(workflowMatch[1]);
+ const workflow = state.workflows.get(workflowId);
+
+ if (!workflow) {
+ return json(404, { detail: 'Workflow not found' });
+ }
+
+ return json(200, {
+ name: workflow.name,
+ workflow: workflow.workflow,
+ workflow_id: workflow.workflow_id,
+ });
+ }
+
+ if (method === 'GET' && (path === '/api/v1/workflows' || path === '/api/v1/workflows/')) {
+ const categories = url.searchParams.getAll('categories');
+ const query = url.searchParams.get('query')?.trim().toLocaleLowerCase() ?? '';
+ const page = Math.max(1, Number(url.searchParams.get('page') ?? 1) || 1);
+ const perPage = Math.max(1, Number(url.searchParams.get('per_page') ?? 20) || 20);
+ const items = [...state.workflows.values()].filter(
+ (workflow) =>
+ (categories.length === 0 || categories.includes(workflow.category)) &&
+ (!query || `${workflow.name} ${workflow.description}`.toLocaleLowerCase().includes(query))
+ );
+ const pages = Math.max(1, Math.ceil(items.length / perPage));
+ const pageItems = items
+ .slice((page - 1) * perPage, page * perPage)
+ .map(({ workflow: _workflow, ...item }) => item);
+
+ return json(200, { items: pageItems, page, pages, total: items.length });
+ }
+
+ return json(404, { detail: `No mock for ${method} ${path}` });
+ } catch (error) {
+ return json(500, { detail: error instanceof Error ? error.message : String(error) });
+ }
});
await new Promise((resolve, reject) => {
@@ -174,11 +549,20 @@ export const startMockBackend = async (port) => {
server.listen(port, '127.0.0.1', resolve);
});
+ const address = server.address();
+ const actualPort = typeof address === 'object' && address ? address.port : port;
+
return {
close: () =>
new Promise((resolve) => {
server.close(resolve);
server.closeAllConnections?.();
}),
+ counts: () => getStateCounts(state),
+ origin: `http://127.0.0.1:${String(actualPort)}`,
+ port: actualPort,
+ profile: () => state.profile,
};
};
+
+export { getMockBackendFixtureCounts };
diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
new file mode 100644
index 0000000000..03273290b5
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
@@ -0,0 +1,273 @@
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { resolve } from 'node:path';
+import process from 'node:process';
+import { chromium } from 'playwright';
+
+import { assertNoAxeViolations } from './accessibility/axe.mjs';
+import { startMockBackend } from './mock-backend.mjs';
+
+const root = resolve(import.meta.dirname, '..');
+const port = Number(process.env.INVOKEAI_ACCESSIBILITY_PORT ?? 4178);
+const origin = `http://127.0.0.1:${String(port)}`;
+const backendPort = Number(process.env.INVOKEAI_ACCESSIBILITY_BACKEND_PORT ?? 4179);
+const backendOrigin = `http://127.0.0.1:${String(backendPort)}`;
+const representativeProjectPath = '/#/app?project=fixture-project-001';
+
+const waitForPreview = async () => {
+ const deadline = Date.now() + 20_000;
+
+ while (Date.now() < deadline) {
+ try {
+ const response = await fetch(origin);
+
+ if (response.ok) {
+ return;
+ }
+ } catch {
+ // Preview is still starting.
+ }
+
+ await new Promise((resolveWait) => {
+ setTimeout(resolveWait, 100);
+ });
+ }
+
+ throw new Error(`Vite preview did not become ready at ${origin}.`);
+};
+
+const waitForSettledDocument = async (page) => {
+ await page.evaluate(async () => {
+ await document.fonts.ready;
+ await new Promise((resolveFrame) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolveFrame));
+ });
+ });
+};
+
+const openRepresentativePage = async (browser, path) => {
+ const resetResponse = await fetch(`${backendOrigin}/__reset?profile=representative`, { method: 'POST' });
+
+ if (!resetResponse.ok) {
+ throw new Error(`Could not reset representative backend: ${resetResponse.status}.`);
+ }
+
+ const context = await browser.newContext({
+ colorScheme: 'dark',
+ reducedMotion: 'reduce',
+ viewport: { height: 1_000, width: 1_440 },
+ });
+ const page = await context.newPage();
+ const pageErrors = [];
+
+ page.on('pageerror', (error) => pageErrors.push(error));
+ await page.goto(`${origin}${path}`, { waitUntil: 'domcontentloaded' });
+
+ return { context, page, pageErrors };
+};
+
+const waitForProjects = async (page) => {
+ await page.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();
+ await page.getByRole('link', { exact: true, name: 'Open Fixture Project 001' }).waitFor();
+};
+
+const waitForModels = async (page) => {
+ await page.getByLabel('Model library', { exact: true }).waitFor();
+ await page.getByText('Fixture Model 001', { exact: true }).waitFor();
+};
+
+const waitForNodes = async (page) => {
+ await page.getByRole('textbox', { exact: true, name: 'Search node packs' }).waitFor();
+ await page.getByText('fixture-pack-01', { exact: true }).waitFor();
+};
+
+const waitForWorkbench = async (page) => {
+ await page.getByRole('main', { exact: true, name: 'Fixture Project 001' }).waitFor();
+ await page.getByRole('button', { name: /^Layout preset:/ }).waitFor();
+};
+
+const selectLayoutPreset = async (page, preset) => {
+ const trigger = page.getByRole('button', { name: /^Layout preset:/ });
+
+ await trigger.click();
+ await page.getByRole('menuitem', { exact: true, name: preset }).click();
+ await page.getByRole('button', { exact: true, name: `Layout preset: ${preset}` }).waitFor();
+ await page.getByRole('tab', { exact: true, name: preset }).waitFor();
+};
+
+const surfaces = [
+ {
+ id: 'launchpad-projects-representative',
+ path: '/#/',
+ ready: waitForProjects,
+ },
+ {
+ id: 'launchpad-models-representative',
+ path: '/#/models',
+ ready: waitForModels,
+ },
+ {
+ id: 'launchpad-nodes-representative',
+ path: '/#/nodes',
+ ready: waitForNodes,
+ },
+ {
+ id: 'workbench-default-representative',
+ path: representativeProjectPath,
+ ready: async (page) => {
+ await waitForWorkbench(page);
+ await page.getByRole('tab', { exact: true, name: 'Preview' }).waitFor();
+ },
+ },
+ {
+ id: 'workbench-canvas-representative',
+ path: representativeProjectPath,
+ ready: async (page) => {
+ await waitForWorkbench(page);
+ await selectLayoutPreset(page, 'Canvas');
+ },
+ },
+ {
+ id: 'workbench-gallery-representative',
+ path: representativeProjectPath,
+ ready: async (page) => {
+ await waitForWorkbench(page);
+ await selectLayoutPreset(page, 'Gallery');
+ await page.getByRole('list', { exact: true, name: 'Gallery images' }).waitFor();
+ },
+ },
+ {
+ id: 'workbench-workflow-representative',
+ path: representativeProjectPath,
+ ready: async (page) => {
+ await waitForWorkbench(page);
+ await selectLayoutPreset(page, 'Workflow');
+ await page.getByText('Fixture Node 001', { exact: true }).waitFor();
+ },
+ },
+];
+
+const runAxeSurface = async (browser, surface) => {
+ const { context, page, pageErrors } = await openRepresentativePage(browser, surface.path);
+
+ try {
+ await surface.ready(page);
+ await waitForSettledDocument(page);
+ await assertNoAxeViolations(page, surface.id);
+
+ if (pageErrors.length > 0) {
+ throw new AggregateError(pageErrors, `${surface.id} raised uncaught browser errors.`);
+ }
+
+ return { id: surface.id, status: 'passed' };
+ } finally {
+ await context.close();
+ }
+};
+
+const expectFocused = async (locator, message) => {
+ assert.equal(await locator.evaluate((element) => element === document.activeElement), true, message);
+};
+
+const runKeyboardJourney = async (browser) => {
+ const { context, page, pageErrors } = await openRepresentativePage(browser, '/#/');
+
+ try {
+ await waitForProjects(page);
+
+ const projectsTab = page.getByRole('tab', { exact: true, name: 'Projects' });
+ const modelsTab = page.getByRole('tab', { exact: true, name: 'Models' });
+
+ await projectsTab.focus();
+ await projectsTab.press('ArrowDown');
+ await expectFocused(modelsTab, 'ArrowDown should move focus from Projects to Models.');
+ await waitForModels(page);
+ assert.match(page.url(), /#\/models$/);
+ assert.equal(await modelsTab.getAttribute('aria-selected'), 'true');
+
+ const paletteTrigger = page.getByRole('button', { exact: true, name: 'Command palette' });
+
+ await paletteTrigger.click();
+ const paletteDialog = page.getByRole('dialog', { exact: true, name: 'Command palette' });
+ const paletteInput = page.getByRole('combobox', { exact: true, name: 'Search commands and settings' });
+
+ await paletteDialog.waitFor();
+ await expectFocused(paletteInput, 'Opening the command palette should focus its search field.');
+ await paletteInput.press('Escape');
+ await paletteDialog.waitFor({ state: 'hidden' });
+ await expectFocused(paletteTrigger, 'Closing the command palette should restore focus to its trigger.');
+
+ await projectsTab.focus();
+ await projectsTab.press('Enter');
+ await waitForProjects(page);
+
+ const projectLink = page.getByRole('link', { exact: true, name: 'Open Fixture Project 001' });
+
+ await projectLink.focus();
+ await projectLink.press('Enter');
+ await waitForWorkbench(page);
+
+ const previewTab = page.getByRole('tab', { exact: true, name: 'Preview' });
+ const canvasTab = page.getByRole('tab', { exact: true, name: 'Canvas' });
+
+ await previewTab.focus();
+ await previewTab.press('ArrowRight');
+ await expectFocused(canvasTab, 'ArrowRight should move focus to the next center view.');
+ assert.equal(await canvasTab.getAttribute('aria-selected'), 'true');
+
+ if (pageErrors.length > 0) {
+ throw new AggregateError(pageErrors, 'keyboard-critical-journey raised uncaught browser errors.');
+ }
+
+ return { id: 'keyboard-critical-journey', status: 'passed' };
+ } finally {
+ await context.close();
+ }
+};
+
+const mockBackend = await startMockBackend(backendPort, { profile: 'representative' });
+const preview = spawn(
+ 'pnpm',
+ ['exec', 'vite', 'preview', '--host', '127.0.0.1', '--port', String(port), '--strictPort'],
+ {
+ cwd: root,
+ detached: true,
+ env: { ...process.env, INVOKEAI_DEV_BACKEND: backendOrigin },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ }
+);
+let previewError = '';
+let browser = null;
+
+preview.stderr.on('data', (chunk) => {
+ previewError += String(chunk);
+});
+
+try {
+ await waitForPreview();
+ browser = await chromium.launch({ headless: true });
+ const reports = [];
+
+ for (const surface of surfaces) {
+ reports.push(await runAxeSurface(browser, surface));
+ }
+
+ reports.push(await runKeyboardJourney(browser));
+ 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}` : ''}`
+ );
+} finally {
+ await browser?.close();
+
+ if (preview.pid) {
+ try {
+ process.kill(-preview.pid, 'SIGTERM');
+ } catch {
+ // Preview may already have exited after a startup failure.
+ }
+ }
+
+ await mockBackend.close();
+}