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(ui): address architecture review blockers

joshistoast6dbb1c90afe1
diff --git a/.github/workflows/frontend-tests.yml b/.github/workflows/frontend-tests.yml
index 451ae9d463..30cc7af3eb 100644
--- a/.github/workflows/frontend-tests.yml
+++ b/.github/workflows/frontend-tests.yml
@@ -98,10 +98,12 @@ jobs:
run: 'pnpm check:architecture'
shell: bash
- - name: upload architecture performance artifacts
+ - name: upload architecture review artifacts
if: ${{ always() && (steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true) }}
uses: actions/upload-artifact@v6
with:
- name: webv2-architecture-performance
- path: invokeai/frontend/webv2/artifacts/architecture-performance
+ name: webv2-architecture-review
+ path: |
+ invokeai/frontend/webv2/artifacts/architecture
+ invokeai/frontend/webv2/artifacts/architecture-performance
if-no-files-found: ignore
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index f3dc5bef8c..351686ad0e 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -4,7 +4,7 @@
"private": true,
"type": "module",
"scripts": {
- "architecture:check": "vitest run --config vitest.config.mts src/architecture/dependencyPolicy.test.ts src/architecture/workbenchOwnership.test.ts && node scripts/write-workbench-ownership-inventory.mjs && node scripts/write-contract-caller-matrix.mjs && node scripts/write-canvas-import-matrix.mjs",
+ "architecture:check": "vitest run --config vitest.config.mts src/architecture/dependencyPolicy.test.ts src/architecture/workbenchOwnership.test.ts src/architecture/productionPortBindings.test.ts && node scripts/write-workbench-ownership-inventory.mjs && node scripts/write-contract-caller-matrix.mjs && node scripts/write-canvas-import-matrix.mjs",
"build": "pnpm run lint && vite build",
"check:architecture": "pnpm run lint && pnpm run test:all && pnpm run test:performance:architecture",
"dev": "vite dev",
@@ -24,6 +24,7 @@
"test:browser": "vitest run --config vitest.browser.config.mts",
"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",
"test:performance:build": "vite build && node scripts/check-architecture-performance.mjs"
},
"dependencies": {
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index c8571fa667..c852d7e734 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -3,25 +3,26 @@
"capturedAt": "2026-07-17",
"routes": [
{
- "domContentLoadedMedianMs": 107.8000000002794,
+ "domContentLoadedMedianMs": 103.30000000074506,
"id": "launchpad",
- "loadMedianMs": 107.8000000002794,
- "longestTaskMaxMs": 78,
+ "loadMedianMs": 103.30000000074506,
+ "longestTaskMaxMs": 73,
"layoutSwitchMedianMs": 0,
"projectSwitchMedianMs": 0,
"owner": "app",
"remediationTicket": "set-performance-budgets",
- "routeReadyMedianMs": 210.20000000018626,
+ "routeReadyMedianMs": 205.30000000074506,
"scriptRequests": [
"Tooltip",
"WorkflowUiContext",
- "baseGenerationPolicies",
"chakra",
"externalStore",
"graph",
"http",
+ "identity",
"imageUrls",
"index",
+ "promptHistory",
"react",
"rolldown-runtime",
"selectors",
@@ -34,22 +35,19 @@
]
},
{
- "domContentLoadedMedianMs": 120.5,
+ "domContentLoadedMedianMs": 105.29999999701977,
"id": "editor-minimal",
- "loadMedianMs": 120.5,
- "longestTaskMaxMs": 106,
+ "loadMedianMs": 105.29999999701977,
+ "longestTaskMaxMs": 110,
"layoutSwitchMedianMs": 0,
- "projectSwitchMedianMs": 220.75787000000128,
+ "projectSwitchMedianMs": 185.3965049999997,
"owner": "workbench",
"remediationTicket": "deepen-widget-registry-loading",
- "routeReadyMedianMs": 558.7000000001863,
+ "routeReadyMedianMs": 719,
"scriptRequests": [
"GalleryImageActionsBridge",
"GalleryUiContext",
- "GenerateCollapsibleSection",
- "GenerationUiContext",
"ModelSelect",
- "PositivePromptField",
"QueueUiContext",
"ReferenceImageControls",
"StreamingImageFrame",
@@ -59,7 +57,6 @@
"WorkflowUiContext",
"api",
"backend",
- "baseGenerationPolicies",
"bboxGrid",
"canvasCompositing",
"canvasImportError",
@@ -67,27 +64,28 @@
"chakra",
"contracts",
"draftRegistry",
- "drafts",
"executeImageRecall",
"externalStore",
- "form",
"gallery",
"galleryDnd",
"galleryStateView",
- "generateDraftRegistry",
"generateFormViewModel",
"graph",
"http",
+ "identity",
"image-actions",
"imageUrls",
"index",
"nodeChrome",
+ "promptHistory",
+ "promptHistoryNavigation",
"queries",
"queueMenuActions",
"react",
"react",
"react",
"react",
+ "react",
"rolldown-runtime",
"selectedImage",
"selectors",
@@ -117,23 +115,20 @@
]
},
{
- "domContentLoadedMedianMs": 117.6999999997206,
+ "domContentLoadedMedianMs": 107.09999999776483,
"id": "editor-canvas",
- "loadMedianMs": 117.6999999997206,
- "longestTaskMaxMs": 103,
- "layoutSwitchMedianMs": 409.86311000000023,
+ "loadMedianMs": 107.09999999776483,
+ "longestTaskMaxMs": 116,
+ "layoutSwitchMedianMs": 405.7275000000009,
"projectSwitchMedianMs": 0,
"owner": "canvas",
"remediationTicket": "deepen-widget-registry-loading",
- "routeReadyMedianMs": 830.7999999998137,
+ "routeReadyMedianMs": 793.6999999992549,
"scriptRequests": [
"GalleryImageActionsBridge",
"GalleryUiContext",
- "GenerateCollapsibleSection",
- "GenerationUiContext",
"LayerContextMenu",
"ModelSelect",
- "PositivePromptField",
"QueueUiContext",
"ReferenceImageControls",
"StreamingImageFrame",
@@ -143,37 +138,36 @@
"WorkflowUiContext",
"api",
"backend",
- "baseGenerationPolicies",
"bboxGrid",
- "canvas",
"canvasCompositing",
"canvasImportError",
"canvasStrength",
"chakra",
+ "components",
"contracts",
"draftRegistry",
- "drafts",
"executeImageRecall",
"externalStore",
- "form",
"gallery",
"galleryDnd",
"galleryStateView",
- "generateDraftRegistry",
"generateFormViewModel",
"graph",
"http",
+ "identity",
"image-actions",
"imageUrls",
"index",
"nodeChrome",
- "prompt-ui",
+ "promptHistory",
+ "promptHistoryNavigation",
"queries",
"queueMenuActions",
"react",
"react",
"react",
"react",
+ "react",
"rolldown-runtime",
"selectedImage",
"selectors",
@@ -205,22 +199,19 @@
]
},
{
- "domContentLoadedMedianMs": 116.10000000009313,
+ "domContentLoadedMedianMs": 110.19999999925494,
"id": "editor-workflow",
- "loadMedianMs": 116.10000000009313,
- "longestTaskMaxMs": 102,
- "layoutSwitchMedianMs": 437.8898649999992,
+ "loadMedianMs": 110.30000000074506,
+ "longestTaskMaxMs": 117,
+ "layoutSwitchMedianMs": 414.1360140000015,
"projectSwitchMedianMs": 0,
"owner": "workflow",
"remediationTicket": "deepen-widget-registry-loading",
- "routeReadyMedianMs": 846.5,
+ "routeReadyMedianMs": 815.5,
"scriptRequests": [
"GalleryImageActionsBridge",
"GalleryUiContext",
- "GenerateCollapsibleSection",
- "GenerationUiContext",
"ModelSelect",
- "PositivePromptField",
"QueueUiContext",
"ReferenceImageControls",
"StreamingImageFrame",
@@ -230,7 +221,6 @@
"WorkflowUiContext",
"api",
"backend",
- "baseGenerationPolicies",
"bboxGrid",
"canvasCompositing",
"canvasImportError",
@@ -238,27 +228,28 @@
"chakra",
"contracts",
"draftRegistry",
- "drafts",
"executeImageRecall",
"externalStore",
- "form",
"gallery",
"galleryDnd",
"galleryStateView",
- "generateDraftRegistry",
"generateFormViewModel",
"graph",
"http",
+ "identity",
"image-actions",
"imageUrls",
"index",
"nodeChrome",
+ "promptHistory",
+ "promptHistoryNavigation",
"queries",
"queueMenuActions",
"react",
"react",
"react",
"react",
+ "react",
"rolldown-runtime",
"selectedImage",
"selectors",
@@ -288,22 +279,19 @@
]
},
{
- "domContentLoadedMedianMs": 118.10000000009313,
+ "domContentLoadedMedianMs": 102,
"id": "editor-gallery",
- "loadMedianMs": 118.10000000009313,
- "longestTaskMaxMs": 102,
- "layoutSwitchMedianMs": 390.20181899999807,
+ "loadMedianMs": 102,
+ "longestTaskMaxMs": 109,
+ "layoutSwitchMedianMs": 375.3589089999987,
"projectSwitchMedianMs": 0,
"owner": "gallery",
"remediationTicket": "deepen-widget-registry-loading",
- "routeReadyMedianMs": 800.8000000002794,
+ "routeReadyMedianMs": 765.0999999977648,
"scriptRequests": [
"GalleryImageActionsBridge",
"GalleryUiContext",
- "GenerateCollapsibleSection",
- "GenerationUiContext",
"ModelSelect",
- "PositivePromptField",
"QueueUiContext",
"ReferenceImageControls",
"StreamingImageFrame",
@@ -313,7 +301,6 @@
"WorkflowUiContext",
"api",
"backend",
- "baseGenerationPolicies",
"bboxGrid",
"canvasCompositing",
"canvasImportError",
@@ -321,27 +308,28 @@
"chakra",
"contracts",
"draftRegistry",
- "drafts",
"executeImageRecall",
"externalStore",
- "form",
"gallery",
"galleryDnd",
"galleryStateView",
- "generateDraftRegistry",
"generateFormViewModel",
"graph",
"http",
+ "identity",
"image-actions",
"imageUrls",
"index",
"nodeChrome",
+ "promptHistory",
+ "promptHistoryNavigation",
"queries",
"queueMenuActions",
"react",
"react",
"react",
"react",
+ "react",
"rolldown-runtime",
"selectedImage",
"selectors",
diff --git a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx
index 085f30e884..39b3e3b56e 100644
--- a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx
+++ b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx
@@ -4,11 +4,13 @@ import type { ReactNode } from 'react';
import { GalleryImageActionsProvider } from '@features/gallery/react';
import { ImageContextMenu, useImageActions, type ImageActions } from '@workbench/image-actions';
-export const GalleryImageContextMenu = ({ actions, ...props }: GalleryImageContextMenuProps) => (
+import { bindProductionPortBinding } from './productionPortBindings';
+
+const GalleryImageContextMenuComponent = ({ actions, ...props }: GalleryImageContextMenuProps) => (
<ImageContextMenu {...props} actions={actions as ImageActions} />
);
-export const GalleryImageActionsAdapter = ({
+const GalleryImageActionsAdapterComponent = ({
boards,
children,
generateValues,
@@ -20,3 +22,11 @@ export const GalleryImageActionsAdapter = ({
return <GalleryImageActionsProvider actions={actions}>{children}</GalleryImageActionsProvider>;
};
+
+const galleryImageActionsBridge = bindProductionPortBinding('gallery.image-actions-bridge', {
+ ImageActionsAdapter: GalleryImageActionsAdapterComponent,
+ ImageContextMenu: GalleryImageContextMenuComponent,
+});
+
+export const GalleryImageActionsAdapter = galleryImageActionsBridge.ImageActionsAdapter;
+export const GalleryImageContextMenu = galleryImageActionsBridge.ImageContextMenu;
diff --git a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
index 04a08cda88..d84e481f3d 100644
--- a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
+++ b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
@@ -12,9 +12,12 @@ import { WorkbenchSessionController } from '@workbench/WorkbenchSessionControlle
import { WorkbenchWidgetRegistryProvider } from '@workbench/WorkbenchWidgetRegistryContext';
import { useMemo } from 'react';
+import { bindProductionPortBinding } from './productionPortBindings';
import { QueueRuntimeAdapter } from './QueueRuntimeAdapter';
import { WorkbenchUiPorts } from './workbenchPorts';
+const WorkbenchQueueRuntime = bindProductionPortBinding('queue.workbench-runtime', QueueRuntimeAdapter);
+
/**
* The authenticated editor: providers, editor-only runtimes, and the shell.
* The shared backend socket is mounted above this route; `WorkbenchRuntime`
@@ -38,7 +41,7 @@ export const WorkbenchApp = () => {
<WorkbenchUiPorts>
<SessionExpiryGuard />
<WorkbenchHotkeyRuntime />
- <QueueRuntimeAdapter />
+ <WorkbenchQueueRuntime />
<WorkbenchRuntime />
<WorkbenchSessionController search={search} />
<WidgetHosts />
diff --git a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx
index 248e5a2008..bee84d476e 100644
--- a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx
@@ -1,13 +1,15 @@
-import type { WorkflowModelSelectProps, WorkflowUiAdapter } from '@features/workflow/react';
+import type { WorkflowGraphPreviewPort, WorkflowModelSelectProps, WorkflowUiAdapter } from '@features/workflow/react';
+import type { WorkbenchPreferences } from '@workbench/settings/contracts';
import type { ComponentType, ReactNode } from 'react';
import { flushGenerateDrafts } from '@features/generation/react';
-import { useAuthSession } from '@features/identity';
+import { getAuthSession, subscribeAuthSession } from '@features/identity';
import { ensureModelsLoaded, useModelsSelector } from '@features/models';
import { nodeExecutionStore } from '@features/nodes';
import { hasPendingWorkflowQueueItem } from '@features/queue';
-import { WorkflowUiProvider } from '@features/workflow/react';
+import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/react';
import { useMountEffect } from '@platform/react/useMountEffect';
+import { shallowEqual } from '@platform/state/selectors';
import { resolveAndSubmitGraphPreviewInvocation } from '@workbench/graphPreviewInvocation';
import { registerHotkeyModalLayer } from '@workbench/hotkeys';
import {
@@ -17,63 +19,131 @@ import {
resolveInvocationRouteInput,
} from '@workbench/invocation';
import { markWorkbenchPerf, measureWorkbenchPerf, timeWorkbenchPerf } from '@workbench/performanceMarks';
-import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
+import { getWorkbenchPreferences, subscribeWorkbenchPreferences } from '@workbench/settings/store';
import { useNotify } from '@workbench/useNotify';
import { getProjectWidgetValues } from '@workbench/widgetState';
import {
- shallowEqual,
useActiveProjectSelector,
useWorkbenchCommands,
+ useWorkbenchInternalStore,
useWorkbenchQueries,
} from '@workbench/WorkbenchContext';
import { lazy, useMemo } from 'react';
+import { createCachedWorkflowReadPort } from './cachedWorkflowReadPort';
+
const ModelSelect = lazy(() => import('@features/models/react').then((module) => ({ default: module.ModelSelect })));
const WorkflowModelSelect: ComponentType<WorkflowModelSelectProps> = ModelSelect;
const selectInvocationRouteInput = createInvocationRouteInputSelector();
-/**
- * Production binding of Workflow's UI port: wires Workbench commands, routes,
- * diagnostics, and Models/Nodes state. No second adapter is expected.
- */
-export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode }) => {
- const project = useActiveProjectSelector((activeProject) => ({
- activeProjectId: activeProject.id,
- galleryValues: getProjectWidgetValues(activeProject, 'gallery'),
- graphHistory: activeProject.graphHistory,
- isWorkflowRunning: hasPendingWorkflowQueueItem(activeProject.queue.items),
- projectGraph: activeProject.projectGraph,
- workflowValues: getProjectWidgetValues(activeProject, 'workflow'),
- }));
+const selectWorkflowPreferences = (preferences: WorkbenchPreferences) => ({
+ reduceMotion: preferences.reduceMotion,
+ themeId: preferences.themeId,
+ workflowEdgeStyle: preferences.workflowEdgeStyle,
+ workflowShowMinimap: preferences.workflowShowMinimap,
+ workflowSnapToGrid: preferences.workflowSnapToGrid,
+ workflowValidateConnections: preferences.workflowValidateConnections,
+});
+
+const WorkflowGraphPreviewAdapterProvider = ({ children }: { children: ReactNode }) => {
const routeInput = useActiveProjectSelector(selectInvocationRouteInput);
- const preferences = useWorkbenchPreferenceSelector(
- (value) => ({
- reduceMotion: value.reduceMotion,
- themeId: value.themeId,
- workflowEdgeStyle: value.workflowEdgeStyle,
- workflowShowMinimap: value.workflowShowMinimap,
- workflowSnapToGrid: value.workflowSnapToGrid,
- workflowValidateConnections: value.workflowValidateConnections,
- }),
- shallowEqual
- );
- const session = useAuthSession();
const models = useModelsSelector((snapshot) => snapshot.models);
const modelsStatus = useModelsSelector((snapshot) => snapshot.status);
const availabilityModels = modelsStatus === 'loaded' ? models : undefined;
const commands = useWorkbenchCommands();
const queries = useWorkbenchQueries();
+
+ const adapter = useMemo<WorkflowGraphPreviewPort>(
+ () => ({
+ getRoute: (sourceId) => {
+ if (!sourceId) {
+ return null;
+ }
+
+ const route = resolveInvocationRouteInput(
+ routeInput,
+ 'dialog',
+ { ...routeInput.invocation, sourceId, sourceLocked: true },
+ availabilityModels
+ );
+
+ return {
+ canInvoke: isInvocationRouteValid(route),
+ label: formatRoute(route),
+ validationMessage: route.validationMessage,
+ };
+ },
+ invoke: async (sourceId) => {
+ flushGenerateDrafts();
+ const { prepareCanvasInvocation } = await import('@workbench/widgets/canvas/invoke/prepareCanvasInvocation');
+ return resolveAndSubmitGraphPreviewInvocation({
+ commands,
+ models: availabilityModels,
+ prepareCanvasInvocation,
+ project: queries.getSnapshot().activeProject,
+ sourceId,
+ });
+ },
+ }),
+ [availabilityModels, commands, queries, routeInput]
+ );
+
+ return <WorkflowGraphPreviewProvider adapter={adapter}>{children}</WorkflowGraphPreviewProvider>;
+};
+
+/** Production binding of Workflow's stable services and narrow read ports. */
+export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode }) => {
+ const store = useWorkbenchInternalStore();
+ const commands = useWorkbenchCommands();
+ const queries = useWorkbenchQueries();
const notify = useNotify();
useMountEffect(() => {
ensureModelsLoaded();
});
+ const project = useMemo(
+ () =>
+ createCachedWorkflowReadPort(
+ store.subscribe,
+ store.getSnapshot,
+ (snapshot) => ({
+ galleryValues: getProjectWidgetValues(snapshot.activeProject, 'gallery'),
+ graphHistory: snapshot.activeProject.graphHistory,
+ id: snapshot.activeProject.id,
+ isWorkflowRunning: hasPendingWorkflowQueueItem(snapshot.activeProject.queue.items),
+ projectGraph: snapshot.activeProject.projectGraph,
+ workflowValues: getProjectWidgetValues(snapshot.activeProject, 'workflow'),
+ }),
+ shallowEqual
+ ),
+ [store]
+ );
+ const preferences = useMemo(
+ () =>
+ createCachedWorkflowReadPort(
+ (listener) => subscribeWorkbenchPreferences(listener),
+ getWorkbenchPreferences,
+ selectWorkflowPreferences,
+ shallowEqual
+ ),
+ []
+ );
+ const capabilities = useMemo(
+ () =>
+ createCachedWorkflowReadPort(
+ subscribeAuthSession,
+ getAuthSession,
+ (session) => ({ canUseCache: !session.multiuserEnabled || session.user?.is_admin === true }),
+ shallowEqual
+ ),
+ []
+ );
+
const adapter = useMemo<WorkflowUiAdapter>(
() => ({
- ...project,
ModelSelect: WorkflowModelSelect,
- canUseCache: !session.multiuserEnabled || session.user?.is_admin === true,
+ capabilities,
commands: {
bindLibraryWorkflow: commands.workflows.bindLibraryWorkflow,
editGraph: commands.workflows.editGraph,
@@ -84,37 +154,7 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })
undo: commands.workflows.undo,
},
getProjectGraph: () => queries.getSnapshot().activeProject.projectGraph,
- graphPreview: {
- getRoute: (sourceId) => {
- if (!sourceId) {
- return null;
- }
-
- const route = resolveInvocationRouteInput(
- routeInput,
- 'dialog',
- { ...routeInput.invocation, sourceId, sourceLocked: true },
- availabilityModels
- );
-
- return {
- canInvoke: isInvocationRouteValid(route),
- label: formatRoute(route),
- validationMessage: route.validationMessage,
- };
- },
- invoke: async (sourceId) => {
- flushGenerateDrafts();
- const { prepareCanvasInvocation } = await import('@workbench/widgets/canvas/invoke/prepareCanvasInvocation');
- return resolveAndSubmitGraphPreviewInvocation({
- commands,
- models: availabilityModels,
- prepareCanvasInvocation,
- project: queries.getSnapshot().activeProject,
- sourceId,
- });
- },
- },
+ nodeExecution: { get: nodeExecutionStore.get, subscribe: nodeExecutionStore.subscribe },
notifications: { error: notify.error, info: notify.info, success: notify.success },
performance: {
mark: (name, source) => markWorkbenchPerf(name, source),
@@ -122,27 +162,20 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })
time: (name, source, callback) => timeWorkbenchPerf(name, source, callback),
},
preferences,
+ project,
registerModalHotkeyLayer: registerHotkeyModalLayer,
- nodeExecution: { get: nodeExecutionStore.get, subscribe: nodeExecutionStore.subscribe },
widgets: {
open: (options) => commands.widgets.open(options),
patchValues: (widgetId, values) => commands.widgets.patchValues(widgetId, values),
select: (options) => commands.widgets.select(options),
},
}),
- [
- availabilityModels,
- commands,
- notify.error,
- notify.info,
- notify.success,
- preferences,
- project,
- queries,
- routeInput,
- session,
- ]
+ [capabilities, commands, notify.error, notify.info, notify.success, preferences, project, queries]
);
- return <WorkflowUiProvider adapter={adapter}>{children}</WorkflowUiProvider>;
+ return (
+ <WorkflowUiProvider adapter={adapter}>
+ <WorkflowGraphPreviewAdapterProvider>{children}</WorkflowGraphPreviewAdapterProvider>
+ </WorkflowUiProvider>
+ );
};
diff --git a/invokeai/frontend/webv2/src/app/cachedWorkflowReadPort.test.ts b/invokeai/frontend/webv2/src/app/cachedWorkflowReadPort.test.ts
new file mode 100644
index 0000000000..21561d01f2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/cachedWorkflowReadPort.test.ts
@@ -0,0 +1,42 @@
+import { shallowEqual } from '@platform/state/selectors';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createCachedWorkflowReadPort } from './cachedWorkflowReadPort';
+
+describe('createCachedWorkflowReadPort', () => {
+ it('keeps mapped snapshots stable and silent for unrelated source changes', () => {
+ let source = {
+ modelsRevision: 0,
+ notificationsRevision: 0,
+ projectId: 'project-1',
+ routeRevision: 0,
+ sessionRevision: 0,
+ };
+ const sourceListeners = new Set<() => void>();
+ const port = createCachedWorkflowReadPort(
+ (listener) => {
+ sourceListeners.add(listener);
+ return () => sourceListeners.delete(listener);
+ },
+ () => source,
+ (snapshot) => ({ id: snapshot.projectId }),
+ shallowEqual
+ );
+ const listener = vi.fn();
+ port.subscribe(listener);
+ const initial = port.getSnapshot();
+
+ source = { ...source, modelsRevision: 1, notificationsRevision: 1, routeRevision: 1, sessionRevision: 1 };
+ sourceListeners.forEach((notify) => notify());
+
+ expect(listener).not.toHaveBeenCalled();
+ expect(port.getSnapshot()).toBe(initial);
+
+ source = { ...source, projectId: 'project-2' };
+ sourceListeners.forEach((notify) => notify());
+
+ expect(listener).toHaveBeenCalledOnce();
+ expect(port.getSnapshot()).toEqual({ id: 'project-2' });
+ expect(port.getSnapshot()).toBe(port.getSnapshot());
+ });
+});
diff --git a/invokeai/frontend/webv2/src/app/cachedWorkflowReadPort.ts b/invokeai/frontend/webv2/src/app/cachedWorkflowReadPort.ts
new file mode 100644
index 0000000000..af2aefa7cd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/cachedWorkflowReadPort.ts
@@ -0,0 +1,40 @@
+import type { WorkflowReadPort } from '@features/workflow/react';
+import type { EqualityFn } from '@platform/state/selectors';
+
+/** Maps a broad external store to a referentially stable narrow read port. */
+export const createCachedWorkflowReadPort = <Source, Snapshot>(
+ subscribe: (listener: () => void) => () => void,
+ getSourceSnapshot: () => Source,
+ mapSnapshot: (source: Source) => Snapshot,
+ isEqual: EqualityFn<Snapshot> = Object.is
+): WorkflowReadPort<Snapshot> => {
+ let sourceSnapshot = getSourceSnapshot();
+ let snapshot = mapSnapshot(sourceSnapshot);
+
+ const refresh = (): boolean => {
+ const nextSourceSnapshot = getSourceSnapshot();
+ if (Object.is(nextSourceSnapshot, sourceSnapshot)) {
+ return false;
+ }
+ sourceSnapshot = nextSourceSnapshot;
+ const nextSnapshot = mapSnapshot(nextSourceSnapshot);
+ if (isEqual(snapshot, nextSnapshot)) {
+ return false;
+ }
+ snapshot = nextSnapshot;
+ return true;
+ };
+
+ return {
+ getSnapshot: () => {
+ refresh();
+ return snapshot;
+ },
+ subscribe: (listener) =>
+ subscribe(() => {
+ if (refresh()) {
+ listener();
+ }
+ }),
+ };
+};
diff --git a/invokeai/frontend/webv2/src/app/main.tsx b/invokeai/frontend/webv2/src/app/main.tsx
index 731bcd2c6e..bc3eb02109 100644
--- a/invokeai/frontend/webv2/src/app/main.tsx
+++ b/invokeai/frontend/webv2/src/app/main.tsx
@@ -6,10 +6,11 @@ import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App';
+import { mountProductionPortBinding } from './productionPortBindings';
// The only production binding that must exist before React mounts; all other
// bindings are enumerated in `app/workbenchPorts.tsx`.
-configureHttpAuth(identityTransportAuthAdapter);
+mountProductionPortBinding('platform.http-auth', () => configureHttpAuth(identityTransportAuthAdapter));
const rootElement = document.getElementById('root');
diff --git a/invokeai/frontend/webv2/src/app/productionPortBindings.ts b/invokeai/frontend/webv2/src/app/productionPortBindings.ts
new file mode 100644
index 0000000000..8c35e8f9d5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/productionPortBindings.ts
@@ -0,0 +1,48 @@
+export type ProductionPortBindingOwner =
+ | 'gallery'
+ | 'generation'
+ | 'models'
+ | 'platform'
+ | 'queue'
+ | 'upscale'
+ | 'workflow';
+
+export type ProductionPortBindingLifetime = 'pre-react' | 'authenticated-session' | 'editor' | 'lazy-editor';
+
+export interface ProductionPortBinding {
+ id: string;
+ lifetime: ProductionPortBindingLifetime;
+ owner: ProductionPortBindingOwner;
+}
+
+/** Complete, implementation-free inventory of App's production bindings. */
+export const productionPortBindingManifest = [
+ { id: 'platform.http-auth', lifetime: 'pre-react', owner: 'platform' },
+ { id: 'platform.authenticated-socket', lifetime: 'authenticated-session', owner: 'platform' },
+ { id: 'queue.workbench-runtime', lifetime: 'editor', owner: 'queue' },
+ { id: 'gallery.image-actions-bridge', lifetime: 'lazy-editor', owner: 'gallery' },
+ { id: 'models.ui', lifetime: 'editor', owner: 'models' },
+ { id: 'queue.ui', lifetime: 'editor', owner: 'queue' },
+ { id: 'gallery.ui', lifetime: 'editor', owner: 'gallery' },
+ { id: 'generation.ui', lifetime: 'editor', owner: 'generation' },
+ { id: 'upscale.ui', lifetime: 'editor', owner: 'upscale' },
+ { id: 'workflow.ui', lifetime: 'editor', owner: 'workflow' },
+] as const satisfies readonly ProductionPortBinding[];
+
+export type ProductionPortBindingId = (typeof productionPortBindingManifest)[number]['id'];
+
+const bindingIds = new Set<ProductionPortBindingId>(productionPortBindingManifest.map((binding) => binding.id));
+
+/** Typed mount declaration used by lifecycle-specific composition modules. */
+export const bindProductionPortBinding = <Mount>(id: ProductionPortBindingId, mount: Mount): Mount => {
+ if (!bindingIds.has(id)) {
+ throw new Error(`Unknown production port binding: ${id}`);
+ }
+ return mount;
+};
+
+/** Typed one-shot mount for the pre-React binding. */
+export const mountProductionPortBinding = <Result>(id: ProductionPortBindingId, mount: () => Result): Result => {
+ bindProductionPortBinding(id, mount);
+ return mount();
+};
diff --git a/invokeai/frontend/webv2/src/app/router.tsx b/invokeai/frontend/webv2/src/app/router.tsx
index fe1937d8bc..7ddd92da73 100644
--- a/invokeai/frontend/webv2/src/app/router.tsx
+++ b/invokeai/frontend/webv2/src/app/router.tsx
@@ -14,8 +14,11 @@ import { Launchpad } from '@workbench/launchpad/Launchpad';
import { peekOpenProjectIds, type WorkbenchSearch } from '@workbench/projects/session';
import { loadWorkbenchSettings } from '@workbench/settings/store';
+import { bindProductionPortBinding } from './productionPortBindings';
import { SocketHubRuntime } from './SocketHubRuntime';
+const AuthenticatedSocketRuntime = bindProductionPortBinding('platform.authenticated-socket', SocketHubRuntime);
+
/**
* Code-based route tree. The authenticated layout route owns the auth guard,
* which resolves the backend's multi-user status once per app load:
@@ -43,7 +46,7 @@ const rootRoute = createRootRoute({ component: Outlet });
*/
const AuthenticatedLayout = () => (
<>
- <SocketHubRuntime />
+ <AuthenticatedSocketRuntime />
<Outlet />
</>
);
diff --git a/invokeai/frontend/webv2/src/app/workbenchPorts.tsx b/invokeai/frontend/webv2/src/app/workbenchPorts.tsx
index 7cb7e91479..6373a28b54 100644
--- a/invokeai/frontend/webv2/src/app/workbenchPorts.tsx
+++ b/invokeai/frontend/webv2/src/app/workbenchPorts.tsx
@@ -5,31 +5,18 @@ import { composeProviders } from '@platform/react/composeProviders';
import { GalleryUiAdapterProvider } from './GalleryUiAdapter';
import { GenerationUiAdapterProvider } from './GenerationUiAdapter';
import { ModelsUiAdapterProvider } from './ModelsUiAdapter';
+import { bindProductionPortBinding } from './productionPortBindings';
import { QueueUiAdapterProvider } from './QueueUiAdapter';
import { UpscaleUiAdapterProvider } from './UpscaleUiAdapter';
import { WorkflowUiAdapterProvider } from './WorkflowUiAdapter';
-/**
- * The enumerable index of production port bindings: this file answers "what
- * does App bind in production?".
- *
- * Provider-shaped bindings are listed in `workbenchUiPortProviders` below.
- * The remaining production bindings are not providers and mount elsewhere:
- * - `QueueRuntimeAdapter` — mounted in `WorkbenchApp` (feeds Queue's runtime
- * its Nodes execution store and Models load-activity sink).
- * - `SocketHubRuntime` — mounted in `router.tsx`'s AuthenticatedLayout, above
- * the editor route.
- * - `GalleryImageActionsBridge` — lazy-loaded by `GalleryUiAdapter`.
- * - `configureHttpAuth(identityTransportAuthAdapter)` — called in `main.tsx`
- * before React mounts.
- */
export const workbenchUiPortProviders: ReadonlyArray<ProviderComponent> = [
- ModelsUiAdapterProvider,
- QueueUiAdapterProvider,
- GalleryUiAdapterProvider,
- GenerationUiAdapterProvider,
- UpscaleUiAdapterProvider,
- WorkflowUiAdapterProvider,
+ bindProductionPortBinding('models.ui', ModelsUiAdapterProvider),
+ bindProductionPortBinding('queue.ui', QueueUiAdapterProvider),
+ bindProductionPortBinding('gallery.ui', GalleryUiAdapterProvider),
+ bindProductionPortBinding('generation.ui', GenerationUiAdapterProvider),
+ bindProductionPortBinding('upscale.ui', UpscaleUiAdapterProvider),
+ bindProductionPortBinding('workflow.ui', WorkflowUiAdapterProvider),
];
/** All six feature UI ports, composed once at module scope (identity must be render-stable). */
diff --git a/invokeai/frontend/webv2/src/architecture/productionPortBindings.test.ts b/invokeai/frontend/webv2/src/architecture/productionPortBindings.test.ts
new file mode 100644
index 0000000000..f187641c9b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/architecture/productionPortBindings.test.ts
@@ -0,0 +1,53 @@
+import { productionPortBindingManifest } from '@app/productionPortBindings';
+import { describe, expect, it } from 'vitest';
+
+describe('production port binding composition', () => {
+ it('enumerates the complete production binding manifest', () => {
+ expect(productionPortBindingManifest).toEqual([
+ { id: 'platform.http-auth', lifetime: 'pre-react', owner: 'platform' },
+ { id: 'platform.authenticated-socket', lifetime: 'authenticated-session', owner: 'platform' },
+ { id: 'queue.workbench-runtime', lifetime: 'editor', owner: 'queue' },
+ { id: 'gallery.image-actions-bridge', lifetime: 'lazy-editor', owner: 'gallery' },
+ { id: 'models.ui', lifetime: 'editor', owner: 'models' },
+ { id: 'queue.ui', lifetime: 'editor', owner: 'queue' },
+ { id: 'gallery.ui', lifetime: 'editor', owner: 'gallery' },
+ { id: 'generation.ui', lifetime: 'editor', owner: 'generation' },
+ { id: 'upscale.ui', lifetime: 'editor', owner: 'upscale' },
+ { id: 'workflow.ui', lifetime: 'editor', owner: 'workflow' },
+ ]);
+ });
+
+ it('has exactly one production mount declaration for every binding', () => {
+ const appModules = import.meta.glob('../app/*.{ts,tsx}', {
+ eager: true,
+ import: 'default',
+ query: '?raw',
+ }) as Record<string, string>;
+ const source = Object.entries(appModules)
+ .filter(([fileName]) => !fileName.endsWith('/productionPortBindings.ts'))
+ .map(([, contents]) => contents)
+ .join('\n');
+
+ for (const binding of productionPortBindingManifest) {
+ const escapedId = binding.id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const mounts = source.match(
+ new RegExp(`(?:bindProductionPortBinding|mountProductionPortBinding)\\(['"]${escapedId}['"]`, 'g')
+ );
+ expect(mounts, binding.id).toHaveLength(1);
+ }
+ });
+
+ it('retains architecture inventories and performance reports in one CI artifact even on failure', () => {
+ const workflows = import.meta.glob('../../../../../.github/workflows/frontend-tests.yml', {
+ eager: true,
+ import: 'default',
+ query: '?raw',
+ }) as Record<string, string>;
+ const workflow = Object.values(workflows)[0] ?? '';
+
+ expect(workflow).toContain('name: webv2-architecture-review');
+ expect(workflow).toContain('invokeai/frontend/webv2/artifacts/architecture');
+ expect(workflow).toContain('invokeai/frontend/webv2/artifacts/architecture-performance');
+ expect(workflow).toContain('if: ${{ always()');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
index bf86ab9252..bcb2751224 100644
--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
@@ -56,6 +56,7 @@
"persistenceRuntime.ts": "workbench",
"projectContracts.ts": "workbench",
"queueHistoryContracts.ts": "workbench",
+ "queueHistoryNormalization.ts": "workbench",
"useCanvasProjectMutationDispatch.ts": "workbench",
"useNotify.ts": "workbench",
"useOpenWorkbenchWidget.ts": "workbench",
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/generateDraftRegistry.ts b/invokeai/frontend/webv2/src/features/generation/ui/generateDraftRegistry.ts
index 0937ef568d..971465fd4a 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/generateDraftRegistry.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/generateDraftRegistry.ts
@@ -1,4 +1,8 @@
-/** @deprecated Import the source-agnostic registry from widgets/draftRegistry. */
+/**
+ * @deprecated Import the source-agnostic Platform registry from
+ * `@platform/react/draftRegistry`. This wrapper only preserves Generation's
+ * established public names while callers migrate.
+ */
export {
flushWorkbenchDrafts as flushGenerateDrafts,
useRegisterDraftFlusher as useRegisterGenerateDraftFlusher,
diff --git a/invokeai/frontend/webv2/src/features/identity/index.ts b/invokeai/frontend/webv2/src/features/identity/index.ts
index cda478966e..f5ffe56faf 100644
--- a/invokeai/frontend/webv2/src/features/identity/index.ts
+++ b/invokeai/frontend/webv2/src/features/identity/index.ts
@@ -6,6 +6,7 @@ export {
getUserStorageScope,
loginWithCredentials,
logoutSession,
+ subscribeAuthSession,
useAuthSession,
type AuthSession,
} from './session';
diff --git a/invokeai/frontend/webv2/src/features/identity/session.ts b/invokeai/frontend/webv2/src/features/identity/session.ts
index b3a2b96be6..36b397cd9b 100644
--- a/invokeai/frontend/webv2/src/features/identity/session.ts
+++ b/invokeai/frontend/webv2/src/features/identity/session.ts
@@ -41,6 +41,9 @@ export const useAuthSession = (): AuthSession => store.useSnapshot();
*/
export const getAuthSession = (): AuthSession => store.getSnapshot();
+/** Stable subscription for App-composed capability read ports. */
+export const subscribeAuthSession = (listener: () => void): (() => void) => store.subscribe(listener);
+
/**
* Sticky across sign-out: a debounced autosave can still fire during the
* logout transition, and it must land in the bucket of the user whose data
diff --git a/invokeai/frontend/webv2/src/features/queue/contracts.ts b/invokeai/frontend/webv2/src/features/queue/contracts.ts
index 2f5fe3d585..10db8d69fe 100644
--- a/invokeai/frontend/webv2/src/features/queue/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/queue/contracts.ts
@@ -11,6 +11,7 @@ export type {
RunRecord,
} from './core/historyTypes';
export type {
+ QueueBackendGraph,
QueueCounts,
QueueCompiledSubmission,
QueueItemIdsReadModel,
@@ -21,10 +22,16 @@ export type {
QueueProcessorReadModel,
QueueQueryScope,
QueueReadModel,
+ QueueSourceId,
QueueStatusReadModel,
+ QueueSubmissionPresentation,
TerminalQueueItemStatus,
} from './core/types';
-export { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from './core/historySnapshot';
+export {
+ getQueueItemSnapshotBatchCount,
+ getQueueItemSnapshotDimensions,
+ getQueueItemSnapshotPositivePrompt,
+} from './core/historySnapshot';
export {
getProjectQueueIndicatorState,
getQueueItemExpectedImageCount,
diff --git a/invokeai/frontend/webv2/src/features/queue/core/historySnapshot.test.ts b/invokeai/frontend/webv2/src/features/queue/core/historySnapshot.test.ts
new file mode 100644
index 0000000000..ea4bbd6fa2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/core/historySnapshot.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import type { QueueItem } from './historyTypes';
+
+import {
+ getQueueItemSnapshotBatchCount,
+ getQueueItemSnapshotDimensions,
+ getQueueItemSnapshotPositivePrompt,
+} from './historySnapshot';
+
+describe('queue history snapshot presentation', () => {
+ it('uses safe shell fallbacks for legacy active and history items without presentation metadata', () => {
+ const item = {
+ id: 'legacy',
+ snapshot: { submittedAt: '2026-07-01T00:00:00.000Z' },
+ status: 'pending',
+ } as unknown as QueueItem;
+
+ expect(getQueueItemSnapshotBatchCount(item)).toBe(1);
+ expect(getQueueItemSnapshotDimensions(item, { height: 640, width: 960 })).toEqual({ height: 640, width: 960 });
+ expect(getQueueItemSnapshotPositivePrompt(item)).toBe('');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/queue/core/historySnapshot.ts b/invokeai/frontend/webv2/src/features/queue/core/historySnapshot.ts
index 4c86aaa64a..6211ce84d2 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/historySnapshot.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/historySnapshot.ts
@@ -1,11 +1,22 @@
import type { QueueItem } from './historyTypes';
-export const getQueueItemSnapshotBatchCount = (item: QueueItem): number => item.snapshot.presentation.batchCount;
+const getPresentation = (item: QueueItem): Partial<QueueItem['snapshot']['presentation']> =>
+ ((item as Partial<QueueItem>).snapshot as Partial<QueueItem['snapshot']> | undefined)?.presentation ?? {};
+
+export const getQueueItemSnapshotBatchCount = (item: QueueItem): number => {
+ const batchCount = getPresentation(item).batchCount;
+ return typeof batchCount === 'number' && Number.isFinite(batchCount) && batchCount > 0 ? batchCount : 1;
+};
+
+export const getQueueItemSnapshotPositivePrompt = (item: QueueItem): string => {
+ const positivePrompt = getPresentation(item).positivePrompt;
+ return typeof positivePrompt === 'string' ? positivePrompt : '';
+};
export const getQueueItemSnapshotDimensions = (
item: QueueItem,
fallback: { height: number; width: number }
): { height: number; width: number } => ({
- height: item.snapshot.presentation.height || fallback.height,
- width: item.snapshot.presentation.width || fallback.width,
+ height: getPresentation(item).height || fallback.height,
+ width: getPresentation(item).width || fallback.width,
});
diff --git a/invokeai/frontend/webv2/src/features/queue/index.ts b/invokeai/frontend/webv2/src/features/queue/index.ts
index adbd8a6cb3..0942ee7ab3 100644
--- a/invokeai/frontend/webv2/src/features/queue/index.ts
+++ b/invokeai/frontend/webv2/src/features/queue/index.ts
@@ -1,4 +1,5 @@
export type {
+ QueueBackendGraph,
QueueCounts,
QueueFeatureCommands,
QueueItemIdsReadModel,
@@ -9,7 +10,9 @@ export type {
QueueProcessorReadModel,
QueueQueryScope,
QueueReadModel,
+ QueueSourceId,
QueueStatusReadModel,
+ QueueSubmissionPresentation,
TerminalQueueItemStatus,
} from './core/types';
export type {
@@ -19,7 +22,11 @@ export type {
QueueSubmissionSnapshot,
RunRecord,
} from './core/historyTypes';
-export { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from './core/historySnapshot';
+export {
+ getQueueItemSnapshotBatchCount,
+ getQueueItemSnapshotDimensions,
+ getQueueItemSnapshotPositivePrompt,
+} from './core/historySnapshot';
export {
getProjectQueueIndicatorState,
getQueueItemExpectedImageCount,
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
index 67018ecfd4..fbc8c32599 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
@@ -4,7 +4,7 @@ import type { QueueBackendPort } from '@features/queue/core/types';
import { buildQueueItemOrigin } from '@features/queue/data/events';
import { describe, expect, it, vi } from 'vitest';
-import { createQueueRuntime, type QueueHistoryCommands } from './runtime';
+import { createQueueItemBackendSubmission, createQueueRuntime, type QueueHistoryCommands } from './runtime';
const createPendingQueueItem = (): QueueItem => ({
cancellable: true,
@@ -35,6 +35,16 @@ const createPendingQueueItem = (): QueueItem => ({
});
describe('queue runtime', () => {
+ it('turns a malformed legacy submission into a failed request instead of throwing', () => {
+ const queueItem = createPendingQueueItem();
+ delete (queueItem.snapshot as Partial<QueueItem['snapshot']>).backendSubmission;
+
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, queueItem)).toEqual({
+ error: 'Queue item is missing a compiled backend submission.',
+ kind: 'invalid',
+ });
+ });
+
it('adopts a persisted backend run before submission so reload cannot duplicate it', async () => {
const queueItem = createPendingQueueItem();
const project = { id: 'project-1', queue: { items: [queueItem] } };
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.ts
index 9fbff1a953..b8ab55e4db 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts
@@ -76,13 +76,47 @@ export const createQueueItemBackendSubmission = (
project: Pick<QueueHistoryProject, 'id'>,
queueItem: QueueItem
): QueueItemBackendSubmission => {
- const submission = queueItem.snapshot.backendSubmission;
+ const submission = (queueItem.snapshot as Partial<QueueItem['snapshot']>).backendSubmission;
+
+ if (!submission || typeof submission !== 'object' || !('kind' in submission)) {
+ return { error: 'Queue item is missing a compiled backend submission.', kind: 'invalid' };
+ }
+
+ if (submission.kind !== 'invalid' && submission.kind !== 'generate' && submission.kind !== 'workflow') {
+ return { error: 'Queue item has an unsupported compiled backend submission.', kind: 'invalid' };
+ }
if (submission.kind === 'invalid') {
- return submission;
+ return typeof submission.error === 'string'
+ ? submission
+ : { error: 'Queue item has an invalid compiled backend submission.', kind: 'invalid' };
+ }
+
+ if (!submission.graph || typeof submission.graph !== 'object') {
+ return { error: 'Queue item backend submission is missing its compiled graph.', kind: 'invalid' };
+ }
+
+ if (
+ typeof submission.batchCount !== 'number' ||
+ !Number.isFinite(submission.batchCount) ||
+ submission.batchCount < 1
+ ) {
+ return { error: 'Queue item backend submission has an invalid batch count.', kind: 'invalid' };
}
if (submission.kind === 'generate') {
+ if (
+ typeof submission.negativePrompt !== 'string' ||
+ typeof submission.negativePromptNodeId !== 'string' ||
+ typeof submission.positivePrompt !== 'string' ||
+ typeof submission.positivePromptNodeId !== 'string' ||
+ typeof submission.seed !== 'number' ||
+ !Number.isFinite(submission.seed) ||
+ typeof submission.seedNodeId !== 'string' ||
+ typeof submission.shouldRandomizeSeed !== 'boolean'
+ ) {
+ return { error: 'Queue item has malformed generate submission metadata.', kind: 'invalid' };
+ }
const { kind: _, ...compiled } = submission;
return {
kind: 'generate',
diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueDataStore.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueDataStore.ts
index a38a6a5d13..a1f51d38ec 100644
--- a/invokeai/frontend/webv2/src/features/queue/ui/queueDataStore.ts
+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueDataStore.ts
@@ -46,9 +46,6 @@ export const ensureQueueLoaded = (scope: QueueQueryScope = {}): void => {
void queryClient.ensureQueryData(getQueueReadModelOptions(scope, onQueueRead));
};
-/** @deprecated Scope is now part of each feature-owned query key. */
-export const setQueueScope = (_scope: QueueQueryScope): void => undefined;
-
export const useQueueCounts = (): QueueCounts => useQueueReadModel().data?.status.queue ?? EMPTY_COUNTS;
/** The processor is "paused" when it has been stopped. */
diff --git a/invokeai/frontend/webv2/src/features/workflow/react.ts b/invokeai/frontend/webv2/src/features/workflow/react.ts
index 974ac1f0be..7638690254 100644
--- a/invokeai/frontend/webv2/src/features/workflow/react.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/react.ts
@@ -1,4 +1,4 @@
export * from './data/templates';
-export { WorkflowUiProvider } from './ui/WorkflowUiContext';
-export type { WorkflowUiAdapter } from './ui/WorkflowUiContext';
+export { WorkflowGraphPreviewProvider, WorkflowUiProvider } from './ui/WorkflowUiContext';
+export type { WorkflowGraphPreviewPort, WorkflowReadPort, WorkflowUiAdapter } from './ui/WorkflowUiContext';
export type { WorkflowModelSelectProps } from './ui/contracts';
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.browser.test.tsx
new file mode 100644
index 0000000000..797fba1c2a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.browser.test.tsx
@@ -0,0 +1,168 @@
+import type { ReactNode } from 'react';
+
+import { act, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { WorkflowGraphPreviewPort, WorkflowReadPort, WorkflowUiAdapter } from './WorkflowUiContext';
+
+import {
+ useWorkflowCapabilitiesSelector,
+ useWorkflowGraphPreview,
+ useWorkflowPreferencesSelector,
+ useWorkflowProjectSelector,
+ useWorkflowUi,
+ WorkflowGraphPreviewProvider,
+ WorkflowUiProvider,
+} from './WorkflowUiContext';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const createMutablePort = <Snapshot,>(initialSnapshot: Snapshot) => {
+ let snapshot = initialSnapshot;
+ const listeners = new Set<() => void>();
+ const port: WorkflowReadPort<Snapshot> = {
+ getSnapshot: () => snapshot,
+ subscribe: (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ };
+ return {
+ port,
+ setSnapshot: (next: Snapshot) => {
+ snapshot = next;
+ for (const listener of listeners) {
+ listener();
+ }
+ },
+ };
+};
+
+const projectState = (id = 'project-1') => ({
+ galleryValues: {},
+ graphHistory: [],
+ id,
+ isWorkflowRunning: false,
+ projectGraph: { edges: [], nodes: [], version: 1 as const },
+ workflowValues: {},
+});
+
+const preferencesState = () => ({
+ reduceMotion: false,
+ themeId: 'classic' as const,
+ workflowEdgeStyle: 'curved' as const,
+ workflowShowMinimap: true,
+ workflowSnapToGrid: false,
+ workflowValidateConnections: true,
+});
+
+describe('Workflow UI read-port isolation', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ });
+
+ it('updates only consumers of the changed project, preference, capability, or graph-preview port', async () => {
+ const project = createMutablePort(projectState());
+ const preferences = createMutablePort(preferencesState());
+ const capabilities = createMutablePort({ canUseCache: true });
+ const counts = { capability: 0, graph: 0, preferences: 0, project: 0, projectEqual: 0, services: 0 };
+ // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime
+ const adapter = {
+ ModelSelect: () => null,
+ capabilities: capabilities.port,
+ commands: {},
+ getProjectGraph: () => project.port.getSnapshot().projectGraph,
+ nodeExecution: { get: () => null, subscribe: () => vi.fn() },
+ notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },
+ performance: { mark: vi.fn(), measure: vi.fn(), time: vi.fn() },
+ preferences: preferences.port,
+ project: project.port,
+ registerModalHotkeyLayer: vi.fn(() => vi.fn()),
+ widgets: {},
+ } as unknown as WorkflowUiAdapter;
+
+ let setGraphPreview: ((adapter: WorkflowGraphPreviewPort) => void) | null = null;
+ const initialGraphPreview: WorkflowGraphPreviewPort = {
+ getRoute: () => null,
+ invoke: () => Promise.resolve(false),
+ };
+ const GraphPreviewHarness = ({ children }: { children: ReactNode }) => {
+ const [graphPreview, setGraphPreviewState] = useState(initialGraphPreview);
+ setGraphPreview = setGraphPreviewState;
+ return <WorkflowGraphPreviewProvider adapter={graphPreview}>{children}</WorkflowGraphPreviewProvider>;
+ };
+ const ProjectConsumer = () => {
+ useWorkflowProjectSelector((snapshot) => snapshot.projectGraph);
+ counts.project += 1;
+ return null;
+ };
+ const EqualProjectConsumer = () => {
+ useWorkflowProjectSelector(
+ (snapshot) => [snapshot.id],
+ (left, right) => left[0] === right[0]
+ );
+ counts.projectEqual += 1;
+ return null;
+ };
+ const PreferencesConsumer = () => {
+ useWorkflowPreferencesSelector((snapshot) => snapshot.workflowSnapToGrid);
+ counts.preferences += 1;
+ return null;
+ };
+ const CapabilityConsumer = () => {
+ useWorkflowCapabilitiesSelector((snapshot) => snapshot.canUseCache);
+ counts.capability += 1;
+ return null;
+ };
+ const ServicesConsumer = () => {
+ useWorkflowUi();
+ counts.services += 1;
+ return null;
+ };
+ const GraphConsumer = () => {
+ useWorkflowGraphPreview();
+ counts.graph += 1;
+ return null;
+ };
+
+ await act(() => {
+ root.render(
+ <WorkflowUiProvider adapter={adapter}>
+ <GraphPreviewHarness>
+ <ProjectConsumer />
+ <EqualProjectConsumer />
+ <PreferencesConsumer />
+ <CapabilityConsumer />
+ <ServicesConsumer />
+ <GraphConsumer />
+ </GraphPreviewHarness>
+ </WorkflowUiProvider>
+ );
+ });
+ expect(counts).toEqual({ capability: 1, graph: 1, preferences: 1, project: 1, projectEqual: 1, services: 1 });
+
+ await act(() => project.setSnapshot({ ...projectState(), projectGraph: { edges: [], nodes: [], version: 1 } }));
+ expect(counts).toEqual({ capability: 1, graph: 1, preferences: 1, project: 2, projectEqual: 1, services: 1 });
+
+ await act(() => preferences.setSnapshot({ ...preferencesState(), workflowSnapToGrid: true }));
+ expect(counts).toEqual({ capability: 1, graph: 1, preferences: 2, project: 2, projectEqual: 1, services: 1 });
+
+ await act(() => capabilities.setSnapshot({ canUseCache: false }));
+ expect(counts).toEqual({ capability: 2, graph: 1, preferences: 2, project: 2, projectEqual: 1, services: 1 });
+
+ await act(() => setGraphPreview?.({ getRoute: () => null, invoke: () => Promise.resolve(true) }));
+ await act(() => setGraphPreview?.({ getRoute: () => null, invoke: () => Promise.resolve(false) }));
+ expect(counts).toEqual({ capability: 2, graph: 3, preferences: 2, project: 2, projectEqual: 1, services: 1 });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx
index d0cfcc5fad..835ecf05aa 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx
@@ -1,6 +1,7 @@
import type { ProjectGraphState } from '@features/workflow/core/types';
import type { ComponentType, ReactNode } from 'react';
+import { useExternalStoreSelector, type EqualityFn } from '@platform/state/selectors';
import { createContext, use, useCallback, useSyncExternalStore } from 'react';
import type {
@@ -22,20 +23,40 @@ export interface WorkflowPreferences {
workflowValidateConnections: boolean;
}
+export interface WorkflowProjectSnapshot {
+ galleryValues: Record<string, unknown>;
+ graphHistory: readonly WorkflowGraphHistoryEntry[];
+ id: string;
+ isWorkflowRunning: boolean;
+ projectGraph: ProjectGraphState;
+ workflowValues: Record<string, unknown>;
+}
+
+export interface WorkflowCapabilities {
+ canUseCache: boolean;
+}
+
+export interface WorkflowReadPort<Snapshot> {
+ getSnapshot(): Snapshot;
+ subscribe(listener: () => void): () => void;
+}
+
+export interface WorkflowGraphPreviewPort {
+ getRoute(
+ sourceId?: WorkflowInvocationSourceId
+ ): { canInvoke: boolean; label: string; validationMessage?: string } | null;
+ invoke(sourceId?: WorkflowInvocationSourceId): Promise<boolean>;
+}
+
/**
* Workflow's UI port. The context is a dependency-direction port (the feature
* may not import workbench), not a test seam; no second adapter is expected.
*/
export interface WorkflowUiAdapter {
ModelSelect: ComponentType<WorkflowModelSelectProps>;
- activeProjectId: string;
- canUseCache: boolean;
- galleryValues: Record<string, unknown>;
- graphHistory: readonly WorkflowGraphHistoryEntry[];
- isWorkflowRunning: boolean;
- preferences: WorkflowPreferences;
- projectGraph: ProjectGraphState;
- workflowValues: Record<string, unknown>;
+ capabilities: WorkflowReadPort<WorkflowCapabilities>;
+ preferences: WorkflowReadPort<WorkflowPreferences>;
+ project: WorkflowReadPort<WorkflowProjectSnapshot>;
commands: WorkflowCommands;
widgets: WorkflowWidgetCommands;
getProjectGraph(): ProjectGraphState;
@@ -44,12 +65,6 @@ export interface WorkflowUiAdapter {
info(title: string, message?: string): void;
success(title: string, message?: string): void;
};
- graphPreview: {
- getRoute(
- sourceId?: WorkflowInvocationSourceId
- ): { canInvoke: boolean; label: string; validationMessage?: string } | null;
- invoke(sourceId?: WorkflowInvocationSourceId): Promise<boolean>;
- };
performance: {
mark(name: string, source: WorkflowPerfSource): void;
measure(name: string, start: string, source: WorkflowPerfSource, end?: string): void;
@@ -63,11 +78,20 @@ export interface WorkflowUiAdapter {
}
const WorkflowUiContext = createContext<WorkflowUiAdapter | null>(null);
+const WorkflowGraphPreviewContext = createContext<WorkflowGraphPreviewPort | null>(null);
export const WorkflowUiProvider = ({ adapter, children }: { adapter: WorkflowUiAdapter; children: ReactNode }) => (
<WorkflowUiContext value={adapter}>{children}</WorkflowUiContext>
);
+export const WorkflowGraphPreviewProvider = ({
+ adapter,
+ children,
+}: {
+ adapter: WorkflowGraphPreviewPort;
+ children: ReactNode;
+}) => <WorkflowGraphPreviewContext value={adapter}>{children}</WorkflowGraphPreviewContext>;
+
export const useWorkflowUi = (): WorkflowUiAdapter => {
const adapter = use(WorkflowUiContext);
@@ -79,24 +103,11 @@ export const useWorkflowUi = (): WorkflowUiAdapter => {
};
export const useWorkflowProjectSelector = <Selected,>(
- selector: (project: {
- id: string;
- projectGraph: ProjectGraphState;
- graphHistory: readonly WorkflowGraphHistoryEntry[];
- galleryValues: Record<string, unknown>;
- workflowValues: Record<string, unknown>;
- isWorkflowRunning: boolean;
- }) => Selected
+ selector: (project: WorkflowProjectSnapshot) => Selected,
+ isEqual?: EqualityFn<Selected>
): Selected => {
- const ui = useWorkflowUi();
- return selector({
- galleryValues: ui.galleryValues,
- graphHistory: ui.graphHistory,
- id: ui.activeProjectId,
- isWorkflowRunning: ui.isWorkflowRunning,
- projectGraph: ui.projectGraph,
- workflowValues: ui.workflowValues,
- });
+ const { project } = useWorkflowUi();
+ return useExternalStoreSelector(project.subscribe, project.getSnapshot, selector, isEqual);
};
export const useWorkflowHostCommands = () => {
@@ -106,8 +117,27 @@ export const useWorkflowHostCommands = () => {
export const useWorkflowPreferencesSelector = <Selected,>(
selector: (preferences: WorkflowPreferences) => Selected,
- _isEqual?: (left: Selected, right: Selected) => boolean
-): Selected => selector(useWorkflowUi().preferences);
+ isEqual?: EqualityFn<Selected>
+): Selected => {
+ const { preferences } = useWorkflowUi();
+ return useExternalStoreSelector(preferences.subscribe, preferences.getSnapshot, selector, isEqual);
+};
+
+export const useWorkflowCapabilitiesSelector = <Selected,>(
+ selector: (capabilities: WorkflowCapabilities) => Selected,
+ isEqual?: EqualityFn<Selected>
+): Selected => {
+ const { capabilities } = useWorkflowUi();
+ return useExternalStoreSelector(capabilities.subscribe, capabilities.getSnapshot, selector, isEqual);
+};
+
+export const useWorkflowGraphPreview = (): WorkflowGraphPreviewPort => {
+ const graphPreview = use(WorkflowGraphPreviewContext);
+ if (!graphPreview) {
+ throw new Error('Workflow graph preview requires an App-composed WorkflowGraphPreviewProvider.');
+ }
+ return graphPreview;
+};
export const useWorkflowNotifications = () => useWorkflowUi().notifications;
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx
index f82a1a69d9..eaf41dc25c 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx
@@ -1,5 +1,5 @@
import { Box, Icon, Popover, Portal, Slider, Stack, Text } from '@chakra-ui/react';
-import { useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';
+import { useWorkflowPreferencesSelector } from '@features/workflow/ui/WorkflowUiContext';
import { IconButton, Toolbar, ToolbarButton, ToolbarSeparator, Tooltip } from '@platform/ui';
import { useReactFlow } from '@xyflow/react';
import {
@@ -47,7 +47,7 @@ export const EditorToolbar = ({
onToolChange: (tool: EditorTool) => void;
}) => {
const { fitView, zoomIn, zoomOut } = useReactFlow();
- const reduceMotion = useWorkflowUi().preferences.reduceMotion;
+ const reduceMotion = useWorkflowPreferencesSelector((preferences) => preferences.reduceMotion);
const opacityTriggerId = useId();
const fitViewDuration = reduceMotion ? 0 : 300;
const opacityIds = useMemo(() => ({ trigger: opacityTriggerId }), [opacityTriggerId]);
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
index 0cd529e4b3..9e62793e20 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
@@ -8,6 +8,7 @@ import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSelector } from
import { FlowMiniMap, flowThemeCss, getFlowColorMode } from '@features/workflow/ui/graph-preview';
import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';
import {
+ useWorkflowCapabilitiesSelector,
useWorkflowNotifications,
useWorkflowPreferencesSelector,
useWorkflowProjectSelector,
@@ -248,7 +249,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {
const templatesStatus = useInvocationTemplatesSelector((snapshot) => snapshot.status);
const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);
const invocationTemplates = templatesStatus === 'loaded' ? templates : undefined;
- const canUseCache = ui.canUseCache;
+ const canUseCache = useWorkflowCapabilitiesSelector((capabilities) => capabilities.canUseCache);
const edgeType: FlowEdgeType = workflowEdgeStyle === 'square' ? 'step' : 'default';
const isLargeGraph = isLargeWorkflowGraph({
edgeCount: projectGraph.edges.length,
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx
index 2512adb13a..ea1aee9581 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx
@@ -2,7 +2,7 @@ import type { XYPosition } from '@features/workflow/contracts';
import type { WorkflowInvocationSourceId, WorkflowPreviewGraph } from '@features/workflow/ui/contracts';
import { Box, Dialog, Portal, SegmentGroup, Text } from '@chakra-ui/react';
-import { useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';
+import { useWorkflowGraphPreview } from '@features/workflow/ui/WorkflowUiContext';
import { Button, JsonPreview } from '@platform/ui';
import { useCallback, useMemo, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
@@ -43,7 +43,7 @@ export const GraphPreviewDialog = ({
onOpenChange,
}: GraphPreviewDialogProps) => {
const { t } = useTranslation();
- const { graphPreview } = useWorkflowUi();
+ const graphPreview = useWorkflowGraphPreview();
const [mode, setMode] = useState<PreviewMode>('nodes');
const dialogRoute = graphPreview.getRoute(sourceId);
const canInvoke = dialogRoute?.canInvoke === true;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
index 634b58ad72..c0c9bafb14 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
@@ -32,6 +32,7 @@ export {
type ComposeForGenerationOptions,
type ComposeForGenerationResult,
type GenerationCompositeExecutorDeps,
+ type GenerationCompositeDedupeCommit,
type GenerationCompositeHost,
type GenerationCompositeMode,
type GenerationComposites,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts
index 6fb8347bfd..e0de0a565b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts
@@ -413,7 +413,7 @@ describe('composeForGeneration', () => {
expect(order).toEqual(['control:control-a', 'control:control-b', 'regional:region-a', 'regional:region-b']);
});
- it('commits the dedupe cache on success so a second compose reuses every upload', async () => {
+ it('publishes dedupe only through an idempotent success commit so a retry reuses every upload', async () => {
const document = makeDoc([rasterLayer('base'), controlLayer('control-a')]);
const harness = makeHost(document);
@@ -421,12 +421,20 @@ describe('composeForGeneration', () => {
expect(first.status).toBe('ok');
const uploadsAfterFirst = harness.uploadImage.mock.calls.length;
expect(uploadsAfterFirst).toBe(2);
- expect(harness.host.dedupe.byKey.size).toBeGreaterThan(0);
+ expect(harness.host.dedupe.byKey.size).toBe(0);
+ if (first.status !== 'ok') {
+ return;
+ }
+ first.dedupeCommit.commit();
+ const committedKeyCount = harness.host.dedupe.byKey.size;
+ expect(committedKeyCount).toBeGreaterThan(0);
+ first.dedupeCommit.commit();
+ expect(harness.host.dedupe.byKey.size).toBe(committedKeyCount);
const second = await compose(harness.host);
expect(second.status).toBe('ok');
expect(harness.uploadImage.mock.calls.length).toBe(uploadsAfterFirst);
- if (first.status === 'ok' && second.status === 'ok') {
+ if (second.status === 'ok') {
expect(second.composites.baseImageName).toBe(first.composites.baseImageName);
expect(second.composites.controlImages).toEqual(first.composites.controlImages);
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
index 9cfd5e7a96..3fc9e2f848 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
@@ -23,11 +23,10 @@
* - `shouldCompositeRegionalMask` vets each planned regional-guidance layer in
* z-order: `false` silently skips the region (no upload).
*
- * Semantic delta vs. the old transaction (documented, intentional): the dedupe
- * commit happens when every composite has succeeded, not after the caller
- * submits the graph. The cache only enables reuse of correctly uploaded
- * content-hashed intermediates, so committing at composite-success is not
- * product-visible — a later submit failure never invalidates the uploads.
+ * Successful composition returns one opaque, idempotent dedupe commit. The
+ * caller publishes it only after graph compilation and synchronous queue
+ * dispatch both succeed; every earlier failure discards the operation-local
+ * cache while the uploaded intermediates remain safe to retry.
*/
import type {
@@ -118,10 +117,18 @@ export interface GenerationCompositeHost {
): Promise<CaptureRasterSnapshotResult>;
/** The engine's composite executor deps (backend, upload, reserve, ...). */
getCompositeExecutorDeps(): GenerationCompositeExecutorDeps;
- /** Engine-scoped dedupe cache, merged into only after every composite succeeds. */
+ /** Engine-scoped dedupe cache, merged into only by the returned commit. */
dedupe: CompositeDedupeCache;
}
+declare const generationCompositeDedupeCommitBrand: unique symbol;
+
+/** Opaque publication handle; callers may only commit the completed transaction. */
+export interface GenerationCompositeDedupeCommit {
+ readonly [generationCompositeDedupeCommitBrand]: true;
+ commit(): void;
+}
+
/** Everything a canvas invoke needs from the composite pipeline. */
export interface GenerationComposites {
/** The frozen canvas state the composites were built from (for the enqueue snapshot). */
@@ -143,7 +150,7 @@ export interface GenerationComposites {
}
export type ComposeForGenerationResult =
- | { status: 'ok'; composites: GenerationComposites }
+ | { status: 'ok'; composites: GenerationComposites; dedupeCommit: GenerationCompositeDedupeCommit }
| { status: 'no-document' | 'stale' | 'aborted' | 'not-ready' | 'over-budget' };
/**
@@ -188,8 +195,8 @@ export const composeForGeneration = async (
}
const rasterSnapshot = capture.snapshot;
- // Operation-scoped dedupe: composites read/write a copy, merged back into the
- // host cache only after every composite succeeded (see the module doc).
+ // Operation-scoped dedupe: composites read/write a copy. Publication remains
+ // provisional until the caller successfully compiles and dispatches.
const operationDedupe: CompositeDedupeCache = {
byHash: new Map(host.dedupe.byHash),
byKey: new Map(host.dedupe.byKey),
@@ -279,14 +286,21 @@ export const composeForGeneration = async (
regionalMaskImages.push({ imageName: result.imageName, layerId });
}
- // Every composite succeeded: publish the operation's dedupe entries so the
- // next invoke reuses the uploads (see the module doc for the timing note).
- for (const [key, value] of operationDedupe.byHash) {
- host.dedupe.byHash.set(key, value);
- }
- for (const [key, value] of operationDedupe.byKey) {
- host.dedupe.byKey.set(key, value);
- }
+ let isCommitted = false;
+ const dedupeCommit = {
+ commit: (): void => {
+ if (isCommitted) {
+ return;
+ }
+ isCommitted = true;
+ for (const [key, value] of operationDedupe.byHash) {
+ host.dedupe.byHash.set(key, value);
+ }
+ for (const [key, value] of operationDedupe.byKey) {
+ host.dedupe.byKey.set(key, value);
+ }
+ },
+ } as GenerationCompositeDedupeCommit;
return {
composites: {
@@ -299,6 +313,7 @@ export const composeForGeneration = async (
noiseMaskImageName,
regionalMaskImages,
},
+ dedupeCommit,
status: 'ok',
};
} finally {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
index f4883dea2a..fe91d93816 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
@@ -4,7 +4,7 @@ import type { Project, WorkbenchState } from '@workbench/projectContracts';
import { getUserStorageScope } from '@features/identity';
import { timeWorkbenchPerf } from '@workbench/performanceMarks';
import { localStorageWorkbenchPersistence, stripTransientWorkbenchState } from '@workbench/persistence';
-import { createDraftProject, createInitialWorkbenchState } from '@workbench/workbenchState';
+import { createDraftProject, createInitialWorkbenchState, normalizeWorkbenchProject } from '@workbench/workbenchState';
import {
createProject as apiCreateProject,
@@ -187,7 +187,10 @@ export const deserializeProjectDocument = (data: Record<string, unknown>): Proje
return null;
}
- return { ...normalizedData, undoRedo: { future: [], past: [] } } as unknown as Project;
+ return normalizeWorkbenchProject({
+ ...normalizedData,
+ undoRedo: { future: [], past: [] },
+ } as unknown as Project);
};
const getSyncMapStorageKey = (): string => `${SYNC_MAP_BASE_KEY}${getUserStorageScope()}`;
diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.ts
new file mode 100644
index 0000000000..ef77dc26b1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.ts
@@ -0,0 +1,219 @@
+import type { GenerateWidgetValues } from '@features/generation/contracts';
+
+import { describe, expect, it } from 'vitest';
+
+import { normalizeWorkbenchQueueHistory } from './queueHistoryNormalization';
+import { createInitialWorkbenchState } from './workbenchState.testing';
+
+const backendGraph = { edges: [], id: 'backend-graph', nodes: {} };
+
+const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWidgetValues =>
+ ({
+ aspectRatioId: '1:1',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 1,
+ batchCount: 3,
+ cfgRescaleMultiplier: 0,
+ cfgScale: 7,
+ clipEmbedModel: null,
+ clipGEmbedModel: null,
+ clipLEmbedModel: null,
+ clipSkip: 0,
+ colorCompensation: false,
+ componentSourceModel: null,
+ height: 768,
+ loras: [],
+ model: { base: 'sdxl', key: 'model', name: 'Model', type: 'main' },
+ modelKey: 'model',
+ negativePrompt: 'fog',
+ negativePromptEnabled: true,
+ negativePromptHeightPx: 80,
+ positivePrompt: 'a lighthouse',
+ positivePromptHeightPx: 80,
+ qwen3EncoderModel: null,
+ qwenVLEncoderModel: null,
+ referenceImages: [],
+ scheduler: 'euler',
+ seamlessXAxis: false,
+ seamlessYAxis: false,
+ seed: 42,
+ shouldRandomizeSeed: false,
+ steps: 20,
+ t5EncoderModel: null,
+ vae: null,
+ vaePrecision: 'fp32',
+ width: 1024,
+ ...overrides,
+ }) as GenerateWidgetValues;
+
+const createContext = () => {
+ const project = createInitialWorkbenchState().projects[0]!;
+ return { canvas: project.canvas, widgetInstances: project.widgetInstances };
+};
+
+const createLegacyItem = (
+ sourceId: string,
+ options: {
+ generate?: Record<string, unknown>;
+ status?: string;
+ widgetStates?: Record<string, unknown>;
+ } = {}
+) => ({
+ cancellable: true,
+ id: `legacy-${sourceId}`,
+ snapshot: {
+ canvas: createContext().canvas,
+ destination: 'gallery',
+ ...(options.generate ? { generate: options.generate } : {}),
+ graph: { backendGraph, edges: [], id: 'graph', label: 'Legacy', nodes: [], updatedAt: '', version: 1 },
+ sourceId,
+ submittedAt: '2026-07-01T00:00:00.000Z',
+ widgetInstances: createContext().widgetInstances,
+ widgetStates: options.widgetStates ?? {},
+ },
+ status: options.status ?? 'pending',
+});
+
+const state = (id: string, values: unknown) => ({ id, label: id, values, version: 1 });
+
+describe('normalizeWorkbenchQueueHistory', () => {
+ it('preserves already-current queue snapshots by identity', () => {
+ const current = {
+ ...createLegacyItem('workflow'),
+ snapshot: {
+ ...createLegacyItem('workflow').snapshot,
+ backendSubmission: { batchCount: 1, graph: backendGraph, kind: 'workflow' },
+ filterIntermediateResults: true,
+ galleryBoardId: null,
+ presentation: { batchCount: 1, height: 512, width: 512 },
+ },
+ };
+ const queue = { items: [current] };
+
+ expect(normalizeWorkbenchQueueHistory(queue, createContext())).toBe(queue);
+ });
+
+ it.each(['pending', 'completed'] as const)('upgrades legacy Generate items with %s status', (status) => {
+ const values = createGenerateValues();
+ const item = createLegacyItem('generate', {
+ status,
+ widgetStates: {
+ gallery: state('gallery', { selectedBoardId: 'board-1' }),
+ generate: state('generate', values),
+ },
+ });
+
+ const normalized = normalizeWorkbenchQueueHistory({ items: [item] }, createContext()).items[0]!;
+
+ expect(normalized.status).toBe(status);
+ expect(normalized.snapshot.backendSubmission).toEqual({
+ batchCount: 3,
+ graph: backendGraph,
+ kind: 'generate',
+ negativePrompt: 'fog',
+ negativePromptNodeId: 'negative_prompt',
+ positivePrompt: 'a lighthouse',
+ positivePromptNodeId: 'positive_prompt',
+ seed: 42,
+ seedNodeId: 'seed',
+ shouldRandomizeSeed: false,
+ });
+ expect(normalized.snapshot.presentation).toEqual({
+ batchCount: 3,
+ height: 768,
+ positivePrompt: 'a lighthouse',
+ width: 1024,
+ });
+ expect(normalized.snapshot).toMatchObject({
+ filterIntermediateResults: false,
+ galleryBoardId: 'board-1',
+ resultNodeIds: ['canvas_output'],
+ });
+ });
+
+ it('upgrades Canvas items both before and after the captured generate payload was added', () => {
+ const widgetValues = createGenerateValues({ positivePrompt: 'widget prompt', seed: 10 });
+ const capturedValues = createGenerateValues({ positivePrompt: 'captured prompt', seed: 99 });
+ const withoutCapture = createLegacyItem('canvas', {
+ widgetStates: { generate: state('generate', widgetValues) },
+ });
+ const withCapture = createLegacyItem('canvas', {
+ generate: {
+ negativePromptNodeId: 'captured-negative',
+ positivePromptNodeId: 'captured-positive',
+ seedNodeId: 'captured-seed',
+ values: capturedValues,
+ },
+ widgetStates: { generate: state('generate', widgetValues) },
+ });
+
+ const [before, after] = normalizeWorkbenchQueueHistory(
+ { items: [withoutCapture, withCapture] },
+ createContext()
+ ).items;
+
+ expect(before?.snapshot.backendSubmission).toMatchObject({ positivePrompt: 'widget prompt', seed: 10 });
+ expect(after?.snapshot.backendSubmission).toMatchObject({
+ negativePromptNodeId: 'captured-negative',
+ positivePrompt: 'captured prompt',
+ positivePromptNodeId: 'captured-positive',
+ seed: 99,
+ seedNodeId: 'captured-seed',
+ });
+ });
+
+ it('upgrades Upscale dimensions and Workflow filtering with source-specific submission rules', () => {
+ const upscale = createLegacyItem('upscale', {
+ widgetStates: {
+ upscale: state('upscale', {
+ batchCount: 2,
+ inputImage: { height: 101, image_name: 'input.png', width: 203 },
+ positivePrompt: 'more detail',
+ scale: 2.5,
+ seed: 7,
+ shouldRandomizeSeed: true,
+ }),
+ },
+ });
+ const workflow = createLegacyItem('project-graph', {
+ widgetStates: { generate: state('generate', { batchCount: 4 }) },
+ });
+
+ const [upscaleResult, workflowResult] = normalizeWorkbenchQueueHistory(
+ { items: [upscale, workflow] },
+ createContext()
+ ).items;
+
+ expect(upscaleResult?.snapshot.backendSubmission).toMatchObject({
+ batchCount: 2,
+ kind: 'generate',
+ positivePrompt: 'more detail',
+ seed: 7,
+ shouldRandomizeSeed: true,
+ });
+ expect(upscaleResult?.snapshot.presentation).toEqual({ batchCount: 2, height: 248, width: 504 });
+ expect(upscaleResult?.snapshot.resultNodeIds).toEqual(['upscale_output']);
+ expect(workflowResult?.snapshot).toMatchObject({
+ backendSubmission: { batchCount: 4, graph: backendGraph, kind: 'workflow' },
+ filterIntermediateResults: true,
+ sourceId: 'workflow',
+ });
+ expect(workflowResult?.snapshot.resultNodeIds).toBeUndefined();
+ });
+
+ it('turns unrecoverable and malformed snapshots into safe invalid submissions', () => {
+ const malformed = { id: 'broken', snapshot: { sourceId: 'generate' }, status: 'pending' };
+ const normalized = normalizeWorkbenchQueueHistory({ items: [malformed, null] }, createContext()).items;
+
+ expect(normalized[0]?.snapshot.backendSubmission).toEqual({
+ error: 'Legacy generate queue item is missing a compiled backend graph.',
+ kind: 'invalid',
+ });
+ expect(normalized[0]?.snapshot.presentation.batchCount).toBe(1);
+ expect(normalized[1]).toMatchObject({
+ id: 'invalid-legacy-queue-item-1',
+ snapshot: { backendSubmission: { kind: 'invalid' }, presentation: { batchCount: 1 } },
+ status: 'failed',
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts
new file mode 100644
index 0000000000..87b8bf78ff
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts
@@ -0,0 +1,279 @@
+import type {
+ QueueBackendGraph,
+ QueueCompiledSubmission,
+ QueueSourceId,
+ QueueSubmissionPresentation,
+} from '@features/queue/contracts';
+import type { CanvasStateContractV2 } from '@workbench/canvas-engine/api';
+import type { GraphContract } from '@workbench/graphContracts';
+import type { WidgetInstanceContract, WidgetInstanceId, WidgetStateMap } from '@workbench/widgetContracts';
+
+import { normalizeGenerateSettings, sanitizeBatchCount } from '@features/generation/settings';
+import { getUpscaleOutputDimensions, normalizeUpscaleWidgetValues } from '@features/upscale';
+
+import type { WorkbenchQueueItem, WorkbenchQueueState } from './queueHistoryContracts';
+
+import { migrateCanvasStateToV2 } from './canvasMigration';
+
+type UnknownRecord = Record<string, unknown>;
+type PresentationSource = { batchCount: number; height?: number; positivePrompt?: string; width?: number } | null;
+
+export interface QueueHistoryNormalizationContext {
+ canvas: CanvasStateContractV2;
+ widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;
+}
+
+const isRecord = (value: unknown): value is UnknownRecord => value !== null && typeof value === 'object';
+
+const normalizeSourceId = (value: unknown): QueueSourceId | null => {
+ if (value === 'project-graph') {
+ return 'workflow';
+ }
+ if (value === 'canvas-fill') {
+ return 'canvas';
+ }
+ return value === 'canvas' || value === 'generate' || value === 'upscale' || value === 'workflow' ? value : null;
+};
+
+const isBackendGraph = (value: unknown): value is QueueBackendGraph =>
+ isRecord(value) && typeof value.id === 'string' && isRecord(value.nodes) && Array.isArray(value.edges);
+
+const isCurrentBackendSubmission = (value: unknown): value is QueueCompiledSubmission => {
+ if (!isRecord(value) || typeof value.kind !== 'string') {
+ return false;
+ }
+ if (value.kind === 'invalid') {
+ return typeof value.error === 'string';
+ }
+ if (
+ (value.kind !== 'generate' && value.kind !== 'workflow') ||
+ !isBackendGraph(value.graph) ||
+ typeof value.batchCount !== 'number' ||
+ !Number.isFinite(value.batchCount) ||
+ value.batchCount < 1
+ ) {
+ return false;
+ }
+ if (value.kind === 'workflow') {
+ return true;
+ }
+ return (
+ typeof value.negativePrompt === 'string' &&
+ typeof value.negativePromptNodeId === 'string' &&
+ typeof value.positivePrompt === 'string' &&
+ typeof value.positivePromptNodeId === 'string' &&
+ typeof value.seed === 'number' &&
+ Number.isFinite(value.seed) &&
+ typeof value.seedNodeId === 'string' &&
+ typeof value.shouldRandomizeSeed === 'boolean'
+ );
+};
+
+const isCurrentPresentation = (value: unknown): value is QueueSubmissionPresentation =>
+ isRecord(value) &&
+ typeof value.batchCount === 'number' &&
+ Number.isFinite(value.batchCount) &&
+ value.batchCount > 0 &&
+ typeof value.height === 'number' &&
+ Number.isFinite(value.height) &&
+ value.height > 0 &&
+ typeof value.width === 'number' &&
+ Number.isFinite(value.width) &&
+ value.width > 0;
+
+const isCurrentSnapshot = (value: UnknownRecord): boolean =>
+ isCurrentBackendSubmission(value.backendSubmission) &&
+ isCurrentPresentation(value.presentation) &&
+ normalizeSourceId(value.sourceId) === value.sourceId &&
+ (value.destination === 'canvas' || value.destination === 'gallery') &&
+ isRecord(value.graph) &&
+ (value.galleryBoardId === null || typeof value.galleryBoardId === 'string') &&
+ typeof value.filterIntermediateResults === 'boolean' &&
+ typeof value.submittedAt === 'string';
+
+const getWidgetStates = (snapshot: UnknownRecord): WidgetStateMap =>
+ isRecord(snapshot.widgetStates) ? (snapshot.widgetStates as WidgetStateMap) : {};
+
+const getWidgetValues = (widgetStates: WidgetStateMap, widgetId: string): unknown => {
+ const state = widgetStates[widgetId];
+ return isRecord(state) && isRecord(state.values) ? state.values : undefined;
+};
+
+const getGenerateCapture = (snapshot: UnknownRecord): UnknownRecord | null =>
+ isRecord(snapshot.generate) ? snapshot.generate : null;
+
+const getFiniteDimension = (value: unknown, fallback: number): number =>
+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback;
+
+const createInvalidSubmission = (message: string): QueueCompiledSubmission => ({ error: message, kind: 'invalid' });
+
+const getBackendSubmission = (
+ sourceId: QueueSourceId | null,
+ snapshot: UnknownRecord,
+ widgetStates: WidgetStateMap
+): { presentationSource: PresentationSource; submission: QueueCompiledSubmission } => {
+ const graph = isRecord(snapshot.graph) ? snapshot.graph : null;
+ const backendGraph = graph?.backendGraph;
+ const generateCapture = getGenerateCapture(snapshot);
+ const generateValues = getWidgetValues(widgetStates, 'generate');
+ const presentationSource = normalizeGenerateSettings(
+ sourceId === 'canvas' ? (generateCapture?.values ?? generateValues) : generateValues
+ );
+
+ if (!sourceId) {
+ return {
+ presentationSource,
+ submission: createInvalidSubmission('Legacy queue item has an unsupported or missing source.'),
+ };
+ }
+ if (!isBackendGraph(backendGraph)) {
+ return {
+ presentationSource,
+ submission: createInvalidSubmission(`Legacy ${sourceId} queue item is missing a compiled backend graph.`),
+ };
+ }
+ if (sourceId === 'workflow') {
+ return {
+ presentationSource,
+ submission: {
+ batchCount: sanitizeBatchCount(isRecord(generateValues) ? generateValues.batchCount : undefined),
+ graph: backendGraph,
+ kind: 'workflow',
+ },
+ };
+ }
+
+ const sourceSettings =
+ sourceId === 'upscale'
+ ? normalizeUpscaleWidgetValues(getWidgetValues(widgetStates, 'upscale'))
+ : sourceId === 'canvas'
+ ? normalizeGenerateSettings(generateCapture?.values ?? generateValues)
+ : normalizeGenerateSettings(generateValues);
+
+ if (!sourceSettings) {
+ return {
+ presentationSource,
+ submission: createInvalidSubmission(`Legacy ${sourceId} queue item is missing source submission metadata.`),
+ };
+ }
+
+ return {
+ presentationSource: sourceId === 'upscale' ? null : sourceSettings,
+ submission: {
+ batchCount: sourceSettings.batchCount,
+ graph: backendGraph,
+ kind: 'generate',
+ negativePrompt: sourceSettings.negativePromptEnabled ? sourceSettings.negativePrompt : '',
+ negativePromptNodeId:
+ typeof generateCapture?.negativePromptNodeId === 'string'
+ ? generateCapture.negativePromptNodeId
+ : 'negative_prompt',
+ positivePrompt: sourceSettings.positivePrompt,
+ positivePromptNodeId:
+ typeof generateCapture?.positivePromptNodeId === 'string'
+ ? generateCapture.positivePromptNodeId
+ : 'positive_prompt',
+ seed: sourceSettings.seed,
+ seedNodeId: typeof generateCapture?.seedNodeId === 'string' ? generateCapture.seedNodeId : 'seed',
+ shouldRandomizeSeed: sourceSettings.shouldRandomizeSeed,
+ },
+ };
+};
+
+const normalizeLegacyQueueItem = (
+ value: unknown,
+ index: number,
+ context: QueueHistoryNormalizationContext
+): WorkbenchQueueItem => {
+ const item = isRecord(value) ? value : {};
+ const snapshot = isRecord(item.snapshot) ? item.snapshot : {};
+ const sourceId = normalizeSourceId(snapshot.sourceId);
+ const widgetStates = getWidgetStates(snapshot);
+ const { presentationSource, submission } = getBackendSubmission(sourceId, snapshot, widgetStates);
+ const upscaleValues =
+ sourceId === 'upscale' ? normalizeUpscaleWidgetValues(getWidgetValues(widgetStates, 'upscale')) : null;
+ const canvas = migrateCanvasStateToV2(snapshot.canvas ?? context.canvas);
+ const canvasDocument = canvas.document;
+ const dimensions =
+ upscaleValues?.inputImage && Number.isFinite(upscaleValues.scale)
+ ? getUpscaleOutputDimensions(upscaleValues.inputImage, upscaleValues.scale)
+ : {
+ height: getFiniteDimension(presentationSource?.height, canvasDocument.height),
+ width: getFiniteDimension(presentationSource?.width, canvasDocument.width),
+ };
+ const galleryValues = getWidgetValues(widgetStates, 'gallery');
+ const selectedBoardId = isRecord(galleryValues) ? galleryValues.selectedBoardId : undefined;
+ const graph = isRecord(snapshot.graph)
+ ? (snapshot.graph as unknown as GraphContract)
+ : {
+ edges: [],
+ id: `invalid-legacy-queue-graph-${index}`,
+ label: 'Unavailable legacy queue graph',
+ nodes: [],
+ updatedAt: new Date(0).toISOString(),
+ version: 1,
+ };
+ const safeSourceId = sourceId ?? 'workflow';
+
+ return {
+ ...item,
+ cancellable: typeof item.cancellable === 'boolean' ? item.cancellable : false,
+ id: typeof item.id === 'string' ? item.id : `invalid-legacy-queue-item-${index}`,
+ snapshot: {
+ ...snapshot,
+ backendSubmission: submission,
+ canvas,
+ destination: snapshot.destination === 'gallery' ? 'gallery' : 'canvas',
+ filterIntermediateResults: safeSourceId === 'workflow',
+ galleryBoardId: typeof selectedBoardId === 'string' ? selectedBoardId : null,
+ graph,
+ presentation: {
+ batchCount: submission.kind === 'invalid' ? 1 : submission.batchCount,
+ height: dimensions.height,
+ ...(presentationSource?.positivePrompt ? { positivePrompt: presentationSource.positivePrompt } : {}),
+ width: dimensions.width,
+ },
+ ...(safeSourceId === 'generate' || safeSourceId === 'canvas'
+ ? { resultNodeIds: ['canvas_output'] }
+ : safeSourceId === 'upscale'
+ ? { resultNodeIds: ['upscale_output'] }
+ : {}),
+ sourceId: safeSourceId,
+ submittedAt: typeof snapshot.submittedAt === 'string' ? snapshot.submittedAt : new Date(0).toISOString(),
+ widgetInstances: isRecord(snapshot.widgetInstances)
+ ? (snapshot.widgetInstances as Record<WidgetInstanceId, WidgetInstanceContract>)
+ : context.widgetInstances,
+ widgetStates,
+ },
+ status:
+ item.status === 'pending' ||
+ item.status === 'running' ||
+ item.status === 'completed' ||
+ item.status === 'failed' ||
+ item.status === 'cancelled'
+ ? item.status
+ : 'failed',
+ } as WorkbenchQueueItem;
+};
+
+/** Upgrades legacy nested snapshots at Workbench's project-ingestion boundary. */
+export const normalizeWorkbenchQueueHistory = (
+ value: unknown,
+ context: QueueHistoryNormalizationContext
+): WorkbenchQueueState => {
+ if (!isRecord(value) || !Array.isArray(value.items)) {
+ return { items: [] };
+ }
+
+ let didChange = false;
+ const items = value.items.map((item, index) => {
+ const snapshot = isRecord(item) && isRecord(item.snapshot) ? item.snapshot : null;
+ if (snapshot && isCurrentSnapshot(snapshot)) {
+ return item as unknown as WorkbenchQueueItem;
+ }
+ didChange = true;
+ return normalizeLegacyQueueItem(item, index, context);
+ });
+
+ return didChange ? ({ ...value, items } as WorkbenchQueueState) : (value as unknown as WorkbenchQueueState);
+};
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsx
index d6f417fb52..1ef0eee191 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsx
@@ -2,6 +2,7 @@ import { Badge, HStack, Icon, Progress, Stack, Text } from '@chakra-ui/react';
import { useModelLoads, type ModelLoadInfo } from '@features/models';
import {
getQueueItemExpectedImageCount,
+ getQueueItemSnapshotPositivePrompt,
getQueueProgressBarState,
getQueueSummary,
type QueueItem,
@@ -141,7 +142,7 @@ const QueueInfoTooltip = ({
);
}
- const prompt = item.snapshot.presentation.positivePrompt?.trim() ?? '';
+ const prompt = getQueueItemSnapshotPositivePrompt(item).trim();
const expectedCount = getQueueItemExpectedImageCount(item);
const activeItemIndex = Math.min(expectedCount, Math.max(1, progress?.activeItemIndex ?? 1));
const activeBackendItemId = item.backendItemIds?.[activeItemIndex - 1];
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
index 2fc9e1b4bb..f96c5b9f60 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
@@ -325,6 +325,17 @@ describe('runCanvasInvocation', () => {
// sd-1 is linear: denoising_start = 1 - 0.75.
expect(nodes.denoise_latents.denoising_start).toBeCloseTo(0.25, 10);
expect(harness.notices()).toHaveLength(0);
+ expect(harness.dedupe.byKey.size).toBeGreaterThan(0);
+ });
+
+ it('reuses committed composite uploads on a later successful invocation', async () => {
+ const harness = makeHarness();
+
+ await runCanvasInvocation(harness.deps);
+ await runCanvasInvocation(harness.deps);
+
+ expect(harness.submittedGraphs()).toHaveLength(2);
+ expect(harness.uploadImage).toHaveBeenCalledTimes(1);
});
it('dispatches resolved prompt and seed metadata with the compiled canvas graph', async () => {
@@ -616,7 +627,7 @@ describe('runCanvasInvocation', () => {
it('records a notice and dispatches no snapshot when the graph fails validation', async () => {
// External image generators are rejected by the graph compiler.
- const harness = makeHarness({ document: makeDoc([]), model: externalModel });
+ const harness = makeHarness({ model: externalModel });
await runCanvasInvocation(harness.deps);
@@ -629,6 +640,24 @@ describe('runCanvasInvocation', () => {
expect(harness.releaseRasterSnapshot).toHaveBeenCalledTimes(1);
});
+ it('discards provisional dedupe entries when synchronous queue dispatch fails', async () => {
+ const dispatch = vi.fn((action: WorkbenchAction) => {
+ if (action.type === 'submitCanvasInvocationSnapshot') {
+ throw new Error('queue dispatch failed');
+ }
+ });
+ const harness = makeHarness({ dispatch });
+
+ await runCanvasInvocation(harness.deps);
+
+ expect(harness.uploadImage).toHaveBeenCalledTimes(1);
+ expect(harness.dedupe.byKey).toHaveLength(0);
+ expect(harness.dedupe.byHash).toHaveLength(0);
+ expect(harness.notices()).toEqual([
+ expect.objectContaining({ message: 'queue dispatch failed', type: 'recordNotice' }),
+ ]);
+ });
+
it('records a notice and dispatches no snapshot when the composite upload fails', async () => {
const uploadImage = vi.fn(() => Promise.reject(new Error('upload exploded')));
const harness = makeHarness({ uploadImage });
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
index 8e90dafa95..9ed2357c76 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
@@ -21,7 +21,8 @@
* enabled nonempty control layer blocks the invoke), and regional-guidance
* rejection as a silent-skip predicate.
* 4. Compile the base-appropriate graph and dispatch it to canvas staging.
- * 5. Any failure (validation throw, upload error, unsupported mode) records a
+ * 5. Publish the operation-local dedupe cache only after dispatch returns.
+ * 6. Any failure (validation throw, upload error, unsupported mode) records a
* notice — the app never gets stuck.
*
* A module-scoped in-flight guard drops an invoke while a prior prepare for the
@@ -377,6 +378,7 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
canvas: composites.canvas,
projectId,
});
+ composed.dedupeCommit.commit();
} catch (error) {
recordNotice(commands.notifications, 'error', error instanceof Error ? error.message : String(error));
} finally {
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 6e455c06b7..089b30df44 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -99,6 +99,7 @@ import {
} from './invocation';
import { defaultLayoutPreset, getLayoutPreset } from './layoutPresets';
import { cloneLayoutPresetWidgetRegions, createLayoutPresetSnapshot } from './layoutPresetSnapshots';
+import { normalizeWorkbenchQueueHistory } from './queueHistoryNormalization';
import { normalizeProjectSettings } from './settings/store';
type QueueGenerateSnapshot = NonNullable<QueueItem['snapshot']['generate']>;
@@ -639,7 +640,7 @@ const getGallerySelectedImageNames = (values: Record<string, unknown>): string[]
/**
* Deep-clones an already-v2 canvas state and normalizes staging candidate placements. Not a
* migration boundary: callers with genuinely unknown/legacy input must run
- * `migrateCanvasStateToV2` first (see `ensureProjectWidgetContracts`).
+ * `migrateCanvasStateToV2` first (see `normalizeWorkbenchProject`).
*/
const cloneCanvas = (canvas: CanvasStateContractV2): CanvasStateContractV2 => {
const document = structuredClone(canvas.document);
@@ -1029,7 +1030,7 @@ const normalizePromptHistory = (value: unknown): PromptHistoryItem[] => {
}, []);
};
-const ensureProjectWidgetContracts = (project: Project): Project => {
+export const normalizeWorkbenchProject = (project: Project): Project => {
const defaultWidgetRegions = createWidgetRegions();
const legacyWidgetRegions = project.widgetRegions as
| Partial<Record<WidgetRegion | 'left-panel' | 'right-panel' | 'status-bar', WidgetRegionState>>
@@ -1067,13 +1068,16 @@ const ensureProjectWidgetContracts = (project: Project): Project => {
widgetInstances.upscale = createWidgetInstance('upscale');
}
+ const canvas = cloneCanvas(migrateCanvasStateToV2(project.canvas));
+
return {
...project,
// `project` may come straight from persisted storage (an unsafe cast boundary), so its
// canvas can still be v1-shaped, malformed, or missing — migrate before cloning.
- canvas: cloneCanvas(migrateCanvasStateToV2(project.canvas)),
+ canvas,
projectGraph: normalizeProjectGraph(project.projectGraph),
promptHistory: normalizePromptHistory((project as Partial<Project>).promptHistory),
+ queue: normalizeWorkbenchQueueHistory(project.queue, { canvas, widgetInstances }),
settings: normalizeProjectSettings(project.settings),
widgetRegions: {
left: leftRegion,
@@ -1293,7 +1297,7 @@ const normalizeWorkbenchState = (state: WorkbenchState): WorkbenchState => ({
// (they live in the settings store now) and must not resurface here.
account: normalizeAccount(state.account),
notifications: [],
- projects: state.projects.map(ensureProjectWidgetContracts),
+ projects: state.projects.map(normalizeWorkbenchProject),
});
const updateActiveLayout = (
@@ -1843,7 +1847,7 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe
return { ...state, activeProjectId: action.project.id };
}
- const project = ensureProjectWidgetContracts(action.project);
+ const project = normalizeWorkbenchProject(action.project);
return { ...state, activeProjectId: project.id, projects: [...state.projects, project] };
}
@@ -1908,7 +1912,7 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe
const preset: LayoutPreset = {
id: action.presetId,
label: action.label.trim() || 'Custom layout',
- snapshot: createLayoutPresetSnapshot(ensureProjectWidgetContracts(activeProject)),
+ snapshot: createLayoutPresetSnapshot(normalizeWorkbenchProject(activeProject)),
};
const customLayoutPresets = [
...(state.account.customLayoutPresets ?? []).filter((candidate) => candidate.id !== action.presetId),
@@ -2853,8 +2857,8 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe
// version takes over the original project id, and the local edits
// continue in the recovered fork — which stays the active project when
// the user was looking at it.
- const normalizedServerProject = ensureProjectWidgetContracts(action.serverProject);
- const recoveredProject = ensureProjectWidgetContracts(action.recoveredProject);
+ const normalizedServerProject = normalizeWorkbenchProject(action.serverProject);
+ const recoveredProject = normalizeWorkbenchProject(action.recoveredProject);
const localProject = state.projects.find((project) => project.id === action.projectId);
const hasOriginal = localProject !== undefined;
// The server document replaces the local one under the SAME project id, so a