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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(webv2): restructure state architecture into app/platform/workbench/features
joshistoast566b17cc98c9
diff --git a/.github/workflows/frontend-tests.yml b/.github/workflows/frontend-tests.ymlindex fd7df90a25..451ae9d463 100644--- a/.github/workflows/frontend-tests.yml+++ b/.github/workflows/frontend-tests.yml@@ -88,17 +88,20 @@ jobs:with:working-directory: invokeai/frontend/webv2- - name: vitest- if: ${{ steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true }}- run: 'pnpm test'- shell: bash-- name: install Chromiumif: ${{ steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true }}run: 'pnpm exec playwright install chromium'shell: bash- - name: vitest browser+ - name: architecture completion gatesif: ${{ steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true }}- run: 'pnpm test:browser'+ run: 'pnpm check:architecture'shell: bash++ - name: upload architecture performance 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+ if-no-files-found: ignorediff --git a/invokeai/frontend/webv2/.gitignore b/invokeai/frontend/webv2/.gitignoreindex 041880077f..5471f649ca 100644--- a/invokeai/frontend/webv2/.gitignore+++ b/invokeai/frontend/webv2/.gitignore@@ -1,6 +1,8 @@dist/node_modules/stats.html+artifacts/# vitest browser-mode failure artifacts.vitest-attachments+__screenshots__/diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdnew file mode 100644index 0000000000..9808864808--- /dev/null+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -0,0 +1,82 @@+# Webv2 module architecture++Webv2 uses four top-level module groups:++- `app/` owns providers, routing, boot, and composition roots.+- `platform/` owns application infrastructure with no workbench or feature dependency.+- `workbench/` owns the atomic project aggregate, layout, shell, widget runtime, and extension runtime.+- `features/<domain>/` owns domain behavior behind a small set of public top-level entry modules (`features/<domain>/index.ts` first among them).++Dependency direction is `app -> workbench/features -> platform`. Feature callers import only a feature's public entry modules — the top-level modules each feature registers in `src/architecture/featureInterfaces.ts` (`index` is implicitly public; an unregistered feature or module is private, fail-closed); everything under `core/`, `data/`, `ui/`, and runtime implementation is private. A feature may group substantial behavior under `core/`, `data/`, and `ui/`; pure cores do not import React, HTTP, or UI code. Production canvas callers use `canvas-engine/api.ts`, not the engine implementation root.++## App and Platform ownership++Ownership is based on invariants, not the first caller:++| Module | Owned implementation | Must not own |+| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |+| `app/` | `main`, provider assembly, routes and guards, route runtimes, adapter selection, cross-module dependency construction, theme/language DOM controllers | Domain behavior, transport implementation, reusable state or UI |+| `platform/transport` | HTTP primitives and URL resolution, injected auth hook, Socket.IO mechanics, connection snapshots | Auth token policy, Queue/model/node event interpretation |+| `platform/state` | React-free listener/store/selector cores and separate React hook adapters | Domain stores or aggregate state |+| `platform/query` | Query client construction and defaults | Feature query keys, DTOs, invalidation policy |+| `platform/i18n` | i18next bootstrap and supported-language metadata | Persisted preference ownership |+| `platform/ui` | Chakra system/theme, reusable controls, toaster, brand mark | Workbench widgets or feature-specific views |+| `platform/runtime` | Domain-neutral build/runtime metadata | Route or feature policy |+| `workbench/backend` | Queue/node/model progress interpretation and transient domain stores pending their feature migrations | HTTP, sockets, connection mechanics, generic stores |+| `workbench/components` | Workbench hydration and Queue progress presentation | Reusable control or theme implementation |++The root of `src/` contains declaration files only. Runtime boot files live in App, the old root entry paths do not exist, and `index.html` names `src/app/main.tsx` directly. `@theme` resolves to Platform UI theme implementation; all other Platform callers use `@platform/*`. No compatibility path exists for moved App, HTTP, socket, external-store, selector, theme, i18n, or reusable-UI modules.++Platform transport receives authentication through `app/configureDependencies.ts`: Auth owns token storage and unauthorized-session behavior, while Platform only requests a token and reports a 401. The Platform socket publishes raw events and connection transitions; Queue and other domains interpret those events. App constructs the production Queue runtime from Queue, Workbench, Gallery, and Workflow adapters.++`pnpm architecture:check` is the executable source of truth for these dependency directions. It uses the TypeScript parser to classify static imports, type imports, dynamic imports, re-exports, and inline imported types after resolving aliases and relative paths. Temporary violations must be recorded in `src/architecture/migrationExceptions.ts` with an owner and a removal ticket; architecture completion requires that registry to be empty.++The queue pilot is the first migrated feature. Its private `QueueBackendPort` is the adapter seam; public callers use domain reads, commands, and production runtime factories from `@features/queue`. Private snake_case HTTP DTOs map explicitly to camelCase Queue read models before crossing that interface. TanStack Query owns the global backend queue read model, and non-React runtimes own reconciliation and realtime orchestration. Persisted per-project queue history remains in the Workbench aggregate.++Workbench persistence follows the same lifetime rule. `createWorkbenchPersistenceRuntime` owns hydration ordering, debounced autosave, revision/generation checks, conflict application, reconnect replay, status publication, and disposal without importing React. `createSyncedWorkbenchPersistence` constructs the local/remote project synchronization state for one mounted Workbench; no process-wide maps, sets, flags, or caches hold that state. `WorkbenchProvider` only constructs these lifetimes, starts/disposes the runtime through the mount lifecycle adapter, and selects aggregate hydration state.++## Contract ownership++Contracts live with the module that owns their invariants. The retired `workbench/types.ts` path is an architecture violation; Workbench aggregate, widget, Canvas, persistence, settings, and feature contracts each have an owner-local canonical path. Persisted schemas and backend DTOs remain private versioned/wire values and cross seams only through explicit serializers, hydrators, or mappers.++Feature callers import a feature's public entry modules; imports of another feature's `core/`, `data/`, `ui/`, or runtime implementation are rejected outside a ticketed migration exception. Wildcard exports may aggregate files inside one owner, but may not cross an ownership seam. The contract caller matrix and development-invalidation budgets are generated by `pnpm architecture:check` and `pnpm test:performance:build` respectively.++Compatibility exports under `workbench/` are temporary. New behavior belongs behind the target module interface and compatibility files must not acquire new implementation logic.++## Workbench ownership destinations++`src/architecture/workbenchOwnershipManifest.json` is the executable current-to-target ownership manifest. `pnpm architecture:check` proves that every production Workbench module has exactly one target owner and writes the detailed import/export inventory to `artifacts/architecture/workbench-ownership-inventory.json`. The generated inventory is regenerated as modules change; tests and type-test fixtures are intentionally excluded.++| Current Workbench path | Target owner | Split or locality decision |+| ---------------------------------------------------------------------------------------------------- | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |+| aggregate root modules, `projects`, `persistence`, `settings` | Workbench | Atomic project/account state and its persistence policy remain local to the aggregate. Persistence mechanics move behind the aggregate's adapter. |+| `shell`, `components/WorkbenchSplashScreen`, `launchpad` shell, `widget-frame`, non-domain `widgets` | Workbench | Route-independent shell, layout, widget hosts, and registration are Workbench implementation. |+| `extensions`, `hotkeys`, `diagnostics` | Workbench | These enforce the Workbench extension runtime; they are not independent vertical domains. |+| `canvas-engine`, `canvas-operations`, Canvas/layers widgets, root Canvas modules | Workbench | Canvas is a deep internal Workbench module behind `canvas-engine/api.ts`, not another top-level Feature. |+| `image-actions`, `images` | Workbench | Cross-surface image orchestration and transient display stay internal until a second independent implementation justifies a seam. |+| `auth`, `users`, Launchpad Users page | `feature:identity` | Session/token policy and user administration form one identity vocabulary. |+| `models`, Launchpad model manager/page, `backend/modelLoadStore` | `feature:models` | Model catalog, install/load lifecycle, and model administration co-locate. |+| `customNodes`, Launchpad node manager/page, `backend/nodeExecutionStore` | `feature:nodes` | Node catalog/template and execution lifecycle co-locate. |+| `backend` except model/node stores, queue root modules, queue widget, Queue progress component | `feature:queue` | Queue owns server-event interpretation, transient progress, submission, reconciliation, and Queue UI. Persisted project queue history stays in Workbench. |+| `gallery`, Gallery widget | `feature:gallery` | Gallery data, selection policy, and Gallery UI form one vertical module. |+| `generation`, Generate widget | `feature:generation` | Generation settings, graph compilation, and Generate UI form one vertical module. |+| `workflows`, `graph-preview`, Workflow widget | `feature:workflow` | Workflow documents, compilation, preview, editor, and library form one vertical module. |+| `upscale`, Upscale widget | `feature:upscale` | Upscale settings, validation, compilation, and UI form one vertical module. |+| `hooks/useMountEffect`, root `useModifierHeld` | Platform | These are domain-neutral React lifecycle/input adapters and must have no Workbench import. |++The mixed-folder rules are longest-prefix rules in the manifest, so the Backend, Components, Launchpad, and Widgets splits are explicit rather than inferred from imports. Root modules are listed individually. Compatibility re-exports keep the target owner of the implementation they forward and are deletion work, never a fifth owner.++The target dependency graph intentionally records the current migration cycle: Workbench and the eight destination Features are one transitional strongly connected component. That is evidence for the cycle-breaking sequence, not permission for the destination architecture to retain the cycle. The migration must replace implementation imports with public module interfaces or composition-root adapters until the only direction is `app -> workbench/features -> platform`.++Feature interfaces remain ordinary module interfaces unless two adapters add leverage. Queue's backend port has production transport/realtime and test adapters; Identity's token/session port has browser-session and test adapters; Models and Nodes use production event/transport and test adapters. Gallery, Generation, Workflow, and Upscale keep their compilation and UI seams internal until their feature tickets demonstrate another independent adapter. Workbench image actions likewise remain internal rather than becoming a shallow Image Feature.++| Feature | Responsibility and representative callers | Allowed dependencies and candidate public interface |+| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Identity | Session/token policy and user administration; App guards/login, Queue capabilities, Workbench account/Launchpad surfaces | Platform plus Models' public capability reads; session reads/commands, token port, user queries and manager contribution |+| Models | Catalog, configuration, install/load lifecycle; Generation, Queue, Workflow, Upscale, Identity, model manager | Platform plus Identity's public authorization reads; descriptors/capabilities, catalog/load commands and manager contribution |+| Nodes | Custom-node catalog/templates and execution lifecycle; Workflow editor and node manager | Platform; descriptors, catalog commands, execution snapshots and manager contribution |+| Queue | Backend queue state, realtime interpretation, submission/reconciliation and Queue UI; App runtime, Workbench aggregate/shell, Generation/Gallery/Workflow | Platform and public envelopes/capabilities from Identity, Models, Generation, Workflow, Upscale; backend port, queue reads/commands and widget contribution |+| Gallery | Image collection, selection, board policy and Gallery UI; App adapter, Generation, Workflow, Upscale, Workbench image actions | Platform and Queue's public progress reads; gallery reads/commands and widget contribution |+| Generation | Generation settings, validation, graph compilation and Generate UI; Workbench invocation, Queue, Gallery, Workflow, Upscale | Platform and public Models/Gallery/Queue interfaces; settings/validation, compiled submission envelope and widget contribution |+| Workflow | Workflow document, validation, compilation, preview/editor/library; App adapter, Workbench invocation, Nodes | Platform and public Nodes/Models/Gallery/Queue interfaces; document reads/commands, compiled submission envelope and widget contribution |+| Upscale | Upscale settings, validation, compilation and UI; Workbench invocation and Queue | Platform and public Models/Gallery/Queue interfaces; value/validation reads, submission command and widget contribution |diff --git a/invokeai/frontend/webv2/index.html b/invokeai/frontend/webv2/index.htmlindex ef74665c23..a5720ff578 100644--- a/invokeai/frontend/webv2/index.html+++ b/invokeai/frontend/webv2/index.html@@ -49,6 +49,6 @@</head><body><div id="root"></div>- <script type="module" src="/src/main.tsx"></script>+ <script type="module" src="/src/app/main.tsx"></script></body></html>diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.jsonindex e3b8b58ae2..f3dc5bef8c 100644--- a/invokeai/frontend/webv2/package.json+++ b/invokeai/frontend/webv2/package.json@@ -4,7 +4,9 @@"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","build": "pnpm run lint && vite build",+ "check:architecture": "pnpm run lint && pnpm run test:all && pnpm run test:performance:architecture","dev": "vite dev","dev:host": "vite dev --host","fix": "pnpm run lint:oxc:fix && pnpm run format:write",@@ -12,14 +14,17 @@"format:write": "oxfmt --write .","i18n:report": "node scripts/i18n-report.mjs","i18n:report:verbose": "node scripts/i18n-report.mjs --verbose",- "lint": "pnpm run format:check && pnpm run lint:oxc && pnpm run lint:tsc",+ "lint": "pnpm run format:check && pnpm run lint:oxc && pnpm run lint:tsc && pnpm run architecture:check","lint:oxc": "oxlint --react-plugin --import-plugin --deny-warnings .","lint:oxc:fix": "oxlint --react-plugin --import-plugin --fix .","lint:tsc": "tsc --noEmit","preview": "vite preview","test": "vitest run --config vitest.config.mts","test:all": "pnpm run test && pnpm run test:browser",- "test:browser": "vitest run --config vitest.browser.config.mts"+ "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:build": "vite build && node scripts/check-architecture-performance.mjs"},"dependencies": {"@chakra-ui/react": "^3.36.0",@@ -29,6 +34,7 @@"@dnd-kit/utilities": "^3.2.2","@emotion/react": "^11.14.0","@fontsource/inter": "^5.2.8",+ "@tanstack/react-query": "^5.101.2","@tanstack/react-router": "^1.170.16","@tanstack/react-virtual": "^3.14.3","@xyflow/react": "^12.11.1",diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonnew file mode 100644index 0000000000..b4f9294716--- /dev/null+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -0,0 +1,133 @@+{+ "schemaVersion": 1,+ "capturedAt": "2026-07-18",+ "build": {+ "launchpad": {+ "source": "index.html",+ "owner": "app",+ "remediationTicket": "set-performance-budgets",+ "baselineOwnedRawBytes": 346465,+ "baselineInitialRawBytes": 1863260,+ "baselineGzipBytes": 541484,+ "baselineBrotliBytes": 538329,+ "initialChunkNames": [+ "Tooltip",+ "WorkflowUiContext",+ "baseGenerationPolicies",+ "chakra",+ "externalStore",+ "graph",+ "http",+ "imageUrls",+ "index",+ "react",+ "rolldown-runtime",+ "selectors",+ "settings",+ "socketHub",+ "ui",+ "utility",+ "validation",+ "vendor"+ ],+ "maxGrowthPercent": 0.02,+ "maxGrowthRawBytes": 20480+ },+ "editor": {+ "source": "src/app/WorkbenchApp.tsx",+ "owner": "workbench",+ "remediationTicket": "deepen-widget-registry-loading",+ "baselineOwnedRawBytes": 1212185,+ "baselineInitialRawBytes": 3093833,+ "baselineGzipBytes": 921612,+ "baselineBrotliBytes": 889327,+ "initialChunkNames": [+ "GalleryUiContext",+ "GenerationUiContext",+ "QueueUiContext",+ "Tooltip",+ "WorkbenchApp",+ "WorkbenchWidgetRegistryContext",+ "WorkflowUiContext",+ "baseGenerationPolicies",+ "bboxGrid",+ "canvasCompositing",+ "canvasStrength",+ "chakra",+ "contracts",+ "draftRegistry",+ "drafts",+ "externalStore",+ "galleryStateView",+ "generateDraftRegistry",+ "graph",+ "http",+ "imageUrls",+ "index",+ "queueMenuActions",+ "react",+ "react",+ "react",+ "rolldown-runtime",+ "selectors",+ "settings",+ "socketHub",+ "submissionApi",+ "ui",+ "useNotify",+ "useOpenWorkbenchWidget",+ "useProjectActions",+ "utility",+ "validation",+ "vendor",+ "widget-frame"+ ],+ "maxGrowthPercent": 0.02,+ "maxGrowthRawBytes": 20480,+ "finalOwnedRawBytesTarget": 848529,+ "finalReductionPercent": 0.3+ }+ },+ "structural": {+ "launchpadForbiddenInitialSources": [+ "src/app/WorkbenchApp.tsx",+ "src/features/models/ui/ModelManagerView.tsx",+ "src/features/nodes/ui/NodeManagerView.tsx",+ "_ag-psd"+ ],+ "editorForbiddenInitialChunkNames": ["ag-psd"],+ "inactiveWidgetGateOwner": "deepen-widget-registry-loading"+ },+ "developmentInvalidation": {+ "platformUiBarrel": {+ "specifier": "@platform/ui",+ "owner": "platform-ui",+ "remediationTicket": "return-contracts-to-owners",+ "maxDirectImporters": 151+ },+ "retiredWorkbenchTypeHub": {+ "specifier": "@workbench/types",+ "owner": "workbench",+ "remediationTicket": "return-contracts-to-owners",+ "maxDirectImporters": 0+ },+ "canvasContracts": {+ "specifier": "@workbench/canvas-engine/contracts",+ "owner": "canvas",+ "remediationTicket": "seal-canvas-engine-seam",+ "maxDirectImporters": 120+ },+ "queuePublicInterface": {+ "specifier": "@features/queue",+ "owner": "queue",+ "remediationTicket": "finish-queue-ownership",+ "maxDirectImporters": 24+ },+ "isolatedGalleryView": {+ "specifier": "./GalleryWidgetView",+ "owner": "gallery",+ "remediationTicket": "define-gallery-feature",+ "maxDirectImporters": 1+ }+ }+}diff --git a/invokeai/frontend/webv2/performance/architecture-fixtures.json b/invokeai/frontend/webv2/performance/architecture-fixtures.jsonnew file mode 100644index 0000000000..fac175602e--- /dev/null+++ b/invokeai/frontend/webv2/performance/architecture-fixtures.json@@ -0,0 +1,53 @@+{+ "schemaVersion": 1,+ "samples": 5,+ "warmups": 1,+ "routes": [+ {+ "id": "launchpad",+ "owner": "app",+ "path": "/#/",+ "remediationTicket": "set-performance-budgets"+ },+ {+ "id": "editor-minimal",+ "owner": "workbench",+ "path": "/#/app?new=true",+ "expectedScriptPattern": "WorkbenchApp-",+ "measureProjectSwitch": true,+ "requiredWidgetRequests": ["GalleryImageActionsBridge", "widget:generate", "widget:preview", "widget:gallery"],+ "forbiddenWidgetRequests": ["widget:canvas", "widget:layers", "widget:project", "widget:upscale"],+ "remediationTicket": "deepen-widget-registry-loading"+ },+ {+ "id": "editor-canvas",+ "owner": "canvas",+ "path": "/#/app?new=true",+ "expectedScriptPattern": "WorkbenchApp-",+ "layoutPreset": "Canvas",+ "requiredWidgetRequests": ["GalleryImageActionsBridge", "widget:canvas", "widget:layers"],+ "forbiddenWidgetRequests": ["widget:project", "widget:upscale"],+ "remediationTicket": "deepen-widget-registry-loading"+ },+ {+ "id": "editor-workflow",+ "owner": "workflow",+ "path": "/#/app?new=true",+ "expectedScriptPattern": "WorkbenchApp-",+ "layoutPreset": "Workflow",+ "requiredWidgetRequests": ["GalleryImageActionsBridge", "widget:workflow", "widget:queue"],+ "forbiddenWidgetRequests": ["widget:canvas", "widget:layers", "widget:project", "widget:upscale"],+ "remediationTicket": "deepen-widget-registry-loading"+ },+ {+ "id": "editor-gallery",+ "owner": "gallery",+ "path": "/#/app?new=true",+ "expectedScriptPattern": "WorkbenchApp-",+ "layoutPreset": "Gallery",+ "requiredWidgetRequests": ["GalleryImageActionsBridge", "widget:gallery", "widget:preview"],+ "forbiddenWidgetRequests": ["widget:canvas", "widget:layers", "widget:project", "widget:upscale"],+ "remediationTicket": "deepen-widget-registry-loading"+ }+ ]+}diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonnew file mode 100644index 0000000000..c8571fa667--- /dev/null+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -0,0 +1,381 @@+{+ "browserExecutable": "/home/toast/.cache/ms-playwright/chromium-1228/chrome-linux64/chrome",+ "capturedAt": "2026-07-17",+ "routes": [+ {+ "domContentLoadedMedianMs": 107.8000000002794,+ "id": "launchpad",+ "loadMedianMs": 107.8000000002794,+ "longestTaskMaxMs": 78,+ "layoutSwitchMedianMs": 0,+ "projectSwitchMedianMs": 0,+ "owner": "app",+ "remediationTicket": "set-performance-budgets",+ "routeReadyMedianMs": 210.20000000018626,+ "scriptRequests": [+ "Tooltip",+ "WorkflowUiContext",+ "baseGenerationPolicies",+ "chakra",+ "externalStore",+ "graph",+ "http",+ "imageUrls",+ "index",+ "react",+ "rolldown-runtime",+ "selectors",+ "settings",+ "socketHub",+ "ui",+ "utility",+ "validation",+ "vendor"+ ]+ },+ {+ "domContentLoadedMedianMs": 120.5,+ "id": "editor-minimal",+ "loadMedianMs": 120.5,+ "longestTaskMaxMs": 106,+ "layoutSwitchMedianMs": 0,+ "projectSwitchMedianMs": 220.75787000000128,+ "owner": "workbench",+ "remediationTicket": "deepen-widget-registry-loading",+ "routeReadyMedianMs": 558.7000000001863,+ "scriptRequests": [+ "GalleryImageActionsBridge",+ "GalleryUiContext",+ "GenerateCollapsibleSection",+ "GenerationUiContext",+ "ModelSelect",+ "PositivePromptField",+ "QueueUiContext",+ "ReferenceImageControls",+ "StreamingImageFrame",+ "Tooltip",+ "WorkbenchApp",+ "WorkbenchWidgetRegistryContext",+ "WorkflowUiContext",+ "api",+ "backend",+ "baseGenerationPolicies",+ "bboxGrid",+ "canvasCompositing",+ "canvasImportError",+ "canvasStrength",+ "chakra",+ "contracts",+ "draftRegistry",+ "drafts",+ "executeImageRecall",+ "externalStore",+ "form",+ "gallery",+ "galleryDnd",+ "galleryStateView",+ "generateDraftRegistry",+ "generateFormViewModel",+ "graph",+ "http",+ "image-actions",+ "imageUrls",+ "index",+ "nodeChrome",+ "queries",+ "queueMenuActions",+ "react",+ "react",+ "react",+ "react",+ "rolldown-runtime",+ "selectedImage",+ "selectors",+ "settings",+ "socketHub",+ "submissionApi",+ "ui",+ "useModifierHeld",+ "useNotify",+ "useOpenWorkbenchWidget",+ "useProjectActions",+ "useStreamingImageSource",+ "utility",+ "validation",+ "vendor",+ "widget-frame",+ "widget:autosave-status",+ "widget:diagnostics",+ "widget:gallery",+ "widget:generate",+ "widget:notifications",+ "widget:preview",+ "widget:queue",+ "widget:server-status",+ "widget:version-status",+ "widget:workflow"+ ]+ },+ {+ "domContentLoadedMedianMs": 117.6999999997206,+ "id": "editor-canvas",+ "loadMedianMs": 117.6999999997206,+ "longestTaskMaxMs": 103,+ "layoutSwitchMedianMs": 409.86311000000023,+ "projectSwitchMedianMs": 0,+ "owner": "canvas",+ "remediationTicket": "deepen-widget-registry-loading",+ "routeReadyMedianMs": 830.7999999998137,+ "scriptRequests": [+ "GalleryImageActionsBridge",+ "GalleryUiContext",+ "GenerateCollapsibleSection",+ "GenerationUiContext",+ "LayerContextMenu",+ "ModelSelect",+ "PositivePromptField",+ "QueueUiContext",+ "ReferenceImageControls",+ "StreamingImageFrame",+ "Tooltip",+ "WorkbenchApp",+ "WorkbenchWidgetRegistryContext",+ "WorkflowUiContext",+ "api",+ "backend",+ "baseGenerationPolicies",+ "bboxGrid",+ "canvas",+ "canvasCompositing",+ "canvasImportError",+ "canvasStrength",+ "chakra",+ "contracts",+ "draftRegistry",+ "drafts",+ "executeImageRecall",+ "externalStore",+ "form",+ "gallery",+ "galleryDnd",+ "galleryStateView",+ "generateDraftRegistry",+ "generateFormViewModel",+ "graph",+ "http",+ "image-actions",+ "imageUrls",+ "index",+ "nodeChrome",+ "prompt-ui",+ "queries",+ "queueMenuActions",+ "react",+ "react",+ "react",+ "react",+ "rolldown-runtime",+ "selectedImage",+ "selectors",+ "settings",+ "socketHub",+ "submissionApi",+ "ui",+ "useModifierHeld",+ "useNotify",+ "useOpenWorkbenchWidget",+ "useProjectActions",+ "useStreamingImageSource",+ "utility",+ "validation",+ "vendor",+ "widget-frame",+ "widget:autosave-status",+ "widget:canvas",+ "widget:diagnostics",+ "widget:gallery",+ "widget:generate",+ "widget:layers",+ "widget:notifications",+ "widget:preview",+ "widget:queue",+ "widget:server-status",+ "widget:version-status",+ "widget:workflow"+ ]+ },+ {+ "domContentLoadedMedianMs": 116.10000000009313,+ "id": "editor-workflow",+ "loadMedianMs": 116.10000000009313,+ "longestTaskMaxMs": 102,+ "layoutSwitchMedianMs": 437.8898649999992,+ "projectSwitchMedianMs": 0,+ "owner": "workflow",+ "remediationTicket": "deepen-widget-registry-loading",+ "routeReadyMedianMs": 846.5,+ "scriptRequests": [+ "GalleryImageActionsBridge",+ "GalleryUiContext",+ "GenerateCollapsibleSection",+ "GenerationUiContext",+ "ModelSelect",+ "PositivePromptField",+ "QueueUiContext",+ "ReferenceImageControls",+ "StreamingImageFrame",+ "Tooltip",+ "WorkbenchApp",+ "WorkbenchWidgetRegistryContext",+ "WorkflowUiContext",+ "api",+ "backend",+ "baseGenerationPolicies",+ "bboxGrid",+ "canvasCompositing",+ "canvasImportError",+ "canvasStrength",+ "chakra",+ "contracts",+ "draftRegistry",+ "drafts",+ "executeImageRecall",+ "externalStore",+ "form",+ "gallery",+ "galleryDnd",+ "galleryStateView",+ "generateDraftRegistry",+ "generateFormViewModel",+ "graph",+ "http",+ "image-actions",+ "imageUrls",+ "index",+ "nodeChrome",+ "queries",+ "queueMenuActions",+ "react",+ "react",+ "react",+ "react",+ "rolldown-runtime",+ "selectedImage",+ "selectors",+ "settings",+ "socketHub",+ "submissionApi",+ "ui",+ "useModifierHeld",+ "useNotify",+ "useOpenWorkbenchWidget",+ "useProjectActions",+ "useStreamingImageSource",+ "utility",+ "validation",+ "vendor",+ "widget-frame",+ "widget:autosave-status",+ "widget:diagnostics",+ "widget:gallery",+ "widget:generate",+ "widget:notifications",+ "widget:preview",+ "widget:queue",+ "widget:server-status",+ "widget:version-status",+ "widget:workflow"+ ]+ },+ {+ "domContentLoadedMedianMs": 118.10000000009313,+ "id": "editor-gallery",+ "loadMedianMs": 118.10000000009313,+ "longestTaskMaxMs": 102,+ "layoutSwitchMedianMs": 390.20181899999807,+ "projectSwitchMedianMs": 0,+ "owner": "gallery",+ "remediationTicket": "deepen-widget-registry-loading",+ "routeReadyMedianMs": 800.8000000002794,+ "scriptRequests": [+ "GalleryImageActionsBridge",+ "GalleryUiContext",+ "GenerateCollapsibleSection",+ "GenerationUiContext",+ "ModelSelect",+ "PositivePromptField",+ "QueueUiContext",+ "ReferenceImageControls",+ "StreamingImageFrame",+ "Tooltip",+ "WorkbenchApp",+ "WorkbenchWidgetRegistryContext",+ "WorkflowUiContext",+ "api",+ "backend",+ "baseGenerationPolicies",+ "bboxGrid",+ "canvasCompositing",+ "canvasImportError",+ "canvasStrength",+ "chakra",+ "contracts",+ "draftRegistry",+ "drafts",+ "executeImageRecall",+ "externalStore",+ "form",+ "gallery",+ "galleryDnd",+ "galleryStateView",+ "generateDraftRegistry",+ "generateFormViewModel",+ "graph",+ "http",+ "image-actions",+ "imageUrls",+ "index",+ "nodeChrome",+ "queries",+ "queueMenuActions",+ "react",+ "react",+ "react",+ "react",+ "rolldown-runtime",+ "selectedImage",+ "selectors",+ "settings",+ "socketHub",+ "submissionApi",+ "ui",+ "useModifierHeld",+ "useNotify",+ "useOpenWorkbenchWidget",+ "useProjectActions",+ "useStreamingImageSource",+ "utility",+ "validation",+ "vendor",+ "widget-frame",+ "widget:autosave-status",+ "widget:diagnostics",+ "widget:gallery",+ "widget:generate",+ "widget:notifications",+ "widget:preview",+ "widget:queue",+ "widget:server-status",+ "widget:version-status",+ "widget:workflow"+ ]+ }+ ],+ "samples": 5,+ "warmups": 1,+ "enforceTiming": false,+ "longTaskTargetMs": 50,+ "schemaVersion": 1,+ "timingStatus": "informational-until-ci-runner-is-stable",+ "timingTolerancePercent": 0.1+}diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yamlindex 5dcfad18af..ce0269eec4 100644--- a/invokeai/frontend/webv2/pnpm-lock.yaml+++ b/invokeai/frontend/webv2/pnpm-lock.yaml@@ -29,6 +29,9 @@ importers:'@fontsource/inter':specifier: ^5.2.8version: 5.2.8+ '@tanstack/react-query':+ specifier: ^5.101.2+ version: 5.101.2([email protected])'@tanstack/react-router':specifier: ^1.170.16@@ -850,6 +853,14 @@ packages:resolution: {integrity: sha512-79pf/RkhteYZTRgcR4F9kbk84P2N8rugQJswxfIqovlbRiT3yI7eBE+5QorIrZaOKktsgzRlXh1l/du/xpl4iA==}engines: {node: '>=20.19'}+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-hH5MLoJhF7KaIGd7q3xTXGXvslI+GYlM1Z/35aSHHWaCJWB7XvTSHYuV3eM7tw+aE0mT/xMro4M4Q9rCGHT0lw==}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-seDkr6kzGzX1okaaTtZPtgA688CDPlXUz1C6xSg0ESqn04Vuc8tlrYms1s3de+znBqhPVxFRfpAfUf+6XvfPWg==}+ peerDependencies:+ react: ^18 || ^19+'@tanstack/[email protected]':resolution: {integrity: sha512-w6eq1IJklujs1tESazaK/FxH0+H2l8vm/QPuu1cD3oRW/ubgKneQpd7b64ti/8gUyEimzimJQZDmJr6YHfP5+g==}engines: {node: '>=20.19'}@@ -2580,6 +2591,13 @@ snapshots:'@tanstack/[email protected]': {}+ '@tanstack/[email protected]': {}++ '@tanstack/[email protected]([email protected])':+ dependencies:+ '@tanstack/query-core': 5.101.2+ react: 19.2.7+dependencies:'@tanstack/history': 1.162.0diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex b95c110a18..79accb75bd 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -150,8 +150,8 @@"createNewProject": "Create new project","deleteFailed": "Delete failed","deleteProject": "Delete project",- "deleteProjectQuestion": "Delete project?","deleteProjectCardBody": "Delete \"{{name}}\"? The project is removed from the server permanently.",+ "deleteProjectQuestion": "Delete project?","deleteProjectTabBody": "Delete \"{{name}}\"? The project and its saved copy on the server are removed permanently. To keep it in your library, close the tab instead.","deleteProjectWithEllipsis": "Delete project…","duplicateFailed": "Duplicate failed",@@ -164,11 +164,12 @@"noSavedProjects": "No saved projects yet.","openProject": "Open project","openProjectLabel": "Open {{name}}",+ "openProjects": "Open projects","projectDetails": "Project details",- "renameFailed": "Rename failed",- "renameWithEllipsis": "Rename…","projectDuplicated": "Project duplicated",- "projectDuplicatedDescription": "\"{{name}}\" was created."+ "projectDuplicatedDescription": "\"{{name}}\" was created.",+ "renameFailed": "Rename failed",+ "renameWithEllipsis": "Rename…"},"users": {"accountCount_one": "{{count}} account in this workspace.",diff --git a/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs b/invokeai/frontend/webv2/scripts/check-architecture-performance.mjsnew file mode 100644index 0000000000..4d5b3a0e2c--- /dev/null+++ b/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs@@ -0,0 +1,176 @@+import assert from 'node:assert/strict';+import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';+import { dirname, resolve } from 'node:path';+import ts from 'typescript';++import { checkRouteBudget, measureRouteBuild } from './performance-budgets.mjs';+import { WIDGET_IMPLEMENTATION_PATTERN, WIDGET_SOURCES } from './widget-sources.mjs';++const root = resolve(import.meta.dirname, '..');+const baseline = JSON.parse(await readFile(resolve(root, 'performance/architecture-baseline.json'), 'utf8'));+const manifest = JSON.parse(await readFile(resolve(root, 'dist/.vite/manifest.json'), 'utf8'));+const readAsset = async (file) => new Uint8Array(await readFile(resolve(root, 'dist', file)));++const assetCache = new Map();+for (const chunk of Object.values(manifest)) {+ if (chunk.file && !assetCache.has(chunk.file)) {+ assetCache.set(chunk.file, await readAsset(chunk.file));+ }+}++const syntheticFailures = checkRouteBudget(+ {+ brotliBytes: 70,+ chunkNames: ['eager-gallery', 'entry'],+ files: ['entry.js', 'gallery.js'],+ gzipBytes: 80,+ initialRawBytes: 150,+ ownedRawBytes: 103,+ routeId: 'launchpad',+ source: 'entry.ts',+ sources: ['entry.ts', 'gallery.ts'],+ },+ {+ baselineOwnedRawBytes: 100,+ initialChunkNames: ['entry'],+ maxGrowthPercent: 0.02,+ maxGrowthRawBytes: 20,+ owner: 'gallery',+ remediationTicket: 'define-gallery-feature',+ source: 'entry.ts',+ }+);+assert.equal(syntheticFailures.length, 2, 'Synthetic byte and request-set regressions must both fail.');+assert.match(syntheticFailures.map((failure) => failure.message).join('\n'), /103 bytes/);+assert.match(syntheticFailures.map((failure) => failure.message).join('\n'), /eager-gallery/);++const measurements = Object.entries(baseline.build).map(([routeId, budget]) =>+ measureRouteBuild(manifest, routeId, budget.source, (file) => assetCache.get(file))+);+const failures = measurements.flatMap((measurement) =>+ checkRouteBudget(measurement, baseline.build[measurement.routeId])+);+const launchpad = measurements.find((measurement) => measurement.routeId === 'launchpad');+const editor = measurements.find((measurement) => measurement.routeId === 'editor');+const widgetImplementationSources = [...WIDGET_SOURCES.keys()];+for (const source of widgetImplementationSources) {+ assert.ok(manifest[source], `Registered widget implementation ${source} is missing from the build manifest.`);+}+for (const source of Object.keys(manifest)) {+ if (WIDGET_IMPLEMENTATION_PATTERN.test(source)) {+ assert.ok(+ WIDGET_SOURCES.has(source),+ `Widget implementation ${source} must be registered in scripts/widget-sources.mjs.`+ );+ }+}+const getInactiveWidgetFailures = (sources) =>+ widgetImplementationSources+ .filter((source) => sources.includes(source))+ .map((source) => ({+ message: `editor eagerly includes inactive widget implementation ${source}.`,+ owner: 'workbench',+ remediationTicket: 'deepen-widget-registry-loading',+ routeId: 'editor',+ }));++assert.equal(+ new Set(widgetImplementationSources.map((source) => manifest[source].file)).size,+ widgetImplementationSources.length,+ 'Every first-party widget implementation must have an independently identifiable chunk.'+);+assert.equal(+ getInactiveWidgetFailures(['src/features/gallery/widget.ts']).length,+ 1,+ 'A synthetic eager widget implementation must fail the structural gate.'+);+failures.push(...getInactiveWidgetFailures(editor.sources));+for (const forbidden of baseline.structural.launchpadForbiddenInitialSources) {+ if (launchpad.sources.some((source) => source === forbidden || source.startsWith(forbidden))) {+ failures.push({+ message: `launchpad eagerly includes ${forbidden}.`,+ owner: 'app',+ remediationTicket: 'set-performance-budgets',+ routeId: 'launchpad',+ });+ }+}+for (const forbidden of baseline.structural.editorForbiddenInitialChunkNames) {+ if (editor.chunkNames.includes(forbidden)) {+ failures.push({+ message: `editor eagerly includes ${forbidden}.`,+ owner: 'workbench',+ remediationTicket: 'deepen-widget-registry-loading',+ routeId: 'editor',+ });+ }+}++const collectFiles = async (directory) => {+ const collected = [];+ for (const entry of await readdir(directory, { withFileTypes: true })) {+ const path = resolve(directory, entry.name);+ if (entry.isDirectory()) {+ collected.push(...(await collectFiles(path)));+ } else if (/\.(?:ts|tsx)$/.test(entry.name) && !/\.test\.|\.type-test\.|\.testing\./.test(entry.name)) {+ collected.push(path);+ }+ }+ return collected;+};+const productionFiles = await collectFiles(resolve(root, 'src'));+const importerCounts = new Map(Object.values(baseline.developmentInvalidation).map((budget) => [budget.specifier, 0]));+for (const path of productionFiles) {+ const source = await readFile(path, 'utf8');+ const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const seen = new Set();+ const visit = (node) => {+ if (+ (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&+ node.moduleSpecifier &&+ ts.isStringLiteralLike(node.moduleSpecifier)+ ) {+ seen.add(node.moduleSpecifier.text);+ }+ ts.forEachChild(node, visit);+ };+ visit(sourceFile);+ for (const specifier of seen) {+ if (importerCounts.has(specifier)) {+ importerCounts.set(specifier, importerCounts.get(specifier) + 1);+ }+ }+}+for (const [metricId, budget] of Object.entries(baseline.developmentInvalidation)) {+ const actual = importerCounts.get(budget.specifier) ?? 0;+ if (actual > budget.maxDirectImporters) {+ failures.push({+ message: `${metricId} has ${actual} direct importers (budget ${budget.maxDirectImporters}).`,+ owner: budget.owner,+ remediationTicket: budget.remediationTicket,+ routeId: 'development-invalidation',+ });+ }+}++const reportPath = resolve(root, 'artifacts/architecture-performance/build-report.json');+await mkdir(dirname(reportPath), { recursive: true });+await writeFile(+ reportPath,+ `${JSON.stringify({ baselineCapturedAt: baseline.capturedAt, failures, importerCounts: Object.fromEntries(importerCounts), measurements }, null, 2)}\n`+);++if (failures.length > 0) {+ throw new Error(+ failures+ .map(+ (failure) =>+ `${failure.message} Owner: ${failure.owner}. Remediation: ${failure.remediationTicket}. Route: ${failure.routeId}.`+ )+ .join('\n')+ );+}++process.stdout.write(+ `${JSON.stringify({ importerCounts: Object.fromEntries(importerCounts), measurements }, null, 2)}\n`+);diff --git a/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs b/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjsnew file mode 100644index 0000000000..e36aa0ba3a--- /dev/null+++ b/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs@@ -0,0 +1,304 @@+import { spawn } from 'node:child_process';+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import { dirname, resolve } from 'node:path';+import process from 'node:process';+import { chromium } from 'playwright';++import { startMockBackend } from './mock-backend.mjs';+import { getWidgetId } from './widget-sources.mjs';++const root = resolve(import.meta.dirname, '..');+const fixtures = JSON.parse(await readFile(resolve(root, 'performance/architecture-fixtures.json'), 'utf8'));+const manifest = JSON.parse(await readFile(resolve(root, 'dist/.vite/manifest.json'), 'utf8'));+const getScriptId = (source, chunk) => {+ const widgetId = getWidgetId(source);++ return widgetId ? `widget:${widgetId}` : (chunk.name ?? chunk.src ?? source);+};+const chunkNameByPath = new Map(+ Object.entries(manifest).map(([source, chunk]) => [`/${chunk.file}`, getScriptId(source, chunk)])+);+const baselinePath = resolve(root, 'performance/browser-baseline.json');+const artifactPath = resolve(root, 'artifacts/architecture-performance/browser-report.json');+const traceDirectory = resolve(root, 'artifacts/architecture-performance/traces');+const port = Number(process.env.INVOKEAI_PERFORMANCE_PORT ?? 4176);+const origin = `http://127.0.0.1:${String(port)}`;+const backendPort = Number(process.env.INVOKEAI_PERFORMANCE_BACKEND_PORT ?? 4177);+const backendOrigin = `http://127.0.0.1:${String(backendPort)}`;+const updateBaseline = process.argv.includes('--update-baseline');++const median = (values) => {+ const sorted = [...values].sort((left, right) => left - right);+ return sorted[Math.floor(sorted.length / 2)] ?? 0;+};++const waitForWidgetRequests = async (fixture, scripts) => {+ const required = new Set(fixture.requiredWidgetRequests ?? []);+ const deadline = Date.now() + 10_000;++ while (Date.now() < deadline) {+ const requested = new Set([...scripts].map((request) => chunkNameByPath.get(request) ?? request));+ if ([...required].every((request) => requested.has(request))) {+ for (const forbidden of fixture.forbiddenWidgetRequests ?? []) {+ if (requested.has(forbidden)) {+ throw new Error(`${fixture.id} requested inactive ${forbidden}.`);+ }+ }+ return;+ }+ await new Promise((resolveWait) => {+ setTimeout(resolveWait, 25);+ });+ }++ throw new Error(`${fixture.id} did not request required widgets ${JSON.stringify([...required])}.`);+};++const waitForPreview = async () => {+ const deadline = Date.now() + 20_000;+ while (Date.now() < deadline) {+ try {+ const response = await fetch(origin);+ if (response.ok) {+ return;+ }+ } catch {+ // The preview server is still starting.+ }+ await new Promise((resolveWait) => {+ setTimeout(resolveWait, 100);+ });+ }+ throw new Error(`Vite preview did not become ready at ${origin}.`);+};++// The measurement is hermetic: the preview proxy targets a disposable+// in-memory mock backend, never a live InvokeAI instance with real data.+const mockBackend = await startMockBackend(backendPort);++const preview = spawn(+ 'pnpm',+ ['exec', 'vite', 'preview', '--host', '127.0.0.1', '--port', String(port), '--strictPort'],+ {+ cwd: root,+ detached: true,+ env: { ...process.env, INVOKEAI_DEV_BACKEND: backendOrigin },+ stdio: ['ignore', 'pipe', 'pipe'],+ }+);+let previewError = '';+preview.stderr.on('data', (chunk) => {+ previewError += String(chunk);+});++try {+ await waitForPreview();+ const browser = await chromium.launch({ headless: true });+ const routeReports = [];++ for (const fixture of fixtures.routes) {+ const samples = [];+ let stableScriptRequests = null;++ for (let index = 0; index < fixtures.warmups + fixtures.samples; index += 1) {+ // Every sample starts from byte-identical backend state.+ await fetch(`${backendOrigin}/__reset`, { method: 'POST' });+ const context = await browser.newContext();+ if (index === fixtures.warmups) {+ await context.tracing.start({ screenshots: true, snapshots: true, sources: true });+ }+ const page = await context.newPage();+ await page.addInitScript(() => {+ window.__architectureLongTasks = [];+ new PerformanceObserver((list) => {+ window.__architectureLongTasks.push(...list.getEntries().map((entry) => entry.duration));+ }).observe({ buffered: true, type: 'longtask' });+ });+ const scripts = new Set();+ page.on('response', (response) => {+ if (response.request().resourceType() === 'script' && response.url().startsWith(origin)) {+ scripts.add(new URL(response.url()).pathname);+ }+ });++ const expectedScript = fixture.expectedScriptPattern+ ? page.waitForResponse(+ (response) =>+ response.request().resourceType() === 'script' && response.url().includes(fixture.expectedScriptPattern),+ { timeout: 10_000 }+ )+ : null;+ await page.goto(`${origin}${fixture.path}`, { waitUntil: 'domcontentloaded' });+ await expectedScript;+ let layoutSwitchMs = 0;+ let projectSwitchMs = 0;+ if (fixture.expectedScriptPattern) {+ const presetTrigger = page.getByRole('button', { exact: true, name: 'Default' });+ await presetTrigger.waitFor({ timeout: 10_000 });+ if (fixture.layoutPreset) {+ const layoutSwitchStart = performance.now();+ await presetTrigger.click();+ await page.getByRole('menuitem', { exact: true, name: fixture.layoutPreset }).click();+ await page+ .getByRole('button', { exact: true, name: fixture.layoutPreset })+ .first()+ .waitFor({ timeout: 10_000 });+ layoutSwitchMs = performance.now() - layoutSwitchStart;+ }+ }+ if (fixture.measureProjectSwitch) {+ const projectTabs = page.getByRole('tab');+ const originalProject = projectTabs.first();+ await page.getByRole('button', { name: /new project/i }).click();+ await projectTabs.nth(1).waitFor({ timeout: 10_000 });+ const projectSwitchStart = performance.now();+ await originalProject.click();+ await originalProject.waitFor({ state: 'visible' });+ await page.waitForFunction(+ (projectTab) => projectTab instanceof HTMLElement && projectTab.getAttribute('aria-selected') === 'true',+ await originalProject.elementHandle()+ );+ projectSwitchMs = performance.now() - projectSwitchStart;+ }+ await waitForWidgetRequests(fixture, scripts);+ await page.waitForTimeout(100);+ const timing = await page.evaluate(() => {+ const navigation = performance.getEntriesByType('navigation')[0];+ const longTasks = window.__architectureLongTasks;+ return {+ domContentLoadedMs: navigation ? navigation.domContentLoadedEventEnd : 0,+ loadMs: navigation ? navigation.loadEventEnd : 0,+ longestTaskMs: longTasks.reduce((maximum, duration) => Math.max(maximum, duration), 0),+ routeReadyMs: performance.now(),+ };+ });+ timing.layoutSwitchMs = layoutSwitchMs;+ timing.projectSwitchMs = projectSwitchMs;++ if (index === fixtures.warmups) {+ await mkdir(traceDirectory, { recursive: true });+ await context.tracing.stop({ path: resolve(traceDirectory, `${fixture.id}.zip`) });+ }+ await context.close();++ if (index >= fixtures.warmups) {+ const scriptRequests = [...scripts].map((request) => chunkNameByPath.get(request) ?? request).sort();+ stableScriptRequests ??= scriptRequests;+ if (JSON.stringify(stableScriptRequests) !== JSON.stringify(scriptRequests)) {+ throw new Error(+ `${fixture.id} request set was unstable between samples: ${JSON.stringify(stableScriptRequests)} vs ${JSON.stringify(scriptRequests)}`+ );+ }+ samples.push(timing);+ }+ }++ routeReports.push({+ domContentLoadedMedianMs: median(samples.map((sample) => sample.domContentLoadedMs)),+ id: fixture.id,+ loadMedianMs: median(samples.map((sample) => sample.loadMs)),+ longestTaskMaxMs: Math.max(...samples.map((sample) => sample.longestTaskMs)),+ layoutSwitchMedianMs: median(samples.map((sample) => sample.layoutSwitchMs)),+ projectSwitchMedianMs: median(samples.map((sample) => sample.projectSwitchMs)),+ owner: fixture.owner,+ remediationTicket: fixture.remediationTicket,+ routeReadyMedianMs: median(samples.map((sample) => sample.routeReadyMs)),+ scriptRequests: stableScriptRequests,+ });+ }++ await browser.close();+ const report = {+ browserExecutable: chromium.executablePath(),+ capturedAt: new Date().toISOString(),+ routes: routeReports,+ samples: fixtures.samples,+ warmups: fixtures.warmups,+ };+ await mkdir(dirname(artifactPath), { recursive: true });+ await writeFile(artifactPath, `${JSON.stringify(report, null, 2)}\n`);++ if (updateBaseline) {+ await writeFile(+ baselinePath,+ `${JSON.stringify(+ {+ ...report,+ capturedAt: '2026-07-17',+ enforceTiming: false,+ longTaskTargetMs: 50,+ schemaVersion: 1,+ timingStatus: 'informational-until-ci-runner-is-stable',+ timingTolerancePercent: 0.1,+ },+ null,+ 2+ )}\n`+ );+ } else {+ const baseline = JSON.parse(await readFile(baselinePath, 'utf8'));+ const failures = [];+ const timingLimit = (value) => value * (1 + baseline.timingTolerancePercent);+ for (const route of routeReports) {+ const expected = baseline.routes.find((candidate) => candidate.id === route.id);+ if (!expected) {+ failures.push(`${route.id} has no checked-in browser baseline (owner ${route.owner}).`);+ continue;+ }+ if (JSON.stringify(route.scriptRequests) !== JSON.stringify(expected.scriptRequests)) {+ failures.push(+ `${route.id} script request set changed (owner ${route.owner}, remediation ${route.remediationTicket}).\nExpected ${JSON.stringify(expected.scriptRequests)}\nReceived ${JSON.stringify(route.scriptRequests)}`+ );+ }+ if (baseline.enforceTiming && route.domContentLoadedMedianMs > timingLimit(expected.domContentLoadedMedianMs)) {+ failures.push(+ `${route.id} DOMContentLoaded median exceeded its timing tolerance (owner ${route.owner}, remediation ${route.remediationTicket}).`+ );+ }+ if (+ baseline.enforceTiming &&+ expected.layoutSwitchMedianMs > 0 &&+ route.layoutSwitchMedianMs > timingLimit(expected.layoutSwitchMedianMs)+ ) {+ failures.push(+ `${route.id} layout-switch median exceeded its timing tolerance (owner ${route.owner}, remediation ${route.remediationTicket}).`+ );+ }+ if (+ baseline.enforceTiming &&+ expected.projectSwitchMedianMs > 0 &&+ route.projectSwitchMedianMs > timingLimit(expected.projectSwitchMedianMs)+ ) {+ failures.push(+ `${route.id} project-switch median exceeded its timing tolerance (owner ${route.owner}, remediation ${route.remediationTicket}).`+ );+ }+ if (+ baseline.enforceTiming &&+ route.longestTaskMaxMs > Math.max(baseline.longTaskTargetMs, timingLimit(expected.longestTaskMaxMs))+ ) {+ failures.push(+ `${route.id} longest task exceeded its timing tolerance (owner ${route.owner}, remediation ${route.remediationTicket}).`+ );+ }+ }+ if (failures.length > 0) {+ throw new Error(failures.join('\n'));+ }+ }++ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);+} catch (error) {+ throw new Error(+ `${error instanceof Error ? error.message : String(error)}${previewError ? `\n${previewError}` : ''}`+ );+} finally {+ if (preview.pid) {+ try {+ process.kill(-preview.pid, 'SIGTERM');+ } catch {+ // The preview process may have already exited after a startup failure.+ }+ }+ await mockBackend.close();+}diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjsnew file mode 100644index 0000000000..3114bde4df--- /dev/null+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -0,0 +1,181 @@+import { createServer } from 'node:http';++/**+ * Disposable in-memory backend for the browser performance measurement.+ * Serves just enough of the InvokeAI REST surface for the measured routes to+ * boot deterministically: stateful projects + client-state KV, and stable+ * empty responses for the read models (queue, models, gallery, workflows).+ * `POST /__reset` wipes all state so every sample starts from byte-identical+ * backend state. No socket.io server is provided; the app measures as+ * disconnected, which is deterministic.+ */++const createState = () => ({+ clientState: new Map(),+ nextProjectNumber: 1,+ projects: new Map(),+});++const timestamp = () => new Date().toISOString().replace('T', ' ').replace('Z', '');++const summaryOf = (project) => ({+ created_at: project.created_at,+ name: project.name,+ project_id: project.project_id,+ revision: project.revision,+ updated_at: project.updated_at,+});++const readBody = (request) =>+ new Promise((resolve, reject) => {+ const chunks = [];+ request.on('data', (chunk) => chunks.push(chunk));+ request.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));+ request.on('error', reject);+ });++export const startMockBackend = async (port) => {+ let state = createState();++ const server = createServer(async (request, response) => {+ const url = new URL(request.url, `http://127.0.0.1:${port}`);+ const path = url.pathname;+ const method = request.method ?? 'GET';++ const json = (status, value) => {+ const body = JSON.stringify(value ?? null);+ response.writeHead(status, { 'content-type': 'application/json' });+ response.end(body);+ };++ if (method === 'POST' && path === '/__reset') {+ state = createState();+ return json(200, { ok: true });+ }++ if (path === '/api/v1/projects/' || path === '/api/v1/projects') {+ if (method === 'GET') {+ return json(200, [...state.projects.values()].map(summaryOf));+ }+ if (method === 'POST') {+ const requested = JSON.parse((await readBody(request)) || '{}');+ const now = timestamp();+ const project = {+ created_at: now,+ data: requested.data ?? {},+ name: requested.name ?? `Project Name #${state.nextProjectNumber}`,+ project_id: requested.project_id ?? `mock-project-${state.nextProjectNumber}`,+ revision: 1,+ updated_at: now,+ };+ state.nextProjectNumber += 1;+ state.projects.set(project.project_id, project);+ return json(200, project);+ }+ }++ const projectMatch = /^\/api\/v1\/projects\/([^/]+)$/.exec(path);+ if (projectMatch) {+ const projectId = decodeURIComponent(projectMatch[1]);+ const project = state.projects.get(projectId);+ if (method === 'GET') {+ return project ? json(200, project) : json(404, { detail: 'Project not found' });+ }+ if (method === 'PUT') {+ if (!project) {+ return json(404, { detail: 'Project not found' });+ }+ const requested = JSON.parse((await readBody(request)) || '{}');+ if (requested.expected_revision !== undefined && requested.expected_revision !== project.revision) {+ return json(409, { detail: 'Revision conflict' });+ }+ project.data = requested.data ?? project.data;+ project.name = requested.name ?? project.name;+ project.revision += 1;+ project.updated_at = timestamp();+ return json(200, project);+ }+ if (method === 'DELETE') {+ state.projects.delete(projectId);+ return json(200, { ok: true });+ }+ }++ if (path.startsWith('/api/v1/client_state/')) {+ const key = url.searchParams.get('key') ?? '';+ if (path.endsWith('/get_by_key')) {+ return json(200, state.clientState.get(key) ?? null);+ }+ if (path.endsWith('/set_by_key')) {+ const value = JSON.parse((await readBody(request)) || 'null');+ state.clientState.set(key, value);+ return json(200, value);+ }+ if (path.endsWith('/delete_by_key')) {+ state.clientState.delete(key);+ return json(200, { ok: true });+ }+ }++ const queueMatch = /^\/api\/v1\/queue\/[^/]+\/(.+)$/.exec(path);+ if (queueMatch) {+ const action = queueMatch[1];+ if (action === 'status') {+ return json(200, {+ processor: { is_processing: false, is_started: true },+ queue: { canceled: 0, completed: 0, failed: 0, in_progress: 0, pending: 0, queue_id: 'default', total: 0 },+ });+ }+ if (action === 'current' || action === 'next') {+ return json(200, null);+ }+ if (action === 'list_all' || action === 'items_by_ids') {+ return json(200, []);+ }+ if (action === 'list') {+ return json(200, { item_ids: [], total_count: 0 });+ }+ return json(200, null);+ }++ if (path.startsWith('/api/v2/models/stats')) {+ return json(200, null);+ }+ if (path.startsWith('/api/v2/models')) {+ return json(200, { models: [] });+ }+ if (path.startsWith('/api/v1/model_relationships')) {+ return json(200, []);+ }+ if (path.startsWith('/api/v1/app/external_providers')) {+ return json(200, []);+ }+ if (path.startsWith('/api/v1/virtual_boards/by_date')) {+ return json(200, []);+ }+ if (path.startsWith('/api/v1/images/images_by_names')) {+ return json(200, []);+ }+ if (path.startsWith('/api/v1/workflows')) {+ return json(200, { items: [], total: 0 });+ }+ if (path.startsWith('/api/v2/custom_nodes')) {+ return json(200, []);+ }++ return json(404, { detail: `No mock for ${method} ${path}` });+ });++ await new Promise((resolve, reject) => {+ server.once('error', reject);+ server.listen(port, '127.0.0.1', resolve);+ });++ return {+ close: () =>+ new Promise((resolve) => {+ server.close(resolve);+ server.closeAllConnections?.();+ }),+ };+};diff --git a/invokeai/frontend/webv2/scripts/performance-budgets.mjs b/invokeai/frontend/webv2/scripts/performance-budgets.mjsnew file mode 100644index 0000000000..a0902f3947--- /dev/null+++ b/invokeai/frontend/webv2/scripts/performance-budgets.mjs@@ -0,0 +1,74 @@+import { brotliCompressSync, constants, gzipSync } from 'node:zlib';++const collectStaticImports = (manifest, source, collected = new Set()) => {+ if (collected.has(source)) {+ return collected;+ }+ const chunk = manifest[source];+ if (!chunk) {+ throw new Error(`Build manifest is missing route source "${source}".`);+ }+ collected.add(source);+ for (const imported of chunk.imports ?? []) {+ collectStaticImports(manifest, imported, collected);+ }+ return collected;+};++const getChunkName = (source, chunk) => chunk.name ?? chunk.src ?? source;++export const measureRouteBuild = (manifest, routeId, source, readAsset) => {+ const sources = [...collectStaticImports(manifest, source)];+ const assets = sources.map((chunkSource) => {+ const chunk = manifest[chunkSource];+ return { bytes: readAsset(chunk.file), chunk, source: chunkSource };+ });+ const owned = assets.find((asset) => asset.source === source);++ return {+ brotliBytes: assets.reduce(+ (total, asset) =>+ total + brotliCompressSync(asset.bytes, { params: { [constants.BROTLI_PARAM_QUALITY]: 4 } }).byteLength,+ 0+ ),+ chunkNames: assets.map((asset) => getChunkName(asset.source, asset.chunk)).sort(),+ files: assets.map((asset) => asset.chunk.file).sort(),+ gzipBytes: assets.reduce((total, asset) => total + gzipSync(asset.bytes, { level: 9 }).byteLength, 0),+ initialRawBytes: assets.reduce((total, asset) => total + asset.bytes.byteLength, 0),+ ownedRawBytes: owned.bytes.byteLength,+ routeId,+ source,+ sources: sources.sort(),+ };+};++export const checkRouteBudget = (measurement, budget) => {+ const failures = [];+ const allowedGrowth = Math.min(+ budget.maxGrowthRawBytes,+ Math.floor(budget.baselineOwnedRawBytes * budget.maxGrowthPercent)+ );+ const maximumOwnedBytes = budget.baselineOwnedRawBytes + allowedGrowth;++ if (measurement.ownedRawBytes > maximumOwnedBytes) {+ failures.push({+ actual: measurement.ownedRawBytes,+ budget: maximumOwnedBytes,+ message: `${measurement.routeId} owned JavaScript grew to ${measurement.ownedRawBytes} bytes (budget ${maximumOwnedBytes}, baseline ${budget.baselineOwnedRawBytes}).`,+ owner: budget.owner,+ remediationTicket: budget.remediationTicket,+ routeId: measurement.routeId,+ });+ }+ if (JSON.stringify(measurement.chunkNames) !== JSON.stringify(budget.initialChunkNames)) {+ failures.push({+ actual: measurement.chunkNames,+ budget: budget.initialChunkNames,+ message: `${measurement.routeId} initial request set changed. Expected [${budget.initialChunkNames.join(', ')}], received [${measurement.chunkNames.join(', ')}].`,+ owner: budget.owner,+ remediationTicket: budget.remediationTicket,+ routeId: measurement.routeId,+ });+ }+ return failures;+};diff --git a/invokeai/frontend/webv2/scripts/widget-sources.mjs b/invokeai/frontend/webv2/scripts/widget-sources.mjsnew file mode 100644index 0000000000..fabb89878e--- /dev/null+++ b/invokeai/frontend/webv2/scripts/widget-sources.mjs@@ -0,0 +1,27 @@+/**+ * Single source of truth for the deferred first-party widget implementation+ * chunks. `check-architecture-performance.mjs` asserts every entry splits into+ * its own chunk and that no manifest source matching WIDGET_IMPLEMENTATION_PATTERN+ * is missing from this registry; `measure-architecture-performance.mjs` derives+ * stable `widget:<id>` script ids from it.+ */+export const WIDGET_IMPLEMENTATION_PATTERN = /^src\/workbench\/widgets\/([^/]+)\/implementation\.ts$/;++export const WIDGET_SOURCES = new Map([+ ['src/workbench/widgets/autosave-status/implementation.ts', 'autosave-status'],+ ['src/workbench/widgets/canvas/implementation.ts', 'canvas'],+ ['src/workbench/widgets/diagnostics/implementation.ts', 'diagnostics'],+ ['src/workbench/widgets/layers/implementation.ts', 'layers'],+ ['src/workbench/widgets/notifications/implementation.ts', 'notifications'],+ ['src/workbench/widgets/preview/implementation.ts', 'preview'],+ ['src/workbench/widgets/project/implementation.ts', 'project'],+ ['src/workbench/widgets/server-status/implementation.ts', 'server-status'],+ ['src/workbench/widgets/version-status/implementation.ts', 'version-status'],+ ['src/features/gallery/widget.ts', 'gallery'],+ ['src/features/generation/widget.ts', 'generate'],+ ['src/features/queue/widget.ts', 'queue'],+ ['src/features/upscale/widget.ts', 'upscale'],+ ['src/features/workflow/ui/implementation.ts', 'workflow'],+]);++export const getWidgetId = (source) => WIDGET_SOURCES.get(source) ?? null;diff --git a/invokeai/frontend/webv2/scripts/write-canvas-import-matrix.mjs b/invokeai/frontend/webv2/scripts/write-canvas-import-matrix.mjsnew file mode 100644index 0000000000..bd71a4d8cb--- /dev/null+++ b/invokeai/frontend/webv2/scripts/write-canvas-import-matrix.mjs@@ -0,0 +1,149 @@+import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';+import { dirname, extname, join, relative, resolve } from 'node:path';+import ts from 'typescript';++const packageRoot = process.cwd();+const sourceRoot = resolve(packageRoot, 'src');+const normalize = (path) => path.replaceAll('\\', '/');+const isTypeScript = (path) => /\.[cm]?[jt]sx?$/.test(path);+const isProduction = (path) => !/(?:\.test|\.browser\.test|\.type-test|\.stories)\.[^.]+$/.test(path);+const stripExtension = (path) => path.slice(0, -extname(path).length);+const paths = readdirSync(sourceRoot, { recursive: true, withFileTypes: true })+ .filter((entry) => entry.isFile())+ .map((entry) => normalize(relative(sourceRoot, join(entry.parentPath, entry.name))))+ .filter(isTypeScript)+ .sort();+const pathByStem = new Map(paths.map((path) => [stripExtension(path), path]));+const aliases = [+ ['@app', 'app'],+ ['@features', 'features'],+ ['@platform', 'platform'],+ ['@theme', 'platform/ui/theme'],+ ['@workbench', 'workbench'],+ ['@', ''],+];++const normalizeSegments = (path) => {+ const parts = [];+ for (const part of path.split('/')) {+ if (!part || part === '.') {+ continue;+ }+ if (part === '..') {+ parts.pop();+ } else {+ parts.push(part);+ }+ }+ return parts.join('/');+};++const resolveImport = (sourcePath, specifier) => {+ let stem = null;+ if (specifier.startsWith('.')) {+ stem = normalizeSegments(`${dirname(sourcePath)}/${specifier}`);+ } else {+ for (const [alias, target] of aliases) {+ if (specifier === alias || specifier.startsWith(`${alias}/`)) {+ stem = normalizeSegments(`${target}${specifier.slice(alias.length)}`);+ break;+ }+ }+ }+ return stem ? (pathByStem.get(stem) ?? pathByStem.get(`${stem}/index`) ?? null) : null;+};++const isCanvasOwned = (path) =>+ path.startsWith('workbench/canvas-engine/') || path.startsWith('workbench/canvas-operations/');+const isCanvasTarget = (path) => isCanvasOwned(path);+const isPublicTarget = (path) =>+ path === 'workbench/canvas-engine/api.ts' ||+ path === 'workbench/canvas-operations/api.ts' ||+ path === 'workbench/canvas-operations/react.ts';+const callerIntent = (path) => {+ if (path.startsWith('workbench/widgets/canvas/')) {+ return 'canvas-widget';+ }+ if (path.startsWith('workbench/widgets/layers/')) {+ return 'layers-widget';+ }+ if (path.startsWith('features/generation/')) {+ return 'generation';+ }+ if (path.startsWith('workbench/image-actions/')) {+ return 'image-actions';+ }+ if (path.startsWith('workbench/widgets/')) {+ return 'other-widget';+ }+ return path.split('/').slice(0, 2).join('/');+};+const importedSymbols = (clause) => {+ if (!clause) {+ return ['side-effect'];+ }+ const symbols = [];+ if (clause.name) {+ symbols.push('default');+ }+ if (clause.namedBindings && ts.isNamespaceImport(clause.namedBindings)) {+ symbols.push('*');+ }+ if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {+ for (const element of clause.namedBindings.elements) {+ symbols.push((element.propertyName ?? element.name).text);+ }+ }+ return symbols.sort();+};++const imports = [];+for (const source of paths.filter(isProduction)) {+ if (isCanvasOwned(source)) {+ continue;+ }+ const text = readFileSync(resolve(sourceRoot, source), 'utf8');+ const file = ts.createSourceFile(+ source,+ text,+ ts.ScriptTarget.Latest,+ true,+ source.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS+ );+ for (const statement of file.statements) {+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteralLike(statement.moduleSpecifier)) {+ continue;+ }+ const target = resolveImport(source, statement.moduleSpecifier.text);+ if (!target || !isCanvasTarget(target)) {+ continue;+ }+ imports.push({+ intent: callerIntent(source),+ interface: target.startsWith('workbench/canvas-engine/') ? 'canvas-engine' : 'canvas-operations',+ private: !isPublicTarget(target),+ source,+ symbols: importedSymbols(statement.importClause),+ target,+ });+ }+}++const grouped = Object.entries(Object.groupBy(imports, ({ intent }) => intent))+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([intent, records]) => ({ intent, imports: records }));+const privateImports = imports.filter((record) => record.private);+const artifact = {+ generatedBy: 'scripts/write-canvas-import-matrix.mjs',+ groups: grouped,+ summary: {+ externalProductionCallerCount: new Set(imports.map(({ source }) => source)).size,+ importDeclarationCount: imports.length,+ privateCallerCount: new Set(privateImports.map(({ source }) => source)).size,+ privateImportDeclarationCount: privateImports.length,+ },+};++const artifactPath = resolve(packageRoot, 'artifacts/architecture/canvas-import-matrix.json');+mkdirSync(dirname(artifactPath), { recursive: true });+writeFileSync(artifactPath, `${JSON.stringify(artifact, null, 2)}\n`);diff --git a/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjs b/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjsnew file mode 100644index 0000000000..c552c3e3f5--- /dev/null+++ b/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjs@@ -0,0 +1,194 @@+import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';+import { dirname, extname, join, relative, resolve } from 'node:path';+import ts from 'typescript';++const packageRoot = process.cwd();+const sourceRoot = resolve(packageRoot, 'src');+const normalize = (path) => path.replaceAll('\\', '/');+const isTypeScript = (path) => /\.[cm]?[jt]sx?$/.test(path);+const isTest = (path) => /(?:\.test|\.browser\.test|\.type-test)\.[^.]+$/.test(path);+const stripExtension = (path) => path.slice(0, -extname(path).length);+const paths = readdirSync(sourceRoot, { recursive: true, withFileTypes: true })+ .filter((entry) => entry.isFile())+ .map((entry) => normalize(relative(sourceRoot, join(entry.parentPath, entry.name))))+ .filter(isTypeScript)+ .sort();+const sources = new Map(paths.map((path) => [path, readFileSync(resolve(sourceRoot, path), 'utf8')]));+const pathByStem = new Map(paths.map((path) => [stripExtension(path), path]));+const aliases = [+ ['@app', 'app'],+ ['@features', 'features'],+ ['@platform', 'platform'],+ ['@theme', 'platform/ui/theme'],+ ['@workbench', 'workbench'],+ ['@', ''],+];+const hubs = [+ 'features/queue/index.ts',+ 'features/gallery/contracts.ts',+ 'features/gallery/index.ts',+ 'features/gallery/queries.ts',+ 'features/gallery/react.ts',+ 'features/gallery/utility.ts',+ 'features/gallery/widget.ts',+ 'features/identity/index.ts',+ 'features/models/index.ts',+ 'features/models/react.ts',+ 'features/nodes/index.ts',+ 'features/generation/batch.ts',+ 'features/generation/canvas.ts',+ 'features/generation/contracts.ts',+ 'features/generation/draft-values.ts',+ 'features/generation/drafts.ts',+ 'features/generation/form.ts',+ 'features/generation/graph.ts',+ 'features/generation/hotkeys.ts',+ 'features/generation/index.ts',+ 'features/generation/prompt.ts',+ 'features/generation/prompt-ui.ts',+ 'features/generation/react.ts',+ 'features/generation/reference-ui.ts',+ 'features/generation/settings.ts',+ 'features/generation/settings-ui.ts',+ 'features/generation/utility.ts',+ 'features/generation/widget.ts',+ 'features/workflow/contracts.ts',+ 'features/workflow/graph.ts',+ 'features/workflow/index.ts',+ 'features/workflow/preview.ts',+ 'features/workflow/queries.ts',+ 'features/workflow/react.ts',+ 'features/workflow/utility.ts',+ 'features/workflow/widget.ts',+ 'features/upscale/index.ts',+ 'features/upscale/widget.ts',+ 'workbench/canvas-engine/contracts.ts',+ 'workbench/canvas-engine/types.ts',+ 'workbench/diagnostics/contracts.ts',+ 'workbench/graphContracts.ts',+ 'workbench/invocationContracts.ts',+ 'workbench/layoutContracts.ts',+ 'workbench/persistenceContracts.ts',+ 'workbench/projectContracts.ts',+ 'workbench/settings/contracts.ts',+ 'workbench/widgetContracts.ts',+];++const normalizeSegments = (path) => {+ const parts = [];+ for (const part of path.split('/')) {+ if (!part || part === '.') {+ continue;+ }+ if (part === '..') {+ parts.pop();+ } else {+ parts.push(part);+ }+ }+ return parts.join('/');+};++const resolveImport = (sourcePath, specifier) => {+ let stem = null;+ if (specifier.startsWith('.')) {+ stem = normalizeSegments(`${sourcePath.slice(0, sourcePath.lastIndexOf('/'))}/${specifier}`);+ } else {+ for (const [alias, target] of aliases) {+ if (specifier === alias || specifier.startsWith(`${alias}/`)) {+ stem = normalizeSegments(`${target}${specifier.slice(alias.length)}`);+ break;+ }+ }+ }+ return stem ? (pathByStem.get(stem) ?? pathByStem.get(`${stem}/index`) ?? null) : null;+};++const parse = (path) =>+ ts.createSourceFile(+ path,+ sources.get(path),+ ts.ScriptTarget.Latest,+ true,+ path.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS+ );++const exportedSymbols = (path) => {+ const symbols = new Set();+ for (const statement of parse(path).statements) {+ const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined;+ if (modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {+ if (statement.name && ts.isIdentifier(statement.name)) {+ symbols.add(statement.name.text);+ }+ if (ts.isVariableStatement(statement)) {+ for (const declaration of statement.declarationList.declarations) {+ if (ts.isIdentifier(declaration.name)) {+ symbols.add(declaration.name.text);+ }+ }+ }+ }+ if (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)) {+ for (const element of statement.exportClause.elements) {+ symbols.add(element.name.text);+ }+ }+ }+ return [...symbols].sort();+};++const callerRecords = new Map(hubs.map((hub) => [hub, new Map()]));+const addCaller = (hub, symbol, caller) => {+ const symbols = callerRecords.get(hub);+ const callers = symbols.get(symbol) ?? new Set();+ callers.add(caller);+ symbols.set(symbol, callers);+};++for (const path of paths) {+ for (const statement of parse(path).statements) {+ if (+ !ts.isImportDeclaration(statement) ||+ !statement.importClause ||+ !ts.isStringLiteralLike(statement.moduleSpecifier)+ ) {+ continue;+ }+ const target = resolveImport(path, statement.moduleSpecifier.text);+ if (!target || !callerRecords.has(target)) {+ continue;+ }+ const bindings = statement.importClause.namedBindings;+ if (bindings && ts.isNamedImports(bindings)) {+ for (const element of bindings.elements) {+ addCaller(target, (element.propertyName ?? element.name).text, path);+ }+ } else {+ addCaller(target, '*', path);+ }+ }+}++const matrix = hubs.map((hub) => {+ const callersBySymbol = callerRecords.get(hub);+ const symbols = exportedSymbols(hub).map((symbol) => {+ const callers = [...(callersBySymbol.get(symbol) ?? [])].sort();+ return {+ callers,+ productionCallers: callers.filter((path) => !isTest(path)),+ symbol,+ };+ });+ const allCallers = [...new Set([...callersBySymbol.values()].flatMap((callers) => [...callers]))].sort();+ return {+ allCallers,+ hub,+ productionCallerCount: allCallers.filter((path) => !isTest(path)).length,+ symbols,+ };+});++const artifactPath = resolve(packageRoot, 'artifacts/architecture/contract-caller-matrix.json');+mkdirSync(dirname(artifactPath), { recursive: true });+writeFileSync(artifactPath, `${JSON.stringify({ hubs: matrix }, null, 2)}\n`);diff --git a/invokeai/frontend/webv2/scripts/write-workbench-ownership-inventory.mjs b/invokeai/frontend/webv2/scripts/write-workbench-ownership-inventory.mjsnew file mode 100644index 0000000000..249ec67eb8--- /dev/null+++ b/invokeai/frontend/webv2/scripts/write-workbench-ownership-inventory.mjs@@ -0,0 +1,289 @@+import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';+import { dirname, extname, join, relative, resolve } from 'node:path';+import ts from 'typescript';++const packageRoot = process.cwd();+const sourceRoot = resolve(packageRoot, 'src');+const manifest = JSON.parse(readFileSync(resolve(sourceRoot, 'architecture/workbenchOwnershipManifest.json'), 'utf8'));+const isSource = (path) => /\.[cm]?[jt]sx?$/.test(path);+const isTest = (path) => /(?:\.test|\.browser\.test|\.type-test)\.[^.]+$/.test(path);+const stripExtension = (path) => path.slice(0, -extname(path).length);+const normalize = (path) => path.replaceAll('\\', '/').replace(/^src\//, '');+const paths = readdirSync(sourceRoot, { recursive: true, withFileTypes: true })+ .filter((entry) => entry.isFile())+ .map((entry) => normalize(relative(sourceRoot, join(entry.parentPath, entry.name))))+ .filter(isSource)+ .sort();+const productionPaths = paths.filter((path) => !isTest(path));+const sources = new Map(productionPaths.map((path) => [path, readFileSync(resolve(sourceRoot, path), 'utf8')]));+const pathByStem = new Map(productionPaths.map((path) => [stripExtension(path), path]));++const aliases = [+ ['@app', 'app'],+ ['@features', 'features'],+ ['@platform', 'platform'],+ ['@theme', 'platform/ui/theme'],+ ['@workbench', 'workbench'],+ ['@', ''],+];++const normalizeSegments = (path) => {+ const parts = [];+ for (const part of path.split('/')) {+ if (!part || part === '.') {+ continue;+ }+ if (part === '..') {+ parts.pop();+ } else {+ parts.push(part);+ }+ }+ return parts.join('/');+};++const resolveImport = (sourcePath, specifier) => {+ let resolved = null;+ if (specifier.startsWith('.')) {+ resolved = normalizeSegments(`${sourcePath.slice(0, sourcePath.lastIndexOf('/'))}/${specifier}`);+ } else {+ for (const [alias, target] of aliases) {+ if (specifier === alias || specifier.startsWith(`${alias}/`)) {+ resolved = normalizeSegments(`${target}${specifier.slice(alias.length)}`);+ break;+ }+ }+ }+ return resolved ? (pathByStem.get(resolved) ?? pathByStem.get(`${resolved}/index`) ?? null) : null;+};++const currentOwner = (path) => {+ const feature = /^features\/([^/]+)/.exec(path)?.[1];+ if (feature) {+ return `feature:${feature}`;+ }+ if (path.startsWith('app/')) {+ return 'app';+ }+ if (path.startsWith('platform/')) {+ return 'platform';+ }+ return 'workbench';+};++const matchesPrefix = (path, prefix) =>+ path === prefix || path.startsWith(`${prefix}.`) || path.startsWith(`${prefix}/`);+const targetRule = (path) => {+ const relativePath = path.replace(/^workbench\//, '');+ const rootOwner = manifest.rootFiles[relativePath];+ if (rootOwner) {+ const stem = stripExtension(relativePath);+ const targetPath =+ rootOwner === 'workbench'+ ? `workbench/${stem}`+ : rootOwner === 'platform'+ ? `platform/state/react/${stem}`+ : `features/${rootOwner.slice('feature:'.length)}/core/${stem}`;+ return { targetOwner: rootOwner, targetPath };+ }+ const override = manifest.overrides+ .filter((rule) => matchesPrefix(relativePath, rule.pathPrefix))+ .sort((a, b) => b.pathPrefix.length - a.pathPrefix.length)[0];+ if (override) {+ return override;+ }+ return manifest.directoryRules[relativePath.split('/')[0]] ?? null;+};+const targetOwner = (path) => (path.startsWith('workbench/') ? targetRule(path)?.targetOwner : currentOwner(path));++const parse = (path, source) => ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const imports = (path, source) => {+ const sourceFile = parse(path, source);+ const specifiers = [];+ const visit = (node) => {+ if (+ (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&+ node.moduleSpecifier &&+ ts.isStringLiteralLike(node.moduleSpecifier)+ ) {+ specifiers.push(node.moduleSpecifier.text);+ } else if (+ ts.isImportTypeNode(node) &&+ ts.isLiteralTypeNode(node.argument) &&+ ts.isStringLiteralLike(node.argument.literal)+ ) {+ specifiers.push(node.argument.literal.text);+ } else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {+ const argument = node.arguments[0];+ if (argument && ts.isStringLiteralLike(argument)) {+ specifiers.push(argument.text);+ }+ }+ ts.forEachChild(node, visit);+ };+ visit(sourceFile);+ return specifiers;+};++const publicExports = (path, source) => {+ const names = new Set();+ for (const statement of parse(path, source).statements) {+ const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined;+ if (modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {+ if (statement.name && ts.isIdentifier(statement.name)) {+ names.add(statement.name.text);+ }+ if (ts.isVariableStatement(statement)) {+ for (const declaration of statement.declarationList.declarations) {+ if (ts.isIdentifier(declaration.name)) {+ names.add(declaration.name.text);+ }+ }+ }+ }+ if (ts.isExportAssignment(statement)) {+ names.add('default');+ }+ if (ts.isExportDeclaration(statement)) {+ if (!statement.exportClause) {+ names.add('*');+ } else if (ts.isNamedExports(statement.exportClause)) {+ for (const element of statement.exportClause.elements) {+ names.add(element.name.text);+ }+ }+ }+ }+ return [...names].sort();+};++const isTypeOnly = (path, source) =>+ parse(path, source).statements.every((statement) => {+ if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) {+ return true;+ }+ if (ts.isImportDeclaration(statement)) {+ return Boolean(statement.importClause?.isTypeOnly);+ }+ if (ts.isExportDeclaration(statement)) {+ return statement.isTypeOnly;+ }+ return ts.isEmptyStatement(statement);+ });++const inbound = new Map();+const graph = new Map();+const fileGraph = new Map();+for (const [sourcePath, source] of sources) {+ const sourceOwner = targetOwner(sourcePath);+ if (!sourceOwner) {+ throw new Error(`Unclassified source: ${sourcePath}`);+ }+ graph.set(sourceOwner, graph.get(sourceOwner) ?? new Set());+ fileGraph.set(sourcePath, fileGraph.get(sourcePath) ?? new Set());+ for (const specifier of imports(sourcePath, source)) {+ const targetPath = resolveImport(sourcePath, specifier);+ if (!targetPath) {+ continue;+ }+ const owner = targetOwner(targetPath);+ if (!owner) {+ throw new Error(`Unclassified target: ${targetPath}`);+ }+ fileGraph.get(sourcePath).add(targetPath);+ const inboundOwners = inbound.get(targetPath) ?? new Set();+ inboundOwners.add(sourceOwner);+ inbound.set(targetPath, inboundOwners);+ graph.set(owner, graph.get(owner) ?? new Set());+ if (owner !== sourceOwner) {+ graph.get(sourceOwner).add(owner);+ }+ }+}++const components = (dependencyGraph) => {+ let index = 0;+ const indexes = new Map();+ const low = new Map();+ const stack = [];+ const onStack = new Set();+ const result = [];+ const visit = (node) => {+ indexes.set(node, index);+ low.set(node, index++);+ stack.push(node);+ onStack.add(node);+ for (const target of dependencyGraph.get(node) ?? []) {+ if (!indexes.has(target)) {+ visit(target);+ low.set(node, Math.min(low.get(node), low.get(target)));+ } else if (onStack.has(target)) {+ low.set(node, Math.min(low.get(node), indexes.get(target)));+ }+ }+ if (low.get(node) === indexes.get(node)) {+ const component = [];+ let member;+ do {+ member = stack.pop();+ onStack.delete(member);+ component.push(member);+ } while (member !== node);+ if (component.length > 1) {+ result.push(component.sort());+ }+ }+ };+ for (const node of dependencyGraph.keys()) {+ if (!indexes.has(node)) {+ visit(node);+ }+ }+ return result.sort((a, b) => a.join().localeCompare(b.join()));+};++const workbenchPaths = productionPaths.filter((path) => path.startsWith('workbench/'));+const modules = workbenchPaths.map((path) => {+ const source = sources.get(path);+ const rule = targetRule(path);+ if (!rule) {+ throw new Error(`Unclassified Workbench module: ${path}`);+ }+ const outboundOwners = new Set(+ imports(path, source)+ .map((specifier) => resolveImport(path, specifier))+ .filter(Boolean)+ .map(targetOwner)+ .filter(Boolean)+ );+ const stem = stripExtension(path);+ return {+ currentOwner: 'workbench',+ inboundOwners: [...(inbound.get(path) ?? [])].sort(),+ moduleKind: isTypeOnly(path, source) ? 'type-only' : 'runtime',+ outboundOwners: [...outboundOwners].sort(),+ path,+ publicExports: publicExports(path, source),+ targetOwner: rule.targetOwner,+ targetPath: rule.targetPath,+ testCompanions: paths.filter((candidate) => candidate.startsWith(`${stem}.`) && isTest(candidate)).sort(),+ };+});++const artifact = {+ counts: {+ productionWorkbenchModules: modules.length,+ runtimeModules: modules.filter((module) => module.moduleKind === 'runtime').length,+ typeOnlyModules: modules.filter((module) => module.moduleKind === 'type-only').length,+ },+ generatedFromManifestVersion: manifest.version,+ fileCycles: components(fileGraph),+ modules,+ targetDependencyGraph: Object.fromEntries(+ [...graph].sort(([a], [b]) => a.localeCompare(b)).map(([owner, targets]) => [owner, [...targets].sort()])+ ),+ transitionalCycles: components(graph),+};+const artifactPath = resolve(packageRoot, 'artifacts/architecture/workbench-ownership-inventory.json');+mkdirSync(dirname(artifactPath), { recursive: true });+writeFileSync(artifactPath, `${JSON.stringify(artifact, null, 2)}\n`);diff --git a/invokeai/frontend/webv2/src/App.tsx b/invokeai/frontend/webv2/src/App.tsxdeleted file mode 100644index 9826a01e03..0000000000--- a/invokeai/frontend/webv2/src/App.tsx+++ /dev/null@@ -1,17 +0,0 @@-import { ChakraProvider } from '@chakra-ui/react';-import { RouterProvider } from '@tanstack/react-router';--import { router } from './router';-import { system } from './theme/system';-import { AppToaster } from './workbench/components/ui/toaster';-import { I18nController } from './workbench/i18n';-import { ThemeController } from './workbench/ThemeController';--export const App = () => (- <ChakraProvider value={system}>- <ThemeController />- <I18nController />- <AppToaster />- <RouterProvider router={router} />- </ChakraProvider>-);diff --git a/invokeai/frontend/webv2/src/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/WorkbenchApp.tsxdeleted file mode 100644index 6ffc11d4c6..0000000000--- a/invokeai/frontend/webv2/src/WorkbenchApp.tsx+++ /dev/null@@ -1,41 +0,0 @@-import { useSearch } from '@tanstack/react-router';-import { WorkbenchShell } from '@workbench/shell';-import { useMemo } from 'react';--import type { WorkbenchSearch } from './workbench/projects/session';--import { SessionExpiryGuard } from './workbench/auth/components/SessionExpiryGuard';-import { WorkbenchHotkeyRuntime } from './workbench/hotkeys/WorkbenchHotkeyRuntime';-import { WidgetHosts } from './workbench/widget-frame/WidgetHosts';-import { WorkbenchProvider } from './workbench/WorkbenchContext';-import { WorkbenchRuntime } from './workbench/WorkbenchRuntime';-import { WorkbenchSessionController } from './workbench/WorkbenchSessionController';--/**- * The authenticated editor: providers, editor-only runtimes, and the shell.- * The shared backend socket is mounted above this route; `WorkbenchRuntime`- * attaches the generation queue listeners while the editor is open.- *- * The route's search params shape the boot: ?project deep-links a library- * project into the session, ?new starts a fresh draft. Both are consumed by- * the persistence load; the session controller handles params that change- * while the editor is already mounted.- */-export const WorkbenchApp = () => {- const search = useSearch({ strict: false }) as WorkbenchSearch;- const loadOptions = useMemo(- () => ({ createNew: search.new, openProjectId: search.project }),- [search.new, search.project]- );-- return (- <WorkbenchProvider loadOptions={loadOptions}>- <SessionExpiryGuard />- <WorkbenchHotkeyRuntime />- <WorkbenchRuntime />- <WorkbenchSessionController search={search} />- <WidgetHosts />- <WorkbenchShell />- </WorkbenchProvider>- );-};diff --git a/invokeai/frontend/webv2/src/app/App.tsx b/invokeai/frontend/webv2/src/app/App.tsxnew file mode 100644index 0000000000..d820540b4b--- /dev/null+++ b/invokeai/frontend/webv2/src/app/App.tsx@@ -0,0 +1,20 @@+import { AppProviders } from '@app/AppProviders';+import { ChakraProvider } from '@chakra-ui/react';+import { AppToaster } from '@platform/ui/toaster';+import { RouterProvider } from '@tanstack/react-router';+import { system } from '@theme/system';++import { I18nController } from './I18nController';+import { router } from './router';+import { ThemeController } from './ThemeController';++export const App = () => (+ <AppProviders>+ <ChakraProvider value={system}>+ <ThemeController />+ <I18nController />+ <AppToaster />+ <RouterProvider router={router} />+ </ChakraProvider>+ </AppProviders>+);diff --git a/invokeai/frontend/webv2/src/app/AppProviders.tsx b/invokeai/frontend/webv2/src/app/AppProviders.tsxnew file mode 100644index 0000000000..009c70fca7--- /dev/null+++ b/invokeai/frontend/webv2/src/app/AppProviders.tsx@@ -0,0 +1,9 @@+import type { ReactNode } from 'react';++import { queryClient } from '@platform/query/client';+import { QueryClientProvider } from '@tanstack/react-query';++/** Application-wide infrastructure providers shared by every route. */+export const AppProviders = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+);diff --git a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsxnew file mode 100644index 0000000000..085f30e884--- /dev/null+++ b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx@@ -0,0 +1,22 @@+import type { GalleryImageActionsOptions, GalleryImageContextMenuProps } from '@features/gallery/react';+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) => (+ <ImageContextMenu {...props} actions={actions as ImageActions} />+);++export const GalleryImageActionsAdapter = ({+ boards,+ children,+ generateValues,+ onImagesDeleted,+ onStarredChange,+ projectId,+}: GalleryImageActionsOptions & { children: ReactNode }) => {+ const actions = useImageActions({ boards, generateValues, onImagesDeleted, onStarredChange, projectId });++ return <GalleryImageActionsProvider actions={actions}>{children}</GalleryImageActionsProvider>;+};diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsxnew file mode 100644index 0000000000..bbcd26719b--- /dev/null+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx@@ -0,0 +1,65 @@+import type { GalleryUiAdapter } from '@features/gallery/react';+import type { ReactNode } from 'react';++import { GalleryUiProvider } from '@features/gallery/react';+import { getProjectWidgetValues } from '@workbench/widgetState';+import {+ useActiveProjectId,+ useActiveProjectName,+ useActiveProjectSelector,+ useWidgetValuesSelector,+ useWorkbenchCommands,+} from '@workbench/WorkbenchContext';+import { lazy, useMemo } from 'react';++const selectWidgetValues = (values: Record<string, unknown>): Record<string, unknown> => values;++const GalleryImageActionsAdapter = lazy(() =>+ import('./GalleryImageActionsBridge').then((module) => ({ default: module.GalleryImageActionsAdapter }))+);+const GalleryImageContextMenu = lazy(() =>+ import('./GalleryImageActionsBridge').then((module) => ({ default: module.GalleryImageContextMenu }))+);++/** App-owned translation between Gallery UI intents and the Workbench aggregate. */+export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode }) => {+ const projectId = useActiveProjectId();+ const projectName = useActiveProjectName();+ const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));+ const generateValues = useWidgetValuesSelector('generate', selectWidgetValues);+ const queueItems = useActiveProjectSelector((project) => project.queue.items);+ const antialiasProgressImages = useActiveProjectSelector((project) => project.settings.antialiasProgressImages);+ const { account, gallery, notifications, widgets } = useWorkbenchCommands();+ const adapter = useMemo<GalleryUiAdapter>(+ () => ({+ account: {+ showProgressImages: () => account.updateProjectPreferences({ showProgressImagesInViewer: true }),+ },+ antialiasProgressImages,+ gallery,+ galleryValues,+ generateValues,+ ImageActionsProvider: GalleryImageActionsAdapter,+ ImageContextMenu: GalleryImageContextMenu,+ notifications,+ projectId,+ projectName,+ queueItems,+ widgets: { patchGalleryValues: (values) => widgets.patchValues('gallery', values) },+ }),+ [+ account,+ antialiasProgressImages,+ gallery,+ galleryValues,+ generateValues,+ notifications,+ projectId,+ projectName,+ queueItems,+ widgets,+ ]+ );++ return <GalleryUiProvider adapter={adapter}>{children}</GalleryUiProvider>;+};diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsxnew file mode 100644index 0000000000..b58297d86f--- /dev/null+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx@@ -0,0 +1,67 @@+import type { GenerationUiAdapter } from '@features/generation/react';+import type { ReactNode } from 'react';++import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';+import { GenerationUiProvider } from '@features/generation/react';+import { ensureModelsLoaded, getModelBaseColorPalette, getModelBaseLabel, useModelsSelector } from '@features/models';+import { useNotify } from '@workbench/useNotify';+import { getProjectWidgetValues } from '@workbench/widgetState';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { lazy, useMemo } from 'react';++const ModelSelect = lazy(() => import('@features/models/react').then((module) => ({ default: module.ModelSelect })));+const GenerateCanvasCompositingSection = lazy(() =>+ import('@workbench/widgets/canvas/GenerateCanvasCompositingSection').then((module) => ({+ default: module.GenerateCanvasCompositingSection,+ }))+);++export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode }) => {+ const project = useActiveProjectSelector((activeProject) => ({+ activeProjectId: activeProject.id,+ canvasValues: getProjectWidgetValues(activeProject, 'canvas'),+ generateValues: getProjectWidgetValues(activeProject, 'generate'),+ invocationSourceId: activeProject.invocation.sourceId,+ promptHistory: activeProject.promptHistory,+ selectedGalleryImage: getSelectedGalleryImageFromValues(getProjectWidgetValues(activeProject, 'gallery')),+ showPromptSyntaxHighlighting: activeProject.settings.showPromptSyntaxHighlighting,+ }));+ const models = useModelsSelector((snapshot) => snapshot.models);+ const modelsError = useModelsSelector((snapshot) => snapshot.error);+ const modelsStatus = useModelsSelector((snapshot) => snapshot.status);+ const { gallery, generation, notifications, widgets } = useWorkbenchCommands();+ const notify = useNotify();+ const adapter = useMemo<GenerationUiAdapter>(+ () => ({+ ...project,+ CanvasCompositingSection: GenerateCanvasCompositingSection,+ ModelSelect,+ clearPromptHistory: () => generation.clearPromptHistory(),+ ensureModelsLoaded,+ getModelBaseColorPalette,+ getModelBaseLabel,+ models,+ modelsError,+ modelsStatus,+ notifications: { error: notify.error, info: notify.info, reportError: notifications.reportError },+ patchCanvasValues: (values) => widgets.patchValues('canvas', values),+ patchGenerateSettings: generation.patchSettings,+ removePromptFromHistory: generation.removePromptFromHistory,+ touchGalleryImages: () => gallery.touchImages(),+ }),+ [+ gallery,+ generation,+ models,+ modelsError,+ modelsStatus,+ notifications.reportError,+ notify.error,+ notify.info,+ project,+ widgets,+ ]+ );++ return <GenerationUiProvider adapter={adapter}>{children}</GenerationUiProvider>;+};diff --git a/invokeai/frontend/webv2/src/workbench/i18n/I18nController.tsx b/invokeai/frontend/webv2/src/app/I18nController.tsxsimilarity index 89%rename from invokeai/frontend/webv2/src/workbench/i18n/I18nController.tsxrename to invokeai/frontend/webv2/src/app/I18nController.tsxindex e6fca0ff90..e3df77c599 100644--- a/invokeai/frontend/webv2/src/workbench/i18n/I18nController.tsx+++ b/invokeai/frontend/webv2/src/app/I18nController.tsx@@ -1,10 +1,8 @@+import i18n from '@platform/i18n/client';+import { getWorkbenchLanguageDirection } from '@platform/i18n/languages';import { useWorkbenchPreferenceSelector, useWorkbenchSettingsSelector } from '@workbench/settings/store';import { useLayoutEffect } from 'react';-import i18n from '@/i18n';--import { getWorkbenchLanguageDirection } from './languages';-const LANGUAGE_HINT_STORAGE_KEY = 'invokeai:v7:webv2:language';export const I18nController = () => {diff --git a/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsx b/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsxnew file mode 100644index 0000000000..ee1756b0f0--- /dev/null+++ b/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsx@@ -0,0 +1,18 @@+import type { ModelsUiAdapter } from '@features/models';+import type { ReactNode } from 'react';++import { ModelsUiProvider } from '@features/models';+import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';+import { useActiveProjectId } from '@workbench/WorkbenchContext';+import { useMemo } from 'react';++export const ModelsUiAdapterProvider = ({ children }: { children: ReactNode }) => {+ const enableModelDescriptions = useWorkbenchPreferenceSelector((value) => value.enableModelDescriptions);+ const managerProjectId = useActiveProjectId();+ const adapter = useMemo<ModelsUiAdapter>(+ () => ({ enableModelDescriptions, managerProjectId }),+ [enableModelDescriptions, managerProjectId]+ );++ return <ModelsUiProvider adapter={adapter}>{children}</ModelsUiProvider>;+};diff --git a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsxnew file mode 100644index 0000000000..e934e2c2fa--- /dev/null+++ b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx@@ -0,0 +1,44 @@+import { nodeExecutionStore } from '@features/nodes';+import { createProductionQueueRuntime } from '@features/queue';+import { ensureInvocationTemplatesLoaded } from '@features/workflow/react';+import { useMountEffect } from '@platform/react/useMountEffect';+import { useWorkbenchCommands, useWorkbenchQueries, useWorkbenchSubscription } from '@workbench/WorkbenchContext';++/** App-owned production composition of Queue, Workbench, Gallery, and Workflow adapters. */+export const QueueRuntimeAdapter = () => {+ const { notifications, queue } = useWorkbenchCommands();+ const queries = useWorkbenchQueries();+ const subscribe = useWorkbenchSubscription();++ useMountEffect(() => {+ const runtime = createProductionQueueRuntime({+ destinations: {+ addImagesToGalleryBoard: async (boardId, imageNames) => {+ const { galleryOrganization } = await import('@features/gallery');++ await galleryOrganization.addToBoard(boardId, imageNames);+ },+ },+ ensureTemplatesLoaded: ensureInvocationTemplatesLoaded,+ history: {+ commands: { ...queue, recordError: notifications.reportError },+ getSnapshot: () => {+ const snapshot = queries.getSnapshot();++ return {+ connectionStatus: snapshot.backendConnection.status,+ isHydrated: snapshot.hasHydrated,+ projects: snapshot.projects,+ };+ },+ subscribe,+ },+ nodeExecution: nodeExecutionStore,+ });++ runtime.start();+ return () => runtime.dispose();+ });++ return null;+};diff --git a/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsxnew file mode 100644index 0000000000..e5fc6eb0cf--- /dev/null+++ b/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx@@ -0,0 +1,35 @@+import { useCapabilities } from '@features/identity';+import { QueueUiProvider, type QueueUiAdapter } from '@features/queue/react';+import { useWorkbenchPreferences } from '@workbench/settings/store';+import { useNotify } from '@workbench/useNotify';+import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';+import { useActiveProjectSelector, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { lazy, useMemo, type ReactNode } from 'react';++const QueueItemActions = lazy(() =>+ import('@workbench/queue-integration/QueueItemActions').then((module) => ({ default: module.QueueItemActions }))+);++/** App-owned adapter for Queue UI concerns that belong to Workbench. */+export const QueueUiAdapterProvider = ({ children }: { children: ReactNode }) => {+ const notify = useNotify();+ const activeProjectId = useActiveProjectSelector((project) => project.id);+ const { canManageModels } = useCapabilities();+ const { queueJobsScope } = useWorkbenchPreferences();+ const openWorkbenchWidget = useOpenWorkbenchWidget();+ const isConnected = useWorkbenchSelector((snapshot) => snapshot.backendConnection.status === 'connected');+ const adapter = useMemo<QueueUiAdapter>(+ () => ({+ activeProjectId,+ ItemActions: QueueItemActions,+ canManageProcessor: canManageModels,+ isConnected,+ notify,+ openQueue: () => openWorkbenchWidget('queue'),+ queueJobsScope,+ }),+ [activeProjectId, canManageModels, isConnected, notify, openWorkbenchWidget, queueJobsScope]+ );++ return <QueueUiProvider adapter={adapter}>{children}</QueueUiProvider>;+};diff --git a/invokeai/frontend/webv2/src/workbench/backend/SocketHubRuntime.tsx b/invokeai/frontend/webv2/src/app/SocketHubRuntime.tsxsimilarity index 67%rename from invokeai/frontend/webv2/src/workbench/backend/SocketHubRuntime.tsxrename to invokeai/frontend/webv2/src/app/SocketHubRuntime.tsxindex 9c8a4b9c91..6a1f402a85 100644--- a/invokeai/frontend/webv2/src/workbench/backend/SocketHubRuntime.tsx+++ b/invokeai/frontend/webv2/src/app/SocketHubRuntime.tsx@@ -1,6 +1,5 @@-import { useEffect } from 'react';--import { socketHub } from './socketHub';+import { useMountEffect } from '@platform/react/useMountEffect';+import { socketHub } from '@platform/transport/socketHub';/*** Renders nothing. Mounted once above both the Launchpad and the editor: opens@@ -9,12 +8,12 @@ import { socketHub } from './socketHub';** It intentionally does NOT disconnect on unmount — that keeps it StrictMode* safe and lets the socket persist across Launchpad↔editor navigation. The- * socket is torn down explicitly on logout/expiry (see `auth/session.ts`).+ * socket is torn down explicitly on logout/expiry (see `features/identity/session.ts`).*/export const SocketHubRuntime = () => {- useEffect(() => {+ useMountEffect(() => {socketHub.connect();- }, []);+ });return null;};diff --git a/invokeai/frontend/webv2/src/workbench/ThemeController.tsx b/invokeai/frontend/webv2/src/app/ThemeController.tsxsimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/ThemeController.tsxrename to invokeai/frontend/webv2/src/app/ThemeController.tsxindex 64124ffe83..8568094540 100644--- a/invokeai/frontend/webv2/src/workbench/ThemeController.tsx+++ b/invokeai/frontend/webv2/src/app/ThemeController.tsx@@ -1,9 +1,8 @@+import { shallowEqual } from '@platform/state/selectors';import { DEFAULT_THEME, THEMES_BY_ID } from '@theme/system';+import { useWorkbenchSettingsSelector } from '@workbench/settings/store';import { useLayoutEffect } from 'react';-import { useWorkbenchSettingsSelector } from './settings/store';-import { shallowEqual } from './WorkbenchContext';-/*** Applies the persisted appearance preferences to the document root.*diff --git a/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsxnew file mode 100644index 0000000000..f802f358b4--- /dev/null+++ b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx@@ -0,0 +1,42 @@+import type { UpscaleUiAdapter } from '@features/upscale';+import type { ReactNode } from 'react';++import { areProjectPromptDraftsEqual, getPromptDraftFromValues } from '@features/generation/utility';+import { UpscaleUiProvider } from '@features/upscale';+import { getProjectWidgetValues } from '@workbench/widgetState';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { useMemo } from 'react';++export const UpscaleUiAdapterProvider = ({ children }: { children: ReactNode }) => {+ const project = useActiveProjectSelector(+ (activeProject) => {+ const instance = Object.values(activeProject.widgetInstances).find((candidate) => candidate.typeId === 'upscale');++ return {+ projectId: activeProject.id,+ promptDraft: getPromptDraftFromValues(getProjectWidgetValues(activeProject, 'generate')),+ rawValues: instance?.state.values ?? {},+ showPromptSyntaxHighlighting: activeProject.settings.showPromptSyntaxHighlighting,+ };+ },+ (left, right) =>+ left.projectId === right.projectId &&+ areProjectPromptDraftsEqual(left.promptDraft, right.promptDraft) &&+ left.rawValues === right.rawValues &&+ left.showPromptSyntaxHighlighting === right.showPromptSyntaxHighlighting+ );+ const commands = useWorkbenchCommands();+ const adapter = useMemo<UpscaleUiAdapter>(+ () => ({+ ...project,+ patchPromptDraft: (values) => commands.generation.patchPromptDraft(values, project.projectId),+ patchValues: (values) => commands.widgets.patchValues('upscale', values, project.projectId),+ reportError: (message) =>+ commands.notifications.reportError({ area: 'upscale', message, namespace: 'generation' }),+ touchGalleryImages: () => commands.gallery.touchImages(),+ }),+ [commands, project]+ );++ return <UpscaleUiProvider adapter={adapter}>{children}</UpscaleUiProvider>;+};diff --git a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsxnew file mode 100644index 0000000000..d3749890ca--- /dev/null+++ b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx@@ -0,0 +1,65 @@+import type { WorkbenchSearch } from '@workbench/projects/session';++import { SessionExpiryGuard } from '@features/identity';+import { useSearch } from '@tanstack/react-router';+import { WorkbenchHotkeyRuntime } from '@workbench/hotkeys/WorkbenchHotkeyRuntime';+import { WorkbenchShell } from '@workbench/shell';+import { WidgetHosts } from '@workbench/widget-frame/WidgetHosts';+import { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';+import { WorkbenchProvider } from '@workbench/WorkbenchContext';+import { WorkbenchRuntime } from '@workbench/WorkbenchRuntime';+import { WorkbenchSessionController } from '@workbench/WorkbenchSessionController';+import { WorkbenchWidgetRegistryProvider } from '@workbench/WorkbenchWidgetRegistryContext';+import { useMemo } from 'react';++import { GalleryUiAdapterProvider } from './GalleryUiAdapter';+import { GenerationUiAdapterProvider } from './GenerationUiAdapter';+import { ModelsUiAdapterProvider } from './ModelsUiAdapter';+import { QueueRuntimeAdapter } from './QueueRuntimeAdapter';+import { QueueUiAdapterProvider } from './QueueUiAdapter';+import { UpscaleUiAdapterProvider } from './UpscaleUiAdapter';+import { WorkflowUiAdapterProvider } from './WorkflowUiAdapter';++/**+ * The authenticated editor: providers, editor-only runtimes, and the shell.+ * The shared backend socket is mounted above this route; `WorkbenchRuntime`+ * attaches the generation queue listeners while the editor is open.+ *+ * The route's search params shape the boot: ?project deep-links a library+ * project into the session, ?new starts a fresh draft. Both are consumed by+ * the persistence load; the session controller handles params that change+ * while the editor is already mounted.+ */+export const WorkbenchApp = () => {+ const search = useSearch({ strict: false }) as WorkbenchSearch;+ const loadOptions = useMemo(+ () => ({ createNew: search.new, openProjectId: search.project }),+ [search.new, search.project]+ );++ return (+ <WorkbenchProvider loadOptions={loadOptions}>+ <WorkbenchWidgetRegistryProvider getWidgetById={getWidgetById} getWidgetsForRegion={getWidgetsForRegion}>+ <ModelsUiAdapterProvider>+ <QueueUiAdapterProvider>+ <GalleryUiAdapterProvider>+ <GenerationUiAdapterProvider>+ <UpscaleUiAdapterProvider>+ <WorkflowUiAdapterProvider>+ <SessionExpiryGuard />+ <WorkbenchHotkeyRuntime />+ <QueueRuntimeAdapter />+ <WorkbenchRuntime />+ <WorkbenchSessionController search={search} />+ <WidgetHosts />+ <WorkbenchShell />+ </WorkflowUiAdapterProvider>+ </UpscaleUiAdapterProvider>+ </GenerationUiAdapterProvider>+ </GalleryUiAdapterProvider>+ </QueueUiAdapterProvider>+ </ModelsUiAdapterProvider>+ </WorkbenchWidgetRegistryProvider>+ </WorkbenchProvider>+ );+};diff --git a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsxnew file mode 100644index 0000000000..977ff3b812--- /dev/null+++ b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx@@ -0,0 +1,147 @@+import type { WorkflowModelSelectProps, WorkflowUiAdapter } from '@features/workflow/react';+import type { DiagnosticSource } from '@workbench/diagnostics/logger';+import type { InvocationSourceId } from '@workbench/invocationContracts';+import type { ComponentType, ReactNode } from 'react';++import { flushGenerateDrafts } from '@features/generation/drafts';+import { useAuthSession } 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 { useMountEffect } from '@platform/react/useMountEffect';+import { resolveAndSubmitGraphPreviewInvocation } from '@workbench/graphPreviewInvocation';+import { registerHotkeyModalLayer } from '@workbench/hotkeys';+import {+ createInvocationRouteInputSelector,+ formatRoute,+ isInvocationRouteValid,+ resolveInvocationRouteInput,+} from '@workbench/invocation';+import { markWorkbenchPerf, measureWorkbenchPerf, timeWorkbenchPerf } from '@workbench/performanceMarks';+import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';+import { useNotify } from '@workbench/useNotify';+import { getProjectWidgetValues } from '@workbench/widgetState';+import {+ shallowEqual,+ useActiveProjectSelector,+ useWorkbenchCommands,+ useWorkbenchQueries,+} from '@workbench/WorkbenchContext';+import { lazy, useMemo } from 'react';++const ModelSelect = lazy(() => import('@features/models/react').then((module) => ({ default: module.ModelSelect })));+const WorkflowModelSelect = ModelSelect as ComponentType<WorkflowModelSelectProps>;+const selectInvocationRouteInput = createInvocationRouteInputSelector();++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 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 notify = useNotify();++ useMountEffect(() => {+ ensureModelsLoaded();+ });++ const adapter = useMemo<WorkflowUiAdapter>(+ () => ({+ ...project,+ ModelSelect: WorkflowModelSelect,+ canUseCache: !session.multiuserEnabled || session.user?.is_admin === true,+ commands: {+ bindLibraryWorkflow: commands.workflows.bindLibraryWorkflow,+ editGraph: commands.workflows.editGraph,+ redo: commands.workflows.redo,+ replace: commands.workflows.replace,+ restoreSnapshot: commands.workflows.restoreSnapshot,+ saveSnapshot: commands.workflows.saveSnapshot,+ undo: commands.workflows.undo,+ },+ getProjectGraph: () => queries.getSnapshot().activeProject.projectGraph,+ graphPreview: {+ getRoute: (sourceId) => {+ if (!sourceId) {+ return null;+ }++ const route = resolveInvocationRouteInput(+ routeInput,+ 'dialog',+ { ...routeInput.invocation, sourceId: sourceId as InvocationSourceId, 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: sourceId as InvocationSourceId | undefined,+ });+ },+ },+ notifications: { error: notify.error, info: notify.info, success: notify.success },+ performance: {+ mark: (name, source) => markWorkbenchPerf(name, source as DiagnosticSource),+ measure: (name, start, source, end) => measureWorkbenchPerf(name, start, source as DiagnosticSource, end),+ time: (name, source, callback) => timeWorkbenchPerf(name, source as DiagnosticSource, callback),+ },+ preferences,+ registerModalHotkeyLayer: registerHotkeyModalLayer,+ nodeExecution: { get: nodeExecutionStore.get, subscribe: nodeExecutionStore.subscribe },+ widgets: {+ open: (options) => commands.widgets.open(options as Parameters<typeof commands.widgets.open>[0]),+ patchValues: (widgetId, values) =>+ commands.widgets.patchValues(widgetId as Parameters<typeof commands.widgets.patchValues>[0], values),+ select: (options) => commands.widgets.select(options as Parameters<typeof commands.widgets.select>[0]),+ },+ }),+ [+ availabilityModels,+ commands,+ notify.error,+ notify.info,+ notify.success,+ preferences,+ project,+ queries,+ routeInput,+ session,+ ]+ );++ return <WorkflowUiProvider adapter={adapter}>{children}</WorkflowUiProvider>;+};diff --git a/invokeai/frontend/webv2/src/app/configureDependencies.ts b/invokeai/frontend/webv2/src/app/configureDependencies.tsnew file mode 100644index 0000000000..6c7e781c5e--- /dev/null+++ b/invokeai/frontend/webv2/src/app/configureDependencies.ts@@ -0,0 +1,7 @@+import { identityTransportAuthAdapter } from '@features/identity';+import { configureHttpAuth } from '@platform/transport/http';++/** The App is the sole production adapter-selection and dependency-construction root. */+export const configureDependencies = (): void => {+ configureHttpAuth(identityTransportAuthAdapter);+};diff --git a/invokeai/frontend/webv2/src/main.tsx b/invokeai/frontend/webv2/src/app/main.tsxsimilarity index 75%rename from invokeai/frontend/webv2/src/main.tsxrename to invokeai/frontend/webv2/src/app/main.tsxindex 6c81cc73d1..9236ee4611 100644--- a/invokeai/frontend/webv2/src/main.tsx+++ b/invokeai/frontend/webv2/src/app/main.tsx@@ -1,9 +1,12 @@import '@fontsource/inter/index.css';-import './i18n';+import '@platform/i18n/client';import { StrictMode } from 'react';import { createRoot } from 'react-dom/client';import { App } from './App';+import { configureDependencies } from './configureDependencies';++configureDependencies();const rootElement = document.getElementById('root');diff --git a/invokeai/frontend/webv2/src/router.tsx b/invokeai/frontend/webv2/src/app/router.tsxsimilarity index 89%rename from invokeai/frontend/webv2/src/router.tsxrename to invokeai/frontend/webv2/src/app/router.tsxindex b9573a9ee0..fe1937d8bc 100644--- a/invokeai/frontend/webv2/src/router.tsx+++ b/invokeai/frontend/webv2/src/app/router.tsx@@ -1,3 +1,4 @@+import { ensureAuthSession, getCapabilities, LoginScreen, SetupScreen, type Capabilities } from '@features/identity';import {createHashHistory,createRootRoute,@@ -8,16 +9,12 @@ import {Outlet,redirect,} from '@tanstack/react-router';+import { WorkbenchSplashScreen } from '@workbench/components/WorkbenchSplashScreen';+import { Launchpad } from '@workbench/launchpad/Launchpad';+import { peekOpenProjectIds, type WorkbenchSearch } from '@workbench/projects/session';+import { loadWorkbenchSettings } from '@workbench/settings/store';-import { getCapabilities, type Capabilities } from './workbench/auth/capabilities';-import { LoginScreen } from './workbench/auth/components/LoginScreen';-import { SetupScreen } from './workbench/auth/components/SetupScreen';-import { ensureAuthSession } from './workbench/auth/session';-import { SocketHubRuntime } from './workbench/backend/SocketHubRuntime';-import { WorkbenchSplashScreen } from './workbench/components/WorkbenchSplashScreen';-import { Launchpad } from './workbench/launchpad/Launchpad';-import { peekOpenProjectIds, type WorkbenchSearch } from './workbench/projects/session';-import { loadWorkbenchSettings } from './workbench/settings/store';+import { SocketHubRuntime } from './SocketHubRuntime';/*** Code-based route tree. The authenticated layout route owns the auth guard,diff --git a/invokeai/frontend/webv2/src/appMetadata.ts b/invokeai/frontend/webv2/src/appMetadata.tsdeleted file mode 100644index c3e51ede92..0000000000--- a/invokeai/frontend/webv2/src/appMetadata.ts+++ /dev/null@@ -1 +0,0 @@-export const APP_VERSION = '7.0';diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.tsnew file mode 100644index 0000000000..fdd99aa26a--- /dev/null+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts@@ -0,0 +1,192 @@+import { describe, expect, it } from 'vitest';++import {+ checkDependency,+ checkSource,+ collectImportReferences,+ formatViolation,+ getModuleOwner,+ isExcepted,+ resolveImportPath,+} from './dependencyPolicy';+import { FEATURE_PUBLIC_INTERFACES } from './featureInterfaces';+import { migrationExceptions } from './migrationExceptions';++const sources = import.meta.glob('../**/*.{ts,tsx}', {+ eager: true,+ import: 'default',+ query: '?raw',+}) as Record<string, string>;++const toSourcePath = (path: string): string => path.replace(/^\.\.\//, '');+const isProduction = (path: string): boolean => !/\.(?:test|browser\.test)\.[^.]+$/.test(path);++describe('dependency policy parser', () => {+ it('classifies every supported TypeScript import form', () => {+ const references = collectImportReferences(`+ import value from '@platform/value';+ import type { Type } from '@platform/type';+ export { named } from '@platform/named';+ export type { NamedType } from '@platform/named-type';+ export * from '@platform/star';+ export * as ns from '@platform/namespace';+ type Inline = import('@platform/inline').Inline;+ const lazy = import('@features/gallery');+ `);++ expect(references).toEqual([+ { exposesCanvasEngine: false, kind: 'import', specifier: '@platform/value' },+ { exposesCanvasEngine: false, kind: 'import', specifier: '@platform/type' },+ { exposesCanvasEngine: false, kind: 'export', specifier: '@platform/named' },+ { exposesCanvasEngine: false, kind: 'export', specifier: '@platform/named-type' },+ { exposesCanvasEngine: true, kind: 'export-star', specifier: '@platform/star' },+ { exposesCanvasEngine: true, kind: 'export-star', specifier: '@platform/namespace' },+ { exposesCanvasEngine: false, kind: 'import-type', specifier: '@platform/inline' },+ { exposesCanvasEngine: false, kind: 'dynamic-import', specifier: '@features/gallery' },+ ]);+ });++ it('normalizes aliases and relative paths before assigning owners', () => {+ expect(resolveImportPath('features/queue/ui/View.tsx', '../../gallery')).toBe('features/gallery');+ expect(resolveImportPath('features/queue/ui/View.tsx', '@workbench/canvas-engine/api')).toBe(+ 'workbench/canvas-engine/api'+ );+ expect(getModuleOwner('features/queue/index.ts')).toBe('feature:queue');+ expect(getModuleOwner('platform/query/client.ts')).toBe('platform');+ });+});++describe('dependency policy rules', () => {+ it('rejects Queue-to-Workbench dependencies with an actionable message', () => {+ const violations = checkDependency('features/queue/runtime.ts', '@workbench/workbenchStore');++ expect(violations.map(formatViolation)).toEqual([+ 'feature-dependency-direction: features/queue/runtime.ts -> workbench/workbenchStore',+ ]);+ });++ it('rejects cross-feature implementation bypasses but permits public interfaces', () => {+ expect(checkDependency('features/queue/ui/View.tsx', '@features/gallery/data/api')).toMatchObject([+ { rule: 'feature-public-interface' },+ ]);+ expect(checkDependency('features/queue/ui/View.tsx', '@features/gallery')).toEqual([]);+ });++ it('rejects private Canvas paths outside Canvas and permits its public API', () => {+ expect(checkDependency('workbench/widgets/canvas/View.tsx', '@workbench/canvas-engine/engine')).toMatchObject([+ { rule: 'canvas-private-interface' },+ ]);+ expect(checkDependency('workbench/widgets/canvas/View.tsx', '@workbench/canvas-engine/api')).toEqual([]);+ expect(checkDependency('workbench/widgets/canvas/View.tsx', '@workbench/canvas-operations/api')).toEqual([]);+ expect(checkDependency('workbench/widgets/canvas/View.tsx', '@workbench/canvas-operations/react')).toEqual([]);+ });++ it.each([+ `export type { CanvasEngine } from '@workbench/canvas-engine/engine';`,+ `export { CanvasEngine as PublicEngine } from '@workbench/canvas-engine/engine';`,+ `export * from '@workbench/canvas-engine/engine';`,+ `export * as Core from '@workbench/canvas-engine/engine';`,+ `import type * as Core from '@workbench/canvas-engine/engine'; type Consumer = Core.CanvasEngine;`,+ `type Consumer = import('@workbench/canvas-operations/createCanvasEngine').CanvasEngine;`,+ ])('keeps the full Canvas engine private: %s', (source) => {+ expect(checkSource('workbench/widgets/canvas/consumer.ts', source)).toContainEqual(+ expect.objectContaining({ rule: 'canvas-construction-private' })+ );+ });++ it('keeps Canvas engine implementation independent of application workflows', () => {+ expect(checkDependency('workbench/canvas-engine/engine.ts', '@features/generation/graph')).toContainEqual(+ expect.objectContaining({ rule: 'canvas-engine-independence' })+ );+ });++ it('permits same-module implementation imports', () => {+ expect(checkDependency('features/queue/ui/View.tsx', '../data/queries')).toEqual([]);+ expect(checkDependency('workbench/canvas-engine/controllers/a.ts', '../engine')).toEqual([]);+ });++ it('rejects the retired global Workbench contract hub', () => {+ expect(checkDependency('workbench/shell/View.tsx', '@workbench/types')).toContainEqual(+ expect.objectContaining({ rule: 'retired-contract-hub' })+ );+ });++ it('rejects private feature paths and broad star exports across ownership seams', () => {+ expect(checkDependency('workbench/backend/coordinator.ts', '@features/queue/core/types')).toContainEqual(+ expect.objectContaining({ rule: 'feature-private-interface' })+ );+ expect(checkDependency('workbench/projectContracts.ts', '@features/queue/contracts')).toEqual([]);+ expect(checkDependency('workbench/backend/coordinator.ts', '@features/queue')).toEqual([]);+ expect(checkSource('workbench/queue.ts', `export * from '@features/queue';`)).toContainEqual(+ expect.objectContaining({ rule: 'cross-owner-star-export' })+ );+ expect(checkSource('platform/ui/index.ts', `export * from './Button';`)).toEqual([]);+ });++ it('keeps fixtures subject to the same parser and rules', () => {+ expect(checkSource('platform/query/client.ts', `export * from '@features/queue';`)).toEqual(+ expect.arrayContaining([expect.objectContaining({ rule: 'platform-independence' })])+ );+ expect(+ checkSource('features/queue/runtime.ts', `type Store = import('@workbench/workbenchStore').WorkbenchStore;`)+ ).toMatchObject([{ rule: 'feature-dependency-direction' }]);+ });+});++describe('feature public-interface registry', () => {+ it('rejects top-level modules a feature has not registered', () => {+ expect(checkDependency('workbench/shell/View.tsx', '@features/workflow/queries')).toMatchObject([+ { rule: 'feature-private-interface' },+ ]);+ expect(checkDependency('workbench/shell/View.tsx', '@features/identity/session')).toMatchObject([+ { rule: 'feature-private-interface' },+ ]);+ expect(checkDependency('workbench/shell/View.tsx', '@features/identity')).toEqual([]);+ expect(checkDependency('features/gallery/ui/View.tsx', '@features/queue/publicApi')).toMatchObject([+ { rule: 'feature-public-interface' },+ ]);+ });++ it('treats unregistered features as fully private', () => {+ expect(checkDependency('workbench/shell/View.tsx', '@features/imaginary')).toMatchObject([+ { rule: 'feature-private-interface' },+ ]);+ expect(checkDependency('workbench/shell/View.tsx', '@features/imaginary/contracts')).toMatchObject([+ { rule: 'feature-private-interface' },+ ]);+ });++ it('registers only real features and existing entry modules', () => {+ const productionPaths = new Set(Object.keys(sources).map(toSourcePath));+ for (const [feature, modules] of Object.entries(FEATURE_PUBLIC_INTERFACES)) {+ expect(+ [...productionPaths].some((path) => path.startsWith(`features/${feature}/`)),+ `features/${feature} does not exist`+ ).toBe(true);+ for (const module of modules) {+ expect(+ productionPaths.has(`features/${feature}/${module}.ts`) ||+ productionPaths.has(`features/${feature}/${module}.tsx`),+ `features/${feature}/${module} does not exist`+ ).toBe(true);+ }+ }+ });+});++describe('production dependency graph', () => {+ it('classifies every production import and has no unowned violation', () => {+ const violations = Object.entries(sources)+ .filter(([path]) => isProduction(path))+ .flatMap(([path, source]) => checkSource(toSourcePath(path), source))+ .filter((violation) => !migrationExceptions.some((exception) => isExcepted(violation, exception)))+ .map(formatViolation)+ .sort();++ expect(violations).toEqual([]);+ });++ it('has no remaining migration exceptions', () => {+ expect(migrationExceptions).toEqual([]);+ });+});diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.tsnew file mode 100644index 0000000000..f0d845017a--- /dev/null+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts@@ -0,0 +1,256 @@+import ts from 'typescript';++import { FEATURE_PUBLIC_INTERFACES } from './featureInterfaces';++export type ModuleOwner = 'app' | 'platform' | 'workbench' | `feature:${string}`;++export interface ImportReference {+ exposesCanvasEngine: boolean;+ kind: 'dynamic-import' | 'export' | 'export-star' | 'import' | 'import-type';+ specifier: string;+}++export interface DependencyViolation {+ rule: string;+ source: string;+ target: string;+}++export interface MigrationException {+ /** Optional ISO date after which the exception is considered expired debt. */+ expires?: string;+ /** ISO date the exception was added. */+ introduced: string;+ owner: string;+ reason: string;+ removalTicket: string;+ rule: string;+ sourcePrefix: string;+ targetPrefix: string;+}++const ALIASES: ReadonlyArray<readonly [string, string]> = [+ ['@app', 'app'],+ ['@features', 'features'],+ ['@platform', 'platform'],+ ['@theme', 'platform/ui/theme'],+ ['@workbench', 'workbench'],+ ['@', ''],+];++const normalizePath = (path: string): string => {+ const parts: string[] = [];++ for (const part of path.replaceAll('\\', '/').split('/')) {+ if (!part || part === '.') {+ continue;+ }+ if (part === '..') {+ parts.pop();+ continue;+ }+ parts.push(part);+ }++ return parts.join('/');+};++export const collectImportReferences = (source: string, fileName = 'source.ts'): ImportReference[] => {+ const sourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const references: ImportReference[] = [];++ const pushLiteral = (kind: ImportReference['kind'], node: ts.Node | undefined, exposesCanvasEngine = false): void => {+ if (node && ts.isStringLiteralLike(node)) {+ references.push({ exposesCanvasEngine, kind, specifier: node.text });+ }+ };++ const visit = (node: ts.Node): void => {+ if (ts.isImportDeclaration(node)) {+ const bindings = node.importClause?.namedBindings;+ const exposesCanvasEngine =+ Boolean(bindings && ts.isNamespaceImport(bindings)) ||+ Boolean(+ bindings &&+ ts.isNamedImports(bindings) &&+ bindings.elements.some((element) => (element.propertyName ?? element.name).text === 'CanvasEngine')+ );+ pushLiteral('import', node.moduleSpecifier, exposesCanvasEngine);+ } else if (ts.isExportDeclaration(node)) {+ const exposesCanvasEngine =+ !node.exportClause ||+ ts.isNamespaceExport(node.exportClause) ||+ node.exportClause.elements.some((element) => (element.propertyName ?? element.name).text === 'CanvasEngine');+ pushLiteral(+ !node.exportClause || ts.isNamespaceExport(node.exportClause) ? 'export-star' : 'export',+ node.moduleSpecifier,+ exposesCanvasEngine+ );+ } else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {+ pushLiteral('import-type', node.argument.literal, node.qualifier?.getText(sourceFile).includes('CanvasEngine'));+ } else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {+ pushLiteral('dynamic-import', node.arguments[0]);+ }++ ts.forEachChild(node, visit);+ };++ visit(sourceFile);+ return references;+};++export const resolveImportPath = (sourcePath: string, specifier: string): string | null => {+ if (specifier.startsWith('.')) {+ const sourceDirectory = sourcePath.slice(0, Math.max(0, sourcePath.lastIndexOf('/')));+ return normalizePath(`${sourceDirectory}/${specifier}`);+ }++ for (const [alias, target] of ALIASES) {+ if (specifier === alias || specifier.startsWith(`${alias}/`)) {+ return normalizePath(`${target}${specifier.slice(alias.length)}`);+ }+ }++ return null;+};++export const getModuleOwner = (path: string): ModuleOwner => {+ const normalized = normalizePath(path).replace(/^src\//, '');+ const feature = /^features\/([^/]+)/.exec(normalized)?.[1];++ if (feature) {+ return `feature:${feature}`;+ }+ if (normalized.startsWith('app/')) {+ return 'app';+ }+ if (normalized.startsWith('platform/')) {+ return 'platform';+ }++ return 'workbench';+};++const FEATURE_ENTRY = /^features\/([^/]+)(?:\/([^/]+?)(?:\.[cm]?[jt]sx?)?)?$/;++const isFeaturePublicInterface = (path: string): boolean => {+ const match = FEATURE_ENTRY.exec(path);+ if (!match) {+ return false;+ }+ const surface = FEATURE_PUBLIC_INTERFACES[match[1]];+ if (surface === undefined) {+ return false;+ }+ const module = match[2];+ return module === undefined || module === 'index' || surface.includes(module);+};++const isCanvasPrivatePath = (path: string): boolean => {+ if (!path.startsWith('workbench/canvas-engine/') && !path.startsWith('workbench/canvas-operations/')) {+ return false;+ }++ return !/^workbench\/(?:canvas-engine\/api|canvas-operations\/(?:api|react))(?:\.[cm]?[jt]sx?)?$/.test(path);+};++const isCanvasOwnedPath = (path: string): boolean =>+ path.startsWith('workbench/canvas-engine/') || path.startsWith('workbench/canvas-operations/');++export const checkDependency = (source: string, specifier: string): DependencyViolation[] => {+ const target = resolveImportPath(source, specifier);++ if (!target) {+ return [];+ }++ const sourcePath = normalizePath(source).replace(/^src\//, '');+ const sourceOwner = getModuleOwner(sourcePath);+ const targetOwner = getModuleOwner(target);+ const violations: DependencyViolation[] = [];+ const add = (rule: string): void => {+ violations.push({ rule, source: sourcePath, target });+ };++ if (sourceOwner === 'platform' && (targetOwner === 'workbench' || targetOwner.startsWith('feature:'))) {+ add('platform-independence');+ }++ if (sourceOwner === 'workbench' && targetOwner === 'app') {+ add('app-composition-root');+ }++ if (sourceOwner.startsWith('feature:')) {+ if (targetOwner === 'app' || targetOwner === 'workbench') {+ add('feature-dependency-direction');+ }++ if (targetOwner.startsWith('feature:') && targetOwner !== sourceOwner && !isFeaturePublicInterface(target)) {+ add('feature-public-interface');+ }++ if (+ sourcePath.includes('/core/') &&+ (specifier === 'react' || target.includes('/ui/') || target.includes('/data/'))+ ) {+ add('feature-core-purity');+ }+ }++ if (!sourceOwner.startsWith('feature:') && targetOwner.startsWith('feature:') && !isFeaturePublicInterface(target)) {+ add('feature-private-interface');+ }++ if (!isCanvasOwnedPath(sourcePath) && isCanvasPrivatePath(target)) {+ add('canvas-private-interface');+ }++ if (target === 'workbench/types') {+ add('retired-contract-hub');+ }++ if (+ sourcePath.startsWith('workbench/canvas-engine/') &&+ [+ 'features/generation',+ 'workbench/backend',+ 'workbench/canvas-operations',+ 'workbench/generation',+ 'workbench/widgets',+ ].some((prefix) => target.startsWith(prefix))+ ) {+ add('canvas-engine-independence');+ }++ return violations;+};++export const checkSource = (sourcePath: string, source: string): DependencyViolation[] =>+ collectImportReferences(source, sourcePath).flatMap(({ exposesCanvasEngine, kind, specifier }) => {+ const violations = checkDependency(sourcePath, specifier);+ const target = resolveImportPath(sourcePath, specifier);+ const normalizedSource = normalizePath(sourcePath).replace(/^src\//, '');+ const isFullEngineModule =+ target === 'workbench/canvas-engine/engine' || target === 'workbench/canvas-operations/createCanvasEngine';+ const mayConstructCanvas =+ normalizedSource === 'workbench/canvas-operations/createCanvasEngine.ts' ||+ normalizedSource === 'workbench/canvas-operations/engineRegistry.ts';++ if (kind === 'export-star' && target && getModuleOwner(normalizedSource) !== getModuleOwner(target)) {+ violations.push({ rule: 'cross-owner-star-export', source: normalizedSource, target });+ }++ if (exposesCanvasEngine && isFullEngineModule && !mayConstructCanvas) {+ violations.push({ rule: 'canvas-construction-private', source: normalizedSource, target });+ }++ return violations;+ });++export const formatViolation = ({ rule, source, target }: DependencyViolation): string =>+ `${rule}: ${source} -> ${target}`;++export const isExcepted = (violation: DependencyViolation, exception: MigrationException): boolean =>+ violation.rule === exception.rule &&+ violation.source.startsWith(exception.sourcePrefix) &&+ violation.target.startsWith(exception.targetPrefix);diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.tsnew file mode 100644index 0000000000..cff0071ac4--- /dev/null+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts@@ -0,0 +1,33 @@+/**+ * Fail-closed public-surface registry. A feature absent from this map has NO+ * public modules; a top-level module absent from its list is private.+ * `index` is implicitly public for every registered feature.+ * To publish a new entry module, add it here and cover it in dependencyPolicy.test.ts.+ */+export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string[]>> = {+ gallery: ['contracts', 'queries', 'react', 'utility', 'widget'],+ generation: [+ 'batch',+ 'canvas',+ 'contracts',+ 'draft-values',+ 'drafts',+ 'form',+ 'graph',+ 'hotkeys',+ 'prompt',+ 'prompt-ui',+ 'react',+ 'reference-ui',+ 'settings',+ 'settings-ui',+ 'utility',+ 'widget',+ ],+ identity: [],+ models: ['react'],+ nodes: [],+ queue: ['contracts', 'menu', 'react', 'utility', 'widget'],+ upscale: ['widget'],+ workflow: ['contracts', 'graph', 'preview', 'react', 'utility', 'widget'],+};diff --git a/invokeai/frontend/webv2/src/architecture/migrationExceptions.ts b/invokeai/frontend/webv2/src/architecture/migrationExceptions.tsnew file mode 100644index 0000000000..0dc535d70a--- /dev/null+++ b/invokeai/frontend/webv2/src/architecture/migrationExceptions.ts@@ -0,0 +1,7 @@+import type { MigrationException } from './dependencyPolicy';++/**+ * Temporary, owned migration debt. The completion gate requires this list to be+ * empty; entries may only point at an open architecture-wayfinder removal ticket.+ */+export const migrationExceptions: readonly MigrationException[] = [] as const;diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnership.test.ts b/invokeai/frontend/webv2/src/architecture/workbenchOwnership.test.tsnew file mode 100644index 0000000000..fe65662a8f--- /dev/null+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnership.test.ts@@ -0,0 +1,262 @@+import ts from 'typescript';+import { describe, expect, it } from 'vitest';++import { collectImportReferences, getModuleOwner, resolveImportPath } from './dependencyPolicy';+import { getWorkbenchTargetOwner, getWorkbenchTargetPath, workbenchOwnershipManifest } from './workbenchOwnership';++const sources = import.meta.glob('../**/*.{ts,tsx}', {+ eager: true,+ import: 'default',+ query: '?raw',+}) as Record<string, string>;++const toSourcePath = (path: string): string => path.replace(/^\.\.\//, '');+const isTest = (path: string): boolean => /(?:\.test|\.browser\.test|\.type-test)\.[^.]+$/.test(path);+const isProduction = (path: string): boolean => !isTest(path);+const stripExtension = (path: string): string => path.replace(/\.[cm]?[jt]sx?$/, '');++const productionSources: Record<string, string> = Object.fromEntries(+ Object.entries(sources)+ .map(([path, source]) => [toSourcePath(path), source])+ .filter(([path]) => isProduction(path))+);++const pathByExtensionlessPath = new Map(Object.keys(productionSources).map((path) => [stripExtension(path), path]));++const resolveSourceFile = (sourcePath: string, specifier: string): string | null => {+ const resolved = resolveImportPath(sourcePath, specifier);+ if (!resolved) {+ return null;+ }+ return pathByExtensionlessPath.get(resolved) ?? pathByExtensionlessPath.get(`${resolved}/index`) ?? null;+};++const getTargetOwner = (path: string) =>+ path.startsWith('workbench/') ? getWorkbenchTargetOwner(path) : getModuleOwner(path);++const collectPublicExports = (source: string, path: string): string[] => {+ const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const exports = new Set<string>();++ for (const statement of sourceFile.statements) {+ const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined;+ if (modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {+ if (+ (ts.isClassDeclaration(statement) ||+ ts.isFunctionDeclaration(statement) ||+ ts.isInterfaceDeclaration(statement) ||+ ts.isTypeAliasDeclaration(statement) ||+ ts.isEnumDeclaration(statement)) &&+ statement.name+ ) {+ exports.add(statement.name.text);+ } else if (ts.isVariableStatement(statement)) {+ for (const declaration of statement.declarationList.declarations) {+ if (ts.isIdentifier(declaration.name)) {+ exports.add(declaration.name.text);+ }+ }+ }+ }+ if (ts.isExportAssignment(statement)) {+ exports.add('default');+ }+ if (ts.isExportDeclaration(statement)) {+ if (!statement.exportClause) {+ exports.add('*');+ } else if (ts.isNamedExports(statement.exportClause)) {+ for (const element of statement.exportClause.elements) {+ exports.add(element.name.text);+ }+ }+ }+ }++ return [...exports].sort();+};++const isTypeOnlyModule = (source: string, path: string): boolean => {+ const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ return sourceFile.statements.every((statement) => {+ if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) {+ return true;+ }+ if (ts.isImportDeclaration(statement)) {+ return Boolean(statement.importClause?.isTypeOnly);+ }+ if (ts.isExportDeclaration(statement)) {+ return statement.isTypeOnly;+ }+ return ts.isEmptyStatement(statement);+ });+};++const stronglyConnectedComponents = (graph: Map<string, Set<string>>): string[][] => {+ let nextIndex = 0;+ const stack: string[] = [];+ const onStack = new Set<string>();+ const indexes = new Map<string, number>();+ const lowLinks = new Map<string, number>();+ const components: string[][] = [];++ const visit = (node: string): void => {+ indexes.set(node, nextIndex);+ lowLinks.set(node, nextIndex);+ nextIndex += 1;+ stack.push(node);+ onStack.add(node);++ for (const target of graph.get(node) ?? []) {+ if (!indexes.has(target)) {+ visit(target);+ lowLinks.set(node, Math.min(lowLinks.get(node)!, lowLinks.get(target)!));+ } else if (onStack.has(target)) {+ lowLinks.set(node, Math.min(lowLinks.get(node)!, indexes.get(target)!));+ }+ }++ if (lowLinks.get(node) === indexes.get(node)) {+ const component: string[] = [];+ let member: string;+ do {+ member = stack.pop()!;+ onStack.delete(member);+ component.push(member);+ } while (member !== node);+ components.push(component.sort());+ }+ };++ for (const node of graph.keys()) {+ if (!indexes.has(node)) {+ visit(node);+ }+ }+ return components.filter((component) => component.length > 1).sort((a, b) => a.join().localeCompare(b.join()));+};++describe('Workbench ownership manifest', () => {+ it('classifies every production Workbench module exactly once and emits an inspectable inventory', () => {+ const workbenchSources = Object.entries(productionSources).filter(([path]) => path.startsWith('workbench/'));+ const actualRootFiles = new Set<string>();++ for (const [path] of workbenchSources) {+ const relativePath = path.slice('workbench/'.length);+ if (!relativePath.includes('/')) {+ actualRootFiles.add(relativePath);+ }+ }++ const actualDirectories = [+ ...new Set([+ ...workbenchSources+ .map(([path]) => path.slice('workbench/'.length))+ .filter((path) => path.includes('/'))+ .map((path) => path.split('/')[0]!),+ ...workbenchOwnershipManifest.emptyDirectories,+ ]),+ ].sort();+ expect(actualDirectories).toEqual(Object.keys(workbenchOwnershipManifest.directoryRules).sort());+ expect([...actualRootFiles].sort()).toEqual(Object.keys(workbenchOwnershipManifest.rootFiles).sort());+ expect(new Set(workbenchOwnershipManifest.overrides.map((rule) => rule.pathPrefix)).size).toBe(+ workbenchOwnershipManifest.overrides.length+ );++ const inbound = new Map<string, Set<string>>();+ const graph = new Map<string, Set<string>>();++ for (const [sourcePath, source] of Object.entries(productionSources)) {+ const sourceOwner = getTargetOwner(sourcePath);+ expect(sourceOwner, `Unclassified source: ${sourcePath}`).not.toBeNull();+ graph.set(sourceOwner!, graph.get(sourceOwner!) ?? new Set<string>());++ for (const reference of collectImportReferences(source, sourcePath)) {+ const targetFile = resolveSourceFile(sourcePath, reference.specifier);+ if (!targetFile) {+ continue;+ }+ const targetOwner = getTargetOwner(targetFile);+ expect(targetOwner, `Unclassified target: ${targetFile}`).not.toBeNull();++ const inboundOwners = inbound.get(targetFile) ?? new Set<string>();+ inboundOwners.add(sourceOwner!);+ inbound.set(targetFile, inboundOwners);+ graph.set(targetOwner!, graph.get(targetOwner!) ?? new Set<string>());+ if (targetOwner !== sourceOwner) {+ graph.get(sourceOwner!)!.add(targetOwner!);+ }+ }+ }++ const records = workbenchSources.map(([path, source]) => {+ const targetOwner = getWorkbenchTargetOwner(path);+ expect(targetOwner, `Unclassified: ${path}`).not.toBeNull();++ const outboundOwners = new Set<string>();+ for (const reference of collectImportReferences(source, path)) {+ const targetFile = resolveSourceFile(path, reference.specifier);+ if (!targetFile) {+ continue;+ }+ const outboundOwner = getTargetOwner(targetFile);+ if (outboundOwner) {+ outboundOwners.add(outboundOwner);+ }+ }++ const stem = stripExtension(path);+ const testCompanions = Object.keys(sources)+ .map(toSourcePath)+ .filter((candidate) => candidate.startsWith(`${stem}.`) && isTest(candidate))+ .sort();++ return {+ currentOwner: 'workbench',+ inboundOwners: [] as string[],+ moduleKind: isTypeOnlyModule(source, path) ? 'type-only' : 'runtime',+ outboundOwners: [...outboundOwners].sort(),+ path,+ publicExports: collectPublicExports(source, path),+ targetOwner,+ targetPath: getWorkbenchTargetPath(path),+ testCompanions,+ };+ });++ for (const record of records) {+ record.inboundOwners = [...(inbound.get(record.path) ?? [])].sort();+ }++ const artifact = {+ counts: {+ productionWorkbenchModules: records.length,+ runtimeModules: records.filter((record) => record.moduleKind === 'runtime').length,+ typeOnlyModules: records.filter((record) => record.moduleKind === 'type-only').length,+ },+ generatedFromManifestVersion: workbenchOwnershipManifest.version,+ modules: records.sort((a, b) => a.path.localeCompare(b.path)),+ targetDependencyGraph: Object.fromEntries(+ [...graph.entries()]+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([owner, targets]) => [owner, [...targets].sort()])+ ),+ transitionalCycles: stronglyConnectedComponents(graph),+ };+ expect(records).toHaveLength(workbenchSources.length);+ expect(records.every((record) => record.targetPath)).toBe(true);+ expect(artifact.counts.productionWorkbenchModules).toBe(workbenchSources.length);+ expect(artifact.transitionalCycles).toHaveLength(0);+ });++ it('rejects responsibility-free target names', () => {+ const paths = [+ ...Object.values(workbenchOwnershipManifest.directoryRules).map((rule) => rule.targetPath),+ ...workbenchOwnershipManifest.overrides.map((rule) => rule.targetPath),+ ];+ expect(paths.filter((path) => /(?:^|\/)(?:common|shared|utils)(?:\/|$)/.test(path))).toEqual([]);+ });++ it('applies mixed-folder exact-file overrides before directory defaults', () => {+ expect(getWorkbenchTargetOwner('workbench/components/QueueProgressIndicator.tsx')).toBe('feature:queue');+ });+});diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnership.ts b/invokeai/frontend/webv2/src/architecture/workbenchOwnership.tsnew file mode 100644index 0000000000..e7645f4c8d--- /dev/null+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnership.ts@@ -0,0 +1,88 @@+import type { ModuleOwner } from './dependencyPolicy';++import manifestJson from './workbenchOwnershipManifest.json';++interface OwnershipRule {+ targetOwner: ModuleOwner;+ targetPath: string;+}++interface OwnershipOverride extends OwnershipRule {+ pathPrefix: string;+}++interface WorkbenchOwnershipManifest {+ currentOwner: 'workbench';+ directoryRules: Record<string, OwnershipRule>;+ emptyDirectories: string[];+ overrides: OwnershipOverride[];+ rootFiles: Record<string, ModuleOwner>;+ version: number;+}++export const workbenchOwnershipManifest = manifestJson as WorkbenchOwnershipManifest;++const stripWorkbenchPrefix = (path: string): string =>+ path+ .replaceAll('\\', '/')+ .replace(/^src\//, '')+ .replace(/^workbench\//, '');++const matchesPrefix = (path: string, prefix: string): boolean =>+ path === prefix || path.startsWith(`${prefix}.`) || path.startsWith(`${prefix}/`);++export const getWorkbenchTargetOwner = (path: string): ModuleOwner | null => {+ const relativePath = stripWorkbenchPrefix(path);+ const rootOwner = workbenchOwnershipManifest.rootFiles[relativePath];++ if (rootOwner) {+ return rootOwner;+ }++ const matchingOverrides = workbenchOwnershipManifest.overrides+ .filter((rule) => matchesPrefix(relativePath, rule.pathPrefix))+ .sort((a, b) => b.pathPrefix.length - a.pathPrefix.length);++ if (+ matchingOverrides.length > 1 &&+ matchingOverrides[0]?.pathPrefix.length === matchingOverrides[1]?.pathPrefix.length+ ) {+ return null;+ }++ if (matchingOverrides[0]) {+ return matchingOverrides[0].targetOwner;+ }++ const directory = relativePath.split('/')[0];+ return directory ? (workbenchOwnershipManifest.directoryRules[directory]?.targetOwner ?? null) : null;+};++export const getWorkbenchTargetPath = (path: string): string | null => {+ const relativePath = stripWorkbenchPrefix(path);+ const rootOwner = workbenchOwnershipManifest.rootFiles[relativePath];++ if (rootOwner) {+ const stem = relativePath.replace(/\.[cm]?[jt]sx?$/, '');+ if (rootOwner === 'workbench') {+ return `workbench/${stem}`;+ }+ if (rootOwner === 'platform') {+ return `platform/state/react/${stem}`;+ }+ if (rootOwner.startsWith('feature:')) {+ return `features/${rootOwner.slice('feature:'.length)}/core/${stem}`;+ }+ }++ const matchingOverride = workbenchOwnershipManifest.overrides+ .filter((rule) => matchesPrefix(relativePath, rule.pathPrefix))+ .sort((a, b) => b.pathPrefix.length - a.pathPrefix.length)[0];++ if (matchingOverride) {+ return matchingOverride.targetPath;+ }++ const directory = relativePath.split('/')[0];+ return directory ? (workbenchOwnershipManifest.directoryRules[directory]?.targetPath ?? null) : null;+};diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.jsonnew file mode 100644index 0000000000..3e246d4d14--- /dev/null+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json@@ -0,0 +1,81 @@+{+ "version": 1,+ "currentOwner": "workbench",+ "emptyDirectories": ["i18n"],+ "directoryRules": {+ "canvas-engine": { "targetOwner": "workbench", "targetPath": "workbench/canvas-engine" },+ "canvas-operations": { "targetOwner": "workbench", "targetPath": "workbench/canvas-operations" },+ "components": { "targetOwner": "workbench", "targetPath": "workbench/components" },+ "diagnostics": { "targetOwner": "workbench", "targetPath": "workbench/diagnostics" },+ "extensions": { "targetOwner": "workbench", "targetPath": "workbench/extensions" },+ "hotkeys": { "targetOwner": "workbench", "targetPath": "workbench/hotkeys" },+ "i18n": { "targetOwner": "workbench", "targetPath": "workbench/i18n" },+ "image-actions": { "targetOwner": "workbench", "targetPath": "workbench/image-actions" },+ "launchpad": { "targetOwner": "workbench", "targetPath": "workbench/launchpad" },+ "projects": { "targetOwner": "workbench", "targetPath": "workbench/projects" },+ "queue-integration": { "targetOwner": "workbench", "targetPath": "workbench/queue-integration" },+ "settings": { "targetOwner": "workbench", "targetPath": "workbench/settings" },+ "shell": { "targetOwner": "workbench", "targetPath": "workbench/shell" },+ "widget-frame": { "targetOwner": "workbench", "targetPath": "workbench/widget-frame" },+ "widgets": { "targetOwner": "workbench", "targetPath": "workbench/widgets" }+ },+ "overrides": [+ {+ "pathPrefix": "components/QueueProgressIndicator",+ "targetOwner": "feature:queue",+ "targetPath": "features/queue/ui/QueueProgressIndicator"+ }+ ],+ "rootFiles": {+ "WorkbenchContext.tsx": "workbench",+ "WorkbenchRuntime.tsx": "workbench",+ "WorkbenchSessionController.tsx": "workbench",+ "WorkbenchWidgetRegistryContext.tsx": "workbench",+ "canvasDimsSync.ts": "workbench",+ "canvasLayerOps.ts": "workbench",+ "canvasMigration.ts": "workbench",+ "canvasProjectMutationPort.ts": "workbench",+ "canvasProjectMutations.ts": "workbench",+ "canvasStagingView.ts": "workbench",+ "controlAdapters.ts": "workbench",+ "focusRegions.tsx": "workbench",+ "galleryWidgetManifest.ts": "workbench",+ "generationWidgetManifest.ts": "workbench",+ "graphPreviewInvocation.ts": "workbench",+ "workflowWidgetManifest.ts": "workbench",+ "graphSurfaces.ts": "workbench",+ "graphContracts.ts": "workbench",+ "iconResolver.tsx": "workbench",+ "invocation.ts": "workbench",+ "invocationContracts.ts": "workbench",+ "invocationSubmit.ts": "workbench",+ "layoutPresetSnapshots.ts": "workbench",+ "layoutPresets.ts": "workbench",+ "layoutContracts.ts": "workbench",+ "panZoom.ts": "workbench",+ "performanceMarks.ts": "workbench",+ "persistence.ts": "workbench",+ "persistenceContracts.ts": "workbench",+ "persistenceRuntime.ts": "workbench",+ "projectContracts.ts": "workbench",+ "queueHistoryContracts.ts": "workbench",+ "queueWidgetManifest.ts": "workbench",+ "upscaleWidgetManifest.ts": "workbench",+ "useCanvasProjectMutationDispatch.ts": "workbench",+ "useNotify.ts": "workbench",+ "useOpenWorkbenchWidget.ts": "workbench",+ "widgetDnd.ts": "workbench",+ "widgetImplementationResource.ts": "workbench",+ "widgetContracts.ts": "workbench",+ "widgetLabels.ts": "workbench",+ "widgetPlacementCommands.ts": "workbench",+ "widgetPlacementMeta.ts": "workbench",+ "widgetRegionItems.ts": "workbench",+ "widgetRegionViewModel.ts": "workbench",+ "widgetRegistry.ts": "workbench",+ "widgetState.ts": "workbench",+ "workbenchState.testing.ts": "workbench",+ "workbenchState.ts": "workbench",+ "workbenchStore.ts": "workbench"+ }+}diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.tsnew file mode 100644index 0000000000..fd386989a3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts@@ -0,0 +1,25 @@+export type {+ GalleryBoard,+ GalleryBoardKind,+ GalleryBoardOrderBy,+ GalleryImage,+ GalleryImageMetadata,+ GalleryImagesPage,+ GalleryOrderDir,+ GalleryView,+ GeneratedImageContract,+} from './core/types';+export {+ DEFAULT_GALLERY_SETTINGS,+ getGallerySettings,+ type GalleryPaginationMode,+ type GallerySettings,+ type GalleryThumbnailFit,+} from './core/settings';+export {+ getGalleryCompareImage,+ getGalleryImagesRefreshToken,+ getGalleryRecentImagesKey,+ getGalleryRefreshToken,+} from './ui/galleryStateView';+export { getSelectedGalleryImageFromValues } from './core/selection';diff --git a/invokeai/frontend/webv2/src/features/gallery/core/imageUrls.ts b/invokeai/frontend/webv2/src/features/gallery/core/imageUrls.tsnew file mode 100644index 0000000000..dcfbbbc498--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/core/imageUrls.ts@@ -0,0 +1,7 @@+import { absolutizeApiUrl } from '@platform/transport/http';++export const getGalleryImageThumbnailUrl = (imageName: string): string =>+ absolutizeApiUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}/thumbnail`);++export const getGalleryImageFullUrl = (imageName: string): string =>+ absolutizeApiUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}/full`);diff --git a/invokeai/frontend/webv2/src/features/gallery/core/selection.ts b/invokeai/frontend/webv2/src/features/gallery/core/selection.tsnew file mode 100644index 0000000000..13249cb9fc--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/core/selection.ts@@ -0,0 +1,30 @@+import type { GalleryImage, GeneratedImageContract } from './types';++const isGeneratedImage = (value: unknown): value is GeneratedImageContract =>+ Boolean(value) && typeof value === 'object' && typeof (value as GeneratedImageContract).imageName === 'string';++const toGalleryImage = (+ image: GeneratedImageContract & Partial<GalleryImage>,+ galleryValues: Record<string, unknown>+): GalleryImage => ({+ ...image,+ boardId:+ image.boardId ?? (typeof galleryValues.selectedBoardId === 'string' ? galleryValues.selectedBoardId : 'none'),+ imageCategory: image.imageCategory ?? 'general',+ starred: image.starred ?? false,+});++export const getSelectedGalleryImageFromValues = (galleryValues: Record<string, unknown>): GalleryImage | null => {+ if (isGeneratedImage(galleryValues.selectedImage)) {+ return toGalleryImage(galleryValues.selectedImage, galleryValues);+ }++ const selectedImageName =+ typeof galleryValues.selectedImageName === 'string' ? galleryValues.selectedImageName : null;+ const recentImages = Array.isArray(galleryValues.recentImages) ? galleryValues.recentImages : [];+ const recentImage = recentImages.find(+ (image): image is GeneratedImageContract => isGeneratedImage(image) && image.imageName === selectedImageName+ );++ return recentImage ? toGalleryImage(recentImage, galleryValues) : null;+};diff --git a/invokeai/frontend/webv2/src/workbench/gallery/settings.ts b/invokeai/frontend/webv2/src/features/gallery/core/settings.tssimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/gallery/settings.tsrename to invokeai/frontend/webv2/src/features/gallery/core/settings.tsindex 71ed1a7ef1..8207f8bf02 100644--- a/invokeai/frontend/webv2/src/workbench/gallery/settings.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/settings.ts@@ -1,4 +1,4 @@-import type { GalleryBoardOrderBy, GalleryOrderDir } from './api';+import type { GalleryBoardOrderBy, GalleryOrderDir } from './types';export type GalleryThumbnailFit = 'square' | 'aspect';diff --git a/invokeai/frontend/webv2/src/features/gallery/core/types.ts b/invokeai/frontend/webv2/src/features/gallery/core/types.tsnew file mode 100644index 0000000000..f46d08f2df--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/core/types.ts@@ -0,0 +1,42 @@+export interface GeneratedImageContract {+ height: number;+ imageName: string;+ imageUrl: string;+ queuedAt: string;+ sourceQueueItemId: string;+ thumbnailUrl: string;+ width: number;+}++export type GalleryView = 'images' | 'assets';++export type GalleryOrderDir = 'ASC' | 'DESC';++export type GalleryBoardOrderBy = 'created_at' | 'board_name';++export type GalleryBoardKind = 'board' | 'uncategorized' | 'date';++export interface GalleryBoard {+ id: string;+ name: string;+ kind: GalleryBoardKind;+ imageCount: number;+ assetCount: number;+ archived: boolean;+ coverImageName?: string | null;+ coverThumbnailUrl?: string;+ ownerName?: string | null;+}++export interface GalleryImage extends GeneratedImageContract {+ boardId: string;+ imageCategory: 'general' | 'control' | 'mask' | 'user' | 'other';+ starred: boolean;+}++export type GalleryImageMetadata = Record<string, unknown>;++export interface GalleryImagesPage {+ images: GalleryImage[];+ total: number;+}diff --git a/invokeai/frontend/webv2/src/workbench/gallery/api.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.tssimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/gallery/api.test.tsrename to invokeai/frontend/webv2/src/features/gallery/data/backend.test.tsindex 4d11fcf874..499364521e 100644--- a/invokeai/frontend/webv2/src/workbench/gallery/api.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts@@ -4,7 +4,7 @@ const mocks = vi.hoisted(() => ({apiFetchJson: vi.fn(),}));-vi.mock('@workbench/backend/http', () => ({+vi.mock('@platform/transport/http', () => ({absolutizeApiUrl: (url: string) => `https://api.test${url}`,apiFetch: vi.fn(),apiFetchJson: mocks.apiFetchJson,@@ -12,7 +12,7 @@ vi.mock('@workbench/backend/http', () => ({sleep: vi.fn(),}));-import { getGalleryImageByName, imageMakeDurableChanges, imageSaveToGalleryChanges } from './api';+import { getGalleryImageByName, imageMakeDurableChanges, imageSaveToGalleryChanges } from './backend';describe('getGalleryImageByName', () => {beforeEach(() => {diff --git a/invokeai/frontend/webv2/src/workbench/gallery/api.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.tssimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/gallery/api.tsrename to invokeai/frontend/webv2/src/features/gallery/data/backend.tsindex 9db903b084..bdd32bec38 100644--- a/invokeai/frontend/webv2/src/workbench/gallery/api.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts@@ -1,14 +1,17 @@-import type { GeneratedImageContract } from '@workbench/types';--import { absolutizeApiUrl, apiFetch, apiFetchJson, apiFetchRaw, sleep } from '@workbench/backend/http';--export type GalleryView = 'images' | 'assets';--export type GalleryOrderDir = 'ASC' | 'DESC';--export type GalleryBoardOrderBy = 'created_at' | 'board_name';--export interface BackendBoardDTO {+import type {+ GalleryBoard,+ GalleryBoardOrderBy,+ GalleryImage,+ GalleryImageMetadata,+ GalleryImagesPage,+ GalleryOrderDir,+ GalleryView,+} from '@features/gallery/core/types';++import { getGalleryImageFullUrl, getGalleryImageThumbnailUrl } from '@features/gallery/core/imageUrls';+import { absolutizeApiUrl, apiFetch, apiFetchJson, apiFetchRaw, sleep } from '@platform/transport/http';++interface BackendBoardDTO {board_id: string;board_name: string;image_count: number;@@ -24,28 +27,13 @@ export interface BackendBoardDTO {* unassigned images (board_id 'none'); 'date' is a read-only virtual board* grouping images by creation date (id 'by_date:YYYY-MM-DD').*/-export type GalleryBoardKind = 'board' | 'uncategorized' | 'date';--export interface GalleryBoard {- id: string;- name: string;- kind: GalleryBoardKind;- imageCount: number;- assetCount: number;- archived: boolean;- coverImageName?: string | null;- coverThumbnailUrl?: string;- /** Owner display name when the backend exposes it (admins in multi-user mode). */- ownerName?: string | null;-}-const DATE_BOARD_ID_PREFIX = 'by_date:';export const isDateBoardId = (boardId: string): boolean => boardId.startsWith(DATE_BOARD_ID_PREFIX);const getDateFromBoardId = (boardId: string): string => boardId.slice(DATE_BOARD_ID_PREFIX.length);-export interface BackendImageDTO {+interface BackendImageDTO {image_name: string;image_url: string;thumbnail_url: string;@@ -58,14 +46,6 @@ export interface BackendImageDTO {board_id?: string | null;}-export interface GalleryImage extends GeneratedImageContract {- boardId: string;- imageCategory: BackendImageDTO['image_category'];- starred: boolean;-}--export type GalleryImageMetadata = Record<string, unknown>;-interface ListImagesResponse {items: BackendImageDTO[];limit: number;@@ -76,12 +56,10 @@ interface ListImagesResponse {const imageCategories = ['general'];const assetCategories = ['control', 'mask', 'user', 'other'];-export const getImageThumbnailUrl = (imageName: string): string =>- absolutizeApiUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}/thumbnail`);+export const getImageThumbnailUrl = getGalleryImageThumbnailUrl;/** The full-resolution image URL for an image referenced only by name (e.g. a v2 canvas layer's `CanvasImageRef`). */-export const getImageFullUrl = (imageName: string): string =>- absolutizeApiUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}/full`);+export const getImageFullUrl = getGalleryImageFullUrl;const toSearchParams = (entries: Record<string, boolean | number | string | string[] | undefined>): string => {const params = new URLSearchParams();@@ -208,11 +186,6 @@ export const listGalleryDateBoards = async (): Promise<GalleryBoard[]> => {}));};-export interface GalleryImagesPage {- images: GalleryImage[];- total: number;-}-export const getGalleryImagesByNames = async (imageNames: string[]): Promise<GalleryImage[]> => {if (imageNames.length === 0) {return [];diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.tsnew file mode 100644index 0000000000..69f91eac49--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts@@ -0,0 +1,55 @@+import { QueryClient } from '@tanstack/react-query';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const backend = vi.hoisted(() => ({+ listGalleryBoards: vi.fn(),+ listGalleryDateBoards: vi.fn(),+ listGalleryImages: vi.fn(),+}));++vi.mock('./backend', () => backend);++import { galleryBoardsOptions, galleryImagesOptions } from './queries';++describe('Gallery query read model', () => {+ beforeEach(() => {+ backend.listGalleryBoards.mockReset();+ backend.listGalleryDateBoards.mockReset();+ backend.listGalleryImages.mockReset();+ });++ it('coalesces board readers through one query key and includes requested virtual boards', async () => {+ const queryClient = new QueryClient();+ const board = { id: 'none', kind: 'uncategorized', name: 'Uncategorized' };+ const dateBoard = { id: 'by_date:2026-07-18', kind: 'date', name: 'July 18' };+ const options = galleryBoardsOptions({ includeDateBoards: true, orderDir: 'DESC' });++ backend.listGalleryBoards.mockResolvedValue([board]);+ backend.listGalleryDateBoards.mockResolvedValue([dateBoard]);++ await expect(Promise.all([queryClient.fetchQuery(options), queryClient.fetchQuery(options)])).resolves.toEqual([+ [board, dateBoard],+ [board, dateBoard],+ ]);+ expect(backend.listGalleryBoards).toHaveBeenCalledOnce();+ expect(backend.listGalleryDateBoards).toHaveBeenCalledOnce();+ });++ it('keeps pagination, search, and refresh identity in the image query key', () => {+ const base = {+ boardId: 'board-1',+ galleryView: 'images' as const,+ limit: 60,+ offset: 0,+ orderDir: 'DESC' as const,+ revision: 'images:1',+ searchTerm: 'portrait',+ starredFirst: true,+ };++ expect(galleryImagesOptions(base).queryKey).not.toEqual(galleryImagesOptions({ ...base, offset: 60 }).queryKey);+ expect(galleryImagesOptions(base).queryKey).not.toEqual(+ galleryImagesOptions({ ...base, revision: 'images:2' }).queryKey+ );+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.tsnew file mode 100644index 0000000000..540138c1f4--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts@@ -0,0 +1,51 @@+import type { GalleryBoardOrderBy, GalleryOrderDir, GalleryView } from '@features/gallery/core/types';++import { queryOptions } from '@tanstack/react-query';++import { listGalleryBoards, listGalleryDateBoards, listGalleryImages } from './backend';++export interface GalleryBoardsQuery {+ includeArchived?: boolean;+ includeDateBoards?: boolean;+ orderBy?: GalleryBoardOrderBy;+ orderDir?: GalleryOrderDir;+ revision?: string;+}++export interface GalleryImagesQuery {+ boardId: string;+ galleryView: GalleryView;+ limit?: number;+ offset?: number;+ orderDir?: GalleryOrderDir;+ revision?: string;+ searchTerm: string;+ starredFirst?: boolean;+}++export const galleryKeys = {+ all: ['gallery'] as const,+ boards: (query: GalleryBoardsQuery) => [...galleryKeys.all, 'boards', query] as const,+ images: (query: GalleryImagesQuery) => [...galleryKeys.all, 'images', query] as const,+};++export const galleryBoardsOptions = (query: GalleryBoardsQuery = {}) =>+ queryOptions({+ queryFn: async () => {+ const [boards, dateBoards] = await Promise.all([+ listGalleryBoards(query),+ query.includeDateBoards ? listGalleryDateBoards() : Promise.resolve([]),+ ]);++ return [...boards, ...dateBoards];+ },+ queryKey: galleryKeys.boards(query),+ staleTime: 60_000,+ });++export const galleryImagesOptions = (query: GalleryImagesQuery) =>+ queryOptions({+ queryFn: () => listGalleryImages(query),+ queryKey: galleryKeys.images(query),+ staleTime: 60_000,+ });diff --git a/invokeai/frontend/webv2/src/features/gallery/index.ts b/invokeai/frontend/webv2/src/features/gallery/index.tsnew file mode 100644index 0000000000..32c8a06e9f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/index.ts@@ -0,0 +1,66 @@+export type {+ GalleryBoard,+ GalleryBoardKind,+ GalleryBoardOrderBy,+ GalleryImage,+ GalleryImageMetadata,+ GalleryImagesPage,+ GalleryOrderDir,+ GalleryView,+ GeneratedImageContract,+} from './core/types';+import {+ addImagesToGalleryBoard,+ deleteGalleryImages,+ downloadGalleryArchive,+ getGalleryImageByName,+ getGalleryImageMetadata,+ getGalleryImagesByNames,+ getImageFullUrl,+ getImageThumbnailUrl,+ isDateBoardId,+ listGalleryBoards,+ makeImageDurable,+ removeImagesFromGalleryBoard,+ saveImageToGallery,+ starGalleryImages,+ unstarGalleryImages,+ uploadGalleryImage,+} from './data/backend';++/** Resolve backend Gallery images without exposing transport DTOs or endpoints. */+export const galleryImages = {+ fullUrl: getImageFullUrl,+ metadata: getGalleryImageMetadata,+ resolve: getGalleryImageByName,+ resolveMany: getGalleryImagesByNames,+ thumbnailUrl: getImageThumbnailUrl,+} as const;++/** Import/export intents shared by image-producing and image-consuming features. */+export const galleryTransfers = {+ downloadArchive: downloadGalleryArchive,+ upload: uploadGalleryImage,+} as const;++/** Durability transitions for intermediate results. */+export const galleryDurability = {+ makeDurable: makeImageDurable,+ save: saveImageToGallery,+} as const;++/** Board and image organization intents. */+export const galleryOrganization = {+ addToBoard: addImagesToGalleryBoard,+ deleteImages: deleteGalleryImages,+ removeFromBoard: removeImagesFromGalleryBoard,+ setStarred: (imageNames: string[], starred: boolean): Promise<void> =>+ starred ? starGalleryImages(imageNames) : unstarGalleryImages(imageNames),+} as const;++/** Destination choices for callers such as Workflow fields. */+export const galleryDestinations = {+ list: listGalleryBoards,+} as const;++export const isGalleryVirtualBoard = isDateBoardId;diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.tsnew file mode 100644index 0000000000..4f10c268a0--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts@@ -0,0 +1,2 @@+export { galleryBoardsOptions, galleryImagesOptions, galleryKeys } from './data/queries';+export type { GalleryBoardsQuery, GalleryImagesQuery } from './data/queries';diff --git a/invokeai/frontend/webv2/src/features/gallery/react.ts b/invokeai/frontend/webv2/src/features/gallery/react.tsnew file mode 100644index 0000000000..43961ec28e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/react.ts@@ -0,0 +1,8 @@+export {+ GalleryUiProvider,+ GalleryImageActionsProvider,+ type GalleryImageActions,+ type GalleryImageActionsOptions,+ type GalleryImageContextMenuProps,+ type GalleryUiAdapter,+} from './ui/GalleryUiContext';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsxsimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardMenu.tsxrename to invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsxindex a43d17a641..036948af7b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardMenu.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx@@ -1,8 +1,8 @@/* eslint-disable react/react-compiler */-import type { GalleryBoard } from '@workbench/gallery/api';+import type { GalleryBoard } from '@features/gallery/core/types';import { Dialog, HStack, Icon, Input, Menu, Portal, Stack, Text } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';+import { Button } from '@platform/ui';import { ArchiveIcon, DownloadIcon, PencilIcon, Trash2Icon, type LucideIcon } from 'lucide-react';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardSelect.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsxsimilarity index 99%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardSelect.tsxrename to invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsxindex 858ad26506..81ce62da5a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardSelect.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx@@ -1,4 +1,4 @@-import type { GalleryBoard } from '@workbench/gallery/api';+import type { GalleryBoard } from '@features/gallery/core/types';import {Badge,@@ -15,7 +15,7 @@ import {Text,} from '@chakra-ui/react';import { useDndContext, useDndMonitor, useDroppable, type DragEndEvent, type DragStartEvent } from '@dnd-kit/core';-import { Button, CloseButton, IconButton } from '@workbench/components/ui';+import { Button, CloseButton, IconButton } from '@platform/ui';import {ArchiveIcon,ArrowDownAZIcon,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxsimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryImageGrid.tsxrename to invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex 42408b62ab..ae8432e724 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -1,16 +1,13 @@-import type { GalleryImage } from '@workbench/gallery/api';-import type { GalleryThumbnailFit } from '@workbench/gallery/settings';+import type { GalleryThumbnailFit } from '@features/gallery/core/settings';+import type { GalleryImage } from '@features/gallery/core/types';import { Badge, Box, Flex, ProgressCircle, ScrollArea, Skeleton, Spinner, Text } from '@chakra-ui/react';import { useDraggable } from '@dnd-kit/core';import { CSS } from '@dnd-kit/utilities';-import { useQueueItemProgressImage } from '@workbench/backend/progressImageStore';-import { useQueueItemProgress } from '@workbench/backend/progressStore';-import { IconButton } from '@workbench/components/ui';-import { ImageContextMenu, type ImageContextMenuTarget } from '@workbench/image-actions';-import { StreamingImageFrame } from '@workbench/images/StreamingImageFrame';-import { progressImageToStreamingSource } from '@workbench/images/streamingImageSource';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useQueueItemProgress, useQueueItemProgressImage } from '@features/queue/react';+import { IconButton } from '@platform/ui';+import { StreamingImageFrame } from '@platform/ui/streaming-image/StreamingImageFrame';+import { progressImageToStreamingSource } from '@platform/ui/streaming-image/streamingImageSource';import { StarIcon, UploadIcon } from 'lucide-react';import {useEffect,@@ -28,8 +25,10 @@ import { useTranslation } from 'react-i18next';import type { GalleryImageDragImage } from './galleryDnd';import type { GalleryQueuePlaceholder } from './galleryStateView';+import type { GalleryImageContextMenuTarget } from './GalleryUiContext';import { getGalleryImageDragData, getGalleryImageDragId } from './galleryDnd';+import { useGalleryUi } from './GalleryUiContext';import { useGalleryWidget } from './GalleryWidgetContext';const GRID_GAP_PX = 4;@@ -68,15 +67,14 @@ type GridCell =export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) => {const { t } = useTranslation();const { actions, gallery, imageActions, runtime } = useGalleryWidget();- const dispatch = useWorkbenchDispatch();- const [contextMenuTarget, setContextMenuTarget] = useState<ImageContextMenuTarget | null>(null);+ const { account, antialiasProgressImages, ImageContextMenu, widgets } = useGalleryUi();+ const [contextMenuTarget, setContextMenuTarget] = useState<GalleryImageContextMenuTarget | null>(null);const [isDropActive, setIsDropActive] = useState(false);const [viewportWidth, setViewportWidth] = useState(() => viewportWidthCache.get(layout) ?? 0);const dragDepthRef = useRef(0);const viewportRef = useRef<HTMLDivElement | null>(null);const { imageDensityPercent, imageOrderDir, paginationMode, showImageDimensions, starredFirst, thumbnailFit } =gallery.settings;- const antialiasProgressImages = useActiveProjectSelector((project) => project.settings.antialiasProgressImages);const columnCount = getGalleryColumnCount(imageDensityPercent, layout);const selectedNames = useMemo(() => new Set(gallery.selectedImageNames), [gallery.selectedImageNames]);const isComparisonActive =@@ -304,11 +302,8 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>);const handleShowProgressImages = useCallback(() => {- dispatch({- settings: { showProgressImagesInViewer: true },- type: 'setActiveProjectSettings',- });- }, [dispatch]);+ account.showProgressImages();+ }, [account]);const handleToggleStarred = useCallback((image: GalleryImage) => void imageActions.setImagesStarred([image.imageName], !image.starred),@@ -351,14 +346,10 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>}if (commandId === 'gallery.clearSelection') {- dispatch({- type: 'patchWidgetValues',- values: {- selectedImage: null,- selectedImageName: null,- selectedImageNames: [],- },- widgetId: 'gallery',+ widgets.patchGalleryValues({+ selectedImage: null,+ selectedImageName: null,+ selectedImageNames: [],});return;}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryPanelContent.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryPanelContent.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryPanelContent.tsxrename to invokeai/frontend/webv2/src/features/gallery/ui/GalleryPanelContent.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryToolbar.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryToolbar.tsxsimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryToolbar.tsxrename to invokeai/frontend/webv2/src/features/gallery/ui/GalleryToolbar.tsxindex a53a603d57..952c04dbbe 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryToolbar.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryToolbar.tsx@@ -1,4 +1,4 @@-import type { GalleryView } from '@workbench/gallery/api';+import type { GalleryView } from '@features/gallery/core/types';import {Box,@@ -14,8 +14,8 @@ import {Switch,Text,} from '@chakra-ui/react';-import { Button, CloseButton, IconButton, Tabs } from '@workbench/components/ui';-import { isDateBoardId } from '@workbench/gallery/api';+import { isDateBoardId } from '@features/gallery/data/backend';+import { Button, CloseButton, IconButton, Tabs } from '@platform/ui';import { SearchIcon, SettingsIcon, UploadIcon } from 'lucide-react';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxnew file mode 100644index 0000000000..826b786bba--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -0,0 +1,117 @@+import type { GallerySettings } from '@features/gallery/core/settings';+import type { GalleryBoard, GalleryImage, GalleryView } from '@features/gallery/core/types';+import type { QueueItem } from '@features/queue/contracts';++import { createContext, use, type ComponentType, type ReactNode } from 'react';++export interface GalleryImageActions {+ deleteImages(imageNames: string[]): Promise<void>;+ moveImagesToBoard(imageNames: string[], boardId: string): Promise<void>;+ setImagesStarred(imageNames: string[], starred: boolean): Promise<void>;+}++export interface GalleryImageActionsOptions {+ boards: GalleryBoard[];+ generateValues: Record<string, unknown>;+ onImagesDeleted(imageNames: string[]): void;+ onStarredChange(imageNames: string[], starred: boolean): void;+ projectId: string;+}++export interface GalleryImageContextMenuTarget {+ images: GalleryImage[];+ x: number;+ y: number;+}++export interface GalleryImageContextMenuProps {+ actions: GalleryImageActions;+ boards: GalleryBoard[];+ target: GalleryImageContextMenuTarget | null;+ onClose(): void;+}++export interface GalleryCommandsPort {+ selectBoard(boardId: string): void;+ selectImage(image: GalleryImage): void;+ setCompareImage(image: GalleryImage | null): void;+ setMultiSelection(imageNames: string[], primaryImage: GalleryImage): void;+ setPage(page: number): void;+ setPageInfo(totalImages: number): void;+ setProjectBoard(boardId: string): void;+ setSearchTerm(searchTerm: string): void;+ setView(view: GalleryView): void;+ toggleImageSelection(image: GalleryImage): void;+ touch(): void;+ updateSettings(settings: Partial<GallerySettings>): void;+}++export interface GalleryNotificationsPort {+ add(notification: { kind: 'info' | 'success'; message?: string; title: string }): void;+ reportError(error: { area: string; message: string; namespace: 'gallery' }): void;+}++export interface GalleryWidgetRuntime {+ commands: {+ register(command: { handler: () => unknown; id: string; title: string }): () => void;+ };+ hotkeys: {+ register(hotkey: { commandId: string; defaultKeys: string[]; id: string; title: string }): () => void;+ };+}++export interface GalleryWidgetProps {+ presentation?: 'compact' | 'expanded' | 'tooltip';+ region: 'bottom' | 'center' | 'dialog' | 'left' | 'popover' | 'right';+ runtime: GalleryWidgetRuntime;+}++export interface GalleryUiAdapter {+ ImageActionsProvider: ComponentType<GalleryImageActionsOptions & { children: ReactNode }>;+ ImageContextMenu: ComponentType<GalleryImageContextMenuProps>;+ account: { showProgressImages(): void };+ antialiasProgressImages: boolean;+ gallery: GalleryCommandsPort;+ galleryValues: Record<string, unknown>;+ generateValues: Record<string, unknown>;+ notifications: GalleryNotificationsPort;+ projectId: string;+ projectName: string;+ queueItems: QueueItem[];+ widgets: { patchGalleryValues(values: Record<string, unknown>): void };+}++const GalleryUiContext = createContext<GalleryUiAdapter | null>(null);+const GalleryImageActionsContext = createContext<GalleryImageActions | null>(null);++export const GalleryImageActionsProvider = ({+ actions,+ children,+}: {+ actions: GalleryImageActions;+ children: ReactNode;+}) => <GalleryImageActionsContext value={actions}>{children}</GalleryImageActionsContext>;++export const useGalleryImageActions = (): GalleryImageActions => {+ const actions = use(GalleryImageActionsContext);++ if (!actions) {+ throw new Error('Gallery image actions require the App-owned image-actions adapter.');+ }++ return actions;+};++export const GalleryUiProvider = ({ adapter, children }: { adapter: GalleryUiAdapter; children: ReactNode }) => (+ <GalleryUiContext value={adapter}>{children}</GalleryUiContext>+);++export const useGalleryUi = (): GalleryUiAdapter => {+ const adapter = use(GalleryUiContext);++ if (!adapter) {+ throw new Error('Gallery UI requires an App-composed GalleryUiProvider.');+ }++ return adapter;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsxsimilarity index 84%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetContext.tsxrename to invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsxindex 9451c0c098..5aa8ab30d2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx@@ -1,11 +1,10 @@-import type { GalleryImage, GalleryView } from '@workbench/gallery/api';-import type { GallerySettings } from '@workbench/gallery/settings';-import type { ImageActions } from '@workbench/image-actions';-import type { WidgetRuntimeApi } from '@workbench/types';+import type { GallerySettings } from '@features/gallery/core/settings';+import type { GalleryImage, GalleryView } from '@features/gallery/core/types';import { createContext, use } from 'react';import type { GalleryStateView } from './galleryStateView';+import type { GalleryImageActions, GalleryWidgetRuntime } from './GalleryUiContext';/*** Gallery-widget intents. The provider (GalleryWidgetView) is the only place@@ -35,9 +34,9 @@ export interface GalleryActions {export interface GalleryWidgetContextValue {gallery: GalleryStateView;actions: GalleryActions;- imageActions: ImageActions;+ imageActions: GalleryImageActions;projectName: string;- runtime: WidgetRuntimeApi;+ runtime: GalleryWidgetRuntime;}export const GalleryWidgetContext = createContext<GalleryWidgetContextValue | null>(null);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetFooter.tsxsimilarity index 74%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsxrename to invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetFooter.tsxindex 6f00d4bf65..1979706574 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetFooter.tsx@@ -1,15 +1,12 @@-import type { WidgetViewProps } from '@workbench/types';-import { ButtonGroup, HStack, Pagination } from '@chakra-ui/react';-import { IconButton } from '@workbench/components/ui';-import { getGallerySettings } from '@workbench/gallery/settings';-import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { getGallerySettings } from '@features/gallery/core/settings';+import { IconButton } from '@platform/ui';import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import { getGalleryPage, getGalleryTotalImages } from './galleryStateView';+import { useGalleryUi } from './GalleryUiContext';import { GALLERY_PAGE_SIZE } from './useGalleryData';const PAGINATION_ITEM_VARIANT = { _selected: 'outline', base: 'ghost' } as const;@@ -19,17 +16,13 @@ const PAGINATION_ITEM_VARIANT = { _selected: 'outline', base: 'ghost' } as const* Reads everything from the gallery widget's persisted values so it stays* decoupled from the view's data fetching.*/-export const GalleryWidgetFooter = (_props: WidgetViewProps) => {+export const GalleryWidgetFooter = () => {const { t } = useTranslation();- const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));- const dispatch = useWorkbenchDispatch();+ const { gallery, galleryValues } = useGalleryUi();const settings = getGallerySettings(galleryValues);const page = getGalleryPage(galleryValues);const totalImages = getGalleryTotalImages(galleryValues);- const handlePageChange = useCallback(- (event: { page: number }) => dispatch({ page: event.page - 1, type: 'setGalleryPage' }),- [dispatch]- );+ const handlePageChange = useCallback((event: { page: number }) => gallery.setPage(event.page - 1), [gallery]);const renderPaginationItem = useCallback((paginationPage: { value: number }) => (<IconButton aria-label={t('common.pageNumber', { page: paginationPage.value })} variant={PAGINATION_ITEM_VARIANT}>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.test.tsrename to invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.test.tsdiff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsxnew file mode 100644index 0000000000..e514564758--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx@@ -0,0 +1,211 @@+import { getGallerySettings } from '@features/gallery/core/settings';+import { StatusWidgetChip } from '@platform/ui';+import { ImageIcon } from 'lucide-react';+import { useCallback, useEffect, useEffectEvent, useMemo, useRef } from 'react';++import type { GalleryStateView } from './galleryStateView';++import { GalleryPanelContent } from './GalleryPanelContent';+import {+ getGalleryPage,+ getGalleryProjectBoardId,+ getGalleryImagesRefreshToken,+ getGalleryRecentImagesKey,+ getGalleryRefreshToken,+ getGallerySearchTerm,+ getGallerySelectedBoardId,+ getGalleryStateView,+ getGalleryTotalImages,+ getGalleryView,+} from './galleryStateView';+import {+ useGalleryImageActions,+ useGalleryUi,+ type GalleryWidgetProps,+ type GalleryWidgetRuntime,+} from './GalleryUiContext';+import { GalleryWidgetContext, type GalleryActions, type GalleryWidgetContextValue } from './GalleryWidgetContext';+import { useGalleryActions } from './useGalleryActions';+import { GALLERY_PAGE_SIZE, useGalleryData } from './useGalleryData';++export const shouldPublishGalleryTotal = ({+ knownTotalImages,+ lastPublishedTotal,+ total,+}: {+ knownTotalImages: number | null;+ lastPublishedTotal: number | null;+ total: number | null;+}): boolean =>+ typeof total === 'number' && Number.isFinite(total) && total !== knownTotalImages && total !== lastPublishedTotal;++export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgetProps) => {+ const {+ gallery: galleryCommands,+ galleryValues,+ generateValues,+ projectId,+ projectName,+ queueItems,+ ImageActionsProvider,+ } = useGalleryUi();+ const galleryView = getGalleryView(galleryValues);+ const searchTerm = getGallerySearchTerm(galleryValues);+ const recentImagesKey = getGalleryRecentImagesKey(galleryValues);+ const refreshToken = getGalleryRefreshToken(galleryValues);+ const imageRefreshToken = getGalleryImagesRefreshToken(galleryValues);+ const page = getGalleryPage(galleryValues);+ const knownTotalImages = getGalleryTotalImages(galleryValues);+ const settings = getGallerySettings(galleryValues);+ const data = useGalleryData({+ galleryView,+ imageRefreshToken,+ page,+ recentImagesKey,+ refreshToken,+ searchTerm,+ selectedBoardId: getGallerySelectedBoardId(galleryValues, []),+ settings,+ });++ const { loadMore, patchImages, total } = data;+ const selectedBoardId = getGallerySelectedBoardId(galleryValues, data.boards);+ const gallery = getGalleryStateView(galleryValues, data.boards, data.images, data.isLoadingImages, queueItems);++ const onStarredChange = useCallback(+ (imageNames: string[], starred: boolean) => {+ patchImages((images) =>+ images.map((image) => (imageNames.includes(image.imageName) ? { ...image, starred } : image))+ );+ },+ [patchImages]+ );++ const lastPublishedTotalRef = useRef<number | null>(null);++ // After a deletion that takes out the previewed image, move the selection to+ // the image that now occupies the old index, else the one before it.+ const onImagesDeleted = useEffectEvent((imageNames: string[]) => {+ const deletedNames = new Set(imageNames);+ const images = gallery.images;+ const anchorName = gallery.selectedImageName;++ if (!anchorName || !deletedNames.has(anchorName)) {+ return;+ }++ const anchorIndex = images.findIndex((image) => image.imageName === anchorName);++ if (anchorIndex === -1) {+ return;+ }++ const remaining = images.filter((image) => !deletedNames.has(image.imageName));+ const remainingBeforeAnchor = images+ .slice(0, anchorIndex)+ .filter((image) => !deletedNames.has(image.imageName)).length;+ const nextImage = remaining[remainingBeforeAnchor] ?? remaining[remainingBeforeAnchor - 1] ?? null;++ if (nextImage) {+ galleryCommands.selectImage(nextImage);+ }+ });++ const actions = useGalleryActions({+ boards: data.boards,+ loadMore,+ projectBoardId: getGalleryProjectBoardId(galleryValues),+ projectName,+ selectedBoardId,+ });++ const isWidePlacement = region === 'center' || (region === 'bottom' && presentation === 'expanded');++ // Publish the backend total into widget values so the manifest footer can+ // render page navigation without its own fetch, and clamp the page when the+ // query shrinks (e.g. after deletions).+ //+ // The effect reacts only to this instance's fetched `total` — the published+ // state (`knownTotalImages`) is read through a ref on purpose. Several+ // gallery views can be mounted at once (e.g. the bottom status chip plus an+ // expanded gallery), and if each instance re-published whenever the shared+ // state disagreed with its own in-flight total, two instances mid-refetch+ // would dispatch in a loop until React aborts with "maximum update depth".+ const publishGalleryTotal = useEffectEvent((nextTotal: number) => {+ const lastPublishedTotal = lastPublishedTotalRef.current;++ lastPublishedTotalRef.current = nextTotal;++ if (shouldPublishGalleryTotal({ knownTotalImages, lastPublishedTotal, total: nextTotal })) {+ galleryCommands.setPageInfo(nextTotal);+ }+ });++ useEffect(() => {+ if (typeof total !== 'number' || !Number.isFinite(total)) {+ return;+ }++ publishGalleryTotal(total);+ }, [total]);++ useEffect(() => {+ if (settings.paginationMode !== 'paginated' || total === null) {+ return;+ }++ const maxPage = Math.max(0, Math.ceil(total / GALLERY_PAGE_SIZE) - 1);++ if (page > maxPage) {+ galleryCommands.setPage(maxPage);+ }+ }, [galleryCommands, page, settings.paginationMode, total]);++ if (region === 'bottom' && presentation !== 'expanded') {+ return <StatusWidgetChip icon={ImageIcon}>Gallery: {total ?? gallery.images.length}</StatusWidgetChip>;+ }++ return (+ <ImageActionsProvider+ boards={data.boards}+ generateValues={generateValues}+ projectId={projectId}+ onImagesDeleted={onImagesDeleted}+ onStarredChange={onStarredChange}+ >+ <GalleryWidgetContent+ actions={actions}+ gallery={gallery}+ layout={isWidePlacement ? 'wide' : 'stacked'}+ projectName={projectName}+ runtime={runtime}+ />+ </ImageActionsProvider>+ );+};++const GalleryWidgetContent = ({+ actions,+ gallery,+ layout,+ projectName,+ runtime,+}: {+ actions: GalleryActions;+ gallery: GalleryStateView;+ layout: 'stacked' | 'wide';+ projectName: string;+ runtime: GalleryWidgetRuntime;+}) => {+ const imageActions = useGalleryImageActions();+ const contextValue = useMemo<GalleryWidgetContextValue>(+ () => ({ actions, gallery, imageActions, projectName, runtime }),+ [actions, gallery, imageActions, projectName, runtime]+ );++ return (+ <GalleryWidgetContext value={contextValue}>+ <GalleryPanelContent layout={layout} />+ </GalleryWidgetContext>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryDnd.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryDnd.test.tsrename to invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryDnd.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryDnd.tsrename to invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.tsindex 9db90b86a4..8cfd20779e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryDnd.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts@@ -1,4 +1,4 @@-import type { GalleryBoardKind } from '@workbench/gallery/api';+import type { GalleryBoardKind } from '@features/gallery/core/types';export interface GalleryImageDragImage {boardId: string;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tssimilarity index 90%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.test.tsrename to invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tsindex 58affc1240..1f28d0c7bc 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -1,5 +1,5 @@-import type { GalleryBoard } from '@workbench/gallery/api';-import type { GeneratedImageContract, QueueItem, QueueItemStatus } from '@workbench/types';+import type { GalleryBoard, GeneratedImageContract } from '@features/gallery/core/types';+import type { QueueHistoryItemStatus, QueueItem } from '@features/queue/contracts';import { describe, expect, it } from 'vitest';@@ -41,23 +41,29 @@ const createQueueItem = ({completedBackendItemIds?: number[];cancelledBackendItemIds?: number[];destination?: 'gallery' | 'canvas';- status?: QueueItemStatus;-}): QueueItem =>- ({- backendItemIds,- cancellable: true,- cancelledBackendItemIds,- completedBackendItemIds,- id: `queue-item-${status}-${boardId}`,- snapshot: {- destination,- widgetStates: {- gallery: { id: 'gallery', label: 'Gallery', values: { selectedBoardId: boardId }, version: 1 },- generate: { id: 'generate', label: 'Generate', values: { batchCount, height: 768, width: 512 }, version: 1 },- },+ status?: QueueHistoryItemStatus;+}): QueueItem => ({+ backendItemIds,+ cancellable: true,+ cancelledBackendItemIds,+ completedBackendItemIds,+ id: `queue-item-${status}-${boardId}`,+ snapshot: {+ backendSubmission: {+ batchCount,+ graph: { edges: [], id: 'gallery-placeholder-graph', nodes: {} },+ kind: 'workflow',},- status,- }) as unknown as QueueItem;+ destination,+ filterIntermediateResults: false,+ galleryBoardId: boardId,+ graph: { id: 'gallery-placeholder-graph', label: 'Gallery placeholder' },+ presentation: { batchCount, height: 768, width: 512 },+ sourceId: 'workflow',+ submittedAt: '2026-06-09T00:00:00.000Z',+ },+ status,+});describe('gallery state view', () => {it('preserves a selected backend board id while boards are still loading', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tssimilarity index 93%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.tsrename to invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex ffa8fb19e1..8a343d93d1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -1,8 +1,8 @@-import type { GalleryBoard, GalleryImage, GalleryView } from '@workbench/gallery/api';-import type { GeneratedImageContract, QueueItem } from '@workbench/types';+import type { GalleryBoard, GalleryImage, GalleryView, GeneratedImageContract } from '@features/gallery/core/types';+import type { QueueItem } from '@features/queue/contracts';-import { getGallerySettings, type GallerySettings } from '@workbench/gallery/settings';-import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from '@workbench/queueSnapshot';+import { getGallerySettings, type GallerySettings } from '@features/gallery/core/settings';+import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from '@features/queue/contracts';const UNCATEGORIZED_BOARD: GalleryBoard = {archived: false,@@ -130,8 +130,7 @@ export const getGalleryQueuePlaceholders = (continue;}- const galleryValues = item.snapshot.widgetStates.gallery?.values ?? {};- const targetBoardId = typeof galleryValues.selectedBoardId === 'string' ? galleryValues.selectedBoardId : 'none';+ const targetBoardId = item.snapshot.galleryBoardId ?? 'none';if (targetBoardId !== selectedBoardId) {continue;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.tssimilarity index 68%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/useGalleryActions.tsrename to invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.tsindex 3666a778c2..057ffe7035 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/useGalleryActions.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts@@ -1,4 +1,4 @@-import type { WorkbenchAction } from '@workbench/workbenchState';+import type { GalleryBoard } from '@features/gallery/core/types';import {createGalleryBoard,@@ -6,38 +6,47 @@ import {downloadGalleryArchive,updateGalleryBoard,uploadGalleryImage,- type GalleryBoard,-} from '@workbench/gallery/api';-import { saveBlobToDisk } from '@workbench/image-actions';-import { useMemo, type Dispatch } from 'react';+} from '@features/gallery/data/backend';+import { useMemo } from 'react';import type { GalleryActions } from './GalleryWidgetContext';+import { useGalleryUi } from './GalleryUiContext';+const ACCEPTED_UPLOAD_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));+const saveBlobToDisk = (blob: Blob, fileName: string): void => {+ const objectUrl = URL.createObjectURL(blob);+ const anchor = document.createElement('a');++ anchor.href = objectUrl;+ anchor.download = fileName;+ anchor.click();+ URL.revokeObjectURL(objectUrl);+};+export const useGalleryActions = ({boards,- dispatch,loadMore,projectBoardId,projectName,selectedBoardId,}: {boards: GalleryBoard[];- dispatch: Dispatch<WorkbenchAction>;loadMore: () => void;projectBoardId: string | null;projectName: string;selectedBoardId: string;}): GalleryActions => {+ const { gallery, notifications } = useGalleryUi();+return useMemo<GalleryActions>(() => {const recordError = (error: unknown) =>- dispatch({ area: 'gallery-actions', message: toErrorMessage(error), namespace: 'gallery', type: 'recordError' });- const recordSuccess = (title: string, message?: string) =>- dispatch({ kind: 'success', message, title, type: 'recordNotice' });- const refresh = () => dispatch({ type: 'touchGalleryRefresh' });+ notifications.reportError({ area: 'gallery-actions', message: toErrorMessage(error), namespace: 'gallery' });+ const recordSuccess = (title: string, message?: string) => notifications.add({ kind: 'success', message, title });+ const refresh = gallery.touch;const getBoardName = (boardId: string) => boards.find((board) => board.id === boardId)?.name ?? 'Uncategorized';return {@@ -47,7 +56,7 @@ export const useGalleryActions = ({recordSuccess(`${archived ? 'Archived' : 'Unarchived'} board "${getBoardName(boardId)}"`);if (archived && boardId === selectedBoardId) {- dispatch({ boardId: 'none', type: 'selectGalleryBoard' });+ gallery.selectBoard('none');}refresh();@@ -59,7 +68,7 @@ export const useGalleryActions = ({try {const board = await createGalleryBoard(boardName);- dispatch({ boardId: board.id, type: 'selectGalleryBoard' });+ gallery.selectBoard(board.id);recordSuccess(`Created board "${board.name}"`);refresh();} catch (error: unknown) {@@ -77,7 +86,7 @@ export const useGalleryActions = ({);if (boardId === selectedBoardId) {- dispatch({ boardId: 'none', type: 'selectGalleryBoard' });+ gallery.selectBoard('none');}refresh();@@ -87,11 +96,10 @@ export const useGalleryActions = ({},downloadBoard: async (boardId) => {try {- dispatch({+ notifications.add({kind: 'info',message: `Preparing an archive of "${getBoardName(boardId)}".`,title: 'Preparing download',- type: 'recordNotice',});const { blob, fileName } = await downloadGalleryArchive({ boardId });@@ -113,13 +121,12 @@ export const useGalleryActions = ({recordError(error);}},- selectBoard: (boardId) => dispatch({ boardId, type: 'selectGalleryBoard' }),- selectImage: (image) => dispatch({ image, type: 'selectGalleryImage' }),- selectImageRange: (imageNames, primaryImage) =>- dispatch({ imageNames, primaryImage, type: 'setGalleryMultiSelection' }),+ selectBoard: gallery.selectBoard,+ selectImage: gallery.selectImage,+ selectImageRange: gallery.setMultiSelection,selectProjectBoard: async () => {if (projectBoardId && boards.some((board) => board.id === projectBoardId)) {- dispatch({ boardId: projectBoardId, type: 'selectGalleryBoard' });+ gallery.selectBoard(projectBoardId);return;}@@ -130,27 +137,26 @@ export const useGalleryActions = ({try {const board = await createGalleryBoard(projectName);- dispatch({ boardId: board.id, type: 'setGalleryProjectBoardId' });- dispatch({ boardId: board.id, type: 'selectGalleryBoard' });+ gallery.setProjectBoard(board.id);+ gallery.selectBoard(board.id);recordSuccess(`Created project board "${board.name}"`);refresh();} catch (error: unknown) {recordError(error);}},- setSearchTerm: (searchTerm) => dispatch({ searchTerm, type: 'setGallerySearchTerm' }),- setView: (galleryView) => dispatch({ galleryView, type: 'setGalleryView' }),- toggleImageInSelection: (image) => dispatch({ image, type: 'toggleGalleryImageInSelection' }),- updateSettings: (settings) => dispatch({ settings, type: 'updateGallerySettings' }),+ setSearchTerm: gallery.setSearchTerm,+ setView: gallery.setView,+ toggleImageInSelection: gallery.toggleImageSelection,+ updateSettings: gallery.updateSettings,uploadFiles: async (files) => {const accepted = files.filter((file) => ACCEPTED_UPLOAD_TYPES.has(file.type));if (accepted.length === 0) {- dispatch({+ notifications.reportError({area: 'gallery-upload',message: 'No supported image files to upload (PNG, JPEG, or WebP).',namespace: 'gallery',- type: 'recordError',});return;}@@ -167,5 +173,5 @@ export const useGalleryActions = ({}},};- }, [boards, dispatch, loadMore, projectBoardId, projectName, selectedBoardId]);+ }, [boards, gallery, loadMore, notifications, projectBoardId, projectName, selectedBoardId]);};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.tsnew file mode 100644index 0000000000..b41e64118b--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts@@ -0,0 +1,100 @@+import type { GallerySettings } from '@features/gallery/core/settings';+import type { GalleryBoard, GalleryImage, GalleryView } from '@features/gallery/core/types';++import { galleryBoardsOptions, galleryImagesOptions } from '@features/gallery/data/queries';+import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query';+import { useCallback, useState } from 'react';++export const GALLERY_PAGE_SIZE = 60;++export interface GalleryData {+ boards: GalleryBoard[];+ hasMore: boolean;+ images: GalleryImage[] | null;+ isLoadingImages: boolean;+ loadMore: () => void;+ patchImages: (getImages: (images: GalleryImage[]) => GalleryImage[]) => void;+ total: number | null;+}++const useGalleryBoards = ({ refreshToken, settings }: { refreshToken: string; settings: GallerySettings }) => {+ const query = useQuery(+ galleryBoardsOptions({+ includeArchived: settings.showArchivedBoards,+ includeDateBoards: settings.showDateBoards,+ orderBy: settings.boardOrderBy,+ orderDir: settings.boardOrderDir,+ revision: refreshToken,+ })+ );++ return { boards: query.data ?? [] };+};++export const useGalleryData = ({+ galleryView,+ imageRefreshToken,+ page,+ recentImagesKey,+ refreshToken,+ searchTerm,+ selectedBoardId,+ settings,+}: {+ galleryView: GalleryView;+ imageRefreshToken: string;+ page: number;+ recentImagesKey: string;+ refreshToken: string;+ searchTerm: string;+ selectedBoardId: string;+ settings: GallerySettings;+}): GalleryData => {+ const queryClient = useQueryClient();+ const { boards } = useGalleryBoards({ refreshToken, settings });+ const boardId =+ boards.length === 0 || boards.some((board) => board.id === selectedBoardId) ? selectedBoardId : 'none';+ const baseKey = [galleryView, boardId, searchTerm.trim(), settings.imageOrderDir, String(settings.starredFirst)].join(+ '\0'+ );+ const [infiniteWindow, setInfiniteWindow] = useState({ baseKey, pageCount: 1 });+ const isPaginated = settings.paginationMode === 'paginated';+ const pageCount = infiniteWindow.baseKey === baseKey ? infiniteWindow.pageCount : 1;+ const offset = isPaginated ? page * GALLERY_PAGE_SIZE : 0;+ const limit = isPaginated ? GALLERY_PAGE_SIZE : pageCount * GALLERY_PAGE_SIZE;+ const options = galleryImagesOptions({+ boardId,+ galleryView,+ limit,+ offset,+ orderDir: settings.imageOrderDir,+ revision: `${imageRefreshToken}:${recentImagesKey}`,+ searchTerm,+ starredFirst: settings.starredFirst,+ });+ const query = useQuery({ ...options, placeholderData: keepPreviousData });+ const images = query.data?.images ?? null;+ const total = query.data?.total ?? null;+ const hasMore = !isPaginated && total !== null && images !== null && images.length < total;+ const loadMore = useCallback(() => {+ if (!hasMore || query.isFetching) {+ return;+ }++ setInfiniteWindow((current) => ({+ baseKey,+ pageCount: current.baseKey === baseKey ? current.pageCount + 1 : 2,+ }));+ }, [baseKey, hasMore, query.isFetching]);++ const patchImages = useCallback(+ (getImages: (images: GalleryImage[]) => GalleryImage[]) => {+ queryClient.setQueryData(options.queryKey, (current) =>+ current ? { ...current, images: getImages(current.images) } : current+ );+ },+ [options.queryKey, queryClient]+ );++ return { boards, hasMore, images, isLoadingImages: query.isFetching, loadMore, patchImages, total };+};diff --git a/invokeai/frontend/webv2/src/features/gallery/utility.ts b/invokeai/frontend/webv2/src/features/gallery/utility.tsnew file mode 100644index 0000000000..c47fabd120--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/utility.ts@@ -0,0 +1,19 @@+export {+ getGalleryBoardDropData,+ getGalleryBoardDropId,+ getGalleryImageDragData,+ getGalleryImageDragId,+ getGalleryImageNamesOutsideBoard,+ isGalleryBoardDropData,+ isGalleryImageDragData,+ type GalleryBoardDropData,+ type GalleryImageDragData,+ type GalleryImageDragImage,+} from './ui/galleryDnd';++import { getGalleryImageFullUrl, getGalleryImageThumbnailUrl } from './core/imageUrls';++export const galleryImageUrls = {+ full: getGalleryImageFullUrl,+ thumbnail: getGalleryImageThumbnailUrl,+} as const;diff --git a/invokeai/frontend/webv2/src/features/gallery/widget.ts b/invokeai/frontend/webv2/src/features/gallery/widget.tsnew file mode 100644index 0000000000..e30742fa4e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/widget.ts@@ -0,0 +1,2 @@+export { GalleryWidgetFooter } from './ui/GalleryWidgetFooter';+export { GalleryWidgetView } from './ui/GalleryWidgetView';diff --git a/invokeai/frontend/webv2/src/features/generation/batch.ts b/invokeai/frontend/webv2/src/features/generation/batch.tsnew file mode 100644index 0000000000..de43c75d8b--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/batch.ts@@ -0,0 +1 @@+export * from './core/batch';diff --git a/invokeai/frontend/webv2/src/features/generation/canvas.ts b/invokeai/frontend/webv2/src/features/generation/canvas.tsnew file mode 100644index 0000000000..0b781e9168--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/canvas.ts@@ -0,0 +1,6 @@+export * from './core/canvas/addControlLayers';+export * from './core/canvas/addRegionalGuidance';+export * from './core/canvas/canvasMode';+export * from './core/canvas/compileCanvasGraph';+export * from './core/canvas/controlValidation';+export type * from './core/canvas/types';diff --git a/invokeai/frontend/webv2/src/features/generation/contracts.ts b/invokeai/frontend/webv2/src/features/generation/contracts.tsnew file mode 100644index 0000000000..491ecd432f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/contracts.ts@@ -0,0 +1,2 @@+export type * from './core/contracts';+export type * from './core/types';diff --git a/invokeai/frontend/webv2/src/features/generation/core/api.ts b/invokeai/frontend/webv2/src/features/generation/core/api.tsnew file mode 100644index 0000000000..d12657615c--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/api.ts@@ -0,0 +1,9 @@+import { apiFetchJson } from '@platform/transport/http';++import type { MainModelConfig } from './types';++export const listMainModels = async (): Promise<MainModelConfig[]> => {+ const body = await apiFetchJson<{ models?: MainModelConfig[] }>('/api/v2/models/?model_type=main');++ return body.models ?? [];+};diff --git a/invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tssimilarity index 99%rename from invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.tsrename to invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex dd35d8c705..995ad26077 100644--- a/invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -1,5 +1,8 @@-import type { KnownModelBase } from '@workbench/models/baseIdentity';-import type { ModelConfig, ModelTaxonomyType } from '@workbench/models/types';+import type {+ GenerationModelCatalogItem as ModelConfig,+ GenerationModelTaxonomyType as ModelTaxonomyType,+ KnownGenerationModelBase as KnownModelBase,+} from '@features/generation/core/contracts';import type {GenerateModelConfig,@@ -33,7 +36,7 @@ import {SEED_MAX,} from './settings';-// Generation policy registry keyed by model base. Display identity stays in @workbench/models/baseIdentity;+// Generation policy registry keyed by model base. Display identity stays in @features/models;// graph topology stays explicit in graph.ts.export interface SchedulerOption {diff --git a/invokeai/frontend/webv2/src/workbench/generation/batch.ts b/invokeai/frontend/webv2/src/features/generation/core/batch.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/batch.tsrename to invokeai/frontend/webv2/src/features/generation/core/batch.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/addControlLayers.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/addControlLayers.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/addControlLayers.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.tssimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/addControlLayers.tsrename to invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.tsindex 9a7e41c72a..b9f5e28ce7 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/addControlLayers.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.ts@@ -20,10 +20,10 @@* distinct control image, exactly like legacy.*/-import type { SupportedGenerateBase } from '@workbench/generation/baseGenerationPolicies';-import type { BackendGraphContract, BackendInvocationContract } from '@workbench/types';+import type { SupportedGenerateBase } from '@features/generation/core/baseGenerationPolicies';+import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';-import { addEdge, addNode } from '@workbench/generation/graphBuilder';+import { addEdge, addNode } from '@features/generation/core/graphBuilder';import type { ControlAdapterKind } from './controlValidation';diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/addRegionalGuidance.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/addRegionalGuidance.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/addRegionalGuidance.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.tssimilarity index 88%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/addRegionalGuidance.tsrename to invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.tsindex e282b4a15b..66dd53ac5c 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/addRegionalGuidance.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts@@ -1,34 +1,6 @@-/**- * Pure regional-guidance graph grafting (legacy parity).- *- * {@link addRegionalGuidance} wires each enabled, valid regional-guidance region- * into the canvas base graph's conditioning collectors: a per-region- * `alpha_mask_to_tensor` node (fed by the region's uploaded mask image) supplies- * a mask tensor that scopes per-region positive/negative prompt conditioning- * (into `pos_cond_collect` / `neg_cond_collect`), an `autoNegative` inverted-mask- * negative conditioning, and mask-scoped reference images (SD `ip_adapter`,- * FLUX `flux_redux`). It mutates the graph in place using the same- * `addNode`/`addEdge` helpers the base builders use — no fetch, no engine, no- * React. Node types + args mirror legacy- * `features/nodes/util/graph/generation/addRegions.ts`.- *- * ## Support matrix (legacy `getRegionalGuidanceWarnings`)- *- * - **sd-1 / sdxl**: full support — positive, negative, autoNegative, regional- * `ip_adapter` reference images.- * - **flux**: positive prompt + `flux_redux` reference images only. Negative- * prompt, autoNegative, and regional `ip_adapter` are NOT supported (silently- * skipped here; surfaced as a rejection reason upstream).- * - Every other base is unsupported (region skipped; rejection reason emitted).- *- * The caller (`prepareCanvasInvocation`) composites + uploads each region's mask- * separately and resolves reference-image models, then passes only valid regions- * in — this module only shapes nodes/edges.- */--import type { BackendGraphContract, BackendInvocationContract } from '@workbench/types';+import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';-import { addEdge, addNode } from '@workbench/generation/graphBuilder';+import { addEdge, addNode } from '@features/generation/core/graphBuilder';/** The deterministic denoise node id every canvas base graph uses. */const DENOISE_NODE_ID = 'denoise_latents';diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/canvasMode.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/canvasMode.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/canvasMode.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/canvasMode.tsrename to invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.tssimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/compileCanvasGraph.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.tsindex d4f1bef1eb..93b1b54240 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/compileCanvasGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts@@ -1,22 +1,21 @@+import type { BackendGraphContract, GenerationProjectSettings } from '@features/generation/core/contracts';import type {ComponentModelConfig,GenerateModelConfig,GenerateSettings,MainModelConfig,VaeModelConfig,-} from '@workbench/generation/types';-import type { BackendGraphContract, ProjectSettings } from '@workbench/types';-import type { CanvasCompositingSettings } from '@workbench/widgets/canvas/invoke/canvasCompositing';+} from '@features/generation/core/types';-import { getDefaultGenerateSettings } from '@workbench/generation/baseGenerationPolicies';-import { DEFAULT_CANVAS_COMPOSITING } from '@workbench/widgets/canvas/invoke/canvasCompositing';+import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';import { describe, expect, it } from 'vitest';import type { ControlLayerGraphInput } from './addControlLayers';import type { RegionalGuidanceInput } from './addRegionalGuidance';-import type { CanvasCompileMode, Rect } from './types';+import type { CanvasCompileMode, CanvasCompositingSettings, Rect } from './types';import { compileCanvasGraph } from './compileCanvasGraph';+import { DEFAULT_CANVAS_COMPOSITING } from './types';const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };const sd2Model: MainModelConfig = { base: 'sd-2', key: 'sd2-model', name: 'SD 2', type: 'main' };@@ -68,7 +67,7 @@ const qwen3Encoder: ComponentModelConfig = {variant: 'qwen3_06b',};-const PROJECT_SETTINGS: Pick<ProjectSettings, 'useCpuNoise'> = { useCpuNoise: true };+const PROJECT_SETTINGS: GenerationProjectSettings = { useCpuNoise: true };const settingsFor = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({...getDefaultGenerateSettings(model),diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/compileCanvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/compileCanvasGraph.tsrename to invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.tsindex 064fd39ed4..21d14baf66 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/compileCanvasGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts@@ -23,20 +23,24 @@* generators have no latent img2img path and are rejected for every canvas mode.*/-import type { SupportedGenerateBase } from '@workbench/generation/baseGenerationPolicies';-import type { GenerateModelConfig, GenerateSettings } from '@workbench/generation/types';-import type { BackendGraphContract, BackendInvocationContract } from '@workbench/types';-import type { CanvasCompositingSettings, CanvasInfillMethod } from '@workbench/widgets/canvas/invoke/canvasCompositing';+import type { SupportedGenerateBase } from '@features/generation/core/baseGenerationPolicies';+import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';+import type { GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';-import { getGenerationValidationReasons } from '@workbench/generation/baseGenerationPolicies';-import { GRAPH_BUILDERS } from '@workbench/generation/graph';-import { addEdge, addNode, toGraphContract } from '@workbench/generation/graphBuilder';-import { DEFAULT_CANVAS_COMPOSITING } from '@workbench/widgets/canvas/invoke/canvasCompositing';+import { getGenerationValidationReasons } from '@features/generation/core/baseGenerationPolicies';+import { GRAPH_BUILDERS } from '@features/generation/core/graph';+import { addEdge, addNode, toGraphContract } from '@features/generation/core/graphBuilder';-import type { CompileCanvasGraphInput, CompiledCanvasGraph } from './types';+import type {+ CanvasCompositingSettings,+ CanvasInfillMethod,+ CompileCanvasGraphInput,+ CompiledCanvasGraph,+} from './types';import { addControlLayers } from './addControlLayers';import { addRegionalGuidance, isRegionalGuidanceSupportedForBase } from './addRegionalGuidance';+import { DEFAULT_CANVAS_COMPOSITING } from './types';/*** The backend image-to-latents (encode) node type per supported base. sd-1 /diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/controlValidation.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/controlValidation.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/controlValidation.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.tssimilarity index 74%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/controlValidation.tsrename to invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.tsindex af3c9c3914..203379d241 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/controlValidation.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.ts@@ -70,4 +70,28 @@ export const getControlValidationReason = (params: {}return null;};-import { areControlAdapterValuesValid } from '@workbench/controlAdapters';+const areControlAdapterValuesValid = (+ kind: ControlAdapterKind,+ weight: unknown,+ beginEndStepPct: unknown+): beginEndStepPct is [number, number] => {+ const minWeight = kind === 'z_image_control' ? 0 : -1;+ if (typeof weight !== 'number' || !Number.isFinite(weight) || weight < minWeight || weight > 2) {+ return false;+ }+ if (!Array.isArray(beginEndStepPct) || beginEndStepPct.length !== 2) {+ return false;+ }+ const [begin, end] = beginEndStepPct;+ return (+ typeof begin === 'number' &&+ Number.isFinite(begin) &&+ begin >= 0 &&+ begin <= 1 &&+ typeof end === 'number' &&+ Number.isFinite(end) &&+ end >= 0 &&+ end <= 1 &&+ begin < end+ );+};diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/types.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/types.tsnew file mode 100644index 0000000000..dbe9462dfc--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/types.ts@@ -0,0 +1,113 @@+import type {+ BackendGraphContract,+ GenerationProjectSettings,+ GraphContract,+ ResultDestination,+} from '@features/generation/core/contracts';+import type { GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';++import type { ControlLayerGraphInput } from './addControlLayers';+import type { RegionalGuidanceInput } from './addRegionalGuidance';++export interface Rect {+ x: number;+ y: number;+ width: number;+ height: number;+}++export type CanvasInfillMethod = 'patchmatch' | 'lama' | 'cv2' | 'color' | 'tile';+export type CanvasCoherenceMode = 'Gaussian Blur' | 'Box Blur' | 'Staged';++export interface CanvasCompositingSettings {+ infillMethod: CanvasInfillMethod;+ infillTileSize: number;+ infillPatchmatchDownscaleSize: number;+ infillColorValue: { r: number; g: number; b: number; a: number };+ maskBlur: number;+ coherenceMode: CanvasCoherenceMode;+ coherenceMinDenoise: number;+ coherenceEdgeSize: number;+}++export const DEFAULT_CANVAS_COMPOSITING: CanvasCompositingSettings = {+ coherenceEdgeSize: 16,+ coherenceMinDenoise: 0,+ coherenceMode: 'Gaussian Blur',+ infillColorValue: { a: 1, b: 0, g: 0, r: 0 },+ infillMethod: 'lama',+ infillPatchmatchDownscaleSize: 1,+ infillTileSize: 32,+ maskBlur: 16,+};++/** The legacy-parity generation modes a canvas invoke resolves to. */+export type CanvasGenerationMode = 'txt2img' | 'img2img' | 'inpaint' | 'outpaint';++/** The generation modes the pure canvas graph compiler supports (full matrix). */+export type CanvasCompileMode = CanvasGenerationMode;++/**+ * Everything {@link import('./compileCanvasGraph').compileCanvasGraph} needs to+ * build a canvas generation graph. Pure data: the executor (Task 16) supplies+ * the already-uploaded `compositeImageName`; no pixels or engine state leak in.+ */+export interface CompileCanvasGraphInput {+ /** Prompts / steps / model-adjacent settings, reused verbatim from Generate. */+ settings: GenerateSettings;+ model: GenerateModelConfig;+ projectSettings: GenerationProjectSettings;+ /** The resolved canvas mode (from `canvasMode.ts`). */+ mode: CanvasCompileMode;+ /**+ * The resolved result destination. `canvas` marks the output node intermediate+ * (staging); `gallery` makes it a durable image, matching `compileGenerateGraph`.+ */+ destination: ResultDestination;+ /** The generation bounding box, in document space. Its size overrides settings dims. */+ bbox: Rect;+ /** The uploaded bbox composite (executor result). Required for image-referencing modes. */+ compositeImageName: string | null;+ /**+ * The uploaded grayscale denoise-limit mask (white = keep, dark = inpaint).+ * Required for `inpaint` / `outpaint`.+ */+ maskImageName?: string | null;+ /**+ * The uploaded grayscale noise mask, present only when at least one enabled+ * mask layer defines a `noiseLevel`. Adds an `img_noise` node before encode.+ */+ noiseMaskImageName?: string | null;+ /** Denoising strength in (0, 1]. Consulted for `img2img` / `inpaint` / `outpaint`. */+ strength: number;+ /** Infill / coherence / mask-blur knobs. Defaults applied by the reader. */+ compositing?: CanvasCompositingSettings;+ /**+ * Valid, already-resolved control layers (each with its own uploaded composite+ * image name). The executor filters + composites these; the compiler only+ * grafts adapter nodes. Present in every mode (control works with all).+ */+ controlLayers?: readonly ControlLayerGraphInput[];+ /**+ * Valid, already-resolved regional-guidance regions (each with its own uploaded+ * mask image name + resolved reference-image models). The executor filters ++ * composites these; the compiler only grafts the mask-tensor + conditioning+ * nodes into the base graph's `pos_cond_collect` / `neg_cond_collect`. Applied+ * only for supported bases (sd-1 / sdxl / flux).+ */+ regionalGuidance?: readonly RegionalGuidanceInput[];+}++/**+ * Mirrors {@link import('../types').CompiledGenerateGraph} with the resolved+ * canvas mode attached so downstream (Task 18) can label / branch without+ * re-deriving it.+ */+export interface CompiledCanvasGraph {+ backendGraph: BackendGraphContract;+ graph: GraphContract;+ negativePromptNodeId: string;+ positivePromptNodeId: string;+ seedNodeId: string;+ mode: CanvasCompileMode;+}diff --git a/invokeai/frontend/webv2/src/workbench/generation/componentCompatibility.test.ts b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/componentCompatibility.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/componentCompatibility.ts b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/componentCompatibility.tsrename to invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.tsdiff --git a/invokeai/frontend/webv2/src/features/generation/core/contracts.ts b/invokeai/frontend/webv2/src/features/generation/core/contracts.tsnew file mode 100644index 0000000000..76fab55437--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/contracts.ts@@ -0,0 +1,96 @@+/** Public, storage-independent contracts owned by Generation. */++export type ResultDestination = 'canvas' | 'gallery';++export interface GenerationProjectSettings {+ useCpuNoise: boolean;+}++export interface PromptHistoryItem {+ positivePrompt: string;+ negativePrompt: string | null;+}++export interface BackendInvocationContract {+ id: string;+ type: string;+ [key: string]: unknown;+}++export interface BackendGraphEdgeContract {+ source: { node_id: string; field: string };+ destination: { node_id: string; field: string };+}++export interface BackendGraphContract {+ id: string;+ nodes: Record<string, BackendInvocationContract>;+ edges: BackendGraphEdgeContract[];+}++export interface GraphNodeContract {+ id: string;+ type: string;+ inputs: Record<string, unknown>;+}++export interface GraphEdgeContract {+ id: string;+ sourceNodeId: string;+ sourceField: string;+ targetNodeId: string;+ targetField: string;+}++export interface GraphContract {+ id: string;+ version: 1;+ label: string;+ nodes: GraphNodeContract[];+ edges: GraphEdgeContract[];+ updatedAt: string;+ backendGraph?: BackendGraphContract;+}++export type KnownGenerationModelBase =+ | 'sd-1'+ | 'sd-2'+ | 'sd-3'+ | 'sdxl'+ | 'sdxl-refiner'+ | 'flux'+ | 'flux2'+ | 'cogview4'+ | 'qwen-image'+ | 'z-image'+ | 'anima'+ | 'external'+ | 'any'+ | 'unknown';++export type GenerationModelTaxonomyType = string;++export interface GenerationModelCatalogItem {+ key: string;+ name: string;+ base: string;+ type: string;+ format?: string;+ variant?: string | null;+ hash?: string;+ submodel_type?: string;+ trigger_phrases?: string[] | null;+ default_settings?: {+ scheduler?: string | null;+ steps?: number | null;+ cfg_scale?: number | null;+ guidance?: number | null;+ cfg_rescale_multiplier?: number | null;+ width?: number | null;+ height?: number | null;+ vae?: string | null;+ vae_precision?: string | null;+ weight?: number | null;+ } | null;+ [key: string]: unknown;+}diff --git a/invokeai/frontend/webv2/src/workbench/generation/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/graph.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/graph.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.tssimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/generation/graph.tsrename to invokeai/frontend/webv2/src/features/generation/core/graph.tsindex 70b24f9d0b..1df5320a68 100644--- a/invokeai/frontend/webv2/src/workbench/generation/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts@@ -1,9 +1,9 @@import type {BackendGraphContract,BackendInvocationContract,- ProjectSettings,+ GenerationProjectSettings,ResultDestination,-} from '@workbench/types';+} from '@features/generation/core/contracts';import type {CompiledGenerateGraph,@@ -294,7 +294,7 @@ const buildSDGraph = (settings: GenerateSettings,model: MainModelConfig,outputIsIntermediate: boolean,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ projectSettings: GenerationProjectSettings): BackendGraphContract => {const graph: BackendGraphContract = { edges: [], id: createId(`${model.base}_graph`), nodes: {} };const modelLoaderType = model.base === 'sdxl' ? 'sdxl_model_loader' : 'main_model_loader';@@ -430,7 +430,7 @@ const buildSD3Graph = (settings: GenerateSettings,model: MainModelConfig,outputIsIntermediate: boolean,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ projectSettings: GenerationProjectSettings): BackendGraphContract => {const graph: BackendGraphContract = { edges: [], id: createId('sd3_graph'), nodes: {} };const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);@@ -483,7 +483,7 @@ const buildFluxGraph = (settings: GenerateSettings,model: MainModelConfig,outputIsIntermediate: boolean,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ projectSettings: GenerationProjectSettings): BackendGraphContract => {if (model.variant === 'dev_fill') {throw new Error('FLUX Fill models do not support text-to-image generation.');@@ -558,7 +558,7 @@ const buildFlux2Graph = (settings: GenerateSettings,model: MainModelConfig,outputIsIntermediate: boolean,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ projectSettings: GenerationProjectSettings): BackendGraphContract => {const sourceModel = getFlux2DiffusersComponentSource(model, settings);const hasBundledComponents = model.format === 'diffusers' || sourceModel;@@ -630,7 +630,7 @@ const buildCogView4Graph = (settings: GenerateSettings,model: MainModelConfig,outputIsIntermediate: boolean,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ projectSettings: GenerationProjectSettings): BackendGraphContract => {const graph: BackendGraphContract = { edges: [], id: createId('cogview4_graph'), nodes: {} };const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);@@ -666,7 +666,7 @@ const buildQwenImageGraph = (settings: GenerateSettings,model: MainModelConfig,outputIsIntermediate: boolean,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ projectSettings: GenerationProjectSettings): BackendGraphContract => {const sourceModel = getCompatibleComponentSource(settings, model);const hasBundledComponents = model.format === 'diffusers' || sourceModel;@@ -779,7 +779,7 @@ const buildZImageGraph = (settings: GenerateSettings,model: MainModelConfig,outputIsIntermediate: boolean,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ projectSettings: GenerationProjectSettings): BackendGraphContract => {const sourceModel = getDiffusersSource(settings, model);const qwen3EncoderModel =@@ -859,7 +859,7 @@ const buildAnimaGraph = (settings: GenerateSettings,model: MainModelConfig,outputIsIntermediate: boolean,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ projectSettings: GenerationProjectSettings): BackendGraphContract => {const vaeModel = requireComponent(settings.vae && isAnimaVae(settings.vae) ? settings.vae : null, 'Anima VAE');const qwen3EncoderModel = requireComponent(@@ -930,7 +930,7 @@ const buildExternalGraph = (settings: GenerateSettings,model: GenerateModelConfig,outputIsIntermediate: boolean,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ projectSettings: GenerationProjectSettings): BackendGraphContract => {if (model.type !== 'external_image_generator') {throw new Error('Selected model is not an external image generator.');@@ -990,7 +990,7 @@ type GenerateGraphBuilder = (settings: GenerateSettings,model: MainModelConfig,outputIsIntermediate: boolean,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ projectSettings: GenerationProjectSettings) => BackendGraphContract;export const GRAPH_BUILDERS = {@@ -1010,7 +1010,7 @@ export const compileGenerateGraph = (settings: GenerateSettings,model: GenerateModelConfig,destination: ResultDestination,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ projectSettings: GenerationProjectSettings): CompiledGenerateGraph => {const validationReasons = getGenerationValidationReasons(model, settings);diff --git a/invokeai/frontend/webv2/src/workbench/generation/graphBuilder.ts b/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/generation/graphBuilder.tsrename to invokeai/frontend/webv2/src/features/generation/core/graphBuilder.tsindex bfae73f160..ccd5ef9ac0 100644--- a/invokeai/frontend/webv2/src/workbench/generation/graphBuilder.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.ts@@ -2,8 +2,8 @@ import type {BackendGraphContract,BackendGraphEdgeContract,BackendInvocationContract,- ProjectSettings,-} from '@workbench/types';+ GenerationProjectSettings,+} from '@features/generation/core/contracts';import type { GenerateLora, GenerateModelConfig, GenerateSettings } from './types';@@ -61,7 +61,7 @@ export const addMetadata = (settings: GenerateSettings,model: GenerateModelConfig,generationMode: string | null,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>,+ projectSettings: GenerationProjectSettings,extras: Record<string, unknown> = {}) => {const activeLoras = getActiveCompatibleLoras(settings, model);diff --git a/invokeai/frontend/webv2/src/workbench/generation/projectPromptDraft.test.ts b/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/projectPromptDraft.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/projectPromptDraft.ts b/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.tssimilarity index 89%rename from invokeai/frontend/webv2/src/workbench/generation/projectPromptDraft.tsrename to invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.tsindex d7caa493a6..197e4ebef5 100644--- a/invokeai/frontend/webv2/src/workbench/generation/projectPromptDraft.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.ts@@ -1,7 +1,3 @@-import type { Project } from '@workbench/types';--import { getProjectWidgetValues } from '@workbench/widgetState';-export interface ProjectPromptDraft {negativePrompt: string;negativePromptEnabled: boolean;@@ -16,9 +12,6 @@ export const getPromptDraftFromValues = (values: Record<string, unknown>): ProjepositivePrompt: typeof values.positivePrompt === 'string' ? values.positivePrompt : '',});-export const getProjectPromptDraft = (project: Project): ProjectPromptDraft =>- getPromptDraftFromValues(getProjectWidgetValues(project, 'generate'));-export const areProjectPromptDraftsEqual = (left: ProjectPromptDraft, right: ProjectPromptDraft): boolean =>left.positivePrompt === right.positivePrompt &&left.negativePrompt === right.negativePrompt &&diff --git a/invokeai/frontend/webv2/src/workbench/generation/prompt/ast.test.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/ast.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/prompt/ast.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/prompt/ast.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/prompt/ast.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/ast.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/prompt/ast.tsrename to invokeai/frontend/webv2/src/features/generation/core/prompt/ast.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/prompt/attention.test.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/prompt/attention.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/prompt/attention.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/prompt/attention.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/prompt/attention.tsrename to invokeai/frontend/webv2/src/features/generation/core/prompt/attention.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/prompt/highlight.test.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/prompt/highlight.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/prompt/highlight.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/prompt/highlight.tsrename to invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/promptHistory.ts b/invokeai/frontend/webv2/src/features/generation/core/promptHistory.tssimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/generation/promptHistory.tsrename to invokeai/frontend/webv2/src/features/generation/core/promptHistory.tsindex 7b9fefdc02..b0de160b99 100644--- a/invokeai/frontend/webv2/src/workbench/generation/promptHistory.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/promptHistory.ts@@ -1,4 +1,4 @@-import type { PromptHistoryItem } from '@workbench/types';+import type { PromptHistoryItem } from '@features/generation/core/contracts';import type { GenerateSettings } from './types';diff --git a/invokeai/frontend/webv2/src/workbench/generation/promptUtilities.ts b/invokeai/frontend/webv2/src/features/generation/core/promptUtilities.tssimilarity index 93%rename from invokeai/frontend/webv2/src/workbench/generation/promptUtilities.tsrename to invokeai/frontend/webv2/src/features/generation/core/promptUtilities.tsindex de73b9bab1..00b712d8bd 100644--- a/invokeai/frontend/webv2/src/workbench/generation/promptUtilities.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/promptUtilities.ts@@ -1,4 +1,4 @@-import { apiFetchJson } from '@workbench/backend/http';+import { apiFetchJson } from '@platform/transport/http';export interface ExpandPromptRequest {prompt: string;diff --git a/invokeai/frontend/webv2/src/workbench/generation/referenceImage.test.ts b/invokeai/frontend/webv2/src/features/generation/core/referenceImage.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/referenceImage.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/referenceImage.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/referenceImage.ts b/invokeai/frontend/webv2/src/features/generation/core/referenceImage.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/generation/referenceImage.tsrename to invokeai/frontend/webv2/src/features/generation/core/referenceImage.tsindex c9f61390eb..48dba8feda 100644--- a/invokeai/frontend/webv2/src/workbench/generation/referenceImage.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/referenceImage.ts@@ -1,6 +1,6 @@-import type { GeneratedImageContract } from '@workbench/types';+import type { GeneratedImageContract } from '@features/gallery';-import { getImageFullUrl, getImageThumbnailUrl } from '@workbench/gallery/api';+import { galleryImageUrls } from '@features/gallery/utility';import type { CroppableImageWithDims, ImageWithDims } from './types';@@ -196,5 +196,5 @@ export const clearReferenceImageCrop = (image: CroppableImageWithDims): Croppablexport const getReferenceImageUrls = (image: CroppableImageWithDims) => {const { image_name } = getEffectiveReferenceImage(image);- return { imageUrl: getImageFullUrl(image_name), thumbnailUrl: getImageThumbnailUrl(image_name) };+ return { imageUrl: galleryImageUrls.full(image_name), thumbnailUrl: galleryImageUrls.thumbnail(image_name) };};diff --git a/invokeai/frontend/webv2/src/workbench/generation/settings.test.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.test.tssimilarity index 94%rename from invokeai/frontend/webv2/src/workbench/generation/settings.test.tsrename to invokeai/frontend/webv2/src/features/generation/core/settings.test.tsindex a55a77b965..b7395bc9ce 100644--- a/invokeai/frontend/webv2/src/workbench/generation/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts@@ -185,6 +185,25 @@ describe('normalizeGenerateSettings', () => {expect(normalized?.qwen3EncoderModel).toBeNull();expect(normalized?.vae).toBeNull();});++ it('is idempotent across persisted-value variations', () => {+ for (let index = 0; index < 128; index += 1) {+ const first = normalizeGenerateSettings({+ ...legacyStoredValues,+ aspectRatioId: index % 3 === 0 ? 'bogus' : index % 2 === 0 ? '1:1' : 'Free',+ batchCount: (index % 20) + 1,+ cfgScale: (index % 30) / 2,+ height: 64 + ((index * 8) % 1984),+ negativePromptEnabled: index % 2 === 0,+ seed: index * 7919,+ shouldRandomizeSeed: index % 5 === 0,+ width: 64 + ((index * 16) % 1984),+ });++ expect(first).not.toBeNull();+ expect(normalizeGenerateSettings(first)).toEqual(first);+ }+ });});describe('Generate widget value snapshots', () => {diff --git a/invokeai/frontend/webv2/src/workbench/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/settings.tsrename to invokeai/frontend/webv2/src/features/generation/core/settings.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/types.ts b/invokeai/frontend/webv2/src/features/generation/core/types.tssimilarity index 74%rename from invokeai/frontend/webv2/src/workbench/generation/types.tsrename to invokeai/frontend/webv2/src/features/generation/core/types.tsindex c70244814b..1542acfc90 100644--- a/invokeai/frontend/webv2/src/workbench/generation/types.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts@@ -1,4 +1,4 @@-import type { BackendGraphContract, GeneratedImageContract, GraphContract, ResultDestination } from '@workbench/types';+import type { BackendGraphContract, GraphContract } from '@features/generation/core/contracts';export type ModelIdentifierConfig = {key: string;@@ -87,9 +87,6 @@ export interface CroppableImageWithDims {/** Canonical persisted/metadata asset for global Generate reference images. */export type GenerateReferenceImageAsset = CroppableImageWithDims;-/** Canvas regional guidance intentionally keeps its flat, URL-bearing image contract. */-export type RegionalGuidanceReferenceImageAsset = GeneratedImageContract;-export type ClipVisionModel = 'ViT-H' | 'ViT-G' | 'ViT-L';export type IPAdapterMethod = 'full' | 'style' | 'composition' | 'style_strong' | 'style_precise';@@ -131,16 +128,6 @@ export interface GenerateReferenceImage {config: GenerateReferenceImageConfig;}-export type RegionalGuidanceReferenceImageConfig =- | IPAdapterReferenceImageConfig<RegionalGuidanceReferenceImageAsset>- | FluxReduxReferenceImageConfig<RegionalGuidanceReferenceImageAsset>;--export interface RegionalGuidanceReferenceImage {- id: string;- isEnabled: boolean;- config: RegionalGuidanceReferenceImageConfig;-}-export type VaePrecision = 'fp16' | 'fp32';export type AspectRatioId =@@ -211,52 +198,3 @@ export interface CompiledGenerateGraph {positivePromptNodeId: string;seedNodeId: string;}--export interface EnqueueGenerateResult {- batchId?: string;- enqueued: number;- itemIds: number[];- requested: number;-}--export interface QueueItemDTO {- item_id: number;- status: 'pending' | 'in_progress' | 'completed' | 'failed' | 'canceled';- batch_id?: string;- origin?: string | null;- destination?: string | null;- error_type?: string | null;- error_message?: string | null;- session?: {- prepared_source_mapping?: Record<string, string>;- results: Record<string, unknown>;- };-}--/** A source-agnostic graph submission (used by the workflow source). */-export interface EnqueueWorkflowRequest {- batchCount: number;- destination: ResultDestination;- graph: BackendGraphContract;- projectId: string;- sourceQueueItemId: string;-}--export interface EnqueueGenerateRequest {- batchCount: number;- destination: ResultDestination;- graph: BackendGraphContract;- negativePrompt: string;- negativePromptNodeId: string;- positivePrompt: string;- positivePromptNodeId: string;- seed: number;- seedNodeId: string;- shouldRandomizeSeed: boolean;- projectId: string;- sourceQueueItemId: string;-}--export interface ImageDTO extends GeneratedImageContract {- isIntermediate: boolean;-}diff --git a/invokeai/frontend/webv2/src/features/generation/draft-values.ts b/invokeai/frontend/webv2/src/features/generation/draft-values.tsnew file mode 100644index 0000000000..52dcde6ca6--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/draft-values.ts@@ -0,0 +1 @@+export { useDebouncedDraftValue } from './ui/useDebouncedDraftValue';diff --git a/invokeai/frontend/webv2/src/features/generation/drafts.ts b/invokeai/frontend/webv2/src/features/generation/drafts.tsnew file mode 100644index 0000000000..4f046f605d--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/drafts.ts@@ -0,0 +1 @@+export { flushGenerateDrafts, useRegisterGenerateDraftFlusher } from './ui/generateDraftRegistry';diff --git a/invokeai/frontend/webv2/src/features/generation/form.ts b/invokeai/frontend/webv2/src/features/generation/form.tsnew file mode 100644index 0000000000..649489a358--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/form.ts@@ -0,0 +1,5 @@+export {+ createGenerateFormValuesSelector,+ getGenerateFormCommitPatch,+ getSettingsWithLatestPromptFields,+} from './ui/generateFormViewModel';diff --git a/invokeai/frontend/webv2/src/features/generation/graph.ts b/invokeai/frontend/webv2/src/features/generation/graph.tsnew file mode 100644index 0000000000..97351ddbc8--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/graph.ts@@ -0,0 +1,2 @@+export * from './core/graph';+export * from './core/graphBuilder';diff --git a/invokeai/frontend/webv2/src/features/generation/hotkeys.ts b/invokeai/frontend/webv2/src/features/generation/hotkeys.tsnew file mode 100644index 0000000000..ebc76c5953--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/hotkeys.ts@@ -0,0 +1,3 @@+export { adjustFocusedPromptAttention } from './ui/promptFields/promptAttentionHotkeys';+export { focusPositivePrompt } from './ui/promptFields/promptFocus';+export { promptHistoryNavigation } from './ui/promptFields/promptHistoryNavigation';diff --git a/invokeai/frontend/webv2/src/features/generation/index.ts b/invokeai/frontend/webv2/src/features/generation/index.tsnew file mode 100644index 0000000000..281d338ce5--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/index.ts@@ -0,0 +1,2 @@+export { compileGenerateGraph, resolveGenerateSeed } from './core/graph';+export { getGenerationModelAvailabilityReasons, getGenerationValidationReasons } from './core/baseGenerationPolicies';diff --git a/invokeai/frontend/webv2/src/features/generation/prompt-ui.ts b/invokeai/frontend/webv2/src/features/generation/prompt-ui.tsnew file mode 100644index 0000000000..21e75a5e44--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/prompt-ui.ts@@ -0,0 +1,4 @@+export { NegativePromptField } from './ui/promptFields/NegativePromptField';+export { PositivePromptField } from './ui/promptFields/PositivePromptField';+export { PromptTextarea } from './ui/promptFields/PromptTextarea';+export { PROMPT_ATTENTION_TARGET_PROPS } from './ui/promptFields/promptAttentionHotkeys';diff --git a/invokeai/frontend/webv2/src/features/generation/prompt.ts b/invokeai/frontend/webv2/src/features/generation/prompt.tsnew file mode 100644index 0000000000..06ecd3fcc8--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/prompt.ts@@ -0,0 +1,5 @@+export * from './core/prompt/ast';+export * from './core/prompt/attention';+export * from './core/prompt/highlight';+export * from './core/promptHistory';+export * from './core/promptUtilities';diff --git a/invokeai/frontend/webv2/src/features/generation/react.ts b/invokeai/frontend/webv2/src/features/generation/react.tsnew file mode 100644index 0000000000..aa8ded7a19--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/react.ts@@ -0,0 +1,7 @@+export {+ GenerationModelSelect,+ GenerationUiProvider,+ useGenerationUi,+ type GenerationModelSelectProps,+ type GenerationUiAdapter,+} from './ui/GenerationUiContext';diff --git a/invokeai/frontend/webv2/src/features/generation/reference-ui.ts b/invokeai/frontend/webv2/src/features/generation/reference-ui.tsnew file mode 100644index 0000000000..4ab921db38--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/reference-ui.ts@@ -0,0 +1 @@+export { FluxReduxControls } from './ui/reference-images/ReferenceImageControls';diff --git a/invokeai/frontend/webv2/src/features/generation/settings-ui.ts b/invokeai/frontend/webv2/src/features/generation/settings-ui.tsnew file mode 100644index 0000000000..cb0d5c7bf5--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/settings-ui.ts@@ -0,0 +1,4 @@+export {+ GenerateCollapsibleSection,+ GenerateCollapsibleSection as GenerationSettingsSection,+} from './ui/shared/GenerateCollapsibleSection';diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsnew file mode 100644index 0000000000..c64e22c46b--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -0,0 +1,3 @@+export * from './core/baseGenerationPolicies';+export * from './core/componentCompatibility';+export * from './core/settings';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateAdvancedFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsxsimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateAdvancedFields.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsxindex d834201246..a8bacdd142 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateAdvancedFields.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx@@ -1,14 +1,14 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */-import type { GenerateModelConfig, GenerateSettings, VaePrecision } from '@workbench/generation/types';+import type { GenerateModelConfig, GenerateSettings, VaePrecision } from '@features/generation/core/types';import type { ChangeEvent } from 'react';import { Badge, HStack, InputGroup, NativeSelect, NumberInput, Switch } from '@chakra-ui/react';-import { Field } from '@workbench/components/ui';-import { getDefaultGenerateSettings, getGenerationUiPolicy } from '@workbench/generation/baseGenerationPolicies';-import { isVaeModelConfig } from '@workbench/generation/settings';-import { ModelSelect } from '@workbench/models/components';+import { getDefaultGenerateSettings, getGenerationUiPolicy } from '@features/generation/core/baseGenerationPolicies';+import { isVaeModelConfig } from '@features/generation/core/settings';+import { Field } from '@platform/ui';import { useTranslation } from 'react-i18next';+import { GenerationModelSelect as ModelSelect } from './GenerationUiContext';import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';import { ModelDefaultButton } from './shared/ModelDefaultButton';diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateCanvasCompositingSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateCanvasCompositingSection.tsxnew file mode 100644index 0000000000..6d743773df--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateCanvasCompositingSection.tsx@@ -0,0 +1,6 @@+import { useGenerationUi } from './GenerationUiContext';++export const GenerateCanvasCompositingSection = () => {+ const { CanvasCompositingSection, invocationSourceId } = useGenerationUi();+ return invocationSourceId === 'canvas' ? <CanvasCompositingSection /> : null;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateComponentsSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsxsimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateComponentsSection.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsxindex 78ee742fdd..79a0b6eacd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateComponentsSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsx@@ -1,18 +1,18 @@-import type { ComponentModelConfig, GenerateModelConfig, GenerateSettings } from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';+import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';+import type { ComponentModelConfig, GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';import { Stack } from '@chakra-ui/react';-import { Field } from '@workbench/components/ui';import {getComponentSectionPolicy,type ComponentPolicyContext,type ComponentSlotPolicy,-} from '@workbench/generation/baseGenerationPolicies';-import { isMainModelConfig, isModelIdentifierConfig, isVaeModelConfig } from '@workbench/generation/settings';-import { ModelSelect } from '@workbench/models/components';+} from '@features/generation/core/baseGenerationPolicies';+import { isMainModelConfig, isModelIdentifierConfig, isVaeModelConfig } from '@features/generation/core/settings';+import { Field } from '@platform/ui';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { GenerationModelSelect as ModelSelect } from './GenerationUiContext';import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';interface GenerateComponentsSectionProps {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateConceptsSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsxsimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateConceptsSection.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsxindex 4ea747a33e..07829dffd7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateConceptsSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx@@ -1,18 +1,21 @@+import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */-import type { GenerateLora, GenerateModelConfig, GenerateSettings, LoraModelConfig } from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';+import type {+ GenerateLora,+ GenerateModelConfig,+ GenerateSettings,+ LoraModelConfig,+} from '@features/generation/core/types';import { Badge, HStack, InputGroup, NumberInput, Slider, Stack, Switch, Text } from '@chakra-ui/react';-import { Field, IconButton, Tooltip } from '@workbench/components/ui';import {DEFAULT_LORA_WEIGHT_CONFIG,getDefaultLoraWeight,isLoraCompatibleWithModel,isLoraModelConfig,syncGenerateLorasWithModels,-} from '@workbench/generation/settings';-import { getModelBaseColorPalette, getModelBaseLabel } from '@workbench/models/baseIdentity';-import { ModelSelect } from '@workbench/models/components';+} from '@features/generation/core/settings';+import { Field, IconButton, Tooltip } from '@platform/ui';import { Trash2Icon } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -20,6 +23,7 @@ import { useTranslation } from 'react-i18next';import type { GenerateSettingsUpdate } from './generateDebounce';import { useRegisterGenerateDraftFlusher } from './generateDraftRegistry';+import { GenerationModelSelect as ModelSelect, useGenerationUi } from './GenerationUiContext';import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';import { ModelDefaultButton } from './shared/ModelDefaultButton';import { useDebouncedDraftValue } from './useDebouncedDraftValue';@@ -163,6 +167,7 @@ const LoraRow = ({onWeightChange: (weight: number) => void;}) => {const { t } = useTranslation();+ const { getModelBaseColorPalette, getModelBaseLabel } = useGenerationUi();const isActive = lora.isEnabled && isCompatible;const defaultWeight = getDefaultLoraWeight(lora.model);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateDimensionFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsxsimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateDimensionFields.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsxindex f5a949dd39..70bc681239 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateDimensionFields.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx@@ -1,10 +1,9 @@/* eslint-disable react/react-compiler, react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */import type { SelectValueChangeDetails } from '@chakra-ui/react';-import type { AspectRatioId, GenerateModelConfig, GenerateSettings } from '@workbench/generation/types';+import type { AspectRatioId, GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';import { Badge, Box, createListCollection, HStack, Icon, InputGroup, NumberInput, Stack, Text } from '@chakra-ui/react';-import { Field, IconButton, Select, Tooltip } from '@workbench/components/ui';-import { getDefaultGenerateSettings, getGenerationDimensions } from '@workbench/generation/baseGenerationPolicies';+import { getDefaultGenerateSettings, getGenerationDimensions } from '@features/generation/core/baseGenerationPolicies';import {ASPECT_RATIO_MAP,ASPECT_RATIO_OPTIONS,@@ -13,7 +12,8 @@ import {isAspectRatioId,MAX_DIMENSION,MIN_DIMENSION,-} from '@workbench/generation/settings';+} from '@features/generation/core/settings';+import { Field, IconButton, Select, Tooltip } from '@platform/ui';import { ArrowLeftRightIcon, LockIcon, LockOpenIcon, RulerDimensionLineIcon, ScalingIcon } from 'lucide-react';import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateModelFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateModelFields.tsxsimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateModelFields.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/GenerateModelFields.tsxindex 8b4ddf67f4..521c169c4f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateModelFields.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateModelFields.tsx@@ -1,27 +1,26 @@+import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */-import type { GenerateModelConfig, GenerateSettings, VaeModelConfig } from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';+import type { GenerateModelConfig, GenerateSettings, VaeModelConfig } from '@features/generation/core/types';import { HStack, Icon, InputGroup, NumberInput, Stack } from '@chakra-ui/react';-import { Button, Combobox, IconButton, Field, Tooltip } from '@workbench/components/ui';import {getDefaultGenerateSettings,getGenerationModelPolicy,getSettingsWithCompatibleModelSelections,getSettingsWithModelDefaults,isGenerateModelSelectable,-} from '@workbench/generation/baseGenerationPolicies';+} from '@features/generation/core/baseGenerationPolicies';import {getModelDefaultVae,hasModelDefaultVae,isGenerateModelConfig,SEED_MAX,-} from '@workbench/generation/settings';-import { ModelSelect } from '@workbench/models/components';-import { useNotify } from '@workbench/useNotify';+} from '@features/generation/core/settings';+import { Button, Combobox, IconButton, Field, Tooltip } from '@platform/ui';import { ArrowRightLeft, DicesIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';+import { GenerationModelSelect as ModelSelect, useGenerationUi } from './GenerationUiContext';import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';import { ModelDefaultButton } from './shared/ModelDefaultButton';@@ -66,7 +65,7 @@ export const GenerateModelFields = ({vaeModels,}: GenerateModelFieldsProps) => {const { t } = useTranslation();- const notify = useNotify();+ const { notifications } = useGenerationUi();const modelDefaults = selectedModel ? getDefaultGenerateSettings(selectedModel) : null;const policy = getGenerationModelPolicy(selectedModel, settings);@@ -101,7 +100,7 @@ export const GenerateModelFields = ({onCommitSettings(result.settings);if (result.clearedLabels.length > 0) {- notify.info(+ notifications.info(t('widgets.generate.incompatibleSettingsCleared'),t('widgets.generate.incompatibleSettingsClearedDescription', {count: result.clearedLabels.length,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateSettingsForm.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.tsxsimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateSettingsForm.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.tsxindex 00798f42be..cfa6b050aa 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateSettingsForm.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.tsx@@ -1,11 +1,11 @@+import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';/* eslint-disable react/react-compiler */import type {GenerateModelConfig,GenerateSettings,LoraModelConfig,VaeModelConfig,-} from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';+} from '@features/generation/core/types';import { Stack, Text } from '@chakra-ui/react';import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsxsimilarity index 66%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsxindex a3822e70bc..64aabbe495 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx@@ -1,29 +1,28 @@+import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';import type {GenerateModelConfig,GenerateSettings,LoraModelConfig,VaeModelConfig,-} from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';+} from '@features/generation/core/types';import {getAutoFlux2ComponentSourceModel,getDefaultGenerateSettings,isSupportedGenerateModel,-} from '@workbench/generation/baseGenerationPolicies';+} from '@features/generation/core/baseGenerationPolicies';import {isLoraModelConfig,normalizeGenerateSettings,normalizeGenerateWidgetValues,syncGenerateWidgetValuesWithModels,-} from '@workbench/generation/settings';-import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';-import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+} from '@features/generation/core/settings';+import { useMountEffect } from '@platform/react/useMountEffect';import { useCallback, useEffect, useMemo } from 'react';-import { areProjectGenerateFormValuesEqual, getGenerateFormCommitPatch } from './generateFormViewModel';+import { getGenerateFormCommitPatch } from './generateFormViewModel';import { GenerateSettingsForm } from './GenerateSettingsForm';+import { useGenerationUi } from './GenerationUiContext';const getSettingsWithAutoComponentSource = (nextSettings: GenerateSettings,@@ -40,20 +39,16 @@ const getSettingsWithAutoComponentSource = (};export const GenerateWidgetView = () => {- const storedSelection = useActiveProjectSelector(- (project) => ({ projectId: project.id, values: getProjectWidgetValues(project, 'generate') }),- areProjectGenerateFormValuesEqual- );- const projectId = storedSelection.projectId;- const storedValues = storedSelection.values;- const dispatch = useWorkbenchDispatch();- const error = useModelsSelector((snapshot) => snapshot.error);- const models = useModelsSelector((snapshot) => snapshot.models);- const status = useModelsSelector((snapshot) => snapshot.status);+ const ui = useGenerationUi();+ const projectId = ui.activeProjectId;+ const storedValues = ui.generateValues;+ const error = ui.modelsError;+ const models = ui.models;+ const status = ui.modelsStatus;- useEffect(() => {- ensureModelsLoaded();- }, []);+ useMountEffect(() => {+ ui.ensureModelsLoaded();+ });const supportedModels = useMemo<GenerateModelConfig[]>(() => models.filter(isSupportedGenerateModel), [models]);const loraModels = useMemo(@@ -91,12 +86,8 @@ export const GenerateWidgetView = () => {return;}- dispatch({- projectId,- type: 'patchGenerateSettings',- values: getGenerateFormCommitPatch({ ...nextSettings, model }),- });- }, [dispatch, models, projectId, selectedModel, settings, storedValues, supportedModels]);+ ui.patchGenerateSettings(getGenerateFormCommitPatch({ ...nextSettings, model }), projectId);+ }, [models, projectId, selectedModel, settings, storedValues, supportedModels, ui]);const commitSettings = useCallback((nextSettings: GenerateSettings) => {@@ -106,23 +97,22 @@ export const GenerateWidgetView = () => {return;}- dispatch({- projectId,- type: 'patchGenerateSettings',- values: getGenerateFormCommitPatch({+ ui.patchGenerateSettings(+ getGenerateFormCommitPatch({...getSettingsWithAutoComponentSource(nextSettings, model, models),model,}),- });+ projectId+ );},- [dispatch, models, projectId, supportedModels]+ [models, projectId, supportedModels, ui]);const patchSettings = useCallback((values: Partial<GenerateSettings>) => {- dispatch({ projectId, type: 'patchGenerateSettings', values });+ ui.patchGenerateSettings(values, projectId);},- [dispatch, projectId]+ [projectId, ui]);return (diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsxnew file mode 100644index 0000000000..a441e95a35--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx@@ -0,0 +1,76 @@+import type { GenerationModelCatalogItem, PromptHistoryItem } from '@features/generation/contracts';+import type { GenerateSettings } from '@features/generation/core/types';+import type { ComponentType, ReactNode } from 'react';++import { createContext, use } from 'react';++export interface GenerationModelSelectProps {+ className?: string;+ disabled?: boolean;+ excludeKeys?: ReadonlySet<string>;+ filter?: (model: GenerationModelCatalogItem) => boolean;+ id?: string;+ invalid?: boolean;+ isClearable?: boolean;+ modelTypes: string[];+ onChange: (model: GenerationModelCatalogItem | null) => void;+ placeholder?: string;+ showManagerButton?: boolean;+ size?: 'xs' | 'sm' | 'md';+ value: string | null;+}++export interface GenerationSelectedImage {+ imageName: string;+ imageUrl: string;+ thumbnailUrl: string;+}++export interface GenerationUiAdapter {+ CanvasCompositingSection: ComponentType;+ ModelSelect: ComponentType<GenerationModelSelectProps>;+ activeProjectId: string;+ canvasValues: Record<string, unknown>;+ ensureModelsLoaded(): void;+ generateValues: Record<string, unknown>;+ getModelBaseColorPalette(base: string): string;+ getModelBaseLabel(base: string): string;+ invocationSourceId: string;+ models: readonly GenerationModelCatalogItem[];+ modelsError: string | null;+ modelsStatus: 'error' | 'idle' | 'loaded' | 'loading';+ notifications: {+ error(title: string, message?: string): void;+ info(title: string, message?: string): void;+ reportError(error: { area: string; message: string; namespace: 'generation'; projectId?: string }): void;+ };+ patchCanvasValues(values: Record<string, unknown>): void;+ patchGenerateSettings(values: Partial<GenerateSettings>, projectId?: string): void;+ promptHistory: readonly PromptHistoryItem[];+ clearPromptHistory(): void;+ removePromptFromHistory(prompt: PromptHistoryItem): void;+ selectedGalleryImage: GenerationSelectedImage | null;+ showPromptSyntaxHighlighting: boolean;+ touchGalleryImages(): void;+}++const GenerationUiContext = createContext<GenerationUiAdapter | null>(null);++export const GenerationUiProvider = ({ adapter, children }: { adapter: GenerationUiAdapter; children: ReactNode }) => (+ <GenerationUiContext value={adapter}>{children}</GenerationUiContext>+);++export const useGenerationUi = (): GenerationUiAdapter => {+ const adapter = use(GenerationUiContext);++ if (!adapter) {+ throw new Error('Generation UI requires an App-composed GenerationUiProvider.');+ }++ return adapter;+};++export const GenerationModelSelect = (props: GenerationModelSelectProps) => {+ const { ModelSelect } = useGenerationUi();+ return <ModelSelect {...props} />;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateDebounce.ts b/invokeai/frontend/webv2/src/features/generation/ui/generateDebounce.tssimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/generateDebounce.tsrename to invokeai/frontend/webv2/src/features/generation/ui/generateDebounce.tsindex 7c492804ef..454a2be709 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateDebounce.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/generateDebounce.ts@@ -1,4 +1,4 @@-import type { GenerateSettings } from '@workbench/generation/types';+import type { GenerateSettings } from '@features/generation/core/types';export type GenerateSettingsUpdate = Partial<GenerateSettings> | ((settings: GenerateSettings) => GenerateSettings);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateDraftRegistry.ts b/invokeai/frontend/webv2/src/features/generation/ui/generateDraftRegistry.tssimilarity index 82%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/generateDraftRegistry.tsrename to invokeai/frontend/webv2/src/features/generation/ui/generateDraftRegistry.tsindex 75d9547583..0937ef568d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateDraftRegistry.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/generateDraftRegistry.ts@@ -2,4 +2,4 @@export {flushWorkbenchDrafts as flushGenerateDrafts,useRegisterDraftFlusher as useRegisterGenerateDraftFlusher,-} from '@workbench/widgets/draftRegistry';+} from '@platform/react/draftRegistry';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateFormViewModel.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/generateFormViewModel.test.tssimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/generateFormViewModel.test.tsrename to invokeai/frontend/webv2/src/features/generation/ui/generateFormViewModel.test.tsindex d54754930b..7313725e04 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateFormViewModel.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/generateFormViewModel.test.ts@@ -1,4 +1,4 @@-import type { GenerateSettings } from '@workbench/generation/types';+import type { GenerateSettings } from '@features/generation/core/types';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateFormViewModel.ts b/invokeai/frontend/webv2/src/features/generation/ui/generateFormViewModel.tssimilarity index 92%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/generateFormViewModel.tsrename to invokeai/frontend/webv2/src/features/generation/ui/generateFormViewModel.tsindex ea858e4b81..f81888b594 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateFormViewModel.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/generateFormViewModel.ts@@ -1,6 +1,6 @@-import type { GenerateSettings, GenerateWidgetValues } from '@workbench/generation/types';+import type { GenerateSettings, GenerateWidgetValues } from '@features/generation/core/types';-import { createStableSelector } from '@workbench/workbenchSelectors';+import { createStableSelector } from '@platform/state/selectors';const PROMPT_FORM_KEYS = ['negativePrompt',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsxsimilarity index 78%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsxindex b5b76c2335..3722e2ac4b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx@@ -1,9 +1,9 @@-import type { GenerateModelConfig, GenerateSettings } from '@workbench/generation/types';-import type { PromptHistoryItem } from '@workbench/types';+import type { PromptHistoryItem } from '@features/generation/contracts';+import type { GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';import { Stack } from '@chakra-ui/react';-import { getPromptPolicy } from '@workbench/generation/baseGenerationPolicies';-import { useActiveProjectSelector, useWidgetValuesSelector } from '@workbench/WorkbenchContext';+import { getPromptPolicy } from '@features/generation/core/baseGenerationPolicies';+import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';import { useCallback } from 'react';import { NegativePromptField } from './NegativePromptField';@@ -33,13 +33,6 @@ const getPromptValues = (values: Record<string, unknown>): GeneratePromptValuespositivePromptHeightPx: typeof values.positivePromptHeightPx === 'number' ? values.positivePromptHeightPx : 96,});-const arePromptValuesEqual = (left: GeneratePromptValues, right: GeneratePromptValues): boolean =>- left.positivePrompt === right.positivePrompt &&- left.negativePrompt === right.negativePrompt &&- left.positivePromptHeightPx === right.positivePromptHeightPx &&- left.negativePromptHeightPx === right.negativePromptHeightPx &&- left.negativePromptEnabled === right.negativePromptEnabled;-export const GeneratePromptFields = ({onCommit,onCommitImmediate,@@ -47,8 +40,8 @@ export const GeneratePromptFields = ({selectedModel,settings,}: GeneratePromptFieldsProps) => {- const showSyntaxHighlighting = useActiveProjectSelector((project) => project.settings.showPromptSyntaxHighlighting);- const promptValues = useWidgetValuesSelector('generate', getPromptValues, arePromptValuesEqual);+ const { generateValues, showPromptSyntaxHighlighting } = useGenerationUi();+ const promptValues = getPromptValues(generateValues);const promptPolicy = getPromptPolicy(selectedModel, settings);const usePromptHistoryItem = useCallback(@@ -93,7 +86,7 @@ export const GeneratePromptFields = ({loras={settings.loras}projectId={projectId}selectedModel={selectedModel}- showSyntaxHighlighting={showSyntaxHighlighting}+ showSyntaxHighlighting={showPromptSyntaxHighlighting}onChange={handlePositivePromptChange}onResizeEnd={handlePositivePromptResizeEnd}onUsePrompt={usePromptHistoryItem}@@ -106,7 +99,7 @@ export const GeneratePromptFields = ({projectId={projectId}selectedModel={selectedModel}helpText={promptPolicy.negativeHelpText}- showSyntaxHighlighting={showSyntaxHighlighting}+ showSyntaxHighlighting={showPromptSyntaxHighlighting}value={promptValues.negativePrompt}onEnabledChange={handleNegativePromptEnabledChange}onChange={handleNegativePromptChange}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/NegativePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsxsimilarity index 92%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/NegativePromptField.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsxindex 91c02a74e6..5038176244 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/NegativePromptField.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx@@ -1,18 +1,18 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop */-import type { GenerateLora, GenerateModelConfig } from '@workbench/generation/types';+import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';import type { ChangeEvent, KeyboardEvent } from 'react';import { HStack, Switch } from '@chakra-ui/react';-import { Field } from '@workbench/components/ui';-import { useRegisterGenerateDraftFlusher } from '@workbench/widgets/generate/generateDraftRegistry';-import { useDebouncedDraftValue } from '@workbench/widgets/generate/useDebouncedDraftValue';+import { useRegisterGenerateDraftFlusher } from '@features/generation/ui/generateDraftRegistry';+import { useDebouncedDraftValue } from '@features/generation/ui/useDebouncedDraftValue';+import { Field } from '@platform/ui';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { AddPromptTriggerButton, PromptTriggerPopover } from './PositivePromptActions';import { PROMPT_ATTENTION_TARGET_PROPS } from './promptAttentionHotkeys';import { insertPromptText, type PromptTextRange } from './promptFocus';-import { resetPromptHistoryNavigation } from './promptHistoryNavigation';+import { promptHistoryNavigation } from './promptHistoryNavigation';import { PromptTextarea } from './PromptTextarea';const PROMPT_INPUT_DEBOUNCE_MS = 250;@@ -63,7 +63,7 @@ export const NegativePromptField = ({const commitPromptChange = useCallback((nextValue: string) => {- resetPromptHistoryNavigation();+ promptHistoryNavigation.reset();setDraftValue(nextValue);},[setDraftValue]diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsxsimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptActions.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsxindex b611748f17..838560fffd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptActions.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx@@ -1,23 +1,15 @@/* eslint-disable react/react-compiler */-import type { GenerateLora, GenerateModelConfig } from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';-import type { PromptHistoryItem } from '@workbench/types';+import type { GenerationModelCatalogItem as ModelConfig, PromptHistoryItem } from '@features/generation/contracts';+import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';import type { ChangeEvent, MouseEvent } from 'react';import { HStack, Icon, Image, Input, Popover, Portal, Separator, Stack, Text } from '@chakra-ui/react';-import { getApiErrorMessage } from '@workbench/backend/http';-import { Button, IconButton, Scrollable, Tooltip } from '@workbench/components/ui';-import { filterPromptHistory } from '@workbench/generation/promptHistory';-import { expandPrompt, imageToPrompt } from '@workbench/generation/promptUtilities';-import { getSelectedGalleryImage } from '@workbench/image-actions';-import { ModelSelect } from '@workbench/models/components/ModelSelect';-import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';-import {- shallowEqual,- useActiveProjectId,- useActiveProjectSelector,- useWorkbenchDispatch,-} from '@workbench/WorkbenchContext';+import { filterPromptHistory } from '@features/generation/core/promptHistory';+import { expandPrompt, imageToPrompt } from '@features/generation/core/promptUtilities';+import { GenerationModelSelect as ModelSelect, useGenerationUi } from '@features/generation/ui/GenerationUiContext';+import { useMountEffect } from '@platform/react/useMountEffect';+import { getApiErrorMessage } from '@platform/transport/http';+import { Button, IconButton, Scrollable, Tooltip } from '@platform/ui';import {BookDashedIcon,CurlyBracesIcon,@@ -28,7 +20,7 @@ import {TrashIcon,Undo2Icon,} from 'lucide-react';-import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';+import { useCallback, useId, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';const DISABLED_PROMPT_ACTIONS = [@@ -195,7 +187,7 @@ export const PromptTriggerPopover = ({onSelect: (trigger: string) => void;}) => {const { t } = useTranslation();- const models = useModelsSelector((snapshot) => snapshot.models);+ const { ensureModelsLoaded, models } = useGenerationUi();const [searchTerm, setSearchTerm] = useState('');const options = useMemo(@@ -253,9 +245,9 @@ export const PromptTriggerPopover = ({setSearchTerm(event.currentTarget.value);}, []);- useEffect(() => {+ useMountEffect(() => {ensureModelsLoaded();- }, []);+ });return (<Popover.Root lazyMount open={open} positioning={popoverPositioning} unmountOnExit onOpenChange={handleOpenChange}>@@ -344,9 +336,7 @@ const ExpandPromptButton = ({onPositivePromptChange: (prompt: string) => void;}) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();- const models = useModelsSelector((snapshot) => snapshot.models);- const activeProjectId = useActiveProjectId();+ const { activeProjectId, ensureModelsLoaded, models, notifications } = useGenerationUi();const activeProjectIdRef = useRef(activeProjectId);const triggerId = useId();const [isOpen, setIsOpen] = useState(false);@@ -357,9 +347,9 @@ const ExpandPromptButton = ({activeProjectIdRef.current = activeProjectId;- useEffect(() => {+ useMountEffect(() => {ensureModelsLoaded();- }, []);+ });const runExpandPrompt = useCallback(async () => {if (!selectedModel || !positivePrompt.trim()) {@@ -377,17 +367,16 @@ const ExpandPromptButton = ({setIsOpen(false);} catch (error) {- dispatch({+ notifications.reportError({area: 'expand-prompt',message: getApiErrorMessage(error, t('widgets.generate.couldNotExpandPrompt')),namespace: 'generation',projectId,- type: 'recordError',});} finally {setIsLoading(false);}- }, [dispatch, onPositivePromptChange, positivePrompt, projectId, selectedModel, t]);+ }, [notifications, onPositivePromptChange, positivePrompt, projectId, selectedModel, t]);const popoverIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);const handleOpenChange = useCallback((event: { open: boolean }) => setIsOpen(event.open), []);@@ -468,10 +457,13 @@ const ImageToPromptButton = ({onPositivePromptChange: (prompt: string) => void;}) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();- const models = useModelsSelector((snapshot) => snapshot.models);- const selectedImage = useActiveProjectSelector(getSelectedGalleryImage, shallowEqual);- const activeProjectId = useActiveProjectId();+ const {+ activeProjectId,+ ensureModelsLoaded,+ models,+ notifications,+ selectedGalleryImage: selectedImage,+ } = useGenerationUi();const activeProjectIdRef = useRef(activeProjectId);const triggerId = useId();const [isOpen, setIsOpen] = useState(false);@@ -482,9 +474,9 @@ const ImageToPromptButton = ({activeProjectIdRef.current = activeProjectId;- useEffect(() => {+ useMountEffect(() => {ensureModelsLoaded();- }, []);+ });const runImageToPrompt = useCallback(async () => {if (!selectedImage || !selectedModel) {@@ -502,17 +494,16 @@ const ImageToPromptButton = ({setIsOpen(false);} catch (error) {- dispatch({+ notifications.reportError({area: 'image-to-prompt',message: getApiErrorMessage(error, t('widgets.generate.couldNotGeneratePromptFromImage')),namespace: 'generation',projectId,- type: 'recordError',});} finally {setIsLoading(false);}- }, [dispatch, onPositivePromptChange, projectId, selectedImage, selectedModel, t]);+ }, [notifications, onPositivePromptChange, projectId, selectedImage, selectedModel, t]);const popoverIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);const handleOpenChange = useCallback((event: { open: boolean }) => setIsOpen(event.open), []);@@ -601,8 +592,7 @@ const ImageToPromptButton = ({const PositivePromptHistoryButton = ({ onUsePrompt }: Pick<PositivePromptActionsProps, 'onUsePrompt'>) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();- const promptHistory = useActiveProjectSelector((project) => project.promptHistory);+ const { clearPromptHistory, promptHistory } = useGenerationUi();const historyTriggerId = useId();const [isOpen, setIsOpen] = useState(false);const [searchTerm, setSearchTerm] = useState('');@@ -622,8 +612,6 @@ const PositivePromptHistoryButton = ({ onUsePrompt }: Pick<PositivePromptActions[onUsePrompt]);- const clearPromptHistory = useCallback(() => dispatch({ type: 'clearPromptHistory' }), [dispatch]);-return (<Popover.Rootids={popoverIds}@@ -717,9 +705,9 @@ const PromptHistoryItemRow = ({prompt: PromptHistoryItem;}) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();+ const { removePromptFromHistory } = useGenerationUi();const handleUsePrompt = useCallback(() => onUsePrompt(prompt), [onUsePrompt, prompt]);- const handleDelete = useCallback(() => dispatch({ prompt, type: 'removePromptFromHistory' }), [dispatch, prompt]);+ const handleDelete = useCallback(() => removePromptFromHistory(prompt), [prompt, removePromptFromHistory]);return (<HStack align="start" gap="1.5" pr="1">diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsxsimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsxindex 1629bf1cf0..ba808c3f47 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx@@ -1,17 +1,17 @@-import type { GenerateLora, GenerateModelConfig } from '@workbench/generation/types';-import type { PromptHistoryItem } from '@workbench/types';+import type { PromptHistoryItem } from '@features/generation/contracts';+import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';import type { ChangeEvent, KeyboardEvent } from 'react';-import { Field } from '@workbench/components/ui';-import { useRegisterGenerateDraftFlusher } from '@workbench/widgets/generate/generateDraftRegistry';-import { useDebouncedDraftValue } from '@workbench/widgets/generate/useDebouncedDraftValue';+import { useRegisterGenerateDraftFlusher } from '@features/generation/ui/generateDraftRegistry';+import { useDebouncedDraftValue } from '@features/generation/ui/useDebouncedDraftValue';+import { Field } from '@platform/ui';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { PositivePromptActions, PromptTriggerPopover } from './PositivePromptActions';import { PROMPT_ATTENTION_TARGET_PROPS } from './promptAttentionHotkeys';import { insertPromptText, type PromptTextRange, registerPositivePromptElement } from './promptFocus';-import { resetPromptHistoryNavigation } from './promptHistoryNavigation';+import { promptHistoryNavigation } from './promptHistoryNavigation';import { PromptTextarea } from './PromptTextarea';const PROMPT_INPUT_DEBOUNCE_MS = 250;@@ -58,7 +58,7 @@ export const PositivePromptField = ({const commitPromptChange = useCallback((nextValue: string) => {- resetPromptHistoryNavigation();+ promptHistoryNavigation.reset();setDraftValue(nextValue);},[setDraftValue]@@ -66,7 +66,7 @@ export const PositivePromptField = ({const commitPromptChangeImmediately = useCallback((nextValue: string) => {- resetPromptHistoryNavigation();+ promptHistoryNavigation.reset();commitDraftValue(nextValue);},[commitDraftValue]diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PromptTextarea.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsxsimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PromptTextarea.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsxindex 9071e72471..488b59fceb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PromptTextarea.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx@@ -1,10 +1,10 @@-import type { ResizableTextareaProps } from '@workbench/components/ui';-import type { PromptHighlightKind, PromptHighlightSegment } from '@workbench/generation/prompt/highlight';+import type { PromptHighlightKind, PromptHighlightSegment } from '@features/generation/core/prompt/highlight';+import type { ResizableTextareaProps } from '@platform/ui';import type { Ref, UIEvent } from 'react';import { Box } from '@chakra-ui/react';-import { ResizableTextarea } from '@workbench/components/ui';-import { buildPromptHighlightSegments } from '@workbench/generation/prompt/highlight';+import { buildPromptHighlightSegments } from '@features/generation/core/prompt/highlight';+import { ResizableTextarea } from '@platform/ui';import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';const MAX_HIGHLIGHTED_PROMPT_LENGTH = 20_000;diff --git a/invokeai/frontend/webv2/src/workbench/components/ui/ResizableTextarea.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsxsimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/components/ui/ResizableTextarea.browser.test.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsxindex fb42ba7958..c71d4c552d 100644--- a/invokeai/frontend/webv2/src/workbench/components/ui/ResizableTextarea.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsx@@ -1,16 +1,15 @@import { ChakraProvider } from '@chakra-ui/react';-import { system } from '@theme/system';import {adjustFocusedPromptAttention,PROMPT_ATTENTION_TARGET_PROPS,-} from '@workbench/widgets/generate/promptFields/promptAttentionHotkeys';-import { PromptTextarea } from '@workbench/widgets/generate/promptFields/PromptTextarea';+} from '@features/generation/ui/promptFields/promptAttentionHotkeys';+import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTextarea';+import { ResizableTextarea } from '@platform/ui/ResizableTextarea';+import { system } from '@theme/system';import { act, useCallback, useState, type ChangeEvent } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';-import { ResizableTextarea } from './ResizableTextarea';-let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/index.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/index.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/index.tsrename to invokeai/frontend/webv2/src/features/generation/ui/promptFields/index.tsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptAttentionHotkeys.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptAttentionHotkeys.tssimilarity index 90%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptAttentionHotkeys.tsrename to invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptAttentionHotkeys.tsindex 864340c595..4e742d1b7d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptAttentionHotkeys.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptAttentionHotkeys.ts@@ -1,6 +1,6 @@-import type { PromptAttentionDirection } from '@workbench/generation/prompt/attention';+import type { PromptAttentionDirection } from '@features/generation/core/prompt/attention';-import { adjustPromptAttention } from '@workbench/generation/prompt/attention';+import { adjustPromptAttention } from '@features/generation/core/prompt/attention';export const PROMPT_ATTENTION_TARGET_ATTR = 'data-prompt-attention-target';export const PROMPT_ATTENTION_TARGET_PROPS = { [PROMPT_ATTENTION_TARGET_ATTR]: 'true' } as const;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptFocus.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptFocus.test.tsrename to invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptFocus.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptFocus.tsrename to invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.tsdiff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.tsnew file mode 100644index 0000000000..7d4012dbfa--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.ts@@ -0,0 +1,134 @@+import type { GenerationModelCatalogItem as ModelConfig, PromptHistoryItem } from '@features/generation/contracts';+import type { GenerateModelConfig } from '@features/generation/core/types';++import { getPromptPolicy, isSupportedGenerateModel } from '@features/generation/core/baseGenerationPolicies';+import { normalizeGenerateSettings } from '@features/generation/core/settings';++import { isPositivePromptFocused } from './promptFocus';++type NavigationState = {+ projectId: string;+ historyIndex: number;+ stashedPrompts: {+ negativePrompt: string;+ negativePromptEnabled: boolean;+ positivePrompt: string;+ };+};++interface NavigateOptions {+ direction: -1 | 1;+ patchValues: (values: Record<string, unknown>, projectId: string) => void;+ models: readonly ModelConfig[] | undefined;+ projectId: string;+ promptHistory: readonly PromptHistoryItem[];+ values: Record<string, unknown>;+}++export interface PromptHistoryNavigation {+ navigate(options: NavigateOptions): void;+ reset(): void;+}++const getSelectedGenerateModel = (+ settings: ReturnType<typeof normalizeGenerateSettings>,+ models: readonly ModelConfig[] | undefined+): GenerateModelConfig | undefined => {+ if (!settings || !models) {+ return undefined;+ }++ return models.filter(isSupportedGenerateModel).find((model) => model.key === settings.modelKey);+};++export const createPromptHistoryNavigation = (): PromptHistoryNavigation => {+ let state: NavigationState | null = null;++ const applyHistoryIndex = ({+ patchValues,+ models,+ projectId,+ promptHistory,+ values,+ }: Omit<NavigateOptions, 'direction'>): void => {+ if (!state) {+ return;+ }++ const prompt = promptHistory[state.historyIndex];+ const settings = normalizeGenerateSettings(values);++ if (!prompt || !settings) {+ return;+ }++ const selectedModel = getSelectedGenerateModel(settings, models);+ const promptPolicy = getPromptPolicy(selectedModel, settings);+ const patch: Record<string, unknown> = { positivePrompt: prompt.positivePrompt };++ if (promptPolicy.negativeVisible) {+ patch.negativePrompt = prompt.negativePrompt ?? '';+ patch.negativePromptEnabled = prompt.negativePrompt ? true : settings.negativePromptEnabled;+ }++ patchValues(patch, projectId);+ };++ return {+ navigate({ direction, patchValues, models, projectId, promptHistory, values }) {+ if (state?.projectId !== projectId) {+ state = null;+ }++ if (!isPositivePromptFocused() || promptHistory.length === 0) {+ return;+ }++ const settings = normalizeGenerateSettings(values);++ if (!settings) {+ return;+ }++ if (direction === -1) {+ if (!state) {+ state = {+ historyIndex: 0,+ projectId,+ stashedPrompts: {+ negativePrompt: settings.negativePrompt,+ negativePromptEnabled: settings.negativePromptEnabled,+ positivePrompt: settings.positivePrompt,+ },+ };+ } else if (state.historyIndex < promptHistory.length - 1) {+ state = { ...state, historyIndex: state.historyIndex + 1 };+ }++ applyHistoryIndex({ models, patchValues, projectId, promptHistory, values });+ return;+ }++ if (!state) {+ return;+ }++ const nextHistoryIndex = state.historyIndex - 1;++ if (nextHistoryIndex < 0) {+ patchValues(state.stashedPrompts, projectId);+ state = null;+ return;+ }++ state = { ...state, historyIndex: nextHistoryIndex };+ applyHistoryIndex({ models, patchValues, projectId, promptHistory, values });+ },+ reset() {+ state = null;+ },+ };+};++/** One navigation cursor per window: the hotkey commands and both prompt fields must share it. */+export const promptHistoryNavigation: PromptHistoryNavigation = createPromptHistoryNavigation();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/GenerateReferenceImagesSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsxsimilarity index 88%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/GenerateReferenceImagesSection.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsxindex 9654e043ec..6a4311bc38 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/GenerateReferenceImagesSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx@@ -1,29 +1,29 @@+import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';import type {GenerateModelConfig,GenerateReferenceImage,GenerateReferenceImageAsset,GenerateSettings,-} from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';-import type { GenerateSettingsUpdate } from '@workbench/widgets/generate/generateDebounce';+} from '@features/generation/core/types';+import type { GenerateSettingsUpdate } from '@features/generation/ui/generateDebounce';import type { ChangeEvent } from 'react';import { Badge, Box, HStack, Input, Stack, Text } from '@chakra-ui/react';import { useDndMonitor, useDroppable } from '@dnd-kit/core';-import { Button, IconButton, Tooltip } from '@workbench/components/ui';-import { getGalleryImagesByNames, uploadGalleryImage } from '@workbench/gallery/api';+import { galleryImages, galleryTransfers } from '@features/gallery';+import { isGalleryImageDragData } from '@features/gallery/utility';import {createReferenceImageId,getDefaultReferenceImageConfig,getGenerationDimensions,getMaxReferenceImages,isReferenceImageSupported,-} from '@workbench/generation/baseGenerationPolicies';-import { generatedImageToReferenceImage, getEffectiveReferenceImage } from '@workbench/generation/referenceImage';-import { clampDimension, deriveAspectRatioId } from '@workbench/generation/settings';-import { isGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';-import { GenerateCollapsibleSection } from '@workbench/widgets/generate/shared/GenerateCollapsibleSection';-import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';+} from '@features/generation/core/baseGenerationPolicies';+import { generatedImageToReferenceImage, getEffectiveReferenceImage } from '@features/generation/core/referenceImage';+import { clampDimension, deriveAspectRatioId } from '@features/generation/core/settings';+import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';+import { GenerateCollapsibleSection } from '@features/generation/ui/shared/GenerateCollapsibleSection';+import { Button, IconButton, Tooltip } from '@platform/ui';import { ScanIcon, UploadIcon } from 'lucide-react';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';@@ -48,7 +48,7 @@ export const GenerateReferenceImagesSection = ({settings,}: GenerateReferenceImagesSectionProps) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();+ const { notifications, touchGalleryImages } = useGenerationUi();const fileInputRef = useRef<HTMLInputElement | null>(null);const referenceImages = settings.referenceImages;const isSupported = isReferenceImageSupported(selectedModel);@@ -140,21 +140,20 @@ export const GenerateReferenceImagesSection = ({try {const uploaded = await Promise.all(- files.slice(0, maxReferenceImages - referenceImageCount).map((file) => uploadGalleryImage(file, 'none'))+ files.slice(0, maxReferenceImages - referenceImageCount).map((file) => galleryTransfers.upload(file, 'none')));appendReferenceImages(uploaded.map(generatedImageToReferenceImage));- dispatch({ type: 'touchGalleryImagesRefresh' });+ touchGalleryImages();} catch (error) {- dispatch({+ notifications.reportError({area: 'reference-images',message: error instanceof Error ? error.message : String(error),namespace: 'generation',- type: 'recordError',});}},- [appendReferenceImages, canAdd, dispatch, maxReferenceImages, referenceImageCount]+ [appendReferenceImages, canAdd, maxReferenceImages, notifications, referenceImageCount, touchGalleryImages]);const handleUploadZoneClick = useCallback(() => {@@ -176,7 +175,7 @@ export const GenerateReferenceImagesSection = ({return;}- const images = await getGalleryImagesByNames(imageNames.slice(0, maxReferenceImages - referenceImageCount));+ const images = await galleryImages.resolveMany(imageNames.slice(0, maxReferenceImages - referenceImageCount));if (images.length > 0) {appendReferenceImages(images.map(generatedImageToReferenceImage));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCard.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsxsimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCard.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsxindex 81715e75a3..7604552d16 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCard.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx@@ -1,16 +1,16 @@+import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';import type {GenerateModelConfig,GenerateReferenceImage,GenerateReferenceImageAsset,GenerateReferenceImageConfig,-} from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';+} from '@features/generation/core/types';import type { CSSProperties } from 'react';import { Box, HStack, Icon, Stack, Text } from '@chakra-ui/react';-import { IconButton, ToggleDot, Tooltip } from '@workbench/components/ui';-import { getEffectiveReferenceImage, getReferenceImageUrls } from '@workbench/generation/referenceImage';-import { ModelSelect } from '@workbench/models/components';+import { getEffectiveReferenceImage, getReferenceImageUrls } from '@features/generation/core/referenceImage';+import { GenerationModelSelect as ModelSelect } from '@features/generation/ui/GenerationUiContext';+import { IconButton, ToggleDot, Tooltip } from '@platform/ui';import { ChevronDownIcon, CropIcon, ImageIcon, RulerIcon, Trash2Icon } from 'lucide-react';import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageControls.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsxsimilarity index 99%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageControls.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsxindex 3ce35a2eac..250222ceb6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageControls.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsx@@ -4,7 +4,7 @@ import type {FluxReduxImageInfluence,GenerateReferenceImageConfig,IPAdapterMethod,-} from '@workbench/generation/types';+} from '@features/generation/core/types';import type { KeyboardEvent, ReactNode } from 'react';import {@@ -17,7 +17,7 @@ import {Stack,Text,} from '@chakra-ui/react';-import { Field, Select, Slider } from '@workbench/components/ui';+import { Field, Select, Slider } from '@platform/ui';import { ChevronRightIcon } from 'lucide-react';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCropDialog.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.test.tssimilarity index 77%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCropDialog.test.tsrename to invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.test.tsindex 5656472143..4a9d3e00e6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCropDialog.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.test.ts@@ -1,12 +1,17 @@import { afterEach, describe, expect, it, vi } from 'vitest';const galleryApi = vi.hoisted(() => ({- getImageFullUrl: vi.fn((imageName: string) => `/full/${imageName}`),- getImageThumbnailUrl: vi.fn((imageName: string) => `/thumbnail/${imageName}`),- uploadGalleryImage: vi.fn(),+ galleryTransfers: { upload: vi.fn() },+}));+const galleryUtility = vi.hoisted(() => ({+ galleryImageUrls: {+ full: vi.fn((imageName: string) => `/full/${imageName}`),+ thumbnail: vi.fn((imageName: string) => `/thumbnail/${imageName}`),+ },}));-vi.mock('@workbench/gallery/api', () => galleryApi);+vi.mock('@features/gallery', () => galleryApi);+vi.mock('@features/gallery/utility', () => galleryUtility);import { applyReferenceImageCropSelection, exportCroppedReferenceImage } from './ReferenceImageCropDialog';@@ -50,7 +55,7 @@ const stubCropBrowserApis = (onLoadUrl?: (url: string) => void) => {};afterEach(() => {- galleryApi.uploadGalleryImage.mockReset();+ galleryApi.galleryTransfers.upload.mockReset();vi.unstubAllGlobals();});@@ -71,11 +76,13 @@ describe('ReferenceImageCropDialog', () => {it('uploads an applied crop as intermediate and preserves the original', async () => {stubCropBrowserApis();- galleryApi.uploadGalleryImage.mockResolvedValue({ height: 300, imageName: 'new-crop.png', width: 400 });+ galleryApi.galleryTransfers.upload.mockResolvedValue({ height: 300, imageName: 'new-crop.png', width: 400 });const result = await applyReferenceImageCropSelection(image, cropBox);- expect(galleryApi.uploadGalleryImage).toHaveBeenCalledWith(expect.any(File), 'none', { isIntermediate: true });+ expect(galleryApi.galleryTransfers.upload).toHaveBeenCalledWith(expect.any(File), 'none', {+ isIntermediate: true,+ });expect(result).toEqual({crop: {box: { height: 300, width: 400, x: 200, y: 60 },diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCropDialog.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsxsimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCropDialog.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsxindex ce14b1ba6b..c052691c15 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCropDialog.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx@@ -1,9 +1,8 @@-import type { GenerateReferenceImageAsset } from '@workbench/generation/types';+import type { GenerateReferenceImageAsset } from '@features/generation/core/types';import type { CSSProperties, PointerEvent } from 'react';import { Box, Dialog, Portal, Stack, Text } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';-import { uploadGalleryImage } from '@workbench/gallery/api';+import { galleryTransfers } from '@features/gallery';import {FULL_REFERENCE_IMAGE_CROP_BOX,generatedImageToReferenceImage,@@ -12,8 +11,9 @@ import {isFullReferenceImageCropBox,resolveReferenceImageCrop,type ReferenceImageCropBoxPct,-} from '@workbench/generation/referenceImage';-import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';+} from '@features/generation/core/referenceImage';+import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';+import { Button } from '@platform/ui';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -142,7 +142,7 @@ export const applyReferenceImageCropSelection = async (}const file = await exportCroppedReferenceImage(image, cropBox);- const croppedImage = await uploadGalleryImage(file, 'none', { isIntermediate: true });+ const croppedImage = await galleryTransfers.upload(file, 'none', { isIntermediate: true });return resolveReferenceImageCrop(image, cropBox, generatedImageToReferenceImage(croppedImage).original.image);};@@ -159,7 +159,7 @@ export const ReferenceImageCropDialog = ({onClose: () => void;}) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();+ const { notifications, touchGalleryImages } = useGenerationUi();const [cropBox, setCropBox] = useState<ReferenceImageCropBoxPct>(() => getReferenceImageCropBoxPct(image));const [isApplying, setIsApplying] = useState(false);const containerRef = useRef<HTMLDivElement | null>(null);@@ -249,20 +249,19 @@ export const ReferenceImageCropDialog = ({try {setIsApplying(true);const croppedImage = await applyReferenceImageCropSelection(image, cropBox);- dispatch({ type: 'touchGalleryImagesRefresh' });+ touchGalleryImages();onApply(croppedImage);onClose();} catch (error) {- dispatch({+ notifications.reportError({area: 'reference-images',message: error instanceof Error ? error.message : String(error),namespace: 'generation',- type: 'recordError',});} finally {setIsApplying(false);}- }, [close, cropBox, dispatch, image, onApply, onClose]);+ }, [close, cropBox, image, notifications, onApply, onClose, touchGalleryImages]);return (<Dialog.Root lazyMount open={isOpen} placement="center" size="lg" unmountOnExit onOpenChange={handleOpenChange}>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/referenceImageConfig.ts b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageConfig.tssimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/referenceImageConfig.tsrename to invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageConfig.tsindex 11dccdfba6..6a3f90e181 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/referenceImageConfig.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageConfig.ts@@ -1,4 +1,4 @@-import type { ClipVisionModel, IPAdapterMethod } from '@workbench/generation/types';+import type { ClipVisionModel, IPAdapterMethod } from '@features/generation/core/types';/** The coarse mode shown in the segmented control. `style` covers all style method variants. */export type ReferenceMode = 'style' | 'composition' | 'full';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/AspectRatioPreview.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioPreview.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/shared/AspectRatioPreview.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioPreview.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/GenerateCollapsibleSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/shared/GenerateCollapsibleSection.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/ModelDefaultButton.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/ModelDefaultButton.tsxsimilarity index 94%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/shared/ModelDefaultButton.tsxrename to invokeai/frontend/webv2/src/features/generation/ui/shared/ModelDefaultButton.tsxindex fedca8e97a..99459843a4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/ModelDefaultButton.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/ModelDefaultButton.tsx@@ -1,5 +1,5 @@import { Icon } from '@chakra-ui/react';-import { IconButton, Tooltip } from '@workbench/components/ui';+import { IconButton, Tooltip } from '@platform/ui';import { SparklesIcon } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/useDebouncedDraftValue.ts b/invokeai/frontend/webv2/src/features/generation/ui/useDebouncedDraftValue.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/useDebouncedDraftValue.tsrename to invokeai/frontend/webv2/src/features/generation/ui/useDebouncedDraftValue.tsdiff --git a/invokeai/frontend/webv2/src/features/generation/utility.ts b/invokeai/frontend/webv2/src/features/generation/utility.tsnew file mode 100644index 0000000000..8521e9d0fb--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/utility.ts@@ -0,0 +1,2 @@+export * from './core/projectPromptDraft';+export * from './core/referenceImage';diff --git a/invokeai/frontend/webv2/src/features/generation/widget.ts b/invokeai/frontend/webv2/src/features/generation/widget.tsnew file mode 100644index 0000000000..ccbfcd754d--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/widget.ts@@ -0,0 +1 @@+export { GenerateWidgetView } from './ui/GenerateWidgetView';diff --git a/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts b/invokeai/frontend/webv2/src/features/identity/capabilities.test.tsnew file mode 100644index 0000000000..6cfc0bf7ca--- /dev/null+++ b/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';++import type { AuthSession } from './session';++import { getCapabilities } from './capabilities';++const session = (overrides: Partial<AuthSession>): AuthSession => ({+ multiuserEnabled: true,+ phase: 'ready',+ sessionExpired: false,+ setupRequired: false,+ strictPasswordChecking: false,+ user: null,+ ...overrides,+});++describe('Identity route capabilities', () => {+ it('allows all local management in single-user mode', () => {+ expect(getCapabilities(session({ multiuserEnabled: false }))).toEqual({+ canManageModels: true,+ canManageNodes: true,+ canManageUsers: false,+ });+ });++ it('limits multi-user administration to admins', () => {+ const baseUser = {+ created_at: '',+ display_name: null,+ email: '[email protected]',+ is_active: true,+ last_login_at: null,+ updated_at: '',+ user_id: 'user',+ };++ expect(getCapabilities(session({ user: { ...baseUser, is_admin: false } }))).toEqual({+ canManageModels: false,+ canManageNodes: false,+ canManageUsers: false,+ });+ expect(getCapabilities(session({ user: { ...baseUser, is_admin: true } }))).toEqual({+ canManageModels: true,+ canManageNodes: true,+ canManageUsers: true,+ });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/auth/capabilities.ts b/invokeai/frontend/webv2/src/features/identity/capabilities.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/auth/capabilities.tsrename to invokeai/frontend/webv2/src/features/identity/capabilities.tsdiff --git a/invokeai/frontend/webv2/src/workbench/auth/schemas.test.ts b/invokeai/frontend/webv2/src/features/identity/core/schemas.test.tssimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/auth/schemas.test.tsrename to invokeai/frontend/webv2/src/features/identity/core/schemas.test.tsindex 59c5a1c87c..456cfb8993 100644--- a/invokeai/frontend/webv2/src/workbench/auth/schemas.test.ts+++ b/invokeai/frontend/webv2/src/features/identity/core/schemas.test.ts@@ -1,4 +1,4 @@-import { ApiError, getApiErrorMessage } from '@workbench/backend/http';+import { ApiError, getApiErrorMessage } from '@platform/transport/http';import { describe, expect, it } from 'vitest';import {diff --git a/invokeai/frontend/webv2/src/workbench/auth/schemas.ts b/invokeai/frontend/webv2/src/features/identity/core/schemas.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/auth/schemas.tsrename to invokeai/frontend/webv2/src/features/identity/core/schemas.tsdiff --git a/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.test.ts b/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.test.tsnew file mode 100644index 0000000000..a91723c9aa--- /dev/null+++ b/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.test.ts@@ -0,0 +1,11 @@+import { describe, expect, it } from 'vitest';++import { shouldExpireUnauthorizedSession } from './sessionPolicy';++describe('unauthorized session policy', () => {+ it('expires only an authenticated multi-user session', () => {+ expect(shouldExpireUnauthorizedSession({ multiuserEnabled: true, user: { user_id: 'admin' } })).toBe(true);+ expect(shouldExpireUnauthorizedSession({ multiuserEnabled: true, user: null })).toBe(false);+ expect(shouldExpireUnauthorizedSession({ multiuserEnabled: false, user: null })).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.ts b/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.tsnew file mode 100644index 0000000000..f1c5ee5906--- /dev/null+++ b/invokeai/frontend/webv2/src/features/identity/core/sessionPolicy.ts@@ -0,0 +1,8 @@+export interface UnauthorizedSessionState {+ multiuserEnabled: boolean;+ user: unknown | null;+}++/** Login failures and single-user requests must never expire the active shell session. */+export const shouldExpireUnauthorizedSession = (session: UnauthorizedSessionState): boolean =>+ session.multiuserEnabled && session.user !== null;diff --git a/invokeai/frontend/webv2/src/features/identity/core/tokenStorage.ts b/invokeai/frontend/webv2/src/features/identity/core/tokenStorage.tsnew file mode 100644index 0000000000..61ce7b42fe--- /dev/null+++ b/invokeai/frontend/webv2/src/features/identity/core/tokenStorage.ts@@ -0,0 +1,37 @@+const AUTH_TOKEN_STORAGE_KEY = 'auth_token';++export interface IdentityTokenAdapter {+ clear(): void;+ get(): string | null;+ set(token: string): void;+}++export const getAuthToken = (): string | null => {+ try {+ return window.localStorage.getItem(AUTH_TOKEN_STORAGE_KEY);+ } catch {+ return null;+ }+};++export const setAuthToken = (token: string): void => {+ try {+ window.localStorage.setItem(AUTH_TOKEN_STORAGE_KEY, token);+ } catch {+ // Storage unavailable: the backend session lasts until reload.+ }+};++export const clearAuthToken = (): void => {+ try {+ window.localStorage.removeItem(AUTH_TOKEN_STORAGE_KEY);+ } catch {+ // Nothing to clear if storage is unavailable.+ }+};++export const browserIdentityTokenAdapter: IdentityTokenAdapter = {+ clear: clearAuthToken,+ get: getAuthToken,+ set: setAuthToken,+};diff --git a/invokeai/frontend/webv2/src/features/identity/data/api.test.ts b/invokeai/frontend/webv2/src/features/identity/data/api.test.tsnew file mode 100644index 0000000000..08ac8bab25--- /dev/null+++ b/invokeai/frontend/webv2/src/features/identity/data/api.test.ts@@ -0,0 +1,36 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({ apiFetch: vi.fn(), apiFetchJson: vi.fn() }));++vi.mock('@platform/transport/http', () => ({ apiFetch: mocks.apiFetch, apiFetchJson: mocks.apiFetchJson }));++import { createUser, deleteUser, updateUser } from './api';++describe('Identity user mutations', () => {+ beforeEach(() => {+ mocks.apiFetch.mockReset().mockResolvedValue(new Response());+ mocks.apiFetchJson.mockReset().mockResolvedValue({});+ });++ it('creates users with the backend DTO shape', async () => {+ const request = { display_name: 'Ada', email: '[email protected]', is_admin: true, password: 'secret' };++ await createUser(request);++ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/auth/users', {+ body: JSON.stringify(request),+ method: 'POST',+ });+ });++ it('encodes user ids for update and delete mutations', async () => {+ await updateUser('user/with space', { is_active: false });+ await deleteUser('user/with space');++ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/auth/users/user%2Fwith%20space', {+ body: JSON.stringify({ is_active: false }),+ method: 'PATCH',+ });+ expect(mocks.apiFetch).toHaveBeenCalledWith('/api/v1/auth/users/user%2Fwith%20space', { method: 'DELETE' });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/auth/api.ts b/invokeai/frontend/webv2/src/features/identity/data/api.tssimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/auth/api.tsrename to invokeai/frontend/webv2/src/features/identity/data/api.tsindex b521e1489d..850373e11d 100644--- a/invokeai/frontend/webv2/src/workbench/auth/api.ts+++ b/invokeai/frontend/webv2/src/features/identity/data/api.ts@@ -1,4 +1,4 @@-import { apiFetch, apiFetchJson } from '@workbench/backend/http';+import { apiFetch, apiFetchJson } from '@platform/transport/http';/*** REST surface for the backend's multi-user endpoints (`/api/v1/auth`). Fielddiff --git a/invokeai/frontend/webv2/src/features/identity/index.ts b/invokeai/frontend/webv2/src/features/identity/index.tsnew file mode 100644index 0000000000..cda478966e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/identity/index.ts@@ -0,0 +1,30 @@+export * from './capabilities';+export {+ completeAdminSetup,+ ensureAuthSession,+ getAuthSession,+ getUserStorageScope,+ loginWithCredentials,+ logoutSession,+ useAuthSession,+ type AuthSession,+} from './session';+export type { IdentityTokenAdapter } from './core/tokenStorage';+export * from './transportAdapter';+export {+ createUser,+ deleteUser,+ generatePassword,+ listUsers,+ updateCurrentUser,+ updateUser,+ type ProfileUpdateRequest,+ type UserCreateRequest,+ type UserDTO,+ type UserUpdateRequest,+} from './data/api';+export { AccountMenu } from './ui/AccountMenu';+export { LoginScreen } from './ui/LoginScreen';+export { SessionExpiryGuard } from './ui/SessionExpiryGuard';+export { SetupScreen } from './ui/SetupScreen';+export { UsersPage } from './ui/UsersPage';diff --git a/invokeai/frontend/webv2/src/workbench/auth/session.ts b/invokeai/frontend/webv2/src/features/identity/session.tssimilarity index 86%rename from invokeai/frontend/webv2/src/workbench/auth/session.tsrename to invokeai/frontend/webv2/src/features/identity/session.tsindex 5a6c66eb49..b3a2b96be6 100644--- a/invokeai/frontend/webv2/src/workbench/auth/session.ts+++ b/invokeai/frontend/webv2/src/features/identity/session.ts@@ -1,8 +1,10 @@-import { ApiError, clearAuthToken, getAuthToken, setAuthToken, setUnauthorizedHandler } from '@workbench/backend/http';-import { socketHub } from '@workbench/backend/socketHub';-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';+import { ApiError } from '@platform/transport/http';+import { socketHub } from '@platform/transport/socketHub';-import { getAuthStatus, getCurrentUser, login, logout, setupAdmin, type AuthStatus, type UserDTO } from './api';+import { shouldExpireUnauthorizedSession } from './core/sessionPolicy';+import { browserIdentityTokenAdapter } from './core/tokenStorage';+import { getAuthStatus, getCurrentUser, login, logout, setupAdmin, type AuthStatus, type UserDTO } from './data/api';/*** Session-lived auth state shared by the router guards and shell chrome. When@@ -74,12 +76,12 @@ const resolveSession = async (): Promise<AuthSession> => {const status = await fetchAuthStatus();let user: UserDTO | null = null;- if (status.multiuser_enabled && !status.setup_required && getAuthToken()) {+ if (status.multiuser_enabled && !status.setup_required && browserIdentityTokenAdapter.get()) {try {user = await getCurrentUser();} catch (error) {if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {- clearAuthToken();+ browserIdentityTokenAdapter.clear();}// Any other failure leaves `user` null; the route guard lands on login.}@@ -116,11 +118,11 @@ export const ensureAuthSession = (): Promise<AuthSession> => {export const loginWithCredentials = async (email: string, password: string, rememberMe: boolean): Promise<void> => {// A stale token must not ride along on the login request itself.- clearAuthToken();+ browserIdentityTokenAdapter.clear();const result = await login({ email, password, remember_me: rememberMe });- setAuthToken(result.token);+ browserIdentityTokenAdapter.set(result.token);setActiveUserScope(result.user);store.patchSnapshot({ sessionExpired: false, user: result.user });};@@ -132,7 +134,7 @@ export const logoutSession = async (): Promise<void> => {// Tokens are stateless on the backend; local sign-out always wins.}- clearAuthToken();+ browserIdentityTokenAdapter.clear();// Tear down the shared socket so it does not linger authenticated as the// previous user; the next authenticated mount reconnects with a fresh token.socketHub.disconnect();@@ -158,14 +160,14 @@ export const setSessionUser = (user: UserDTO): void => {// A 401 on any authenticated request means the stored token expired or was// revoked. Only react while an authenticated multi-user session is live, so// failed login attempts and single-user mode never trip it.-setUnauthorizedHandler(() => {+export const handleUnauthorizedResponse = (): void => {const session = store.getSnapshot();- if (!session.multiuserEnabled || session.user === null) {+ if (!shouldExpireUnauthorizedSession(session)) {return;}- clearAuthToken();+ browserIdentityTokenAdapter.clear();socketHub.disconnect();store.patchSnapshot({ sessionExpired: true, user: null });-});+};diff --git a/invokeai/frontend/webv2/src/features/identity/transportAdapter.test.ts b/invokeai/frontend/webv2/src/features/identity/transportAdapter.test.tsnew file mode 100644index 0000000000..0184967fdf--- /dev/null+++ b/invokeai/frontend/webv2/src/features/identity/transportAdapter.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it, vi } from 'vitest';++import type { IdentityTokenAdapter } from './core/tokenStorage';++import { createIdentityTransportAuthAdapter } from './transportAdapter';++describe('Identity transport auth adapter', () => {+ it('gives browser and test token stores the same transport contract', () => {+ let token: string | null = 'test-token';+ const testTokenAdapter: IdentityTokenAdapter = {+ clear: () => {+ token = null;+ },+ get: () => token,+ set: (value) => {+ token = value;+ },+ };+ const onUnauthorized = vi.fn();+ const adapter = createIdentityTransportAuthAdapter(testTokenAdapter, onUnauthorized);++ expect(adapter.getToken()).toBe('test-token');+ testTokenAdapter.set('next-token');+ expect(adapter.getToken()).toBe('next-token');+ adapter.onUnauthorized();+ expect(onUnauthorized).toHaveBeenCalledOnce();+ });+});diff --git a/invokeai/frontend/webv2/src/features/identity/transportAdapter.ts b/invokeai/frontend/webv2/src/features/identity/transportAdapter.tsnew file mode 100644index 0000000000..af5ed12a05--- /dev/null+++ b/invokeai/frontend/webv2/src/features/identity/transportAdapter.ts@@ -0,0 +1,22 @@+import type { IdentityTokenAdapter } from './core/tokenStorage';++import { browserIdentityTokenAdapter } from './core/tokenStorage';+import { handleUnauthorizedResponse } from './session';++export interface IdentityTransportAuthAdapter {+ getToken(): string | null;+ onUnauthorized(): void;+}++export const createIdentityTransportAuthAdapter = (+ token: IdentityTokenAdapter,+ onUnauthorized: () => void+): IdentityTransportAuthAdapter => ({+ getToken: token.get,+ onUnauthorized,+});++export const identityTransportAuthAdapter = createIdentityTransportAuthAdapter(+ browserIdentityTokenAdapter,+ handleUnauthorizedResponse+);diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/AccountMenu.tsx b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsxsimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/auth/components/AccountMenu.tsxrename to invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsxindex 4145911c71..71407e3a3a 100644--- a/invokeai/frontend/webv2/src/workbench/auth/components/AccountMenu.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsx@@ -1,7 +1,7 @@import { Avatar, Badge, Box, chakra, HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';+import { logoutSession, useAuthSession } from '@features/identity/session';+import { MenuContent } from '@platform/ui';import { useNavigate } from '@tanstack/react-router';-import { logoutSession, useAuthSession } from '@workbench/auth/session';-import { MenuContent } from '@workbench/components/ui';import { ChevronDownIcon, LogOutIcon, UserRoundCogIcon, UsersIcon } from 'lucide-react';import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/AuthScreen.tsx b/invokeai/frontend/webv2/src/features/identity/ui/AuthScreen.tsxsimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/auth/components/AuthScreen.tsxrename to invokeai/frontend/webv2/src/features/identity/ui/AuthScreen.tsxindex 6ff8eaabb8..d07590fcbd 100644--- a/invokeai/frontend/webv2/src/workbench/auth/components/AuthScreen.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/AuthScreen.tsx@@ -1,7 +1,7 @@import type { ReactNode } from 'react';import { Alert, Flex, Heading, Stack, Text } from '@chakra-ui/react';-import { InvokeMark } from '@workbench/components/InvokeMark';+import { InvokeMark } from '@platform/ui/InvokeMark';/*** Centered scaffold shared by the login and first-run setup screens. Thesediff --git a/invokeai/frontend/webv2/src/workbench/auth/components/LoginScreen.tsx b/invokeai/frontend/webv2/src/features/identity/ui/LoginScreen.tsxsimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/auth/components/LoginScreen.tsxrename to invokeai/frontend/webv2/src/features/identity/ui/LoginScreen.tsxindex 0201cd4ab0..db4ef3fff0 100644--- a/invokeai/frontend/webv2/src/workbench/auth/components/LoginScreen.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/LoginScreen.tsx@@ -1,10 +1,10 @@import { chakra, Checkbox, Input } from '@chakra-ui/react';+import { loginSchema } from '@features/identity/core/schemas';+import { loginWithCredentials, useAuthSession } from '@features/identity/session';+import { useZodForm } from '@platform/react/useZodForm';+import { getApiErrorMessage } from '@platform/transport/http';+import { Button, Field } from '@platform/ui';import { useNavigate } from '@tanstack/react-router';-import { loginSchema } from '@workbench/auth/schemas';-import { loginWithCredentials, useAuthSession } from '@workbench/auth/session';-import { getApiErrorMessage } from '@workbench/backend/http';-import { Button, Field } from '@workbench/components/ui';-import { useZodForm } from '@workbench/models/useZodForm';import { useCallback, type ChangeEvent, type FormEvent } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/PasswordInput.tsx b/invokeai/frontend/webv2/src/features/identity/ui/PasswordInput.tsxsimilarity index 94%rename from invokeai/frontend/webv2/src/workbench/auth/components/PasswordInput.tsxrename to invokeai/frontend/webv2/src/features/identity/ui/PasswordInput.tsxindex 3dafe2e8b6..5e0abd2abc 100644--- a/invokeai/frontend/webv2/src/workbench/auth/components/PasswordInput.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/PasswordInput.tsx@@ -1,6 +1,6 @@import { Box, HStack, Input, InputGroup, Text } from '@chakra-ui/react';-import { getPasswordStrength, type PasswordStrength } from '@workbench/auth/schemas';-import { IconButton } from '@workbench/components/ui';+import { getPasswordStrength, type PasswordStrength } from '@features/identity/core/schemas';+import { IconButton } from '@platform/ui';import { EyeIcon, EyeOffIcon } from 'lucide-react';import { useCallback, useMemo, useState, type ComponentProps } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/ProfileDialog.tsx b/invokeai/frontend/webv2/src/features/identity/ui/ProfileDialog.tsxsimilarity index 92%rename from invokeai/frontend/webv2/src/workbench/auth/components/ProfileDialog.tsxrename to invokeai/frontend/webv2/src/features/identity/ui/ProfileDialog.tsxindex 6072075dae..822ddb441c 100644--- a/invokeai/frontend/webv2/src/workbench/auth/components/ProfileDialog.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/ProfileDialog.tsx@@ -1,11 +1,16 @@import { Dialog, HStack, Input, Portal, Stack, Text } from '@chakra-ui/react';-import { generatePassword, updateCurrentUser, type ProfileUpdateRequest, type UserDTO } from '@workbench/auth/api';-import { createProfileSchema, PASSWORD_RULES_HINT, type ProfileFormValues } from '@workbench/auth/schemas';-import { setSessionUser, useAuthSession } from '@workbench/auth/session';-import { getApiErrorMessage } from '@workbench/backend/http';-import { Button, CloseButton, Field, FieldLabel } from '@workbench/components/ui';-import { useZodForm } from '@workbench/models/useZodForm';-import { useNotify } from '@workbench/useNotify';+import { createProfileSchema, PASSWORD_RULES_HINT, type ProfileFormValues } from '@features/identity/core/schemas';+import {+ generatePassword,+ updateCurrentUser,+ type ProfileUpdateRequest,+ type UserDTO,+} from '@features/identity/data/api';+import { setSessionUser, useAuthSession } from '@features/identity/session';+import { useIdentityNotify } from '@features/identity/ui/useIdentityNotify';+import { useZodForm } from '@platform/react/useZodForm';+import { getApiErrorMessage } from '@platform/transport/http';+import { Button, CloseButton, Field, FieldLabel } from '@platform/ui';import { WandSparklesIcon } from 'lucide-react';import { useCallback, useMemo, useState, type ChangeEvent } from 'react';import { useTranslation } from 'react-i18next';@@ -63,7 +68,7 @@ export const ProfileDialog = ({ isOpen, onClose, user }: { isOpen: boolean; onClconst ProfileForm = ({ onClose, user }: { onClose: () => void; user: UserDTO }) => {const { t } = useTranslation();const session = useAuthSession();- const notify = useNotify();+ const notify = useIdentityNotify();const [isGenerating, setIsGenerating] = useState(false);const schema = useMemo(() => createProfileSchema(session.strictPasswordChecking), [session.strictPasswordChecking]);const initialValues: ProfileFormValues = useMemo(diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/SessionExpiryGuard.tsx b/invokeai/frontend/webv2/src/features/identity/ui/SessionExpiryGuard.tsxsimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/auth/components/SessionExpiryGuard.tsxrename to invokeai/frontend/webv2/src/features/identity/ui/SessionExpiryGuard.tsxindex 9f34f706ba..0a21be6b7d 100644--- a/invokeai/frontend/webv2/src/workbench/auth/components/SessionExpiryGuard.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/SessionExpiryGuard.tsx@@ -1,5 +1,5 @@+import { useAuthSession } from '@features/identity/session';import { useNavigate } from '@tanstack/react-router';-import { useAuthSession } from '@workbench/auth/session';import { useEffect } from 'react';/**diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/SetupScreen.tsx b/invokeai/frontend/webv2/src/features/identity/ui/SetupScreen.tsxsimilarity index 93%rename from invokeai/frontend/webv2/src/workbench/auth/components/SetupScreen.tsxrename to invokeai/frontend/webv2/src/features/identity/ui/SetupScreen.tsxindex 3e5a32cbd7..4efbc79a7c 100644--- a/invokeai/frontend/webv2/src/workbench/auth/components/SetupScreen.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/SetupScreen.tsx@@ -1,10 +1,10 @@import { chakra, Input, Stack } from '@chakra-ui/react';+import { createSetupSchema, PASSWORD_RULES_HINT, type SetupFormValues } from '@features/identity/core/schemas';+import { completeAdminSetup, useAuthSession } from '@features/identity/session';+import { useZodForm } from '@platform/react/useZodForm';+import { getApiErrorMessage } from '@platform/transport/http';+import { Button, Field } from '@platform/ui';import { useNavigate } from '@tanstack/react-router';-import { createSetupSchema, PASSWORD_RULES_HINT, type SetupFormValues } from '@workbench/auth/schemas';-import { completeAdminSetup, useAuthSession } from '@workbench/auth/session';-import { getApiErrorMessage } from '@workbench/backend/http';-import { Button, Field } from '@workbench/components/ui';-import { useZodForm } from '@workbench/models/useZodForm';import { useCallback, useMemo, type ChangeEvent, type FormEvent } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/users/UserFormDialog.tsx b/invokeai/frontend/webv2/src/features/identity/ui/UserFormDialog.tsxsimilarity index 92%rename from invokeai/frontend/webv2/src/workbench/users/UserFormDialog.tsxrename to invokeai/frontend/webv2/src/features/identity/ui/UserFormDialog.tsxindex 04527fd1f0..235bbcc20c 100644--- a/invokeai/frontend/webv2/src/workbench/users/UserFormDialog.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/UserFormDialog.tsx@@ -1,13 +1,19 @@import { Dialog, HStack, Input, Portal, Stack, Switch, Text } from '@chakra-ui/react';-import { createUser, generatePassword, updateUser, type UserDTO, type UserUpdateRequest } from '@workbench/auth/api';-import { AuthFormAlert } from '@workbench/auth/components/AuthScreen';-import { PasswordInput, PasswordStrengthMeter } from '@workbench/auth/components/PasswordInput';-import { createUserFormSchema, PASSWORD_RULES_HINT, type UserFormValues } from '@workbench/auth/schemas';-import { useAuthSession } from '@workbench/auth/session';-import { getApiErrorMessage } from '@workbench/backend/http';-import { Button, CloseButton, Field } from '@workbench/components/ui';-import { useZodForm } from '@workbench/models/useZodForm';-import { useNotify } from '@workbench/useNotify';+import { createUserFormSchema, PASSWORD_RULES_HINT, type UserFormValues } from '@features/identity/core/schemas';+import {+ createUser,+ generatePassword,+ updateUser,+ type UserDTO,+ type UserUpdateRequest,+} from '@features/identity/data/api';+import { useAuthSession } from '@features/identity/session';+import { AuthFormAlert } from '@features/identity/ui/AuthScreen';+import { PasswordInput, PasswordStrengthMeter } from '@features/identity/ui/PasswordInput';+import { useIdentityNotify } from '@features/identity/ui/useIdentityNotify';+import { useZodForm } from '@platform/react/useZodForm';+import { getApiErrorMessage } from '@platform/transport/http';+import { Button, CloseButton, Field } from '@platform/ui';import { WandSparklesIcon } from 'lucide-react';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -94,7 +100,7 @@ const UserForm = ({}) => {const { t } = useTranslation();const session = useAuthSession();- const notify = useNotify();+ const notify = useIdentityNotify();const [isGenerating, setIsGenerating] = useState(false);const isCreate = target.mode === 'create';const editedUser = target.mode === 'edit' ? target.user : null;diff --git a/invokeai/frontend/webv2/src/workbench/users/UserManagement.tsx b/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsxsimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/users/UserManagement.tsxrename to invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsxindex 661fb92b39..d5d44a75cb 100644--- a/invokeai/frontend/webv2/src/workbench/users/UserManagement.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx@@ -1,10 +1,10 @@/* eslint-disable react/react-compiler */import { Avatar, Badge, Box, Center, Flex, HStack, Spinner, Stack, Switch, Table, Text } from '@chakra-ui/react';-import { deleteUser, listUsers, updateUser, type UserDTO } from '@workbench/auth/api';-import { useAuthSession } from '@workbench/auth/session';-import { getApiErrorMessage } from '@workbench/backend/http';-import { Button, IconButton, ConfirmDialog, Scrollable, Tooltip } from '@workbench/components/ui';-import { useNotify } from '@workbench/useNotify';+import { deleteUser, listUsers, updateUser, type UserDTO } from '@features/identity/data/api';+import { useAuthSession } from '@features/identity/session';+import { useIdentityNotify } from '@features/identity/ui/useIdentityNotify';+import { getApiErrorMessage } from '@platform/transport/http';+import { Button, IconButton, ConfirmDialog, Scrollable, Tooltip } from '@platform/ui';import { PencilIcon, Trash2Icon, UserPlusIcon } from 'lucide-react';import { useCallback, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -50,7 +50,7 @@ export const UsersManagementPanel = () => {const UsersDirectory = ({ currentUserId }: { currentUserId: string }) => {const { t } = useTranslation();- const notify = useNotify();+ const notify = useIdentityNotify();const [users, setUsers] = useState<UserDTO[] | null>(null);const [loadError, setLoadError] = useState<string | null>(null);const [formTarget, setFormTarget] = useState<UserFormTarget | null>(null);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/pages/UsersPage.tsx b/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsxsimilarity index 85%rename from invokeai/frontend/webv2/src/workbench/launchpad/pages/UsersPage.tsxrename to invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsxindex 5a74d4667e..b5580fe7e2 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/pages/UsersPage.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsx@@ -1,10 +1,11 @@import type { SystemStyleObject } from '@chakra-ui/react';import { Box } from '@chakra-ui/react';-import { Scrollable } from '@workbench/components/ui';-import { UsersManagementPanel } from '@workbench/users';+import { Scrollable } from '@platform/ui';import { useTranslation } from 'react-i18next';+import { UsersManagementPanel } from './UserManagement';+/*** Admin-only section: create, edit, and remove users. Mirrors the Projects* page's centered measure and self-scroll so the chrome stays put.diff --git a/invokeai/frontend/webv2/src/features/identity/ui/useIdentityNotify.ts b/invokeai/frontend/webv2/src/features/identity/ui/useIdentityNotify.tsnew file mode 100644index 0000000000..df7aa0d41d--- /dev/null+++ b/invokeai/frontend/webv2/src/features/identity/ui/useIdentityNotify.ts@@ -0,0 +1,19 @@+import { toaster } from '@platform/ui';++export interface IdentityNotify {+ error(title: string, message?: string): void;+ info(title: string, message?: string): void;+ success(title: string, message?: string): void;+}++const createNotice = (type: 'error' | 'info' | 'success') => (title: string, message?: string) => {+ toaster.create({ description: message, title, type });+};++const identityNotify: IdentityNotify = {+ error: createNotice('error'),+ info: createNotice('info'),+ success: createNotice('success'),+};++export const useIdentityNotify = (): IdentityNotify => identityNotify;diff --git a/invokeai/frontend/webv2/src/workbench/models/baseIdentity.test.ts b/invokeai/frontend/webv2/src/features/models/core/baseIdentity.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/models/baseIdentity.test.tsrename to invokeai/frontend/webv2/src/features/models/core/baseIdentity.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/models/baseIdentity.ts b/invokeai/frontend/webv2/src/features/models/core/baseIdentity.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/models/baseIdentity.tsrename to invokeai/frontend/webv2/src/features/models/core/baseIdentity.tsindex d21ab9b71e..42fb3a6dbc 100644--- a/invokeai/frontend/webv2/src/workbench/models/baseIdentity.ts+++ b/invokeai/frontend/webv2/src/features/models/core/baseIdentity.ts@@ -3,7 +3,7 @@ import type { ColorPalette } from '@chakra-ui/react';import type { ModelBase, ModelConfig } from './types';// Model-base identity registry: labels, colors, and scalar display facts only.-// Generation behavior keyed by base lives in @workbench/generation/baseGenerationPolicies.+// Generation behavior keyed by base lives in @features/generation/settings.export interface ModelBaseInfo {base: ModelBase;diff --git a/invokeai/frontend/webv2/src/workbench/models/library.test.ts b/invokeai/frontend/webv2/src/features/models/core/library.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/models/library.test.tsrename to invokeai/frontend/webv2/src/features/models/core/library.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/models/library.ts b/invokeai/frontend/webv2/src/features/models/core/library.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/models/library.tsrename to invokeai/frontend/webv2/src/features/models/core/library.tsdiff --git a/invokeai/frontend/webv2/src/workbench/models/schemas.ts b/invokeai/frontend/webv2/src/features/models/core/schemas.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/models/schemas.tsrename to invokeai/frontend/webv2/src/features/models/core/schemas.tsdiff --git a/invokeai/frontend/webv2/src/workbench/models/taxonomy.ts b/invokeai/frontend/webv2/src/features/models/core/taxonomy.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/models/taxonomy.tsrename to invokeai/frontend/webv2/src/features/models/core/taxonomy.tsdiff --git a/invokeai/frontend/webv2/src/workbench/models/types.ts b/invokeai/frontend/webv2/src/features/models/core/types.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/models/types.tsrename to invokeai/frontend/webv2/src/features/models/core/types.tsdiff --git a/invokeai/frontend/webv2/src/workbench/models/api.test.ts b/invokeai/frontend/webv2/src/features/models/data/api.test.tssimilarity index 79%rename from invokeai/frontend/webv2/src/workbench/models/api.test.tsrename to invokeai/frontend/webv2/src/features/models/data/api.test.tsindex adde067b3d..bf0cfcae40 100644--- a/invokeai/frontend/webv2/src/workbench/models/api.test.ts+++ b/invokeai/frontend/webv2/src/features/models/data/api.test.ts@@ -1,13 +1,18 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { ModelsDataPort } from './transport';+const mocks = vi.hoisted(() => ({+ request: vi.fn(),apiFetchJson: vi.fn(),}));-vi.mock('../backend/http', () => ({- apiFetch: vi.fn(),- apiFetchJson: mocks.apiFetchJson,- buildApiUrl: (path: string) => path,+vi.mock('./transport', () => ({+ browserModelsDataPort: {+ buildUrl: (path: string) => path,+ request: mocks.request,+ requestJson: mocks.apiFetchJson,+ } satisfies ModelsDataPort,}));describe('installModel', () => {diff --git a/invokeai/frontend/webv2/src/workbench/models/api.ts b/invokeai/frontend/webv2/src/features/models/data/api.tssimilarity index 63%rename from invokeai/frontend/webv2/src/workbench/models/api.tsrename to invokeai/frontend/webv2/src/features/models/data/api.tsindex f3cb477066..b9a04121df 100644--- a/invokeai/frontend/webv2/src/workbench/models/api.ts+++ b/invokeai/frontend/webv2/src/features/models/data/api.ts@@ -1,5 +1,3 @@-import { apiFetch, apiFetchJson, buildApiUrl } from '@workbench/backend/http';-import type {BulkDeleteModelsResponse,DeleteOrphanedModelsResponse,@@ -11,43 +9,46 @@ import type {ModelRecordChanges,OrphanedModelInfo,StarterModelResponse,-} from './types';+} from '@features/models/core/types';++import { browserModelsDataPort } from './transport';/** REST client for the backend model manager (`/api/v2/models`). */const MODELS_BASE = '/api/v2/models';+const { buildUrl, request, requestJson } = browserModelsDataPort;export const listModels = async (): Promise<ModelConfig[]> => {- const body = await apiFetchJson<{ models?: ModelConfig[] }>(`${MODELS_BASE}/`);+ const body = await requestJson<{ models?: ModelConfig[] }>(`${MODELS_BASE}/`);return body.models ?? [];};/** Models whose database record points at a file that no longer exists. */export const listMissingModels = async (): Promise<ModelConfig[]> => {- const body = await apiFetchJson<{ models?: ModelConfig[] }>(`${MODELS_BASE}/missing`);+ const body = await requestJson<{ models?: ModelConfig[] }>(`${MODELS_BASE}/missing`);return body.models ?? [];};/** Absolute server path of the models directory; relative model `path`s resolve against it. */-export const getModelsDir = (): Promise<string> => apiFetchJson<string>(`${MODELS_BASE}/models_dir`);+export const getModelsDir = (): Promise<string> => requestJson<string>(`${MODELS_BASE}/models_dir`);export const getModel = (key: string): Promise<ModelConfig> =>- apiFetchJson<ModelConfig>(`${MODELS_BASE}/i/${encodeURIComponent(key)}`);+ requestJson<ModelConfig>(`${MODELS_BASE}/i/${encodeURIComponent(key)}`);export const updateModel = (key: string, changes: ModelRecordChanges): Promise<ModelConfig> =>- apiFetchJson<ModelConfig>(`${MODELS_BASE}/i/${encodeURIComponent(key)}`, {+ requestJson<ModelConfig>(`${MODELS_BASE}/i/${encodeURIComponent(key)}`, {body: JSON.stringify(changes),method: 'PATCH',});export const deleteModel = async (key: string): Promise<void> => {- await apiFetch(`${MODELS_BASE}/i/${encodeURIComponent(key)}`, { method: 'DELETE' });+ await request(`${MODELS_BASE}/i/${encodeURIComponent(key)}`, { method: 'DELETE' });};export const bulkDeleteModels = (keys: string[]): Promise<BulkDeleteModelsResponse> =>- apiFetchJson<BulkDeleteModelsResponse>(`${MODELS_BASE}/i/bulk_delete`, {+ requestJson<BulkDeleteModelsResponse>(`${MODELS_BASE}/i/bulk_delete`, {body: JSON.stringify({ keys }),headers: { 'Content-Type': 'application/json' },method: 'POST',@@ -55,26 +56,24 @@ export const bulkDeleteModels = (keys: string[]): Promise<BulkDeleteModelsRespon/** Re-probe the model files to refresh auto-detected base/type/format. */export const reidentifyModel = (key: string): Promise<ModelConfig> =>- apiFetchJson<ModelConfig>(`${MODELS_BASE}/i/${encodeURIComponent(key)}/reidentify`, { method: 'POST' });+ requestJson<ModelConfig>(`${MODELS_BASE}/i/${encodeURIComponent(key)}/reidentify`, { method: 'POST' });export const convertModelToDiffusers = (key: string): Promise<ModelConfig> =>- apiFetchJson<ModelConfig>(`${MODELS_BASE}/convert/${encodeURIComponent(key)}`, { method: 'PUT' });+ requestJson<ModelConfig>(`${MODELS_BASE}/convert/${encodeURIComponent(key)}`, { method: 'PUT' });/** Stable URL for a model's cover image; cache-busted via updated marker. */export const getModelImageUrl = (key: string, cacheKey?: string): string =>- buildApiUrl(- `${MODELS_BASE}/i/${encodeURIComponent(key)}/image${cacheKey ? `?t=${encodeURIComponent(cacheKey)}` : ''}`- );+ buildUrl(`${MODELS_BASE}/i/${encodeURIComponent(key)}/image${cacheKey ? `?t=${encodeURIComponent(cacheKey)}` : ''}`);export const updateModelImage = async (key: string, image: Blob): Promise<void> => {const formData = new FormData();formData.append('image', image);- await apiFetch(`${MODELS_BASE}/i/${encodeURIComponent(key)}/image`, { body: formData, method: 'PATCH' });+ await request(`${MODELS_BASE}/i/${encodeURIComponent(key)}/image`, { body: formData, method: 'PATCH' });};export const deleteModelImage = async (key: string): Promise<void> => {- await apiFetch(`${MODELS_BASE}/i/${encodeURIComponent(key)}/image`, { method: 'DELETE' });+ await request(`${MODELS_BASE}/i/${encodeURIComponent(key)}/image`, { method: 'DELETE' });};export interface InstallModelRequest {@@ -103,7 +102,7 @@ export const installModel = ({headers['X-Model-Source-Access-Token'] = accessToken;}- return apiFetchJson<ModelInstallJob>(`${MODELS_BASE}/install?${params.toString()}`, {+ return requestJson<ModelInstallJob>(`${MODELS_BASE}/install?${params.toString()}`, {body: JSON.stringify(config ?? {}),headers,method: 'POST',@@ -111,61 +110,61 @@ export const installModel = ({};export const listModelInstalls = (): Promise<ModelInstallJob[]> =>- apiFetchJson<ModelInstallJob[]>(`${MODELS_BASE}/install`);+ requestJson<ModelInstallJob[]>(`${MODELS_BASE}/install`);export const cancelModelInstall = async (id: number): Promise<void> => {- await apiFetch(`${MODELS_BASE}/install/${id}`, { method: 'DELETE' });+ await request(`${MODELS_BASE}/install/${id}`, { method: 'DELETE' });};export const pauseModelInstall = (id: number): Promise<ModelInstallJob> =>- apiFetchJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/pause`, { method: 'POST' });+ requestJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/pause`, { method: 'POST' });export const resumeModelInstall = (id: number): Promise<ModelInstallJob> =>- apiFetchJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/resume`, { method: 'POST' });+ requestJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/resume`, { method: 'POST' });export const restartFailedModelInstall = (id: number): Promise<ModelInstallJob> =>- apiFetchJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/restart_failed`, { method: 'POST' });+ requestJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/restart_failed`, { method: 'POST' });/** Restart a single download part (by its file URL) of an install job. */export const restartModelInstallFile = (id: number, fileSource: string): Promise<ModelInstallJob> =>- apiFetchJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/restart_file`, {+ requestJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/restart_file`, {body: JSON.stringify(fileSource),method: 'POST',});export const pruneCompletedModelInstalls = async (): Promise<void> => {- await apiFetch(`${MODELS_BASE}/install`, { method: 'DELETE' });+ await request(`${MODELS_BASE}/install`, { method: 'DELETE' });};export const scanFolderForModels = (scanPath: string): Promise<FoundModel[]> =>- apiFetchJson<FoundModel[]>(`${MODELS_BASE}/scan_folder?scan_path=${encodeURIComponent(scanPath)}`);+ requestJson<FoundModel[]>(`${MODELS_BASE}/scan_folder?scan_path=${encodeURIComponent(scanPath)}`);export const getHuggingFaceModels = (repo: string): Promise<HuggingFaceModels> =>- apiFetchJson<HuggingFaceModels>(`${MODELS_BASE}/hugging_face?hugging_face_repo=${encodeURIComponent(repo)}`);+ requestJson<HuggingFaceModels>(`${MODELS_BASE}/hugging_face?hugging_face_repo=${encodeURIComponent(repo)}`);export const getStarterModels = (): Promise<StarterModelResponse> =>- apiFetchJson<StarterModelResponse>(`${MODELS_BASE}/starter_models`);+ requestJson<StarterModelResponse>(`${MODELS_BASE}/starter_models`);-export const getHFTokenStatus = (): Promise<HFTokenStatus> => apiFetchJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`);+export const getHFTokenStatus = (): Promise<HFTokenStatus> => requestJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`);export const setHFToken = (token: string): Promise<HFTokenStatus> =>- apiFetchJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`, { body: JSON.stringify({ token }), method: 'POST' });+ requestJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`, { body: JSON.stringify({ token }), method: 'POST' });export const resetHFToken = (): Promise<HFTokenStatus> =>- apiFetchJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`, { method: 'DELETE' });+ requestJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`, { method: 'DELETE' });export const getOrphanedModels = (): Promise<OrphanedModelInfo[]> =>- apiFetchJson<OrphanedModelInfo[]>(`${MODELS_BASE}/sync/orphaned`);+ requestJson<OrphanedModelInfo[]>(`${MODELS_BASE}/sync/orphaned`);export const deleteOrphanedModels = (paths: string[]): Promise<DeleteOrphanedModelsResponse> =>- apiFetchJson<DeleteOrphanedModelsResponse>(`${MODELS_BASE}/sync/orphaned`, {+ requestJson<DeleteOrphanedModelsResponse>(`${MODELS_BASE}/sync/orphaned`, {body: JSON.stringify({ paths }),headers: { 'Content-Type': 'application/json' },method: 'DELETE',});export const emptyModelCache = async (): Promise<void> => {- await apiFetch(`${MODELS_BASE}/empty_model_cache`, { method: 'POST' });+ await request(`${MODELS_BASE}/empty_model_cache`, { method: 'POST' });};/** Model relationships: bidirectional "related model" links between configs. */@@ -173,10 +172,10 @@ export const emptyModelCache = async (): Promise<void> => {const RELATIONSHIPS_BASE = '/api/v1/model_relationships';export const getRelatedModelKeys = (key: string): Promise<string[]> =>- apiFetchJson<string[]>(`${RELATIONSHIPS_BASE}/i/${encodeURIComponent(key)}`);+ requestJson<string[]>(`${RELATIONSHIPS_BASE}/i/${encodeURIComponent(key)}`);export const addModelRelationship = async (modelKey1: string, modelKey2: string): Promise<void> => {- await apiFetch(`${RELATIONSHIPS_BASE}/`, {+ await request(`${RELATIONSHIPS_BASE}/`, {body: JSON.stringify({ model_key_1: modelKey1, model_key_2: modelKey2 }),headers: { 'Content-Type': 'application/json' },method: 'POST',@@ -184,7 +183,7 @@ export const addModelRelationship = async (modelKey1: string, modelKey2: string)};export const removeModelRelationship = async (modelKey1: string, modelKey2: string): Promise<void> => {- await apiFetch(`${RELATIONSHIPS_BASE}/`, {+ await request(`${RELATIONSHIPS_BASE}/`, {body: JSON.stringify({ model_key_1: modelKey1, model_key_2: modelKey2 }),headers: { 'Content-Type': 'application/json' },method: 'DELETE',@@ -202,18 +201,18 @@ export interface ExternalProviderConfig {}export const getExternalProviderConfigs = (): Promise<ExternalProviderConfig[]> =>- apiFetchJson<ExternalProviderConfig[]>(`${EXTERNAL_PROVIDERS_BASE}/config`);+ requestJson<ExternalProviderConfig[]>(`${EXTERNAL_PROVIDERS_BASE}/config`);export const setExternalProviderConfig = (providerId: string,config: { api_key?: string; base_url?: string | null }): Promise<ExternalProviderConfig> =>- apiFetchJson<ExternalProviderConfig>(`${EXTERNAL_PROVIDERS_BASE}/config/${encodeURIComponent(providerId)}`, {+ requestJson<ExternalProviderConfig>(`${EXTERNAL_PROVIDERS_BASE}/config/${encodeURIComponent(providerId)}`, {body: JSON.stringify(config),method: 'POST',});export const resetExternalProviderConfig = (providerId: string): Promise<ExternalProviderConfig> =>- apiFetchJson<ExternalProviderConfig>(`${EXTERNAL_PROVIDERS_BASE}/config/${encodeURIComponent(providerId)}`, {+ requestJson<ExternalProviderConfig>(`${EXTERNAL_PROVIDERS_BASE}/config/${encodeURIComponent(providerId)}`, {method: 'DELETE',});diff --git a/invokeai/frontend/webv2/src/workbench/models/apiKeys.ts b/invokeai/frontend/webv2/src/features/models/data/apiKeys.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/models/apiKeys.tsrename to invokeai/frontend/webv2/src/features/models/data/apiKeys.tsindex ab7a5d66ae..941fad8182 100644--- a/invokeai/frontend/webv2/src/workbench/models/apiKeys.ts+++ b/invokeai/frontend/webv2/src/features/models/data/apiKeys.ts@@ -1,4 +1,4 @@-import { getUserStorageScope } from '@workbench/auth/session';+import { getUserStorageScope } from '@features/identity';/*** Client-side API key storage for remote model sources. The HuggingFace tokendiff --git a/invokeai/frontend/webv2/src/features/models/data/installsStore.test.ts b/invokeai/frontend/webv2/src/features/models/data/installsStore.test.tsnew file mode 100644index 0000000000..5cc1b5ca96--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/data/installsStore.test.ts@@ -0,0 +1,64 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const dependencies = vi.hoisted(() => ({+ listModelInstalls: vi.fn(),+ refreshModels: vi.fn(),+ refreshStartersIfLoaded: vi.fn(),+}));++vi.mock('./api', () => ({ listModelInstalls: dependencies.listModelInstalls }));+vi.mock('./modelsStore', () => ({ refreshModels: dependencies.refreshModels }));+vi.mock('./startersStore', () => ({ refreshStartersIfLoaded: dependencies.refreshStartersIfLoaded }));++beforeEach(() => {+ vi.resetModules();+ vi.useFakeTimers();+ dependencies.listModelInstalls.mockReset().mockResolvedValue([]);+ dependencies.refreshModels.mockReset().mockResolvedValue(undefined);+ dependencies.refreshStartersIfLoaded.mockReset();+});++describe('model install event interpretation', () => {+ it('projects download progress immediately and coalesces the REST refresh', async () => {+ const store = await import('./installsStore');++ store.addInstallJob({ id: 7, source: 'org/model', status: 'waiting' });+ store.handleModelInstallSocketEvent('model_install_download_progress', {+ bytes: 25,+ id: 7,+ total_bytes: 100,+ });++ expect(store.getInstallsSnapshot().jobs[0]?.status).toBe('downloading');+ expect(store.getInstallProgress(7)).toEqual({ bytes: 25, totalBytes: 100 });++ store.handleModelInstallSocketEvent('model_install_started', { id: 7 });+ store.handleModelInstallSocketEvent('model_install_download_started', { id: 7 });+ await vi.advanceTimersByTimeAsync(250);++ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(1);+ });++ it('records completion identity and refreshes catalog capabilities', async () => {+ const store = await import('./installsStore');++ store.handleModelInstallSocketEvent('model_install_complete', {+ config: { name: 'Installed Model' },+ id: 8,+ source: { repo_id: 'org/model' },+ });++ expect(store.getInstallOutcomes()[0]).toMatchObject({+ error: null,+ jobId: 8,+ kind: 'completed',+ modelName: 'Installed Model',+ source: 'org/model',+ });+ expect(dependencies.refreshModels).toHaveBeenCalledTimes(1);+ expect(dependencies.refreshStartersIfLoaded).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(250);+ expect(dependencies.listModelInstalls).toHaveBeenCalledTimes(1);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/models/installsStore.ts b/invokeai/frontend/webv2/src/features/models/data/installsStore.tssimilarity index 94%rename from invokeai/frontend/webv2/src/workbench/models/installsStore.tsrename to invokeai/frontend/webv2/src/features/models/data/installsStore.tsindex 581d839f60..7284f193fc 100644--- a/invokeai/frontend/webv2/src/workbench/models/installsStore.ts+++ b/invokeai/frontend/webv2/src/features/models/data/installsStore.ts@@ -1,6 +1,6 @@-import { createExternalStore, createKeyedTransientStore } from '@workbench/externalStore';+import type { ModelInstallJob, ModelInstallStatus } from '@features/models/core/types';-import type { ModelInstallJob, ModelInstallStatus } from './types';+import { createExternalStore, createKeyedTransientStore } from '@platform/state/externalStore';import { listModelInstalls } from './api';import { refreshModels } from './modelsStore';@@ -226,6 +226,8 @@ export const useInstallsSelector = store.useSelector;export const useInstallsSnapshot = (): InstallsSnapshot => store.useSnapshot();+export const getInstallsSnapshot = (): InstallsSnapshot => store.getSnapshot();+/*** Source strings (URL, repo id, or path) of jobs currently in flight, cached* per jobs-array so list rows can show an "installing" state by source.@@ -246,4 +248,8 @@ export const useActiveInstallSources = (): ReadonlySet<string> =>export const useInstallProgress = (jobId: number): InstallDownloadProgress | null =>progressByJobId.useValue(jobId) ?? null;+export const getInstallProgress = (jobId: number): InstallDownloadProgress | null => progressByJobId.get(jobId) ?? null;+export const useInstallOutcomes = (): InstallOutcome[] => outcomesStore.useSelector((snapshot) => snapshot.outcomes);++export const getInstallOutcomes = (): InstallOutcome[] => outcomesStore.getSnapshot().outcomes;diff --git a/invokeai/frontend/webv2/src/features/models/data/modelLoadStore.test.ts b/invokeai/frontend/webv2/src/features/models/data/modelLoadStore.test.tsnew file mode 100644index 0000000000..adfa9126cb--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/data/modelLoadStore.test.ts@@ -0,0 +1,28 @@+import { beforeEach, describe, expect, it } from 'vitest';++import { getModelLoads, modelLoadActivitySink } from './modelLoadStore';++beforeEach(() => {+ modelLoadActivitySink.reset();+});++describe('model load activity', () => {+ it('owns backend payload interpretation and balances matching loads', () => {+ const payload = { config: { base: 'flux', name: 'FLUX Dev', type: 'main' }, submodel_type: 'transformer' };++ modelLoadActivitySink.started(payload);+ modelLoadActivitySink.started({ config: { name: 'VAE' } });++ expect(getModelLoads()).toEqual([{ label: 'FLUX Dev (flux, main, transformer)' }, { label: 'VAE' }]);++ modelLoadActivitySink.completed(payload);+ expect(getModelLoads()).toEqual([{ label: 'VAE' }]);+ });++ it('falls back deterministically for malformed completion payloads', () => {+ modelLoadActivitySink.started(null);+ modelLoadActivitySink.completed({});++ expect(getModelLoads()).toEqual([]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/backend/modelLoadStore.ts b/invokeai/frontend/webv2/src/features/models/data/modelLoadStore.tssimilarity index 80%rename from invokeai/frontend/webv2/src/workbench/backend/modelLoadStore.tsrename to invokeai/frontend/webv2/src/features/models/data/modelLoadStore.tsindex d4835cd331..fcd275fc60 100644--- a/invokeai/frontend/webv2/src/workbench/backend/modelLoadStore.ts+++ b/invokeai/frontend/webv2/src/features/models/data/modelLoadStore.ts@@ -1,4 +1,4 @@-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';export interface ModelLoadInfo {label: string;@@ -17,7 +17,13 @@ const getModelLoadLabel = (payload: unknown): string => {return extras.length ? `${name} (${extras.join(', ')})` : name;};-export const modelLoadStore = {+export interface ModelLoadActivitySink {+ started(payload: unknown): void;+ completed(payload: unknown): void;+ reset(): void;+}++export const modelLoadActivitySink: ModelLoadActivitySink = {started(payload: unknown): void {store.patchSnapshot({ activeLoads: [...store.getSnapshot().activeLoads, { label: getModelLoadLabel(payload) }] });},@@ -36,3 +42,5 @@ export const modelLoadStore = {};export const useModelLoads = (): ModelLoadInfo[] => store.useSelector((snapshot) => snapshot.activeLoads);++export const getModelLoads = (): ModelLoadInfo[] => store.getSnapshot().activeLoads;diff --git a/invokeai/frontend/webv2/src/workbench/models/modelsStore.ts b/invokeai/frontend/webv2/src/features/models/data/modelsStore.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/models/modelsStore.tsrename to invokeai/frontend/webv2/src/features/models/data/modelsStore.tsindex fdd31a69ee..50014cd7c3 100644--- a/invokeai/frontend/webv2/src/workbench/models/modelsStore.ts+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts@@ -1,6 +1,6 @@-import { createExternalStore } from '@workbench/externalStore';+import type { ModelConfig } from '@features/models/core/types';-import type { ModelConfig } from './types';+import { createExternalStore } from '@platform/state/externalStore';import { getModelsDir, listMissingModels, listModels } from './api';diff --git a/invokeai/frontend/webv2/src/workbench/models/startersStore.ts b/invokeai/frontend/webv2/src/features/models/data/startersStore.tssimilarity index 92%rename from invokeai/frontend/webv2/src/workbench/models/startersStore.tsrename to invokeai/frontend/webv2/src/features/models/data/startersStore.tsindex df668c7262..9517cc097f 100644--- a/invokeai/frontend/webv2/src/workbench/models/startersStore.ts+++ b/invokeai/frontend/webv2/src/features/models/data/startersStore.ts@@ -1,6 +1,6 @@-import { createExternalStore } from '@workbench/externalStore';+import type { StarterModelResponse } from '@features/models/core/types';-import type { StarterModelResponse } from './types';+import { createExternalStore } from '@platform/state/externalStore';import { getStarterModels } from './api';diff --git a/invokeai/frontend/webv2/src/features/models/data/transport.ts b/invokeai/frontend/webv2/src/features/models/data/transport.tsnew file mode 100644index 0000000000..284ffb9281--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/data/transport.ts@@ -0,0 +1,13 @@+import { apiFetch, apiFetchJson, buildApiUrl } from '@platform/transport/http';++export interface ModelsDataPort {+ buildUrl(path: string): string;+ request(path: string, init?: RequestInit): Promise<Response>;+ requestJson<T>(path: string, init?: RequestInit): Promise<T>;+}++export const browserModelsDataPort: ModelsDataPort = {+ buildUrl: buildApiUrl,+ request: apiFetch,+ requestJson: apiFetchJson,+};diff --git a/invokeai/frontend/webv2/src/features/models/index.ts b/invokeai/frontend/webv2/src/features/models/index.tsnew file mode 100644index 0000000000..8a5a4015ba--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/index.ts@@ -0,0 +1,25 @@+export type {+ AnyModelDefaultSettings,+ ModelBase,+ ModelConfig,+ ModelFileFormat,+ ModelTaxonomyType,+ PredictionType,+} from './core/types';+export { getModelBaseColorPalette, getModelBaseLabel } from './core/baseIdentity';+export {+ ensureModelsLoaded,+ getModelsSnapshot,+ refreshModels,+ useModelsSelector,+ useModelsSnapshot,+ type ModelsSnapshot,+} from './data/modelsStore';+export {+ modelLoadActivitySink,+ useModelLoads,+ type ModelLoadActivitySink,+ type ModelLoadInfo,+} from './data/modelLoadStore';+export { ModelsPage } from './ui/ModelsPage';+export { ModelsUiProvider, type ModelsUiAdapter } from './ui/ModelsUiContext';diff --git a/invokeai/frontend/webv2/src/features/models/react.ts b/invokeai/frontend/webv2/src/features/models/react.tsnew file mode 100644index 0000000000..b58eda7de0--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/react.ts@@ -0,0 +1 @@+export { ModelSelect } from './ui/components/ModelSelect';diff --git a/invokeai/frontend/webv2/src/workbench/models/ModelInstallRuntime.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelInstallRuntime.tsxsimilarity index 70%rename from invokeai/frontend/webv2/src/workbench/models/ModelInstallRuntime.tsxrename to invokeai/frontend/webv2/src/features/models/ui/ModelInstallRuntime.tsxindex 35e11d4008..430925639f 100644--- a/invokeai/frontend/webv2/src/workbench/models/ModelInstallRuntime.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelInstallRuntime.tsx@@ -1,9 +1,13 @@-import { getConnectionStatus, subscribeConnection } from '@workbench/backend/connectionStore';-import { socketHub } from '@workbench/backend/socketHub';+import {+ handleModelInstallSocketEvent,+ MODEL_INSTALL_SOCKET_EVENTS,+ refreshInstalls,+} from '@features/models/data/installsStore';+import { refreshModels } from '@features/models/data/modelsStore';+import { getConnectionStatus, subscribeConnection } from '@platform/transport/connectionStore';+import { socketHub } from '@platform/transport/socketHub';import { useEffect } from 'react';-import { handleModelInstallSocketEvent, MODEL_INSTALL_SOCKET_EVENTS, refreshInstalls } from './installsStore';-import { refreshModels } from './modelsStore';import { useInstallOutcomeToasts } from './useInstallOutcomeToasts';/** Admin model-manager runtime: install socket events, reconnect refresh, and outcome toasts. */diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/ModelManagerView.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelManagerView.tsxsimilarity index 67%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/ModelManagerView.tsxrename to invokeai/frontend/webv2/src/features/models/ui/ModelManagerView.tsxindex ba30a42d9a..ef2b9588fc 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/ModelManagerView.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelManagerView.tsx@@ -1,16 +1,16 @@import { Flex } from '@chakra-ui/react';-import { ModelInstallRuntime } from '@workbench/models/ModelInstallRuntime';-import { ensureModelsLoaded } from '@workbench/models/modelsStore';-import { useEffect } from 'react';+import { ensureModelsLoaded } from '@features/models/data/modelsStore';+import { ModelInstallRuntime } from '@features/models/ui/ModelInstallRuntime';+import { useMountEffect } from '@platform/react/useMountEffect';import { DetailPane } from './manager/DetailPane';import { LibraryColumn } from './manager/LibraryColumn';/** Full model manager: persistent library column plus right-side detail pane. */export const ModelManagerView = () => {- useEffect(() => {+ useMountEffect(() => {ensureModelsLoaded();- }, []);+ });return (<Flex direction="column" h="full" minH="0" w="full">diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/pages/ModelsPage.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelsPage.tsxsimilarity index 89%rename from invokeai/frontend/webv2/src/workbench/launchpad/pages/ModelsPage.tsxrename to invokeai/frontend/webv2/src/features/models/ui/ModelsPage.tsxindex 3140717955..5f8750e1cc 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/pages/ModelsPage.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelsPage.tsx@@ -13,7 +13,7 @@ import { lazy, Suspense } from 'react';* external stores, so the view needs no workbench providers here.*/const ModelManagerView = lazy(() =>- import('@workbench/launchpad/models/ModelManagerView').then((module) => ({ default: module.ModelManagerView }))+ import('@features/models/ui/ModelManagerView').then((module) => ({ default: module.ModelManagerView })));const FALLBACK = (diff --git a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsxnew file mode 100644index 0000000000..1fa202f6ad--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx@@ -0,0 +1,21 @@+import type { ReactNode } from 'react';++import { createContext, use } from 'react';++export interface ModelsUiAdapter {+ enableModelDescriptions: boolean;+ managerProjectId: string | null;+}++const DEFAULT_MODELS_UI_ADAPTER: ModelsUiAdapter = {+ enableModelDescriptions: true,+ managerProjectId: null,+};++const ModelsUiContext = createContext<ModelsUiAdapter>(DEFAULT_MODELS_UI_ADAPTER);++export const ModelsUiProvider = ({ adapter, children }: { adapter: ModelsUiAdapter; children: ReactNode }) => (+ <ModelsUiContext value={adapter}>{children}</ModelsUiContext>+);++export const useModelsUi = (): ModelsUiAdapter => use(ModelsUiContext);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/AccessTokenPopover.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/AccessTokenPopover.tsxsimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/AccessTokenPopover.tsxrename to invokeai/frontend/webv2/src/features/models/ui/add-models/AccessTokenPopover.tsxindex 18cbf1aaaa..22f9e8afda 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/AccessTokenPopover.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/AccessTokenPopover.tsx@@ -1,6 +1,6 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import { Icon, Input, Popover, Portal, Stack, Text } from '@chakra-ui/react';-import { Button, IconButton } from '@workbench/components/ui';+import { Button, IconButton } from '@platform/ui';import { KeyRoundIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/AddModelsView.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsxsimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/AddModelsView.tsxrename to invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsxindex de03d03616..d3fdc60e63 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/AddModelsView.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx@@ -1,15 +1,15 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { ModelSortField } from '@workbench/models/library';-import type { StarterModel } from '@workbench/models/types';+import type { ModelSortField } from '@features/models/core/library';+import type { StarterModel } from '@features/models/core/types';import { Box, Checkbox, Flex, HStack, Icon, Input, InputGroup, Stack, Text } from '@chakra-ui/react';-import { Button, Scrollable, Tooltip } from '@workbench/components/ui';-import { getExternalProviderConfigs, getHuggingFaceModels, scanFolderForModels } from '@workbench/models/api';-import { getModelBaseLabel } from '@workbench/models/baseIdentity';-import { collectBases, collectTypes } from '@workbench/models/library';-import { ensureStartersLoaded, useStartersSelector } from '@workbench/models/startersStore';-import { updateModelsUi, useModelsUiSelector } from '@workbench/models/uiStore';-import { useNotify } from '@workbench/useNotify';+import { getModelBaseLabel } from '@features/models/core/baseIdentity';+import { collectBases, collectTypes } from '@features/models/core/library';+import { getExternalProviderConfigs, getHuggingFaceModels, scanFolderForModels } from '@features/models/data/api';+import { ensureStartersLoaded, useStartersSelector } from '@features/models/data/startersStore';+import { updateModelsUi, useModelsUiSelector } from '@features/models/ui/uiStore';+import { useNotify } from '@features/models/ui/useModelsNotify';+import { Button, Scrollable, Tooltip } from '@platform/ui';import { DownloadIcon, FileIcon, FolderIcon, FolderSearchIcon, LinkIcon, SearchIcon } from 'lucide-react';import { useDeferredValue, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/BundleChips.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.tsxsimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/BundleChips.tsxrename to invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.tsxindex 069ece9ec9..352c126b59 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/BundleChips.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.tsx@@ -1,9 +1,9 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { StarterModelBundle } from '@workbench/models/types';+import type { StarterModelBundle } from '@features/models/core/types';import type { ReactNode } from 'react';import { Badge, Box, HStack, Icon } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';+import { Button } from '@platform/ui';import { CheckIcon, FolderIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/HuggingFaceFiles.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/HuggingFaceFiles.tsxsimilarity index 89%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/HuggingFaceFiles.tsxrename to invokeai/frontend/webv2/src/features/models/ui/add-models/HuggingFaceFiles.tsxindex 70743b4f45..3e985ab5b0 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/HuggingFaceFiles.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/HuggingFaceFiles.tsx@@ -1,9 +1,9 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { HFLookupState } from '@workbench/models/uiStore';+import type { HFLookupState } from '@features/models/ui/uiStore';import { Stack } from '@chakra-ui/react';-import { ResultsListHeader } from '@workbench/launchpad/models/shared/ResultsListHeader';-import { InstallSourceButton, SourceListItem } from '@workbench/launchpad/models/shared/SourceListItem';+import { ResultsListHeader } from '@features/models/ui/shared/ResultsListHeader';+import { InstallSourceButton, SourceListItem } from '@features/models/ui/shared/SourceListItem';import { useDeferredValue, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/ScanResults.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.tsxsimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/ScanResults.tsxrename to invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.tsxindex 63386acec5..108fed4142 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/ScanResults.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.tsx@@ -1,10 +1,10 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { FoundModel } from '@workbench/models/types';+import type { FoundModel } from '@features/models/core/types';import { Checkbox, HStack, Icon, Stack, Text } from '@chakra-ui/react';-import { IconButton } from '@workbench/components/ui';-import { ResultsListHeader } from '@workbench/launchpad/models/shared/ResultsListHeader';-import { InstallSourceButton, SourceListItem } from '@workbench/launchpad/models/shared/SourceListItem';+import { ResultsListHeader } from '@features/models/ui/shared/ResultsListHeader';+import { InstallSourceButton, SourceListItem } from '@features/models/ui/shared/SourceListItem';+import { IconButton } from '@platform/ui';import { XIcon } from 'lucide-react';import { useDeferredValue, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/SelectedBundleBar.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/SelectedBundleBar.tsxsimilarity index 89%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/SelectedBundleBar.tsxrename to invokeai/frontend/webv2/src/features/models/ui/add-models/SelectedBundleBar.tsxindex fb9ef8305a..ac6f7694a3 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/SelectedBundleBar.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/SelectedBundleBar.tsx@@ -1,7 +1,7 @@-import type { StarterModelBundle } from '@workbench/models/types';+import type { StarterModelBundle } from '@features/models/core/types';import { HStack, Icon, Text } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';+import { Button } from '@platform/ui';import { DownloadIcon } from 'lucide-react';/** Summary + install action for the currently selected bundle. */diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/StarterFilterMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/StarterFilterMenu.tsxsimilarity index 87%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/StarterFilterMenu.tsxrename to invokeai/frontend/webv2/src/features/models/ui/add-models/StarterFilterMenu.tsxindex 29f8ddf8ba..0f12d16e52 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/StarterFilterMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/StarterFilterMenu.tsx@@ -1,9 +1,9 @@+import type { ModelSortField } from '@features/models/core/library';+import type { ModelTaxonomyType } from '@features/models/core/types';/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { ModelFilterSortOption } from '@workbench/launchpad/models/shared/ModelFilterMenu';-import type { ModelSortField } from '@workbench/models/library';-import type { ModelTaxonomyType } from '@workbench/models/types';+import type { ModelFilterSortOption } from '@features/models/ui/shared/ModelFilterMenu';-import { ModelFilterMenu } from '@workbench/launchpad/models/shared/ModelFilterMenu';+import { ModelFilterMenu } from '@features/models/ui/shared/ModelFilterMenu';import { useTranslation } from 'react-i18next';export interface StarterModelFilters {diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/StarterList.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/StarterList.tsxsimilarity index 90%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/StarterList.tsxrename to invokeai/frontend/webv2/src/features/models/ui/add-models/StarterList.tsxindex ad94f9d235..b705b77466 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/StarterList.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/StarterList.tsx@@ -1,12 +1,12 @@+import type { StarterModel } from '@features/models/core/types';/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { useStartersSnapshot } from '@workbench/models/startersStore';-import type { StarterModel } from '@workbench/models/types';+import type { useStartersSnapshot } from '@features/models/data/startersStore';import { Badge, Flex, Icon, Spinner, Stack, Text } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';-import { InstallSourceButton, SourceListItem } from '@workbench/launchpad/models/shared/SourceListItem';-import { getModelBaseColorPalette, getModelBaseLabel } from '@workbench/models/baseIdentity';-import { getModelTypeLabel } from '@workbench/models/taxonomy';+import { getModelBaseColorPalette, getModelBaseLabel } from '@features/models/core/baseIdentity';+import { getModelTypeLabel } from '@features/models/core/taxonomy';+import { InstallSourceButton, SourceListItem } from '@features/models/ui/shared/SourceListItem';+import { Button } from '@platform/ui';import { KeyRoundIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/sourceClassifier.ts b/invokeai/frontend/webv2/src/features/models/ui/add-models/sourceClassifier.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/sourceClassifier.tsrename to invokeai/frontend/webv2/src/features/models/ui/add-models/sourceClassifier.tsdiff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/starterModelInstallSources.test.ts b/invokeai/frontend/webv2/src/features/models/ui/add-models/starterModelInstallSources.test.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/starterModelInstallSources.test.tsrename to invokeai/frontend/webv2/src/features/models/ui/add-models/starterModelInstallSources.test.tsindex 3f5600e6bc..9082b020a3 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/starterModelInstallSources.test.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/starterModelInstallSources.test.ts@@ -1,4 +1,4 @@-import type { StarterModel, StarterModelBundle } from '@workbench/models/types';+import type { StarterModel, StarterModelBundle } from '@features/models/core/types';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/starterModelInstallSources.ts b/invokeai/frontend/webv2/src/features/models/ui/add-models/starterModelInstallSources.tssimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/starterModelInstallSources.tsrename to invokeai/frontend/webv2/src/features/models/ui/add-models/starterModelInstallSources.tsindex 1d17e06ad0..43007cbcc5 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/starterModelInstallSources.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/starterModelInstallSources.ts@@ -1,4 +1,4 @@-import type { ModelRecordChanges, StarterModel, StarterModelBundle } from '@workbench/models/types';+import type { ModelRecordChanges, StarterModel, StarterModelBundle } from '@features/models/core/types';/** A source to install plus the curated config metadata to register it with. */export interface StarterInstallSource {diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/useInstallActions.ts b/invokeai/frontend/webv2/src/features/models/ui/add-models/useInstallActions.tssimilarity index 84%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/useInstallActions.tsrename to invokeai/frontend/webv2/src/features/models/ui/add-models/useInstallActions.tsindex 970271abb7..c3ce15cac5 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/useInstallActions.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/useInstallActions.ts@@ -1,7 +1,7 @@-import { installModel, type InstallModelRequest } from '@workbench/models/api';-import { getAccessTokenForSource } from '@workbench/models/apiKeys';-import { addInstallJob } from '@workbench/models/installsStore';-import { useNotify } from '@workbench/useNotify';+import { installModel, type InstallModelRequest } from '@features/models/data/api';+import { getAccessTokenForSource } from '@features/models/data/apiKeys';+import { addInstallJob } from '@features/models/data/installsStore';+import { useNotify } from '@features/models/ui/useModelsNotify';import { useCallback, useState } from 'react';/**diff --git a/invokeai/frontend/webv2/src/workbench/models/components/ModelSelect.tsx b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsxsimilarity index 93%rename from invokeai/frontend/webv2/src/workbench/models/components/ModelSelect.tsxrename to invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsxindex 47f2eb87c2..b3b31c93f5 100644--- a/invokeai/frontend/webv2/src/workbench/models/components/ModelSelect.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx@@ -1,5 +1,5 @@/* eslint-disable react/react-compiler, react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */-import type { ModelConfig, ModelTaxonomyType } from '@workbench/models/types';+import type { ModelConfig, ModelTaxonomyType } from '@features/models/core/types';import {Badge,@@ -15,16 +15,16 @@ import {Stack,Text,} from '@chakra-ui/react';+import { getModelBaseColorPalette, getModelBaseLabel } from '@features/models/core/baseIdentity';+import { getModelPickerGroups } from '@features/models/core/library';+import { formatBytes, getModelTypePluralLabel } from '@features/models/core/taxonomy';+import { ensureModelsLoaded, useModelsSelector } from '@features/models/data/modelsStore';+import { useModelsUi } from '@features/models/ui/ModelsUiContext';+import { useMountEffect } from '@platform/react/useMountEffect';+import { Button, CloseButton, IconButton, Tooltip } from '@platform/ui';import { Link } from '@tanstack/react-router';-import { Button, CloseButton, IconButton, Tooltip } from '@workbench/components/ui';-import { getModelBaseColorPalette, getModelBaseLabel } from '@workbench/models/baseIdentity';-import { getModelPickerGroups } from '@workbench/models/library';-import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';-import { formatBytes, getModelTypePluralLabel } from '@workbench/models/taxonomy';-import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';-import { useActiveProjectId } from '@workbench/WorkbenchContext';import { BoxIcon, CheckIcon, ChevronDownIcon, RotateCcwIcon, SearchIcon, XIcon } from 'lucide-react';-import { useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';+import { useDeferredValue, useMemo, useRef, useState } from 'react';const EMPTY_BASES: ReadonlySet<string> = new Set();@@ -68,18 +68,29 @@ export const ModelSelect = ({/** Selected model key, or null. */value: string | null;}) => {- const enableModelDescriptions = useWorkbenchPreferenceSelector((preferences) => preferences.enableModelDescriptions);+ const { enableModelDescriptions } = useModelsUi();const models = useModelsSelector((snapshot) => snapshot.models);const [isOpen, setIsOpen] = useState(false);const [searchTerm, setSearchTerm] = useState('');const [selectedBases, setSelectedBases] = useState<ReadonlySet<string>>(EMPTY_BASES);+ const [lastDisabled, setLastDisabled] = useState(disabled);const deferredSearchTerm = useDeferredValue(searchTerm);const searchInputRef = useRef<HTMLInputElement>(null);const optionRefs = useRef<HTMLElement[]>([]);- useEffect(() => {+ useMountEffect(() => {ensureModelsLoaded();- }, []);+ });++ if (disabled !== lastDisabled) {+ setLastDisabled(disabled);++ if (disabled) {+ setIsOpen(false);+ setSearchTerm('');+ setSelectedBases(EMPTY_BASES);+ }+ }const { availableBases, candidates, groups } = useMemo(() =>@@ -105,12 +116,6 @@ export const ModelSelect = ({setSelectedBases(EMPTY_BASES);};- useEffect(() => {- if (disabled) {- closeAndReset();- }- }, [disabled]);-const toggleBase = (base: string) => {setSelectedBases((prev) => {const next = new Set(prev);@@ -399,8 +404,8 @@ export const ModelSelect = ({};const ModelManagerLinkButton = () => {- const projectId = useActiveProjectId();- const search = useMemo(() => ({ project: projectId }), [projectId]);+ const { managerProjectId } = useModelsUi();+ const search = useMemo(() => ({ project: managerProjectId ?? undefined }), [managerProjectId]);return (<Tooltip content="Manage models" showArrow>diff --git a/invokeai/frontend/webv2/src/workbench/models/components/index.ts b/invokeai/frontend/webv2/src/features/models/ui/components/index.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/models/components/index.tsrename to invokeai/frontend/webv2/src/features/models/ui/components/index.tsdiff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/credentials/ApiKeysSection.tsx b/invokeai/frontend/webv2/src/features/models/ui/credentials/ApiKeysSection.tsxsimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/credentials/ApiKeysSection.tsxrename to invokeai/frontend/webv2/src/features/models/ui/credentials/ApiKeysSection.tsxindex c7f0332e9b..2ac3a29473 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/credentials/ApiKeysSection.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/credentials/ApiKeysSection.tsx@@ -1,8 +1,7 @@/* eslint-disable react/react-compiler, react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { HFTokenStatus } from '@workbench/models/types';+import type { HFTokenStatus } from '@features/models/core/types';import { Badge, Flex, Grid, HStack, Icon, Input, Stack, Switch, Text } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';import {getExternalProviderConfigs,getHFTokenStatus,@@ -11,11 +10,12 @@ import {setExternalProviderConfig,setHFToken,type ExternalProviderConfig,-} from '@workbench/models/api';-import { clearCivitaiApiKey, getCivitaiApiKey, setCivitaiApiKey } from '@workbench/models/apiKeys';-import { refreshInstalls } from '@workbench/models/installsStore';-import { refreshStartersIfLoaded } from '@workbench/models/startersStore';-import { useNotify } from '@workbench/useNotify';+} from '@features/models/data/api';+import { clearCivitaiApiKey, getCivitaiApiKey, setCivitaiApiKey } from '@features/models/data/apiKeys';+import { refreshInstalls } from '@features/models/data/installsStore';+import { refreshStartersIfLoaded } from '@features/models/data/startersStore';+import { useNotify } from '@features/models/ui/useModelsNotify';+import { Button } from '@platform/ui';import { HexagonIcon } from 'lucide-react';import { useEffect, useState, type ElementType } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/DefaultSettingsSection.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsxsimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/detail/DefaultSettingsSection.tsxrename to invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsxindex c4f3cfb972..5e9a1609b3 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/DefaultSettingsSection.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx@@ -1,12 +1,12 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { AnyModelDefaultSettings, ModelConfig } from '@workbench/models/types';+import type { AnyModelDefaultSettings, ModelConfig } from '@features/models/core/types';import type { TFunction } from 'i18next';import { Grid, HStack, Icon, NativeSelect, NumberInput, Stack, Switch, Text } from '@chakra-ui/react';-import { Button, Combobox, FieldLabel, Panel } from '@workbench/components/ui';-import { updateModel } from '@workbench/models/api';-import { replaceModelInStore } from '@workbench/models/modelsStore';-import { loraDefaultSettingsSchema, mainDefaultSettingsSchema } from '@workbench/models/schemas';+import { loraDefaultSettingsSchema, mainDefaultSettingsSchema } from '@features/models/core/schemas';+import { updateModel } from '@features/models/data/api';+import { replaceModelInStore } from '@features/models/data/modelsStore';+import { Button, Combobox, FieldLabel, Panel } from '@platform/ui';import { MoveHorizontalIcon } from 'lucide-react';import { useMemo, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelBadges.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelBadges.tsxsimilarity index 80%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelBadges.tsxrename to invokeai/frontend/webv2/src/features/models/ui/detail/ModelBadges.tsxindex 347fbb2075..0021e4661d 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelBadges.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelBadges.tsx@@ -1,8 +1,8 @@-import type { ModelConfig } from '@workbench/models/types';+import type { ModelConfig } from '@features/models/core/types';import { Badge, HStack } from '@chakra-ui/react';-import { getModelBaseColorPalette, getModelBaseLabel } from '@workbench/models/baseIdentity';-import { getModelFormatLabel } from '@workbench/models/taxonomy';+import { getModelBaseColorPalette, getModelBaseLabel } from '@features/models/core/baseIdentity';+import { getModelFormatLabel } from '@features/models/core/taxonomy';export const ModelBaseBadge = ({ base }: { base: ModelConfig['base'] }) => (<Badge colorPalette={getModelBaseColorPalette(base)} flexShrink={0} fontSize="2xs" size="sm" variant="surface">diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelDetail.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsxsimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelDetail.tsxrename to invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsxindex 36447916ae..d8238f0c7c 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelDetail.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx@@ -1,13 +1,13 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { AnyModelDefaultSettings, ModelConfig, ModelTaxonomyType } from '@workbench/models/types';+import type { AnyModelDefaultSettings, ModelConfig, ModelTaxonomyType } from '@features/models/core/types';import { DataList, HStack, Icon, Menu, Portal, Separator, Stack, Text } from '@chakra-ui/react';-import { Button, IconButton, ConfirmDialog, MenuContent } from '@workbench/components/ui';-import { isConvertibleToDiffusers } from '@workbench/models/baseIdentity';-import { useModelsSelector } from '@workbench/models/modelsStore';-import { formatBytes } from '@workbench/models/taxonomy';-import { useNotify } from '@workbench/useNotify';-import { areArraysEqual } from '@workbench/workbenchSelectors';+import { isConvertibleToDiffusers } from '@features/models/core/baseIdentity';+import { formatBytes } from '@features/models/core/taxonomy';+import { useModelsSelector } from '@features/models/data/modelsStore';+import { useNotify } from '@features/models/ui/useModelsNotify';+import { areArraysEqual } from '@platform/state/selectors';+import { Button, IconButton, ConfirmDialog, MenuContent } from '@platform/ui';import { ArrowLeftIcon, MoreHorizontalIcon, PencilIcon, RefreshCcwIcon, Trash2Icon } from 'lucide-react';import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelEditForm.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.tsxsimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelEditForm.tsxrename to invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.tsxindex 20ebd42e8d..cfbb8e4465 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelEditForm.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.tsx@@ -1,14 +1,14 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { ModelConfig, PredictionType } from '@workbench/models/types';+import type { ModelConfig, PredictionType } from '@features/models/core/types';import { HStack, Input, NativeSelect, Stack, Text, Textarea } from '@chakra-ui/react';-import { Button, Field } from '@workbench/components/ui';-import { updateModel } from '@workbench/models/api';-import { getModelBaseLabel } from '@workbench/models/baseIdentity';-import { replaceModelInStore } from '@workbench/models/modelsStore';-import { modelEditSchema, type ModelEditFormValues } from '@workbench/models/schemas';-import { getModelTypeLabel, MODEL_CATEGORIES } from '@workbench/models/taxonomy';-import { useZodForm } from '@workbench/models/useZodForm';+import { getModelBaseLabel } from '@features/models/core/baseIdentity';+import { modelEditSchema, type ModelEditFormValues } from '@features/models/core/schemas';+import { getModelTypeLabel, MODEL_CATEGORIES } from '@features/models/core/taxonomy';+import { updateModel } from '@features/models/data/api';+import { replaceModelInStore } from '@features/models/data/modelsStore';+import { useZodForm } from '@platform/react/useZodForm';+import { Button, Field } from '@platform/ui';import { useTranslation } from 'react-i18next';const KNOWN_BASES = [diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelImageUpload.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsxsimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelImageUpload.tsxrename to invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsxindex bbe52ef0f8..022f2cb050 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelImageUpload.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx@@ -1,10 +1,10 @@/* eslint-disable react/react-compiler, react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { ModelConfig } from '@workbench/models/types';+import type { ModelConfig } from '@features/models/core/types';import { Box, Flex, Icon, Image, Stack, Text } from '@chakra-ui/react';-import { IconButton, Tooltip } from '@workbench/components/ui';-import { deleteModelImage, getModelImageUrl, updateModelImage } from '@workbench/models/api';-import { markCoverImageChanged, useModelsSelector } from '@workbench/models/modelsStore';+import { deleteModelImage, getModelImageUrl, updateModelImage } from '@features/models/data/api';+import { markCoverImageChanged, useModelsSelector } from '@features/models/data/modelsStore';+import { IconButton, Tooltip } from '@platform/ui';import { ImageIcon, UploadIcon, XIcon } from 'lucide-react';import { useEffect, useRef, useState, type DragEvent } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/RelatedModelsSection.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsxsimilarity index 90%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/detail/RelatedModelsSection.tsxrename to invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsxindex 4794f74597..d2dcaf9f45 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/RelatedModelsSection.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx@@ -1,14 +1,14 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { ModelConfig, ModelTaxonomyType } from '@workbench/models/types';+import type { ModelConfig, ModelTaxonomyType } from '@features/models/core/types';import { Badge, Icon, Spinner, Stack, Text } from '@chakra-ui/react';-import { IconButton, FieldLabel, Tooltip } from '@workbench/components/ui';-import { SourceListItem } from '@workbench/launchpad/models/shared/SourceListItem';-import { addModelRelationship, getRelatedModelKeys, removeModelRelationship } from '@workbench/models/api';-import { getModelBaseColorPalette, getModelBaseLabel } from '@workbench/models/baseIdentity';-import { ModelSelect } from '@workbench/models/components';-import { useModelsSelector } from '@workbench/models/modelsStore';-import { getModelTypeLabel } from '@workbench/models/taxonomy';+import { getModelBaseColorPalette, getModelBaseLabel } from '@features/models/core/baseIdentity';+import { getModelTypeLabel } from '@features/models/core/taxonomy';+import { addModelRelationship, getRelatedModelKeys, removeModelRelationship } from '@features/models/data/api';+import { useModelsSelector } from '@features/models/data/modelsStore';+import { ModelSelect } from '@features/models/ui/components';+import { SourceListItem } from '@features/models/ui/shared/SourceListItem';+import { IconButton, FieldLabel, Tooltip } from '@platform/ui';import { Link2OffIcon } from 'lucide-react';import { useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/TriggerPhrasesEditor.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsxsimilarity index 94%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/detail/TriggerPhrasesEditor.tsxrename to invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsxindex 8f380496f0..f9aa52afaf 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/TriggerPhrasesEditor.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsx@@ -1,9 +1,9 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import { HStack, Icon, Input, Tag, Text, Wrap } from '@chakra-ui/react';-import { Button, Field } from '@workbench/components/ui';-import { updateModel } from '@workbench/models/api';-import { replaceModelInStore } from '@workbench/models/modelsStore';-import { triggerPhraseSchema } from '@workbench/models/schemas';+import { triggerPhraseSchema } from '@features/models/core/schemas';+import { updateModel } from '@features/models/data/api';+import { replaceModelInStore } from '@features/models/data/modelsStore';+import { Button, Field } from '@platform/ui';import { PlusIcon } from 'lucide-react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/useModelActions.ts b/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.tssimilarity index 83%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/detail/useModelActions.tsrename to invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.tsindex 52865ed846..49892de5bf 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/useModelActions.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts@@ -1,9 +1,9 @@-import type { ModelConfig } from '@workbench/models/types';+import type { ModelConfig } from '@features/models/core/types';-import { convertModelToDiffusers, deleteModel, reidentifyModel } from '@workbench/models/api';-import { removeModelsFromStore, replaceModelInStore } from '@workbench/models/modelsStore';-import { pruneModelsUiKeys } from '@workbench/models/uiStore';-import { useNotify } from '@workbench/useNotify';+import { convertModelToDiffusers, deleteModel, reidentifyModel } from '@features/models/data/api';+import { removeModelsFromStore, replaceModelInStore } from '@features/models/data/modelsStore';+import { pruneModelsUiKeys } from '@features/models/ui/uiStore';+import { useNotify } from '@features/models/ui/useModelsNotify';import { useCallback } from 'react';/**diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallJobProgress.tsx b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobProgress.tsxsimilarity index 82%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallJobProgress.tsxrename to invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobProgress.tsxindex b3c63398a2..68ab61c568 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallJobProgress.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobProgress.tsx@@ -1,8 +1,8 @@-import type { ModelInstallJob } from '@workbench/models/types';+import type { ModelInstallJob } from '@features/models/core/types';import { Box, Progress, Text } from '@chakra-ui/react';-import { useInstallProgress } from '@workbench/models/installsStore';-import { formatBytes } from '@workbench/models/taxonomy';+import { formatBytes } from '@features/models/core/taxonomy';+import { useInstallProgress } from '@features/models/data/installsStore';import { useTranslation } from 'react-i18next';export const InstallJobProgress = ({ job }: { job: ModelInstallJob }) => {diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallJobRow.tsx b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobRow.tsxsimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallJobRow.tsxrename to invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobRow.tsxindex 5c80c98085..5c56f6f54c 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallJobRow.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallJobRow.tsx@@ -1,18 +1,18 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { ModelInstallJob } from '@workbench/models/types';+import type { ModelInstallJob } from '@features/models/core/types';import { Badge, HStack, Icon, Stack, Text } from '@chakra-ui/react';-import { useConnectionStatusSelector } from '@workbench/backend/connectionStore';-import { IconButton, Tooltip } from '@workbench/components/ui';+import { getInstallSourceLabel } from '@features/models/core/taxonomy';import {cancelModelInstall,pauseModelInstall,restartFailedModelInstall,restartModelInstallFile,resumeModelInstall,-} from '@workbench/models/api';-import { isActiveInstallStatus, refreshInstalls, replaceInstallJob } from '@workbench/models/installsStore';-import { getInstallSourceLabel } from '@workbench/models/taxonomy';+} from '@features/models/data/api';+import { isActiveInstallStatus, refreshInstalls, replaceInstallJob } from '@features/models/data/installsStore';+import { useConnectionStatusSelector } from '@platform/transport/connectionStore';+import { IconButton, Tooltip } from '@platform/ui';import { PauseIcon, PlayIcon, RotateCcwIcon, TriangleAlertIcon, XIcon } from 'lucide-react';import { useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallQueueBar.tsx b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.tsxsimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallQueueBar.tsxrename to invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.tsxindex 5300a56553..6369ba7480 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallQueueBar.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueBar.tsx@@ -1,21 +1,21 @@-import type { ModelInstallJob } from '@workbench/models/types';+import type { ModelInstallJob } from '@features/models/core/types';import { Badge, Box, Collapsible, Flex, HStack, Icon, Spinner, Text } from '@chakra-ui/react';-import { Button, IconButton, Tooltip } from '@workbench/components/ui';import {cancelModelInstall,pauseModelInstall,pruneCompletedModelInstalls,resumeModelInstall,-} from '@workbench/models/api';+} from '@features/models/data/api';import {ensureInstallsLoaded,isActiveInstallStatus,refreshInstalls,useInstallsSelector,-} from '@workbench/models/installsStore';-import { setQueueExpanded, useModelsUiSelector } from '@workbench/models/uiStore';-import { useNotify } from '@workbench/useNotify';+} from '@features/models/data/installsStore';+import { setQueueExpanded, useModelsUiSelector } from '@features/models/ui/uiStore';+import { useNotify } from '@features/models/ui/useModelsNotify';+import { Button, IconButton, Tooltip } from '@platform/ui';import { ChevronUpIcon, ListOrderedIcon, PauseIcon, PlayIcon, RefreshCcwIcon, Trash2Icon, XIcon } from 'lucide-react';import { useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallQueueList.tsx b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueList.tsxsimilarity index 88%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallQueueList.tsxrename to invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueList.tsxindex b82b2b76b1..61ec775190 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallQueueList.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/InstallQueueList.tsx@@ -1,10 +1,10 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { ModelInstallJob } from '@workbench/models/types';+import type { ModelInstallJob } from '@features/models/core/types';import { Flex, Spinner, Stack, Text } from '@chakra-ui/react';-import { Button, Scrollable } from '@workbench/components/ui';-import { refreshInstalls } from '@workbench/models/installsStore';-import { useNotify } from '@workbench/useNotify';+import { refreshInstalls } from '@features/models/data/installsStore';+import { useNotify } from '@features/models/ui/useModelsNotify';+import { Button, Scrollable } from '@platform/ui';import { useTranslation } from 'react-i18next';import { InstallJobRow } from './InstallJobRow';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/queueUtils.ts b/invokeai/frontend/webv2/src/features/models/ui/install-queue/queueUtils.tssimilarity index 80%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/queueUtils.tsrename to invokeai/frontend/webv2/src/features/models/ui/install-queue/queueUtils.tsindex 652c00ad07..64528e1128 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/queueUtils.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/install-queue/queueUtils.ts@@ -1,6 +1,6 @@-import type { ModelInstallJob, ModelInstallStatus } from '@workbench/models/types';+import type { ModelInstallJob, ModelInstallStatus } from '@features/models/core/types';-import { getInstallSourceLabel } from '@workbench/models/taxonomy';+import { getInstallSourceLabel } from '@features/models/core/taxonomy';export const STATUS_BADGES: Record<ModelInstallStatus, { label: string; palette: string }> = {cancelled: { label: 'Cancelled', palette: 'gray' },diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/MaintenanceMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsxsimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/library/MaintenanceMenu.tsxrename to invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsxindex 05269aefe1..fd5fdde5a9 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/MaintenanceMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx@@ -1,12 +1,12 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { OrphanedModelInfo } from '@workbench/models/types';+import type { OrphanedModelInfo } from '@features/models/core/types';import { Checkbox, Dialog, Flex, Icon, Menu, Portal, Spinner, Stack, Text } from '@chakra-ui/react';-import { Button, CloseButton, IconButton, MenuContent, Panel } from '@workbench/components/ui';-import { deleteOrphanedModels, emptyModelCache, getOrphanedModels } from '@workbench/models/api';-import { refreshModels } from '@workbench/models/modelsStore';-import { formatBytes } from '@workbench/models/taxonomy';-import { useNotify } from '@workbench/useNotify';+import { formatBytes } from '@features/models/core/taxonomy';+import { deleteOrphanedModels, emptyModelCache, getOrphanedModels } from '@features/models/data/api';+import { refreshModels } from '@features/models/data/modelsStore';+import { useNotify } from '@features/models/ui/useModelsNotify';+import { Button, CloseButton, IconButton, MenuContent, Panel } from '@platform/ui';import { BrushCleaningIcon, FolderSearchIcon, MoreHorizontalIcon, RefreshCcwIcon } from 'lucide-react';import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelFilterBar.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/ModelFilterBar.tsxsimilarity index 93%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelFilterBar.tsxrename to invokeai/frontend/webv2/src/features/models/ui/library/ModelFilterBar.tsxindex 61927e724d..4fd1e864f8 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelFilterBar.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/library/ModelFilterBar.tsx@@ -1,9 +1,9 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { ModelLibraryFilters, ModelSortField } from '@workbench/models/library';-import type { ModelTaxonomyType } from '@workbench/models/types';+import type { ModelLibraryFilters, ModelSortField } from '@features/models/core/library';+import type { ModelTaxonomyType } from '@features/models/core/types';import { HStack, Icon, Input, InputGroup } from '@chakra-ui/react';-import { FilterMenuItem, ModelFilterMenu } from '@workbench/launchpad/models/shared/ModelFilterMenu';+import { FilterMenuItem, ModelFilterMenu } from '@features/models/ui/shared/ModelFilterMenu';import { SearchIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelLibraryList.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsxsimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelLibraryList.tsxrename to invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsxindex f639f7ecb0..261f915d27 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelLibraryList.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsx@@ -1,18 +1,18 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import { Box, Checkbox, Flex, HStack, Icon, Image, ScrollArea, Spinner, Stack, Text } from '@chakra-ui/react';-import { Button, Row } from '@workbench/components/ui';-import { EmptyState } from '@workbench/components/ui/EmptyState';-import { MissingFileBadge, ModelBaseBadge, ModelFormatBadge } from '@workbench/launchpad/models/detail/ModelBadges';-import { getModelImageUrl } from '@workbench/models/api';import {filterModels,flattenGroupsToRows,groupModelsByType,type ModelLibraryFilters,-} from '@workbench/models/library';-import { useModelsSelector } from '@workbench/models/modelsStore';-import { formatBytes } from '@workbench/models/taxonomy';-import { getLibraryScrollOffset, openModelManagerTab, saveLibraryScrollOffset } from '@workbench/models/uiStore';+} from '@features/models/core/library';+import { formatBytes } from '@features/models/core/taxonomy';+import { getModelImageUrl } from '@features/models/data/api';+import { useModelsSelector } from '@features/models/data/modelsStore';+import { MissingFileBadge, ModelBaseBadge, ModelFormatBadge } from '@features/models/ui/detail/ModelBadges';+import { getLibraryScrollOffset, openModelManagerTab, saveLibraryScrollOffset } from '@features/models/ui/uiStore';+import { Button, Row } from '@platform/ui';+import { EmptyState } from '@platform/ui/EmptyState';import { ArrowRightIcon, BoxIcon, CircleAlert } from 'lucide-react';import { memo, useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';import { useVirtualizer } from 'react-hook-tanstack-virtual';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelRowContextMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsxsimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelRowContextMenu.tsxrename to invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsxindex d559d832dd..ba7a158121 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelRowContextMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsx@@ -1,11 +1,11 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { ModelConfig } from '@workbench/models/types';+import type { ModelConfig } from '@features/models/core/types';import { Icon, Menu, Portal } from '@chakra-ui/react';-import { ConfirmDialog, MenuContent } from '@workbench/components/ui';-import { useModelActions } from '@workbench/launchpad/models/detail/useModelActions';-import { isConvertibleToDiffusers } from '@workbench/models/baseIdentity';-import { useModelsSelector } from '@workbench/models/modelsStore';+import { isConvertibleToDiffusers } from '@features/models/core/baseIdentity';+import { useModelsSelector } from '@features/models/data/modelsStore';+import { useModelActions } from '@features/models/ui/detail/useModelActions';+import { ConfirmDialog, MenuContent } from '@platform/ui';import { RefreshCcwIcon, Trash2Icon } from 'lucide-react';import { useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/manager/DetailPane.tsx b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsxsimilarity index 87%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/manager/DetailPane.tsxrename to invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsxindex f6e56c08d4..bf749fa1a8 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/manager/DetailPane.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsx@@ -1,12 +1,12 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import { Box, Flex, Icon, Text } from '@chakra-ui/react';-import { Scrollable, Tabs } from '@workbench/components/ui';-import { AddModelsView } from '@workbench/launchpad/models/add-models/AddModelsView';-import { ApiKeysSection } from '@workbench/launchpad/models/credentials/ApiKeysSection';-import { ModelDetail } from '@workbench/launchpad/models/detail/ModelDetail';-import { InstallQueueBar } from '@workbench/launchpad/models/install-queue/InstallQueueBar';-import { useModelsSelector } from '@workbench/models/modelsStore';-import { updateModelsUi, useModelsUiSelector, type ModelManagerTab } from '@workbench/models/uiStore';+import { useModelsSelector } from '@features/models/data/modelsStore';+import { AddModelsView } from '@features/models/ui/add-models/AddModelsView';+import { ApiKeysSection } from '@features/models/ui/credentials/ApiKeysSection';+import { ModelDetail } from '@features/models/ui/detail/ModelDetail';+import { InstallQueueBar } from '@features/models/ui/install-queue/InstallQueueBar';+import { updateModelsUi, useModelsUiSelector, type ModelManagerTab } from '@features/models/ui/uiStore';+import { Scrollable, Tabs } from '@platform/ui';import { BoxIcon, KeyRoundIcon, PlusIcon } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/manager/LibraryColumn.tsx b/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsxsimilarity index 90%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/manager/LibraryColumn.tsxrename to invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsxindex fd9f376365..1466937818 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/manager/LibraryColumn.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx@@ -1,20 +1,20 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import { Box, Flex, HStack, Icon, Separator, Text } from '@chakra-ui/react';-import { Button, IconButton, ConfirmDialog } from '@workbench/components/ui';-import { MaintenanceMenu } from '@workbench/launchpad/models/library/MaintenanceMenu';-import { ModelFilterBar } from '@workbench/launchpad/models/library/ModelFilterBar';-import { ModelLibraryList } from '@workbench/launchpad/models/library/ModelLibraryList';-import { bulkDeleteModels } from '@workbench/models/api';-import { collectBases, collectTypes } from '@workbench/models/library';-import { refreshModels, removeModelsFromStore, useModelsSelector } from '@workbench/models/modelsStore';+import { collectBases, collectTypes } from '@features/models/core/library';+import { bulkDeleteModels } from '@features/models/data/api';+import { refreshModels, removeModelsFromStore, useModelsSelector } from '@features/models/data/modelsStore';+import { MaintenanceMenu } from '@features/models/ui/library/MaintenanceMenu';+import { ModelFilterBar } from '@features/models/ui/library/ModelFilterBar';+import { ModelLibraryList } from '@features/models/ui/library/ModelLibraryList';import {openModelDetail,pruneModelsUiKeys,toggleModelSelection,updateModelsUi,useModelsUiSelector,-} from '@workbench/models/uiStore';-import { useNotify } from '@workbench/useNotify';+} from '@features/models/ui/uiStore';+import { useNotify } from '@features/models/ui/useModelsNotify';+import { Button, IconButton, ConfirmDialog } from '@platform/ui';import { Trash2Icon, XIcon } from 'lucide-react';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/manager/layoutConstants.ts b/invokeai/frontend/webv2/src/features/models/ui/manager/layoutConstants.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/manager/layoutConstants.tsrename to invokeai/frontend/webv2/src/features/models/ui/manager/layoutConstants.tsdiff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/shared/ModelFilterMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsxsimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/shared/ModelFilterMenu.tsxrename to invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsxindex 0ba6de199c..10f6714803 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/shared/ModelFilterMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx@@ -1,12 +1,12 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { ModelSortField } from '@workbench/models/library';-import type { ModelTaxonomyType } from '@workbench/models/types';+import type { ModelSortField } from '@features/models/core/library';+import type { ModelTaxonomyType } from '@features/models/core/types';import type { ReactNode } from 'react';import { Icon, Menu, Portal, Text } from '@chakra-ui/react';-import { IconButton, MenuContent } from '@workbench/components/ui';-import { getModelBaseLabel } from '@workbench/models/baseIdentity';-import { getModelTypeLabel } from '@workbench/models/taxonomy';+import { getModelBaseLabel } from '@features/models/core/baseIdentity';+import { getModelTypeLabel } from '@features/models/core/taxonomy';+import { IconButton, MenuContent } from '@platform/ui';import { CheckIcon, SlidersHorizontalIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/shared/ResultsListHeader.tsx b/invokeai/frontend/webv2/src/features/models/ui/shared/ResultsListHeader.tsxsimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/shared/ResultsListHeader.tsxrename to invokeai/frontend/webv2/src/features/models/ui/shared/ResultsListHeader.tsxindex 70533a7567..474669bbaf 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/shared/ResultsListHeader.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/ResultsListHeader.tsx@@ -1,5 +1,5 @@import { HStack, Icon, Input, InputGroup, Stack, Text } from '@chakra-ui/react';-import { Button, IconButton } from '@workbench/components/ui';+import { Button, IconButton } from '@platform/ui';import { DownloadIcon, SearchIcon, XIcon } from 'lucide-react';import { useCallback, type ChangeEvent, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/shared/SourceListItem.tsx b/invokeai/frontend/webv2/src/features/models/ui/shared/SourceListItem.tsxsimilarity index 93%rename from invokeai/frontend/webv2/src/workbench/launchpad/models/shared/SourceListItem.tsxrename to invokeai/frontend/webv2/src/features/models/ui/shared/SourceListItem.tsxindex 93b04aa6b5..5fb4494a1f 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/shared/SourceListItem.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/SourceListItem.tsx@@ -2,9 +2,9 @@import type { ReactNode } from 'react';import { Badge, HStack, Icon, Spinner, Stack, Text } from '@chakra-ui/react';-import { Button, Panel } from '@workbench/components/ui';-import { useActiveInstallSources } from '@workbench/models/installsStore';-import { openInstallQueue } from '@workbench/models/uiStore';+import { useActiveInstallSources } from '@features/models/data/installsStore';+import { openInstallQueue } from '@features/models/ui/uiStore';+import { Button, Panel } from '@platform/ui';import { DownloadIcon } from 'lucide-react';/**diff --git a/invokeai/frontend/webv2/src/workbench/models/uiStore.ts b/invokeai/frontend/webv2/src/features/models/ui/uiStore.tssimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/models/uiStore.tsrename to invokeai/frontend/webv2/src/features/models/ui/uiStore.tsindex 57b2c52667..366c4281e1 100644--- a/invokeai/frontend/webv2/src/workbench/models/uiStore.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts@@ -1,8 +1,7 @@-import { createExternalStore } from '@workbench/externalStore';+import type { FoundModel } from '@features/models/core/types';-import type { FoundModel } from './types';--import { DEFAULT_LIBRARY_FILTERS, type ModelLibraryFilters } from './library';+import { DEFAULT_LIBRARY_FILTERS, type ModelLibraryFilters } from '@features/models/core/library';+import { createExternalStore } from '@platform/state/externalStore';/*** Session-lived UI state for the model manager. Views unmount whenever the userdiff --git a/invokeai/frontend/webv2/src/workbench/models/useInstallOutcomeToasts.ts b/invokeai/frontend/webv2/src/features/models/ui/useInstallOutcomeToasts.tssimilarity index 89%rename from invokeai/frontend/webv2/src/workbench/models/useInstallOutcomeToasts.tsrename to invokeai/frontend/webv2/src/features/models/ui/useInstallOutcomeToasts.tsindex 1279c2b00f..e2d9553886 100644--- a/invokeai/frontend/webv2/src/workbench/models/useInstallOutcomeToasts.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/useInstallOutcomeToasts.ts@@ -1,8 +1,7 @@-import { useNotify } from '@workbench/useNotify';+import { useInstallOutcomes } from '@features/models/data/installsStore';+import { useNotify } from '@features/models/ui/useModelsNotify';import { useEffect, useRef } from 'react';-import { useInstallOutcomes } from './installsStore';-/*** Turns settled install outcomes (completed/failed/cancelled) into notifications,* while the model manager is mounted. Provider-free: `useNotify` falls back todiff --git a/invokeai/frontend/webv2/src/features/models/ui/useModelsNotify.ts b/invokeai/frontend/webv2/src/features/models/ui/useModelsNotify.tsnew file mode 100644index 0000000000..543b6c9364--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/ui/useModelsNotify.ts@@ -0,0 +1,19 @@+import { toaster } from '@platform/ui';++export interface ModelsNotify {+ error(title: string, message?: string): void;+ info(title: string, message?: string): void;+ success(title: string, message?: string): void;+}++const createNotice = (type: 'error' | 'info' | 'success') => (title: string, message?: string) => {+ toaster.create({ description: message, title, type });+};++const modelsNotify: ModelsNotify = {+ error: createNotice('error'),+ info: createNotice('info'),+ success: createNotice('success'),+};++export const useNotify = (): ModelsNotify => modelsNotify;diff --git a/invokeai/frontend/webv2/src/features/nodes/core/catalog.test.ts b/invokeai/frontend/webv2/src/features/nodes/core/catalog.test.tsnew file mode 100644index 0000000000..f7e970cf51--- /dev/null+++ b/invokeai/frontend/webv2/src/features/nodes/core/catalog.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest';++import { normalizeNodePackCatalog, normalizeNodePackInfo } from './catalog';++describe('node catalog normalization', () => {+ it('maps backend fields into the owned descriptor vocabulary', () => {+ expect(+ normalizeNodePackInfo({+ name: 'invokeai-node-pack',+ node_count: 3,+ node_types: ['alpha', 'beta', 42],+ path: '/nodes/invokeai-node-pack',+ })+ ).toEqual({+ name: 'invokeai-node-pack',+ nodeCount: 3,+ nodeTypes: ['alpha', 'beta'],+ path: '/nodes/invokeai-node-pack',+ });+ });++ it('drops invalid packs and heals optional catalog fields', () => {+ expect(+ normalizeNodePackCatalog({+ custom_nodes_path: '/nodes',+ node_packs: [{ name: 'valid', path: '/nodes/valid' }, { name: 'missing-path' }, null],+ })+ ).toEqual({+ customNodesPath: '/nodes',+ nodePacks: [{ name: 'valid', nodeCount: 0, nodeTypes: [], path: '/nodes/valid' }],+ });+ });+});diff --git a/invokeai/frontend/webv2/src/features/nodes/core/catalog.ts b/invokeai/frontend/webv2/src/features/nodes/core/catalog.tsnew file mode 100644index 0000000000..60f933508e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/nodes/core/catalog.ts@@ -0,0 +1,43 @@+export interface NodePackInfo {+ name: string;+ path: string;+ nodeCount: number;+ nodeTypes: string[];+}++export interface NodePackCatalog {+ customNodesPath: string;+ nodePacks: NodePackInfo[];+}++const asRecord = (value: unknown): Record<string, unknown> | null =>+ value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null;++export const normalizeNodePackInfo = (value: unknown): NodePackInfo | null => {+ const record = asRecord(value);++ if (!record || typeof record.name !== 'string' || typeof record.path !== 'string') {+ return null;+ }++ return {+ name: record.name,+ nodeCount: typeof record.node_count === 'number' && Number.isFinite(record.node_count) ? record.node_count : 0,+ nodeTypes: Array.isArray(record.node_types)+ ? record.node_types.filter((nodeType): nodeType is string => typeof nodeType === 'string')+ : [],+ path: record.path,+ };+};++export const normalizeNodePackCatalog = (value: unknown): NodePackCatalog => {+ const record = asRecord(value);+ const nodePacks = Array.isArray(record?.node_packs)+ ? record.node_packs.map(normalizeNodePackInfo).filter((pack): pack is NodePackInfo => pack !== null)+ : [];++ return {+ customNodesPath: typeof record?.custom_nodes_path === 'string' ? record.custom_nodes_path : '',+ nodePacks,+ };+};diff --git a/invokeai/frontend/webv2/src/features/nodes/core/executionContracts.ts b/invokeai/frontend/webv2/src/features/nodes/core/executionContracts.tsnew file mode 100644index 0000000000..71a51bc248--- /dev/null+++ b/invokeai/frontend/webv2/src/features/nodes/core/executionContracts.ts@@ -0,0 +1,13 @@+export interface NodeInvocationStartedEvent {+ invocation_source_id: string;+}++export interface NodeInvocationCompleteEvent {+ invocation_source_id: string;+ result: unknown;+}++export interface NodeInvocationErrorEvent {+ invocation_source_id: string;+ error_message: string;+}diff --git a/invokeai/frontend/webv2/src/features/nodes/data/api.test.ts b/invokeai/frontend/webv2/src/features/nodes/data/api.test.tsnew file mode 100644index 0000000000..c25996de8e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/nodes/data/api.test.ts@@ -0,0 +1,50 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { NodesDataPort } from './transport';++const adapter = vi.hoisted(() => ({ request: vi.fn(), requestJson: vi.fn() }));++vi.mock('./transport', () => ({+ browserNodesDataPort: {+ buildUrl: (path: string) => path,+ request: adapter.request,+ requestJson: adapter.requestJson,+ } satisfies NodesDataPort,+}));++beforeEach(() => {+ adapter.request.mockReset().mockResolvedValue(new Response());+ adapter.requestJson.mockReset();+});++describe('custom node data adapter', () => {+ it('normalizes catalog DTOs returned by the fixture adapter', async () => {+ adapter.requestJson.mockResolvedValue({+ custom_nodes_path: '/nodes',+ node_packs: [{ name: 'pack', node_count: 2, node_types: ['one', 'two'], path: '/nodes/pack' }],+ });+ const { listCustomNodePacks } = await import('./api');++ await expect(listCustomNodePacks()).resolves.toEqual({+ customNodesPath: '/nodes',+ nodePacks: [{ name: 'pack', nodeCount: 2, nodeTypes: ['one', 'two'], path: '/nodes/pack' }],+ });+ expect(adapter.requestJson).toHaveBeenCalledWith('/api/v2/custom_nodes/');+ });++ it('encodes pack identifiers and sends install intent in the body', async () => {+ adapter.requestJson.mockResolvedValue({ success: true });+ const { installCustomNodePack, uninstallCustomNodePack } = await import('./api');++ await installCustomNodePack('https://example.test/nodes.git');+ await uninstallCustomNodePack('pack/with spaces');++ expect(adapter.requestJson).toHaveBeenNthCalledWith(1, '/api/v2/custom_nodes/install', {+ body: JSON.stringify({ source: 'https://example.test/nodes.git' }),+ method: 'POST',+ });+ expect(adapter.requestJson).toHaveBeenNthCalledWith(2, '/api/v2/custom_nodes/pack%2Fwith%20spaces', {+ method: 'DELETE',+ });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/customNodes/api.ts b/invokeai/frontend/webv2/src/features/nodes/data/api.tssimilarity index 52%rename from invokeai/frontend/webv2/src/workbench/customNodes/api.tsrename to invokeai/frontend/webv2/src/features/nodes/data/api.tsindex eec33c2f4a..b2f5f78c9b 100644--- a/invokeai/frontend/webv2/src/workbench/customNodes/api.ts+++ b/invokeai/frontend/webv2/src/features/nodes/data/api.ts@@ -1,20 +1,11 @@-import { apiFetch, apiFetchJson } from '@workbench/backend/http';+import { normalizeNodePackCatalog, type NodePackCatalog } from '@features/nodes/core/catalog';++import { browserNodesDataPort } from './transport';/** REST client for the custom nodes manager (`/api/v2/custom_nodes`). */const CUSTOM_NODES_BASE = '/api/v2/custom_nodes';--export interface NodePackInfo {- name: string;- path: string;- node_count: number;- node_types: string[];-}--export interface NodePackListResponse {- node_packs: NodePackInfo[];- custom_nodes_path: string;-}+const { request, requestJson } = browserNodesDataPort;export interface InstallNodePackResponse {name: string;@@ -31,18 +22,18 @@ export interface UninstallNodePackResponse {message: string;}-export const listCustomNodePacks = (): Promise<NodePackListResponse> =>- apiFetchJson<NodePackListResponse>(`${CUSTOM_NODES_BASE}/`);+export const listCustomNodePacks = async (): Promise<NodePackCatalog> =>+ normalizeNodePackCatalog(await requestJson<unknown>(`${CUSTOM_NODES_BASE}/`));export const installCustomNodePack = (source: string): Promise<InstallNodePackResponse> =>- apiFetchJson<InstallNodePackResponse>(`${CUSTOM_NODES_BASE}/install`, {+ requestJson<InstallNodePackResponse>(`${CUSTOM_NODES_BASE}/install`, {body: JSON.stringify({ source }),method: 'POST',});export const uninstallCustomNodePack = (packName: string): Promise<UninstallNodePackResponse> =>- apiFetchJson<UninstallNodePackResponse>(`${CUSTOM_NODES_BASE}/${encodeURIComponent(packName)}`, { method: 'DELETE' });+ requestJson<UninstallNodePackResponse>(`${CUSTOM_NODES_BASE}/${encodeURIComponent(packName)}`, { method: 'DELETE' });export const reloadCustomNodes = async (): Promise<void> => {- await apiFetch(`${CUSTOM_NODES_BASE}/reload`, { method: 'POST' });+ await request(`${CUSTOM_NODES_BASE}/reload`, { method: 'POST' });};diff --git a/invokeai/frontend/webv2/src/workbench/customNodes/installLogStore.ts b/invokeai/frontend/webv2/src/features/nodes/data/installLogStore.tssimilarity index 92%rename from invokeai/frontend/webv2/src/workbench/customNodes/installLogStore.tsrename to invokeai/frontend/webv2/src/features/nodes/data/installLogStore.tsindex 9acd002ff5..71257e26b1 100644--- a/invokeai/frontend/webv2/src/workbench/customNodes/installLogStore.ts+++ b/invokeai/frontend/webv2/src/features/nodes/data/installLogStore.ts@@ -1,4 +1,4 @@-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';export interface CustomNodeInstallLogEntry {id: number;diff --git a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.test.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.test.tsnew file mode 100644index 0000000000..c2b33d3d3f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.test.ts@@ -0,0 +1,44 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('./transport', () => ({+ browserNodesDataPort: {+ buildUrl: (path: string) => `https://api.test${path}`,+ request: vi.fn(),+ requestJson: vi.fn(),+ },+}));++import { nodeExecutionStore } from './nodeExecutionStore';++beforeEach(() => {+ nodeExecutionStore.clearAll();+});++describe('node execution lifecycle', () => {+ it('preserves the latest image across progress and failure transitions', () => {+ nodeExecutionStore.completed({+ invocation_source_id: 'node-1',+ result: { image: { image_name: 'result image.png' } },+ });+ nodeExecutionStore.progress('node-1', 0.5, 'Sampling');+ nodeExecutionStore.failed({ error_message: 'Out of memory', invocation_source_id: 'node-1' });++ expect(nodeExecutionStore.get('node-1')).toEqual({+ error: 'Out of memory',+ outputImageUrl: 'https://api.test/api/v1/images/i/result%20image.png/thumbnail',+ progress: null,+ progressMessage: null,+ status: 'failed',+ });+ });++ it('settles every running node without disturbing terminal state', () => {+ nodeExecutionStore.started({ invocation_source_id: 'running' });+ nodeExecutionStore.failed({ error_message: 'failed', invocation_source_id: 'terminal' });++ nodeExecutionStore.settleRunning();++ expect(nodeExecutionStore.get('running')?.status).toBe('completed');+ expect(nodeExecutionStore.get('terminal')?.status).toBe('failed');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/backend/nodeExecutionStore.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.tssimilarity index 69%rename from invokeai/frontend/webv2/src/workbench/backend/nodeExecutionStore.tsrename to invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.tsindex 477f732f64..2da9b29db7 100644--- a/invokeai/frontend/webv2/src/workbench/backend/nodeExecutionStore.ts+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts@@ -1,8 +1,12 @@-import { createKeyedTransientStore } from '@workbench/externalStore';+import type {+ NodeInvocationCompleteEvent,+ NodeInvocationErrorEvent,+ NodeInvocationStartedEvent,+} from '@features/nodes/core/executionContracts';-import type { InvocationCompleteEvent, InvocationErrorEvent, InvocationStartedEvent } from './events';+import { createKeyedTransientStore } from '@platform/state/externalStore';-import { buildApiUrl } from './http';+import { browserNodesDataPort } from './transport';/*** Ephemeral per-node execution state, keyed by the invocation's source node id@@ -27,7 +31,7 @@ export interface NodeExecutionState {const stateByNodeId = createKeyedTransientStore<string, NodeExecutionState>();/** Pull the produced image out of an invocation output, whatever the node type. */-const getResultImageName = (result: InvocationCompleteEvent['result']): string | null => {+const getResultImageName = (result: unknown): string | null => {const image = (result as { image?: { image_name?: unknown } }).image;return typeof image?.image_name === 'string' ? image.image_name : null;@@ -37,21 +41,27 @@ export const nodeExecutionStore = {clearAll(): void {stateByNodeId.clear();},- completed(event: InvocationCompleteEvent): void {+ get(nodeId: string): NodeExecutionState | null {+ return stateByNodeId.get(nodeId) ?? null;+ },+ subscribe(nodeId: string, listener: () => void): () => void {+ return stateByNodeId.subscribeKey(nodeId, listener);+ },+ completed(event: NodeInvocationCompleteEvent): void {const imageName = getResultImageName(event.result);const previous = stateByNodeId.get(event.invocation_source_id);stateByNodeId.set(event.invocation_source_id, {error: null,outputImageUrl: imageName- ? buildApiUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}/thumbnail`)+ ? browserNodesDataPort.buildUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}/thumbnail`): (previous?.outputImageUrl ?? null),progress: null,progressMessage: null,status: 'completed',});},- failed(event: InvocationErrorEvent): void {+ failed(event: NodeInvocationErrorEvent): void {const previous = stateByNodeId.get(event.invocation_source_id);stateByNodeId.set(event.invocation_source_id, {@@ -81,7 +91,7 @@ export const nodeExecutionStore = {}}},- started(event: InvocationStartedEvent): void {+ started(event: NodeInvocationStartedEvent): void {const previous = stateByNodeId.get(event.invocation_source_id);stateByNodeId.set(event.invocation_source_id, {@@ -94,7 +104,16 @@ export const nodeExecutionStore = {},};-export type NodeExecutionSink = typeof nodeExecutionStore;+export interface NodeExecutionSink {+ clearAll(): void;+ completed(event: NodeInvocationCompleteEvent): void;+ failed(event: NodeInvocationErrorEvent): void;+ get(nodeId: string): NodeExecutionState | null;+ progress(nodeId: string, percentage: number | null, message: string): void;+ settleRunning(): void;+ started(event: NodeInvocationStartedEvent): void;+ subscribe(nodeId: string, listener: () => void): () => void;+}export const useNodeExecutionState = (nodeId: string): NodeExecutionState | null =>stateByNodeId.useValue(nodeId) ?? null;diff --git a/invokeai/frontend/webv2/src/workbench/customNodes/nodesStore.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.tssimilarity index 84%rename from invokeai/frontend/webv2/src/workbench/customNodes/nodesStore.tsrename to invokeai/frontend/webv2/src/features/nodes/data/nodesStore.tsindex da7474a603..7ac56f63f4 100644--- a/invokeai/frontend/webv2/src/workbench/customNodes/nodesStore.ts+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.ts@@ -1,7 +1,7 @@-import { getApiErrorMessage } from '@workbench/backend/http';-import { createExternalStore } from '@workbench/externalStore';+import type { NodePackInfo } from '@features/nodes/core/catalog';-import type { NodePackInfo } from './api';+import { createExternalStore } from '@platform/state/externalStore';+import { getApiErrorMessage } from '@platform/transport/http';import { listCustomNodePacks } from './api';@@ -31,9 +31,9 @@ export const refreshCustomNodePacks = (): Promise<void> => {inflightRefresh = listCustomNodePacks().then((response) => {store.patchSnapshot({- customNodesPath: response.custom_nodes_path,+ customNodesPath: response.customNodesPath,error: null,- nodePacks: response.node_packs,+ nodePacks: response.nodePacks,status: 'loaded',});})diff --git a/invokeai/frontend/webv2/src/features/nodes/data/transport.ts b/invokeai/frontend/webv2/src/features/nodes/data/transport.tsnew file mode 100644index 0000000000..f1e95e0029--- /dev/null+++ b/invokeai/frontend/webv2/src/features/nodes/data/transport.ts@@ -0,0 +1,13 @@+import { apiFetch, apiFetchJson, buildApiUrl } from '@platform/transport/http';++export interface NodesDataPort {+ buildUrl(path: string): string;+ request(path: string, init?: RequestInit): Promise<Response>;+ requestJson<T>(path: string, init?: RequestInit): Promise<T>;+}++export const browserNodesDataPort: NodesDataPort = {+ buildUrl: buildApiUrl,+ request: apiFetch,+ requestJson: apiFetchJson,+};diff --git a/invokeai/frontend/webv2/src/features/nodes/index.ts b/invokeai/frontend/webv2/src/features/nodes/index.tsnew file mode 100644index 0000000000..8f562e0e68--- /dev/null+++ b/invokeai/frontend/webv2/src/features/nodes/index.ts@@ -0,0 +1,21 @@+export type {+ NodeInvocationCompleteEvent,+ NodeInvocationErrorEvent,+ NodeInvocationStartedEvent,+} from './core/executionContracts';+export type { NodePackInfo } from './core/catalog';+export {+ ensureCustomNodePacksLoaded,+ refreshCustomNodePacks,+ useCustomNodesSelector,+ useCustomNodesSnapshot,+ type CustomNodesSnapshot,+} from './data/nodesStore';+export {+ nodeExecutionStore,+ useNodeExecutionState,+ type NodeExecutionSink,+ type NodeExecutionState,+ type NodeExecutionStatus,+} from './data/nodeExecutionStore';+export { NodesPage } from './ui/NodesPage';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/NodeManagerView.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/NodeManagerView.tsxsimilarity index 74%rename from invokeai/frontend/webv2/src/workbench/launchpad/nodes/NodeManagerView.tsxrename to invokeai/frontend/webv2/src/features/nodes/ui/NodeManagerView.tsxindex 89e7afcb64..806e9eeec7 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/NodeManagerView.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/NodeManagerView.tsx@@ -1,15 +1,15 @@import { Flex } from '@chakra-ui/react';-import { ensureCustomNodePacksLoaded } from '@workbench/customNodes/nodesStore';-import { useEffect } from 'react';+import { ensureCustomNodePacksLoaded } from '@features/nodes/data/nodesStore';+import { useMountEffect } from '@platform/react/useMountEffect';import { DetailPane } from './manager/DetailPane';import { LibraryColumn } from './manager/LibraryColumn';/** Full custom nodes manager: persistent pack library plus right-side detail pane. */export const NodeManagerView = () => {- useEffect(() => {+ useMountEffect(() => {ensureCustomNodePacksLoaded();- }, []);+ });return (<Flex direction="column" h="full" minH="0" w="full">diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/pages/NodesPage.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/NodesPage.tsxsimilarity index 75%rename from invokeai/frontend/webv2/src/workbench/launchpad/pages/NodesPage.tsxrename to invokeai/frontend/webv2/src/features/nodes/ui/NodesPage.tsxindex 52081a89e5..92afc102ec 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/pages/NodesPage.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/NodesPage.tsx@@ -2,7 +2,7 @@ import { Center, Spinner } from '@chakra-ui/react';import { lazy, Suspense } from 'react';const NodeManagerView = lazy(() =>- import('@workbench/launchpad/nodes/NodeManagerView').then((module) => ({ default: module.NodeManagerView }))+ import('@features/nodes/ui/NodeManagerView').then((module) => ({ default: module.NodeManagerView })));const FALLBACK = (diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/activity/NodeActivityBar.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/activity/NodeActivityBar.tsxsimilarity index 94%rename from invokeai/frontend/webv2/src/workbench/launchpad/nodes/activity/NodeActivityBar.tsxrename to invokeai/frontend/webv2/src/features/nodes/ui/activity/NodeActivityBar.tsxindex 5abbab32d2..d8c84b74e9 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/activity/NodeActivityBar.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/activity/NodeActivityBar.tsx@@ -1,8 +1,8 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import { Badge, Box, Collapsible, Flex, HStack, Icon, Spinner, Text } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';-import { clearCustomNodeInstallLog, useCustomNodeInstallLog } from '@workbench/customNodes/installLogStore';-import { setNodeActivityExpanded, useNodesUiSelector } from '@workbench/customNodes/nodesUiStore';+import { clearCustomNodeInstallLog, useCustomNodeInstallLog } from '@features/nodes/data/installLogStore';+import { setNodeActivityExpanded, useNodesUiSelector } from '@features/nodes/ui/nodesUiStore';+import { Button } from '@platform/ui';import { ChevronUpIcon, ListOrderedIcon, Trash2Icon } from 'lucide-react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/activity/NodeInstallLog.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/activity/NodeInstallLog.tsxsimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/launchpad/nodes/activity/NodeInstallLog.tsxrename to invokeai/frontend/webv2/src/features/nodes/ui/activity/NodeInstallLog.tsxindex 3153d4f5b0..fab9511b73 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/activity/NodeInstallLog.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/activity/NodeInstallLog.tsx@@ -1,11 +1,11 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import type { SystemStyleObject } from '@chakra-ui/react';-import type { CustomNodeInstallLogEntry } from '@workbench/customNodes/installLogStore';+import type { CustomNodeInstallLogEntry } from '@features/nodes/data/installLogStore';import { Badge, Icon, Table, Text } from '@chakra-ui/react';-import { Scrollable } from '@workbench/components/ui';-import { EmptyState } from '@workbench/components/ui/EmptyState';-import { useCustomNodeInstallLog } from '@workbench/customNodes/installLogStore';+import { useCustomNodeInstallLog } from '@features/nodes/data/installLogStore';+import { Scrollable } from '@platform/ui';+import { EmptyState } from '@platform/ui/EmptyState';import { InboxIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/add-nodes/AddNodesView.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsxsimilarity index 93%rename from invokeai/frontend/webv2/src/workbench/launchpad/nodes/add-nodes/AddNodesView.tsxrename to invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsxindex b032bfd188..d43bf25119 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/add-nodes/AddNodesView.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsx@@ -1,10 +1,10 @@import { Alert, Box, HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';-import { getApiErrorMessage } from '@workbench/backend/http';-import { Button, Field, Scrollable, Tabs, toaster } from '@workbench/components/ui';-import { installCustomNodePack } from '@workbench/customNodes/api';-import { addCustomNodeInstallLogEntry } from '@workbench/customNodes/installLogStore';-import { refreshCustomNodePacks, useCustomNodesSelector } from '@workbench/customNodes/nodesStore';-import { updateNodesUi, useNodesUiSelector, type AddNodesTab } from '@workbench/customNodes/nodesUiStore';+import { installCustomNodePack } from '@features/nodes/data/api';+import { addCustomNodeInstallLogEntry } from '@features/nodes/data/installLogStore';+import { refreshCustomNodePacks, useCustomNodesSelector } from '@features/nodes/data/nodesStore';+import { updateNodesUi, useNodesUiSelector, type AddNodesTab } from '@features/nodes/ui/nodesUiStore';+import { getApiErrorMessage } from '@platform/transport/http';+import { Button, Field, Scrollable, Tabs, toaster } from '@platform/ui';import { FolderOpenIcon, GitBranchIcon } from 'lucide-react';import { useCallback, useState, type ChangeEvent, type KeyboardEvent } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/detail/NodePackDetail.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePackDetail.tsxsimilarity index 87%rename from invokeai/frontend/webv2/src/workbench/launchpad/nodes/detail/NodePackDetail.tsxrename to invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePackDetail.tsxindex eb6e02d698..84bce9c52f 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/detail/NodePackDetail.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePackDetail.tsx@@ -1,11 +1,11 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { NodePackInfo } from '@workbench/customNodes/api';+import type { NodePackInfo } from '@features/nodes/core/catalog';import { Badge, Box, Flex, HStack, Icon, Spinner, Stack, Text } from '@chakra-ui/react';-import { Button, ConfirmDialog } from '@workbench/components/ui';-import { EmptyState } from '@workbench/components/ui/EmptyState';-import { useNodePackActions } from '@workbench/launchpad/nodes/shared/useNodePackActions';-import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSelector } from '@workbench/workflows/templates';+import { useNodePackActions } from '@features/nodes/ui/shared/useNodePackActions';+import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSelector } from '@features/workflow/react';+import { Button, ConfirmDialog } from '@platform/ui';+import { EmptyState } from '@platform/ui/EmptyState';import { BlocksIcon, TriangleAlertIcon, Trash2Icon } from 'lucide-react';import { useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -16,7 +16,7 @@ import { NodePreviewCard } from './NodePreviewCard';* Detail pane for a selected pack: a metadata header with an uninstall action,* then a live preview of every node the pack contributes. Previews are built* from the invocation templates the backend parsed from its OpenAPI schema —- * `pack.node_types` are the exact invocation type keys, and a pack's nodes all+ * `pack.nodeTypes` are the exact invocation type keys, and a pack's nodes all* share `template.nodePack === pack.name`.*/export const NodePackDetail = ({ onUninstalled, pack }: { onUninstalled: () => void; pack: NodePackInfo }) => {@@ -29,8 +29,8 @@ export const NodePackDetail = ({ onUninstalled, pack }: { onUninstalled: () => v}, []);const packTemplates = useMemo(- () => pack.node_types.map((nodeType) => templates[nodeType]).filter((template) => template !== undefined),- [pack.node_types, templates]+ () => pack.nodeTypes.map((nodeType) => templates[nodeType]).filter((template) => template !== undefined),+ [pack.nodeTypes, templates]);const isLoadingTemplates = (status === 'idle' || status === 'loading') && packTemplates.length === 0;@@ -50,7 +50,7 @@ export const NodePackDetail = ({ onUninstalled, pack }: { onUninstalled: () => v</Text><HStack gap="1.5" wrap="wrap"><Badge colorPalette="blue" fontSize="2xs" variant="surface">- {t('nodes.nodeCount', { count: pack.node_count })}+ {t('nodes.nodeCount', { count: pack.nodeCount })}</Badge></HStack></Stack>diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/detail/NodePreviewCard.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.tsxsimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/launchpad/nodes/detail/NodePreviewCard.tsxrename to invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.tsxindex b9435c50af..e400a74b62 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/detail/NodePreviewCard.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.tsx@@ -4,12 +4,12 @@ import type {FieldOutputTemplate,FieldType,InvocationTemplate,-} from '@workbench/workflows/types';+} from '@features/workflow/contracts';import { Box, Flex, Icon, Stack, Text } from '@chakra-ui/react';-import { Tooltip } from '@workbench/components/ui';-import { getWorkflowNodeChromeProps } from '@workbench/widgets/workflow/editor/nodeChrome';-import { getFieldTypeColor, getFieldTypeLabel, isModelFieldType } from '@workbench/workflows/fields';+import { getWorkflowNodeChromeProps } from '@features/workflow/preview';+import { getFieldTypeColor, getFieldTypeLabel, isModelFieldType } from '@features/workflow/utility';+import { Tooltip } from '@platform/ui';import { InfoIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/library/NodePackContextMenu.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackContextMenu.tsxsimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/launchpad/nodes/library/NodePackContextMenu.tsxrename to invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackContextMenu.tsxindex 5e649583bc..d71cbfafdf 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/library/NodePackContextMenu.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackContextMenu.tsx@@ -1,9 +1,9 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { NodePackInfo } from '@workbench/customNodes/api';+import type { NodePackInfo } from '@features/nodes/core/catalog';import { Icon, Menu, Portal } from '@chakra-ui/react';-import { ConfirmDialog, MenuContent } from '@workbench/components/ui';-import { useNodePackActions } from '@workbench/launchpad/nodes/shared/useNodePackActions';+import { useNodePackActions } from '@features/nodes/ui/shared/useNodePackActions';+import { ConfirmDialog, MenuContent } from '@platform/ui';import { Trash2Icon } from 'lucide-react';import { useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/library/NodePackList.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackList.tsxsimilarity index 94%rename from invokeai/frontend/webv2/src/workbench/launchpad/nodes/library/NodePackList.tsxrename to invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackList.tsxindex adab87b4a5..92093b3cda 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/library/NodePackList.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackList.tsx@@ -1,10 +1,10 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { NodePackInfo } from '@workbench/customNodes/api';+import type { NodePackInfo } from '@features/nodes/core/catalog';import { Badge, Flex, Icon, Input, InputGroup, Spinner, Stack, Text } from '@chakra-ui/react';-import { Button, Row, Scrollable } from '@workbench/components/ui';-import { EmptyState } from '@workbench/components/ui/EmptyState';-import { refreshCustomNodePacks } from '@workbench/customNodes/nodesStore';+import { refreshCustomNodePacks } from '@features/nodes/data/nodesStore';+import { Button, Row, Scrollable } from '@platform/ui';+import { EmptyState } from '@platform/ui/EmptyState';import { BlocksIcon, PackageOpenIcon, SearchIcon, TriangleAlertIcon } from 'lucide-react';import { useDeferredValue, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -161,7 +161,7 @@ const PackRow = ({variant={isActive ? 'solid' : 'surface'}ms="auto">- {pack.node_count}+ {pack.nodeCount}</Badge></Row>);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/DetailPane.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/manager/DetailPane.tsxsimilarity index 87%rename from invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/DetailPane.tsxrename to invokeai/frontend/webv2/src/features/nodes/ui/manager/DetailPane.tsxindex fe7beafa68..a862680790 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/DetailPane.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/manager/DetailPane.tsx@@ -1,11 +1,11 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import { Box, Flex, Icon, Text } from '@chakra-ui/react';-import { Scrollable, Tabs } from '@workbench/components/ui';-import { useCustomNodesSelector } from '@workbench/customNodes/nodesStore';-import { updateNodesUi, useNodesUiSelector, type NodesManagerTab } from '@workbench/customNodes/nodesUiStore';-import { NodeActivityBar } from '@workbench/launchpad/nodes/activity/NodeActivityBar';-import { AddNodesView } from '@workbench/launchpad/nodes/add-nodes/AddNodesView';-import { NodePackDetail } from '@workbench/launchpad/nodes/detail/NodePackDetail';+import { useCustomNodesSelector } from '@features/nodes/data/nodesStore';+import { NodeActivityBar } from '@features/nodes/ui/activity/NodeActivityBar';+import { AddNodesView } from '@features/nodes/ui/add-nodes/AddNodesView';+import { NodePackDetail } from '@features/nodes/ui/detail/NodePackDetail';+import { updateNodesUi, useNodesUiSelector, type NodesManagerTab } from '@features/nodes/ui/nodesUiStore';+import { Scrollable, Tabs } from '@platform/ui';import { BlocksIcon, PlusIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/LibraryColumn.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/manager/LibraryColumn.tsxsimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/LibraryColumn.tsxrename to invokeai/frontend/webv2/src/features/nodes/ui/manager/LibraryColumn.tsxindex 3fd4e0b552..be19e99c75 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/LibraryColumn.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/manager/LibraryColumn.tsx@@ -1,8 +1,8 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import { Box, Flex, HStack, Text } from '@chakra-ui/react';-import { useCustomNodesSelector } from '@workbench/customNodes/nodesStore';-import { openNodePackDetail, updateNodesUi, useNodesUiSelector } from '@workbench/customNodes/nodesUiStore';-import { NodePackList } from '@workbench/launchpad/nodes/library/NodePackList';+import { useCustomNodesSelector } from '@features/nodes/data/nodesStore';+import { NodePackList } from '@features/nodes/ui/library/NodePackList';+import { openNodePackDetail, updateNodesUi, useNodesUiSelector } from '@features/nodes/ui/nodesUiStore';import { useTranslation } from 'react-i18next';import { HEADER_MIN_HEIGHT, PACK_LIBRARY_WIDTH } from './layoutConstants';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/ReloadNodesButton.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.tsxsimilarity index 81%rename from invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/ReloadNodesButton.tsxrename to invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.tsxindex 0e20e41110..2a92ef0ea7 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/ReloadNodesButton.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.tsx@@ -1,10 +1,10 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import { Icon } from '@chakra-ui/react';-import { getApiErrorMessage } from '@workbench/backend/http';-import { Button } from '@workbench/components/ui';-import { reloadCustomNodes } from '@workbench/customNodes/api';-import { refreshCustomNodePacks } from '@workbench/customNodes/nodesStore';-import { useNotify } from '@workbench/useNotify';+import { reloadCustomNodes } from '@features/nodes/data/api';+import { refreshCustomNodePacks } from '@features/nodes/data/nodesStore';+import { useNotify } from '@features/nodes/ui/useNodesNotify';+import { getApiErrorMessage } from '@platform/transport/http';+import { Button } from '@platform/ui';import { RefreshCwIcon } from 'lucide-react';import { useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/layoutConstants.ts b/invokeai/frontend/webv2/src/features/nodes/ui/manager/layoutConstants.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/layoutConstants.tsrename to invokeai/frontend/webv2/src/features/nodes/ui/manager/layoutConstants.tsdiff --git a/invokeai/frontend/webv2/src/workbench/customNodes/nodesUiStore.ts b/invokeai/frontend/webv2/src/features/nodes/ui/nodesUiStore.tssimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/customNodes/nodesUiStore.tsrename to invokeai/frontend/webv2/src/features/nodes/ui/nodesUiStore.tsindex c2b6fc0271..bdd4c004a9 100644--- a/invokeai/frontend/webv2/src/workbench/customNodes/nodesUiStore.ts+++ b/invokeai/frontend/webv2/src/features/nodes/ui/nodesUiStore.ts@@ -1,4 +1,4 @@-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';/*** Session-lived UI state for the Launchpad nodes manager. Keeping the activediff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/shared/useNodePackActions.ts b/invokeai/frontend/webv2/src/features/nodes/ui/shared/useNodePackActions.tssimilarity index 67%rename from invokeai/frontend/webv2/src/workbench/launchpad/nodes/shared/useNodePackActions.tsrename to invokeai/frontend/webv2/src/features/nodes/ui/shared/useNodePackActions.tsindex a87af50c85..acbd1b0662 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/shared/useNodePackActions.ts+++ b/invokeai/frontend/webv2/src/features/nodes/ui/shared/useNodePackActions.ts@@ -1,10 +1,10 @@-import type { NodePackInfo } from '@workbench/customNodes/api';+import type { NodePackInfo } from '@features/nodes/core/catalog';-import { getApiErrorMessage } from '@workbench/backend/http';-import { uninstallCustomNodePack } from '@workbench/customNodes/api';-import { addCustomNodeInstallLogEntry } from '@workbench/customNodes/installLogStore';-import { refreshCustomNodePacks, removeCustomNodePackFromStore } from '@workbench/customNodes/nodesStore';-import { useNotify } from '@workbench/useNotify';+import { uninstallCustomNodePack } from '@features/nodes/data/api';+import { addCustomNodeInstallLogEntry } from '@features/nodes/data/installLogStore';+import { refreshCustomNodePacks, removeCustomNodePackFromStore } from '@features/nodes/data/nodesStore';+import { useNotify } from '@features/nodes/ui/useNodesNotify';+import { getApiErrorMessage } from '@platform/transport/http';export const useNodePackActions = () => {const notify = useNotify();diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/useNodesNotify.ts b/invokeai/frontend/webv2/src/features/nodes/ui/useNodesNotify.tsnew file mode 100644index 0000000000..762a33b5db--- /dev/null+++ b/invokeai/frontend/webv2/src/features/nodes/ui/useNodesNotify.ts@@ -0,0 +1,19 @@+import { toaster } from '@platform/ui';++export interface NodesNotify {+ error(title: string, message?: string): void;+ info(title: string, message?: string): void;+ success(title: string, message?: string): void;+}++const createNotice = (type: 'error' | 'info' | 'success') => (title: string, message?: string) => {+ toaster.create({ description: message, title, type });+};++const nodesNotify: NodesNotify = {+ error: createNotice('error'),+ info: createNotice('info'),+ success: createNotice('success'),+};++export const useNotify = (): NodesNotify => nodesNotify;diff --git a/invokeai/frontend/webv2/src/features/queue/contracts.ts b/invokeai/frontend/webv2/src/features/queue/contracts.tsnew file mode 100644index 0000000000..2f5fe3d585--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/contracts.ts@@ -0,0 +1,59 @@+/**+ * Stable, implementation-free Queue contracts for owners that persist or+ * present Queue state. Keeping this facade separate prevents contract-only+ * consumers from loading the Queue runtime and widget implementation.+ */+export type {+ QueueHistoryItemStatus,+ QueueItem,+ QueueState,+ QueueSubmissionSnapshot,+ RunRecord,+} from './core/historyTypes';+export type {+ QueueCounts,+ QueueCompiledSubmission,+ QueueItemIdsReadModel,+ QueueItemProgress,+ QueueItemReadModel,+ QueueItemStatus,+ QueueNodeFieldValue,+ QueueProcessorReadModel,+ QueueQueryScope,+ QueueReadModel,+ QueueStatusReadModel,+ TerminalQueueItemStatus,+} from './core/types';+export { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from './core/historySnapshot';+export {+ getProjectQueueIndicatorState,+ getQueueItemExpectedImageCount,+ getQueueProgressBarState,+ getQueueProgressBarValue,+ getQueueSummary,+ isOpenQueueItem,+ type ProjectQueueIndicatorState,+ type QueueProgressBarState,+ type QueueSummary,+} from './core/historySummary';+export {+ BACKEND_SUBMITTABLE_SOURCE_IDS,+ isBackendSubmittableSourceId,+ shouldSubmitPendingQueueItem,+} from './core/submissionRules';+export { extractGenerationMeta, type QueueGenerationMeta } from './core/generationMeta';+export {+ buildProjectQueueItemOriginPrefix,+ buildQueueItemOrigin,+ buildUtilityQueueItemOrigin,+ isTerminalBackendStatus,+ isUtilityQueueItemOrigin,+ parseQueueItemOrigin,+ parseQueueItemOriginProjectId,+ type BackendSocketEvents,+ type InvocationCompleteEvent,+ type InvocationErrorEvent,+ type InvocationProgressEvent,+ type InvocationStartedEvent,+ type QueueItemStatusChangedEvent,+} from './data/events';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/fieldValues.ts b/invokeai/frontend/webv2/src/features/queue/core/generationMeta.tssimilarity index 51%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/fieldValues.tsrename to invokeai/frontend/webv2/src/features/queue/core/generationMeta.tsindex 4e27f471f8..fc64b7b149 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/fieldValues.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/generationMeta.ts@@ -1,10 +1,10 @@-import type { QueueServerItem } from './queueServerApi';+import type { QueueItemReadModel } from '@features/queue/core/types';/*** Best-effort recovery of the human-facing generation parameters for a queue* item. The reliable source is the local submission snapshot (matched in the* view by origin), but server items from other clients/sources only carry- * `field_values` — generic `{node_path, field_name, value}` substitutions. For+ * field values — generic node/field/value substitutions. For* webv2 generate batches these are exactly the seed (number) + positive/negative* prompts (strings), so we recover them by value type and order, degrading* gracefully for unknown graphs.@@ -16,11 +16,11 @@ export interface QueueGenerationMeta {seed?: number;}-export const extractGenerationMeta = (item: QueueServerItem): QueueGenerationMeta => {+export const extractGenerationMeta = (item: QueueItemReadModel): QueueGenerationMeta => {const meta: QueueGenerationMeta = {};const prompts: string[] = [];- for (const fieldValue of item.field_values ?? []) {+ for (const fieldValue of item.fieldValues ?? []) {const { value } = fieldValue;if (typeof value === 'number' && meta.seed === undefined) {@@ -42,27 +42,6 @@ export const extractGenerationMeta = (item: QueueServerItem): QueueGenerationMet};/** First result image name from a completed item's session, or null. */-export const getResultImageName = (item: QueueServerItem): string | null => {- for (const result of Object.values(item.session?.results ?? {})) {- if (!result || typeof result !== 'object') {- continue;- }-- const image = (result as { image?: { image_name?: unknown } }).image;- if (typeof image?.image_name === 'string') {- return image.image_name;- }-- const collection = (result as { collection?: unknown }).collection;- if (Array.isArray(collection)) {- for (const entry of collection) {- const imageName = entry && typeof entry === 'object' ? (entry as { image_name?: unknown }).image_name : null;- if (typeof imageName === 'string') {- return imageName;- }- }- }- }-- return null;+export const getResultImageName = (item: QueueItemReadModel): string | null => {+ return item.resultImageNames[0] ?? null;};diff --git a/invokeai/frontend/webv2/src/features/queue/core/historySnapshot.ts b/invokeai/frontend/webv2/src/features/queue/core/historySnapshot.tsnew file mode 100644index 0000000000..4c86aaa64a--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/core/historySnapshot.ts@@ -0,0 +1,11 @@+import type { QueueItem } from './historyTypes';++export const getQueueItemSnapshotBatchCount = (item: QueueItem): number => item.snapshot.presentation.batchCount;++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,+});diff --git a/invokeai/frontend/webv2/src/workbench/queueSummary.test.ts b/invokeai/frontend/webv2/src/features/queue/core/historySummary.test.tssimilarity index 90%rename from invokeai/frontend/webv2/src/workbench/queueSummary.test.tsrename to invokeai/frontend/webv2/src/features/queue/core/historySummary.test.tsindex a57843d032..ea85f341a9 100644--- a/invokeai/frontend/webv2/src/workbench/queueSummary.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/historySummary.test.ts@@ -1,14 +1,14 @@-import { describe, expect, it } from 'vitest';+import type { QueueItem } from '@features/queue';+import type { QueueItemProgress } from '@features/queue/core/types';-import type { QueueItemProgress } from './backend/progressStore';-import type { QueueItem } from './types';+import { describe, expect, it } from 'vitest';import {getProjectQueueIndicatorState,getQueueProgressBarState,getQueueProgressBarValue,getQueueSummary,-} from './queueSummary';+} from './historySummary';const createQueueItem = ({backendItemIds,@@ -29,36 +29,14 @@ const createQueueItem = ({cancellable: true,id,snapshot: {- canvas: {- document: {- background: 'transparent',- bbox: { height: 1024, width: 1024, x: 0, y: 0 },- height: 1024,- layers: [],- selectedLayerId: null,- version: 2,- width: 1024,- },- documentRevision: 0,- snapshots: [],- stagingArea: {- areThumbnailsVisible: false,- autoSwitchMode: 'off',- isVisible: false,- pendingImageIds: [],- pendingImages: [],- selectedImageIndex: 0,- },- version: 2,- },+ backendSubmission: { error: 'not submitted in summary tests', kind: 'invalid' },destination: 'gallery',+ filterIntermediateResults: false,+ galleryBoardId: null,graph: { edges: [], id: 'graph-1', label: 'Graph', nodes: [], updatedAt: submittedAt, version: 1 },+ presentation: { batchCount, height: 1024, width: 1024 },sourceId,submittedAt,- widgetInstances: {},- widgetStates: {- generate: { id: 'generate', label: 'Generate', values: { batchCount }, version: 1 },- } as unknown as QueueItem['snapshot']['widgetStates'],},status,});diff --git a/invokeai/frontend/webv2/src/workbench/queueSummary.ts b/invokeai/frontend/webv2/src/features/queue/core/historySummary.tssimilarity index 94%rename from invokeai/frontend/webv2/src/workbench/queueSummary.tsrename to invokeai/frontend/webv2/src/features/queue/core/historySummary.tsindex a060939c02..36a132e445 100644--- a/invokeai/frontend/webv2/src/workbench/queueSummary.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/historySummary.ts@@ -1,7 +1,7 @@-import type { QueueItemProgress } from './backend/progressStore';-import type { QueueItem } from './types';+import type { QueueItem } from '@features/queue/core/historyTypes';+import type { QueueItemProgress } from '@features/queue/core/types';-import { getQueueItemSnapshotBatchCount } from './queueSnapshot';+import { getQueueItemSnapshotBatchCount } from '@features/queue/core/historySnapshot';export interface QueueSummary {current: number;diff --git a/invokeai/frontend/webv2/src/features/queue/core/historyTypes.ts b/invokeai/frontend/webv2/src/features/queue/core/historyTypes.tsnew file mode 100644index 0000000000..645385cce3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/core/historyTypes.ts@@ -0,0 +1,53 @@+import type {+ QueueCompiledSubmission,+ QueueGraphSnapshot,+ QueueResultImage,+ QueueResultDestination,+ QueueSourceId,+ QueueSubmissionPresentation,+} from './types';++export type QueueHistoryItemStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';++export interface QueueSubmissionSnapshot {+ backendSubmission: QueueCompiledSubmission;+ sourceId: QueueSourceId;+ destination: QueueResultDestination;+ graph: QueueGraphSnapshot;+ /** Gallery board captured at enqueue time; null means uncategorized. */+ galleryBoardId: string | null;+ /** Workflow outputs omit intermediate node images. */+ filterIntermediateResults: boolean;+ resultNodeIds?: readonly string[];+ presentation: QueueSubmissionPresentation;+ submittedAt: string;+}++export interface QueueItem {+ id: string;+ status: QueueHistoryItemStatus;+ cancellable: boolean;+ snapshot: QueueSubmissionSnapshot;+ backendItemIds?: number[];+ completedBackendItemIds?: number[];+ cancelledBackendItemIds?: number[];+ backendBatchId?: string;+ error?: string;+ resultImages?: QueueResultImage[];+}++export interface QueueState {+ items: QueueItem[];+}++export interface RunRecord {+ id: string;+ projectId: string;+ queueItemId: string;+ sourceId: QueueSourceId;+ destination: QueueResultDestination;+ graphSnapshotId: string;+ status: QueueHistoryItemStatus;+ submittedAt: string;+ completedAt?: string;+}diff --git a/invokeai/frontend/webv2/src/features/queue/core/progressImage.ts b/invokeai/frontend/webv2/src/features/queue/core/progressImage.tsnew file mode 100644index 0000000000..580702df47--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/core/progressImage.ts@@ -0,0 +1,10 @@+export interface QueueProgressImage {+ dataUrl: string;+ height: number;+ width: number;+}++export const mergeQueueProgressImage = <Image extends QueueProgressImage>(+ previous: Image | null | undefined,+ next: Image | null | undefined+): Image | null | undefined => (next === undefined ? previous : next);diff --git a/invokeai/frontend/webv2/src/workbench/queueSubmission.test.ts b/invokeai/frontend/webv2/src/features/queue/core/submissionRules.test.tssimilarity index 88%rename from invokeai/frontend/webv2/src/workbench/queueSubmission.test.tsrename to invokeai/frontend/webv2/src/features/queue/core/submissionRules.test.tsindex 9c137d736d..878ce42cf1 100644--- a/invokeai/frontend/webv2/src/workbench/queueSubmission.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/submissionRules.test.ts@@ -1,15 +1,16 @@-import { describe, expect, it } from 'vitest';+import type { QueueHistoryItemStatus, QueueItem } from '@features/queue';+import type { QueueSourceId } from '@features/queue/core/types';-import type { InvocationSourceId, QueueItem, QueueItemStatus } from './types';+import { describe, expect, it } from 'vitest';import {BACKEND_SUBMITTABLE_SOURCE_IDS,isBackendSubmittableSourceId,shouldSubmitPendingQueueItem,-} from './queueSubmission';+} from './submissionRules';/** Minimal queue item whose submission gate only reads `status` + `snapshot.sourceId`. */-const makeQueueItem = (sourceId: InvocationSourceId, status: QueueItemStatus): QueueItem =>+const makeQueueItem = (sourceId: QueueSourceId, status: QueueHistoryItemStatus): QueueItem =>({id: 'queue-item-1',status,diff --git a/invokeai/frontend/webv2/src/features/queue/core/submissionRules.ts b/invokeai/frontend/webv2/src/features/queue/core/submissionRules.tsnew file mode 100644index 0000000000..84500c5833--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/core/submissionRules.ts@@ -0,0 +1,23 @@+import type { QueueItem } from '@features/queue/core/historyTypes';+import type { QueueSourceId } from '@features/queue/core/types';++/** Source kinds whose pending queue items the runtime enqueues to the backend. */+export const BACKEND_SUBMITTABLE_SOURCE_IDS = [+ 'generate',+ 'workflow',+ 'upscale',+ 'canvas',+] as const satisfies readonly QueueSourceId[];++const BACKEND_SUBMITTABLE_SOURCE_ID_SET: ReadonlySet<QueueSourceId> = new Set(BACKEND_SUBMITTABLE_SOURCE_IDS);++/** Whether a queue item's source is one the runtime knows how to enqueue. */+export const isBackendSubmittableSourceId = (sourceId: QueueSourceId): boolean =>+ BACKEND_SUBMITTABLE_SOURCE_ID_SET.has(sourceId);++/**+ * Whether a queue item is a fresh, backend-submittable `pending` item — the+ * runtime still applies its own "already started this id" dedupe on top of this.+ */+export const shouldSubmitPendingQueueItem = (queueItem: QueueItem): boolean =>+ queueItem.status === 'pending' && isBackendSubmittableSourceId(queueItem.snapshot.sourceId);diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.tsnew file mode 100644index 0000000000..57b4a57d0b--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts@@ -0,0 +1,227 @@+import type { BackendConnectionStatus } from '@platform/transport/types';++export interface QueueBackendInvocation {+ id: string;+ type: string;+ [key: string]: unknown;+}++export interface QueueBackendGraphEdge {+ destination: { field: string; node_id: string };+ source: { field: string; node_id: string };+}++export interface QueueBackendGraph {+ edges: QueueBackendGraphEdge[];+ id: string;+ nodes: Record<string, QueueBackendInvocation>;+}++export type QueueResultDestination = 'canvas' | 'gallery';+export type QueueSourceId = 'canvas' | 'generate' | 'upscale' | 'workflow';++export interface QueueSubmissionPresentation {+ batchCount: number;+ height: number;+ positivePrompt?: string;+ width: number;+}++export interface QueueGraphSnapshot {+ backendGraph?: QueueBackendGraph;+ edges?: unknown[];+ id: string;+ label: string;+ nodes?: unknown[];+ updatedAt?: string;+ version?: number;+}++export interface QueueEnqueueWorkflowRequest {+ batchCount: number;+ destination: QueueResultDestination;+ graph: QueueBackendGraph;+ projectId: string;+ sourceQueueItemId: string;+}++export interface QueueEnqueueGenerateRequest extends QueueEnqueueWorkflowRequest {+ negativePrompt: string;+ negativePromptNodeId: string;+ positivePrompt: string;+ positivePromptNodeId: string;+ seed: number;+ seedNodeId: string;+ shouldRandomizeSeed: boolean;+}++export interface QueueEnqueueResult {+ batchId?: string;+ enqueued: number;+ itemIds: number[];+ requested: number;+}++/** Immutable source-compiled payload. Queue submits it without reading source widget state. */+export type QueueCompiledSubmission =+ | {+ batchCount: number;+ graph: QueueBackendGraph;+ kind: 'workflow';+ }+ | {+ batchCount: number;+ graph: QueueBackendGraph;+ kind: 'generate';+ negativePrompt: string;+ negativePromptNodeId: string;+ positivePrompt: string;+ positivePromptNodeId: string;+ seed: number;+ seedNodeId: string;+ shouldRandomizeSeed: boolean;+ }+ | { error: string; kind: 'invalid' };++export interface QueueBackendItem {+ batchId?: string;+ destination?: string | null;+ errorMessage?: string | null;+ errorType?: string | null;+ id: number;+ origin?: string | null;+ status: QueueItemStatus;+}++export interface QueueResultImage {+ height: number;+ imageName: string;+ imageUrl: string;+ isIntermediate?: boolean;+ queuedAt: string;+ sourceQueueItemId: string;+ thumbnailUrl: string;+ width: number;+}++export type QueueItemStatus = 'pending' | 'in_progress' | 'completed' | 'failed' | 'canceled';+export type TerminalQueueItemStatus = Extract<QueueItemStatus, 'completed' | 'failed' | 'canceled'>;++export interface QueueQueryScope {+ originPrefix?: string;+}++export interface QueueNodeFieldValue {+ fieldName: string;+ nodePath: string;+ value: string | number | { imageName?: string } | null;+}++/** Live, UI-facing representation of one backend queue item. */+export interface QueueItemReadModel {+ batchId: string;+ completedAt?: string | null;+ createdAt: string;+ destination?: string | null;+ errorMessage?: string | null;+ errorTraceback?: string | null;+ errorType?: string | null;+ fieldValues?: QueueNodeFieldValue[] | null;+ id: number;+ origin?: string | null;+ resultImageNames: string[];+ retriedFromItemId?: number | null;+ sessionId: string;+ startedAt?: string | null;+ status: QueueItemStatus;+ updatedAt: string;+}++export interface QueueCounts {+ batchId?: string | null;+ canceled: number;+ completed: number;+ failed: number;+ inProgress: number;+ itemId?: number | null;+ pending: number;+ queueId: string;+ sessionId?: string | null;+ total: number;+}++export interface QueueProcessorReadModel {+ isProcessing: boolean;+ isStarted: boolean;+}++export interface QueueStatusReadModel {+ processor: QueueProcessorReadModel;+ queue: QueueCounts;+}++export interface QueueItemIdsReadModel {+ itemIds: number[];+ totalCount: number;+}++export interface QueueItemProgress {+ /** 1-based image slot currently executing inside this local batch. */+ activeItemIndex?: number;+ completedItemCount?: number;+ message: string;+ /** 0..1, or null while indeterminate. */+ percentage: number | null;+ totalItemCount?: number;+}++export interface QueueReadModel {+ current: QueueItemReadModel | null;+ items: QueueItemReadModel[];+ next: QueueItemReadModel | null;+ scope: QueueQueryScope;+ status: QueueStatusReadModel;+}++export interface QueueResultImageOptions {+ resultNodeIds?: readonly string[];+}++/** User-facing Queue commands; transport and adapter details stay private. */+export interface QueueFeatureCommands {+ cancelCurrentItem(): Promise<void>;+ cancelItem(itemId: number): Promise<void>;+ cancelScopedItems(scope?: QueueQueryScope, currentItemId?: number | null): Promise<void>;+ clearFailedItems(scope?: QueueQueryScope): Promise<void>;+ clearItems(scope?: QueueQueryScope): Promise<void>;+ pauseProcessor(): Promise<void>;+ resumeProcessor(): Promise<void>;+}++/**+ * The queue feature's backend seam. It owns both command transport and realtime+ * events so runtimes never assemble HTTP calls and socket subscriptions.+ */+export interface QueueBackendPort extends QueueFeatureCommands {+ cancelQueueItems(itemIds: number[]): Promise<void>;+ cancelQueueItemsByBatchIds(batchIds: string[]): Promise<void>;+ enqueueGenerate(request: QueueEnqueueGenerateRequest): Promise<QueueEnqueueResult>;+ enqueueWorkflow(request: QueueEnqueueWorkflowRequest): Promise<QueueEnqueueResult>;+ getItem(itemId: number): Promise<QueueBackendItem>;+ getResultImages(+ itemId: number,+ sourceQueueItemId: string,+ queuedAt: string,+ options?: QueueResultImageOptions+ ): Promise<QueueResultImage[]>;+ listItems(): Promise<QueueBackendItem[]>;+ readCurrent(scope?: QueueQueryScope): Promise<QueueItemReadModel | null>;+ readItemIds(order: 'asc' | 'desc', scope?: QueueQueryScope): Promise<QueueItemIdsReadModel>;+ readItemsById(itemIds: number[]): Promise<QueueItemReadModel[]>;+ readNext(scope?: QueueQueryScope): Promise<QueueItemReadModel | null>;+ readStatus(scope?: QueueQueryScope): Promise<QueueStatusReadModel>;+ retryItems(itemIds: number[]): Promise<unknown>;+ emit(event: string, payload: unknown): void;+ on(event: string, handler: (payload: never) => void): () => void;+ onConnectionChange(handler: (status: BackendConnectionStatus, error?: string) => void): () => void;+}diff --git a/invokeai/frontend/webv2/src/workbench/backend/events.ts b/invokeai/frontend/webv2/src/features/queue/data/events.tssimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/backend/events.tsrename to invokeai/frontend/webv2/src/features/queue/data/events.tsindex 48f709a61f..b5d6506418 100644--- a/invokeai/frontend/webv2/src/workbench/backend/events.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/events.ts@@ -1,14 +1,11 @@+import type { QueueItemStatus, TerminalQueueItemStatus } from '@features/queue/core/types';+/*** Typed contracts for the backend Socket.IO events webv2 consumes. Payload* shapes mirror the pydantic models in* `invokeai/app/services/events/events_common.py` (serialized as snake_case).*/-/** Backend queue item lifecycle status. Note the backend spells it `canceled`. */-export type BackendQueueItemStatus = 'pending' | 'in_progress' | 'completed' | 'failed' | 'canceled';--export type TerminalBackendQueueItemStatus = Extract<BackendQueueItemStatus, 'completed' | 'failed' | 'canceled'>;-export interface QueueItemEventBase {queue_id: string;item_id: number;@@ -18,7 +15,7 @@ export interface QueueItemEventBase {}export interface QueueItemStatusChangedEvent extends QueueItemEventBase {- status: BackendQueueItemStatus;+ status: QueueItemStatus;error_type: string | null;error_message: string | null;error_traceback: string | null;@@ -86,7 +83,7 @@ export interface BackendSocketEvents {invocation_error: InvocationErrorEvent;}-export const isTerminalBackendStatus = (status: BackendQueueItemStatus): status is TerminalBackendQueueItemStatus =>+export const isTerminalBackendStatus = (status: QueueItemStatus): status is TerminalQueueItemStatus =>status === 'completed' || status === 'failed' || status === 'canceled';/**@@ -105,7 +102,7 @@ const PROJECT_QUEUE_ITEM_ORIGIN_PREFIX = 'webv2:p:';* The whole point of a distinct prefix is result isolation (plan Risk 4): a* utility item must never be mistaken for a project queue item and routed into* staging or the gallery. `parseQueueItemOrigin` therefore returns `null` for it- * — so `queueCoordinator.reconcile` and `isQueueServerItemInProject` never map a+ * — so `queueCoordinator.reconcile` and `isQueueItemReadModelInProject` never map a* utility backend item to a local project item, and `routeQueueItemResults`* (only ever invoked for coordinator-tracked project runs, which utility items* are never registered as) never sees it. The `util:` segment sits under thediff --git a/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts b/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.tsnew file mode 100644index 0000000000..d5cd4a9fe6--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts@@ -0,0 +1,68 @@+import type { QueueBackendPort } from '@features/queue/core/types';++import { socketHub } from '@platform/transport/socketHub';++import { mapQueueBackendItemDTO, mapQueueItemDTO, mapQueueItemIdsDTO, mapQueueStatusDTO } from './mappers';+import {+ cancelByBatchIds,+ cancelCurrentQueueItem,+ cancelQueueItem,+ cancelQueueItems,+ cancelScopedQueueItems,+ clearFailedQueueItems,+ clearScopedQueue,+ getCurrentQueueItem,+ getNextQueueItem,+ getQueueItem,+ getQueueItemIds,+ getQueueItemsByIds,+ getQueueStatus,+ listAllQueueItems,+ pauseQueueProcessor,+ retryItemsById,+ resumeQueueProcessor,+} from './serverApi';+import { enqueueGenerate, enqueueWorkflow, getResultImages } from './submissionApi';++/** Production adapter for the queue backend port. */+export const queueBackend: QueueBackendPort = {+ cancelCurrentItem: cancelCurrentQueueItem,+ cancelQueueItems,+ cancelQueueItemsByBatchIds: async (batchIds) => {+ await cancelByBatchIds(batchIds);+ },+ cancelItem: async (itemId) => {+ await cancelQueueItem(itemId);+ },+ cancelScopedItems: cancelScopedQueueItems,+ clearFailedItems: clearFailedQueueItems,+ clearItems: clearScopedQueue,+ emit: socketHub.emit,+ enqueueGenerate,+ enqueueWorkflow,+ getItem: async (itemId) => mapQueueBackendItemDTO(await getQueueItem(itemId)),+ getResultImages,+ listItems: async () => (await listAllQueueItems()).map(mapQueueBackendItemDTO),+ on: socketHub.on,+ onConnectionChange: socketHub.onConnectionChange,+ pauseProcessor: async () => {+ await pauseQueueProcessor();+ },+ readCurrent: async (scope) => {+ const item = await getCurrentQueueItem(scope);++ return item ? mapQueueItemDTO(item) : null;+ },+ readItemIds: async (order, scope) => mapQueueItemIdsDTO(await getQueueItemIds(order, scope)),+ readItemsById: async (itemIds) => (await getQueueItemsByIds(itemIds)).map(mapQueueItemDTO),+ readNext: async (scope) => {+ const item = await getNextQueueItem(scope);++ return item ? mapQueueItemDTO(item) : null;+ },+ readStatus: async (scope) => mapQueueStatusDTO(await getQueueStatus(scope)),+ retryItems: retryItemsById,+ resumeProcessor: async () => {+ await resumeQueueProcessor();+ },+};diff --git a/invokeai/frontend/webv2/src/workbench/backend/itemProgressStore.test.ts b/invokeai/frontend/webv2/src/features/queue/data/itemProgressStore.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/backend/itemProgressStore.test.tsrename to invokeai/frontend/webv2/src/features/queue/data/itemProgressStore.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/backend/itemProgressStore.ts b/invokeai/frontend/webv2/src/features/queue/data/itemProgressStore.tssimilarity index 80%rename from invokeai/frontend/webv2/src/workbench/backend/itemProgressStore.tsrename to invokeai/frontend/webv2/src/features/queue/data/itemProgressStore.tsindex dee301fff1..ff2bbd49cf 100644--- a/invokeai/frontend/webv2/src/workbench/backend/itemProgressStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/itemProgressStore.ts@@ -1,5 +1,5 @@-import { createKeyedTransientStore } from '@workbench/externalStore';-import { mergeDenoiseProgressImage, type DenoiseProgressImage } from '@workbench/images/streamingImageSource';+import { mergeQueueProgressImage, type QueueProgressImage } from '@features/queue/core/progressImage';+import { createKeyedTransientStore } from '@platform/state/externalStore';/*** Live progress for in-flight queue items keyed by the backend `item_id`. The@@ -13,7 +13,7 @@ export interface ItemProgress {message: string;/** 0..1, or null while indeterminate. */percentage: number | null;- image?: DenoiseProgressImage | null;+ image?: QueueProgressImage | null;}const progressByItemId = createKeyedTransientStore<number, ItemProgress>();@@ -24,7 +24,7 @@ export const itemProgressStore = {},set(itemId: number, progress: ItemProgress): void {const current = progressByItemId.get(itemId);- const image = mergeDenoiseProgressImage(current?.image, progress.image);+ const image = mergeQueueProgressImage(current?.image, progress.image);const next = image === undefined ? progress : { ...progress, image };progressByItemId.set(itemId, next);diff --git a/invokeai/frontend/webv2/src/features/queue/data/mappers.test.ts b/invokeai/frontend/webv2/src/features/queue/data/mappers.test.tsnew file mode 100644index 0000000000..7172da4891--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/data/mappers.test.ts@@ -0,0 +1,106 @@+import { describe, expect, it } from 'vitest';++import { mapQueueItemDTO, mapQueueItemIdsDTO, mapQueueStatusDTO } from './mappers';++describe('queue transport mappers', () => {+ it('maps a backend queue item into the live read model', () => {+ expect(+ mapQueueItemDTO({+ batch_id: 'batch-1',+ completed_at: '2026-07-18T01:00:00Z',+ created_at: '2026-07-18T00:00:00Z',+ destination: 'gallery',+ error_message: null,+ error_traceback: null,+ error_type: null,+ field_values: [+ { field_name: 'seed', node_path: 'noise', value: 42 },+ { field_name: 'image', node_path: 'input', value: { image_name: 'input.png' } },+ ],+ item_id: 7,+ origin: 'webv2:item-1',+ retried_from_item_id: 3,+ session: {+ results: {+ collection: { collection: [{ image_name: 'first.png' }, { image_name: 'second.png' }] },+ image: { image: { image_name: 'single.png' } },+ },+ },+ session_id: 'session-1',+ started_at: '2026-07-18T00:30:00Z',+ status: 'completed',+ updated_at: '2026-07-18T01:00:00Z',+ })+ ).toEqual({+ batchId: 'batch-1',+ completedAt: '2026-07-18T01:00:00Z',+ createdAt: '2026-07-18T00:00:00Z',+ destination: 'gallery',+ errorMessage: null,+ errorTraceback: null,+ errorType: null,+ fieldValues: [+ { fieldName: 'seed', nodePath: 'noise', value: 42 },+ { fieldName: 'image', nodePath: 'input', value: { imageName: 'input.png' } },+ ],+ id: 7,+ origin: 'webv2:item-1',+ resultImageNames: ['first.png', 'second.png', 'single.png'],+ retriedFromItemId: 3,+ sessionId: 'session-1',+ startedAt: '2026-07-18T00:30:00Z',+ status: 'completed',+ updatedAt: '2026-07-18T01:00:00Z',+ });+ });++ it('preserves absent nullable fields without exposing the raw session', () => {+ const item = mapQueueItemDTO({+ batch_id: 'batch-2',+ created_at: '2026-07-18T00:00:00Z',+ item_id: 8,+ session_id: 'session-2',+ status: 'pending',+ updated_at: '2026-07-18T00:00:00Z',+ });++ expect(item.fieldValues).toBeUndefined();+ expect(item.resultImageNames).toEqual([]);+ expect(item).not.toHaveProperty('session');+ });++ it('maps status and id-list response names at the adapter boundary', () => {+ expect(mapQueueItemIdsDTO({ item_ids: [9, 8], total_count: 2 })).toEqual({ itemIds: [9, 8], totalCount: 2 });+ expect(+ mapQueueStatusDTO({+ processor: { is_processing: true, is_started: true },+ queue: {+ batch_id: 'batch-1',+ canceled: 1,+ completed: 2,+ failed: 3,+ in_progress: 4,+ item_id: 7,+ pending: 5,+ queue_id: 'default',+ session_id: 'session-1',+ total: 15,+ },+ })+ ).toEqual({+ processor: { isProcessing: true, isStarted: true },+ queue: {+ batchId: 'batch-1',+ canceled: 1,+ completed: 2,+ failed: 3,+ inProgress: 4,+ itemId: 7,+ pending: 5,+ queueId: 'default',+ sessionId: 'session-1',+ total: 15,+ },+ });+ });+});diff --git a/invokeai/frontend/webv2/src/features/queue/data/mappers.ts b/invokeai/frontend/webv2/src/features/queue/data/mappers.tsnew file mode 100644index 0000000000..69986aa3c3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/data/mappers.ts@@ -0,0 +1,106 @@+import type {+ QueueBackendItem,+ QueueItemIdsReadModel,+ QueueItemReadModel,+ QueueNodeFieldValue,+ QueueStatusReadModel,+} from '@features/queue/core/types';++import type {+ QueueAndProcessorStatusDTO,+ QueueItemIdsResultDTO,+ QueueNodeFieldValueDTO,+ QueueServerItemDTO,+} from './serverTypes';++const mapNodeFieldValue = (dto: QueueNodeFieldValueDTO): QueueNodeFieldValue => ({+ fieldName: dto.field_name,+ nodePath: dto.node_path,+ value: dto.value && typeof dto.value === 'object' ? { imageName: dto.value.image_name } : dto.value,+});++const getResultImageNames = (dto: QueueServerItemDTO): string[] => {+ const imageNames: string[] = [];++ for (const result of Object.values(dto.session?.results ?? {})) {+ if (!result || typeof result !== 'object') {+ continue;+ }++ const image = (result as { image?: { image_name?: unknown } }).image;++ if (typeof image?.image_name === 'string') {+ imageNames.push(image.image_name);+ }++ const collection = (result as { collection?: unknown }).collection;++ if (Array.isArray(collection)) {+ for (const entry of collection) {+ const imageName = entry && typeof entry === 'object' ? (entry as { image_name?: unknown }).image_name : null;++ if (typeof imageName === 'string') {+ imageNames.push(imageName);+ }+ }+ }+ }++ return imageNames;+};++export const mapQueueItemDTO = (dto: QueueServerItemDTO): QueueItemReadModel => ({+ batchId: dto.batch_id,+ completedAt: dto.completed_at,+ createdAt: dto.created_at,+ destination: dto.destination,+ errorMessage: dto.error_message,+ errorTraceback: dto.error_traceback,+ errorType: dto.error_type,+ fieldValues:+ dto.field_values === null || dto.field_values === undefined+ ? dto.field_values+ : dto.field_values.map(mapNodeFieldValue),+ id: dto.item_id,+ origin: dto.origin,+ resultImageNames: getResultImageNames(dto),+ retriedFromItemId: dto.retried_from_item_id,+ sessionId: dto.session_id,+ startedAt: dto.started_at,+ status: dto.status,+ updatedAt: dto.updated_at,+});++export const mapQueueBackendItemDTO = (dto: QueueServerItemDTO): QueueBackendItem => ({+ batchId: dto.batch_id,+ destination: dto.destination,+ errorMessage: dto.error_message,+ errorType: dto.error_type,+ id: dto.item_id,+ origin: dto.origin,+ status: dto.status,+});++export const mapQueueItemIdsDTO = (dto: QueueItemIdsResultDTO): QueueItemIdsReadModel => ({+ itemIds: dto.item_ids,+ totalCount: dto.total_count,+});++export const mapQueueStatusDTO = (dto: QueueAndProcessorStatusDTO): QueueStatusReadModel => ({+ processor: {+ isProcessing: dto.processor.is_processing,+ isStarted: dto.processor.is_started,+ },+ queue: {+ batchId: dto.queue.batch_id,+ canceled: dto.queue.canceled,+ completed: dto.queue.completed,+ failed: dto.queue.failed,+ inProgress: dto.queue.in_progress,+ itemId: dto.queue.item_id,+ pending: dto.queue.pending,+ queueId: dto.queue.queue_id,+ sessionId: dto.queue.session_id,+ total: dto.queue.total,+ },+});diff --git a/invokeai/frontend/webv2/src/workbench/backend/progressImageStore.ts b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.tssimilarity index 92%rename from invokeai/frontend/webv2/src/workbench/backend/progressImageStore.tsrename to invokeai/frontend/webv2/src/features/queue/data/progressImageStore.tsindex fd1ce3e21e..505352f227 100644--- a/invokeai/frontend/webv2/src/workbench/backend/progressImageStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts@@ -1,6 +1,6 @@-import type { DenoiseProgressImage } from '@workbench/images/streamingImageSource';+import type { QueueProgressImage } from '@features/queue/core/progressImage';-import { createExternalStore, createKeyedTransientStore } from '@workbench/externalStore';+import { createExternalStore, createKeyedTransientStore } from '@platform/state/externalStore';/*** The most recent denoising preview image from `invocation_progress` events,@@ -8,7 +8,7 @@ import { createExternalStore, createKeyedTransientStore } from '@workbench/exter* Current Image node, progress surfaces) fall back to the last real output.*/-export type ProgressImageSnapshot = DenoiseProgressImage;+export type ProgressImageSnapshot = QueueProgressImage;export interface ProgressImageTarget {queueItemId: string;diff --git a/invokeai/frontend/webv2/src/workbench/backend/progressStore.ts b/invokeai/frontend/webv2/src/features/queue/data/progressStore.tssimilarity index 76%rename from invokeai/frontend/webv2/src/workbench/backend/progressStore.tsrename to invokeai/frontend/webv2/src/features/queue/data/progressStore.tsindex b96ac07884..4223d46804 100644--- a/invokeai/frontend/webv2/src/workbench/backend/progressStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/progressStore.ts@@ -1,4 +1,6 @@-import { createKeyedTransientStore } from '@workbench/externalStore';+import type { QueueItemProgress } from '@features/queue/core/types';++import { createKeyedTransientStore } from '@platform/state/externalStore';/*** Ephemeral live-progress store for in-flight queue items, keyed by the local@@ -9,16 +11,6 @@ import { createKeyedTransientStore } from '@workbench/externalStore';* `useQueueItemProgress` and only re-renders when that item's progress moves.*/-export interface QueueItemProgress {- /** 1-based image slot currently executing inside this local batch. */- activeItemIndex?: number;- completedItemCount?: number;- message: string;- /** 0..1, or null while indeterminate. */- percentage: number | null;- totalItemCount?: number;-}-export interface QueueItemProgressSink {clearAll?(): void;set(queueItemId: string, progress: QueueItemProgress): void;diff --git a/invokeai/frontend/webv2/src/features/queue/data/queries.test.ts b/invokeai/frontend/webv2/src/features/queue/data/queries.test.tsnew file mode 100644index 0000000000..82fa55fb49--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/data/queries.test.ts@@ -0,0 +1,85 @@+import type { QueueBackendPort } from '@features/queue/core/types';++import { QueryClient } from '@tanstack/react-query';+import { describe, expect, it, vi } from 'vitest';++import { invalidateQueueReadModels, queueKeys, queueReadModelOptions } from './queries';++const createBackend = (): QueueBackendPort => ({+ cancelCurrentItem: vi.fn(),+ cancelQueueItems: vi.fn(),+ cancelQueueItemsByBatchIds: vi.fn(),+ cancelItem: vi.fn(),+ cancelScopedItems: vi.fn(),+ clearFailedItems: vi.fn(),+ clearItems: vi.fn(),+ emit: vi.fn(),+ enqueueGenerate: vi.fn(),+ enqueueWorkflow: vi.fn(),+ getItem: vi.fn(),+ getResultImages: vi.fn(),+ listItems: vi.fn(),+ on: vi.fn(),+ onConnectionChange: vi.fn(),+ pauseProcessor: vi.fn(),+ readCurrent: vi.fn().mockResolvedValue(null),+ readItemIds: vi.fn().mockResolvedValue({ itemIds: [2, 1], totalCount: 2 }),+ readItemsById: vi.fn().mockResolvedValue([+ { batchId: 'batch', createdAt: '', id: 2, resultImageNames: [], sessionId: 's2', status: 'pending', updatedAt: '' },+ {+ batchId: 'batch',+ createdAt: '',+ id: 1,+ resultImageNames: [],+ sessionId: 's1',+ status: 'completed',+ updatedAt: '',+ },+ ]),+ readNext: vi.fn().mockResolvedValue(null),+ readStatus: vi.fn().mockResolvedValue({+ processor: { isProcessing: false, isStarted: true },+ queue: { canceled: 0, completed: 1, failed: 0, inProgress: 0, pending: 1, queueId: 'default', total: 2 },+ }),+ retryItems: vi.fn(),+ resumeProcessor: vi.fn(),+});++describe('queue queries', () => {+ it('deduplicates concurrent reads and serves fresh cached data', async () => {+ const backend = createBackend();+ const client = new QueryClient();+ const options = queueReadModelOptions(backend, {});++ const [first, second] = await Promise.all([client.fetchQuery(options), client.fetchQuery(options)]);+ const cached = await client.fetchQuery(options);++ expect(first).toBe(second);+ expect(cached).toBe(first);+ expect(backend.readStatus).toHaveBeenCalledTimes(1);+ expect(backend.readItemsById).toHaveBeenCalledWith([2, 1]);+ });++ it('keeps project-scoped queue reads in distinct cache entries', async () => {+ const backend = createBackend();+ const client = new QueryClient();++ await client.fetchQuery(queueReadModelOptions(backend, { originPrefix: 'webv2:p:one:q:' }));+ await client.fetchQuery(queueReadModelOptions(backend, { originPrefix: 'webv2:p:two:q:' }));++ expect(client.getQueryData(queueKeys.readModel({ originPrefix: 'webv2:p:one:q:' }))).toBeDefined();+ expect(client.getQueryData(queueKeys.readModel({ originPrefix: 'webv2:p:two:q:' }))).toBeDefined();+ expect(backend.readStatus).toHaveBeenCalledTimes(2);+ });++ it('invalidates every scoped read model through the feature key', async () => {+ const backend = createBackend();+ const client = new QueryClient();+ const key = queueKeys.readModel({ originPrefix: 'webv2:p:one:q:' });++ await client.fetchQuery(queueReadModelOptions(backend, { originPrefix: 'webv2:p:one:q:' }));+ await invalidateQueueReadModels(client);++ expect(client.getQueryState(key)?.isInvalidated).toBe(true);+ });+});diff --git a/invokeai/frontend/webv2/src/features/queue/data/queries.ts b/invokeai/frontend/webv2/src/features/queue/data/queries.tsnew file mode 100644index 0000000000..0e24a281d6--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/data/queries.ts@@ -0,0 +1,40 @@+import type { QueueBackendPort, QueueQueryScope, QueueReadModel } from '@features/queue/core/types';++import { queryOptions, type QueryClient } from '@tanstack/react-query';++export const QUEUE_RECENT_WINDOW = 50;++export const queueKeys = {+ all: ['queue'] as const,+ readModel: (scope: QueueQueryScope) => [...queueKeys.all, 'read-model', scope.originPrefix ?? 'all'] as const,+};++export const queueReadModelOptions = (+ backend: QueueBackendPort,+ scope: QueueQueryScope,+ onRead?: (model: QueueReadModel) => void+) =>+ queryOptions({+ queryFn: async (): Promise<QueueReadModel> => {+ const [status, current, next, idsResult] = await Promise.all([+ backend.readStatus(scope),+ backend.readCurrent(scope),+ backend.readNext(scope),+ backend.readItemIds('desc', scope),+ ]);+ const items = await backend.readItemsById(idsResult.itemIds.slice(0, QUEUE_RECENT_WINDOW));++ const model = { current, items, next, scope, status };++ onRead?.(model);++ return model;+ },+ queryKey: queueKeys.readModel(scope),+ staleTime: 5_000,+ });++/** Coalesced by QueryClient; only active queue observers refetch. */+export const invalidateQueueReadModels = async (queryClient: QueryClient): Promise<void> => {+ await queryClient.invalidateQueries({ queryKey: queueKeys.all });+};diff --git a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.ts b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.tsnew file mode 100644index 0000000000..85f9e25e50--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.ts@@ -0,0 +1,95 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createQueueRealtimeRuntime } from './realtimeRuntime';++describe('queue realtime runtime', () => {+ const handlers = new Map<string, (payload: never) => void>();+ const detachers: Array<ReturnType<typeof vi.fn>> = [];+ const backend = {+ on: vi.fn((event: string, handler: (payload: never) => void) => {+ handlers.set(event, handler);+ const detach = vi.fn(() => handlers.delete(event));+ detachers.push(detach);+ return detach;+ }),+ onConnectionChange: vi.fn((handler: (status: 'connected') => void) => {+ handler('connected');+ const detach = vi.fn();+ detachers.push(detach);+ return detach;+ }),+ };+ const invalidate = vi.fn();+ const progress = { clear: vi.fn(), clearAll: vi.fn(), set: vi.fn() };+ const refreshModelCache = vi.fn();++ beforeEach(() => {+ vi.useFakeTimers();+ handlers.clear();+ detachers.length = 0;+ backend.on.mockClear();+ backend.onConnectionChange.mockClear();+ invalidate.mockReset();+ progress.clear.mockReset();+ progress.clearAll.mockReset();+ progress.set.mockReset();+ refreshModelCache.mockReset();+ });++ afterEach(() => vi.useRealTimers());++ it('attaches once and coalesces a burst of queue events into one invalidation', () => {+ const runtime = createQueueRealtimeRuntime({ backend, invalidate, progress, refreshModelCache });++ runtime.start();+ runtime.start();+ handlers.get('batch_enqueued')?.({} as never);+ handlers.get('queue_cleared')?.({} as never);+ handlers.get('queue_items_retried')?.({} as never);++ expect(backend.onConnectionChange).toHaveBeenCalledTimes(1);+ expect(backend.on).toHaveBeenCalledTimes(7);+ expect(invalidate).not.toHaveBeenCalled();++ vi.advanceTimersByTime(50);++ expect(invalidate).toHaveBeenCalledTimes(1);+ runtime.dispose();+ expect(detachers.every((detach) => detach.mock.calls.length === 1)).toBe(true);+ });++ it('updates transient progress without invalidating the queue list', () => {+ const runtime = createQueueRealtimeRuntime({ backend, invalidate, progress, refreshModelCache });++ runtime.start();+ vi.advanceTimersByTime(50);+ invalidate.mockClear();++ handlers.get('invocation_progress')?.({+ image: { dataURL: 'data:image/png;base64,preview', height: 32, width: 64 },+ item_id: 42,+ message: 'Denoising',+ percentage: 0.5,+ } as never);++ expect(progress.set).toHaveBeenCalledWith(42, {+ image: { dataUrl: 'data:image/png;base64,preview', height: 32, width: 64 },+ message: 'Denoising',+ percentage: 0.5,+ });+ expect(invalidate).not.toHaveBeenCalled();+ runtime.dispose();+ });++ it('keeps completed previews until result hydration and clears failed previews immediately', () => {+ const runtime = createQueueRealtimeRuntime({ backend, invalidate, progress, refreshModelCache });++ runtime.start();+ handlers.get('queue_item_status_changed')?.({ item_id: 42, status: 'completed' } as never);+ handlers.get('queue_item_status_changed')?.({ item_id: 43, status: 'failed' } as never);++ expect(progress.clear).not.toHaveBeenCalledWith(42);+ expect(progress.clear).toHaveBeenCalledWith(43);+ runtime.dispose();+ });+});diff --git a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.ts b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.tsnew file mode 100644index 0000000000..83b2bccb81--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.ts@@ -0,0 +1,126 @@+import type { QueueBackendPort } from '@features/queue/core/types';+import type {+ InvocationProgressEvent,+ InvocationStartedEvent,+ QueueItemStatusChangedEvent,+} from '@features/queue/data/events';++import { isTerminalBackendStatus } from '@features/queue/data/events';++export interface QueueItemProgressPort {+ clear(itemId: number): void;+ clearAll(): void;+ set(+ itemId: number,+ progress: {+ image?: { dataUrl: string; height: number; width: number };+ message: string;+ percentage: number | null;+ }+ ): void;+}++export interface QueueRealtimeRuntime {+ dispose(): void;+ start(): void;+}++/**+ * Owns the global queue read model's one realtime subscription. Event bursts+ * collapse into one invalidation; progress frames update their transient store+ * directly and never force the full queue list through React state.+ */+export const createQueueRealtimeRuntime = ({+ backend,+ coalesceMs = 50,+ invalidate,+ progress,+ refreshModelCache,+}: {+ backend: Pick<QueueBackendPort, 'on' | 'onConnectionChange'>;+ coalesceMs?: number;+ invalidate: () => void | Promise<void>;+ progress: QueueItemProgressPort;+ refreshModelCache: () => void | Promise<void>;+}): QueueRealtimeRuntime => {+ const detachers: Array<() => void> = [];+ let invalidationTimer: ReturnType<typeof setTimeout> | null = null;+ let isStarted = false;++ const scheduleInvalidation = (): void => {+ if (invalidationTimer !== null) {+ return;+ }++ invalidationTimer = setTimeout(() => {+ invalidationTimer = null;+ void invalidate();+ }, coalesceMs);+ };++ const start = (): void => {+ if (isStarted) {+ return;+ }++ isStarted = true;+ void refreshModelCache();+ scheduleInvalidation();++ detachers.push(+ backend.on('queue_item_status_changed', (payload: never) => {+ const event = payload as unknown as QueueItemStatusChangedEvent;++ if (isTerminalBackendStatus(event.status) && event.status !== 'completed') {+ progress.clear(event.item_id);+ }++ scheduleInvalidation();+ }),+ backend.on('batch_enqueued', scheduleInvalidation),+ backend.on('queue_cleared', scheduleInvalidation),+ backend.on('queue_items_retried', scheduleInvalidation),+ backend.on('invocation_started', (payload: never) => {+ const event = payload as unknown as InvocationStartedEvent;++ progress.set(event.item_id, { message: '', percentage: null });+ }),+ backend.on('invocation_progress', (payload: never) => {+ const event = payload as unknown as InvocationProgressEvent;++ progress.set(event.item_id, {+ image: event.image?.dataURL+ ? { dataUrl: event.image.dataURL, height: event.image.height, width: event.image.width }+ : undefined,+ message: event.message,+ percentage: event.percentage,+ });+ }),+ backend.on('model_load_complete', () => {+ void refreshModelCache();+ }),+ backend.onConnectionChange((status) => {+ if (status === 'connected') {+ progress.clearAll();+ scheduleInvalidation();+ void refreshModelCache();+ }+ })+ );+ };++ const dispose = (): void => {+ for (const detach of detachers.splice(0)) {+ detach();+ }++ if (invalidationTimer !== null) {+ clearTimeout(invalidationTimer);+ invalidationTimer = null;+ }++ isStarted = false;+ };++ return { dispose, start };+};diff --git a/invokeai/frontend/webv2/src/workbench/backend/revealHoldStore.test.ts b/invokeai/frontend/webv2/src/features/queue/data/revealHoldStore.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/backend/revealHoldStore.test.tsrename to invokeai/frontend/webv2/src/features/queue/data/revealHoldStore.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/backend/revealHoldStore.ts b/invokeai/frontend/webv2/src/features/queue/data/revealHoldStore.tssimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/backend/revealHoldStore.tsrename to invokeai/frontend/webv2/src/features/queue/data/revealHoldStore.tsindex 2c1f925a68..127426f687 100644--- a/invokeai/frontend/webv2/src/workbench/backend/revealHoldStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/revealHoldStore.ts@@ -1,4 +1,4 @@-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';/*** A short "reveal window" after a generation completes: consumers that showdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueServerApi.ts b/invokeai/frontend/webv2/src/features/queue/data/serverApi.tssimilarity index 55%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/queueServerApi.tsrename to invokeai/frontend/webv2/src/features/queue/data/serverApi.tsindex 40ae400768..7a7b59e8f5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueServerApi.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts@@ -1,27 +1,15 @@-import type { BackendQueueItemStatus } from '@workbench/backend/events';--import { apiFetchJson } from '@workbench/backend/http';--/**- * Server-wide session-queue REST layer for the Queue widget. This mirrors the- * legacy v6 queue API surface (`frontend/web/src/services/api/endpoints/queue.ts`)- * — the same status/list/current/next reads, the `item_ids → items_by_ids`- * windowed pagination, and the clear/prune/cancel/pause mutations — ported to- * webv2's `apiFetchJson` idiom. Socket events drive refresh (see- * `queueDataStore` + `QueueDataRuntime`) in place of RTK Query tag invalidation.- *- * Unlike the local in-session queue (`project.queue.items`, which only tracks- * this client's submissions), this reads the whole backend queue: counts and- * items from every source and every client.- */+import type { QueueQueryScope } from '@features/queue/core/types';+import type {+ QueueAndProcessorStatusDTO,+ QueueItemIdsResultDTO,+ QueueServerItemDTO,+} from '@features/queue/data/serverTypes';++import { apiFetchJson } from '@platform/transport/http';const QUEUE_ID = 'default';const buildQueueUrl = (path = ''): string => `/api/v1/queue/${QUEUE_ID}/${path}`;-export interface QueueQueryScope {- originPrefix?: string;-}-const buildQueryString = (params: Record<string, string | undefined>): string => {const searchParams = new URLSearchParams();@@ -36,107 +24,48 @@ const buildQueryString = (params: Record<string, string | undefined>): string =>return queryString ? `?${queryString}` : '';};-/** A single batch substitution recorded for a queue item (prompt / seed / image field). */-export interface QueueNodeFieldValue {- node_path: string;- field_name: string;- value: string | number | { image_name?: string } | null;-}--/**- * The backend `SessionQueueItem` shape, narrowed to the fields the widget reads.- * `session` is the heavy execution graph; we only ever touch `session.results`- * to resolve a result image, so it is loosely typed here.- */-export interface QueueServerItem {- item_id: number;- status: BackendQueueItemStatus;- batch_id: string;- origin?: string | null;- destination?: string | null;- session_id: string;- error_type?: string | null;- error_message?: string | null;- error_traceback?: string | null;- created_at: string;- updated_at: string;- started_at?: string | null;- completed_at?: string | null;- field_values?: QueueNodeFieldValue[] | null;- retried_from_item_id?: number | null;- session?: { results?: Record<string, unknown> };-}--export interface QueueStatusCounts {- queue_id: string;- item_id?: number | null;- batch_id?: string | null;- session_id?: string | null;- pending: number;- in_progress: number;- completed: number;- failed: number;- canceled: number;- total: number;-}--export interface QueueProcessorStatus {- is_started: boolean;- is_processing: boolean;-}--export interface QueueAndProcessorStatus {- queue: QueueStatusCounts;- processor: QueueProcessorStatus;-}--export interface QueueItemIdsResult {- item_ids: number[];- total_count: number;-}--// --- Reads -------------------------------------------------------------------export const getQueueStatus = (scope: QueueQueryScope = {}): Promise<QueueAndProcessorStatus> =>- apiFetchJson<QueueAndProcessorStatus>(+export const getQueueStatus = (scope: QueueQueryScope = {}): Promise<QueueAndProcessorStatusDTO> =>+ apiFetchJson<QueueAndProcessorStatusDTO>(buildQueueUrl(`status${buildQueryString({ origin_prefix: scope.originPrefix })}`));-export const getCurrentQueueItem = (scope: QueueQueryScope = {}): Promise<QueueServerItem | null> =>- apiFetchJson<QueueServerItem | null>(+export const getCurrentQueueItem = (scope: QueueQueryScope = {}): Promise<QueueServerItemDTO | null> =>+ apiFetchJson<QueueServerItemDTO | null>(buildQueueUrl(`current${buildQueryString({ origin_prefix: scope.originPrefix })}`));-export const getNextQueueItem = (scope: QueueQueryScope = {}): Promise<QueueServerItem | null> =>- apiFetchJson<QueueServerItem | null>(buildQueueUrl(`next${buildQueryString({ origin_prefix: scope.originPrefix })}`));+export const getNextQueueItem = (scope: QueueQueryScope = {}): Promise<QueueServerItemDTO | null> =>+ apiFetchJson<QueueServerItemDTO | null>(+ buildQueueUrl(`next${buildQueryString({ origin_prefix: scope.originPrefix })}`)+ );-export const getQueueItem = (itemId: number): Promise<QueueServerItem> =>- apiFetchJson<QueueServerItem>(buildQueueUrl(`i/${itemId}`));+export const getQueueItem = (itemId: number): Promise<QueueServerItemDTO> =>+ apiFetchJson<QueueServerItemDTO>(buildQueueUrl(`i/${itemId}`));++export const listAllQueueItems = (): Promise<QueueServerItemDTO[]> =>+ apiFetchJson<QueueServerItemDTO[]>(buildQueueUrl('list_all'));export const getQueueItemIds = (orderDir: 'asc' | 'desc' = 'desc',scope: QueueQueryScope = {}-): Promise<QueueItemIdsResult> =>- apiFetchJson<QueueItemIdsResult>(+): Promise<QueueItemIdsResultDTO> =>+ apiFetchJson<QueueItemIdsResultDTO>(buildQueueUrl(`item_ids${buildQueryString({ order_dir: orderDir.toUpperCase(), origin_prefix: scope.originPrefix })}`));-/** Fetch full items for the given ids, preserving order. Mirrors legacy `items_by_ids`. */-export const getQueueItemsByIds = (itemIds: number[]): Promise<QueueServerItem[]> => {+export const getQueueItemsByIds = (itemIds: number[]): Promise<QueueServerItemDTO[]> => {if (itemIds.length === 0) {return Promise.resolve([]);}- return apiFetchJson<QueueServerItem[]>(buildQueueUrl('items_by_ids'), {+ return apiFetchJson<QueueServerItemDTO[]>(buildQueueUrl('items_by_ids'), {body: JSON.stringify({ item_ids: itemIds }),method: 'POST',});};-// --- Mutations --------------------------------------------------------------export const clearQueue = (): Promise<unknown> => apiFetchJson(buildQueueUrl('clear'), { method: 'PUT' });export const pruneQueue = (): Promise<unknown> => apiFetchJson(buildQueueUrl('prune'), { method: 'PUT' });@@ -176,6 +105,14 @@ export const cancelAllExceptCurrent = (): Promise<unknown> =>export const cancelQueueItem = (itemId: number): Promise<unknown> =>apiFetchJson(buildQueueUrl(`i/${itemId}/cancel`), { method: 'PUT' });+export const cancelCurrentQueueItem = async (): Promise<void> => {+ const current = await getCurrentQueueItem();++ if (current) {+ await cancelQueueItem(current.item_id);+ }+};+export const cancelScopedQueueItems = async (scope: QueueQueryScope = {},currentItemId?: number | nulldiff --git a/invokeai/frontend/webv2/src/features/queue/data/serverTypes.ts b/invokeai/frontend/webv2/src/features/queue/data/serverTypes.tsnew file mode 100644index 0000000000..7f9bdf5ac6--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/data/serverTypes.ts@@ -0,0 +1,67 @@+import type { QueueItemStatus } from '@features/queue/core/types';++/** Private HTTP wire contracts. These names and fields mirror backend JSON. */+export interface QueueNodeFieldValueDTO {+ field_name: string;+ node_path: string;+ value: string | number | { image_name?: string } | null;+}++export interface QueueServerItemDTO {+ batch_id: string;+ completed_at?: string | null;+ created_at: string;+ destination?: string | null;+ error_message?: string | null;+ error_traceback?: string | null;+ error_type?: string | null;+ field_values?: QueueNodeFieldValueDTO[] | null;+ item_id: number;+ origin?: string | null;+ retried_from_item_id?: number | null;+ session?: {+ prepared_source_mapping?: Record<string, string>;+ results?: Record<string, unknown>;+ };+ session_id: string;+ started_at?: string | null;+ status: QueueItemStatus;+ updated_at: string;+}++export interface QueueImageDTO {+ height: number;+ image_name: string;+ image_url: string;+ is_intermediate: boolean;+ thumbnail_url: string;+ width: number;+}++export interface QueueStatusCountsDTO {+ batch_id?: string | null;+ canceled: number;+ completed: number;+ failed: number;+ in_progress: number;+ item_id?: number | null;+ pending: number;+ queue_id: string;+ session_id?: string | null;+ total: number;+}++export interface QueueProcessorStatusDTO {+ is_processing: boolean;+ is_started: boolean;+}++export interface QueueAndProcessorStatusDTO {+ processor: QueueProcessorStatusDTO;+ queue: QueueStatusCountsDTO;+}++export interface QueueItemIdsResultDTO {+ item_ids: number[];+ total_count: number;+}diff --git a/invokeai/frontend/webv2/src/workbench/generation/api.test.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.tssimilarity index 79%rename from invokeai/frontend/webv2/src/workbench/generation/api.test.tsrename to invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.tsindex 5872e36476..ee736a1902 100644--- a/invokeai/frontend/webv2/src/workbench/generation/api.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts@@ -1,12 +1,12 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { QueueEnqueueGenerateRequest, QueueEnqueueWorkflowRequest } from '@features/queue/core/types';-import type { EnqueueGenerateRequest, EnqueueWorkflowRequest } from './types';+import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({apiFetchJson: vi.fn(),}));-vi.mock('../backend/http', () => ({+vi.mock('@platform/transport/http', () => ({absolutizeApiUrl: (url: string) => url,ApiError: class ApiError extends Error {status: number;@@ -19,7 +19,7 @@ vi.mock('../backend/http', () => ({apiFetchJson: mocks.apiFetchJson,}));-const createRequest = (overrides: Partial<EnqueueGenerateRequest> = {}): EnqueueGenerateRequest => ({+const createRequest = (overrides: Partial<QueueEnqueueGenerateRequest> = {}): QueueEnqueueGenerateRequest => ({batchCount: 3,destination: 'gallery',graph: { edges: [], id: 'graph-1', nodes: {} },@@ -35,7 +35,7 @@ const createRequest = (overrides: Partial<EnqueueGenerateRequest> = {}): Enqueue...overrides,});-const createWorkflowRequest = (overrides: Partial<EnqueueWorkflowRequest> = {}): EnqueueWorkflowRequest => ({+const createWorkflowRequest = (overrides: Partial<QueueEnqueueWorkflowRequest> = {}): QueueEnqueueWorkflowRequest => ({batchCount: 2,destination: 'gallery',graph: { edges: [], id: 'graph-1', nodes: {} },@@ -58,7 +58,7 @@ const getSubmittedBody = () => {};};-describe('enqueueGenerateGraph', () => {+describe('enqueueGenerate', () => {beforeEach(() => {mocks.apiFetchJson.mockReset();mocks.apiFetchJson.mockResolvedValue({@@ -70,9 +70,9 @@ describe('enqueueGenerateGraph', () => {});it('keeps a fixed seed for every run when randomization is disabled', async () => {- const { enqueueGenerateGraph } = await import('./api');+ const { enqueueGenerate } = await import('./submissionApi');- await enqueueGenerateGraph(createRequest({ shouldRandomizeSeed: false }));+ await enqueueGenerate(createRequest({ shouldRandomizeSeed: false }));const body = getSubmittedBody();@@ -85,9 +85,9 @@ describe('enqueueGenerateGraph', () => {});it('expands seeds per batch item only when randomization is enabled', async () => {- const { enqueueGenerateGraph } = await import('./api');+ const { enqueueGenerate } = await import('./submissionApi');- await enqueueGenerateGraph(createRequest({ shouldRandomizeSeed: true }));+ await enqueueGenerate(createRequest({ shouldRandomizeSeed: true }));const body = getSubmittedBody();@@ -104,15 +104,15 @@ describe('enqueueGenerateGraph', () => {});it('includes project-aware webv2 origin metadata', async () => {- const { enqueueGenerateGraph } = await import('./api');+ const { enqueueGenerate } = await import('./submissionApi');- await enqueueGenerateGraph(createRequest());+ await enqueueGenerate(createRequest());expect(getSubmittedBody().batch.origin).toBe('webv2:p:project-1:q:local-1');});});-describe('enqueueWorkflowGraph', () => {+describe('enqueueWorkflow', () => {beforeEach(() => {mocks.apiFetchJson.mockReset();mocks.apiFetchJson.mockResolvedValue({@@ -124,23 +124,23 @@ describe('enqueueWorkflowGraph', () => {});it('submits workflow runs for the requested batch count', async () => {- const { enqueueWorkflowGraph } = await import('./api');+ const { enqueueWorkflow } = await import('./submissionApi');- await enqueueWorkflowGraph(createWorkflowRequest());+ await enqueueWorkflow(createWorkflowRequest());expect(getSubmittedBody().batch.runs).toBe(2);});it('does not cap workflow runs', async () => {- const { enqueueWorkflowGraph } = await import('./api');+ const { enqueueWorkflow } = await import('./submissionApi');- await enqueueWorkflowGraph(createWorkflowRequest({ batchCount: 10_000 }));+ await enqueueWorkflow(createWorkflowRequest({ batchCount: 10_000 }));expect(getSubmittedBody().batch.runs).toBe(10_000);});});-describe('getQueueItemResultImages', () => {+describe('getResultImages', () => {beforeEach(() => {mocks.apiFetchJson.mockReset();});@@ -179,9 +179,9 @@ describe('getQueueItemResultImages', () => {});});- const { getQueueItemResultImages } = await import('./api');+ const { getResultImages } = await import('./submissionApi');- const images = await getQueueItemResultImages(1, 'source-1', '2026-06-15T00:00:00.000Z', {+ const images = await getResultImages(1, 'source-1', '2026-06-15T00:00:00.000Z', {resultNodeIds: ['canvas_output'],});@@ -215,9 +215,9 @@ describe('getQueueItemResultImages', () => {});});- const { getQueueItemResultImages } = await import('./api');+ const { getResultImages } = await import('./submissionApi');- const images = await getQueueItemResultImages(1, 'source-1', '2026-06-15T00:00:00.000Z');+ const images = await getResultImages(1, 'source-1', '2026-06-15T00:00:00.000Z');expect(images.map((image) => image.imageName)).toEqual(['external-a.png', 'external-b.png']);});diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.tsnew file mode 100644index 0000000000..98f11453ed--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts@@ -0,0 +1,178 @@+import type {+ QueueEnqueueGenerateRequest,+ QueueEnqueueResult,+ QueueEnqueueWorkflowRequest,+ QueueResultImage,+ QueueResultImageOptions,+} from '@features/queue/core/types';++import { absolutizeApiUrl, ApiError, apiFetchJson } from '@platform/transport/http';++import type { QueueImageDTO, QueueServerItemDTO } from './serverTypes';++import { buildQueueItemOrigin } from './events';+import { getQueueItem } from './serverApi';++const SEED_MAX = 4_294_967_295;++const sanitizeBatchCount = (value: unknown): number =>+ typeof value === 'number' && Number.isFinite(value) ? Math.max(1, Math.round(value)) : 1;++const generateSeedSequence = (start: number, count: number): number[] =>+ Array.from({ length: sanitizeBatchCount(count) }, (_, index) => (start + index) % SEED_MAX);++const mapEnqueueResult = (result: {+ batch?: { batch_id?: string };+ enqueued?: number;+ item_ids?: number[];+ requested?: number;+}): QueueEnqueueResult => ({+ batchId: result.batch?.batch_id,+ enqueued: result.enqueued ?? 0,+ itemIds: result.item_ids ?? [],+ requested: result.requested ?? 0,+});++export const enqueueGenerate = async (request: QueueEnqueueGenerateRequest): Promise<QueueEnqueueResult> => {+ const batchCount = sanitizeBatchCount(request.batchCount);+ const seeds = request.shouldRandomizeSeed ? generateSeedSequence(request.seed, batchCount) : [request.seed];+ const prompts = request.shouldRandomizeSeed ? seeds.map(() => request.positivePrompt) : [request.positivePrompt];+ const negativePrompts = request.shouldRandomizeSeed+ ? seeds.map(() => request.negativePrompt)+ : [request.negativePrompt];+ const result = await apiFetchJson<{+ batch?: { batch_id?: string };+ enqueued?: number;+ item_ids?: number[];+ requested?: number;+ }>('/api/v1/queue/default/enqueue_batch', {+ body: JSON.stringify({+ batch: {+ data: [+ [+ { field_name: 'value', items: seeds, node_path: request.seedNodeId },+ { field_name: 'value', items: prompts, node_path: request.positivePromptNodeId },+ { field_name: 'value', items: negativePrompts, node_path: request.negativePromptNodeId },+ ],+ ],+ destination: request.destination,+ graph: request.graph,+ origin: buildQueueItemOrigin(request.sourceQueueItemId, request.projectId),+ runs: request.shouldRandomizeSeed ? 1 : batchCount,+ },+ prepend: false,+ }),+ method: 'POST',+ });++ return mapEnqueueResult(result);+};++export const enqueueWorkflow = async (request: QueueEnqueueWorkflowRequest): Promise<QueueEnqueueResult> => {+ const result = await apiFetchJson<{+ batch?: { batch_id?: string };+ enqueued?: number;+ item_ids?: number[];+ requested?: number;+ }>('/api/v1/queue/default/enqueue_batch', {+ body: JSON.stringify({+ batch: {+ destination: request.destination,+ graph: request.graph,+ origin: buildQueueItemOrigin(request.sourceQueueItemId, request.projectId),+ runs: sanitizeBatchCount(request.batchCount),+ },+ prepend: false,+ }),+ method: 'POST',+ });++ return mapEnqueueResult(result);+};++export const enqueueUtility = async (request: {+ graph: QueueEnqueueWorkflowRequest['graph'];+ origin: string;+}): Promise<{ enqueued: number; itemIds: number[] }> => {+ const result = await apiFetchJson<{ enqueued?: number; item_ids?: number[] }>('/api/v1/queue/default/enqueue_batch', {+ body: JSON.stringify({ batch: { graph: request.graph, origin: request.origin, runs: 1 }, prepend: false }),+ method: 'POST',+ });++ return { enqueued: result.enqueued ?? 0, itemIds: result.item_ids ?? [] };+};++const getResultImageNames = (queueItem: QueueServerItemDTO, options?: QueueResultImageOptions): string[] => {+ const imageNames = new Set<string>();+ const results = queueItem.session?.results ?? {};+ const preparedSourceMapping = queueItem.session?.prepared_source_mapping ?? {};+ const resultValues = options?.resultNodeIds+ ? Object.entries(results)+ .filter(([nodeId]) => options.resultNodeIds?.includes(preparedSourceMapping[nodeId] ?? nodeId))+ .map(([, result]) => result)+ : Object.values(results);++ for (const result of resultValues) {+ if (!result || typeof result !== 'object') {+ continue;+ }++ const imageName = (result as { image?: { image_name?: unknown } }).image?.image_name;+ if (typeof imageName === 'string') {+ imageNames.add(imageName);+ }++ const collection = (result as { collection?: unknown }).collection;+ if (Array.isArray(collection)) {+ for (const item of collection) {+ const collectionImageName =+ item && typeof item === 'object' ? (item as { image_name?: unknown }).image_name : undefined;+ if (typeof collectionImageName === 'string') {+ imageNames.add(collectionImageName);+ }+ }+ }+ }++ return [...imageNames];+};++const getResultImage = async (+ imageName: string,+ queuedAt: string,+ sourceQueueItemId: string+): Promise<QueueResultImage | null> => {+ try {+ const image = await apiFetchJson<QueueImageDTO>(`/api/v1/images/i/${encodeURIComponent(imageName)}`);++ return {+ height: image.height,+ imageName: image.image_name,+ imageUrl: absolutizeApiUrl(image.image_url),+ isIntermediate: image.is_intermediate,+ queuedAt,+ sourceQueueItemId,+ thumbnailUrl: absolutizeApiUrl(image.thumbnail_url),+ width: image.width,+ };+ } catch (error) {+ if (error instanceof ApiError && error.status === 404) {+ return null;+ }+ throw error;+ }+};++export const getResultImages = async (+ itemId: number,+ sourceQueueItemId: string,+ queuedAt: string,+ options?: QueueResultImageOptions+): Promise<QueueResultImage[]> => {+ const item = await getQueueItem(itemId);+ const images = await Promise.all(+ getResultImageNames(item, options).map((imageName) => getResultImage(imageName, queuedAt, sourceQueueItemId))+ );++ return images.filter((image): image is QueueResultImage => image !== null);+};diff --git a/invokeai/frontend/webv2/src/features/queue/index.ts b/invokeai/frontend/webv2/src/features/queue/index.tsnew file mode 100644index 0000000000..adbd8a6cb3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/index.ts@@ -0,0 +1,55 @@+export type {+ QueueCounts,+ QueueFeatureCommands,+ QueueItemIdsReadModel,+ QueueItemProgress,+ QueueItemReadModel,+ QueueItemStatus,+ QueueNodeFieldValue,+ QueueProcessorReadModel,+ QueueQueryScope,+ QueueReadModel,+ QueueStatusReadModel,+ TerminalQueueItemStatus,+} from './core/types';+export type {+ QueueHistoryItemStatus,+ QueueItem,+ QueueState,+ QueueSubmissionSnapshot,+ RunRecord,+} from './core/historyTypes';+export { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from './core/historySnapshot';+export {+ getProjectQueueIndicatorState,+ getQueueItemExpectedImageCount,+ getQueueProgressBarState,+ getQueueProgressBarValue,+ getQueueSummary,+ isOpenQueueItem,+ type ProjectQueueIndicatorState,+ type QueueProgressBarState,+ type QueueSummary,+} from './core/historySummary';+export {+ BACKEND_SUBMITTABLE_SOURCE_IDS,+ isBackendSubmittableSourceId,+ shouldSubmitPendingQueueItem,+} from './core/submissionRules';+export {+ buildProjectQueueItemOriginPrefix,+ buildQueueItemOrigin,+ buildUtilityQueueItemOrigin,+ isTerminalBackendStatus,+ isUtilityQueueItemOrigin,+ parseQueueItemOrigin,+ parseQueueItemOriginProjectId,+ type BackendSocketEvents,+ type InvocationCompleteEvent,+ type InvocationErrorEvent,+ type InvocationProgressEvent,+ type InvocationStartedEvent,+ type QueueItemStatusChangedEvent,+} from './data/events';+export { createProductionQueueRuntime, queueCommands } from './publicApi';+export { hasPendingWorkflowQueueItem } from './ui/queueViewModel';diff --git a/invokeai/frontend/webv2/src/features/queue/menu.ts b/invokeai/frontend/webv2/src/features/queue/menu.tsnew file mode 100644index 0000000000..3e86914d51--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/menu.ts@@ -0,0 +1,2 @@+/** Queue menu integration surface for the Workbench top bar. */+export { QueueMenuItems, useQueueMenuActions } from './ui/queueMenuActions';diff --git a/invokeai/frontend/webv2/src/features/queue/publicApi.ts b/invokeai/frontend/webv2/src/features/queue/publicApi.tsnew file mode 100644index 0000000000..8264a747ac--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/publicApi.ts@@ -0,0 +1,54 @@+import type { QueueFeatureCommands, QueueQueryScope, QueueReadModel } from './core/types';+import type { QueueItemProgressPort, QueueRealtimeRuntime } from './data/realtimeRuntime';+import type { QueueHistoryPort, QueueResultDestinationPort, QueueRuntime } from './runtime';+import type { QueueNodeExecutionPort } from './runtime/coordinator';++import { queueBackend } from './data/httpRealtimeQueueBackend';+import { queueReadModelOptions } from './data/queries';+import { createQueueRealtimeRuntime } from './data/realtimeRuntime';+import { createQueueRuntime } from './runtime';++export const queueCommands: QueueFeatureCommands = {+ cancelCurrentItem: queueBackend.cancelCurrentItem,+ cancelItem: async (itemId) => {+ await queueBackend.cancelItem(itemId);+ },+ cancelScopedItems: queueBackend.cancelScopedItems,+ clearFailedItems: queueBackend.clearFailedItems,+ clearItems: queueBackend.clearItems,+ pauseProcessor: async () => {+ await queueBackend.pauseProcessor();+ },+ resumeProcessor: async () => {+ await queueBackend.resumeProcessor();+ },+};++export const getQueueReadModelOptions = (scope: QueueQueryScope, onRead?: (model: QueueReadModel) => void) =>+ queueReadModelOptions(queueBackend, scope, onRead);++export const createProductionQueueRealtimeRuntime = ({+ coalesceMs,+ invalidate,+ progress,+ refreshModelCache,+}: {+ coalesceMs?: number;+ invalidate: () => void | Promise<void>;+ progress: QueueItemProgressPort;+ refreshModelCache: () => void | Promise<void>;+}): QueueRealtimeRuntime =>+ createQueueRealtimeRuntime({ backend: queueBackend, coalesceMs, invalidate, progress, refreshModelCache });++export const createProductionQueueRuntime = ({+ destinations,+ ensureTemplatesLoaded,+ history,+ nodeExecution,+}: {+ destinations: QueueResultDestinationPort;+ ensureTemplatesLoaded: () => void;+ history: QueueHistoryPort;+ nodeExecution: QueueNodeExecutionPort;+}): QueueRuntime =>+ createQueueRuntime({ backend: queueBackend, destinations, ensureTemplatesLoaded, history, nodeExecution });diff --git a/invokeai/frontend/webv2/src/features/queue/react.ts b/invokeai/frontend/webv2/src/features/queue/react.tsnew file mode 100644index 0000000000..c609fa2465--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/react.ts@@ -0,0 +1,11 @@+/** React-facing Queue read models, kept separate from widget registration. */+export type { QueueItemProgress } from './core/types';+export { type ItemProgress, useItemProgress } from './data/itemProgressStore';+export {+ type LatestProgressImageSnapshot,+ useProgressImage,+ useQueueItemProgressImage,+} from './data/progressImageStore';+export { type QueueItemProgressSink, useQueueItemProgress } from './data/progressStore';+export { useRevealHold } from './data/revealHoldStore';+export { QueueUiProvider, type QueueUiAdapter } from './ui/QueueUiContext';diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.tsnew file mode 100644index 0000000000..292a902e52--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts@@ -0,0 +1,125 @@+import type { QueueItem } from '@features/queue/core/historyTypes';+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';++const createPendingQueueItem = (): QueueItem => ({+ cancellable: true,+ id: 'local-queue-item',+ snapshot: {+ backendSubmission: {+ batchCount: 1,+ graph: { edges: [], id: 'backend-graph', nodes: {} },+ kind: 'generate',+ negativePrompt: '',+ negativePromptNodeId: 'negative_prompt',+ positivePrompt: '',+ positivePromptNodeId: 'positive_prompt',+ seed: 0,+ seedNodeId: 'seed',+ shouldRandomizeSeed: false,+ },+ destination: 'canvas',+ filterIntermediateResults: false,+ galleryBoardId: null,+ graph: { id: 'graph', label: 'Generate' },+ presentation: { batchCount: 1, height: 1024, width: 1024 },+ resultNodeIds: ['canvas_output'],+ sourceId: 'generate',+ submittedAt: '2026-07-17T00:00:00.000Z',+ },+ status: 'pending',+});++describe('queue runtime', () => {+ 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] } };+ const enqueueGenerate = vi.fn();+ const listItems = vi.fn().mockResolvedValue([+ {+ batchId: 'backend-batch',+ id: 77,+ origin: buildQueueItemOrigin(queueItem.id, project.id),+ status: 'in_progress',+ },+ ]);+ const backend: QueueBackendPort = {+ cancelCurrentItem: vi.fn(),+ cancelItem: vi.fn(),+ cancelQueueItems: vi.fn(),+ cancelQueueItemsByBatchIds: vi.fn(),+ cancelScopedItems: vi.fn(),+ clearFailedItems: vi.fn(),+ clearItems: vi.fn(),+ emit: vi.fn(),+ enqueueGenerate,+ enqueueWorkflow: vi.fn(),+ getItem: vi.fn(),+ getResultImages: vi.fn(),+ listItems,+ on: vi.fn(() => vi.fn()),+ onConnectionChange: vi.fn((listener) => {+ listener('connected');+ return vi.fn();+ }),+ pauseProcessor: vi.fn(),+ readCurrent: vi.fn(),+ readItemIds: vi.fn(),+ readItemsById: vi.fn(),+ readNext: vi.fn(),+ readStatus: vi.fn(),+ resumeProcessor: vi.fn(),+ retryItems: vi.fn(),+ };+ const commands: QueueHistoryCommands = {+ markBackendCancelled: vi.fn(),+ markBackendSubmitted: ({ backendBatchId, backendItemIds }) => {+ queueItem.backendBatchId = backendBatchId;+ queueItem.backendItemIds = backendItemIds;+ queueItem.status = 'running';+ },+ recordError: vi.fn(),+ refreshBackendData: vi.fn(),+ routePartialResults: vi.fn(),+ routeResults: vi.fn(),+ setConnectionStatus: vi.fn(),+ setStatus: vi.fn(),+ };+ const runtime = createQueueRuntime({+ backend,+ destinations: { addImagesToGalleryBoard: vi.fn() },+ ensureTemplatesLoaded: vi.fn(),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ nodeExecution: {+ clearAll: vi.fn(),+ completed: vi.fn(),+ failed: vi.fn(),+ progress: vi.fn(),+ settleRunning: vi.fn(),+ started: vi.fn(),+ },+ });++ runtime.start();++ await vi.waitFor(() => {+ expect(queueItem).toMatchObject({+ backendBatchId: 'backend-batch',+ backendItemIds: [77],+ status: 'running',+ });+ });+ expect(listItems).toHaveBeenCalledTimes(1);+ expect(enqueueGenerate).not.toHaveBeenCalled();++ runtime.dispose();+ });+});diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.tsnew file mode 100644index 0000000000..19a25d0257--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts@@ -0,0 +1,500 @@+import type { QueueItem } from '@features/queue/core/historyTypes';+import type {+ QueueBackendPort,+ QueueEnqueueGenerateRequest,+ QueueEnqueueWorkflowRequest,+ QueueResultImage,+ QueueResultImageOptions,+} from '@features/queue/core/types';+import type { BackendConnectionStatus } from '@platform/transport/types';++import { shouldSubmitPendingQueueItem } from '@features/queue/core/submissionRules';+import {+ createQueueCoordinator,+ QueueItemCancelledError,+ type QueueCoordinator,+ type QueueNodeExecutionPort,+ type ReconcileInput,+} from '@features/queue/runtime/coordinator';+import { getApiErrorMessage } from '@platform/transport/http';++export interface QueueResultDestinationPort {+ addImagesToGalleryBoard(boardId: string, imageNames: string[]): Promise<void>;+}++export interface QueueRuntime {+ dispose(): void;+ start(): void;+}++export interface QueueHistoryProject {+ id: string;+ queue: { items: QueueItem[] };+}++export interface QueueHistoryCommands {+ markBackendCancelled(payload: { backendItemId: number; projectId: string; queueItemId: string }): void;+ markBackendSubmitted(payload: {+ backendBatchId?: string;+ backendItemIds: number[];+ projectId: string;+ queueItemId: string;+ }): void;+ recordError(payload: { area: string; message: string; namespace: 'queue'; projectId?: string }): void;+ refreshBackendData(): void;+ routePartialResults(payload: {+ backendItemId: number;+ images: QueueResultImage[];+ projectId: string;+ queueItemId: string;+ }): void;+ routeResults(payload: { images: QueueResultImage[]; projectId: string; queueItemId: string }): void;+ setConnectionStatus(payload: { error?: string; status: BackendConnectionStatus }): void;+ setStatus(payload: {+ error?: string;+ notify?: boolean;+ projectId: string;+ queueItemId: string;+ status: QueueItem['status'];+ }): void;+}++type QueueItemBackendSubmission =+ | { kind: 'generate'; request: QueueEnqueueGenerateRequest }+ | { kind: 'workflow'; request: QueueEnqueueWorkflowRequest }+ | { error: string; kind: 'invalid' };++const toErrorMessage = (error: unknown): string =>+ getApiErrorMessage(error, error instanceof Error ? error.message : String(error));++export const getQueueItemResultImageOptions = (queueItem: QueueItem): QueueResultImageOptions | undefined => {+ return queueItem.snapshot.resultNodeIds ? { resultNodeIds: queueItem.snapshot.resultNodeIds } : undefined;+};++export const createQueueItemBackendSubmission = (+ project: Pick<QueueHistoryProject, 'id'>,+ queueItem: QueueItem+): QueueItemBackendSubmission => {+ const submission = queueItem.snapshot.backendSubmission;++ if (submission.kind === 'invalid') {+ return submission;+ }++ if (submission.kind === 'generate') {+ const { kind: _, ...compiled } = submission;+ return {+ kind: 'generate',+ request: {+ ...compiled,+ destination: queueItem.snapshot.destination,+ projectId: project.id,+ sourceQueueItemId: queueItem.id,+ },+ };+ }++ const { kind: _, ...compiled } = submission;+ return {+ kind: 'workflow',+ request: {+ ...compiled,+ destination: queueItem.snapshot.destination,+ projectId: project.id,+ sourceQueueItemId: queueItem.id,+ },+ };+};++export interface QueueHistoryPort {+ commands: QueueHistoryCommands;+ getSnapshot(): {+ connectionStatus: BackendConnectionStatus;+ isHydrated: boolean;+ projects: QueueHistoryProject[];+ };+ subscribe(listener: () => void): () => void;+}++const getRouteTarget = (history: QueueHistoryPort, localQueueItemId: string) =>+ history+ .getSnapshot()+ .projects.map((project) => ({+ project,+ queueItem: project.queue.items.find((item) => item.id === localQueueItemId),+ }))+ .find((target) => target.queueItem !== undefined);++export const createQueueRuntime = ({+ backend,+ destinations,+ ensureTemplatesLoaded,+ history,+ nodeExecution,+}: {+ backend: QueueBackendPort;+ destinations: QueueResultDestinationPort;+ ensureTemplatesLoaded: () => void;+ history: QueueHistoryPort;+ nodeExecution: QueueNodeExecutionPort;+}): QueueRuntime => {+ const commands = history.commands;+ const startedQueueItemIds = new Set<string>();+ const cancelledQueueItemIds = new Set<string>();+ const detachers: Array<() => void> = [];+ let reconcileState: 'idle' | 'running' | 'done' = 'idle';+ let isDisposed = false;+ let isStarted = false;++ const addImagesToDestination = async (queueItem: QueueItem, imageNames: string[]): Promise<void> => {+ if (queueItem.snapshot.destination !== 'gallery') {+ return;+ }++ const boardId = queueItem.snapshot.galleryBoardId;++ if (boardId && boardId !== 'none') {+ await destinations.addImagesToGalleryBoard(boardId, imageNames);+ }+ };++ /** Drop intermediates when the item asks for it, then land what remains on its destination. */+ const deliverVisibleImages = async (+ queueItem: QueueItem,+ allImages: QueueResultImage[]+ ): Promise<QueueResultImage[]> => {+ const images = queueItem.snapshot.filterIntermediateResults+ ? allImages.filter((image) => !image.isIntermediate)+ : allImages;++ await addImagesToDestination(+ queueItem,+ images.map((image) => image.imageName)+ );++ return images;+ };++ const routeRunResults = async (+ coordinator: QueueCoordinator,+ projectId: string,+ queueItem: QueueItem+ ): Promise<void> => {+ try {+ const allImages = await coordinator.waitForResults(+ queueItem.id,+ queueItem.snapshot.submittedAt,+ getQueueItemResultImageOptions(queueItem)+ );+ const images = await deliverVisibleImages(queueItem, allImages);++ if (isDisposed) {+ return;+ }++ commands.routeResults({ images, projectId, queueItemId: queueItem.id });+ if (queueItem.snapshot.destination === 'gallery') {+ commands.refreshBackendData();+ }+ } catch (error) {+ if (isDisposed) {+ return;+ }++ if (error instanceof QueueItemCancelledError) {+ commands.setStatus({ projectId, queueItemId: queueItem.id, status: 'cancelled' });+ return;+ }++ commands.setStatus({+ error: toErrorMessage(error),+ projectId,+ queueItemId: queueItem.id,+ status: 'failed',+ });+ }+ };++ const routeBackendItemResults = async (+ projectId: string,+ queueItem: QueueItem,+ backendItemId: number+ ): Promise<void> => {+ try {+ const images = await backend.getResultImages(+ backendItemId,+ queueItem.id,+ queueItem.snapshot.submittedAt,+ getQueueItemResultImageOptions(queueItem)+ );+ const visibleImages = await deliverVisibleImages(queueItem, images);++ if (isDisposed) {+ return;+ }++ commands.routePartialResults({+ backendItemId,+ images: visibleImages,+ projectId,+ queueItemId: queueItem.id,+ });+ if (queueItem.snapshot.destination === 'gallery') {+ commands.refreshBackendData();+ }+ } catch (error) {+ if (!isDisposed) {+ commands.recordError({+ area: 'queue-results',+ message: toErrorMessage(error),+ namespace: 'queue',+ projectId,+ });+ }+ }+ };++ const coordinator = createQueueCoordinator(+ {+ onBackendItemCancelled: (localQueueItemId, backendItemId) => {+ const target = getRouteTarget(history, localQueueItemId);++ if (!target?.queueItem || target.queueItem.cancelledBackendItemIds?.includes(backendItemId)) {+ return;+ }++ commands.markBackendCancelled({+ backendItemId,+ projectId: target.project.id,+ queueItemId: localQueueItemId,+ });+ },+ onBackendItemComplete: (localQueueItemId, backendItemId) => {+ const target = getRouteTarget(history, localQueueItemId);++ if (!target?.queueItem || target.queueItem.completedBackendItemIds?.includes(backendItemId)) {+ return;+ }++ return routeBackendItemResults(target.project.id, target.queueItem, backendItemId);+ },+ onGalleryRefresh: commands.refreshBackendData,+ },+ { backend, nodeExecution }+ );++ const submitQueueItem = (project: QueueHistoryProject, queueItem: QueueItem): void => {+ const submission = createQueueItemBackendSubmission(project, queueItem);++ if (submission.kind === 'invalid') {+ commands.setStatus({+ error: submission.error,+ projectId: project.id,+ queueItemId: queueItem.id,+ status: 'failed',+ });+ return;+ }++ const request =+ submission.kind === 'generate'+ ? coordinator.submitGenerate(queueItem.id, submission.request)+ : coordinator.submitWorkflow(queueItem.id, submission.request);++ request+ .then(({ batchId, itemIds }) => {+ if (isDisposed) {+ return;+ }++ commands.markBackendSubmitted({+ backendBatchId: batchId,+ backendItemIds: itemIds,+ projectId: project.id,+ queueItemId: queueItem.id,+ });+ void backend.resumeProcessor().catch(() => undefined);++ return routeRunResults(coordinator, project.id, queueItem);+ })+ .catch((error: unknown) => {+ if (!isDisposed) {+ commands.setStatus({+ error: toErrorMessage(error),+ projectId: project.id,+ queueItemId: queueItem.id,+ status: 'failed',+ });+ }+ });+ };++ const processQueueItems = (): void => {+ if (isDisposed || reconcileState !== 'done') {+ return;+ }++ for (const project of history.getSnapshot().projects) {+ for (const queueItem of project.queue.items) {+ if (shouldSubmitPendingQueueItem(queueItem) && !startedQueueItemIds.has(queueItem.id)) {+ startedQueueItemIds.add(queueItem.id);+ submitQueueItem(project, queueItem);+ }++ if (+ queueItem.status === 'cancelled' &&+ (queueItem.backendBatchId || queueItem.backendItemIds?.length) &&+ !cancelledQueueItemIds.has(queueItem.id)+ ) {+ cancelledQueueItemIds.add(queueItem.id);+ coordinator+ .cancelRun({ backendBatchId: queueItem.backendBatchId, backendItemIds: queueItem.backendItemIds })+ .catch((error: unknown) => {+ if (!isDisposed) {+ commands.recordError({+ area: 'queue-cancel',+ message: toErrorMessage(error),+ namespace: 'queue',+ });+ }+ });+ }+ }+ }+ };++ const reconcile = (): void => {+ if (+ isDisposed ||+ reconcileState !== 'idle' ||+ !history.getSnapshot().isHydrated ||+ history.getSnapshot().connectionStatus !== 'connected'+ ) {+ return;+ }++ reconcileState = 'running';+ const openItems = history+ .getSnapshot()+ .projects.flatMap((project) =>+ project.queue.items+ .filter((queueItem) => queueItem.status === 'pending' || queueItem.status === 'running')+ .map((queueItem) => ({ project, queueItem }))+ );++ for (const { queueItem } of openItems) {+ startedQueueItemIds.add(queueItem.id);+ }++ const inputs: ReconcileInput[] = openItems.map(({ queueItem }) => ({+ backendBatchId: queueItem.backendBatchId,+ backendItemIds: queueItem.backendItemIds,+ id: queueItem.id,+ status: queueItem.status === 'running' ? 'running' : 'pending',+ }));++ coordinator+ .reconcile(inputs)+ .then((outcomes) => {+ if (isDisposed) {+ return;+ }++ for (const { project, queueItem } of openItems) {+ const outcome = outcomes.get(queueItem.id);++ switch (outcome?.kind) {+ case 'enqueue':+ startedQueueItemIds.delete(queueItem.id);+ break;+ case 'adopted':+ commands.markBackendSubmitted({+ backendBatchId: outcome.backendBatchId,+ backendItemIds: outcome.backendItemIds,+ projectId: project.id,+ queueItemId: queueItem.id,+ });+ void routeRunResults(coordinator, project.id, queueItem);+ break;+ case 'resumed':+ void routeRunResults(coordinator, project.id, queueItem);+ break;+ case 'missing':+ commands.setStatus({+ error: 'This run is no longer on the backend queue (it may have been cleared).',+ notify: false,+ projectId: project.id,+ queueItemId: queueItem.id,+ status: 'failed',+ });+ break;+ }+ }+ })+ .catch((error: unknown) => {+ if (isDisposed) {+ return;+ }++ commands.recordError({+ area: 'queue-reconciliation',+ message: `Queue reconciliation failed: ${toErrorMessage(error)}`,+ namespace: 'queue',+ });++ for (const { project, queueItem } of openItems) {+ if (queueItem.status === 'pending') {+ startedQueueItemIds.delete(queueItem.id);+ } else {+ commands.setStatus({+ error: 'Could not reconcile this run with the backend queue after reload.',+ projectId: project.id,+ queueItemId: queueItem.id,+ status: 'failed',+ });+ }+ }+ })+ .finally(() => {+ if (!isDisposed) {+ reconcileState = 'done';+ processQueueItems();+ }+ });+ };++ const synchronize = (): void => {+ reconcile();+ processQueueItems();+ };++ const start = (): void => {+ if (isStarted || isDisposed) {+ return;+ }++ isStarted = true;+ coordinator.connect();+ ensureTemplatesLoaded();+ detachers.push(+ history.subscribe(synchronize),+ backend.onConnectionChange((status, error) => {+ commands.setConnectionStatus({ error, status });+ synchronize();+ })+ );+ synchronize();+ };++ const dispose = (): void => {+ isDisposed = true;++ for (const detach of detachers.splice(0)) {+ detach();+ }++ coordinator.dispose();+ };++ return { dispose, start };+};diff --git a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.tssimilarity index 85%rename from invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.tsrename to invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.tsindex 1fa2bec550..b5f5d05edb 100644--- a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts@@ -1,20 +1,28 @@-import type { EnqueueGenerateRequest, ImageDTO, QueueItemDTO } from '@workbench/generation/types';+import type {+ QueueBackendItem,+ QueueEnqueueGenerateRequest,+ QueueItemProgress,+ QueueResultImage,+} from '@features/queue/core/types';+import type { QueueItemProgressSink } from '@features/queue/data/progressStore';+import {+ buildQueueItemOrigin,+ buildUtilityQueueItemOrigin,+ type QueueItemStatusChangedEvent,+} from '@features/queue/data/events';+import { ApiError } from '@platform/transport/http';+import { createSocketHub, type BackendSocket } from '@platform/transport/socketHub';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { NodeExecutionSink } from './nodeExecutionStore';-import type { QueueItemProgress, QueueItemProgressSink } from './progressStore';--import { buildQueueItemOrigin, buildUtilityQueueItemOrigin, type QueueItemStatusChangedEvent } from './events';-import { ApiError } from './http';import {createQueueCoordinator,QueueItemCancelledError,type QueueCoordinator,- type QueueCoordinatorApi,+ type QueueCoordinatorBackendPort,type QueueCoordinatorCallbacks,-} from './queueCoordinator';-import { createSocketHub, type BackendSocket } from './socketHub';+ type QueueNodeExecutionPort,+} from './coordinator';class FakeSocket implements BackendSocket {readonly emitted: { event: string; payload: unknown }[] = [];@@ -68,14 +76,13 @@ const createStatusEvent = (overrides: Partial<QueueItemStatusChangedEvent>): Que...overrides,});-const createQueueItemDTO = (overrides: Partial<QueueItemDTO>): QueueItemDTO => ({- item_id: 1,- session: { results: {} },+const createQueueBackendItem = (overrides: Partial<QueueBackendItem>): QueueBackendItem => ({+ id: 1,status: 'in_progress',...overrides,});-const createImage = (imageName: string, sourceQueueItemId: string): ImageDTO => ({+const createImage = (imageName: string, sourceQueueItemId: string): QueueResultImage => ({height: 64,imageName,imageUrl: `https://example.test/${imageName}`,@@ -86,7 +93,7 @@ const createImage = (imageName: string, sourceQueueItemId: string): ImageDTO =>width: 64,});-const generateRequest: EnqueueGenerateRequest = {+const generateRequest: QueueEnqueueGenerateRequest = {batchCount: 1,destination: 'gallery',graph: { edges: [], id: 'graph-1', nodes: {} },@@ -102,11 +109,13 @@ const generateRequest: EnqueueGenerateRequest = {};interface Harness {- api: { [Key in keyof QueueCoordinatorApi]: ReturnType<typeof vi.fn> };+ api: {+ [Key in Exclude<keyof QueueCoordinatorBackendPort, 'emit' | 'on' | 'onConnectionChange'>]: ReturnType<typeof vi.fn>;+ };callbacks: { [Key in keyof QueueCoordinatorCallbacks]: ReturnType<typeof vi.fn> };coordinator: QueueCoordinator;hub: ReturnType<typeof createSocketHub>;- nodeExecution: { [Key in keyof NodeExecutionSink]: ReturnType<typeof vi.fn> };+ nodeExecution: { [Key in keyof QueueNodeExecutionPort]: ReturnType<typeof vi.fn> };progressImage: { clear: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };progressEntries: Map<string, QueueItemProgress>;socket: FakeSocket;@@ -126,13 +135,13 @@ const createHarness = (options: { galleryRefreshCoalesceMs?: number } = {}): Harconst api = {cancelQueueItems: vi.fn(() => Promise.resolve()),cancelQueueItemsByBatchIds: vi.fn(() => Promise.resolve()),- enqueueGenerateGraph: vi.fn(() => Promise.resolve({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 })),- enqueueWorkflowGraph: vi.fn(() => Promise.resolve({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 })),- getQueueItem: vi.fn((itemId: number) => Promise.resolve(createQueueItemDTO({ item_id: itemId }))),- getQueueItemResultImages: vi.fn((itemId: number, sourceQueueItemId: string) =>+ enqueueGenerate: vi.fn(() => Promise.resolve({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 })),+ enqueueWorkflow: vi.fn(() => Promise.resolve({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 })),+ getItem: vi.fn((itemId: number) => Promise.resolve(createQueueBackendItem({ id: itemId }))),+ getResultImages: vi.fn((itemId: number, sourceQueueItemId: string) =>Promise.resolve([createImage(`image-${itemId}.png`, sourceQueueItemId)])),- listAllQueueItems: vi.fn((): Promise<QueueItemDTO[]> => Promise.resolve([])),+ listItems: vi.fn((): Promise<QueueBackendItem[]> => Promise.resolve([])),};const callbacks = {onGalleryRefresh: vi.fn(),@@ -151,9 +160,13 @@ const createHarness = (options: { galleryRefreshCoalesceMs?: number } = {}): Harhub.connect();const coordinator = createQueueCoordinator(callbacks, {- api,+ backend: {+ ...api,+ emit: hub.emit,+ on: hub.on,+ onConnectionChange: hub.onConnectionChange,+ },galleryRefreshCoalesceMs: options.galleryRefreshCoalesceMs ?? 1,- hub,nodeExecution,progress,progressImage,@@ -176,7 +189,7 @@ describe('queueCoordinator', () => {});it('settles submitted runs from terminal socket events without polling', async () => {- harness.api.enqueueGenerateGraph.mockResolvedValue({+ harness.api.enqueueGenerate.mockResolvedValue({batchId: 'batch-1',enqueued: 2,itemIds: [1, 2],@@ -193,7 +206,7 @@ describe('queueCoordinator', () => {const images = await resultsPromise;expect(images.map((image) => image.imageName)).toEqual(['image-1.png', 'image-2.png']);- expect(harness.api.getQueueItem).not.toHaveBeenCalled();+ expect(harness.api.getItem).not.toHaveBeenCalled();});it('rejects with the backend error message when a run fails', async () => {@@ -223,7 +236,7 @@ describe('queueCoordinator', () => {it('returns completed batch item results when sibling backend items are canceled', async () => {harness.callbacks.onBackendItemCancelled = vi.fn();- harness.api.enqueueGenerateGraph.mockResolvedValue({+ harness.api.enqueueGenerate.mockResolvedValue({batchId: 'batch-1',enqueued: 3,itemIds: [1, 2, 3],@@ -241,8 +254,8 @@ describe('queueCoordinator', () => {const images = await resultsPromise;expect(images.map((image) => image.imageName)).toEqual(['image-2.png']);- expect(harness.api.getQueueItemResultImages).toHaveBeenCalledTimes(1);- expect(harness.api.getQueueItemResultImages).toHaveBeenCalledWith(2, 'local-1', '2026-06-10T00:00:00Z');+ expect(harness.api.getResultImages).toHaveBeenCalledTimes(1);+ expect(harness.api.getResultImages).toHaveBeenCalledWith(2, 'local-1', '2026-06-10T00:00:00Z');expect(harness.callbacks.onBackendItemCancelled).toHaveBeenCalledWith('local-1', 1);expect(harness.callbacks.onBackendItemCancelled).toHaveBeenCalledWith('local-1', 3);});@@ -259,13 +272,13 @@ describe('queueCoordinator', () => {await resultsPromise;- expect(harness.api.getQueueItemResultImages).toHaveBeenCalledWith(1, 'local-1', '2026-06-10T00:00:00Z', {+ expect(harness.api.getResultImages).toHaveBeenCalledWith(1, 'local-1', '2026-06-10T00:00:00Z', {resultNodeIds: ['canvas_output'],});});it('rejects with QueueItemCancelledError when every backend item in a batch is canceled', async () => {- harness.api.enqueueGenerateGraph.mockResolvedValue({+ harness.api.enqueueGenerate.mockResolvedValue({batchId: 'batch-1',enqueued: 2,itemIds: [1, 2],@@ -280,7 +293,7 @@ describe('queueCoordinator', () => {harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 2, status: 'canceled' }));await expect(resultsPromise).rejects.toBeInstanceOf(QueueItemCancelledError);- expect(harness.api.getQueueItemResultImages).not.toHaveBeenCalled();+ expect(harness.api.getResultImages).not.toHaveBeenCalled();});it('settles runs whose terminal event arrived before tracking began', async () => {@@ -297,7 +310,7 @@ describe('queueCoordinator', () => {});it('rejects runs when the backend queue accepts no items', async () => {- harness.api.enqueueGenerateGraph.mockResolvedValue({ batchId: 'batch-1', enqueued: 0, itemIds: [], requested: 1 });+ harness.api.enqueueGenerate.mockResolvedValue({ batchId: 'batch-1', enqueued: 0, itemIds: [], requested: 1 });await expect(harness.coordinator.submitGenerate('local-1', generateRequest)).rejects.toThrow('The backend queue did not accept this generation.'@@ -305,7 +318,7 @@ describe('queueCoordinator', () => {});it('rejects runs when the backend queue accepts only part of the batch', async () => {- harness.api.enqueueGenerateGraph.mockResolvedValue({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 2 });+ harness.api.enqueueGenerate.mockResolvedValue({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 2 });await expect(harness.coordinator.submitGenerate('local-1', generateRequest)).rejects.toThrow('The backend queue accepted 1 of 2 requested items.'@@ -315,7 +328,7 @@ describe('queueCoordinator', () => {it('coalesces gallery refreshes across a burst of completions', async () => {vi.useFakeTimers();harness = createHarness({ galleryRefreshCoalesceMs: 400 });- harness.api.enqueueGenerateGraph.mockResolvedValue({+ harness.api.enqueueGenerate.mockResolvedValue({batchId: 'batch-1',enqueued: 10,itemIds: Array.from({ length: 10 }, (_, index) => index + 1),@@ -338,7 +351,7 @@ describe('queueCoordinator', () => {it('does not refresh the gallery for failed or canceled items', async () => {vi.useFakeTimers();harness = createHarness({ galleryRefreshCoalesceMs: 400 });- harness.api.enqueueGenerateGraph.mockResolvedValue({+ harness.api.enqueueGenerate.mockResolvedValue({batchId: 'batch-1',enqueued: 2,itemIds: [1, 2],@@ -420,7 +433,7 @@ describe('queueCoordinator', () => {it('notifies when one backend item in a batch completes', async () => {harness.callbacks.onBackendItemComplete = vi.fn();- harness.api.enqueueGenerateGraph.mockResolvedValue({+ harness.api.enqueueGenerate.mockResolvedValue({batchId: 'batch-1',enqueued: 2,itemIds: [1, 2],@@ -436,7 +449,7 @@ describe('queueCoordinator', () => {});it('routes progress images to the active image slot inside a submitted batch', async () => {- harness.api.enqueueGenerateGraph.mockResolvedValue({+ harness.api.enqueueGenerate.mockResolvedValue({batchId: 'batch-1',enqueued: 2,itemIds: [1, 2],@@ -500,7 +513,7 @@ describe('queueCoordinator', () => {});it('tracks the active image index inside a submitted batch', async () => {- harness.api.enqueueGenerateGraph.mockResolvedValue({+ harness.api.enqueueGenerate.mockResolvedValue({batchId: 'batch-1',enqueued: 2,itemIds: [1, 2],@@ -537,23 +550,23 @@ describe('queueCoordinator', () => {describe('reconcile', () => {it('adopts pending items the backend already accepted, by origin', async () => {- harness.api.listAllQueueItems.mockResolvedValue([- createQueueItemDTO({ batch_id: 'batch-9', item_id: 7, origin: buildQueueItemOrigin('local-1') }),+ harness.api.listItems.mockResolvedValue([+ createQueueBackendItem({ batchId: 'batch-9', id: 7, origin: buildQueueItemOrigin('local-1') }),]);const outcomes = await harness.coordinator.reconcile([{ id: 'local-1', status: 'pending' }]);expect(outcomes.get('local-1')).toEqual({ backendBatchId: 'batch-9', backendItemIds: [7], kind: 'adopted' });- expect(harness.api.enqueueGenerateGraph).not.toHaveBeenCalled();+ expect(harness.api.enqueueGenerate).not.toHaveBeenCalled();});it('resumes running items and settles them from their listed terminal status', async () => {- harness.api.getQueueItem.mockResolvedValue(createQueueItemDTO({ item_id: 7, status: 'completed' }));+ harness.api.getItem.mockResolvedValue(createQueueBackendItem({ id: 7, status: 'completed' }));const outcomes = await harness.coordinator.reconcile([{ backendItemIds: [7], id: 'local-1', status: 'running' }]);expect(outcomes.get('local-1')).toEqual({ kind: 'resumed' });- expect(harness.api.listAllQueueItems).not.toHaveBeenCalled();+ expect(harness.api.listItems).not.toHaveBeenCalled();const images = await harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');@@ -561,16 +574,16 @@ describe('queueCoordinator', () => {});it('marks running items missing when their backend items vanished', async () => {- harness.api.getQueueItem.mockRejectedValue(new ApiError('not found', 404));+ harness.api.getItem.mockRejectedValue(new ApiError('not found', 404));const outcomes = await harness.coordinator.reconcile([{ backendItemIds: [7], id: 'local-1', status: 'running' }]);expect(outcomes.get('local-1')).toEqual({ kind: 'missing' });- expect(harness.api.listAllQueueItems).not.toHaveBeenCalled();+ expect(harness.api.listItems).not.toHaveBeenCalled();});it('asks for a fresh enqueue when a pending item left no backend trace', async () => {- harness.api.listAllQueueItems.mockResolvedValue([]);+ harness.api.listItems.mockResolvedValue([]);const outcomes = await harness.coordinator.reconcile([{ id: 'local-1', status: 'pending' }]);@@ -581,24 +594,23 @@ describe('queueCoordinator', () => {const outcomes = await harness.coordinator.reconcile([]);expect(outcomes.size).toBe(0);- expect(harness.api.listAllQueueItems).not.toHaveBeenCalled();+ expect(harness.api.listItems).not.toHaveBeenCalled();});// Review fix (Task 38, finding 3): the prior "Risk-4" coverage only asserted// the parse primitive (`parseQueueItemOrigin(utilityOrigin) === null`) in// isolation. This drives the REAL `reconcile` path with a completed,// result-carrying `webv2:util:<uuid>`-origin backend item mixed into a live- // `listAllQueueItems` response, proving the coordinator itself — not just the+ // `listItems` response, proving the coordinator itself — not just the// helper it calls — never adopts it into a project queue item (which is the// only way a utility item's images could ever reach `routeQueueItemResults`// and land in canvas staging or the gallery).it('never adopts a completed, result-carrying utility-origin item into a project queue item', async () => {- harness.api.listAllQueueItems.mockResolvedValue([- createQueueItemDTO({- batch_id: 'util-batch',- item_id: 99,+ harness.api.listItems.mockResolvedValue([+ createQueueBackendItem({+ batchId: 'util-batch',+ id: 99,origin: buildUtilityQueueItemOrigin('util-run-1'),- session: { results: { n1: { image: { image_name: 'util-result.png' }, type: 'image_output' } } },status: 'completed',}),]);@@ -610,8 +622,8 @@ describe('queueCoordinator', () => {// backend trace of its own and is asked to enqueue fresh — never// "adopted" with the utility item's id, and never routed anywhere.expect(outcomes.get('local-1')).toEqual({ kind: 'enqueue' });- expect(harness.api.getQueueItemResultImages).not.toHaveBeenCalled();- expect(harness.api.getQueueItem).not.toHaveBeenCalledWith(99);+ expect(harness.api.getResultImages).not.toHaveBeenCalled();+ expect(harness.api.getItem).not.toHaveBeenCalledWith(99);});});@@ -623,7 +635,7 @@ describe('queueCoordinator', () => {// The completion event was lost to a disconnect; the reconnect sweep// re-checks every outstanding item.- harness.api.getQueueItem.mockResolvedValue(createQueueItemDTO({ item_id: 1, status: 'completed' }));+ harness.api.getItem.mockResolvedValue(createQueueBackendItem({ id: 1, status: 'completed' }));harness.socket.fire('connect', undefined);const images = await resultsPromise;@@ -637,7 +649,7 @@ describe('queueCoordinator', () => {await harness.coordinator.submitGenerate('local-1', generateRequest);const resultsPromise = harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');- harness.api.getQueueItem.mockRejectedValue(new ApiError('not found', 404));+ harness.api.getItem.mockRejectedValue(new ApiError('not found', 404));harness.socket.fire('connect', undefined);await expect(resultsPromise).rejects.toThrow('no longer on the backend queue');diff --git a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.tssimilarity index 79%rename from invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.tsrename to invokeai/frontend/webv2/src/features/queue/runtime/coordinator.tsindex e85810f4e6..14556e4c71 100644--- a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts@@ -1,25 +1,16 @@import type {- EnqueueGenerateRequest,- EnqueueGenerateResult,- EnqueueWorkflowRequest,- ImageDTO,- QueueItemDTO,-} from '@workbench/generation/types';-import type { BackendConnectionStatus } from '@workbench/types';--import {- cancelQueueItems,- cancelQueueItemsByBatchIds,- enqueueGenerateGraph,- enqueueWorkflowGraph,- getQueueItem,- getQueueItemResultImages,- listAllQueueItems,- type QueueItemResultImageOptions,-} from '@workbench/generation/api';--import type { SocketHub } from './socketHub';-+ QueueBackendItem,+ QueueBackendPort,+ QueueEnqueueGenerateRequest,+ QueueEnqueueResult,+ QueueEnqueueWorkflowRequest,+ QueueResultImage,+ QueueResultImageOptions,+ TerminalQueueItemStatus,+} from '@features/queue/core/types';+import type { BackendConnectionStatus } from '@platform/transport/types';++import { modelLoadActivitySink } from '@features/models';import {isTerminalBackendStatus,parseQueueItemOrigin,@@ -28,29 +19,43 @@ import {type InvocationProgressEvent,type InvocationStartedEvent,type QueueItemStatusChangedEvent,- type TerminalBackendQueueItemStatus,-} from './events';-import { ApiError } from './http';-import { modelLoadStore } from './modelLoadStore';-import { nodeExecutionStore, type NodeExecutionSink } from './nodeExecutionStore';-import { progressImageStore, type ProgressImageSink, type ProgressImageTarget } from './progressImageStore';-import { queueItemProgressStore, type QueueItemProgressSink } from './progressStore';-import { revealHoldStore, type RevealHoldSink } from './revealHoldStore';+} from '@features/queue/data/events';+import {+ progressImageStore,+ type ProgressImageSink,+ type ProgressImageTarget,+} from '@features/queue/data/progressImageStore';+import { queueItemProgressStore, type QueueItemProgressSink } from '@features/queue/data/progressStore';+import { revealHoldStore, type RevealHoldSink } from '@features/queue/data/revealHoldStore';+import { ApiError } from '@platform/transport/http';const GALLERY_REFRESH_COALESCE_MS = 400;const SAFETY_SWEEP_INTERVAL_MS = 30_000;const TERMINAL_EVENT_BUFFER_LIMIT = 256;-export interface QueueCoordinatorApi {- cancelQueueItems: typeof cancelQueueItems;- cancelQueueItemsByBatchIds: typeof cancelQueueItemsByBatchIds;- enqueueGenerateGraph: typeof enqueueGenerateGraph;- enqueueWorkflowGraph: typeof enqueueWorkflowGraph;- getQueueItem: typeof getQueueItem;- getQueueItemResultImages: typeof getQueueItemResultImages;- listAllQueueItems: typeof listAllQueueItems;+export interface QueueNodeExecutionPort {+ clearAll(): void;+ completed(event: InvocationCompleteEvent): void;+ failed(event: InvocationErrorEvent): void;+ progress(nodeId: string, percentage: number | null, message: string): void;+ settleRunning(): void;+ started(event: InvocationStartedEvent): void;}+export type QueueCoordinatorBackendPort = Pick<+ QueueBackendPort,+ | 'cancelQueueItems'+ | 'cancelQueueItemsByBatchIds'+ | 'emit'+ | 'enqueueGenerate'+ | 'enqueueWorkflow'+ | 'getItem'+ | 'getResultImages'+ | 'listItems'+ | 'on'+ | 'onConnectionChange'+>;+export interface QueueCoordinatorCallbacks {/** Fired when one backend item in a local batch completes, before the whole local batch necessarily settles. */onBackendItemComplete?(localQueueItemId: string, backendItemId: number): void | Promise<void>;@@ -102,9 +107,9 @@ export interface QueueCoordinator {*/reconcile(items: ReconcileInput[]): Promise<Map<string, ReconcileOutcome>>;/** Enqueue a generate batch and track its backend items for event-driven settlement. */- submitGenerate(localQueueItemId: string, request: EnqueueGenerateRequest): Promise<EnqueueGenerateResult>;+ submitGenerate(localQueueItemId: string, request: QueueEnqueueGenerateRequest): Promise<QueueEnqueueResult>;/** Enqueue a compiled workflow graph and track its backend items the same way. */- submitWorkflow(localQueueItemId: string, request: EnqueueWorkflowRequest): Promise<EnqueueGenerateResult>;+ submitWorkflow(localQueueItemId: string, request: QueueEnqueueWorkflowRequest): Promise<QueueEnqueueResult>;/*** Resolve once every backend item of the run reaches a terminal status —* driven by socket events, with a slow safety sweep as the only polling.@@ -114,8 +119,8 @@ export interface QueueCoordinator {waitForResults(localQueueItemId: string,queuedAt: string,- options?: QueueItemResultImageOptions- ): Promise<ImageDTO[]>;+ options?: QueueResultImageOptions+ ): Promise<QueueResultImage[]>;cancelRun(request: CancelRunRequest): Promise<void>;}@@ -139,18 +144,8 @@ interface WaitState {settle: (outcome: TerminalOutcome) => void;}-const defaultApi: QueueCoordinatorApi = {- cancelQueueItems,- cancelQueueItemsByBatchIds,- enqueueGenerateGraph,- enqueueWorkflowGraph,- getQueueItem,- getQueueItemResultImages,- listAllQueueItems,-};-const toTerminalOutcome = (- status: TerminalBackendQueueItemStatus,+ status: TerminalQueueItemStatus,error?: string | null,errorType?: string | null): TerminalOutcome => {@@ -168,20 +163,19 @@ const toTerminalOutcome = (export const createQueueCoordinator = (callbacks: QueueCoordinatorCallbacks,options: {- hub: Pick<SocketHub, 'on' | 'emit' | 'onConnectionChange'>;- api?: Partial<QueueCoordinatorApi>;+ /** One adapter owns Queue HTTP commands and realtime events. */+ backend: QueueCoordinatorBackendPort;galleryRefreshCoalesceMs?: number;- nodeExecution?: NodeExecutionSink;+ nodeExecution: QueueNodeExecutionPort;progress?: QueueItemProgressSink;progressImage?: ProgressImageSink;revealHold?: RevealHoldSink;sweepIntervalMs?: number;}): QueueCoordinator => {- const api: QueueCoordinatorApi = { ...defaultApi, ...options.api };- const hub = options.hub;+ const backend = options.backend;const progress = options.progress ?? queueItemProgressStore;- const nodeExecution = options.nodeExecution ?? nodeExecutionStore;+ const nodeExecution = options.nodeExecution;const progressImage = options.progressImage ?? progressImageStore;const revealHold = options.revealHold ?? revealHoldStore;const galleryRefreshCoalesceMs = options.galleryRefreshCoalesceMs ?? GALLERY_REFRESH_COALESCE_MS;@@ -321,9 +315,9 @@ export const createQueueCoordinator = (wait.settle(outcome);};- const settleFromQueueItem = (queueItem: QueueItemDTO): void => {+ const settleFromQueueItem = (queueItem: QueueBackendItem): void => {if (queueItem.status !== 'pending' && queueItem.status !== 'in_progress') {- settleWait(queueItem.item_id, toTerminalOutcome(queueItem.status, queueItem.error_message, queueItem.error_type));+ settleWait(queueItem.id, toTerminalOutcome(queueItem.status, queueItem.errorMessage, queueItem.errorType));}};@@ -372,7 +366,7 @@ export const createQueueCoordinator = (await Promise.all([...waits.keys()].map(async (backendItemId) => {try {- settleFromQueueItem(await api.getQueueItem(backendItemId));+ settleFromQueueItem(await backend.getItem(backendItemId));} catch (error) {if (error instanceof ApiError && error.status === 404) {settleWait(backendItemId, {@@ -435,14 +429,14 @@ export const createQueueCoordinator = (};/**- * React to the shared socket's connection lifecycle. The hub owns the socket,- * the connection store, and `modelLoadStore.reset()`; the coordinator only- * clears its generation-scoped stores and, on (re)connect, schedules a gallery- * refresh and sweeps for events missed while disconnected.+ * React to the shared socket's connection lifecycle. The Platform hub owns+ * transport mechanics only; this Queue coordinator clears its domain stores+ * and, on (re)connect, schedules a gallery refresh and missed-event sweep.*/const handleConnectionChange = (status: BackendConnectionStatus): void => {progress.clearAll?.();nodeExecution.clearAll();+ modelLoadActivitySink.reset();if (status === 'connected') {scheduleGalleryRefresh();@@ -459,40 +453,40 @@ export const createQueueCoordinator = (isAttached = true;detachers.push(- hub.on('queue_item_status_changed', handleStatusChanged),- hub.on('invocation_progress', handleProgress),- hub.on('invocation_started', (event: InvocationStartedEvent) => {+ backend.on('queue_item_status_changed', handleStatusChanged),+ backend.on('invocation_progress', handleProgress),+ backend.on('invocation_started', (event: InvocationStartedEvent) => {if (!isTrackedEvent(event)) {return;}nodeExecution.started(event);}),- hub.on('invocation_complete', (event: InvocationCompleteEvent) => {+ backend.on('invocation_complete', (event: InvocationCompleteEvent) => {if (!isTrackedEvent(event)) {return;}nodeExecution.completed(event);}),- hub.on('invocation_error', (event: InvocationErrorEvent) => {+ backend.on('invocation_error', (event: InvocationErrorEvent) => {if (!isTrackedEvent(event)) {return;}nodeExecution.failed(event);}),- hub.on('model_load_started', (payload: never) => {- modelLoadStore.started(payload);+ backend.on('model_load_started', (payload: never) => {+ modelLoadActivitySink.started(payload);}),- hub.on('model_load_complete', (payload: never) => {- modelLoadStore.completed(payload);+ backend.on('model_load_complete', (payload: never) => {+ modelLoadActivitySink.completed(payload);}));// Fires synchronously with the current status, so attaching after the hub// has already connected still triggers the initial clear + sweep.- detachers.push(hub.onConnectionChange(handleConnectionChange));+ detachers.push(backend.onConnectionChange(handleConnectionChange));sweepTimer = setInterval(() => {void sweep();@@ -518,6 +512,16 @@ export const createQueueCoordinator = (clearInterval(sweepTimer);sweepTimer = null;}++ // A disposed coordinator can never observe another event, so pending+ // waits settle as canceled (raw, no completion/cancel side effects) —+ // otherwise `waitForResults` awaiters hang forever. The backend run+ // itself continues; a later `reconcile` re-adopts it.+ for (const wait of waits.values()) {+ wait.settle({ status: 'canceled' });+ }++ waits.clear();};const reconcile = async (items: ReconcileInput[]): Promise<Map<string, ReconcileOutcome>> => {@@ -534,7 +538,7 @@ export const createQueueCoordinator = (.flatMap((item) => item.backendItemIds ?? []).map(async (itemId) => {try {- return await api.getQueueItem(itemId);+ return await backend.getItem(itemId);} catch (error) {if (error instanceof ApiError && error.status === 404) {return undefined;@@ -545,9 +549,9 @@ export const createQueueCoordinator = (}))).filter((item) => item !== undefined)- : await api.listAllQueueItems();- const backendItemsById = new Map(backendItems.map((item) => [item.item_id, item]));- const backendItemsByLocalId = new Map<string, QueueItemDTO[]>();+ : await backend.listItems();+ const backendItemsById = new Map(backendItems.map((item) => [item.id, item]));+ const backendItemsByLocalId = new Map<string, QueueBackendItem[]>();for (const backendItem of backendItems) {const localQueueItemId = parseQueueItemOrigin(backendItem.origin);@@ -574,8 +578,8 @@ export const createQueueCoordinator = (continue;}- const backendItemIds = foundBackendItems.map((backendItem) => backendItem.item_id);- const backendBatchId = item.backendBatchId ?? foundBackendItems[0]?.batch_id;+ const backendItemIds = foundBackendItems.map((backendItem) => backendItem.id);+ const backendBatchId = item.backendBatchId ?? foundBackendItems[0]?.batchId;beginRun(item.id, backendItemIds, backendBatchId);@@ -592,14 +596,14 @@ export const createQueueCoordinator = (return outcomes;};- const submitGenerate = async (+ /** Reject partial acceptance and start tracking the accepted backend items. */+ const adoptEnqueueResult = (localQueueItemId: string,- request: EnqueueGenerateRequest- ): Promise<EnqueueGenerateResult> => {- const result = await api.enqueueGenerateGraph(request);-+ result: QueueEnqueueResult,+ workKind: 'generation' | 'workflow'+ ): QueueEnqueueResult => {if (result.enqueued === 0) {- throw new Error('The backend queue did not accept this generation. The queue may be full.');+ throw new Error(`The backend queue did not accept this ${workKind}. The queue may be full.`);}if (result.requested !== result.enqueued) {@@ -611,30 +615,23 @@ export const createQueueCoordinator = (return result;};- const submitWorkflow = async (+ const submitGenerate = async (localQueueItemId: string,- request: EnqueueWorkflowRequest- ): Promise<EnqueueGenerateResult> => {- const result = await api.enqueueWorkflowGraph(request);+ request: QueueEnqueueGenerateRequest+ ): Promise<QueueEnqueueResult> =>+ adoptEnqueueResult(localQueueItemId, await backend.enqueueGenerate(request), 'generation');- if (result.enqueued === 0) {- throw new Error('The backend queue did not accept this workflow. The queue may be full.');- }-- if (result.requested !== result.enqueued) {- throw new Error(`The backend queue accepted ${result.enqueued} of ${result.requested} requested items.`);- }-- beginRun(localQueueItemId, result.itemIds, result.batchId);-- return result;- };+ const submitWorkflow = async (+ localQueueItemId: string,+ request: QueueEnqueueWorkflowRequest+ ): Promise<QueueEnqueueResult> =>+ adoptEnqueueResult(localQueueItemId, await backend.enqueueWorkflow(request), 'workflow');const waitForResults = async (localQueueItemId: string,queuedAt: string,- options?: QueueItemResultImageOptions- ): Promise<ImageDTO[]> => {+ options?: QueueResultImageOptions+ ): Promise<QueueResultImage[]> => {const run = runs.get(localQueueItemId);if (!run) {@@ -660,8 +657,8 @@ export const createQueueCoordinator = (const imagesPerItem = await Promise.all(completedBackendItemIds.map((backendItemId) =>options- ? api.getQueueItemResultImages(backendItemId, localQueueItemId, queuedAt, options)- : api.getQueueItemResultImages(backendItemId, localQueueItemId, queuedAt)+ ? backend.getResultImages(backendItemId, localQueueItemId, queuedAt, options)+ : backend.getResultImages(backendItemId, localQueueItemId, queuedAt)));@@ -676,12 +673,12 @@ export const createQueueCoordinator = (const cancelRun = async ({ backendBatchId, backendItemIds }: CancelRunRequest): Promise<void> => {try {if (backendItemIds?.length) {- await api.cancelQueueItems(backendItemIds);+ await backend.cancelQueueItems(backendItemIds);return;}if (backendBatchId) {- await api.cancelQueueItemsByBatchIds([backendBatchId]);+ await backend.cancelQueueItemsByBatchIds([backendBatchId]);}} catch (error) {if (error instanceof ApiError && error.status === 404) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/utilityQueue.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.test.tssimilarity index 99%rename from invokeai/frontend/webv2/src/workbench/canvas-operations/backend/utilityQueue.test.tsrename to invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.test.tsindex baaaaca799..617b88c091 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/utilityQueue.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.test.ts@@ -1,18 +1,18 @@-import type { InvocationCompleteEvent, QueueItemStatusChangedEvent } from '@workbench/backend/events';-import type { SocketHub } from '@workbench/backend/socketHub';+import type { InvocationCompleteEvent, QueueItemStatusChangedEvent } from '@features/queue/contracts';+import type { SocketHub } from '@platform/transport/socketHub';import {buildQueueItemOrigin,buildUtilityQueueItemOrigin,isUtilityQueueItemOrigin,parseQueueItemOrigin,-} from '@workbench/backend/events';-import { ApiError } from '@workbench/backend/http';+} from '@features/queue/contracts';+import { ApiError } from '@platform/transport/http';import { afterEach, describe, expect, it, vi } from 'vitest';-import type { UtilityEnqueue } from './utilityQueue';+import type { UtilityEnqueue } from './utilityGraph';-import { DEFAULT_UTILITY_QUEUE_TIMEOUT_MS, runUtilityGraph, UtilityQueueError } from './utilityQueue';+import { DEFAULT_UTILITY_QUEUE_TIMEOUT_MS, runUtilityGraph, UtilityQueueError } from './utilityGraph';/** A fake socket hub that records handlers per event and can emit to them, mirroring `hub.on`. */const createFakeHub = () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/utilityQueue.ts b/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/canvas-operations/backend/utilityQueue.tsrename to invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.tsindex 2619d94703..31ddb66630 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/utilityQueue.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.ts@@ -8,7 +8,7 @@* 1. Mints a fresh `webv2:util:<uuid>` origin (see `backend/events.ts`). That* origin is deliberately invisible to project routing — `parseQueueItemOrigin`* returns `null` for it, so `queueCoordinator.reconcile` /- * `isQueueServerItemInProject` never adopt it and `routeQueueItemResults`+ * `isQueueItemReadModelInProject` never adopt it and `routeQueueItemResults`* (only invoked for coordinator-tracked project runs, which a utility item is* never registered as) never sees it. This is the plan's Risk-4 guard.* 2. Attaches raw `socketHub.on` listeners (they survive socket recreation) for@@ -25,13 +25,14 @@* tests against fakes. Every side-effecting dependency is a parameter.*/-import type { InvocationCompleteEvent, QueueItemStatusChangedEvent } from '@workbench/backend/events';-import type { SocketHub } from '@workbench/backend/socketHub';-import type { BackendGraphContract } from '@workbench/types';+import type { QueueBackendGraph } from '@features/queue/core/types';+import type { InvocationCompleteEvent, QueueItemStatusChangedEvent } from '@features/queue/data/events';+import type { SocketHub } from '@platform/transport/socketHub';-import { buildUtilityQueueItemOrigin } from '@workbench/backend/events';-import { ApiError } from '@workbench/backend/http';-import { cancelQueueItems, enqueueUtilityGraph, getQueueItem } from '@workbench/generation/api';+import { buildUtilityQueueItemOrigin } from '@features/queue/data/events';+import { cancelQueueItems, getQueueItem } from '@features/queue/data/serverApi';+import { enqueueUtility } from '@features/queue/data/submissionApi';+import { ApiError } from '@platform/transport/http';/** The default time a utility graph may run before it is abandoned. */export const DEFAULT_UTILITY_QUEUE_TIMEOUT_MS = 120_000;@@ -52,7 +53,7 @@ export class UtilityQueueError extends Error {/** The enqueue seam: posts the graph under `origin`, resolving to its backend item ids. */export type UtilityEnqueue = (request: {- graph: BackendGraphContract;+ graph: QueueBackendGraph;origin: string;}) => Promise<{ itemIds: number[]; enqueued: number }>;@@ -116,7 +117,7 @@ const scheduleUtilityReconcileRetry: UtilityReconcileRetryScheduler = (callback,/** Dependencies for {@link runUtilityGraph} (all injectable for tests). */export interface RunUtilityGraphOptions {/** The graph to enqueue and await. */- graph: BackendGraphContract;+ graph: QueueBackendGraph;/*** The source node id whose `invocation_complete` output image is the result.* When omitted, the first image-bearing completion for our origin is used.@@ -216,7 +217,7 @@ export const reconcileUtilityCompletedOutput: UtilityCompletedOutputReconciler =*/export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<UtilityGraphResult> => {const { graph, hub, outputNodeId, signal } = options;- const enqueue = options.enqueue ?? enqueueUtilityGraph;+ const enqueue = options.enqueue ?? enqueueUtility;const cancel = options.cancel ?? cancelQueueItems;const timeoutMs = options.timeoutMs ?? DEFAULT_UTILITY_QUEUE_TIMEOUT_MS;const reconcileCompletedOutput = options.reconcileCompletedOutput ?? reconcileUtilityCompletedOutput;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/CancelQueueItemButton.tsx b/invokeai/frontend/webv2/src/features/queue/ui/CancelQueueItemButton.tsxsimilarity index 81%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/CancelQueueItemButton.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/CancelQueueItemButton.tsxindex 168cb15ee4..33d9e4ce69 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/CancelQueueItemButton.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/CancelQueueItemButton.tsx@@ -1,15 +1,16 @@import type { MouseEvent as ReactMouseEvent } from 'react';import { Icon } from '@chakra-ui/react';-import { getApiErrorMessage } from '@workbench/backend/http';-import { IconButton, Tooltip } from '@workbench/components/ui';-import { useNotify } from '@workbench/useNotify';+import { queueCommands } from '@features/queue/publicApi';+import { getApiErrorMessage } from '@platform/transport/http';+import { IconButton } from '@platform/ui/Button';+import { Tooltip } from '@platform/ui/Tooltip';import { XIcon } from 'lucide-react';import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';import { refreshQueue } from './queueDataStore';-import { cancelQueueItem } from './queueServerApi';+import { useQueueUi } from './QueueUiContext';/*** Cancel a single queue item by its backend id. Works for any in-flight item@@ -19,7 +20,7 @@ import { cancelQueueItem } from './queueServerApi';*/export const CancelQueueItemButton = ({ itemId }: { itemId: number }) => {const { t } = useTranslation();- const notify = useNotify();+ const { notify } = useQueueUi();const [busy, setBusy] = useState(false);const onCancel = useCallback(@@ -28,7 +29,7 @@ export const CancelQueueItemButton = ({ itemId }: { itemId: number }) => {setBusy(true);try {- await cancelQueueItem(itemId);+ await queueCommands.cancelItem(itemId);await refreshQueue();} catch (error) {notify.error(t('common.cancelFailed'), getApiErrorMessage(error, t('widgets.queue.couldNotCancelItem')));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/ModelCacheFooter.tsx b/invokeai/frontend/webv2/src/features/queue/ui/ModelCacheFooter.tsxsimilarity index 89%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/ModelCacheFooter.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/ModelCacheFooter.tsxindex 63754d8c45..2e91709de4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/ModelCacheFooter.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/ModelCacheFooter.tsx@@ -1,19 +1,20 @@import { Collapsible, HStack, Icon, Progress, Stack, Text } from '@chakra-ui/react';-import { getApiErrorMessage } from '@workbench/backend/http';-import { Button } from '@workbench/components/ui';-import { formatBytes } from '@workbench/models/taxonomy';-import { useNotify } from '@workbench/useNotify';+import { useMountEffect } from '@platform/react/useMountEffect';+import { getApiErrorMessage } from '@platform/transport/http';+import { Button } from '@platform/ui/Button';import { ChevronUpIcon, DatabaseIcon, Trash2Icon } from 'lucide-react';-import { useCallback, useEffect, useState } from 'react';+import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';import {clearModelCache,+ formatModelCacheBytes,getModelCacheClearToast,getModelCacheUsage,refreshModelCacheStats,useModelCacheStats,} from './modelCacheStore';+import { useQueueUi } from './QueueUiContext';const INDICATOR_OPEN = { transform: 'rotate(180deg)' } as const;const TRIGGER_HOVER = { color: 'fg' } as const;@@ -36,13 +37,13 @@ const CacheStat = ({ label, value }: { label: string; value: number }) => (export const ModelCacheFooter = () => {const { t } = useTranslation();const { stats } = useModelCacheStats();- const notify = useNotify();+ const { notify } = useQueueUi();const [expanded, setExpanded] = useState(false);const [busy, setBusy] = useState(false);- useEffect(() => {+ useMountEffect(() => {void refreshModelCacheStats();- }, []);+ });const { total, used } = getModelCacheUsage(stats);const ratio = total > 0 ? Math.min(1, used / total) : 0;@@ -93,8 +94,8 @@ export const ModelCacheFooter = () => {<Progress.Rootaria-label={t('widgets.queue.modelCache.usage')}aria-valuetext={t('widgets.queue.modelCache.usedOfTotal', {- total: formatBytes(total),- used: formatBytes(used),+ total: formatModelCacheBytes(total),+ used: formatModelCacheBytes(used),})}colorPalette="accent"max={1}@@ -129,7 +130,7 @@ export const ModelCacheFooter = () => {{t('widgets.queue.modelCache.label')}</Text><Text color="fg.subtle" fontSize="2xs" fontVariantNumeric="tabular-nums">- {formatBytes(used)} / {formatBytes(total)}+ {formatModelCacheBytes(used)} / {formatModelCacheBytes(total)}</Text><Collapsible.Indicator _open={INDICATOR_OPEN} transition="transform var(--wb-motion-duration-slow)"><Icon as={ChevronUpIcon} boxSize="4" color="fg.subtle" flexShrink={0} />diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/NowNextSection.tsx b/invokeai/frontend/webv2/src/features/queue/ui/NowNextSection.tsxsimilarity index 79%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/NowNextSection.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/NowNextSection.tsxindex 11f85dd2f4..61671dc4d7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/NowNextSection.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/NowNextSection.tsx@@ -1,14 +1,14 @@import { Stack } from '@chakra-ui/react';import { useTranslation } from 'react-i18next';+import { useCurrentBatchItems } from './queueDataStore';import { QueueItemRow } from './QueueItemRow';-import { useScopedCurrentBatchItems } from './queueScope';import { SectionHeader } from './SectionHeader';/** CURRENT BATCH — the running item plus every pending item in the same backend batch. */export const CurrentBatchSection = () => {const { t } = useTranslation();- const items = useScopedCurrentBatchItems();+ const items = useCurrentBatchItems();const count = items.length;if (count === 0) {@@ -20,7 +20,7 @@ export const CurrentBatchSection = () => {<SectionHeader count={count} title={t('widgets.queue.currentBatch')} /><Stack gap="1">{items.map((item) => (- <QueueItemRow key={item.item_id} item={item} />+ <QueueItemRow key={item.id} item={item} />))}</Stack></Stack>diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsxnew file mode 100644index 0000000000..4474b2e5f4--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsx@@ -0,0 +1,38 @@+import { itemProgressStore } from '@features/queue/data/itemProgressStore';+import { createProductionQueueRealtimeRuntime } from '@features/queue/publicApi';+import { queryClient } from '@platform/query/client';+import { useMountEffect } from '@platform/react/useMountEffect';+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';++import { refreshModelCacheStats } from './modelCacheStore';+import { clearQueueConfirmation, useQueueConfirmation } from './queueConfirmationStore';++export const attachQueueDataRuntime = (): (() => void) => {+ const runtime = createProductionQueueRealtimeRuntime({+ invalidate: () => queryClient.invalidateQueries({ queryKey: ['queue'] }),+ progress: itemProgressStore,+ refreshModelCache: refreshModelCacheStats,+ });++ runtime.start();++ return runtime.dispose;+};++/** React is only the idempotent lifecycle adapter for the non-React runtime. */+export const QueueDataRuntime = () => {+ const confirmation = useQueueConfirmation();++ useMountEffect(attachQueueDataRuntime);++ return confirmation ? (+ <ConfirmDialog+ body={confirmation.body}+ confirmLabel={confirmation.confirmLabel}+ isOpen={true}+ title={confirmation.title}+ onClose={clearQueueConfirmation}+ onConfirm={confirmation.onConfirm}+ />+ ) : null;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueFilterTabs.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueFilterTabs.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/QueueFilterTabs.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/QueueFilterTabs.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderActions.test.ts b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderActions.test.tsrename to invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderActions.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.tsxsimilarity index 71%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderActions.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.tsxindex 0332c4fbe6..40047b5c1f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.tsx@@ -1,23 +1,22 @@+import type { QueueItemReadModel } from '@features/queue/core/types';+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */import { Icon } from '@chakra-ui/react';-import { getApiErrorMessage } from '@workbench/backend/http';-import { Button } from '@workbench/components/ui';-import { useNotify } from '@workbench/useNotify';-import { useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { queueCommands } from '@features/queue/publicApi';+import { getApiErrorMessage } from '@platform/transport/http';+import { Button } from '@platform/ui/Button';import { XIcon } from 'lucide-react';import { useState } from 'react';import { useTranslation } from 'react-i18next';-import type { QueueServerItem } from './queueServerApi';-import { refreshQueue, useNowNextItems } from './queueDataStore';-import { cancelQueueItem } from './queueServerApi';+import { useQueueUi } from './QueueUiContext';export const getQueueHeaderCancelState = ({currentStatus,isConnected,}: {- currentStatus: QueueServerItem['status'] | null;+ currentStatus: QueueItemReadModel['status'] | null;isConnected: boolean;}): { disabled: boolean; itemLabel: string } => ({disabled: !isConnected || currentStatus !== 'in_progress',@@ -30,11 +29,10 @@ export const getQueueHeaderCancelState = ({*/export const QueueHeaderActions = () => {const { t } = useTranslation();- const isConnected = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status === 'connected');+ const { isConnected, notify } = useQueueUi();const { current } = useNowNextItems();- const notify = useNotify();const [busy, setBusy] = useState(false);- const currentItemId = current?.item_id ?? null;+ const currentItemId = current?.id ?? null;const { disabled, itemLabel } = getQueueHeaderCancelState({currentStatus: current?.status ?? null,isConnected,@@ -48,7 +46,7 @@ export const QueueHeaderActions = () => {setBusy(true);try {- await cancelQueueItem(currentItemId);+ await queueCommands.cancelItem(currentItemId);await refreshQueue();} catch (error) {notify.error(t('common.cancelFailed'), getApiErrorMessage(error, t('widgets.queue.couldNotCancelCurrentItem')));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderLabel.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderLabel.tsxsimilarity index 82%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderLabel.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderLabel.tsxindex 837a7837a5..3470d61749 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderLabel.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderLabel.tsx@@ -1,7 +1,7 @@import { Stack, Text } from '@chakra-ui/react';import { useTranslation } from 'react-i18next';-import { useScopedQueueCounts } from './queueScope';+import { useQueueCounts } from './queueDataStore';/*** The Queue widget's header title: "Queue" over a live "N generating · M waiting"@@ -11,8 +11,8 @@ import { useScopedQueueCounts } from './queueScope';*/export const QueueHeaderLabel = () => {const { t } = useTranslation();- const counts = useScopedQueueCounts();- const isGenerating = counts.in_progress > 0;+ const counts = useQueueCounts();+ const isGenerating = counts.inProgress > 0;return (<Stack gap="0.5" minW="0">@@ -21,7 +21,7 @@ export const QueueHeaderLabel = () => {</Text><Text color="fg.subtle" fontSize="2xs" fontVariantNumeric="tabular-nums" lineHeight="1.15" truncate mb="-1.5"><Text as="span" color={isGenerating ? 'accent.solid' : 'fg.subtle'} fontWeight={isGenerating ? '600' : '400'}>- {t('widgets.queue.generating', { count: counts.in_progress })}+ {t('widgets.queue.generating', { count: counts.inProgress })}</Text>{' '}· {t('widgets.queue.waiting', { count: counts.pending })}</Text>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderMenu.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderMenu.tsxsimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderMenu.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderMenu.tsxindex 8f24971970..e7ba45cf35 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderMenu.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderMenu.tsx@@ -1,6 +1,6 @@import { Icon, Menu } from '@chakra-ui/react';-import { getApiErrorMessage } from '@workbench/backend/http';-import { useNotify } from '@workbench/useNotify';+import { queueCommands } from '@features/queue/publicApi';+import { getApiErrorMessage } from '@platform/transport/http';import { Trash2Icon, TrashIcon } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -9,7 +9,7 @@ import { requestQueueConfirmation } from './queueConfirmationStore';import { refreshQueue, useQueueCounts } from './queueDataStore';import { QueueMenuItems, useQueueMenuActions } from './queueMenuActions';import { useQueueQueryScope } from './queueScope';-import { clearFailedQueueItems, clearScopedQueue } from './queueServerApi';+import { useQueueUi } from './QueueUiContext';const ERROR_ITEM_HOVER_PROPS = { bg: 'bg.error', color: 'fg.error' };@@ -23,11 +23,11 @@ export const QueueHeaderMenu = () => {const actions = useQueueMenuActions();const counts = useQueueCounts();const scope = useQueueQueryScope();- const notify = useNotify();+ const { notify } = useQueueUi();const clearFailed = useCallback(async () => {try {- await clearFailedQueueItems(scope);+ await queueCommands.clearFailedItems(scope);await refreshQueue();notify.success(t('widgets.queue.failedItemsCleared'));} catch (error) {@@ -40,7 +40,7 @@ export const QueueHeaderMenu = () => {const clearAll = useCallback(async () => {try {- await clearScopedQueue(scope);+ await queueCommands.clearItems(scope);await refreshQueue();notify.success(t('widgets.queue.queueCleared'));} catch (error) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemDetails.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueItemDetails.tsxsimilarity index 73%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemDetails.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/QueueItemDetails.tsxindex 9b9ecec9ae..18d810c129 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemDetails.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueItemDetails.tsx@@ -1,14 +1,12 @@+import type { QueueItemReadModel } from '@features/queue/core/types';import type { ReactNode } from 'react';import { DataList, Separator, Text } from '@chakra-ui/react';+import { extractGenerationMeta } from '@features/queue/core/generationMeta';import { useTranslation } from 'react-i18next';-import type { QueueServerItem } from './queueServerApi';--import { extractGenerationMeta } from './fieldValues';import { formatDuration } from './formatDuration';-import { QueueItemActions } from './QueueItemActions';-import { useLocalGenerateValues } from './useLocalGenerateValues';+import { useQueueUi } from './QueueUiContext';const DetailRow = ({ label, children }: { label: string; children: ReactNode }) => (<DataList.Item key={label} alignItems="start">@@ -22,11 +20,11 @@ const DetailRow = ({ label, children }: { label: string; children: ReactNode }));/** Expanded detail grid + actions for a RECENT queue item row. */-export const QueueItemDetails = ({ item }: { item: QueueServerItem }) => {+export const QueueItemDetails = ({ item }: { item: QueueItemReadModel }) => {const { t } = useTranslation();+ const { ItemActions } = useQueueUi();const meta = extractGenerationMeta(item);- const localGenerateValues = useLocalGenerateValues(item.origin);- const duration = formatDuration(item.started_at, item.completed_at);+ const duration = formatDuration(item.startedAt, item.completedAt);return (<DataList.Root gap="1.5" orientation="horizontal" size="sm">@@ -37,28 +35,28 @@ export const QueueItemDetails = ({ item }: { item: QueueServerItem }) => {{meta.seed ?? '—'}</Text></DetailRow>- <DetailRow label={t('common.created')}>{new Date(item.created_at).toLocaleString()}</DetailRow>+ <DetailRow label={t('common.created')}>{new Date(item.createdAt).toLocaleString()}</DetailRow><DetailRow label={t('widgets.queue.took')}>{duration ?? '—'}</DetailRow><DetailRow label={t('widgets.queue.batch')}><Text as="span" truncate>- {item.batch_id}+ {item.batchId}</Text></DetailRow><DetailRow label={t('common.item')}><Text as="span" fontVariantNumeric="tabular-nums">- #{item.item_id}+ #{item.id}</Text></DetailRow>- {item.error_message ? (+ {item.errorMessage ? (<DetailRow label={t('common.error')}><Text as="span" color="fg.error">- {item.error_message}+ {item.errorMessage}</Text></DetailRow>) : null}<Separator borderColor="border.subtle" my="0.5" />- <QueueItemActions item={item} localGenerateValues={localGenerateValues} />+ <ItemActions item={item} /></DataList.Root>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemRow.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueItemRow.tsxsimilarity index 84%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemRow.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/QueueItemRow.tsxindex 9d5969f916..e35617369f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemRow.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueItemRow.tsx@@ -1,16 +1,15 @@import type { SystemStyleObject } from '@chakra-ui/react';+import type { QueueItemReadModel } from '@features/queue/core/types';import { Box, HStack, Icon, Stack, Text } from '@chakra-ui/react';-import { useItemProgress } from '@workbench/backend/itemProgressStore';-import { Row } from '@workbench/components/ui';+import { extractGenerationMeta, getResultImageName } from '@features/queue/core/generationMeta';+import { useItemProgress } from '@features/queue/data/itemProgressStore';+import { Row } from '@platform/ui/Row';import { ChevronRightIcon } from 'lucide-react';import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';-import type { QueueServerItem } from './queueServerApi';-import { CancelQueueItemButton } from './CancelQueueItemButton';-import { extractGenerationMeta, getResultImageName } from './fieldValues';import { formatCompactAge, formatDuration } from './formatDuration';import { QueueItemDetails } from './QueueItemDetails';import { QueueItemThumbnail } from './QueueItemThumbnail';@@ -34,17 +33,17 @@ const QUEUE_ITEM_BUTTON_SX: SystemStyleObject = {transitionDuration: 'fastest',} as const;-export const QueueItemRow = memo(({ item }: { item: QueueServerItem }) => {+export const QueueItemRow = memo(({ item }: { item: QueueItemReadModel }) => {const { t } = useTranslation();const [expanded, setExpanded] = useState(false);const toggle = useCallback(() => setExpanded((open) => !open), []);const meta = extractGenerationMeta(item);- const duration = formatDuration(item.started_at, item.completed_at);- const age = formatCompactAge(item.completed_at ?? item.created_at);+ const duration = formatDuration(item.startedAt, item.completedAt);+ const age = formatCompactAge(item.completedAt ?? item.createdAt);const ageLabel = [duration, age].filter(Boolean).join(' · ');const isFailed = item.status === 'failed';const isCancellable = item.status === 'pending' || item.status === 'in_progress';- const progress = useItemProgress(item.item_id);+ const progress = useItemProgress(item.id);const liveImage = progress?.image ?? null;const resultImageName = getResultImageName(item);const statusLabel = t(getStatusMeta(item.status).labelKey);@@ -79,7 +78,7 @@ export const QueueItemRow = memo(({ item }: { item: QueueServerItem }) => {</Row>{isCancellable ? (<Box flexShrink={0} pe="1">- <CancelQueueItemButton itemId={item.item_id} />+ <CancelQueueItemButton itemId={item.id} /></Box>) : null}</HStack>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemThumbnail.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueItemThumbnail.tsxsimilarity index 84%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemThumbnail.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/QueueItemThumbnail.tsxindex de350aad0d..d11a5977d4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemThumbnail.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueItemThumbnail.tsx@@ -1,7 +1,10 @@import { Icon, type SystemStyleObject } from '@chakra-ui/react';-import { absolutizeApiUrl } from '@workbench/backend/http';-import { StreamingImageFrame } from '@workbench/images/StreamingImageFrame';-import { imageUrlToStreamingSource, progressImageToStreamingSource } from '@workbench/images/streamingImageSource';+import { absolutizeApiUrl } from '@platform/transport/http';+import { StreamingImageFrame } from '@platform/ui/streaming-image/StreamingImageFrame';+import {+ imageUrlToStreamingSource,+ progressImageToStreamingSource,+} from '@platform/ui/streaming-image/streamingImageSource';import { ImageOffIcon } from 'lucide-react';/**diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStats.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueStats.tsxsimilarity index 92%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStats.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/QueueStats.tsxindex e0575e419a..c67d7c3236 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStats.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueStats.tsx@@ -1,7 +1,7 @@import { SimpleGrid, Stat } from '@chakra-ui/react';import { useTranslation } from 'react-i18next';-import { useScopedQueueCounts } from './queueScope';+import { useQueueCounts } from './queueDataStore';/*** The four headline counts (done / failed / canceled / total) as a row of cards.@@ -17,7 +17,7 @@ const QueueStatCard = ({ value, label, danger }: { value: number; label: string;export const QueueStats = () => {const { t } = useTranslation();- const counts = useScopedQueueCounts();+ const counts = useQueueCounts();return (<SimpleGrid columns={4}>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStatusDot.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueStatusDot.tsxsimilarity index 84%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStatusDot.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/QueueStatusDot.tsxindex 0d6a62d37d..bd5c60c9a0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStatusDot.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueStatusDot.tsx@@ -1,4 +1,4 @@-import type { BackendQueueItemStatus } from '@workbench/backend/events';+import type { QueueItemStatus } from '@features/queue/core/types';import { Box } from '@chakra-ui/react';import { useTranslation } from 'react-i18next';@@ -8,7 +8,7 @@ import { getStatusMeta } from './statusMeta';const ACTIVE_HALO = { boxShadow: '0 0 0 3px {colors.accent.subtle}' } as const;/** Small status indicator dot; the running state gets a soft accent halo. */-export const QueueStatusDot = ({ status, boxSize = '2' }: { status: BackendQueueItemStatus; boxSize?: string }) => {+export const QueueStatusDot = ({ status, boxSize = '2' }: { status: QueueItemStatus; boxSize?: string }) => {const { t } = useTranslation();const { dotColor, labelKey } = getStatusMeta(status);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStepProgress.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueStepProgress.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStepProgress.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/QueueStepProgress.tsxdiff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsxnew file mode 100644index 0000000000..570e9104a8--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx@@ -0,0 +1,35 @@+import type { QueueItemReadModel } from '@features/queue/core/types';++import { createContext, useContext, type ComponentType, type ReactNode } from 'react';++export interface QueueUiNotificationPort {+ error(title: string, description?: string): void;+ info(title: string, description?: string): void;+ success(title: string, description?: string): void;+}++export interface QueueUiAdapter {+ ItemActions: ComponentType<{ item: QueueItemReadModel }>;+ activeProjectId: string | null;+ canManageProcessor: boolean;+ isConnected: boolean;+ notify: QueueUiNotificationPort;+ openQueue(): void;+ queueJobsScope: 'active-project' | 'all';+}++const QueueUiContext = createContext<QueueUiAdapter | null>(null);++export const QueueUiProvider = ({ adapter, children }: { adapter: QueueUiAdapter; children: ReactNode }) => (+ <QueueUiContext.Provider value={adapter}>{children}</QueueUiContext.Provider>+);++export const useQueueUi = (): QueueUiAdapter => {+ const adapter = useContext(QueueUiContext);++ if (!adapter) {+ throw new Error('Queue UI requires an App-composed QueueUiProvider.');+ }++ return adapter;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsxsimilarity index 74%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsxindex e85a7a9552..2b48247b36 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx@@ -1,7 +1,5 @@-import type { WidgetViewProps } from '@workbench/types';-import { Stack } from '@chakra-ui/react';-import { StatusWidgetChip } from '@workbench/widget-frame';+import { StatusWidgetChip } from '@platform/ui/StatusWidgetChip';import { ListOrderedIcon } from 'lucide-react';import { useState } from 'react';import { useTranslation } from 'react-i18next';@@ -9,8 +7,8 @@ import { useTranslation } from 'react-i18next';import type { QueueFilterId } from './queueFilters';import { CurrentBatchSection } from './NowNextSection';+import { useQueueCounts } from './queueDataStore';import { QueueFilterTabs } from './QueueFilterTabs';-import { useScopedQueueCounts } from './queueScope';import { QueueStats } from './QueueStats';import { RecentSection } from './RecentSection';@@ -20,17 +18,23 @@ import { RecentSection } from './RecentSection';* provided through the manifest's chrome slots; this view is just the scrolling* body. In a collapsed bottom dock it degrades to a single status chip.*/-export const QueueWidgetView = ({ presentation, region }: WidgetViewProps) => {+export const QueueWidgetView = ({+ presentation,+ region,+}: {+ presentation?: 'compact' | 'expanded' | 'tooltip';+ region: 'bottom' | 'center' | 'dialog' | 'left' | 'popover' | 'right';+}) => {const { t } = useTranslation();- const counts = useScopedQueueCounts();+ const counts = useQueueCounts();if (region === 'bottom' && presentation !== 'expanded') {- const isGenerating = counts.in_progress > 0;+ const isGenerating = counts.inProgress > 0;return (<StatusWidgetChip icon={ListOrderedIcon} tone={isGenerating ? 'accent' : undefined}>{isGenerating- ? t('widgets.queue.generating', { count: counts.in_progress })+ ? t('widgets.queue.generating', { count: counts.inProgress }): t('widgets.queue.queued', { count: counts.pending })}</StatusWidgetChip>);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/RecentSection.tsx b/invokeai/frontend/webv2/src/features/queue/ui/RecentSection.tsxsimilarity index 75%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/RecentSection.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/RecentSection.tsxindex 677f1ec9b2..c70120e0c4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/RecentSection.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/RecentSection.tsx@@ -4,10 +4,9 @@ import { useTranslation } from 'react-i18next';import type { QueueFilterId } from './queueFilters';-import { useQueueLoadState } from './queueDataStore';+import { useCurrentBatchItems, useQueueLoadState, useRecentItems } from './queueDataStore';import { matchesFilter } from './queueFilters';import { QueueItemRow } from './QueueItemRow';-import { useScopedCurrentBatchItems, useScopedRecentItems } from './queueScope';import { SectionHeader } from './SectionHeader';/**@@ -16,13 +15,13 @@ import { SectionHeader } from './SectionHeader';*/export const RecentSection = ({ filter }: { filter: QueueFilterId }) => {const { t } = useTranslation();- const currentBatchItems = useScopedCurrentBatchItems();- const items = useScopedRecentItems();+ const currentBatchItems = useCurrentBatchItems();+ const items = useRecentItems();const { error, loadState } = useQueueLoadState();- const excluded = useMemo(() => new Set(currentBatchItems.map((item) => item.item_id)), [currentBatchItems]);+ const excluded = useMemo(() => new Set(currentBatchItems.map((item) => item.id)), [currentBatchItems]);const filtered = useMemo(- () => items.filter((item) => !excluded.has(item.item_id) && matchesFilter(item.status, filter)),+ () => items.filter((item) => !excluded.has(item.id) && matchesFilter(item.status, filter)),[excluded, filter, items]);@@ -40,7 +39,7 @@ export const RecentSection = ({ filter }: { filter: QueueFilterId }) => {) : (<Stack gap="1">{filtered.map((item) => (- <QueueItemRow key={item.item_id} item={item} />+ <QueueItemRow key={item.id} item={item} />))}</Stack>)}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/SectionHeader.tsx b/invokeai/frontend/webv2/src/features/queue/ui/SectionHeader.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/SectionHeader.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/SectionHeader.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/currentBatchItems.test.ts b/invokeai/frontend/webv2/src/features/queue/ui/currentBatchItems.test.tssimilarity index 68%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/currentBatchItems.test.tsrename to invokeai/frontend/webv2/src/features/queue/ui/currentBatchItems.test.tsindex efb918a64d..86edf7d801 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/currentBatchItems.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/currentBatchItems.test.ts@@ -1,16 +1,17 @@-import { describe, expect, it } from 'vitest';+import type { QueueItemReadModel } from '@features/queue';-import type { QueueServerItem } from './queueServerApi';+import { describe, expect, it } from 'vitest';import { getCurrentBatchItems } from './currentBatchItems';-const createItem = (item_id: number, batch_id: string, status: QueueServerItem['status']): QueueServerItem => ({- batch_id,- created_at: '2026-06-26T00:00:00Z',- item_id,- session_id: `session-${item_id}`,+const createItem = (id: number, batchId: string, status: QueueItemReadModel['status']): QueueItemReadModel => ({+ batchId,+ createdAt: '2026-06-26T00:00:00Z',+ id,+ resultImageNames: [],+ sessionId: `session-${id}`,status,- updated_at: '2026-06-26T00:00:00Z',+ updatedAt: '2026-06-26T00:00:00Z',});describe('getCurrentBatchItems', () => {@@ -24,7 +25,7 @@ describe('getCurrentBatchItems', () => {];expect(- getCurrentBatchItems({ current, items, next: createItem(3, 'batch-a', 'pending') }).map((item) => item.item_id)+ getCurrentBatchItems({ current, items, next: createItem(3, 'batch-a', 'pending') }).map((item) => item.id)).toEqual([2, 3]);});@@ -32,6 +33,6 @@ describe('getCurrentBatchItems', () => {const next = createItem(5, 'batch-c', 'pending');const items = [createItem(6, 'batch-c', 'pending'), next, createItem(4, 'batch-b', 'pending')];- expect(getCurrentBatchItems({ current: null, items, next }).map((item) => item.item_id)).toEqual([5, 6]);+ expect(getCurrentBatchItems({ current: null, items, next }).map((item) => item.id)).toEqual([5, 6]);});});diff --git a/invokeai/frontend/webv2/src/features/queue/ui/currentBatchItems.ts b/invokeai/frontend/webv2/src/features/queue/ui/currentBatchItems.tsnew file mode 100644index 0000000000..f951cc03ca--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/ui/currentBatchItems.ts@@ -0,0 +1,40 @@+import type { QueueItemReadModel } from '@features/queue/core/types';++const isCurrentBatchStatus = (status: QueueItemReadModel['status']): boolean =>+ status === 'pending' || status === 'in_progress';++export const getCurrentBatchItems = ({+ current,+ items,+ next,+}: {+ current: QueueItemReadModel | null;+ items: QueueItemReadModel[];+ next: QueueItemReadModel | null;+}): QueueItemReadModel[] => {+ const batchId = current?.batchId ?? next?.batchId ?? null;++ if (!batchId) {+ return [];+ }++ const itemsById = new Map<number, QueueItemReadModel>();++ for (const item of [current, next, ...items]) {+ if (item && item.batchId === batchId && isCurrentBatchStatus(item.status)) {+ itemsById.set(item.id, item);+ }+ }++ return [...itemsById.values()].sort((left, right) => {+ if (left.status === 'in_progress' && right.status !== 'in_progress') {+ return -1;+ }++ if (left.status !== 'in_progress' && right.status === 'in_progress') {+ return 1;+ }++ return left.id - right.id;+ });+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/formatDuration.ts b/invokeai/frontend/webv2/src/features/queue/ui/formatDuration.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/formatDuration.tsrename to invokeai/frontend/webv2/src/features/queue/ui/formatDuration.tsdiff --git a/invokeai/frontend/webv2/src/features/queue/ui/index.ts b/invokeai/frontend/webv2/src/features/queue/ui/index.tsnew file mode 100644index 0000000000..9ad996c606--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/ui/index.ts@@ -0,0 +1,6 @@+export { ModelCacheFooter } from './ModelCacheFooter';+export { QueueDataRuntime } from './QueueDataRuntime';+export { QueueHeaderActions } from './QueueHeaderActions';+export { QueueHeaderLabel } from './QueueHeaderLabel';+export { QueueHeaderMenu } from './QueueHeaderMenu';+export { QueueWidgetView } from './QueueWidgetView';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/modelCacheStore.test.ts b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/modelCacheStore.test.tsrename to invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/modelCacheStore.ts b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.tssimilarity index 82%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/modelCacheStore.tsrename to invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.tsindex c18d368a09..d852eab738 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/modelCacheStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts@@ -1,8 +1,25 @@import type { TFunction } from 'i18next';-import { apiFetchJson, getApiErrorMessage } from '@workbench/backend/http';-import { createExternalStore } from '@workbench/externalStore';-import { formatBytes } from '@workbench/models/taxonomy';+import { createExternalStore } from '@platform/state/externalStore';+import { apiFetchJson, getApiErrorMessage } from '@platform/transport/http';++const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'] as const;++export const formatModelCacheBytes = (bytes: number | null | undefined): string => {+ if (bytes === null || bytes === undefined || !Number.isFinite(bytes) || bytes < 0) {+ return '—';+ }++ let value = bytes;+ let unitIndex = 0;++ while (value >= 1024 && unitIndex < BYTE_UNITS.length - 1) {+ value /= 1024;+ unitIndex += 1;+ }++ return `${unitIndex === 0 ? value : value.toFixed(1)} ${BYTE_UNITS[unitIndex]}`;+};/*** RAM/VRAM model-cache statistics for the Queue widget's footer. Pull-based:@@ -54,7 +71,7 @@ export const getModelCacheClearToast = (return {description: t('widgets.queue.modelCache.clearedDescription', {- bytes: formatBytes(bytes_freed),+ bytes: formatModelCacheBytes(bytes_freed),count: models_cleared,}),status: 'success',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueConfirmationStore.test.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueConfirmationStore.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/queueConfirmationStore.test.tsrename to invokeai/frontend/webv2/src/features/queue/ui/queueConfirmationStore.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueConfirmationStore.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueConfirmationStore.tssimilarity index 92%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/queueConfirmationStore.tsrename to invokeai/frontend/webv2/src/features/queue/ui/queueConfirmationStore.tsindex e83a53bdd7..5ca7fed451 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueConfirmationStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueConfirmationStore.ts@@ -1,6 +1,6 @@import type { ReactNode } from 'react';-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';export interface QueueConfirmation {body: ReactNode;diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueDataStore.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueDataStore.tsnew file mode 100644index 0000000000..a38a6a5d13--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueDataStore.ts@@ -0,0 +1,79 @@+import type { QueueCounts, QueueItemReadModel, QueueQueryScope } from '@features/queue/core/types';++import { getQueueReadModelOptions } from '@features/queue/publicApi';+import { queryClient } from '@platform/query/client';+import { useQuery } from '@tanstack/react-query';++import { getCurrentBatchItems } from './currentBatchItems';+import { clearProgressForQueueItemsWithResults } from './queueProgressCleanup';+import { useQueueQueryScope } from './queueScope';++const EMPTY_COUNTS: QueueCounts = {+ canceled: 0,+ completed: 0,+ failed: 0,+ inProgress: 0,+ pending: 0,+ queueId: 'default',+ total: 0,+};++const onQueueRead = ({+ current,+ items,+ next,+}: {+ current: QueueItemReadModel | null;+ items: QueueItemReadModel[];+ next: QueueItemReadModel | null;+}): void => {+ clearProgressForQueueItemsWithResults([current, next, ...items].filter((item) => item !== null));+};++const useQueueReadModel = () => {+ const scope = useQueueQueryScope();++ return useQuery(getQueueReadModelOptions(scope, onQueueRead));+};++/** Invalidate queue data; TanStack Query deduplicates concurrent callers. */+export const refreshQueue = async (): Promise<void> => {+ await queryClient.invalidateQueries({ queryKey: ['queue'] });+};++/** Imperative prefetch for non-React composition roots. */+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. */+export const useIsProcessorPaused = (): boolean => useQueueReadModel().data?.status.processor.isStarted === false;++export const useNowNextItems = (): { current: QueueItemReadModel | null; next: QueueItemReadModel | null } => {+ const data = useQueueReadModel().data;++ return { current: data?.current ?? null, next: data?.next ?? null };+};++export const useCurrentBatchItems = (): QueueItemReadModel[] => {+ const data = useQueueReadModel().data;++ return data ? getCurrentBatchItems(data) : [];+};++export const useRecentItems = (): QueueItemReadModel[] => useQueueReadModel().data?.items ?? [];++export const useQueueLoadState = (): { loadState: 'loading' | 'loaded' | 'error'; error: string | null } => {+ const query = useQueueReadModel();++ if (query.isError) {+ return { error: query.error instanceof Error ? query.error.message : 'Failed to load queue', loadState: 'error' };+ }++ return { error: null, loadState: query.isPending ? 'loading' : 'loaded' };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueFilters.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueFilters.tssimilarity index 72%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/queueFilters.tsrename to invokeai/frontend/webv2/src/features/queue/ui/queueFilters.tsindex f57e3ef22b..560984e96b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueFilters.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueFilters.ts@@ -1,6 +1,4 @@-import type { BackendQueueItemStatus } from '@workbench/backend/events';--import type { QueueStatusCounts } from './queueServerApi';+import type { QueueCounts, QueueItemStatus } from '@features/queue/core/types';/** Status filters for the RECENT list, matching the screenshot's tab row. */export type QueueFilterId = 'all' | 'active' | 'completed' | 'failed' | 'canceled';@@ -13,7 +11,7 @@ export const QUEUE_FILTERS: { id: QueueFilterId; labelKey: string }[] = [{ id: 'canceled', labelKey: 'common.canceled' },];-export const matchesFilter = (status: BackendQueueItemStatus, filter: QueueFilterId): boolean => {+export const matchesFilter = (status: QueueItemStatus, filter: QueueFilterId): boolean => {if (filter === 'all') {return true;}@@ -26,12 +24,12 @@ export const matchesFilter = (status: BackendQueueItemStatus, filter: QueueFilte};/** Count for a filter, derived from the server-wide status counts (not the windowed list). */-export const getFilterCount = (counts: QueueStatusCounts, filter: QueueFilterId): number => {+export const getFilterCount = (counts: QueueCounts, filter: QueueFilterId): number => {switch (filter) {case 'all':return counts.total;case 'active':- return counts.pending + counts.in_progress;+ return counts.pending + counts.inProgress;case 'completed':return counts.completed;case 'failed':diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueMenuActions.test.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/queueMenuActions.test.tsrename to invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueMenuActions.tsx b/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.tsxsimilarity index 84%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/queueMenuActions.tsxrename to invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.tsxindex 3e88700477..6fdf20858b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueMenuActions.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.tsx@@ -1,9 +1,6 @@import { Icon, Menu } from '@chakra-ui/react';-import { useCapabilities } from '@workbench/auth/capabilities';-import { getApiErrorMessage } from '@workbench/backend/http';-import { useNotify } from '@workbench/useNotify';-import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';-import { useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { queueCommands } from '@features/queue/publicApi';+import { getApiErrorMessage } from '@platform/transport/http';import { ListOrderedIcon, PauseIcon, PlayIcon, XIcon, type LucideIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -11,7 +8,7 @@ import { useTranslation } from 'react-i18next';import { requestQueueConfirmation } from './queueConfirmationStore';import { refreshQueue, useNowNextItems, useQueueCounts } from './queueDataStore';import { useQueueQueryScope } from './queueScope';-import { cancelQueueItem, cancelScopedQueueItems, pauseQueueProcessor, resumeQueueProcessor } from './queueServerApi';+import { useQueueUi } from './QueueUiContext';const ERROR_ITEM_HOVER_PROPS = { bg: 'bg.error', color: 'fg.error' };@@ -102,15 +99,11 @@ export const getQueueMenuActions = ({export const useQueueMenuActions = (): QueueMenuAction[] => {const { t } = useTranslation();- const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);const counts = useQueueCounts();const { current } = useNowNextItems();const scope = useQueueQueryScope();- const { canManageModels } = useCapabilities();- const notify = useNotify();- const openWorkbenchWidget = useOpenWorkbenchWidget();- const isConnected = backendConnectionStatus === 'connected';- const cancellableCount = counts.pending + counts.in_progress;+ const { canManageProcessor, isConnected, notify, openQueue } = useQueueUi();+ const cancellableCount = counts.pending + counts.inProgress;const hasRunningItem = current?.status === 'in_progress';const hasPendingQueueWork = counts.pending > 0;@@ -120,13 +113,11 @@ export const useQueueMenuActions = (): QueueMenuAction[] => {return;}- cancelQueueItem(current.item_id)+ queueCommands+ .cancelItem(current.id).then(() => refreshQueue()).then(() =>- notify.success(- t('widgets.queue.cancellationRequested'),- t('widgets.queue.backendItem', { id: current.item_id })- )+ notify.success(t('widgets.queue.cancellationRequested'), t('widgets.queue.backendItem', { id: current.id }))).catch((error: unknown) =>notify.error(@@ -137,7 +128,8 @@ export const useQueueMenuActions = (): QueueMenuAction[] => {}, [current, notify, t]);const cancelAllExceptCurrent = useCallback(() => {- cancelScopedQueueItems(scope, current?.item_id ?? null)+ queueCommands+ .cancelScopedItems(scope, current?.id ?? null).then(() => refreshQueue()).then(() =>notify.success(@@ -151,11 +143,11 @@ export const useQueueMenuActions = (): QueueMenuAction[] => {getApiErrorMessage(error, t('widgets.queue.couldNotCancelItems'))));- }, [current?.item_id, notify, scope, t]);+ }, [current?.id, notify, scope, t]);const runProcessorAction = useCallback((label: 'pause' | 'resume') => {- const action = label === 'pause' ? pauseQueueProcessor : resumeQueueProcessor;+ const action = label === 'pause' ? queueCommands.pauseProcessor : queueCommands.resumeProcessor;action().then(() =>@@ -172,7 +164,8 @@ export const useQueueMenuActions = (): QueueMenuAction[] => {[notify, t]);const cancelAll = useCallback(() => {- cancelScopedQueueItems(scope)+ queueCommands+ .cancelScopedItems(scope).then(() => refreshQueue()).then(() =>notify.success(t('widgets.queue.queueCancellationRequested'), t('widgets.queue.allScopedItemsRequested'))@@ -186,7 +179,6 @@ export const useQueueMenuActions = (): QueueMenuAction[] => {}, [notify, scope, t]);const resumeProcessor = useCallback(() => runProcessorAction('resume'), [runProcessorAction]);const pauseProcessor = useCallback(() => runProcessorAction('pause'), [runProcessorAction]);- const openQueue = useCallback(() => openWorkbenchWidget('queue'), [openWorkbenchWidget]);return useMemo(() =>@@ -200,7 +192,7 @@ export const useQueueMenuActions = (): QueueMenuAction[] => {resumeProcessor: t('widgets.queue.resumeProcessor'),},cancellableCount,- canManageProcessor: canManageModels,+ canManageProcessor,hasPendingQueueWork,hasRunningItem,isConnected,@@ -216,7 +208,7 @@ export const useQueueMenuActions = (): QueueMenuAction[] => {cancelAllExceptCurrent,cancelCurrent,cancellableCount,- canManageModels,+ canManageProcessor,hasPendingQueueWork,hasRunningItem,isConnected,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueProgressCleanup.test.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueProgressCleanup.test.tssimilarity index 66%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/queueProgressCleanup.test.tsrename to invokeai/frontend/webv2/src/features/queue/ui/queueProgressCleanup.test.tsindex 03d7eec07a..8d28845bf9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueProgressCleanup.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueProgressCleanup.test.ts@@ -1,17 +1,17 @@-import { describe, expect, it } from 'vitest';+import type { QueueItemReadModel } from '@features/queue';-import type { QueueServerItem } from './queueServerApi';+import { describe, expect, it } from 'vitest';import { getQueueItemIdsWithResultImages } from './queueProgressCleanup';-const createItem = (itemId: number, results: Record<string, unknown> = {}): QueueServerItem => ({- batch_id: 'batch-1',- created_at: '2026-06-27T00:00:00Z',- item_id: itemId,- session: { results },- session_id: 'session-1',+const createItem = (itemId: number, results: Record<string, unknown> = {}): QueueItemReadModel => ({+ batchId: 'batch-1',+ createdAt: '2026-06-27T00:00:00Z',+ id: itemId,+ resultImageNames: Object.keys(results).length > 0 ? ['result.png'] : [],+ sessionId: 'session-1',status: 'completed',- updated_at: '2026-06-27T00:00:00Z',+ updatedAt: '2026-06-27T00:00:00Z',});describe('getQueueItemIdsWithResultImages', () => {diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueProgressCleanup.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueProgressCleanup.tsnew file mode 100644index 0000000000..82a5e2f621--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueProgressCleanup.ts@@ -0,0 +1,22 @@+import type { QueueItemReadModel } from '@features/queue/core/types';++import { getResultImageName } from '@features/queue/core/generationMeta';+import { itemProgressStore } from '@features/queue/data/itemProgressStore';++export const getQueueItemIdsWithResultImages = (items: QueueItemReadModel[]): number[] => {+ const itemIds: number[] = [];++ for (const item of items) {+ if (getResultImageName(item)) {+ itemIds.push(item.id);+ }+ }++ return itemIds;+};++export const clearProgressForQueueItemsWithResults = (items: QueueItemReadModel[]): void => {+ for (const itemId of getQueueItemIdsWithResultImages(items)) {+ itemProgressStore.clear(itemId);+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueScope.test.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueScope.test.tssimilarity index 56%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/queueScope.test.tsrename to invokeai/frontend/webv2/src/features/queue/ui/queueScope.test.tsindex 2d6bacc8c0..04e12ec221 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueScope.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueScope.test.ts@@ -1,18 +1,11 @@-import type { Project, QueueItem } from '@workbench/types';+import type { QueueItem, QueueItemReadModel } from '@features/queue';-import { buildQueueItemOrigin, buildProjectQueueItemOriginPrefix } from '@workbench/backend/events';+import { buildQueueItemOrigin, buildProjectQueueItemOriginPrefix } from '@features/queue';import { describe, expect, it } from 'vitest';-import type { QueueServerItem } from './queueServerApi';+import { getQueueQueryScope, isQueueItemReadModelInProject } from './queueScope';-import { getQueueQueryScope, isQueueServerItemInProject } from './queueScope';--const createProject = (items: QueueItem[]): Project =>- ({- id: 'project-1',- name: 'Project 1',- queue: { items },- }) as Project;+const createProject = (items: QueueItem[]) => ({ id: 'project-1', name: 'Project 1', queue: { items } });const createLocalQueueItem = ({backendItemIds,@@ -29,26 +22,26 @@ const createLocalQueueItem = ({status,}) as QueueItem;-const createServerQueueItem = ({ itemId, origin }: { itemId: number; origin?: string | null }): QueueServerItem =>+const createServerQueueItem = ({ itemId, origin }: { itemId: number; origin?: string | null }): QueueItemReadModel =>({- item_id: itemId,+ id: itemId,origin,- }) as QueueServerItem;+ }) as QueueItemReadModel;-describe('isQueueServerItemInProject', () => {+describe('isQueueItemReadModelInProject', () => {it('matches server queue items by webv2 origin', () => {const project = createProject([createLocalQueueItem({ id: 'local-1', status: 'pending' })]);expect(- isQueueServerItemInProject(+ isQueueItemReadModelInProject(createServerQueueItem({ itemId: 7, origin: buildQueueItemOrigin('local-1', 'project-1') }),project)).toBe(true);- expect(isQueueServerItemInProject(createServerQueueItem({ itemId: 7, origin: 'webv2:local-1' }), project)).toBe(+ expect(isQueueItemReadModelInProject(createServerQueueItem({ itemId: 7, origin: 'webv2:local-1' }), project)).toBe(true);- expect(isQueueServerItemInProject(createServerQueueItem({ itemId: 8, origin: 'webv2:local-2' }), project)).toBe(+ expect(isQueueItemReadModelInProject(createServerQueueItem({ itemId: 8, origin: 'webv2:local-2' }), project)).toBe(false);});@@ -56,8 +49,8 @@ describe('isQueueServerItemInProject', () => {it('falls back to backend item ids when origin is unavailable', () => {const project = createProject([createLocalQueueItem({ backendItemIds: [7, 8], id: 'local-1', status: 'running' })]);- expect(isQueueServerItemInProject(createServerQueueItem({ itemId: 8, origin: null }), project)).toBe(true);- expect(isQueueServerItemInProject(createServerQueueItem({ itemId: 9, origin: null }), project)).toBe(false);+ expect(isQueueItemReadModelInProject(createServerQueueItem({ itemId: 8, origin: null }), project)).toBe(true);+ expect(isQueueItemReadModelInProject(createServerQueueItem({ itemId: 9, origin: null }), project)).toBe(false);});it('builds backend origin-prefix scopes from the active project', () => {expect(getQueueQueryScope({ projectId: 'project-1', queueJobsScope: 'active-project' })).toEqual({diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueScope.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueScope.tsnew file mode 100644index 0000000000..624292a159--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueScope.ts@@ -0,0 +1,39 @@+import type { QueueItem } from '@features/queue/core/historyTypes';+import type { QueueItemReadModel, QueueQueryScope } from '@features/queue/core/types';++import { buildProjectQueueItemOriginPrefix, parseQueueItemOrigin } from '@features/queue/data/events';+import { useMemo } from 'react';++import { useQueueUi } from './QueueUiContext';++export type QueueJobsScope = 'active-project' | 'all';++export const isQueueItemReadModelInProject = (+ serverItem: QueueItemReadModel,+ project: { queue: { items: QueueItem[] } }+): boolean => {+ const localQueueItemId = parseQueueItemOrigin(serverItem.origin);++ if (localQueueItemId && project.queue.items.some((item) => item.id === localQueueItemId)) {+ return true;+ }++ return project.queue.items.some((item) => item.backendItemIds?.includes(serverItem.id) ?? false);+};++export const getQueueQueryScope = ({+ projectId,+ queueJobsScope,+}: {+ projectId: string | null;+ queueJobsScope: QueueJobsScope;+}): QueueQueryScope =>+ queueJobsScope === 'active-project' && projectId+ ? { originPrefix: buildProjectQueueItemOriginPrefix(projectId) }+ : {};++export const useQueueQueryScope = (): QueueQueryScope => {+ const { activeProjectId: projectId, queueJobsScope } = useQueueUi();++ return useMemo(() => getQueueQueryScope({ projectId, queueJobsScope }), [projectId, queueJobsScope]);+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueViewModel.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueViewModel.tssimilarity index 92%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/queueViewModel.tsrename to invokeai/frontend/webv2/src/features/queue/ui/queueViewModel.tsindex 73589fec60..057b0e34ae 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueViewModel.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueViewModel.ts@@ -1,6 +1,6 @@-import type { Project, QueueItem } from '@workbench/types';+import type { QueueItem } from '@features/queue/core/historyTypes';-import { createStableSelector } from '@workbench/workbenchSelectors';+import { createStableSelector } from '@platform/state/selectors';export interface QueueRow {item: QueueItem;@@ -30,7 +30,7 @@ export const areQueueRowsEqual = (left: readonly QueueRow[], right: readonly Queexport const createQueueRowsSelector = () =>createStableSelector(- (projects: readonly Project[]): QueueRow[] =>+ (projects: readonly { id: string; name: string; queue: { items: QueueItem[] } }[]): QueueRow[] =>projects.flatMap((project) =>project.queue.items.map((item) => ({ item, projectId: project.id, projectName: project.name }))),diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/statusMeta.ts b/invokeai/frontend/webv2/src/features/queue/ui/statusMeta.tssimilarity index 77%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/statusMeta.tsrename to invokeai/frontend/webv2/src/features/queue/ui/statusMeta.tsindex 811fe994dc..9bdb8fe5d3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/statusMeta.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/statusMeta.ts@@ -1,4 +1,4 @@-import type { BackendQueueItemStatus } from '@workbench/backend/events';+import type { QueueItemStatus } from '@features/queue/core/types';/*** Presentation metadata for each backend queue status: the human label, the@@ -11,7 +11,7 @@ export interface QueueStatusMeta {dotColor: string;}-const STATUS_META: Record<BackendQueueItemStatus, QueueStatusMeta> = {+const STATUS_META: Record<QueueItemStatus, QueueStatusMeta> = {canceled: { colorPalette: 'orange', dotColor: 'orange.solid', labelKey: 'common.status.canceled' },completed: { colorPalette: 'green', dotColor: 'green.solid', labelKey: 'common.status.completed' },failed: { colorPalette: 'red', dotColor: 'red.solid', labelKey: 'common.status.failed' },@@ -19,4 +19,4 @@ const STATUS_META: Record<BackendQueueItemStatus, QueueStatusMeta> = {pending: { colorPalette: 'gray', dotColor: 'fg.muted', labelKey: 'common.status.pending' },};-export const getStatusMeta = (status: BackendQueueItemStatus): QueueStatusMeta => STATUS_META[status];+export const getStatusMeta = (status: QueueItemStatus): QueueStatusMeta => STATUS_META[status];diff --git a/invokeai/frontend/webv2/src/features/queue/utility.ts b/invokeai/frontend/webv2/src/features/queue/utility.tsnew file mode 100644index 0000000000..d39f110043--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/utility.ts@@ -0,0 +1,7 @@+/** One-shot Queue execution interface for utility graphs such as Canvas filters. */+export {+ runUtilityGraph,+ UtilityQueueError,+ type RunUtilityGraphOptions,+ type UtilityGraphResult,+} from './runtime/utilityGraph';diff --git a/invokeai/frontend/webv2/src/features/queue/widget.ts b/invokeai/frontend/webv2/src/features/queue/widget.tsnew file mode 100644index 0000000000..470cb6a3ae--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/widget.ts@@ -0,0 +1,9 @@+/** Queue-owned deferred widget slots; Workbench supplies the manifest adapter. */+export {+ ModelCacheFooter,+ QueueDataRuntime,+ QueueHeaderActions,+ QueueHeaderLabel,+ QueueHeaderMenu,+ QueueWidgetView,+} from './ui';diff --git a/invokeai/frontend/webv2/src/workbench/upscale/graph.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/upscale/graph.test.tsrename to invokeai/frontend/webv2/src/features/upscale/core/graph.test.tsindex 24ca7c35d1..b588604cb1 100644--- a/invokeai/frontend/webv2/src/workbench/upscale/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts@@ -1,5 +1,5 @@-import type { GenerateLora, VaeModelConfig } from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';+import type { GenerateLora, VaeModelConfig } from '@features/generation/contracts';+import type { ModelConfig } from '@features/models';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/upscale/graph.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/upscale/graph.tsrename to invokeai/frontend/webv2/src/features/upscale/core/graph.tsindex bbbaf1194e..40c745ca73 100644--- a/invokeai/frontend/webv2/src/workbench/upscale/graph.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts@@ -1,19 +1,19 @@import type {BackendGraphContract,BackendInvocationContract,- ProjectSettings,+ GenerationProjectSettings,ResultDestination,-} from '@workbench/types';+} from '@features/generation/contracts';-import { coerceSchedulerForGraph } from '@workbench/generation/baseGenerationPolicies';-import { addLoraCollectionLoader } from '@workbench/generation/graph';import {+ addLoraCollectionLoader,addEdge,addNode,getActiveCompatibleLoras,toGraphContract,toModelIdentifier,-} from '@workbench/generation/graphBuilder';+} from '@features/generation/graph';+import { coerceSchedulerForGraph } from '@features/generation/settings';import type { CompiledUpscaleGraph, UpscaleWidgetValues } from './types';@@ -42,7 +42,7 @@ const addUpscaleMetadata = (graph: BackendGraphContract,output: BackendInvocationContract,settings: UpscaleWidgetValues,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ projectSettings: GenerationProjectSettings): void => {if (!settings.model || !settings.upscaleModel || !settings.inputImage) {return;@@ -109,7 +109,7 @@ const addUpscaleMetadata = (export const compileUpscaleGraph = (settings: UpscaleWidgetValues,destination: ResultDestination,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ projectSettings: GenerationProjectSettings): CompiledUpscaleGraph => {const reasons = getUpscaleValidationReasons(settings);diff --git a/invokeai/frontend/webv2/src/workbench/upscale/integration.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/integration.test.tssimilarity index 85%rename from invokeai/frontend/webv2/src/workbench/upscale/integration.test.tsrename to invokeai/frontend/webv2/src/features/upscale/core/integration.test.tsindex 88792e9900..11fc358285 100644--- a/invokeai/frontend/webv2/src/workbench/upscale/integration.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts@@ -1,7 +1,6 @@-import type { ModelConfig } from '@workbench/models/types';+import type { ModelConfig } from '@features/models';-import { createQueueItemBackendSubmission, getQueueItemResultImageOptions } from '@workbench/WorkbenchRuntime';-import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState';+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';import { describe, expect, it, vi } from 'vitest';import { createDefaultUpscaleWidgetValues } from './settings';@@ -79,15 +78,13 @@ describe('Upscale snapshot submission', () => {is_intermediate: false,type: 'l2i',});- expect(getQueueItemResultImageOptions(queueItem)).toEqual({ resultNodeIds: ['upscale_output'] });- expect(createQueueItemBackendSubmission(project, queueItem)).toMatchObject({+ expect(queueItem.snapshot.resultNodeIds).toEqual(['upscale_output']);+ expect(queueItem.snapshot.backendSubmission).toMatchObject({+ batchCount: 3,kind: 'generate',- request: {- batchCount: 3,- negativePrompt: 'blur',- positivePrompt: 'fine detail',- seedNodeId: 'seed',- },+ negativePrompt: 'blur',+ positivePrompt: 'fine detail',+ seedNodeId: 'seed',});expect(getProjectPromptValues(project)).toMatchObject({negativePrompt: 'changed later',diff --git a/invokeai/frontend/webv2/src/workbench/upscale/settings.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/upscale/settings.test.tsrename to invokeai/frontend/webv2/src/features/upscale/core/settings.test.tsindex 3d175df83e..1e4df878e0 100644--- a/invokeai/frontend/webv2/src/workbench/upscale/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts@@ -1,5 +1,5 @@-import type { GenerateLora, VaeModelConfig } from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';+import type { GenerateLora, VaeModelConfig } from '@features/generation/contracts';+import type { ModelConfig } from '@features/models';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/upscale/settings.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.tssimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/upscale/settings.tsrename to invokeai/frontend/webv2/src/features/upscale/core/settings.tsindex afc5ca2e94..95b6577cce 100644--- a/invokeai/frontend/webv2/src/workbench/upscale/settings.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.ts@@ -4,11 +4,10 @@ import type {MainModelConfig,ModelIdentifierConfig,VaePrecision,-} from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';+} from '@features/generation/contracts';+import type { ModelConfig } from '@features/models';-import { sanitizeBatchCount } from '@workbench/generation/batch';-import { isVaeCompatibleWithGenerateModel } from '@workbench/generation/componentCompatibility';+import { sanitizeBatchCount } from '@features/generation/batch';import {DEFAULT_NEGATIVE_PROMPT_HEIGHT_PX,DEFAULT_POSITIVE_PROMPT_HEIGHT_PX,@@ -17,12 +16,13 @@ import {isMainModelConfig,isModelIdentifierConfig,isVaeModelConfig,+ isVaeCompatibleWithGenerateModel,MAX_NEGATIVE_PROMPT_HEIGHT_PX,MAX_POSITIVE_PROMPT_HEIGHT_PX,MIN_NEGATIVE_PROMPT_HEIGHT_PX,MIN_POSITIVE_PROMPT_HEIGHT_PX,SEED_MAX,-} from '@workbench/generation/settings';+} from '@features/generation/settings';import type { SpandrelModelConfig, TileControlNetModelConfig, UpscaleWidgetValues } from './types';diff --git a/invokeai/frontend/webv2/src/workbench/upscale/types.ts b/invokeai/frontend/webv2/src/features/upscale/core/types.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/upscale/types.tsrename to invokeai/frontend/webv2/src/features/upscale/core/types.tsindex f996fac7f3..731241a891 100644--- a/invokeai/frontend/webv2/src/workbench/upscale/types.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/types.ts@@ -6,7 +6,7 @@ import type {ModelIdentifierConfig,VaeModelConfig,VaePrecision,-} from '@workbench/generation/types';+} from '@features/generation/contracts';export type SpandrelModelConfig = ModelIdentifierConfig & { type: 'spandrel_image_to_image' };export type TileControlNetModelConfig = ModelIdentifierConfig & { type: 'controlnet' };diff --git a/invokeai/frontend/webv2/src/features/upscale/index.ts b/invokeai/frontend/webv2/src/features/upscale/index.tsnew file mode 100644index 0000000000..d0c5a4a648--- /dev/null+++ b/invokeai/frontend/webv2/src/features/upscale/index.ts@@ -0,0 +1,18 @@+export { compileUpscaleGraph } from './core/graph';+export {+ clearDeletedUpscaleInput,+ cloneUpscaleWidgetValues,+ createDefaultUpscaleWidgetValues,+ getUpscaleOutputDimensions,+ getUpscaleValidationReasons,+ normalizeUpscaleWidgetValues,+ resolveUpscaleSeed,+ syncUpscaleWidgetValuesWithModels,+} from './core/settings';+export type {+ CompiledUpscaleGraph,+ SpandrelModelConfig,+ TileControlNetModelConfig,+ UpscaleWidgetValues,+} from './core/types';+export { UpscaleUiProvider, type UpscaleUiAdapter } from './ui/UpscaleUiContext';diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsxnew file mode 100644index 0000000000..cdbabcedeb--- /dev/null+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx@@ -0,0 +1,32 @@+import type { ProjectPromptDraft, ProjectPromptDraftPatch } from '@features/generation/utility';+import type { UpscaleWidgetValues } from '@features/upscale/core/types';+import type { ReactNode } from 'react';++import { createContext, use } from 'react';++export interface UpscaleUiAdapter {+ patchPromptDraft(values: ProjectPromptDraftPatch): void;+ patchValues(values: Partial<UpscaleWidgetValues>): void;+ projectId: string;+ promptDraft: ProjectPromptDraft;+ rawValues: Record<string, unknown>;+ reportError(message: string): void;+ showPromptSyntaxHighlighting: boolean;+ touchGalleryImages(): void;+}++const UpscaleUiContext = createContext<UpscaleUiAdapter | null>(null);++export const UpscaleUiProvider = ({ adapter, children }: { adapter: UpscaleUiAdapter; children: ReactNode }) => (+ <UpscaleUiContext value={adapter}>{children}</UpscaleUiContext>+);++export const useUpscaleUi = (): UpscaleUiAdapter => {+ const adapter = use(UpscaleUiContext);++ if (!adapter) {+ throw new Error('Upscale UI requires an App-composed UpscaleUiProvider.');+ }++ return adapter;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/upscale/UpscaleWidgetView.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsxsimilarity index 89%rename from invokeai/frontend/webv2/src/workbench/widgets/upscale/UpscaleWidgetView.tsxrename to invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsxindex e2f23cf389..c99c94c34a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/upscale/UpscaleWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx@@ -1,8 +1,8 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop */-import type { GenerateLora, MainModelConfig, VaePrecision } from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';-import type { PromptHistoryItem } from '@workbench/types';-import type { UpscaleWidgetValues } from '@workbench/upscale/types';+import type { GenerateLora, MainModelConfig, PromptHistoryItem, VaePrecision } from '@features/generation/contracts';+import type { ProjectPromptDraft, ProjectPromptDraftPatch } from '@features/generation/utility';+import type { ModelConfig } from '@features/models';+import type { UpscaleWidgetValues } from '@features/upscale/core/types';import type { ChangeEvent } from 'react';import {@@ -23,27 +23,21 @@ import {Text,} from '@chakra-ui/react';import { useDndMonitor, useDroppable } from '@dnd-kit/core';-import { Button, Combobox, Field, IconButton, Slider, Tooltip } from '@workbench/components/ui';-import { toaster } from '@workbench/components/ui/toaster';-import { getGalleryImagesByNames, getImageThumbnailUrl, uploadGalleryImage } from '@workbench/gallery/api';-import { SCHEDULER_OPTIONS } from '@workbench/generation/baseGenerationPolicies';-import {- areProjectPromptDraftsEqual,- getProjectPromptDraft,- type ProjectPromptDraft,- type ProjectPromptDraftPatch,-} from '@workbench/generation/projectPromptDraft';+import { galleryImages, galleryTransfers } from '@features/gallery';+import { isGalleryImageDragData } from '@features/gallery/utility';+import { NegativePromptField, PositivePromptField } from '@features/generation/prompt-ui';import {+ SCHEDULER_OPTIONS,getDefaultLoraWeight,isLoraCompatibleWithModel,isLoraModelConfig,isMainModelConfig,isVaeModelConfig,SEED_MAX,-} from '@workbench/generation/settings';-import { useMountEffect } from '@workbench/hooks/useMountEffect';-import { ModelSelect } from '@workbench/models/components';-import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';+} from '@features/generation/settings';+import { GenerateCollapsibleSection } from '@features/generation/settings-ui';+import { ensureModelsLoaded, useModelsSelector } from '@features/models';+import { ModelSelect } from '@features/models/react';import {createDefaultUpscaleWidgetValues,getUpscaleOutputDimensions,@@ -63,16 +57,16 @@ import {UPSCALE_TILE_OVERLAP_MIN,UPSCALE_TILE_SIZE_MAX,UPSCALE_TILE_SIZE_MIN,-} from '@workbench/upscale/settings';-import { isGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';-import { NegativePromptField } from '@workbench/widgets/generate/promptFields/NegativePromptField';-import { PositivePromptField } from '@workbench/widgets/generate/promptFields/PositivePromptField';-import { GenerateCollapsibleSection } from '@workbench/widgets/generate/shared/GenerateCollapsibleSection';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+} from '@features/upscale/core/settings';+import { useMountEffect } from '@platform/react/useMountEffect';+import { Button, Combobox, Field, IconButton, Slider, Tooltip } from '@platform/ui';+import { toaster } from '@platform/ui/toaster';import { DicesIcon, ImagePlusIcon, Trash2Icon, UploadIcon, XIcon } from 'lucide-react';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useUpscaleUi } from './UpscaleUiContext';+const DROP_ID = 'upscale-input-image';const LARGE_OUTPUT_MEGAPIXELS = 50;const DIMENSION_FORMATTER = new Intl.NumberFormat();@@ -179,15 +173,13 @@ const UpscaleOutputPreflight = ({ values }: { values: UpscaleWidgetValues }) =>};const UpscaleModelReconciler = ({- projectId,rawValues,values,}: {- projectId: string;rawValues: Record<string, unknown>;values: UpscaleWidgetValues;}) => {- const dispatch = useWorkbenchDispatch();+ const { patchValues } = useUpscaleUi();useMountEffect(() => {const normalized = normalizeUpscaleWidgetValues(rawValues);@@ -196,7 +188,7 @@ const UpscaleModelReconciler = ({return;}- dispatch({ projectId, type: 'patchWidgetValues', values: { ...values }, widgetId: 'upscale' });+ patchValues({ ...values });});return null;@@ -334,7 +326,7 @@ const UpscaleImageField = ({onChange: (image: UpscaleWidgetValues['inputImage']) => void;}) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();+ const { reportError, touchGalleryImages } = useUpscaleUi();const fileInputRef = useRef<HTMLInputElement | null>(null);const { isOver, setNodeRef } = useDroppable({ data: { kind: DROP_ID }, id: DROP_ID });const [isLoading, setIsLoading] = useState(false);@@ -346,7 +338,7 @@ const UpscaleImageField = ({setIsLoading(true);try {- const [image] = await getGalleryImagesByNames([imageName]);+ const [image] = await galleryImages.resolveMany([imageName]);if (image) {onChange({ height: image.height, image_name: image.imageName, width: image.width });@@ -354,12 +346,12 @@ const UpscaleImageField = ({} catch (error) {const message = error instanceof Error ? error.message : String(error);setErrorMessage(message);- dispatch({ area: 'upscale', message, namespace: 'generation', type: 'recordError' });+ reportError(message);} finally {setIsLoading(false);}},- [dispatch, onChange]+ [onChange, reportError]);useDndMonitor({@@ -382,36 +374,26 @@ const UpscaleImageField = ({if (!['image/png', 'image/jpeg', 'image/webp'].includes(file.type)) {setErrorMessage(t('widgets.upscale.unsupportedFile'));- dispatch({- area: 'upscale',- message: t('widgets.upscale.unsupportedFile'),- namespace: 'generation',- type: 'recordError',- });+ reportError(t('widgets.upscale.unsupportedFile'));return;}setIsLoading(true);try {- const image = await uploadGalleryImage(file, 'none');+ const image = await galleryTransfers.upload(file, 'none');onChange({ height: image.height, image_name: image.imageName, width: image.width });- dispatch({ type: 'touchGalleryImagesRefresh' });+ touchGalleryImages();} catch (error) {const message = error instanceof Error ? error.message : String(error);setErrorMessage(message);- dispatch({- area: 'upscale',- message,- namespace: 'generation',- type: 'recordError',- });+ reportError(message);} finally {setIsLoading(false);}},- [dispatch, onChange, t]+ [onChange, reportError, t, touchGalleryImages]);const handleFileChange = useCallback(@@ -461,7 +443,7 @@ const UpscaleImageField = ({outline="1px solid rgba(0, 0, 0, 0.1)"outlineOffset="-1px"rounded="sm"- src={getImageThumbnailUrl(inputImage.image_name)}+ src={galleryImages.thumbnailUrl(inputImage.image_name)}_dark={{ outlineColor: 'rgba(255, 255, 255, 0.1)' }}/></Box>@@ -517,24 +499,7 @@ const UpscaleImageField = ({export const UpscaleWidgetView = () => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();- const selection = useActiveProjectSelector(- (project) => {- const instance = Object.values(project.widgetInstances).find((candidate) => candidate.typeId === 'upscale');-- return {- promptDraft: getProjectPromptDraft(project),- projectId: project.id,- rawValues: instance?.state.values ?? {},- showPromptSyntaxHighlighting: project.settings.showPromptSyntaxHighlighting,- };- },- (left, right) =>- left.projectId === right.projectId &&- areProjectPromptDraftsEqual(left.promptDraft, right.promptDraft) &&- left.rawValues === right.rawValues &&- left.showPromptSyntaxHighlighting === right.showPromptSyntaxHighlighting- );+ const selection = useUpscaleUi();const models = useModelsSelector((snapshot) => snapshot.models);const modelsStatus = useModelsSelector((snapshot) => snapshot.status);const normalized = normalizeUpscaleWidgetValues(selection.rawValues) ?? createDefaultUpscaleWidgetValues();@@ -579,21 +544,12 @@ export const UpscaleWidgetView = () => {UPSCALE_TILE_SIZE_MAX),};- const patch = useCallback(- (next: Partial<UpscaleWidgetValues>) =>- dispatch({ projectId: selection.projectId, type: 'patchWidgetValues', values: next, widgetId: 'upscale' }),- [dispatch, selection.projectId]- );+ const patch = useCallback((next: Partial<UpscaleWidgetValues>) => selection.patchValues(next), [selection]);const patchPromptDraft = useCallback(- (next: ProjectPromptDraftPatch) =>- dispatch({ projectId: selection.projectId, type: 'patchProjectPromptDraft', values: next }),- [dispatch, selection.projectId]- );- const replace = useCallback(- (next: UpscaleWidgetValues) =>- dispatch({ projectId: selection.projectId, type: 'patchWidgetValues', values: { ...next }, widgetId: 'upscale' }),- [dispatch, selection.projectId]+ (next: ProjectPromptDraftPatch) => selection.patchPromptDraft(next),+ [selection]);+ const replace = useCallback((next: UpscaleWidgetValues) => selection.patchValues({ ...next }), [selection]);useMountEffect(() => {ensureModelsLoaded();@@ -650,7 +606,6 @@ export const UpscaleWidgetView = () => {<Stack gap="2" minW="0" p="2"><UpscaleModelReconcilerkey={`${selection.projectId}:${modelsStatus}:${modelsFingerprint}`}- projectId={selection.projectId}rawValues={selection.rawValues}values={values}/>diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/implementation.ts b/invokeai/frontend/webv2/src/features/upscale/ui/implementation.tsnew file mode 100644index 0000000000..e3ad07de6b--- /dev/null+++ b/invokeai/frontend/webv2/src/features/upscale/ui/implementation.ts@@ -0,0 +1,3 @@+import { UpscaleWidgetView } from './UpscaleWidgetView';++export const widgetImplementation = { view: UpscaleWidgetView };diff --git a/invokeai/frontend/webv2/src/features/upscale/widget.ts b/invokeai/frontend/webv2/src/features/upscale/widget.tsnew file mode 100644index 0000000000..3182b7a7f8--- /dev/null+++ b/invokeai/frontend/webv2/src/features/upscale/widget.ts@@ -0,0 +1 @@+export { widgetImplementation } from './ui/implementation';diff --git a/invokeai/frontend/webv2/src/features/workflow/contracts.ts b/invokeai/frontend/webv2/src/features/workflow/contracts.tsnew file mode 100644index 0000000000..f3c3945b0c--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/contracts.ts@@ -0,0 +1,3 @@+export type * from './core/graphContracts';+export type * from './core/types';+export { isConnectorNode, isCurrentImageNode, isInvocationNode, isNotesNode } from './core/types';diff --git a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.tssimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.tsrename to invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.tsindex 84e931fc46..d62d6b79ae 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts@@ -1,7 +1,6 @@import { describe, expect, it } from 'vitest';-import type { InvocationTemplatesSnapshot } from './templates';-import type { FieldInputTemplate, InvocationTemplate, ProjectGraphState } from './types';+import type { FieldInputTemplate, InvocationTemplate, InvocationTemplatesSnapshot, ProjectGraphState } from './types';import { compileProjectGraph, getProjectGraphReadiness } from './buildGraph';import {diff --git a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.tssimilarity index 93%rename from invokeai/frontend/webv2/src/workbench/workflows/buildGraph.tsrename to invokeai/frontend/webv2/src/features/workflow/core/buildGraph.tsindex 7da1cbeb7f..611dd23fb9 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts@@ -1,7 +1,11 @@-import type { BackendGraphContract, GraphContract } from '@workbench/types';--import type { InvocationTemplatesSnapshot } from './templates';-import type { FieldInputTemplate, InvocationTemplates, ProjectGraphState, WorkflowInvocationNode } from './types';+import type { CompiledWorkflowGraph, WorkflowBackendGraph } from './graphContracts';+import type {+ FieldInputTemplate,+ InvocationTemplates,+ InvocationTemplatesSnapshot,+ ProjectGraphState,+ WorkflowInvocationNode,+} from './types';import { getResolvedWorkflowEdgesIndexed } from './connectors';import { createWorkflowId } from './document';@@ -147,10 +151,13 @@ const toGraphInputValue = (inputTemplate: FieldInputTemplate, value: unknown): u};/** Compiles the document into a `GraphContract` carrying the executable backend graph. */-export const compileProjectGraph = (document: ProjectGraphState, templates: InvocationTemplates): GraphContract => {+export const compileProjectGraph = (+ document: ProjectGraphState,+ templates: InvocationTemplates+): CompiledWorkflowGraph => {const executableNodes = getExecutableNodes(document).filter((node) => templates[node.data.type] !== undefined);const executableNodeIds = new Set(executableNodes.map((node) => node.id));- const backendGraph: BackendGraphContract = { edges: [], id: createWorkflowId('workflow-graph'), nodes: {} };+ const backendGraph: WorkflowBackendGraph = { edges: [], id: createWorkflowId('workflow-graph'), nodes: {} };const index = createWorkflowGraphIndex(document.nodes, document.edges);const resolvedEdges = getResolvedWorkflowEdgesIndexed(document.edges, index, templates);@@ -177,7 +184,7 @@ export const compileProjectGraph = (document: ProjectGraphState, templates: Invo}}- backendGraph.nodes[node.id] = graphNode as BackendGraphContract['nodes'][string];+ backendGraph.nodes[node.id] = graphNode as WorkflowBackendGraph['nodes'][string];}const seenEdgeKeys = new Set<string>();diff --git a/invokeai/frontend/webv2/src/workbench/workflows/connectorHandles.ts b/invokeai/frontend/webv2/src/features/workflow/core/connectorHandles.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/connectorHandles.tsrename to invokeai/frontend/webv2/src/features/workflow/core/connectorHandles.tsdiff --git a/invokeai/frontend/webv2/src/workbench/workflows/connectors.ts b/invokeai/frontend/webv2/src/features/workflow/core/connectors.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/connectors.tsrename to invokeai/frontend/webv2/src/features/workflow/core/connectors.tsdiff --git a/invokeai/frontend/webv2/src/workbench/workflows/document.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/document.test.tsrename to invokeai/frontend/webv2/src/features/workflow/core/document.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/workflows/document.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/document.tsrename to invokeai/frontend/webv2/src/features/workflow/core/document.tsdiff --git a/invokeai/frontend/webv2/src/workbench/workflows/fields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/fields.test.tsrename to invokeai/frontend/webv2/src/features/workflow/core/fields.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/workflows/fields.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/fields.tsrename to invokeai/frontend/webv2/src/features/workflow/core/fields.tsdiff --git a/invokeai/frontend/webv2/src/features/workflow/core/graphContracts.ts b/invokeai/frontend/webv2/src/features/workflow/core/graphContracts.tsnew file mode 100644index 0000000000..fb27419d2c--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/core/graphContracts.ts@@ -0,0 +1,30 @@+export interface WorkflowBackendInvocation {+ id: string;+ type: string;+ [key: string]: unknown;+}++export interface WorkflowBackendGraph {+ id: string;+ nodes: Record<string, WorkflowBackendInvocation>;+ edges: Array<{+ source: { node_id: string; field: string };+ destination: { node_id: string; field: string };+ }>;+}++export interface CompiledWorkflowGraph {+ id: string;+ version: 1;+ label: string;+ nodes: Array<{ id: string; type: string; inputs: Record<string, unknown> }>;+ edges: Array<{+ id: string;+ sourceNodeId: string;+ sourceField: string;+ targetNodeId: string;+ targetField: string;+ }>;+ updatedAt: string;+ backendGraph: WorkflowBackendGraph;+}diff --git a/invokeai/frontend/webv2/src/workbench/workflows/graphIndex.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/graphIndex.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/graphIndex.test.tsrename to invokeai/frontend/webv2/src/features/workflow/core/graphIndex.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/workflows/graphIndex.ts b/invokeai/frontend/webv2/src/features/workflow/core/graphIndex.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/graphIndex.tsrename to invokeai/frontend/webv2/src/features/workflow/core/graphIndex.tsdiff --git a/invokeai/frontend/webv2/src/workbench/workflows/layerWorkflow.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.tssimilarity index 99%rename from invokeai/frontend/webv2/src/workbench/workflows/layerWorkflow.test.tsrename to invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.tsindex 5e5b45d8e4..b417e68f3c 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/layerWorkflow.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.ts@@ -1,10 +1,10 @@import { describe, expect, it } from 'vitest';-import type { InvocationTemplatesSnapshot } from './templates';import type {FieldInputTemplate,FieldOutputTemplate,InvocationTemplate,+ InvocationTemplatesSnapshot,InvocationTemplates,ProjectGraphState,WorkflowEdge,diff --git a/invokeai/frontend/webv2/src/workbench/workflows/layerWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.tssimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/workflows/layerWorkflow.tsrename to invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.tsindex 825b9ac6d7..45493648df 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/layerWorkflow.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts@@ -1,10 +1,9 @@-import type { BackendGraphContract } from '@workbench/types';--import type { InvocationTemplatesSnapshot } from './templates';+import type { WorkflowBackendGraph } from './graphContracts';import type {FieldInputTemplate,FieldOutputTemplate,InvocationTemplates,+ InvocationTemplatesSnapshot,ProjectGraphState,WorkflowInvocationNode,} from './types';@@ -43,7 +42,7 @@ export interface BuildLayerWorkflowGraphOptions {}export interface BuiltLayerWorkflowGraph {- graph: BackendGraphContract;+ graph: WorkflowBackendGraph;outputNodeId: string;}@@ -182,7 +181,7 @@ const getAvailableBinding = (selected: WorkflowImageBinding): WorkflowImageBinding | undefined => bindings.find((candidate) => isSameBinding(candidate, selected));-const allocateNodeId = (graph: BackendGraphContract, base: string): string => {+const allocateNodeId = (graph: WorkflowBackendGraph, base: string): string => {if (!graph.nodes[base]) {return base;}diff --git a/invokeai/frontend/webv2/src/features/workflow/core/properties.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/properties.test.tsnew file mode 100644index 0000000000..2579492b4f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/core/properties.test.ts@@ -0,0 +1,136 @@+import { describe, expect, it } from 'vitest';++import type { InvocationTemplate, ProjectGraphState, WorkflowEdge } from './types';++import {+ buildInvocationNode,+ createProjectGraph,+ getFormChildren,+ isFieldExposed,+ projectGraphReducer,+} from './document';+import { parseWorkflowJson, serializeWorkflowJson } from './workflowJson';++const template: InvocationTemplate = {+ category: 'property-test',+ classification: 'stable',+ description: '',+ inputs: {+ value: {+ default: '',+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ input: 'any',+ maximum: null,+ minimum: null,+ multipleOf: null,+ name: 'value',+ options: null,+ required: false,+ title: 'Value',+ type: { batch: false, cardinality: 'SINGLE', name: 'StringField' },+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelType: null,+ uiOrder: null,+ },+ },+ nodePack: 'invokeai',+ outputs: {+ value: {+ description: '',+ name: 'value',+ title: 'Value',+ type: { batch: false, cardinality: 'SINGLE', name: 'StringField' },+ },+ },+ outputType: 'string_output',+ tags: [],+ title: 'Value',+ type: 'value',+ useCache: true,+ version: '1.0.0',+};++const buildScenario = (seed: number): ProjectGraphState => {+ const nodeCount = (seed % 6) + 1;+ let document = createProjectGraph(`property-${seed}`, `Workflow ${seed}`);++ for (let index = 0; index < nodeCount; index += 1) {+ const node = buildInvocationNode(template, { x: seed * 3 + index * 17, y: index * 11 });++ document = projectGraphReducer(document, { node, type: 'addNode' });+ document = projectGraphReducer(document, {+ fieldName: 'value',+ nodeId: node.id,+ type: 'setFieldValue',+ value: `seed-${seed}-node-${index}`,+ });++ if ((seed + index) % 2 === 0) {+ document = projectGraphReducer(document, {+ fieldIdentifier: { fieldName: 'value', nodeId: node.id },+ type: 'exposeField',+ });+ }+ }++ for (let index = 1; index < document.nodes.length; index += 1) {+ const source = document.nodes[index - 1];+ const target = document.nodes[index];++ if (source && target) {+ const edge: WorkflowEdge = {+ id: `edge-${seed}-${index}`,+ source: source.id,+ sourceHandle: 'value',+ target: target.id,+ targetHandle: 'value',+ type: 'default',+ };++ document = projectGraphReducer(document, { edge, type: 'addEdge' });+ }+ }++ return document;+};++describe('workflow document properties', () => {+ it('keeps transport round-trips, migrations, edges, and linear projections stable across varied documents', () => {+ for (let seed = 0; seed < 128; seed += 1) {+ const original = buildScenario(seed);+ const serialized = serializeWorkflowJson(original);+ const firstParse = parseWorkflowJson(serialized);+ const secondParse = parseWorkflowJson(serializeWorkflowJson(firstParse.document));++ expect(firstParse.warnings, `first parse warnings for seed ${seed}`).toEqual([]);+ expect(secondParse.warnings, `second parse warnings for seed ${seed}`).toEqual([]);+ expect(serializeWorkflowJson(secondParse.document), `stable migration for seed ${seed}`).toEqual(+ serializeWorkflowJson(firstParse.document)+ );++ const nodeIds = new Set(firstParse.document.nodes.map((node) => node.id));++ expect(+ firstParse.document.edges.every((edge) => nodeIds.has(edge.source) && nodeIds.has(edge.target)),+ `edge validity for seed ${seed}`+ ).toBe(true);++ const projectedFields = getFormChildren(firstParse.document.form).filter(+ (element) => element.type === 'node-field'+ );++ for (const element of projectedFields) {+ expect(nodeIds.has(element.data.fieldIdentifier.nodeId), `projection node for seed ${seed}`).toBe(true);+ expect(+ isFieldExposed(firstParse.document.form, element.data.fieldIdentifier),+ `projection exposure for seed ${seed}`+ ).toBe(true);+ }+ }+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/workflows/types.ts b/invokeai/frontend/webv2/src/features/workflow/core/types.tssimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/workflows/types.tsrename to invokeai/frontend/webv2/src/features/workflow/core/types.tsindex a2164a1963..301ff44054 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/types.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/types.ts@@ -229,6 +229,12 @@ export interface ProjectGraphState extends WorkflowMetadata {updatedAt: string;}+export interface InvocationTemplatesSnapshot {+ status: 'idle' | 'loading' | 'loaded' | 'error';+ error: string | null;+ templates: InvocationTemplates;+}+export const isInvocationNode = (node: WorkflowNode): node is WorkflowInvocationNode => node.type === 'invocation';export const isNotesNode = (node: WorkflowNode): node is WorkflowNotesNode => node.type === 'notes';diff --git a/invokeai/frontend/webv2/src/workbench/workflows/validation.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/validation.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/validation.test.tsrename to invokeai/frontend/webv2/src/features/workflow/core/validation.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/workflows/validation.ts b/invokeai/frontend/webv2/src/features/workflow/core/validation.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/validation.tsrename to invokeai/frontend/webv2/src/features/workflow/core/validation.tsdiff --git a/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/workflowJson.test.tsrename to invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.ts b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/workflowJson.tsrename to invokeai/frontend/webv2/src/features/workflow/core/workflowJson.tsdiff --git a/invokeai/frontend/webv2/src/workbench/workflows/api.ts b/invokeai/frontend/webv2/src/features/workflow/data/api.tssimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/workflows/api.tsrename to invokeai/frontend/webv2/src/features/workflow/data/api.tsindex ee7be74b94..59b45b06f6 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/api.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/api.ts@@ -1,4 +1,4 @@-import { apiFetch, apiFetchJson } from '@workbench/backend/http';+import { apiFetch, apiFetchJson } from '@platform/transport/http';/*** Client for the backend workflow library (`/api/v1/workflows`). The librarydiff --git a/invokeai/frontend/webv2/src/workbench/workflows/libraryCache.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/libraryCache.tsrename to invokeai/frontend/webv2/src/features/workflow/data/libraryCache.tsdiff --git a/invokeai/frontend/webv2/src/workbench/workflows/templates.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/workflows/templates.test.tsrename to invokeai/frontend/webv2/src/features/workflow/data/templates.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/workflows/templates.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.tssimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/workflows/templates.tsrename to invokeai/frontend/webv2/src/features/workflow/data/templates.tsindex fbe8cc841c..9a5dafb552 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/templates.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.ts@@ -1,13 +1,16 @@-import { apiFetchJson, getApiErrorMessage } from '@workbench/backend/http';-import { createExternalStore } from '@workbench/externalStore';-import type {FieldInputTemplate,FieldOutputTemplate,FieldType,InvocationTemplate,InvocationTemplates,-} from './types';+ InvocationTemplatesSnapshot,+} from '@features/workflow/core/types';++import { createExternalStore } from '@platform/state/externalStore';+import { apiFetchJson, getApiErrorMessage } from '@platform/transport/http';++export type { InvocationTemplatesSnapshot } from '@features/workflow/core/types';/*** Invocation templates parsed from the backend OpenAPI schema. They are@@ -16,12 +19,6 @@ import type {* than in project state.*/-export interface InvocationTemplatesSnapshot {- status: 'idle' | 'loading' | 'loaded' | 'error';- error: string | null;- templates: InvocationTemplates;-}-const store = createExternalStore<InvocationTemplatesSnapshot>({ error: null, status: 'idle', templates: {} });type JsonObject = Record<string, unknown>;diff --git a/invokeai/frontend/webv2/src/features/workflow/graph.ts b/invokeai/frontend/webv2/src/features/workflow/graph.tsnew file mode 100644index 0000000000..d01f7b2bf7--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/graph.ts@@ -0,0 +1,2 @@+export * from './core/buildGraph';+export * from './core/layerWorkflow';diff --git a/invokeai/frontend/webv2/src/features/workflow/index.ts b/invokeai/frontend/webv2/src/features/workflow/index.tsnew file mode 100644index 0000000000..1211a63ab1--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/index.ts@@ -0,0 +1,3 @@+export type * from './contracts';+export { compileProjectGraph, getProjectGraphReadiness } from './graph';+export { ensureInvocationTemplatesLoaded, getInvocationTemplatesSnapshot } from './react';diff --git a/invokeai/frontend/webv2/src/features/workflow/preview.ts b/invokeai/frontend/webv2/src/features/workflow/preview.tsnew file mode 100644index 0000000000..90a0f58dd1--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/preview.ts@@ -0,0 +1,2 @@+export { documentToPreviewGraph, GraphPreviewDialog, GraphPreviewFlow } from './ui/graph-preview';+export { getWorkflowNodeChromeProps } from './ui/editor/nodeChrome';diff --git a/invokeai/frontend/webv2/src/features/workflow/queries.ts b/invokeai/frontend/webv2/src/features/workflow/queries.tsnew file mode 100644index 0000000000..00d3a58d77--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/queries.ts@@ -0,0 +1,2 @@+export * from './data/api';+export * from './data/libraryCache';diff --git a/invokeai/frontend/webv2/src/features/workflow/react.ts b/invokeai/frontend/webv2/src/features/workflow/react.tsnew file mode 100644index 0000000000..974ac1f0be--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/react.ts@@ -0,0 +1,4 @@+export * from './data/templates';+export { WorkflowUiProvider } from './ui/WorkflowUiContext';+export type { WorkflowUiAdapter } from './ui/WorkflowUiContext';+export type { WorkflowModelSelectProps } from './ui/contracts';diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsxnew file mode 100644index 0000000000..eee0b6b48f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx@@ -0,0 +1,120 @@+import type { ProjectGraphState } from '@features/workflow/core/types';+import type { ComponentType, ReactNode } from 'react';++import { createContext, use, useCallback, useSyncExternalStore } from 'react';++import type {+ WorkflowCommands,+ WorkflowGraphHistoryEntry,+ WorkflowModelSelectProps,+ WorkflowNodeExecutionState,+ WorkflowPerfSource,+ WorkflowWidgetCommands,+} from './contracts';++export interface WorkflowPreferences {+ reduceMotion: boolean;+ themeId: 'classic' | 'light' | 'forest' | 'mono' | 'ultradark';+ workflowEdgeStyle: 'curved' | 'square';+ workflowShowMinimap: boolean;+ workflowSnapToGrid: boolean;+ workflowValidateConnections: boolean;+}++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>;+ commands: WorkflowCommands;+ widgets: WorkflowWidgetCommands;+ getProjectGraph(): ProjectGraphState;+ notifications: {+ error(title: string, message?: string): void;+ info(title: string, message?: string): void;+ success(title: string, message?: string): void;+ };+ graphPreview: {+ getRoute(sourceId?: string): { canInvoke: boolean; label: string; validationMessage?: string } | null;+ invoke(sourceId?: string): Promise<boolean>;+ };+ performance: {+ mark(name: string, source: WorkflowPerfSource): void;+ measure(name: string, start: string, source: WorkflowPerfSource, end?: string): void;+ time<T>(name: string, source: WorkflowPerfSource, callback: () => T): T;+ };+ registerModalHotkeyLayer(id: string): () => void;+ nodeExecution: {+ get(nodeId: string): WorkflowNodeExecutionState | null;+ subscribe(nodeId: string, listener: () => void): () => void;+ };+}++const WorkflowUiContext = createContext<WorkflowUiAdapter | null>(null);++export const WorkflowUiProvider = ({ adapter, children }: { adapter: WorkflowUiAdapter; children: ReactNode }) => (+ <WorkflowUiContext value={adapter}>{children}</WorkflowUiContext>+);++export const useWorkflowUi = (): WorkflowUiAdapter => {+ const adapter = use(WorkflowUiContext);++ if (!adapter) {+ throw new Error('Workflow UI requires an App-composed WorkflowUiProvider.');+ }++ return adapter;+};++export const useWorkflowProjectSelector = <Selected,>(+ selector: (project: {+ id: string;+ projectGraph: ProjectGraphState;+ graphHistory: readonly WorkflowGraphHistoryEntry[];+ galleryValues: Record<string, unknown>;+ workflowValues: Record<string, unknown>;+ isWorkflowRunning: boolean;+ }) => 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,+ });+};++export const useWorkflowHostCommands = () => {+ const ui = useWorkflowUi();+ return { widgets: ui.widgets, workflows: ui.commands };+};++export const useWorkflowPreferencesSelector = <Selected,>(+ selector: (preferences: WorkflowPreferences) => Selected,+ _isEqual?: (left: Selected, right: Selected) => boolean+): Selected => selector(useWorkflowUi().preferences);++export const useWorkflowNotifications = () => useWorkflowUi().notifications;++export const WorkflowModelSelect = (props: WorkflowModelSelectProps) => {+ const { ModelSelect } = useWorkflowUi();+ return <ModelSelect {...props} />;+};++export const useWorkflowNodeExecutionState = (nodeId: string): WorkflowNodeExecutionState | null => {+ const { nodeExecution } = useWorkflowUi();+ const subscribe = useCallback(+ (listener: () => void) => nodeExecution.subscribe(nodeId, listener),+ [nodeExecution, nodeId]+ );+ const getSnapshot = useCallback(() => nodeExecution.get(nodeId), [nodeExecution, nodeId]);+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxsimilarity index 53%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxindex 8522f0ec86..b898128264 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -1,30 +1,37 @@-/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-jsx-as-prop */-import type { WidgetLabelProps, WidgetViewProps } from '@workbench/types';-import type { InvocationTemplate, XYPosition } from '@workbench/workflows/types';+import type { InvocationTemplate, XYPosition } from '@features/workflow/contracts';import { HStack, Icon, Input, Menu, Portal, Stack, Text } from '@chakra-ui/react';-import { IconButton, ConfirmDialog, Tooltip } from '@workbench/components/ui';-import { useNotify } from '@workbench/useNotify';-import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchStore } from '@workbench/WorkbenchContext';-import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from '@workbench/workflows/connectors';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import {buildConnectorNode,buildCurrentImageNode,buildInvocationNode,buildNotesNode,+ CONNECTOR_INPUT_HANDLE,+ CONNECTOR_OUTPUT_HANDLE,createProjectGraph,createWorkflowId,-} from '@workbench/workflows/document';-import { getCompatibleInputTemplate, getCompatibleOutputTemplate } from '@workbench/workflows/validation';-import { parseWorkflowJson } from '@workbench/workflows/workflowJson';+ getCompatibleInputTemplate,+ getCompatibleOutputTemplate,+ parseWorkflowJson,+} from '@features/workflow/utility';+import { IconButton, ConfirmDialog, Tooltip } from '@platform/ui';import { HistoryIcon, LibraryIcon, PlusIcon } from 'lucide-react';-import { useEffect, useId, useRef, type ChangeEvent } from 'react';+import { useCallback, useEffect, useId, useMemo, useRef, type ChangeEvent } from 'react';import { useTranslation } from 'react-i18next';+import type { WorkflowWidgetLabelProps, WorkflowWidgetViewProps } from './contracts';+import { AddNodeDialog } from './editor/AddNodeDialog';import { getWorkflowFlowInstance } from './editor/flowInstanceStore';import { WorkflowLibraryDialog } from './library/WorkflowLibraryDialog';import { copyWorkflowJson, downloadWorkflowJson } from './workflowTransfer';+import {+ useWorkflowHostCommands,+ useWorkflowNotifications,+ useWorkflowProjectSelector,+ useWorkflowUi,+} from './WorkflowUiContext';import {requestWorkflowImport,setAddNodeOpen,@@ -41,10 +48,15 @@ import {* mounted) and are driven through `workflowUiStore`.*/-export const WorkflowWidgetLabel = ({ region }: WidgetLabelProps) => {+export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {const { t } = useTranslation();- const workflowName = useActiveProjectSelector((project) => project.projectGraph.name);- const dispatch = useWorkbenchDispatch();+ const workflowName = useWorkflowProjectSelector((project) => project.projectGraph.name);+ const { editGraph } = useProjectGraphCommands();+ const changeWorkflowName = useCallback(+ (event: ChangeEvent<HTMLInputElement>) =>+ editGraph({ patch: { name: event.currentTarget.value }, type: 'setMetadata' }),+ [editGraph]+ );if (region !== 'center') {return (@@ -72,35 +84,38 @@ export const WorkflowWidgetLabel = ({ region }: WidgetLabelProps) => {size="2xs"value={workflowName}variant="flushed"- onChange={(event: ChangeEvent<HTMLInputElement>) =>- dispatch({- action: { patch: { name: event.currentTarget.value }, type: 'setMetadata' },- type: 'applyProjectGraphAction',- })- }+ onChange={changeWorkflowName}/></HStack>);};/** Entries contributed to the shared widget actions menu. */-export const WorkflowMenuItems = (_props: WidgetViewProps) => {+export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {const { t } = useTranslation();- const store = useWorkbenchStore();- const dispatch = useWorkbenchDispatch();- const notify = useNotify();-- const openDetailsPanel = () => {- dispatch({ region: 'left', type: 'openRegionWidget', widgetId: 'workflow' });- dispatch({ type: 'patchWidgetValues', values: { editTab: 'details', panelMode: 'edit' }, widgetId: 'workflow' });- };+ const { getProjectGraph } = useWorkflowUi();+ const { widgets } = useWorkflowHostCommands();+ const { saveSnapshot } = useProjectGraphCommands();+ const notify = useWorkflowNotifications();++ const openDetailsPanel = useCallback(() => {+ widgets.open({ region: 'left', widgetId: 'workflow' });+ widgets.patchValues('workflow', { editTab: 'details', panelMode: 'edit' });+ }, [widgets]);+ const exportWorkflow = useCallback(() => downloadWorkflowJson(getProjectGraph()), [getProjectGraph]);+ const copyWorkflow = useCallback(() => {+ copyWorkflowJson(getProjectGraph())+ .then(() => notify.success(t('widgets.workflow.copyJsonSuccess')))+ .catch(() => notify.error(t('widgets.workflow.copyJsonFailed')));+ }, [getProjectGraph, notify, t]);+ const createNewWorkflow = useCallback(() => setNewWorkflowConfirmOpen(true), []);return (<Menu.ItemGroup><Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">{t('widgets.labels.workflow')}</Menu.ItemGroupLabel>- <Menu.Item value="snapshot" onClick={() => dispatch({ type: 'saveProjectGraphSnapshot' })}>+ <Menu.Item value="snapshot" onClick={saveSnapshot}>{t('widgets.workflow.saveGraphSnapshot')}</Menu.Item><Menu.Item value="details" onClick={openDetailsPanel}>@@ -109,32 +124,33 @@ export const WorkflowMenuItems = (_props: WidgetViewProps) => {<Menu.Item value="import" onClick={requestWorkflowImport}>{t('widgets.workflow.importJsonWithEllipsis')}</Menu.Item>- <Menu.Item value="export" onClick={() => downloadWorkflowJson(store.getSnapshot().activeProject.projectGraph)}>+ <Menu.Item value="export" onClick={exportWorkflow}>{t('widgets.workflow.exportJson')}</Menu.Item>- <Menu.Item- value="copy"- onClick={() => {- copyWorkflowJson(store.getSnapshot().activeProject.projectGraph)- .then(() => notify.success(t('widgets.workflow.copyJsonSuccess')))- .catch(() => notify.error(t('widgets.workflow.copyJsonFailed')));- }}- >+ <Menu.Item value="copy" onClick={copyWorkflow}>{t('widgets.workflow.copyJson')}</Menu.Item>- <Menu.Item color="fg.error" value="new" onClick={() => setNewWorkflowConfirmOpen(true)}>+ <Menu.Item color="fg.error" value="new" onClick={createNewWorkflow}>{t('widgets.workflow.newWorkflowWithEllipsis')}</Menu.Item></Menu.ItemGroup>);};-export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {+export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {const { t } = useTranslation();- const graphHistory = useActiveProjectSelector((project) => project.graphHistory);- const dispatch = useWorkbenchDispatch();+ const graphHistory = useWorkflowProjectSelector((project) => project.graphHistory);+ const { restoreSnapshot } = useProjectGraphCommands();const restorableHistory = graphHistory.filter((entry) => entry.document);const historyTriggerId = useId();+ const openAddNode = useCallback(() => setAddNodeOpen(true), []);+ const openWorkflowLibrary = useCallback(() => setWorkflowLibraryOpen(true), []);+ const historyIds = useMemo(() => ({ trigger: historyTriggerId }), [historyTriggerId]);+ const historyPositioning = useMemo(() => ({ placement: 'bottom-end' as const }), []);+ const restoreHistoryEntry = useCallback(+ (details: { value: string }) => restoreSnapshot(details.value),+ [restoreSnapshot]+ );return (<HStack gap="0.5">@@ -145,7 +161,7 @@ export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {color="fg.muted"size="2xs"variant="ghost"- onClick={() => setAddNodeOpen(true)}+ onClick={openAddNode}><Icon as={PlusIcon} boxSize="3.5" /></IconButton>@@ -157,13 +173,13 @@ export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {color="fg.muted"size="2xs"variant="ghost"- onClick={() => setWorkflowLibraryOpen(true)}+ onClick={openWorkflowLibrary}><Icon as={LibraryIcon} boxSize="3.5" /></IconButton></Tooltip>- <Menu.Root ids={{ trigger: historyTriggerId }} positioning={{ placement: 'bottom-end' }}>- <Tooltip content={t('widgets.workflow.graphHistorySnapshots')} ids={{ trigger: historyTriggerId }}>+ <Menu.Root ids={historyIds} positioning={historyPositioning} onSelect={restoreHistoryEntry}>+ <Tooltip content={t('widgets.workflow.graphHistorySnapshots')} ids={historyIds}><Menu.Trigger asChild><IconButtonaria-label={t('widgets.workflow.graphHistorySnapshots')}@@ -184,11 +200,7 @@ export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {{t('widgets.workflow.graphHistorySnapshots')}</Menu.ItemGroupLabel>{restorableHistory.map((entry) => (- <Menu.Item- key={entry.id}- value={entry.id}- onClick={() => dispatch({ snapshotId: entry.id, type: 'restoreProjectGraphSnapshot' })}- >+ <Menu.Item key={entry.id} value={entry.id}><Stack gap="0" minW="0"><Menu.ItemText fontSize="xs" truncate>{entry.label}@@ -209,8 +221,8 @@ export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {};export const WorkflowDialogHost = () => {- const dispatch = useWorkbenchDispatch();- const notify = useNotify();+ const { editGraph, replace } = useProjectGraphCommands();+ const notify = useWorkflowNotifications();const fileInputRef = useRef<HTMLInputElement | null>(null);const addNodeConnection = workflowUiStore.useSelector((snapshot) => snapshot.addNodeConnection);const addNodePosition = workflowUiStore.useSelector((snapshot) => snapshot.addNodePosition);@@ -228,7 +240,7 @@ export const WorkflowDialogHost = () => {lastImportRequestRef.current = importRequestCount;}, [importRequestCount]);- const getInsertPosition = (): XYPosition => {+ const getInsertPosition = useCallback((): XYPosition => {if (addNodePosition) {return addNodePosition;}@@ -240,32 +252,26 @@ export const WorkflowDialogHost = () => {// Slight scatter so repeated inserts do not stack perfectly.return { x: center.x + (Math.random() - 0.5) * 80, y: center.y + (Math.random() - 0.5) * 80 };- };-- const addNode = (template: InvocationTemplate) => {- const node = buildInvocationNode(template, getInsertPosition());-- if (!addNodeConnection) {- dispatch({- action: { node, type: 'addNode' },- type: 'applyProjectGraphAction',- });- return;- }+ }, [addNodePosition]);- if (addNodeConnection.kind === 'source') {- const targetInput = getCompatibleInputTemplate(template, addNodeConnection.sourceType);+ const addNode = useCallback(+ (template: InvocationTemplate) => {+ const node = buildInvocationNode(template, getInsertPosition());- if (!targetInput) {- dispatch({- action: { node, type: 'addNode' },- type: 'applyProjectGraphAction',- });+ if (!addNodeConnection) {+ editGraph({ node, type: 'addNode' });return;}- dispatch({- action: {+ if (addNodeConnection.kind === 'source') {+ const targetInput = getCompatibleInputTemplate(template, addNodeConnection.sourceType);++ if (!targetInput) {+ editGraph({ node, type: 'addNode' });+ return;+ }++ editGraph({edge: {id: createWorkflowId('edge'),source: addNodeConnection.sourceNodeId,@@ -276,24 +282,18 @@ export const WorkflowDialogHost = () => {},node,type: 'addNodeAndEdge',- },- type: 'applyProjectGraphAction',- });- return;- }+ });+ return;+ }- const sourceOutput = getCompatibleOutputTemplate(template, addNodeConnection.targetType);+ const sourceOutput = getCompatibleOutputTemplate(template, addNodeConnection.targetType);- if (!sourceOutput) {- dispatch({- action: { node, type: 'addNode' },- type: 'applyProjectGraphAction',- });- return;- }+ if (!sourceOutput) {+ editGraph({ node, type: 'addNode' });+ return;+ }- dispatch({- action: {+ editGraph({edge: {id: createWorkflowId('edge'),source: node.id,@@ -304,100 +304,93 @@ export const WorkflowDialogHost = () => {},node,type: 'addNodeAndEdge',- },- type: 'applyProjectGraphAction',- });- };+ });+ },+ [addNodeConnection, editGraph, getInsertPosition]+ );- const addNote = () => {- dispatch({- action: { node: buildNotesNode(getInsertPosition()), type: 'addNode' },- type: 'applyProjectGraphAction',- });- };+ const addNote = useCallback(() => {+ editGraph({ node: buildNotesNode(getInsertPosition()), type: 'addNode' });+ }, [editGraph, getInsertPosition]);- const addConnector = () => {+ const addConnector = useCallback(() => {const node = buildConnectorNode(getInsertPosition());if (!addNodeConnection) {- dispatch({- action: { node, type: 'addNode' },- type: 'applyProjectGraphAction',- });+ editGraph({ node, type: 'addNode' });return;}- dispatch({- action: {- edge:- addNodeConnection.kind === 'source'- ? {- id: createWorkflowId('edge'),- source: addNodeConnection.sourceNodeId,- sourceHandle: addNodeConnection.sourceHandle,- target: node.id,- targetHandle: CONNECTOR_INPUT_HANDLE,- type: 'default',- }- : {- id: createWorkflowId('edge'),- source: node.id,- sourceHandle: CONNECTOR_OUTPUT_HANDLE,- target: addNodeConnection.targetNodeId,- targetHandle: addNodeConnection.targetHandle,- type: 'default',- },- node,- type: 'addNodeAndEdge',- },- type: 'applyProjectGraphAction',+ editGraph({+ edge:+ addNodeConnection.kind === 'source'+ ? {+ id: createWorkflowId('edge'),+ source: addNodeConnection.sourceNodeId,+ sourceHandle: addNodeConnection.sourceHandle,+ target: node.id,+ targetHandle: CONNECTOR_INPUT_HANDLE,+ type: 'default',+ }+ : {+ id: createWorkflowId('edge'),+ source: node.id,+ sourceHandle: CONNECTOR_OUTPUT_HANDLE,+ target: addNodeConnection.targetNodeId,+ targetHandle: addNodeConnection.targetHandle,+ type: 'default',+ },+ node,+ type: 'addNodeAndEdge',});- };+ }, [addNodeConnection, editGraph, getInsertPosition]);- const addCurrentImage = () => {- dispatch({- action: { node: buildCurrentImageNode(getInsertPosition()), type: 'addNode' },- type: 'applyProjectGraphAction',- });- };+ const addCurrentImage = useCallback(() => {+ editGraph({ node: buildCurrentImageNode(getInsertPosition()), type: 'addNode' });+ }, [editGraph, getInsertPosition]);- const importFile = (file: File) => {- file- .text()- .then((text) => {- const { document, warnings } = parseWorkflowJson(JSON.parse(text));+ const importFile = useCallback(+ (file: File) => {+ file+ .text()+ .then((text) => {+ const { document, warnings } = parseWorkflowJson(JSON.parse(text));- dispatch({ document, label: `Imported "${file.name}"`, type: 'replaceProjectGraph' });+ replace(document, `Imported "${file.name}"`);- for (const warning of warnings) {- notify.info('Workflow import warning', warning);- }- })- .catch((error: unknown) => {- notify.error(- 'Failed to import workflow',- error instanceof Error ? error.message : 'The file is not a valid workflow JSON.'- );- });- };+ for (const warning of warnings) {+ notify.info('Workflow import warning', warning);+ }+ })+ .catch((error: unknown) => {+ notify.error(+ 'Failed to import workflow',+ error instanceof Error ? error.message : 'The file is not a valid workflow JSON.'+ );+ });+ },+ [notify, replace]+ );+ const handleImportFile = useCallback(+ (event: ChangeEvent<HTMLInputElement>) => {+ const file = event.currentTarget.files?.[0];++ event.currentTarget.value = '';++ if (file) {+ importFile(file);+ }+ },+ [importFile]+ );+ const closeNewWorkflowConfirm = useCallback(() => setNewWorkflowConfirmOpen(false), []);+ const confirmNewWorkflow = useCallback(() => {+ replace(createProjectGraph(createWorkflowId('workflow')), 'New workflow');+ }, [replace]);return (<>- <input- ref={fileInputRef}- accept=".json,application/json"- hidden- type="file"- onChange={(event: ChangeEvent<HTMLInputElement>) => {- const file = event.currentTarget.files?.[0];-- event.currentTarget.value = '';-- if (file) {- importFile(file);- }- }}- />+ <input ref={fileInputRef} accept=".json,application/json" hidden type="file" onChange={handleImportFile} /><AddNodeDialogconnectionFilter={addNodeConnection}isOpen={isAddNodeOpen}@@ -413,14 +406,8 @@ export const WorkflowDialogHost = () => {confirmLabel="New workflow"isOpen={isNewWorkflowConfirmOpen}title="New workflow"- onClose={() => setNewWorkflowConfirmOpen(false)}- onConfirm={() => {- dispatch({- document: createProjectGraph(createWorkflowId('workflow')),- label: 'New workflow',- type: 'replaceProjectGraph',- });- }}+ onClose={closeNewWorkflowConfirm}+ onConfirm={confirmNewWorkflow}/></>);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetView.tsxsimilarity index 75%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetView.tsxindex fb79567d83..0efac795f0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetView.tsx@@ -1,12 +1,11 @@-import type { WidgetViewProps } from '@workbench/types';-import { Box, HStack, Icon, Text } from '@chakra-ui/react';-import { hasPendingWorkflowQueueItem } from '@workbench/widgets/queue/queueViewModel';-import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { WorkflowIcon } from 'lucide-react';+import type { WorkflowWidgetViewProps } from './contracts';+import { WorkflowEditorView } from './editor/WorkflowEditorView';import { WorkflowLinearPanel } from './linear/WorkflowLinearPanel';+import { useWorkflowProjectSelector } from './WorkflowUiContext';/*** The workflow widget's surfaces, per its manifest: the center region is the@@ -17,8 +16,8 @@ import { WorkflowLinearPanel } from './linear/WorkflowLinearPanel';*/const WorkflowStatusBarItem = () => {- const workflowName = useActiveProjectSelector((project) => project.projectGraph.name);- const isRunning = useActiveProjectSelector((project) => hasPendingWorkflowQueueItem(project.queue.items));+ const workflowName = useWorkflowProjectSelector((project) => project.projectGraph.name);+ const isRunning = useWorkflowProjectSelector((project) => project.isWorkflowRunning);return (<HStack gap="1" maxW="14rem" minW="0" px="2">@@ -31,7 +30,7 @@ const WorkflowStatusBarItem = () => {);};-export const WorkflowWidgetView = ({ presentation, region, runtime }: WidgetViewProps) => {+export const WorkflowWidgetView = ({ presentation, region, runtime }: WorkflowWidgetViewProps) => {if (region === 'bottom') {return presentation === 'expanded' ? <WorkflowEditorView runtime={runtime} /> : <WorkflowStatusBarItem />;}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.tsnew file mode 100644index 0000000000..25d87bb40f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts@@ -0,0 +1,102 @@+import type { ProjectGraphAction } from '@features/workflow/core/document';+import type { ProjectGraphState } from '@features/workflow/core/types';++export type WorkflowRegion = 'left' | 'right' | 'bottom' | 'center' | 'dialog' | 'popover';++export interface WorkflowRuntimeApi {+ instanceId: string;+ typeId: string;+ region: WorkflowRegion;+ commands: {+ register(command: { id: string; title: string; handler: () => unknown }): () => void;+ };+ hotkeys: {+ register(hotkey: { id: string; commandId: string; defaultKeys: string[]; title: string }): () => void;+ };+}++export interface WorkflowWidgetViewProps {+ region: WorkflowRegion;+ runtime: WorkflowRuntimeApi;+ presentation?: 'compact' | 'expanded' | 'tooltip';+}++export interface WorkflowWidgetLabelProps {+ region: WorkflowRegion;+ presentation?: 'compact' | 'expanded' | 'tooltip';+}++export interface WorkflowGraphHistoryEntry {+ id: string;+ createdAt: string;+ label: string;+ document?: ProjectGraphState;+}++export interface WorkflowCommands {+ bindLibraryWorkflow(libraryWorkflowId: string): void;+ editGraph(action: ProjectGraphAction): void;+ replace(document: ProjectGraphState, label: string): void;+ redo(): void;+ restoreSnapshot(snapshotId: string): void;+ saveSnapshot(): void;+ undo(): void;+}++export interface WorkflowWidgetCommands {+ open(options: { region: WorkflowRegion; widgetId: string }): void;+ patchValues(widgetId: string, values: Record<string, unknown>): void;+ select(options: { region: WorkflowRegion; widgetId: string }): void;+}++export interface WorkflowModel {+ base: string;+ hash?: string;+ key: string;+ name: string;+ type: string;+}++export interface WorkflowModelSelectProps {+ className?: string;+ filter?: (model: WorkflowModel) => boolean;+ id?: string;+ invalid?: boolean;+ isClearable?: boolean;+ modelTypes: string[];+ onChange(model: WorkflowModel | null): void;+ size?: 'xs' | 'sm' | 'md';+ value: string | null;+}++export interface WorkflowNodeExecutionState {+ status: 'running' | 'completed' | 'failed';+ progress: number | null;+ progressMessage: string | null;+ outputImageUrl: string | null;+ error: string | null;+}++export interface WorkflowPreviewGraph {+ id: string;+ label?: string;+ updatedAt?: string;+ version?: 1;+ nodes: Array<{ id: string; type: string; inputs: Record<string, unknown> }>;+ edges: Array<{+ id: string;+ sourceNodeId: string;+ sourceField: string;+ targetNodeId: string;+ targetField: string;+ }>;+ backendGraph?: unknown;+}++export interface WorkflowPerfSource {+ instanceId: string;+ kind: 'widget';+ projectId: string;+ region: WorkflowRegion;+ typeId: string;+}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsxsimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsxindex 64c10999f0..927ea9a511 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsx@@ -1,11 +1,11 @@-import type { AddNodeConnectionFilter } from '@workbench/widgets/workflow/workflowUiStore';-import type { InvocationTemplate } from '@workbench/workflows/types';+import type { InvocationTemplate } from '@features/workflow/contracts';+import type { AddNodeConnectionFilter } from '@features/workflow/ui/workflowUiStore';import { Badge, Box, Dialog, HStack, Icon, Input, Portal, ScrollArea, Stack, Text } from '@chakra-ui/react';-import { IconButton, Tooltip } from '@workbench/components/ui';-import { registerHotkeyModalLayer } from '@workbench/hotkeys';-import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';-import { getCompatibleInputTemplate, getCompatibleOutputTemplate } from '@workbench/workflows/validation';+import { useInvocationTemplatesSelector } from '@features/workflow/react';+import { useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';+import { getCompatibleInputTemplate, getCompatibleOutputTemplate } from '@features/workflow/utility';+import { IconButton, Tooltip } from '@platform/ui';import { ChevronDownIcon, ChevronsDownUpIcon, ChevronsUpDownIcon, HammerIcon } from 'lucide-react';import {startTransition,@@ -220,6 +220,7 @@ export const AddNodeDialog = ({onAddNote: () => void;onOpenChange: (isOpen: boolean) => void;}) => {+ const { registerModalHotkeyLayer } = useWorkflowUi();const onDialogOpenChange = useCallback((event: { open: boolean }) => {if (!event.open) {@@ -234,8 +235,8 @@ export const AddNodeDialog = ({return;}- return registerHotkeyModalLayer('workflow-add-node');- }, [isOpen]);+ return registerModalHotkeyLayer('workflow-add-node');+ }, [isOpen, registerModalHotkeyLayer]);return (<Dialog.Rootdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/ConnectorFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/ConnectorFlowNode.tsxsimilarity index 90%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/ConnectorFlowNode.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/ConnectorFlowNode.tsxindex 4b2285de66..691f3ec239 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/ConnectorFlowNode.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/ConnectorFlowNode.tsx@@ -1,9 +1,14 @@-import type { FieldType } from '@workbench/workflows/types';+import type { FieldType } from '@features/workflow/contracts';import { Box, Flex } from '@chakra-ui/react';-import { Tooltip } from '@workbench/components/ui';-import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from '@workbench/workflows/connectors';-import { getFieldTypeColor, getFieldTypeLabel, isModelFieldType } from '@workbench/workflows/fields';+import {+ CONNECTOR_INPUT_HANDLE,+ CONNECTOR_OUTPUT_HANDLE,+ getFieldTypeColor,+ getFieldTypeLabel,+ isModelFieldType,+} from '@features/workflow/utility';+import { Tooltip } from '@platform/ui';import { Handle, Position, type NodeProps } from '@xyflow/react';import { memo, useMemo } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsxsimilarity index 79%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsxindex f3bf429901..eff2d15a3a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx@@ -1,12 +1,14 @@-import type { GeneratedImageContract } from '@workbench/types';+import type { GeneratedImageContract } from '@features/gallery';import type { NodeProps } from '@xyflow/react';import { Box, Flex, Text } from '@chakra-ui/react';-import { useProgressImage } from '@workbench/backend/progressImageStore';-import { StreamingImageFrame } from '@workbench/images/StreamingImageFrame';-import { imageUrlToStreamingSource, progressImageToStreamingSource } from '@workbench/images/streamingImageSource';-import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { useProgressImage } from '@features/queue/react';+import { useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';+import { StreamingImageFrame } from '@platform/ui/streaming-image/StreamingImageFrame';+import {+ imageUrlToStreamingSource,+ progressImageToStreamingSource,+} from '@platform/ui/streaming-image/streamingImageSource';import { memo } from 'react';import type { CurrentImageFlowNode as CurrentImageFlowNodeType } from './flowAdapters';@@ -26,7 +28,7 @@ const getLatestImage = (values: Record<string, unknown>): GeneratedImageContract};const CurrentImageFlowNodeComponent = ({ data, selected }: NodeProps<CurrentImageFlowNodeType>) => {- const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));+ const galleryValues = useWorkflowProjectSelector((project) => project.galleryValues);const progressImage = useProgressImage();const node = data.documentNode;const latestImage = getLatestImage(galleryValues);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/EditorToolbar.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsxsimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/EditorToolbar.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsxindex cc65395d4e..f82a1a69d9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/EditorToolbar.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx@@ -1,6 +1,6 @@import { Box, Icon, Popover, Portal, Slider, Stack, Text } from '@chakra-ui/react';-import { IconButton, Toolbar, ToolbarButton, ToolbarSeparator, Tooltip } from '@workbench/components/ui';-import { useWorkbenchReduceMotion } from '@workbench/settings/store';+import { useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';+import { IconButton, Toolbar, ToolbarButton, ToolbarSeparator, Tooltip } from '@platform/ui';import { useReactFlow } from '@xyflow/react';import {BlendIcon,@@ -47,7 +47,7 @@ export const EditorToolbar = ({onToolChange: (tool: EditorTool) => void;}) => {const { fitView, zoomIn, zoomOut } = useReactFlow();- const reduceMotion = useWorkbenchReduceMotion();+ const reduceMotion = useWorkflowUi().preferences.reduceMotion;const opacityTriggerId = useId();const fitViewDuration = reduceMotion ? 0 : 300;const opacityIds = useMemo(() => ({ trigger: opacityTriggerId }), [opacityTriggerId]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsxsimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsxindex 28f70b3f5d..181414e385 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx@@ -4,14 +4,14 @@ import type {FieldOutputTemplate,FieldType,WorkflowInvocationNode,-} from '@workbench/workflows/types';+} from '@features/workflow/contracts';+import type { WorkflowNodeExecutionState as NodeExecutionState } from '@features/workflow/ui/contracts';import { Box, Checkbox, Field, Flex, HStack, Icon, IconButton, Image, Input, Stack, Text } from '@chakra-ui/react';-import { useNodeExecutionState, type NodeExecutionState } from '@workbench/backend/nodeExecutionStore';-import { Tooltip } from '@workbench/components/ui';-import { FieldDescriptionPopover } from '@workbench/widgets/workflow/fields/FieldDescriptionPopover';-import { WorkflowFieldInput } from '@workbench/widgets/workflow/fields/WorkflowFieldInput';-import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { FieldDescriptionPopover } from '@features/workflow/ui/fields/FieldDescriptionPopover';+import { WorkflowFieldInput } from '@features/workflow/ui/fields/WorkflowFieldInput';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';+import { useWorkflowNodeExecutionState } from '@features/workflow/ui/WorkflowUiContext';import {cloneWorkflowFieldDefault,getFieldTypeColor,@@ -21,7 +21,8 @@ import {isExposableField,isWorkflowFieldValueDefault,isModelFieldType,-} from '@workbench/workflows/fields';+} from '@features/workflow/utility';+import { Tooltip } from '@platform/ui';import { Handle, Position, useStore, type NodeProps } from '@xyflow/react';import {ChevronDownIcon,@@ -138,7 +139,7 @@ const NodeProgressStrip = ({ execution }: { execution: NodeExecutionState | null};const NodeTitle = ({ node, title }: { node: WorkflowInvocationNode; title: string }) => {- const dispatch = useWorkbenchDispatch();+ const { editGraph } = useProjectGraphCommands();const [draftLabel, setDraftLabel] = useState<string | null>(null);if (draftLabel !== null) {@@ -150,10 +151,7 @@ const NodeTitle = ({ node, title }: { node: WorkflowInvocationNode; title: strinsize="2xs"value={draftLabel}onBlur={() => {- dispatch({- action: { label: draftLabel.trim(), nodeId: node.id, type: 'setNodeLabel' },- type: 'applyProjectGraphAction',- });+ editGraph({ label: draftLabel.trim(), nodeId: node.id, type: 'setNodeLabel' });setDraftLabel(null);}}onChange={(event: ChangeEvent<HTMLInputElement>) => setDraftLabel(event.currentTarget.value)}@@ -277,7 +275,7 @@ const NodeInfoButton = ({);const NodeFooter = ({ canUseCache, node }: { canUseCache: boolean; node: WorkflowInvocationNode }) => {- const dispatch = useWorkbenchDispatch();+ const { editGraph } = useProjectGraphCommands();return (<Flex@@ -300,10 +298,7 @@ const NodeFooter = ({ canUseCache, node }: { canUseCache: boolean; node: WorkflocolorPalette="accent"size="xs"onCheckedChange={(event) =>- dispatch({- action: { nodeId: node.id, type: 'setNodeUseCache', useCache: event.checked === true },- type: 'applyProjectGraphAction',- })+ editGraph({ nodeId: node.id, type: 'setNodeUseCache', useCache: event.checked === true })}><Checkbox.HiddenInput />@@ -316,10 +311,7 @@ const NodeFooter = ({ canUseCache, node }: { canUseCache: boolean; node: WorkflocolorPalette="accent"size="xs"onCheckedChange={(event) =>- dispatch({- action: { isIntermediate: event.checked !== true, nodeId: node.id, type: 'setNodeIsIntermediate' },- type: 'applyProjectGraphAction',- })+ editGraph({ isIntermediate: event.checked !== true, nodeId: node.id, type: 'setNodeIsIntermediate' })}><Checkbox.HiddenInput />@@ -344,7 +336,7 @@ const InputFieldRow = ({node: WorkflowInvocationNode;template: FieldInputTemplate;}) => {- const dispatch = useWorkbenchDispatch();+ const { editGraph } = useProjectGraphCommands();const instance = node.data.inputs[template.name];const fieldIdentifier = { fieldName: template.name, nodeId: node.id };const showsControl = !isConnected && isDirectInputField(template);@@ -433,14 +425,11 @@ const InputFieldRow = ({title="Reset to default value"variant="ghost"onClick={() =>- dispatch({- action: {- fieldName: template.name,- nodeId: node.id,- type: 'setFieldValue',- value: cloneWorkflowFieldDefault(template),- },- type: 'applyProjectGraphAction',+ editGraph({+ fieldName: template.name,+ nodeId: node.id,+ type: 'setFieldValue',+ value: cloneWorkflowFieldDefault(template),})}>@@ -462,12 +451,7 @@ const InputFieldRow = ({size="2xs"title={isExposed ? 'Remove from Linear UI form' : 'Expose in Linear UI form'}variant="ghost"- onClick={() =>- dispatch({- action: { fieldIdentifier, type: isExposed ? 'unexposeField' : 'exposeField' },- type: 'applyProjectGraphAction',- })- }+ onClick={() => editGraph({ fieldIdentifier, type: isExposed ? 'unexposeField' : 'exposeField' })}><Icon as={isExposed ? PinOffIcon : PinIcon} boxSize="3" /></IconButton>@@ -482,10 +466,7 @@ const InputFieldRow = ({template={template}value={instance?.value}onChange={(value) =>- dispatch({- action: { fieldName: template.name, nodeId: node.id, type: 'setFieldValue', value },- type: 'applyProjectGraphAction',- })+ editGraph({ fieldName: template.name, nodeId: node.id, type: 'setFieldValue', value })}/></Box>@@ -656,11 +637,11 @@ const CompactInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeT};const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeType>) => {- const dispatch = useWorkbenchDispatch();+ const { editGraph } = useProjectGraphCommands();const isZoomedOut = useIsZoomedOut();const node = data.documentNode;const templateView = data.template;- const execution = useNodeExecutionState(node.id);+ const execution = useWorkflowNodeExecutionState(node.id);if (!templateView) {return (@@ -709,12 +690,7 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeclassName="nodrag"size="2xs"variant="ghost"- onClick={() =>- dispatch({- action: { isOpen: !isOpen, nodeId: node.id, type: 'setNodeIsOpen' },- type: 'applyProjectGraphAction',- })- }+ onClick={() => editGraph({ isOpen: !isOpen, nodeId: node.id, type: 'setNodeIsOpen' })}><Icon as={isOpen ? ChevronDownIcon : ChevronRightIcon} boxSize="3.5" /></IconButton>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NodeContextMenu.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsxsimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NodeContextMenu.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsxindex d25bf155b6..69d7900461 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NodeContextMenu.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsx@@ -1,4 +1,4 @@-import type { XYPosition } from '@workbench/workflows/types';+import type { XYPosition } from '@features/workflow/contracts';import { Icon, Menu, Portal } from '@chakra-ui/react';import {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NotesFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NotesFlowNode.tsxsimilarity index 73%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NotesFlowNode.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/NotesFlowNode.tsxindex 8b3681efc2..8fed383fb7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NotesFlowNode.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NotesFlowNode.tsx@@ -1,7 +1,7 @@import type { NodeProps } from '@xyflow/react';import { Box, Input, Textarea } from '@chakra-ui/react';-import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import { memo, useCallback, type ChangeEvent } from 'react';import type { NotesFlowNode as NotesFlowNodeType } from './flowAdapters';@@ -9,23 +9,17 @@ import type { NotesFlowNode as NotesFlowNodeType } from './flowAdapters';import { getWorkflowNodeChromeProps } from './nodeChrome';const NotesFlowNodeComponent = ({ data, selected }: NodeProps<NotesFlowNodeType>) => {- const dispatch = useWorkbenchDispatch();+ const { editGraph } = useProjectGraphCommands();const node = data.documentNode;const onLabelChange = useCallback((event: ChangeEvent<HTMLInputElement>) =>- dispatch({- action: { label: event.currentTarget.value, nodeId: node.id, type: 'setNodeLabel' },- type: 'applyProjectGraphAction',- }),- [dispatch, node.id]+ editGraph({ label: event.currentTarget.value, nodeId: node.id, type: 'setNodeLabel' }),+ [editGraph, node.id]);const onNotesChange = useCallback((event: ChangeEvent<HTMLTextAreaElement>) =>- dispatch({- action: { nodeId: node.id, notes: event.currentTarget.value, type: 'setNodeNotes' },- type: 'applyProjectGraphAction',- }),- [dispatch, node.id]+ editGraph({ nodeId: node.id, notes: event.currentTarget.value, type: 'setNodeNotes' }),+ [editGraph, node.id]);return (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEdge.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEdge.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEdge.test.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEdge.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEdge.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEdge.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEdge.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEdge.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.test.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsxsimilarity index 86%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsxindex d7cc32494c..0cd529e4b3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx@@ -1,27 +1,29 @@-import type { DiagnosticSource } from '@workbench/diagnostics/logger';-/* eslint-disable react/react-compiler */-import type { WidgetRuntimeApi } from '@workbench/types';-import type { ProjectGraphState, XYPosition } from '@workbench/workflows/types';+import type { ProjectGraphState, XYPosition } from '@features/workflow/contracts';+import type { WorkflowPerfSource, WorkflowRuntimeApi } from '@features/workflow/ui/contracts';import { Box, Flex, HStack, Spinner, Stack, Text } from '@chakra-ui/react';-import { useAuthSession } from '@workbench/auth/session';-import { FlowMiniMap, flowThemeCss, getFlowColorMode } from '@workbench/graph-preview';+import { getProjectGraphReadiness } from '@features/workflow/graph';import '@xyflow/react/dist/style.css';-import { markWorkbenchPerf, measureWorkbenchPerf, timeWorkbenchPerf } from '@workbench/performanceMarks';-import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';-import { useModifierHeld } from '@workbench/useModifierHeld';-import { useNotify } from '@workbench/useNotify';-import { setAddNodeOpen } from '@workbench/widgets/workflow/workflowUiStore';-import { shallowEqual, useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { getProjectGraphReadiness } from '@workbench/workflows/buildGraph';-import { buildConnectorNode, createWorkflowId } from '@workbench/workflows/document';-import { createWorkflowGraphIndex } from '@workbench/workflows/graphIndex';-import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSelector } from '@workbench/workflows/templates';+import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSelector } from '@features/workflow/react';+import { FlowMiniMap, flowThemeCss, getFlowColorMode } from '@features/workflow/ui/graph-preview';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import {+ useWorkflowNotifications,+ useWorkflowPreferencesSelector,+ useWorkflowProjectSelector,+ useWorkflowUi,+} from '@features/workflow/ui/WorkflowUiContext';+import { setAddNodeOpen } from '@features/workflow/ui/workflowUiStore';+import {+ buildConnectorNode,+ createWorkflowGraphIndex,+ createWorkflowId,getWorkflowSourceFieldType,getWorkflowTargetFieldType,validateConnection,-} from '@workbench/workflows/validation';+} from '@features/workflow/utility';+import { useModifierHeld } from '@platform/react/useModifierHeld';+import { shallowEqual } from '@platform/state/selectors';import {Background,BackgroundVariant,@@ -133,27 +135,29 @@ const buildWorkflowFlowModel = ({isCompact = false,canUseCache = false,perfSource,+ time,}: {canUseCache?: boolean;document: ProjectGraphState;edgeType: FlowEdgeType;isCompact?: boolean;invocationTemplates?: Parameters<typeof toFlowNodes>[2];- perfSource?: DiagnosticSource;+ perfSource: WorkflowPerfSource;previousEdges?: WorkflowFlowEdge[];previousNodes?: WorkflowFlowNode[];reduceMotion: boolean;selectedNodeIds?: Set<string>;+ time: <T>(name: string, source: WorkflowPerfSource, callback: () => T) => T;}): WorkflowFlowModel => {- const index = timeWorkbenchPerf('workflow:create-graph-index', perfSource, () =>+ const index = time('workflow:create-graph-index', perfSource, () =>createWorkflowGraphIndex(document.nodes, document.edges));- return timeWorkbenchPerf('workflow:build-flow-model', perfSource, () => ({- edges: timeWorkbenchPerf('workflow:to-flow-edges', perfSource, () =>+ return time('workflow:build-flow-model', perfSource, () => ({+ edges: time('workflow:to-flow-edges', perfSource, () =>toFlowEdges(document, previousEdges, edgeType, selectedNodeIds, invocationTemplates, reduceMotion, index)),- nodes: timeWorkbenchPerf('workflow:to-flow-nodes', perfSource, () =>+ nodes: time('workflow:to-flow-nodes', perfSource, () =>toFlowNodes(document, previousNodes, invocationTemplates, index, isCompact, canUseCache)),}));@@ -216,12 +220,13 @@ export const getInitialRenderFlowModel = (model: WorkflowFlowModel, viewport: Vireturn { edges, nodes };};-const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {- const projectGraph = useActiveProjectSelector((project) => project.projectGraph);- const projectId = useActiveProjectSelector((project) => project.id);- const session = useAuthSession();- const dispatch = useWorkbenchDispatch();- const notify = useNotify();+const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {+ const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);+ const projectId = useWorkflowProjectSelector((project) => project.id);+ const ui = useWorkflowUi();+ const { mark: markWorkbenchPerf, measure: measureWorkbenchPerf, time: timeWorkbenchPerf } = ui.performance;+ const { editGraph, redo, undo } = useProjectGraphCommands();+ const notify = useWorkflowNotifications();const {reduceMotion,themeId,@@ -229,7 +234,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {workflowShowMinimap,workflowSnapToGrid,workflowValidateConnections,- } = useWorkbenchPreferenceSelector(+ } = useWorkflowPreferencesSelector((preferences) => ({reduceMotion: preferences.reduceMotion,themeId: preferences.themeId,@@ -243,7 +248,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {const templatesStatus = useInvocationTemplatesSelector((snapshot) => snapshot.status);const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);const invocationTemplates = templatesStatus === 'loaded' ? templates : undefined;- const canUseCache = !session.multiuserEnabled || session.user?.is_admin === true;+ const canUseCache = ui.canUseCache;const edgeType: FlowEdgeType = workflowEdgeStyle === 'square' ? 'step' : 'default';const isLargeGraph = isLargeWorkflowGraph({edgeCount: projectGraph.edges.length,@@ -253,7 +258,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {() => getWorkflowViewportKey(projectId, runtime.instanceId),[projectId, runtime.instanceId]);- const perfSource = useMemo<DiagnosticSource>(+ const perfSource = useMemo<WorkflowPerfSource>(() => ({instanceId: runtime.instanceId,kind: 'widget',@@ -275,6 +280,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {isCompact: isLargeGraph,perfSource,reduceMotion,+ time: timeWorkbenchPerf,}));const flowNodes = flowModel?.nodes ?? EMPTY_FLOW_NODES;@@ -288,7 +294,6 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {const [isMinimapReady, setIsMinimapReady] = useState(!isLargeGraph);const [contextMenu, setContextMenu] = useState<WorkflowContextMenuState | null>(null);const selectedNodeIds = workflowSelectionStore.useSelector((snapshot) => snapshot.selectedNodeIds);- const selectionRequest = workflowSelectionStore.useSelector((snapshot) => snapshot.selectionRequest);const isSnapHeld = useModifierHeld('Control');const hasClipboardNodes = useHasClipboardNodes();const backgroundId = useId().replace(/:/g, '');@@ -345,7 +350,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {const existingNodeIds = projectGraph.nodes.filter((node) => requestedNodeIds.has(node.id)).map((node) => node.id);if (existingNodeIds.length > 0) {- dispatch({ action: { nodeIds: existingNodeIds, type: 'removeNodes' }, type: 'applyProjectGraphAction' });+ editGraph({ nodeIds: existingNodeIds, type: 'removeNodes' });}const removedNodeIds = new Set(existingNodeIds);@@ -358,10 +363,10 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {.map((edge) => edge.id);if (existingEdgeIds.length > 0) {- dispatch({ action: { edgeIds: existingEdgeIds, type: 'removeEdges' }, type: 'applyProjectGraphAction' });+ editGraph({ edgeIds: existingEdgeIds, type: 'removeEdges' });}},- [dispatch, projectGraph.edges, projectGraph.nodes]+ [editGraph, projectGraph.edges, projectGraph.nodes]);const { eraserHandlers, eraserOverlay } = useEraser({enabled: tool === 'eraser',@@ -379,14 +384,9 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {const renderedFlowNodes = renderedFlowModel?.nodes ?? EMPTY_FLOW_NODES;const renderedFlowEdges = renderedFlowModel?.edges ?? EMPTY_FLOW_EDGES;- useEffect(() => {- hasScheduledFullGraphMountRef.current = false;- setIsFullGraphMounted(!isLargeGraph);- }, [isLargeGraph, projectId]);-useEffect(() => {markWorkbenchPerf(perfMountMarkRef.current, perfSource);- }, [perfSource]);+ }, [markWorkbenchPerf, perfSource]);useEffect(() => {if (isPreparing) {@@ -400,7 +400,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {perfSource,perfReadyMarkRef.current);- }, [isPreparing, perfSource]);+ }, [isPreparing, markWorkbenchPerf, measureWorkbenchPerf, perfSource]);useEffect(() => {if (!isFullGraphMounted || !isLargeGraph) {@@ -414,22 +414,10 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {perfSource,'workflow:full-graph-mounted');- }, [isFullGraphMounted, isLargeGraph, perfSource]);+ }, [isFullGraphMounted, isLargeGraph, markWorkbenchPerf, measureWorkbenchPerf, perfSource]);useEffect(() => {- if (!workflowShowMinimap) {- setIsMinimapReady(false);- return undefined;- }-- if (!isLargeGraph) {- setIsMinimapReady(true);- return undefined;- }-- setIsMinimapReady(false);-- if (isPreparing) {+ if (!workflowShowMinimap || !isLargeGraph || isPreparing) {return undefined;}@@ -439,7 +427,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {}, WORKFLOW_MINIMAP_DELAY_MS);return () => window.clearTimeout(timeoutId);- }, [isLargeGraph, isPreparing, perfSource, workflowShowMinimap]);+ }, [isLargeGraph, isPreparing, markWorkbenchPerf, perfSource, workflowShowMinimap]);useEffect(() => {const pendingSelection = pendingSelectionRef.current;@@ -485,6 +473,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {previousNodes: current?.nodes,reduceMotion,selectedNodeIds: nextSelectedNodeIdSet,+ time: timeWorkbenchPerf,});return { ...next, nodes: withNodeSelection(next.nodes, nextSelectedNodeIdSet) };@@ -517,6 +506,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {reduceMotion,selectedNodeIds,shouldDeferInitialBuild,+ timeWorkbenchPerf,]);// Expose the instance to the widget header's actions (outside this provider).@@ -532,9 +522,9 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {};}, [flowInstance]);- // Outside surfaces (the form builder's zoom-to-node) request a selection;- // the editor applies it and brings the nodes into view.- useEffect(() => {+ const applyRequestedSelection = useEffectEvent(() => {+ const selectionRequest = workflowSelectionStore.getSnapshot().selectionRequest;+if (!selectionRequest || !flowInstance) {return;}@@ -546,7 +536,20 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {nodes: selectionRequest.nodeIds.map((id) => ({ id })),});clearNodeSelectionRequest();- }, [flowInstance, reduceMotion, selectNodes, selectionRequest]);+ });++ // Outside surfaces publish selection requests through an external store.+ // Subscribe at that seam so the request does not need an intermediate+ // render-and-effect cycle before it reaches the flow instance.+ useEffect(() => {+ const pendingRequestTimer = window.setTimeout(applyRequestedSelection, 0);+ const unsubscribe = workflowSelectionStore.subscribe(applyRequestedSelection);++ return () => {+ window.clearTimeout(pendingRequestTimer);+ unsubscribe();+ };+ }, [flowInstance]);/** The context-menu node acts alone unless it is part of the current selection. */const getActionNodeIds = useCallback(@@ -581,8 +584,8 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {}pendingSelectionRef.current = nodes.map((node) => node.id);- dispatch({ action: { edges, nodes, type: 'addGraphElements' }, type: 'applyProjectGraphAction' });- }, [dispatch]);+ editGraph({ edges, nodes, type: 'addGraphElements' });+ }, [editGraph]);const duplicateNodes = useCallback((nodeId?: string) => {@@ -593,9 +596,9 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {}pendingSelectionRef.current = nodes.map((node) => node.id);- dispatch({ action: { edges, nodes, type: 'addGraphElements' }, type: 'applyProjectGraphAction' });+ editGraph({ edges, nodes, type: 'addGraphElements' });},- [dispatch, getActionNodeIds, projectGraph]+ [editGraph, getActionNodeIds, projectGraph]);const deleteNodes = useCallback(@@ -603,17 +606,17 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {const nodeIds = getActionNodeIds(nodeId);if (nodeIds.length > 0) {- dispatch({ action: { nodeIds, type: 'removeNodes' }, type: 'applyProjectGraphAction' });+ editGraph({ nodeIds, type: 'removeNodes' });}},- [dispatch, getActionNodeIds]+ [editGraph, getActionNodeIds]);const addConnector = useCallback((position: XYPosition) => {- dispatch({ action: { node: buildConnectorNode(position), type: 'addNode' }, type: 'applyProjectGraphAction' });+ editGraph({ node: buildConnectorNode(position), type: 'addNode' });},- [dispatch]+ [editGraph]);const selectAll = () => {@@ -625,11 +628,11 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {const edgeIds = flowEdges.filter((edge) => edge.selected).map((edge) => edge.id);if (nodeIds.length > 0) {- dispatch({ action: { nodeIds, type: 'removeNodes' }, type: 'applyProjectGraphAction' });+ editGraph({ nodeIds, type: 'removeNodes' });}if (edgeIds.length > 0) {- dispatch({ action: { edgeIds, type: 'removeEdges' }, type: 'applyProjectGraphAction' });+ editGraph({ edgeIds, type: 'removeEdges' });}};@@ -661,11 +664,11 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {return;}case 'workflows.undo': {- dispatch({ type: 'undoProjectChange' });+ undo();return;}case 'workflows.redo': {- dispatch({ type: 'redoProjectChange' });+ redo();return;}}@@ -698,21 +701,18 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {const removedNodeIds = changes.flatMap((change) => (change.type === 'remove' ? [change.id] : []));if (removedNodeIds.length > 0) {- dispatch({ action: { nodeIds: removedNodeIds, type: 'removeNodes' }, type: 'applyProjectGraphAction' });+ editGraph({ nodeIds: removedNodeIds, type: 'removeNodes' });}for (const change of changes) {if (change.type === 'position' && change.dragging === false && change.position) {- dispatch({- action: { nodeId: change.id, position: change.position, type: 'setNodePosition' },- type: 'applyProjectGraphAction',- });+ editGraph({ nodeId: change.id, position: change.position, type: 'setNodePosition' });}}setFlowModel((current) => (current ? { ...current, nodes: applyNodeChanges(changes, current.nodes) } : current));},- [dispatch]+ [editGraph]);const onEdgesChange = useCallback(@@ -720,12 +720,12 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {const removedEdgeIds = changes.flatMap((change) => (change.type === 'remove' ? [change.id] : []));if (removedEdgeIds.length > 0) {- dispatch({ action: { edgeIds: removedEdgeIds, type: 'removeEdges' }, type: 'applyProjectGraphAction' });+ editGraph({ edgeIds: removedEdgeIds, type: 'removeEdges' });}setFlowModel((current) => (current ? { ...current, edges: applyEdgeChanges(changes, current.edges) } : current));},- [dispatch]+ [editGraph]);const isValidConnection: IsValidConnection<WorkflowFlowEdge> = useCallback(@@ -761,22 +761,19 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {return;}- dispatch({- action: {- edge: {- id: createWorkflowId('edge'),- source: connection.source,- sourceHandle: connection.sourceHandle,- target: connection.target,- targetHandle: connection.targetHandle,- type: 'default',- },- type: 'addEdge',+ editGraph({+ edge: {+ id: createWorkflowId('edge'),+ source: connection.source,+ sourceHandle: connection.sourceHandle,+ target: connection.target,+ targetHandle: connection.targetHandle,+ type: 'default',},- type: 'applyProjectGraphAction',+ type: 'addEdge',});},- [dispatch]+ [editGraph]);const onConnectEnd = useCallback<OnConnectEnd>(@@ -989,7 +986,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {}, 0);}},- [isFullGraphMounted, isLargeGraph, perfSource]+ [isFullGraphMounted, isLargeGraph, markWorkbenchPerf, measureWorkbenchPerf, perfSource]);const editorCss = useMemo(@@ -1044,14 +1041,11 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {}, [pasteNodes]);const onContextMenuToggleOpen = useCallback(() => {if (contextMenu?.kind === 'node' && contextMenu.nodeId && contextMenu.isNodeOpen !== null) {- dispatch({- action: { isOpen: !contextMenu.isNodeOpen, nodeId: contextMenu.nodeId, type: 'setNodeIsOpen' },- type: 'applyProjectGraphAction',- });+ editGraph({ isOpen: !contextMenu.isNodeOpen, nodeId: contextMenu.nodeId, type: 'setNodeIsOpen' });}setContextMenu(null);- }, [contextMenu, dispatch]);+ }, [contextMenu, editGraph]);if (isPreparing) {return <WorkflowEditorPreparingState edgeCount={projectGraph.edges.length} nodeCount={projectGraph.nodes.length} />;@@ -1118,7 +1112,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {onNodeOpacityChange={setNodeOpacity}onToolChange={setTool}/>- {workflowShowMinimap && isMinimapReady ? <FlowMiniMap /> : null}+ {workflowShowMinimap && (!isLargeGraph || isMinimapReady) ? <FlowMiniMap /> : null}</ReactFlow>{lassoOverlay}{eraserOverlay}@@ -1138,7 +1132,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {};const ReadinessBanner = () => {- const projectGraph = useActiveProjectSelector((project) => project.projectGraph);+ const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);const templatesStatus = useInvocationTemplatesSelector((snapshot) => snapshot.status);const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);const templatesSnapshot = useMemo(@@ -1183,7 +1177,12 @@ const ReadinessBanner = () => {);};-export const WorkflowEditorView = ({ runtime }: { runtime: WidgetRuntimeApi }) => {+export const WorkflowEditorView = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {+ const flowIdentity = useWorkflowProjectSelector(+ (project) =>+ `${project.id}:${isLargeWorkflowGraph({ edgeCount: project.projectGraph.edges.length, nodeCount: project.projectGraph.nodes.length }) ? 'large' : 'standard'}`+ );+useEffect(() => {ensureInvocationTemplatesLoaded();}, []);@@ -1192,7 +1191,7 @@ export const WorkflowEditorView = ({ runtime }: { runtime: WidgetRuntimeApi }) =<ReactFlowProvider><Flex direction="column" h="full" minH="0" w="full"><Box flex="1" minH="0" position="relative">- <WorkflowFlow runtime={runtime} />+ <WorkflowFlow key={flowIdentity} runtime={runtime} /><ReadinessBanner /></Box></Flex>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.test.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.test.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.test.tsindex 6807415831..5accfd432e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.test.ts@@ -1,6 +1,6 @@-import type { ProjectGraphState, WorkflowEdge, WorkflowInvocationNode } from '@workbench/workflows/types';+import type { ProjectGraphState, WorkflowEdge, WorkflowInvocationNode } from '@features/workflow/contracts';-import { createProjectGraph } from '@workbench/workflows/document';+import { createProjectGraph } from '@features/workflow/utility';import { describe, expect, it } from 'vitest';import { buildDuplicateElements, buildPasteElements, copyNodesToClipboard, hasClipboardNodes } from './clipboard';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.tssimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.tsindex fb85dc4f72..60cdd490db 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.ts@@ -1,7 +1,7 @@-import type { ProjectGraphState, WorkflowEdge, WorkflowNode, XYPosition } from '@workbench/workflows/types';+import type { ProjectGraphState, WorkflowEdge, WorkflowNode, XYPosition } from '@features/workflow/contracts';-import { createExternalStore } from '@workbench/externalStore';-import { createWorkflowId } from '@workbench/workflows/document';+import { createWorkflowId } from '@features/workflow/utility';+import { createExternalStore } from '@platform/state/externalStore';/*** Session-lived clipboard for workflow nodes. Copies hold deep clones of thediff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.test.tssimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.test.tsindex 3616f91ae3..a2c01cfbb6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.test.ts@@ -6,10 +6,14 @@ import type {WorkflowConnectorNode,WorkflowEdge,WorkflowInvocationNode,-} from '@workbench/workflows/types';--import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from '@workbench/workflows/connectors';-import { buildCurrentImageNode, createProjectGraph } from '@workbench/workflows/document';+} from '@features/workflow/contracts';++import {+ buildCurrentImageNode,+ CONNECTOR_INPUT_HANDLE,+ CONNECTOR_OUTPUT_HANDLE,+ createProjectGraph,+} from '@features/workflow/utility';import { describe, expect, it } from 'vitest';import { getWorkflowEdgeData, toFlowEdges, toFlowNodes, withNodeSelection } from './flowAdapters';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.tsindex d6eb1f955f..13d2084f1f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.ts@@ -10,19 +10,22 @@ import type {WorkflowEdge,WorkflowInvocationNode,WorkflowNotesNode,-} from '@workbench/workflows/types';+} from '@features/workflow/contracts';import type { Edge as FlowEdge, Node as FlowNode } from '@xyflow/react';import type { CSSProperties } from 'react';-import { isExecutableInvocationType } from '@workbench/workflows/buildGraph';+import { isExecutableInvocationType } from '@features/workflow/graph';import {CONNECTOR_INPUT_HANDLE,CONNECTOR_OUTPUT_HANDLE,+ createWorkflowGraphIndex,+ getFieldTypeColor,+ getFieldTypeLabel,getResolvedWorkflowEdgesIndexed,-} from '@workbench/workflows/connectors';-import { getFieldTypeColor, getFieldTypeLabel } from '@workbench/workflows/fields';-import { createWorkflowGraphIndex, type WorkflowGraphIndex } from '@workbench/workflows/graphIndex';-import { getWorkflowSourceFieldType, getWorkflowTargetFieldType } from '@workbench/workflows/validation';+ getWorkflowSourceFieldType,+ getWorkflowTargetFieldType,+ type WorkflowGraphIndex,+} from '@features/workflow/utility';/*** Adapters between the project graph document and xyflow's node/edge state.diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowInstanceStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowInstanceStore.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.tsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/handleTooltip.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/handleTooltip.test.tssimilarity index 92%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/handleTooltip.test.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/handleTooltip.test.tsindex 0ad8d6c1e1..625edb6973 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/handleTooltip.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/handleTooltip.test.ts@@ -1,4 +1,4 @@-import type { FieldType } from '@workbench/workflows/types';+import type { FieldType } from '@features/workflow/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/handleTooltip.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/handleTooltip.tssimilarity index 64%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/handleTooltip.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/handleTooltip.tsindex 2ca6114539..deecc52267 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/handleTooltip.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/handleTooltip.ts@@ -1,6 +1,6 @@-import type { FieldType } from '@workbench/workflows/types';+import type { FieldType } from '@features/workflow/contracts';-import { getFieldTypeLabel } from '@workbench/workflows/fields';+import { getFieldTypeLabel } from '@features/workflow/utility';export const getHandleTypeTooltip = (type: FieldType | null, fallback = 'Any'): string => {if (!type) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/nodeChrome.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/nodeChrome.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/nodeChrome.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/nodeChrome.tsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/performanceConstants.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/performanceConstants.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/performanceConstants.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/performanceConstants.tsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/selectionStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/selectionStore.tssimilarity index 96%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/selectionStore.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/selectionStore.tsindex f570993dad..a3b40ebda2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/selectionStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/selectionStore.ts@@ -1,4 +1,4 @@-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';/*** Session-lived editor selection, shared with surfaces outside the flow (thediff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useEraser.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/useEraser.tsxsimilarity index 99%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useEraser.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/useEraser.tsxindex daaa79ad11..6f64470598 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useEraser.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/useEraser.tsx@@ -1,4 +1,4 @@-import type { XYPosition } from '@workbench/workflows/types';+import type { XYPosition } from '@features/workflow/contracts';import { Box } from '@chakra-ui/react';import {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useLasso.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/useLasso.tsxsimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useLasso.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/useLasso.tsxindex 9694c2d70e..5edccfa144 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useLasso.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/useLasso.tsx@@ -1,4 +1,4 @@-import type { XYPosition } from '@workbench/workflows/types';+import type { XYPosition } from '@features/workflow/contracts';import { Box } from '@chakra-ui/react';import {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/workflowViewportStore.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/workflowViewportStore.test.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/workflowViewportStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.tssimilarity index 79%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/workflowViewportStore.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.tsindex b182028331..d8f6941cf9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/workflowViewportStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.ts@@ -1,10 +1,8 @@-import type { WidgetInstanceId } from '@workbench/types';import type { Viewport } from '@xyflow/react';const viewports = new Map<string, Viewport>();-export const getWorkflowViewportKey = (projectId: string, instanceId: WidgetInstanceId): string =>- `${projectId}:${instanceId}`;+export const getWorkflowViewportKey = (projectId: string, instanceId: string): string => `${projectId}:${instanceId}`;export const getWorkflowViewport = (key: string): Viewport | null => {const viewport = viewports.get(key);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/FieldDescriptionPopover.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/FieldDescriptionPopover.tsxsimilarity index 86%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/FieldDescriptionPopover.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/fields/FieldDescriptionPopover.tsxindex cafe861b79..6470b0e438 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/FieldDescriptionPopover.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/FieldDescriptionPopover.tsx@@ -1,7 +1,7 @@import type { ChangeEvent } from 'react';import { Icon, Popover, Portal, Stack, Text, Textarea, IconButton } from '@chakra-ui/react';-import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import { FileTextIcon } from 'lucide-react';import { useCallback } from 'react';@@ -23,19 +23,16 @@ export const FieldDescriptionPopover = ({nodeId: string;templateDescription: string;}) => {- const dispatch = useWorkbenchDispatch();+ const { editGraph } = useProjectGraphCommands();const onDescriptionChange = useCallback((event: ChangeEvent<HTMLTextAreaElement>) =>- dispatch({- action: {- description: event.currentTarget.value,- fieldName,- nodeId,- type: 'setFieldDescription',- },- type: 'applyProjectGraphAction',+ editGraph({+ description: event.currentTarget.value,+ fieldName,+ nodeId,+ type: 'setFieldDescription',}),- [dispatch, fieldName, nodeId]+ [editGraph, fieldName, nodeId]);return (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxsimilarity index 92%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex 420f43a92c..1414793d88 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -1,14 +1,14 @@-import type { ModelConfig, ModelTaxonomyType } from '@workbench/models/types';-import type { GeneratedImageContract } from '@workbench/types';-import type { FieldInputTemplate } from '@workbench/workflows/types';+import type { FieldInputTemplate } from '@features/workflow/contracts';+import type { WorkflowModel as ModelConfig } from '@features/workflow/ui/contracts';import { HStack, Input, NativeSelect, Switch, Text, Textarea } from '@chakra-ui/react';-import { Button, Combobox } from '@workbench/components/ui';-import { listGalleryBoards, type GalleryBoard } from '@workbench/gallery/api';-import { SCHEDULER_OPTIONS } from '@workbench/generation/baseGenerationPolicies';-import { ModelSelect } from '@workbench/models/components';-import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { galleryDestinations, type GalleryBoard, type GeneratedImageContract } from '@features/gallery';+import { SCHEDULER_OPTIONS } from '@features/generation/settings';+import {+ WorkflowModelSelect as ModelSelect,+ useWorkflowProjectSelector,+} from '@features/workflow/ui/WorkflowUiContext';+import { Button, Combobox } from '@platform/ui';import { useCallback, useEffect, useMemo, useState, type ChangeEvent } from 'react';/**@@ -212,12 +212,12 @@ const EnumInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInpu);};-const DEFAULT_MODEL_TYPES: ModelTaxonomyType[] = ['main', 'vae', 'lora', 'controlnet', 't2i_adapter', 'ip_adapter'];+const DEFAULT_MODEL_TYPES = ['main', 'vae', 'lora', 'controlnet', 't2i_adapter', 'ip_adapter'];const ModelIdentifierInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {const selectedKey =typeof (value as { key?: unknown } | null)?.key === 'string' ? (value as { key: string }).key : null;- const modelTypes = (template.uiModelType as ModelTaxonomyType[] | null) ?? DEFAULT_MODEL_TYPES;+ const modelTypes = template.uiModelType ?? DEFAULT_MODEL_TYPES;const allowedBases = template.uiModelBase;const filter = useCallback((model: ModelConfig) => (allowedBases ? allowedBases.includes(model.base) : true),@@ -263,7 +263,8 @@ let boardOptionsRequest: Promise<GalleryBoard[]> | null = null;const getBoardOptions = (): Promise<GalleryBoard[]> => {if (!boardOptionsRequest) {- boardOptionsRequest = listGalleryBoards()+ boardOptionsRequest = galleryDestinations+ .list().then((loadedBoards) => loadedBoards.filter((board) => board.kind === 'board')).catch((error: unknown) => {boardOptionsRequest = null;@@ -327,8 +328,8 @@ const BoardInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInp};const ImageInput = ({ invalid, onChange, value }: WorkflowFieldInputProps) => {- const gallerySelection = useActiveProjectSelector(- (project) => getProjectWidgetValues(project, 'gallery').selectedImage as GeneratedImageContract | null | undefined+ const gallerySelection = useWorkflowProjectSelector(+ (project) => project.galleryValues.selectedImage as GeneratedImageContract | null | undefined);const imageName =typeof (value as { image_name?: unknown } | null)?.image_name === 'string'diff --git a/invokeai/frontend/webv2/src/workbench/graph-preview/FlowMiniMap.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/FlowMiniMap.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/graph-preview/FlowMiniMap.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/FlowMiniMap.tsxdiff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsxnew file mode 100644index 0000000000..9394368ed4--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx@@ -0,0 +1,121 @@+import type { XYPosition } from '@features/workflow/contracts';+import type { WorkflowPreviewGraph } from '@features/workflow/ui/contracts';++import { Box, Dialog, Portal, SegmentGroup, Text } from '@chakra-ui/react';+import { useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';+import { Button, JsonPreview } from '@platform/ui';+import { useCallback, useMemo, useState, type ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { GraphPreviewFlow } from './GraphPreviewFlow';++interface GraphPreviewDialogProps {+ graph: WorkflowPreviewGraph | null;+ graphId: string;+ isOpen: boolean;+ /** Editor positions keyed by node id, when the graph mirrors an editable document. */+ positionHints?: Record<string, XYPosition>;+ sourceId?: string;+ title: string;+ onOpenChange: (isOpen: boolean) => void;+}++type PreviewMode = 'nodes' | 'json';++const modeItems = [+ { labelKey: 'graphPreview.nodes', value: 'nodes' },+ { labelKey: 'common.json', value: 'json' },+];++const PreviewPane = ({ children }: { children: ReactNode }) => (+ <Box flex="1" h="full" minH="0" minW="0" w="full" rounded="md" borderWidth={1} overflow="hidden">+ {children}+ </Box>+);++export const GraphPreviewDialog = ({+ graph,+ graphId,+ isOpen,+ positionHints,+ sourceId,+ title,+ onOpenChange,+}: GraphPreviewDialogProps) => {+ const { t } = useTranslation();+ const { graphPreview } = useWorkflowUi();+ const [mode, setMode] = useState<PreviewMode>('nodes');+ const dialogRoute = graphPreview.getRoute(sourceId);+ const canInvoke = dialogRoute?.canInvoke === true;++ const handleOpenChange = useCallback((event: { open: boolean }) => onOpenChange(event.open), [onOpenChange]);+ const handleModeChange = useCallback(+ (event: { value: string | null }) => setMode(event.value === 'json' ? 'json' : 'nodes'),+ []+ );+ const closeDialog = useCallback(() => onOpenChange(false), [onOpenChange]);+ const invokeRoute = useCallback(() => {+ void graphPreview.invoke(sourceId).then((submitted) => {+ if (submitted) {+ onOpenChange(false);+ }+ });+ }, [graphPreview, onOpenChange, sourceId]);+ const jsonLabel = useMemo(() => t('graphPreview.graphJsonLabel', { title }), [t, title]);++ return (+ <Dialog.Root open={isOpen} size="xl" onOpenChange={handleOpenChange}>+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content h="62vh" maxH="62vh">+ <Dialog.Header alignItems="center" flexDirection="row" justifyContent="space-between">+ <Dialog.Title>{t('graphPreview.title', { title })}</Dialog.Title>+ <SegmentGroup.Root size="xs" value={mode} onValueChange={handleModeChange}>+ <SegmentGroup.Indicator />+ {modeItems.map((item) => (+ <SegmentGroup.Item key={item.value} value={item.value}>+ <SegmentGroup.ItemHiddenInput />+ <SegmentGroup.ItemText>{t(item.labelKey)}</SegmentGroup.ItemText>+ </SegmentGroup.Item>+ ))}+ </SegmentGroup.Root>+ </Dialog.Header>+ <Dialog.Body display="flex" flex="1" flexDirection="column" minH="0">+ {!graph ? (+ <Text color="fg.muted" fontSize="sm">+ {t('graphPreview.noCompiledGraph', { graphId })}+ </Text>+ ) : mode === 'nodes' ? (+ <PreviewPane>+ <GraphPreviewFlow graph={graph} positionHints={positionHints} />+ </PreviewPane>+ ) : (+ <PreviewPane>+ <JsonPreview h="full" label={jsonLabel} maxH="100%" value={graph} />+ </PreviewPane>+ )}+ </Dialog.Body>+ <Dialog.Footer>+ {dialogRoute ? (+ <Button+ aria-disabled={!canInvoke}+ cursor={canInvoke ? undefined : 'not-allowed'}+ opacity={canInvoke ? undefined : 0.6}+ size="sm"+ title={dialogRoute.validationMessage}+ onClick={invokeRoute}+ >+ {t('graphPreview.invokeRoute', { route: dialogRoute.label })}+ </Button>+ ) : null}+ <Button size="sm" variant="outline" onClick={closeDialog}>+ {t('common.close')}+ </Button>+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewFlow.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsxsimilarity index 89%rename from invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewFlow.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsxindex 2ab939b345..47fe78c1c4 100644--- a/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewFlow.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx@@ -1,10 +1,10 @@-import type { GraphContract } from '@workbench/types';+import type { WorkflowPreviewGraph } from '@features/workflow/ui/contracts';import { Badge, Box, Stack, Text } from '@chakra-ui/react';-import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';+import { isInvocationNode, type ProjectGraphState, type XYPosition } from '@features/workflow/contracts';import '@xyflow/react/dist/style.css';-import { getResolvedWorkflowEdges } from '@workbench/workflows/connectors';-import { isInvocationNode, type ProjectGraphState, type XYPosition } from '@workbench/workflows/types';+import { useWorkflowPreferencesSelector } from '@features/workflow/ui/WorkflowUiContext';+import { getResolvedWorkflowEdges } from '@features/workflow/utility';import {Background,BackgroundVariant,@@ -38,7 +38,7 @@ type PreviewFlowNode = FlowNode<{ inputCount: number; nodeId: string; nodeType:export const documentToPreviewGraph = (document: ProjectGraphState,fallbackLabel: string-): { graph: GraphContract; positionHints: Record<string, XYPosition> } => {+): { graph: WorkflowPreviewGraph; positionHints: Record<string, XYPosition> } => {const invocationNodes = document.nodes.filter(isInvocationNode);const invocationNodeIds = new Set(invocationNodes.map((node) => node.id));@@ -95,7 +95,7 @@ const PreviewNode = ({ data }: NodeProps<PreviewFlowNode>) => {const nodeTypes: NodeTypes = { preview: PreviewNode };/** Longest-path-from-roots depth per node; cycle members settle at their first depth. */-const getNodeDepths = (graph: GraphContract): Map<string, number> => {+const getNodeDepths = (graph: WorkflowPreviewGraph): Map<string, number> => {const depths = new Map<string, number>();const incoming = new Map<string, string[]>();@@ -131,7 +131,7 @@ const getNodeDepths = (graph: GraphContract): Map<string, number> => {return depths;};-const toPreviewNodes = (graph: GraphContract, positionHints?: Record<string, XYPosition>): PreviewFlowNode[] => {+const toPreviewNodes = (graph: WorkflowPreviewGraph, positionHints?: Record<string, XYPosition>): PreviewFlowNode[] => {const depths = getNodeDepths(graph);const rowsPerDepth = new Map<number, number>();@@ -161,7 +161,7 @@ const toPreviewNodes = (graph: GraphContract, positionHints?: Record<string, XYP});};-const toPreviewEdges = (graph: GraphContract): FlowEdge[] =>+const toPreviewEdges = (graph: WorkflowPreviewGraph): FlowEdge[] =>graph.edges.map((edge) => ({id: edge.id,source: edge.sourceNodeId,@@ -173,10 +173,10 @@ export const GraphPreviewFlow = ({graph,positionHints,}: {- graph: GraphContract;+ graph: WorkflowPreviewGraph;positionHints?: Record<string, XYPosition>;}) => {- const themeId = useWorkbenchPreferenceSelector((preferences) => preferences.themeId);+ const themeId = useWorkflowPreferencesSelector((preferences) => preferences.themeId);const backgroundId = useId().replace(/:/g, '');const nodes = useMemo(() => toPreviewNodes(graph, positionHints), [graph, positionHints]);const edges = useMemo(() => toPreviewEdges(graph), [graph]);diff --git a/invokeai/frontend/webv2/src/workbench/graph-preview/flowTheme.ts b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/flowTheme.tssimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/graph-preview/flowTheme.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/flowTheme.tsindex 4013aa234f..15c9eb1eb0 100644--- a/invokeai/frontend/webv2/src/workbench/graph-preview/flowTheme.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/flowTheme.ts@@ -1,5 +1,5 @@import type { SystemStyleObject } from '@chakra-ui/react';-import type { WorkbenchThemeId } from '@workbench/types';+import type { WorkbenchThemeId } from '@theme/themes';import { THEMES_BY_ID } from '@theme/themes';diff --git a/invokeai/frontend/webv2/src/workbench/graph-preview/index.ts b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/index.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/graph-preview/index.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/index.tsdiff --git a/invokeai/frontend/webv2/src/features/workflow/ui/implementation.ts b/invokeai/frontend/webv2/src/features/workflow/ui/implementation.tsnew file mode 100644index 0000000000..b354d851f9--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/implementation.ts@@ -0,0 +1,15 @@+import {+ WorkflowDialogHost,+ WorkflowHeaderActions,+ WorkflowMenuItems,+ WorkflowWidgetLabel,+} from './WorkflowWidgetChrome';+import { WorkflowWidgetView } from './WorkflowWidgetView';++export const widgetImplementation = {+ headerActions: WorkflowHeaderActions,+ headerLabel: WorkflowWidgetLabel,+ headerMenu: WorkflowMenuItems,+ host: WorkflowDialogHost,+ view: WorkflowWidgetView,+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsxsimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/library/WorkflowLibraryDialog.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsxindex d187dc9f27..4def7c8357 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/library/WorkflowLibraryDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx@@ -1,27 +1,25 @@/* eslint-disable react/react-compiler, react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */-import type { ProjectGraphState } from '@workbench/workflows/types';+import type { ProjectGraphState } from '@features/workflow/contracts';import { Box, Dialog, HStack, Input, Portal, SegmentGroup, Stack, Tabs, Text } from '@chakra-ui/react';-import { getApiErrorMessage } from '@workbench/backend/http';-import { Button, CloseButton, ConfirmDialog, JsonPreview, Scrollable } from '@workbench/components/ui';-import { documentToPreviewGraph, GraphPreviewFlow } from '@workbench/graph-preview';-import { useNotify } from '@workbench/useNotify';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';import {createLibraryWorkflow,deleteLibraryWorkflow,- touchLibraryWorkflowOpenedAt,- updateLibraryWorkflow,- type WorkflowLibraryCategory,- type WorkflowLibraryListItem,-} from '@workbench/workflows/api';-import {getCachedWorkflowPage,getLibraryWorkflowCached,invalidateWorkflowLibraryCache,listLibraryWorkflowsCached,-} from '@workbench/workflows/libraryCache';-import { parseWorkflowJson, serializeWorkflowJson } from '@workbench/workflows/workflowJson';+ touchLibraryWorkflowOpenedAt,+ updateLibraryWorkflow,+ type WorkflowLibraryCategory,+ type WorkflowLibraryListItem,+} from '@features/workflow/queries';+import { documentToPreviewGraph, GraphPreviewFlow } from '@features/workflow/ui/graph-preview';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';+import { useWorkflowNotifications, useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';+import { parseWorkflowJson, serializeWorkflowJson } from '@features/workflow/utility';+import { getApiErrorMessage } from '@platform/transport/http';+import { Button, CloseButton, ConfirmDialog, JsonPreview, Scrollable } from '@platform/ui';import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';import { useTranslation } from 'react-i18next';@@ -102,9 +100,9 @@ export const WorkflowLibraryDialog = ({isOpen: boolean;onOpenChange: (isOpen: boolean) => void;}) => {- const projectGraph = useActiveProjectSelector((project) => project.projectGraph);- const dispatch = useWorkbenchDispatch();- const notify = useNotify();+ const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);+ const { bindLibraryWorkflow, replace } = useProjectGraphCommands();+ const notify = useWorkflowNotifications();const [category, setCategory] = useState<WorkflowLibraryCategory>('user');const [searchTerm, setSearchTerm] = useState('');const [items, setItems] = useState<WorkflowLibraryListItem[]>([]);@@ -184,7 +182,7 @@ export const WorkflowLibraryDialog = ({};const applyLoadedWorkflow = (item: WorkflowLibraryListItem, document: ProjectGraphState, warnings: string[]) => {- dispatch({ document, label: `Loaded "${item.name}" from library`, type: 'replaceProjectGraph' });+ replace(document, `Loaded "${item.name}" from library`);for (const warning of warnings) {notify.info('Workflow load warning', warning);@@ -236,7 +234,7 @@ export const WorkflowLibraryDialog = ({} else {const workflowId = await createLibraryWorkflow(serialized);- dispatch({ libraryWorkflowId: workflowId, type: 'setProjectGraphLibraryBinding' });+ bindLibraryWorkflow(workflowId);notify.success('Workflow saved', `Saved "${projectGraph.name || 'Untitled Workflow'}" to the library.`);}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsxsimilarity index 84%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsxindex ae6ab12b94..a79db2e158 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx@@ -1,23 +1,21 @@-/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */-import type {- ContainerFormElement,- InvocationTemplates,- NodeFieldFormElement,- ProjectGraphState,- WorkflowFormElement,-} from '@workbench/workflows/types';-import { Box, HStack, Icon, Input, Menu, Portal, Separator, Stack, Text, Textarea } from '@chakra-ui/react';-import { Button, IconButton } from '@workbench/components/ui';-import { getWorkflowNodeChromeProps } from '@workbench/widgets/workflow/editor/nodeChrome';-import { requestNodeSelection, workflowSelectionStore } from '@workbench/widgets/workflow/editor/selectionStore';-import { FieldDescriptionPopover } from '@workbench/widgets/workflow/fields/FieldDescriptionPopover';-import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { getResolvedWorkflowEdges } from '@workbench/workflows/connectors';-import { getFormChildren } from '@workbench/workflows/document';-import { getWorkflowFieldInvalidReason } from '@workbench/workflows/fields';-import { useInvocationTemplatesSelector, type InvocationTemplatesSnapshot } from '@workbench/workflows/templates';-import { isInvocationNode } from '@workbench/workflows/types';+/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */+import {+ isInvocationNode,+ type ContainerFormElement,+ type InvocationTemplates,+ type NodeFieldFormElement,+ type ProjectGraphState,+ type WorkflowFormElement,+} from '@features/workflow/contracts';+import { useInvocationTemplatesSelector, type InvocationTemplatesSnapshot } from '@features/workflow/react';+import { getWorkflowNodeChromeProps } from '@features/workflow/ui/editor/nodeChrome';+import { requestNodeSelection, workflowSelectionStore } from '@features/workflow/ui/editor/selectionStore';+import { FieldDescriptionPopover } from '@features/workflow/ui/fields/FieldDescriptionPopover';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';+import { useWorkflowHostCommands } from '@features/workflow/ui/WorkflowUiContext';+import { getFormChildren, getResolvedWorkflowEdges, getWorkflowFieldInvalidReason } from '@features/workflow/utility';+import { Button, IconButton } from '@platform/ui';import {Columns2Icon,CrosshairIcon,@@ -77,7 +75,7 @@ const BuilderCard = ({parentId: string;title: string;}) => {- const dispatch = useWorkbenchDispatch();+ const { editGraph } = useProjectGraphCommands();const { draggingElementId, setDraggingElementId } = use(BuilderDndContext);const [isDragArmed, setIsDragArmed] = useState(false);const [dropEdge, setDropEdge] = useState<DropEdge | null>(null);@@ -103,14 +101,11 @@ const BuilderCard = ({event.preventDefault();event.stopPropagation();- dispatch({- action: {- elementId: draggingElementId,- index: dropEdge === 'above' ? index : index + 1,- parentId,- type: 'moveFormElementTo',- },- type: 'applyProjectGraphAction',+ editGraph({+ elementId: draggingElementId,+ index: dropEdge === 'above' ? index : index + 1,+ parentId,+ type: 'moveFormElementTo',});setDropEdge(null);};@@ -179,12 +174,7 @@ const BuilderCard = ({aria-label="Remove from form"size="2xs"variant="ghost"- onClick={() =>- dispatch({- action: { elementId: element.id, type: 'removeFormElement' },- type: 'applyProjectGraphAction',- })- }+ onClick={() => editGraph({ elementId: element.id, type: 'removeFormElement' })}><Icon as={XIcon} boxSize="3" /></IconButton>@@ -200,7 +190,7 @@ const BuilderCard = ({/** Drop zone covering a container's body, appending at the end. Doubles as the empty-container hint. */const ContainerDropZone = ({ container, isEmpty }: { container: ContainerFormElement; isEmpty: boolean }) => {- const dispatch = useWorkbenchDispatch();+ const { editGraph } = useProjectGraphCommands();const { draggingElementId } = use(BuilderDndContext);const [isActive, setIsActive] = useState(false);const canDrop = draggingElementId !== null && draggingElementId !== container.id;@@ -237,14 +227,11 @@ const ContainerDropZone = ({ container, isEmpty }: { container: ContainerFormEleevent.preventDefault();event.stopPropagation();- dispatch({- action: {- elementId: draggingElementId,- index: container.data.children.length,- parentId: container.id,- type: 'moveFormElementTo',- },- type: 'applyProjectGraphAction',+ editGraph({+ elementId: draggingElementId,+ index: container.data.children.length,+ parentId: container.id,+ type: 'moveFormElementTo',});setIsActive(false);}}@@ -295,7 +282,8 @@ const BuilderElement = ({projectGraph: ProjectGraphState;selectedNodeIds: Set<string>;}) => {- const dispatch = useWorkbenchDispatch();+ const { widgets } = useWorkflowHostCommands();+ const { editGraph } = useProjectGraphCommands();switch (element.type) {case 'container': {@@ -311,10 +299,7 @@ const BuilderElement = ({title={isRow ? 'Switch to column layout' : 'Switch to row layout'}variant="ghost"onClick={() =>- dispatch({- action: { elementId: element.id, layout: isRow ? 'column' : 'row', type: 'setContainerLayout' },- type: 'applyProjectGraphAction',- })+ editGraph({ elementId: element.id, layout: isRow ? 'column' : 'row', type: 'setContainerLayout' })}><Icon as={isRow ? Rows2Icon : Columns2Icon} boxSize="3" />@@ -354,7 +339,7 @@ const BuilderElement = ({title="Zoom to node in the Workflow editor"variant="ghost"onClick={() => {- dispatch({ region: 'center', type: 'selectRegionWidget', widgetId: 'workflow' });+ widgets.select({ region: 'center', widgetId: 'workflow' });requestNodeSelection([element.data.fieldIdentifier.nodeId]);}}>@@ -368,13 +353,10 @@ const BuilderElement = ({title={element.data.showDescription ? 'Hide field description' : 'Show field description'}variant="ghost"onClick={() =>- dispatch({- action: {- elementId: element.id,- showDescription: !element.data.showDescription,- type: 'setNodeFieldShowDescription',- },- type: 'applyProjectGraphAction',+ editGraph({+ elementId: element.id,+ showDescription: !element.data.showDescription,+ type: 'setNodeFieldShowDescription',})}>@@ -405,10 +387,7 @@ const BuilderElement = ({value={element.data.content}variant="flushed"onChange={(event: ChangeEvent<HTMLInputElement>) =>- dispatch({- action: { content: event.currentTarget.value, elementId: element.id, type: 'setFormElementContent' },- type: 'applyProjectGraphAction',- })+ editGraph({ content: event.currentTarget.value, elementId: element.id, type: 'setFormElementContent' })}/></BuilderCard>@@ -428,10 +407,7 @@ const BuilderElement = ({value={element.data.content}variant="flushed"onChange={(event: ChangeEvent<HTMLTextAreaElement>) =>- dispatch({- action: { content: event.currentTarget.value, elementId: element.id, type: 'setFormElementContent' },- type: 'applyProjectGraphAction',- })+ editGraph({ content: event.currentTarget.value, elementId: element.id, type: 'setFormElementContent' })}/></BuilderCard>@@ -448,9 +424,9 @@ const BuilderElement = ({};const AddElementMenu = () => {- const dispatch = useWorkbenchDispatch();+ const { editGraph } = useProjectGraphCommands();const add = (elementType: 'divider' | 'heading' | 'text' | 'container', layout?: 'row' | 'column') =>- dispatch({ action: { elementType, layout, type: 'addFormElement' }, type: 'applyProjectGraphAction' });+ editGraph({ elementType, layout, type: 'addFormElement' });return (<Menu.Root positioning={{ placement: 'bottom-start' }}>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/LinearFormView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/LinearFormView.tsxsimilarity index 83%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/LinearFormView.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/linear/LinearFormView.tsxindex 2ad8f9c5c2..9d253a68c4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/LinearFormView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/LinearFormView.tsx@@ -1,9 +1,9 @@-import type { ProjectGraphState, WorkflowFormElement } from '@workbench/workflows/types';+import type { ProjectGraphState, WorkflowFormElement } from '@features/workflow/contracts';import { Separator, Stack, Text } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';-import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { getFormChildren } from '@workbench/workflows/document';+import { useWorkflowHostCommands } from '@features/workflow/ui/WorkflowUiContext';+import { getFormChildren } from '@features/workflow/utility';+import { Button } from '@platform/ui';import { useCallback } from 'react';import { NodeFieldControl } from './NodeFieldControl';@@ -43,11 +43,11 @@ const ViewElement = ({ element, projectGraph }: { element: WorkflowFormElement;};export const LinearFormView = ({ projectGraph }: { projectGraph: ProjectGraphState }) => {- const dispatch = useWorkbenchDispatch();+ const { widgets } = useWorkflowHostCommands();const rootChildren = getFormChildren(projectGraph.form);const onOpenWorkflowEditorClick = useCallback(- () => dispatch({ region: 'center', type: 'selectRegionWidget', widgetId: 'workflow' }),- [dispatch]+ () => widgets.select({ region: 'center', widgetId: 'workflow' }),+ [widgets]);if (rootChildren.length === 0) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsxsimilarity index 81%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsxindex 82a1dcc706..7e81cd692c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx@@ -1,18 +1,16 @@-import type { NodeFieldFormElement, ProjectGraphState } from '@workbench/workflows/types';-import { Alert, Field, HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';-import { FieldLabel, IconButton, Tooltip } from '@workbench/components/ui';-import { WorkflowFieldInput } from '@workbench/widgets/workflow/fields/WorkflowFieldInput';-import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { getResolvedWorkflowEdges } from '@workbench/workflows/connectors';+import { isInvocationNode, type NodeFieldFormElement, type ProjectGraphState } from '@features/workflow/contracts';+import { useInvocationTemplatesSelector } from '@features/workflow/react';+import { WorkflowFieldInput } from '@features/workflow/ui/fields/WorkflowFieldInput';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import {cloneWorkflowFieldDefault,+ getResolvedWorkflowEdges,getWorkflowFieldInvalidReason,isDirectInputField,isWorkflowFieldValueDefault,-} from '@workbench/workflows/fields';-import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';-import { isInvocationNode } from '@workbench/workflows/types';+} from '@features/workflow/utility';+import { FieldLabel, IconButton, Tooltip } from '@platform/ui';import { RotateCcwIcon } from 'lucide-react';import { useCallback, useMemo, useState, type ChangeEvent } from 'react';@@ -46,7 +44,7 @@ export const NodeFieldControl = ({isLabelEditable?: boolean;projectGraph: ProjectGraphState;}) => {- const dispatch = useWorkbenchDispatch();+ const { editGraph } = useProjectGraphCommands();const { fieldName, instance, invocationNode, nodeContext, nodeId, template } = useNodeFieldBinding(element,projectGraph@@ -74,36 +72,26 @@ export const NodeFieldControl = ({const valueInputId = `${element.id}-value`;const onResetClick = useCallback(() =>- dispatch({- action: {- fieldName,- nodeId,- type: 'setFieldValue',- value: template ? cloneWorkflowFieldDefault(template) : undefined,- },- type: 'applyProjectGraphAction',+ editGraph({+ fieldName,+ nodeId,+ type: 'setFieldValue',+ value: template ? cloneWorkflowFieldDefault(template) : undefined,}),- [dispatch, fieldName, nodeId, template]+ [editGraph, fieldName, nodeId, template]);const onLabelBlur = useCallback(() => setDraftLabel(null), []);const onLabelChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {setDraftLabel(event.currentTarget.value);- dispatch({- action: { fieldName, label: event.currentTarget.value, nodeId, type: 'setFieldLabel' },- type: 'applyProjectGraphAction',- });+ editGraph({ fieldName, label: event.currentTarget.value, nodeId, type: 'setFieldLabel' });},- [dispatch, fieldName, nodeId]+ [editGraph, fieldName, nodeId]);const onLabelFocus = useCallback(() => setDraftLabel(label), [label]);const onValueChange = useCallback(- (value: unknown) =>- dispatch({- action: { fieldName, nodeId, type: 'setFieldValue', value },- type: 'applyProjectGraphAction',- }),- [dispatch, fieldName, nodeId]+ (value: unknown) => editGraph({ fieldName, nodeId, type: 'setFieldValue', value }),+ [editGraph, fieldName, nodeId]);const resetAriaLabel = useMemo(() => `Reset ${label} to default value`, [label]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsxsimilarity index 86%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsxindex 3f0ca9b653..d233b301b2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx@@ -3,15 +3,15 @@ import type {ProjectGraphState,WorkflowInvocationNode,WorkflowNode,-} from '@workbench/workflows/types';+} from '@features/workflow/contracts';import type { ChangeEvent } from 'react';import { Flex, HStack, Stack, Text, Textarea } from '@chakra-ui/react';-import { JsonPreview, Scrollable, Tabs } from '@workbench/components/ui';-import { workflowSelectionStore } from '@workbench/widgets/workflow/editor/selectionStore';-import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';+import { useInvocationTemplatesSelector } from '@features/workflow/react';+import { workflowSelectionStore } from '@features/workflow/ui/editor/selectionStore';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';+import { useWorkflowHostCommands, useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';+import { JsonPreview, Scrollable, Tabs } from '@platform/ui';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -43,14 +43,11 @@ const JsonBlock = ({ label, value }: { label: string; value: unknown }) => <Jsonconst DetailsTab = ({ node, template }: { node: WorkflowInvocationNode; template: InvocationTemplate | undefined }) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();+ const { editGraph } = useProjectGraphCommands();const onNotesChange = useCallback((event: ChangeEvent<HTMLTextAreaElement>) =>- dispatch({- action: { nodeId: node.id, notes: event.currentTarget.value, type: 'setNodeNotes' },- type: 'applyProjectGraphAction',- }),- [dispatch, node.id]+ editGraph({ nodeId: node.id, notes: event.currentTarget.value, type: 'setNodeNotes' }),+ [editGraph, node.id]);return (@@ -143,15 +140,14 @@ const InspectorBody = ({ node, tab }: { node: WorkflowNode; tab: InspectorTab })export const NodeInspector = ({ projectGraph }: { projectGraph: ProjectGraphState }) => {const { t } = useTranslation();- const workflowWidgetValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'workflow'));- const dispatch = useWorkbenchDispatch();+ const workflowWidgetValues = useWorkflowProjectSelector((project) => project.workflowValues);+ const { widgets } = useWorkflowHostCommands();const selectedNodeIds = workflowSelectionStore.useSelector((snapshot) => snapshot.selectedNodeIds);const tab = getInspectorTab(workflowWidgetValues);const selectedNode = projectGraph.nodes.find((node) => node.id === selectedNodeIds[0]);const onTabValueChange = useCallback(- (event: { value: string }) =>- dispatch({ type: 'patchWidgetValues', values: { inspectorTab: event.value }, widgetId: 'workflow' }),- [dispatch]+ (event: { value: string }) => widgets.patchValues('workflow', { inspectorTab: event.value }),+ [widgets]);return (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowDetailsTab.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowDetailsTab.tsxsimilarity index 87%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowDetailsTab.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowDetailsTab.tsxindex 274e79a48f..1c65872dfc 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowDetailsTab.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowDetailsTab.tsx@@ -1,20 +1,19 @@-import type { WorkflowMetadata } from '@workbench/workflows/types';+import type { WorkflowMetadata } from '@features/workflow/contracts';import type { ChangeEvent } from 'react';import { HStack, Input, Stack, Textarea } from '@chakra-ui/react';-import { Field } from '@workbench/components/ui';-import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';+import { Field } from '@platform/ui';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';/** Workflow metadata editing — the legacy "Details" tab. */export const WorkflowDetailsTab = ({ metadata }: { metadata: WorkflowMetadata }) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();+ const { editGraph } = useProjectGraphCommands();const commit = useCallback(- (patch: Partial<WorkflowMetadata>) =>- dispatch({ action: { patch, type: 'setMetadata' }, type: 'applyProjectGraphAction' }),- [dispatch]+ (patch: Partial<WorkflowMetadata>) => editGraph({ patch, type: 'setMetadata' }),+ [editGraph]);const onNameChange = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowJsonTab.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowJsonTab.tsxsimilarity index 71%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowJsonTab.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowJsonTab.tsxindex 4195a0e6fb..5c6e0c0f86 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowJsonTab.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowJsonTab.tsx@@ -1,8 +1,8 @@-import type { ProjectGraphState } from '@workbench/workflows/types';+import type { ProjectGraphState } from '@features/workflow/contracts';import { Flex } from '@chakra-ui/react';-import { JsonPreview } from '@workbench/components/ui';-import { getWorkflowJsonText } from '@workbench/widgets/workflow/workflowTransfer';+import { getWorkflowJsonText } from '@features/workflow/ui/workflowTransfer';+import { JsonPreview } from '@platform/ui';import { useTranslation } from 'react-i18next';/** Read-only view of the serialized workflow — the legacy "JSON" tab. */diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.tsxsimilarity index 88%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.tsxindex 0dcb4faa54..10cf1cf63d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.tsx@@ -1,9 +1,10 @@import { Flex, HStack, Icon, SegmentGroup, Splitter } from '@chakra-ui/react';-import { Scrollable, Tabs } from '@workbench/components/ui';-import { useActiveProjectSelector, useWidgetValuesSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { ensureInvocationTemplatesLoaded } from '@workbench/workflows/templates';+import { ensureInvocationTemplatesLoaded } from '@features/workflow/react';+import { useWorkflowHostCommands, useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';+import { useMountEffect } from '@platform/react/useMountEffect';+import { Scrollable, Tabs } from '@platform/ui';import { EyeIcon, PencilIcon } from 'lucide-react';-import { useCallback, useEffect, useMemo } from 'react';+import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { FormBuilderTab } from './FormBuilderTab';@@ -90,20 +91,18 @@ const PanelModeToggle = ({ mode, onChange }: { mode: PanelMode; onChange: (mode:export const WorkflowLinearPanel = () => {const { t } = useTranslation();- const { editTab, inspectorSizePct, mode } = useWidgetValuesSelector(- 'workflow',- getWorkflowPanelState,- areWorkflowPanelStatesEqual+ const { editTab, inspectorSizePct, mode } = useWorkflowProjectSelector((project) =>+ getWorkflowPanelState(project.workflowValues));- const dispatch = useWorkbenchDispatch();+ const { widgets } = useWorkflowHostCommands();- useEffect(() => {+ useMountEffect(() => {ensureInvocationTemplatesLoaded();- }, []);+ });const patchValues = useCallback(- (values: Record<string, unknown>) => dispatch({ type: 'patchWidgetValues', values, widgetId: 'workflow' }),- [dispatch]+ (values: Record<string, unknown>) => widgets.patchValues('workflow', values),+ [widgets]);const onPanelModeChange = useCallback((panelMode: PanelMode) => patchValues({ panelMode }), [patchValues]);const onEditTabChange = useCallback(@@ -142,7 +141,7 @@ export const WorkflowLinearPanel = () => {const WorkflowLinearViewContent = () => {const { t } = useTranslation();- const projectGraph = useActiveProjectSelector((project) => project.projectGraph);+ const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);return (<Scrollable flex="1" label={t('widgets.workflow.panelContent')} minH="0">@@ -161,7 +160,7 @@ const WorkflowLinearEditContent = ({patchValues: (values: Record<string, unknown>) => void;}) => {const { t } = useTranslation();- const projectGraph = useActiveProjectSelector((project) => project.projectGraph);+ const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);const defaultSize = useMemo(() => [100 - inspectorSizePct, inspectorSizePct], [inspectorSizePct]);const onResizeEnd = useCallback((details: { size: number[] }) => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/useProjectGraphCommands.ts b/invokeai/frontend/webv2/src/features/workflow/ui/useProjectGraphCommands.tsnew file mode 100644index 0000000000..330c0f95f3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/useProjectGraphCommands.ts@@ -0,0 +1,3 @@+import { useWorkflowUi } from './WorkflowUiContext';++export const useProjectGraphCommands = () => useWorkflowUi().commands;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowTransfer.ts b/invokeai/frontend/webv2/src/features/workflow/ui/workflowTransfer.tssimilarity index 84%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowTransfer.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/workflowTransfer.tsindex bb7b3383dc..ff52fb57c3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowTransfer.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/workflowTransfer.ts@@ -1,6 +1,6 @@-import type { ProjectGraphState } from '@workbench/workflows/types';+import type { ProjectGraphState } from '@features/workflow/contracts';-import { serializeWorkflowJson } from '@workbench/workflows/workflowJson';+import { serializeWorkflowJson } from '@features/workflow/utility';/** Export-side helpers shared by the workflow menu items and panels. */diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.tssimilarity index 92%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.tsrename to invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.tsindex b0f53e52ac..ee66096be7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts@@ -1,6 +1,6 @@-import type { FieldType, XYPosition } from '@workbench/workflows/types';+import type { FieldType, XYPosition } from '@features/workflow/contracts';-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';export type AddNodeConnectionFilter =| {diff --git a/invokeai/frontend/webv2/src/features/workflow/utility.ts b/invokeai/frontend/webv2/src/features/workflow/utility.tsnew file mode 100644index 0000000000..d22b04a8e8--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/utility.ts@@ -0,0 +1,7 @@+export * from './core/connectorHandles';+export * from './core/connectors';+export * from './core/document';+export * from './core/fields';+export * from './core/graphIndex';+export * from './core/validation';+export * from './core/workflowJson';diff --git a/invokeai/frontend/webv2/src/features/workflow/widget.ts b/invokeai/frontend/webv2/src/features/workflow/widget.tsnew file mode 100644index 0000000000..1557198793--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/widget.ts@@ -0,0 +1,2 @@+export const loadWorkflowWidgetImplementation = () =>+ import('./ui/implementation').then((module) => module.widgetImplementation);diff --git a/invokeai/frontend/webv2/src/i18n.ts b/invokeai/frontend/webv2/src/platform/i18n/client.tssimilarity index 100%rename from invokeai/frontend/webv2/src/i18n.tsrename to invokeai/frontend/webv2/src/platform/i18n/client.tsdiff --git a/invokeai/frontend/webv2/src/workbench/i18n/languages.ts b/invokeai/frontend/webv2/src/platform/i18n/languages.tssimilarity index 97%rename from invokeai/frontend/webv2/src/workbench/i18n/languages.tsrename to invokeai/frontend/webv2/src/platform/i18n/languages.tsindex 90c7a41af8..ff4a5850fc 100644--- a/invokeai/frontend/webv2/src/workbench/i18n/languages.ts+++ b/invokeai/frontend/webv2/src/platform/i18n/languages.ts@@ -1,3 +1,4 @@+/** Supported application languages and their document direction. */export const WORKBENCH_LANGUAGE_OPTIONS = [{ value: 'ar', label: 'العربية', direction: 'rtl' },{ value: 'az', label: 'Azərbaycan dili', direction: 'ltr' },diff --git a/invokeai/frontend/webv2/src/platform/query/client.ts b/invokeai/frontend/webv2/src/platform/query/client.tsnew file mode 100644index 0000000000..49916d2189--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/query/client.ts@@ -0,0 +1,15 @@+import { QueryClient } from '@tanstack/react-query';++/**+ * The application query cache. Feature modules own their keys and options;+ * non-React runtimes use this same client for precise realtime updates.+ */+export const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ refetchOnWindowFocus: false,+ retry: 1,+ staleTime: 5_000,+ },+ },+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/draftRegistry.ts b/invokeai/frontend/webv2/src/platform/react/draftRegistry.tssimilarity index 91%rename from invokeai/frontend/webv2/src/workbench/widgets/draftRegistry.tsrename to invokeai/frontend/webv2/src/platform/react/draftRegistry.tsindex b4f16b92b6..37418ce2a5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/draftRegistry.ts+++ b/invokeai/frontend/webv2/src/platform/react/draftRegistry.ts@@ -1,4 +1,4 @@-import { useMountEffect } from '@workbench/hooks/useMountEffect';+import { useMountEffect } from '@platform/react/useMountEffect';import { useEffectEvent } from 'react';type DraftFlusher = () => void;diff --git a/invokeai/frontend/webv2/src/workbench/useModifierHeld.ts b/invokeai/frontend/webv2/src/platform/react/useModifierHeld.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/useModifierHeld.tsrename to invokeai/frontend/webv2/src/platform/react/useModifierHeld.tsdiff --git a/invokeai/frontend/webv2/src/workbench/hooks/useMountEffect.ts b/invokeai/frontend/webv2/src/platform/react/useMountEffect.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/hooks/useMountEffect.tsrename to invokeai/frontend/webv2/src/platform/react/useMountEffect.tsdiff --git a/invokeai/frontend/webv2/src/workbench/models/useZodForm.ts b/invokeai/frontend/webv2/src/platform/react/useZodForm.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/models/useZodForm.tsrename to invokeai/frontend/webv2/src/platform/react/useZodForm.tsdiff --git a/invokeai/frontend/webv2/src/platform/runtime/appMetadata.ts b/invokeai/frontend/webv2/src/platform/runtime/appMetadata.tsnew file mode 100644index 0000000000..717f5cd11e--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/runtime/appMetadata.ts@@ -0,0 +1,2 @@+/** Build-time application metadata with no domain dependencies. */+export const APP_VERSION = '7.0';diff --git a/invokeai/frontend/webv2/src/workbench/externalStore.test.ts b/invokeai/frontend/webv2/src/platform/state/externalStore.test.tssimilarity index 89%rename from invokeai/frontend/webv2/src/workbench/externalStore.test.tsrename to invokeai/frontend/webv2/src/platform/state/externalStore.test.tsindex 7a39c7acac..a0d7764ff0 100644--- a/invokeai/frontend/webv2/src/workbench/externalStore.test.ts+++ b/invokeai/frontend/webv2/src/platform/state/externalStore.test.ts@@ -1,8 +1,10 @@+import { createElement } from 'react';+import { renderToString } from 'react-dom/server';import { describe, expect, it, vi } from 'vitest';import { createCollectionStore, createExternalStore, createKeyedTransientStore } from './externalStore';-describe('createExternalStore', () => {+describe('platform createExternalStore', () => {it('does not notify listeners for identical snapshots or empty patches', () => {const initial = { count: 0, label: 'idle' };const store = createExternalStore(initial);@@ -31,6 +33,15 @@ describe('createExternalStore', () => {});describe('createKeyedTransientStore', () => {+ it('provides a server snapshot for server rendering', () => {+ const store = createKeyedTransientStore<string, number>();+ store.set('answer', 42);++ const View = () => createElement('span', null, store.useValue('answer'));++ expect(renderToString(createElement(View))).toBe('<span>42</span>');+ });+it('notifies only listeners for the changed key and global listeners', () => {const store = createKeyedTransientStore<string, number>();const keyListener = vi.fn();diff --git a/invokeai/frontend/webv2/src/platform/state/externalStore.ts b/invokeai/frontend/webv2/src/platform/state/externalStore.tsnew file mode 100644index 0000000000..5f4b45aa07--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/state/externalStore.ts@@ -0,0 +1,57 @@+import { useCallback, useSyncExternalStore } from 'react';++import {+ createCollectionStoreCore,+ createExternalStoreCore,+ createKeyedTransientStoreCore,+ type CollectionStoreCore,+ type ExternalStoreCore,+ type KeyedTransientStoreCore,+} from './externalStoreCore';+import { shallowEqual, useExternalStoreSelector, type EqualityFn } from './selectors';++export * from './externalStoreCore';++export interface ExternalStore<Snapshot extends object> extends ExternalStoreCore<Snapshot> {+ useSelector: <Selected>(selector: (snapshot: Snapshot) => Selected, isEqual?: EqualityFn<Selected>) => Selected;+ useSnapshot: () => Snapshot;+}++export const createExternalStore = <Snapshot extends object>(initialSnapshot: Snapshot): ExternalStore<Snapshot> => {+ const store = createExternalStoreCore(initialSnapshot);+ return {+ ...store,+ useSelector: <Selected>(+ selector: (snapshot: Snapshot) => Selected,+ isEqual: EqualityFn<Selected> = shallowEqual+ ): Selected => useExternalStoreSelector(store.subscribe, store.getSnapshot, selector, isEqual),+ useSnapshot: () => useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot),+ };+};++export interface KeyedTransientStore<Key, Value> extends KeyedTransientStoreCore<Key, Value> {+ useValue: (key: Key) => Value | undefined;+}++export const createKeyedTransientStore = <Key, Value>(+ isEqual: EqualityFn<Value | undefined> = Object.is+): KeyedTransientStore<Key, Value> => {+ const store = createKeyedTransientStoreCore<Key, Value>(isEqual);+ return {+ ...store,+ useValue: (key) => {+ const subscribe = useCallback((listener: () => void) => store.subscribeKey(key, listener), [key]);+ const getSnapshot = useCallback(() => store.get(key), [key]);+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);+ },+ };+};++export interface CollectionStore<Contribution> extends CollectionStoreCore<Contribution> {+ useList: () => Contribution[];+}++export const createCollectionStore = <Contribution>(): CollectionStore<Contribution> => {+ const store = createCollectionStoreCore<Contribution>();+ return { ...store, useList: () => useSyncExternalStore(store.subscribe, store.list, store.list) };+};diff --git a/invokeai/frontend/webv2/src/workbench/externalStore.ts b/invokeai/frontend/webv2/src/platform/state/externalStoreCore.tssimilarity index 57%rename from invokeai/frontend/webv2/src/workbench/externalStore.tsrename to invokeai/frontend/webv2/src/platform/state/externalStoreCore.tsindex d0a26ae455..1f5716663e 100644--- a/invokeai/frontend/webv2/src/workbench/externalStore.ts+++ b/invokeai/frontend/webv2/src/platform/state/externalStoreCore.ts@@ -1,15 +1,5 @@-import { useCallback, useSyncExternalStore } from 'react';+import { shallowEqual, type EqualityFn } from './selectorCore';-import { shallowEqual, useExternalStoreSelector, type EqualityFn } from './workbenchSelectors';--/**- * Minimal factory for module-level stores backed by `useSyncExternalStore`.- * For backend-owned or session-lived state shared across widget surfaces- * (model library, install jobs, starter catalog) where the workbench reducer- * is the wrong home. See `models/modelsStore.ts` for the canonical usage.- */--/** A bare listener channel, for auxiliary data living beside a snapshot. */export interface ListenerChannel {subscribe: (listener: () => void) => () => void;notify: () => void;@@ -17,7 +7,6 @@ export interface ListenerChannel {export const createListenerChannel = (): ListenerChannel => {const listeners = new Set<() => void>();-return {notify: () => {for (const listener of listeners) {@@ -26,118 +15,84 @@ export const createListenerChannel = (): ListenerChannel => {},subscribe: (listener) => {listeners.add(listener);-- return () => {- listeners.delete(listener);- };+ return () => listeners.delete(listener);},};};-export interface ExternalStore<Snapshot extends object> extends ListenerChannel {+export interface ExternalStoreCore<Snapshot extends object> extends ListenerChannel {getSnapshot: () => Snapshot;- /** Replace the snapshot and notify subscribers. */- setSnapshot: (next: Snapshot) => void;- /** Merge a partial snapshot and notify subscribers. */patchSnapshot: (next: Partial<Snapshot>) => void;- /** Replace without notifying — for data read imperatively, never rendered. */+ setSnapshot: (next: Snapshot) => void;setSnapshotSilently: (next: Snapshot) => void;- /** Subscribe the calling component to the snapshot. */- useSnapshot: () => Snapshot;- /** Subscribe the calling component to a selected snapshot value. */- useSelector: <Selected>(- selector: (snapshot: Snapshot) => Selected,- isEqual?: (left: Selected, right: Selected) => boolean- ) => Selected;}const hasPatchChanges = <Snapshot extends object>(snapshot: Snapshot, patch: Partial<Snapshot>): boolean =>Object.entries(patch).some(- ([key, value]) =>- !Object.prototype.hasOwnProperty.call(snapshot, key) || !Object.is(snapshot[key as keyof Snapshot], value)+ ([key, value]) => !Object.hasOwn(snapshot, key) || !Object.is(snapshot[key as keyof Snapshot], value));-export const createExternalStore = <Snapshot extends object>(initialSnapshot: Snapshot): ExternalStore<Snapshot> => {+export const createExternalStoreCore = <Snapshot extends object>(+ initialSnapshot: Snapshot+): ExternalStoreCore<Snapshot> => {let snapshot = initialSnapshot;const channel = createListenerChannel();-const getSnapshot = (): Snapshot => snapshot;-const setSnapshot = (next: Snapshot): void => {if (shallowEqual(next, snapshot)) {return;}-snapshot = next;channel.notify();};- const useSnapshot = (): Snapshot => useSyncExternalStore(channel.subscribe, getSnapshot);-- const useSelector = <Selected>(- selector: (snapshot: Snapshot) => Selected,- isEqual: EqualityFn<Selected> = shallowEqual- ): Selected => useExternalStoreSelector(channel.subscribe, getSnapshot, selector, isEqual);-return {...channel,getSnapshot,patchSnapshot: (next) => {- if (!hasPatchChanges(snapshot, next)) {- return;+ if (hasPatchChanges(snapshot, next)) {+ setSnapshot({ ...snapshot, ...next });}-- setSnapshot({ ...snapshot, ...next });},setSnapshot,setSnapshotSilently: (next) => {snapshot = next;},- useSelector,- useSnapshot,};};-export interface KeyedTransientStore<Key, Value> extends ListenerChannel {+export interface KeyedTransientStoreCore<Key, Value> extends ListenerChannel {clear: () => void;delete: (key: Key) => void;entries: () => Array<[Key, Value]>;get: (key: Key) => Value | undefined;set: (key: Key, value: Value) => void;subscribeKey: (key: Key, listener: () => void) => () => void;- useValue: (key: Key) => Value | undefined;}-export const createKeyedTransientStore = <Key, Value>(+export const createKeyedTransientStoreCore = <Key, Value>(isEqual: EqualityFn<Value | undefined> = Object.is-): KeyedTransientStore<Key, Value> => {+): KeyedTransientStoreCore<Key, Value> => {const values = new Map<Key, Value>();const channel = createListenerChannel();const keyedListeners = new Map<Key, Set<() => void>>();-const notifyKey = (key: Key): void => {for (const listener of keyedListeners.get(key) ?? []) {listener();}-channel.notify();};-const subscribeKey = (key: Key, listener: () => void): (() => void) => {const listeners = keyedListeners.get(key) ?? new Set<() => void>();-listeners.add(listener);keyedListeners.set(key, listeners);-return () => {listeners.delete(listener);-if (listeners.size === 0) {keyedListeners.delete(key);}};};-const get = (key: Key): Value | undefined => values.get(key);return {@@ -146,16 +101,13 @@ export const createKeyedTransientStore = <Key, Value>(if (values.size === 0) {return;}-const keys = Array.from(values.keys());values.clear();-for (const key of keys) {for (const listener of keyedListeners.get(key) ?? []) {listener();}}-channel.notify();},delete: (key) => {@@ -166,31 +118,22 @@ export const createKeyedTransientStore = <Key, Value>(entries: () => [...values.entries()],get,set: (key, value) => {- if (values.has(key) && isEqual(values.get(key), value)) {- return;+ if (!values.has(key) || !isEqual(values.get(key), value)) {+ values.set(key, value);+ notifyKey(key);}-- values.set(key, value);- notifyKey(key);},subscribeKey,- useValue: (key) => {- const subscribe = useCallback((listener: () => void) => subscribeKey(key, listener), [key]);- const getKeySnapshot = useCallback(() => get(key), [key]);-- return useSyncExternalStore(subscribe, getKeySnapshot);- },};};-export interface CollectionStore<Contribution> extends ListenerChannel {+export interface CollectionStoreCore<Contribution> extends ListenerChannel {findLatest: (predicate: (contribution: Contribution) => boolean) => Contribution | undefined;list: () => Contribution[];register: (contribution: Contribution, registrationKey: string) => () => void;- useList: () => Contribution[];}-export const createCollectionStore = <Contribution>(): CollectionStore<Contribution> => {+export const createCollectionStoreCore = <Contribution>(): CollectionStoreCore<Contribution> => {let nextRegistrationId = 0;const contributions = new Map<string, { contribution: Contribution; token: number }>();const channel = createListenerChannel();@@ -204,35 +147,28 @@ export const createCollectionStore = <Contribution>(): CollectionStore<Contribut...channel,findLatest: (predicate) => {const items = list();-for (let index = items.length - 1; index >= 0; index -= 1) {const contribution = items[index];-if (contribution !== undefined && predicate(contribution)) {return contribution;}}-return undefined;},list,register: (contribution, registrationKey) => {- const id = registrationKey;const token = nextRegistrationId;-nextRegistrationId += 1;- contributions.delete(id);- contributions.set(id, { contribution, token });+ contributions.delete(registrationKey);+ contributions.set(registrationKey, { contribution, token });refreshListSnapshot();channel.notify();-return () => {- if (contributions.get(id)?.token === token && contributions.delete(id)) {+ if (contributions.get(registrationKey)?.token === token && contributions.delete(registrationKey)) {refreshListSnapshot();channel.notify();}};},- useList: () => useSyncExternalStore(channel.subscribe, list),};};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchSelectors.ts b/invokeai/frontend/webv2/src/platform/state/selectorCore.tssimilarity index 85%rename from invokeai/frontend/webv2/src/workbench/workbenchSelectors.tsrename to invokeai/frontend/webv2/src/platform/state/selectorCore.tsindex cd69af9a32..42c6685885 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchSelectors.ts+++ b/invokeai/frontend/webv2/src/platform/state/selectorCore.ts@@ -1,5 +1,3 @@-import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector';-export type EqualityFn<T> = (left: T, right: T) => boolean;export interface SelectorCache<Snapshot, Selected> {@@ -14,22 +12,18 @@ export const shallowEqual = <T>(left: T, right: T): boolean => {if (Object.is(left, right)) {return true;}-if (Array.isArray(left) && Array.isArray(right)) {return areArraysEqual(left, right);}-if (left instanceof Set && right instanceof Set) {return left.size === right.size && Array.from(left).every((value) => right.has(value));}-if (left instanceof Map && right instanceof Map) {return (left.size === right.size &&Array.from(left).every(([key, value]) => right.has(key) && Object.is(right.get(key), value)));}-if (typeof left !== 'object' || left === null || typeof right !== 'object' || right === null) {return false;}@@ -37,7 +31,6 @@ export const shallowEqual = <T>(left: T, right: T): boolean => {const leftRecord = left as Record<PropertyKey, unknown>;const rightRecord = right as Record<PropertyKey, unknown>;const leftKeys = Reflect.ownKeys(leftRecord);-if (leftKeys.length !== Reflect.ownKeys(rightRecord).length) {return false;}@@ -59,14 +52,11 @@ export const createSelectorCache = <Snapshot, Selected>(return {read: (snapshot) => {const next = selector(snapshot);-if (hasSelection && isEqual(selection, next)) {return selection;}-hasSelection = true;selection = next;-return next;},setSelector: (nextSelector, nextIsEqual) => {@@ -76,18 +66,10 @@ export const createSelectorCache = <Snapshot, Selected>(};};-export const useExternalStoreSelector = <Snapshot, Selected>(- subscribe: (listener: () => void) => () => void,- getSnapshot: () => Snapshot,- selector: (snapshot: Snapshot) => Selected,- isEqual: EqualityFn<Selected> = shallowEqual-): Selected => useSyncExternalStoreWithSelector(subscribe, getSnapshot, getSnapshot, selector, isEqual);-export const createStableSelector = <Input, Selected>(selector: (input: Input) => Selected,isEqual: EqualityFn<Selected> = shallowEqual): ((input: Input) => Selected) => {const cache = createSelectorCache(selector, isEqual);-return (input) => cache.read(input);};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchSelectors.test.ts b/invokeai/frontend/webv2/src/platform/state/selectors.test.tssimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/workbenchSelectors.test.tsrename to invokeai/frontend/webv2/src/platform/state/selectors.test.tsindex f4e5692ec6..e0d2f42d79 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchSelectors.test.ts+++ b/invokeai/frontend/webv2/src/platform/state/selectors.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { createSelectorCache, createStableSelector } from './workbenchSelectors';+import { createSelectorCache, createStableSelector } from './selectors';describe('createSelectorCache', () => {it('uses shallow equality by default for derived objects', () => {diff --git a/invokeai/frontend/webv2/src/platform/state/selectors.ts b/invokeai/frontend/webv2/src/platform/state/selectors.tsnew file mode 100644index 0000000000..3348eb1fed--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/state/selectors.ts@@ -0,0 +1,13 @@+import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector';++import { shallowEqual, type EqualityFn } from './selectorCore';++export * from './selectorCore';++/** React adapter for a React-free external-store subscription. */+export const useExternalStoreSelector = <Snapshot, Selected>(+ subscribe: (listener: () => void) => () => void,+ getSnapshot: () => Snapshot,+ selector: (snapshot: Snapshot) => Selected,+ isEqual: EqualityFn<Selected> = shallowEqual+): Selected => useSyncExternalStoreWithSelector(subscribe, getSnapshot, getSnapshot, selector, isEqual);diff --git a/invokeai/frontend/webv2/src/platform/state/singleFlight.test.ts b/invokeai/frontend/webv2/src/platform/state/singleFlight.test.tsnew file mode 100644index 0000000000..f847cd2363--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/state/singleFlight.test.ts@@ -0,0 +1,80 @@+import { describe, expect, it, vi } from 'vitest';++import { createSingleFlight } from './singleFlight';++const deferred = <T>(): { promise: Promise<T>; resolve: (value: T) => void } => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((r) => {+ resolve = r;+ });++ return { promise, resolve };+};++describe('platform createSingleFlight', () => {+ it('shares one in-flight promise between concurrent same-key callers', async () => {+ const flight = createSingleFlight<string>();+ const { promise, resolve } = deferred<string>();+ const task = vi.fn(() => promise);++ const first = flight.run('a', task);+ const second = flight.run('a', task);++ expect(second).toBe(first);+ expect(task).toHaveBeenCalledTimes(1);+ resolve('done');+ await expect(first).resolves.toBe('done');+ });++ it('starts a fresh task after the previous flight settles', async () => {+ const flight = createSingleFlight<number>();+ const task = vi.fn(() => Promise.resolve(1));++ await flight.run('a', task);+ await flight.run('a', task);++ expect(task).toHaveBeenCalledTimes(2);+ });++ it('starts a fresh task for a different key while one is in flight', async () => {+ const flight = createSingleFlight<string>();+ const flightA = deferred<string>();+ const taskA = vi.fn(() => flightA.promise);+ const taskB = vi.fn(() => Promise.resolve('b'));++ const a = flight.run('a', taskA);+ const b = flight.run('b', taskB);++ expect(b).not.toBe(a);+ expect(taskB).toHaveBeenCalledTimes(1);+ flightA.resolve('a');+ await Promise.all([a, b]);+ });++ it('does not let a superseded flight clear a newer one when it settles', async () => {+ const flight = createSingleFlight<string>();+ const oldFlight = deferred<string>();+ const newFlight = deferred<string>();+ const newTask = vi.fn(() => newFlight.promise);++ void flight.run('old', () => oldFlight.promise);+ const renewed = flight.run('new', newTask);++ oldFlight.resolve('old');+ await Promise.resolve();+ // The new flight must still be the shared in-flight promise.+ expect(flight.run('new', newTask)).toBe(renewed);+ expect(newTask).toHaveBeenCalledTimes(1);+ newFlight.resolve('new');+ await renewed;+ });++ it('clears the flight when the task rejects so the next run retries', async () => {+ const flight = createSingleFlight<string>();+ const failing = vi.fn(() => Promise.reject(new Error('nope')));++ await expect(flight.run('a', failing)).rejects.toThrow('nope');+ await expect(flight.run('a', failing)).rejects.toThrow('nope');+ expect(failing).toHaveBeenCalledTimes(2);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/state/singleFlight.ts b/invokeai/frontend/webv2/src/platform/state/singleFlight.tsnew file mode 100644index 0000000000..0da2184f7a--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/state/singleFlight.ts@@ -0,0 +1,27 @@+export interface SingleFlight<T> {+ /** Runs task unless a run with the same key is in flight; concurrent callers share the promise. */+ run(key: string, task: () => Promise<T>): Promise<T>;+}++export const createSingleFlight = <T>(): SingleFlight<T> => {+ let pending: Promise<T> | null = null;+ let pendingKey: string | null = null;++ return {+ run(key, task) {+ if (pending && pendingKey === key) {+ return pending;+ }+ const flight = task().finally(() => {+ // A newer flight for a different key may have replaced this one; only clear our own.+ if (pending === flight) {+ pending = null;+ pendingKey = null;+ }+ });+ pending = flight;+ pendingKey = key;+ return flight;+ },+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/backend/connectionStore.ts b/invokeai/frontend/webv2/src/platform/transport/connectionStore.tssimilarity index 89%rename from invokeai/frontend/webv2/src/workbench/backend/connectionStore.tsrename to invokeai/frontend/webv2/src/platform/transport/connectionStore.tsindex d2e87c5beb..1a8809495a 100644--- a/invokeai/frontend/webv2/src/workbench/backend/connectionStore.ts+++ b/invokeai/frontend/webv2/src/platform/transport/connectionStore.ts@@ -1,6 +1,6 @@-import type { BackendConnectionStatus } from '@workbench/types';+import { createExternalStore } from '@platform/state/externalStore';-import { createExternalStore } from '@workbench/externalStore';+import type { BackendConnectionStatus } from './types';/*** Provider-free connection status for the shared backend socket. The socket hubdiff --git a/invokeai/frontend/webv2/src/workbench/backend/http.ts b/invokeai/frontend/webv2/src/platform/transport/http.tssimilarity index 82%rename from invokeai/frontend/webv2/src/workbench/backend/http.tsrename to invokeai/frontend/webv2/src/platform/transport/http.tsindex 399c644b56..864faf62ee 100644--- a/invokeai/frontend/webv2/src/workbench/backend/http.ts+++ b/invokeai/frontend/webv2/src/platform/transport/http.ts@@ -1,48 +1,30 @@/*** Shared HTTP client for the InvokeAI backend. Every REST call goes through* `apiFetch` so authentication matches the WebSocket connection: both read the- * same `auth_token` and send it as a bearer token. The token is read per- * request, so a login that lands mid-session applies without a reload.+ * an Auth-owned adapter and send it as a bearer token. The token is read per+ * request, so an identity change applies without a reload.*/const API_BASE_URL = import.meta.env.VITE_INVOKEAI_API_BASE_URL ?? '';-const AUTH_TOKEN_STORAGE_KEY = 'auth_token';+export interface HttpAuthAdapter {+ getToken(): string | null;+ onUnauthorized(): void;+}-export const getAuthToken = (): string | null => {- try {- return window.localStorage.getItem(AUTH_TOKEN_STORAGE_KEY);- } catch {- return null;- }-};+let authAdapter: HttpAuthAdapter = { getToken: () => null, onUnauthorized: () => undefined };-export const setAuthToken = (token: string): void => {- try {- window.localStorage.setItem(AUTH_TOKEN_STORAGE_KEY, token);- } catch {- // Storage unavailable (private mode, quota): the session lasts until reload.- }+/** Selected once by the App composition root; Platform owns no Auth policy. */+export const configureHttpAuth = (adapter: HttpAuthAdapter): void => {+ authAdapter = adapter;};-export const clearAuthToken = (): void => {- try {- window.localStorage.removeItem(AUTH_TOKEN_STORAGE_KEY);- } catch {- // Nothing to clear if storage is unavailable.- }-};+export const getHttpAuthToken = (): string | null => authAdapter.getToken();/*** Called when an authenticated request comes back 401 — the stored token is no* longer valid. The auth session store registers itself here so the HTTP layer* stays unaware of session semantics.*/-let unauthorizedHandler: (() => void) | null = null;--export const setUnauthorizedHandler = (handler: (() => void) | null): void => {- unauthorizedHandler = handler;-};-export const getBackendSocketUrl = (): string => {if (!API_BASE_URL.trim()) {return window.location.origin;@@ -126,7 +108,7 @@ export const assertOk = async (response: Response): Promise<Response> => {/** Authenticated fetch that leaves status handling to the caller. */export const apiFetchRaw = (path: string, init?: RequestInit): Promise<Response> => {- const token = getAuthToken();+ const token = getHttpAuthToken();const headers = new Headers(init?.headers);if (token && !headers.has('Authorization')) {@@ -137,11 +119,11 @@ export const apiFetchRaw = (path: string, init?: RequestInit): Promise<Response>};export const apiFetch = async (path: string, init?: RequestInit): Promise<Response> => {- const hadToken = getAuthToken() !== null;+ const hadToken = getHttpAuthToken() !== null;const response = await apiFetchRaw(path, init);if (response.status === 401 && hadToken) {- unauthorizedHandler?.();+ authAdapter.onUnauthorized();}return assertOk(response);diff --git a/invokeai/frontend/webv2/src/workbench/backend/socketHub.test.ts b/invokeai/frontend/webv2/src/platform/transport/socketHub.test.tssimilarity index 94%rename from invokeai/frontend/webv2/src/workbench/backend/socketHub.test.tsrename to invokeai/frontend/webv2/src/platform/transport/socketHub.test.tsindex 3f2a574786..871496c5e5 100644--- a/invokeai/frontend/webv2/src/workbench/backend/socketHub.test.ts+++ b/invokeai/frontend/webv2/src/platform/transport/socketHub.test.ts@@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { BackendSocket } from './socketHub';import { getConnectionStatus } from './connectionStore';-import { modelLoadStore } from './modelLoadStore';import { createSocketHub } from './socketHub';class FakeSocket implements BackendSocket {@@ -141,14 +140,11 @@ describe('socketHub', () => {expect(handler).toHaveBeenCalledTimes(1);});- it('resets model loads and reports a disconnect', () => {- const resetSpy = vi.spyOn(modelLoadStore, 'reset');+ it('reports a disconnect without interpreting domain events', () => {const socket = new FakeSocket();const hub = createSocketHub({ createSocket: () => socket });hub.connect();- expect(resetSpy).toHaveBeenCalled();-socket.fire('disconnect', 'transport close');expect(getConnectionStatus().status).toBe('disconnected');diff --git a/invokeai/frontend/webv2/src/workbench/backend/socketHub.ts b/invokeai/frontend/webv2/src/platform/transport/socketHub.tssimilarity index 93%rename from invokeai/frontend/webv2/src/workbench/backend/socketHub.tsrename to invokeai/frontend/webv2/src/platform/transport/socketHub.tsindex 344d236bb8..61ffc2ef42 100644--- a/invokeai/frontend/webv2/src/workbench/backend/socketHub.ts+++ b/invokeai/frontend/webv2/src/platform/transport/socketHub.ts@@ -1,10 +1,9 @@-import type { BackendConnectionStatus } from '@workbench/types';-import { io } from 'socket.io-client';+import type { BackendConnectionStatus } from './types';+import { setConnectionStatus } from './connectionStore';-import { getAuthToken, getBackendSocketUrl } from './http';-import { modelLoadStore } from './modelLoadStore';+import { getBackendSocketUrl, getHttpAuthToken } from './http';const SOCKET_PATH = '/ws/socket.io';@@ -39,7 +38,7 @@ export interface SocketHub {}const createDefaultSocket = (): BackendSocket => {- const token = getAuthToken();+ const token = getHttpAuthToken();// Socket.IO's generic `off` overload does not structurally match our minimal// facade; the socket satisfies the surface we actually use, so narrow it here.@@ -84,16 +83,13 @@ export const createSocketHub = (options: { createSocket?: () => BackendSocket }publishStatus('connecting');nextSocket.on('connect', () => {- modelLoadStore.reset();publishStatus('connected');nextSocket.emit('subscribe_queue', { queue_id: 'default' });});nextSocket.on('connect_error', (error: { message: string }) => {- modelLoadStore.reset();publishStatus('disconnected', error.message);});nextSocket.on('disconnect', (reason: string) => {- modelLoadStore.reset();publishStatus('disconnected', reason);});diff --git a/invokeai/frontend/webv2/src/platform/transport/types.ts b/invokeai/frontend/webv2/src/platform/transport/types.tsnew file mode 100644index 0000000000..6366bcce63--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/transport/types.ts@@ -0,0 +1 @@+export type BackendConnectionStatus = 'connecting' | 'connected' | 'disconnected';diff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Button.tsx b/invokeai/frontend/webv2/src/platform/ui/Button.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/Button.tsxrename to invokeai/frontend/webv2/src/platform/ui/Button.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/ColorPicker.test.tsx b/invokeai/frontend/webv2/src/platform/ui/ColorPicker.test.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/ColorPicker.test.tsxrename to invokeai/frontend/webv2/src/platform/ui/ColorPicker.test.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/ColorPicker.tsx b/invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/ColorPicker.tsxrename to invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Combobox.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Combobox.browser.test.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/Combobox.browser.test.tsxrename to invokeai/frontend/webv2/src/platform/ui/Combobox.browser.test.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Combobox.tsx b/invokeai/frontend/webv2/src/platform/ui/Combobox.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/Combobox.tsxrename to invokeai/frontend/webv2/src/platform/ui/Combobox.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/ConfirmDialog.tsx b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/ConfirmDialog.tsxrename to invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/EmptyState.tsx b/invokeai/frontend/webv2/src/platform/ui/EmptyState.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/EmptyState.tsxrename to invokeai/frontend/webv2/src/platform/ui/EmptyState.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Field.tsx b/invokeai/frontend/webv2/src/platform/ui/Field.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/Field.tsxrename to invokeai/frontend/webv2/src/platform/ui/Field.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/InvokeMark.tsx b/invokeai/frontend/webv2/src/platform/ui/InvokeMark.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/InvokeMark.tsxrename to invokeai/frontend/webv2/src/platform/ui/InvokeMark.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/JsonPreview.tsx b/invokeai/frontend/webv2/src/platform/ui/JsonPreview.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/JsonPreview.tsxrename to invokeai/frontend/webv2/src/platform/ui/JsonPreview.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Menu.tsx b/invokeai/frontend/webv2/src/platform/ui/Menu.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/Menu.tsxrename to invokeai/frontend/webv2/src/platform/ui/Menu.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Panel.tsx b/invokeai/frontend/webv2/src/platform/ui/Panel.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/Panel.tsxrename to invokeai/frontend/webv2/src/platform/ui/Panel.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/RenameDialog.tsx b/invokeai/frontend/webv2/src/platform/ui/RenameDialog.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/RenameDialog.tsxrename to invokeai/frontend/webv2/src/platform/ui/RenameDialog.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/ResizableTextarea.tsx b/invokeai/frontend/webv2/src/platform/ui/ResizableTextarea.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/ResizableTextarea.tsxrename to invokeai/frontend/webv2/src/platform/ui/ResizableTextarea.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Row.tsx b/invokeai/frontend/webv2/src/platform/ui/Row.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/Row.tsxrename to invokeai/frontend/webv2/src/platform/ui/Row.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Scrollable.tsx b/invokeai/frontend/webv2/src/platform/ui/Scrollable.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/Scrollable.tsxrename to invokeai/frontend/webv2/src/platform/ui/Scrollable.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Select.tsx b/invokeai/frontend/webv2/src/platform/ui/Select.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/Select.tsxrename to invokeai/frontend/webv2/src/platform/ui/Select.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Slider.tsx b/invokeai/frontend/webv2/src/platform/ui/Slider.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/Slider.tsxrename to invokeai/frontend/webv2/src/platform/ui/Slider.tsxdiff --git a/invokeai/frontend/webv2/src/platform/ui/StatusWidgetChip.tsx b/invokeai/frontend/webv2/src/platform/ui/StatusWidgetChip.tsxnew file mode 100644index 0000000000..2f5532be6b--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/StatusWidgetChip.tsx@@ -0,0 +1,24 @@+import type { LucideIcon } from 'lucide-react';+import type { ReactNode } from 'react';++import { HStack, Icon, Text, type RecipeVariantProps, useRecipe } from '@chakra-ui/react';+import { chipRecipe } from '@theme/recipes';++export const StatusWidgetChip = ({+ children,+ icon,+ tone,+}: {+ children: ReactNode;+ icon: LucideIcon;+ tone?: NonNullable<RecipeVariantProps<typeof chipRecipe>>['tone'];+}) => {+ const recipe = useRecipe({ recipe: chipRecipe });++ return (+ <HStack css={recipe({ tone })}>+ <Icon as={icon} boxSize="3" />+ <Text whiteSpace="nowrap">{children}</Text>+ </HStack>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Tabs.tsx b/invokeai/frontend/webv2/src/platform/ui/Tabs.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/Tabs.tsxrename to invokeai/frontend/webv2/src/platform/ui/Tabs.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/ToggleDot.tsx b/invokeai/frontend/webv2/src/platform/ui/ToggleDot.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/ToggleDot.tsxrename to invokeai/frontend/webv2/src/platform/ui/ToggleDot.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Toolbar.tsx b/invokeai/frontend/webv2/src/platform/ui/Toolbar.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/Toolbar.tsxrename to invokeai/frontend/webv2/src/platform/ui/Toolbar.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Tooltip.tsx b/invokeai/frontend/webv2/src/platform/ui/Tooltip.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/Tooltip.tsxrename to invokeai/frontend/webv2/src/platform/ui/Tooltip.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/colorPickerSync.test.ts b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/colorPickerSync.test.tsrename to invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/colorPickerSync.ts b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/colorPickerSync.tsrename to invokeai/frontend/webv2/src/platform/ui/colorPickerSync.tsdiff --git a/invokeai/frontend/webv2/src/workbench/components/ui/index.ts b/invokeai/frontend/webv2/src/platform/ui/index.tssimilarity index 93%rename from invokeai/frontend/webv2/src/workbench/components/ui/index.tsrename to invokeai/frontend/webv2/src/platform/ui/index.tsindex 50e2702632..28d600a2f7 100644--- a/invokeai/frontend/webv2/src/workbench/components/ui/index.ts+++ b/invokeai/frontend/webv2/src/platform/ui/index.ts@@ -12,6 +12,7 @@ export * from './Row';export * from './Scrollable';export * from './Select';export * from './Slider';+export * from './StatusWidgetChip';export * from './Tabs';export * from './toaster';export * from './Toolbar';diff --git a/invokeai/frontend/webv2/src/workbench/images/StreamingImageFrame.tsx b/invokeai/frontend/webv2/src/platform/ui/streaming-image/StreamingImageFrame.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/images/StreamingImageFrame.tsxrename to invokeai/frontend/webv2/src/platform/ui/streaming-image/StreamingImageFrame.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/images/streamingImageSource.test.ts b/invokeai/frontend/webv2/src/platform/ui/streaming-image/streamingImageSource.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/images/streamingImageSource.test.tsrename to invokeai/frontend/webv2/src/platform/ui/streaming-image/streamingImageSource.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/images/streamingImageSource.ts b/invokeai/frontend/webv2/src/platform/ui/streaming-image/streamingImageSource.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/images/streamingImageSource.tsrename to invokeai/frontend/webv2/src/platform/ui/streaming-image/streamingImageSource.tsdiff --git a/invokeai/frontend/webv2/src/workbench/images/useStreamingImageSource.ts b/invokeai/frontend/webv2/src/platform/ui/streaming-image/useStreamingImageSource.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/images/useStreamingImageSource.tsrename to invokeai/frontend/webv2/src/platform/ui/streaming-image/useStreamingImageSource.tsdiff --git a/invokeai/frontend/webv2/src/theme/__fixtures__/legacyTokenBaseline.json b/invokeai/frontend/webv2/src/platform/ui/theme/__fixtures__/legacyTokenBaseline.jsonsimilarity index 100%rename from invokeai/frontend/webv2/src/theme/__fixtures__/legacyTokenBaseline.jsonrename to invokeai/frontend/webv2/src/platform/ui/theme/__fixtures__/legacyTokenBaseline.jsondiff --git a/invokeai/frontend/webv2/src/theme/__tokenResolve.ts b/invokeai/frontend/webv2/src/platform/ui/theme/__tokenResolve.tssimilarity index 100%rename from invokeai/frontend/webv2/src/theme/__tokenResolve.tsrename to invokeai/frontend/webv2/src/platform/ui/theme/__tokenResolve.tsdiff --git a/invokeai/frontend/webv2/src/theme/recipes.ts b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.tssimilarity index 98%rename from invokeai/frontend/webv2/src/theme/recipes.tsrename to invokeai/frontend/webv2/src/platform/ui/theme/recipes.tsindex a3ca67514b..373511b28e 100644--- a/invokeai/frontend/webv2/src/theme/recipes.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts@@ -12,7 +12,7 @@ import { slotRecipes as chakraSlotRecipes } from '@chakra-ui/react/theme';* instance app-wide gets the workbench chrome with zero props at the call* site.* 2. Workbench-specific recipes (`panel`, `row`, `chip`, `fieldLabel`,- * `themeCard`) — consumed via the wrappers in `workbench/components/ui`+ * `themeCard`) — consumed via the wrappers in `platform/ui`* with `useRecipe({ recipe })` / `useSlotRecipe({ recipe })`, which keeps* them fully typed without the Chakra typegen step.*@@ -188,7 +188,7 @@ export const progressCircleSlotRecipe = defineSlotRecipe({});/* -------------------------------------------------------------------------- *- * Workbench recipes (consumed through workbench/components/ui wrappers)+ * Reusable UI recipes (consumed through Platform UI wrappers)* -------------------------------------------------------------------------- *//** Bordered surface container — panels, cards, wells. */diff --git a/invokeai/frontend/webv2/src/theme/system.test.ts b/invokeai/frontend/webv2/src/platform/ui/theme/system.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/theme/system.test.tsrename to invokeai/frontend/webv2/src/platform/ui/theme/system.test.tsdiff --git a/invokeai/frontend/webv2/src/theme/system.ts b/invokeai/frontend/webv2/src/platform/ui/theme/system.tssimilarity index 100%rename from invokeai/frontend/webv2/src/theme/system.tsrename to invokeai/frontend/webv2/src/platform/ui/theme/system.tsdiff --git a/invokeai/frontend/webv2/src/theme/themes.ts b/invokeai/frontend/webv2/src/platform/ui/theme/themes.tssimilarity index 99%rename from invokeai/frontend/webv2/src/theme/themes.tsrename to invokeai/frontend/webv2/src/platform/ui/theme/themes.tsindex 082823b5b8..7231b494b1 100644--- a/invokeai/frontend/webv2/src/theme/themes.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/themes.ts@@ -1,4 +1,4 @@-import type { WorkbenchThemeId } from '@workbench/types';+export type WorkbenchThemeId = 'classic' | 'light' | 'forest' | 'mono' | 'ultradark';/*** Steps of the neutral ramp. `50` is the lightest, `950` the darkest — the samediff --git a/invokeai/frontend/webv2/src/workbench/components/ui/toaster.tsx b/invokeai/frontend/webv2/src/platform/ui/toaster.tsxsimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/components/ui/toaster.tsxrename to invokeai/frontend/webv2/src/platform/ui/toaster.tsxdiff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsxindex 273c175c8a..6f0a766b66 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx@@ -1,44 +1,24 @@-import {- createContext,- use,- useEffect,- useEffectEvent,- useRef,- useSyncExternalStore,- useState,- type Dispatch,- type ReactNode,-} from 'react';--import type {- Project,- ProjectLayoutState,- ProjectSettings,- WidgetInstanceId,- WidgetTypeId,- WorkbenchState,-} from './types';+import type { ProjectLayoutState } from '@workbench/layoutContracts';+import type { Project } from '@workbench/projectContracts';+import type { ProjectSettings } from '@workbench/settings/contracts';+import type { WidgetInstanceId, WidgetTypeId } from '@workbench/widgetContracts';++import { useMountEffect } from '@platform/react/useMountEffect';+import { shallowEqual as selectorShallowEqual, useExternalStoreSelector } from '@platform/state/selectors';+import { createContext, use, useEffect, useSyncExternalStore, useState, type ReactNode } from 'react';import { WorkbenchSplashScreen } from './components/WorkbenchSplashScreen';+import { createWorkbenchPersistenceRuntime } from './persistenceRuntime';import {- syncedWorkbenchPersistence,+ createSyncedWorkbenchPersistence,+ type SyncedWorkbenchPersistence,type WorkbenchLoadOptions,- type WorkbenchSaveResult,} from './projects/syncedPersistence';import { getProjectWidgetValues } from './widgetState';-import { getAutosaveScheduleDecision, isAutosaveCompletionCurrent } from './workbenchAutosave';-import { shallowEqual as selectorShallowEqual, useExternalStoreSelector } from './workbenchSelectors';-import {- createWorkbenchStore,- type WorkbenchAction,- type WorkbenchSnapshot,- type WorkbenchStore,-} from './workbenchStore';+import { createWorkbenchStore, type WorkbenchSnapshot, type WorkbenchInternalStore } from './workbenchStore';interface WorkbenchContextValue {- state: WorkbenchState;activeProject: Project;- dispatch: Dispatch<WorkbenchAction>;/*** True once the persisted snapshot has been loaded (or found absent). Side* effects that read or mutate the queue must wait for this, or they race the@@ -50,22 +30,13 @@ interface WorkbenchContextValue {type EqualityFn<T> = (left: T, right: T) => boolean;type WorkbenchSelector<T> = (snapshot: WorkbenchSnapshot) => T;-const WorkbenchStoreContext = createContext<WorkbenchStore | null>(null);+const WorkbenchStoreContext = createContext<WorkbenchInternalStore | null>(null);+const WorkbenchPersistenceContext = createContext<SyncedWorkbenchPersistence | null>(null);const subscribeToNothing = (): (() => void) => () => {};const getNullSnapshot = (): null => null;export const shallowEqual = selectorShallowEqual;-/**- * The reducer dispatch alone, on its own context. `dispatch` is stable for the- * provider's lifetime, so subscribers never re-render on state changes — the- * subscription of choice for hot, many-instance components (e.g. flow nodes)- * that only write.- */-const WorkbenchDispatchContext = createContext<Dispatch<WorkbenchAction> | null>(null);--const AUTOSAVE_DELAY_MS = 500;-export const WorkbenchProvider = ({children,loadOptions,@@ -75,241 +46,44 @@ export const WorkbenchProvider = ({loadOptions?: WorkbenchLoadOptions;}) => {const [store] = useState(() => createWorkbenchStore());- const dispatch = store.dispatch;- const [hasHydrated, setHasHydrated] = useState(store.getSnapshot().hasHydrated);- const hasLoadedPersistenceRef = useRef(false);- const lastSavedPersistedRevisionRef = useRef(store.getPersistedRevision());- const failedPersistedRevisionRef = useRef<number | null>(null);- // Captured once: the options describe how this mount of the editor boots.- // Later search-param changes are handled live by WorkbenchSessionController.- const bootOptionsRef = useRef(loadOptions);-- useEffect(() => {- let isCancelled = false;-- const loadPersistedState = async () => {- const bootOptions = bootOptionsRef.current;-- try {- const snapshot = await syncedWorkbenchPersistence.loadWorkbench(bootOptions);-- if (isCancelled) {- return;- }-- if (snapshot) {- const isPendingSnapshot = syncedWorkbenchPersistence.hasPendingChanges();-- dispatch({ state: snapshot.state, type: 'hydrateWorkbench' });-- if (!isPendingSnapshot) {- lastSavedPersistedRevisionRef.current = store.getPersistedRevision();- }- }-- const requestedId = bootOptions?.openProjectId;- const projects = snapshot?.state.projects ?? store.getState().projects;-- if (requestedId && !projects.some((project) => project.id === requestedId)) {- dispatch({+ const [persistence] = useState(createSyncedWorkbenchPersistence);+ const hasHydrated = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot).hasHydrated;++ // The runtime is created inside the effect: disposal is terminal, so each+ // mount (including a StrictMode remount) must get its own instance.+ useMountEffect(() => {+ const persistenceRuntime = createWorkbenchPersistenceRuntime({+ aggregate: {+ ...store.internal.persistence,+ getPersistedRevision: store.getPersistedRevision,+ notifyProjectNotFound: () =>+ store.commands.notifications.add({kind: 'info',message: 'The linked project does not exist on this account — it may have been deleted.',title: 'Project not found',- type: 'recordNotice',- });- }- } catch (error) {- dispatch({- area: 'persistence-load',- message: error instanceof Error ? error.message : 'Failed to load persisted workbench.',- namespace: 'system',- type: 'recordError',- });- } finally {- hasLoadedPersistenceRef.current = true;-- if (!isCancelled) {- store.setHasHydrated(true);- setHasHydrated(true);- }- }- };-- void loadPersistedState();-- return () => {- isCancelled = true;- };- }, [dispatch, store]);-- // Revision conflicts surfaced by a save are applied to state here: the- // server version adopts the project id and the local edits continue in a- // recovered fork. The follow-up autosave still persists the reconciled- // session/cache, while project document pushes are no-ops because the sync- // layer already acknowledged them.- const applySaveResult = useEffectEvent((result: WorkbenchSaveResult): void => {- for (const conflict of result.conflicts) {- dispatch({- projectId: conflict.projectId,- recoveredProject: conflict.recoveredProject,- serverProject: conflict.serverProject,- type: 'reconcileProjectConflict',- });- }- });-- useEffect(() => {- let timeoutId: number | null = null;- let saveGeneration = 0;- let scheduledPersistedRevision: number | null = null;-- const clearScheduledSave = (): void => {- if (timeoutId !== null) {- window.clearTimeout(timeoutId);- timeoutId = null;- }- };-- const scheduleSave = (): void => {- if (!hasLoadedPersistenceRef.current) {- return;- }-- const persistedRevision = store.getPersistedRevision();- const decision = getAutosaveScheduleDecision({- failedPersistedRevision: failedPersistedRevisionRef.current,- lastSavedPersistedRevision: lastSavedPersistedRevisionRef.current,- persistedRevision,- scheduledPersistedRevision,- });-- failedPersistedRevisionRef.current = decision.failedPersistedRevision;-- if (!decision.shouldSchedule) {- return;- }-- scheduledPersistedRevision = persistedRevision;- saveGeneration += 1;- const generation = saveGeneration;-- clearScheduledSave();-- timeoutId = window.setTimeout(() => {- const stateToSave = store.getState();- const revisionToSave = store.getPersistedRevision();-- dispatch({ type: 'autosaveStarted' });-- syncedWorkbenchPersistence- .saveWorkbench(stateToSave)- .then((result) => {- if (generation !== saveGeneration) {- return;- }-- lastSavedPersistedRevisionRef.current = revisionToSave;- failedPersistedRevisionRef.current = null;- scheduledPersistedRevision = null;- dispatch({ savedAt: result.snapshot.savedAt, type: 'autosaveSucceeded' });- applySaveResult(result);- })- .catch((error: unknown) => {- if (generation !== saveGeneration) {- return;- }-- failedPersistedRevisionRef.current = revisionToSave;- scheduledPersistedRevision = null;- dispatch({- error: error instanceof Error ? error.message : 'Failed to autosave workbench.',- type: 'autosaveFailed',- });- });- }, AUTOSAVE_DELAY_MS);- };-- const unsubscribe = store.subscribe(scheduleSave);- scheduleSave();-- return () => {- unsubscribe();- saveGeneration += 1;- clearScheduledSave();- };- }, [dispatch, store]);-- // Replay changes that queued up while the backend was unreachable as soon- // as the socket reports it is back.- useEffect(() => {- let previousStatus = store.getState().backendConnection.status;-- return store.subscribe(() => {- const status = store.getState().backendConnection.status;-- if (status === previousStatus) {- return;- }-- previousStatus = status;-- if (- status !== 'connected' ||- !hasLoadedPersistenceRef.current ||- !syncedWorkbenchPersistence.hasPendingChanges()- ) {- return;- }-- const stateToSave = store.getState();- const revisionToSave = store.getPersistedRevision();-- void syncedWorkbenchPersistence- .saveWorkbench(stateToSave)- .then((result) => {- if (- !isAutosaveCompletionCurrent({- completedPersistedRevision: revisionToSave,- currentPersistedRevision: store.getPersistedRevision(),- })- ) {- return;- }-- lastSavedPersistedRevisionRef.current = revisionToSave;- failedPersistedRevisionRef.current = null;- dispatch({ savedAt: result.snapshot.savedAt, type: 'autosaveSucceeded' });- applySaveResult(result);- })- .catch((error: unknown) => {- if (- !isAutosaveCompletionCurrent({- completedPersistedRevision: revisionToSave,- currentPersistedRevision: store.getPersistedRevision(),- })- ) {- return;- }-- failedPersistedRevisionRef.current = revisionToSave;- dispatch({- error: error instanceof Error ? error.message : 'Failed to autosave workbench.',- type: 'autosaveFailed',- });- });+ }),+ reportLoadError: (message) =>+ store.commands.notifications.reportError({ area: 'persistence-load', message, namespace: 'system' }),+ setHasHydrated: store.setHasHydrated,+ subscribe: store.subscribe,+ },+ loadOptions,+ persistence,});- }, [dispatch, store]);+ persistenceRuntime.start();+ return () => persistenceRuntime.dispose();+ });return (- <WorkbenchStoreContext value={store}>- <WorkbenchDispatchContext value={dispatch}>+ <WorkbenchPersistenceContext value={persistence}>+ <WorkbenchStoreContext value={store}>{hasHydrated ? children : <WorkbenchSplashScreen messageKey="splash.openingProject" />}- </WorkbenchDispatchContext>- </WorkbenchStoreContext>+ </WorkbenchStoreContext>+ </WorkbenchPersistenceContext>);};-export const useWorkbenchStore = (): WorkbenchStore => {+const useWorkbenchStore = (): WorkbenchInternalStore => {const store = use(WorkbenchStoreContext);if (!store) {@@ -319,7 +93,12 @@ export const useWorkbenchStore = (): WorkbenchStore => {return store;};-export const useOptionalWorkbenchStore = (): WorkbenchStore | null => use(WorkbenchStoreContext);+const useOptionalWorkbenchStore = (): WorkbenchInternalStore | null => use(WorkbenchStoreContext);++/** Privileged aggregate adapter for persistence and resource-owning runtimes only. */+export const useWorkbenchInternalStore = (): WorkbenchInternalStore => useWorkbenchStore();++export const useHasWorkbenchProvider = (): boolean => useOptionalWorkbenchStore() !== null;export const useWorkbenchSelector = <Selected,>(selector: WorkbenchSelector<Selected>,@@ -362,7 +141,7 @@ export const useActiveProjectSelector = <Selected,>(isEqual?: EqualityFn<Selected>): Selected => useWorkbenchSelector((snapshot) => selector(snapshot.activeProject), isEqual);-export const useActiveProjectId = (): string => useWorkbenchSelector((snapshot) => snapshot.state.activeProjectId);+export const useActiveProjectId = (): string => useWorkbenchSelector((snapshot) => snapshot.activeProject.id);export const useActiveProjectName = (): string => useActiveProjectSelector((project) => project.name);@@ -396,13 +175,39 @@ export const useProjectWidgetInstanceValuesSelector = <Selected,>(isEqual?: EqualityFn<Selected>): Selected =>useWorkbenchSelector((snapshot) => {- const project = snapshot.state.projects.find((candidate) => candidate.id === projectId);+ const project = snapshot.projects.find((candidate) => candidate.id === projectId);return selector(project?.widgetInstances[instanceId]?.state.values ?? {});}, isEqual);export const useWorkbenchHasHydrated = (): boolean => useWorkbenchSelector((snapshot) => snapshot.hasHydrated);+/** Stable intent-oriented aggregate commands; callers never receive reducer actions. */+export const useWorkbenchCommands = () => useWorkbenchStore().commands;++export const useWorkbenchQueries = () => useWorkbenchStore().queries;++/** Stable read-model subscription used by external runtime adapters. */+export const useWorkbenchSubscription = () => useWorkbenchStore().subscribe;++/** Privileged persistence read/write port; this is the only UI-adjacent full-state adapter. */+export const useWorkbenchPersistenceAdapter = () => useWorkbenchStore().internal.persistence;++export const useWorkbenchPersistenceService = (): SyncedWorkbenchPersistence => {+ const persistence = use(WorkbenchPersistenceContext);+ if (!persistence) {+ throw new Error('useWorkbenchPersistenceService must be used within a WorkbenchProvider.');+ }+ return persistence;+};++export const useOptionalWorkbenchPersistenceService = (): SyncedWorkbenchPersistence | null =>+ use(WorkbenchPersistenceContext);++export const useOptionalWorkbenchCommands = () => useOptionalWorkbenchStore()?.commands ?? null;++export const useOptionalWorkbenchQueries = () => useOptionalWorkbenchStore()?.queries ?? null;+export const useOptionalWorkbenchSelector = <Selected,>(selector: WorkbenchSelector<Selected>,fallback: Selected,@@ -418,14 +223,11 @@ export const useOptionalWorkbenchSelector = <Selected,>();};-export const useOptionalWorkbenchDispatch = (): Dispatch<WorkbenchAction> | null =>- useOptionalWorkbenchStore()?.dispatch ?? null;-export const useWorkbench = (): WorkbenchContextValue => {const store = useWorkbenchStore();const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);- return { ...snapshot, dispatch: store.dispatch };+ return snapshot;};export const useOptionalWorkbench = (): WorkbenchContextValue | null => {@@ -436,15 +238,5 @@ export const useOptionalWorkbench = (): WorkbenchContextValue | null => {store?.getSnapshot ?? getNullSnapshot);- return store && snapshot ? { ...snapshot, dispatch: store.dispatch } : null;-};--export const useWorkbenchDispatch = (): Dispatch<WorkbenchAction> => {- const dispatch = use(WorkbenchDispatchContext);-- if (!dispatch) {- throw new Error('useWorkbenchDispatch must be used within a WorkbenchProvider.');- }-- return dispatch;+ return store && snapshot ? snapshot : null;};diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.test.tsdeleted file mode 100644index 45fa97d01f..0000000000--- a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.test.ts+++ /dev/null@@ -1,167 +0,0 @@-import { describe, expect, it } from 'vitest';--import type { GenerateWidgetValues, MainModelConfig } from './generation/types';-import type { GraphContract, Project, QueueItem } from './types';--import { getDefaultGenerateSettings } from './generation/baseGenerationPolicies';-import { createQueueItemBackendSubmission, getQueueItemResultImageOptions } from './WorkbenchRuntime';-import { createInitialWorkbenchState } from './workbenchState';--const model: MainModelConfig = { base: 'sd-1', key: 'sd1', name: 'SD 1.5', type: 'main' };--const createValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWidgetValues => ({- ...getDefaultGenerateSettings(model),- model,- modelKey: model.key,- negativePrompt: 'low quality',- positivePrompt: 'a canvas prompt',- seed: 123,- shouldRandomizeSeed: true,- ...overrides,-});--const graph: GraphContract = {- backendGraph: { edges: [], id: 'backend-graph', nodes: {} },- edges: [],- id: 'graph-1',- label: 'Canvas',- nodes: [],- updatedAt: '2026-06-09T00:00:00.000Z',- version: 1,-};--const createProject = (): Project => createInitialWorkbenchState().projects[0]!;--const createQueueItem = (project: Project, overrides: Partial<QueueItem['snapshot']>): QueueItem => ({- cancellable: true,- id: 'local-1',- snapshot: {- canvas: project.canvas,- destination: 'canvas',- graph,- sourceId: 'canvas',- submittedAt: '2026-06-09T00:00:00.000Z',- widgetInstances: project.widgetInstances,- widgetStates: Object.fromEntries(- Object.values(project.widgetInstances).map((instance) => [instance.typeId, instance.state])- ),- ...overrides,- },- status: 'pending',-});--describe('createQueueItemBackendSubmission', () => {- it('submits canvas queue items through the generate batch path with resolved prompt and seed metadata', () => {- const project = createProject();- const values = createValues({- batchCount: 4,- negativePrompt: 'avoid blur',- positivePrompt: 'inpaint prompt',- seed: 987,- });- const queueItem = createQueueItem(project, {- generate: {- negativePromptNodeId: 'canvas_negative_prompt',- positivePromptNodeId: 'canvas_positive_prompt',- seedNodeId: 'canvas_seed',- values,- },- sourceId: 'canvas',- });-- const submission = createQueueItemBackendSubmission(project, queueItem);-- expect(submission).toEqual({- kind: 'generate',- request: {- batchCount: 4,- destination: 'canvas',- graph: graph.backendGraph,- negativePrompt: 'avoid blur',- negativePromptNodeId: 'canvas_negative_prompt',- positivePrompt: 'inpaint prompt',- positivePromptNodeId: 'canvas_positive_prompt',- projectId: project.id,- seed: 987,- seedNodeId: 'canvas_seed',- shouldRandomizeSeed: true,- sourceQueueItemId: 'local-1',- },- });- });-- it('falls back to legacy canvas widget-state metadata when a persisted snapshot has no generate payload', () => {- const project = createProject();- const values = createValues({- batchCount: 2,- negativePrompt: 'legacy negative',- positivePrompt: 'legacy prompt',- seed: 321,- shouldRandomizeSeed: false,- });- const queueItem = createQueueItem(project, {- sourceId: 'canvas',- widgetStates: {- ...createQueueItem(project, {}).snapshot.widgetStates,- generate: { id: 'generate', label: 'Generate', values: { ...values } as Record<string, unknown>, version: 1 },- },- });-- const submission = createQueueItemBackendSubmission(project, queueItem);-- expect(submission).toEqual({- kind: 'generate',- request: {- batchCount: 2,- destination: 'canvas',- graph: graph.backendGraph,- negativePrompt: 'legacy negative',- negativePromptNodeId: 'negative_prompt',- positivePrompt: 'legacy prompt',- positivePromptNodeId: 'positive_prompt',- projectId: project.id,- seed: 321,- seedNodeId: 'seed',- shouldRandomizeSeed: false,- sourceQueueItemId: 'local-1',- },- });- });-- it('keeps workflow queue items on the workflow path', () => {- const project = createProject();- const queueItem = createQueueItem(project, { destination: 'gallery', sourceId: 'workflow' });-- const submission = createQueueItemBackendSubmission(project, queueItem);-- expect(submission).toEqual({- kind: 'workflow',- request: {- batchCount: 1,- destination: 'gallery',- graph: graph.backendGraph,- projectId: project.id,- sourceQueueItemId: 'local-1',- },- });- });-});--describe('getQueueItemResultImageOptions', () => {- it('limits generated and canvas queue items to the compiled graph output node', () => {- const project = createProject();-- expect(getQueueItemResultImageOptions(createQueueItem(project, { sourceId: 'generate' }))).toEqual({- resultNodeIds: ['canvas_output'],- });- expect(getQueueItemResultImageOptions(createQueueItem(project, { sourceId: 'canvas' }))).toEqual({- resultNodeIds: ['canvas_output'],- });- });-- it('leaves workflow result nodes unconstrained', () => {- const project = createProject();-- expect(getQueueItemResultImageOptions(createQueueItem(project, { sourceId: 'workflow' }))).toBeUndefined();- });-});diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsxindex 1d526b37c0..a758b8f6eb 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx@@ -1,593 +1,33 @@-import { useEffect, useRef, useState, type Dispatch } from 'react';+import { useMountEffect } from '@platform/react/useMountEffect';-import type { EnqueueGenerateRequest, EnqueueWorkflowRequest } from './generation/types';-import type { Project, QueueItem } from './types';-import type { WorkbenchAction } from './workbenchState';--import { getConnectionStatus, subscribeConnection } from './backend/connectionStore';-import { getApiErrorMessage } from './backend/http';-import {- createQueueCoordinator,- QueueItemCancelledError,- type QueueCoordinator,- type ReconcileInput,-} from './backend/queueCoordinator';-import { socketHub } from './backend/socketHub';import { createCanvasDimsSync } from './canvasDimsSync';import { configureDiagnostics } from './diagnostics/logger';-import { addImagesToGalleryBoard } from './gallery/api';-import { getQueueItemResultImages, resumeQueueProcessor, type QueueItemResultImageOptions } from './generation/api';-import { normalizeGenerateSettings } from './generation/settings';-import { getQueueItemSnapshotBatchCount } from './queueSnapshot';-import { shouldSubmitPendingQueueItem } from './queueSubmission';-import { useWorkbenchPreferenceSelector } from './settings/store';-import { normalizeUpscaleWidgetValues } from './upscale/settings';-import {- useWorkbenchDispatch,- useWorkbenchHasHydrated,- useWorkbenchSelector,- useWorkbenchStore,-} from './WorkbenchContext';-import { createStableSelector } from './workbenchSelectors';-import { ensureInvocationTemplatesLoaded } from './workflows/templates';--const getSnapshotGalleryBoardId = (queueItem: QueueItem): string | null => {- const selectedBoardId = queueItem.snapshot.widgetStates.gallery.values.selectedBoardId;-- return typeof selectedBoardId === 'string' ? selectedBoardId : null;-};--const toErrorMessage = (error: unknown): string =>- getApiErrorMessage(error, error instanceof Error ? error.message : String(error));--type QueueItemBackendSubmission =- | { kind: 'generate'; request: EnqueueGenerateRequest }- | { kind: 'workflow'; request: EnqueueWorkflowRequest }- | { error: string; kind: 'invalid' };--const COMPILED_GENERATE_RESULT_NODE_ID = 'canvas_output';-const COMPILED_UPSCALE_RESULT_NODE_ID = 'upscale_output';--export const getQueueItemResultImageOptions = (queueItem: QueueItem): QueueItemResultImageOptions | undefined => {- if (queueItem.snapshot.sourceId === 'generate' || queueItem.snapshot.sourceId === 'canvas') {- return { resultNodeIds: [COMPILED_GENERATE_RESULT_NODE_ID] };- }- if (queueItem.snapshot.sourceId === 'upscale') {- return { resultNodeIds: [COMPILED_UPSCALE_RESULT_NODE_ID] };- }-- return undefined;-};--export const createQueueItemBackendSubmission = (- project: Project,- queueItem: QueueItem-): QueueItemBackendSubmission => {- const graph = queueItem.snapshot.graph.backendGraph;-- if (!graph) {- return { error: `${queueItem.snapshot.sourceId} queue item is missing a compiled backend graph.`, kind: 'invalid' };- }-- if (queueItem.snapshot.sourceId === 'generate') {- const generateValues = normalizeGenerateSettings(queueItem.snapshot.widgetStates.generate?.values);-- if (!generateValues) {- return { error: 'generate queue item is missing generation settings.', kind: 'invalid' };- }-- return {- kind: 'generate',- request: {- batchCount: generateValues.batchCount,- destination: queueItem.snapshot.destination,- graph,- negativePrompt: generateValues.negativePromptEnabled ? generateValues.negativePrompt : '',- negativePromptNodeId: 'negative_prompt',- positivePrompt: generateValues.positivePrompt,- positivePromptNodeId: 'positive_prompt',- projectId: project.id,- seed: generateValues.seed,- seedNodeId: 'seed',- shouldRandomizeSeed: generateValues.shouldRandomizeSeed,- sourceQueueItemId: queueItem.id,- },- };- }-- if (queueItem.snapshot.sourceId === 'canvas') {- const generate = queueItem.snapshot.generate;- // Persisted canvas queue items from before `snapshot.generate` existed still- // carry the generate widget snapshot; use it rather than falling back to- // backend primitive defaults for prompt/seed.- const generateValues = normalizeGenerateSettings(- generate ? generate.values : queueItem.snapshot.widgetStates.generate?.values- );-- if (!generateValues) {- return { error: 'canvas queue item is missing generation submission metadata.', kind: 'invalid' };- }-- return {- kind: 'generate',- request: {- batchCount: generateValues.batchCount,- destination: queueItem.snapshot.destination,- graph,- negativePrompt: generateValues.negativePromptEnabled ? generateValues.negativePrompt : '',- negativePromptNodeId: generate?.negativePromptNodeId ?? 'negative_prompt',- positivePrompt: generateValues.positivePrompt,- positivePromptNodeId: generate?.positivePromptNodeId ?? 'positive_prompt',- projectId: project.id,- seed: generateValues.seed,- seedNodeId: generate?.seedNodeId ?? 'seed',- shouldRandomizeSeed: generateValues.shouldRandomizeSeed,- sourceQueueItemId: queueItem.id,- },- };- }-- if (queueItem.snapshot.sourceId === 'upscale') {- const upscaleValues = normalizeUpscaleWidgetValues(queueItem.snapshot.widgetStates.upscale?.values);-- if (!upscaleValues) {- return { error: 'upscale queue item is missing upscale submission metadata.', kind: 'invalid' };- }-- return {- kind: 'generate',- request: {- batchCount: upscaleValues.batchCount,- destination: queueItem.snapshot.destination,- graph,- negativePrompt: upscaleValues.negativePromptEnabled ? upscaleValues.negativePrompt : '',- negativePromptNodeId: 'negative_prompt',- positivePrompt: upscaleValues.positivePrompt,- positivePromptNodeId: 'positive_prompt',- projectId: project.id,- seed: upscaleValues.seed,- seedNodeId: 'seed',- shouldRandomizeSeed: upscaleValues.shouldRandomizeSeed,- sourceQueueItemId: queueItem.id,- },- };- }-- return {- kind: 'workflow',- request: {- batchCount: getQueueItemSnapshotBatchCount(queueItem),- destination: queueItem.snapshot.destination,- graph,- projectId: project.id,- sourceQueueItemId: queueItem.id,- },- };-};--const selectQueueRevision = createStableSelector((snapshot: { state: { projects: Project[] } }) =>- snapshot.state.projects- .map((project) =>- [- project.id,- project.queue.items- .map((item) =>- [- item.id,- item.status,- item.backendBatchId ?? '',- item.backendItemIds?.join('.') ?? '',- item.cancelledBackendItemIds?.join('.') ?? '',- item.completedBackendItemIds?.join('.') ?? '',- ].join(':')- )- .join(','),- ].join('=')- )- .join('|')-);+import { subscribeWorkbenchPreferences } from './settings/store';+import { useWorkbenchInternalStore } from './WorkbenchContext';/**- * Await a tracked run's terminal outcome, route its images to the queue item's- * destination, and reflect the outcome in workbench state.+ * Workbench-owned lifecycle adapter for aggregate-local synchronization and+ * diagnostics. Cross-module adapters are constructed by App.*/-const routeRunResults = async (- coordinator: QueueCoordinator,- projectId: string,- queueItem: QueueItem,- dispatch: Dispatch<WorkbenchAction>-): Promise<void> => {- try {- const allImages = await coordinator.waitForResults(- queueItem.id,- queueItem.snapshot.submittedAt,- getQueueItemResultImageOptions(queueItem)- );- // A workflow session reports every image its nodes produced; only the- // non-intermediate outputs are user-facing results.- const images =- queueItem.snapshot.sourceId === 'workflow' ? allImages.filter((image) => !image.isIntermediate) : allImages;-- if (queueItem.snapshot.destination === 'gallery') {- const selectedBoardId = getSnapshotGalleryBoardId(queueItem);-- if (selectedBoardId && selectedBoardId !== 'none') {- await addImagesToGalleryBoard(- selectedBoardId,- images.map((image) => image.imageName)- );- }- }-- dispatch({ images, projectId, queueItemId: queueItem.id, type: 'routeQueueItemResults' });- if (queueItem.snapshot.destination === 'gallery') {- dispatch({ type: 'refreshBackendData' });- }- } catch (error) {- if (error instanceof QueueItemCancelledError) {- dispatch({ projectId, queueItemId: queueItem.id, status: 'cancelled', type: 'setQueueItemStatus' });- return;- }-- dispatch({- error: toErrorMessage(error),- projectId,- queueItemId: queueItem.id,- status: 'failed',- type: 'setQueueItemStatus',- });- }-};--/** Route one completed backend item from a still-running local batch into its destination. */-const routeBackendItemResults = async (- projectId: string,- queueItem: QueueItem,- backendItemId: number,- dispatch: Dispatch<WorkbenchAction>-): Promise<void> => {- try {- const resultImageOptions = getQueueItemResultImageOptions(queueItem);- const allImages = resultImageOptions- ? await getQueueItemResultImages(backendItemId, queueItem.id, queueItem.snapshot.submittedAt, resultImageOptions)- : await getQueueItemResultImages(backendItemId, queueItem.id, queueItem.snapshot.submittedAt);- const images =- queueItem.snapshot.sourceId === 'workflow' ? allImages.filter((image) => !image.isIntermediate) : allImages;- if (queueItem.snapshot.destination === 'gallery') {- const selectedBoardId = getSnapshotGalleryBoardId(queueItem);-- if (selectedBoardId && selectedBoardId !== 'none') {- await addImagesToGalleryBoard(- selectedBoardId,- images.map((image) => image.imageName)- );- }- }-- dispatch({ backendItemId, images, projectId, queueItemId: queueItem.id, type: 'routeQueueItemPartialResults' });- if (queueItem.snapshot.destination === 'gallery') {- dispatch({ type: 'refreshBackendData' });- }- } catch (error) {- dispatch({- area: 'queue-results',- message: toErrorMessage(error),- namespace: 'queue',- projectId,- type: 'recordError',- });- }-};--const submitQueueItem = (- coordinator: QueueCoordinator,- project: Project,- queueItem: QueueItem,- dispatch: Dispatch<WorkbenchAction>-): void => {- const backendSubmission = createQueueItemBackendSubmission(project, queueItem);-- if (backendSubmission.kind === 'invalid') {- dispatch({- error: backendSubmission.error,- projectId: project.id,- queueItemId: queueItem.id,- status: 'failed',- type: 'setQueueItemStatus',- });- return;- }-- const submission =- backendSubmission.kind === 'generate'- ? coordinator.submitGenerate(queueItem.id, backendSubmission.request)- : coordinator.submitWorkflow(queueItem.id, backendSubmission.request);-- submission- .then(({ batchId, itemIds }) => {- dispatch({- backendBatchId: batchId,- backendItemIds: itemIds,- projectId: project.id,- queueItemId: queueItem.id,- type: 'markQueueItemBackendSubmitted',- });-- // Enqueuing implies intent to run: a paused processor would otherwise leave- // the batch stuck "waiting for progress" forever. Mirrors the legacy app's- // `anyEnqueued` listener; `resume` is a no-op when already running.- void resumeQueueProcessor().catch(() => undefined);-- return routeRunResults(coordinator, project.id, queueItem, dispatch);- })- .catch((error: unknown) => {- dispatch({- error: toErrorMessage(error),- projectId: project.id,- queueItemId: queueItem.id,- status: 'failed',- type: 'setQueueItemStatus',+export const WorkbenchRuntime = () => {+ const store = useWorkbenchInternalStore();++ useMountEffect(() => {+ const canvasDimsSync = createCanvasDimsSync(store);+ const unsubscribeDiagnostics = subscribeWorkbenchPreferences((preferences) => {+ configureDiagnostics({+ enabled: preferences.developerLogEnabled,+ level: preferences.developerLogLevel,+ namespaces: preferences.developerLogNamespaces,+ performanceTimingsEnabled: preferences.developerPerformanceTimingsEnabled,});});-};--/**- * Bridges workbench state to the backend queue coordinator: it submits pending- * queue items, forwards cancellations, and reflects connection status, while- * the coordinator owns the socket and event-driven settlement. Mounted once- * inside the WorkbenchProvider; renders nothing.- */-export const WorkbenchRuntime = () => {- const store = useWorkbenchStore();- const dispatch = useWorkbenchDispatch();- const hasHydrated = useWorkbenchHasHydrated();- const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);- const diagnosticsPreferences = useWorkbenchPreferenceSelector((preferences) => ({- enabled: preferences.developerLogEnabled,- level: preferences.developerLogLevel,- namespaces: preferences.developerLogNamespaces,- performanceTimingsEnabled: preferences.developerPerformanceTimingsEnabled,- }));- const queueRevision = useWorkbenchSelector(selectQueueRevision);- const coordinatorRef = useRef<QueueCoordinator | null>(null);- const stateRef = useRef(store.getState());- const startedQueueItemIdsRef = useRef(new Set<string>());- const cancelledQueueItemIdsRef = useRef(new Set<string>());- const reconcileStateRef = useRef<'idle' | 'running' | 'done'>('idle');- const [isReconciled, setIsReconciled] = useState(false);-- useEffect(- () =>- store.subscribe(() => {- stateRef.current = store.getState();- }),- [store]- );-- // Keep the canvas generation frame and the generate-widget dimensions in sync- // while a project invokes into the canvas (the frame is the generation size).- // Lives beside the other store subscriptions; renders nothing.- useEffect(() => {- const sync = createCanvasDimsSync(store);-- return () => sync.dispose();- }, [store]);-- useEffect(() => {- configureDiagnostics(diagnosticsPreferences);- }, [diagnosticsPreferences]);-- // Mirror the shared socket's connection status (owned by the hub, above the- // workbench) into workbench state so the editor's many `backendConnection`- // consumers and the reconcile gate keep working unchanged. Seeds on mount so- // opening the editor over an already-live socket reconciles immediately.- useEffect(() => {- const syncConnection = () => {- const { error, status } = getConnectionStatus();-- dispatch({ error, status, type: 'setBackendConnectionStatus' });- };-- syncConnection();-- return subscribeConnection(syncConnection);- }, [dispatch]);-- useEffect(() => {- const coordinator = createQueueCoordinator(- {- onBackendItemComplete: (localQueueItemId, backendItemId) => {- const routeTarget = stateRef.current.projects- .map((project) => ({- project,- queueItem: project.queue.items.find((item) => item.id === localQueueItemId),- }))- .find((target) => target.queueItem !== undefined);-- if (!routeTarget?.queueItem || routeTarget.queueItem.completedBackendItemIds?.includes(backendItemId)) {- return;- }-- return routeBackendItemResults(routeTarget.project.id, routeTarget.queueItem, backendItemId, dispatch);- },- onBackendItemCancelled: (localQueueItemId, backendItemId) => {- const routeTarget = stateRef.current.projects- .map((project) => ({- project,- queueItem: project.queue.items.find((item) => item.id === localQueueItemId),- }))- .find((target) => target.queueItem !== undefined);-- if (!routeTarget?.queueItem || routeTarget.queueItem.cancelledBackendItemIds?.includes(backendItemId)) {- return;- }-- dispatch({- backendItemId,- projectId: routeTarget.project.id,- queueItemId: localQueueItemId,- type: 'markQueueItemBackendCancelled',- });- },- onGalleryRefresh: () => {- dispatch({ type: 'refreshBackendData' });- },- },- { hub: socketHub }- );-- coordinatorRef.current = coordinator;- coordinator.connect();- // Node definitions back workflow route validation, which can be the- // persisted invocation source before any workflow surface has mounted.- ensureInvocationTemplatesLoaded();return () => {- coordinatorRef.current = null;- coordinator.dispose();+ unsubscribeDiagnostics();+ canvasDimsSync.dispose();};- }, [dispatch]);-- // Reconcile persisted queue items against the live backend queue exactly- // once, after hydration and first connect. Until this finishes, submission- // is held back so an item the backend already accepted is not enqueued twice.- useEffect(() => {- const coordinator = coordinatorRef.current;-- if (- !coordinator ||- !hasHydrated ||- backendConnectionStatus !== 'connected' ||- reconcileStateRef.current !== 'idle'- ) {- return;- }-- reconcileStateRef.current = 'running';-- const openItems = stateRef.current.projects.flatMap((project) =>- project.queue.items- .filter((queueItem) => queueItem.status === 'pending' || queueItem.status === 'running')- .map((queueItem) => ({ project, queueItem }))- );-- for (const { queueItem } of openItems) {- startedQueueItemIdsRef.current.add(queueItem.id);- }-- const inputs: ReconcileInput[] = openItems.map(({ queueItem }) => ({- backendBatchId: queueItem.backendBatchId,- backendItemIds: queueItem.backendItemIds,- id: queueItem.id,- status: queueItem.status === 'running' ? 'running' : 'pending',- }));-- coordinator- .reconcile(inputs)- .then((outcomes) => {- for (const { project, queueItem } of openItems) {- const outcome = outcomes.get(queueItem.id);-- switch (outcome?.kind) {- case 'enqueue': {- startedQueueItemIdsRef.current.delete(queueItem.id);- break;- }- case 'adopted': {- dispatch({- backendBatchId: outcome.backendBatchId,- backendItemIds: outcome.backendItemIds,- projectId: project.id,- queueItemId: queueItem.id,- type: 'markQueueItemBackendSubmitted',- });- void routeRunResults(coordinator, project.id, queueItem, dispatch);- break;- }- case 'resumed': {- void routeRunResults(coordinator, project.id, queueItem, dispatch);- break;- }- case 'missing': {- dispatch({- error: 'This run is no longer on the backend queue (it may have been cleared).',- notify: false,- projectId: project.id,- queueItemId: queueItem.id,- status: 'failed',- type: 'setQueueItemStatus',- });- break;- }- }- }- })- .catch((error: unknown) => {- // Release pending items to the normal submission path; running items- // cannot be re-attached without backend state, so fail them visibly- // rather than leaving them stuck as running forever.- dispatch({- area: 'queue-reconciliation',- message: `Queue reconciliation failed: ${toErrorMessage(error)}`,- namespace: 'queue',- type: 'recordError',- });-- for (const { project, queueItem } of openItems) {- if (queueItem.status === 'pending') {- startedQueueItemIdsRef.current.delete(queueItem.id);- continue;- }-- dispatch({- error: 'Could not reconcile this run with the backend queue after reload.',- projectId: project.id,- queueItemId: queueItem.id,- status: 'failed',- type: 'setQueueItemStatus',- });- }- })- .finally(() => {- reconcileStateRef.current = 'done';- setIsReconciled(true);- });- }, [backendConnectionStatus, dispatch, hasHydrated, queueRevision]);-- useEffect(() => {- const coordinator = coordinatorRef.current;-- if (!coordinator || !isReconciled) {- return;- }-- for (const project of stateRef.current.projects) {- for (const queueItem of project.queue.items) {- if (shouldSubmitPendingQueueItem(queueItem) && !startedQueueItemIdsRef.current.has(queueItem.id)) {- startedQueueItemIdsRef.current.add(queueItem.id);- submitQueueItem(coordinator, project, queueItem, dispatch);- }-- if (- queueItem.status === 'cancelled' &&- (queueItem.backendBatchId || queueItem.backendItemIds?.length) &&- !cancelledQueueItemIdsRef.current.has(queueItem.id)- ) {- cancelledQueueItemIdsRef.current.add(queueItem.id);- coordinator- .cancelRun({ backendBatchId: queueItem.backendBatchId, backendItemIds: queueItem.backendItemIds })- .catch((error: unknown) => {- dispatch({- area: 'queue-cancel',- message: toErrorMessage(error),- namespace: 'queue',- type: 'recordError',- });- });- }- }- }- }, [dispatch, isReconciled, queueRevision]);+ });return null;};diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsxindex ded91294fd..86c16365b7 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsx@@ -1,83 +1,54 @@+import { flushGenerateDrafts } from '@features/generation/drafts';+import { useMountEffect } from '@platform/react/useMountEffect';+import { areArraysEqual } from '@platform/state/selectors';import { useNavigate } from '@tanstack/react-router';-import { useEffect, useRef } from 'react';import type { WorkbenchSearch } from './projects/session';-import { hydrateProjectFromServer } from './projects/syncedPersistence';-import { flushGenerateDrafts } from './widgets/generate/generateDraftRegistry';-import { useWorkbenchDispatch, useWorkbenchHasHydrated, useWorkbenchSelector } from './WorkbenchContext';-import { areArraysEqual } from './workbenchSelectors';+import {+ useWorkbenchCommands,+ useWorkbenchHasHydrated,+ useWorkbenchPersistenceService,+ useWorkbenchSelector,+} from './WorkbenchContext';-/**- * Keeps a mounted editor in line with the /app search params. Renders nothing.- *- * Boot is not its job — `WorkbenchProvider` consumes the params present at- * mount as load options. This covers what happens afterwards:- *- * - `?new` is stripped once hydration has consumed it, so a reload (or a- * bookmark) does not mint another draft project.- * - `?project` changing while the editor is open (a deep link clicked from- * elsewhere) focuses the tab if it is open, or hydrates it from the- * library and opens it if not.- */-export const WorkbenchSessionController = ({ search }: { search: WorkbenchSearch }) => {- const projectIds = useWorkbenchSelector(- (snapshot) => snapshot.state.projects.map((project) => project.id),- areArraysEqual- );- const dispatch = useWorkbenchDispatch();- const hasHydrated = useWorkbenchHasHydrated();+const HydratedSessionController = ({ search }: { search: WorkbenchSearch }) => {+ const commands = useWorkbenchCommands();const navigate = useNavigate();- const latestProjectIdsRef = useRef(projectIds);- // The mount-time param was already handled by the boot load options.- const handledProjectIdRef = useRef<string | null>(search.project ?? null);-- useEffect(() => {- latestProjectIdsRef.current = projectIds;- }, [projectIds]);-- const isNewRequested = search.new === true;+ const persistence = useWorkbenchPersistenceService();+ const projectIds = useWorkbenchSelector((snapshot) => snapshot.projects.map((project) => project.id), areArraysEqual);- useEffect(() => {- if (!hasHydrated || !isNewRequested) {+ useMountEffect(() => {+ if (search.new === true) {+ void navigate({ replace: true, search: {}, to: '/app' });return;}- void navigate({ replace: true, search: {}, to: '/app' });- }, [hasHydrated, isNewRequested, navigate]);-- const requestedProjectId = search.project;-- useEffect(() => {- if (!hasHydrated || !requestedProjectId || handledProjectIdRef.current === requestedProjectId) {- return undefined;+ const requestedProjectId = search.project;+ if (!requestedProjectId) {+ return;}- handledProjectIdRef.current = requestedProjectId;-- if (latestProjectIdsRef.current.includes(requestedProjectId)) {+ if (projectIds.includes(requestedProjectId)) {flushGenerateDrafts();- dispatch({ projectId: requestedProjectId, type: 'switchProject' });-- return undefined;+ commands.projects.switchTo(requestedProjectId);+ return;}let isCancelled = false;-- void hydrateProjectFromServer(requestedProjectId).then((project) => {+ void persistence.hydrateProjectFromServer(requestedProjectId).then((project) => {if (isCancelled) {return;}if (project) {flushGenerateDrafts();- dispatch({ project, type: 'openProject' });+ commands.projects.open(project);} else {- dispatch({+ commands.notifications.add({kind: 'info',message: 'The linked project does not exist on this account — it may have been deleted.',title: 'Project not found',- type: 'recordNotice',});}});@@ -85,7 +56,21 @@ export const WorkbenchSessionController = ({ search }: { search: WorkbenchSearchreturn () => {isCancelled = true;};- }, [dispatch, hasHydrated, requestedProjectId]);+ });return null;};++/**+ * Search changes remount the lifecycle adapter, eliminating effect-based prop+ * synchronization while preserving cancellation for asynchronous hydration.+ */+export const WorkbenchSessionController = ({ search }: { search: WorkbenchSearch }) => {+ const hasHydrated = useWorkbenchHasHydrated();++ if (!hasHydrated) {+ return null;+ }++ return <HydratedSessionController key={`${search.new === true}:${search.project ?? ''}`} search={search} />;+};diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchWidgetRegistryContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchWidgetRegistryContext.tsxindex bd61387b53..1accbc210b 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchWidgetRegistryContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchWidgetRegistryContext.tsx@@ -1,6 +1,7 @@-import { createContext, use, useMemo, type ReactNode } from 'react';+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { RegisteredWidget, WidgetTypeId } from '@workbench/widgetContracts';-import type { RegisteredWidget, WidgetRegion, WidgetTypeId } from './types';+import { createContext, use, useMemo, type ReactNode } from 'react';interface WorkbenchWidgetRegistryContextValue {getWidgetById: (widgetId: WidgetTypeId) => RegisteredWidget | undefined;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/api.tsindex 0dd22b0ddf..7a6d5a77e5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts@@ -1,211 +1,8 @@-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type {- CanvasDocumentContractV2,- CanvasImageRef,- CanvasLayerContract,- CanvasStagingCandidateContract,- CanvasStateContractV2,-} from '@workbench/types';--import type { CanvasEditGate } from './editGate';-import type { EngineStores } from './engineStores';-import type { RasterCompositeExportRequest, RasterCompositeExportResult } from './exportRasterComposite';-import type { RasterSurface } from './render/raster';-import type { Rect, ToolId, Vec2 } from './types';-import type { Viewport } from './viewport';--/** Opaque snapshot identity carried through asynchronous layer operations. */-export interface LayerExportGuard {- readonly projectId: string;- readonly layerId: string;- readonly layer: CanvasLayerContract;- readonly cacheVersion: number;- readonly documentGeneration: number;-}--export type CanvasCoreStores = EngineStores;--export interface CanvasCoreStoreCapability {- readonly stores: CanvasCoreStores;-}--export interface CanvasSurfaceCapability {- attach(screenCanvas: HTMLCanvasElement, overlayCanvas: HTMLCanvasElement): void;- detach(): void;- resize(cssWidth: number, cssHeight: number, dpr: number): void;-}--export interface CanvasDocumentCapability {- captureSnapshot(): CanvasDocumentSnapshot | null;- getDocument(): CanvasDocumentContractV2 | null;-}--/** Immutable reducer canvas state captured at one engine document generation. */-export interface CanvasDocumentSnapshot {- readonly canvas: CanvasStateContractV2;- readonly documentGeneration: number;-}--export interface CanvasDetachedLayerSurface {- readonly rect: Rect;- readonly surface: RasterSurface;-}--/** Caller-owned frozen pixels paired with the exact canvas contract that planned them. */-export interface CanvasRasterSnapshot extends CanvasDocumentSnapshot {- /** Requested layers confirmed to have no current live or persisted pixels. */- readonly emptyLayerIds: ReadonlySet<string>;- readonly layerSurfaces: ReadonlyMap<string, CanvasDetachedLayerSurface>;- /** Idempotently releases all detached-pixel memory owned by this snapshot. */- release(): void;-}--export type CaptureRasterSnapshotResult =- | { status: 'ok'; snapshot: CanvasRasterSnapshot }- | { status: 'stale' | 'aborted' | 'not-ready' | 'over-budget' };--export type PsdExportResult = 'exported' | 'nothing' | 'too-large' | 'not-ready' | 'over-budget' | 'stale' | 'aborted';--export interface CanvasPsdExportCapability {- exportRasterLayersToPsd(fileName: string): Promise<PsdExportResult>;-}--export interface CanvasViewportCapability {- getViewport(): Viewport;- fitToView(): void;- setBboxGrid(size: number): void;-}--export interface CanvasToolCapability {- setTool(toolId: ToolId, options?: { temporary?: boolean }): void;- stepBrushSize(direction: 1 | -1): void;-}--export interface CanvasHistoryCapability {- undo(): void;- redo(): void;- clearHistory(): void;-}--export type LayerThumbnailRequestResult = 'ready' | 'stale' | 'error' | 'missing' | 'unsupported' | 'over-budget';--export interface CanvasPreviewCapability {- drawLayerThumbnail(layerId: string, target: HTMLCanvasElement, maxSize: number): boolean;- requestLayerThumbnail(layerId: string): Promise<LayerThumbnailRequestResult>;-}--export interface CanvasExportCapability {- captureRasterSnapshot(- documentSnapshot: CanvasDocumentSnapshot,- layerIds: readonly string[],- options?: { signal?: AbortSignal; includeDisabled?: boolean }- ): Promise<CaptureRasterSnapshotResult>;- captureLayerExportGuard(layerId: string): LayerExportGuard | null;- exportBakedLayerBlob(layerId: string, options?: ExportBakedLayerPixelsOptions): Promise<ExportBakedLayerBlobResult>;- exportRasterComposite(request: RasterCompositeExportRequest): Promise<RasterCompositeExportResult>;- getCompositeExecutorDeps(): CanvasCompositeExecutorDeps;- hasExportableLayerContent(layerId: string): boolean;- isLayerExportGuardCurrent(guard: LayerExportGuard): boolean;-}--export type {- RasterCompositeExportRequest,- RasterCompositeExportResult,- RasterCompositeExportSnapshot,-} from './exportRasterComposite';--export interface ExportLayerPixelsOptions {- includeDisabled?: boolean;- applyAdjustments?: boolean;- signal?: AbortSignal;-}--export type ExportBakedLayerPixelsOptions = Omit<ExportLayerPixelsOptions, 'applyAdjustments'> & {- applyAdjustments?: boolean;-};--export type ExportBakedLayerBlobResult =- | { status: 'ok'; blob: Blob; rect: Rect; guard: LayerExportGuard }- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' | 'aborted' };--export interface CanvasCompositeExecutorDeps {- backend: {- createSurface(width: number, height: number): RasterSurface;- encodeSurface(surface: RasterSurface, type?: string): Promise<Blob>;- };- getLayerSurface(layerId: string): Promise<{ surface: RasterSurface; rect: Rect }>;- reserve?(- bytes: number- ):- | { status: 'ok'; lease: { release(): void } }- | { status: 'over-budget'; requestedBytes: number; availableBytes: number };- uploadImage(blob: Blob): Promise<{ imageName: string; width: number; height: number }>;-}--export interface CanvasSelectionCapability {- deselect(): void;- eraseSelection(): void;- fillSelection(): void;- getSelectionBounds(): Rect | null;- getSelectionMaskRect(): Rect | null;- invertSelection(): void;- replaceSelectionFromImage(- guard: LayerExportGuard,- image: CanvasImageRef,- rect: Rect,- signal?: AbortSignal- ): Promise<ReplaceSelectionFromImageResult>;- selectAll(): void;-}--export type ReplaceSelectionFromImageResult =- | { status: 'selected' }- | { status: 'aborted' | 'missing' | 'locked' | 'stale' | 'unsupported' | 'busy' }- | { status: 'failed'; message: string };--export interface CanvasLayerCapability {- applyStructuralPreview(action: CanvasProjectMutation): boolean;- canCommitStructural(): boolean;- commitGeneratedImageResult(options: CommitGeneratedImageOptions): Promise<CommitGeneratedImageResult>;- commitStagedImage(options: CommitStagedImageOptions): CommitStagedImageResult;- commitStructural(label: string, forward: CanvasProjectMutation, inverse: CanvasProjectMutation): boolean;- invertMask(layerId: string): boolean;-}--export interface CommitStagedImageOptions {- candidate: CanvasStagingCandidateContract;- selectedImageIndex: number;-}--export type CommitStagedImageResult =- | { status: 'committed'; layerId: string }- | { status: 'busy' | 'stale' | 'missing' };--export type GeneratedImageTarget = 'replace' | 'copy-raster' | 'copy-control';--export interface CommitGeneratedImageOptions {- guard: LayerExportGuard;- image: CanvasImageRef;- origin: Vec2;- target: GeneratedImageTarget;- historyLabel?: string;- copyLayerName?: string;- signal?: AbortSignal;-}--export type CommitGeneratedImageResult =- | { status: 'committed'; layerId: string }- | { status: 'missing' | 'locked' | 'stale' | 'unsupported' | 'busy' | 'aborted' }- | { status: 'failed'; message: string };--export type CanvasLifecycleState = 'active' | 'cooling' | 'cool' | 'disposed';--export interface CanvasLifecycleCapability {- activate(): void;- beginCooldown(): Promise<'cooled' | 'dirty'>;- dispose(): void;- getLifecycleState(): CanvasLifecycleState;- flushPendingUploads(): Promise<void>;-}--export type CanvasEditCapability = CanvasEditGate;+/**+ * Sole caller interface for the complete Canvas module.+ *+ * The rendering core depends only on `capabilities.ts`; this facade may compose+ * core capabilities with Canvas-owned application workflows without reversing+ * the core dependency direction.+ */+export * from './capabilities';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.tsindex b9b367e170..5b3900bfe2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts@@ -1,12 +1,12 @@import type {- CanvasCompositeExecutorDeps,CommitGeneratedImageOptions,CommitGeneratedImageResult,ExportBakedLayerBlobResult,ExportLayerPixelsOptions,LayerExportGuard,ReplaceSelectionFromImageResult,-} from '@workbench/canvas-engine/api';+} from '@workbench/canvas-engine/capabilities';+import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/canvas-engine/contracts';import type {CommitRasterFilterOptions,CommitRasterFilterResult,@@ -15,10 +15,10 @@ import type {CommitMaskImageResult,CommitMaskImageResultOptions,} from '@workbench/canvas-engine/controllers/maskResultController';+import type { CanvasCompositeExecutorDeps } from '@workbench/canvas-engine/rasterTransactions';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { SamInteractionState, SamVisualInput } from '@workbench/canvas-engine/samInteraction';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/types';export type SelectObjectStartContext =| { status: 'missing' | 'disabled' | 'locked' | 'unsupported' | 'not-ready' }diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.tsindex d21ac5a5a5..a0e64eb59c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts@@ -1,9 +1,9 @@-import type { Mat2d } from '@workbench/canvas-engine/types';import type {CanvasDocumentContractV2,CanvasLayerSourceContract,CanvasRasterLayerContractV2,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';+import type { Mat2d } from '@workbench/canvas-engine/types';import { executePsdExport, planPsdExport } from '@workbench/canvas-engine/export/psdExport';import { createHistory } from '@workbench/canvas-engine/history/history';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsnew file mode 100644index 0000000000..0cb6c3c7f8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -0,0 +1,417 @@+import type {+ CanvasDocumentContractV2,+ CanvasImageRef,+ CanvasLayerContract,+ CanvasStagingCandidateContract,+ CanvasStateContractV2,+} from '@workbench/canvas-engine/contracts';+import type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';+import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';++import type { CanvasEditGate } from './editGate';+import type {+ BboxToolOptions,+ BrushOptions,+ CheckerColors,+ EraserOptions,+ GradientToolOptions,+ LassoToolOptions,+ LayerThumbnailStatus,+ ShapeToolOptions,+ TextEditSession,+ TextToolOptions,+ TransformSession,+} from './engineStores';+import type { RasterCompositeExportRequest, RasterCompositeExportResult } from './exportRasterComposite';+import type { Rect, ToolId, Vec2 } from './types';+import type { Viewport } from './viewport';++/** Opaque snapshot identity carried through asynchronous layer operations. */+export interface LayerExportGuard {+ readonly projectId: string;+ readonly layerId: string;+ readonly layer: CanvasLayerContract;+ readonly cacheVersion: number;+ readonly documentGeneration: number;+}++export type CommitRasterFilterResult =+ | { status: 'committed'; layerId: string }+ | { status: 'missing' | 'locked' | 'stale' | 'unsupported' | 'busy' | 'aborted' }+ | { status: 'failed'; message: string };+export interface RasterFilterSettings {+ type: string;+ settings: Record<string, unknown>;+}+export type RasterFilterCommitTarget = 'apply' | 'raster' | 'control';+export interface CommitRasterFilterOptions {+ guard: LayerExportGuard;+ image: CanvasImageRef;+ rect: Rect;+ mode: 'replace' | 'copy';+ filter?: RasterFilterSettings;+ target?: RasterFilterCommitTarget;+ requireExactImageDimensions?: boolean;+ signal?: AbortSignal;+}+export type MaskImageResultTarget = 'inpaint_mask' | 'regional_guidance';+export interface CommitMaskImageResultOptions {+ guard: LayerExportGuard;+ image: CanvasImageRef;+ rect: Rect;+ target: MaskImageResultTarget;+ signal?: AbortSignal;+}+export type CommitMaskImageResult =+ | { status: 'committed'; layerId: string }+ | { status: 'aborted' | 'missing' | 'locked' | 'stale' | 'unsupported' | 'busy' };++export interface CanvasInteractionState {+ activeTool: ToolId;+ bboxGrid: number;+ bboxOptions: BboxToolOptions;+ bboxOverlay: boolean;+ brushOptions: BrushOptions;+ canRedo: boolean;+ canUndo: boolean;+ checkerboard: boolean;+ checkerColors: CheckerColors;+ documentEditingLocked: boolean;+ eraserOptions: EraserOptions;+ gradientOptions: GradientToolOptions;+ hasSelection: boolean;+ invertBrushSizeScroll: boolean;+ lassoOptions: LassoToolOptions;+ ruleOfThirds: boolean;+ shapeOptions: ShapeToolOptions;+ showBbox: boolean;+ showGrid: boolean;+ snapToGrid: boolean;+ textEditSession: TextEditSession | null;+ textOptions: TextToolOptions;+ transformSession: TransformSession | null;+ viewportReady: boolean;+ zoom: number;+}++export interface CanvasInteractionStateCapability {+ get<K extends keyof CanvasInteractionState>(key: K): CanvasInteractionState[K];+ set<K extends keyof CanvasInteractionState>(key: K, value: CanvasInteractionState[K]): void;+ subscribe<K extends keyof CanvasInteractionState>(key: K, listener: () => void): () => void;+ getLayerThumbnailStatus(layerId: string): LayerThumbnailStatus | 'idle';+ getLayerThumbnailVersion(layerId: string): number | undefined;+ subscribeLayerThumbnailStatus(layerId: string, listener: () => void): () => void;+ subscribeLayerThumbnailVersion(layerId: string, listener: () => void): () => void;+}++export interface CanvasCoreStoreCapability {+ readonly interaction: CanvasInteractionStateCapability;+}++export interface CanvasSurfaceCapability {+ attach(screenCanvas: HTMLCanvasElement, overlayCanvas: HTMLCanvasElement): void;+ detach(): void;+ resize(cssWidth: number, cssHeight: number, dpr: number): void;+}++export interface CanvasDocumentCapability {+ captureSnapshot(): CanvasDocumentSnapshot | null;+ getDocument(): CanvasDocumentContractV2 | null;+}++/** Immutable reducer canvas state captured at one engine document generation. */+export interface CanvasDocumentSnapshot {+ readonly canvas: CanvasStateContractV2;+ readonly documentGeneration: number;+}++export type PsdExportResult = 'exported' | 'nothing' | 'too-large' | 'not-ready' | 'over-budget' | 'stale' | 'aborted';++export interface CanvasPsdExportCapability {+ exportRasterLayersToPsd(fileName: string): Promise<PsdExportResult>;+}++export interface CanvasViewportCapability {+ getViewport(): Viewport;+ fitToView(): void;+ setBboxGrid(size: number): void;+}++export interface CanvasToolCapability {+ setTool(toolId: ToolId, options?: { temporary?: boolean }): void;+ stepBrushSize(direction: 1 | -1): void;+}++export interface CanvasHistoryCapability {+ undo(): void;+ redo(): void;+ clearHistory(): void;+}++export type LayerThumbnailRequestResult = 'ready' | 'stale' | 'error' | 'missing' | 'unsupported' | 'over-budget';++export interface CanvasPreviewCapability {+ drawLayerThumbnail(layerId: string, target: HTMLCanvasElement, maxSize: number): boolean;+ requestLayerThumbnail(layerId: string): Promise<LayerThumbnailRequestResult>;+}++export interface CanvasExportCapability {+ captureLayerExportGuard(layerId: string): LayerExportGuard | null;+ exportBakedLayerBlob(layerId: string, options?: ExportBakedLayerPixelsOptions): Promise<ExportBakedLayerBlobResult>;+ exportRasterComposite(request: RasterCompositeExportRequest): Promise<RasterCompositeExportResult>;+ hasExportableLayerContent(layerId: string): boolean;+ isLayerExportGuardCurrent(guard: LayerExportGuard): boolean;+}++export type { RasterCompositeExportRequest, RasterCompositeExportResult } from './exportRasterComposite';++export interface ExportLayerPixelsOptions {+ includeDisabled?: boolean;+ applyAdjustments?: boolean;+ signal?: AbortSignal;+}++export type ExportBakedLayerPixelsOptions = Omit<ExportLayerPixelsOptions, 'applyAdjustments'> & {+ applyAdjustments?: boolean;+};++export type ExportBakedLayerBlobResult =+ | { status: 'ok'; blob: Blob; rect: Rect; guard: LayerExportGuard }+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' | 'aborted' };++export interface CanvasSelectionCapability {+ deselect(): void;+ eraseSelection(): void;+ fillSelection(): void;+ getSelectionBounds(): Rect | null;+ getSelectionMaskRect(): Rect | null;+ invertSelection(): void;+ replaceSelectionFromImage(+ guard: LayerExportGuard,+ image: CanvasImageRef,+ rect: Rect,+ signal?: AbortSignal+ ): Promise<ReplaceSelectionFromImageResult>;+ selectAll(): void;+}++export type ReplaceSelectionFromImageResult =+ | { status: 'selected' }+ | { status: 'aborted' | 'missing' | 'locked' | 'stale' | 'unsupported' | 'busy' }+ | { status: 'failed'; message: string };++export interface CanvasLayerCapability {+ applyStructuralPreview(action: CanvasProjectMutation): boolean;+ canCommitStructural(): boolean;+ commitGeneratedImageResult(options: CommitGeneratedImageOptions): Promise<CommitGeneratedImageResult>;+ commitStagedImage(options: CommitStagedImageOptions): CommitStagedImageResult;+ commitStructural(label: string, forward: CanvasProjectMutation, inverse: CanvasProjectMutation): boolean;+ invertMask(layerId: string): boolean;+}++export interface CommitStagedImageOptions {+ candidate: CanvasStagingCandidateContract;+ selectedImageIndex: number;+}++export type CommitStagedImageResult =+ | { status: 'committed'; layerId: string }+ | { status: 'busy' | 'stale' | 'missing' };++export type GeneratedImageTarget = 'replace' | 'copy-raster' | 'copy-control';++export interface CommitGeneratedImageOptions {+ guard: LayerExportGuard;+ image: CanvasImageRef;+ origin: Vec2;+ target: GeneratedImageTarget;+ historyLabel?: string;+ copyLayerName?: string;+ signal?: AbortSignal;+}++export type CommitGeneratedImageResult =+ | { status: 'committed'; layerId: string }+ | { status: 'missing' | 'locked' | 'stale' | 'unsupported' | 'busy' | 'aborted' }+ | { status: 'failed'; message: string };++export type CanvasLifecycleState = 'active' | 'cooling' | 'cool' | 'disposed';++export interface CanvasLifecycleCapability {+ activate(): void;+ beginCooldown(): Promise<'cooled' | 'dirty'>;+ dispose(): void;+ getLifecycleState(): CanvasLifecycleState;+ flushPendingUploads(): Promise<void>;+}++export type CanvasEditCapability = CanvasEditGate;++export interface FilterPreviewInput {+ imageName: string;+ rect: Rect;+ filterType?: string;+}++export type MergeVisibleResult = 'merged' | 'not-ready' | 'busy' | 'nothing';+export type BooleanRasterResult = 'merged' | 'missing' | 'unsupported' | 'not-ready' | 'busy' | 'empty';+export type ExtractMaskedAreaResult =+ | { status: 'extracted'; layerId: string }+ | { status: 'missing' | 'unsupported' | 'not-ready' | 'busy' | 'empty' };+export type CropLayerResult =+ | { status: 'cropped' }+ | { status: 'missing' | 'locked' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' | 'busy' }+ | { status: 'failed'; message: string };+export interface CanvasDiagnosticsCapability {+ clearCaches(): Promise<void>;+ getDiagnostics(): Readonly<CanvasDiagnosticsSnapshot>;+ logDebugInfo(): void;+}++export interface CanvasDiagnosticsSnapshot {+ readonly surfaceCreations: number;+ readonly surfaceResizes: number;+ readonly allocatedBaseBytes: number;+ readonly allocatedDerivedBytes: number;+ readonly imageDataReads: number;+ readonly imageDataWrites: number;+ readonly derivedCacheHits: number;+ readonly derivedCacheMisses: number;+ readonly derivedCacheEvictions: number;+ readonly layersConsidered: number;+ readonly layersCulled: number;+ readonly layersDrawn: number;+ readonly compositeFrames: number;+ readonly overlayFrames: number;+ readonly overBudgetVisibleBaseBytes: number;+}++export interface CanvasEngineToolCapability extends CanvasToolCapability {+ contextMenuLayerIdAt(screenPoint: Vec2): string | null;+ handleEscapePriority(options: { gestureWasActive: boolean }): void;+ onStrokeCommitted(listener: (event: StrokeCommittedEvent) => void): () => void;+ setInteractionLocked(locked: boolean): void;+}++export interface CanvasEngineLayerCapability extends CanvasLayerCapability {+ applyTransform(): void;+ booleanMergeRasterLayers(upperLayerId: string, operation: BooleanRasterOperation): Promise<BooleanRasterResult>;+ cancelTextEdit(): void;+ cancelTransform(): void;+ clearMask(layerId: string): boolean;+ commitLayerConversion(label: string, expectedLiveLayer: CanvasLayerContract, after: CanvasLayerContract): boolean;+ commitLayerCopy(label: string, sourceLayerId: string, layer: CanvasLayerContract, index: number): boolean;+ commitMaskImageResult(options: CommitMaskImageResultOptions): Promise<CommitMaskImageResult>;+ commitOpenTextSession(): boolean;+ commitRasterFilterResult(options: CommitRasterFilterOptions): Promise<CommitRasterFilterResult>;+ commitTextEdit(content: string, styleChanges?: Partial<TextToolOptions>): void;+ copyLayerToRaster(layerId: string): Promise<string | null>;+ cropLayerToBbox(layerId: string): Promise<CropLayerResult>;+ mergeLayerDown(upperLayerId: string): boolean;+ mergeVisibleRasterLayers(): Promise<MergeVisibleResult>;+ nudgeSelectedLayer(dx: number, dy: number): void;+ openTextCreate(docPoint: Vec2): void;+ openTextEdit(layerId: string): void;+ rasterizeLayer(layerId: string): boolean;+ setTextEditContentReader(reader: (() => string) | null): void;+ updateTextEditStyle(patch: Partial<TextToolOptions>): void;+ updateTransformSession(transform: LayerTransform): void;+}++export interface CanvasEngineExportCapability extends CanvasExportCapability {+ exportRasterLayersToPsd(fileName: string): Promise<PsdExportResult>;+ extractMaskedArea(maskLayerId: string): Promise<ExtractMaskedAreaResult>;+}++export interface CanvasEnginePreviewCapability extends CanvasPreviewCapability {+ setGuardedFilterPreview(+ layerId: string,+ input: FilterPreviewInput,+ guard: LayerExportGuard+ ): Promise<'shown' | 'missing' | 'stale'>;+ setStagedPreview(input: StagedPreviewInput | null): void;+}++/** Public capability-only handle. Construction and mutable stores are intentionally absent. */+export interface CanvasEngine {+ readonly projectId: string;+ readonly surface: CanvasSurfaceCapability;+ readonly viewport: CanvasViewportCapability;+ readonly tools: CanvasEngineToolCapability;+ readonly history: CanvasHistoryCapability;+ readonly lifecycle: CanvasLifecycleCapability;+ readonly layers: CanvasEngineLayerCapability;+ readonly previews: CanvasEnginePreviewCapability;+ readonly selection: CanvasSelectionCapability;+ readonly edits: CanvasEditCapability;+ readonly document: CanvasDocumentCapability;+ readonly exports: CanvasEngineExportCapability;+ readonly diagnostics: CanvasDiagnosticsCapability;+ readonly interaction: CanvasInteractionStateCapability;+}++// Public Canvas-owned value contracts. These remain serializable and contain+// no engine implementation, mutable store, controller, or construction type.+export type * from './contracts';+export type BooleanRasterOperation = 'intersect' | 'cutout' | 'cutaway' | 'exclude';+export interface StagedPreviewPlacement extends Rect {+ opacity: number;+}+export type StagedPreviewInput =+ | { imageName: string; placement?: StagedPreviewPlacement }+ | { dataUrl: string; width: number; height: number };+export type {+ BboxToolOptions,+ BrushOptions,+ CheckerColors,+ EraserOptions,+ GradientStop,+ GradientToolOptions,+ LassoToolOptions,+ LayerThumbnailStatus,+ ShapeToolOptions,+ TextEditSession,+ TextToolOptions,+ TransformSession,+} from './engineStores';+export {+ MAX_BRUSH_SIZE,+ MAX_SHAPE_STROKE_WIDTH,+ MAX_TEXT_FONT_SIZE,+ MIN_BRUSH_SIZE,+ MIN_TEXT_FONT_SIZE,+ TEXT_FONT_FAMILIES,+ TEXT_FONT_WEIGHTS,+} from './engineStores';+export type { LayerTransform } from './transform/transformMath';+export type { ImageResolver } from './render/rasterizers';+export type { Rect, SelectionOp, ToolId, Vec2 } from './types';+export { adjustmentsKey, buildCurveLut, DEFAULT_ADJUSTMENTS } from './render/adjustments';+export { DEFAULT_CHECKER_COLORS } from './render/compositor';+export {+ getBaseRasterContentBounds,+ getCompositeLayerBounds,+ planBaseRasterComposite,+ type CompositeEntry,+ type CompositeLayerRef,+} from './render/rasterComposite';+export {+ getSourceBounds,+ getSourceContentRect,+ isMergeableRasterLayer,+ isRenderableLayer,+ renderableSourceOf,+} from './document/sources';+export { canMergeVisibleRasters } from './document/mergeVisible';+export { documentToExportLocalSamPoint } from './samCoordinates';+export { bboxEquals, constrainBboxToRatio, roundBbox } from './tools/bboxHitTest';+export { isEmpty, union } from './math/rect';+export { ZOOM_SNAP_CANDIDATES } from './math/snapping';+export { isLayerPixelEditEligible } from './editing/controlPixelEdit';+export {+ getLayerThumbnailFallbackRenderState,+ nextLayerThumbnailFallbackStage,+ resolveLayerThumbnailImageRef,+ type LayerThumbnailFallbackStage,+} from './render/thumbnail';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.tsnew file mode 100644index 0000000000..02071a1ae2--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts@@ -0,0 +1,296 @@+import type { GeneratedImageContract } from '@features/gallery';++export type RegionalGuidanceReferenceImageAsset = GeneratedImageContract;++export type RegionalGuidanceIPAdapterMethod = 'full' | 'style' | 'composition' | 'style_strong' | 'style_precise';++export interface RegionalGuidanceModelRef {+ key: string;+ name: string;+ base: string;+ type: string;+ format?: string;+ variant?: string | null;+ hash?: string;+ submodel_type?: string;+ [key: string]: unknown;+}++export type RegionalGuidanceReferenceImageConfig =+ | {+ type: 'ip_adapter';+ image: RegionalGuidanceReferenceImageAsset | null;+ model: RegionalGuidanceModelRef | null;+ weight: number;+ beginEndStepPct: [number, number];+ method: RegionalGuidanceIPAdapterMethod;+ clipVisionModel: 'ViT-H' | 'ViT-G' | 'ViT-L';+ }+ | {+ type: 'flux_redux';+ image: RegionalGuidanceReferenceImageAsset | null;+ model: RegionalGuidanceModelRef | null;+ imageInfluence: 'lowest' | 'low' | 'medium' | 'high' | 'highest';+ };++export interface RegionalGuidanceReferenceImage {+ id: string;+ isEnabled: boolean;+ config: RegionalGuidanceReferenceImageConfig;+}++export interface CanvasPlacementContract {+ x: number;+ y: number;+ width: number;+ height: number;+ opacity: number;+}++export interface CanvasStagingCandidateContract extends GeneratedImageContract {+ placement: CanvasPlacementContract;+ sourceBackendItemId?: number;+}++export interface CanvasRasterLayerContract extends GeneratedImageContract {+ id: string;+ acceptedAt: string;+ label: string;+ placement: CanvasPlacementContract;+}++export interface CanvasDocumentContract {+ version: 1;+ width: number;+ height: number;+ layers: CanvasRasterLayerContract[];+}++/** @deprecated legacy v1 shape, superseded by {@link CanvasStagingAreaContractV2}. Extracted so v1 and v2 canvas state can share its structure. */+export interface CanvasStagingAreaContract {+ sourceQueueItemId?: string;+ selectedLayerId?: string;+ pendingImageIds: string[];+ pendingImages: CanvasStagingCandidateContract[];+ selectedImageIndex: number;+ isVisible: boolean;+ areThumbnailsVisible: boolean;+}++/** @deprecated legacy v1 shape, superseded by {@link CanvasStateContractV2}. Kept for migration input typing and the still-v1-shaped staging area. */+export interface CanvasStateContract {+ version: 1;+ document: CanvasDocumentContract;+ stagingArea: CanvasStagingAreaContract;+}++// ---------------------------------------------------------------------------+// Canvas v2 document contracts+//+// The canvas document is being rebuilt as a full photo editor: a layer stack+// supporting raster, control, regional-guidance, and inpaint-mask layers, each+// with its own transform/opacity/blend-mode. `CanvasStateContract` (v1) only+// ever produced single-image raster layers positioned by `placement`; v2+// layers are positioned by `transform` and reference bitmaps by `imageName`+// (via `CanvasImageRef`) rather than by resolved URLs, since URLs are+// ephemeral/backend-derived while the document is persisted. The staging+// area (pending queue results awaiting placement onto the canvas) keeps its+// v1 shape unchanged — only the accepted document evolves.+// ---------------------------------------------------------------------------++export type CanvasBlendMode =+ | 'normal'+ | 'multiply'+ | 'screen'+ | 'overlay'+ | 'darken'+ | 'lighten'+ | 'color-dodge'+ | 'color-burn'+ | 'hard-light'+ | 'soft-light'+ | 'difference'+ | 'exclusion'+ | 'hue'+ | 'saturation'+ | 'color'+ | 'luminosity';++/** A reference to a persisted image asset by name, not by resolved URL. */+export interface CanvasImageRef {+ imageName: string;+ width: number;+ height: number;+ contentHash?: string;+}++export type CanvasLayerSourceContract =+ | {+ type: 'paint';+ bitmap: CanvasImageRef | null;+ /**+ * The layer-local origin of `bitmap`'s top-left pixel. Paint layers are+ * content-sized: the persisted bitmap covers only the painted region, and+ * this offset records where that region sits in the layer's local space+ * (it can be negative). Absent (or `{ x: 0, y: 0 }`) for legacy documents+ * whose paint bitmaps were document-sized at the origin — they load+ * identically.+ */+ offset?: { x: number; y: number };+ }+ | { type: 'image'; image: CanvasImageRef }+ | {+ type: 'text';+ content: string;+ fontFamily: string;+ fontSize: number;+ fontWeight: number;+ lineHeight: number;+ align: 'left' | 'center' | 'right';+ color: string;+ }+ | {+ type: 'shape';+ kind: 'rect' | 'ellipse' | 'polygon';+ points?: { x: number; y: number }[];+ width: number;+ height: number;+ fill: string | null;+ stroke: string | null;+ strokeWidth: number;+ }+ | {+ type: 'gradient';+ kind: 'linear' | 'radial';+ angle: number;+ stops: { offset: number; color: string }[];+ /**+ * The gradient's explicit content extent (layer-local pixels). Gradient+ * layers are content-sized like every other layer: the extent is set at+ * creation (bbox-sized) and preserved across angle edits. Absent for legacy+ * documents whose gradients were document-sized by construction — they+ * default to the document dimensions on load (see `getSourceContentRect`).+ */+ width?: number;+ height?: number;+ };++export interface CanvasLayerBaseContract {+ id: string;+ name: string;+ isEnabled: boolean;+ isLocked: boolean;+ opacity: number;+ blendMode: CanvasBlendMode;+ transform: { x: number; y: number; scaleX: number; scaleY: number; rotation: number };+}++export interface CanvasAdjustmentsContract {+ brightness: number;+ contrast: number;+ saturation: number;+ curves?: { r: [number, number][]; g: [number, number][]; b: [number, number][] };+}++export interface CanvasControlAdapterContract {+ kind: 'controlnet' | 't2i_adapter' | 'control_lora' | 'z_image_control';+ model: string | null;+ weight: number;+ beginEndStepPct: [number, number];+ controlMode: 'balanced' | 'more_prompt' | 'more_control' | 'unbalanced' | null;+}++export interface CanvasMaskFillContract {+ style: 'solid' | 'grid' | 'crosshatch' | 'diagonal' | 'horizontal' | 'vertical';+ color: string;+}++export interface CanvasMaskContract {+ bitmap: CanvasImageRef | null;+ fill: CanvasMaskFillContract;+ /**+ * The layer-local origin of `bitmap`'s top-left pixel. Mask layers are+ * content-sized exactly like paint layers: the persisted mask bitmap covers+ * only the painted region, and this offset records where that region sits in+ * the layer's local space (it can be negative). Absent (or `{ x: 0, y: 0 }`)+ * for legacy documents whose mask bitmaps were document-sized at the origin —+ * they load identically. Mirrors {@link CanvasLayerSourceContract} `paint`.+ */+ offset?: { x: number; y: number };+}++export interface CanvasRasterLayerContractV2 extends CanvasLayerBaseContract {+ type: 'raster';+ source: CanvasLayerSourceContract;+ adjustments?: CanvasAdjustmentsContract;+ isTransparencyLocked?: boolean;+ filter?: { type: string; settings: Record<string, unknown> };+}++export interface CanvasControlLayerContract extends CanvasLayerBaseContract {+ type: 'control';+ source: CanvasLayerSourceContract;+ adapter: CanvasControlAdapterContract;+ withTransparencyEffect: boolean;+ filter?: { type: string; settings: Record<string, unknown> };+}++export interface CanvasRegionalGuidanceLayerContract extends CanvasLayerBaseContract {+ type: 'regional_guidance';+ mask: CanvasMaskContract;+ positivePrompt: string | null;+ negativePrompt: string | null;+ autoNegative: boolean;+ referenceImages: RegionalGuidanceReferenceImage[];+}++export interface CanvasInpaintMaskLayerContract extends CanvasLayerBaseContract {+ type: 'inpaint_mask';+ mask: CanvasMaskContract;+ noiseLevel?: number;+ denoiseLimit?: number;+}++export type CanvasLayerContract =+ | CanvasRasterLayerContractV2+ | CanvasControlLayerContract+ | CanvasRegionalGuidanceLayerContract+ | CanvasInpaintMaskLayerContract;++export interface CanvasDocumentContractV2 {+ version: 2;+ width: number;+ height: number;+ background: 'transparent' | { color: string };+ /** Index 0 is the top-most layer. */+ layers: CanvasLayerContract[];+ bbox: { x: number; y: number; width: number; height: number };+ selectedLayerId: string | null;+}++export interface CanvasSnapshotContract {+ id: string;+ name: string;+ createdAt: string;+ document: CanvasDocumentContractV2;+}++export interface CanvasStagingAreaContractV2 extends CanvasStagingAreaContract {+ autoSwitchMode: 'off' | 'latest' | 'progress';+}++export interface CanvasStateContractV2 {+ version: 2;+ document: CanvasDocumentContractV2;+ /**+ * Monotonic counter bumped whenever the document is swapped wholesale+ * (snapshot restore, `replaceCanvasDocument`) rather than incrementally+ * edited. The document mirror treats any change to this value as a full+ * document replacement (clearing engine pixel history), even when the new+ * document keeps the same dimensions and reuses layer ids — the case a+ * reference/dimension diff alone cannot distinguish from an ordinary edit.+ */+ documentRevision: number;+ snapshots: CanvasSnapshotContract[];+ stagingArea: CanvasStagingAreaContractV2;+}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.tsindex 19ce862c53..69efbdc377 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts@@ -1,9 +1,9 @@-import type { LayerExportGuard } from '@workbench/canvas-engine/api';+import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';import { isMergeableRasterLayer } from '@workbench/canvas-engine/document/sources';import { isEmpty, roundOut, union } from '@workbench/canvas-engine/math/rect';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.tsindex 329da8ee44..5def15f3c0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts@@ -1,3 +1,4 @@+import type { CanvasControlLayerContract, CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { BitmapStore } from '@workbench/canvas-engine/document/bitmapStore';import type { History } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';@@ -11,7 +12,6 @@ import type {} from '@workbench/canvas-engine/tools/tool';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasControlLayerContract, CanvasDocumentContractV2 } from '@workbench/types';import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';import {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.tsindex 1601911e9e..6275b9377a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts@@ -1,9 +1,9 @@-import type { LayerExportGuard } from '@workbench/canvas-engine/api';+import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';type ExportResult =| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.tsindex 3f22fc11e5..b717754920 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts@@ -1,9 +1,13 @@-import type { LayerExportGuard } from '@workbench/canvas-engine/api';+import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasLayerSourceContract,+} from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasLayerSourceContract } from '@workbench/types';import { renderableSourceOf } from '@workbench/canvas-engine/document/sources';import { intersect, isEmpty, roundOut } from '@workbench/canvas-engine/math/rect';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.tsindex 38c615a4f9..0689b4ceb3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts@@ -1,7 +1,7 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { CanvasEditGate, CanvasEditGateController } from '@workbench/canvas-engine/editGate';import type { SelectionState, SelectionStateDeps } from '@workbench/canvas-engine/selection/selectionState';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2 } from '@workbench/types';import { getSourceBounds, isRenderableLayer } from '@workbench/canvas-engine/document/sources';import { createCanvasEditGate } from '@workbench/canvas-engine/editGate';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.tsindex 4b51cf854b..00ac84789c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts@@ -1,4 +1,5 @@-import type { LayerExportGuard } from '@workbench/canvas-engine/api';+import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import type { History } from '@workbench/canvas-engine/history/history';import type { DerivedSurfaceCache } from '@workbench/canvas-engine/render/derivedSurfaceCache';@@ -6,7 +7,6 @@ import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';import { isEmpty } from '@workbench/canvas-engine/math/rect';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.tsindex 50fe03f33b..87e3a12428 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts@@ -1,4 +1,14 @@-import type { LayerExportGuard } from '@workbench/canvas-engine/api';+import type {+ CommitRasterFilterOptions,+ CommitRasterFilterResult,+ LayerExportGuard,+} from '@workbench/canvas-engine/capabilities';+import type {+ CanvasDocumentContractV2,+ CanvasImageRef,+ CanvasLayerContract,+ CanvasRasterLayerContractV2,+} from '@workbench/canvas-engine/contracts';import type { CapturedLayerCache } from '@workbench/canvas-engine/controllers/layerMutationController';import type { DecodeImageResult } from '@workbench/canvas-engine/controllers/rasterController';import type { History } from '@workbench/canvas-engine/history/history';@@ -6,35 +16,16 @@ import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/renimport type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type {- CanvasDocumentContractV2,- CanvasImageRef,- CanvasLayerContract,- CanvasRasterLayerContractV2,-} from '@workbench/types';import { createControlLayer } from '@workbench/canvas-engine/document/layerFactories';import { LayerFilterOutputDimensionError } from '@workbench/canvas-engine/filterError';-export type CommitRasterFilterResult =- | { status: 'committed'; layerId: string }- | { status: 'missing' | 'locked' | 'stale' | 'unsupported' | 'busy' | 'aborted' }- | { status: 'failed'; message: string };-export interface RasterFilterSettings {- type: string;- settings: Record<string, unknown>;-}-export type RasterFilterCommitTarget = 'apply' | 'raster' | 'control';-export interface CommitRasterFilterOptions {- guard: LayerExportGuard;- image: CanvasImageRef;- rect: Rect;- mode: 'replace' | 'copy';- filter?: RasterFilterSettings;- target?: RasterFilterCommitTarget;- requireExactImageDimensions?: boolean;- signal?: AbortSignal;-}+export type {+ CommitRasterFilterOptions,+ CommitRasterFilterResult,+ RasterFilterCommitTarget,+ RasterFilterSettings,+} from '@workbench/canvas-engine/capabilities';export interface FilterResultControllerOptions<Permit, Owner = symbol> {readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => CapturedLayerCache;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.tsindex c3b746942a..5d9216c62d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts@@ -2,7 +2,8 @@ import type {CommitGeneratedImageOptions,CommitGeneratedImageResult,LayerExportGuard,-} from '@workbench/canvas-engine/api';+} from '@workbench/canvas-engine/capabilities';+import type { CanvasDocumentContractV2, CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CapturedLayerCache } from '@workbench/canvas-engine/controllers/layerMutationController';import type { DecodeImageResult } from '@workbench/canvas-engine/controllers/rasterController';import type { History } from '@workbench/canvas-engine/history/history';@@ -11,7 +12,6 @@ import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { Rect } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasImageRef, CanvasLayerContract } from '@workbench/types';import { createControlLayer, nextControlLayerName } from '@workbench/canvas-engine/document/layerFactories';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.tsindex e017b9ca35..25eba1292c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts@@ -1,4 +1,4 @@-import type { CanvasToolCapability } from '@workbench/canvas-engine/api';+import type { CanvasToolCapability } from '@workbench/canvas-engine/capabilities';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { ToolId } from '@workbench/canvas-engine/types';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.tsindex 0318b34f9f..f53e6d2ab5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts@@ -1,4 +1,4 @@-import type { CanvasLayerCapability, CanvasPreviewCapability } from '@workbench/canvas-engine/api';+import type { CanvasLayerCapability, CanvasPreviewCapability } from '@workbench/canvas-engine/capabilities';import type { MaskLayerControllerOptions } from './maskLayerController';import type { StructuralLayerController } from './structuralLayerController';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.tsindex 6583424137..b1f2545e77 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts@@ -1,9 +1,9 @@+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';export type CapturedLayerCache = { pixels: RasterSurface; rect: Rect } | null | 'not-ready';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.tsindex 66859a118a..6835d258c7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.ts@@ -1,9 +1,9 @@+import type { CanvasDocumentContractV2, CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { Rect } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasImageRef, CanvasLayerContract } from '@workbench/types';import { getSourceContentRect, isMaskLayer } from '@workbench/canvas-engine/document/sources';import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.tsindex d884b932d1..8dcf9635e3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts@@ -1,8 +1,11 @@-import type { LayerExportGuard } from '@workbench/canvas-engine/api';+import type {+ CommitMaskImageResult,+ CommitMaskImageResultOptions,+ LayerExportGuard,+} from '@workbench/canvas-engine/capabilities';+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';-import type { Rect } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/types';import {createInpaintMaskFromImage,@@ -13,17 +16,11 @@ import {nextRegionalGuidanceName,} from '@workbench/canvas-engine/document/layerFactories';-export type MaskImageResultTarget = 'inpaint_mask' | 'regional_guidance';-export interface CommitMaskImageResultOptions {- guard: LayerExportGuard;- image: CanvasImageRef;- rect: Rect;- target: MaskImageResultTarget;- signal?: AbortSignal;-}-export type CommitMaskImageResult =- | { status: 'committed'; layerId: string }- | { status: 'aborted' | 'missing' | 'locked' | 'stale' | 'unsupported' | 'busy' };+export type {+ CommitMaskImageResult,+ CommitMaskImageResultOptions,+ MaskImageResultTarget,+} from '@workbench/canvas-engine/capabilities';export interface MaskResultControllerOptions<Owner = symbol> {readonly canEdit: (owner?: Owner) => boolean;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.tsindex 2fcd2e08c3..dcab58d733 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts@@ -1,10 +1,10 @@-import type { LayerExportGuard } from '@workbench/canvas-engine/api';+import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';import { mergeDownMatrix } from '@workbench/canvas-engine/document/mergeDown';import { getMergeVisibleRasterLayers } from '@workbench/canvas-engine/document/mergeVisible';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/previewStateController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/previewStateController.tsindex 25421a62d6..6be4d5f5b8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/previewStateController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/previewStateController.ts@@ -1,4 +1,4 @@-import type { LayerExportGuard } from '@workbench/canvas-engine/api';+import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.test.tsindex 577fc3f083..136fd73557 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.test.ts@@ -1,6 +1,11 @@-import type { CanvasDocumentSnapshot, CanvasRasterSnapshot } from '@workbench/canvas-engine/api';+import type { CanvasDocumentSnapshot } from '@workbench/canvas-engine/capabilities';+import type {+ CanvasDocumentContractV2,+ CanvasRasterLayerContractV2,+ CanvasStateContractV2,+} from '@workbench/canvas-engine/contracts';import type { ExecutePsdExportDeps, PsdExportPlan } from '@workbench/canvas-engine/export/psdExport';-import type { CanvasDocumentContractV2, CanvasRasterLayerContractV2, CanvasStateContractV2 } from '@workbench/types';+import type { CanvasRasterSnapshot } from '@workbench/canvas-engine/rasterTransactions';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.tsindex 416eb3ecbc..bf06d0211e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts@@ -1,11 +1,10 @@+import type { CanvasDocumentSnapshot, PsdExportResult } from '@workbench/canvas-engine/capabilities';+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type {CanvasDetachedLayerSurface,- CanvasDocumentSnapshot,CaptureRasterSnapshotResult,- PsdExportResult,-} from '@workbench/canvas-engine/api';+} from '@workbench/canvas-engine/rasterTransactions';import type { RasterBackend } from '@workbench/canvas-engine/render/raster';-import type { CanvasLayerContract } from '@workbench/types';import {executePsdExport,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.tsindex 6f43351a18..447f9b81ad 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts@@ -1,4 +1,4 @@-import type { CanvasRasterLayerContractV2 } from '@workbench/types';+import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.tsindex 52bce8f99f..7f4b687091 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts@@ -1,12 +1,12 @@-import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';-import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';-import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type {CanvasDocumentContractV2,CanvasImageRef,CanvasLayerContract,CanvasLayerSourceContract,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';+import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';+import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';export type DecodeImageResult =| { status: 'ok'; surface: RasterSurface; decodedWidth: number; decodedHeight: number }diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.tsindex 4362cd4a17..0e33124738 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2 } from '@workbench/types';+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.tsindex bf84ccc9a8..09c33f1e54 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts@@ -3,11 +3,15 @@ import type {ExportBakedLayerPixelsOptions,ExportLayerPixelsOptions,LayerExportGuard,-} from '@workbench/canvas-engine/api';+} from '@workbench/canvas-engine/capabilities';+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasLayerSourceContract,+} from '@workbench/canvas-engine/contracts';import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasLayerSourceContract } from '@workbench/types';import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';import { fromTRS } from '@workbench/canvas-engine/math/mat2d';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.tsindex 2c547f7145..af824086cf 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts@@ -1,9 +1,9 @@+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend } from '@workbench/canvas-engine/render/raster';import type { RasterizeDeps } from '@workbench/canvas-engine/render/rasterizers';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';import { roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionImageController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionImageController.tsindex 5c4fe48796..ae02f85c6f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionImageController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionImageController.ts@@ -1,8 +1,8 @@-import type { LayerExportGuard, ReplaceSelectionFromImageResult } from '@workbench/canvas-engine/api';+import type { LayerExportGuard, ReplaceSelectionFromImageResult } from '@workbench/canvas-engine/capabilities';+import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/canvas-engine/contracts';import type { DecodeImageResult } from '@workbench/canvas-engine/controllers/rasterController';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/types';export interface SelectionImageControllerOptions<Permit, Owner = symbol> {readonly capturePermit: (owner?: Owner) => Permit | null;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.tsindex 2c183133dd..142fb414db 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts@@ -1,5 +1,5 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';-import type { CanvasDocumentContractV2 } from '@workbench/types';import { createHistory } from '@workbench/canvas-engine/history/history';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.tsindex 75b427caa5..88faab5c48 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts@@ -1,3 +1,4 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';@@ -5,7 +6,6 @@ import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/rendimport type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { ControlPixelEditTransaction } from '@workbench/canvas-engine/tools/tool';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2 } from '@workbench/types';import { getSourceBounds } from '@workbench/canvas-engine/document/sources';import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.tsindex a247b1c0be..57bd8418ff 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.ts@@ -1,6 +1,6 @@+import type { CanvasStagingCandidateContract } from '@workbench/canvas-engine/contracts';import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasStagingCandidateContract } from '@workbench/types';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { createCanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';@@ -59,8 +59,8 @@ describe('staged result project-port integration', () => {const projectId = store.getState().activeProjectId;const first = { ...candidate, placement: { ...candidate.placement, x: 10 } };const selected = { ...candidate, placement: { ...candidate.placement, x: 90 } };- store.dispatch({ candidate: first, projectId, type: 'appendCanvasStagingCandidate' });- store.dispatch({ candidate: selected, projectId, type: 'appendCanvasStagingCandidate' });+ store.commands.canvas.appendStagingCandidate({ candidate: first, projectId });+ store.commands.canvas.appendStagingCandidate({ candidate: selected, projectId });const engine = createCanvasEngine({backend: createTestStubRasterBackend(),imageResolver: () => Promise.resolve(new Blob()),@@ -79,7 +79,7 @@ describe('staged result project-port integration', () => {it('rolls back the exact layer, event, selection, and staging when initial mirror acceptance fails', () => {const store = createWorkbenchStore();const projectId = store.getState().activeProjectId;- store.dispatch({ candidate, projectId, type: 'appendCanvasStagingCandidate' });+ store.commands.canvas.appendStagingCandidate({ candidate, projectId });const before = structuredClone(store.getState().projects.find((project) => project.id === projectId)!);const rejectingPort = createMirrorRejectingPort(store, projectId);rejectingPort.arm('commitStagedImage');@@ -103,7 +103,7 @@ describe('staged result project-port integration', () => {it('compensates a reducer-accepted undo when mirror acceptance fails and keeps history retryable', () => {const store = createWorkbenchStore();const projectId = store.getState().activeProjectId;- store.dispatch({ candidate, projectId, type: 'appendCanvasStagingCandidate' });+ store.commands.canvas.appendStagingCandidate({ candidate, projectId });const rejectingPort = createMirrorRejectingPort(store, projectId);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -127,7 +127,7 @@ describe('staged result project-port integration', () => {it('compensates a reducer-accepted redo when mirror acceptance fails and keeps history retryable', () => {const store = createWorkbenchStore();const projectId = store.getState().activeProjectId;- store.dispatch({ candidate, projectId, type: 'appendCanvasStagingCandidate' });+ store.commands.canvas.appendStagingCandidate({ candidate, projectId });const rejectingPort = createMirrorRejectingPort(store, projectId);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.tsindex d664eaad3d..1f865d5da1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts@@ -1,5 +1,5 @@+import type { CanvasStagingCandidateContract, CanvasStateContractV2 } from '@workbench/canvas-engine/contracts';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasStagingCandidateContract, CanvasStateContractV2 } from '@workbench/types';import { createHistory } from '@workbench/canvas-engine/history/history';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.tsindex 53648c5237..e6e0c56ae3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts@@ -1,13 +1,13 @@-import type { CommitStagedImageOptions, CommitStagedImageResult } from '@workbench/canvas-engine/api';-import type { History } from '@workbench/canvas-engine/history/history';-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import type { CommitStagedImageOptions, CommitStagedImageResult } from '@workbench/canvas-engine/capabilities';import type {CanvasDocumentContractV2,CanvasRasterLayerContractV2,CanvasStagingCandidateContract,CanvasStateContractV2,- ProjectEvent,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';+import type { History } from '@workbench/canvas-engine/history/history';+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import type { ProjectEvent } from '@workbench/projectContracts';import { getCanvasStagingCandidateFingerprint } from '@workbench/canvasStagingView';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.tsindex 36bb7244e2..1d41e7a8f6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2 } from '@workbench/types';+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import { createHistory } from '@workbench/canvas-engine/history/history';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.tsindex c4e364b4e4..180b858981 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts@@ -1,6 +1,6 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2 } from '@workbench/types';import { createDocumentPatchEntry } from '@workbench/canvas-engine/history/documentPatch';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.tsindex 0c2bd9f367..7d086a04c9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts@@ -1,5 +1,5 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { TextEditSession } from '@workbench/canvas-engine/engineStores';-import type { CanvasDocumentContractV2 } from '@workbench/types';import { DEFAULT_TEXT_OPTIONS } from '@workbench/canvas-engine/engineStores';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.tsindex ee93ab402d..325c359050 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts@@ -1,7 +1,7 @@+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { TextEditSession, TextSource, TextToolOptions } from '@workbench/canvas-engine/engineStores';import type { Vec2 } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';export interface TextEditingControllerOptions {readonly session: {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.test.tsindex 6b064d5ad0..17166a9efd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.test.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2 } from '@workbench/types';+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.tsindex 6afe026dff..8985a72a33 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.ts@@ -1,7 +1,11 @@-import type { LayerThumbnailRequestResult } from '@workbench/canvas-engine/api';+import type { LayerThumbnailRequestResult } from '@workbench/canvas-engine/capabilities';+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasLayerSourceContract,+} from '@workbench/canvas-engine/contracts';import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasLayerSourceContract } from '@workbench/types';import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';import { applyAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.tsindex ee787c732a..c5c4ff43c2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts@@ -1,5 +1,5 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { TransformSession } from '@workbench/canvas-engine/engineStores';-import type { CanvasDocumentContractV2 } from '@workbench/types';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.tsindex 03dcecd906..62c6ef86fd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts@@ -1,3 +1,4 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { TransformSession } from '@workbench/canvas-engine/engineStores';import type { HistoryEntry } from '@workbench/canvas-engine/history/history';import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';@@ -5,7 +6,6 @@ import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/rendimport type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { Rect } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2 } from '@workbench/types';import { isRenderableLayer } from '@workbench/canvas-engine/document/sources';import { createDocumentPatchEntry } from '@workbench/canvas-engine/history/documentPatch';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/diagnostics.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/diagnostics.tsindex ba70fe7627..18952c4ce1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/diagnostics.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/diagnostics.ts@@ -1,20 +1,6 @@-export interface CanvasDiagnosticsSnapshot {- readonly surfaceCreations: number;- readonly surfaceResizes: number;- readonly allocatedBaseBytes: number;- readonly allocatedDerivedBytes: number;- readonly imageDataReads: number;- readonly imageDataWrites: number;- readonly derivedCacheHits: number;- readonly derivedCacheMisses: number;- readonly derivedCacheEvictions: number;- readonly layersConsidered: number;- readonly layersCulled: number;- readonly layersDrawn: number;- readonly compositeFrames: number;- readonly overlayFrames: number;- readonly overBudgetVisibleBaseBytes: number;-}+import type { CanvasDiagnosticsSnapshot } from './capabilities';++export type { CanvasDiagnosticsSnapshot } from './capabilities';export type CanvasDiagnosticsCounter = keyof CanvasDiagnosticsSnapshot;type MutableCanvasDiagnosticsSnapshot = { -readonly [K in CanvasDiagnosticsCounter]: number };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.tsindex 786ef5f532..fa6c2f13c8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts@@ -1,7 +1,7 @@+import type { CanvasImageRef, CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasImageRef, CanvasLayerSourceContract } from '@workbench/types';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.tsindex 3b779d8e92..550df7d2a6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts@@ -46,10 +46,10 @@* injectable, so this runs in node tests with fakes. Zero React.*/+import type { CanvasImageRef, CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasImageRef, CanvasLayerSourceContract } from '@workbench/types';/** Default idle window before a dirty layer is flushed. */export const DEFAULT_DEBOUNCE_MS = 1500;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.tsindex 104b5bfa45..758a9f178c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts@@ -5,7 +5,7 @@ import type {CanvasRasterLayerContractV2,CanvasStagingAreaContractV2,CanvasStateContractV2,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.tsindex 238d369df3..214bcd3aee 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts@@ -1,42 +1,8 @@-/**- * The document mirror: the one-way bridge from the reducer-owned canvas- * document into the engine.- *- * The reducer owns the document; the engine only reads it. External changes- * (layer edits, undo/redo, staging accept, project switch) arrive via a plain- * `store.subscribe`, and the mirror translates a new state into the narrowest- * possible set of callbacks by diffing against the last-seen references:- *- * - document object identical → nothing happened (fast path; this is what makes- * unrelated-project changes free, since the reducer preserves identity).- * - `documentRevision` changed → `onDocumentReplaced` (a full invalidate). This- * is bumped by the reducer on wholesale document swaps (snapshot restore,- * `replaceCanvasDocument`) that reuse the same dimensions and layer ids, which- * a reference/dimension diff alone cannot tell apart from an ordinary edit.- * - dimensions / background changed, or the document appeared/disappeared →- * `onDocumentReplaced` (a full invalidate).- * - otherwise diff the layer array element-wise by reference (id-keyed) →- * `onLayersChanged(changedIds, sourceChangedIds)`. The second argument is the- * subset of ids whose *rasterization source* reference changed (an image/paint- * swap, or a newly added layer) — as opposed to a prop/transform-only edit- * (opacity, blend, lock, visibility, rename, nudge) that replaces the layer- * object but keeps its `source`/`mask` reference. The engine invalidates a- * layer's raster cache ONLY for a source change: re-rasterizing on a prop edit- * is wasteful for image layers and destructive for an unflushed paint layer- * (a `bitmap: null` source rasterizes to a cleared surface, wiping cached- * strokes that have not been persisted yet).- * - layers array reference changed but every id kept the same element- * reference, just in a different order (a pure reorder) →- * `onLayerOrderChanged` (recomposite only; nothing to re-rasterize).- * - bbox value changed → `onBboxChanged`.- * - stagingArea reference changed → `onStagingChanged`.- *- * A missing/deleted project is a no-op safe: the mirror simply reports `null`.- *- * Zero React, zero import-time side effects.- */--import type { CanvasDocumentContractV2, CanvasStagingAreaContractV2, CanvasStateContractV2 } from '@workbench/types';+import type {+ CanvasDocumentContractV2,+ CanvasStagingAreaContractV2,+ CanvasStateContractV2,+} from '@workbench/canvas-engine/contracts';/** The minimal store shape the mirror depends on (a superset of `WorkbenchStore`). */export interface DocumentMirrorStore {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.tsindex 92d9ee4a17..4dc389ab5a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.ts@@ -1,11 +1,11 @@-import type { Rect } from '@workbench/canvas-engine/types';import type {CanvasControlLayerContract,CanvasImageRef,CanvasInpaintMaskLayerContract,CanvasMaskFillContract,CanvasRegionalGuidanceLayerContract,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';+import type { Rect } from '@workbench/canvas-engine/types';import { CONTROL_ADAPTER_DEFAULTS } from '@workbench/controlAdapters';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeDown.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeDown.test.tsindex 176a28ade3..903556685f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeDown.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeDown.test.ts@@ -1,4 +1,4 @@-import type { CanvasLayerBaseContract } from '@workbench/types';+import type { CanvasLayerBaseContract } from '@workbench/canvas-engine/contracts';import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeDown.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeDown.tsindex 03d5f370a4..4856565501 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeDown.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeDown.ts@@ -15,8 +15,8 @@* Zero React, zero DOM, zero import-time side effects.*/+import type { CanvasLayerBaseContract } from '@workbench/canvas-engine/contracts';import type { Mat2d } from '@workbench/canvas-engine/types';-import type { CanvasLayerBaseContract } from '@workbench/types';import { fromTRS, invert, multiply } from '@workbench/canvas-engine/math/mat2d';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.tsindex 1e8ac0ea47..57dd36976a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.ts@@ -2,7 +2,7 @@ import type {CanvasInpaintMaskLayerContract,CanvasLayerContract,CanvasRasterLayerContractV2,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.tsindex 5510635be3..5e8064efde 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts@@ -1,12 +1,4 @@-/**- * Pure contributor selection for the raster group's "merge visible" action.- *- * Legacy merge-visible composites every visible raster entity with content into- * a new raster layer. Source kind and lock state do not affect participation:- * locks prevent editing a source, not reading its rendered pixels.- */--import type { CanvasLayerContract } from '@workbench/types';+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';export type HasMergeVisibleContent = (layerId: string) => boolean;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.tsindex 466fbb6271..20a204bce8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.ts@@ -1,4 +1,8 @@-import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasLayerSourceContract } from '@workbench/types';+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasLayerSourceContract,+} from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.tsindex b77fdd1d96..57657d6eeb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts@@ -12,8 +12,12 @@* Zero React, zero import-time side effects.*/+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasLayerSourceContract,+} from '@workbench/canvas-engine/contracts';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasLayerSourceContract } from '@workbench/types';import { fromTRS } from '@workbench/canvas-engine/math/mat2d';import { transformBounds } from '@workbench/canvas-engine/math/rect';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.tsindex b23528e7f1..e1dc13fdd7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.ts@@ -1,4 +1,4 @@-import type { CanvasControlLayerContract, CanvasLayerContract } from '@workbench/types';+import type { CanvasControlLayerContract, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import { createTestStubRasterBackend, type StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.tsindex 8221c82e64..530747a79c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts@@ -1,6 +1,6 @@+import type { CanvasControlLayerContract, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasControlLayerContract, CanvasLayerContract } from '@workbench/types';import { roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { bakeMatrix, IDENTITY_TRANSFORM, type LayerTransform } from '@workbench/canvas-engine/transform/transformMath';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.tsindex f7687c4aff..09e281ea48 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts@@ -7,10 +7,11 @@* engine test suite.*/+import type { CanvasDocumentContractV2, CanvasStateContractV2 } from '@workbench/canvas-engine/contracts';import type { StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';-import type { CanvasDocumentContractV2, CanvasStateContractV2, Project, WorkbenchState } from '@workbench/types';-import type { WorkbenchAction } from '@workbench/workbenchState';+import type { Project, WorkbenchState } from '@workbench/projectContracts';+import type { WorkbenchAction } from '@workbench/workbenchState.testing';import {applyCanvasProjectMutation,@@ -25,7 +26,7 @@ import {createCanvasEngine as createApplicationCanvasEngine,type CanvasEngineOptions,} from '@workbench/canvas-operations/createCanvasEngine';-import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState';+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';import { afterEach, describe, expect, it, vi } from 'vitest';import type { StrokeCommittedEvent } from './tools/tool';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 6dc538670a..452b5bf766 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -1,3 +1,13 @@+import type {+ CanvasControlLayerContract,+ CanvasDocumentContractV2,+ CanvasInpaintMaskLayerContract,+ CanvasLayerContract,+ CanvasLayerSourceContract,+ CanvasRasterLayerContractV2,+ CanvasStagingCandidateContract,+ CanvasStateContractV2,+} from '@workbench/canvas-engine/contracts';import type * as ImagePatchModule from '@workbench/canvas-engine/history/imagePatch';import type * as LayerSnapshotModule from '@workbench/canvas-engine/history/layerSnapshot';import type * as AdjustedSurfaceCacheModule from '@workbench/canvas-engine/render/adjustedSurfaceCache';@@ -9,19 +19,8 @@ import type {} from '@workbench/canvas-engine/render/raster.testStub';import type { ToolId } from '@workbench/canvas-engine/types';import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';-import type {- CanvasControlLayerContract,- CanvasDocumentContractV2,- CanvasInpaintMaskLayerContract,- CanvasLayerContract,- CanvasLayerSourceContract,- CanvasRasterLayerContractV2,- CanvasStagingCandidateContract,- CanvasStateContractV2,- Project,- WorkbenchState,-} from '@workbench/types';-import type { WorkbenchAction } from '@workbench/workbenchState';+import type { Project, WorkbenchState } from '@workbench/projectContracts';+import type { WorkbenchAction } from '@workbench/workbenchState.testing';import {applyCanvasProjectMutation,@@ -36,12 +35,12 @@ import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/rasimport { canvasApplicationPort } from '@workbench/canvas-operations/applicationPort';import {createCanvasEngine as createApplicationCanvasEngine,- getCanvasOperations,type CanvasEngine,type CanvasEngineOptions,} from '@workbench/canvas-operations/createCanvasEngine';import { FILTER_AUTO_PROCESS_DEBOUNCE_MS } from '@workbench/canvas-operations/filterOperationSession';-import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState';+import { getCanvasOperationImplementation as getCanvasOperations } from '@workbench/canvas-operations/operationAccess';+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';import { afterEach, describe, expect, it, type Mock, vi } from 'vitest';import type { BitmapStore } from './document/bitmapStore';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 05ca1979db..5d69ff1779 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -27,13 +27,12 @@import type {CanvasHistoryCapability,- CanvasEditCapability,- CanvasCompositeExecutorDeps,+ CanvasEngine,+ CanvasInteractionState,+ CanvasInteractionStateCapability,CanvasDocumentCapability,CanvasDocumentSnapshot,CanvasExportCapability,- CanvasRasterSnapshot,- CaptureRasterSnapshotResult,CanvasLifecycleCapability,CanvasLayerCapability,CanvasPreviewCapability,@@ -41,12 +40,21 @@ import type {CanvasSurfaceCapability,CanvasToolCapability,CanvasViewportCapability,+ BooleanRasterOperation,ExportBakedLayerPixelsOptions,ExportLayerPixelsOptions,LayerExportGuard,PsdExportResult,-} from '@workbench/canvas-engine/api';+ StagedPreviewInput,+ StagedPreviewPlacement,+} from '@workbench/canvas-engine/capabilities';+import type {+ CanvasCompositeExecutorDeps,+ CanvasRasterSnapshot,+ CaptureRasterSnapshotResult,+} from '@workbench/canvas-engine/rasterTransactions';export type {+ CanvasEngine,CommitGeneratedImageOptions,CommitGeneratedImageResult,CommitStagedImageOptions,@@ -59,7 +67,7 @@ export type {LayerThumbnailRequestResult,PsdExportResult,ReplaceSelectionFromImageResult,-} from '@workbench/canvas-engine/api';+} from '@workbench/canvas-engine/capabilities';export type {CommitMaskImageResult,CommitMaskImageResultOptions,@@ -70,6 +78,12 @@ export type {CommitRasterFilterResult,} from '@workbench/canvas-engine/controllers/filterResultController';import type { CanvasApplicationHost, SelectObjectStartContext } from '@workbench/canvas-engine/applicationHost';+import type {+ CanvasImageRef,+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasLayerSourceContract,+} from '@workbench/canvas-engine/contracts';import type { CreatePath2D } from '@workbench/canvas-engine/freehand';import type { FontLoadApi } from '@workbench/canvas-engine/render/fontLoader';import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';@@ -79,12 +93,6 @@ import type { SamVisualInput } from '@workbench/canvas-engine/samInteraction';import type { Rect, RenderFlags, ToolId, Vec2 } from '@workbench/canvas-engine/types';import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type {- CanvasImageRef,- CanvasDocumentContractV2,- CanvasLayerContract,- CanvasLayerSourceContract,-} from '@workbench/types';import { ControlPixelController } from '@workbench/canvas-engine/controllers/controlPixelController';import { EditingController } from '@workbench/canvas-engine/controllers/editingController';@@ -111,7 +119,12 @@ import { RenderController } from '@workbench/canvas-engine/controllers/renderConimport { StagedResultController } from '@workbench/canvas-engine/controllers/stagedResultController';import { StructuralLayerController } from '@workbench/canvas-engine/controllers/structuralLayerController';import { createCanvasDiagnostics, type CanvasDiagnosticsSnapshot } from '@workbench/canvas-engine/diagnostics';-import { createEngineStores, type EngineStores, type TextToolOptions } from '@workbench/canvas-engine/engineStores';+import {+ createEngineStores,+ type EngineStores,+ type ScalarStore,+ type TextToolOptions,+} from '@workbench/canvas-engine/engineStores';import {exportRasterComposite as exportRasterCompositeWithDeps,RasterCompositeOverBudgetError,@@ -170,14 +183,6 @@ import { createViewTool } from './tools/viewTool';* inline data-URL with explicit document-space dimensions (a live* denoise-progress frame, scaled to fill those dims at the current bbox).*/-export interface StagedPreviewPlacement extends Rect {- opacity: number;-}--export type StagedPreviewInput =- | { imageName: string; placement?: StagedPreviewPlacement }- | { dataUrl: string; width: number; height: number };-export interface FilterPreviewInput {imageName: string;rect: Rect;@@ -192,7 +197,6 @@ export interface FilterPreviewInput {*/export type MergeVisibleResult = 'merged' | 'not-ready' | 'busy' | 'nothing';-export type BooleanRasterOperation = 'intersect' | 'cutout' | 'cutaway' | 'exclude';export type BooleanRasterResult = 'merged' | 'missing' | 'unsupported' | 'not-ready' | 'busy' | 'empty';export type ExtractMaskedAreaResult =@@ -340,6 +344,11 @@ export interface CanvasEngineLayerCapability extends CanvasLayerCapability {}export interface CanvasEngineExportCapability extends CanvasExportCapability {+ captureRasterSnapshot(+ documentSnapshot: CanvasDocumentSnapshot,+ layerIds: readonly string[],+ options?: { signal?: AbortSignal; includeDisabled?: boolean }+ ): Promise<CaptureRasterSnapshotResult>;exportBakedLayerPixels(layerId: string,options?: ExportBakedLayerPixelsOptions@@ -347,6 +356,7 @@ export interface CanvasEngineExportCapability extends CanvasExportCapability {exportLayerPixels(layerId: string, options?: ExportLayerPixelsOptions): Promise<ExportLayerPixelsResult>;exportRasterLayersToPsd(fileName: string): Promise<PsdExportResult>;extractMaskedArea(maskLayerId: string): Promise<ExtractMaskedAreaResult>;+ getCompositeExecutorDeps(): CanvasCompositeExecutorDeps;}export interface CanvasEngineSelectionCapability extends CanvasSelectionCapability {}@@ -366,27 +376,14 @@ export interface CanvasDiagnosticsCapability {logDebugInfo(): void;}-/** The public engine handle. */-export interface CanvasEngine {- readonly projectId: string;- readonly surface: CanvasSurfaceCapability;- readonly viewport: CanvasViewportCapability;- readonly tools: CanvasEngineToolCapability;- readonly history: CanvasHistoryCapability;- readonly lifecycle: CanvasLifecycleCapability;- readonly layers: CanvasEngineLayerCapability;- readonly previews: CanvasEnginePreviewCapability;- readonly selection: CanvasEngineSelectionCapability;- readonly edits: CanvasEditCapability;- readonly document: CanvasDocumentCapability;+/** Private engine composition shape used only inside the Canvas implementation and its tests. */+export interface CanvasEngineImplementation extends CanvasEngine {readonly exports: CanvasEngineExportCapability;- readonly diagnostics: CanvasDiagnosticsCapability;- /** The transient stores React subscribes to. */readonly stores: EngineStores;}export interface CanvasEngineCoreComposition {- readonly engine: CanvasEngine;+ readonly engine: CanvasEngineImplementation;readonly applicationHost: CanvasApplicationHost;}@@ -462,6 +459,42 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC});const layerCache = rasterController.layers;const stores = createEngineStores();+ const interactionStores: { [K in keyof CanvasInteractionState]: ScalarStore<CanvasInteractionState[K]> } = {+ activeTool: stores.activeTool,+ bboxGrid: stores.bboxGrid,+ bboxOptions: stores.bboxOptions,+ bboxOverlay: stores.bboxOverlay,+ brushOptions: stores.brushOptions,+ canRedo: stores.canRedo,+ canUndo: stores.canUndo,+ checkerboard: stores.checkerboard,+ checkerColors: stores.checkerColors,+ documentEditingLocked: stores.documentEditingLocked,+ eraserOptions: stores.eraserOptions,+ gradientOptions: stores.gradientOptions,+ hasSelection: stores.hasSelection,+ invertBrushSizeScroll: stores.invertBrushSizeScroll,+ lassoOptions: stores.lassoOptions,+ ruleOfThirds: stores.ruleOfThirds,+ shapeOptions: stores.shapeOptions,+ showBbox: stores.showBbox,+ showGrid: stores.showGrid,+ snapToGrid: stores.snapToGrid,+ textEditSession: stores.textEditSession,+ textOptions: stores.textOptions,+ transformSession: stores.transformSession,+ viewportReady: stores.viewportReady,+ zoom: stores.zoom,+ };+ const interaction: CanvasInteractionStateCapability = {+ get: (key) => interactionStores[key].get(),+ getLayerThumbnailStatus: (layerId) => stores.thumbnailStatus.get(layerId) ?? 'idle',+ getLayerThumbnailVersion: (layerId) => stores.thumbnailVersion.get(layerId),+ set: (key, value) => interactionStores[key].set(value),+ subscribe: (key, listener) => interactionStores[key].subscribe(listener),+ subscribeLayerThumbnailStatus: (layerId, listener) => stores.thumbnailStatus.subscribeKey(layerId, listener),+ subscribeLayerThumbnailVersion: (layerId, listener) => stores.thumbnailVersion.subscribeKey(layerId, listener),+ };// Web-font readiness for text layers: re-rasterizes a text layer once its font// resolves (a no-op in node / when `document.fonts` is absent). `undefined`// opts.fonts falls back to the DOM api; an explicit `null` forces the no-op.@@ -3400,12 +3433,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC},};- const engine: CanvasEngine = {+ const engine: CanvasEngineImplementation = {diagnostics: diagnosticsCapability,document: documentCapability,edits: editingController.edits,exports: exportCapability,history: historyCapability,+ interaction,lifecycle,layers: layersCapability,projectId,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.tsindex ec0830f9ca..b1628aeff8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts@@ -4,19 +4,17 @@* These are the narrow, imperative channels React subscribes to (in the widget* task) to observe engine-owned interaction state — active tool, zoom,* readiness, cursor, and per-layer thumbnail versions — without the engine ever- * importing React. They follow the `externalStore.ts` pattern (a listener- * channel plus a snapshot getter, `useSyncExternalStore`-compatible) but- * deliberately do NOT import it: `externalStore.ts` pulls in React, and this- * module must stay node-safe and React-free. The React hooks live with the- * widget shell.+ * importing React. They follow Platform's React-free external-store core (a+ * listener channel plus a snapshot getter, `useSyncExternalStore`-compatible).+ * The React hooks live with the widget shell.** Zero React, zero import-time side effects.*/+import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { SamInteractionState } from '@workbench/canvas-engine/samInteraction';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { Rect, SelectionOp, ToolId, Vec2 } from '@workbench/canvas-engine/types';-import type { CanvasLayerSourceContract } from '@workbench/types';import { type CheckerColors, DEFAULT_CHECKER_COLORS } from '@workbench/canvas-engine/render/compositor';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.tsindex 5881ed568c..a8ac429cba 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts@@ -1,5 +1,5 @@+import type { CanvasBlendMode } from '@workbench/canvas-engine/contracts';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasBlendMode } from '@workbench/types';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.tsindex 94ca2a06ba..6b3c17174e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts@@ -32,9 +32,9 @@* user sees. Opacity/blend stay as PSD layer properties (not baked).*/+import type { CanvasAdjustmentsContract, CanvasBlendMode } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Mat2d, Rect } from '@workbench/canvas-engine/types';-import type { CanvasAdjustmentsContract, CanvasBlendMode } from '@workbench/types';import type { BlendMode, Layer as AgPsdLayer, Psd } from 'ag-psd';import { fromTRS } from '@workbench/canvas-engine/math/mat2d';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.tsindex 8a5c55a2f1..0f6e32aef0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.ts@@ -1,6 +1,6 @@+import type { CanvasDocumentContractV2, CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2, CanvasImageRef, CanvasLayerContract } from '@workbench/types';import { RasterMemoryBudgetController } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.tsindex ac78c2041d..beb37b560f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts@@ -1,6 +1,6 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2 } from '@workbench/types';import { isEmpty } from '@workbench/canvas-engine/math/rect';import {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.test.tsindex 39de4f79f4..10945ccca5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.test.ts@@ -1,4 +1,4 @@-import type { CanvasControlLayerContract } from '@workbench/types';+import type { CanvasControlLayerContract } from '@workbench/canvas-engine/contracts';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.tsindex 7a407444a4..29af30bbaf 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.ts@@ -1,5 +1,5 @@+import type { CanvasControlLayerContract } from '@workbench/canvas-engine/contracts';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasControlLayerContract } from '@workbench/types';import type { HistoryEntry } from './history';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/importBoundaries.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/importBoundaries.test.tsdeleted file mode 100644index 80ce2d192b..0000000000--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/importBoundaries.test.ts+++ /dev/null@@ -1,33 +0,0 @@-import { describe, expect, it } from 'vitest';--const forbiddenPrefixes = [- '@workbench/backend',- '@workbench/canvas-operations',- '@workbench/generation',- '@workbench/widgets',-];--const modules = import.meta.glob('./**/*.ts', { eager: true, import: 'default', query: '?raw' });--const violations = (): string[] => {- const result: string[] = [];- for (const [file, loaded] of Object.entries(modules)) {- if (file.endsWith('.test.ts') || typeof loaded !== 'string') {- continue;- }- const source = loaded;- for (const match of source.matchAll(/from\s+['"]([^'"]+)['"]/g)) {- const specifier = match[1];- if (specifier && forbiddenPrefixes.some((prefix) => specifier.startsWith(prefix))) {- result.push(`${file.slice(2)} -> ${specifier}`);- }- }- }- return result.sort();-};--describe('canvas-engine import boundary', () => {- it('does not import application workflows, widgets, generation graphs, or backend networking', () => {- expect(violations()).toEqual([]);- });-});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.tsnew file mode 100644index 0000000000..4577e2f08b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts@@ -0,0 +1,34 @@+import type { CanvasStateContractV2 } from './contracts';+import type { RasterSurface } from './render/raster';+import type { Rect } from './types';++export interface CanvasDetachedLayerSurface {+ readonly rect: Rect;+ readonly surface: RasterSurface;+}++export interface CanvasRasterSnapshot {+ readonly canvas: CanvasStateContractV2;+ readonly documentGeneration: number;+ readonly emptyLayerIds: ReadonlySet<string>;+ readonly layerSurfaces: ReadonlyMap<string, CanvasDetachedLayerSurface>;+ release(): void;+}++export type CaptureRasterSnapshotResult =+ | { status: 'ok'; snapshot: CanvasRasterSnapshot }+ | { status: 'stale' | 'aborted' | 'not-ready' | 'over-budget' };++export interface CanvasCompositeExecutorDeps {+ backend: {+ createSurface(width: number, height: number): RasterSurface;+ encodeSurface(surface: RasterSurface, type?: string): Promise<Blob>;+ };+ getLayerSurface(layerId: string): Promise<{ surface: RasterSurface; rect: Rect }>;+ reserve?(+ bytes: number+ ):+ | { status: 'ok'; lease: { release(): void } }+ | { status: 'over-budget'; requestedBytes: number; availableBytes: number };+ uploadImage(blob: Blob): Promise<{ imageName: string; width: number; height: number }>;+}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.test.tsindex f06df52843..0de8f051e6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.test.ts@@ -1,4 +1,4 @@-import type { CanvasAdjustmentsContract } from '@workbench/types';+import type { CanvasAdjustmentsContract } from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.tsindex 176e5c51cc..741d8f5351 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.ts@@ -1,20 +1,4 @@-/**- * A cached, non-destructive "adjusted surface" per raster layer.- *- * Raster adjustments (brightness/contrast/saturation + curves) must be applied at- * composite time WITHOUT recomputing every frame (the plan explicitly forbids a- * third per-frame recompute alongside the mask-colorize and control-transparency- * smells). This store memoizes each layer's adjusted pixels, keyed by the source- * cache's `version` AND the adjustments' identity ({@link adjustmentsKey}), and- * rebuilds only when either changes — so a steady frame reuses the cached surface,- * an edit to the layer (cache version bump) invalidates it, and an unrelated- * layer's edit does not.- *- * Everything flows through the injected {@link RasterBackend} seam, so it runs- * unchanged in node tests. Zero React, zero import-time side effects.- */--import type { CanvasAdjustmentsContract } from '@workbench/types';+import type { CanvasAdjustmentsContract } from '@workbench/canvas-engine/contracts';import type { LayerCacheEntry } from './layerCache';import type { RasterBackend, RasterSurface } from './raster';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustments.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustments.test.tsindex 8fbe92e6b7..41d191941f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustments.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustments.test.ts@@ -1,4 +1,4 @@-import type { CanvasAdjustmentsContract } from '@workbench/types';+import type { CanvasAdjustmentsContract } from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustments.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustments.tsindex 9548f80b41..e32145bb1c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustments.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustments.ts@@ -1,28 +1,4 @@-/**- * Pure raster-adjustment math (no DOM, no engine, no React).- *- * Turns a {@link CanvasAdjustmentsContract} into per-channel 256-entry lookup- * tables and applies them (plus saturation) to raw `ImageData`. Kept pure and- * allocation-conscious so it can drive BOTH the non-destructive display cache- * (`adjustedSurfaceCache.ts`) and the generation composite- * (`export/compositeForGeneration.ts`), and so its correctness is exhaustively- * node-testable without any canvas.- *- * ## Composition order (documented, tested)- *- * Per channel, a single LUT is built as `contrast(brightness(curve(i)))`:- * 1. **Curve** — the per-channel monotone-cubic curve remaps the raw value.- * 2. **Brightness** — additive offset (`+ brightness * 255`).- * 3. **Contrast** — linear scale about mid-grey (`(v - 128) * (1 + contrast) + 128`).- * The LUT is applied to R/G/B; alpha is never touched. **Saturation** is applied- * last, per pixel, on the post-LUT values (a luminance lerp), since it mixes- * channels and cannot be expressed as an independent per-channel LUT.- *- * All scalar params are in `[-1, 1]` with `0` = identity; curve control points- * are `[input, output]` pairs in `[0, 255]`.- */--import type { CanvasAdjustmentsContract } from '@workbench/types';+import type { CanvasAdjustmentsContract } from '@workbench/canvas-engine/contracts';/** The identity adjustment (no brightness/contrast/saturation, no curves). */export const DEFAULT_ADJUSTMENTS: CanvasAdjustmentsContract = { brightness: 0, contrast: 0, saturation: 0 };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.tsindex c2cd087182..59d0b26ac9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.ts@@ -1,4 +1,8 @@-import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/types';+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasRasterLayerContractV2,+} from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.tsindex e4a59d82d8..3b2cdc1bf7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts@@ -13,8 +13,8 @@* Zero React, zero import-time side effects.*/+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { Mat2d, Vec2 } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2 } from '@workbench/types';import { isRenderableLayer } from '@workbench/canvas-engine/document/sources';import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.tsindex d7b7d0f41f..821e84ca44 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts@@ -1,11 +1,11 @@-import type { Mat2d } from '@workbench/canvas-engine/types';import type {CanvasBlendMode,CanvasDocumentContractV2,CanvasImageRef,CanvasLayerContract,CanvasRasterLayerContractV2,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';+import type { Mat2d } from '@workbench/canvas-engine/types';import { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import { identity } from '@workbench/canvas-engine/math/mat2d';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.tsindex d80aa00a6b..213295e6b7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts@@ -13,9 +13,13 @@* Zero React, zero import-time side effects.*/+import type {+ CanvasBlendMode,+ CanvasDocumentContractV2,+ CanvasLayerContract,+} from '@workbench/canvas-engine/contracts';import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';-import type { CanvasBlendMode, CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';import { LAYER_GROUP_COUNT, layerGroupRank } from '@workbench/canvas-engine/document/sources';import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.tsindex 86385ffe66..f1a5369490 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2, CanvasRasterLayerContractV2 } from '@workbench/types';+import type { CanvasDocumentContractV2, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.tsindex 96e29c979c..85f9757aef 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts@@ -1,5 +1,5 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2 } from '@workbench/types';import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';import { fromTRS } from '@workbench/canvas-engine/math/mat2d';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemandBudget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemandBudget.test.tsindex fe6deb56e4..201aa2b235 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemandBudget.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemandBudget.test.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2, CanvasRasterLayerContractV2 } from '@workbench/types';+import type { CanvasDocumentContractV2, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.test.tsindex 889ed647e2..670bd98e1f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.test.ts@@ -1,4 +1,4 @@-import type { CanvasMaskFillContract } from '@workbench/types';+import type { CanvasMaskFillContract } from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.tsindex 9967c413ee..6c59da9e94 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.ts@@ -1,25 +1,4 @@-/**- * Mask fill rendering: turns a mask layer's alpha stencil into a tinted,- * translucent overlay coloured by its {@link CanvasMaskFillContract}.- *- * Mirrors legacy (`features/controlLayers/konva/CanvasEntity/CanvasEntityObjectRenderer.ts`):- * the mask objects are drawn as an opaque alpha stencil, then a fill (a solid- * colour, or one of five line PATTERNS) is composited over them with- * `globalCompositeOperation: 'source-in'` so the colour/pattern shows ONLY where- * the mask is painted. The whole overlay is drawn above all raster/control- * content at the layer's opacity (legacy default `1`).- *- * Pattern tiles are small, colour-specific, cached surfaces built through the- * {@link RasterBackend} seam (like the transparency checkerboard). Legacy anchors- * its pattern to the screen; here the colorized surface is drawn through the- * layer transform, so the pattern is OBJECT-anchored (it scales/pans with the- * mask content) — a deliberate, documented simplification of the screen-anchored- * legacy behaviour that keeps the whole pipeline node-testable through the seam.- *- * Zero React, zero import-time side effects.- */--import type { CanvasMaskFillContract } from '@workbench/types';+import type { CanvasMaskFillContract } from '@workbench/canvas-engine/contracts';import type { RasterBackend, RasterSurface } from './raster';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.tsindex ed392ee353..26452bc12a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts@@ -1,5 +1,3 @@-import type { RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { Mat2d, Rect } from '@workbench/canvas-engine/types';import type {CanvasAdjustmentsContract,CanvasBlendMode,@@ -7,7 +5,9 @@ import type {CanvasLayerContract,CanvasLayerSourceContract,CanvasRasterLayerContractV2,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { Mat2d, Rect } from '@workbench/canvas-engine/types';import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';import { roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.test.tsindex ba15212d22..2cb0660a7a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.test.ts@@ -1,5 +1,5 @@+import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';-import type { CanvasLayerSourceContract } from '@workbench/types';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.tsindex fc31489014..baf5bfc502 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.ts@@ -13,8 +13,8 @@* Zero React, zero import-time side effects.*/+import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { CanvasLayerSourceContract } from '@workbench/types';import type { RasterizeDeps, RasterizeResult } from './types';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/imageRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/imageRasterizer.tsindex 270e04d2b9..f70ec5b8f4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/imageRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/imageRasterizer.ts@@ -8,9 +8,9 @@* with fakes. Zero React, zero import-time side effects.*/+import type { CanvasImageRef } from '@workbench/canvas-engine/contracts';import type { DecodedBitmapLease } from '@workbench/canvas-engine/render/decodedBitmapPool';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { CanvasImageRef } from '@workbench/types';import { createDecodedBitmapPool } from '@workbench/canvas-engine/render/decodedBitmapPool';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.tsindex 76c0c33676..e63f940e12 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts@@ -9,8 +9,8 @@* Zero React, zero import-time side effects.*/+import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { CanvasLayerSourceContract } from '@workbench/types';import type { RasterizeDeps, RasterizeResult } from './types';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/paintRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/paintRasterizer.tsindex 996f0282bb..9ef8f158ef 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/paintRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/paintRasterizer.ts@@ -9,8 +9,8 @@* Zero React, zero import-time side effects.*/+import type { CanvasImageRef } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { CanvasImageRef } from '@workbench/types';import type { RasterizeDeps, RasterizeResult } from './types';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/rasterizeSource.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/rasterizeSource.test.tsindex 4b5bc34e98..02127b6ea3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/rasterizeSource.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/rasterizeSource.test.ts@@ -1,5 +1,5 @@+import type { CanvasImageRef, CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { RasterBackend } from '@workbench/canvas-engine/render/raster';-import type { CanvasImageRef, CanvasLayerSourceContract } from '@workbench/types';import { createDecodedBitmapPool } from '@workbench/canvas-engine/render/decodedBitmapPool';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.test.tsindex 479963d877..7bb3f000f2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.test.ts@@ -1,5 +1,5 @@+import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';-import type { CanvasLayerSourceContract } from '@workbench/types';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.tsindex c4150d75fc..225aacbee5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts@@ -18,8 +18,8 @@* Zero React, zero import-time side effects.*/+import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { CanvasLayerSourceContract } from '@workbench/types';import type { RasterizeDeps, RasterizeResult } from './types';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.tsindex 63a57d3a33..7b61f3a805 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.ts@@ -26,8 +26,8 @@* Zero React, zero import-time side effects.*/+import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { CanvasLayerSourceContract } from '@workbench/types';import type { RasterizeDeps, RasterizeResult } from './types';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.test.tsindex 1bdd7ba10b..38096e9b74 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.test.ts@@ -1,4 +1,4 @@-import type { CanvasLayerContract, CanvasLayerSourceContract } from '@workbench/types';+import type { CanvasLayerContract, CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.tsindex 2b3d0f2474..71b4a0fca2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.ts@@ -1,15 +1,4 @@-/**- * Pure helpers for layer thumbnails.- *- * A layer's cache surface can be any size (up to the document dimensions); a- * thumbnail must fit within a small square box while preserving aspect ratio- * and never upscaling past the source. Extracted from the engine's- * `drawLayerThumbnail` so the arithmetic is unit-testable without a canvas.- *- * Zero React, zero DOM, zero import-time side effects.- */--import type { CanvasImageRef, CanvasLayerContract } from '@workbench/types';+import type { CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import { renderableSourceOf } from '@workbench/canvas-engine/document/sources';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.tsindex 6987f3f261..f5836df4a9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts@@ -1,8 +1,8 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2 } from '@workbench/types';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.tsindex 4847530b03..07f11a5ce4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts@@ -1,8 +1,8 @@+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { createLayerCacheStore, type LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.tsindex 348b8f279d..bdd06b14ca 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts@@ -1,8 +1,8 @@+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.tsindex 109ce6201f..3e0d23f4c8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts@@ -23,9 +23,9 @@* Zero React, zero import-time side effects.*/+import type { CanvasLayerSourceContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import type { Vec2 } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasLayerSourceContract, CanvasRasterLayerContractV2 } from '@workbench/types';import type { Tool, ToolContext } from './tool';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.tsindex 4940cfa7cc..1701bae609 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts@@ -1,7 +1,7 @@import type { SelectionCommit } from '@workbench/canvas-engine/selection/selectionState';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput } from '@workbench/canvas-engine/types';-import type { WorkbenchAction } from '@workbench/workbenchState';+import type { WorkbenchAction } from '@workbench/workbenchState.testing';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { createLassoTool, lassoOpFor } from '@workbench/canvas-engine/tools/lassoTool';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.tsindex 75403560c8..b4a2fad706 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import { estimateTextExtent } from '@workbench/canvas-engine/render/rasterizers/textRasterizer';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.tsindex 2b11e9c9ff..e10f36d1e9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts@@ -19,8 +19,12 @@* Zero React, zero import-time side effects.*/+import type {+ CanvasDocumentContractV2,+ CanvasLayerBaseContract,+ CanvasLayerContract,+} from '@workbench/canvas-engine/contracts';import type { Rect, Vec2 } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2, CanvasLayerBaseContract, CanvasLayerContract } from '@workbench/types';import {getSourceContentRect,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.tsindex c481a30180..8dd5124224 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts@@ -1,7 +1,7 @@+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.tsindex 4fdd551466..e7ce55c4c7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts@@ -20,8 +20,8 @@* Zero React, zero import-time side effects.*/+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';-import type { CanvasLayerContract } from '@workbench/types';import type { Tool, ToolContext } from './tool';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.tsindex 03d6f69039..3803a86c78 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts@@ -1,3 +1,8 @@+import type {+ CanvasControlLayerContract,+ CanvasDocumentContractV2,+ CanvasLayerContract,+} from '@workbench/canvas-engine/contracts';import type { StubRasterBackend, StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';import type {ControlPixelEditTransaction,@@ -7,7 +12,6 @@ import type {} from '@workbench/canvas-engine/tools/tool';import type { PointerInput } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasControlLayerContract, CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { isEmpty } from '@workbench/canvas-engine/math/rect';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.tsindex fddfc19887..df4484f939 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts@@ -14,8 +14,8 @@* Zero React, zero import-time side effects.*/+import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import type { PointerInput } from '@workbench/canvas-engine/types';-import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/types';import type { StrokeCommittedEvent, Tool, ToolContext } from './tool';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.tsindex cfa876f32e..f422734bc9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts@@ -1,8 +1,8 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2 } from '@workbench/types';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.tsindex 5bee9a84d0..f192aed0aa 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts@@ -20,9 +20,9 @@* Zero React, zero import-time side effects.*/+import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import type { Rect, Vec2 } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasRasterLayerContractV2 } from '@workbench/types';import type { Tool, ToolContext } from './tool';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.tsindex 211e492d24..f9daf9be72 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts@@ -28,10 +28,10 @@* unchanged on the node test stub. Zero React, zero dispatch on the move path.*/+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { PlacedSurface, PointerInput, Rect } from '@workbench/canvas-engine/types';-import type { CanvasLayerContract } from '@workbench/types';import { strokeToPath, type StrokeSamplePoint } from '@workbench/canvas-engine/freehand';import { intersect, isEmpty, roundOut, union } from '@workbench/canvas-engine/math/rect';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.tsindex 31cd513e97..ecae165733 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.ts@@ -1,6 +1,6 @@+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.tsindex ab0d7cad09..d0a53fee08 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.ts@@ -32,8 +32,12 @@* Zero React, zero import-time side effects.*/+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasLayerSourceContract,+} from '@workbench/canvas-engine/contracts';import type { Vec2 } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasLayerSourceContract } from '@workbench/types';import { applyToPoint, invert } from '@workbench/canvas-engine/math/mat2d';import { estimateTextExtent } from '@workbench/canvas-engine/render/rasterizers/textRasterizer';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex d0dc350f8c..61701964a4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -13,6 +13,7 @@* Zero React, zero import-time side effects.*/+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { EngineStores } from '@workbench/canvas-engine/engineStores';import type { CreatePath2D } from '@workbench/canvas-engine/freehand';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';@@ -25,7 +26,6 @@ import type { LayerTransform } from '@workbench/canvas-engine/transform/transforimport type { PlacedSurface, PointerInput, PointerModifiers, Rect, ToolId, Vec2 } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';/*** Emitted once per completed brush/eraser gesture. Persistence (Task P2.2) anddiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.tsindex 69dff9b25d..7ccbd8a3cb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts@@ -1,7 +1,7 @@+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { TRANSFORM_ROTATE_NUB_PX, transformOverlayGeometry } from '@workbench/canvas-engine/transform/transformMath';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.tsindex 3833123d0c..fb2f8c138f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts@@ -28,9 +28,9 @@* zero import-time side effects.*/+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { LayerTransform, TransformRect, TransformTarget } from '@workbench/canvas-engine/transform/transformMath';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';-import type { CanvasLayerContract } from '@workbench/types';import {applyMove,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.tsindex 86a18d21aa..0b81fe61ef 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.ts@@ -17,8 +17,8 @@* Zero React, zero DOM, zero import-time side effects.*/+import type { CanvasLayerBaseContract } from '@workbench/canvas-engine/contracts';import type { Mat2d, Vec2 } from '@workbench/canvas-engine/types';-import type { CanvasLayerBaseContract } from '@workbench/types';import { applyToPoint, fromTRS } from '@workbench/canvas-engine/math/mat2d';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/FilterOperationCoordinator.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/FilterOperationCoordinator.tsindex c0a7ca9e5f..577f398ac8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/FilterOperationCoordinator.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/FilterOperationCoordinator.ts@@ -1,4 +1,5 @@import type { LayerExportGuard } from '@workbench/canvas-engine/api';+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type {CanvasOperationActionResult,@@ -14,14 +15,14 @@ import type {FilterOperationSession,} from '@workbench/canvas-operations/contracts';import type { FilterCommitTarget, LayerFilterSettings } from '@workbench/canvas-operations/operationTypes';-import type { BackendGraphContract, CanvasDocumentContractV2 } from '@workbench/types';+import type { BackendGraphContract } from '@workbench/graphContracts';import {buildFilterDefaults,DEFAULT_CONTROL_FILTER_TYPE,getFilterDefinition,isFilterConfigValid,-} from '@workbench/generation/canvas/filterGraphs';+} from '@workbench/canvas-operations/filterGraphs';import { createFilterOperationSession } from './filterOperationSession';import { runLayerFilter } from './layerFilterRunner';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.tsindex 44bbb4210d..fe3655675d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts@@ -1,77 +1,59 @@-import type { CommitGeneratedImageResult, ReplaceSelectionFromImageResult } from '@workbench/canvas-engine/api';-import type { CommitRasterFilterResult } from '@workbench/canvas-engine/controllers/filterResultController';-import type {- CommitMaskImageResult,- MaskImageResultTarget,-} from '@workbench/canvas-engine/controllers/maskResultController';-import type {- CanvasApplicationOperationStores,- CanvasOperationController,- SelectObjectSessionProcessResult,-} from '@workbench/canvas-operations/contracts';-import type {- FilterCommitTarget,- LayerFilterSettings,- SamInput,- SamModel,- SamPointLabel,-} from '@workbench/canvas-operations/operationTypes';--export type StartSelectObjectSessionResult =- | 'started'- | 'missing'- | 'disabled'- | 'locked'- | 'unsupported'- | 'not-ready';-export type StartFilterOperationResult = 'started' | 'missing' | 'disabled' | 'locked' | 'unsupported' | 'not-ready';-export type CanvasOperationActionResult = 'completed' | 'blocked' | 'stale';-export type FilterCommitOperationResult = 'committed' | 'blocked' | 'stale';-export type CanvasOperationMutationResult = 'updated' | 'blocked' | 'stale';-export type SelectObjectSaveTarget = 'selection' | 'raster' | 'control' | MaskImageResultTarget;-export type SaveSelectObjectSessionResult =- | CommitGeneratedImageResult- | CommitMaskImageResult- | ReplaceSelectionFromImageResult;--export interface SelectObjectSessionUpdate {- input?: SamInput;- pointLabel?: SamPointLabel;- model?: SamModel;- invert?: boolean;- applyPolygonRefinement?: boolean;- autoProcess?: boolean;- isolatedPreview?: boolean;-}--export interface CanvasOperationCapability {- readonly controller: CanvasOperationController;- readonly stores: CanvasApplicationOperationStores;- startSelectObject(layerId: string): StartSelectObjectSessionResult;- startFilterOperation(layerId: string, recommendedFilterType?: string | null): StartFilterOperationResult;- updateFilterOperation(draft: LayerFilterSettings): CanvasOperationMutationResult;- setFilterOperationAutoProcess(value: boolean): CanvasOperationMutationResult;- processFilterOperation(): Promise<CanvasOperationActionResult>;- resetFilterOperation(settings: Record<string, unknown>): CanvasOperationMutationResult;- commitFilterOperation(- target: FilterCommitTarget,- makeImageDurable: (imageName: string) => Promise<void>- ): Promise<FilterCommitOperationResult>;- cancelFilterOperation(): void;- updateSelectObjectSession(changes: SelectObjectSessionUpdate): CanvasOperationMutationResult;- processSelectObjectSession(): Promise<SelectObjectSessionProcessResult>;- applySelectObjectSession(makeImageDurable: (imageName: string) => Promise<void>): Promise<CommitGeneratedImageResult>;- saveSelectObjectSession(- target: SelectObjectSaveTarget,- makeImageDurable: (imageName: string) => Promise<void>- ): Promise<SaveSelectObjectSessionResult>;- resetSelectObjectSession(): CanvasOperationMutationResult;- cancelSelectObjectSession(): void;-}--export type { CommitRasterFilterResult };+export type {+ CanvasOperationActionResult,+ CanvasCompositeTransaction,+ CanvasCompositeTransactionResult,+ CanvasOperationCapability,+ CanvasOperationMutationResult,+ CanvasOperationState,+ FilterCommitOperationResult,+ SaveSelectObjectSessionResult,+ SelectObjectSaveTarget,+ SelectObjectSessionUpdate,+ StartFilterOperationResult,+ StartSelectObjectSessionResult,+} from './contracts';export {importGalleryImagesToCanvas,type GalleryCanvasImportDestination,type ImportGalleryImagesResult,} from './importGalleryImages';+export { getCanvasImportNotice } from './canvasImportNotice';+export type {+ FilterOperationSessionState,+ SamInput,+ SamModel,+ SamSessionError,+ SamSessionErrorCode,+ SamSessionSnapshot,+} from './operationTypes';+export { getCanvasOperations } from './operationAccess';+export { getCanvasEngine } from './engineRegistry';+export { saveCanvasToGallery, type CanvasGallerySaveRegion } from './saveCanvasToGallery';+export { computeCompositeContentBounds } from './compositeForGeneration';+export {+ getBaseRasterContentBounds,+ getCompositeLayerBounds,+ planBaseRasterComposite,+ planComposites,+ planControlComposites,+ planRegionalMaskComposites,+} from './generationCompositePlan';+export type {+ CompositeEntry,+ CompositeLayerRef,+ CompositeMaskLayerRef,+ CompositePlan,+ Rect,+} from './generationContracts';+export {+ CONTROL_FILTERS,+ buildFilterGraph,+ buildFilterDefaults,+ getFilterDefinition,+ getFilterNumberBounds,+ isFilterConfigValid,+ isSpandrelModelIdentifier,+ type FilterParamSpec,+} from './filterGraphs';+export { resolveDefaultFilterForModel } from './controlRecommendations';+export { buildSamGraph, documentToExportLocalSamInput, isSamDocumentInputValid, isSamInputValid } from './samGraph';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/applicationPort.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/applicationPort.tsindex 35936f4123..d7488f7686 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/applicationPort.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/applicationPort.ts@@ -1,8 +1,8 @@import type { CanvasApplicationPort } from '@workbench/canvas-operations/contracts';-import { socketHub } from '@workbench/backend/socketHub';+import { runUtilityGraph } from '@features/queue/utility';+import { socketHub } from '@platform/transport/socketHub';import { uploadCanvasImage } from '@workbench/canvas-operations/backend/canvasImages';-import { runUtilityGraph } from '@workbench/canvas-operations/backend/utilityQueue';import {createFilterOperationCoordinator,type FilterOperationCoordinatorDeps,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.tsindex a2ae692bde..1202223b1b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts@@ -15,7 +15,7 @@import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';-import { buildApiUrl, getAuthToken } from '@workbench/backend/http';+import { buildApiUrl, getHttpAuthToken } from '@platform/transport/http';export type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';@@ -88,7 +88,7 @@ export const uploadCanvasImage = async (}const headers = new Headers();- const token = getAuthToken();+ const token = getHttpAuthToken();if (token) {headers.set('Authorization', `Bearer ${token}`);}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.tsindex 6a87283a5c..f36c43f130 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.ts@@ -1,16 +1,16 @@-import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';-import type { RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';-import type { Rect } from '@workbench/generation/canvas/types';import type {CanvasDocumentContractV2,CanvasImageRef,CanvasLayerContract,CanvasRasterLayerContractV2,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';+import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';+import type { Rect } from '@workbench/canvas-operations/generationContracts';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';-import { planComposites } from '@workbench/generation/canvas/compositePlan';+import { planComposites } from '@workbench/canvas-operations/generationCompositePlan';import { describe, expect, it, vi } from 'vitest';import type { ExecuteCompositePlanDeps } from './compositeForGeneration';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.tsindex ac31136540..a211a5176b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts@@ -28,11 +28,15 @@import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Mat2d, Rect } from '@workbench/canvas-engine/types';-import type { CompositeEntry, CompositeMaskLayerRef, CompositePlan } from '@workbench/generation/canvas/types';+import type {+ CompositeEntry,+ CompositeMaskLayerRef,+ CompositePlan,+} from '@workbench/canvas-operations/generationContracts';import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';import { renderRasterComposite } from '@workbench/canvas-engine/render/rasterComposite';-import { getCompositeLayerBounds } from '@workbench/generation/canvas/compositePlan';+import { getCompositeLayerBounds } from '@workbench/canvas-operations/generationCompositePlan';type Ctx = RasterSurface['ctx'];@@ -82,6 +86,28 @@ export const createCompositeDedupeCache = (): CompositeDedupeCache => ({byKey: new Map(),});+class BoundedMap<K, V> extends Map<K, V> {+ constructor(private readonly capacity: number) {+ super();+ }++ override set(key: K, value: V): this {+ if (!this.has(key) && this.size >= this.capacity) {+ const oldest = this.keys().next().value;+ if (oldest !== undefined) {+ this.delete(oldest);+ }+ }+ return super.set(key, value);+ }+}++/** Canvas-owned bounded cache used across generation transactions. */+export const createBoundedCompositeDedupeCache = (capacity = 16): CompositeDedupeCache => ({+ byHash: new BoundedMap(capacity),+ byKey: new BoundedMap(capacity),+});+/** Injected dependencies for {@link executeCompositePlan}. */export interface ExecuteCompositePlanDeps {/** Surface factory + encoder seam (usually the engine's `RasterBackend`). */diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.tsindex 34ba5a4ad6..959c417efc 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts@@ -1,18 +1,26 @@import type {CommitGeneratedImageResult,+ CanvasDocumentSnapshot,+ CanvasStateContractV2,LayerExportGuard,ReplaceSelectionFromImageResult,} from '@workbench/canvas-engine/api';+import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/canvas-engine/contracts';import type { CommitRasterFilterResult } from '@workbench/canvas-engine/controllers/filterResultController';import type {CommitMaskImageResult,MaskImageResultTarget,} from '@workbench/canvas-engine/controllers/maskResultController';import type { CanvasEditGate } from '@workbench/canvas-engine/editGate';-export type { CanvasCompositeExecutorDeps } from '@workbench/canvas-engine/api';import type { ExportBakedLayerBlobResult, ExportLayerPixelsResult } from '@workbench/canvas-engine/engine';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';+import type {+ CompositeEntryResult,+ CompositeResult,+ MaskCompositeResult,+} from '@workbench/canvas-operations/compositeForGeneration';+import type { CompositeEntry, CompositePlan } from '@workbench/canvas-operations/generationContracts';import type {FilterCommitTarget,FilterOperationSessionState,@@ -22,7 +30,8 @@ import type {SamSessionError,SamSessionSnapshot,} from '@workbench/canvas-operations/operationTypes';-import type { BackendGraphContract, CanvasDocumentContractV2, CanvasImageRef, WorkbenchState } from '@workbench/types';+import type { BackendGraphContract } from '@workbench/graphContracts';+import type { WorkbenchState } from '@workbench/projectContracts';export type StartSelectObjectSessionResult =| 'started'@@ -50,6 +59,63 @@ export interface SelectObjectSessionUpdate {isolatedPreview?: boolean;}+/** Intent-oriented application operations attached to one Canvas engine. */+export interface CanvasOperationCapability {+ captureCompositeTransaction(+ snapshot: CanvasDocumentSnapshot,+ layerIds: readonly string[],+ options: { signal: AbortSignal }+ ): Promise<CanvasCompositeTransactionResult>;+ uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;+ getOperationState(): CanvasOperationState;+ subscribeOperation(listener: () => void): () => void;+ getFilterSessionState(): FilterOperationSessionState | null;+ subscribeFilterSession(listener: () => void): () => void;+ getSamSessionState(): SamSessionSnapshot | null;+ subscribeSamSession(listener: () => void): () => void;+ startSelectObject(layerId: string): StartSelectObjectSessionResult;+ startFilterOperation(layerId: string, recommendedFilterType?: string | null): StartFilterOperationResult;+ updateFilterOperation(draft: LayerFilterSettings): CanvasOperationMutationResult;+ setFilterOperationAutoProcess(value: boolean): CanvasOperationMutationResult;+ processFilterOperation(): Promise<CanvasOperationActionResult>;+ resetFilterOperation(settings: Record<string, unknown>): CanvasOperationMutationResult;+ commitFilterOperation(+ target: FilterCommitTarget,+ makeImageDurable: (imageName: string) => Promise<void>+ ): Promise<FilterCommitOperationResult>;+ cancelFilterOperation(): void;+ updateSelectObjectSession(changes: SelectObjectSessionUpdate): CanvasOperationMutationResult;+ processSelectObjectSession(): Promise<SelectObjectSessionProcessResult>;+ applySelectObjectSession(makeImageDurable: (imageName: string) => Promise<void>): Promise<CommitGeneratedImageResult>;+ saveSelectObjectSession(+ target: SelectObjectSaveTarget,+ makeImageDurable: (imageName: string) => Promise<void>+ ): Promise<SaveSelectObjectSessionResult>;+ resetSelectObjectSession(): CanvasOperationMutationResult;+ cancelSelectObjectSession(): void;+}++/** Opaque generation transaction; pixels, surfaces, caches, and reservations remain Canvas-owned. */+export interface CanvasCompositeTransaction {+ readonly canvas: CanvasStateContractV2;+ executePlan(plan: CompositePlan): Promise<CompositeResult>;+ executeControl(entry: CompositeEntry): Promise<CompositeEntryResult>;+ executeMask(entry: CompositeEntry): Promise<MaskCompositeResult>;+ executeRegionalMask(entry: CompositeEntry): Promise<CompositeEntryResult>;+ commit(): void;+ release(): void;+}++export type CanvasCompositeTransactionResult =+ | { status: 'ok'; transaction: CanvasCompositeTransaction }+ | { status: 'stale' | 'aborted' | 'not-ready' | 'over-budget' };++/** Private composition shape; mutable stores and controller never cross the Canvas interface. */+export interface CanvasOperationImplementation extends CanvasOperationCapability {+ readonly controller: CanvasOperationController;+ readonly stores: CanvasApplicationOperationStores;+}+export type CanvasOperationIdentity =| { kind: 'select-object'; projectId: string; layerId: string }| { kind: 'filter'; projectId: string; layerId: string };diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/controlRecommendations.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/controlRecommendations.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/controlRecommendations.test.tsrename to invokeai/frontend/webv2/src/workbench/canvas-operations/controlRecommendations.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/controlRecommendations.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/controlRecommendations.tssimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/controlRecommendations.tsrename to invokeai/frontend/webv2/src/workbench/canvas-operations/controlRecommendations.tsindex 51cad604cd..4285d42e33 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/controlRecommendations.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/controlRecommendations.ts@@ -1,4 +1,4 @@-import type { ModelConfig } from '@workbench/models/types';+import type { ModelConfig } from '@features/models';import { isSupportedFilterType } from './filterGraphs';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.tsindex 205e71e4b9..b83fb976d4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts@@ -1,14 +1,23 @@import type {- CanvasEngine as CoreCanvasEngine,+ CanvasEngineImplementation as CoreCanvasEngineImplementation,CanvasEngineOptions as CoreCanvasEngineOptions,} from '@workbench/canvas-engine/engine';import type { CanvasUtilityGraphResult } from '@workbench/canvas-operations/contracts';-import type { BackendGraphContract } from '@workbench/types';+import type { BackendGraphContract } from '@workbench/graphContracts';import { createCanvasEngine as createCanvasEngineCore } from '@workbench/canvas-engine/engine';import { canvasApplicationPort } from '@workbench/canvas-operations/applicationPort';+import {+ createBoundedCompositeDedupeCache,+ executeCompositePlan,+ executeControlComposite,+ executeMaskComposite,+ executeRegionalMaskComposite,+} from '@workbench/canvas-operations/compositeForGeneration';-import type { CanvasOperationCapability } from './api';+import type { CanvasOperationCapability, CanvasOperationImplementation } from './contracts';++import { attachCanvasOperations } from './operationAccess';export interface CanvasEngineOptions extends Omit<CoreCanvasEngineOptions, 'uploadImage' | 'getMainModelBase'> {getMainModelBase?: () => string | null;@@ -31,17 +40,8 @@ export interface CanvasEngineOptions extends Omit<CoreCanvasEngineOptions, 'uplo}export type CanvasOperationsCapability = CanvasOperationCapability;-export type CanvasEngine = CoreCanvasEngine;--const operationsByEngine = new WeakMap<object, CanvasOperationCapability>();--export const getCanvasOperations = (engine: object): CanvasOperationCapability => {- const operations = operationsByEngine.get(engine);- if (!operations) {- throw new Error('Canvas application operations are unavailable for this engine.');- }- return operations;-};+/** Private application composition shape; public callers receive the capability-only handle from the registry API. */+export type CanvasEngine = CoreCanvasEngineImplementation;/** Application composition root: owns SAM/filter sessions, queues, uploads, and their core capability adapters. */export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine => {@@ -203,12 +203,57 @@ export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine =syncEditingLock();syncSamInteraction();- const operations: CanvasOperationCapability = {+ const compositeDedupe = createBoundedCompositeDedupeCache();++ const operations: CanvasOperationImplementation = {applySelectObjectSession: selectObjectCoordinator.apply,cancelFilterOperation: filterCoordinator.cancel,cancelSelectObjectSession: selectObjectCoordinator.cancel,+ captureCompositeTransaction: async (snapshot, layerIds, captureOptions) => {+ const capture = await core.exports.captureRasterSnapshot(snapshot, layerIds, captureOptions);+ if (capture.status !== 'ok') {+ return capture;+ }+ const rasterSnapshot = capture.snapshot;+ const transactionDedupe = {+ byHash: new Map(compositeDedupe.byHash),+ byKey: new Map(compositeDedupe.byKey),+ };+ const deps = {+ ...core.exports.getCompositeExecutorDeps(),+ dedupe: transactionDedupe,+ getLayerSurface: (layerId: string) => {+ const detached = rasterSnapshot.layerSurfaces.get(layerId);+ return detached+ ? Promise.resolve(detached)+ : Promise.reject(new Error(`Canvas raster snapshot is missing layer ${layerId}.`));+ },+ };+ return {+ status: 'ok',+ transaction: {+ canvas: rasterSnapshot.canvas,+ commit: () => {+ for (const [key, value] of transactionDedupe.byHash) {+ compositeDedupe.byHash.set(key, value);+ }+ for (const [key, value] of transactionDedupe.byKey) {+ compositeDedupe.byKey.set(key, value);+ }+ },+ executeControl: (entry) => executeControlComposite(entry, deps),+ executeMask: (entry) => executeMaskComposite(entry, deps),+ executePlan: (plan) => executeCompositePlan(plan, deps),+ executeRegionalMask: (entry) => executeRegionalMaskComposite(entry, deps),+ release: rasterSnapshot.release,+ },+ };+ },commitFilterOperation: filterCoordinator.commit,controller,+ getFilterSessionState: stores.filterSession.get,+ getOperationState: controller.getSnapshot,+ getSamSessionState: stores.samSession.get,processFilterOperation: filterCoordinator.process,processSelectObjectSession: selectObjectCoordinator.process,resetFilterOperation: filterCoordinator.reset,@@ -218,8 +263,21 @@ export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine =startFilterOperation: filterCoordinator.start,startSelectObject: selectObjectCoordinator.start,stores,+ subscribeFilterSession: stores.filterSession.subscribe,+ subscribeOperation: controller.subscribe,+ subscribeSamSession: stores.samSession.subscribe,updateFilterOperation: filterCoordinator.updateDraft,updateSelectObjectSession: selectObjectCoordinator.update,+ uploadIntermediate: async (blob, signal) => {+ if (signal?.aborted) {+ throw new DOMException('Canvas upload aborted', 'AbortError');+ }+ const uploaded = await canvasApplicationPort.uploadImage(blob, { isIntermediate: true });+ if (signal?.aborted) {+ throw new DOMException('Canvas upload aborted', 'AbortError');+ }+ return { imageName: uploaded.imageName };+ },};const coreSetInteractionLocked = core.tools.setInteractionLocked;@@ -277,6 +335,6 @@ export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine =};const engine: CanvasEngine = { ...core, diagnostics, lifecycle, tools };- operationsByEngine.set(engine, operations);+ attachCanvasOperations(engine, operations);return engine;};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.tsindex acffc3885f..ef67c63952 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts@@ -2,7 +2,7 @@ import type {CanvasControlLayerContract,CanvasDocumentContractV2,CanvasRegionalGuidanceLayerContract,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';import { createBitmapStore } from '@workbench/canvas-engine/document/bitmapStore';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';@@ -11,9 +11,12 @@ import {executeControlComposite,executeRegionalMaskComposite,} from '@workbench/canvas-operations/compositeForGeneration';+import {+ planControlComposites,+ planRegionalMaskComposites,+} from '@workbench/canvas-operations/generationCompositePlan';import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';-import { planControlComposites, planRegionalMaskComposites } from '@workbench/generation/canvas/compositePlan';import { createInitialWorkbenchState } from '@workbench/workbenchState';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.tsindex 1e714fc0c0..541b34ab88 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts@@ -14,6 +14,8 @@* Zero React, zero import-time side effects.*/+import type { CanvasEngine as PublicCanvasEngine } from '@workbench/canvas-engine/api';+import {createCanvasEngine,type CanvasEngine,@@ -128,5 +130,8 @@ export const createEngineRegistry = (const defaultRegistry = createEngineRegistry();export const getOrCreateEngine = defaultRegistry.getOrCreateEngine;-export const getEngine = defaultRegistry.getEngine;export const releaseEngine = defaultRegistry.releaseEngine;++/** Non-owning public lookup. Engine construction and lease management stay inside Canvas composition. */+export const getCanvasEngine = (projectId: string): PublicCanvasEngine | undefined =>+ defaultRegistry.getEngine(projectId);diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.test.tssimilarity index 100%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.test.tsrename to invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.test.tsdiff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.tssimilarity index 94%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.tsrename to invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.tsindex 65db2a0299..e301b0d920 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.ts@@ -1,21 +1,4 @@-/**- * Pure control-filter graph builders (legacy parity).- *- * A control layer can non-destructively preview a filter (canny, depth, pose, …)- * over its composited source. This module names each supported filter, its- * legacy-default settings, and the one-node backend graph it compiles to — with- * NO fetch, NO engine, NO React. The executor composites + uploads the layer's- * source image, then {@link buildFilterGraph} shapes the graph the utility queue- * runs; its `outputNodeId` names the node whose output image is the preview.- *- * Node type strings + defaults mirror legacy- * `features/controlLayers/store/filters.ts` (`IMAGE_FILTERS`): every filter here- * builds the exact backend nodes used by legacy, fed `image: { image_name }`- * plus the filter's parameters. The registry is the spec — settings editors- * read `buildDefaults()` and the param metadata.- */--import type { BackendGraphContract } from '@workbench/types';+import type { BackendGraphContract } from '@workbench/graphContracts';/** The deterministic node id every single-node filter graph uses. */export const FILTER_NODE_ID = 'control_filter';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.test.tsindex 0286869867..8375d7dad1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.test.ts@@ -1,5 +1,5 @@+import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import type { ExportLayerPixelsResult, LayerExportGuard } from '@workbench/canvas-engine/engine';-import type { CanvasRasterLayerContractV2 } from '@workbench/types';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { createCanvasOperationController } from '@workbench/canvas-operations/operationController';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/fullEngineImportAudit.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/fullEngineImportAudit.tsdeleted file mode 100644index 47e438d7e8..0000000000--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/fullEngineImportAudit.ts+++ /dev/null@@ -1,37 +0,0 @@-const FULL_ENGINE_MODULE_PATTERN = String.raw`(?:@workbench/canvas-engine/engine|@workbench/canvas-operations/createCanvasEngine)`;-const FULL_ENGINE_MODULE = new RegExp(String.raw`['"]${FULL_ENGINE_MODULE_PATTERN}['"]`);--/** Detects every supported syntax that exposes or references the full CanvasEngine type. */-export const referencesFullCanvasEngine = (source: string): boolean => {- const namedReference = new RegExp(- String.raw`(?:import|export)(?:\s+type)?\s*\{[^}]*\bCanvasEngine\b[^}]*\}\s*from\s*['"]${FULL_ENGINE_MODULE_PATTERN}['"]`,- 's'- );- if (namedReference.test(source)) {- return true;- }-- const starReExport = new RegExp(- String.raw`export\s*\*\s*(?:as\s+[A-Za-z_$][\w$]*\s*)?from\s*['"]${FULL_ENGINE_MODULE_PATTERN}['"]`- );- if (starReExport.test(source)) {- return true;- }-- const inlineReference = new RegExp(- String.raw`import\s*\(\s*['"]${FULL_ENGINE_MODULE_PATTERN}['"]\s*\)\s*\.\s*CanvasEngine\b`- );- if (inlineReference.test(source)) {- return true;- }-- const namespaceImport = /import(?:\s+type)?\s*\*\s*as\s*[A-Za-z_$][\w$]*\s*from\s*([^;\n]+)/g;- for (const match of source.matchAll(namespaceImport)) {- const moduleSource = match[1];- if (moduleSource && FULL_ENGINE_MODULE.test(moduleSource)) {- return true;- }- }-- return false;-};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/fullEngineImports.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/fullEngineImports.test.tsdeleted file mode 100644index ae4741a4fe..0000000000--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/fullEngineImports.test.ts+++ /dev/null@@ -1,54 +0,0 @@-import { describe, expect, it } from 'vitest';--import { referencesFullCanvasEngine } from './fullEngineImportAudit';--const modules = import.meta.glob('../**/*.{ts,tsx}', { eager: true, import: 'default', query: '?raw' });--const ALLOWED = new Set(['./createCanvasEngine.ts', './engineRegistry.ts']);-const fullEngineImports = (): string[] => {- const result: string[] = [];- for (const [file, source] of Object.entries(modules)) {- const relative = file.replace('../', '');- if (- relative.endsWith('.test.ts') ||- relative.endsWith('.test.tsx') ||- ALLOWED.has(relative) ||- typeof source !== 'string'- ) {- continue;- }- if (referencesFullCanvasEngine(source)) {- result.push(relative);- }- }- return result.sort();-};--describe('full CanvasEngine consumer boundary', () => {- it.each([- [`export type { CanvasEngine } from '@workbench/canvas-engine/engine';`, 'named type re-export'],- [`export { CanvasEngine as PublicEngine } from '@workbench/canvas-engine/engine';`, 'aliased re-export'],- [`export * from '@workbench/canvas-engine/engine';`, 'star re-export'],- [`export * as Core from '@workbench/canvas-engine/engine';`, 'namespace re-export'],- [- `import type * as Core from '@workbench/canvas-engine/engine'; type Consumer = Core.CanvasEngine;`,- 'qualified namespace reference',- ],- [`import * as Core from '@workbench/canvas-engine/engine'; void Core;`, 'namespace import'],- [`type Consumer = import('@workbench/canvas-operations/createCanvasEngine').CanvasEngine;`, 'inline imported type'],- ])('detects $1', (source) => {- expect(referencesFullCanvasEngine(source)).toBe(true);- });-- it('does not reject a named import of a narrow capability', () => {- expect(- referencesFullCanvasEngine(- `import type { CanvasCoreStores } from '@workbench/canvas-engine/engine'; type Stores = CanvasCoreStores;`- )- ).toBe(false);- });-- it('limits the full engine type to registry and composition roots', () => {- expect(fullEngineImports()).toEqual([]);- });-});diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.tssimilarity index 99%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.test.tsrename to invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.tsindex cef05be6db..fd137e2da3 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.ts@@ -5,18 +5,18 @@ import type {CanvasLayerContract,CanvasRasterLayerContractV2,CanvasRegionalGuidanceLayerContract,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';-import type { Rect } from './types';+import type { Rect } from './generationContracts';import {getBaseRasterContentBounds,planComposites,planControlComposites,planRegionalMaskComposites,-} from './compositePlan';+} from './generationCompositePlan';const imageRef = (imageName: string, width = 64, height = 48): CanvasImageRef => ({ height, imageName, width });diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.tssimilarity index 86%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.tsrename to invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.tsindex ca5591186f..658658642e 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.ts@@ -1,29 +1,3 @@-/**- * Pure composite planner.- *- * {@link planComposites} turns a canvas document + generation bbox into a- * {@link CompositePlan} — a pixel-free description of what the executor must- * composite and upload — without touching any pixels or the engine. Phase 4.2- * emits a single `base-raster` entry: the enabled raster layers (image/paint- * sources) in z-order, each with its transform / opacity / blend mode.- *- * ## Stable identity key- *- * Each entry carries a `key` derived from exactly the inputs that determine its- * pixels: the bbox rect plus, for each contributing layer in z-order, its- * `(id, sourceRef, transform, opacity, blendMode)`. Only *enabled* raster- * layers contribute, so a layer's enablement is encoded by its presence in the- * list (toggling it on/off changes the set, and thus the key). This makes the- * key:- * - **stable**: same document + bbox → byte-identical key;- * - **sensitive** to reorder, opacity, transform, source swap, and bbox moves;- * - **insensitive** to irrelevant edits: `selectedLayerId`, background, and any- * change to a disabled layer (it never appears in the list).- *- * The key is a plain deterministic string (no hashing needed) so it stays cheap- * and debuggable; the executor uses it as a map key to skip redundant work.- */-import type {CanvasControlLayerContract,CanvasDocumentContractV2,@@ -31,18 +5,24 @@ import type {CanvasLayerContract,CanvasLayerSourceContract,CanvasRegionalGuidanceLayerContract,-} from '@workbench/types';+} from '@workbench/canvas-engine/api';-import { adjustmentsKey } from '@workbench/canvas-engine/render/adjustments';import {+ adjustmentsKey,getBaseRasterContentBounds,getCompositeLayerBounds,planBaseRasterComposite,-} from '@workbench/canvas-engine/render/rasterComposite';+} from '@workbench/canvas-engine/api';-import type { CompositeEntry, CompositeLayerRef, CompositeMaskLayerRef, CompositePlan, Rect } from './types';+import type {+ CompositeEntry,+ CompositeLayerRef,+ CompositeMaskLayerRef,+ CompositePlan,+ Rect,+} from './generationContracts';-import { DEFAULT_MASK_DENOISE_LIMIT } from './types';+import { DEFAULT_MASK_DENOISE_LIMIT } from './generationContracts';/** A stable string identifying a source's pixels (its asset name, or an empty sentinel). */const sourceRefOf = (source: CanvasLayerSourceContract): string => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationContracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationContracts.tsnew file mode 100644index 0000000000..2ce6c5edb4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationContracts.ts@@ -0,0 +1,26 @@+import type { CompositeEntry as RasterCompositeEntry, CompositeLayerRef, Rect } from '@workbench/canvas-engine/api';++export type { CompositeLayerRef, Rect };++export const DEFAULT_MASK_DENOISE_LIMIT = 1;++export type CompositeEntryKind = 'base-raster' | 'inpaint-mask' | 'noise-mask' | 'control-layer' | 'regional-mask';++export interface CompositeMaskLayerRef extends Pick<+ CompositeLayerRef,+ 'id' | 'sourceRef' | 'contentSize' | 'contentOffset' | 'transform'+> {+ attributeValue: number;+}++export interface CompositeEntry extends RasterCompositeEntry {+ kind: CompositeEntryKind;+ key: string;+ maskLayers?: CompositeMaskLayerRef[];+ layerId?: string;+}++export interface CompositePlan {+ bbox: Rect;+ entries: CompositeEntry[];+}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.tsindex 123c79dfc0..6aa2e3f3d0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts@@ -1,9 +1,10 @@+import type { GalleryImage } from '@features/gallery';+import type { GenerateWidgetValues } from '@features/generation/contracts';+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CanvasEngine } from '@workbench/canvas-engine/engine';import type { uploadCanvasImage } from '@workbench/canvas-operations/backend/canvasImages';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { GalleryImage } from '@workbench/gallery/api';-import type { GenerateWidgetValues } from '@workbench/generation/types';-import type { CanvasLayerContract, Project, WorkbenchState } from '@workbench/types';+import type { Project, WorkbenchState } from '@workbench/projectContracts';import {createControlLayer,@@ -15,11 +16,16 @@ import {nextRegionalGuidanceFillColor,} from '@workbench/widgets/layers/layerOps';import { getProjectWidgetValues } from '@workbench/widgetState';-import { createInitialWorkbenchState, type WorkbenchAction } from '@workbench/workbenchState';+import { createInitialWorkbenchState, type WorkbenchAction } from '@workbench/workbenchState.testing';import { describe, expect, it, vi } from 'vitest';import { importGalleryImagesToCanvas, type GalleryCanvasImportDestination } from './importGalleryImages';+const queriesFor = (getState: () => WorkbenchState) => ({+ getProject: (projectId: string) => getState().projects.find((project) => project.id === projectId) ?? null,+ isActiveProject: (projectId: string) => getState().activeProjectId === projectId,+});+const image = (imageName: string, width = 320, height = 160): GalleryImage => ({boardId: 'none',height,@@ -190,9 +196,10 @@ describe('importGalleryImagesToCanvas', () => {const result = await importGalleryImagesToCanvas({destination,- dispatch,+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),engine: canvasEngine,- getState: () => state,+ ...queriesFor(() => state),images,project,});@@ -238,10 +245,11 @@ describe('importGalleryImagesToCanvas', () => {const result = await importGalleryImagesToCanvas({destination: 'control-resized',- dispatch,+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),engine: null,fetchImage,- getState: () => state,+ ...queriesFor(() => state),images: [image('wide.png', 1600, 900), image('square.png', 400, 400)],project,uploadImage,@@ -305,9 +313,10 @@ describe('importGalleryImagesToCanvas', () => {const dispatch = vi.fn<(action: WorkbenchAction) => void>();const result = await importGalleryImagesToCanvas({destination: 'raster',- dispatch,+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),engine: null,- getState: () => state,+ ...queriesFor(() => state),images: [],project,});@@ -321,13 +330,13 @@ describe('importGalleryImagesToCanvas', () => {const uploadImage = vi.fn<typeof uploadCanvasImage>();const result = await importGalleryImagesToCanvas({destination: 'control-resized',- dispatch: vi.fn(),+ applyCanvasMutation: () => undefined,engine: engine(project.id,vi.fn(() => false)),fetchImage,- getState: () => state,+ ...queriesFor(() => state),images: [image('a.png')],project,uploadImage,@@ -348,14 +357,14 @@ describe('importGalleryImagesToCanvas', () => {>(() => false);const result = await importGalleryImagesToCanvas({destination: 'control-resized',- dispatch: vi.fn(),+ applyCanvasMutation: () => undefined,engine: engine(project.id,vi.fn(() => true),commitStructural),fetchImage,- getState: () => state,+ ...queriesFor(() => state),images: [image('a.png')],project,uploadImage,@@ -382,10 +391,11 @@ describe('importGalleryImagesToCanvas', () => {const dispatch = vi.fn<(action: WorkbenchAction) => void>();const result = await importGalleryImagesToCanvas({destination: 'control-resized',- dispatch,+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),engine: null,fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),- getState: () => current,+ ...queriesFor(() => current),images: [image('a.png')],project,uploadImage,@@ -406,10 +416,11 @@ describe('importGalleryImagesToCanvas', () => {});const result = await importGalleryImagesToCanvas({destination: 'control-resized',- dispatch,+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),engine: matchingEngine,fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),- getState: () => current,+ ...queriesFor(() => current),images: [image('a.png')],project,uploadImage,@@ -438,10 +449,11 @@ describe('importGalleryImagesToCanvas', () => {const result = await importGalleryImagesToCanvas({destination: 'control-resized',- dispatch,+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),engine: matchingEngine,fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),- getState: () => current,+ ...queriesFor(() => current),images: [image('a.png')],project,uploadImage,@@ -469,10 +481,11 @@ describe('importGalleryImagesToCanvas', () => {const dispatch = vi.fn<(action: WorkbenchAction) => void>();const result = await importGalleryImagesToCanvas({destination: 'control-resized',- dispatch,+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),engine: null,fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),- getState: () => current,+ ...queriesFor(() => current),images: [image('a.png')],project,uploadImage,@@ -498,27 +511,27 @@ describe('importGalleryImagesToCanvas', () => {);const firstImport = importGalleryImagesToCanvas({destination: 'control-resized',- dispatch: vi.fn(),+ applyCanvasMutation: () => undefined,engine: null,fetchImage,- getState: () => first.state,+ ...queriesFor(() => first.state),images: [image('a.png')],project: first.project,uploadImage,});const overlap = await importGalleryImagesToCanvas({destination: 'raster',- dispatch: vi.fn(),+ applyCanvasMutation: () => undefined,engine: null,- getState: () => first.state,+ ...queriesFor(() => first.state),images: [image('b.png')],project: first.project,});const independent = await importGalleryImagesToCanvas({destination: 'raster',- dispatch: vi.fn(),+ applyCanvasMutation: () => undefined,engine: null,- getState: () => secondState,+ ...queriesFor(() => secondState),images: [image('c.png')],project: secondProject,});@@ -551,10 +564,11 @@ describe('importGalleryImagesToCanvas', () => {const dispatch = vi.fn<(action: WorkbenchAction) => void>();const importing = importGalleryImagesToCanvas({destination: 'control-resized',- dispatch,+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),engine: null,fetchImage,- getState: () => state,+ ...queriesFor(() => state),images: Array.from({ length: 7 }, (_, index) => image(`${index}.png`)),project,uploadImage,@@ -582,10 +596,10 @@ describe('importGalleryImagesToCanvas', () => {const { project, state } = withProject();const options = {destination: 'control-resized' as const,- dispatch: vi.fn(),+ applyCanvasMutation: () => undefined,engine: null,fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),- getState: () => state,+ ...queriesFor(() => state),images: [image('a.png'), image('b.png')],project,uploadImage: vi.fn<typeof uploadCanvasImage>(() => Promise.reject(new Error('failed'))),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.tsindex 302eda495b..15e54593fe 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts@@ -1,12 +1,14 @@+import type { GalleryImage } from '@features/gallery';import type { CanvasLayerCapability } from '@workbench/canvas-engine/api';+import type { CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { GalleryImage } from '@workbench/gallery/api';-import type { CanvasImageRef, CanvasLayerContract, Project, WorkbenchState } from '@workbench/types';-import type { WorkbenchAction } from '@workbench/workbenchState';-import type { Dispatch } from 'react';+import type { Project } from '@workbench/projectContracts';-import { getGenerationDimensions } from '@workbench/generation/baseGenerationPolicies';-import { calculateNewSize, normalizeGenerateWidgetValues } from '@workbench/generation/settings';+import {+ calculateNewSize,+ getGenerationDimensions,+ normalizeGenerateWidgetValues,+} from '@features/generation/settings';import {createControlLayer,createEmptyPaintLayer,@@ -215,22 +217,24 @@ const resizeImages = async (type GalleryImportEngine = { readonly projectId: string; readonly layers: CanvasLayerCapability };export const importGalleryImagesToCanvas = async (options: {+ applyCanvasMutation: (projectId: string, mutation: CanvasProjectMutation) => boolean | void;destination: GalleryCanvasImportDestination;- dispatch: Dispatch<WorkbenchAction>;engine: GalleryImportEngine | null;- getState: () => WorkbenchState;+ getProject: (projectId: string) => Project | null;+ isActiveProject: (projectId: string) => boolean;images: readonly GalleryImage[];project: Project;fetchImage?: typeof fetch;uploadImage?: typeof uploadCanvasImage;}): Promise<ImportGalleryImagesResult> => {const {+ applyCanvasMutation,destination,- dispatch,engine,fetchImage = globalThis.fetch,- getState,+ getProject,images,+ isActiveProject,project,uploadImage = uploadCanvasImage,} = options;@@ -244,13 +248,8 @@ export const importGalleryImagesToCanvas = async (options: {try {const capturedDocument = project.canvas.document;- const initialState = getState();const matchingProjectEngine = engine !== null && engine.projectId === project.id ? engine : null;- if (- matchingProjectEngine &&- initialState.activeProjectId === project.id &&- !matchingProjectEngine.layers.canCommitStructural()- ) {+ if (matchingProjectEngine && isActiveProject(project.id) && !matchingProjectEngine.layers.canCommitStructural()) {return { status: 'blocked' };}@@ -277,8 +276,7 @@ export const importGalleryImagesToCanvas = async (options: {type: 'applyCanvasLayerStackMutation',};- const latestState = getState();- const latestProject = latestState.projects.find((candidate) => candidate.id === project.id);+ const latestProject = getProject(project.id);if (!latestProject) {return { status: 'stale-project' };}@@ -286,12 +284,12 @@ export const importGalleryImagesToCanvas = async (options: {return { status: 'stale-document' };}- if (matchingProjectEngine && latestState.activeProjectId === project.id) {+ if (matchingProjectEngine && isActiveProject(project.id)) {if (!matchingProjectEngine.layers.commitStructural('Import gallery images', forward, inverse)) {return { status: 'blocked' };}} else {- dispatch({ mutation: forward, projectId: project.id, type: 'applyCanvasProjectMutation' });+ applyCanvasMutation(project.id, forward);}return { failedImageNames, layerIds: layers.map((layer) => layer.id), status: 'imported' };} finally {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerFilterRunner.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerFilterRunner.tsindex ce3b0e7284..3796e5c924 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerFilterRunner.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerFilterRunner.ts@@ -1,9 +1,9 @@import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-import type { BackendGraphContract } from '@workbench/types';+import type { BackendGraphContract } from '@workbench/graphContracts';import { LayerFilterOutputDimensionError } from '@workbench/canvas-engine/filterError';-import { buildFilterGraph } from '@workbench/generation/canvas/filterGraphs';+import { buildFilterGraph } from '@workbench/canvas-operations/filterGraphs';export { LayerFilterOutputDimensionError } from '@workbench/canvas-engine/filterError';export interface LayerFilterResult {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerImageResult.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerImageResult.test.tsindex 3ab9ceb8aa..53f8b3e0a2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerImageResult.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerImageResult.test.ts@@ -1,5 +1,5 @@+import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import type { LayerExportGuard } from '@workbench/canvas-engine/engine';-import type { CanvasRasterLayerContractV2 } from '@workbench/types';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerImageResult.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerImageResult.tsindex 9a10e27ac8..92470579d5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerImageResult.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerImageResult.ts@@ -1,12 +1,12 @@+import type { RunUtilityGraphOptions, UtilityGraphResult } from '@features/queue/utility';+import type { CanvasImageRef } from '@workbench/canvas-engine/contracts';import type { ExportBakedLayerBlobResult, LayerExportGuard } from '@workbench/canvas-engine/engine';import type { Rect } from '@workbench/canvas-engine/types';-import type { RunUtilityGraphOptions, UtilityGraphResult } from '@workbench/canvas-operations/backend/utilityQueue';import type { SamSessionErrorCode } from '@workbench/canvas-operations/operationTypes';-import type { SamInput, SamModel } from '@workbench/generation/canvas/samGraph';-import type { CanvasImageRef } from '@workbench/types';+import type { SamInput, SamModel } from '@workbench/canvas-operations/samGraph';-import { UtilityQueueError } from '@workbench/canvas-operations/backend/utilityQueue';-import { buildSamGraph, documentToExportLocalSamInput, isSamInputValid } from '@workbench/generation/canvas/samGraph';+import { UtilityQueueError } from '@features/queue/utility';+import { buildSamGraph, documentToExportLocalSamInput, isSamInputValid } from '@workbench/canvas-operations/samGraph';export interface SelectObjectReadyResult {status: 'ready';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/operationAccess.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/operationAccess.tsnew file mode 100644index 0000000000..d0e18c41c6--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/operationAccess.ts@@ -0,0 +1,19 @@+import type { CanvasOperationCapability, CanvasOperationImplementation } from './contracts';++const operationsByEngine = new WeakMap<object, CanvasOperationImplementation>();++export const getCanvasOperationImplementation = (engine: object): CanvasOperationImplementation => {+ const operations = operationsByEngine.get(engine);+ if (!operations) {+ throw new Error('Canvas application operations are unavailable for this engine.');+ }+ return operations;+};++export const getCanvasOperations = (engine: object): CanvasOperationCapability =>+ getCanvasOperationImplementation(engine);++/** Canvas composition hook; callers consume only `getCanvasOperations`. */+export const attachCanvasOperations = (engine: object, operations: CanvasOperationImplementation): void => {+ operationsByEngine.set(engine, operations);+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/operationController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/operationController.test.tsindex 1327aac1f0..c06a14d630 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/operationController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/operationController.test.ts@@ -1,5 +1,5 @@import type { LayerExportGuard } from '@workbench/canvas-engine/api';-import type { CanvasRasterLayerContractV2 } from '@workbench/types';+import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import { createCanvasEditGate } from '@workbench/canvas-engine/editGate';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/react.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/react.tsnew file mode 100644index 0000000000..b05592949a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/react.ts@@ -0,0 +1,2 @@+/** React lifecycle adapter for the Canvas engine registry. Core operations remain React-free. */+export { type CanvasEngineHandle, useCanvasEngine } from './useCanvasEngine';diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/samGraph.test.tssimilarity index 99%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.test.tsrename to invokeai/frontend/webv2/src/workbench/canvas-operations/samGraph.test.tsindex 4297f0f95e..36e152b941 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/samGraph.test.ts@@ -1,4 +1,4 @@-import type { BackendGraphEdgeContract } from '@workbench/types';+import type { BackendGraphEdgeContract } from '@workbench/graphContracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/samGraph.tssimilarity index 95%rename from invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.tsrename to invokeai/frontend/webv2/src/workbench/canvas-operations/samGraph.tsindex 16c1a0788a..714ca2c2df 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/samGraph.ts@@ -1,10 +1,10 @@-import type { Rect, Vec2 } from '@workbench/canvas-engine/types';-import type { SamInput, SamModel } from '@workbench/canvas-operations/operationTypes';-import type { BackendGraphContract } from '@workbench/types';-export type { SamInput, SamModel } from '@workbench/canvas-operations/operationTypes';+import type { Rect, Vec2 } from '@workbench/canvas-engine/api';+import type { SamInput, SamModel } from '@workbench/canvas-operations/api';+import type { BackendGraphContract } from '@workbench/graphContracts';+export type { SamInput, SamModel } from '@workbench/canvas-operations/api';-import { documentToExportLocalSamPoint } from '@workbench/canvas-engine/samCoordinates';-import { addEdge, addNode } from '@workbench/generation/graphBuilder';+import { addEdge, addNode } from '@features/generation/graph';+import { documentToExportLocalSamPoint } from '@workbench/canvas-engine/api';export interface BuildSamGraphOptions {imageName: string;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.tsindex d7b33aa709..3a120830c1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts@@ -1,10 +1,11 @@+import type { GenerateModelConfig, GenerateWidgetValues, MainModelConfig } from '@features/generation/contracts';+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { CanvasEngine } from '@workbench/canvas-engine/engine';import type { RasterCompositeExportResult } from '@workbench/canvas-engine/exportRasterComposite';import type { Rect } from '@workbench/canvas-engine/types';-import type { GenerateModelConfig, GenerateWidgetValues, MainModelConfig } from '@workbench/generation/types';-import type { CanvasDocumentContractV2, Project } from '@workbench/types';+import type { Project } from '@workbench/projectContracts';-import { getDefaultGenerateSettings } from '@workbench/generation/baseGenerationPolicies';+import { getDefaultGenerateSettings } from '@features/generation/settings';import { getProjectWidgetInstance } from '@workbench/widgetState';import { createInitialWorkbenchState } from '@workbench/workbenchState';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.tsindex 3cc872c6bb..255831fb25 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts@@ -4,12 +4,11 @@ import type {CanvasLifecycleCapability,} from '@workbench/canvas-engine/api';import type { Rect } from '@workbench/canvas-engine/types';-import type { Project } from '@workbench/types';+import type { Project } from '@workbench/projectContracts';-import { isDateBoardId } from '@workbench/gallery/api';-import { isSupportedGenerateModel } from '@workbench/generation/baseGenerationPolicies';-import { toModelIdentifier } from '@workbench/generation/graphBuilder';-import { normalizeGenerateWidgetValues } from '@workbench/generation/settings';+import { isGalleryVirtualBoard } from '@features/gallery';+import { toModelIdentifier } from '@features/generation/graph';+import { isSupportedGenerateModel, normalizeGenerateWidgetValues } from '@features/generation/settings';import { getProjectWidgetValues } from '@workbench/widgetState';import { uploadCanvasImage } from './backend/canvasImages';@@ -46,7 +45,7 @@ const buildCanvasSaveMetadata = (project: Project, rect: Rect): Record<string, uconst getCanvasSaveBoardId = (project: Project): string | undefined => {const selectedBoardId = getProjectWidgetValues(project, 'gallery').selectedBoardId;- return typeof selectedBoardId === 'string' && selectedBoardId !== 'none' && !isDateBoardId(selectedBoardId)+ return typeof selectedBoardId === 'string' && selectedBoardId !== 'none' && !isGalleryVirtualBoard(selectedBoardId)? selectedBoardId: undefined;};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.test.tsindex 83cc88af1d..2e4d48eb14 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.test.ts@@ -1,8 +1,8 @@+import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import type { LayerExportGuard } from '@workbench/canvas-engine/engine';import type { SamSessionError } from '@workbench/canvas-operations/operationTypes';-import type { CanvasRasterLayerContractV2 } from '@workbench/types';-import { UtilityQueueError } from '@workbench/canvas-operations/backend/utilityQueue';+import { UtilityQueueError } from '@features/queue/utility';import { createCanvasOperationController } from '@workbench/canvas-operations/operationController';import { afterEach, describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.tsindex 7fcbb37985..ef80c6b04c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.ts@@ -1,15 +1,15 @@+import type { RunUtilityGraphOptions, UtilityGraphResult } from '@features/queue/utility';import type { ExportBakedLayerBlobResult, LayerExportGuard } from '@workbench/canvas-engine/engine';import type { Rect } from '@workbench/canvas-engine/types';-import type { RunUtilityGraphOptions, UtilityGraphResult } from '@workbench/canvas-operations/backend/utilityQueue';import type {CanvasOperationController,CanvasOperationRunResult,CanvasOperationSession,} from '@workbench/canvas-operations/operationController';import type { SamSessionError, SamSessionErrorCode } from '@workbench/canvas-operations/operationTypes';-import type { SamInput, SamModel } from '@workbench/generation/canvas/samGraph';+import type { SamInput, SamModel } from '@workbench/canvas-operations/samGraph';-import { isSamDocumentInputValid } from '@workbench/generation/canvas/samGraph';+import { isSamDocumentInputValid } from '@workbench/canvas-operations/samGraph';import type { SelectObjectPreparedSource, SelectObjectReadyResult } from './layerImageResult';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.test.tsnew file mode 100644index 0000000000..6f9778f95f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.test.ts@@ -0,0 +1,59 @@+import type { CanvasEngine } from '@workbench/canvas-engine/api';++import { beforeEach, describe, expect, it, vi } from 'vitest';++const registry = vi.hoisted(() => ({+ acquire: vi.fn(),+ release: vi.fn(),+}));++vi.mock('./engineRegistry', () => ({+ getOrCreateEngine: registry.acquire,+ releaseEngine: registry.release,+}));++import { createCanvasEngineResource } from './useCanvasEngine';++describe('Canvas engine React resource', () => {+ beforeEach(() => {+ registry.acquire.mockReset();+ registry.release.mockReset();+ });++ it('acquires only while subscribed and balances one lease across subscribers', () => {+ const engine = { projectId: 'project-a' } as CanvasEngine;+ registry.acquire.mockReturnValue(engine);+ const resource = createCanvasEngineResource('project-a', {} as never);+ const firstListener = vi.fn();+ const secondListener = vi.fn();++ expect(resource.getSnapshot()).toBeNull();+ expect(registry.acquire).not.toHaveBeenCalled();++ const unsubscribeFirst = resource.subscribe(firstListener);+ expect(resource.getSnapshot()).toBe(engine);+ expect(registry.acquire).toHaveBeenCalledOnce();+ expect(firstListener).toHaveBeenCalledOnce();++ const unsubscribeSecond = resource.subscribe(secondListener);+ expect(registry.acquire).toHaveBeenCalledOnce();+ unsubscribeFirst();+ expect(registry.release).not.toHaveBeenCalled();++ unsubscribeSecond();+ expect(resource.getSnapshot()).toBeNull();+ expect(registry.release).toHaveBeenCalledWith('project-a');+ });++ it('reacquires after the last subscriber releases the resource', () => {+ const engine = { projectId: 'project-a' } as CanvasEngine;+ registry.acquire.mockReturnValue(engine);+ const resource = createCanvasEngineResource('project-a', {} as never);++ resource.subscribe(() => undefined)();+ resource.subscribe(() => undefined)();++ expect(registry.acquire).toHaveBeenCalledTimes(2);+ expect(registry.release).toHaveBeenCalledTimes(2);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.tsnew file mode 100644index 0000000000..6981fa6a07--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts@@ -0,0 +1,77 @@+import type { CanvasEngine, ImageResolver } from '@workbench/canvas-engine/api';++import { galleryImageUrls } from '@features/gallery/utility';+import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';+import { getSelectedModelBase } from '@workbench/widgets/layers/selectedModel';+import { useActiveProjectId, useWorkbenchCommands, useWorkbenchInternalStore } from '@workbench/WorkbenchContext';+import { useMemo, useSyncExternalStore } from 'react';++import type { EngineDeps } from './engineRegistry';++import { getOrCreateEngine, releaseEngine } from './engineRegistry';++export type CanvasEngineHandle = CanvasEngine;++export interface CanvasEngineResource {+ getSnapshot(): CanvasEngine | null;+ subscribe(listener: () => void): () => void;+}++/** Fetches a persisted image asset to a Blob for the engine rasterizers. */+const createImageResolver = (): ImageResolver => async (imageName, signal) => {+ const response = await fetch(galleryImageUrls.full(imageName), { signal });+ if (!response.ok) {+ throw new Error(`Failed to load canvas image "${imageName}" (${response.status})`);+ }+ return response.blob();+};++/**+ * Turns one registry lease into a React external store. The first subscriber+ * acquires the engine and the last subscriber releases it, so speculative+ * renders never create engines and StrictMode subscriptions remain balanced.+ */+export const createCanvasEngineResource = (projectId: string, deps: EngineDeps): CanvasEngineResource => {+ let engine: CanvasEngine | null = null;+ const listeners = new Set<() => void>();++ return {+ getSnapshot: () => engine,+ subscribe: (listener) => {+ listeners.add(listener);+ if (listeners.size === 1) {+ engine = getOrCreateEngine(projectId, deps);+ listener();+ }+ return () => {+ listeners.delete(listener);+ if (listeners.size === 0 && engine) {+ engine = null;+ releaseEngine(projectId);+ }+ };+ },+ };+};++/** Returns the active project's shared engine through a balanced registry lease. */+export const useCanvasEngine = (): CanvasEngineHandle | null => {+ const store = useWorkbenchInternalStore();+ const { notifications } = useWorkbenchCommands();+ const projectId = useActiveProjectId();+ const resource = useMemo(+ () =>+ createCanvasEngineResource(projectId, {+ getMainModelBase: () => {+ const project = store.getState().projects.find((candidate) => candidate.id === projectId);+ return project ? getSelectedModelBase(project) : null;+ },+ imageResolver: createImageResolver(),+ mutationPort: createCanvasProjectMutationPort(store, projectId),+ reportError: notifications.reportError,+ }),+ [notifications.reportError, projectId, store]+ );++ return useSyncExternalStore(resource.subscribe, resource.getSnapshot, resource.getSnapshot);+};diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.tsindex 6f1fbb871a..4878a7e853 100644--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts@@ -1,9 +1,9 @@+import type { MainModelConfig } from '@features/generation/contracts';+import type { WorkbenchState } from '@workbench/projectContracts';+import { describe, expect, it } from 'vitest';import type { CanvasProjectMutation } from './canvasProjectMutations';-import type { MainModelConfig } from './generation/types';-import type { WorkbenchState } from './types';-import type { WorkbenchAction } from './workbenchState';import { type CanvasDimsSnapshot, createCanvasDimsSync, reconcileCanvasDims } from './canvasDimsSync';import { getProjectWidgetValues } from './widgetState';@@ -12,7 +12,7 @@ import { createWorkbenchStore } from './workbenchStore';const bbox = (width: number, height: number, x = 0, y = 0) => ({ height, width, x, y });const dispatchCanvas = (store: ReturnType<typeof createWorkbenchStore>, mutation: CanvasProjectMutation): void => {- store.dispatch({ mutation, projectId: store.getState().activeProjectId, type: 'applyCanvasProjectMutation' });+ store.commands.canvas.apply(store.getState().activeProjectId, mutation);};const snapshot = (bboxW: number, bboxH: number, dimsW: number, dimsH: number): CanvasDimsSnapshot => ({@@ -209,17 +209,26 @@ const setupCanvasStore = () => {const store = createWorkbenchStore();// Put the active project into canvas mode with concrete generate dims/model.- store.dispatch({ type: 'setInvocationSource', sourceId: 'canvas' });- store.dispatch({- type: 'patchGenerateSettings',- values: { height: 1024, model, modelKey: model.key, width: 1024 },- });+ store.commands.generation.setSource('canvas');+ store.commands.generation.patchSettings({ height: 1024, model, modelKey: model.key, width: 1024 });let syncDispatches = 0;const countingStore = {- dispatch: (action: WorkbenchAction) => {- syncDispatches += 1;- store.dispatch(action);+ commands: {+ canvas: {+ apply: (...args: Parameters<typeof store.commands.canvas.apply>) => {+ syncDispatches += 1;+ return store.commands.canvas.apply(...args);+ },+ appendStagingCandidate: store.commands.canvas.appendStagingCandidate,+ },+ generation: {+ ...store.commands.generation,+ patchSettings: (...args: Parameters<typeof store.commands.generation.patchSettings>) => {+ syncDispatches += 1;+ store.commands.generation.patchSettings(...args);+ },+ },},getState: store.getState,subscribe: store.subscribe,@@ -289,7 +298,7 @@ describe('createCanvasDimsSync (wiring)', () => {dispatchCanvas(store, { bbox: { height: 1024, width: 1024, x: 32, y: 48 }, type: 'setCanvasBbox' });const before = getSyncDispatches();- store.dispatch({ type: 'patchGenerateSettings', values: { width: 512 } });+ store.commands.generation.patchSettings({ width: 512 });const { bbox: nextBbox } = getActiveGenerate(store.getState());expect(nextBbox).toEqual({ height: 1024, width: 512, x: 32, y: 48 });@@ -309,7 +318,7 @@ describe('createCanvasDimsSync (wiring)', () => {// another round of reconciliation (the snapped bbox and the still-501-wide// dims disagree by construction, but the sync's re-entrancy guard must// still hold the total dispatch count for this one external change to 1).- store.dispatch({ type: 'patchGenerateSettings', values: { width: 501 } });+ store.commands.generation.patchSettings({ width: 501 });const { bbox: nextBbox } = getActiveGenerate(store.getState());expect(nextBbox.width).toBe(504); // snapped up to the nearest multiple of 8@@ -331,17 +340,26 @@ describe('createCanvasDimsSync (wiring)', () => {it('stays inert when the project is not invoking into the canvas', () => {const store = createWorkbenchStore();- store.dispatch({ type: 'setInvocationSource', sourceId: 'generate' });- store.dispatch({- type: 'patchGenerateSettings',- values: { height: 1024, model, modelKey: model.key, width: 1024 },- });+ store.commands.generation.setSource('generate');+ store.commands.generation.patchSettings({ height: 1024, model, modelKey: model.key, width: 1024 });let syncDispatches = 0;const countingStore = {- dispatch: (action: WorkbenchAction) => {- syncDispatches += 1;- store.dispatch(action);+ commands: {+ canvas: {+ apply: (...args: Parameters<typeof store.commands.canvas.apply>) => {+ syncDispatches += 1;+ return store.commands.canvas.apply(...args);+ },+ appendStagingCandidate: store.commands.canvas.appendStagingCandidate,+ },+ generation: {+ ...store.commands.generation,+ patchSettings: (...args: Parameters<typeof store.commands.generation.patchSettings>) => {+ syncDispatches += 1;+ store.commands.generation.patchSettings(...args);+ },+ },},getState: store.getState,subscribe: store.subscribe,@@ -361,15 +379,12 @@ describe('createCanvasDimsSync (wiring)', () => {it('aligns dims to the bbox when a project enters canvas mode', () => {const store = createWorkbenchStore();// Diverge the frame from the dims while still in generate mode.- store.dispatch({- type: 'patchGenerateSettings',- values: { height: 1024, model, modelKey: model.key, width: 1024 },- });+ store.commands.generation.patchSettings({ height: 1024, model, modelKey: model.key, width: 1024 });dispatchCanvas(store, { bbox: { height: 640, width: 896, x: 0, y: 0 }, type: 'setCanvasBbox' });const sync = createCanvasDimsSync(store);// Switching into canvas mode should let the bbox win and drive the dims.- store.dispatch({ type: 'setInvocationSource', sourceId: 'canvas' });+ store.commands.generation.setSource('canvas');const { values } = getActiveGenerate(store.getState());expect(values.width).toBe(896);diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.tsindex 3841e93ded..3f30b098dc 100644--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts@@ -26,11 +26,14 @@* does today. Zero React.*/-import type { AspectRatioId } from './generation/types';-import type { CanvasDocumentContractV2, WorkbenchState } from './types';-import type { WorkbenchAction } from './workbenchState';+import type { AspectRatioId } from '@features/generation/contracts';+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/api';+import type { WorkbenchState } from '@workbench/projectContracts';++import { deriveAspectRatioId } from '@features/generation/settings';++import type { WorkbenchCommands } from './workbenchStore';-import { deriveAspectRatioId } from './generation/settings';import { gridSizeForModelBase } from './widgets/canvas/bboxGrid';import { getProjectWidgetValues } from './widgetState';@@ -128,9 +131,9 @@ export const reconcileCanvasDims = ({/** The minimal workbench store surface the sync depends on. */export interface CanvasDimsSyncStore {+ commands: Pick<WorkbenchCommands, 'canvas' | 'generation'>;getState(): WorkbenchState;subscribe(listener: () => void): () => void;- dispatch(action: WorkbenchAction): void;}export interface CanvasDimsSync {@@ -215,16 +218,15 @@ export const createCanvasDimsSync = (store: CanvasDimsSyncStore): CanvasDimsSync};isSyncing = true;try {- store.dispatch({- projectId: project.id,- type: 'patchGenerateSettings',- values: {+ store.commands.generation.patchSettings(+ {aspectRatioId: result.aspectRatioId,aspectRatioValue: result.aspectRatioValue,height: result.height,width: result.width,},- });+ project.id+ );} finally {isSyncing = false;}@@ -239,11 +241,7 @@ export const createCanvasDimsSync = (store: CanvasDimsSyncStore): CanvasDimsSync};isSyncing = true;try {- store.dispatch({- mutation: { bbox: result.bbox, type: 'setCanvasBbox' },- projectId: project.id,- type: 'applyCanvasProjectMutation',- });+ store.commands.canvas.apply(project.id, { bbox: result.bbox, type: 'setCanvasBbox' });} finally {isSyncing = false;}diff --git a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.test.ts b/invokeai/frontend/webv2/src/workbench/canvasLayerOps.test.tsindex 3f3f69da9e..fdc5d27690 100644--- a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasLayerOps.test.ts@@ -1,6 +1,6 @@-import { describe, expect, it } from 'vitest';+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';-import type { CanvasLayerContract } from './types';+import { describe, expect, it } from 'vitest';import {deleteLayerActions,diff --git a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.ts b/invokeai/frontend/webv2/src/workbench/canvasLayerOps.tsindex 8306ec8bc0..5f71c04aad 100644--- a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasLayerOps.ts@@ -10,8 +10,9 @@* Zero React, zero import-time side effects.*/+import type { CanvasLayerContract } from '@workbench/canvas-engine/api';+import type { CanvasProjectMutation } from './canvasProjectMutations';-import type { CanvasLayerContract } from './types';/** A forward/inverse reducer-action pair for one reversible structural edit. */export interface StructuralActions {diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.tsindex a55332cf37..69cf6a378a 100644--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts@@ -1,19 +1,3 @@-import { z } from 'zod';--/**- * Canvas v1 -> v2 document migration.- *- * `CanvasStateContract` (v1) only ever produced a flat stack of single-image- * raster layers positioned by an absolute `placement` rect. `CanvasStateContractV2`- * (see `types.ts`) generalizes the document into a typed layer union (raster,- * control, regional guidance, inpaint mask) positioned by a `transform`, with- * bitmaps referenced by `imageName` rather than by resolved URL.- *- * `migrateCanvasStateToV2` accepts genuinely unknown input (as read from- * localStorage) so it doubles as both the v1->v2 converter and the- * garbage/undefined-input fallback used when normalizing a loaded project.- * Already-v2 input passes through normalized, not double-migrated.- */import type {CanvasDocumentContractV2,CanvasImageRef,@@ -22,7 +6,9 @@ import type {CanvasRasterLayerContractV2,CanvasStagingAreaContractV2,CanvasStateContractV2,-} from './types';+} from '@workbench/canvas-engine/api';++import { z } from 'zod';import { normalizeControlAdapter } from './controlAdapters';diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.tsindex dfb4887392..dc0f292545 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts@@ -1,10 +1,10 @@-import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type {CanvasInpaintMaskLayerContract,CanvasLayerContract,CanvasLayerSourceContract,CanvasRasterLayerContractV2,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import { createBitmapStore } from '@workbench/canvas-engine/document/bitmapStore';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';@@ -75,29 +75,19 @@ const getPaintSource = (const setupProjects = (originLayer: CanvasLayerContract, otherLayer: CanvasLayerContract) => {const store = createWorkbenchStore();const originProjectId = store.getState().activeProjectId;- store.dispatch({- mutation: { document: createEmptyCanvasDocumentV2(), type: 'replaceCanvasDocument' },- projectId: originProjectId,- type: 'applyCanvasProjectMutation',+ store.commands.canvas.apply(originProjectId, {+ document: createEmptyCanvasDocumentV2(),+ type: 'replaceCanvasDocument',});- store.dispatch({- mutation: { layer: originLayer, type: 'addCanvasLayer' },- projectId: originProjectId,- type: 'applyCanvasProjectMutation',- });- store.dispatch({ type: 'createProject' });+ store.commands.canvas.apply(originProjectId, { layer: originLayer, type: 'addCanvasLayer' });+ store.commands.projects.create();const otherProjectId = store.getState().activeProjectId;- store.dispatch({- mutation: { document: createEmptyCanvasDocumentV2(), type: 'replaceCanvasDocument' },- projectId: otherProjectId,- type: 'applyCanvasProjectMutation',- });- store.dispatch({- mutation: { layer: otherLayer, type: 'addCanvasLayer' },- projectId: otherProjectId,- type: 'applyCanvasProjectMutation',+ store.commands.canvas.apply(otherProjectId, {+ document: createEmptyCanvasDocumentV2(),+ type: 'replaceCanvasDocument',});- store.dispatch({ projectId: originProjectId, type: 'switchProject' });+ store.commands.canvas.apply(otherProjectId, { layer: otherLayer, type: 'addCanvasLayer' });+ store.commands.projects.switchTo(originProjectId);return { originProjectId, otherProjectId, store };};@@ -146,7 +136,7 @@ describe('project-bound bitmap persistence', () => {const upload = beginUpload(h.store, h.originProjectId, 'origin-layer');await drainUntil(() => upload.uploadImage.mock.calls.length === 1);- h.store.dispatch({ projectId: h.otherProjectId, type: 'switchProject' });+ h.store.commands.projects.switchTo(h.otherProjectId);upload.uploaded.resolve({ height: 8, imageName: 'origin-upload.png', width: 8 });await upload.flush;@@ -162,7 +152,7 @@ describe('project-bound bitmap persistence', () => {const upload = beginUpload(h.store, h.originProjectId, 'shared-layer');await drainUntil(() => upload.uploadImage.mock.calls.length === 1);- h.store.dispatch({ projectId: h.otherProjectId, type: 'switchProject' });+ h.store.commands.projects.switchTo(h.otherProjectId);upload.uploaded.resolve({ height: 8, imageName: 'origin-shared.png', width: 8 });await upload.flush;@@ -178,7 +168,7 @@ describe('project-bound bitmap persistence', () => {const upload = beginUpload(h.store, h.originProjectId, 'shared-mask', true);await drainUntil(() => upload.uploadImage.mock.calls.length === 1);- h.store.dispatch({ projectId: h.otherProjectId, type: 'switchProject' });+ h.store.commands.projects.switchTo(h.otherProjectId);upload.uploaded.resolve({ height: 8, imageName: 'origin-mask.png', width: 8 });await upload.flush;@@ -194,8 +184,8 @@ describe('project-bound bitmap persistence', () => {const upload = beginUpload(h.store, h.originProjectId, 'reacquired');await drainUntil(() => upload.uploadImage.mock.calls.length === 1);- h.store.dispatch({ projectId: h.otherProjectId, type: 'switchProject' });- h.store.dispatch({ projectId: h.originProjectId, type: 'switchProject' });+ h.store.commands.projects.switchTo(h.otherProjectId);+ h.store.commands.projects.switchTo(h.originProjectId);upload.uploaded.resolve({ height: 8, imageName: 'reacquired.png', width: 8 });await upload.flush;@@ -241,8 +231,8 @@ describe('project-bound bitmap persistence', () => {const upload = beginUpload(h.store, h.originProjectId, 'deleted-project-layer');await drainUntil(() => upload.uploadImage.mock.calls.length === 1);- h.store.dispatch({ projectId: h.otherProjectId, type: 'switchProject' });- h.store.dispatch({ projectId: h.originProjectId, type: 'closeProject' });+ h.store.commands.projects.switchTo(h.otherProjectId);+ h.store.commands.projects.close(h.originProjectId);upload.uploaded.resolve({ height: 8, imageName: 'orphaned.png', width: 8 });await upload.flush;await upload.bitmapStore.flushPendingUploads();diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.tsindex bcab928703..76575afc3a 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts@@ -1,6 +1,8 @@+import type { CanvasStateContractV2 } from '@workbench/canvas-engine/api';+import type { WorkbenchState } from '@workbench/projectContracts';+import type { CanvasProjectMutation } from './canvasProjectMutations';-import type { CanvasStateContractV2 } from './types';-import type { WorkbenchStore } from './workbenchStore';+import type { WorkbenchCanvasCommands } from './workbenchStore';export interface CanvasProjectMutationPort {getCanvasState(): CanvasStateContractV2 | null;@@ -9,21 +11,18 @@ export interface CanvasProjectMutationPort {}export const createCanvasProjectMutationPort = (- store: Pick<WorkbenchStore, 'dispatch' | 'getState' | 'subscribe'>,+ store: {+ commands: { canvas: WorkbenchCanvasCommands };+ getState: () => WorkbenchState;+ subscribe: (listener: () => void) => () => void;+ },projectId: string): CanvasProjectMutationPort => {const getCanvasState = (): CanvasStateContractV2 | null =>store.getState().projects.find((project) => project.id === projectId)?.canvas ?? null;return {- dispatch: (mutation) => {- const before = getCanvasState();- if (!before) {- return false;- }- store.dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' });- return getCanvasState() !== before;- },+ dispatch: (mutation) => store.commands.canvas.apply(projectId, mutation),getCanvasState,subscribe: store.subscribe,};diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.tsindex c8b54b290b..d111849a9d 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts@@ -9,11 +9,10 @@ import type {CanvasMaskContract,CanvasRasterLayerContractV2,CanvasRegionalGuidanceLayerContract,- ProjectEvent,CanvasStagingAreaContractV2,CanvasStateContractV2,- Project,-} from './types';+} from '@workbench/canvas-engine/api';+import type { ProjectEvent, Project } from '@workbench/projectContracts';import { normalizeCanvasDocumentControlAdapters } from './canvasMigration';import {diff --git a/invokeai/frontend/webv2/src/workbench/canvasStagingView.test.ts b/invokeai/frontend/webv2/src/workbench/canvasStagingView.test.tsindex ff75681d12..2772764c5f 100644--- a/invokeai/frontend/webv2/src/workbench/canvasStagingView.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasStagingView.test.ts@@ -1,6 +1,9 @@-import { describe, expect, it } from 'vitest';+import type { GeneratedImageContract } from '@features/gallery';+import type { QueueHistoryItemStatus } from '@features/queue/contracts';+import type { CanvasStagingCandidateContract } from '@workbench/canvas-engine/contracts';+import type { WorkbenchQueueItem as QueueItem } from '@workbench/queueHistoryContracts';-import type { CanvasStagingCandidateContract, GeneratedImageContract, QueueItem, QueueItemStatus } from './types';+import { describe, expect, it } from 'vitest';import { createEmptyCanvasStateV2 } from './canvasMigration';import {@@ -78,7 +81,7 @@ const createQueueItem = ({destination?: 'canvas' | 'gallery';id: string;revision?: number;- status?: QueueItemStatus;+ status?: QueueHistoryItemStatus;submittedAt?: string;}): QueueItem =>({@@ -88,9 +91,13 @@ const createQueueItem = ({completedBackendItemIds,id,snapshot: {+ backendSubmission: { error: 'not submitted in staging view tests', kind: 'invalid' },canvas: createCanvas({ bbox, revision }),destination,+ filterIntermediateResults: false,+ galleryBoardId: null,graph: { edges: [], id: 'graph', label: 'Graph', nodes: [], updatedAt: '2026-06-09T00:00:00.000Z', version: 1 },+ presentation: { batchCount, height: bbox.height, width: bbox.width },sourceId: 'canvas',submittedAt,widgetInstances: {},diff --git a/invokeai/frontend/webv2/src/workbench/canvasStagingView.ts b/invokeai/frontend/webv2/src/workbench/canvasStagingView.tsindex 348e368ea8..493ca70334 100644--- a/invokeai/frontend/webv2/src/workbench/canvasStagingView.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasStagingView.ts@@ -1,6 +1,7 @@-import type { CanvasStagingCandidateContract, CanvasStateContractV2, QueueItem } from './types';+import type { CanvasStagingCandidateContract, CanvasStateContractV2 } from '@workbench/canvas-engine/api';+import type { WorkbenchQueueItem as QueueItem } from '@workbench/queueHistoryContracts';-import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from './queueSnapshot';+import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from '@features/queue/contracts';export interface CanvasQueuePlaceholderSlot {height: number;diff --git a/invokeai/frontend/webv2/src/workbench/components/QueueProgressIndicator.tsx b/invokeai/frontend/webv2/src/workbench/components/QueueProgressIndicator.tsxindex 8e1278eabd..f6366875db 100644--- a/invokeai/frontend/webv2/src/workbench/components/QueueProgressIndicator.tsx+++ b/invokeai/frontend/webv2/src/workbench/components/QueueProgressIndicator.tsx@@ -1,4 +1,4 @@-import type { QueueProgressBarState } from '@workbench/queueSummary';+import type { QueueProgressBarState } from '@features/queue/contracts';import type { ComponentProps } from 'react';import { Progress, ProgressCircle } from '@chakra-ui/react';diff --git a/invokeai/frontend/webv2/src/workbench/components/WorkbenchSplashScreen.tsx b/invokeai/frontend/webv2/src/workbench/components/WorkbenchSplashScreen.tsxindex a247000b52..0f33122264 100644--- a/invokeai/frontend/webv2/src/workbench/components/WorkbenchSplashScreen.tsx+++ b/invokeai/frontend/webv2/src/workbench/components/WorkbenchSplashScreen.tsx@@ -1,10 +1,9 @@import splashImageUrl from '@assets/SplashImage.webp';import { Box, Flex, Heading, HStack, Spinner, Text, VStack } from '@chakra-ui/react';-import { InvokeMark } from '@workbench/components/InvokeMark';+import { APP_VERSION } from '@platform/runtime/appMetadata';+import { InvokeMark } from '@platform/ui/InvokeMark';import { useTranslation } from 'react-i18next';-import { APP_VERSION } from '@/appMetadata';-const splashImageStyle = { backgroundPosition: 'center', backgroundSize: 'cover' } as const;export const WorkbenchSplashScreen = ({ messageKey = 'splash.loadingWorkspace' }: { messageKey?: string }) => {diff --git a/invokeai/frontend/webv2/src/workbench/controlAdapters.ts b/invokeai/frontend/webv2/src/workbench/controlAdapters.tsindex 415c1905a5..e7e2387391 100644--- a/invokeai/frontend/webv2/src/workbench/controlAdapters.ts+++ b/invokeai/frontend/webv2/src/workbench/controlAdapters.ts@@ -1,4 +1,4 @@-import type { CanvasControlAdapterContract } from './types';+import type { CanvasControlAdapterContract } from '@workbench/canvas-engine/api';export const CONTROL_ADAPTER_DEFAULTS: Readonly<Record<CanvasControlAdapterContract['kind'], CanvasControlAdapterContract>diff --git a/invokeai/frontend/webv2/src/workbench/diagnostics/contracts.ts b/invokeai/frontend/webv2/src/workbench/diagnostics/contracts.tsnew file mode 100644index 0000000000..83aed49486--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/diagnostics/contracts.ts@@ -0,0 +1,20 @@+/**+ * Identifier for a workbench color theme. The matching palette lives in+ * `theme/themes.ts`; the active id is applied to `<html data-theme>` so the+ * semantic-token conditions in `theme/system.ts` resolve to the right colors.+ */+export type DeveloperLogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';++export type DeveloperLogNamespace =+ | 'canvas'+ | 'canvas-workflow-integration'+ | 'config'+ | 'dnd'+ | 'events'+ | 'gallery'+ | 'generation'+ | 'metadata'+ | 'models'+ | 'system'+ | 'queue'+ | 'workflows';diff --git a/invokeai/frontend/webv2/src/workbench/diagnostics/logger.ts b/invokeai/frontend/webv2/src/workbench/diagnostics/logger.tsindex e920d613c2..42b34ff02c 100644--- a/invokeai/frontend/webv2/src/workbench/diagnostics/logger.ts+++ b/invokeai/frontend/webv2/src/workbench/diagnostics/logger.ts@@ -1,4 +1,5 @@-import type { DeveloperLogLevel, DeveloperLogNamespace, WidgetContributionSource } from '@workbench/types';+import type { DeveloperLogLevel, DeveloperLogNamespace } from '@workbench/diagnostics/contracts';+import type { WidgetContributionSource } from '@workbench/widgetContracts';import { useSyncExternalStore } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.test.ts b/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.test.tsindex 5fb22c8472..342b84a1b2 100644--- a/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.test.ts+++ b/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.test.ts@@ -1,4 +1,4 @@-import type { WidgetContributionSource } from '@workbench/types';+import type { WidgetContributionSource } from '@workbench/widgetContracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.ts b/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.tsindex b454643f2a..10780cdd68 100644--- a/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.ts+++ b/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.ts@@ -1,4 +1,4 @@-import type { WidgetContributionSource } from '@workbench/types';+import type { WidgetContributionSource } from '@workbench/widgetContracts';const GLOBAL_SOURCE_KEY = 'global';diff --git a/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.ts b/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.tsindex fbc7e3e0f0..94565dbf2a 100644--- a/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.ts+++ b/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.ts@@ -12,9 +12,9 @@ import type {WidgetSearchProvider,WidgetToolbarApi,WidgetToolbarContribution,-} from '@workbench/types';+} from '@workbench/widgetContracts';-import { createCollectionStore } from '@workbench/externalStore';+import { createCollectionStore } from '@platform/state/externalStore';import { areWidgetContributionSourcesEqual, getWidgetContributionRegistrationKey } from './contributionSource';diff --git a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx b/invokeai/frontend/webv2/src/workbench/focusRegions.tsxindex 3af79a18bf..970c449c1e 100644--- a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx+++ b/invokeai/frontend/webv2/src/workbench/focusRegions.tsx@@ -1,10 +1,9 @@+import type { WidgetRegion } from '@workbench/layoutContracts';/* oxlint-disable react-perf/jsx-no-new-object-as-prop */import type { FocusEvent, PointerEvent, ReactNode } from 'react';import { createContext, use, useState } from 'react';-import type { WidgetRegion } from './types';-import { useWorkbenchPreferenceSelector } from './settings/store';let focusedRegionSnapshot: WidgetRegion | null = null;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/index.ts b/invokeai/frontend/webv2/src/workbench/galleryWidgetManifest.tssimilarity index 64%rename from invokeai/frontend/webv2/src/workbench/widgets/gallery/index.tsrename to invokeai/frontend/webv2/src/workbench/galleryWidgetManifest.tsindex da0b1c4de2..900d3135e8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/index.ts+++ b/invokeai/frontend/webv2/src/workbench/galleryWidgetManifest.ts@@ -1,20 +1,20 @@-import type { WidgetManifest } from '@workbench/types';+import type { WidgetManifest } from '@workbench/widgetContracts';import { ImageIcon } from 'lucide-react';-import { GalleryWidgetFooter } from './GalleryWidgetFooter';-import { GalleryWidgetView } from './GalleryWidgetView';-export const galleryWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['left', 'right', 'center', 'bottom'],bottomPanel: 'expandable',chrome: { header: 'hidden' },failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },- footer: GalleryWidgetFooter,icon: ImageIcon,id: 'gallery',label: (t) => t('widgets.labels.gallery'),+ load: () =>+ import('@features/gallery/widget').then((module) => ({+ footer: module.GalleryWidgetFooter,+ view: module.GalleryWidgetView,+ })),version: 1,- view: GalleryWidgetView,};diff --git a/invokeai/frontend/webv2/src/workbench/generation/api.ts b/invokeai/frontend/webv2/src/workbench/generation/api.tsdeleted file mode 100644index 1f7e1dc65e..0000000000--- a/invokeai/frontend/webv2/src/workbench/generation/api.ts+++ /dev/null@@ -1,255 +0,0 @@-import type { BackendGraphContract } from '@workbench/types';--import { buildQueueItemOrigin } from '@workbench/backend/events';-import { absolutizeApiUrl, ApiError, apiFetchJson } from '@workbench/backend/http';--import type {- EnqueueGenerateRequest,- EnqueueGenerateResult,- EnqueueWorkflowRequest,- ImageDTO,- MainModelConfig,- QueueItemDTO,-} from './types';--import { sanitizeBatchCount } from './batch';-import { generateSeedSequence } from './graph';--export const listMainModels = async (): Promise<MainModelConfig[]> => {- const body = await apiFetchJson<{ models?: MainModelConfig[] }>('/api/v2/models/?model_type=main');-- return body.models ?? [];-};--export const enqueueGenerateGraph = async (request: EnqueueGenerateRequest): Promise<EnqueueGenerateResult> => {- const batchCount = sanitizeBatchCount(request.batchCount);- const seeds = request.shouldRandomizeSeed ? generateSeedSequence(request.seed, batchCount) : [request.seed];- const prompts = request.shouldRandomizeSeed ? seeds.map(() => request.positivePrompt) : [request.positivePrompt];- const negativePrompts = request.shouldRandomizeSeed- ? seeds.map(() => request.negativePrompt)- : [request.negativePrompt];- const body = {- batch: {- data: [- [- { field_name: 'value', items: seeds, node_path: request.seedNodeId },- { field_name: 'value', items: prompts, node_path: request.positivePromptNodeId },- { field_name: 'value', items: negativePrompts, node_path: request.negativePromptNodeId },- ],- ],- destination: request.destination,- graph: request.graph satisfies BackendGraphContract,- origin: buildQueueItemOrigin(request.sourceQueueItemId, request.projectId),- runs: request.shouldRandomizeSeed ? 1 : batchCount,- },- prepend: false,- };- const result = await apiFetchJson<{- batch?: { batch_id?: string };- enqueued?: number;- item_ids?: number[];- requested?: number;- }>('/api/v1/queue/default/enqueue_batch', { body: JSON.stringify(body), method: 'POST' });-- return {- batchId: result.batch?.batch_id,- enqueued: result.enqueued ?? 0,- itemIds: result.item_ids ?? [],- requested: result.requested ?? 0,- };-};--/** Enqueue an arbitrary compiled graph — the workflow path. */-export const enqueueWorkflowGraph = async (request: EnqueueWorkflowRequest): Promise<EnqueueGenerateResult> => {- const batchCount = sanitizeBatchCount(request.batchCount);- const body = {- batch: {- destination: request.destination,- graph: request.graph satisfies BackendGraphContract,- origin: buildQueueItemOrigin(request.sourceQueueItemId, request.projectId),- runs: batchCount,- },- prepend: false,- };- const result = await apiFetchJson<{- batch?: { batch_id?: string };- enqueued?: number;- item_ids?: number[];- requested?: number;- }>('/api/v1/queue/default/enqueue_batch', { body: JSON.stringify(body), method: 'POST' });-- return {- batchId: result.batch?.batch_id,- enqueued: result.enqueued ?? 0,- itemIds: result.item_ids ?? [],- requested: result.requested ?? 0,- };-};--/**- * Enqueues a small graph OUTSIDE any project's queue, tagged with a caller-built- * utility origin (`webv2:util:<id>`). Used by {@link import('@workbench/canvas-operations/backend/utilityQueue').runUtilityGraph}- * for filter previews / SAM: the origin is intentionally opaque to project- * routing (see `events.ts`), so results are never staged or added to the gallery.- * A single deterministic run (no seed/prompt batch data).- */-export const enqueueUtilityGraph = async (request: {- graph: BackendGraphContract;- origin: string;-}): Promise<{ itemIds: number[]; enqueued: number }> => {- const body = {- batch: {- graph: request.graph satisfies BackendGraphContract,- origin: request.origin,- runs: 1,- },- prepend: false,- };- const result = await apiFetchJson<{ enqueued?: number; item_ids?: number[] }>('/api/v1/queue/default/enqueue_batch', {- body: JSON.stringify(body),- method: 'POST',- });-- return { enqueued: result.enqueued ?? 0, itemIds: result.item_ids ?? [] };-};--export const getQueueItem = (itemId: number): Promise<QueueItemDTO> =>- apiFetchJson<QueueItemDTO>(`/api/v1/queue/default/i/${itemId}`);--export const listAllQueueItems = (): Promise<QueueItemDTO[]> =>- apiFetchJson<QueueItemDTO[]>('/api/v1/queue/default/list_all');--export interface QueueItemResultImageOptions {- /** Source graph node ids whose prepared execution results should be read. */- resultNodeIds?: readonly string[];-}--const getImageDTO = async (- imageName: string,- queuedAt: string,- sourceQueueItemId: string-): Promise<ImageDTO | null> => {- try {- const body = await apiFetchJson<{- image_name: string;- image_url: string;- thumbnail_url: string;- width: number;- height: number;- is_intermediate: boolean;- }>(`/api/v1/images/i/${encodeURIComponent(imageName)}`);-- return {- height: body.height,- imageName: body.image_name,- imageUrl: absolutizeApiUrl(body.image_url),- isIntermediate: body.is_intermediate,- queuedAt,- sourceQueueItemId,- thumbnailUrl: absolutizeApiUrl(body.thumbnail_url),- width: body.width,- };- } catch (error) {- if (error instanceof ApiError && error.status === 404) {- return null;- }-- throw error;- }-};--const getResultImageNames = (queueItem: QueueItemDTO, options?: QueueItemResultImageOptions): string[] => {- const imageNames = new Set<string>();- const results = queueItem.session?.results ?? {};- const preparedSourceMapping = queueItem.session?.prepared_source_mapping ?? {};- const resultNodeIds = options?.resultNodeIds;- const resultValues = resultNodeIds- ? Object.entries(results)- // Backend result keys are prepared execution ids; source ids carry the graph contract.- .filter(([nodeId]) => resultNodeIds.includes(preparedSourceMapping[nodeId] ?? nodeId))- .map(([, result]) => result)- : Object.values(results);-- for (const result of resultValues) {- if (!result || typeof result !== 'object') {- continue;- }-- const image = (result as { image?: { image_name?: unknown } }).image;- if (typeof image?.image_name === 'string') {- imageNames.add(image.image_name);- }-- const collection = (result as { collection?: unknown }).collection;- if (Array.isArray(collection)) {- for (const item of collection) {- if (!item || typeof item !== 'object') {- continue;- }-- const imageName = (item as { image_name?: unknown }).image_name;- if (typeof imageName === 'string') {- imageNames.add(imageName);- }- }- }- }-- return [...imageNames];-};--/** Fetch the result image DTOs of a completed queue item. */-export const getQueueItemResultImages = async (- itemId: number,- sourceQueueItemId: string,- queuedAt: string,- options?: QueueItemResultImageOptions-): Promise<ImageDTO[]> => {- const queueItem = await getQueueItem(itemId);-- const images = await Promise.all(- getResultImageNames(queueItem, options).map((imageName) => getImageDTO(imageName, queuedAt, sourceQueueItemId))- );-- return images.filter((image): image is ImageDTO => image !== null);-};--export const cancelQueueItemsByBatchIds = async (batchIds: string[]): Promise<void> => {- if (batchIds.length === 0) {- return;- }-- await apiFetchJson('/api/v1/queue/default/cancel_by_batch_ids', {- body: JSON.stringify({ batch_ids: batchIds }),- method: 'PUT',- });-};--export const getCurrentQueueItem = (): Promise<QueueItemDTO | null> =>- apiFetchJson<QueueItemDTO | null>('/api/v1/queue/default/current');--export const cancelQueueItem = (itemId: number): Promise<QueueItemDTO> =>- apiFetchJson<QueueItemDTO>(`/api/v1/queue/default/i/${itemId}/cancel`, { method: 'PUT' });--export const cancelQueueItems = async (itemIds: number[]): Promise<void> => {- await Promise.all(itemIds.map(cancelQueueItem));-};--export const cancelCurrentQueueItem = async (): Promise<QueueItemDTO | null> => {- const currentQueueItem = await getCurrentQueueItem();-- if (!currentQueueItem) {- return null;- }-- return cancelQueueItem(currentQueueItem.item_id);-};--export const cancelAllExceptCurrentQueueItems = (): Promise<unknown> =>- apiFetchJson('/api/v1/queue/default/cancel_all_except_current', { method: 'PUT' });--export const resumeQueueProcessor = (): Promise<unknown> =>- apiFetchJson('/api/v1/queue/default/processor/resume', { method: 'PUT' });--export const pauseQueueProcessor = (): Promise<unknown> =>- apiFetchJson('/api/v1/queue/default/processor/pause', { method: 'PUT' });diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/types.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/types.tsdeleted file mode 100644index 4bc15cb9ca..0000000000--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/types.ts+++ /dev/null@@ -1,163 +0,0 @@-/**- * Shared vocabulary for the canvas → generation-graph pipeline.- *- * This module is pure data: it names the generation mode a canvas invoke maps- * to and the shape of a *composite plan* — a pixel-free description of what the- * executor must composite and upload before a graph can be built. It has no- * runtime dependency on the canvas engine (shared engine vocabulary is imported- * type-only), so the planner (`compositePlan.ts`) and mode detector- * (`canvasMode.ts`) stay pure, node-testable, data-in/data-out functions.- *- * The plan is deliberately open-ended: Phase 4.2 only emits the single- * `base-raster` composite, but later phases add `control-layer`,- * `regional-mask`, and `inpaint-mask` composites to the same {@link CompositePlan}- * structure — each a {@link CompositeEntry} with its own stable identity key.- */--import type {- CompositeEntry as RasterCompositeEntry,- CompositeLayerRef,-} from '@workbench/canvas-engine/render/rasterComposite';-import type { Rect } from '@workbench/canvas-engine/types';-import type { GenerateModelConfig, GenerateSettings } from '@workbench/generation/types';-import type { BackendGraphContract, GraphContract, ProjectSettings, ResultDestination } from '@workbench/types';-import type { CanvasCompositingSettings } from '@workbench/widgets/canvas/invoke/canvasCompositing';--import type { ControlLayerGraphInput } from './addControlLayers';-import type { RegionalGuidanceInput } from './addRegionalGuidance';--export type { CompositeLayerRef, Rect };--/** The legacy-parity generation modes a canvas invoke resolves to. */-export type CanvasGenerationMode = 'txt2img' | 'img2img' | 'inpaint' | 'outpaint';--/**- * Legacy default resolution for undefined mask attributes (`addInpaint.ts`):- * a fresh mask with `denoiseLimit === undefined` denoises fully (1.0), and a- * fresh mask with `noiseLevel === undefined` is EXCLUDED from the noise- * composite entirely (no `img_noise`) — it must not be treated as noise 0.- */-export const DEFAULT_MASK_DENOISE_LIMIT = 1;--/** The kind of composite an entry describes. */-export type CompositeEntryKind = 'base-raster' | 'inpaint-mask' | 'noise-mask' | 'control-layer' | 'regional-mask';--/**- * A mask layer's contribution to a grayscale mask composite. The executor draws- * each mask's alpha and colors it by `attributeValue` (white = keep, darker =- * inpaint), darken-compositing multiple masks over a white background, exactly- * like the legacy `getGrayscaleMaskCompositeImageDTO`.- */-export interface CompositeMaskLayerRef extends Pick<- CompositeLayerRef,- 'id' | 'sourceRef' | 'contentSize' | 'contentOffset' | 'transform'-> {- /**- * The per-layer attribute value in [0, 1] driving the grayscale gray value- * (`255 - round(255 * attributeValue)` for masked pixels). For the- * `inpaint-mask` (denoise-limit) entry, an undefined `denoiseLimit` resolves- * to {@link DEFAULT_MASK_DENOISE_LIMIT}; for the `noise-mask` entry it is the- * layer's `noiseLevel` (only layers with a defined `noiseLevel` appear).- */- attributeValue: number;-}--/**- * One composite the executor must produce: a set of layers composited over a- * bbox into a single uploadable image. `key` is a content-identity hash of- * everything that determines the entry's pixels (see {@link CompositePlan}).- */-export interface CompositeEntry extends RasterCompositeEntry {- kind: CompositeEntryKind;- /**- * Stable identity key: same document + bbox → same key, so the executor can- * skip recompositing / re-uploading when nothing that affects these pixels- * changed between invokes.- */- key: string;- /** Contributing mask layers, for grayscale mask entries (`inpaint-mask` / `noise-mask`). */- maskLayers?: CompositeMaskLayerRef[];- /**- * The single document layer id a `control-layer` entry composites (each- * enabled control layer is composited SEPARATELY, never blended together).- */- layerId?: string;-}--/**- * A pixel-free description of everything an invoke must composite/upload. Phase- * 4.2 emits exactly one `base-raster` entry; later phases append more.- */-export interface CompositePlan {- /** The bbox (document space) the plan is scoped to. */- bbox: Rect;- entries: CompositeEntry[];-}--/** The generation modes the pure canvas graph compiler supports (full matrix). */-export type CanvasCompileMode = CanvasGenerationMode;--/**- * Everything {@link import('./compileCanvasGraph').compileCanvasGraph} needs to- * build a canvas generation graph. Pure data: the executor (Task 16) supplies- * the already-uploaded `compositeImageName`; no pixels or engine state leak in.- */-export interface CompileCanvasGraphInput {- /** Prompts / steps / model-adjacent settings, reused verbatim from Generate. */- settings: GenerateSettings;- model: GenerateModelConfig;- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>;- /** The resolved canvas mode (from `canvasMode.ts`). */- mode: CanvasCompileMode;- /**- * The resolved result destination. `canvas` marks the output node intermediate- * (staging); `gallery` makes it a durable image, matching `compileGenerateGraph`.- */- destination: ResultDestination;- /** The generation bounding box, in document space. Its size overrides settings dims. */- bbox: Rect;- /** The uploaded bbox composite (executor result). Required for image-referencing modes. */- compositeImageName: string | null;- /**- * The uploaded grayscale denoise-limit mask (white = keep, dark = inpaint).- * Required for `inpaint` / `outpaint`.- */- maskImageName?: string | null;- /**- * The uploaded grayscale noise mask, present only when at least one enabled- * mask layer defines a `noiseLevel`. Adds an `img_noise` node before encode.- */- noiseMaskImageName?: string | null;- /** Denoising strength in (0, 1]. Consulted for `img2img` / `inpaint` / `outpaint`. */- strength: number;- /** Infill / coherence / mask-blur knobs. Defaults applied by the reader. */- compositing?: CanvasCompositingSettings;- /**- * Valid, already-resolved control layers (each with its own uploaded composite- * image name). The executor filters + composites these; the compiler only- * grafts adapter nodes. Present in every mode (control works with all).- */- controlLayers?: readonly ControlLayerGraphInput[];- /**- * Valid, already-resolved regional-guidance regions (each with its own uploaded- * mask image name + resolved reference-image models). The executor filters +- * composites these; the compiler only grafts the mask-tensor + conditioning- * nodes into the base graph's `pos_cond_collect` / `neg_cond_collect`. Applied- * only for supported bases (sd-1 / sdxl / flux).- */- regionalGuidance?: readonly RegionalGuidanceInput[];-}--/**- * Mirrors {@link import('../types').CompiledGenerateGraph} with the resolved- * canvas mode attached so downstream (Task 18) can label / branch without- * re-deriving it.- */-export interface CompiledCanvasGraph {- backendGraph: BackendGraphContract;- graph: GraphContract;- negativePromptNodeId: string;- positivePromptNodeId: string;- seedNodeId: string;- mode: CanvasCompileMode;-}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/index.ts b/invokeai/frontend/webv2/src/workbench/generationWidgetManifest.tssimilarity index 72%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/index.tsrename to invokeai/frontend/webv2/src/workbench/generationWidgetManifest.tsindex 6d1b097965..25547c892b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/index.ts+++ b/invokeai/frontend/webv2/src/workbench/generationWidgetManifest.ts@@ -1,9 +1,7 @@-import type { WidgetManifest } from '@workbench/types';+import type { WidgetManifest } from '@workbench/widgetContracts';import { SlidersHorizontalIcon } from 'lucide-react';-import { GenerateWidgetView } from './GenerateWidgetView';-export const generateWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['left'],@@ -12,6 +10,6 @@ export const generateWidgetManifest: WidgetManifest = {icon: SlidersHorizontalIcon,id: 'generate',label: (t) => t('widgets.labels.generate'),+ load: () => import('@features/generation/widget').then((module) => ({ view: module.GenerateWidgetView })),version: 1,- view: GenerateWidgetView,};diff --git a/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewDialog.tsx b/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewDialog.tsxdeleted file mode 100644index 20f65aa22c..0000000000--- a/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewDialog.tsx+++ /dev/null@@ -1,206 +0,0 @@-import type { ModelConfig } from '@workbench/models/types';-import type { GraphContract, GraphId, InvocationSourceId, Project } from '@workbench/types';-import type { WorkbenchAction } from '@workbench/workbenchState';-import type { XYPosition } from '@workbench/workflows/types';--import { Box, Dialog, Portal, SegmentGroup, Text } from '@chakra-ui/react';-import { Button, JsonPreview } from '@workbench/components/ui';-import {- createInvocationRouteInputSelector,- formatRoute,- isInvocationRouteValid,- resolveInvocationRoute,- resolveInvocationRouteInput,-} from '@workbench/invocation';-import { submitResolvedInvocation } from '@workbench/invocationSubmit';-import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';-import { prepareCanvasInvocation } from '@workbench/widgets/canvas/invoke/prepareCanvasInvocation';-import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';-import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchStore } from '@workbench/WorkbenchContext';-import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';-import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';-import { useTranslation } from 'react-i18next';--import { GraphPreviewFlow } from './GraphPreviewFlow';--export interface GraphPreviewInvokeDeps {- dispatch: (action: WorkbenchAction) => void;- models: readonly ModelConfig[] | undefined;- prepareCanvasInvocation: typeof prepareCanvasInvocation;- project: Project;- sourceId: InvocationSourceId | undefined;-}--/**- * Resolves the dialog-locked invocation route for `sourceId` against the- * post-flush project and, when valid, submits it through the shared- * canvas-vs-generate submit decision (`submitResolvedInvocation`) — the same- * routing the topbar Invoke control and the Invoke hotkey use. Without this,- * a valid Canvas route would dispatch `submitResolvedInvocationSnapshot`- * directly, which silently no-ops for a canvas source. Returns whether the- * route was valid and submitted, so the dialog only closes on success.- */-export const resolveAndSubmitGraphPreviewInvocation = ({- dispatch,- models,- prepareCanvasInvocation: prepareCanvas,- project,- sourceId,-}: GraphPreviewInvokeDeps): boolean => {- if (!sourceId) {- return false;- }-- const route = resolveInvocationRoute(- project,- 'dialog',- { ...project.invocation, sourceId, sourceLocked: true },- models- );-- if (!isInvocationRouteValid(route)) {- return false;- }-- submitResolvedInvocation({ dispatch, models, prepareCanvasInvocation: prepareCanvas, project, route });- return true;-};--interface GraphPreviewDialogProps {- graph: GraphContract | null;- graphId: GraphId;- isOpen: boolean;- /** Editor positions keyed by node id, when the graph mirrors an editable document. */- positionHints?: Record<string, XYPosition>;- sourceId?: InvocationSourceId;- title: string;- onOpenChange: (isOpen: boolean) => void;-}--type PreviewMode = 'nodes' | 'json';--const selectInvocationRouteInput = createInvocationRouteInputSelector();-const modeItems = [- { labelKey: 'graphPreview.nodes', value: 'nodes' },- { labelKey: 'common.json', value: 'json' },-];--const PreviewPane = ({ children }: { children: ReactNode }) => (- <Box flex="1" h="full" minH="0" minW="0" w="full" rounded="md" borderWidth={1} overflow="hidden">- {children}- </Box>-);--export const GraphPreviewDialog = ({- graph,- graphId,- isOpen,- positionHints,- sourceId,- title,- onOpenChange,-}: GraphPreviewDialogProps) => {- const { t } = useTranslation();- const routeInput = useActiveProjectSelector(selectInvocationRouteInput);- const dispatch = useWorkbenchDispatch();- const store = useWorkbenchStore();- const models = useModelsSelector((snapshot) => snapshot.models);- const modelsStatus = useModelsSelector((snapshot) => snapshot.status);- const availabilityModels = modelsStatus === 'loaded' ? models : undefined;- const [mode, setMode] = useState<PreviewMode>('nodes');-- useInvocationTemplatesSelector((snapshot) => snapshot.status);-- const dialogRoute = sourceId- ? resolveInvocationRouteInput(- routeInput,- 'dialog',- { ...routeInput.invocation, sourceId, sourceLocked: true },- availabilityModels- )- : null;- const canInvoke = dialogRoute ? isInvocationRouteValid(dialogRoute) : false;-- useEffect(() => {- ensureModelsLoaded();- }, []);-- const handleOpenChange = useCallback((event: { open: boolean }) => onOpenChange(event.open), [onOpenChange]);- const handleModeChange = useCallback(- (event: { value: string | null }) => setMode(event.value === 'json' ? 'json' : 'nodes'),- []- );- const closeDialog = useCallback(() => onOpenChange(false), [onOpenChange]);- const invokeRoute = useCallback(() => {- flushGenerateDrafts();- const postFlushProject = store.getSnapshot().activeProject;- const submitted = resolveAndSubmitGraphPreviewInvocation({- dispatch,- models: availabilityModels,- prepareCanvasInvocation,- project: postFlushProject,- sourceId,- });-- if (submitted) {- onOpenChange(false);- }- }, [availabilityModels, dispatch, onOpenChange, sourceId, store]);- const jsonLabel = useMemo(() => t('graphPreview.graphJsonLabel', { title }), [t, title]);-- return (- <Dialog.Root open={isOpen} size="xl" onOpenChange={handleOpenChange}>- <Portal>- <Dialog.Backdrop />- <Dialog.Positioner>- <Dialog.Content h="62vh" maxH="62vh">- <Dialog.Header alignItems="center" flexDirection="row" justifyContent="space-between">- <Dialog.Title>{t('graphPreview.title', { title })}</Dialog.Title>- <SegmentGroup.Root size="xs" value={mode} onValueChange={handleModeChange}>- <SegmentGroup.Indicator />- {modeItems.map((item) => (- <SegmentGroup.Item key={item.value} value={item.value}>- <SegmentGroup.ItemHiddenInput />- <SegmentGroup.ItemText>{t(item.labelKey)}</SegmentGroup.ItemText>- </SegmentGroup.Item>- ))}- </SegmentGroup.Root>- </Dialog.Header>- <Dialog.Body display="flex" flex="1" flexDirection="column" minH="0">- {!graph ? (- <Text color="fg.muted" fontSize="sm">- {t('graphPreview.noCompiledGraph', { graphId })}- </Text>- ) : mode === 'nodes' ? (- <PreviewPane>- <GraphPreviewFlow graph={graph} positionHints={positionHints} />- </PreviewPane>- ) : (- <PreviewPane>- <JsonPreview h="full" label={jsonLabel} maxH="100%" value={graph} />- </PreviewPane>- )}- </Dialog.Body>- <Dialog.Footer>- {dialogRoute ? (- <Button- aria-disabled={!canInvoke}- cursor={canInvoke ? undefined : 'not-allowed'}- opacity={canInvoke ? undefined : 0.6}- size="sm"- title={dialogRoute.validationMessage}- onClick={invokeRoute}- >- {t('graphPreview.invokeRoute', { route: formatRoute(dialogRoute) })}- </Button>- ) : null}- <Button size="sm" variant="outline" onClick={closeDialog}>- {t('common.close')}- </Button>- </Dialog.Footer>- </Dialog.Content>- </Dialog.Positioner>- </Portal>- </Dialog.Root>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/graphContracts.ts b/invokeai/frontend/webv2/src/workbench/graphContracts.tsnew file mode 100644index 0000000000..6c03985f8a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/graphContracts.ts@@ -0,0 +1,48 @@+export type GraphId = string;++export interface GraphNodeContract {+ id: string;+ type: string;+ inputs: Record<string, unknown>;+}++export interface GraphEdgeContract {+ id: string;+ sourceNodeId: string;+ sourceField: string;+ targetNodeId: string;+ targetField: string;+}++export interface GraphContract {+ id: GraphId;+ version: 1;+ label: string;+ nodes: GraphNodeContract[];+ edges: GraphEdgeContract[];+ updatedAt: string;+ backendGraph?: BackendGraphContract;+}++export interface BackendInvocationContract {+ id: string;+ type: string;+ [key: string]: unknown;+}++export interface BackendGraphEdgeContract {+ source: {+ node_id: string;+ field: string;+ };+ destination: {+ node_id: string;+ field: string;+ };+}++export interface BackendGraphContract {+ id: string;+ nodes: Record<string, BackendInvocationContract>;+ edges: BackendGraphEdgeContract[];+}diff --git a/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewDialog.test.ts b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.tssimilarity index 77%rename from invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewDialog.test.tsrename to invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.tsindex a61cbe6eea..c8befdb04c 100644--- a/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewDialog.test.ts+++ b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts@@ -3,13 +3,14 @@ import type {MainModelConfig,VaeModelConfig,ComponentModelConfig,-} from '@workbench/generation/types';+} from '@features/generation/contracts';-import { getDefaultGenerateSettings } from '@workbench/generation/baseGenerationPolicies';-import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState';+import { getDefaultGenerateSettings } from '@features/generation/settings';+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';+import { createWorkbenchStore } from '@workbench/workbenchStore';import { describe, expect, it, vi } from 'vitest';-import { resolveAndSubmitGraphPreviewInvocation } from './GraphPreviewDialog';+import { resolveAndSubmitGraphPreviewInvocation } from './graphPreviewInvocation';const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };const animaVae: VaeModelConfig = { base: 'qwen-image', key: 'anima-vae', name: 'Anima VAE', type: 'vae' };@@ -61,11 +62,12 @@ const withCanvasWidgetMounted = (describe('resolveAndSubmitGraphPreviewInvocation', () => {it('routes a canvas source through prepareCanvasInvocation and does not dispatch a resolved snapshot', () => {const project = withCanvasWidgetMounted(getActiveProject(createGenerateValues()));- const dispatch = vi.fn();+ const commands = createWorkbenchStore().commands;+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');const prepareCanvasInvocation = vi.fn();const submitted = resolveAndSubmitGraphPreviewInvocation({- dispatch,+ commands,models: undefined,prepareCanvasInvocation,project,@@ -73,18 +75,19 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {});expect(submitted).toBe(true);- expect(dispatch).not.toHaveBeenCalled();+ expect(submitResolved).not.toHaveBeenCalled();expect(prepareCanvasInvocation).toHaveBeenCalledTimes(1);expect(prepareCanvasInvocation.mock.calls[0]?.[0]).toMatchObject({ projectId: project.id });});it('dispatches submitResolvedInvocationSnapshot for a non-canvas source and never prepares the canvas', () => {const project = getActiveProject(createGenerateValues());- const dispatch = vi.fn();+ const commands = createWorkbenchStore().commands;+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');const prepareCanvasInvocation = vi.fn();const submitted = resolveAndSubmitGraphPreviewInvocation({- dispatch,+ commands,models: undefined,prepareCanvasInvocation,project,@@ -93,20 +96,20 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {expect(submitted).toBe(true);expect(prepareCanvasInvocation).not.toHaveBeenCalled();- expect(dispatch).toHaveBeenCalledTimes(1);- expect(dispatch.mock.calls[0]?.[0]).toMatchObject({+ expect(submitResolved).toHaveBeenCalledTimes(1);+ expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({route: expect.objectContaining({ sourceId: 'generate' }),- type: 'submitResolvedInvocationSnapshot',});});it('returns false and does not submit when there is no sourceId', () => {const project = getActiveProject(createGenerateValues());- const dispatch = vi.fn();+ const commands = createWorkbenchStore().commands;+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');const prepareCanvasInvocation = vi.fn();const submitted = resolveAndSubmitGraphPreviewInvocation({- dispatch,+ commands,models: undefined,prepareCanvasInvocation,project,@@ -114,17 +117,18 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {});expect(submitted).toBe(false);- expect(dispatch).not.toHaveBeenCalled();+ expect(submitResolved).not.toHaveBeenCalled();expect(prepareCanvasInvocation).not.toHaveBeenCalled();});it('returns false and does not submit when the resolved route is invalid', () => {const project = getActiveProject(createGenerateValues({ qwen3EncoderModel: undefined }));- const dispatch = vi.fn();+ const commands = createWorkbenchStore().commands;+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');const prepareCanvasInvocation = vi.fn();const submitted = resolveAndSubmitGraphPreviewInvocation({- dispatch,+ commands,models: undefined,prepareCanvasInvocation,project,@@ -132,7 +136,7 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {});expect(submitted).toBe(false);- expect(dispatch).not.toHaveBeenCalled();+ expect(submitResolved).not.toHaveBeenCalled();expect(prepareCanvasInvocation).not.toHaveBeenCalled();});});diff --git a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.tsnew file mode 100644index 0000000000..0e0c2491c6--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts@@ -0,0 +1,44 @@+import type { ModelConfig } from '@features/models';++import type { InvocationSourceId } from './invocationContracts';+import type { Project } from './projectContracts';+import type { prepareCanvasInvocation } from './widgets/canvas/invoke/prepareCanvasInvocation';+import type { WorkbenchCommands } from './workbenchStore';++import { isInvocationRouteValid, resolveInvocationRoute } from './invocation';+import { submitResolvedInvocation } from './invocationSubmit';++export interface GraphPreviewInvokeDeps {+ commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;+ models: readonly ModelConfig[] | undefined;+ prepareCanvasInvocation: typeof prepareCanvasInvocation;+ project: Project;+ sourceId: InvocationSourceId | undefined;+}++/** Resolves and submits a preview against the post-draft-flush project snapshot. */+export const resolveAndSubmitGraphPreviewInvocation = ({+ commands,+ models,+ prepareCanvasInvocation: prepareCanvas,+ project,+ sourceId,+}: GraphPreviewInvokeDeps): boolean => {+ if (!sourceId) {+ return false;+ }++ const route = resolveInvocationRoute(+ project,+ 'dialog',+ { ...project.invocation, sourceId, sourceLocked: true },+ models+ );++ if (!isInvocationRouteValid(route)) {+ return false;+ }++ submitResolvedInvocation({ commands, models, prepareCanvasInvocation: prepareCanvas, project, route });+ return true;+};diff --git a/invokeai/frontend/webv2/src/workbench/graphSurfaces.ts b/invokeai/frontend/webv2/src/workbench/graphSurfaces.tsindex 42d8821b67..75e1ed6c64 100644--- a/invokeai/frontend/webv2/src/workbench/graphSurfaces.ts+++ b/invokeai/frontend/webv2/src/workbench/graphSurfaces.ts@@ -1,4 +1,4 @@-import type { GraphBearingSurfaceContract, WidgetManifest, WorkbenchRegion } from './types';+import type { GraphBearingSurfaceContract, WidgetManifest, WorkbenchRegion } from '@workbench/widgetContracts';import { isInvocationSourceAvailable } from './invocation';diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsxindex fc927e5aa4..1f80c9262b 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx@@ -1,5 +1,4 @@-/* eslint-disable react/react-compiler */-import type { WidgetContributionSource } from '@workbench/types';+import type { WidgetContributionSource } from '@workbench/widgetContracts';import { commandApi } from '@workbench/extensions/extensionApi';import { getFocusedRegionSnapshot } from '@workbench/focusRegions';@@ -101,7 +100,7 @@ export const WorkbenchHotkeyRuntime = () => {executeHotkey(hotkey, commandSource);});- const keybindings = useMemo(() => {+ useEffect(() => {const bindings: Record<string, (event: KeyboardEvent) => void> = {};for (const hotkey of registeredHotkeys) {@@ -118,16 +117,12 @@ export const WorkbenchHotkeyRuntime = () => {}}- return bindings;- }, [registeredHotkeys]);-- useEffect(() => {- if (Object.keys(keybindings).length === 0) {+ if (Object.keys(bindings).length === 0) {return;}- return tinykeys(window, keybindings, { ignore: () => false });- }, [keybindings]);+ return tinykeys(window, bindings, { ignore: () => false });+ }, [registeredHotkeys]);return null;};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.tsindex 80e7ed5b44..e528cc0a06 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts@@ -1,4 +1,5 @@-import type { WidgetHotkeyContribution, WidgetRegion, WorkbenchRegion } from '@workbench/types';+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { WidgetHotkeyContribution, WorkbenchRegion } from '@workbench/widgetContracts';import { extensionContributionStores } from '@workbench/extensions/extensionApi';import { useMemo } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.tsindex 7a2f524f4a..a5ca69da54 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts@@ -1,21 +1,24 @@-import { getConnectionStatus } from '@workbench/backend/connectionStore';+import type { ImageRecallKind } from '@workbench/image-actions/imageRecall';++import { flushGenerateDrafts } from '@features/generation/drafts';+import {+ adjustFocusedPromptAttention,+ focusPositivePrompt,+ promptHistoryNavigation,+} from '@features/generation/hotkeys';+import { ensureModelsLoaded, getModelsSnapshot } from '@features/models';+import { queueCommands } from '@features/queue';+import { useInvocationTemplatesSelector } from '@features/workflow/react';+import { useMountEffect } from '@platform/react/useMountEffect';+import { getConnectionStatus } from '@platform/transport/connectionStore';import { commandApi } from '@workbench/extensions/extensionApi';-import { cancelCurrentQueueItem } from '@workbench/generation/api';-import { executeImageRecall, getSelectedGalleryImage, type ImageRecallKind } from '@workbench/image-actions';import { isInvocationRouteValid, resolveInvocationRoute } from '@workbench/invocation';import { submitResolvedInvocation } from '@workbench/invocationSubmit';-import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';import { openWidgetPlacement } from '@workbench/widgetPlacementCommands';import { getWidgetsForRegion } from '@workbench/widgetRegistry';-import { prepareCanvasInvocation } from '@workbench/widgets/canvas/invoke/prepareCanvasInvocation';-import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';-import { focusPositivePrompt } from '@workbench/widgets/generate/promptFields';-import { adjustFocusedPromptAttention } from '@workbench/widgets/generate/promptFields/promptAttentionHotkeys';-import { navigatePromptHistory } from '@workbench/widgets/generate/promptFields/promptHistoryNavigation';import { getProjectWidgetValues } from '@workbench/widgetState';-import { useWorkbenchDispatch, useWorkbenchStore } from '@workbench/WorkbenchContext';-import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';-import { useEffect, useEffectEvent, useRef } from 'react';+import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';+import { useEffect, useEffectEvent } from 'react';const imageRecallCommands: Record<string, ImageRecallKind> = {'gallery.remix': 'remix',@@ -51,38 +54,33 @@ export const FIRST_PARTY_IMAGE_RECALL_COMMAND_IDS = Object.keys(imageRecallCommaexport const FIRST_PARTY_COMMAND_IDS = [...FIRST_PARTY_APP_COMMAND_IDS, ...Object.keys(imageRecallCommands)] as const;-export const useRegisterFirstPartyCommands = () => {- const store = useWorkbenchStore();- const dispatch = useWorkbenchDispatch();- const models = useModelsSelector((snapshot) => snapshot.models);- const modelsStatus = useModelsSelector((snapshot) => snapshot.status);- const availabilityModels = modelsStatus === 'loaded' ? models : undefined;- const projectRef = useRef(store.getSnapshot().activeProject);- const modelsRef = useRef(availabilityModels);+const getAvailableModels = () => {+ const snapshot = getModelsSnapshot();+ return snapshot.status === 'loaded' ? snapshot.models : undefined;+};+export const useRegisterFirstPartyCommands = () => {+ const commands = useWorkbenchCommands();+ const queries = useWorkbenchQueries();+ const { layout, notifications, queue, widgets } = commands;useInvocationTemplatesSelector((snapshot) => snapshot.status);- useEffect(() => {- modelsRef.current = availabilityModels;- }, [availabilityModels]);-- useEffect(- () =>- store.subscribe(() => {- projectRef.current = store.getSnapshot().activeProject;- }),- [store]- );-- useEffect(() => {+ useMountEffect(() => {ensureModelsLoaded();- }, []);+ });- const submitInvocation = useEffectEvent(() => {+ const submitInvocation = useEffectEvent(async () => {flushGenerateDrafts();- const activeProject = projectRef.current;- const resolvedRoute = resolveInvocationRoute(activeProject, 'global', activeProject.invocation, modelsRef.current);+ const { prepareCanvasInvocation } = await import('@workbench/widgets/canvas/invoke/prepareCanvasInvocation');++ const activeProject = queries.getSnapshot().activeProject;+ const resolvedRoute = resolveInvocationRoute(+ activeProject,+ 'global',+ activeProject.invocation,+ getAvailableModels()+ );const { status } = getConnectionStatus();if (!isInvocationRouteValid(resolvedRoute) || status !== 'connected') {@@ -90,8 +88,8 @@ export const useRegisterFirstPartyCommands = () => {}submitResolvedInvocation({- dispatch,- models: modelsRef.current,+ commands,+ models: getAvailableModels(),prepareCanvasInvocation,project: activeProject,route: resolvedRoute,@@ -99,34 +97,37 @@ export const useRegisterFirstPartyCommands = () => {});const recallSelectedImage = useEffectEvent(async (kind: ImageRecallKind) => {- const activeProject = projectRef.current;+ const [{ executeImageRecall }, { getSelectedGalleryImage }] = await Promise.all([+ import('@workbench/image-actions/executeImageRecall'),+ import('@workbench/image-actions/selectedImage'),+ ]);+ const activeProject = queries.getSnapshot().activeProject;const image = getSelectedGalleryImage(activeProject);if (!image) {- dispatch({+ notifications.add({kind: 'info',message: 'Select an image in Gallery or Preview first.',title: 'No image selected',- type: 'recordNotice',});return;}const didRecall = await executeImageRecall({- dispatch,+ commands,generateValues: getProjectWidgetValues(activeProject, 'generate'),image,kind,- models: modelsRef.current ?? [],+ models: getAvailableModels() ?? [],projectId: activeProject.id,});- if (didRecall && store.getSnapshot().activeProject.id === activeProject.id) {+ if (didRecall && queries.isActiveProject(activeProject.id)) {openWidgetPlacement({- dispatch,getWidgetsForRegion,options: { preferredRegions: ['left'] },typeId: 'generate',+ widgets,});}});@@ -136,22 +137,22 @@ export const useRegisterFirstPartyCommands = () => {commandApi.register({ handler: submitInvocation, id: 'app.invoke', title: 'Invoke' }),commandApi.register({ handler: submitInvocation, id: 'app.invokeFront', title: 'Invoke front' }),commandApi.register({- handler: () => void cancelCurrentQueueItem().finally(() => dispatch({ type: 'refreshBackendData' })),+ handler: () => void queueCommands.cancelCurrentItem().finally(queue.refreshBackendData),id: 'app.cancelQueueItem',title: 'Cancel current queue item',}),commandApi.register({- handler: () => dispatch({ projectId: projectRef.current.id, type: 'cancelAllQueueItems' }),+ handler: () => queue.cancelAll(queries.getSnapshot().activeProject.id),id: 'app.clearQueue',title: 'Clear queue',}),commandApi.register({handler: () =>openWidgetPlacement({- dispatch,getWidgetsForRegion,options: { preferredRegions: ['left'] },typeId: 'generate',+ widgets,}),id: 'app.selectGenerateTab',title: 'Select Generate tab',@@ -159,10 +160,10 @@ export const useRegisterFirstPartyCommands = () => {commandApi.register({handler: () =>openWidgetPlacement({- dispatch,getWidgetsForRegion,options: { preferredRegions: ['center'], requireCenterView: true },typeId: 'canvas',+ widgets,}),id: 'app.selectCanvasTab',title: 'Select Canvas tab',@@ -170,26 +171,27 @@ export const useRegisterFirstPartyCommands = () => {commandApi.register({handler: () =>openWidgetPlacement({- dispatch,getWidgetsForRegion,options: { preferredRegions: ['center'], requireCenterView: true },typeId: 'workflow',+ widgets,}),id: 'app.selectWorkflowsTab',title: 'Select Workflows tab',}),commandApi.register({- handler: () => (window.location.hash = `#/models?project=${encodeURIComponent(projectRef.current.id)}`),+ handler: () =>+ (window.location.hash = `#/models?project=${encodeURIComponent(queries.getSnapshot().activeProject.id)}`),id: 'app.selectModelsTab',title: 'Select Models tab',}),commandApi.register({handler: () =>openWidgetPlacement({- dispatch,getWidgetsForRegion,options: { preferredRegions: ['right', 'bottom'] },typeId: 'queue',+ widgets,}),id: 'app.selectQueueTab',title: 'Select Queue tab',@@ -197,10 +199,10 @@ export const useRegisterFirstPartyCommands = () => {commandApi.register({handler: () => {openWidgetPlacement({- dispatch,getWidgetsForRegion,options: { preferredRegions: ['left'] },typeId: 'generate',+ widgets,});window.requestAnimationFrame(() => focusPositivePrompt());},@@ -211,11 +213,15 @@ export const useRegisterFirstPartyCommands = () => {handler: () => {flushGenerateDrafts();- navigatePromptHistory({+ const project = queries.getSnapshot().activeProject;++ promptHistoryNavigation.navigate({direction: -1,- dispatch,- models: modelsRef.current,- project: projectRef.current,+ models: getAvailableModels(),+ patchValues: (values, projectId) => widgets.patchValues('generate', values, projectId),+ projectId: project.id,+ promptHistory: project.promptHistory,+ values: getProjectWidgetValues(project, 'generate'),});},id: 'app.promptHistoryPrev',@@ -225,11 +231,15 @@ export const useRegisterFirstPartyCommands = () => {handler: () => {flushGenerateDrafts();- navigatePromptHistory({+ const project = queries.getSnapshot().activeProject;++ promptHistoryNavigation.navigate({direction: 1,- dispatch,- models: modelsRef.current,- project: projectRef.current,+ models: getAvailableModels(),+ patchValues: (values, projectId) => widgets.patchValues('generate', values, projectId),+ projectId: project.id,+ promptHistory: project.promptHistory,+ values: getProjectWidgetValues(project, 'generate'),});},id: 'app.promptHistoryNext',@@ -237,47 +247,53 @@ export const useRegisterFirstPartyCommands = () => {}),commandApi.register({handler: () =>- adjustFocusedPromptAttention('increment', projectRef.current.settings.preferNumericAttentionStyle),+ adjustFocusedPromptAttention(+ 'increment',+ queries.getSnapshot().activeProject.settings.preferNumericAttentionStyle+ ),id: 'app.promptWeightUp',title: 'Increase prompt weight',}),commandApi.register({handler: () =>- adjustFocusedPromptAttention('decrement', projectRef.current.settings.preferNumericAttentionStyle),+ adjustFocusedPromptAttention(+ 'decrement',+ queries.getSnapshot().activeProject.settings.preferNumericAttentionStyle+ ),id: 'app.promptWeightDown',title: 'Decrease prompt weight',}),commandApi.register({handler: () => {- const region = projectRef.current.widgetRegions.left;+ const region = queries.getSnapshot().activeProject.widgetRegions.left;- dispatch({ isCollapsed: !region.isCollapsed, region: 'left', type: 'setRegionWidgetCollapsed' });+ layout.setRegionCollapsed('left', !region.isCollapsed);},id: 'app.toggleLeftPanel',title: 'Toggle left panel',}),commandApi.register({handler: () => {- const region = projectRef.current.widgetRegions.right;+ const region = queries.getSnapshot().activeProject.widgetRegions.right;- dispatch({ isCollapsed: !region.isCollapsed, region: 'right', type: 'setRegionWidgetCollapsed' });+ layout.setRegionCollapsed('right', !region.isCollapsed);},id: 'app.toggleRightPanel',title: 'Toggle right panel',}),commandApi.register({- handler: () => dispatch({ type: 'resetActiveLayout' }),+ handler: layout.reset,id: 'app.resetPanelLayout',title: 'Reset panel layout',}),commandApi.register({handler: () => {- const { bottom, left, right } = projectRef.current.widgetRegions;+ const { bottom, left, right } = queries.getSnapshot().activeProject.widgetRegions;const shouldCollapse = !left.isCollapsed || !right.isCollapsed || !bottom.isCollapsed;- dispatch({ isCollapsed: shouldCollapse, region: 'left', type: 'setRegionWidgetCollapsed' });- dispatch({ isCollapsed: shouldCollapse, region: 'right', type: 'setRegionWidgetCollapsed' });- dispatch({ isCollapsed: shouldCollapse, region: 'bottom', type: 'setRegionWidgetCollapsed' });+ layout.setRegionCollapsed('left', shouldCollapse);+ layout.setRegionCollapsed('right', shouldCollapse);+ layout.setRegionCollapsed('bottom', shouldCollapse);},id: 'app.togglePanels',title: 'Toggle panels',@@ -290,5 +306,5 @@ export const useRegisterFirstPartyCommands = () => {return () => {disposers.forEach((dispose) => dispose());};- }, [dispatch]);+ }, [commands, layout, notifications, queries, queue, widgets]);};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.tsindex 600bde0bd7..028943477e 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.ts@@ -1,4 +1,4 @@-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';const store = createExternalStore<{ activeLayerIds: ReadonlySet<string> }>({ activeLayerIds: new Set<string>() });diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.tsindex ce201e64ba..23c7ec0133 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts@@ -1,4 +1,4 @@-import type { WidgetInstanceId, WidgetTypeId, WorkbenchRegion } from '@workbench/types';+import type { WidgetInstanceId, WidgetTypeId, WorkbenchRegion } from '@workbench/widgetContracts';export const getHotkeyTargetWidget = (target: EventTarget | nulldiff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/types.tsindex 3a586c98e2..edeb9fe0b8 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts@@ -1,4 +1,5 @@-import type { WidgetContributionSource, WidgetInstanceId, WidgetRegion, WidgetTypeId } from '@workbench/types';+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { WidgetContributionSource, WidgetInstanceId, WidgetTypeId } from '@workbench/widgetContracts';export type HotkeyCategory = 'app' | 'canvas' | 'gallery' | 'viewer' | 'workflows';diff --git a/invokeai/frontend/webv2/src/workbench/i18n/index.ts b/invokeai/frontend/webv2/src/workbench/i18n/index.tsdeleted file mode 100644index 4a9d71541e..0000000000--- a/invokeai/frontend/webv2/src/workbench/i18n/index.ts+++ /dev/null@@ -1,9 +0,0 @@-export { I18nController } from './I18nController';-export {- getWorkbenchLanguageDirection,- normalizeWorkbenchLanguage,- WORKBENCH_LANGUAGE_OPTIONS,- WORKBENCH_LANGUAGES,- type WorkbenchLanguage,- type WorkbenchLanguageDirection,-} from './languages';diff --git a/invokeai/frontend/webv2/src/workbench/iconResolver.tsx b/invokeai/frontend/webv2/src/workbench/iconResolver.tsxindex 0704ee8a7f..051de214bc 100644--- a/invokeai/frontend/webv2/src/workbench/iconResolver.tsx+++ b/invokeai/frontend/webv2/src/workbench/iconResolver.tsx@@ -1,8 +1,8 @@+import type { WidgetIconComponent } from '@workbench/widgetContracts';+import { Icon, type IconProps } from '@chakra-ui/react';import { SquareIcon } from 'lucide-react';-import type { WidgetIconComponent } from './types';-export const WidgetIcon = ({ icon, ...props }: IconProps & { icon?: WidgetIconComponent }) => {const ResolvedIcon = icon ?? SquareIcon;diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.test.tsindex 947b8fe0f7..8bc2428a9c 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.test.ts@@ -1,4 +1,4 @@-import type { GalleryImage } from '@workbench/gallery/api';+import type { GalleryImage } from '@features/gallery';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsxindex fa809f9c6a..36c84a94cf 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx@@ -1,12 +1,12 @@+import type { GalleryBoard, GalleryImage } from '@features/gallery';/* eslint-disable react/react-compiler */import type { GalleryCanvasImportDestination } from '@workbench/canvas-operations/api';-import type { GalleryBoard, GalleryImage } from '@workbench/gallery/api';import { Dialog, HStack, Icon, Menu, Portal, ScrollArea, Text } from '@chakra-ui/react';-import { Button, MenuContent, Tooltip } from '@workbench/components/ui';+import { Button, MenuContent, Tooltip } from '@platform/ui';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';-import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useWorkbenchCommands } from '@workbench/WorkbenchContext';import {AsteriskIcon,ChevronRightIcon,@@ -340,17 +340,15 @@ const SingleImageMenuItems = ({const handleRecallClipSkip = useRecallImageDataHandler(actions, image, 'clipSkip');const handleSelectForCompare = useSelectForCompareHandler(actions, image);const handleUseAsReferenceImage = useUseAsReferenceImageHandler(actions, image);- const dispatch = useWorkbenchDispatch();+ const { generation, widgets } = useWorkbenchCommands();const openWidget = useOpenWorkbenchWidget();const handleSendToUpscale = useCallback(() => {openWidget('upscale', { preferredRegions: ['left'] });- dispatch({- type: 'patchWidgetValues',- values: { inputImage: { height: image.height, image_name: image.imageName, width: image.width } },- widgetId: 'upscale',+ widgets.patchValues('upscale', {+ inputImage: { height: image.height, image_name: image.imageName, width: image.width },});- dispatch({ sourceId: 'upscale', type: 'setInvocationSource' });- }, [dispatch, image.height, image.imageName, image.width, openWidget]);+ generation.setSource('upscale');+ }, [generation, image.height, image.imageName, image.width, openWidget, widgets]);return (<>diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsxindex faa7b86332..ad7a68a0c1 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsx@@ -1,5 +1,5 @@import { ButtonGroup, Icon } from '@chakra-ui/react';-import { Button, Tooltip } from '@workbench/components/ui';+import { Button, Tooltip } from '@platform/ui';import {AsteriskIcon,QuoteIcon,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/canvasImportError.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/canvasImportError.test.tsindex c30fee61b7..2b08cafe7c 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/canvasImportError.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/canvasImportError.test.ts@@ -1,27 +1,28 @@+import type { WorkbenchNotificationCommands } from '@workbench/workbenchStore';+import { describe, expect, it, vi } from 'vitest';import { recordCanvasImportError } from './canvasImportError';describe('recordCanvasImportError', () => {it('dispatches one localized diagnostic error and no notice', () => {- const dispatch = vi.fn();+ const reportError = vi.fn();+ const notifications = { reportError } as unknown as WorkbenchNotificationCommands;recordCanvasImportError({- dispatch,+ notifications,error: new Error('resize backend failed'),localizedMessage: "Couldn't add images to canvas",projectId: 'project-1',});- expect(dispatch).toHaveBeenCalledTimes(1);- expect(dispatch).toHaveBeenCalledWith({+ expect(reportError).toHaveBeenCalledTimes(1);+ expect(reportError).toHaveBeenCalledWith({area: 'image-actions',context: { error: 'resize backend failed' },message: "Couldn't add images to canvas",namespace: 'gallery',projectId: 'project-1',- type: 'recordError',});- expect(dispatch.mock.calls.some(([action]) => action.type === 'recordNotice')).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/canvasImportError.ts b/invokeai/frontend/webv2/src/workbench/image-actions/canvasImportError.tsindex f558b7a82f..c41101acc1 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/canvasImportError.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/canvasImportError.ts@@ -1,25 +1,23 @@-import type { WorkbenchAction } from '@workbench/workbenchState';-import type { Dispatch } from 'react';+import type { WorkbenchNotificationCommands } from '@workbench/workbenchStore';const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));export const recordCanvasImportError = ({- dispatch,+ notifications,error,localizedMessage,projectId,}: {- dispatch: Dispatch<WorkbenchAction>;+ notifications: WorkbenchNotificationCommands;error: unknown;localizedMessage: string;projectId?: string;}): void => {- dispatch({+ notifications.reportError({area: 'image-actions',context: { error: toErrorMessage(error) },message: localizedMessage,namespace: 'gallery',projectId,- type: 'recordError',});};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.tsindex 4773bbcb06..5d3ef3c9f1 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts@@ -1,14 +1,17 @@-import type { GalleryImage } from '@workbench/gallery/api';-import type { ModelConfig } from '@workbench/models/types';+import type { GalleryImage } from '@features/gallery';+import type { ModelConfig } from '@features/models';+import type { WorkbenchCommands } from '@workbench/workbenchStore';import { beforeEach, describe, expect, it, vi } from 'vitest';const galleryApi = vi.hoisted(() => ({- getGalleryImageMetadata: vi.fn(),- getGalleryImagesByNames: vi.fn(),+ galleryImages: {+ metadata: vi.fn(),+ resolveMany: vi.fn(),+ },}));-vi.mock('@workbench/gallery/api', () => galleryApi);+vi.mock('@features/gallery', () => galleryApi);import { executeImageRecall } from './executeImageRecall';@@ -38,20 +41,31 @@ const image: GalleryImage = {width: 512,};+const createCommands = () => {+ const add = vi.fn();+ const setSettings = vi.fn();+ const commands = {+ generation: { setSettings } as unknown as WorkbenchCommands['generation'],+ notifications: { add, reportError: vi.fn() } as unknown as WorkbenchCommands['notifications'],+ };++ return { add, commands, setSettings };+};+describe('executeImageRecall', () => {beforeEach(() => {- galleryApi.getGalleryImageMetadata.mockReset();- galleryApi.getGalleryImagesByNames.mockReset();+ galleryApi.galleryImages.metadata.mockReset();+ galleryApi.galleryImages.resolveMany.mockReset();});it('recalls remix settings into Generate values', async () => {- const dispatch = vi.fn();+ const { add, commands, setSettings } = createCommands();- galleryApi.getGalleryImageMetadata.mockResolvedValue({ positive_prompt: 'recalled prompt' });+ galleryApi.galleryImages.metadata.mockResolvedValue({ positive_prompt: 'recalled prompt' });await expect(executeImageRecall({- dispatch,+ commands,generateValues: { modelKey: model.key },image,kind: 'remix',@@ -60,23 +74,20 @@ describe('executeImageRecall', () => {})).resolves.toBe(true);- expect(galleryApi.getGalleryImageMetadata).toHaveBeenCalledWith('selected.png');- expect(dispatch).toHaveBeenCalledWith({- projectId: 'project-1',- type: 'setGenerateSettings',- values: expect.objectContaining({ positivePrompt: 'recalled prompt' }),- });- expect(dispatch).toHaveBeenCalledWith(- expect.objectContaining({ kind: 'success', title: 'Recalled remix settings', type: 'recordNotice' })+ expect(galleryApi.galleryImages.metadata).toHaveBeenCalledWith('selected.png');+ expect(setSettings).toHaveBeenCalledWith(+ expect.objectContaining({ positivePrompt: 'recalled prompt' }),+ 'project-1');+ expect(add).toHaveBeenCalledWith(expect.objectContaining({ kind: 'success', title: 'Recalled remix settings' }));});it('uses the freshest Generate values when recalling image dimensions', async () => {- const dispatch = vi.fn();+ const { commands, setSettings } = createCommands();await expect(executeImageRecall({- dispatch,+ commands,generateValues: { modelKey: model.key, positivePrompt: 'stale prompt' },getGenerateValues: () => ({ modelKey: model.key, positivePrompt: 'fresh prompt' }),image,@@ -86,15 +97,14 @@ describe('executeImageRecall', () => {})).resolves.toBe(true);- expect(dispatch).toHaveBeenCalledWith({- projectId: 'project-1',- type: 'setGenerateSettings',- values: expect.objectContaining({ positivePrompt: 'fresh prompt', height: image.height, width: image.width }),- });+ expect(setSettings).toHaveBeenCalledWith(+ expect.objectContaining({ positivePrompt: 'fresh prompt', height: image.height, width: image.width }),+ 'project-1'+ );});it('bulk-checks effective reference images and omits deleted entries before committing', async () => {- const dispatch = vi.fn();+ const { commands, setSettings } = createCommands();const recallImage = { ...image, imageName: 'selected-with-references.png' };const makeReference = (id: string, imageName: string) => ({config: {@@ -112,15 +122,15 @@ describe('executeImageRecall', () => {isEnabled: true,});- galleryApi.getGalleryImageMetadata.mockResolvedValue({+ galleryApi.galleryImages.metadata.mockResolvedValue({positive_prompt: 'keep other fields',ref_images: [makeReference('valid', 'valid-crop.png'), makeReference('deleted', 'deleted-crop.png')],});- galleryApi.getGalleryImagesByNames.mockResolvedValue([{ ...image, imageName: 'valid-crop.png' }]);+ galleryApi.galleryImages.resolveMany.mockResolvedValue([{ ...image, imageName: 'valid-crop.png' }]);await expect(executeImageRecall({- dispatch,+ commands,generateValues: { modelKey: model.key },image: recallImage,kind: 'all',@@ -129,14 +139,13 @@ describe('executeImageRecall', () => {})).resolves.toBe(true);- expect(galleryApi.getGalleryImagesByNames).toHaveBeenCalledWith(['valid-crop.png', 'deleted-crop.png']);- expect(dispatch).toHaveBeenCalledWith({- projectId: 'project-1',- type: 'setGenerateSettings',- values: expect.objectContaining({+ expect(galleryApi.galleryImages.resolveMany).toHaveBeenCalledWith(['valid-crop.png', 'deleted-crop.png']);+ expect(setSettings).toHaveBeenCalledWith(+ expect.objectContaining({positivePrompt: 'keep other fields',referenceImages: [expect.objectContaining({ id: 'valid' })],}),- });+ 'project-1'+ );});});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.tsindex 93fb4f91f4..9553dec8d8 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts@@ -1,13 +1,16 @@-import type { GalleryImage } from '@workbench/gallery/api';-import type { GenerateModelConfig, GenerateWidgetValues, VaeModelConfig } from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';-import type { WorkbenchAction } from '@workbench/workbenchState';-import type { Dispatch } from 'react';+import type { GalleryImage } from '@features/gallery';+import type { GenerateModelConfig, GenerateWidgetValues, VaeModelConfig } from '@features/generation/contracts';+import type { ModelConfig } from '@features/models';+import type { WorkbenchCommands } from '@workbench/workbenchStore';-import { getGalleryImageMetadata, getGalleryImagesByNames } from '@workbench/gallery/api';-import { getDefaultGenerateSettings, isSupportedGenerateModel } from '@workbench/generation/baseGenerationPolicies';-import { getEffectiveReferenceImage } from '@workbench/generation/referenceImage';-import { isVaeModelConfig, normalizeGenerateWidgetValues } from '@workbench/generation/settings';+import { galleryImages } from '@features/gallery';+import {+ getDefaultGenerateSettings,+ isSupportedGenerateModel,+ isVaeModelConfig,+ normalizeGenerateWidgetValues,+} from '@features/generation/settings';+import { getEffectiveReferenceImage } from '@features/generation/utility';import {buildImageRecallSettings,@@ -27,7 +30,7 @@ const loadImageMetadata = (imageName: string): Promise<unknown> => {return cachedRequest;}- const request = getGalleryImageMetadata(imageName).catch((error: unknown) => {+ const request = galleryImages.metadata(imageName).catch((error: unknown) => {imageMetadataRequests.delete(imageName);throw error;});@@ -64,7 +67,7 @@ export const getCurrentGenerateValues = ({};export const executeImageRecall = async ({- dispatch,+ commands,generateValues,getGenerateValues,image,@@ -72,7 +75,7 @@ export const executeImageRecall = async ({models,projectId,}: {- dispatch: Dispatch<WorkbenchAction>;+ commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;generateValues: Record<string, unknown>;getGenerateValues?: () => Record<string, unknown>;image: GalleryImage;@@ -89,11 +92,10 @@ export const executeImageRecall = async ({try {if (!currentGenerateValues) {- dispatch({+ commands.notifications.add({kind: 'info',message: 'Select a supported Generate model first.',title: 'Cannot recall image data',- type: 'recordNotice',});return false;}@@ -110,11 +112,10 @@ export const executeImageRecall = async ({});if (!result) {- dispatch({+ commands.notifications.add({kind: 'info',message: 'This image does not include supported Generate metadata.',title: 'No recallable image data',- type: 'recordNotice',});return false;}@@ -124,7 +125,9 @@ export const executeImageRecall = async ({referenceImage.config.image ? [getEffectiveReferenceImage(referenceImage.config.image).image_name] : []);const availableNames = new Set(- (await getGalleryImagesByNames([...new Set(effectiveNames)])).map((availableImage) => availableImage.imageName)+ (await galleryImages.resolveMany([...new Set(effectiveNames)])).map(+ (availableImage) => availableImage.imageName+ ));result.values.referenceImages = result.values.referenceImages.filter((referenceImage) => {const referenceAsset = referenceImage.config.image;@@ -137,30 +140,27 @@ export const executeImageRecall = async ({}if (result.fields.length === 0) {- dispatch({+ commands.notifications.add({kind: 'info',message: 'This image does not include supported Generate metadata.',title: 'No recallable image data',- type: 'recordNotice',});return false;}- dispatch({ projectId, type: 'setGenerateSettings', values: result.values });- dispatch({+ commands.generation.setSettings(result.values, projectId);+ commands.notifications.add({kind: 'success',message: getImageRecallMessage(result.fields),title: getImageRecallTitle(kind),- type: 'recordNotice',});return true;} catch (error: unknown) {- dispatch({+ commands.notifications.reportError({area: 'image-recall',message: toErrorMessage(error),namespace: 'generation',projectId,- type: 'recordError',});return false;}diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.tsindex 48d66f5d98..5a08cc0098 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@ -1,10 +1,10 @@-import type { GalleryImage } from '@workbench/gallery/api';+import type { GalleryImage } from '@features/gallery';import type {ComponentModelConfig,GenerateWidgetValues,MainModelConfig,VaeModelConfig,-} from '@workbench/generation/types';+} from '@features/generation/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.tsindex b388640479..ada06080e2 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts@@ -1,11 +1,11 @@-import type { GalleryImage } from '@workbench/gallery/api';+import type { GalleryImage } from '@features/gallery';import type {ComponentModelConfig,GenerateModelConfig,GenerateWidgetValues,MainModelConfig,VaeModelConfig,-} from '@workbench/generation/types';+} from '@features/generation/contracts';import {getCompatibleReferenceImages,@@ -13,9 +13,7 @@ import {getGenerationUiPolicy,getSettingsWithModelDefaults,isKnownScheduler,-} from '@workbench/generation/baseGenerationPolicies';-import { isVaeCompatibleWithGenerateModel } from '@workbench/generation/componentCompatibility';-import {+ isVaeCompatibleWithGenerateModel,cloneGenerateWidgetValues,getModelDefaultVae,hasModelDefaultVae,@@ -25,7 +23,7 @@ import {deriveAspectRatioId,normalizeReferenceImages,SEED_MAX,-} from '@workbench/generation/settings';+} from '@features/generation/settings';export type ImageRecallKind = 'all' | 'remix' | 'prompts' | 'seed' | 'dimensions' | 'clipSkip';diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.test.tsindex 8096ef5a34..7e67bb3d03 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.test.ts@@ -1,4 +1,4 @@-import type { GeneratedImageContract } from '@workbench/types';+import type { GeneratedImageContract } from '@features/gallery';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.ts b/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.tsindex e2c6812e4c..f833c704d6 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.ts@@ -1,36 +1,10 @@-import type { GalleryImage } from '@workbench/gallery/api';-import type { GeneratedImageContract, Project } from '@workbench/types';+import type { GalleryImage } from '@features/gallery';+import type { Project } from '@workbench/projectContracts';+import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';import { getProjectWidgetValues } from '@workbench/widgetState';-const isGeneratedImage = (value: unknown): value is GeneratedImageContract =>- Boolean(value) && typeof value === 'object' && typeof (value as GeneratedImageContract).imageName === 'string';--const toGalleryImage = (- image: GeneratedImageContract & Partial<GalleryImage>,- galleryValues: Record<string, unknown>-): GalleryImage => ({- ...image,- boardId:- image.boardId ?? (typeof galleryValues.selectedBoardId === 'string' ? galleryValues.selectedBoardId : 'none'),- imageCategory: image.imageCategory ?? 'general',- starred: image.starred ?? false,-});--export const getSelectedGalleryImageFromValues = (galleryValues: Record<string, unknown>): GalleryImage | null => {- if (isGeneratedImage(galleryValues.selectedImage)) {- return toGalleryImage(galleryValues.selectedImage, galleryValues);- }-- const selectedImageName =- typeof galleryValues.selectedImageName === 'string' ? galleryValues.selectedImageName : null;- const recentImages = Array.isArray(galleryValues.recentImages) ? galleryValues.recentImages : [];- const recentImage = recentImages.find(- (image): image is GeneratedImageContract => isGeneratedImage(image) && image.imageName === selectedImageName- );-- return recentImage ? toGalleryImage(recentImage, galleryValues) : null;-};+export { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';export const getSelectedGalleryImage = (project: Project): GalleryImage | null =>getSelectedGalleryImageFromValues(getProjectWidgetValues(project, 'gallery'));diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex 29eb1e976a..a68522ad3e 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -1,34 +1,33 @@-import type { VaeModelConfig } from '@workbench/generation/types';-import type { WorkbenchAction } from '@workbench/workbenchState';+import type { VaeModelConfig } from '@features/generation/contracts';-import { importGalleryImagesToCanvas, type GalleryCanvasImportDestination } from '@workbench/canvas-operations/api';-import { getCanvasImportNotice } from '@workbench/canvas-operations/canvasImportNotice';-import { getEngine } from '@workbench/canvas-operations/engineRegistry';import {- addImagesToGalleryBoard,- deleteGalleryImages,- downloadGalleryArchive,- getGalleryImageMetadata,- removeImagesFromGalleryBoard,- starGalleryImages,- unstarGalleryImages,+ galleryImages,+ galleryOrganization,+ galleryTransfers,type GalleryBoard,type GalleryImage,-} from '@workbench/gallery/api';+} from '@features/gallery';import {createReferenceImageId,getDefaultReferenceImageConfig,getMaxReferenceImages,+ isVaeModelConfig,isReferenceImageSupported,isSupportedGenerateModel,-} from '@workbench/generation/baseGenerationPolicies';-import { generatedImageToReferenceImage } from '@workbench/generation/referenceImage';-import { isVaeModelConfig } from '@workbench/generation/settings';-import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';+} from '@features/generation/settings';+import { generatedImageToReferenceImage } from '@features/generation/utility';+import { ensureModelsLoaded, useModelsSelector } from '@features/models';+import { useMountEffect } from '@platform/react/useMountEffect';+import {+ getCanvasImportNotice,+ getCanvasEngine,+ importGalleryImagesToCanvas,+ type GalleryCanvasImportDestination,+} from '@workbench/canvas-operations/api';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';import { getProjectWidgetValues } from '@workbench/widgetState';-import { useWorkbenchStore } from '@workbench/WorkbenchContext';-import { useEffect, useMemo, type Dispatch } from 'react';+import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';+import { useMemo } from 'react';import { useTranslation } from 'react-i18next';import { recordCanvasImportError } from './canvasImportError';@@ -92,14 +91,12 @@ const toPngBlob = async (blob: Blob): Promise<Blob> => {export const useImageActions = ({boards,- dispatch,generateValues,onImagesDeleted,onStarredChange,projectId,}: {boards: GalleryBoard[];- dispatch: Dispatch<WorkbenchAction>;generateValues: Record<string, unknown>;projectId?: string;/** Called after a successful deletion so the host can select a neighboring image. */@@ -108,7 +105,9 @@ export const useImageActions = ({onStarredChange?: (imageNames: string[], starred: boolean) => void;}): ImageActions => {const openWorkbenchWidget = useOpenWorkbenchWidget();- const store = useWorkbenchStore();+ const commands = useWorkbenchCommands();+ const { gallery, generation, notifications } = commands;+ const queries = useWorkbenchQueries();const { t } = useTranslation();const models = useModelsSelector((snapshot) => snapshot.models);const supportedModels = useMemo(() => models.filter(isSupportedGenerateModel), [models]);@@ -117,28 +116,26 @@ export const useImageActions = ({return getCurrentGenerateValues({ generateValues, supportedModels });}, [generateValues, supportedModels]);- useEffect(() => {+ useMountEffect(() => {ensureModelsLoaded();- }, []);+ });return useMemo<ImageActions>(() => {const recordError = (error: unknown) =>- dispatch({+ notifications.reportError({area: 'image-actions',message: toErrorMessage(error),namespace: 'gallery',projectId,- type: 'recordError',});- const recordSuccess = (title: string, message?: string) =>- dispatch({ kind: 'success', message, title, type: 'recordNotice' });- const refreshGallery = () => dispatch({ projectId, type: 'touchGalleryRefresh' });- const refreshGalleryImages = () => dispatch({ projectId, type: 'touchGalleryImagesRefresh' });+ const recordSuccess = (title: string, message?: string) => notifications.add({ kind: 'success', message, title });+ const refreshGallery = () => gallery.touch(projectId);+ const refreshGalleryImages = () => gallery.touchImages(projectId);const getBoardName = (boardId: string) => boards.find((board) => board.id === boardId)?.name ?? 'Uncategorized';const getLatestGenerateValues = () => {- const snapshot = store.getSnapshot();+ const snapshot = queries.getSnapshot();const project = projectId- ? snapshot.state.projects.find((candidate) => candidate.id === projectId)+ ? snapshot.projects.find((candidate) => candidate.id === projectId): snapshot.activeProject;return project ? getProjectWidgetValues(project, 'generate') : {};@@ -158,8 +155,8 @@ export const useImageActions = ({},deleteImages: async (imageNames) => {try {- await deleteGalleryImages(imageNames);- dispatch({ imageNames, projectId, type: 'removeGalleryImages' });+ await galleryOrganization.deleteImages(imageNames);+ gallery.removeImages(imageNames, projectId);onImagesDeleted?.(imageNames);recordSuccess(imageNames.length === 1 ? 'Deleted image' : `Deleted ${imageNames.length} images`);refreshGallery();@@ -183,14 +180,13 @@ export const useImageActions = ({},downloadImages: async (imageNames) => {try {- dispatch({+ notifications.add({kind: 'info',message: `Preparing an archive of ${imageNames.length} images.`,title: 'Preparing download',- type: 'recordNotice',});- const { blob, fileName } = await downloadGalleryArchive({ imageNames });+ const { blob, fileName } = await galleryTransfers.downloadArchive({ imageNames });saveBlobToDisk(blob, fileName);recordSuccess('Download ready');@@ -204,7 +200,7 @@ export const useImageActions = ({}try {- const metadata = await getGalleryImageMetadata(image.imageName);+ const metadata = await galleryImages.metadata(image.imageName);return getImageRecallCapabilities({currentValues: currentGenerateValues,@@ -225,9 +221,9 @@ export const useImageActions = ({moveImagesToBoard: async (imageNames, boardId) => {try {if (boardId === 'none') {- await removeImagesFromGalleryBoard(imageNames);+ await galleryOrganization.removeFromBoard(imageNames);} else {- await addImagesToGalleryBoard(boardId, imageNames);+ await galleryOrganization.addToBoard(boardId, imageNames);}recordSuccess(@@ -241,12 +237,12 @@ export const useImageActions = ({}},openImageInPreview: (image) => {- dispatch({ image, projectId, type: 'selectGalleryImage' });+ gallery.selectImage(image, projectId);openWorkbenchWidget('preview', { preferredRegions: ['center'], requireCenterView: true });},recallImageData: async (image, kind) => {const didRecall = await executeImageRecall({- dispatch,+ commands,generateValues,getGenerateValues: getLatestGenerateValues,image,@@ -255,44 +251,44 @@ export const useImageActions = ({projectId,});- if (didRecall && (!projectId || store.getSnapshot().activeProject.id === projectId)) {+ if (didRecall && (!projectId || queries.isActiveProject(projectId))) {openWorkbenchWidget('generate', { preferredRegions: ['left'] });}},selectForCompare: (image) => {- dispatch({ image, projectId, type: 'setGalleryCompareImage' });+ gallery.setCompareImage(image, projectId);},sendToCanvas: async (images, destination) => {try {- const state = store.getState();- const targetProjectId = projectId ?? state.activeProjectId;- const project = state.projects.find((candidate) => candidate.id === targetProjectId);+ const targetProjectId = projectId ?? queries.getSnapshot().activeProject.id;+ const project = queries.getProject(targetProjectId);if (!project) {const notice = getCanvasImportNotice({ status: 'stale-project' });- dispatch({ kind: notice.kind, title: t(notice.titleKey, notice.options ?? {}), type: 'recordNotice' });+ notifications.add({ kind: notice.kind, title: t(notice.titleKey, notice.options ?? {}) });return;}const result = await importGalleryImagesToCanvas({+ applyCanvasMutation: commands.canvas.apply,destination,- dispatch,- engine: getEngine(project.id) ?? null,- getState: store.getState,+ engine: getCanvasEngine(project.id) ?? null,+ getProject: queries.getProject,images,+ isActiveProject: queries.isActiveProject,project,});const notice = getCanvasImportNotice(result);- dispatch({ kind: notice.kind, title: t(notice.titleKey, notice.options ?? {}), type: 'recordNotice' });+ notifications.add({ kind: notice.kind, title: t(notice.titleKey, notice.options ?? {}) });- if (result.status === 'imported' && store.getState().activeProjectId === project.id) {+ if (result.status === 'imported' && queries.isActiveProject(project.id)) {openWorkbenchWidget('canvas', { preferredRegions: ['center'], requireCenterView: true });}} catch (error: unknown) {recordCanvasImportError({- dispatch,error,localizedMessage: t('widgets.canvas.import.failed'),+ notifications,projectId,});}@@ -301,7 +297,7 @@ export const useImageActions = ({onStarredChange?.(imageNames, starred);try {- await (starred ? starGalleryImages : unstarGalleryImages)(imageNames);+ await galleryOrganization.setStarred(imageNames, starred);refreshGalleryImages();} catch (error: unknown) {onStarredChange?.(imageNames, !starred);@@ -330,25 +326,24 @@ export const useImageActions = ({isEnabled: true,};- dispatch({- projectId,- type: 'patchGenerateSettings',- values: { referenceImages: [...currentValues.referenceImages, referenceImage] },- });+ generation.patchSettings({ referenceImages: [...currentValues.referenceImages, referenceImage] }, projectId);openWorkbenchWidget('generate', { preferredRegions: ['left'] });},};}, [boards,currentGenerateValues,- dispatch,+ commands,+ gallery,generateValues,+ generation,models,+ notifications,onImagesDeleted,onStarredChange,openWorkbenchWidget,projectId,- store,+ queries,supportedModels,t,vaeModels,diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.tsindex 7e608bbc9a..3b1f3585e3 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts@@ -1,20 +1,22 @@-import { describe, expect, it, vi } from 'vitest';-import type {ComponentModelConfig,GenerateModelConfig,GenerateWidgetValues,MainModelConfig,VaeModelConfig,-} from './generation/types';-import type { ModelConfig } from './models/types';-import type { InvocationRoute, WidgetId } from './types';+} from '@features/generation/contracts';+import type { ModelConfig } from '@features/models';+import type { InvocationRoute } from '@workbench/invocationContracts';+import type { WidgetId } from '@workbench/widgetContracts';++import { getDefaultGenerateSettings } from '@features/generation/settings';+import { createDefaultUpscaleWidgetValues } from '@features/upscale';+import { describe, expect, it, vi } from 'vitest';-import { getDefaultGenerateSettings } from './generation/baseGenerationPolicies';import { getInvocationRouteInput, resolveInvocationRoute, resolveInvocationRouteInput } from './invocation';import { submitResolvedInvocation } from './invocationSubmit';-import { createDefaultUpscaleWidgetValues } from './upscale/settings';-import { createInitialWorkbenchState, workbenchReducer } from './workbenchState';+import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';+import { createWorkbenchStore } from './workbenchStore';const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };const animaVae: VaeModelConfig = { base: 'qwen-image', key: 'anima-vae', name: 'Anima VAE', type: 'vae' };@@ -280,13 +282,14 @@ describe('submitResolvedInvocation', () => {const project = getActiveProject(createGenerateValues(animaModel, { qwen3EncoderModel: qwen3Encoder, vae: animaVae }));- const dispatch = vi.fn();+ const commands = createWorkbenchStore().commands;+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');const prepareCanvasInvocation = vi.fn();const route = routeFor(project, { ...project.invocation, destination: 'gallery', sourceId: 'canvas' });- submitResolvedInvocation({ dispatch, models: undefined, prepareCanvasInvocation, project, route });+ submitResolvedInvocation({ commands, models: undefined, prepareCanvasInvocation, project, route });- expect(dispatch).not.toHaveBeenCalled();+ expect(submitResolved).not.toHaveBeenCalled();expect(prepareCanvasInvocation).toHaveBeenCalledTimes(1);// The resolved destination rides through so a Canvas source can target the Gallery.expect(prepareCanvasInvocation.mock.calls[0]?.[0]).toMatchObject({@@ -299,17 +302,17 @@ describe('submitResolvedInvocation', () => {const project = getActiveProject(createGenerateValues(animaModel, { qwen3EncoderModel: qwen3Encoder, vae: animaVae }));- const dispatch = vi.fn();+ const commands = createWorkbenchStore().commands;+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');const prepareCanvasInvocation = vi.fn();const route = routeFor(project, { ...project.invocation, destination: 'gallery', sourceId: 'generate' });- submitResolvedInvocation({ dispatch, models: undefined, prepareCanvasInvocation, project, route });+ submitResolvedInvocation({ commands, models: undefined, prepareCanvasInvocation, project, route });expect(prepareCanvasInvocation).not.toHaveBeenCalled();- expect(dispatch).toHaveBeenCalledTimes(1);- expect(dispatch.mock.calls[0]?.[0]).toMatchObject({+ expect(submitResolved).toHaveBeenCalledTimes(1);+ expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({route: expect.objectContaining({ destination: 'gallery', sourceId: 'generate' }),- type: 'submitResolvedInvocationSnapshot',});});});diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.tsindex fdcade7c62..77914603f3 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts@@ -1,26 +1,27 @@-import type { ModelConfig } from './models/types';+import type { ModelConfig } from '@features/models';+import type { ProjectGraphState } from '@features/workflow/contracts';import type {InvocationMode,InvocationRoute,InvocationSourceId,- Project,ResolvedInvocationRoute,ResultDestination,- WidgetId,-} from './types';-import type { ProjectGraphState } from './workflows/types';+} from '@workbench/invocationContracts';+import type { Project } from '@workbench/projectContracts';+import type { WidgetId } from '@workbench/widgetContracts';import {getGenerationModelAvailabilityReasons,getGenerationValidationReasons,isSupportedGenerateModel,-} from './generation/baseGenerationPolicies';-import { normalizeGenerateWidgetValues } from './generation/settings';-import { getUpscaleValidationReasons, normalizeUpscaleWidgetValues } from './upscale/settings';+ normalizeGenerateWidgetValues,+} from '@features/generation/settings';+import { getUpscaleValidationReasons, normalizeUpscaleWidgetValues } from '@features/upscale';+import { getProjectGraphReadiness } from '@features/workflow/graph';+import { getInvocationTemplatesSnapshot } from '@features/workflow/react';+import { areArraysEqual, createStableSelector } from '@platform/state/selectors';+import { getProjectWidgetValues } from './widgetState';-import { areArraysEqual, createStableSelector } from './workbenchSelectors';-import { getProjectGraphReadiness } from './workflows/buildGraph';-import { getInvocationTemplatesSnapshot } from './workflows/templates';/*** Static metadata for the Invocation Controller surfaces.diff --git a/invokeai/frontend/webv2/src/workbench/invocationContracts.ts b/invokeai/frontend/webv2/src/workbench/invocationContracts.tsnew file mode 100644index 0000000000..c0c3667194--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/invocationContracts.ts@@ -0,0 +1,26 @@+export type InvocationSourceId = 'generate' | 'workflow' | 'upscale' | 'canvas';++export type InvocationMode = 'global' | 'dialog';++export type ResultDestination = 'canvas' | 'gallery';++export interface InvocationRoute {+ sourceId: InvocationSourceId;+ destination: ResultDestination;+ sourceLocked: boolean;+ destinationLocked: boolean;+}++export interface ResolvedInvocationRoute extends InvocationRoute {+ mode: InvocationMode;+ sourceValid: boolean;+ destinationValid: boolean;+ /** The top validation issue, shown on the fixed Invoke control's secondary line. */+ validationMessage?: string;+ /** Every reason the route cannot run right now (legacy `reasonsWhyCannotEnqueue` equivalent). */+ validationReasons: string[];+}++export interface InvocationControllerState extends InvocationRoute {+ lastSubmittedRunId?: string;+}diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.tsindex e613ceb75f..e2e041c26c 100644--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts@@ -13,10 +13,12 @@* node-testable with a fake dispatch + a stubbed canvas pipeline.*/-import type { ModelConfig } from './models/types';-import type { Project, ResolvedInvocationRoute } from './types';+import type { ModelConfig } from '@features/models';+import type { ResolvedInvocationRoute } from '@workbench/invocationContracts';+import type { Project } from '@workbench/projectContracts';+import type { PrepareCanvasInvocationArgs } from './widgets/canvas/invoke/prepareCanvasInvocation';-import type { WorkbenchAction } from './workbenchState';+import type { WorkbenchCommands } from './workbenchStore';import { readCanvasCompositingSettings } from './widgets/canvas/invoke/canvasCompositing';import { readCanvasDenoisingStrength } from './widgets/canvas/invoke/canvasStrength';@@ -29,7 +31,7 @@ export interface SubmitResolvedInvocationDeps {project: Project;/** Loaded models (or `undefined` while loading), forwarded verbatim to both paths. */models: readonly ModelConfig[] | undefined;- dispatch: (action: WorkbenchAction) => void;+ commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;/*** The async canvas-invoke entry point, injected for testability. The real* implementation is fire-and-track (its returned promise is intentionally not@@ -39,7 +41,7 @@ export interface SubmitResolvedInvocationDeps {}export const submitResolvedInvocation = ({- dispatch,+ commands,models,prepareCanvasInvocation,project,@@ -54,7 +56,7 @@ export const submitResolvedInvocation = ({prepareCanvasInvocation({compositing: readCanvasCompositingSettings(getProjectWidgetValues(project, 'canvas')),destination: route.destination,- dispatch,+ commands,generateValues: getProjectWidgetValues(project, 'generate'),models,projectId: project.id,@@ -64,10 +66,9 @@ export const submitResolvedInvocation = ({return;}- dispatch({+ commands.generation.submitResolved({backendSupportsCancellation: true,models,route,- type: 'submitResolvedInvocationSnapshot',});};diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsxindex b05d34a5a6..a5d9e08b2c 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx@@ -1,17 +1,16 @@import { Box, Flex, type SystemStyleObject } from '@chakra-ui/react';+import { useCapabilities, UsersPage } from '@features/identity';+import { ModelsPage } from '@features/models';+import { NodesPage } from '@features/nodes';+import { Tabs } from '@platform/ui';import { useLocation, useNavigate } from '@tanstack/react-router';-import { useCapabilities } from '@workbench/auth/capabilities';-import { Tabs } from '@workbench/components/ui';import { BoxIcon, BlocksIcon, FolderIcon, UsersIcon, type LucideIcon } from 'lucide-react';import { useCallback, useMemo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import { LaunchpadNav } from './LaunchpadNav';import { LaunchpadTopBar } from './LaunchpadTopBar';-import { ModelsPage } from './pages/ModelsPage';-import { NodesPage } from './pages/NodesPage';import { ProjectsPage } from './pages/ProjectsPage';-import { UsersPage } from './pages/UsersPage';/*** The landing surface at `/`: a full-height shell with a slim section rail anddiff --git a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadNav.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadNav.tsxindex ecf41f4d01..61dc790b16 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadNav.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadNav.tsx@@ -1,7 +1,7 @@import type { LucideIcon } from 'lucide-react';import { Box, Icon, Stack, Text } from '@chakra-ui/react';-import { Tabs } from '@workbench/components/ui';+import { Tabs } from '@platform/ui';import { ResourceLinks } from './ResourceLinks';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsxindex 8b5e4748ae..562c02a9ca 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx@@ -1,11 +1,11 @@-import type { BackendConnectionStatus } from '@workbench/types';+import type { BackendConnectionStatus } from '@platform/transport/types';import { Box, Flex, HStack, Text } from '@chakra-ui/react';+import { AccountMenu } from '@features/identity';+import { useConnectionStatusSelector } from '@platform/transport/connectionStore';+import { Button } from '@platform/ui';+import { InvokeMark } from '@platform/ui/InvokeMark';import { Link, useSearch } from '@tanstack/react-router';-import { AccountMenu } from '@workbench/auth/components/AccountMenu';-import { useConnectionStatusSelector } from '@workbench/backend/connectionStore';-import { InvokeMark } from '@workbench/components/InvokeMark';-import { Button } from '@workbench/components/ui';import { SettingsButton } from '@workbench/settings/SettingsDialog';import { ArrowLeftIcon } from 'lucide-react';import { useMemo } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/ProjectCard.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/ProjectCard.tsxindex 8e96f173e7..0a79fcca9d 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/ProjectCard.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/ProjectCard.tsx@@ -1,6 +1,6 @@import { Box, Flex, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';+import { IconButton, ConfirmDialog, MenuContent, RenameDialog, toaster } from '@platform/ui';import { Link } from '@tanstack/react-router';-import { IconButton, ConfirmDialog, MenuContent, RenameDialog, toaster } from '@workbench/components/ui';import {deleteLibraryProject,duplicateLibraryProject,diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/ProjectsGrid.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/ProjectsGrid.tsxindex 4f9fee1631..cd2fe58bcf 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/ProjectsGrid.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/ProjectsGrid.tsx@@ -1,5 +1,5 @@import { Alert, SimpleGrid, Skeleton, Stack } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';+import { Button } from '@platform/ui';import { refreshProjectLibrary, useProjectLibrarySelector } from '@workbench/projects/library';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsxindex eaa082c9ea..e705b8d3ac 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx@@ -1,9 +1,9 @@import type { SystemStyleObject } from '@chakra-ui/react';import { Flex, Heading, HStack, Stack, Text } from '@chakra-ui/react';+import { useAuthSession } from '@features/identity';+import { Button, Scrollable, toaster } from '@platform/ui';import { Link, useNavigate } from '@tanstack/react-router';-import { useAuthSession } from '@workbench/auth/session';-import { Button, Scrollable, toaster } from '@workbench/components/ui';import { ProjectsGrid } from '@workbench/launchpad/ProjectsGrid';import { refreshProjectLibrary } from '@workbench/projects/library';import { importProjectFile, pickProjectFile } from '@workbench/projects/projectFile';diff --git a/invokeai/frontend/webv2/src/workbench/layoutContracts.ts b/invokeai/frontend/webv2/src/workbench/layoutContracts.tsnew file mode 100644index 0000000000..5cad4c79d8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/layoutContracts.ts@@ -0,0 +1,47 @@+import type { WidgetInstanceId, WidgetTypeId } from './widgetContracts';++export type BuiltInLayoutPresetId = 'canvas-default' | 'gallery' | 'workflow' | 'canvas';++export type LayoutPresetId = BuiltInLayoutPresetId | (string & {});++export type CenterViewId = 'canvas' | 'gallery' | 'preview' | 'workflow';++export interface PanelState {+ isLeftOpen: boolean;+ isRightOpen: boolean;+ isBottomOpen: boolean;+}++export type WidgetRegion = 'left' | 'right' | 'bottom' | 'center';++export interface WidgetRegionState {+ activeInstanceId: WidgetInstanceId;+ instanceIds: WidgetInstanceId[];+ isCollapsed: boolean;+ sizePx: number;+}++export interface ProjectLayoutState {+ presetId: LayoutPresetId;+ centerViewId: CenterViewId;+ panels: PanelState;+}++export interface LayoutPresetWidgetInstanceSnapshot {+ id: WidgetInstanceId;+ typeId: WidgetTypeId;+ title?: string;+}++export interface LayoutPresetSnapshot {+ layout: ProjectLayoutState;+ widgetInstances: Record<WidgetInstanceId, LayoutPresetWidgetInstanceSnapshot>;+ widgetRegions: Record<WidgetRegion, WidgetRegionState>;+}++export interface LayoutPreset {+ id: LayoutPresetId;+ label: string;+ isBuiltIn?: boolean;+ snapshot: LayoutPresetSnapshot;+}diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.tsindex 48e3d5c6f2..5636bc6615 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts@@ -2,11 +2,11 @@ import type {LayoutPreset,LayoutPresetSnapshot,LayoutPresetWidgetInstanceSnapshot,- Project,- WidgetInstanceId,WidgetRegion,WidgetRegionState,-} from './types';+} from '@workbench/layoutContracts';+import type { Project } from '@workbench/projectContracts';+import type { WidgetInstanceId } from '@workbench/widgetContracts';const widgetRegions: WidgetRegion[] = ['left', 'right', 'bottom', 'center'];diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.tsindex 8e621c7062..a4f73f7fc0 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts@@ -5,11 +5,10 @@ import type {LayoutPresetSnapshot,LayoutPresetWidgetInstanceSnapshot,PanelState,- WidgetInstanceId,WidgetRegion,WidgetRegionState,- WidgetTypeId,-} from './types';+} from '@workbench/layoutContracts';+import type { WidgetInstanceId, WidgetTypeId } from '@workbench/widgetContracts';const defaultBottomInstanceIds: WidgetInstanceId[] = ['server-status',diff --git a/invokeai/frontend/webv2/src/workbench/persistence.test.ts b/invokeai/frontend/webv2/src/workbench/persistence.test.tsindex f8f1949cc5..d10549ecb3 100644--- a/invokeai/frontend/webv2/src/workbench/persistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/persistence.test.ts@@ -1,7 +1,11 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { localStorageWorkbenchPersistence, migrateWorkbenchPersistenceSnapshot } from './persistence';-import { createInitialWorkbenchState, workbenchReducer } from './workbenchState';+import {+ hydratePersistedWorkbenchSnapshot,+ localStorageWorkbenchPersistence,+ serializeWorkbenchPersistenceSnapshot,+} from './persistence';+import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';const storage = new Map<string, string>();@@ -24,14 +28,14 @@ beforeEach(() => {describe('workbench persistence migration', () => {it('accepts current versioned workbench snapshots', () => {const state = createInitialWorkbenchState();- const snapshot = migrateWorkbenchPersistenceSnapshot({ savedAt: '2026-06-09T00:00:00.000Z', state, version: 1 });+ const snapshot = hydratePersistedWorkbenchSnapshot({ savedAt: '2026-06-09T00:00:00.000Z', state, version: 1 });expect(snapshot).toEqual({ savedAt: '2026-06-09T00:00:00.000Z', state, version: 1 });});it('migrates legacy schemaVersion snapshots to the authoritative version field', () => {const state = createInitialWorkbenchState();- const snapshot = migrateWorkbenchPersistenceSnapshot({+ const snapshot = hydratePersistedWorkbenchSnapshot({savedAt: '2026-06-09T00:00:00.000Z',schemaVersion: 1,state,@@ -43,14 +47,26 @@ describe('workbench persistence migration', () => {it('drops legacy error logs from persisted snapshots', () => {const state = { ...createInitialWorkbenchState(), errorLog: ['old error'] };- const snapshot = migrateWorkbenchPersistenceSnapshot({ savedAt: '2026-06-09T00:00:00.000Z', state, version: 1 });+ const snapshot = hydratePersistedWorkbenchSnapshot({ savedAt: '2026-06-09T00:00:00.000Z', state, version: 1 });expect(snapshot?.state).not.toHaveProperty('errorLog');});it('rejects unsupported persistence snapshots', () => {- expect(migrateWorkbenchPersistenceSnapshot({ state: createInitialWorkbenchState(), version: 999 })).toBeNull();- expect(migrateWorkbenchPersistenceSnapshot({ state: { projects: [] }, version: 1 })).toBeNull();+ expect(hydratePersistedWorkbenchSnapshot({ state: createInitialWorkbenchState(), version: 999 })).toBeNull();+ expect(hydratePersistedWorkbenchSnapshot({ state: { projects: [] }, version: 1 })).toBeNull();+ });++ it('maps the trusted live snapshot to a versioned untrusted storage contract', () => {+ const state = createInitialWorkbenchState();+ const persisted = serializeWorkbenchPersistenceSnapshot({+ savedAt: '2026-06-09T00:00:00.000Z',+ state,+ version: 1,+ });++ expect(persisted).toEqual({ savedAt: '2026-06-09T00:00:00.000Z', state, version: 1 });+ expect(hydratePersistedWorkbenchSnapshot(persisted)?.state).toEqual(state);});it('drops corrupt localStorage snapshots instead of throwing', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/persistence.ts b/invokeai/frontend/webv2/src/workbench/persistence.tsindex ebbb5c6cc8..a5a692614c 100644--- a/invokeai/frontend/webv2/src/workbench/persistence.ts+++ b/invokeai/frontend/webv2/src/workbench/persistence.ts@@ -1,6 +1,8 @@-import type { WorkbenchPersistenceSnapshot, WorkbenchState } from './types';+import type { HydratedWorkbenchSnapshot, PersistedWorkbenchSnapshotV1 } from '@workbench/persistenceContracts';+import type { WorkbenchState } from '@workbench/projectContracts';++import { getUserStorageScope } from '@features/identity';-import { getUserStorageScope } from './auth/session';import { timeWorkbenchPerf } from './performanceMarks';const BASE_STORAGE_KEY = 'invokeai:v7:webv2:workbench';@@ -14,8 +16,8 @@ const WORKBENCH_SCHEMA_VERSION = 1;const getStorageKey = (): string => `${BASE_STORAGE_KEY}${getUserStorageScope()}`;export interface WorkbenchPersistenceService {- loadWorkbench(): Promise<WorkbenchPersistenceSnapshot | null>;- saveWorkbench(state: WorkbenchState): Promise<WorkbenchPersistenceSnapshot>;+ loadWorkbench(): Promise<HydratedWorkbenchSnapshot | null>;+ saveWorkbench(state: WorkbenchState): Promise<HydratedWorkbenchSnapshot>;clearWorkbench(): Promise<void>;}@@ -30,7 +32,7 @@ export const stripTransientWorkbenchState = (state: WorkbenchState): WorkbenchSt};};-const createSnapshot = (state: WorkbenchState): WorkbenchPersistenceSnapshot => ({+const createSnapshot = (state: WorkbenchState): HydratedWorkbenchSnapshot => ({savedAt: new Date().toISOString(),state: stripTransientWorkbenchState(state),version: WORKBENCH_SCHEMA_VERSION,@@ -46,12 +48,12 @@ const isWorkbenchState = (value: unknown): value is WorkbenchState => {return Array.isArray(record.projects) && typeof record.activeProjectId === 'string';};-export const migrateWorkbenchPersistenceSnapshot = (value: unknown): WorkbenchPersistenceSnapshot | null => {+export const hydratePersistedWorkbenchSnapshot = (value: unknown): HydratedWorkbenchSnapshot | null => {if (!value || typeof value !== 'object') {return null;}- const record = value as Partial<WorkbenchPersistenceSnapshot> & { schemaVersion?: number };+ const record = value as Partial<PersistedWorkbenchSnapshotV1> & { schemaVersion?: number };const version = record.version ?? record.schemaVersion;if (version !== WORKBENCH_SCHEMA_VERSION || !isWorkbenchState(record.state)) {@@ -65,6 +67,14 @@ export const migrateWorkbenchPersistenceSnapshot = (value: unknown): WorkbenchPe};};+export const serializeWorkbenchPersistenceSnapshot = (+ snapshot: HydratedWorkbenchSnapshot+): PersistedWorkbenchSnapshotV1 => ({+ savedAt: snapshot.savedAt,+ state: snapshot.state,+ version: WORKBENCH_SCHEMA_VERSION,+});+export const localStorageWorkbenchPersistence: WorkbenchPersistenceService = {clearWorkbench() {if (!isBrowser()) {@@ -87,7 +97,7 @@ export const localStorageWorkbenchPersistence: WorkbenchPersistenceService = {}try {- return Promise.resolve(migrateWorkbenchPersistenceSnapshot(JSON.parse(value)));+ return Promise.resolve(hydratePersistedWorkbenchSnapshot(JSON.parse(value)));} catch {window.localStorage.removeItem(getStorageKey());@@ -107,7 +117,7 @@ export const localStorageWorkbenchPersistence: WorkbenchPersistenceService = {timeWorkbenchPerf('workbench:persistence-localstorage-stringify',{ area: 'persistence', kind: 'workbench', projectId: state.activeProjectId },- () => JSON.stringify(snapshot)+ () => JSON.stringify(serializeWorkbenchPersistenceSnapshot(snapshot))));} catch {diff --git a/invokeai/frontend/webv2/src/workbench/persistenceContracts.ts b/invokeai/frontend/webv2/src/workbench/persistenceContracts.tsnew file mode 100644index 0000000000..9880e7d671--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/persistenceContracts.ts@@ -0,0 +1,14 @@+import type { WorkbenchState } from './projectContracts';++export interface HydratedWorkbenchSnapshot {+ version: 1;+ savedAt: string;+ state: WorkbenchState;+}++/** Versioned storage wire shape. `state` is untrusted until the persistence adapter maps it. */+export interface PersistedWorkbenchSnapshotV1 {+ version: 1;+ savedAt: string;+ state: unknown;+}diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.tsnew file mode 100644index 0000000000..3b0d1a1b94--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts@@ -0,0 +1,367 @@+import type { HydratedWorkbenchSnapshot } from '@workbench/persistenceContracts';+import type { WorkbenchState } from '@workbench/projectContracts';++import { describe, expect, it, vi } from 'vitest';++import type { WorkbenchSaveResult } from './projects/syncedPersistence';++import {+ createWorkbenchPersistenceRuntime,+ type PersistenceAggregatePort,+ type PersistenceClock,+ type WorkbenchPersistencePort,+} from './persistenceRuntime';+import { createInitialWorkbenchState } from './workbenchState.testing';++const flushPromises = async (): Promise<void> => {+ await Promise.resolve();+ await Promise.resolve();+};++const deferred = <T>() => {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, reject, resolve };+};++const snapshot = (state: WorkbenchState, savedAt = '2026-07-17T00:00:00.000Z'): HydratedWorkbenchSnapshot => ({+ savedAt,+ state,+ version: 1,+});++const saveResult = (state: WorkbenchState, savedAt?: string): WorkbenchSaveResult => ({+ conflicts: [],+ hasPendingChanges: false,+ snapshot: snapshot(state, savedAt),+});++class FakeClock implements PersistenceClock {+ private nextId = 0;+ private readonly callbacks = new Map<number, () => void>();++ clearTimeout(id: unknown): void {+ this.callbacks.delete(id as number);+ }++ runAll(): void {+ const callbacks = [...this.callbacks.values()];+ this.callbacks.clear();+ for (const callback of callbacks) {+ callback();+ }+ }++ setTimeout(callback: () => void): unknown {+ this.nextId += 1;+ this.callbacks.set(this.nextId, callback);+ return this.nextId;+ }+}++const createAggregate = (initialState = createInitialWorkbenchState()) => {+ let state = structuredClone(initialState);+ let revision = 0;+ let hasHydrated = false;+ const listeners = new Set<() => void>();+ const events: string[] = [];+ const emit = () => {+ for (const listener of listeners) {+ listener();+ }+ };+ const port: PersistenceAggregatePort = {+ getPersistedRevision: () => revision,+ getState: () => state,+ hydrate: (nextState) => {+ state = structuredClone(nextState);+ revision += 1;+ events.push('hydrate');+ emit();+ },+ notifyProjectNotFound: () => events.push('not-found'),+ reconcileConflict: (conflict) => {+ state = {+ ...state,+ projects: [+ ...state.projects.filter((project) => project.id !== conflict.projectId),+ conflict.serverProject,+ conflict.recoveredProject,+ ],+ };+ revision += 1;+ events.push('conflict');+ emit();+ },+ reportLoadError: (error) => events.push(`load-error:${error}`),+ saveFailed: (error) => events.push(`save-failed:${error}`),+ saveStarted: () => events.push('save-started'),+ saveSucceeded: (savedAt) => events.push(`save-succeeded:${savedAt}`),+ setHasHydrated: (next) => {+ hasHydrated = next;+ events.push(`hydrated:${next}`);+ emit();+ },+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };++ return {+ connect() {+ state = { ...state, backendConnection: { status: 'connected' } };+ emit();+ },+ edit(name = 'Edited') {+ state = {+ ...state,+ projects: state.projects.map((project, index) => (index === 0 ? { ...project, name } : project)),+ };+ revision += 1;+ emit();+ },+ events,+ get hasHydrated() {+ return hasHydrated;+ },+ get revision() {+ return revision;+ },+ get state() {+ return state;+ },+ port,+ };+};++const createPersistence = (load: WorkbenchPersistencePort['loadWorkbench']) => {+ let pending = false;+ const persistence: WorkbenchPersistencePort = {+ hasPendingChanges: () => pending,+ loadWorkbench: vi.fn(load),+ saveWorkbench: vi.fn((state) => Promise.resolve(saveResult(state))),+ };+ return {+ persistence,+ setPending(next: boolean) {+ pending = next;+ },+ };+};++describe('Workbench persistence runtime', () => {+ it('hydrates before enabling saves and publishes lifecycle status', async () => {+ const aggregate = createAggregate();+ const loadedState = createInitialWorkbenchState();+ loadedState.projects[0]!.name = 'Loaded';+ const { persistence } = createPersistence(() => Promise.resolve(snapshot(loadedState)));+ const clock = new FakeClock();+ const runtime = createWorkbenchPersistenceRuntime({ aggregate: aggregate.port, clock, persistence });+ const phases: string[] = [];+ runtime.subscribe(() => phases.push(runtime.getSnapshot().phase));++ runtime.start();+ expect(runtime.getSnapshot().phase).toBe('hydrating');+ expect(persistence.saveWorkbench).not.toHaveBeenCalled();+ await flushPromises();++ expect(aggregate.state.projects[0]?.name).toBe('Loaded');+ expect(aggregate.hasHydrated).toBe(true);+ expect(phases).toEqual(['hydrating', 'idle']);+ clock.runAll();+ expect(persistence.saveWorkbench).not.toHaveBeenCalled();+ });++ it('reports load failure, hydrates the shell, and remains usable', async () => {+ const aggregate = createAggregate();+ const { persistence } = createPersistence(() => Promise.reject(new Error('server unavailable')));+ const runtime = createWorkbenchPersistenceRuntime({+ aggregate: aggregate.port,+ clock: new FakeClock(),+ persistence,+ });++ runtime.start();+ await flushPromises();++ expect(aggregate.events).toContain('load-error:server unavailable');+ expect(aggregate.hasHydrated).toBe(true);+ expect(runtime.getSnapshot()).toEqual({ error: null, phase: 'idle' });+ });++ it('preserves an edit made during load and saves it only after load settles', async () => {+ const aggregate = createAggregate();+ const load = deferred<HydratedWorkbenchSnapshot | null>();+ const { persistence } = createPersistence(() => load.promise);+ const clock = new FakeClock();+ const runtime = createWorkbenchPersistenceRuntime({ aggregate: aggregate.port, clock, persistence });++ runtime.start();+ aggregate.edit('Local edit during load');+ clock.runAll();+ expect(persistence.saveWorkbench).not.toHaveBeenCalled();++ const remote = createInitialWorkbenchState();+ remote.projects[0]!.name = 'Remote';+ load.resolve(snapshot(remote));+ await flushPromises();+ clock.runAll();++ expect(aggregate.state.projects[0]?.name).toBe('Local edit during load');+ expect(persistence.saveWorkbench).toHaveBeenCalledWith(+ expect.objectContaining({ projects: [expect.objectContaining({ name: 'Local edit during load' })] })+ );+ });++ it('debounces edits and ignores stale completions after a newer revision', async () => {+ const aggregate = createAggregate();+ const { persistence } = createPersistence(() => Promise.resolve(null));+ const first = deferred<WorkbenchSaveResult>();+ const second = deferred<WorkbenchSaveResult>();+ vi.mocked(persistence.saveWorkbench)+ .mockImplementationOnce(() => first.promise)+ .mockImplementationOnce(() => second.promise);+ const clock = new FakeClock();+ const runtime = createWorkbenchPersistenceRuntime({ aggregate: aggregate.port, clock, persistence });++ runtime.start();+ await flushPromises();+ aggregate.edit('First');+ aggregate.edit('Second');+ expect(persistence.saveWorkbench).not.toHaveBeenCalled();+ clock.runAll();+ expect(persistence.saveWorkbench).toHaveBeenCalledTimes(1);++ aggregate.edit('Third');+ clock.runAll();+ first.resolve(saveResult(aggregate.state, 'stale'));+ await flushPromises();+ expect(aggregate.events).not.toContain('save-succeeded:stale');++ second.resolve(saveResult(aggregate.state, 'current'));+ await flushPromises();+ expect(aggregate.events).toContain('save-succeeded:current');+ });++ it('holds a failed revision until a new edit and then retries', async () => {+ const aggregate = createAggregate();+ const { persistence } = createPersistence(() => Promise.resolve(null));+ vi.mocked(persistence.saveWorkbench).mockRejectedValueOnce(new Error('offline'));+ const clock = new FakeClock();+ const runtime = createWorkbenchPersistenceRuntime({ aggregate: aggregate.port, clock, persistence });++ runtime.start();+ await flushPromises();+ aggregate.edit();+ clock.runAll();+ await flushPromises();+ expect(aggregate.events).toContain('save-failed:offline');++ clock.runAll();+ expect(persistence.saveWorkbench).toHaveBeenCalledTimes(1);+ aggregate.edit('Retry revision');+ clock.runAll();+ await flushPromises();+ expect(persistence.saveWorkbench).toHaveBeenCalledTimes(2);+ });++ it('replays pending work immediately on reconnect and rejects a stale replay', async () => {+ const aggregate = createAggregate();+ const { persistence, setPending } = createPersistence(() => Promise.resolve(null));+ const replay = deferred<WorkbenchSaveResult>();+ vi.mocked(persistence.saveWorkbench).mockImplementationOnce(() => replay.promise);+ const clock = new FakeClock();+ const runtime = createWorkbenchPersistenceRuntime({ aggregate: aggregate.port, clock, persistence });++ runtime.start();+ await flushPromises();+ aggregate.edit('Offline edit');+ setPending(true);+ aggregate.connect();+ expect(persistence.saveWorkbench).toHaveBeenCalledTimes(1);++ aggregate.edit('Edit during replay');+ replay.resolve(saveResult(aggregate.state, 'stale-replay'));+ await flushPromises();+ expect(aggregate.events).not.toContain('save-succeeded:stale-replay');+ clock.runAll();+ expect(persistence.saveWorkbench).toHaveBeenCalledTimes(2);+ });++ it('applies conflict recovery and schedules the reconciled fork', async () => {+ const aggregate = createAggregate();+ const { persistence } = createPersistence(() => Promise.resolve(null));+ const clock = new FakeClock();+ const runtime = createWorkbenchPersistenceRuntime({ aggregate: aggregate.port, clock, persistence });++ runtime.start();+ await flushPromises();+ aggregate.edit();+ const original = aggregate.state.projects[0]!;+ vi.mocked(persistence.saveWorkbench).mockResolvedValueOnce({+ conflicts: [+ {+ projectId: original.id,+ recoveredProject: { ...original, id: 'recovered', name: 'Recovered' },+ serverProject: { ...original, name: 'Server' },+ },+ ],+ hasPendingChanges: false,+ snapshot: snapshot(aggregate.state),+ });+ clock.runAll();+ await flushPromises();++ expect(aggregate.events).toContain('conflict');+ expect(aggregate.state.projects.map((project) => project.name)).toEqual(['Server', 'Recovered']);+ clock.runAll();+ expect(persistence.saveWorkbench).toHaveBeenCalledTimes(2);+ });++ it('cancels timers and ignores load/save completions after disposal', async () => {+ const aggregate = createAggregate();+ const load = deferred<HydratedWorkbenchSnapshot | null>();+ const { persistence } = createPersistence(() => load.promise);+ const clock = new FakeClock();+ const runtime = createWorkbenchPersistenceRuntime({ aggregate: aggregate.port, clock, persistence });+ const listener = vi.fn();+ runtime.subscribe(listener);++ runtime.start();+ runtime.dispose();+ load.resolve(snapshot(createInitialWorkbenchState()));+ await flushPromises();+ aggregate.edit();+ clock.runAll();++ expect(runtime.getSnapshot().phase).toBe('disposed');+ expect(aggregate.hasHydrated).toBe(false);+ expect(persistence.saveWorkbench).not.toHaveBeenCalled();+ expect(listener).toHaveBeenCalledTimes(1);+ });++ it('hydrates through a fresh instance after a prior one was disposed mid-load (StrictMode remount)', async () => {+ const aggregate = createAggregate();+ const loadedState = createInitialWorkbenchState();+ loadedState.projects[0]!.name = 'Loaded';+ const { persistence } = createPersistence(() => Promise.resolve(snapshot(loadedState)));+ const clock = new FakeClock();++ const first = createWorkbenchPersistenceRuntime({ aggregate: aggregate.port, clock, persistence });+ first.start();+ first.dispose();++ const second = createWorkbenchPersistenceRuntime({ aggregate: aggregate.port, clock, persistence });+ second.start();+ await flushPromises();++ expect(aggregate.hasHydrated).toBe(true);+ expect(aggregate.state.projects[0]?.name).toBe('Loaded');+ expect(second.getSnapshot()).toEqual({ error: null, phase: 'idle' });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.tsnew file mode 100644index 0000000000..08547fd390--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts@@ -0,0 +1,256 @@+import type { HydratedWorkbenchSnapshot } from '@workbench/persistenceContracts';+import type { WorkbenchState } from '@workbench/projectContracts';++import type { WorkbenchLoadOptions, WorkbenchSaveResult } from './projects/syncedPersistence';++export interface PersistenceAggregatePort {+ getPersistedRevision(): number;+ getState(): WorkbenchState;+ hydrate(state: WorkbenchState): void;+ notifyProjectNotFound(): void;+ reconcileConflict(conflict: WorkbenchSaveResult['conflicts'][number]): void;+ reportLoadError(error: string): void;+ saveFailed(error: string): void;+ saveStarted(): void;+ saveSucceeded(savedAt: string): void;+ setHasHydrated(hasHydrated: boolean): void;+ subscribe(listener: () => void): () => void;+}++export interface WorkbenchPersistencePort {+ hasPendingChanges(): boolean;+ loadWorkbench(options?: WorkbenchLoadOptions): Promise<HydratedWorkbenchSnapshot | null>;+ saveWorkbench(state: WorkbenchState): Promise<WorkbenchSaveResult>;+}++export interface PersistenceClock {+ clearTimeout(id: unknown): void;+ setTimeout(callback: () => void, delayMs: number): unknown;+}++export interface PersistenceRuntimeSnapshot {+ error: string | null;+ phase: 'disposed' | 'hydrating' | 'idle' | 'saving';+}++export interface WorkbenchPersistenceRuntime {+ dispose(): void;+ getSnapshot(): PersistenceRuntimeSnapshot;+ start(): void;+ subscribe(listener: () => void): () => void;+}++const browserClock: PersistenceClock = {+ clearTimeout: (id) => window.clearTimeout(id as number),+ setTimeout: (callback, delayMs) => window.setTimeout(callback, delayMs),+};++const errorMessage = (error: unknown, fallback: string): string => (error instanceof Error ? error.message : fallback);++export const createWorkbenchPersistenceRuntime = ({+ aggregate,+ clock = browserClock,+ loadOptions,+ persistence,+ saveDelayMs = 500,+}: {+ aggregate: PersistenceAggregatePort;+ clock?: PersistenceClock;+ loadOptions?: WorkbenchLoadOptions;+ persistence: WorkbenchPersistencePort;+ saveDelayMs?: number;+}): WorkbenchPersistenceRuntime => {+ let snapshot: PersistenceRuntimeSnapshot = { error: null, phase: 'idle' };+ const listeners = new Set<() => void>();+ let started = false;+ let disposed = false;+ let hasLoaded = false;+ let generation = 0;+ let timeoutId: unknown | null = null;+ let scheduledRevision: number | null = null;+ let failedRevision: number | null = null;+ let lastSavedRevision = aggregate.getPersistedRevision();+ let previousConnectionStatus = aggregate.getState().backendConnection.status;+ let unsubscribeAggregate: (() => void) | null = null;++ const publish = (next: PersistenceRuntimeSnapshot): void => {+ if (disposed || (snapshot.error === next.error && snapshot.phase === next.phase)) {+ return;+ }+ snapshot = next;+ for (const listener of listeners) {+ listener();+ }+ };++ const clearScheduledSave = (): void => {+ if (timeoutId !== null) {+ clock.clearTimeout(timeoutId);+ timeoutId = null;+ }+ };++ const applySaveResult = (result: WorkbenchSaveResult): void => {+ for (const conflict of result.conflicts) {+ aggregate.reconcileConflict(conflict);+ }+ };++ const isStaleSave = (revision: number, saveGeneration: number, requireCurrentRevision: boolean): boolean =>+ disposed ||+ saveGeneration !== generation ||+ (requireCurrentRevision && aggregate.getPersistedRevision() !== revision);++ const completeSave = (+ result: WorkbenchSaveResult,+ revision: number,+ saveGeneration: number,+ requireCurrentRevision: boolean+ ): void => {+ if (isStaleSave(revision, saveGeneration, requireCurrentRevision)) {+ return;+ }+ lastSavedRevision = revision;+ failedRevision = null;+ scheduledRevision = null;+ aggregate.saveSucceeded(result.snapshot.savedAt);+ applySaveResult(result);+ publish({ error: null, phase: 'idle' });+ };++ const failSave = (+ error: unknown,+ revision: number,+ saveGeneration: number,+ requireCurrentRevision: boolean+ ): void => {+ if (isStaleSave(revision, saveGeneration, requireCurrentRevision)) {+ return;+ }+ const message = errorMessage(error, 'Failed to autosave workbench.');+ failedRevision = revision;+ scheduledRevision = null;+ aggregate.saveFailed(message);+ publish({ error: message, phase: 'idle' });+ };++ const save = (requireCurrentRevision: boolean): void => {+ if (disposed || !hasLoaded) {+ return;+ }+ timeoutId = null;+ const state = aggregate.getState();+ const revision = aggregate.getPersistedRevision();+ generation += 1;+ const saveGeneration = generation;++ aggregate.saveStarted();+ publish({ error: null, phase: 'saving' });+ void persistence+ .saveWorkbench(state)+ .then((result) => completeSave(result, revision, saveGeneration, requireCurrentRevision))+ .catch((error: unknown) => failSave(error, revision, saveGeneration, requireCurrentRevision));+ };++ const scheduleSave = (): void => {+ if (disposed || !hasLoaded) {+ return;+ }+ const revision = aggregate.getPersistedRevision();+ if (revision === lastSavedRevision || revision === scheduledRevision || revision === failedRevision) {+ return;+ }+ failedRevision = null;+ scheduledRevision = revision;+ generation += 1;+ clearScheduledSave();+ timeoutId = clock.setTimeout(() => save(false), saveDelayMs);+ };++ const onAggregateChange = (): void => {+ if (disposed) {+ return;+ }+ const connectionStatus = aggregate.getState().backendConnection.status;+ if (connectionStatus !== previousConnectionStatus) {+ previousConnectionStatus = connectionStatus;+ if (connectionStatus === 'connected' && hasLoaded && persistence.hasPendingChanges()) {+ clearScheduledSave();+ scheduledRevision = aggregate.getPersistedRevision();+ save(true);+ return;+ }+ }+ scheduleSave();+ };++ const load = async (): Promise<void> => {+ const loadGeneration = generation;+ const revisionBeforeLoad = aggregate.getPersistedRevision();+ publish({ error: null, phase: 'hydrating' });+ let loadedSnapshot: HydratedWorkbenchSnapshot | null = null;++ try {+ loadedSnapshot = await persistence.loadWorkbench(loadOptions);+ if (disposed || loadGeneration !== generation) {+ return;+ }++ // A persisted edit made while loading is newer than the loaded snapshot.+ // Preserve it and let the first autosave reconcile it with remote storage.+ const wasEditedDuringLoad = aggregate.getPersistedRevision() !== revisionBeforeLoad;+ if (loadedSnapshot && !wasEditedDuringLoad) {+ const isPendingSnapshot = persistence.hasPendingChanges();+ aggregate.hydrate(loadedSnapshot.state);+ if (!isPendingSnapshot) {+ lastSavedRevision = aggregate.getPersistedRevision();+ }+ }++ const requestedId = loadOptions?.openProjectId;+ const projects = loadedSnapshot?.state.projects ?? aggregate.getState().projects;+ if (requestedId && !projects.some((project) => project.id === requestedId)) {+ aggregate.notifyProjectNotFound();+ }+ } catch (error) {+ if (!disposed) {+ aggregate.reportLoadError(errorMessage(error, 'Failed to load persisted workbench.'));+ }+ } finally {+ if (!disposed && loadGeneration === generation) {+ hasLoaded = true;+ aggregate.setHasHydrated(true);+ publish({ error: null, phase: 'idle' });+ scheduleSave();+ }+ }+ };++ return {+ dispose() {+ if (disposed) {+ return;+ }+ disposed = true;+ generation += 1;+ clearScheduledSave();+ unsubscribeAggregate?.();+ unsubscribeAggregate = null;+ snapshot = { error: null, phase: 'disposed' };+ listeners.clear();+ },+ getSnapshot: () => snapshot,+ start() {+ if (started || disposed) {+ return;+ }+ started = true;+ unsubscribeAggregate = aggregate.subscribe(onAggregateChange);+ void load();+ },+ subscribe(listener) {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/projectContracts.ts b/invokeai/frontend/webv2/src/workbench/projectContracts.tsnew file mode 100644index 0000000000..c01c7b993e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projectContracts.ts@@ -0,0 +1,143 @@+import type { ProjectGraphState } from '@features/workflow/contracts';+import type { BackendConnectionStatus } from '@platform/transport/types';++import type { CanvasStateContractV2 } from './canvas-engine/api';+import type { GraphContract } from './graphContracts';+import type { InvocationControllerState } from './invocationContracts';+import type {+ LayoutPreset,+ LayoutPresetId,+ ProjectLayoutState,+ WidgetRegion,+ WidgetRegionState,+} from './layoutContracts';+import type { WorkbenchQueueState } from './queueHistoryContracts';+import type { ProjectSettings } from './settings/contracts';+import type { WidgetFailure, WidgetInstanceContract, WidgetInstanceId, WidgetTypeId } from './widgetContracts';++export type ProjectEventType =+ | 'project-created'+ | 'layout-updated'+ | 'invocation-updated'+ | 'queue-submitted'+ | 'canvas-layer-accepted'+ | 'graph-replaced'+ | 'graph-snapshot-saved';++export interface Project {+ id: string;+ name: string;+ /**+ * Set on recovery forks created when a save loses a revision race: the id+ * of the root project this recovered from (chains collapse to the root, so+ * a recovery of a recovery still points at the original).+ */+ recoveryOf?: string;+ recoveredAt?: string;+ settings: ProjectSettings;+ layout: ProjectLayoutState;+ invocation: InvocationControllerState;+ /** The one active project graph: an editable workflow document, compiled to a `GraphContract` at invoke time. */+ projectGraph: ProjectGraphState;+ widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;+ widgetRegions: Record<WidgetRegion, WidgetRegionState>;+ widgetGraphs: Partial<Record<WidgetTypeId, GraphContract>>;+ canvas: CanvasStateContractV2;+ graphHistory: GraphHistorySnapshot[];+ promptHistory: PromptHistoryItem[];+ undoRedo: UndoRedoHistory;+ queue: WorkbenchQueueState;+ events: ProjectEvent[];+}++export interface WorkbenchState {+ projects: Project[];+ activeProjectId: string;+ backendConnection: BackendConnectionState;+ notifications: WorkbenchNotification[];+ autosave: AutosaveState;+ account: AccountState;+ widgetFailures: WidgetFailure[];+}++export interface BackendConnectionState {+ status: BackendConnectionStatus;+ error?: string;+ lastConnectedAt?: string;+ lastDisconnectedAt?: string;+}++export type WorkbenchNotificationKind = 'error' | 'success' | 'info';++export interface WorkbenchNotification {+ id: string;+ kind: WorkbenchNotificationKind;+ title: string;+ message?: string;+ createdAt: string;+ projectId?: string;+ isRead: boolean;+}++/**+ * One entry of the project's graph history. Queue submissions record the+ * compiled `graph`; workflow snapshots (manual save, pre-replacement) record+ * the editable `document`, which is what makes them restorable.+ */+export interface GraphHistorySnapshot {+ id: string;+ createdAt: string;+ label: string;+ graph?: GraphContract;+ document?: ProjectGraphState;+}++export interface PromptHistoryItem {+ positivePrompt: string;+ negativePrompt: string | null;+}++export interface UndoRedoEntry {+ id: string;+ createdAt: string;+ label: string;+ project: ProjectUndoSnapshot;+}++/**+ * Project-level undo snapshot. Deliberately excludes `canvas`: the canvas+ * rendering engine owns its own pixel-patch history, so project undo/redo+ * passes the live `project.canvas` through untouched (see `restoreUndoSnapshot`).+ */+export interface ProjectUndoSnapshot {+ layout: ProjectLayoutState;+ invocation: InvocationControllerState;+ projectGraph: ProjectGraphState;+ widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;+ widgetRegions: Record<WidgetRegion, WidgetRegionState>;+ widgetGraphs: Partial<Record<WidgetTypeId, GraphContract>>;+}++export interface UndoRedoHistory {+ past: UndoRedoEntry[];+ future: UndoRedoEntry[];+}++export interface ProjectEvent {+ id: string;+ type: ProjectEventType;+ createdAt: string;+ summary: string;+ runId?: string;+}++export interface AutosaveState {+ status: 'idle' | 'saving' | 'saved' | 'error';+ lastSavedAt?: string;+ error?: string;+}++export interface AccountState {+ activeLayoutPresetId: LayoutPresetId;+ customLayoutPresets?: LayoutPreset[];+}diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.ts b/invokeai/frontend/webv2/src/workbench/projects/api.tsindex 22dc8c55fe..5deae9daec 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.ts@@ -1,4 +1,4 @@-import { ApiError, apiFetch, apiFetchJson } from '@workbench/backend/http';+import { ApiError, apiFetch, apiFetchJson } from '@platform/transport/http';/*** REST surface for server-side project persistence (`/api/v1/projects`) anddiff --git a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsxindex d5d4ef07b5..6ebce8a2f5 100644--- a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx@@ -1,41 +1,45 @@import { Dialog, Icon, Portal, Spinner, Stack, Text } from '@chakra-ui/react';-import { Button, CloseButton, Row, Scrollable } from '@workbench/components/ui';+import { flushGenerateDrafts } from '@features/generation/drafts';+import { useMountEffect } from '@platform/react/useMountEffect';+import { areArraysEqual } from '@platform/state/selectors';+import { Button, CloseButton, Row, Scrollable } from '@platform/ui';import { formatRelativeTime } from '@workbench/launchpad/formatRelativeTime';import { refreshProjectLibrary, useProjectLibrarySelector, type ProjectSummary } from '@workbench/projects/library';import { importProjectFile, pickProjectFile } from '@workbench/projects/projectFile';-import { adoptProjectRecord, hydrateProjectFromServer } from '@workbench/projects/syncedPersistence';import { useNotify } from '@workbench/useNotify';-import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';-import { useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';-import { areArraysEqual } from '@workbench/workbenchSelectors';+import {+ useWorkbenchCommands,+ useWorkbenchPersistenceService,+ useWorkbenchSelector,+} from '@workbench/WorkbenchContext';import { ArrowRightIcon, FileUpIcon } from 'lucide-react';-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';const disabledRowStyles = { opacity: 0.6 } as const;+const ProjectLibraryRefresh = () => {+ useMountEffect(() => {+ void refreshProjectLibrary();+ });++ return null;+};+/*** "Open project…" from the tab bar: the saved projects that are not already* open as tabs, plus import. Selecting one hydrates its document from the* library and opens it in place — no navigation, the editor stays mounted.*/export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) => {- const projectIds = useWorkbenchSelector(- (snapshot) => snapshot.state.projects.map((project) => project.id),- areArraysEqual- );- const dispatch = useWorkbenchDispatch();+ const projectIds = useWorkbenchSelector((snapshot) => snapshot.projects.map((project) => project.id), areArraysEqual);+ const { projects } = useWorkbenchCommands();+ const persistence = useWorkbenchPersistenceService();const notify = useNotify();const { t } = useTranslation();const summaries = useProjectLibrarySelector((snapshot) => snapshot.summaries);const [busyProjectId, setBusyProjectId] = useState<string | null>(null);- useEffect(() => {- if (isOpen) {- void refreshProjectLibrary();- }- }, [isOpen]);-const openProjectIds = useMemo(() => new Set(projectIds), [projectIds]);const available = useMemo(() => summaries.filter((summary) => !openProjectIds.has(summary.id)),@@ -46,7 +50,7 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClosasync (summary: ProjectSummary) => {setBusyProjectId(summary.id);- const project = await hydrateProjectFromServer(summary.id);+ const project = await persistence.hydrateProjectFromServer(summary.id);setBusyProjectId(null);@@ -58,10 +62,10 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClos}flushGenerateDrafts();- dispatch({ project, type: 'openProject' });+ projects.open(project);onClose();},- [dispatch, notify, onClose, t]+ [notify, onClose, persistence, projects, t]);const handleImport = useCallback(async () => {@@ -73,17 +77,17 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClostry {const record = await importProjectFile(file);- const project = adoptProjectRecord(record);+ const project = persistence.adoptProjectRecord(record);if (project) {flushGenerateDrafts();- dispatch({ project, type: 'openProject' });+ projects.open(project);onClose();}} catch (error) {notify.error(t('projects.importFailed'), error instanceof Error ? error.message : undefined);}- }, [dispatch, notify, onClose, t]);+ }, [notify, onClose, persistence, projects, t]);const handleOpenChange = useCallback((event: { open: boolean }) => {@@ -98,6 +102,7 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClosreturn (<Dialog.Root lazyMount open={isOpen} placement="center" size="sm" unmountOnExit onOpenChange={handleOpenChange}>+ {isOpen ? <ProjectLibraryRefresh /> : null}<Portal><Dialog.Backdrop /><Dialog.Positioner>diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsxindex ed03ba995c..2c611249f1 100644--- a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsx@@ -1,29 +1,21 @@-/* eslint-disable react/react-compiler */-import type { Project, QueueItem, WidgetRegion } from '@workbench/types';--import { Icon, Menu, Portal, Separator } from '@chakra-ui/react';-import { useModelLoads } from '@workbench/backend/modelLoadStore';-import { useQueueItemProgress } from '@workbench/backend/progressStore';+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { Project } from '@workbench/projectContracts';++import { Flex, Icon, Menu, Portal, ScrollArea, Separator } from '@chakra-ui/react';+import { flushGenerateDrafts } from '@features/generation/drafts';+import { useModelLoads } from '@features/models';+import { getProjectQueueIndicatorState, type QueueItem } from '@features/queue/contracts';+import { useQueueItemProgress } from '@features/queue/react';+import { CloseButton, IconButton, ConfirmDialog, MenuContent, RenameDialog, Tabs, Tooltip } from '@platform/ui';import { QueueCircularProgress } from '@workbench/components/QueueProgressIndicator';-import {- CloseButton,- IconButton,- ConfirmDialog,- MenuContent,- RenameDialog,- Tabs,- Tooltip,-} from '@workbench/components/ui';import { exportOpenProject } from '@workbench/projects/projectFile';import { useProjectActions } from '@workbench/projects/useProjectActions';-import { getProjectQueueIndicatorState } from '@workbench/queueSummary';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';-import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';import {useActiveProjectSelector,- useWorkbenchDispatch,+ useWorkbenchCommands,+ useWorkbenchQueries,useWorkbenchSelector,- useWorkbenchStore,} from '@workbench/WorkbenchContext';import {FileDownIcon,@@ -35,7 +27,7 @@ import {Trash2Icon,XIcon,} from 'lucide-react';-import { useCallback, useMemo, useRef, useState, type MouseEvent } from 'react';+import { useCallback, useMemo, useState, type MouseEvent } from 'react';import { useTranslation } from 'react-i18next';import { OpenProjectDialog } from './OpenProjectDialog';@@ -63,6 +55,13 @@ const selectProjectTabSummaries = (projects: readonly Project[]): ProjectTabSummconst deleteMenuItemHover = { bg: 'bg.error', color: 'fg.error' } as const;+// `min-width: 0` lets the strip shrink in flex layout, but does not stop its+// content from propagating into the tab list's intrinsic (shrink-to-fit)+// width — `contain: inline-size` zeroes that contribution so a long tab row+// can never stretch the list over the top bar's other controls. Same rule as+// the preview filmstrip.+const TAB_STRIP_CONTAIN_CSS = { contain: 'inline-size' } as const;+/*** Document-style tabs for the open projects (the session), immediately right* of the Invoke control. Tabs are not the library: closing one only removes@@ -77,32 +76,28 @@ const deleteMenuItemHover = { bg: 'bg.error', color: 'fg.error' } as const;export const ProjectTabs = () => {const { t } = useTranslation();const projectTabSummaries = useWorkbenchSelector(- (snapshot) => selectProjectTabSummaries(snapshot.state.projects),+ (snapshot) => selectProjectTabSummaries(snapshot.projects),areProjectTabSummariesEqual);const activeProjectId = useActiveProjectSelector((project) => project.id);- const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);+ const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.backendConnection.status);const modelLoads = useModelLoads();- const store = useWorkbenchStore();- const dispatch = useWorkbenchDispatch();+ const queries = useWorkbenchQueries();+ const { projects } = useWorkbenchCommands();const { closeProject, deleteProject } = useProjectActions();const [menuTarget, setMenuTarget] = useState<{ project: ProjectTabSummary; x: number; y: number } | null>(null);const [renameTarget, setRenameTarget] = useState<ProjectTabSummary | null>(null);const [deleteTarget, setDeleteTarget] = useState<ProjectTabSummary | null>(null);const [isOpenDialogVisible, setIsOpenDialogVisible] = useState(false);- const getProject = useCallback(- (projectId: string): Project | null =>- store.getState().projects.find((project) => project.id === projectId) ?? null,- [store]- );+ const getProject = useCallback((projectId: string): Project | null => queries.getProject(projectId), [queries]);const onSwitchProject = useCallback((projectId: string) => {flushGenerateDrafts();- dispatch({ projectId, type: 'switchProject' });+ projects.switchTo(projectId);},- [dispatch]+ [projects]);const openContextMenu = useCallback((project: ProjectTabSummary, event: MouseEvent) => {@@ -112,8 +107,8 @@ export const ProjectTabs = () => {const createProject = useCallback(() => {flushGenerateDrafts();- dispatch({ type: 'createProject' });- }, [dispatch]);+ projects.create();+ }, [projects]);const showOpenDialog = useCallback(() => setIsOpenDialogVisible(true), []);const hideOpenDialog = useCallback(() => setIsOpenDialogVisible(false), []);@@ -139,10 +134,10 @@ export const ProjectTabs = () => {const renameProject = useCallback((name: string) => {if (renameTarget) {- dispatch({ name, projectId: renameTarget.id, type: 'renameProject' });+ projects.rename(renameTarget.id, name);}},- [dispatch, renameTarget]+ [projects, renameTarget]);const confirmDeleteProject = useCallback(async () => {@@ -157,20 +152,32 @@ export const ProjectTabs = () => {return (<>- <Tabs.Root minW="max-content" variant="subtle" value={activeProjectId} h="full" w="full">- <Tabs.List flex="1 1 auto" h="full" py="1">- {projectTabSummaries.map((project) => (- <ProjectTab- key={project.id}- backendConnectionStatus={backendConnectionStatus}- isActive={project.id === activeProjectId}- loadingModelsCount={modelLoads.length}- project={project}- onCloseProject={closeProjectBySummary}- onContextMenu={openContextMenu}- onSwitchProject={onSwitchProject}- />- ))}+ <Tabs.Root minW="0" variant="subtle" value={activeProjectId} h="full" w="full">+ <Tabs.List flex="1 1 auto" minW="0" w="full" h="full" py="1">+ {/* Only the tabs scroll; the new/open controls stay pinned in view. */}+ <ScrollArea.Root css={TAB_STRIP_CONTAIN_CSS} flex="1 1 auto" minW="0" h="full" size="xs" variant="hover">+ <ScrollArea.Viewport aria-label={t('projects.openProjects')} h="full" w="full">+ <ScrollArea.Content asChild>+ <Flex align="center" h="full">+ {projectTabSummaries.map((project) => (+ <ProjectTab+ key={project.id}+ backendConnectionStatus={backendConnectionStatus}+ isActive={project.id === activeProjectId}+ loadingModelsCount={modelLoads.length}+ project={project}+ onCloseProject={closeProjectBySummary}+ onContextMenu={openContextMenu}+ onSwitchProject={onSwitchProject}+ />+ ))}+ </Flex>+ </ScrollArea.Content>+ </ScrollArea.Viewport>+ <ScrollArea.Scrollbar orientation="horizontal">+ <ScrollArea.Thumb />+ </ScrollArea.Scrollbar>+ </ScrollArea.Root><Separator orientation="vertical" h={5} mx="1" alignSelf="center" />@@ -262,6 +269,18 @@ const ProjectTab = ({const { t } = useTranslation();const openContextMenu = useCallback((event: MouseEvent) => onContextMenu(project, event), [onContextMenu, project]);+ // Callback ref, not an effect: identity changes with `isActive`, so React+ // re-attaches it on every selection change and the newly active tab scrolls+ // into the strip's viewport.+ const scrollIntoViewWhenActive = useCallback(+ (node: HTMLButtonElement | null) => {+ if (node && isActive) {+ node.scrollIntoView({ block: 'nearest', inline: 'nearest' });+ }+ },+ [isActive]+ );+const closeProject = useCallback((event: MouseEvent) => {event.stopPropagation();@@ -271,7 +290,15 @@ const ProjectTab = ({);return (- <Tabs.Trigger value={project.id} onClick={switchProject} onContextMenu={openContextMenu} fontSize="xs" h="full">+ <Tabs.Trigger+ ref={scrollIntoViewWhenActive}+ value={project.id}+ onClick={switchProject}+ onContextMenu={openContextMenu}+ fontSize="xs"+ flexShrink={0}+ h="full"+ >{progressState.kind === 'idle' ? (<Icon as={isActive ? FolderOpenIcon : FolderIcon} boxSize="4" />) : (@@ -305,36 +332,31 @@ const ProjectTabContextMenu = ({onRename: (project: ProjectTabSummary) => void;target: { project: ProjectTabSummary; x: number; y: number } | null;}) => {- const dispatch = useWorkbenchDispatch();- const store = useWorkbenchStore();+ const { projects } = useWorkbenchCommands();+ const queries = useWorkbenchQueries();const openWorkbenchWidget = useOpenWorkbenchWidget();- const targetRef = useRef(target);const { t } = useTranslation();- targetRef.current = target;-const positioning = useMemo(() => ({getAnchorRect: () => {- const currentTarget = targetRef.current;-- return currentTarget ? { height: 1, width: 1, x: currentTarget.x, y: currentTarget.y } : null;+ return target ? { height: 1, width: 1, x: target.x, y: target.y } : null;},placement: 'bottom-start' as const,}),- []+ [target]);const openProjectDetails = useCallback((projectSummary: ProjectTabSummary) => {- const project = store.getState().projects.find((candidate) => candidate.id === projectSummary.id);+ const project = queries.getProject(projectSummary.id);if (!project) {return;}flushGenerateDrafts();- dispatch({ projectId: project.id, type: 'switchProject' });+ projects.switchTo(project.id);// Reveal the Project panel wherever the project already shows it; default// to enabling it in the right rail. Both actions operate on the active@@ -349,7 +371,7 @@ const ProjectTabContextMenu = ({openWorkbenchWidget('project', { preferredRegions });},- [dispatch, openWorkbenchWidget, store]+ [openWorkbenchWidget, projects, queries]);const handleOpenChange = useCallback(@@ -362,39 +384,36 @@ const ProjectTabContextMenu = ({);const renameTarget = useCallback(() => {- if (targetRef.current) {- onRename(targetRef.current.project);+ if (target) {+ onRename(target.project);}- }, [onRename]);+ }, [onRename, target]);const showDetails = useCallback(() => {- if (targetRef.current) {- openProjectDetails(targetRef.current.project);+ if (target) {+ openProjectDetails(target.project);}- }, [openProjectDetails]);+ }, [openProjectDetails, target]);const exportProject = useCallback(() => {- const currentTarget = targetRef.current;- const project = currentTarget- ? store.getState().projects.find((candidate) => candidate.id === currentTarget.project.id)- : null;+ const project = target ? queries.getProject(target.project.id) : null;if (project) {exportOpenProject(project);}- }, [store]);+ }, [queries, target]);const closeTargetProject = useCallback(() => {- if (targetRef.current) {- onCloseProject(targetRef.current.project);+ if (target) {+ onCloseProject(target.project);}- }, [onCloseProject]);+ }, [onCloseProject, target]);const deleteTargetProject = useCallback(() => {- if (targetRef.current) {- onDelete(targetRef.current.project);+ if (target) {+ onDelete(target.project);}- }, [onDelete]);+ }, [onDelete, target]);return (<Menu.Rootdiff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.tsindex 1c3654d700..aac4aff30f 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts@@ -1,4 +1,5 @@-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';+import { createSingleFlight } from '@platform/state/singleFlight';import {createProject as apiCreateProject,@@ -78,26 +79,22 @@ export const seedProjectLibrary = (dtos: ProjectSummaryDTO[]): void => {store.setSnapshot({ status: 'ready', summaries: sortSummaries(dtos.map(toSummary)) });};-let pendingRefresh: Promise<void> | null = null;+const refreshFlight = createSingleFlight<void>();/** Re-list from the server; concurrent calls share one request. */-export const refreshProjectLibrary = (): Promise<void> => {- pendingRefresh ??= listProjects()- .then((dtos) => {- seedProjectLibrary(dtos);- })- .catch((error: unknown) => {- store.patchSnapshot({- error: error instanceof Error ? error.message : 'Failed to load projects.',- status: 'error',- });- })- .finally(() => {- pendingRefresh = null;- });-- return pendingRefresh;-};+export const refreshProjectLibrary = (): Promise<void> =>+ refreshFlight.run('project-library', () =>+ listProjects()+ .then((dtos) => {+ seedProjectLibrary(dtos);+ })+ .catch((error: unknown) => {+ store.patchSnapshot({+ error: error instanceof Error ? error.message : 'Failed to load projects.',+ status: 'error',+ });+ })+ );/*** Reflect a save the editor just pushed, so the library stays current withoutdiff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.tsindex 5d5ece1a39..5bb8b205bd 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts@@ -1,4 +1,4 @@-import type { Project } from '@workbench/types';+import type { Project } from '@workbench/projectContracts';import { createProject as apiCreateProject, getProject as apiGetProject, type ProjectRecordDTO } from './api';import { createProjectId } from './ids';diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.tsindex 6f16c27f6b..41e32859f8 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts@@ -1,6 +1,6 @@-import type { Project } from '@workbench/types';+import type { Project } from '@workbench/projectContracts';-import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState';+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';import { describe, expect, it } from 'vitest';import { createRecoveredDocument, deserializeProjectDocument, serializeProjectDocument } from './syncedPersistence';@@ -57,9 +57,13 @@ describe('project document serialization', () => {cancellable: true,id: 'legacy-queue-item',snapshot: {+ backendSubmission: { batchCount: 1, graph: { edges: [], id: 'graph', nodes: {} }, kind: 'workflow' },canvas: base.canvas,destination: 'gallery',+ filterIntermediateResults: true,+ galleryBoardId: null,graph: { edges: [], id: 'graph', label: 'Graph', nodes: [], updatedAt: 'now', version: 1 },+ presentation: { batchCount: 1, height: 1024, width: 1024 },sourceId: 'workflow',submittedAt: 'now',widgetInstances: {},diff --git a/invokeai/frontend/webv2/src/workbench/projects/session.ts b/invokeai/frontend/webv2/src/workbench/projects/session.tsindex 0c2ce3cd14..88c39c2627 100644--- a/invokeai/frontend/webv2/src/workbench/projects/session.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/session.ts@@ -1,4 +1,5 @@-import type { AccountState, WorkbenchPreferences, WorkbenchState } from '@workbench/types';+import type { AccountState, WorkbenchState } from '@workbench/projectContracts';+import type { WorkbenchPreferences } from '@workbench/settings/contracts';import { getClientStateValue } from './api';diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts b/invokeai/frontend/webv2/src/workbench/projects/syncStore.tsindex 1ab80c4f76..44dbbdd13b 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts@@ -1,4 +1,4 @@-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';/*** Read-only window into the project sync layer for shell surfaces (thediff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.tsindex 6ef2beeaf2..9a99623380 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts@@ -1,4 +1,4 @@-import type { Project, WorkbenchState } from '@workbench/types';+import type { Project, WorkbenchState } from '@workbench/projectContracts';import { createDraftProject, createInitialWorkbenchState } from '@workbench/workbenchState';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -145,6 +145,7 @@ const SESSION_KEY = 'webv2:workbench-account';let persistence: typeof persistenceModule;let library: typeof libraryModule;+let service: persistenceModule.SyncedWorkbenchPersistence;const seedSessionBlob = (blob: Record<string, unknown>): void => {api.__clientState.set(SESSION_KEY, JSON.stringify(blob));@@ -176,10 +177,22 @@ beforeEach(async () => {api.updateProject.mockClear();persistence = await import('./syncedPersistence');+ service = persistence.createSyncedWorkbenchPersistence();library = await import('./library');});describe('loadWorkbench session hydration', () => {+ it('constructs isolated synchronization lifetimes instead of sharing pending state', async () => {+ const first = persistence.createSyncedWorkbenchPersistence();+ const second = persistence.createSyncedWorkbenchPersistence();+ api.listProjects.mockRejectedValueOnce(new Error('offline'));++ await first.loadWorkbench();++ expect(first.hasPendingChanges()).toBe(true);+ expect(second.hasPendingChanges()).toBe(false);+ });+it('hydrates only the open set and seeds the full library', async () => {const first = seedServerProject('First');const second = seedServerProject('Second');@@ -188,12 +201,12 @@ describe('loadWorkbench session hydration', () => {seedSessionBlob({ account, activeProjectId: second.id, openProjectIds: [second.id] });- const snapshot = await persistence.syncedWorkbenchPersistence.loadWorkbench();+ const snapshot = await service.loadWorkbench();expect(snapshot?.state.projects.map((project) => project.id)).toEqual([second.id]);expect(snapshot?.state.activeProjectId).toBe(second.id);expect(api.getProject).toHaveBeenCalledTimes(1);- expect(persistence.syncedWorkbenchPersistence.hasPendingChanges()).toBe(false);+ expect(service.hasPendingChanges()).toBe(false);const libraryIds = library.getProjectLibrary().summaries.map((summary) => summary.id);@@ -209,7 +222,7 @@ describe('loadWorkbench session hydration', () => {seedSessionBlob({ account, activeProjectId: 'missing' });- const snapshot = await persistence.syncedWorkbenchPersistence.loadWorkbench();+ const snapshot = await service.loadWorkbench();expect(snapshot?.state.projects).toHaveLength(2);});@@ -218,7 +231,7 @@ describe('loadWorkbench session hydration', () => {seedServerProject('Backend Project');storage.set('invokeai:v7:webv2:workbench', '{not json');- const snapshot = await persistence.syncedWorkbenchPersistence.loadWorkbench();+ const snapshot = await service.loadWorkbench();expect(snapshot?.state.projects.map((project) => project.name)).toEqual(['Backend Project']);});@@ -229,12 +242,12 @@ describe('loadWorkbench session hydration', () => {seedSessionBlob({ account, activeProjectId: '', openProjectIds: [] });- const snapshot = await persistence.syncedWorkbenchPersistence.loadWorkbench();+ const snapshot = await service.loadWorkbench();expect(snapshot?.state.projects).toHaveLength(1);expect(snapshot?.state.projects[0].id).not.toBe(existing.id);expect(snapshot?.state.activeProjectId).toBe(snapshot?.state.projects[0].id);- expect(persistence.syncedWorkbenchPersistence.hasPendingChanges()).toBe(true);+ expect(service.hasPendingChanges()).toBe(true);});it('joins a deep-linked project into the open set and focuses it', async () => {@@ -244,11 +257,11 @@ describe('loadWorkbench session hydration', () => {seedSessionBlob({ account, activeProjectId: first.id, openProjectIds: [first.id] });- const snapshot = await persistence.syncedWorkbenchPersistence.loadWorkbench({ openProjectId: second.id });+ const snapshot = await service.loadWorkbench({ openProjectId: second.id });expect(snapshot?.state.projects.map((project) => project.id)).toEqual([first.id, second.id]);expect(snapshot?.state.activeProjectId).toBe(second.id);- expect(persistence.syncedWorkbenchPersistence.hasPendingChanges()).toBe(true);+ expect(service.hasPendingChanges()).toBe(true);});it('appends and activates a draft when a new project is requested', async () => {@@ -257,11 +270,11 @@ describe('loadWorkbench session hydration', () => {seedSessionBlob({ account, activeProjectId: first.id, openProjectIds: [first.id] });- const snapshot = await persistence.syncedWorkbenchPersistence.loadWorkbench({ createNew: true });+ const snapshot = await service.loadWorkbench({ createNew: true });expect(snapshot?.state.projects).toHaveLength(2);expect(snapshot?.state.activeProjectId).not.toBe(first.id);- expect(persistence.syncedWorkbenchPersistence.hasPendingChanges()).toBe(true);+ expect(service.hasPendingChanges()).toBe(true);});});@@ -273,7 +286,7 @@ describe('saveWorkbench', () => {seedSessionBlob({ account, activeProjectId: first.id, openProjectIds: [first.id, second.id] });- const snapshot = await persistence.syncedWorkbenchPersistence.loadWorkbench();+ const snapshot = await service.loadWorkbench();const open = snapshot?.state.projects ?? [];expect(open).toHaveLength(2);@@ -284,7 +297,7 @@ describe('saveWorkbench', () => {first.id);- await persistence.syncedWorkbenchPersistence.saveWorkbench(closed);+ await service.saveWorkbench(closed);expect(api.deleteProject).not.toHaveBeenCalled();expect(api.__records.has(second.id)).toBe(true);@@ -296,11 +309,11 @@ describe('saveWorkbench', () => {seedSessionBlob({ account, activeProjectId: first.id, openProjectIds: [first.id] });- const snapshot = await persistence.syncedWorkbenchPersistence.loadWorkbench();+ const snapshot = await service.loadWorkbench();const open = snapshot?.state.projects ?? [];const draft = createDraftProject(open);- await persistence.syncedWorkbenchPersistence.saveWorkbench(stateWithProjects([...open, draft], draft.id));+ await service.saveWorkbench(stateWithProjects([...open, draft], draft.id));const blob = JSON.parse(api.__clientState.get(SESSION_KEY) ?? '{}') as {activeProjectId?: string;@@ -315,8 +328,8 @@ describe('saveWorkbench', () => {const project = createDraftProject([]);const state = stateWithProjects([project]);- persistence.markProjectDeleted(project.id);- await persistence.syncedWorkbenchPersistence.saveWorkbench(state);+ service.markProjectDeleted(project.id);+ await service.saveWorkbench(state);expect(api.createProject).not.toHaveBeenCalled();expect(api.updateProject).not.toHaveBeenCalled();@@ -331,9 +344,9 @@ describe('persistEmptySession', () => {seedSessionBlob({ account, activeProjectId: first.id, openProjectIds: [first.id] });- const snapshot = await persistence.syncedWorkbenchPersistence.loadWorkbench();+ const snapshot = await service.loadWorkbench();- await persistence.persistEmptySession(snapshot?.state ?? createInitialWorkbenchState());+ await service.persistEmptySession(snapshot?.state ?? createInitialWorkbenchState());const blob = JSON.parse(api.__clientState.get(SESSION_KEY) ?? '{}') as { openProjectIds?: string[] };@@ -346,7 +359,7 @@ describe('persistEmptySession', () => {describe('hydrateProjectFromServer', () => {it('returns an openable project and registers its revision for future saves', async () => {const project = seedServerProject('Closed project');- const hydrated = await persistence.hydrateProjectFromServer(project.id);+ const hydrated = await service.hydrateProjectFromServer(project.id);expect(hydrated?.id).toBe(project.id);expect(hydrated?.undoRedo).toEqual({ future: [], past: [] });@@ -354,13 +367,13 @@ describe('hydrateProjectFromServer', () => {// A subsequent save updates in place rather than re-creating.const renamed = { ...hydrated!, name: 'Renamed after reopen' };- await persistence.syncedWorkbenchPersistence.saveWorkbench(stateWithProjects([renamed]));+ await service.saveWorkbench(stateWithProjects([renamed]));expect(api.createProject).not.toHaveBeenCalled();expect(api.__records.get(project.id)?.name).toBe('Renamed after reopen');});it('returns null for unknown projects', async () => {- expect(await persistence.hydrateProjectFromServer('nope')).toBeNull();+ expect(await service.hydrateProjectFromServer('nope')).toBeNull();});});diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.tsindex 92bb472fe6..f4883dea2a 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts@@ -1,6 +1,7 @@-import type { Project, WorkbenchPersistenceSnapshot, WorkbenchState } from '@workbench/types';+import type { HydratedWorkbenchSnapshot } from '@workbench/persistenceContracts';+import type { Project, WorkbenchState } from '@workbench/projectContracts';-import { getUserStorageScope } from '@workbench/auth/session';+import { getUserStorageScope } from '@features/identity';import { timeWorkbenchPerf } from '@workbench/performanceMarks';import { localStorageWorkbenchPersistence, stripTransientWorkbenchState } from '@workbench/persistence';import { createDraftProject, createInitialWorkbenchState } from '@workbench/workbenchState';@@ -60,7 +61,7 @@ export interface ProjectConflictResolution {}export interface WorkbenchSaveResult {- snapshot: WorkbenchPersistenceSnapshot;+ snapshot: HydratedWorkbenchSnapshot;conflicts: ProjectConflictResolution[];/** True when changes are cached locally but could not reach the backend. */hasPendingChanges: boolean;@@ -73,16 +74,23 @@ export interface WorkbenchLoadOptions {createNew?: boolean;}-/** Server-known projects, keyed by project id. */-const syncEntries = new Map<string, SyncEntry>();-/**- * Ids deleted this page session. An autosave that raced the delete must not- * resurrect the project through the not-found-recreate path.- */-const deletedProjectIds = new Set<string>();-let lastPushedAccount: string | null = null;-let hasPending = false;-const projectDocumentJsonCache = new WeakMap<Project, { document: Record<string, unknown>; json: string }>();+interface SyncedPersistenceState {+ /** Ids deleted in this runtime lifetime, guarding against racing saves. */+ deletedProjectIds: Set<string>;+ hasPending: boolean;+ lastPushedAccount: string | null;+ projectDocumentJsonCache: WeakMap<Project, { document: Record<string, unknown>; json: string }>;+ /** Server-known projects, keyed by project id. */+ syncEntries: Map<string, SyncEntry>;+}++const createSyncedPersistenceState = (): SyncedPersistenceState => ({+ deletedProjectIds: new Set(),+ hasPending: false,+ lastPushedAccount: null,+ projectDocumentJsonCache: new WeakMap(),+ syncEntries: new Map(),+});/*** Undo/redo stacks are session-only (each entry is a full project snapshot,@@ -95,8 +103,11 @@ export const serializeProjectDocument = (project: Project): Record<string, unknoreturn document;};-const getSerializedProjectDocument = (project: Project): { document: Record<string, unknown>; json: string } => {- const cached = projectDocumentJsonCache.get(project);+const getSerializedProjectDocument = (+ syncState: SyncedPersistenceState,+ project: Project+): { document: Record<string, unknown>; json: string } => {+ const cached = syncState.projectDocumentJsonCache.get(project);if (cached) {return cached;@@ -110,7 +121,7 @@ const getSerializedProjectDocument = (project: Project): { document: Record<stri);const serialized = { document, json };- projectDocumentJsonCache.set(project, serialized);+ syncState.projectDocumentJsonCache.set(project, serialized);return serialized;};@@ -187,11 +198,11 @@ const getSyncMapStorageKey = (): string => `${SYNC_MAP_BASE_KEY}${getUserStorage* elsewhere — drop it)" apart from "this local project was created offline* (push it)".*/-const persistSyncMap = (): void => {+const persistSyncMap = (syncState: SyncedPersistenceState): void => {try {const revisions: Record<string, number> = {};- for (const [projectId, entry] of syncEntries) {+ for (const [projectId, entry] of syncState.syncEntries) {revisions[projectId] = entry.revision;}@@ -212,20 +223,20 @@ const loadPersistedRevisions = (): Record<string, number> => {}};-const createSnapshot = (state: WorkbenchState): WorkbenchPersistenceSnapshot => ({+const createSnapshot = (state: WorkbenchState): HydratedWorkbenchSnapshot => ({savedAt: new Date().toISOString(),state: stripTransientWorkbenchState(state),version: 1,});/** Import a never-synced project to the server; returns false when it could not reach it. */-const pushNewProject = async (project: Project): Promise<boolean> => {+const pushNewProject = async (syncState: SyncedPersistenceState, project: Project): Promise<boolean> => {const document = serializeProjectDocument(project);try {const created = await apiCreateProject({ data: document, name: project.name, project_id: project.id });- syncEntries.set(project.id, { pushedDoc: JSON.stringify(document), revision: created.revision });+ syncState.syncEntries.set(project.id, { pushedDoc: JSON.stringify(document), revision: created.revision });return true;} catch (error) {@@ -235,7 +246,10 @@ const pushNewProject = async (project: Project): Promise<boolean> => {try {const existing = await apiGetProject(project.id);- syncEntries.set(project.id, { pushedDoc: JSON.stringify(existing.data), revision: existing.revision });+ syncState.syncEntries.set(project.id, {+ pushedDoc: JSON.stringify(existing.data),+ revision: existing.revision,+ });return true;} catch {@@ -294,6 +308,7 @@ type ConflictOutcome =* into a "(recovered)" project so nothing is lost*/const recoverConflictingProject = async (+ syncState: SyncedPersistenceState,project: Project,document: Record<string, unknown>,documentJson: string,@@ -303,7 +318,7 @@ const recoverConflictingProject = async (const server = await apiGetProject(project.id);const serverDocJson = JSON.stringify(server.data);- syncEntries.set(project.id, { pushedDoc: serverDocJson, revision: server.revision });+ syncState.syncEntries.set(project.id, { pushedDoc: serverDocJson, revision: server.revision });if (serverDocJson === documentJson) {return { kind: 'adopted' };@@ -328,7 +343,10 @@ const recoverConflictingProject = async (const created = await apiCreateProject({ data: recoveredDocument, name: recoveredName, project_id: recoveredId });- syncEntries.set(recoveredId, { pushedDoc: JSON.stringify(recoveredDocument), revision: created.revision });+ syncState.syncEntries.set(recoveredId, {+ pushedDoc: JSON.stringify(recoveredDocument),+ revision: created.revision,+ });return { kind: 'forked', resolution: { projectId: project.id, recoveredProject, serverProject } };} catch {@@ -336,17 +354,21 @@ const recoverConflictingProject = async (}};-const pushProject = async (project: Project, conflicts: ProjectConflictResolution[]): Promise<string> => {- const { document, json: documentJson } = getSerializedProjectDocument(project);- const entry = syncEntries.get(project.id);+const pushProject = async (+ syncState: SyncedPersistenceState,+ project: Project,+ conflicts: ProjectConflictResolution[]+): Promise<string> => {+ const { document, json: documentJson } = getSerializedProjectDocument(syncState, project);+ const entry = syncState.syncEntries.get(project.id);- if (deletedProjectIds.has(project.id) || entry?.pushedDoc === documentJson) {+ if (syncState.deletedProjectIds.has(project.id) || entry?.pushedDoc === documentJson) {return documentJson;}if (!entry) {- if (!(await pushNewProject(project))) {- hasPending = true;+ if (!(await pushNewProject(syncState, project))) {+ syncState.hasPending = true;}return documentJson;@@ -359,65 +381,66 @@ const pushProject = async (project: Project, conflicts: ProjectConflictResolutioname: project.name,});- syncEntries.set(project.id, { pushedDoc: documentJson, revision: updated.revision });+ syncState.syncEntries.set(project.id, { pushedDoc: documentJson, revision: updated.revision });} catch (error) {if (isProjectConflictError(error)) {- const outcome = await recoverConflictingProject(project, document, documentJson, entry.pushedDoc);+ const outcome = await recoverConflictingProject(syncState, project, document, documentJson, entry.pushedDoc);if (outcome.kind === 'retry') {try {- const baseRevision = syncEntries.get(project.id)?.revision ?? entry.revision;+ const baseRevision = syncState.syncEntries.get(project.id)?.revision ?? entry.revision;const retried = await apiUpdateProject(project.id, {data: document,expected_revision: baseRevision,name: project.name,});- syncEntries.set(project.id, { pushedDoc: documentJson, revision: retried.revision });+ syncState.syncEntries.set(project.id, { pushedDoc: documentJson, revision: retried.revision });} catch {// A genuinely concurrent writer; the next save re-evaluates.- hasPending = true;+ syncState.hasPending = true;}} else if (outcome.kind === 'forked') {conflicts.push(outcome.resolution);} else if (outcome.kind === 'failed') {- hasPending = true;+ syncState.hasPending = true;}} else if (isProjectNotFoundError(error)) {// Deleted on another device while we held local edits: recreate rather// than drop the user's work.- syncEntries.delete(project.id);+ syncState.syncEntries.delete(project.id);- if (!(await pushNewProject(project))) {- hasPending = true;+ if (!(await pushNewProject(syncState, project))) {+ syncState.hasPending = true;}} else {- hasPending = true;+ syncState.hasPending = true;}}return documentJson;};-const pushSessionState = async (state: WorkbenchState): Promise<void> => {+const pushSessionState = async (syncState: SyncedPersistenceState, state: WorkbenchState): Promise<void> => {const blob = serializeSessionBlob(state);- if (blob === lastPushedAccount) {+ if (blob === syncState.lastPushedAccount) {return;}try {await setClientStateValue(SESSION_STATE_KEY, blob);- lastPushedAccount = blob;+ syncState.lastPushedAccount = blob;} catch {- hasPending = true;+ syncState.hasPending = true;}};const loadFromBackend = async (- local: WorkbenchPersistenceSnapshot | null,+ syncState: SyncedPersistenceState,+ local: HydratedWorkbenchSnapshot | null,options?: WorkbenchLoadOptions-): Promise<WorkbenchPersistenceSnapshot> => {+): Promise<HydratedWorkbenchSnapshot> => {const [summaries, sessionBlob] = await Promise.all([listProjects(), fetchSessionBlob()]);const persistedRevisions = loadPersistedRevisions();@@ -427,17 +450,17 @@ const loadFromBackend = async (// workbench (one-time import of the pre-backend localStorage data).if (summaries.length === 0 && local && local.state.projects.length > 0) {for (const project of local.state.projects) {- if (!(await pushNewProject(project))) {- hasPending = true;+ if (!(await pushNewProject(syncState, project))) {+ syncState.hasPending = true;}- const entry = syncEntries.get(project.id);+ const entry = syncState.syncEntries.get(project.id);upsertProjectSummary({ id: project.id, name: project.name, revision: entry?.revision ?? null });}- await pushSessionState(local.state);- persistSyncMap();+ await pushSessionState(syncState, local.state);+ persistSyncMap(syncState);return local;}@@ -471,7 +494,10 @@ const loadFromBackend = async (if (project) {serverProjects.push(project);- syncEntries.set(record.project_id, { pushedDoc: JSON.stringify(record.data), revision: record.revision });+ syncState.syncEntries.set(record.project_id, {+ pushedDoc: JSON.stringify(record.data),+ revision: record.revision,+ });}}@@ -484,13 +510,13 @@ const loadFromBackend = async ();if (offlineCreated.length > 0) {- hasPending = true;+ syncState.hasPending = true;}let projects = [...serverProjects, ...offlineCreated];if (sessionBlob) {- lastPushedAccount = JSON.stringify(sessionBlob);+ syncState.lastPushedAccount = JSON.stringify(sessionBlob);}const base = local?.state ?? createInitialWorkbenchState();@@ -523,22 +549,22 @@ const loadFromBackend = async (projects,};- if (serializeSessionBlob(state) !== lastPushedAccount) {- hasPending = true;+ if (serializeSessionBlob(state) !== syncState.lastPushedAccount) {+ syncState.hasPending = true;}reportProjectSync({- hasPendingChanges: hasPending,+ hasPendingChanges: syncState.hasPending,projects: Object.fromEntries(projects.map((project) => {- const entry = syncEntries.get(project.id);+ const entry = syncState.syncEntries.get(project.id);return [project.id, { isPendingPush: entry === undefined, revision: entry?.revision ?? null }];})),});- persistSyncMap();+ persistSyncMap(syncState);const snapshot = createSnapshot(state);@@ -548,203 +574,203 @@ const loadFromBackend = async (return snapshot;};-export const syncedWorkbenchPersistence = {- /**- * Load from the backend, falling back to the localStorage cache when it is- * unreachable. Returns null when there is nothing anywhere (first run with- * no backend); the caller then keeps its default boot state.- */- async loadWorkbench(options?: WorkbenchLoadOptions): Promise<WorkbenchPersistenceSnapshot | null> {- let local: WorkbenchPersistenceSnapshot | null = null;-- try {- local = await localStorageWorkbenchPersistence.loadWorkbench();- } catch {- local = null;- }-- try {- return await loadFromBackend(local, options);- } catch {- // Backend unreachable: run from the cache; saves queue up locally and- // replay on reconnect.- hasPending = true;-- const persistedRevisions = loadPersistedRevisions();-- for (const [projectId, revision] of Object.entries(persistedRevisions)) {- syncEntries.set(projectId, { pushedDoc: null, revision });- }-- reportProjectSync({- hasPendingChanges: true,- projects: Object.fromEntries(- (local?.state.projects ?? []).map((project) => [- project.id,- { isPendingPush: true, revision: persistedRevisions[project.id] ?? null },- ])- ),- });-- // A cache holding an empty session (last tab closed offline) cannot- // hydrate the editor; boot a fresh draft instead.- return local && local.state.projects.length > 0 ? local : null;- }- },+export interface SyncedWorkbenchPersistence {+ adoptProjectRecord(record: ProjectRecordDTO): Project | null;+ clearWorkbench(): Promise<void>;+ flushProjectToServer(project: Project): Promise<void>;+ hasPendingChanges(): boolean;+ hydrateProjectFromServer(projectId: string): Promise<Project | null>;+ loadWorkbench(options?: WorkbenchLoadOptions): Promise<HydratedWorkbenchSnapshot | null>;+ markProjectDeleted(projectId: string): void;+ persistEmptySession(state: WorkbenchState): Promise<void>;+ releaseProjectSync(projectId: string): void;+ saveWorkbench(state: WorkbenchState): Promise<WorkbenchSaveResult>;+ unmarkProjectDeleted(projectId: string): void;+}- /**- * Write-through save: localStorage cache always, then every dirty open- * project and the session blob to the backend. Revision conflicts come- * back as resolutions for the caller to apply to workbench state. Saving- * never deletes anything: a project absent from state is merely closed,- * and removal happens only through the library's explicit delete.- */- async saveWorkbench(state: WorkbenchState): Promise<WorkbenchSaveResult> {- const snapshot = createSnapshot(state);+/**+ * One-shot maintenance operation: deletes server projects and the session+ * blob, then clears the local cache, project library, and persisted sync map.+ * Independent of any mounted Workbench lifetime; callers are expected to+ * reload afterwards.+ */+export const clearAllWorkbenchData = async (): Promise<void> => {+ try {+ const summaries = await listProjects();- await localStorageWorkbenchPersistence.saveWorkbench(state);+ await Promise.all(summaries.map((summary) => apiDeleteProject(summary.project_id)));+ await deleteClientStateValue(SESSION_STATE_KEY);+ } catch {+ // Backend unreachable; at least reset this browser.+ }- hasPending = false;+ seedProjectLibrary([]);- const conflicts: ProjectConflictResolution[] = [];- const projectSyncInfos: Record<string, ProjectSyncInfo> = {};+ try {+ window.localStorage.removeItem(getSyncMapStorageKey());+ } catch {+ // Nothing to clear if storage is unavailable.+ }- await pushSessionState(state);+ await localStorageWorkbenchPersistence.clearWorkbench();+};- for (const project of state.projects) {- const lastAckedDoc = syncEntries.get(project.id)?.pushedDoc ?? null;- const documentJson = await pushProject(project, conflicts);- const entry = syncEntries.get(project.id);+/** Construct one synchronization lifetime per mounted Workbench. */+export const createSyncedWorkbenchPersistence = (): SyncedWorkbenchPersistence => {+ const syncState = createSyncedPersistenceState();- projectSyncInfos[project.id] = {- isPendingPush: entry?.pushedDoc !== documentJson,- revision: entry?.revision ?? null,- };+ const adoptProjectRecord = (record: ProjectRecordDTO): Project | null => {+ const project = deserializeProjectDocument(record.data);- // The server acknowledged new content for this project — keep the- // library summary current without a refetch.- if (entry && entry.pushedDoc === documentJson && lastAckedDoc !== documentJson) {- upsertProjectSummary({ id: project.id, name: project.name, revision: entry.revision });- }+ if (!project) {+ return null;}- persistSyncMap();- reportProjectSync({ hasPendingChanges: hasPending, projects: projectSyncInfos });+ syncState.syncEntries.set(record.project_id, {+ pushedDoc: JSON.stringify(record.data),+ revision: record.revision,+ });+ persistSyncMap(syncState);- return { conflicts, hasPendingChanges: hasPending, snapshot };- },+ return project;+ };- /** True when local changes have not reached the backend yet. */- hasPendingChanges(): boolean {- return hasPending;- },+ return {+ adoptProjectRecord,+ /** Clear everywhere: server projects + session blob, local cache, sync map, and this lifetime's sync state. */+ async clearWorkbench(): Promise<void> {+ await clearAllWorkbenchData();++ syncState.syncEntries.clear();+ syncState.deletedProjectIds.clear();+ syncState.lastPushedAccount = null;+ syncState.hasPending = false;+ },+ async flushProjectToServer(project): Promise<void> {+ const conflicts: ProjectConflictResolution[] = [];- /** Clear everywhere: server projects + session blob, local cache, sync map. */- async clearWorkbench(): Promise<void> {- try {- const summaries = await listProjects();+ await pushProject(syncState, project, conflicts);+ persistSyncMap(syncState);+ },+ hasPendingChanges(): boolean {+ return syncState.hasPending;+ },+ async hydrateProjectFromServer(projectId): Promise<Project | null> {+ try {+ return adoptProjectRecord(await apiGetProject(projectId));+ } catch {+ return null;+ }+ },+ /**+ * Load from the backend, falling back to the localStorage cache when it is+ * unreachable. Returns null when there is nothing anywhere (first run with+ * no backend); the caller then keeps its default boot state.+ */+ async loadWorkbench(options?: WorkbenchLoadOptions): Promise<HydratedWorkbenchSnapshot | null> {+ let local: HydratedWorkbenchSnapshot | null = null;- await Promise.all(summaries.map((summary) => apiDeleteProject(summary.project_id)));- await deleteClientStateValue(SESSION_STATE_KEY);- } catch {- // Backend unreachable; at least reset this browser.- }+ try {+ local = await localStorageWorkbenchPersistence.loadWorkbench();+ } catch {+ local = null;+ }- syncEntries.clear();- deletedProjectIds.clear();- seedProjectLibrary([]);- lastPushedAccount = null;- hasPending = false;+ try {+ return await loadFromBackend(syncState, local, options);+ } catch {+ // Backend unreachable: run from the cache; saves queue up locally and+ // replay on reconnect.+ syncState.hasPending = true;- try {- window.localStorage.removeItem(getSyncMapStorageKey());- } catch {- // Nothing to clear if storage is unavailable.- }+ const persistedRevisions = loadPersistedRevisions();- await localStorageWorkbenchPersistence.clearWorkbench();- },-};+ for (const [projectId, revision] of Object.entries(persistedRevisions)) {+ syncState.syncEntries.set(projectId, { pushedDoc: null, revision });+ }-/**- * Adopt a full project record fetched (or just created) on the server into- * the sync layer, returning the hydrated project ready to open as a tab.- */-export const adoptProjectRecord = (record: ProjectRecordDTO): Project | null => {- const project = deserializeProjectDocument(record.data);+ reportProjectSync({+ hasPendingChanges: true,+ projects: Object.fromEntries(+ (local?.state.projects ?? []).map((project) => [+ project.id,+ { isPendingPush: true, revision: persistedRevisions[project.id] ?? null },+ ])+ ),+ });++ // A cache holding an empty session (last tab closed offline) cannot+ // hydrate the editor; boot a fresh draft instead.+ return local && local.state.projects.length > 0 ? local : null;+ }+ },- if (!project) {- return null;- }+ /**+ * Write-through save: localStorage cache always, then every dirty open+ * project and the session blob to the backend. Revision conflicts come+ * back as resolutions for the caller to apply to workbench state. Saving+ * never deletes anything: a project absent from state is merely closed,+ * and removal happens only through the library's explicit delete.+ */+ markProjectDeleted(projectId): void {+ syncState.deletedProjectIds.add(projectId);+ syncState.syncEntries.delete(projectId);+ persistSyncMap(syncState);+ },+ async persistEmptySession(state): Promise<void> {+ const emptied: WorkbenchState = { ...state, activeProjectId: '', projects: [] };- syncEntries.set(record.project_id, { pushedDoc: JSON.stringify(record.data), revision: record.revision });- persistSyncMap();+ await localStorageWorkbenchPersistence.saveWorkbench(emptied);- return project;-};+ try {+ const blob = serializeSessionBlob(emptied);-/** Hydrate one library project into an openable document; null when it cannot be fetched. */-export const hydrateProjectFromServer = async (projectId: string): Promise<Project | null> => {- try {- return adoptProjectRecord(await apiGetProject(projectId));- } catch {- return null;- }-};+ await setClientStateValue(SESSION_STATE_KEY, blob);+ syncState.lastPushedAccount = blob;+ } catch {+ syncState.hasPending = true;+ }+ },+ releaseProjectSync(projectId): void {+ syncState.syncEntries.delete(projectId);+ persistSyncMap(syncState);+ },+ async saveWorkbench(state: WorkbenchState): Promise<WorkbenchSaveResult> {+ const snapshot = createSnapshot(state);-/**- * Push one project's document immediately — used when its tab closes, so the- * final edits land on the server even though the project is about to leave- * the autosaved state.- */-export const flushProjectToServer = async (project: Project): Promise<void> => {- const conflicts: ProjectConflictResolution[] = [];+ await localStorageWorkbenchPersistence.saveWorkbench(state);- await pushProject(project, conflicts);- persistSyncMap();-};+ syncState.hasPending = false;-/** Forget a project's sync entry once its tab is closed. */-export const releaseProjectSync = (projectId: string): void => {- syncEntries.delete(projectId);- persistSyncMap();-};+ const conflicts: ProjectConflictResolution[] = [];+ const projectSyncInfos: Record<string, ProjectSyncInfo> = {};-/**- * Make an explicit delete safe against in-flight autosaves: pushes for this- * id become no-ops, so a save that started before the delete cannot recreate- * the project on the server.- */-export const markProjectDeleted = (projectId: string): void => {- deletedProjectIds.add(projectId);- syncEntries.delete(projectId);- persistSyncMap();-};+ await pushSessionState(syncState, state);-/**- * The delete failed server-side: let pushes flow again. The dropped sync- * entry rebuilds itself on the next save (create → conflict → adopt), so no- * edits are lost.- */-export const unmarkProjectDeleted = (projectId: string): void => {- deletedProjectIds.delete(projectId);-};+ for (const project of state.projects) {+ const lastAckedDoc = syncState.syncEntries.get(project.id)?.pushedDoc ?? null;+ const documentJson = await pushProject(syncState, project, conflicts);+ const entry = syncState.syncEntries.get(project.id);-/**- * Persist "no tabs open" — the last tab was closed and the editor is about- * to navigate Home, unmounting the autosave loop before it could run.- */-export const persistEmptySession = async (state: WorkbenchState): Promise<void> => {- const emptied: WorkbenchState = { ...state, activeProjectId: '', projects: [] };+ projectSyncInfos[project.id] = {+ isPendingPush: entry?.pushedDoc !== documentJson,+ revision: entry?.revision ?? null,+ };- await localStorageWorkbenchPersistence.saveWorkbench(emptied);+ // The server acknowledged new content for this project — keep the+ // library summary current without a refetch.+ if (entry && entry.pushedDoc === documentJson && lastAckedDoc !== documentJson) {+ upsertProjectSummary({ id: project.id, name: project.name, revision: entry.revision });+ }+ }- try {- const blob = serializeSessionBlob(emptied);+ persistSyncMap(syncState);+ reportProjectSync({ hasPendingChanges: syncState.hasPending, projects: projectSyncInfos });- await setClientStateValue(SESSION_STATE_KEY, blob);- lastPushedAccount = blob;- } catch {- hasPending = true;- }+ return { conflicts, hasPendingChanges: syncState.hasPending, snapshot };+ },+ unmarkProjectDeleted(projectId): void {+ syncState.deletedProjectIds.delete(projectId);+ },+ };};diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.tsindex 8e7640d226..0268febc30 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts@@ -1,19 +1,17 @@-import type { Project } from '@workbench/types';+import type { Project } from '@workbench/projectContracts';+import { flushGenerateDrafts } from '@features/generation/drafts';import { useNavigate } from '@tanstack/react-router';import { useNotify } from '@workbench/useNotify';-import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';-import { useWorkbenchDispatch, useWorkbenchStore } from '@workbench/WorkbenchContext';+import {+ useWorkbenchCommands,+ useWorkbenchPersistenceAdapter,+ useWorkbenchPersistenceService,+ useWorkbenchQueries,+} from '@workbench/WorkbenchContext';import { useTranslation } from 'react-i18next';import { deleteLibraryProject } from './library';-import {- flushProjectToServer,- markProjectDeleted,- persistEmptySession,- releaseProjectSync,- unmarkProjectDeleted,-} from './syncedPersistence';/*** Close and delete for projects that are open in the editor, shared by the@@ -29,21 +27,21 @@ export const useProjectActions = (): {closeProject: (project: Project) => void;deleteProject: (project: Project) => Promise<void>;} => {- const store = useWorkbenchStore();- const dispatch = useWorkbenchDispatch();+ const queries = useWorkbenchQueries();+ const persistence = useWorkbenchPersistenceAdapter();+ const persistenceService = useWorkbenchPersistenceService();+ const commands = useWorkbenchCommands();const navigate = useNavigate();const notify = useNotify();const { t } = useTranslation();/** When the last tab goes, the session empties and Home takes over. */const leaveEditorIfLast = (projectId: string): boolean => {- const state = store.getState();-- if (state.projects.some((project) => project.id !== projectId)) {+ if (queries.getSnapshot().projects.some((project) => project.id !== projectId)) {return false;}- void persistEmptySession(state);+ void persistenceService.persistEmptySession(persistence.getState());void navigate({ to: '/' });return true;@@ -52,29 +50,29 @@ export const useProjectActions = (): {const closeProject = (project: Project): void => {flushGenerateDrafts();- const projectToFlush = store.getState().projects.find((candidate) => candidate.id === project.id) ?? project;+ const projectToFlush = queries.getProject(project.id) ?? project;- void flushProjectToServer(projectToFlush).finally(() => {- releaseProjectSync(project.id);+ void persistenceService.flushProjectToServer(projectToFlush).finally(() => {+ persistenceService.releaseProjectSync(project.id);});if (leaveEditorIfLast(project.id)) {return;}- dispatch({ projectId: project.id, type: 'closeProject' });+ commands.projects.close(project.id);};const deleteProject = async (project: Project): Promise<void> => {flushGenerateDrafts();// Marked before the request so an in-flight autosave cannot recreate the// project server-side between the DELETE and the tab closing.- markProjectDeleted(project.id);+ persistenceService.markProjectDeleted(project.id);try {await deleteLibraryProject(project.id);} catch (error) {- unmarkProjectDeleted(project.id);+ persistenceService.unmarkProjectDeleted(project.id);notify.error(t('projects.deleteFailed'), error instanceof Error ? error.message : undefined);return;@@ -84,7 +82,7 @@ export const useProjectActions = (): {return;}- dispatch({ projectId: project.id, type: 'closeProject' });+ commands.projects.close(project.id);};return { closeProject, deleteProject };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemActions.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsxsimilarity index 76%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemActions.tsxrename to invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsxindex e3876ddbd7..89d9dd7994 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx@@ -1,27 +1,28 @@-import type { GenerateWidgetValues } from '@workbench/generation/types';+import type { QueueItemReadModel } from '@features/queue/contracts';import { Dialog, Icon, Portal } from '@chakra-ui/react';-import { Button, CloseButton, JsonPreview } from '@workbench/components/ui';-import { isSupportedGenerateModel } from '@workbench/generation/baseGenerationPolicies';+import { createGenerateFormValuesSelector } from '@features/generation/form';+import { isSupportedGenerateModel } from '@features/generation/settings';+import { ensureModelsLoaded, useModelsSelector } from '@features/models';+import { extractGenerationMeta } from '@features/queue/contracts';+import { useMountEffect } from '@platform/react/useMountEffect';+import { Button, CloseButton } from '@platform/ui/Button';+import { JsonPreview } from '@platform/ui/JsonPreview';import {getCurrentGenerateValues,getImageRecallTitle,RecallActionButtons,type ImageRecallKind,} from '@workbench/image-actions';-import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';import { useNotify } from '@workbench/useNotify';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';-import { createGenerateFormValuesSelector } from '@workbench/widgets/generate/generateFormViewModel';-import { useWidgetValuesSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useWidgetValuesSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { FileTextIcon, WandSparklesIcon } from 'lucide-react';-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import type { QueueServerItem } from './queueServerApi';--import { extractGenerationMeta } from './fieldValues';import { buildQueueRecallValues, getQueueRecallCapabilities } from './queueRecall';+import { useLocalGenerateValues } from './useLocalGenerateValues';const selectGenerateRecallValues = createGenerateFormValuesSelector();@@ -32,17 +33,12 @@ const selectGenerateRecallValues = createGenerateFormValuesSelector();* snapshot; foreign items still offer prompts + the executed seed from the* session. "View JSON" opens the raw queue item in a dialog.*/-export const QueueItemActions = ({- item,- localGenerateValues,-}: {- item: QueueServerItem;- localGenerateValues: GenerateWidgetValues | null;-}) => {+export const QueueItemActions = ({ item }: { item: QueueItemReadModel }) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();+ const { generation } = useWorkbenchCommands();const openWidget = useOpenWorkbenchWidget();const notify = useNotify();+ const localGenerateValues = useLocalGenerateValues(item.origin);const [jsonOpen, setJsonOpen] = useState(false);const generateValues = useWidgetValuesSelector('generate', selectGenerateRecallValues);const models = useModelsSelector((snapshot) => snapshot.models);@@ -53,9 +49,9 @@ export const QueueItemActions = ({[localGenerateValues, meta]);- useEffect(() => {+ useMountEffect(() => {ensureModelsLoaded();- }, []);+ });const onRecall = useCallback((kind: ImageRecallKind) => {@@ -67,11 +63,11 @@ export const QueueItemActions = ({return;}- dispatch({ type: 'setGenerateSettings', values });+ generation.setSettings(values);openWidget('generate', { preferredRegions: ['left'] });notify.success(getImageRecallTitle(kind), t('widgets.queue.settingsRecalledDescription'));},- [dispatch, generateValues, localGenerateValues, meta, notify, openWidget, supportedModels, t]+ [generateValues, generation, localGenerateValues, meta, notify, openWidget, supportedModels, t]);const onSendToCanvas = useCallback(@@ -106,11 +102,11 @@ export const QueueItemActions = ({<Dialog.Content bg="bg.subtle" borderColor="border.subtle" borderWidth="1px" color="fg"><Dialog.Header><Dialog.Title fontSize="sm" fontWeight="700">- {t('widgets.queue.itemTitle', { id: item.item_id })}+ {t('widgets.queue.itemTitle', { id: item.id })}</Dialog.Title></Dialog.Header><Dialog.Body>- <JsonPreview label={t('widgets.queue.itemJsonLabel', { id: item.item_id })} maxH="60vh" value={item} />+ <JsonPreview label={t('widgets.queue.itemJsonLabel', { id: item.id })} maxH="60vh" value={item} /></Dialog.Body><Dialog.CloseTrigger asChild><CloseButton color="fg.muted" size="sm" />diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueRecall.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.tssimilarity index 98%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/queueRecall.test.tsrename to invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.tsindex 74ab900d89..d63cbbc747 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts@@ -1,4 +1,4 @@-import type { GenerateWidgetValues } from '@workbench/generation/types';+import type { GenerateWidgetValues } from '@features/generation/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.tssimilarity index 94%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/queueRecall.tsrename to invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.tsindex 9295a0eca0..36cf975e61 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts@@ -1,8 +1,7 @@-import type { GenerateWidgetValues } from '@workbench/generation/types';+import type { GenerateWidgetValues } from '@features/generation/contracts';+import type { QueueGenerationMeta } from '@features/queue/contracts';import type { ImageRecallCapabilities, ImageRecallKind } from '@workbench/image-actions';-import type { QueueGenerationMeta } from './fieldValues';-/*** Snapshot/session-based recall for queue items, mirroring the image-metadata* recall semantics: partial kinds merge the recalled fields into the CURRENTdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/useLocalGenerateValues.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalGenerateValues.tssimilarity index 85%rename from invokeai/frontend/webv2/src/workbench/widgets/queue/useLocalGenerateValues.tsrename to invokeai/frontend/webv2/src/workbench/queue-integration/useLocalGenerateValues.tsindex 4722dd331d..7a5fd8f50b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/useLocalGenerateValues.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalGenerateValues.ts@@ -1,6 +1,6 @@-import type { GenerateWidgetValues } from '@workbench/generation/types';+import type { GenerateWidgetValues } from '@features/generation/contracts';-import { parseQueueItemOrigin } from '@workbench/backend/events';+import { parseQueueItemOrigin } from '@features/queue/contracts';import { useWorkbenchSelector } from '@workbench/WorkbenchContext';/**@@ -18,7 +18,7 @@ export const useLocalGenerateValues = (origin?: string | null): GenerateWidgetVareturn null;}- for (const project of snapshot.state.projects) {+ for (const project of snapshot.projects) {const localItem = project.queue.items.find((queueItem) => queueItem.id === localId);if (localItem && (localItem.snapshot.sourceId === 'generate' || localItem.snapshot.sourceId === 'canvas')) {diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.tsnew file mode 100644index 0000000000..83f2874936--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.ts@@ -0,0 +1,24 @@+import type { GenerateWidgetValues } from '@features/generation/contracts';+import type { QueueItem, QueueState, QueueSubmissionSnapshot } from '@features/queue/contracts';++import type { CanvasStateContractV2 } from './canvas-engine/api';+import type { WidgetInstanceContract, WidgetInstanceId, WidgetStateMap } from './widgetContracts';++/** Workbench-owned persistence context that Queue stores but never interprets. */+export interface WorkbenchQueueSubmissionContext {+ canvas: CanvasStateContractV2;+ generate?: {+ negativePromptNodeId: string;+ positivePromptNodeId: string;+ seedNodeId: string;+ values: GenerateWidgetValues;+ };+ widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;+ widgetStates: WidgetStateMap;+}++export type WorkbenchQueueItem = Omit<QueueItem, 'snapshot'> & {+ snapshot: QueueSubmissionSnapshot & WorkbenchQueueSubmissionContext;+};++export type WorkbenchQueueState = Omit<QueueState, 'items'> & { items: WorkbenchQueueItem[] };diff --git a/invokeai/frontend/webv2/src/workbench/queueSnapshot.ts b/invokeai/frontend/webv2/src/workbench/queueSnapshot.tsdeleted file mode 100644index 16b641b6dc..0000000000--- a/invokeai/frontend/webv2/src/workbench/queueSnapshot.ts+++ /dev/null@@ -1,37 +0,0 @@-import type { QueueItem } from './types';--import { sanitizeBatchCount } from './generation/batch';-import { getUpscaleOutputDimensions, normalizeUpscaleWidgetValues } from './upscale/settings';--/** Values owned by the source that created this immutable queue snapshot. */-export const getQueueItemSourceWidgetValues = (item: QueueItem): Record<string, unknown> => {- if (item.snapshot.sourceId === 'upscale') {- return item.snapshot.widgetStates.upscale?.values ?? {};- }-- // Canvas intentionally shares Generate settings. Workflow has no first-party- // batch form yet and keeps the historical Generate batch-count fallback.- return item.snapshot.widgetStates.generate?.values ?? {};-};--export const getQueueItemSnapshotBatchCount = (item: QueueItem): number =>- sanitizeBatchCount(getQueueItemSourceWidgetValues(item).batchCount);--export const getQueueItemSnapshotDimensions = (- item: QueueItem,- fallback: { width: number; height: number }-): { width: number; height: number } => {- if (item.snapshot.sourceId === 'upscale') {- const values = normalizeUpscaleWidgetValues(item.snapshot.widgetStates.upscale?.values);-- if (values?.inputImage) {- return getUpscaleOutputDimensions(values.inputImage, values.scale);- }- }-- const values = getQueueItemSourceWidgetValues(item);- const width = typeof values.width === 'number' && Number.isFinite(values.width) ? values.width : fallback.width;- const height = typeof values.height === 'number' && Number.isFinite(values.height) ? values.height : fallback.height;-- return { height: Math.max(1, Math.round(height)), width: Math.max(1, Math.round(width)) };-};diff --git a/invokeai/frontend/webv2/src/workbench/queueSubmission.ts b/invokeai/frontend/webv2/src/workbench/queueSubmission.tsdeleted file mode 100644index 8aba851aef..0000000000--- a/invokeai/frontend/webv2/src/workbench/queueSubmission.ts+++ /dev/null@@ -1,47 +0,0 @@-/**- * Which pending queue items the {@link import('./WorkbenchRuntime').WorkbenchRuntime}- * submission bridge is allowed to POST to the backend queue.- *- * This is the gate that decides whether a locally-enqueued `pending` queue item- * gets handed to the coordinator (`submitGenerate` / `submitWorkflow`). It lives- * in its own pure module — separate from the React effect that consumes it — so- * it can be unit-tested under node-env vitest (the runtime component cannot).- *- * ## Why `canvas` MUST be here- * Every Invoke — generate, workflow, AND canvas — first lands an optimistic local- * `pending` queue item (see `enqueueCompiledSnapshot`). The runtime loop then- * enqueues each pending item to the backend exactly once. If a source id is- * missing from this set, its items are created locally but **never POSTed**, so- * they stack in the queue as `pending` forever and nothing ever generates. That- * was the canvas→canvas stall: canvas snapshots carry `sourceId: 'canvas'`, which- * was absent from the loop's allow-list, so each Invoke only produced a dead- * local row. Canvas items use the generate-style backend submission path: the- * graph is compiled ahead of time, but prompt/seed batch data still has to ride- * along so repeated invokes are not silently run with backend primitive defaults.- *- * Upscale uses the same prompt/seed batch path as Generate after compiling its- * own immutable widget snapshot.- */--import type { InvocationSourceId, QueueItem } from './types';--/** Source kinds whose pending queue items the runtime enqueues to the backend. */-export const BACKEND_SUBMITTABLE_SOURCE_IDS = [- 'generate',- 'workflow',- 'upscale',- 'canvas',-] as const satisfies readonly InvocationSourceId[];--const BACKEND_SUBMITTABLE_SOURCE_ID_SET: ReadonlySet<InvocationSourceId> = new Set(BACKEND_SUBMITTABLE_SOURCE_IDS);--/** Whether a queue item's source is one the runtime knows how to enqueue. */-export const isBackendSubmittableSourceId = (sourceId: InvocationSourceId): boolean =>- BACKEND_SUBMITTABLE_SOURCE_ID_SET.has(sourceId);--/**- * Whether a queue item is a fresh, backend-submittable `pending` item — the- * runtime still applies its own "already started this id" dedupe on top of this.- */-export const shouldSubmitPendingQueueItem = (queueItem: QueueItem): boolean =>- queueItem.status === 'pending' && isBackendSubmittableSourceId(queueItem.snapshot.sourceId);diff --git a/invokeai/frontend/webv2/src/workbench/queueWidgetManifest.ts b/invokeai/frontend/webv2/src/workbench/queueWidgetManifest.tsnew file mode 100644index 0000000000..0f0a005546--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queueWidgetManifest.ts@@ -0,0 +1,27 @@+import type { WidgetManifest } from '@workbench/widgetContracts';++import { ListOrderedIcon } from 'lucide-react';++export const queueWidgetManifest: WidgetManifest = {+ allowMultiple: false,+ allowedRegions: ['right'],+ failurePolicy: {+ isolateRenderFailure: true,+ onRegistrationFailure: 'disable',+ },+ hasHost: true,+ icon: ListOrderedIcon,+ id: 'queue',+ label: (t) => t('widgets.labels.queue'),+ load: () =>+ import('@features/queue/widget').then((module) => ({+ footer: module.ModelCacheFooter,+ headerActions: module.QueueHeaderActions,+ headerLabel: module.QueueHeaderLabel,+ headerMenu: module.QueueHeaderMenu,+ host: module.QueueDataRuntime,+ view: module.QueueWidgetView,+ })),+ settingsSection: 'queue',+ version: 1,+};diff --git a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsxindex 240dd1a34f..da500e0a01 100644--- a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx@@ -1,7 +1,7 @@import type { HotkeyCategory, HotkeyDefinition } from '@workbench/hotkeys';import { Badge, Box, Flex, HStack, Icon, Input, InputGroup, Kbd, ScrollArea, Stack, Text } from '@chakra-ui/react';-import { Button, IconButton } from '@workbench/components/ui';+import { Button, IconButton } from '@platform/ui';import {firstPartyHotkeyCatalog,formatHotkeyForPlatform,diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsxindex f3bcebd1ae..cc7ebb5d75 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx@@ -1,13 +1,8 @@-import type {- DeveloperLogLevel,- DeveloperLogNamespace,- ProjectSettings,- Project,- SettingsSectionId,- WorkbenchLanguage,- WorkbenchPreferences,- WorkbenchThemeId,-} from '@workbench/types';+import type { WorkbenchThemeId } from '@theme/themes';+import type { DeveloperLogLevel, DeveloperLogNamespace } from '@workbench/diagnostics/contracts';+import type { Project } from '@workbench/projectContracts';+import type { ProjectSettings, WorkbenchLanguage, WorkbenchPreferences } from '@workbench/settings/contracts';+import type { SettingsSectionId } from '@workbench/widgetContracts';import {Box,@@ -26,17 +21,18 @@ import {Field,useSlotRecipe,} from '@chakra-ui/react';+import { WORKBENCH_LANGUAGE_OPTIONS } from '@platform/i18n/languages';+import { Button, CloseButton, IconButton, ConfirmDialog, Tabs, Tooltip } from '@platform/ui';import { themeCardRecipe } from '@theme/recipes';import { previewSwatches, THEMES, type ThemeDefinition } from '@theme/system';-import { Button, CloseButton, IconButton, ConfirmDialog, Tabs, Tooltip } from '@workbench/components/ui';import { registerHotkeyModalLayer } from '@workbench/hotkeys';-import { WORKBENCH_LANGUAGE_OPTIONS } from '@workbench/i18n';-import { syncedWorkbenchPersistence } from '@workbench/projects/syncedPersistence';+import { clearAllWorkbenchData } from '@workbench/projects/syncedPersistence';import {shallowEqual,- useOptionalWorkbenchDispatch,+ useHasWorkbenchProvider,+ useOptionalWorkbenchCommands,+ useOptionalWorkbenchPersistenceService,useOptionalWorkbenchSelector,- useOptionalWorkbenchStore,} from '@workbench/WorkbenchContext';import {CheckIcon,@@ -198,7 +194,7 @@ const SettingsDialogContent = ({ onClose }: { onClose: () => void }) => {const SettingsTabs = () => {const { t } = useTranslation();- const hasWorkbench = useOptionalWorkbenchStore() !== null;+ const hasWorkbench = useHasWorkbenchProvider();const settingsTabs: SettingsTabDefinition[] = useMemo(() => [{@@ -452,12 +448,12 @@ const ProjectSection = () => {null,shallowEqual);- const dispatch = useOptionalWorkbenchDispatch();+ const commands = useOptionalWorkbenchCommands();const updateProjectSettings = useCallback((patch: Partial<ProjectSettings>) => {- dispatch?.({ settings: patch, type: 'setActiveProjectSettings' });+ commands?.account.updateProjectPreferences(patch);},- [dispatch]+ [commands]);const updateUseCpuNoise = useCallback((checked: boolean) => {@@ -496,7 +492,7 @@ const ProjectSection = () => {[updateProjectSettings]);- if (!activeProject || !dispatch) {+ if (!activeProject || !commands) {return null;}@@ -719,15 +715,19 @@ const DeveloperNamespaceCheckbox = ({};const WorkspaceSection = () => {- const dispatch = useOptionalWorkbenchDispatch();+ const commands = useOptionalWorkbenchCommands();+ const mountedPersistence = useOptionalWorkbenchPersistenceService();const { scope } = useWorkbenchSettings();const [isClearConfirmOpen, setIsClearConfirmOpen] = useState(false);const clearSavedData = useCallback(async () => {- await Promise.all([syncedWorkbenchPersistence.clearWorkbench(), clearWorkbenchSettings()]);+ await Promise.all([+ mountedPersistence ? mountedPersistence.clearWorkbench() : clearAllWorkbenchData(),+ clearWorkbenchSettings(),+ ]);window.location.reload();- }, []);- const resetLayout = useCallback(() => dispatch?.({ type: 'resetActiveLayout' }), [dispatch]);+ }, [mountedPersistence]);+ const resetLayout = useCallback(() => commands?.layout.reset(), [commands]);const openClearConfirm = useCallback(() => setIsClearConfirmOpen(true), []);const closeClearConfirm = useCallback(() => setIsClearConfirmOpen(false), []);@@ -737,7 +737,7 @@ const WorkspaceSection = () => {title="Workspace"><HStack gap="2" wrap="wrap">- {dispatch ? (+ {commands ? (<Button size="sm" variant="outline" onClick={resetLayout}><RotateCcwIcon />Reset layoutdiff --git a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts b/invokeai/frontend/webv2/src/workbench/settings/contracts.tsnew file mode 100644index 0000000000..d54fddb39a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts@@ -0,0 +1,40 @@+import type { WorkbenchLanguage } from '@platform/i18n/languages';+import type { WorkbenchThemeId } from '@theme/themes';+import type { DeveloperLogLevel, DeveloperLogNamespace } from '@workbench/diagnostics/contracts';++export type { WorkbenchLanguage } from '@platform/i18n/languages';++export interface ProjectSettings {+ useCpuNoise: boolean;+ showProgressDetails: boolean;+ antialiasProgressImages: boolean;+ showProgressImagesInViewer: boolean;+ preferNumericAttentionStyle: boolean;+ showPromptSyntaxHighlighting: boolean;+}++/** User-tunable appearance + behavior preferences surfaced in the Settings modal. */+export interface WorkbenchPreferences {+ themeId: WorkbenchThemeId;+ reduceMotion: boolean;+ showFocusRegionHighlight: boolean;+ confirmImageDeletion: boolean;+ queueJobsScope: 'active-project' | 'all';+ language: WorkbenchLanguage;+ enableInformationalPopovers: boolean;+ enableModelDescriptions: boolean;+ developerLogEnabled: boolean;+ developerLogLevel: DeveloperLogLevel;+ developerLogNamespaces: DeveloperLogNamespace[];+ developerPerformanceTimingsEnabled: boolean;+ /** Always snap workflow nodes to the grid (Ctrl snaps temporarily when off). */+ workflowSnapToGrid: boolean;+ /** Show the minimap in the workflow editor. */+ workflowShowMinimap: boolean;+ /** Reject workflow connections with incompatible field types. */+ workflowValidateConnections: boolean;+ /** Connection line rendering in the workflow editor. */+ workflowEdgeStyle: 'curved' | 'square';+ /** Account-bound overrides keyed by hotkey id (`app.invoke`, `gallery.galleryNavLeft`, etc.). */+ customHotkeys: Record<string, string[]>;+}diff --git a/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts b/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.tsindex 5806ffa491..13b9f05c4c 100644--- a/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts@@ -1,6 +1,6 @@-import type { SettingsSectionId } from '@workbench/types';+import type { SettingsSectionId } from '@workbench/widgetContracts';-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';/*** Open/close state for the workbench settings dialog, addressable fromdiff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.tsindex 6d8b4beb10..12d7a8d3a3 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts@@ -30,7 +30,7 @@ const api = vi.hoisted(() => {const auth = vi.hoisted(() => ({ scope: '' }));vi.mock('../projects/api', () => api);-vi.mock('../auth/session', () => ({ getUserStorageScope: () => auth.scope }));+vi.mock('@features/identity', () => ({ getUserStorageScope: () => auth.scope }));const storage = new Map<string, string>();diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex f96f4a9feb..082f448443 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -1,13 +1,15 @@-import type { DeveloperLogLevel, DeveloperLogNamespace, ProjectSettings, WorkbenchPreferences } from '@workbench/types';+import type { DeveloperLogLevel, DeveloperLogNamespace } from '@workbench/diagnostics/contracts';+import type { ProjectSettings, WorkbenchPreferences } from '@workbench/settings/contracts';+import { getUserStorageScope } from '@features/identity';+import { normalizeWorkbenchLanguage } from '@platform/i18n/languages';+import { createExternalStore } from '@platform/state/externalStore';+import { createSingleFlight } from '@platform/state/singleFlight';import { DEFAULT_THEME_ID, isWorkbenchThemeId } from '@theme/themes';-import { getUserStorageScope } from '@workbench/auth/session';-import { createExternalStore } from '@workbench/externalStore';-import { normalizeWorkbenchLanguage } from '@workbench/i18n/languages';import { deleteClientStateValue, getClientStateValue, setClientStateValue } from '@workbench/projects/api';import { fetchSessionBlob } from '@workbench/projects/session';-export { WORKBENCH_LANGUAGES } from '@workbench/i18n/languages';+export { WORKBENCH_LANGUAGES } from '@platform/i18n/languages';const SETTINGS_BASE_STORAGE_KEY = 'invokeai:v7:webv2:settings';const LEGACY_WORKBENCH_BASE_STORAGE_KEY = 'invokeai:v7:webv2:workbench';@@ -60,6 +62,8 @@ export const DEFAULT_PREFERENCES: WorkbenchPreferences = {};interface WorkbenchSettingsSnapshot {+ /** Account-scope storage key these preferences were hydrated for; null until a load succeeds. */+ hydratedStorageKey: string | null;preferences: WorkbenchPreferences;scope: 'global' | 'user';status: 'idle' | 'loading' | 'ready' | 'error';@@ -67,6 +71,7 @@ interface WorkbenchSettingsSnapshot {}const store = createExternalStore<WorkbenchSettingsSnapshot>({+ hydratedStorageKey: null,preferences: DEFAULT_PREFERENCES,scope: 'global',status: 'idle',@@ -295,8 +300,12 @@ const loadLegacySessionPreferences = async (): Promise<WorkbenchPreferences | nureturn blob?.account.preferences ? normalizeWorkbenchPreferences(blob.account.preferences) : null;};-const replaceSnapshot = (preferences: WorkbenchPreferences, status: WorkbenchSettingsSnapshot['status']): void => {- store.setSnapshot({ preferences, scope: getSettingsScope(), status });+const replaceSnapshot = (+ preferences: WorkbenchPreferences,+ status: WorkbenchSettingsSnapshot['status'],+ hydratedStorageKey: string | null = store.getSnapshot().hydratedStorageKey+): void => {+ store.setSnapshot({ hydratedStorageKey, preferences, scope: getSettingsScope(), status });};const pushPreferences = (preferences: WorkbenchPreferences): Promise<void> =>@@ -328,9 +337,7 @@ const resolveSettings = async (local: StoredSettings | null): Promise<WorkbenchPreturn preferences;};-let pendingLoad: Promise<WorkbenchPreferences> | null = null;-let pendingLoadStorageKey = '';-let loadedStorageKey: string | null = null;+const settingsLoad = createSingleFlight<WorkbenchPreferences>();/*** Resolve settings once per account scope (a sign-in/out switches scope and@@ -340,26 +347,19 @@ let loadedStorageKey: string | null = null;export const loadWorkbenchSettings = (): Promise<WorkbenchPreferences> => {const storageKey = getSettingsStorageKey();- if (pendingLoad && pendingLoadStorageKey === storageKey) {- return pendingLoad;- }-- if (loadedStorageKey === storageKey) {+ if (store.getSnapshot().hydratedStorageKey === storageKey) {return Promise.resolve(getWorkbenchPreferences());}- pendingLoadStorageKey = storageKey;- store.patchSnapshot({ scope: getSettingsScope(), status: 'loading' });-- pendingLoad = (async () => {+ return settingsLoad.run(storageKey, async () => {+ store.patchSnapshot({ scope: getSettingsScope(), status: 'loading' });const local = readLocalSettings();try {const preferences = await resolveSettings(local);writeLocalSettings(preferences);- replaceSnapshot(preferences, 'ready');- loadedStorageKey = storageKey;+ replaceSnapshot(preferences, 'ready', storageKey);return preferences;} catch (error) {@@ -369,6 +369,7 @@ export const loadWorkbenchSettings = (): Promise<WorkbenchPreferences> => {writeLocalSettings(preferences, local?.pendingPush);store.setSnapshot({error: error instanceof Error ? error.message : 'Failed to load settings from the backend.',+ hydratedStorageKey: null,preferences,scope: getSettingsScope(),status: fallback ? 'ready' : 'error',@@ -376,11 +377,7 @@ export const loadWorkbenchSettings = (): Promise<WorkbenchPreferences> => {return preferences;}- })().finally(() => {- pendingLoad = null;});-- return pendingLoad;};export const useWorkbenchSettings = (): WorkbenchSettingsSnapshot => store.useSnapshot();@@ -402,6 +399,13 @@ export const useWorkbenchPreferenceSelector = <Selected>(export const getWorkbenchPreferences = (): WorkbenchPreferences => store.getSnapshot().preferences;+/** Non-React runtimes use this to keep infrastructure configuration current. */+export const subscribeWorkbenchPreferences = (listener: (preferences: WorkbenchPreferences) => void): (() => void) => {+ listener(store.getSnapshot().preferences);++ return store.subscribe(() => listener(store.getSnapshot().preferences));+};+export const getWorkbenchReduceMotion = (): boolean => store.getSnapshot().preferences.reduceMotion;export const useWorkbenchReduceMotion = (): boolean =>@@ -426,8 +430,7 @@ export const patchWorkbenchPreferences = async (preferences: Partial<WorkbenchPrexport const clearWorkbenchSettings = async (): Promise<void> => {removeLocalSettings();- replaceSnapshot(normalizeWorkbenchPreferences(), 'ready');- loadedStorageKey = getSettingsStorageKey();+ replaceSnapshot(normalizeWorkbenchPreferences(), 'ready', getSettingsStorageKey());try {await deleteClientStateValue(SETTINGS_CLIENT_STATE_KEY);diff --git a/invokeai/frontend/webv2/src/workbench/shell/BottomPanel.tsx b/invokeai/frontend/webv2/src/workbench/shell/BottomPanel.tsxindex 0adf0588cd..2d00d8d461 100644--- a/invokeai/frontend/webv2/src/workbench/shell/BottomPanel.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/BottomPanel.tsx@@ -14,7 +14,6 @@ export const BottomPanel = () => {areWidgetRenderInstancesEqual);const widget = instance ? getWidgetById(instance.typeId) : undefined;- const View = widget?.manifest.view;const canShowBottomPanel =panels.isBottomOpen &&!bottomRegion.isCollapsed &&@@ -26,7 +25,7 @@ export const BottomPanel = () => {return null;}- if (!instance || !widget || !View) {+ if (!instance || !widget) {return (<MissingWidgetFramelabel={widget ? resolveWidgetLabel(widget.manifest, t) : bottomRegion.activeInstanceId}diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsxindex 88865de6b5..1823cafe40 100644--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx@@ -7,13 +7,13 @@ import type {import { Box, Flex, Text } from '@chakra-ui/react';import { horizontalListSortingStrategy } from '@dnd-kit/sortable';-import { useModelLoads } from '@workbench/backend/modelLoadStore';-import { useQueueItemProgress } from '@workbench/backend/progressStore';+import { useModelLoads } from '@features/models';+import { getProjectQueueIndicatorState, type QueueProgressBarState } from '@features/queue/contracts';+import { useQueueItemProgress } from '@features/queue/react';+import { Tabs } from '@platform/ui';import { QueueTabBackgroundProgress } from '@workbench/components/QueueProgressIndicator';-import { Tabs } from '@workbench/components/ui';import { useFocusRegionProps } from '@workbench/focusRegions';import { WidgetIcon } from '@workbench/iconResolver';-import { getProjectQueueIndicatorState, type QueueProgressBarState } from '@workbench/queueSummary';import {WidgetEnableMenu,WidgetInstanceContextMenu,@@ -32,7 +32,7 @@ import {isRequiredCenterView,} from '@workbench/widgetRegionViewModel';import { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';-import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchSelector } from '@workbench/WorkbenchContext';import { type MouseEvent, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -49,9 +49,9 @@ export const CenterArea = ({ dropState }: { dropState: WidgetRegionDropState })const centerRegion = useActiveProjectSelector((project) => project.widgetRegions.center);const invocation = useActiveProjectSelector((project) => project.invocation);const queueItems = useActiveProjectSelector((project) => project.queue.items);- const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);+ const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.backendConnection.status);const modelLoads = useModelLoads();- const dispatch = useWorkbenchDispatch();+ const { widgets } = useWorkbenchCommands();const [enableMenuTarget, setEnableMenuTarget] = useState<{x: number;y: number;@@ -115,14 +115,14 @@ export const CenterArea = ({ dropState }: { dropState: WidgetRegionDropState })(item: WidgetEnableMenuItem) =>item.isEnabled? closeWidgetPlacement({- dispatch,+ widgets,getWidgetById,instanceId: item.id,project: placementProject,region: 'center',}): openWidgetPlacement({- dispatch,+ widgets,getWidgetsForRegion,options: {createNew: item.allowMultiple,@@ -130,18 +130,18 @@ export const CenterArea = ({ dropState }: { dropState: WidgetRegionDropState })},typeId: item.typeId,}),- [dispatch, placementProject]+ [placementProject, widgets]);const handleCenterTabChange = useCallback((event: { value: string }) =>revealWidgetPlacement({- dispatch,instanceId: event.value as CenterWidgetItem['id'],project: placementProject,region: 'center',+ widgets,}),- [dispatch, placementProject]+ [placementProject, widgets]);const handleContextClose = useCallback(() => setEnableMenuTarget(null), []);@@ -290,9 +290,7 @@ const CenterViewSlot = ({}) => {const widget = items.find((item) => item.id === activeWidgetId)?.widget;const instance = items.find((item) => item.id === activeWidgetId)?.instance;- const View = widget?.manifest.view;-- if (!instance || !widget || widget.status !== 'enabled' || !View) {+ if (!instance || !widget || widget.status !== 'enabled') {return <FallbackCenterView label="Center widget unavailable" />;}diff --git a/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx b/invokeai/frontend/webv2/src/workbench/shell/Panels.tsxindex f16aef41cc..1f8365d33d 100644--- a/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx@@ -1,4 +1,4 @@-import type { WidgetInstanceId, WorkbenchRegion } from '@workbench/types';+import type { WidgetInstanceId, WorkbenchRegion } from '@workbench/widgetContracts';import { MissingWidgetFrame, WidgetRendererById } from '@workbench/widget-frame';import { areWidgetRenderInstancesEqual } from '@workbench/widget-frame/widgetRenderInstance';@@ -29,10 +29,9 @@ const WidgetPanelSlot = ({ instanceId, panel }: { instanceId: WidgetInstanceId;areWidgetRenderInstancesEqual);const widget = instance ? getWidgetById(instance.typeId) : undefined;- const View = widget?.manifest.view;const region = panelRegions[panel];- if (!instance || !widget || widget.status !== 'enabled' || !View) {+ if (!instance || !widget || widget.status !== 'enabled') {return <MissingWidgetFrame label={widget ? resolveWidgetLabel(widget.manifest, t) : instanceId} region={region} />;}diff --git a/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsx b/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsxindex c5c46e7722..160dd799a2 100644--- a/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsx@@ -1,10 +1,10 @@-import type { WidgetInstanceId } from '@workbench/types';+import type { WidgetInstanceId } from '@workbench/widgetContracts';import type { WidgetRegionDropState } from '@workbench/widgetDnd';import type { PlacedWidgetRegionItem, WidgetPlacementInstanceMeta } from '@workbench/widgetRegionViewModel';import { Box } from '@chakra-ui/react';import { horizontalListSortingStrategy } from '@dnd-kit/sortable';-import { Row, Tooltip } from '@workbench/components/ui';+import { Row, Tooltip } from '@platform/ui';import {WidgetEnableMenu,WidgetInstanceContextMenu,@@ -24,7 +24,7 @@ import {isExpandableBottomItem,} from '@workbench/widgetRegionViewModel';import { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { type KeyboardEvent, type MouseEvent, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -42,7 +42,7 @@ export const StatusBar = ({ dropState }: { dropState: WidgetRegionDropState }) =const { t } = useTranslation();const placementProject = useActiveProjectSelector(getWidgetPlacementProject, areWidgetPlacementProjectsEqual);const bottomRegion = useActiveProjectSelector((project) => project.widgetRegions.bottom);- const dispatch = useWorkbenchDispatch();+ const { widgets } = useWorkbenchCommands();const [enableMenuTarget, setEnableMenuTarget] = useState<{ x: number; y: number } | null>(null);const [instanceMenuTarget, setInstanceMenuTarget] = useState<WidgetInstanceContextMenuTarget | null>(null);const getWidgetLabel = useCallback(@@ -78,24 +78,24 @@ export const StatusBar = ({ dropState }: { dropState: WidgetRegionDropState }) =(item: WidgetEnableMenuItem) =>item.isEnabled? closeWidgetPlacement({- dispatch,+ widgets,getWidgetById,instanceId: item.id,project: placementProject,region: 'bottom',}): openWidgetPlacement({- dispatch,+ widgets,getWidgetsForRegion,options: { createNew: item.allowMultiple, preferredRegions: ['bottom'] },typeId: item.typeId,}),- [dispatch, placementProject]+ [placementProject, widgets]);const handleSelect = useCallback((instanceId: WidgetInstanceId) =>- revealWidgetPlacement({ dispatch, instanceId, project: placementProject, region: 'bottom' }),- [dispatch, placementProject]+ revealWidgetPlacement({ instanceId, project: placementProject, region: 'bottom', widgets }),+ [placementProject, widgets]);const handleContextClose = useCallback(() => setEnableMenuTarget(null), []);const handleInstanceClose = useCallback(() => setInstanceMenuTarget(null), []);@@ -160,7 +160,6 @@ const CompactBottomWidget = ({onContextMenu: (item: BottomWidgetItem, event: MouseEvent) => void;onSelect: (widgetId: WidgetInstanceId) => void;}) => {- const View = item.widget.manifest.view;const { dragHandleProps, isDragging, setNodeRef, style } = useWidgetSortable({instanceId: item.id,region: 'bottom',@@ -197,10 +196,6 @@ const CompactBottomWidget = ({const handleContextMenu = useCallback((event: MouseEvent) => onContextMenu(item, event), [item, onContextMenu]);const tooltipContent = useMemo(() => (item.instance ? <BottomWidgetTooltipContent item={item} /> : null), [item]);- if (!View) {- return null;- }-const content = (<Box ref={setNodeRef} h="full" style={style}><Rowdiff --git a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsxindex 3150eb75de..9948ecbe8b 100644--- a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx@@ -11,6 +11,7 @@ import {} from '@dnd-kit/core';import { restrictToWindowEdges } from '@dnd-kit/modifiers';import { sortableKeyboardCoordinates } from '@dnd-kit/sortable';+import { useMountEffect } from '@platform/react/useMountEffect';import { FocusRegionProvider } from '@workbench/focusRegions';import { WidgetIcon } from '@workbench/iconResolver';import { WidgetBar } from '@workbench/widget-frame';@@ -32,9 +33,8 @@ import {import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';import { createWidgetRegionViewModelFromState, getWidgetRegionItems } from '@workbench/widgetRegionViewModel';import { getWidgetById, getWidgetsForRegion, widgetRegistrationFailures } from '@workbench/widgetRegistry';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { WorkbenchWidgetRegistryProvider } from '@workbench/WorkbenchWidgetRegistryContext';-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { BottomPanel } from './BottomPanel';@@ -47,7 +47,7 @@ import { TopBar } from './topbar';const DND_MODIFIERS = [restrictToWindowEdges];export const WorkbenchShell = () => {- const dispatch = useWorkbenchDispatch();+ const { notifications, widgets } = useWorkbenchCommands();const { t } = useTranslation();const panels = useActiveProjectSelector((project) => project.layout.panels);const leftRegion = useActiveProjectSelector((project) => project.widgetRegions.left);@@ -113,11 +113,11 @@ export const WorkbenchShell = () => {[activeDrag, placementProject]);- useEffect(() => {+ useMountEffect(() => {for (const failure of widgetRegistrationFailures) {- dispatch({ failure, type: 'recordWidgetFailure' });+ notifications.recordWidgetFailure(failure);}- }, [dispatch]);+ });const handleDragStart = useCallback((event: DragStartEvent) => {@@ -162,108 +162,106 @@ export const WorkbenchShell = () => {return;}- dispatchWidgetDragEndPlacement({ dispatch, resolution });+ dispatchWidgetDragEndPlacement({ resolution, widgets });},- [dispatch, placementProject]+ [placementProject, widgets]);const handleDragCancel = useCallback(() => setActiveDrag(null), []);const handleSelectLeft = useCallback(- (instanceId: string) => revealWidgetPlacement({ dispatch, instanceId, project: placementProject, region: 'left' }),- [dispatch, placementProject]+ (instanceId: string) => revealWidgetPlacement({ instanceId, project: placementProject, region: 'left', widgets }),+ [placementProject, widgets]);const handleSelectRight = useCallback(- (instanceId: string) => revealWidgetPlacement({ dispatch, instanceId, project: placementProject, region: 'right' }),- [dispatch, placementProject]+ (instanceId: string) => revealWidgetPlacement({ instanceId, project: placementProject, region: 'right', widgets }),+ [placementProject, widgets]);const handleToggleLeft = useCallback((item: (typeof leftMenuItems)[number]) =>item.isEnabled? closeWidgetPlacement({- dispatch,+ widgets,getWidgetById,instanceId: item.id,project: placementProject,region: 'left',}): openWidgetPlacement({- dispatch,+ widgets,getWidgetsForRegion,options: { createNew: item.allowMultiple, preferredRegions: ['left'] },typeId: item.typeId,}),- [dispatch, placementProject]+ [placementProject, widgets]);const handleToggleRight = useCallback((item: (typeof rightMenuItems)[number]) =>item.isEnabled? closeWidgetPlacement({- dispatch,+ widgets,getWidgetById,instanceId: item.id,project: placementProject,region: 'right',}): openWidgetPlacement({- dispatch,+ widgets,getWidgetsForRegion,options: { createNew: item.allowMultiple, preferredRegions: ['right'] },typeId: item.typeId,}),- [dispatch, placementProject]+ [placementProject, widgets]);return (- <WorkbenchWidgetRegistryProvider getWidgetById={getWidgetById} getWidgetsForRegion={getWidgetsForRegion}>- <FocusRegionProvider>- <DndContext- collisionDetection={widgetCollisionDetection}- modifiers={DND_MODIFIERS}- sensors={sensors}- onDragCancel={handleDragCancel}- onDragEnd={handleDragEnd}- onDragStart={handleDragStart}- >- <Flex direction="column" h="100vh" w="100vw">- <WorkbenchNotificationToaster />- <TopBar />+ <FocusRegionProvider>+ <DndContext+ collisionDetection={widgetCollisionDetection}+ modifiers={DND_MODIFIERS}+ sensors={sensors}+ onDragCancel={handleDragCancel}+ onDragEnd={handleDragEnd}+ onDragStart={handleDragStart}+ >+ <Flex direction="column" h="100vh" w="100vw">+ <WorkbenchNotificationToaster />+ <TopBar />- <Flex as="main" flex="1" minH="0" overflow="hidden">- <WidgetBar- activeId={panels.isLeftOpen && !leftRegion.isCollapsed ? leftRegion.activeInstanceId : null}- dropState={leftDropState}- menuItems={leftMenuItems}- railItems={leftRailItems}- region="left"- side="left"- onSelect={handleSelectLeft}- onToggle={handleToggleLeft}- />- {panels.isLeftOpen && !leftRegion.isCollapsed && canShowLeftPanel ? (- <LeftPanel instanceId={leftRegion.activeInstanceId} />- ) : null}- <CenterArea dropState={centerDropState} />- {panels.isRightOpen && !rightRegion.isCollapsed && canShowRightPanel ? (- <RightPanel instanceId={rightRegion.activeInstanceId} />- ) : null}- <WidgetBar- activeId={panels.isRightOpen && !rightRegion.isCollapsed ? rightRegion.activeInstanceId : null}- dropState={rightDropState}- menuItems={rightMenuItems}- railItems={rightRailItems}- region="right"- side="right"- onSelect={handleSelectRight}- onToggle={handleToggleRight}- />- </Flex>-- <BottomPanel />- <StatusBar dropState={bottomDropState} />+ <Flex as="main" flex="1" minH="0" overflow="hidden">+ <WidgetBar+ activeId={panels.isLeftOpen && !leftRegion.isCollapsed ? leftRegion.activeInstanceId : null}+ dropState={leftDropState}+ menuItems={leftMenuItems}+ railItems={leftRailItems}+ region="left"+ side="left"+ onSelect={handleSelectLeft}+ onToggle={handleToggleLeft}+ />+ {panels.isLeftOpen && !leftRegion.isCollapsed && canShowLeftPanel ? (+ <LeftPanel instanceId={leftRegion.activeInstanceId} />+ ) : null}+ <CenterArea dropState={centerDropState} />+ {panels.isRightOpen && !rightRegion.isCollapsed && canShowRightPanel ? (+ <RightPanel instanceId={rightRegion.activeInstanceId} />+ ) : null}+ <WidgetBar+ activeId={panels.isRightOpen && !rightRegion.isCollapsed ? rightRegion.activeInstanceId : null}+ dropState={rightDropState}+ menuItems={rightMenuItems}+ railItems={rightRailItems}+ region="right"+ side="right"+ onSelect={handleSelectRight}+ onToggle={handleToggleRight}+ /></Flex>- <DragOverlay>{activeDrag ? <WidgetDragPreview activeDrag={activeDrag} /> : null}</DragOverlay>- </DndContext>- </FocusRegionProvider>- </WorkbenchWidgetRegistryProvider>++ <BottomPanel />+ <StatusBar dropState={bottomDropState} />+ </Flex>+ <DragOverlay>{activeDrag ? <WidgetDragPreview activeDrag={activeDrag} /> : null}</DragOverlay>+ </DndContext>+ </FocusRegionProvider>);};diff --git a/invokeai/frontend/webv2/src/workbench/shell/notifications/WorkbenchNotificationToaster.tsx b/invokeai/frontend/webv2/src/workbench/shell/notifications/WorkbenchNotificationToaster.tsxindex f148ebeb83..5b0bb91131 100644--- a/invokeai/frontend/webv2/src/workbench/shell/notifications/WorkbenchNotificationToaster.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/notifications/WorkbenchNotificationToaster.tsx@@ -1,6 +1,6 @@-import type { WorkbenchNotificationKind } from '@workbench/types';+import type { WorkbenchNotificationKind } from '@workbench/projectContracts';-import { toaster } from '@workbench/components/ui';+import { toaster } from '@platform/ui';import { useWorkbenchSelector } from '@workbench/WorkbenchContext';import { useEffect, useRef } from 'react';@@ -11,7 +11,7 @@ const notificationToastType: Record<WorkbenchNotificationKind, 'error' | 'info'};export const WorkbenchNotificationToaster = () => {- const notifications = useWorkbenchSelector((snapshot) => snapshot.state.notifications);+ const notifications = useWorkbenchSelector((snapshot) => snapshot.notifications);const toastedNotificationIdsRef = useRef<Set<string> | null>(null);useEffect(() => {diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsxindex 7aa34fcad5..f924eb6339 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx@@ -1,6 +1,6 @@import { NumberInput } from '@chakra-ui/react';-import { MIN_BATCH_COUNT, sanitizeBatchCount } from '@workbench/generation/batch';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { MIN_BATCH_COUNT, sanitizeBatchCount } from '@features/generation/batch';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { useCallback } from 'react';const getBatchCount = (values: Record<string, unknown>): number => {@@ -20,18 +20,18 @@ export const BatchCountField = () => {},(left, right) => left.batchCount === right.batchCount && left.sourceId === right.sourceId);- const dispatch = useWorkbenchDispatch();+ const { generation, widgets } = useWorkbenchCommands();const handleValueChange = useCallback(({ valueAsNumber }: { valueAsNumber: number }) => {if (Number.isFinite(valueAsNumber)) {if (sourceId === 'upscale') {- dispatch({ type: 'patchWidgetValues', values: { batchCount: valueAsNumber }, widgetId: 'upscale' });+ widgets.patchValues('upscale', { batchCount: valueAsNumber });} else {- dispatch({ batchCount: valueAsNumber, type: 'setGenerateBatchCount' });+ generation.setBatchCount(valueAsNumber);}}},- [dispatch, sourceId]+ [generation, sourceId, widgets]);return (diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsxindex 823d1b3faa..aa93a6a908 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx@@ -1,10 +1,12 @@-/* eslint-disable react/react-compiler */-import type { InvocationRoute, InvocationSourceId, ResultDestination } from '@workbench/types';+import type { InvocationRoute, InvocationSourceId, ResultDestination } from '@workbench/invocationContracts';import { Flex, Group, HStack, Icon, Menu, Portal, Separator, Stack, Text, VStack } from '@chakra-ui/react';-import { Button, IconButton, Tooltip } from '@workbench/components/ui';-import { sanitizeBatchCount } from '@workbench/generation/batch';-import { useMountEffect } from '@workbench/hooks/useMountEffect';+import { sanitizeBatchCount } from '@features/generation/batch';+import { flushGenerateDrafts } from '@features/generation/drafts';+import { ensureModelsLoaded, useModelsSelector } from '@features/models';+import { useInvocationTemplatesSelector } from '@features/workflow/react';+import { useMountEffect } from '@platform/react/useMountEffect';+import { Button, IconButton, Tooltip } from '@platform/ui';import {formatRoute,createInvocationRouteInputSelector,@@ -16,18 +18,14 @@ import {resultDestinations,} from '@workbench/invocation';import { submitResolvedInvocation } from '@workbench/invocationSubmit';-import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';-import { prepareCanvasInvocation } from '@workbench/widgets/canvas/invoke/prepareCanvasInvocation';-import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';import {useActiveProjectSelector,- useWorkbenchDispatch,+ useWorkbenchCommands,+ useWorkbenchQueries,useWorkbenchSelector,- useWorkbenchStore,} from '@workbench/WorkbenchContext';-import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';import { CheckIcon, ChevronDownIcon, LockKeyholeIcon, SparklesIcon } from 'lucide-react';-import { useCallback, useMemo, useRef } from 'react';+import { useCallback, useMemo } from 'react';const CONTROL_WIDTH = '10rem';const selectInvocationRouteInput = createInvocationRouteInputSelector();@@ -105,9 +103,10 @@ const InvokeTooltipContent = ({export const InvokeControl = () => {const routeInput = useActiveProjectSelector(selectInvocationRouteInput);- const dispatch = useWorkbenchDispatch();- const store = useWorkbenchStore();- const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);+ const commands = useWorkbenchCommands();+ const { generation } = commands;+ const queries = useWorkbenchQueries();+ const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.backendConnection.status);const models = useModelsSelector((snapshot) => snapshot.models);const modelsStatus = useModelsSelector((snapshot) => snapshot.status);const availabilityModels = modelsStatus === 'loaded' ? models : undefined;@@ -127,36 +126,33 @@ export const InvokeControl = () => {);const isValid = isInvocationRouteValid(resolvedRoute) && isConnected;const routeLabel = isValid ? formatRoute(resolvedRoute) : (blockingReasons[0] ?? formatRoute(resolvedRoute));- const modelsRef = useRef(availabilityModels);-- modelsRef.current = availabilityModels;-useMountEffect(() => {ensureModelsLoaded();});- const onInvoke = useCallback(() => {+ const onInvoke = useCallback(async () => {flushGenerateDrafts();- const snapshot = store.getSnapshot();+ const { prepareCanvasInvocation } = await import('@workbench/widgets/canvas/invoke/prepareCanvasInvocation');+ const snapshot = queries.getSnapshot();const postFlushRoute = resolveInvocationRoute(snapshot.activeProject,'global',snapshot.activeProject.invocation,- modelsRef.current+ availabilityModels);- if (!isInvocationRouteValid(postFlushRoute) || snapshot.state.backendConnection.status !== 'connected') {+ if (!isInvocationRouteValid(postFlushRoute) || snapshot.backendConnection.status !== 'connected') {return;}submitResolvedInvocation({- dispatch,- models: modelsRef.current,+ commands,+ models: availabilityModels,prepareCanvasInvocation,project: snapshot.activeProject,route: postFlushRoute,});- }, [dispatch, store]);+ }, [availabilityModels, commands, queries]);const tooltipContent = useMemo(() => (<InvokeTooltipContent@@ -178,18 +174,13 @@ export const InvokeControl = () => {]);const handleSourceChange = useCallback(- (event: { value: string }) =>- dispatch({ sourceId: event.value as InvocationSourceId, type: 'setInvocationSource' }),- [dispatch]+ (event: { value: string }) => generation.setSource(event.value as InvocationSourceId),+ [generation]);const handleDestinationChange = useCallback(- (event: { value: string }) =>- dispatch({ destination: event.value as ResultDestination, type: 'setInvocationDestination' }),- [dispatch]+ (event: { value: string }) => generation.setDestination(event.value as ResultDestination),+ [generation]);- const handleToggleSourceLock = useCallback(() => dispatch({ type: 'toggleSourceLock' }), [dispatch]);- const handleToggleDestinationLock = useCallback(() => dispatch({ type: 'toggleDestinationLock' }), [dispatch]);-return (<Flex><Menu.Root positioning={MENU_POSITIONING}>@@ -278,11 +269,11 @@ export const InvokeControl = () => {<Menu.Separator borderColor="border.subtle" />- <Menu.Item value="lock-source" closeOnSelect={false} onClick={handleToggleSourceLock}>+ <Menu.Item value="lock-source" closeOnSelect={false} onClick={generation.toggleSourceLock}><Icon as={LockKeyholeIcon} boxSize="3" opacity={invocation.sourceLocked ? 1 : 0.35} /><Menu.ItemText>{invocation.sourceLocked ? 'Unlock source' : 'Lock source'}</Menu.ItemText></Menu.Item>- <Menu.Item value="lock-destination" closeOnSelect={false} onClick={handleToggleDestinationLock}>+ <Menu.Item value="lock-destination" closeOnSelect={false} onClick={generation.toggleDestinationLock}><Icon as={LockKeyholeIcon} boxSize="3" opacity={invocation.destinationLocked ? 1 : 0.35} /><Menu.ItemText>{invocation.destinationLocked ? 'Unlock destination' : 'Lock destination'}diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetMenu.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetMenu.tsxindex 124818bc33..42fe080e12 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetMenu.tsx@@ -1,11 +1,12 @@-import type { LayoutPreset } from '@workbench/types';+import type { LayoutPreset } from '@workbench/layoutContracts';import type { MouseEvent } from 'react';import { HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';-import { Button, ConfirmDialog, IconButton, MenuContent, RenameDialog } from '@workbench/components/ui';+import { Button, ConfirmDialog, IconButton, MenuContent, RenameDialog } from '@platform/ui';import { layoutPresets } from '@workbench/layoutPresets';import { areLayoutPresetSnapshotsEqual, createLayoutPresetSnapshot } from '@workbench/layoutPresetSnapshots';-import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { preloadWidget } from '@workbench/widgetRegistry';+import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchSelector } from '@workbench/WorkbenchContext';import { CheckIcon, ChevronDownIcon, EllipsisVerticalIcon, PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react';import { useCallback, useMemo, useState } from 'react';@@ -24,11 +25,21 @@ const MENU_POSITIONING = { placement: 'bottom-end' } as const;const TRIGGER_HOVER_PROPS = { bg: 'bg.muted' };const DISABLED_PROPS = { opacity: 0.45 };+const preloadLayoutPreset = (preset: LayoutPreset): void => {+ for (const region of Object.values(preset.snapshot.widgetRegions)) {+ const typeId = preset.snapshot.widgetInstances[region.activeInstanceId]?.typeId;++ if (typeId) {+ preloadWidget(typeId);+ }+ }+};+/** Global layout preset registry surfaced as a menu. */export const LayoutPresetMenu = () => {const activeLayoutSnapshot = useActiveProjectSelector(createLayoutPresetSnapshot, areLayoutPresetSnapshotsEqual);- const customPresets = useWorkbenchSelector((snapshot) => snapshot.state.account.customLayoutPresets ?? []);- const dispatch = useWorkbenchDispatch();+ const customPresets = useWorkbenchSelector((snapshot) => snapshot.account.customLayoutPresets ?? []);+ const { layout } = useWorkbenchCommands();const [isAddOpen, setIsAddOpen] = useState(false);const [renameTarget, setRenameTarget] = useState<LayoutPreset | null>(null);const [deleteTarget, setDeleteTarget] = useState<LayoutPreset | null>(null);@@ -42,27 +53,30 @@ export const LayoutPresetMenu = () => {const addPreset = useCallback((label: string) => {- dispatch({ label, presetId: createCustomPresetId(), type: 'addLayoutPreset' });+ layout.createPreset(createCustomPresetId(), label);},- [dispatch]+ [layout]);const renamePreset = useCallback((preset: LayoutPreset, label: string) => {- dispatch({ label, presetId: preset.id, type: 'renameLayoutPreset' });+ layout.renamePreset(preset.id, label);},- [dispatch]+ [layout]);const deletePreset = useCallback((preset: LayoutPreset) => {- dispatch({ presetId: preset.id, type: 'deleteLayoutPreset' });+ layout.deletePreset(preset.id);},- [dispatch]+ [layout]);const applyPreset = useCallback(- (preset: LayoutPreset) => dispatch({ presetId: preset.id, type: 'applyPreset' }),- [dispatch]+ (preset: LayoutPreset) => {+ preloadLayoutPreset(preset);+ layout.applyPreset(preset.id);+ },+ [layout]);const openActionMenu = useCallback((preset: LayoutPreset, event: MouseEvent<HTMLElement>) => {event.preventDefault();@@ -123,6 +137,7 @@ export const LayoutPresetMenu = () => {matchingPreset={matchingPreset}presets={layoutPresets}onApply={applyPreset}+ onPreload={preloadLayoutPreset}/>{customPresets.length ? (<>@@ -135,6 +150,7 @@ export const LayoutPresetMenu = () => {onAction={openActionMenu}onApply={applyPreset}onContextMenu={openActionMenu}+ onPreload={preloadLayoutPreset}/></>) : null}@@ -202,6 +218,7 @@ const PresetGroup = ({onAction,onApply,onContextMenu,+ onPreload,presets,}: {isCustom?: boolean;@@ -210,6 +227,7 @@ const PresetGroup = ({onAction?: (preset: LayoutPreset, event: MouseEvent<HTMLElement>) => void;onApply: (preset: LayoutPreset) => void;onContextMenu?: (preset: LayoutPreset, event: MouseEvent<HTMLElement>) => void;+ onPreload: (preset: LayoutPreset) => void;presets: LayoutPreset[];}) => (<Menu.ItemGroup>@@ -225,6 +243,7 @@ const PresetGroup = ({onAction={onAction}onApply={onApply}onContextMenu={onContextMenu}+ onPreload={onPreload}/>))}</Menu.ItemGroup>@@ -236,6 +255,7 @@ const PresetMenuItem = ({onAction,onApply,onContextMenu,+ onPreload,preset,}: {isCustom: boolean;@@ -244,6 +264,7 @@ const PresetMenuItem = ({onAction?: (preset: LayoutPreset, event: MouseEvent<HTMLElement>) => void;onApply: (preset: LayoutPreset) => void;onContextMenu?: (preset: LayoutPreset, event: MouseEvent<HTMLElement>) => void;+ onPreload: (preset: LayoutPreset) => void;}) => {const handleApply = useCallback(() => onApply(preset), [onApply, preset]);const handleContextMenu = useCallback(@@ -251,9 +272,16 @@ const PresetMenuItem = ({[onContextMenu, preset]);const handleAction = useCallback((event: MouseEvent<HTMLElement>) => onAction?.(preset, event), [onAction, preset]);+ const handlePreload = useCallback(() => onPreload(preset), [onPreload, preset]);return (- <Menu.Item value={preset.id} onClick={handleApply} onContextMenu={handleContextMenu}>+ <Menu.Item+ value={preset.id}+ onClick={handleApply}+ onContextMenu={handleContextMenu}+ onFocus={handlePreload}+ onPointerEnter={handlePreload}+ ><Stack gap="0" flex="1" minW="0"><Text fontSize="xs" fontWeight="600">{preset.label}diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/ModelManagerButton.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/ModelManagerButton.tsxindex 4578489b42..34cf8e909a 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/ModelManagerButton.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/ModelManagerButton.tsx@@ -1,5 +1,5 @@+import { IconButton, Tooltip } from '@platform/ui';import { Link } from '@tanstack/react-router';-import { IconButton, Tooltip } from '@workbench/components/ui';import { useActiveProjectId } from '@workbench/WorkbenchContext';import { BoxIcon } from 'lucide-react';import { useMemo } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/NodeManagerButton.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/NodeManagerButton.tsxindex cfdd52b52d..2d3ce1dc9a 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/NodeManagerButton.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/NodeManagerButton.tsx@@ -1,6 +1,6 @@import { Icon } from '@chakra-ui/react';+import { IconButton, Tooltip } from '@platform/ui';import { Link } from '@tanstack/react-router';-import { IconButton, Tooltip } from '@workbench/components/ui';import { BlocksIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsxindex 338a3981e8..9e985dc4a0 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsx@@ -1,6 +1,6 @@import { Group, Menu, Portal } from '@chakra-ui/react';-import { IconButton, Tooltip } from '@workbench/components/ui';-import { QueueMenuItems, useQueueMenuActions } from '@workbench/widgets/queue/queueMenuActions';+import { QueueMenuItems, useQueueMenuActions } from '@features/queue/menu';+import { IconButton, Tooltip } from '@platform/ui';import { ChevronDownIcon, XIcon } from 'lucide-react';/** Queue cancel cluster and processor actions. */diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsxindex 7569517b83..d6f417fb52 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsx@@ -1,13 +1,14 @@-/* eslint-disable react/react-compiler */-import type { QueueItem } from '@workbench/types';-import { Badge, HStack, Icon, Progress, Stack, Text } from '@chakra-ui/react';-import { useModelLoads, type ModelLoadInfo } from '@workbench/backend/modelLoadStore';-import { useQueueItemProgress, type QueueItemProgress } from '@workbench/backend/progressStore';-import { Button, Tooltip } from '@workbench/components/ui';+import { useModelLoads, type ModelLoadInfo } from '@features/models';+import {+ getQueueItemExpectedImageCount,+ getQueueProgressBarState,+ getQueueSummary,+ type QueueItem,+} from '@features/queue/contracts';+import { useQueueItemProgress, type QueueItemProgress } from '@features/queue/react';+import { Button, Tooltip } from '@platform/ui';import { getDestinationLabel, getSourceLabel } from '@workbench/invocation';-import { getQueueItemSourceWidgetValues } from '@workbench/queueSnapshot';-import { getQueueItemExpectedImageCount, getQueueProgressBarState, getQueueSummary } from '@workbench/queueSummary';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';import { useActiveProjectSelector, useWorkbenchSelector } from '@workbench/WorkbenchContext';import { ListOrderedIcon } from 'lucide-react';@@ -17,12 +18,13 @@ const TOOLTIP_CONTENT_PROPS = { maxW: '22rem', p: '0' };export const QueueInfo = () => {const queueItems = useActiveProjectSelector((project) => project.queue.items);- const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);+ const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.backendConnection.status);const modelLoads = useModelLoads();const openWorkbenchWidget = useOpenWorkbenchWidget();const baseSummary = getQueueSummary(queueItems);const runningProgress = useQueueItemProgress(baseSummary.runningQueueItemId ?? '');const summary = getQueueSummary(queueItems, runningProgress);+ const { current, total } = summary;const runningItem = summary.runningQueueItemId? queueItems.find((item) => item.id === summary.runningQueueItemId): undefined;@@ -40,11 +42,11 @@ export const QueueInfo = () => {item={runningItem}modelLoads={modelLoads}progress={runningProgress}- total={summary.total}- current={summary.current}+ total={total}+ current={current}/>),- [modelLoads, runningItem, runningProgress, summary]+ [current, modelLoads, runningItem, runningProgress, total]);const handleOpenQueue = useCallback(() => openWorkbenchWidget('queue'), [openWorkbenchWidget]);@@ -139,8 +141,7 @@ const QueueInfoTooltip = ({);}- const sourceValues = getQueueItemSourceWidgetValues(item);- const prompt = typeof sourceValues.positivePrompt === 'string' ? sourceValues.positivePrompt.trim() : '';+ const prompt = item.snapshot.presentation.positivePrompt?.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/shell/topbar/TopBar.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsxindex ada53902ff..6825a95c1e 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx@@ -1,10 +1,9 @@import { Flex, HStack, Separator } from '@chakra-ui/react';+import { AccountMenu, useCapabilities } from '@features/identity';+import { InvokeMark } from '@platform/ui/InvokeMark';import { Link } from '@tanstack/react-router';-import { useCapabilities } from '@workbench/auth/capabilities';-import { AccountMenu } from '@workbench/auth/components/AccountMenu';import { ProjectTabs } from '@workbench/projects/components';-import { InvokeMark } from '@/workbench/components/InvokeMark';import { SettingsButton } from '@/workbench/settings';import { BatchCountField } from './BatchCountField';diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.tsdeleted file mode 100644index 6236fe4ac7..0000000000--- a/invokeai/frontend/webv2/src/workbench/types.ts+++ /dev/null@@ -1,951 +0,0 @@-import type { TFunction } from 'i18next';-import type { ComponentType, ExoticComponent, JSXElementConstructor, SVGProps } from 'react';--// `generation/types.ts` imports value-less (`import type`) symbols back from this-// module; both sides are type-only so this doesn't create a runtime cycle.-import type { GenerateWidgetValues, RegionalGuidanceReferenceImage } from './generation/types';-import type { WorkbenchLanguage } from './i18n/languages';-import type { ProjectGraphState } from './workflows/types';--export type { WorkbenchLanguage } from './i18n/languages';--export type BuiltInLayoutPresetId = 'canvas-default' | 'gallery' | 'workflow' | 'canvas';-export type LayoutPresetId = BuiltInLayoutPresetId | (string & {});--export type CenterViewId = 'canvas' | 'gallery' | 'preview' | 'workflow';--export type GraphId = string;--export type FirstPartyWidgetTypeId =- | 'autosave-status'- | 'canvas'- | 'diagnostics'- | 'gallery'- | 'generate'- | 'history-controls'- | 'layers'- | 'notifications'- | 'preview'- | 'project'- | 'queue'- | 'server-status'- | 'upscale'- | 'users'- | 'version-status'- | 'workflow';--export type WidgetTypeId = FirstPartyWidgetTypeId | (string & {});-export type WidgetInstanceId = string;-export type WidgetId = WidgetTypeId;--export type WorkbenchRegion = 'left' | 'right' | 'center' | 'bottom' | 'dialog' | 'popover';--export type QueueItemStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';--export type ProjectEventType =- | 'project-created'- | 'layout-updated'- | 'invocation-updated'- | 'queue-submitted'- | 'canvas-layer-accepted'- | 'graph-replaced'- | 'graph-snapshot-saved';--export interface GraphNodeContract {- id: string;- type: string;- inputs: Record<string, unknown>;-}--export interface GraphEdgeContract {- id: string;- sourceNodeId: string;- sourceField: string;- targetNodeId: string;- targetField: string;-}--export interface GraphContract {- id: GraphId;- version: 1;- label: string;- nodes: GraphNodeContract[];- edges: GraphEdgeContract[];- updatedAt: string;- backendGraph?: BackendGraphContract;-}--export interface BackendInvocationContract {- id: string;- type: string;- [key: string]: unknown;-}--export interface BackendGraphEdgeContract {- source: {- node_id: string;- field: string;- };- destination: {- node_id: string;- field: string;- };-}--export interface BackendGraphContract {- id: string;- nodes: Record<string, BackendInvocationContract>;- edges: BackendGraphEdgeContract[];-}--export interface WidgetStateContract {- id: WidgetTypeId;- label: string;- version: 1;- values: Record<string, unknown>;- graphId?: GraphId;-}--export type WidgetStateMap = Record<string, WidgetStateContract>;--export interface WidgetInstanceContract {- id: WidgetInstanceId;- typeId: WidgetTypeId;- title?: string;- state: WidgetStateContract;- createdAt: string;-}--export interface WidgetInstanceRuntimeMeta {- id: WidgetInstanceId;- typeId: WidgetTypeId;- title?: string;- createdAt: string;-}--export interface GraphBearingSurfaceContract {- surfaceId: string;- widgetId: WidgetId;- label: string;- sourceId: InvocationSourceId;- graphId: GraphId;- region: WorkbenchRegion;- canSetSource: boolean;- canPreviewGraph: boolean;-}--export interface WidgetViewProps {- region: WorkbenchRegion;- manifest: WidgetManifest;- /** Chrome metadata only. Read reactive widget values through `runtime.state`. */- instance: WidgetInstanceRuntimeMeta;- runtime: WidgetRuntimeApi;- presentation?: 'compact' | 'expanded' | 'tooltip';-}--export type WidgetView = ComponentType<WidgetViewProps>;--export type WidgetHeaderActions = ComponentType<WidgetViewProps>;-export type WidgetHeaderMenu = ComponentType<WidgetViewProps>;-export type WidgetFooter = ComponentType<WidgetViewProps>;-export type WidgetHost = ComponentType;--export interface WidgetLabelProps {- region: WorkbenchRegion;- presentation?: 'compact' | 'expanded' | 'tooltip';-}--export type WidgetLabel = string | ((t: TFunction) => string);-export type WidgetHeaderLabel = ComponentType<WidgetLabelProps>;--export type WidgetIconComponent =- | JSXElementConstructor<SVGProps<SVGSVGElement>>- | ExoticComponent<SVGProps<SVGSVGElement>>;--export interface WidgetStateRegistration<State extends Record<string, unknown> = Record<string, unknown>> {- version: 1;- createInitial: () => State;- migrate?: (state: unknown, fromVersion: number) => State;- persistence?: 'project' | 'workspace' | 'session' | 'none';-}--export interface WidgetRuntimeApi<State extends Record<string, unknown> = Record<string, unknown>> {- instanceId: WidgetInstanceId;- typeId: WidgetTypeId;- region: WorkbenchRegion;- state: WidgetRuntimeStateApi<State>;- diagnostics: WidgetDiagnosticsApi;- commands: WidgetCommandApi;- hotkeys: WidgetHotkeyApi;- menus: WidgetMenuApi;- palette: WidgetCommandPaletteApi;- search: WidgetSearchApi;- toolbars: WidgetToolbarApi;- workbench: WidgetWorkbenchApi;-}--export interface WidgetDiagnosticsApi {- logger: (namespace: DeveloperLogNamespace) => {- debug: (messageOrContext: string | Record<string, unknown>, message?: string) => void;- error: (messageOrContext: string | Record<string, unknown>, message?: string) => void;- fatal: (messageOrContext: string | Record<string, unknown>, message?: string) => void;- info: (messageOrContext: string | Record<string, unknown>, message?: string) => void;- trace: (messageOrContext: string | Record<string, unknown>, message?: string) => void;- warn: (messageOrContext: string | Record<string, unknown>, message?: string) => void;- };-}--export interface WidgetRuntimeStateApi<State extends Record<string, unknown> = Record<string, unknown>> {- getSnapshot: () => Readonly<State>;- useSelector: <Selected>(- selector: (state: Readonly<State>) => Selected,- isEqual?: (left: Selected, right: Selected) => boolean- ) => Selected;- patch: (values: Partial<State>) => void;- set: (values: State) => void;-}--export interface WidgetContributionSource {- instanceId: WidgetInstanceId;- projectId: string;- region: WorkbenchRegion;- typeId: WidgetTypeId;-}--export interface WidgetCommandApi {- execute: (commandId: string, ...args: unknown[]) => Promise<unknown>;- executeForSource: (- commandId: string,- source: WidgetContributionSource | null,- ...args: unknown[]- ) => Promise<unknown>;- register: (command: WidgetCommandContribution) => () => void;-}--export interface WidgetCommandContribution {- id: string;- title: string;- handler: (...args: unknown[]) => unknown | Promise<unknown>;- source?: WidgetContributionSource;-}--export interface WidgetHotkeyApi {- register: (hotkey: WidgetHotkeyContribution) => () => void;-}--export interface WidgetHotkeyContribution {- id: string;- commandId: string;- defaultKeys: string[];- title: string;- description?: string;- scope?: 'focused-region' | 'global' | 'instance' | 'widget';- source?: WidgetContributionSource;- preventDefault?: boolean;- allowInEditable?: boolean;-}--export interface WidgetMenuApi {- register: (menu: WidgetMenuContribution) => () => void;-}--export interface WidgetMenuContribution {- id: string;- items: Array<{ commandId: string; group?: string }>;- source?: WidgetContributionSource;-}--export interface WidgetCommandPaletteApi {- register: (entry: WidgetCommandPaletteContribution) => () => void;-}--export interface WidgetCommandPaletteContribution {- commandId: string;- title: string;- keywords?: string[];-}--export interface WidgetSearchApi {- registerProvider: (provider: WidgetSearchProvider) => () => void;-}--export interface WidgetSearchProvider {- id: string;- label: string;- search: (query: string) => Promise<WidgetSearchResult[]> | WidgetSearchResult[];-}--export interface WidgetSearchResult {- id: string;- title: string;- subtitle?: string;- commandId?: string;-}--export interface WidgetToolbarApi {- register: (toolbar: WidgetToolbarContribution) => () => void;-}--export interface WidgetToolbarContribution {- id: string;- location: 'center.tabs.trailing' | 'status.left' | 'status.right';- items: Array<{- commandId: string;- icon?: WidgetIconComponent;- label?: string;- }>;-}--export interface OpenWorkbenchWidgetOptions {- createNew?: boolean;- preferredRegions?: ReadonlyArray<WidgetRegion>;- requireCenterView?: boolean;-}--export type WidgetWorkbenchApiResult =- | { ok: true; region?: WidgetRegion }- | { ok: false; reason: 'unavailable' | 'unsupported' | 'not-found' };--export interface WidgetWorkbenchApi {- openWidget: (typeId: WidgetTypeId, options?: OpenWorkbenchWidgetOptions) => WidgetWorkbenchApiResult;- revealWidgetInstance: (instanceId: WidgetInstanceId) => WidgetWorkbenchApiResult;- closeWidgetInstance: (instanceId: WidgetInstanceId) => WidgetWorkbenchApiResult;-}--/** Sections of the workbench settings dialog, addressable via `openWorkbenchSettings`. */-export type SettingsSectionId =- | 'appearance'- | 'behavior'- | 'hotkeys'- | 'project'- | 'queue'- | 'workflow'- | 'developer'- | 'workspace';--export interface WidgetManifest {- /** Widget runtime API contract version. Defaults to 1 during registry normalization. */- apiVersion?: 1;- id: WidgetTypeId;- label: WidgetLabel;- headerLabel?: WidgetHeaderLabel;- version: 1;- allowedRegions: WidgetRegion[];- allowMultiple: boolean;- icon: WidgetIconComponent;- bottomPanel?: 'expandable' | 'tooltip';- centerPlacement?: 'toolbar' | 'view';- /** Only offered while an admin is signed in to a multi-user backend. */- requiresAdmin?: boolean;- chrome?: {- header?: 'hidden' | 'visible';- };- view?: WidgetView;- /**- * Stable singleton UI owned by the widget but not by any widget instance.- * Use for dialogs, file inputs, and other portals driven by widget-level- * stores. Mounted once under WorkbenchProvider, independent of widget chrome.- */- host?: WidgetHost;- headerActions?: WidgetHeaderActions;- /**- * Extra entries for the widget's shared header actions menu. Rendered inside- * the same menu as the universal graph actions, so widgets extend the frame- * menu instead of stacking their own. Render `Menu.Item`/`Menu.ItemGroup`- * children only; use `host` for stable dialogs or file inputs.- */- headerMenu?: WidgetHeaderMenu;- /** When set, the frame header shows a gear that opens this settings dialog section. */- settingsSection?: SettingsSectionId;- footer?: WidgetFooter;- state?: WidgetStateRegistration;- graphBearing?: {- sourceId: InvocationSourceId;- defaultGraphId: GraphId;- surfaces: WorkbenchRegion[];- };- failurePolicy: {- onRegistrationFailure: 'disable' | 'hide';- isolateRenderFailure: boolean;- };-}--export interface NormalizedWidgetManifest extends Omit<WidgetManifest, 'apiVersion' | 'state'> {- apiVersion: 1;- state: WidgetStateRegistration;-}--export interface RegisteredWidget {- manifest: NormalizedWidgetManifest;- status: 'enabled' | 'disabled' | 'hidden';- failure?: WidgetFailure;-}--export interface WidgetFailure {- widgetId: WidgetTypeId;- message: string;- details: string;- occurredAt: string;-}--export interface GeneratedImageContract {- imageName: string;- imageUrl: string;- thumbnailUrl: string;- width: number;- height: number;- queuedAt: string;- sourceQueueItemId: string;-}--export interface CanvasPlacementContract {- x: number;- y: number;- width: number;- height: number;- opacity: number;-}--export interface CanvasStagingCandidateContract extends GeneratedImageContract {- placement: CanvasPlacementContract;- sourceBackendItemId?: number;-}--export interface CanvasRasterLayerContract extends GeneratedImageContract {- id: string;- acceptedAt: string;- label: string;- placement: CanvasPlacementContract;-}--export interface CanvasDocumentContract {- version: 1;- width: number;- height: number;- layers: CanvasRasterLayerContract[];-}--/** @deprecated legacy v1 shape, superseded by {@link CanvasStagingAreaContractV2}. Extracted so v1 and v2 canvas state can share its structure. */-export interface CanvasStagingAreaContract {- sourceQueueItemId?: string;- selectedLayerId?: string;- pendingImageIds: string[];- pendingImages: CanvasStagingCandidateContract[];- selectedImageIndex: number;- isVisible: boolean;- areThumbnailsVisible: boolean;-}--/** @deprecated legacy v1 shape, superseded by {@link CanvasStateContractV2}. Kept for migration input typing and the still-v1-shaped staging area. */-export interface CanvasStateContract {- version: 1;- document: CanvasDocumentContract;- stagingArea: CanvasStagingAreaContract;-}--// ----------------------------------------------------------------------------// Canvas v2 document contracts-//-// The canvas document is being rebuilt as a full photo editor: a layer stack-// supporting raster, control, regional-guidance, and inpaint-mask layers, each-// with its own transform/opacity/blend-mode. `CanvasStateContract` (v1) only-// ever produced single-image raster layers positioned by `placement`; v2-// layers are positioned by `transform` and reference bitmaps by `imageName`-// (via `CanvasImageRef`) rather than by resolved URLs, since URLs are-// ephemeral/backend-derived while the document is persisted. The staging-// area (pending queue results awaiting placement onto the canvas) keeps its-// v1 shape unchanged — only the accepted document evolves.-// -----------------------------------------------------------------------------export type CanvasBlendMode =- | 'normal'- | 'multiply'- | 'screen'- | 'overlay'- | 'darken'- | 'lighten'- | 'color-dodge'- | 'color-burn'- | 'hard-light'- | 'soft-light'- | 'difference'- | 'exclusion'- | 'hue'- | 'saturation'- | 'color'- | 'luminosity';--/** A reference to a persisted image asset by name, not by resolved URL. */-export interface CanvasImageRef {- imageName: string;- width: number;- height: number;- contentHash?: string;-}--export type CanvasLayerSourceContract =- | {- type: 'paint';- bitmap: CanvasImageRef | null;- /**- * The layer-local origin of `bitmap`'s top-left pixel. Paint layers are- * content-sized: the persisted bitmap covers only the painted region, and- * this offset records where that region sits in the layer's local space- * (it can be negative). Absent (or `{ x: 0, y: 0 }`) for legacy documents- * whose paint bitmaps were document-sized at the origin — they load- * identically.- */- offset?: { x: number; y: number };- }- | { type: 'image'; image: CanvasImageRef }- | {- type: 'text';- content: string;- fontFamily: string;- fontSize: number;- fontWeight: number;- lineHeight: number;- align: 'left' | 'center' | 'right';- color: string;- }- | {- type: 'shape';- kind: 'rect' | 'ellipse' | 'polygon';- points?: { x: number; y: number }[];- width: number;- height: number;- fill: string | null;- stroke: string | null;- strokeWidth: number;- }- | {- type: 'gradient';- kind: 'linear' | 'radial';- angle: number;- stops: { offset: number; color: string }[];- /**- * The gradient's explicit content extent (layer-local pixels). Gradient- * layers are content-sized like every other layer: the extent is set at- * creation (bbox-sized) and preserved across angle edits. Absent for legacy- * documents whose gradients were document-sized by construction — they- * default to the document dimensions on load (see `getSourceContentRect`).- */- width?: number;- height?: number;- };--export interface CanvasLayerBaseContract {- id: string;- name: string;- isEnabled: boolean;- isLocked: boolean;- opacity: number;- blendMode: CanvasBlendMode;- transform: { x: number; y: number; scaleX: number; scaleY: number; rotation: number };-}--export interface CanvasAdjustmentsContract {- brightness: number;- contrast: number;- saturation: number;- curves?: { r: [number, number][]; g: [number, number][]; b: [number, number][] };-}--export interface CanvasControlAdapterContract {- kind: 'controlnet' | 't2i_adapter' | 'control_lora' | 'z_image_control';- model: string | null;- weight: number;- beginEndStepPct: [number, number];- controlMode: 'balanced' | 'more_prompt' | 'more_control' | 'unbalanced' | null;-}--export interface CanvasMaskFillContract {- style: 'solid' | 'grid' | 'crosshatch' | 'diagonal' | 'horizontal' | 'vertical';- color: string;-}--export interface CanvasMaskContract {- bitmap: CanvasImageRef | null;- fill: CanvasMaskFillContract;- /**- * The layer-local origin of `bitmap`'s top-left pixel. Mask layers are- * content-sized exactly like paint layers: the persisted mask bitmap covers- * only the painted region, and this offset records where that region sits in- * the layer's local space (it can be negative). Absent (or `{ x: 0, y: 0 }`)- * for legacy documents whose mask bitmaps were document-sized at the origin —- * they load identically. Mirrors {@link CanvasLayerSourceContract} `paint`.- */- offset?: { x: number; y: number };-}--export interface CanvasRasterLayerContractV2 extends CanvasLayerBaseContract {- type: 'raster';- source: CanvasLayerSourceContract;- adjustments?: CanvasAdjustmentsContract;- isTransparencyLocked?: boolean;- filter?: { type: string; settings: Record<string, unknown> };-}--export interface CanvasControlLayerContract extends CanvasLayerBaseContract {- type: 'control';- source: CanvasLayerSourceContract;- adapter: CanvasControlAdapterContract;- withTransparencyEffect: boolean;- filter?: { type: string; settings: Record<string, unknown> };-}--export interface CanvasRegionalGuidanceLayerContract extends CanvasLayerBaseContract {- type: 'regional_guidance';- mask: CanvasMaskContract;- positivePrompt: string | null;- negativePrompt: string | null;- autoNegative: boolean;- referenceImages: RegionalGuidanceReferenceImage[];-}--export interface CanvasInpaintMaskLayerContract extends CanvasLayerBaseContract {- type: 'inpaint_mask';- mask: CanvasMaskContract;- noiseLevel?: number;- denoiseLimit?: number;-}--export type CanvasLayerContract =- | CanvasRasterLayerContractV2- | CanvasControlLayerContract- | CanvasRegionalGuidanceLayerContract- | CanvasInpaintMaskLayerContract;--export interface CanvasDocumentContractV2 {- version: 2;- width: number;- height: number;- background: 'transparent' | { color: string };- /** Index 0 is the top-most layer. */- layers: CanvasLayerContract[];- bbox: { x: number; y: number; width: number; height: number };- selectedLayerId: string | null;-}--export interface CanvasSnapshotContract {- id: string;- name: string;- createdAt: string;- document: CanvasDocumentContractV2;-}--export interface CanvasStagingAreaContractV2 extends CanvasStagingAreaContract {- autoSwitchMode: 'off' | 'latest' | 'progress';-}--export interface CanvasStateContractV2 {- version: 2;- document: CanvasDocumentContractV2;- /**- * Monotonic counter bumped whenever the document is swapped wholesale- * (snapshot restore, `replaceCanvasDocument`) rather than incrementally- * edited. The document mirror treats any change to this value as a full- * document replacement (clearing engine pixel history), even when the new- * document keeps the same dimensions and reuses layer ids — the case a- * reference/dimension diff alone cannot distinguish from an ordinary edit.- */- documentRevision: number;- snapshots: CanvasSnapshotContract[];- stagingArea: CanvasStagingAreaContractV2;-}--export type InvocationSourceId = 'generate' | 'workflow' | 'upscale' | 'canvas';--export type InvocationMode = 'global' | 'dialog';--export type ResultDestination = 'canvas' | 'gallery';--export interface InvocationRoute {- sourceId: InvocationSourceId;- destination: ResultDestination;- sourceLocked: boolean;- destinationLocked: boolean;-}--export interface ResolvedInvocationRoute extends InvocationRoute {- mode: InvocationMode;- sourceValid: boolean;- destinationValid: boolean;- /** The top validation issue, shown on the fixed Invoke control's secondary line. */- validationMessage?: string;- /** Every reason the route cannot run right now (legacy `reasonsWhyCannotEnqueue` equivalent). */- validationReasons: string[];-}--export interface InvocationControllerState extends InvocationRoute {- lastSubmittedRunId?: string;-}--export interface PanelState {- isLeftOpen: boolean;- isRightOpen: boolean;- isBottomOpen: boolean;-}--export type WidgetRegion = 'left' | 'right' | 'bottom' | 'center';--export interface WidgetRegionState {- activeInstanceId: WidgetInstanceId;- instanceIds: WidgetInstanceId[];- isCollapsed: boolean;- sizePx: number;-}--export interface ProjectLayoutState {- presetId: LayoutPresetId;- centerViewId: CenterViewId;- panels: PanelState;-}--export interface LayoutPresetWidgetInstanceSnapshot {- id: WidgetInstanceId;- typeId: WidgetTypeId;- title?: string;-}--export interface LayoutPresetSnapshot {- layout: ProjectLayoutState;- widgetInstances: Record<WidgetInstanceId, LayoutPresetWidgetInstanceSnapshot>;- widgetRegions: Record<WidgetRegion, WidgetRegionState>;-}--export interface Project {- id: string;- name: string;- /**- * Set on recovery forks created when a save loses a revision race: the id- * of the root project this recovered from (chains collapse to the root, so- * a recovery of a recovery still points at the original).- */- recoveryOf?: string;- recoveredAt?: string;- settings: ProjectSettings;- layout: ProjectLayoutState;- invocation: InvocationControllerState;- /** The one active project graph: an editable workflow document, compiled to a `GraphContract` at invoke time. */- projectGraph: ProjectGraphState;- widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;- widgetRegions: Record<WidgetRegion, WidgetRegionState>;- widgetGraphs: Partial<Record<WidgetTypeId, GraphContract>>;- canvas: CanvasStateContractV2;- graphHistory: GraphHistorySnapshot[];- promptHistory: PromptHistoryItem[];- undoRedo: UndoRedoHistory;- queue: QueueState;- events: ProjectEvent[];-}--export interface LayoutPreset {- id: LayoutPresetId;- label: string;- isBuiltIn?: boolean;- snapshot: LayoutPresetSnapshot;-}--export interface WorkbenchState {- projects: Project[];- activeProjectId: string;- backendConnection: BackendConnectionState;- notifications: WorkbenchNotification[];- autosave: AutosaveState;- account: AccountState;- widgetFailures: WidgetFailure[];-}--export type BackendConnectionStatus = 'connecting' | 'connected' | 'disconnected';--export interface BackendConnectionState {- status: BackendConnectionStatus;- error?: string;- lastConnectedAt?: string;- lastDisconnectedAt?: string;-}--export type WorkbenchNotificationKind = 'error' | 'success' | 'info';--export interface WorkbenchNotification {- id: string;- kind: WorkbenchNotificationKind;- title: string;- message?: string;- createdAt: string;- projectId?: string;- isRead: boolean;-}--/**- * One entry of the project's graph history. Queue submissions record the- * compiled `graph`; workflow snapshots (manual save, pre-replacement) record- * the editable `document`, which is what makes them restorable.- */-export interface GraphHistorySnapshot {- id: string;- createdAt: string;- label: string;- graph?: GraphContract;- document?: ProjectGraphState;-}--export interface PromptHistoryItem {- positivePrompt: string;- negativePrompt: string | null;-}--export interface UndoRedoEntry {- id: string;- createdAt: string;- label: string;- project: ProjectUndoSnapshot;-}--/**- * Project-level undo snapshot. Deliberately excludes `canvas`: the canvas- * rendering engine owns its own pixel-patch history, so project undo/redo- * passes the live `project.canvas` through untouched (see `restoreUndoSnapshot`).- */-export interface ProjectUndoSnapshot {- layout: ProjectLayoutState;- invocation: InvocationControllerState;- projectGraph: ProjectGraphState;- widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;- widgetRegions: Record<WidgetRegion, WidgetRegionState>;- widgetGraphs: Partial<Record<WidgetTypeId, GraphContract>>;-}--export interface UndoRedoHistory {- past: UndoRedoEntry[];- future: UndoRedoEntry[];-}--export interface QueueSubmissionSnapshot {- sourceId: InvocationSourceId;- destination: ResultDestination;- graph: GraphContract;- generate?: {- values: GenerateWidgetValues;- negativePromptNodeId: string;- positivePromptNodeId: string;- seedNodeId: string;- };- widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;- widgetStates: WidgetStateMap;- canvas: CanvasStateContractV2;- submittedAt: string;-}--export interface QueueItem {- id: string;- status: QueueItemStatus;- cancellable: boolean;- snapshot: QueueSubmissionSnapshot;- backendItemIds?: number[];- completedBackendItemIds?: number[];- cancelledBackendItemIds?: number[];- backendBatchId?: string;- error?: string;- resultImages?: GeneratedImageContract[];-}--export interface QueueState {- items: QueueItem[];-}--export interface ProjectEvent {- id: string;- type: ProjectEventType;- createdAt: string;- summary: string;- runId?: string;-}--export interface RunRecord {- id: string;- projectId: string;- queueItemId: string;- sourceId: InvocationSourceId;- destination: ResultDestination;- graphSnapshotId: string;- status: QueueItemStatus;- submittedAt: string;- completedAt?: string;-}--export interface AutosaveState {- status: 'idle' | 'saving' | 'saved' | 'error';- lastSavedAt?: string;- error?: string;-}--/**- * Identifier for a workbench color theme. The matching palette lives in- * `theme/themes.ts`; the active id is applied to `<html data-theme>` so the- * semantic-token conditions in `theme/system.ts` resolve to the right colors.- */-export type WorkbenchThemeId = 'classic' | 'light' | 'forest' | 'mono' | 'ultradark';--export type DeveloperLogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';--export type DeveloperLogNamespace =- | 'canvas'- | 'canvas-workflow-integration'- | 'config'- | 'dnd'- | 'events'- | 'gallery'- | 'generation'- | 'metadata'- | 'models'- | 'system'- | 'queue'- | 'workflows';--export interface ProjectSettings {- useCpuNoise: boolean;- showProgressDetails: boolean;- antialiasProgressImages: boolean;- showProgressImagesInViewer: boolean;- preferNumericAttentionStyle: boolean;- showPromptSyntaxHighlighting: boolean;-}--/** User-tunable appearance + behavior preferences surfaced in the Settings modal. */-export interface WorkbenchPreferences {- themeId: WorkbenchThemeId;- reduceMotion: boolean;- showFocusRegionHighlight: boolean;- confirmImageDeletion: boolean;- queueJobsScope: 'active-project' | 'all';- language: WorkbenchLanguage;- enableInformationalPopovers: boolean;- enableModelDescriptions: boolean;- developerLogEnabled: boolean;- developerLogLevel: DeveloperLogLevel;- developerLogNamespaces: DeveloperLogNamespace[];- developerPerformanceTimingsEnabled: boolean;- /** Always snap workflow nodes to the grid (Ctrl snaps temporarily when off). */- workflowSnapToGrid: boolean;- /** Show the minimap in the workflow editor. */- workflowShowMinimap: boolean;- /** Reject workflow connections with incompatible field types. */- workflowValidateConnections: boolean;- /** Connection line rendering in the workflow editor. */- workflowEdgeStyle: 'curved' | 'square';- /** Account-bound overrides keyed by hotkey id (`app.invoke`, `gallery.galleryNavLeft`, etc.). */- customHotkeys: Record<string, string[]>;-}--export interface AccountState {- activeLayoutPresetId: LayoutPresetId;- customLayoutPresets?: LayoutPreset[];-}--export interface WorkbenchPersistenceSnapshot {- version: 1;- savedAt: string;- state: WorkbenchState;-}diff --git a/invokeai/frontend/webv2/src/workbench/upscale/index.ts b/invokeai/frontend/webv2/src/workbench/upscale/index.tsdeleted file mode 100644index 3f02e7e171..0000000000--- a/invokeai/frontend/webv2/src/workbench/upscale/index.ts+++ /dev/null@@ -1,3 +0,0 @@-export { compileUpscaleGraph } from './graph';-export * from './settings';-export type * from './types';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/upscale/index.ts b/invokeai/frontend/webv2/src/workbench/upscaleWidgetManifest.tssimilarity index 73%rename from invokeai/frontend/webv2/src/workbench/widgets/upscale/index.tsrename to invokeai/frontend/webv2/src/workbench/upscaleWidgetManifest.tsindex 9fa9fd5e3a..8cceff31cc 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/upscale/index.ts+++ b/invokeai/frontend/webv2/src/workbench/upscaleWidgetManifest.ts@@ -1,9 +1,7 @@-import type { WidgetManifest } from '@workbench/types';+import type { WidgetManifest } from '@workbench/widgetContracts';import { ImageUpscaleIcon } from 'lucide-react';-import { UpscaleWidgetView } from './UpscaleWidgetView';-export const upscaleWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['left'],@@ -12,6 +10,6 @@ export const upscaleWidgetManifest: WidgetManifest = {icon: ImageUpscaleIcon,id: 'upscale',label: (t) => t('widgets.labels.upscale'),+ load: () => import('@features/upscale/widget').then((module) => module.widgetImplementation),version: 1,- view: UpscaleWidgetView,};diff --git a/invokeai/frontend/webv2/src/workbench/useCanvasProjectMutationDispatch.ts b/invokeai/frontend/webv2/src/workbench/useCanvasProjectMutationDispatch.tsindex 69bba034d7..15431f4a8c 100644--- a/invokeai/frontend/webv2/src/workbench/useCanvasProjectMutationDispatch.ts+++ b/invokeai/frontend/webv2/src/workbench/useCanvasProjectMutationDispatch.ts@@ -2,23 +2,13 @@ import { useCallback } from 'react';import type { CanvasProjectMutation } from './canvasProjectMutations';-import { useActiveProjectId, useWorkbenchStore } from './WorkbenchContext';+import { useActiveProjectId, useWorkbenchCommands } from './WorkbenchContext';export type CanvasProjectMutationDispatch = (mutation: CanvasProjectMutation) => boolean;export const useCanvasProjectMutationDispatch = (): CanvasProjectMutationDispatch => {const projectId = useActiveProjectId();- const store = useWorkbenchStore();+ const { canvas } = useWorkbenchCommands();- return useCallback(- (mutation: CanvasProjectMutation) => {- const before = store.getState().projects.find((project) => project.id === projectId)?.canvas;- if (!before) {- return false;- }- store.dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' });- return store.getState().projects.find((project) => project.id === projectId)?.canvas !== before;- },- [projectId, store]- );+ return useCallback((mutation: CanvasProjectMutation) => canvas.apply(projectId, mutation), [canvas, projectId]);};diff --git a/invokeai/frontend/webv2/src/workbench/useNotify.ts b/invokeai/frontend/webv2/src/workbench/useNotify.tsindex 48e0903f2f..7ec4208507 100644--- a/invokeai/frontend/webv2/src/workbench/useNotify.ts+++ b/invokeai/frontend/webv2/src/workbench/useNotify.ts@@ -1,9 +1,9 @@-import { toaster } from '@workbench/components/ui';-import { useMemo } from 'react';+import type { WorkbenchNotificationKind } from '@workbench/projectContracts';-import type { WorkbenchNotificationKind } from './types';+import { toaster } from '@platform/ui';+import { useMemo } from 'react';-import { useOptionalWorkbenchDispatch } from './WorkbenchContext';+import { useOptionalWorkbenchCommands } from './WorkbenchContext';/*** Notification helper: records into the workbench shell when present, and@@ -22,19 +22,19 @@ const notificationToastType: Record<WorkbenchNotificationKind, 'error' | 'info'};export const useNotify = (): Notify => {- const dispatch = useOptionalWorkbenchDispatch();+ const commands = useOptionalWorkbenchCommands();return useMemo(() => {const record =(kind: WorkbenchNotificationKind) =>(title: string, message?: string): void => {- if (dispatch) {- dispatch({ kind, message, title, type: 'recordNotice' });+ if (commands) {+ commands.notifications.add({ kind, message, title });} else {toaster.create({ description: message, title, type: notificationToastType[kind] });}};return { error: record('error'), info: record('info'), success: record('success') };- }, [dispatch]);+ }, [commands]);};diff --git a/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts b/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.tsindex b27fd5ab7e..7706d1e32f 100644--- a/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts+++ b/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts@@ -1,48 +1,50 @@-import { useCallback, type Dispatch } from 'react';+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { OpenWorkbenchWidgetOptions, RegisteredWidget, WidgetTypeId } from '@workbench/widgetContracts';-import type { OpenWorkbenchWidgetOptions, RegisteredWidget, WidgetRegion, WidgetTypeId } from './types';-import type { WorkbenchAction } from './workbenchState';+import { useCallback } from 'react';++import type { WorkbenchWidgetCommands } from './workbenchStore';import { openWidgetPlacement } from './widgetPlacementCommands';-import { useOptionalWorkbenchDispatch, useWorkbenchDispatch } from './WorkbenchContext';+import { useOptionalWorkbenchCommands, useWorkbenchCommands } from './WorkbenchContext';import { useOptionalWorkbenchWidgetRegistry, useWorkbenchWidgetRegistry } from './WorkbenchWidgetRegistryContext';export type OpenWorkbenchWidgetResult = { ok: true; region: WidgetRegion } | { ok: false; reason: 'unavailable' };export const openWorkbenchWidget = (- dispatch: Dispatch<WorkbenchAction>,+ widgets: WorkbenchWidgetCommands,getWidgetsForRegion: (region: WidgetRegion) => RegisteredWidget[],widgetId: WidgetTypeId,options?: OpenWorkbenchWidgetOptions): OpenWorkbenchWidgetResult => {- const result = openWidgetPlacement({ dispatch, getWidgetsForRegion, options, typeId: widgetId });+ const result = openWidgetPlacement({ getWidgetsForRegion, options, typeId: widgetId, widgets });return result.ok ? { ok: true, region: result.region as WidgetRegion } : { ok: false, reason: 'unavailable' };};export const useOpenWorkbenchWidget = () => {- const dispatch = useWorkbenchDispatch();+ const { widgets } = useWorkbenchCommands();const { getWidgetsForRegion } = useWorkbenchWidgetRegistry();return useCallback((widgetId: WidgetTypeId, options?: OpenWorkbenchWidgetOptions): OpenWorkbenchWidgetResult =>- openWorkbenchWidget(dispatch, getWidgetsForRegion, widgetId, options),- [dispatch, getWidgetsForRegion]+ openWorkbenchWidget(widgets, getWidgetsForRegion, widgetId, options),+ [getWidgetsForRegion, widgets]);};export const useOptionalOpenWorkbenchWidget = () => {- const dispatch = useOptionalWorkbenchDispatch();+ const commands = useOptionalWorkbenchCommands();const registry = useOptionalWorkbenchWidgetRegistry();return useCallback((widgetId: WidgetTypeId, options?: OpenWorkbenchWidgetOptions): OpenWorkbenchWidgetResult => {- if (!dispatch || !registry) {+ if (!commands || !registry) {return { ok: false, reason: 'unavailable' };}- return openWorkbenchWidget(dispatch, registry.getWidgetsForRegion, widgetId, options);+ return openWorkbenchWidget(commands.widgets, registry.getWidgetsForRegion, widgetId, options);},- [dispatch, registry]+ [commands, registry]);};diff --git a/invokeai/frontend/webv2/src/workbench/users/index.ts b/invokeai/frontend/webv2/src/workbench/users/index.tsdeleted file mode 100644index 1d4eea7229..0000000000--- a/invokeai/frontend/webv2/src/workbench/users/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from './UserFormDialog';-export * from './UserManagement';diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsxindex f1dcde1d46..ec2473f934 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx@@ -1,24 +1,22 @@+import type { GraphContract } from '@workbench/graphContracts';+import type { Project } from '@workbench/projectContracts';import type {GraphBearingSurfaceContract,- GraphContract,- Project,WidgetInstanceRuntimeMeta,+ WidgetHeaderMenu,WidgetManifest,WidgetRuntimeApi,WorkbenchRegion,-} from '@workbench/types';+} from '@workbench/widgetContracts';import { Icon, Menu, Portal, Text } from '@chakra-ui/react';-import { IconButton } from '@workbench/components/ui';-import { GraphPreviewDialog } from '@workbench/graph-preview';+import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';+import { IconButton } from '@platform/ui';import { createGraphBearingSurface } from '@workbench/graphSurfaces';import { resolveWidgetLabel } from '@workbench/widgetLabels';-import { flushWorkbenchDrafts } from '@workbench/widgets/draftRegistry';-import { shallowEqual, useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { compileProjectGraph } from '@workbench/workflows/buildGraph';-import { getInvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import { shallowEqual, useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { GitBranchIcon, MoreHorizontalIcon, TargetIcon } from 'lucide-react';-import { useCallback, useState } from 'react';+import { lazy, Suspense, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';/**@@ -28,10 +26,21 @@ import { useTranslation } from 'react-i18next';* widgets extend the frame instead of stacking their own menus and toolbars.*/-const getPreviewGraph = (project: Project, surface: GraphBearingSurfaceContract): GraphContract | null => {+const GraphPreviewDialog = lazy(() =>+ import('@features/workflow/preview').then((module) => ({ default: module.GraphPreviewDialog }))+);++const getPreviewGraph = async (+ project: Project,+ surface: GraphBearingSurfaceContract+): Promise<GraphContract | null> => {// The project graph compiles fresh for preview so `View Graph` always shows// what Invoke would run right now; widget graphs keep their last compile.if (surface.sourceId === 'workflow') {+ const [{ compileProjectGraph }, { getInvocationTemplatesSnapshot }] = await Promise.all([+ import('@features/workflow/graph'),+ import('@features/workflow/react'),+ ]);const templatesSnapshot = getInvocationTemplatesSnapshot();if (templatesSnapshot.status !== 'loaded') {@@ -60,12 +69,9 @@ const GraphSurfaceMenuItems = ({}) => {const { t } = useTranslation();const activeSourceId = useActiveProjectSelector((project) => project.invocation.sourceId);- const dispatch = useWorkbenchDispatch();+ const { generation } = useWorkbenchCommands();const isActiveSource = activeSourceId === surface.sourceId;- const handleSetSource = useCallback(- () => dispatch({ sourceId: surface.sourceId, type: 'setInvocationSource' }),- [dispatch, surface.sourceId]- );+ const handleSetSource = useCallback(() => generation.setSource(surface.sourceId), [generation, surface.sourceId]);return (<Menu.ItemGroup>@@ -95,11 +101,13 @@ const GraphSurfaceMenuItems = ({};export const WidgetActionsMenu = ({+ HeaderMenu,instance,manifest,region,runtime,}: {+ HeaderMenu?: WidgetHeaderMenu;instance: WidgetInstanceRuntimeMeta;manifest: WidgetManifest;region: WorkbenchRegion;@@ -111,16 +119,21 @@ export const WidgetActionsMenu = ({shallowEqual) as Project;const [isPreviewOpen, setIsPreviewOpen] = useState(false);- const HeaderMenu = manifest.headerMenu;+ const [previewGraph, setPreviewGraph] = useState<GraphContract | null>(null);const label = resolveWidgetLabel(manifest, t);- const surface = manifest.graphBearing?.surfaces.includes(region)- ? createGraphBearingSurface(manifest, region, label)- : null;+ const surface = useMemo(+ () =>+ manifest.graphBearing?.surfaces.includes(region) ? createGraphBearingSurface(manifest, region, label) : null,+ [label, manifest, region]+ );const surfaceSourceId = surface?.sourceId;- const handlePreview = useCallback(() => {+ const handlePreview = useCallback(async () => {flushWorkbenchDrafts();+ if (surface) {+ setPreviewGraph(await getPreviewGraph(activeProject, surface));+ }setIsPreviewOpen(true);- }, []);+ }, [activeProject, surface]);const positionHints =isPreviewOpen && surfaceSourceId === 'workflow'? Object.fromEntries(activeProject.projectGraph.nodes.map((node) => [node.id, node.position]))@@ -130,7 +143,6 @@ export const WidgetActionsMenu = ({return null;}- const previewGraph = surface && isPreviewOpen ? getPreviewGraph(activeProject, surface) : null;// The project graph mirrors the editable document, so the preview can reuse// the editor's node positions instead of auto-layouting.return (@@ -154,15 +166,17 @@ export const WidgetActionsMenu = ({</Portal></Menu.Root>{surface && isPreviewOpen ? (- <GraphPreviewDialog- graph={previewGraph}- graphId={surface.graphId}- isOpen={isPreviewOpen}- positionHints={positionHints}- sourceId={surface.sourceId}- title={surface.label}- onOpenChange={setIsPreviewOpen}- />+ <Suspense fallback={null}>+ <GraphPreviewDialog+ graph={previewGraph}+ graphId={surface.graphId}+ isOpen={isPreviewOpen}+ positionHints={positionHints}+ sourceId={surface.sourceId}+ title={surface.label}+ onOpenChange={setIsPreviewOpen}+ />+ </Suspense>) : null}</>);diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsxindex ac6eb4f443..12f50ae7d3 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx@@ -1,10 +1,11 @@-import type { WidgetInstanceId, WidgetRegion } from '@workbench/types';+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { WidgetInstanceId } from '@workbench/widgetContracts';import type { WidgetRegionDropState } from '@workbench/widgetDnd';import type { WidgetPlacementInstanceMeta, WidgetRegionItem } from '@workbench/widgetRegionViewModel';import { Box, type SystemStyleObject } from '@chakra-ui/react';import { verticalListSortingStrategy } from '@dnd-kit/sortable';-import { Row, Tooltip } from '@workbench/components/ui';+import { Row, Tooltip } from '@platform/ui';import { WidgetIcon } from '@workbench/iconResolver';import { type MouseEvent, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetEnableMenu.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetEnableMenu.tsxindex e381197c94..5025c18223 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetEnableMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetEnableMenu.tsx@@ -1,13 +1,8 @@-import type {- RegisteredWidget,- WidgetIconComponent,- WidgetInstanceId,- WidgetRegion,- WidgetTypeId,-} from '@workbench/types';+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { RegisteredWidget, WidgetIconComponent, WidgetInstanceId, WidgetTypeId } from '@workbench/widgetContracts';import { Flex, Icon, Menu, Portal, Text } from '@chakra-ui/react';-import { IconButton } from '@workbench/components/ui';+import { IconButton } from '@platform/ui';import { WidgetIcon } from '@workbench/iconResolver';import { CheckIcon, MoreHorizontalIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsxindex 739369f085..ccaa469371 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsx@@ -1,13 +1,14 @@-import type { WidgetId } from '@workbench/types';+import type { WidgetId } from '@workbench/widgetContracts';import { Code, ScrollArea, Stack, Text } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';+import { Button } from '@platform/ui';import { Component, type ErrorInfo, type ReactNode } from 'react';interface WidgetFailureBoundaryProps {widgetId: WidgetId;resetKey: string;children: ReactNode;+ onRetry?: () => void;}interface WidgetFailureBoundaryState {@@ -20,6 +21,7 @@ export class WidgetFailureBoundary extends Component<WidgetFailureBoundaryProps,state: WidgetFailureBoundaryState = { resetKey: this.props.resetKey };private handleRetry = () => {+ this.props.onRetry?.();this.setState({ details: undefined, error: undefined, resetKey: this.props.resetKey });};diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsxindex 8e25fd9b82..3e6925fc48 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx@@ -1,22 +1,22 @@-/* eslint-disable react/react-compiler */+import type { WidgetRegion } from '@workbench/layoutContracts';import type {WidgetInstanceId,WidgetInstanceRuntimeMeta,+ WidgetHeaderLabel,+ WidgetHeaderMenu,WidgetManifest,- WidgetRegion,WidgetRuntimeApi,WidgetTypeId,WorkbenchRegion,-} from '@workbench/types';+} from '@workbench/widgetContracts';-import { Box, Flex, HStack, Icon, Stack, Text, type RecipeVariantProps, useRecipe } from '@chakra-ui/react';-import { chipRecipe } from '@theme/recipes';-import { IconButton, Tooltip } from '@workbench/components/ui';+import { Box, Flex, HStack, Icon, Stack, Text } from '@chakra-ui/react';+import { IconButton, Tooltip } from '@platform/ui';import { useFocusRegionProps } from '@workbench/focusRegions';import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';import { resolveWidgetLabel } from '@workbench/widgetLabels';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { SettingsIcon, type LucideIcon } from 'lucide-react';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { SettingsIcon } from 'lucide-react';import {useCallback,useMemo,@@ -63,12 +63,12 @@ export const WidgetPanelFrame = ({typeId?: WidgetTypeId;}) => {const regionState = useActiveProjectSelector((project) => project.widgetRegions[region]);- const dispatch = useWorkbenchDispatch();+ const { layout } = useWorkbenchCommands();const [dragSizePx, setDragSizePx] = useState<number | null>(null);const isLeft = region === 'left';const isBottom = region === 'bottom';const displaySizePx = dragSizePx ?? regionState.sizePx;- const sizeBounds = getPanelSizeBounds(region);+ const { max: maxPanelSizePx, min: minPanelSizePx } = getPanelSizeBounds(region);const focusRegionProps = useFocusRegionProps(region);const commitSize = useCallback(@@ -76,10 +76,10 @@ export const WidgetPanelFrame = ({const nextSizePx = clampSize(region, sizePx);if (nextSizePx !== regionState.sizePx) {- dispatch({ region, sizePx: nextSizePx, type: 'setRegionWidgetSize' });+ layout.setRegionSize(region, nextSizePx);}},- [dispatch, region, regionState.sizePx]+ [layout, region, regionState.sizePx]);const handlePointerDown = useCallback(@@ -91,6 +91,7 @@ export const WidgetPanelFrame = ({const startSizePx = regionState.sizePx;let nextSizePx = startSizePx;const direction = isLeft ? 1 : -1;+ const pointerSession = new AbortController();const handlePointerMove = (moveEvent: PointerEvent) => {const deltaPx = isBottom ? startY - moveEvent.clientY : (moveEvent.clientX - startX) * direction;@@ -100,16 +101,14 @@ export const WidgetPanelFrame = ({};const handlePointerUp = () => {- window.removeEventListener('pointermove', handlePointerMove);- window.removeEventListener('pointerup', handlePointerUp);- window.removeEventListener('pointercancel', handlePointerUp);+ pointerSession.abort();setDragSizePx(null);commitSize(nextSizePx);};- window.addEventListener('pointermove', handlePointerMove);- window.addEventListener('pointerup', handlePointerUp);- window.addEventListener('pointercancel', handlePointerUp);+ window.addEventListener('pointermove', handlePointerMove, { signal: pointerSession.signal });+ window.addEventListener('pointerup', handlePointerUp, { signal: pointerSession.signal });+ window.addEventListener('pointercancel', handlePointerUp, { signal: pointerSession.signal });},[commitSize, isBottom, isLeft, region, regionState.sizePx]);@@ -118,12 +117,12 @@ export const WidgetPanelFrame = ({(event: ReactKeyboardEvent<HTMLDivElement>) => {const step = event.shiftKey ? PANEL_SIZE_STEP_PX * 2 : PANEL_SIZE_STEP_PX;const sizeChanges: Partial<Record<string, number>> = isBottom- ? { ArrowDown: -step, ArrowUp: step, End: sizeBounds.max - displaySizePx, Home: sizeBounds.min - displaySizePx }+ ? { ArrowDown: -step, ArrowUp: step, End: maxPanelSizePx - displaySizePx, Home: minPanelSizePx - displaySizePx }: {ArrowLeft: isLeft ? -step : step,ArrowRight: isLeft ? step : -step,- End: sizeBounds.max - displaySizePx,- Home: sizeBounds.min - displaySizePx,+ End: maxPanelSizePx - displaySizePx,+ Home: minPanelSizePx - displaySizePx,};const sizeChange = sizeChanges[event.key];@@ -134,7 +133,7 @@ export const WidgetPanelFrame = ({event.preventDefault();commitSize(displaySizePx + sizeChange);},- [commitSize, displaySizePx, isBottom, isLeft, sizeBounds.max, sizeBounds.min]+ [commitSize, displaySizePx, isBottom, isLeft, maxPanelSizePx, minPanelSizePx]);const panelSizeProps = useMemo(() => (isBottom ? { h: `${displaySizePx}px`, w: 'full' } : { h: 'full', w: `${displaySizePx}px` }),@@ -171,8 +170,8 @@ export const WidgetPanelFrame = ({<Boxaria-label={`Resize ${region} widget panel`}aria-orientation={isBottom ? 'horizontal' : 'vertical'}- aria-valuemax={sizeBounds.max}- aria-valuemin={sizeBounds.min}+ aria-valuemax={maxPanelSizePx}+ aria-valuemin={minPanelSizePx}aria-valuenow={displaySizePx}as="div"cursor={isBottom ? 'ns-resize' : 'ew-resize'}@@ -195,12 +194,16 @@ export const WidgetPanelFrame = ({export const WidgetHeader = ({actions,+ HeaderLabel,+ HeaderMenu,instance,manifest,region,runtime,}: {actions?: ReactNode;+ HeaderLabel?: WidgetHeaderLabel;+ HeaderMenu?: WidgetHeaderMenu;instance: WidgetInstanceRuntimeMeta;manifest: WidgetManifest;region: WorkbenchRegion;@@ -209,7 +212,6 @@ export const WidgetHeader = ({const { t } = useTranslation();// Manifests may provide a component label (e.g. Workflow's editable// `Workflow / [name]`); plain strings render as the standard title.- const HeaderLabel = manifest.headerLabel;const label = resolveWidgetLabel(manifest, t);const handleSettingsClick = useCallback(() => openWorkbenchSettings(manifest.settingsSection),@@ -242,7 +244,13 @@ export const WidgetHeader = ({</IconButton></Tooltip>) : null}- <WidgetActionsMenu instance={instance} manifest={manifest} region={region} runtime={runtime} />+ <WidgetActionsMenu+ HeaderMenu={HeaderMenu}+ instance={instance}+ manifest={manifest}+ region={region}+ runtime={runtime}+ /></HStack></HStack>);@@ -256,22 +264,3 @@ export const FieldPlaceholder = ({ label, h }: { label: string; h: string }) =><Box bg="bg.subtle" borderWidth="1px" borderColor="border.subtle" h={h} rounded="md" w="full" /></Stack>);--export const StatusWidgetChip = ({- children,- icon,- tone,-}: {- children: ReactNode;- icon: LucideIcon;- tone?: NonNullable<RecipeVariantProps<typeof chipRecipe>>['tone'];-}) => {- const recipe = useRecipe({ recipe: chipRecipe });-- return (- <HStack css={recipe({ tone })}>- <Icon as={icon} boxSize="3" />- <Text whiteSpace="nowrap">{children}</Text>- </HStack>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsxindex 29bf828f63..104dda0544 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx@@ -1,11 +1,38 @@import { getWidgetHosts } from '@workbench/widgetRegistry';+import { Suspense, use } from 'react';++import { WidgetFailureBoundary } from './WidgetFailureBoundary';++const WidgetHost = ({ widget }: { widget: ReturnType<typeof getWidgetHosts>[number] }) => {+ const Host = use(widget.implementation.load()).host;++ return Host ? <Host /> : null;+};++const WidgetHostBoundary = ({ widget }: { widget: ReturnType<typeof getWidgetHosts>[number] }) => {+ const content = (+ <Suspense fallback={null}>+ <WidgetHost widget={widget} />+ </Suspense>+ );++ return widget.manifest.failurePolicy.isolateRenderFailure ? (+ <WidgetFailureBoundary+ resetKey={widget.manifest.id}+ widgetId={widget.manifest.id}+ onRetry={widget.implementation.retry}+ >+ {content}+ </WidgetFailureBoundary>+ ) : (+ content+ );+};export const WidgetHosts = () => (<>- {getWidgetHosts().map((widget) => {- const Host = widget.manifest.host;-- return Host ? <Host key={widget.manifest.id} /> : null;- })}+ {getWidgetHosts().map((widget) => (+ <WidgetHostBoundary key={widget.manifest.id} widget={widget} />+ ))}</>);diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.tsxindex 001e5a3693..c3ceb87ede 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.tsx@@ -1,4 +1,4 @@-import type { WidgetViewProps } from '@workbench/types';+import type { WidgetViewProps } from '@workbench/widgetContracts';import { Flex, HStack, Spinner, Text } from '@chakra-ui/react';diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsxindex 80a3dee0ec..b759d7948e 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx@@ -1,17 +1,18 @@import type {RegisteredWidget,+ WidgetImplementation,WidgetInstanceContract,WidgetInstanceRuntimeMeta,WidgetRuntimeApi,WidgetViewProps,-} from '@workbench/types';+} from '@workbench/widgetContracts';import { Box, Flex, Text } from '@chakra-ui/react';-import { Scrollable } from '@workbench/components/ui';+import { Scrollable } from '@platform/ui';import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useWorkbenchWidgetRegistry } from '@workbench/WorkbenchWidgetRegistryContext';-import { memo, Suspense, useMemo } from 'react';+import { memo, Suspense, use, useMemo } from 'react';import { useWidgetRuntime } from './createWidgetRuntime';import { WidgetFailureBoundary } from './WidgetFailureBoundary';@@ -39,10 +40,29 @@ export const WidgetRendererById = ({ instanceId, widget, ...props }: WidgetRende};export const WidgetRenderer = ({ instance, presentation, region, widget }: WidgetRendererProps) => {- const dispatch = useWorkbenchDispatch();+ const loadingFallback = useMemo(() => <WidgetLoadingFallback presentation={presentation} />, [presentation]);+ const content = (+ <Suspense fallback={loadingFallback}>+ <LoadedWidgetRenderer instance={instance} presentation={presentation} region={region} widget={widget} />+ </Suspense>+ );++ if (!widget.manifest.failurePolicy.isolateRenderFailure) {+ return content;+ }++ return (+ <WidgetFailureBoundary resetKey={instance.id} widgetId={widget.manifest.id} onRetry={widget.implementation.retry}>+ {content}+ </WidgetFailureBoundary>+ );+};++const LoadedWidgetRenderer = ({ instance, presentation, region, widget }: WidgetRendererProps) => {const { getWidgetById, getWidgetsForRegion } = useWorkbenchWidgetRegistry();const project = useActiveProjectSelector(getWidgetPlacementProject, areWidgetPlacementProjectsEqual);- const View = widget.manifest.view;+ const implementation = use(widget.implementation.load());+ const View = implementation.view;const instanceMeta: WidgetInstanceRuntimeMeta = useMemo(() => ({createdAt: instance.createdAt,@@ -53,33 +73,25 @@ export const WidgetRenderer = ({ instance, presentation, region, widget }: Widge[instance.createdAt, instance.id, instance.title, instance.typeId]);const runtime = useWidgetRuntime({- dispatch,getWidgetById,getWidgetsForRegion,instance: instanceMeta,project,region,});- const loadingFallback = useMemo(() => <WidgetLoadingFallback presentation={presentation} />, [presentation]);-- if (!View) {- return null;- }-const content = (- <Suspense fallback={loadingFallback}>- <View- instance={instanceMeta}- manifest={widget.manifest}- presentation={presentation}- region={region}- runtime={runtime}- />- </Suspense>+ <View+ instance={instanceMeta}+ manifest={widget.manifest}+ presentation={presentation}+ region={region}+ runtime={runtime}+ />);return (<WidgetShellFrame+ implementation={implementation}instance={instanceMeta}presentation={presentation}region={region}@@ -93,6 +105,7 @@ export const WidgetRenderer = ({ instance, presentation, region, widget }: Widgeconst WidgetShellFrame = ({children,+ implementation,instance,presentation,region,@@ -100,17 +113,14 @@ const WidgetShellFrame = ({widget,}: {children: React.ReactNode;+ implementation: WidgetImplementation;instance: WidgetInstanceRuntimeMeta;presentation: WidgetViewProps['presentation'];region: WidgetViewProps['region'];runtime: WidgetRuntimeApi;widget: RegisteredWidget;}) => {- const safeContent = (- <RenderFailureSlot instance={instance} widget={widget}>- {children}- </RenderFailureSlot>- );+ const safeContent = children;if (region === 'popover' || region === 'dialog' || presentation === 'compact' || presentation === 'tooltip') {return safeContent;@@ -119,9 +129,23 @@ const WidgetShellFrame = ({if (region === 'left' || region === 'right' || region === 'bottom') {return (<WidgetPanelFrame instanceId={instance.id} region={region} typeId={instance.typeId}>- <HeaderSlot instance={instance} presentation={presentation} region={region} runtime={runtime} widget={widget} />+ <HeaderSlot+ implementation={implementation}+ instance={instance}+ presentation={presentation}+ region={region}+ runtime={runtime}+ widget={widget}+ /><PanelBodySlot>{safeContent}</PanelBodySlot>- <FooterSlot instance={instance} presentation={presentation} region={region} runtime={runtime} widget={widget} />+ <FooterSlot+ implementation={implementation}+ instance={instance}+ presentation={presentation}+ region={region}+ runtime={runtime}+ widget={widget}+ /></WidgetPanelFrame>);}@@ -137,40 +161,35 @@ const WidgetShellFrame = ({minH="0"w="full">- <HeaderSlot instance={instance} presentation={presentation} region={region} runtime={runtime} widget={widget} />+ <HeaderSlot+ implementation={implementation}+ instance={instance}+ presentation={presentation}+ region={region}+ runtime={runtime}+ widget={widget}+ /><Box flex="1" minH="0" overflow="hidden" position="relative">{safeContent}</Box>- <FooterSlot instance={instance} presentation={presentation} region={region} runtime={runtime} widget={widget} />+ <FooterSlot+ implementation={implementation}+ instance={instance}+ presentation={presentation}+ region={region}+ runtime={runtime}+ widget={widget}+ /></Flex>);};-const RenderFailureSlot = ({- children,- instance,- widget,-}: {- children: React.ReactNode;- instance: WidgetInstanceRuntimeMeta;- widget: RegisteredWidget;-}) => {- if (!widget.manifest.failurePolicy.isolateRenderFailure) {- return children;- }-- return (- <WidgetFailureBoundary resetKey={instance.id} widgetId={widget.manifest.id}>- {children}- </WidgetFailureBoundary>- );-};-const areWidgetChromeInstancesEqual = (left: WidgetInstanceRuntimeMeta, right: WidgetInstanceRuntimeMeta): boolean =>left.id === right.id && left.typeId === right.typeId && left.title === right.title;const areSlotPropsEqual = (left: {+ implementation: WidgetImplementation;instance: WidgetInstanceRuntimeMeta;presentation: WidgetViewProps['presentation'];region: WidgetViewProps['region'];@@ -178,6 +197,7 @@ const areSlotPropsEqual = (widget: RegisteredWidget;},right: {+ implementation: WidgetImplementation;instance: WidgetInstanceRuntimeMeta;presentation: WidgetViewProps['presentation'];region: WidgetViewProps['region'];@@ -186,25 +206,28 @@ const areSlotPropsEqual = (}): boolean =>left.presentation === right.presentation &&+ left.implementation === right.implementation &&left.region === right.region &&left.widget === right.widget &&left.runtime === right.runtime &&areWidgetChromeInstancesEqual(left.instance, right.instance);const HeaderSlot = memo(function HeaderSlot({+ implementation,instance,presentation,region,runtime,widget,}: {+ implementation: WidgetImplementation;instance: WidgetInstanceRuntimeMeta;presentation: WidgetViewProps['presentation'];region: WidgetViewProps['region'];runtime: WidgetRuntimeApi;widget: RegisteredWidget;}) {- const HeaderActions = widget.manifest.headerActions;+ const HeaderActions = implementation.headerActions;const actions = useMemo(() =>HeaderActions ? (@@ -227,6 +250,8 @@ const HeaderSlot = memo(function HeaderSlot({return (<Box bg={bg} flexShrink={0}><WidgetHeader+ HeaderLabel={implementation.headerLabel}+ HeaderMenu={implementation.headerMenu}actions={actions}instance={instance}manifest={widget.manifest}@@ -258,19 +283,21 @@ export const PanelBodySlot = ({ children }: { children: React.ReactNode }) => ();const FooterSlot = memo(function FooterSlot({+ implementation,instance,presentation,region,runtime,widget,}: {+ implementation: WidgetImplementation;instance: WidgetInstanceRuntimeMeta;presentation: WidgetViewProps['presentation'];region: WidgetViewProps['region'];runtime: WidgetRuntimeApi;widget: RegisteredWidget;}) {- const Footer = widget.manifest.footer;+ const Footer = implementation.footer;if (!Footer) {return null;diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetStrip.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetStrip.tsxindex c7b880d831..b8b9aee266 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetStrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetStrip.tsx@@ -1,4 +1,5 @@-import type { WidgetInstanceId, WidgetRegion } from '@workbench/types';+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { WidgetInstanceId } from '@workbench/widgetContracts';import type { WidgetRegionDropState } from '@workbench/widgetDnd';import { Flex, type FlexProps } from '@chakra-ui/react';diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.tsindex a677dfbdad..817972a950 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts@@ -1,14 +1,16 @@+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { Project } from '@workbench/projectContracts';import type {- Project,NormalizedWidgetManifest,RegisteredWidget,WidgetInstanceContract,- WidgetRegion,WidgetTypeId,-} from '@workbench/types';-import type { WorkbenchAction } from '@workbench/workbenchState';+} from '@workbench/widgetContracts';+import type { WorkbenchAction } from '@workbench/workbenchState.testing';+import type { WorkbenchWidgetCommands } from '@workbench/workbenchStore';import { clearProjectDiagnostics, configureDiagnostics, getProjectDiagnostics } from '@workbench/diagnostics/logger';+import { createWidgetImplementationResource } from '@workbench/widgetImplementationResource';import { beforeEach, describe, expect, it, vi } from 'vitest';import { cloneWidgetRuntimeState, createWidgetRuntime, getProjectWidgetRuntimeState } from './createWidgetRuntime';@@ -19,6 +21,7 @@ const TestView = () => null;const createWidget = (overrides: Partial<NormalizedWidgetManifest> & Pick<NormalizedWidgetManifest, 'id' | 'label'>): RegisteredWidget => ({+ implementation: createWidgetImplementationResource(overrides.id, () => Promise.resolve({ view: TestView })),manifest: {apiVersion: 1,allowMultiple: false,@@ -27,9 +30,9 @@ const createWidget = (centerPlacement: 'view',failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },icon: TestIcon,+ load: () => Promise.resolve({ view: TestView }),state: { createInitial: () => ({}), persistence: 'project', version: 1 },version: 1,- view: TestView,...overrides,},status: 'enabled',@@ -48,7 +51,20 @@ const createDispatch = () => {actions.push(action);};- return { actions, dispatch };+ const widgets: WorkbenchWidgetCommands = {+ move: (options) => dispatch({ ...options, type: 'moveWidgetInstance' }),+ open: (options) => dispatch({ ...options, type: 'openRegionWidget' }),+ patchInstanceValues: (instanceId, values, projectId) =>+ dispatch({ instanceId, projectId, type: 'patchWidgetInstanceValues', values }),+ patchValues: (widgetId, values, projectId) => dispatch({ projectId, type: 'patchWidgetValues', values, widgetId }),+ reorder: (options) => dispatch({ ...options, type: 'reorderWidgetInstances' }),+ select: (options) => dispatch({ ...options, type: 'selectRegionWidget' }),+ setInstanceValues: (instanceId, values, projectId) =>+ dispatch({ instanceId, projectId, type: 'setWidgetInstanceValues', values }),+ toggle: (options) => dispatch({ ...options, type: 'toggleRegionWidget' }),+ };++ return { actions, widgets };};const createStateApi = () => ({@@ -107,10 +123,10 @@ describe('createWidgetRuntime', () => {});it('exposes widget state reads and writes through the state namespace', () => {- const { actions, dispatch } = createDispatch();+ const { actions, widgets } = createDispatch();const state = createStateApi();const runtime = createWidgetRuntime({- dispatch,+ widgets,getWidgetById: () => undefined,getWidgetsForRegion: createRegistry({}),instance: createInstance(),@@ -129,9 +145,9 @@ describe('createWidgetRuntime', () => {});it('binds diagnostics to the current widget source', () => {- const { dispatch } = createDispatch();+ const { widgets } = createDispatch();const runtime = createWidgetRuntime({- dispatch,+ widgets,getWidgetById: () => undefined,getWidgetsForRegion: createRegistry({}),instance: createInstance('workflow:center', 'workflow'),@@ -159,10 +175,10 @@ describe('createWidgetRuntime', () => {});it('opens widgets through canonical validation and seeded initial values', () => {- const { actions, dispatch } = createDispatch();+ const { actions, widgets } = createDispatch();const createInitial = vi.fn(() => ({ seeded: true }));const runtime = createWidgetRuntime({- dispatch,+ widgets,getWidgetById: () => undefined,getWidgetsForRegion: createRegistry({bottom: [createWidget({ bottomPanel: 'tooltip', id: 'tooltip-widget', label: 'Tooltip Widget' })],@@ -212,9 +228,9 @@ describe('createWidgetRuntime', () => {});it('dispatches own-region close and reveal actions', () => {- const { actions, dispatch } = createDispatch();+ const { actions, widgets } = createDispatch();const runtime = createWidgetRuntime({- dispatch,+ widgets,getWidgetById: (typeId) => createWidget({ id: typeId, label: typeId }),getWidgetsForRegion: createRegistry({}),instance: createInstance(),@@ -239,9 +255,9 @@ describe('createWidgetRuntime', () => {});it('returns unsupported for cross-region close and reveal', () => {- const { actions, dispatch } = createDispatch();+ const { actions, widgets } = createDispatch();const runtime = createWidgetRuntime({- dispatch,+ widgets,getWidgetById: () => undefined,getWidgetsForRegion: createRegistry({}),instance: createInstance(),@@ -256,9 +272,9 @@ describe('createWidgetRuntime', () => {});it('executes commands registered by the current widget source', async () => {- const { dispatch } = createDispatch();+ const { widgets } = createDispatch();const alphaRuntime = createWidgetRuntime({- dispatch,+ widgets,getWidgetById: () => undefined,getWidgetsForRegion: createRegistry({}),instance: createInstance('alpha', 'test-widget'),@@ -267,7 +283,7 @@ describe('createWidgetRuntime', () => {state: createStateApi(),});const betaRuntime = createWidgetRuntime({- dispatch,+ widgets,getWidgetById: () => undefined,getWidgetsForRegion: createRegistry({}),instance: createInstance('beta', 'test-widget'),@@ -294,9 +310,9 @@ describe('createWidgetRuntime', () => {});it('does not execute commands registered by the same widget instance in another project', async () => {- const { dispatch } = createDispatch();+ const { widgets } = createDispatch();const projectOneRuntime = createWidgetRuntime({- dispatch,+ widgets,getWidgetById: () => undefined,getWidgetsForRegion: createRegistry({}),instance: createInstance('alpha', 'test-widget'),@@ -305,7 +321,7 @@ describe('createWidgetRuntime', () => {state: createStateApi(),});const projectTwoRuntime = createWidgetRuntime({- dispatch,+ widgets,getWidgetById: () => undefined,getWidgetsForRegion: createRegistry({}),instance: createInstance('alpha', 'test-widget'),diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.tsindex 9eb3e095af..44985f6d10 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.ts@@ -1,19 +1,18 @@-/* eslint-disable react/react-compiler */+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { Project } from '@workbench/projectContracts';import type {- Project,WidgetHotkeyApi,OpenWorkbenchWidgetOptions,RegisteredWidget,WidgetContributionSource,WidgetInstanceRuntimeMeta,- WidgetRegion,WidgetRuntimeStateApi,WidgetRuntimeApi,WidgetTypeId,WorkbenchRegion,-} from '@workbench/types';+} from '@workbench/widgetContracts';import type { WidgetPlacementProject } from '@workbench/widgetPlacementCommands';-import type { WorkbenchAction } from '@workbench/workbenchState';+import type { WorkbenchWidgetCommands } from '@workbench/workbenchStore';import { createProjectLogger } from '@workbench/diagnostics/logger';import {@@ -25,8 +24,8 @@ import {toolbarApi,} from '@workbench/extensions/extensionApi';import { closeWidgetPlacement, openWidgetPlacement, revealWidgetPlacement } from '@workbench/widgetPlacementCommands';-import { useProjectWidgetInstanceValuesSelector, useWorkbenchStore } from '@workbench/WorkbenchContext';-import { useMemo, type Dispatch } from 'react';+import { useWorkbenchInternalStore } from '@workbench/WorkbenchContext';+import { useMemo } from 'react';const WIDGET_REGIONS = new Set<WidgetRegion>(['bottom', 'center', 'left', 'right']);@@ -72,21 +71,21 @@ export const getProjectWidgetRuntimeState = <State extends Record<string, unknow);export const createWidgetRuntime = ({- dispatch,getWidgetsForRegion,getWidgetById,instance,project,region,state,+ widgets,}: {- dispatch: Dispatch<WorkbenchAction>;getWidgetById: (typeId: WidgetTypeId) => RegisteredWidget | undefined;getWidgetsForRegion: (region: WidgetRegion) => RegisteredWidget[];instance: WidgetInstanceRuntimeMeta;project: WidgetPlacementProject;region: WorkbenchRegion;state: WidgetRuntimeStateApi;+ widgets: WorkbenchWidgetCommands;}): WidgetRuntimeApi => {const sourceProjectId = project.projectId ?? '';const source: WidgetContributionSource = {@@ -133,67 +132,48 @@ export const createWidgetRuntime = ({return { ok: false, reason: 'unsupported' };}- return closeWidgetPlacement({ dispatch, getWidgetById, instanceId, project, region });+ return closeWidgetPlacement({ getWidgetById, instanceId, project, region, widgets });},openWidget: (typeId: WidgetTypeId, options?: OpenWorkbenchWidgetOptions) =>- openWidgetPlacement({ dispatch, getWidgetsForRegion, options, projectId: project.projectId, typeId }),+ openWidgetPlacement({ getWidgetsForRegion, options, projectId: project.projectId, typeId, widgets }),revealWidgetInstance: (instanceId) => {if (!isWidgetRegion(region)) {return { ok: false, reason: 'unsupported' };}- return revealWidgetPlacement({ dispatch, instanceId, project, region });+ return revealWidgetPlacement({ instanceId, project, region, widgets });},},};};export const useWidgetRuntime = ({- dispatch,getWidgetsForRegion,getWidgetById,instance,project,region,}: {- dispatch: Dispatch<WorkbenchAction>;getWidgetById: (typeId: WidgetTypeId) => RegisteredWidget | undefined;getWidgetsForRegion: (region: WidgetRegion) => RegisteredWidget[];instance: WidgetInstanceRuntimeMeta;project: WidgetPlacementProject;region: WorkbenchRegion;}): WidgetRuntimeApi => {- const store = useWorkbenchStore();+ const store = useWorkbenchInternalStore();+ const { widgets } = store.commands;const projectId = project.projectId ?? store.getSnapshot().activeProject.id;const state = useMemo<WidgetRuntimeStateApi>(() => ({getSnapshot: () => getProjectWidgetRuntimeState(store.getState().projects, projectId, instance.id),- patch: (values) =>- dispatch({- instanceId: instance.id,- projectId,- type: 'patchWidgetInstanceValues',- values: cloneWidgetRuntimeState(values),- }),- set: (values) =>- dispatch({- instanceId: instance.id,- projectId,- type: 'setWidgetInstanceValues',- values: cloneWidgetRuntimeState(values),- }),- useSelector<Selected>(- selector: (state: Record<string, unknown>) => Selected,- isEqual?: (left: Selected, right: Selected) => boolean- ): Selected {- return useProjectWidgetInstanceValuesSelector(projectId, instance.id, selector, isEqual);- },+ patch: (values) => widgets.patchInstanceValues(instance.id, cloneWidgetRuntimeState(values), projectId),+ set: (values) => widgets.setInstanceValues(instance.id, cloneWidgetRuntimeState(values), projectId),}),- [dispatch, instance.id, projectId, store]+ [instance.id, projectId, store, widgets]);return useMemo(- () => createWidgetRuntime({ dispatch, getWidgetById, getWidgetsForRegion, instance, project, region, state }),- [dispatch, getWidgetById, getWidgetsForRegion, instance, project, region, state]+ () => createWidgetRuntime({ getWidgetById, getWidgetsForRegion, instance, project, region, state, widgets }),+ [getWidgetById, getWidgetsForRegion, instance, project, region, state, widgets]);};diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/index.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/index.tsindex c0536106a3..3390268f8c 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/index.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/index.ts@@ -2,7 +2,8 @@ export { WidgetActionsMenu } from './WidgetActionsMenu';export { WidgetBar, type WidgetBarItem } from './WidgetBar';export { WidgetEnableMenu, type WidgetEnableMenuItem } from './WidgetEnableMenu';export { WidgetFailureBoundary } from './WidgetFailureBoundary';-export { FieldPlaceholder, StatusWidgetChip, WidgetHeader, WidgetPanelFrame } from './WidgetFrames';+export { FieldPlaceholder, WidgetHeader, WidgetPanelFrame } from './WidgetFrames';+export { StatusWidgetChip } from '@platform/ui';export { WidgetInstanceContextMenu, type WidgetInstanceContextMenuTarget } from './WidgetInstanceContextMenu';export { WidgetRegionDropOverlay } from './WidgetRegionDropOverlay';export { WidgetStrip } from './WidgetStrip';diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/useWidgetSortable.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/useWidgetSortable.tsindex 89ec5f76b7..f40c5f9d01 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/useWidgetSortable.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/useWidgetSortable.ts@@ -1,4 +1,5 @@-import type { WidgetInstanceId, WidgetRegion, WidgetTypeId } from '@workbench/types';+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { WidgetInstanceId, WidgetTypeId } from '@workbench/widgetContracts';import type { CSSProperties } from 'react';import { useSortable } from '@dnd-kit/sortable';diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.test.tsindex 9ea057e5b8..81bb2ee1ea 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.test.ts@@ -1,4 +1,4 @@-import type { WidgetInstanceContract } from '@workbench/types';+import type { WidgetInstanceContract } from '@workbench/widgetContracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.tsindex 4e4b613a77..8e02cf71da 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.ts@@ -1,4 +1,4 @@-import type { WidgetInstanceContract } from '@workbench/types';+import type { WidgetInstanceContract } from '@workbench/widgetContracts';export interface ProjectWidgetRenderInstance {instance: WidgetInstanceContract | undefined;diff --git a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts b/invokeai/frontend/webv2/src/workbench/widgetContracts.tsnew file mode 100644index 0000000000..26b52a0cde--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts@@ -0,0 +1,335 @@+import type { TFunction } from 'i18next';+import type { ComponentType, ExoticComponent, JSXElementConstructor, SVGProps } from 'react';++import type { DeveloperLogNamespace } from './diagnostics/contracts';+import type { GraphId } from './graphContracts';+import type { InvocationSourceId } from './invocationContracts';+import type { WidgetRegion } from './layoutContracts';++export type FirstPartyWidgetTypeId =+ | 'autosave-status'+ | 'canvas'+ | 'diagnostics'+ | 'gallery'+ | 'generate'+ | 'history-controls'+ | 'layers'+ | 'notifications'+ | 'preview'+ | 'project'+ | 'queue'+ | 'server-status'+ | 'upscale'+ | 'users'+ | 'version-status'+ | 'workflow';++export type WidgetTypeId = FirstPartyWidgetTypeId | (string & {});++export type WidgetInstanceId = string;++export type WidgetId = WidgetTypeId;++export type WorkbenchRegion = 'left' | 'right' | 'center' | 'bottom' | 'dialog' | 'popover';++export interface WidgetStateContract {+ id: WidgetTypeId;+ label: string;+ version: 1;+ values: Record<string, unknown>;+ graphId?: GraphId;+}++export type WidgetStateMap = Record<string, WidgetStateContract>;++export interface WidgetInstanceContract {+ id: WidgetInstanceId;+ typeId: WidgetTypeId;+ title?: string;+ state: WidgetStateContract;+ createdAt: string;+}++export interface WidgetInstanceRuntimeMeta {+ id: WidgetInstanceId;+ typeId: WidgetTypeId;+ title?: string;+ createdAt: string;+}++export interface GraphBearingSurfaceContract {+ surfaceId: string;+ widgetId: WidgetId;+ label: string;+ sourceId: InvocationSourceId;+ graphId: GraphId;+ region: WorkbenchRegion;+ canSetSource: boolean;+ canPreviewGraph: boolean;+}++export interface WidgetViewProps {+ region: WorkbenchRegion;+ manifest: WidgetManifest;+ /** Chrome metadata only. Read reactive widget values through `runtime.state`. */+ instance: WidgetInstanceRuntimeMeta;+ runtime: WidgetRuntimeApi;+ presentation?: 'compact' | 'expanded' | 'tooltip';+}++export type WidgetView = ComponentType<WidgetViewProps>;++export type WidgetHeaderActions = ComponentType<WidgetViewProps>;++export type WidgetHeaderMenu = ComponentType<WidgetViewProps>;++export type WidgetFooter = ComponentType<WidgetViewProps>;++export type WidgetHost = ComponentType;++/** Deferred render implementation shared by every slot for one widget type. */+export interface WidgetImplementation {+ view: WidgetView;+ host?: WidgetHost;+ headerActions?: WidgetHeaderActions;+ headerLabel?: WidgetHeaderLabel;+ headerMenu?: WidgetHeaderMenu;+ footer?: WidgetFooter;+}++export type WidgetImplementationLoadStatus = 'idle' | 'loading' | 'loaded' | 'failed';++/** Registry-owned, single-flight resource for a deferred widget implementation. */+export interface WidgetImplementationResource {+ getStatus: () => WidgetImplementationLoadStatus;+ load: () => Promise<WidgetImplementation>;+ preload: () => void;+ retry: () => Promise<WidgetImplementation>;+}++export interface WidgetLabelProps {+ region: WorkbenchRegion;+ presentation?: 'compact' | 'expanded' | 'tooltip';+}++export type WidgetLabel = string | ((t: TFunction) => string);++export type WidgetHeaderLabel = ComponentType<WidgetLabelProps>;++export type WidgetIconComponent =+ | JSXElementConstructor<SVGProps<SVGSVGElement>>+ | ExoticComponent<SVGProps<SVGSVGElement>>;++export interface WidgetStateRegistration<State extends Record<string, unknown> = Record<string, unknown>> {+ version: 1;+ createInitial: () => State;+ migrate?: (state: unknown, fromVersion: number) => State;+ persistence?: 'project' | 'workspace' | 'session' | 'none';+}++export interface WidgetRuntimeApi<State extends Record<string, unknown> = Record<string, unknown>> {+ instanceId: WidgetInstanceId;+ typeId: WidgetTypeId;+ region: WorkbenchRegion;+ state: WidgetRuntimeStateApi<State>;+ diagnostics: WidgetDiagnosticsApi;+ commands: WidgetCommandApi;+ hotkeys: WidgetHotkeyApi;+ menus: WidgetMenuApi;+ palette: WidgetCommandPaletteApi;+ search: WidgetSearchApi;+ toolbars: WidgetToolbarApi;+ workbench: WidgetWorkbenchApi;+}++export interface WidgetDiagnosticsApi {+ logger: (namespace: DeveloperLogNamespace) => {+ debug: (messageOrContext: string | Record<string, unknown>, message?: string) => void;+ error: (messageOrContext: string | Record<string, unknown>, message?: string) => void;+ fatal: (messageOrContext: string | Record<string, unknown>, message?: string) => void;+ info: (messageOrContext: string | Record<string, unknown>, message?: string) => void;+ trace: (messageOrContext: string | Record<string, unknown>, message?: string) => void;+ warn: (messageOrContext: string | Record<string, unknown>, message?: string) => void;+ };+}++export interface WidgetRuntimeStateApi<State extends Record<string, unknown> = Record<string, unknown>> {+ getSnapshot: () => Readonly<State>;+ patch: (values: Partial<State>) => void;+ set: (values: State) => void;+}++export interface WidgetContributionSource {+ instanceId: WidgetInstanceId;+ projectId: string;+ region: WorkbenchRegion;+ typeId: WidgetTypeId;+}++export interface WidgetCommandApi {+ execute: (commandId: string, ...args: unknown[]) => Promise<unknown>;+ executeForSource: (+ commandId: string,+ source: WidgetContributionSource | null,+ ...args: unknown[]+ ) => Promise<unknown>;+ register: (command: WidgetCommandContribution) => () => void;+}++export interface WidgetCommandContribution {+ id: string;+ title: string;+ handler: (...args: unknown[]) => unknown | Promise<unknown>;+ source?: WidgetContributionSource;+}++export interface WidgetHotkeyApi {+ register: (hotkey: WidgetHotkeyContribution) => () => void;+}++export interface WidgetHotkeyContribution {+ id: string;+ commandId: string;+ defaultKeys: string[];+ title: string;+ description?: string;+ scope?: 'focused-region' | 'global' | 'instance' | 'widget';+ source?: WidgetContributionSource;+ preventDefault?: boolean;+ allowInEditable?: boolean;+}++export interface WidgetMenuApi {+ register: (menu: WidgetMenuContribution) => () => void;+}++export interface WidgetMenuContribution {+ id: string;+ items: Array<{ commandId: string; group?: string }>;+ source?: WidgetContributionSource;+}++export interface WidgetCommandPaletteApi {+ register: (entry: WidgetCommandPaletteContribution) => () => void;+}++export interface WidgetCommandPaletteContribution {+ commandId: string;+ title: string;+ keywords?: string[];+}++export interface WidgetSearchApi {+ registerProvider: (provider: WidgetSearchProvider) => () => void;+}++export interface WidgetSearchProvider {+ id: string;+ label: string;+ search: (query: string) => Promise<WidgetSearchResult[]> | WidgetSearchResult[];+}++export interface WidgetSearchResult {+ id: string;+ title: string;+ subtitle?: string;+ commandId?: string;+}++export interface WidgetToolbarApi {+ register: (toolbar: WidgetToolbarContribution) => () => void;+}++export interface WidgetToolbarContribution {+ id: string;+ location: 'center.tabs.trailing' | 'status.left' | 'status.right';+ items: Array<{+ commandId: string;+ icon?: WidgetIconComponent;+ label?: string;+ }>;+}++export interface OpenWorkbenchWidgetOptions {+ createNew?: boolean;+ preferredRegions?: ReadonlyArray<WidgetRegion>;+ requireCenterView?: boolean;+}++export type WidgetWorkbenchApiResult =+ | { ok: true; region?: WidgetRegion }+ | { ok: false; reason: 'unavailable' | 'unsupported' | 'not-found' };++export interface WidgetWorkbenchApi {+ openWidget: (typeId: WidgetTypeId, options?: OpenWorkbenchWidgetOptions) => WidgetWorkbenchApiResult;+ revealWidgetInstance: (instanceId: WidgetInstanceId) => WidgetWorkbenchApiResult;+ closeWidgetInstance: (instanceId: WidgetInstanceId) => WidgetWorkbenchApiResult;+}++/** Sections of the workbench settings dialog, addressable via `openWorkbenchSettings`. */+export type SettingsSectionId =+ | 'appearance'+ | 'behavior'+ | 'hotkeys'+ | 'project'+ | 'queue'+ | 'workflow'+ | 'developer'+ | 'workspace';++export interface WidgetManifest {+ /** Widget runtime API contract version. Defaults to 1 during registry normalization. */+ apiVersion?: 1;+ id: WidgetTypeId;+ label: WidgetLabel;+ headerLabel?: WidgetHeaderLabel;+ version: 1;+ allowedRegions: WidgetRegion[];+ allowMultiple: boolean;+ icon: WidgetIconComponent;+ bottomPanel?: 'expandable' | 'tooltip';+ centerPlacement?: 'toolbar' | 'view';+ /** Only offered while an admin is signed in to a multi-user backend. */+ requiresAdmin?: boolean;+ chrome?: {+ header?: 'hidden' | 'visible';+ };+ /**+ * Literal dynamic loader for all render slots. The registry owns caching,+ * failure state, and retry; callers never invoke this directly.+ */+ load: () => Promise<WidgetImplementation>;+ /** The deferred implementation contains a singleton host mounted at editor boot. */+ hasHost?: boolean;+ /** When set, the frame header shows a gear that opens this settings dialog section. */+ settingsSection?: SettingsSectionId;+ state?: WidgetStateRegistration;+ graphBearing?: {+ sourceId: InvocationSourceId;+ defaultGraphId: GraphId;+ surfaces: WorkbenchRegion[];+ };+ failurePolicy: {+ onRegistrationFailure: 'disable' | 'hide';+ isolateRenderFailure: boolean;+ };+}++export interface NormalizedWidgetManifest extends Omit<WidgetManifest, 'apiVersion' | 'state'> {+ apiVersion: 1;+ state: WidgetStateRegistration;+}++export interface RegisteredWidget {+ implementation: WidgetImplementationResource;+ manifest: NormalizedWidgetManifest;+ status: 'enabled' | 'disabled' | 'hidden';+ failure?: WidgetFailure;+}++export interface WidgetFailure {+ widgetId: WidgetTypeId;+ message: string;+ details: string;+ occurredAt: string;+}diff --git a/invokeai/frontend/webv2/src/workbench/widgetDnd.test.ts b/invokeai/frontend/webv2/src/workbench/widgetDnd.test.tsindex 2f7a0dd7e3..9e6861e339 100644--- a/invokeai/frontend/webv2/src/workbench/widgetDnd.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetDnd.test.ts@@ -1,9 +1,10 @@import type { CollisionDetection, DroppableContainer } from '@dnd-kit/core';+import type { Project, WorkbenchState } from '@workbench/projectContracts';+import type { WidgetTypeId } from '@workbench/widgetContracts';+import { getGalleryImageDragData } from '@features/gallery/utility';import { describe, expect, it } from 'vitest';-import type { Project, WidgetTypeId, WorkbenchState } from './types';-import {getRegionDropState,getWidgetInstanceDragData,@@ -13,7 +14,6 @@ import {widgetCollisionDetection,} from './widgetDnd';import { getCanvasImageDropData } from './widgets/canvas/canvasImageDnd';-import { getGalleryImageDragData } from './widgets/gallery/galleryDnd';import { createInitialWorkbenchState } from './workbenchState';type CollisionArgs = Parameters<CollisionDetection>[0];diff --git a/invokeai/frontend/webv2/src/workbench/widgetDnd.ts b/invokeai/frontend/webv2/src/workbench/widgetDnd.tsindex 184b3f1789..53c0076911 100644--- a/invokeai/frontend/webv2/src/workbench/widgetDnd.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetDnd.ts@@ -1,8 +1,9 @@+import type { WidgetRegion, WidgetRegionState } from '@workbench/layoutContracts';+import type { WidgetIconComponent, WidgetInstanceId, WidgetTypeId } from '@workbench/widgetContracts';+import { closestCenter, pointerWithin, type CollisionDetection } from '@dnd-kit/core';import { arrayMove } from '@dnd-kit/sortable';-import type { WidgetIconComponent, WidgetInstanceId, WidgetRegion, WidgetRegionState, WidgetTypeId } from './types';-export interface WidgetDndProject {widgetInstances: Record<WidgetInstanceId, { typeId: WidgetTypeId; title?: string }>;widgetRegions: Record<WidgetRegion, Pick<WidgetRegionState, 'activeInstanceId' | 'instanceIds'>>;diff --git a/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.browser.test.tsxnew file mode 100644index 0000000000..7d0447b8ff--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.browser.test.tsx@@ -0,0 +1,85 @@+import type { WidgetImplementationResource } from '@workbench/widgetContracts';++import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { Suspense, act, use } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { WidgetFailureBoundary } from './widget-frame/WidgetFailureBoundary';+import { createWidgetImplementationResource } from './widgetImplementationResource';++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const TestView = () => null;+const loadingFallback = <div data-testid="loading">Loading</div>;++const ResourceProbe = ({ resource }: { resource: WidgetImplementationResource }) => {+ use(resource.load());++ return <div data-testid="loaded">Loaded</div>;+};++const renderResource = async (resource: WidgetImplementationResource) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);++ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <WidgetFailureBoundary resetKey="test" widgetId="test" onRetry={resource.retry}>+ <Suspense fallback={loadingFallback}>+ <ResourceProbe resource={resource} />+ </Suspense>+ </WidgetFailureBoundary>+ </ChakraProvider>+ );+ });+};++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('widget implementation resource rendering', () => {+ it('suspends until the shared implementation resolves', async () => {+ let resolveLoad: (() => void) | undefined;+ const resource = createWidgetImplementationResource(+ 'test',+ () =>+ new Promise((resolve) => {+ resolveLoad = () => resolve({ view: TestView });+ })+ );++ await renderResource(resource);+ expect(host?.querySelector('[data-testid="loading"]')).not.toBeNull();++ await act(() => resolveLoad?.());+ expect(host?.querySelector('[data-testid="loaded"]')).not.toBeNull();+ });++ it('isolates a rejected chunk and retries through the same resource', async () => {+ const loader = vi+ .fn()+ .mockRejectedValueOnce(new Error('chunk unavailable'))+ .mockResolvedValueOnce({ view: TestView });+ const resource = createWidgetImplementationResource('test', loader);++ await renderResource(resource);+ await expect.poll(() => host?.textContent).toContain('Widget failed: test');++ const retry = [...(host?.querySelectorAll('button') ?? [])].find((button) => button.textContent === 'Retry');+ expect(retry).toBeDefined();+ await act(() => retry?.click());++ await expect.poll(() => host?.querySelector('[data-testid="loaded"]')).not.toBeNull();+ expect(loader).toHaveBeenCalledTimes(2);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.test.ts b/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.test.tsnew file mode 100644index 0000000000..3a482273b0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it, vi } from 'vitest';++import type { WidgetImplementation } from './widgetContracts';++import { createWidgetImplementationResource } from './widgetImplementationResource';++const TestView = () => null;+const implementation: WidgetImplementation = { view: TestView };++describe('widget implementation resource', () => {+ it('loads once and shares the promise and implementation instance', async () => {+ const loader = vi.fn(() => Promise.resolve(implementation));+ const resource = createWidgetImplementationResource('test', loader);++ const first = resource.load();+ const second = resource.load();++ expect(first).toBe(second);+ await expect(first).resolves.toBe(implementation);+ expect(resource.load()).toBe(first);+ expect(loader).toHaveBeenCalledOnce();+ expect(resource.getStatus()).toBe('loaded');+ });++ it('caches a rejected load and starts exactly one new attempt on retry', async () => {+ const failure = new Error('chunk unavailable');+ const loader = vi.fn().mockRejectedValueOnce(failure).mockResolvedValueOnce(implementation);+ const resource = createWidgetImplementationResource('test', loader);++ const failed = resource.load();+ await expect(failed).rejects.toBe(failure);+ expect(resource.load()).toBe(failed);+ expect(resource.getStatus()).toBe('failed');++ const retry = resource.retry();+ expect(resource.retry()).toBe(retry);+ await expect(retry).resolves.toBe(implementation);+ expect(loader).toHaveBeenCalledTimes(2);+ });++ it('rejects implementations without a view through the same failure state', async () => {+ const resource = createWidgetImplementationResource('test', () => Promise.resolve({} as WidgetImplementation));++ await expect(resource.load()).rejects.toThrow('must provide a view component');+ expect(resource.getStatus()).toBe('failed');+ });++ it('preloads without leaking a rejected promise', async () => {+ const loader = vi.fn().mockRejectedValue(new Error('offline'));+ const resource = createWidgetImplementationResource('test', loader);++ resource.preload();+ await vi.waitFor(() => expect(resource.getStatus()).toBe('failed'));+ expect(loader).toHaveBeenCalledOnce();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.ts b/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.tsnew file mode 100644index 0000000000..8ea36f7d1a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgetImplementationResource.ts@@ -0,0 +1,66 @@+import type {+ WidgetImplementation,+ WidgetImplementationLoadStatus,+ WidgetImplementationResource,+ WidgetTypeId,+} from './widgetContracts';++type ResourceState =+ | { status: 'idle' }+ | { promise: Promise<WidgetImplementation>; status: 'loading' }+ | { promise: Promise<WidgetImplementation>; status: 'loaded'; value: WidgetImplementation }+ | { error: unknown; promise: Promise<WidgetImplementation>; status: 'failed' };++const validateImplementation = (widgetId: WidgetTypeId, value: WidgetImplementation): WidgetImplementation => {+ if (!value || typeof value !== 'object' || typeof value.view !== 'function') {+ throw new TypeError(`Widget ${widgetId} implementation must provide a view component.`);+ }++ return value;+};++export const createWidgetImplementationResource = (+ widgetId: WidgetTypeId,+ loader: () => Promise<WidgetImplementation>+): WidgetImplementationResource => {+ let state: ResourceState = { status: 'idle' };++ const start = (): Promise<WidgetImplementation> => {+ const promise = Promise.resolve()+ .then(loader)+ .then((implementation) => validateImplementation(widgetId, implementation));+ state = { promise, status: 'loading' };+ void promise.then(+ (value) => {+ state = { promise, status: 'loaded', value };+ },+ (error: unknown) => {+ state = { error, promise, status: 'failed' };+ }+ );+ return promise;+ };++ const load = (): Promise<WidgetImplementation> => {+ if (state.status === 'loading' || state.status === 'loaded' || state.status === 'failed') {+ return state.promise;+ }++ return start();+ };++ return {+ getStatus: (): WidgetImplementationLoadStatus => state.status,+ load,+ preload: () => {+ void load().catch(() => undefined);+ },+ retry: () => {+ if (state.status === 'failed') {+ state = { status: 'idle' };+ }++ return load();+ },+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgetLabels.ts b/invokeai/frontend/webv2/src/workbench/widgetLabels.tsindex 8909154189..5f1a09b3e1 100644--- a/invokeai/frontend/webv2/src/workbench/widgetLabels.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetLabels.ts@@ -1,7 +1,6 @@+import type { WidgetManifest, WidgetTypeId } from '@workbench/widgetContracts';import type { TFunction } from 'i18next';-import type { WidgetManifest, WidgetTypeId } from './types';-type WidgetLabelSource = Pick<WidgetManifest, 'id' | 'label'>;export const resolveWidgetLabel = (manifest: WidgetLabelSource, t: TFunction): string =>diff --git a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.tsindex ebbfc547d2..3cf6827e61 100644--- a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts@@ -1,10 +1,15 @@+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { Project, WorkbenchState } from '@workbench/projectContracts';+import type { NormalizedWidgetManifest, RegisteredWidget } from '@workbench/widgetContracts';+import { describe, expect, it } from 'vitest';-import type { NormalizedWidgetManifest, Project, RegisteredWidget, WidgetRegion, WorkbenchState } from './types';-import type { WorkbenchAction } from './workbenchState';+import type { WorkbenchAction } from './workbenchState.testing';+import type { WorkbenchWidgetCommands } from './workbenchStore';+import { createWidgetImplementationResource } from './widgetImplementationResource';import { closeWidgetPlacement, openWidgetPlacement, revealWidgetPlacement } from './widgetPlacementCommands';-import { createInitialWorkbenchState, workbenchReducer } from './workbenchState';+import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';const TestIcon = () => null;const TestView = () => null;@@ -20,6 +25,7 @@ const getActiveProject = (state: WorkbenchState): Project => {const createWidget = (overrides: Partial<NormalizedWidgetManifest> & Pick<NormalizedWidgetManifest, 'id' | 'label'>): RegisteredWidget => ({+ implementation: createWidgetImplementationResource(overrides.id, () => Promise.resolve({ view: TestView })),manifest: {apiVersion: 1,allowMultiple: false,@@ -28,9 +34,9 @@ const createWidget = (centerPlacement: 'view',failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },icon: TestIcon,+ load: () => Promise.resolve({ view: TestView }),state: { createInitial: () => ({}), persistence: 'project', version: 1 },version: 1,- view: TestView,...overrides,},status: 'enabled',@@ -41,28 +47,38 @@ const createRegistry =(region: WidgetRegion): RegisteredWidget[] =>widgetsByRegion[region] ?? [];-const applyCommand = (- state: WorkbenchState,- command: (dispatch: (action: WorkbenchAction) => void) => void-): WorkbenchState => {+const applyCommand = (state: WorkbenchState, command: (widgets: WorkbenchWidgetCommands) => void): WorkbenchState => {let nextState = state;const dispatch = (action: WorkbenchAction): void => {nextState = workbenchReducer(nextState, action);};- command(dispatch);+ command(createWidgetCommands(dispatch));return nextState;};+const createWidgetCommands = (dispatch: (action: WorkbenchAction) => void): WorkbenchWidgetCommands => ({+ move: (options) => dispatch({ ...options, type: 'moveWidgetInstance' }),+ open: (options) => dispatch({ ...options, type: 'openRegionWidget' }),+ patchInstanceValues: (instanceId, values, projectId) =>+ dispatch({ instanceId, projectId, type: 'patchWidgetInstanceValues', values }),+ patchValues: (widgetId, values, projectId) => dispatch({ projectId, type: 'patchWidgetValues', values, widgetId }),+ reorder: (options) => dispatch({ ...options, type: 'reorderWidgetInstances' }),+ select: (options) => dispatch({ ...options, type: 'selectRegionWidget' }),+ setInstanceValues: (instanceId, values, projectId) =>+ dispatch({ instanceId, projectId, type: 'setWidgetInstanceValues', values }),+ toggle: (options) => dispatch({ ...options, type: 'toggleRegionWidget' }),+});+describe('widget placement commands', () => {it('opens a singleton already in the target region without duplicating it', () => {const state = createInitialWorkbenchState();const widget = createWidget({ id: 'queue', label: 'Queue' });- const nextState = applyCommand(state, (dispatch) => {+ const nextState = applyCommand(state, (widgets) => {expect(openWidgetPlacement({- dispatch,+ widgets,getWidgetsForRegion: createRegistry({ right: [widget] }),options: { preferredRegions: ['right'] },typeId: 'queue',@@ -73,14 +89,15 @@ describe('widget placement commands', () => {expect(rightRegion.instanceIds.filter((instanceId) => instanceId === 'queue')).toHaveLength(1);expect(rightRegion.activeInstanceId).toBe('queue');+ expect(widget.implementation.getStatus()).toBe('loading');});it('opens an existing singleton instance from another region', () => {const state = createInitialWorkbenchState();const widget = createWidget({ id: 'preview', label: 'Preview' });- const nextState = applyCommand(state, (dispatch) => {+ const nextState = applyCommand(state, (widgets) => {openWidgetPlacement({- dispatch,+ widgets,getWidgetsForRegion: createRegistry({ right: [widget] }),options: { preferredRegions: ['right'] },typeId: 'preview',@@ -94,10 +111,11 @@ describe('widget placement commands', () => {it('passes allowMultiple through as createNew', () => {const actions: WorkbenchAction[] = [];+ const widgets = createWidgetCommands((action) => actions.push(action));const widget = createWidget({ allowMultiple: true, id: 'queue', label: 'Queue' });openWidgetPlacement({- dispatch: (action) => actions.push(action),+ widgets,getWidgetsForRegion: createRegistry({ right: [widget] }),options: { createNew: true, preferredRegions: ['right'] },typeId: 'queue',@@ -108,10 +126,11 @@ describe('widget placement commands', () => {it('does not create a new instance for singleton widgets even when requested', () => {const actions: WorkbenchAction[] = [];+ const widgets = createWidgetCommands((action) => actions.push(action));const widget = createWidget({ allowMultiple: false, id: 'queue', label: 'Queue' });openWidgetPlacement({- dispatch: (action) => actions.push(action),+ widgets,getWidgetsForRegion: createRegistry({ right: [widget] }),options: { createNew: true, preferredRegions: ['right'] },typeId: 'queue',@@ -127,10 +146,11 @@ describe('widget placement commands', () => {const dispatch = (action: WorkbenchAction): void => {actions.push(action);};+ const widgets = createWidgetCommands(dispatch);expect(openWidgetPlacement({- dispatch,+ widgets,getWidgetsForRegion: createRegistry({left: [createWidget({ allowedRegions: ['center'], id: 'models', label: 'Models' })],}),@@ -140,7 +160,7 @@ describe('widget placement commands', () => {).toEqual({ ok: false, reason: 'unavailable' });expect(openWidgetPlacement({- dispatch,+ widgets,getWidgetsForRegion: createRegistry({bottom: [createWidget({ bottomPanel: 'tooltip', id: 'diagnostics', label: 'Diagnostics' })],}),@@ -150,7 +170,7 @@ describe('widget placement commands', () => {).toEqual({ ok: false, reason: 'unavailable' });expect(openWidgetPlacement({- dispatch,+ widgets,getWidgetsForRegion: createRegistry({center: [createWidget({ centerPlacement: 'toolbar', id: 'toolbar-tools', label: 'Toolbar Tools' })],}),@@ -163,11 +183,12 @@ describe('widget placement commands', () => {it('prevents removing the last center view', () => {const actions: WorkbenchAction[] = [];+ const widgets = createWidgetCommands((action) => actions.push(action));const project = getActiveProject(createInitialWorkbenchState());expect(closeWidgetPlacement({- dispatch: (action) => actions.push(action),+ widgets,getWidgetById: (typeId) => createWidget({ id: typeId, label: typeId }),instanceId: 'canvas',project: {@@ -200,9 +221,9 @@ describe('widget placement commands', () => {: candidate),};- const nextState = applyCommand(collapsedState, (dispatch) => {+ const nextState = applyCommand(collapsedState, (widgets) => {revealWidgetPlacement({- dispatch,+ widgets,instanceId: 'queue',project: getActiveProject(collapsedState),region: 'right',@@ -217,9 +238,9 @@ describe('widget placement commands', () => {it('closes a placement and preserves reducer fallback active item behavior', () => {const state = createInitialWorkbenchState();- const nextState = applyCommand(state, (dispatch) => {+ const nextState = applyCommand(state, (widgets) => {closeWidgetPlacement({- dispatch,+ widgets,getWidgetById: (typeId) => createWidget({ id: typeId, label: typeId }),instanceId: 'layers',project: getActiveProject(state),diff --git a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.ts b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.tsindex 5e0f2d345b..3efae431c6 100644--- a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.ts@@ -1,19 +1,17 @@-import type { Dispatch } from 'react';-+import type { WidgetRegion, WidgetRegionState } from '@workbench/layoutContracts';import type {OpenWorkbenchWidgetOptions,RegisteredWidget,WidgetInstanceId,- WidgetRegion,- WidgetRegionState,WidgetTypeId,WidgetWorkbenchApiResult,-} from './types';+} from '@workbench/widgetContracts';++import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';+import type { WidgetDragEndResolution } from './widgetDnd';import type { WidgetPlacementMeta } from './widgetRegionViewModel';-import type { WorkbenchAction } from './workbenchState';--import { flushWorkbenchDrafts } from './widgets/draftRegistry';+import type { WorkbenchWidgetCommands } from './workbenchStore';export interface WidgetPlacementProject {projectId?: string;@@ -26,7 +24,7 @@ const DEFAULT_OPEN_REGIONS: ReadonlyArray<WidgetRegion> = ['center', 'right', 'lexport type WidgetPlacementCommandResult = WidgetWorkbenchApiResult;export const canRenderWidgetInRegion = (widget: RegisteredWidget, region: WidgetRegion): boolean => {- if (widget.status !== 'enabled' || !widget.manifest.view || !widget.manifest.allowedRegions.includes(region)) {+ if (widget.status !== 'enabled' || !widget.manifest.allowedRegions.includes(region)) {return false;}@@ -63,6 +61,7 @@ export const getOpenableWidgetPlacement = ({const widget = getWidgetsForRegion(region).find((candidate) => candidate.manifest.id === typeId);if (widget && canRenderWidgetInRegion(widget, region)) {+ widget.implementation.preload();return { region, widget };}}@@ -71,16 +70,16 @@ export const getOpenableWidgetPlacement = ({};export const openWidgetPlacement = ({- dispatch,getWidgetsForRegion,options,projectId,typeId,+ widgets,}: {- dispatch: Dispatch<WorkbenchAction>;getWidgetsForRegion: (region: WidgetRegion) => RegisteredWidget[];projectId?: string;typeId: WidgetTypeId;+ widgets: WorkbenchWidgetCommands;options?: OpenWorkbenchWidgetOptions;}): WidgetPlacementCommandResult => {const target = getOpenableWidgetPlacement({ getWidgetsForRegion, options, typeId });@@ -89,12 +88,11 @@ export const openWidgetPlacement = ({return { ok: false, reason: 'unavailable' };}- dispatch({+ widgets.open({createNew: target.widget.manifest.allowMultiple ? options?.createNew : undefined,initialValues: target.widget.manifest.state?.createInitial(),projectId,region: target.region,- type: 'openRegionWidget',widgetId: typeId,});@@ -113,17 +111,17 @@ const getEnabledCenterViewCount = (}).length;export const closeWidgetPlacement = ({- dispatch,getWidgetById,instanceId,project,region,+ widgets,}: {- dispatch: Dispatch<WorkbenchAction>;getWidgetById: (typeId: WidgetTypeId) => RegisteredWidget | undefined;project: WidgetPlacementProject;region: WidgetRegion;instanceId: WidgetInstanceId;+ widgets: WorkbenchWidgetCommands;}): WidgetPlacementCommandResult => {if (!project.widgetInstances[instanceId]) {return { ok: false, reason: 'not-found' };@@ -144,21 +142,21 @@ export const closeWidgetPlacement = ({}flushWorkbenchDrafts();- dispatch({ projectId: project.projectId, region, type: 'toggleRegionWidget', widgetId: instanceId });+ widgets.toggle({ projectId: project.projectId, region, widgetId: instanceId });return { ok: true, region };};export const revealWidgetPlacement = ({- dispatch,instanceId,project,region,+ widgets,}: {- dispatch: Dispatch<WorkbenchAction>;project: WidgetPlacementProject;region: WidgetRegion;instanceId: WidgetInstanceId;+ widgets: WorkbenchWidgetCommands;}): WidgetPlacementCommandResult => {if (!project.widgetInstances[instanceId]) {return { ok: false, reason: 'not-found' };@@ -168,35 +166,33 @@ export const revealWidgetPlacement = ({return { ok: false, reason: 'unsupported' };}- dispatch({ projectId: project.projectId, region, type: 'selectRegionWidget', widgetId: instanceId });+ widgets.select({ projectId: project.projectId, region, widgetId: instanceId });return { ok: true, region };};export const dispatchWidgetDragEndPlacement = ({- dispatch,resolution,+ widgets,}: {- dispatch: Dispatch<WorkbenchAction>;resolution: WidgetDragEndResolution;+ widgets: WorkbenchWidgetCommands;}): WidgetPlacementCommandResult => {if (resolution.type === 'reorder') {- dispatch({+ widgets.reorder({activeInstanceId: resolution.activeInstanceId,instanceIds: resolution.instanceIds,region: resolution.region,- type: 'reorderWidgetInstances',});return { ok: true, region: resolution.region };}- dispatch({+ widgets.move({fromRegion: resolution.fromRegion,instanceId: resolution.instanceId,toIndex: resolution.toIndex,toRegion: resolution.toRegion,- type: 'moveWidgetInstance',});return { ok: true, region: resolution.toRegion };diff --git a/invokeai/frontend/webv2/src/workbench/widgetPlacementMeta.ts b/invokeai/frontend/webv2/src/workbench/widgetPlacementMeta.tsindex 0bda7b4666..451772e25f 100644--- a/invokeai/frontend/webv2/src/workbench/widgetPlacementMeta.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetPlacementMeta.ts@@ -1,4 +1,7 @@-import type { Project, WidgetInstanceId, WidgetRegion, WidgetRegionState } from './types';+import type { WidgetRegion, WidgetRegionState } from '@workbench/layoutContracts';+import type { Project } from '@workbench/projectContracts';+import type { WidgetInstanceId } from '@workbench/widgetContracts';+import type { WidgetPlacementProject } from './widgetPlacementCommands';import type { WidgetPlacementMeta } from './widgetRegionViewModel';diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.test.ts b/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.test.tsindex dedec0f91f..85664be8ba 100644--- a/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.test.ts@@ -1,7 +1,13 @@-import { describe, expect, it, vi } from 'vitest';+import type {+ NormalizedWidgetManifest,+ RegisteredWidget,+ WidgetInstanceContract,+ WidgetTypeId,+} from '@workbench/widgetContracts';-import type { NormalizedWidgetManifest, RegisteredWidget, WidgetInstanceContract, WidgetTypeId } from './types';+import { describe, expect, it, vi } from 'vitest';+import { createWidgetImplementationResource } from './widgetImplementationResource';import {canRemoveItem,createWidgetRegionViewModel,@@ -15,15 +21,16 @@ const TestView = () => null;const createWidget = (overrides: Partial<NormalizedWidgetManifest> & Pick<NormalizedWidgetManifest, 'id' | 'label'>): RegisteredWidget => ({+ implementation: createWidgetImplementationResource(overrides.id, () => Promise.resolve({ view: TestView })),manifest: {apiVersion: 1,allowMultiple: false,allowedRegions: ['left', 'center', 'bottom'],failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },icon: TestIcon,+ load: () => Promise.resolve({ view: TestView }),state: { createInitial: () => ({}), persistence: 'project', version: 1 },version: 1,- view: TestView,...overrides,},status: 'enabled',diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.ts b/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.tsindex 08886fcb2f..2ea771ed4b 100644--- a/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.ts@@ -1,13 +1,12 @@+import type { WidgetRegion, WidgetRegionState } from '@workbench/layoutContracts';import type {NormalizedWidgetManifest,RegisteredWidget,WidgetIconComponent,WidgetInstanceContract,WidgetInstanceId,- WidgetRegion,- WidgetRegionState,WidgetTypeId,-} from './types';+} from '@workbench/widgetContracts';export interface WidgetPlacementInstanceMeta {id: WidgetInstanceId;diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.ts b/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.tsindex d925b8c4e9..01fb25f803 100644--- a/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.ts@@ -1,13 +1,14 @@-import { ImageUpscaleIcon } from 'lucide-react';-import { describe, expect, it } from 'vitest';+import type { WidgetManifest } from '@workbench/widgetContracts';-import type { WidgetManifest } from './types';+import { ImageUpscaleIcon } from 'lucide-react';+import { describe, expect, it, vi } from 'vitest';+import { upscaleWidgetManifest } from './upscaleWidgetManifest';import { getWidgetHosts, registerFirstPartyWidgets, registerWidgets } from './widgetRegistry';-import { upscaleWidgetManifest } from './widgets/upscale';const TestIcon = () => null;const TestView = () => null;+const load = () => Promise.resolve({ view: TestView });const createManifest = (overrides: Partial<WidgetManifest> = {}): WidgetManifest => ({allowMultiple: false,@@ -16,8 +17,8 @@ const createManifest = (overrides: Partial<WidgetManifest> = {}): WidgetManifesticon: TestIcon,id: 'vendor.widget',label: 'Test Widget',+ load,version: 1,- view: TestView,...overrides,});@@ -35,12 +36,14 @@ describe('widget registry', () => {});it('normalizes default state and api version', () => {- const [widget] = registerWidgets([createManifest({ state: undefined })]);+ const loader = vi.fn(load);+ const [widget] = registerWidgets([createManifest({ load: loader, state: undefined })]);expect(widget.status).toBe('enabled');expect(widget.manifest.apiVersion).toBe(1);expect(widget.manifest.state).toMatchObject({ persistence: 'project', version: 1 });expect(widget.manifest.state.createInitial()).toEqual({});+ expect(loader).not.toHaveBeenCalled();});it('exposes enabled widget singleton hosts', () => {@@ -61,18 +64,26 @@ describe('widget registry', () => {expect(widget.failure?.message).toContain('must declare at least one allowed region');});- it('fails closed for renderable regions without a view', () => {- const [widget] = registerWidgets([createManifest({ view: undefined })]);+ it('validates descriptors without loading their implementation', () => {+ const loader = vi.fn(load);+ const [widget] = registerWidgets([createManifest({ load: loader })]);++ expect(widget.status).toBe('enabled');+ expect(loader).not.toHaveBeenCalled();+ });++ it('fails closed without a deferred implementation loader', () => {+ const [widget] = registerWidgets([createManifest({ load: undefined as unknown as WidgetManifest['load'] })]);expect(widget.status).toBe('disabled');- expect(widget.failure?.message).toContain('does not include manifest.view');+ expect(widget.failure?.message).toContain('must provide a deferred implementation loader');});it('honors hidden failure policy for invalid manifests', () => {const [widget] = registerWidgets([createManifest({failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'hide' },- view: undefined,+ load: undefined as unknown as WidgetManifest['load'],}),]);diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts b/invokeai/frontend/webv2/src/workbench/widgetRegistry.tsindex e1a6601b9c..62cce5eac3 100644--- a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts@@ -1,27 +1,29 @@+import type { WidgetRegion } from '@workbench/layoutContracts';import type {NormalizedWidgetManifest,RegisteredWidget,WidgetFailure,WidgetManifest,- WidgetRegion,WidgetTypeId,-} from './types';+} from '@workbench/widgetContracts';-import { getAuthSession } from './auth/session';+import { getAuthSession } from '@features/identity';+import { queueWidgetManifest } from '@workbench/queueWidgetManifest';++import { galleryWidgetManifest } from './galleryWidgetManifest';+import { generateWidgetManifest } from './generationWidgetManifest';+import { upscaleWidgetManifest } from './upscaleWidgetManifest';+import { createWidgetImplementationResource } from './widgetImplementationResource';import { autosaveStatusWidgetManifest } from './widgets/autosave-status';import { canvasWidgetManifest } from './widgets/canvas';import { diagnosticsWidgetManifest } from './widgets/diagnostics';-import { galleryWidgetManifest } from './widgets/gallery';-import { generateWidgetManifest } from './widgets/generate';import { layersWidgetManifest } from './widgets/layers';import { notificationsWidgetManifest } from './widgets/notifications';import { previewWidgetManifest } from './widgets/preview';import { projectWidgetManifest } from './widgets/project';-import { queueWidgetManifest } from './widgets/queue';import { serverStatusWidgetManifest } from './widgets/server-status';-import { upscaleWidgetManifest } from './widgets/upscale';import { versionStatusWidgetManifest } from './widgets/version-status';-import { workflowWidgetManifest } from './widgets/workflow';+import { workflowWidgetManifest } from './workflowWidgetManifest';export const firstPartyWidgetManifests: WidgetManifest[] = [generateWidgetManifest,@@ -75,8 +77,8 @@ const validateManifest = (manifest: NormalizedWidgetManifest): void => {throw new TypeError(`Widget ${manifest.id} must provide an icon component.`);}- if (manifest.allowedRegions.some((region) => renderableRegions.has(region)) && !manifest.view) {- throw new Error(`Widget ${manifest.id} declares a renderable region but does not include manifest.view.`);+ if (typeof manifest.load !== 'function') {+ throw new TypeError(`Widget ${manifest.id} must provide a deferred implementation loader.`);}};@@ -93,12 +95,21 @@ export const registerWidgets = (manifests: WidgetManifest[]): RegisteredWidget[]try {validateManifest(manifest);- return { manifest, status: 'enabled' as const };+ return {+ implementation: createWidgetImplementationResource(manifest.id, manifest.load),+ manifest,+ status: 'enabled' as const,+ };} catch (error) {const failure = createFailure(manifest.id, error);const status = manifest.failurePolicy.onRegistrationFailure === 'hide' ? 'hidden' : 'disabled';- return { failure, manifest, status };+ return {+ failure,+ implementation: createWidgetImplementationResource(manifest.id, manifest.load),+ manifest,+ status,+ };}});@@ -130,12 +141,21 @@ export const getWidgetsForRegion = (region: WidgetRegion): RegisteredWidget[] =>export const getWidgetHosts = (): RegisteredWidget[] =>registeredWidgets.filter(- (widget) => widget.status === 'enabled' && widget.manifest.host && isWidgetAvailable(widget)+ (widget) => widget.status === 'enabled' && widget.manifest.hasHost && isWidgetAvailable(widget));export const getWidgetById = (widgetId: WidgetTypeId): RegisteredWidget | undefined =>registeredWidgets.find((widget) => widget.manifest.id === widgetId);+/** Starts a cached implementation load for an explicit user intent. */+export const preloadWidget = (widgetId: WidgetTypeId): void => {+ const widget = getWidgetById(widgetId);++ if (widget?.status === 'enabled') {+ widget.implementation.preload();+ }+};+export const widgetRegistrationFailures = registeredWidgets.flatMap((widget) =>widget.failure ? [widget.failure] : []);diff --git a/invokeai/frontend/webv2/src/workbench/widgetState.ts b/invokeai/frontend/webv2/src/workbench/widgetState.tsindex 63c14a7ef6..d2474fe83e 100644--- a/invokeai/frontend/webv2/src/workbench/widgetState.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetState.ts@@ -1,4 +1,5 @@-import type { Project, WidgetInstanceContract, WidgetStateContract, WidgetTypeId } from './types';+import type { Project } from '@workbench/projectContracts';+import type { WidgetInstanceContract, WidgetStateContract, WidgetTypeId } from '@workbench/widgetContracts';const emptyWidgetState = (widgetId: WidgetTypeId): WidgetStateContract => ({id: widgetId,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/AutosaveStatusWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/AutosaveStatusWidgetView.tsxindex 0fe18d913b..50cf2d6ebf 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/AutosaveStatusWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/AutosaveStatusWidgetView.tsx@@ -1,4 +1,4 @@-import type { WidgetViewProps } from '@workbench/types';+import type { WidgetViewProps } from '@workbench/widgetContracts';import { Stack, Text } from '@chakra-ui/react';import { StatusWidgetChip } from '@workbench/widget-frame';@@ -8,7 +8,7 @@ import { useTranslation } from 'react-i18next';export const AutosaveStatusWidgetView = ({ presentation }: WidgetViewProps) => {const { t } = useTranslation();- const autosave = useWorkbenchSelector((snapshot) => snapshot.state.autosave);+ const autosave = useWorkbenchSelector((snapshot) => snapshot.autosave);const icon = autosave.status === 'error' ? CloudAlertIcon : CloudCheckIcon;const label = autosave.status === 'saved' ? t('common.saved') : autosave.status;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/implementation.tsnew file mode 100644index 0000000000..801e337290--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/implementation.ts@@ -0,0 +1,5 @@+import type { WidgetImplementation } from '@workbench/widgetContracts';++import { AutosaveStatusWidgetView } from './AutosaveStatusWidgetView';++export const widgetImplementation = { view: AutosaveStatusWidgetView } satisfies WidgetImplementation;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/index.tsindex 5c6bdea35e..dd9c94964c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/index.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/index.ts@@ -1,9 +1,7 @@-import type { WidgetManifest } from '@workbench/types';+import type { WidgetManifest } from '@workbench/widgetContracts';import { CloudCheckIcon } from 'lucide-react';-import { AutosaveStatusWidgetView } from './AutosaveStatusWidgetView';-export const autosaveStatusWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['bottom'],@@ -12,6 +10,6 @@ export const autosaveStatusWidgetManifest: WidgetManifest = {icon: CloudCheckIcon,id: 'autosave-status',label: (t) => t('widgets.labels.autosaveStatus'),+ load: () => import('./implementation').then((module) => module.widgetImplementation),version: 1,- view: AutosaveStatusWidgetView,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasBottomControls.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasBottomControls.tsxindex 686daa0701..2ce6f06366 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasBottomControls.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasBottomControls.tsx@@ -1,5 +1,5 @@/* oxlint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop */-import type { CanvasOperationState } from '@workbench/canvas-operations/operationController';+import type { CanvasOperationState } from '@workbench/canvas-operations/api';import type { ReactNode } from 'react';import { Box } from '@chakra-ui/react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFloatingBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFloatingBar.tsxindex e14c986857..5bdc95dd65 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFloatingBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFloatingBar.tsx@@ -1,7 +1,7 @@-import type { PanelProps } from '@workbench/components/ui';+import type { PanelProps } from '@platform/ui';import { Box } from '@chakra-ui/react';-import { Panel } from '@workbench/components/ui';+import { Panel } from '@platform/ui';/*** Shared floating-panel chrome for the canvas: the raised, rounded, shadoweddiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasGlobalContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasGlobalContextMenu.tsxindex 52ef142c29..8928fd0e9a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasGlobalContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasGlobalContextMenu.tsx@@ -1,7 +1,7 @@import type { ReactNode } from 'react';import { Menu, Portal } from '@chakra-ui/react';-import { MenuContent } from '@workbench/components/ui';+import { MenuContent } from '@platform/ui';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsxindex 10a7108f7a..13e9f4c92d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx@@ -1,15 +1,16 @@-import type { Rect } from '@workbench/canvas-engine/types';-import type { Project, WidgetViewProps } from '@workbench/types';+import type { Rect } from '@workbench/canvas-engine/api';+import type { Project } from '@workbench/projectContracts';+import type { WidgetViewProps } from '@workbench/widgetContracts';/* oxlint-disable react-perf/jsx-no-new-function-as-prop */import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import { Box, HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';+import { useModifierHeld } from '@platform/react/useModifierHeld';+import { ConfirmDialog, IconButton, MenuContent, Tooltip } from '@platform/ui';import { createNewCanvasStateV2 } from '@workbench/canvasMigration';-import { ConfirmDialog, IconButton, MenuContent, Tooltip } from '@workbench/components/ui';import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';-import { useModifierHeld } from '@workbench/useModifierHeld';import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import {BugIcon,CheckIcon,@@ -42,7 +43,7 @@ import { computeFitBboxToLayers, computeFitBboxToMasks } from './fitBbox';import { useCanvasEngine } from './useCanvasEngine';import { formatZoomPercent, zoomMenuOptions } from './zoomOptions';-type CanvasHeaderEngine = Pick<CanvasEngineHandle, 'diagnostics' | 'history' | 'layers' | 'stores' | 'viewport'>;+type CanvasHeaderEngine = Pick<CanvasEngineHandle, 'diagnostics' | 'history' | 'interaction' | 'layers' | 'viewport'>;const ZOOM_OPTIONS = zoomMenuOptions();const MENU_POSITIONING = { placement: 'bottom-end' } as const;@@ -304,17 +305,13 @@ const HeaderDivider = () => <Box bg="border.subtle" flexShrink={0} h="4" mx="1"*/const CanvasSettingsMenu = ({ editingLocked, engine }: { editingLocked: boolean; engine: CanvasHeaderEngine }) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();+ const { widgets } = useWorkbenchCommands();const settings = useActiveProjectSelector(selectCanvasSettings, canvasSettingsEqual);// Shift reveals the Debug section, matching legacy `useShiftModifier` (event-driven).const shiftHeld = useModifierHeld('Shift');const toggle = (setting: CanvasBooleanSetting) => {- dispatch({- type: 'patchWidgetValues',- values: { [setting.key]: !settings[setting.key] },- widgetId: 'canvas',- });+ widgets.patchValues('canvas', { [setting.key]: !settings[setting.key] });};return (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropOverlay.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropOverlay.tsxindex d51caba9b4..3b60d11d19 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropOverlay.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropOverlay.tsx@@ -1,6 +1,6 @@import { Grid } from '@chakra-ui/react';import { useDndContext } from '@dnd-kit/core';-import { isGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';+import { isGalleryImageDragData } from '@features/gallery/utility';import { getCanvasImageDropData, getCanvasImageDropId } from './canvasImageDnd';import { CanvasImageDropZone, type CanvasImageDropZoneProps } from './CanvasImageDropZone';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSaveToGallerySubmenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSaveToGallerySubmenu.tsxindex 6b21996119..f91a5e32de 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSaveToGallerySubmenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSaveToGallerySubmenu.tsx@@ -1,7 +1,7 @@-import type { CanvasGallerySaveRegion } from '@workbench/canvas-operations/saveCanvasToGallery';+import type { CanvasGallerySaveRegion } from '@workbench/canvas-operations/api';import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';-import { MenuContent } from '@workbench/components/ui';+import { MenuContent } from '@platform/ui';import { ChevronRightIcon, SaveIcon } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsxindex 9fa5cf971d..1e5cc11b54 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx@@ -1,7 +1,7 @@+import type { CanvasStateContractV2 } from '@workbench/canvas-engine/contracts';import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';import type { EngineDeps, EngineRegistry } from '@workbench/canvas-operations/engineRegistry';import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';-import type { CanvasStateContractV2 } from '@workbench/types';import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsxindex ecbedc752e..473c7004dd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx@@ -7,7 +7,10 @@ import { shouldFocusCanvasSurface } from '@workbench/widgets/canvas/surfaceFocusimport { TextEditPortal } from '@workbench/widgets/canvas/TextEditPortal';import { useRef } from 'react';-export type CanvasSurfaceEngine = Pick<CanvasEngineHandle, 'document' | 'layers' | 'stores' | 'surface' | 'viewport'>;+export type CanvasSurfaceEngine = Pick<+ CanvasEngineHandle,+ 'document' | 'interaction' | 'layers' | 'surface' | 'viewport'+>;/*** Give the canvas widget hotkey focus on a pointerdown on the surface, so tooldiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsxindex 026f3d4c77..0404831c47 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx@@ -1,5 +1,7 @@+import type { CanvasStagingCandidateContract } from '@workbench/canvas-engine/contracts';import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';-import type { CanvasStagingCandidateContract, Project, WidgetViewProps } from '@workbench/types';+import type { Project } from '@workbench/projectContracts';+import type { WidgetViewProps } from '@workbench/widgetContracts';import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';@@ -14,16 +16,21 @@ const harness = vi.hoisted(() => ({ engine: null as CanvasEngine | null, projectvi.mock('@dnd-kit/core', () => ({ useDndMonitor: () => undefined }));vi.mock('@workbench/WorkbenchContext', () => ({useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(harness.project!),- useWorkbenchDispatch: () => () => undefined,- useWorkbenchStore: () => ({+ useWorkbenchCommands: () => ({+ canvas: { apply: vi.fn() },+ notifications: { add: vi.fn(), reportError: vi.fn() },+ queue: { cancel: vi.fn() },+ }),+ useWorkbenchQueries: () => ({+ getProject: (projectId: string) => (harness.project?.id === projectId ? harness.project : null),getSnapshot: () => ({ activeProject: harness.project }),- getState: () => ({ projects: harness.project ? [harness.project] : [] }),+ isActiveProject: (projectId: string) => harness.project?.id === projectId,}),}));vi.mock('@workbench/useCanvasProjectMutationDispatch', () => ({useCanvasProjectMutationDispatch: () => () => undefined,}));-vi.mock('@workbench/backend/progressImageStore', () => ({ useQueueItemProgressImage: () => null }));+vi.mock('@features/queue', () => ({ useQueueItemProgressImage: () => null }));vi.mock('./engineStoreHooks', () => ({ useCanvasOperation: () => null }));vi.mock('./useCanvasEngine', () => ({ useCanvasEngine: () => harness.engine }));vi.mock('./useCanvasGallerySave', () => ({@@ -81,7 +88,7 @@ describe('CanvasWidgetView staged acceptance eligibility', () => {it('drives the rendered Chakra Accept button disabled state from interaction capabilities', () => {const store = createWorkbenchStore();const projectId = store.getState().activeProjectId;- store.dispatch({ candidate, projectId, type: 'appendCanvasStagingCandidate' });+ store.commands.canvas.appendStagingCandidate({ candidate, projectId });harness.project = store.getState().projects[0]!;harness.engine = null;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex 2e828a4487..62019dccd3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -1,11 +1,10 @@-/* oxlint-disable react-perf/jsx-no-new-function-as-prop */-import type { WidgetViewProps } from '@workbench/types';+import type { WidgetViewProps } from '@workbench/widgetContracts';import type { MouseEvent as ReactMouseEvent } from 'react';import { Box } from '@chakra-ui/react';import { useDndMonitor, type DragEndEvent } from '@dnd-kit/core';-import { useQueueItemProgressImage } from '@workbench/backend/progressImageStore';-import { getCanvasImportNotice } from '@workbench/canvas-operations/canvasImportNotice';+import { useQueueItemProgressImage } from '@features/queue/react';+import { getCanvasImportNotice } from '@workbench/canvas-operations/api';import {createLayerId,deleteLayerActions,@@ -21,7 +20,7 @@ import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutimport { CanvasLayerContextMenu } from '@workbench/widgets/layers/LayerContextMenu';import { canMergeLayerDown } from '@workbench/widgets/layers/layerOps';import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchStore } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';import { useCallback, useEffect, useEffectEvent, useLayoutEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -85,9 +84,9 @@ const REORDER_KINDS: Record<string, LayerReorderKind> = {*/export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();+ const { canvas: canvasCommands, notifications, queue } = useWorkbenchCommands();const canvasDispatch = useCanvasProjectMutationDispatch();- const store = useWorkbenchStore();+ const queries = useWorkbenchQueries();const engine = useCanvasEngine();const canvas = useActiveProjectSelector((project) => project.canvas);const queueItems = useActiveProjectSelector((project) => project.queue.items);@@ -101,29 +100,6 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {// pointer. Locked interaction skips the hit-test but keeps global save visible.const [contextMenuTarget, setContextMenuTarget] = useState<CanvasContextMenuTarget | null>(null);const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);- const handleSurfaceContextMenu = (event: ReactMouseEvent<HTMLDivElement>) => {- // Keep the native menu inside inline editors (the text tool's contenteditable- // overlay), consistent with the surface-focus INLINE_EDIT_SELECTOR.- const rect = event.currentTarget.getBoundingClientRect();- const resolution = resolveCanvasContextMenu({- clientX: event.clientX,- clientY: event.clientY,- hitTest: engine ? (point) => engine.tools.contextMenuLayerIdAt(point) : undefined,- isInlineEditor: event.target instanceof Element && !!event.target.closest(INLINE_EDIT_SELECTOR),- isInteractionLocked,- surfaceLeft: rect.left,- surfaceTop: rect.top,- });- if (!resolution.preventDefault) {- return;- }- event.preventDefault();- if (resolution.target?.layerId) {- canvasDispatch({ id: resolution.target.layerId, type: 'setCanvasSelectedLayer' });- }- setContextMenuTarget(resolution.target);- };-// The bbox tool snaps to a model-dependent grid; the engine is model-agnostic,// so read the active generate model's base and feed the grid size in.const modelBase = useActiveProjectSelector((project) => {@@ -150,7 +126,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {// Only engine-backed settings feed a store; React-consumed ones (e.g.// showProgressOnCanvas, read below) have no store and are skipped here.if (setting.store) {- engine.stores[setting.store].set(settings[setting.key]);+ engine.interaction.set(setting.store, settings[setting.key]);}}}, [engine, settings]);@@ -163,7 +139,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {// passive effect in the same commit, so getComputedStyle reads the new theme.const themeId = useWorkbenchSettingsSelector((snapshot) => snapshot.preferences.themeId);useEffect(() => {- engine?.stores.checkerColors.set(resolveCheckerColors());+ engine?.interaction.set('checkerColors', resolveCheckerColors());}, [engine, themeId]);const stagingSlots = getCanvasStagingSlots(canvas, queueItems);@@ -190,6 +166,31 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {operationKind: operation?.status === 'active' ? operation.identity.kind : null,});const isInteractionLocked = interactionCapabilities.isSurfaceInteractionLocked;+ const handleSurfaceContextMenu = useCallback(+ (event: ReactMouseEvent<HTMLDivElement>) => {+ // Keep the native menu inside inline editors (the text tool's contenteditable+ // overlay), consistent with the surface-focus INLINE_EDIT_SELECTOR.+ const rect = event.currentTarget.getBoundingClientRect();+ const resolution = resolveCanvasContextMenu({+ clientX: event.clientX,+ clientY: event.clientY,+ hitTest: engine ? (point) => engine.tools.contextMenuLayerIdAt(point) : undefined,+ isInlineEditor: event.target instanceof Element && !!event.target.closest(INLINE_EDIT_SELECTOR),+ isInteractionLocked,+ surfaceLeft: rect.left,+ surfaceTop: rect.top,+ });+ if (!resolution.preventDefault) {+ return;+ }+ event.preventDefault();+ if (resolution.target?.layerId) {+ canvasDispatch({ id: resolution.target.layerId, type: 'setCanvasSelectedLayer' });+ }+ setContextMenuTarget(resolution.target);+ },+ [canvasDispatch, engine, isInteractionLocked]+ );const handleCanvasImageDrop = useCallback((event: DragEndEvent) => {@@ -200,26 +201,26 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {// Capture the destination project and mounted engine before any network// work so a project switch cannot retarget this import mid-flight.- const project = store.getSnapshot().activeProject;+ const project = queries.getSnapshot().activeProject;const mountedEngine = engine;const execute = async (): Promise<void> => {try {const result = await executeCanvasImageDropImport({destination: resolution.destination,- dispatch,+ canvas: canvasCommands,engine: mountedEngine,- getState: store.getState,+ queries,imageNames: resolution.imageNames,project,});const notice = getCanvasImportNotice(result);- dispatch({ kind: notice.kind, title: t(notice.titleKey, notice.options ?? {}), type: 'recordNotice' });+ notifications.add({ kind: notice.kind, title: t(notice.titleKey, notice.options ?? {}) });} catch (error: unknown) {recordCanvasImportError({- dispatch,error,localizedMessage: t('widgets.canvas.import.failed'),+ notifications,projectId: project.id,});}@@ -227,7 +228,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {void execute();},- [dispatch, engine, store, t]+ [canvasCommands, engine, notifications, queries, t]);useDndMonitor({ onDragEnd: handleCanvasImageDrop });@@ -237,6 +238,44 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {return () => engine?.tools.setInteractionLocked(false);}, [engine, isInteractionLocked]);+ const acceptStagedImage = useEffectEvent(() => {+ if (selectedSlot?.kind === 'candidate') {+ engine?.layers.commitStagedImage({+ candidate: selectedSlot.candidate,+ selectedImageIndex: stagingArea.selectedImageIndex,+ });+ }+ });+ const cancelQueueItem = useCallback((queueItemId: string) => queue.cancel(undefined, queueItemId), [queue]);+ const cycleStagedImage = useCallback(+ (direction: -1 | 1) => canvasDispatch({ direction, type: 'cycleStagedImage' }),+ [canvasDispatch]+ );+ const discardAllStagedImages = useCallback(+ () => canvasDispatch({ type: 'discardAllStagedImages' }),+ [canvasDispatch]+ );+ const discardSelectedStagedImage = useCallback(+ () => canvasDispatch({ type: 'discardSelectedStagedImage' }),+ [canvasDispatch]+ );+ const selectStagedImage = useCallback(+ (imageIndex: number) => canvasDispatch({ imageIndex, type: 'setStagedImageIndex' }),+ [canvasDispatch]+ );+ const setStagingAutoSwitch = useCallback(+ (mode: 'off' | 'latest' | 'progress') => canvasDispatch({ mode, type: 'setCanvasStagingAutoSwitch' }),+ [canvasDispatch]+ );+ const toggleStagingThumbnails = useCallback(+ () => canvasDispatch({ type: 'toggleCanvasStagingThumbnailsVisibility' }),+ [canvasDispatch]+ );+ const toggleStagingVisibility = useCallback(+ () => canvasDispatch({ type: 'toggleCanvasStagingVisibility' }),+ [canvasDispatch]+ );+// "Show progress on canvas" gates ONLY the selected placeholder's live denoise// frame; a selected finished candidate still previews (that's staging, not progress).const selectedPlaceholderProgressImage = useQueueItemProgressImage(@@ -514,22 +553,15 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {selectedImageIndex={stagingArea.selectedImageIndex}selectedSlot={selectedSlot}slots={stagingSlots}- onAccept={() => {- if (selectedSlot?.kind === 'candidate') {- engine?.layers.commitStagedImage({- candidate: selectedSlot.candidate,- selectedImageIndex: stagingArea.selectedImageIndex,- });- }- }}- onCancelQueueItem={(queueItemId) => dispatch({ queueItemId, type: 'cancelQueueItem' })}- onCycle={(direction) => canvasDispatch({ direction, type: 'cycleStagedImage' })}- onDiscardAll={() => canvasDispatch({ type: 'discardAllStagedImages' })}- onDiscardSelected={() => canvasDispatch({ type: 'discardSelectedStagedImage' })}- onSelectImage={(imageIndex) => canvasDispatch({ imageIndex, type: 'setStagedImageIndex' })}- onSetAutoSwitch={(mode) => canvasDispatch({ mode, type: 'setCanvasStagingAutoSwitch' })}- onToggleThumbnails={() => canvasDispatch({ type: 'toggleCanvasStagingThumbnailsVisibility' })}- onToggleVisibility={() => canvasDispatch({ type: 'toggleCanvasStagingVisibility' })}+ onAccept={acceptStagedImage}+ onCancelQueueItem={cancelQueueItem}+ onCycle={cycleStagedImage}+ onDiscardAll={discardAllStagedImages}+ onDiscardSelected={discardSelectedStagedImage}+ onSelectImage={selectStagedImage}+ onSetAutoSwitch={setStagingAutoSwitch}+ onToggleThumbnails={toggleStagingThumbnails}+ onToggleVisibility={toggleStagingVisibility}/></CanvasBottomOverlay.Staging>) : null}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateCanvasCompositingSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsxsimilarity index 90%rename from invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateCanvasCompositingSection.tsxrename to invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsxindex fa78578e0c..e2ceff3e87 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateCanvasCompositingSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsx@@ -15,7 +15,8 @@ import type { NumberInput as ChakraNumberInput, SelectValueChangeDetails } fromimport type { CanvasCoherenceMode, CanvasInfillMethod } from '@workbench/widgets/canvas/invoke/canvasCompositing';import { createListCollection, NumberInput, Stack } from '@chakra-ui/react';-import { Field, Select } from '@workbench/components/ui';+import { GenerationSettingsSection } from '@features/generation/settings-ui';+import { Field, Select } from '@platform/ui';import {CANVAS_COHERENCE_EDGE_SIZE_MAX,CANVAS_COMPOSITING_KEYS,@@ -23,39 +24,29 @@ import {readCanvasCompositingSettings,} from '@workbench/widgets/canvas/invoke/canvasCompositing';import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';-const INFILL_METHODS: readonly CanvasInfillMethod[] = ['patchmatch', 'lama', 'cv2', 'color', 'tile'];const COHERENCE_MODES: readonly CanvasCoherenceMode[] = ['Gaussian Blur', 'Box Blur', 'Staged'];const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: false } as const;-export const GenerateCanvasCompositingSection = () => {- const sourceId = useActiveProjectSelector((project) => project.invocation.sourceId);- if (sourceId !== 'canvas') {- return null;- }- return <CanvasCompositingControls />;-};-const selectCanvasValues = (project: Parameters<typeof getProjectWidgetValues>[0]): Record<string, unknown> =>getProjectWidgetValues(project, 'canvas');-const CanvasCompositingControls = () => {+export const GenerateCanvasCompositingSection = () => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();+ const { widgets } = useWorkbenchCommands();const values = useActiveProjectSelector(selectCanvasValues);const settings = useMemo(() => readCanvasCompositingSettings(values), [values]);const patch = useCallback((partial: Record<string, unknown>) => {- dispatch({ type: 'patchWidgetValues', values: partial, widgetId: 'canvas' });+ widgets.patchValues('canvas', partial);},- [dispatch]+ [widgets]);const infillCollection = useMemo(@@ -133,7 +124,7 @@ const CanvasCompositingControls = () => {const opt = (key: string) => t(`widgets.generate.compositingOptions.${key}`);return (- <GenerateCollapsibleSection label={t('widgets.generate.compositing')}>+ <GenerationSettingsSection label={t('widgets.generate.compositing')}><Stack gap="2" p="2"><Field label={opt('infillMethod')}><Select@@ -197,6 +188,6 @@ const CanvasCompositingControls = () => {</NumberInput.Root></Field></Stack>- </GenerateCollapsibleSection>+ </GenerationSettingsSection>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsxindex 06b1739423..32db403f2a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx@@ -1,6 +1,6 @@+import type { CanvasStagingAreaContractV2, CanvasStagingCandidateContract } from '@workbench/canvas-engine/api';/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop */import type { CanvasStagingSlot } from '@workbench/canvasStagingView';-import type { CanvasStagingAreaContractV2, CanvasStagingCandidateContract } from '@workbench/types';import {Flex,@@ -14,13 +14,12 @@ import {Stack,Text,} from '@chakra-ui/react';-import { useQueueItemProgressImage } from '@workbench/backend/progressImageStore';-import { useQueueItemProgress } from '@workbench/backend/progressStore';+import { galleryDurability, galleryImages } from '@features/gallery';+import { useQueueItemProgress, useQueueItemProgressImage } from '@features/queue/react';+import { Button, IconButton, MenuContent, toaster, Tooltip } from '@platform/ui';+import { StreamingImageFrame } from '@platform/ui/streaming-image/StreamingImageFrame';+import { progressImageToStreamingSource } from '@platform/ui/streaming-image/streamingImageSource';import { getCancelableCanvasStagingQueueItemId } from '@workbench/canvasStagingView';-import { Button, IconButton, MenuContent, toaster, Tooltip } from '@workbench/components/ui';-import { getImageThumbnailUrl, saveImageToGallery } from '@workbench/gallery/api';-import { StreamingImageFrame } from '@workbench/images/StreamingImageFrame';-import { progressImageToStreamingSource } from '@workbench/images/streamingImageSource';import { CanvasOptionsBar } from '@workbench/widgets/canvas/tool-options/CanvasOptionsBar';import {CheckIcon,@@ -111,7 +110,7 @@ export const StagingBar = ({}setIsSaving(true);try {- await saveImageToGallery(selectedCandidate.imageName);+ await galleryDurability.save(selectedCandidate.imageName);toaster.create({description: t('widgets.canvas.staging.savedDescription', { name: selectedCandidate.imageName }),title: t('widgets.canvas.staging.saved'),@@ -358,7 +357,7 @@ const StagingThumbnail = ({{slot.kind === 'candidate' ? (<imgalt={slot.candidate.imageName}- src={slot.candidate.thumbnailUrl || getImageThumbnailUrl(slot.candidate.imageName)}+ src={slot.candidate.thumbnailUrl || galleryImages.thumbnailUrl(slot.candidate.imageName)}style={{ display: 'block', height: '100%', objectFit: 'cover', width: '100%' }}/>) : (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsxindex eb22969480..03f0df1d45 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx@@ -1,4 +1,4 @@-import type { TextEditSession } from '@workbench/canvas-engine/engineStores';+import type { TextEditSession } from '@workbench/canvas-engine/api';/* oxlint-disable react-perf/jsx-no-new-object-as-prop -- the editable's style object is derived from the live session/viewport and intentionally recomputed each render. */import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { CSSProperties, KeyboardEvent as ReactKeyboardEvent } from 'react';@@ -6,7 +6,7 @@ import type { CSSProperties, KeyboardEvent as ReactKeyboardEvent } from 'react';import { useTextEditSession } from '@workbench/widgets/canvas/engineStoreHooks';import { useCallback, useSyncExternalStore } from 'react';-type TextEditEngine = Pick<CanvasEngineHandle, 'layers' | 'stores' | 'viewport'>;+type TextEditEngine = Pick<CanvasEngineHandle, 'interaction' | 'layers' | 'viewport'>;/*** The text-editing portal: a positioned `contenteditable` div, rendered over thediff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsxindex 39984204c9..1b5631c8c5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx@@ -1,8 +1,7 @@-import type { CanvasCoreStoreCapability, CanvasToolCapability } from '@workbench/canvas-engine/api';-import type { ToolId } from '@workbench/canvas-engine/types';+import type { CanvasCoreStoreCapability, CanvasToolCapability, ToolId } from '@workbench/canvas-engine/api';import { Box } from '@chakra-ui/react';-import { Toolbar, ToolbarButton } from '@workbench/components/ui';+import { Toolbar, ToolbarButton } from '@platform/ui';import {BrushIcon,EraserIcon,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.test.tsindex 82dc1e088d..ec33895c8b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.test.ts@@ -31,7 +31,6 @@ describe('getCanvasGallerySaveErrorAction', () => {message: "Couldn't save to gallery",namespace: 'canvas',projectId: 'project-1',- type: 'recordError',});});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.tsindex 9a2f4d0db1..089d43c0e2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.ts@@ -1,16 +1,21 @@+import type { WorkbenchNotificationCommands } from '@workbench/workbenchStore';+interface CanvasProjectIdentity {readonly projectId: string;}const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));-export const getCanvasGallerySaveErrorAction = (error: unknown, projectId: string, message: string) => ({+export const getCanvasGallerySaveErrorAction = (+ error: unknown,+ projectId: string,+ message: string+): Parameters<WorkbenchNotificationCommands['reportError']>[0] => ({area: 'canvas-save-to-gallery',context: { error: toErrorMessage(error) },message,namespace: 'canvas' as const,projectId,- type: 'recordError' as const,});export const withMatchingCanvasProject = <Engine extends CanvasProjectIdentity, Result>(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.tsindex 6f376aadfd..9259b3e0c6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.ts@@ -1,7 +1,7 @@+import type { GalleryImage } from '@features/gallery';import type { GalleryCanvasImportDestination } from '@workbench/canvas-operations/api';-import type { GalleryImage } from '@workbench/gallery/api';-import { isGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';+import { isGalleryImageDragData } from '@features/gallery/utility';export interface CanvasImageDropData {kind: 'canvas-image-target';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDropLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDropLayout.test.tsindex 1d27f2d79e..ab05fcbf31 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDropLayout.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDropLayout.test.ts@@ -1,8 +1,9 @@+import type { GalleryImage } from '@features/gallery';import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';-import type { GalleryImage } from '@workbench/gallery/api';-import type { Project, WorkbenchState } from '@workbench/types';+import type { Project } from '@workbench/projectContracts';+import type { WorkbenchCanvasCommands } from '@workbench/workbenchStore';-import { getGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';+import { getGalleryImageDragData } from '@features/gallery/utility';import { describe, expect, it } from 'vitest';import {@@ -97,19 +98,22 @@ describe('executeCanvasImageDropImport', () => {const extra = { imageName: 'extra.png' } as GalleryImage;const project = { id: 'captured-project' } as Project;const engine = { projectId: project.id } as CanvasEngine;- const getState = () => ({ activeProjectId: project.id }) as WorkbenchState;+ const queries = {+ getProject: (projectId: string) => (projectId === project.id ? project : null),+ isActiveProject: (projectId: string) => projectId === project.id,+ };const lookupCalls: string[][] = [];const importCalls: unknown[] = [];const result = await executeCanvasImageDropImport({+ canvas: { apply: () => false } as unknown as WorkbenchCanvasCommands,destination: 'control',- dispatch: () => undefined,engine,getGalleryImages: (imageNames) => {lookupCalls.push([...imageNames]);return Promise.resolve([second, extra, first]);},- getState,+ queries,imageNames: ['first.png', 'second.png'],importGalleryImages: (options) => {importCalls.push(options);@@ -123,8 +127,9 @@ describe('executeCanvasImageDropImport', () => {expect(importCalls[0]).toMatchObject({destination: 'control',engine,- getState,+ getProject: queries.getProject,images: [first, second],+ isActiveProject: queries.isActiveProject,project,});expect(result).toEqual({ failedImageNames: [], layerIds: ['layer-1', 'layer-2'], status: 'imported' });diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.tsindex d053674b65..fb713242de 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.ts@@ -1,4 +1,6 @@-import type { CanvasStagingCandidateContract, QueueItem, QueueItemStatus } from '@workbench/types';+import type { QueueHistoryItemStatus } from '@features/queue/contracts';+import type { CanvasStagingCandidateContract } from '@workbench/canvas-engine/contracts';+import type { WorkbenchQueueItem as QueueItem } from '@workbench/queueHistoryContracts';import { createEmptyCanvasStateV2 } from '@workbench/canvasMigration';import { describe, expect, it } from 'vitest';@@ -37,7 +39,7 @@ const createCanvas = ({ revision = 1, staged = false }: { revision?: number; sta};};-const createQueueItem = ({ revision = 1, status }: { revision?: number; status: QueueItemStatus }): QueueItem =>+const createQueueItem = ({ revision = 1, status }: { revision?: number; status: QueueHistoryItemStatus }): QueueItem =>({backendItemIds: [1],completedBackendItemIds: [1],diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.tsindex ec616529f8..c020a8dc6b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.ts@@ -1,5 +1,5 @@-import type { ToolId } from '@workbench/canvas-engine/types';-import type { CanvasStateContractV2, QueueItem } from '@workbench/types';+import type { CanvasStateContractV2, ToolId } from '@workbench/canvas-engine/api';+import type { WorkbenchQueueItem as QueueItem } from '@workbench/queueHistoryContracts';import { getCanvasStagingSlots } from '@workbench/canvasStagingView';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/checkerColors.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/checkerColors.tsindex 0ea15e17c8..fa4e1320b3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/checkerColors.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/checkerColors.ts@@ -13,7 +13,7 @@*/import { system } from '@theme/system';-import { type CheckerColors, DEFAULT_CHECKER_COLORS } from '@workbench/canvas-engine/render/compositor';+import { type CheckerColors, DEFAULT_CHECKER_COLORS } from '@workbench/canvas-engine/api';/*** The two Chakra semantic tokens used for the checker squares. `bg.subtle` anddiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.tsindex 39f52acfc6..fa68198ff3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts@@ -8,29 +8,39 @@* `widgets/`) preserves the engine's zero-React boundary.*/-import type { CanvasCoreStoreCapability } from '@workbench/canvas-engine/api';import type {BboxToolOptions,BrushOptions,+ CanvasCoreStoreCapability,+ CanvasInteractionState,EraserOptions,GradientToolOptions,LassoToolOptions,- ScalarStore,ShapeToolOptions,TextEditSession,TextToolOptions,TransformSession,LayerThumbnailStatus,-} from '@workbench/canvas-engine/engineStores';-import type { ToolId } from '@workbench/canvas-engine/types';-import type { CanvasOperationState } from '@workbench/canvas-operations/operationController';-import type { FilterOperationSessionState, SamSessionSnapshot } from '@workbench/canvas-operations/operationTypes';--import { getCanvasOperations } from '@workbench/canvas-operations/createCanvasEngine';+ ToolId,+} from '@workbench/canvas-engine/api';++import {+ getCanvasOperations,+ type CanvasOperationState,+ type FilterOperationSessionState,+ type SamSessionSnapshot,+} from '@workbench/canvas-operations/api';import { useCallback, useSyncExternalStore } from 'react';/** Subscribes the calling component to a single engine scalar store. */-const useScalarStore = <T>(store: ScalarStore<T>): T => useSyncExternalStore(store.subscribe, store.get);+const useCanvasInteractionState = <K extends keyof CanvasInteractionState>(+ engine: CanvasCoreStoreCapability,+ key: K+): CanvasInteractionState[K] => {+ const subscribe = useCallback((listener: () => void) => engine.interaction.subscribe(key, listener), [engine, key]);+ const getSnapshot = useCallback(() => engine.interaction.get(key), [engine, key]);+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);+};/*** Subscribes to a single layer's thumbnail version on `engine`, re-rendering@@ -44,10 +54,11 @@ export const useLayerThumbnailVersion = (layerId: string): number | undefined => {const subscribe = useCallback(- (onStoreChange: () => void) => engine?.stores.thumbnailVersion.subscribeKey(layerId, onStoreChange) ?? (() => {}),+ (onStoreChange: () => void) =>+ engine?.interaction.subscribeLayerThumbnailVersion(layerId, onStoreChange) ?? (() => {}),[engine, layerId]);- const getSnapshot = useCallback(() => engine?.stores.thumbnailVersion.get(layerId), [engine, layerId]);+ const getSnapshot = useCallback(() => engine?.interaction.getLayerThumbnailVersion(layerId), [engine, layerId]);return useSyncExternalStore(subscribe, getSnapshot);};@@ -57,104 +68,122 @@ export const useLayerThumbnailStatus = (layerId: string): LayerThumbnailStatus | 'idle' => {const subscribe = useCallback(- (onStoreChange: () => void) => engine?.stores.thumbnailStatus.subscribeKey(layerId, onStoreChange) ?? (() => {}),+ (onStoreChange: () => void) =>+ engine?.interaction.subscribeLayerThumbnailStatus(layerId, onStoreChange) ?? (() => {}),+ [engine, layerId]+ );+ const getSnapshot = useCallback(+ () => engine?.interaction.getLayerThumbnailStatus(layerId) ?? 'idle',[engine, layerId]);- const getSnapshot = useCallback(() => engine?.stores.thumbnailStatus.get(layerId) ?? 'idle', [engine, layerId]);return useSyncExternalStore(subscribe, getSnapshot);};/** Current viewport zoom factor for `engine` (re-renders on zoom change). */-export const useCanvasZoom = (engine: CanvasCoreStoreCapability): number => useScalarStore(engine.stores.zoom);+export const useCanvasZoom = (engine: CanvasCoreStoreCapability): number => useCanvasInteractionState(engine, 'zoom');/** Whether `engine` has render targets bound and its viewport is live. */export const useCanvasViewportReady = (engine: CanvasCoreStoreCapability): boolean =>- useScalarStore(engine.stores.viewportReady);+ useCanvasInteractionState(engine, 'viewportReady');/** The active tool id for `engine`. */export const useCanvasActiveTool = (engine: CanvasCoreStoreCapability): ToolId =>- useScalarStore(engine.stores.activeTool);+ useCanvasInteractionState(engine, 'activeTool');const IDLE_CANVAS_OPERATION: CanvasOperationState = { status: 'idle' };export const useCanvasOperation = (engine: object | null): CanvasOperationState => {const subscribe = useCallback(- (listener: () => void) => (engine ? getCanvasOperations(engine).controller.subscribe(listener) : () => undefined),+ (listener: () => void) => (engine ? getCanvasOperations(engine).subscribeOperation(listener) : () => undefined),[engine]);const getSnapshot = useCallback(- () => (engine ? getCanvasOperations(engine).controller.getSnapshot() : IDLE_CANVAS_OPERATION),+ () => (engine ? getCanvasOperations(engine).getOperationState() : IDLE_CANVAS_OPERATION),[engine]);return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);};-export const useSamSession = (engine: object): SamSessionSnapshot | null =>- useScalarStore(getCanvasOperations(engine).stores.samSession);+export const useSamSession = (engine: object): SamSessionSnapshot | null => {+ const operations = getCanvasOperations(engine);+ return useSyncExternalStore(+ operations.subscribeSamSession,+ operations.getSamSessionState,+ operations.getSamSessionState+ );+};-export const useFilterSession = (engine: object): FilterOperationSessionState | null =>- useScalarStore(getCanvasOperations(engine).stores.filterSession);+export const useFilterSession = (engine: object): FilterOperationSessionState | null => {+ const operations = getCanvasOperations(engine);+ return useSyncExternalStore(+ operations.subscribeFilterSession,+ operations.getFilterSessionState,+ operations.getFilterSessionState+ );+};/** Whether the engine-owned canvas history has an entry to undo (enables the header undo button). */-export const useCanvasCanUndo = (engine: CanvasCoreStoreCapability): boolean => useScalarStore(engine.stores.canUndo);+export const useCanvasCanUndo = (engine: CanvasCoreStoreCapability): boolean =>+ useCanvasInteractionState(engine, 'canUndo');/** Whether the engine-owned canvas history has an entry to redo (enables the header redo button). */-export const useCanvasCanRedo = (engine: CanvasCoreStoreCapability): boolean => useScalarStore(engine.stores.canRedo);+export const useCanvasCanRedo = (engine: CanvasCoreStoreCapability): boolean =>+ useCanvasInteractionState(engine, 'canRedo');/** Whether a SAM/filter operation currently excludes ordinary canvas document edits. */export const useCanvasDocumentEditingLocked = (engine: CanvasCoreStoreCapability | null): boolean => {const subscribe = useCallback(- (listener: () => void) => engine?.stores.documentEditingLocked.subscribe(listener) ?? (() => undefined),+ (listener: () => void) => engine?.interaction.subscribe('documentEditingLocked', listener) ?? (() => undefined),[engine]);- const getSnapshot = useCallback(() => engine?.stores.documentEditingLocked.get() ?? false, [engine]);+ const getSnapshot = useCallback(() => engine?.interaction.get('documentEditingLocked') ?? false, [engine]);return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);};/*** The brush tool's current options (size / color / opacity / pressure). Write- * through `engine.stores.brushOptions.set(...)` directly — there is no reducer+ * through `engine.interaction.set('brushOptions', ...)` directly — there is no reducer* mirror to dispatch through, so the options bar reads and writes this one* store.*/export const useBrushOptions = (engine: CanvasCoreStoreCapability): BrushOptions =>- useScalarStore(engine.stores.brushOptions);+ useCanvasInteractionState(engine, 'brushOptions');-/** The eraser tool's current options (size / opacity). Write through `engine.stores.eraserOptions.set(...)`. */+/** The eraser tool's current options (size / opacity). Write through `engine.interaction.set`. */export const useEraserOptions = (engine: CanvasCoreStoreCapability): EraserOptions =>- useScalarStore(engine.stores.eraserOptions);+ useCanvasInteractionState(engine, 'eraserOptions');-/** The bbox tool's current options (aspect lock / ratio). Write through `engine.stores.bboxOptions.set(...)`. */+/** The bbox tool's current options (aspect lock / ratio). Write through `engine.interaction.set`. */export const useBboxOptions = (engine: CanvasCoreStoreCapability): BboxToolOptions =>- useScalarStore(engine.stores.bboxOptions);+ useCanvasInteractionState(engine, 'bboxOptions');/** The bbox tool's current snapping grid size (document px). */-export const useBboxGrid = (engine: CanvasCoreStoreCapability): number => useScalarStore(engine.stores.bboxGrid);+export const useBboxGrid = (engine: CanvasCoreStoreCapability): number => useCanvasInteractionState(engine, 'bboxGrid');/** The active transform-tool session (layer id + live transform), or `null`. */export const useTransformSession = (engine: CanvasCoreStoreCapability): TransformSession | null =>- useScalarStore(engine.stores.transformSession);+ useCanvasInteractionState(engine, 'transformSession');/** Whether a pixel selection currently exists (enables fill/erase/invert/deselect controls). */export const useCanvasHasSelection = (engine: CanvasCoreStoreCapability): boolean =>- useScalarStore(engine.stores.hasSelection);+ useCanvasInteractionState(engine, 'hasSelection');-/** The lasso tool's current options (the committed boolean op mode). Write through `engine.stores.lassoOptions.set(...)`. */+/** The lasso tool's current options (the committed boolean op mode). Write through `engine.interaction.set`. */export const useLassoOptions = (engine: CanvasCoreStoreCapability): LassoToolOptions =>- useScalarStore(engine.stores.lassoOptions);+ useCanvasInteractionState(engine, 'lassoOptions');-/** The shape tool's current options (kind / fill / stroke / stroke width). Write through `engine.stores.shapeOptions.set(...)`. */+/** The shape tool's current options (kind / fill / stroke / stroke width). Write through `engine.interaction.set`. */export const useShapeOptions = (engine: CanvasCoreStoreCapability): ShapeToolOptions =>- useScalarStore(engine.stores.shapeOptions);+ useCanvasInteractionState(engine, 'shapeOptions');-/** The gradient tool's current options (kind / angle / stops). Write through `engine.stores.gradientOptions.set(...)`. */+/** The gradient tool's current options (kind / angle / stops). Write through `engine.interaction.set`. */export const useGradientOptions = (engine: CanvasCoreStoreCapability): GradientToolOptions =>- useScalarStore(engine.stores.gradientOptions);+ useCanvasInteractionState(engine, 'gradientOptions');/** The text tool's current options (font / size / weight / line-height / align / color). */export const useTextOptions = (engine: CanvasCoreStoreCapability): TextToolOptions =>- useScalarStore(engine.stores.textOptions);+ useCanvasInteractionState(engine, 'textOptions');/** The active text-editing session (create/edit mode + live source + transform), or `null`. */export const useTextEditSession = (engine: CanvasCoreStoreCapability): TextEditSession | null =>- useScalarStore(engine.stores.textEditSession);+ useCanvasInteractionState(engine, 'textEditSession');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.tsindex 1b916cb1ba..85e7a39c78 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts@@ -1,14 +1,13 @@-import type { Project, WorkbenchState } from '@workbench/types';+import type { Project } from '@workbench/projectContracts';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';-import type { WorkbenchAction } from '@workbench/workbenchState';-import type { Dispatch } from 'react';+import type { WorkbenchCanvasCommands, WorkbenchQueries } from '@workbench/workbenchStore';+import { galleryImages } from '@features/gallery';import {importGalleryImagesToCanvas,type GalleryCanvasImportDestination,type ImportGalleryImagesResult,} from '@workbench/canvas-operations/api';-import { getGalleryImagesByNames } from '@workbench/gallery/api';import { orderCanvasImageDropImages } from './canvasImageDnd';@@ -16,19 +15,19 @@ type CanvasImageDropEngine = Pick<CanvasEngineHandle, 'layers' | 'projectId'>;export const executeCanvasImageDropImport = async ({destination,- dispatch,+ canvas,engine,- getGalleryImages = getGalleryImagesByNames,- getState,+ getGalleryImages = galleryImages.resolveMany,+ queries,imageNames,importGalleryImages = importGalleryImagesToCanvas,project,}: {destination: GalleryCanvasImportDestination;- dispatch: Dispatch<WorkbenchAction>;+ canvas: WorkbenchCanvasCommands;engine: CanvasImageDropEngine | null;- getGalleryImages?: typeof getGalleryImagesByNames;- getState: () => WorkbenchState;+ getGalleryImages?: typeof galleryImages.resolveMany;+ queries: Pick<WorkbenchQueries, 'getProject' | 'isActiveProject'>;imageNames: readonly string[];importGalleryImages?: typeof importGalleryImagesToCanvas;project: Project;@@ -36,5 +35,13 @@ export const executeCanvasImageDropImport = async ({const fetchedImages = await getGalleryImages([...imageNames]);const images = orderCanvasImageDropImages(imageNames, fetchedImages);- return importGalleryImages({ destination, dispatch, engine, getState, images, project });+ return importGalleryImages({+ applyCanvasMutation: canvas.apply,+ destination,+ engine,+ getProject: queries.getProject,+ images,+ isActiveProject: queries.isActiveProject,+ project,+ });};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.tsindex 540b0eb413..b461ba8b19 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.tsindex 4650ef1626..fdcaaac7b2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts@@ -20,11 +20,15 @@* Zero React, zero engine/DOM state — unit-tested in node.*/-import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';--import { getSourceBounds, isRenderableLayer } from '@workbench/canvas-engine/document/sources';-import { isEmpty, union } from '@workbench/canvas-engine/math/rect';+import {+ getSourceBounds,+ isEmpty,+ isRenderableLayer,+ union,+ type CanvasDocumentContractV2,+ type CanvasLayerContract,+ type Rect,+} from '@workbench/canvas-engine/api';/** Fixed outward padding (document px) applied to the mask union before grid-fitting. */const MASK_FIT_PADDING = 8;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/implementation.tsnew file mode 100644index 0000000000..8d90b4b3f2--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/implementation.ts@@ -0,0 +1,9 @@+import type { WidgetImplementation } from '@workbench/widgetContracts';++import { CanvasHeaderActions } from './CanvasHeaderActions';+import { CanvasWidgetView } from './CanvasWidgetView';++export const widgetImplementation = {+ headerActions: CanvasHeaderActions,+ view: CanvasWidgetView,+} satisfies WidgetImplementation;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/index.tsindex 9dcadede16..4ccd487e44 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/index.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/index.ts@@ -1,19 +1,15 @@-import type { WidgetManifest } from '@workbench/types';+import type { WidgetManifest } from '@workbench/widgetContracts';import { WandSparklesIcon } from 'lucide-react';-import { CanvasHeaderActions } from './CanvasHeaderActions';-import { CanvasWidgetView } from './CanvasWidgetView';-export const canvasWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['center'],failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },graphBearing: { defaultGraphId: 'canvas-graph', sourceId: 'canvas', surfaces: ['center'] },- headerActions: CanvasHeaderActions,icon: WandSparklesIcon,id: 'canvas',label: (t) => t('widgets.labels.canvas'),+ load: () => import('./implementation').then((module) => module.widgetImplementation),version: 1,- view: CanvasWidgetView,};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.tsindex 2c2a0e0bfe..c425f80b41 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@@ -1,27 +1,32 @@-import type { CanvasRasterSnapshot } from '@workbench/canvas-engine/api';-import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';-import type { RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { Rect } from '@workbench/canvas-engine/types';-import type {- GenerateModelConfig,- MainModelConfig,- RegionalGuidanceReferenceImage,- RegionalGuidanceReferenceImageAsset,-} from '@workbench/generation/types';+import type { GenerateModelConfig, MainModelConfig } from '@features/generation/contracts';import type {CanvasDocumentContractV2,CanvasControlLayerContract,CanvasLayerContract,CanvasRasterLayerContractV2,CanvasStateContractV2,- WorkbenchState,-} from '@workbench/types';-import type { WorkbenchAction } from '@workbench/workbenchState';+ RegionalGuidanceReferenceImage,+ RegionalGuidanceReferenceImageAsset,+} from '@workbench/canvas-engine/contracts';+import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { Rect } from '@workbench/canvas-engine/types';+import type { CanvasCompositeTransaction } from '@workbench/canvas-operations/api';+import type { WorkbenchState } from '@workbench/projectContracts';+import type { WorkbenchAction } from '@workbench/workbenchState.testing';+import type { WorkbenchCommands } from '@workbench/workbenchStore';+import { getDefaultGenerateSettings } from '@features/generation/settings';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';-import { createCompositeDedupeCache } from '@workbench/canvas-operations/compositeForGeneration';-import { getDefaultGenerateSettings } from '@workbench/generation/baseGenerationPolicies';-import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState';+import {+ createCompositeDedupeCache,+ executeCompositePlan,+ executeControlComposite,+ executeMaskComposite,+ executeRegionalMaskComposite,+ type ExecuteCompositePlanDeps,+} from '@workbench/canvas-operations/compositeForGeneration';+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { RunCanvasInvocationDeps } from './prepareCanvasInvocation';@@ -88,6 +93,8 @@ interface Harness {events: string[];surfaceIds: string[];releaseRasterSnapshot: ReturnType<typeof vi.fn>;+ dedupe: ReturnType<typeof createCompositeDedupeCache>;+ executorDeps: Omit<ExecuteCompositePlanDeps, 'dedupe' | 'getLayerSurface'>;submittedGraphs: () => Extract<WorkbenchAction, { type: 'submitCanvasInvocationSnapshot' }>[];notices: () => { message?: string }[];}@@ -158,6 +165,7 @@ const makeHarness = (options: HarnessOptions = {}): Harness => {const dispatch = options.dispatch ?? vi.fn((_action: WorkbenchAction) => {});const releaseRasterSnapshot = vi.fn();+ const dedupe = createCompositeDedupeCache();const makeCanvas = (document: CanvasDocumentContractV2): CanvasStateContractV2 => ({document: structuredClone(document),@@ -174,33 +182,65 @@ const makeHarness = (options: HarnessOptions = {}): Harness => {version: 2,});+ const executorDeps: Omit<ExecuteCompositePlanDeps, 'dedupe' | 'getLayerSurface'> = {+ backend,+ hashBlob: (blob: Blob) => blob.text(),+ readImageData: (_surface, rect) => uniformImageData(rect.width, rect.height, alpha),+ uploadImage: uploadImage as (blob: Blob) => Promise<CanvasImageUploadResult>,+ };+const deps: RunCanvasInvocationDeps = {captureDocumentSnapshot: () => ({canvas: makeCanvas(options.document ?? makeDoc([rasterLayer('layer-a')])),documentGeneration: 0,}),- captureRasterSnapshot: async (documentSnapshot, layerIds) => {+ captureCompositeTransaction: async (documentSnapshot, layerIds) => {const layerSurfaces = new Map<string, { surface: RasterSurface; rect: Rect }>();for (const layerId of layerIds) {layerSurfaces.set(layerId, await getLayerSurface(layerId));}- const snapshot: CanvasRasterSnapshot = {- ...documentSnapshot,- emptyLayerIds: new Set<string>(),- layerSurfaces,+ const transactionDedupe = createCompositeDedupeCache();+ for (const [key, value] of dedupe.byHash) {+ transactionDedupe.byHash.set(key, value);+ }+ for (const [key, value] of dedupe.byKey) {+ transactionDedupe.byKey.set(key, value);+ }+ const compositeDeps: ExecuteCompositePlanDeps = {+ ...executorDeps,+ dedupe: transactionDedupe,+ getLayerSurface: (layerId) => {+ const detached = layerSurfaces.get(layerId);+ return detached ? Promise.resolve(detached) : Promise.reject(new Error(`Missing ${layerId}`));+ },+ };+ const transaction: CanvasCompositeTransaction = {+ canvas: documentSnapshot.canvas,+ commit: () => {+ for (const [key, value] of transactionDedupe.byHash) {+ dedupe.byHash.set(key, value);+ }+ for (const [key, value] of transactionDedupe.byKey) {+ dedupe.byKey.set(key, value);+ }+ },+ executeControl: (entry) => executeControlComposite(entry, compositeDeps),+ executeMask: (entry) => executeMaskComposite(entry, compositeDeps),+ executePlan: (plan) => executeCompositePlan(plan, compositeDeps),+ executeRegionalMask: (entry) => executeRegionalMaskComposite(entry, compositeDeps),release: releaseRasterSnapshot,};- return { snapshot, status: 'ok' };+ return { status: 'ok', transaction };},compositing: DEFAULT_CANVAS_COMPOSITING,- dedupe: createCompositeDedupeCache(),destination: options.destination ?? 'canvas',- dispatch,- executorDeps: {- backend,- hashBlob: (blob: Blob) => blob.text(),- readImageData: (_surface, rect) => uniformImageData(rect.width, rect.height, alpha),- uploadImage: uploadImage as (blob: Blob) => Promise<CanvasImageUploadResult>,+ commands: {+ generation: {+ submitCanvas: (payload) => dispatch({ ...payload, type: 'submitCanvasInvocationSnapshot' }),+ } as WorkbenchCommands['generation'],+ notifications: {+ add: (notice) => dispatch({ ...notice, type: 'recordNotice' }),+ } as WorkbenchCommands['notifications'],},flushPendingUploads: flushPendingUploads as () => Promise<void>,generateValues: generateValuesFor(model),@@ -218,8 +258,10 @@ const makeHarness = (options: HarnessOptions = {}): Harness => {dispatch.mock.calls.map(([action]) => action).filter((action) => action.type === 'recordNotice');return {+ dedupe,deps,dispatch,+ executorDeps,events,flushPendingUploads,notices,@@ -440,42 +482,42 @@ describe('runCanvasInvocation', () => {};Object.assign(harness.deps, {captureDocumentSnapshot: vi.fn(() => snapshot),- captureRasterSnapshot: vi.fn(() => Promise.resolve({ status: 'stale' as const })),+ captureCompositeTransaction: vi.fn(() => Promise.resolve({ status: 'stale' as const })),});await runCanvasInvocation(harness.deps);expect(harness.submittedGraphs()).toHaveLength(0);expect(harness.notices()).toHaveLength(1);- expect(harness.deps.dedupe.byKey).toHaveLength(0);- expect(harness.deps.dedupe.byHash).toHaveLength(0);+ expect(harness.dedupe.byKey).toHaveLength(0);+ expect(harness.dedupe.byHash).toHaveLength(0);});it.each(['aborted', 'not-ready', 'over-budget'] as const)('does not submit when raster capture returns the typed %s outcome',async (status) => {const harness = makeHarness();- harness.deps.captureRasterSnapshot = vi.fn(() => Promise.resolve({ status }));+ harness.deps.captureCompositeTransaction = vi.fn(() => Promise.resolve({ status }));await runCanvasInvocation(harness.deps);expect(harness.submittedGraphs()).toHaveLength(0);expect(harness.notices()).toHaveLength(1);- expect(harness.deps.dedupe.byKey).toHaveLength(0);- expect(harness.deps.dedupe.byHash).toHaveLength(0);+ expect(harness.dedupe.byKey).toHaveLength(0);+ expect(harness.dedupe.byHash).toHaveLength(0);});it('passes the orchestration AbortSignal into raster snapshot capture', async () => {const harness = makeHarness();const controller = new AbortController();- const captureRasterSnapshot = vi.fn(() => Promise.resolve({ status: 'aborted' as const }));- Object.assign(harness.deps, { captureRasterSnapshot, signal: controller.signal });+ const captureCompositeTransaction = vi.fn(() => Promise.resolve({ status: 'aborted' as const }));+ Object.assign(harness.deps, { captureCompositeTransaction, signal: controller.signal });controller.abort(new DOMException('invoke cancelled', 'AbortError'));await runCanvasInvocation(harness.deps);- expect(captureRasterSnapshot).toHaveBeenCalledWith(+ expect(captureCompositeTransaction).toHaveBeenCalledWith(expect.any(Object),['layer-a'],expect.objectContaining({ signal: controller.signal })@@ -507,9 +549,9 @@ describe('runCanvasInvocation', () => {},documentGeneration: 9,});- const captureRasterSnapshot = harness.deps.captureRasterSnapshot;- harness.deps.captureRasterSnapshot = async (snapshot, layerIds) => {- const result = await captureRasterSnapshot(snapshot, layerIds, { signal: harness.deps.signal });+ const captureCompositeTransaction = harness.deps.captureCompositeTransaction;+ harness.deps.captureCompositeTransaction = async (snapshot, layerIds) => {+ const result = await captureCompositeTransaction(snapshot, layerIds, { signal: harness.deps.signal });// The transaction is fully detached at this boundary. Subsequent edits// must not alter any composite/upload/compile/dispatch input.liveDocument = {@@ -528,7 +570,7 @@ describe('runCanvasInvocation', () => {expect(harness.submittedGraphs()[0]?.canvas.document.bbox).toEqual({ height: 64, width: 64, x: 7, y: 11 });expect(harness.submittedGraphs()[0]?.canvas.document.layers[0]?.id).toBe('frozen-layer');expect(harness.releaseRasterSnapshot).toHaveBeenCalledTimes(1);- expect(harness.deps.dedupe.byKey.size).toBeGreaterThan(0);+ expect(harness.dedupe.byKey.size).toBeGreaterThan(0);});it.each(['coverage-scan', 'encode', 'upload'] as const)(@@ -557,20 +599,20 @@ describe('runCanvasInvocation', () => {liveDocument = { ...liveDocument, bbox: { height: 64, width: 64, x: 88, y: 99 } };};if (boundary === 'coverage-scan') {- const readImageData = harness.deps.executorDeps.readImageData!;- harness.deps.executorDeps.readImageData = (...args) => {+ const readImageData = harness.executorDeps.readImageData!;+ harness.executorDeps.readImageData = (...args) => {editLiveBbox();return readImageData(...args);};} else if (boundary === 'encode') {- const encodeSurface = harness.deps.executorDeps.backend.encodeSurface;- harness.deps.executorDeps.backend.encodeSurface = (...args) => {+ const encodeSurface = harness.executorDeps.backend.encodeSurface;+ harness.executorDeps.backend.encodeSurface = (...args) => {editLiveBbox();return encodeSurface(...args);};} else {- const uploadImage = harness.deps.executorDeps.uploadImage;- harness.deps.executorDeps.uploadImage = (...args) => {+ const uploadImage = harness.executorDeps.uploadImage;+ harness.executorDeps.uploadImage = (...args) => {editLiveBbox();return uploadImage(...args);};@@ -594,8 +636,8 @@ describe('runCanvasInvocation', () => {const notices = harness.notices();expect(notices).toHaveLength(1);expect(notices[0]?.message).toContain('does not support canvas generation');- expect(harness.deps.dedupe.byKey).toHaveLength(0);- expect(harness.deps.dedupe.byHash).toHaveLength(0);+ expect(harness.dedupe.byKey).toHaveLength(0);+ expect(harness.dedupe.byHash).toHaveLength(0);expect(harness.releaseRasterSnapshot).toHaveBeenCalledTimes(1);});@@ -609,8 +651,8 @@ describe('runCanvasInvocation', () => {const notices = harness.notices();expect(notices).toHaveLength(1);expect(notices[0]?.message).toBe('upload exploded');- expect(harness.deps.dedupe.byKey).toHaveLength(0);- expect(harness.deps.dedupe.byHash).toHaveLength(0);+ expect(harness.dedupe.byKey).toHaveLength(0);+ expect(harness.dedupe.byHash).toHaveLength(0);expect(harness.releaseRasterSnapshot).toHaveBeenCalledTimes(1);});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.tsindex 74cbfdf7c3..2d8f3d178e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts@@ -24,64 +24,50 @@* same project is still running (the Invoke hotkey can be mashed).*/+import type { GenerateModelConfig } from '@features/generation/contracts';+import type { ModelConfig } from '@features/models';import type {CanvasDocumentSnapshot,- CanvasDocumentCapability,- CanvasExportCapability,- CanvasLifecycleCapability,- CaptureRasterSnapshotResult,-} from '@workbench/canvas-engine/api';-import type {- CompositeDedupeCache,- ExecuteCompositePlanDeps,-} from '@workbench/canvas-operations/compositeForGeneration';-import type { ControlLayerGraphInput } from '@workbench/generation/canvas/addControlLayers';-import type {- RegionalGuidanceInput,- RegionalReferenceImageInput,-} from '@workbench/generation/canvas/addRegionalGuidance';-import type { CanvasCompileMode } from '@workbench/generation/canvas/types';-import type { GenerateModelConfig, RegionalGuidanceReferenceImage } from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';-import type {CanvasDocumentContractV2,- ProjectSettings,- ResultDestination,- WorkbenchNotificationKind,-} from '@workbench/types';-import type { CanvasCompositingSettings } from '@workbench/widgets/canvas/invoke/canvasCompositing';-import type { WorkbenchAction } from '@workbench/workbenchState';+ RegionalGuidanceReferenceImage,+} from '@workbench/canvas-engine/api';+import type { ResultDestination } from '@workbench/invocationContracts';+import type { WorkbenchNotificationKind } from '@workbench/projectContracts';+import type { ProjectSettings } from '@workbench/settings/contracts';+import type { WorkbenchCommands, WorkbenchNotificationCommands } from '@workbench/workbenchStore';import {- computeCompositeContentBounds,- executeCompositePlan,- executeControlComposite,- executeMaskComposite,- executeRegionalMaskComposite,-} from '@workbench/canvas-operations/compositeForGeneration';-import { getEngine } from '@workbench/canvas-operations/engineRegistry';-import {+ compileCanvasGraph,+ detectCanvasMode,+ getControlValidationReason,getRegionalGuidanceRejectionReason,isRegionalGuidanceSupportedForBase,-} from '@workbench/generation/canvas/addRegionalGuidance';-import { detectCanvasMode, rectsIntersect } from '@workbench/generation/canvas/canvasMode';-import { compileCanvasGraph } from '@workbench/generation/canvas/compileCanvasGraph';+ rectsIntersect,+ type CanvasCompileMode,+ type ControlLayerGraphInput,+ type RegionalGuidanceInput,+ type RegionalReferenceImageInput,+} from '@features/generation/canvas';+import { resolveGenerateSeed } from '@features/generation/graph';+import { normalizeGenerateWidgetValues, syncGenerateWidgetValuesWithModels } from '@features/generation/settings';import {+ computeCompositeContentBounds,+ getCanvasEngine,+ getCanvasOperations,+ type CanvasCompositeTransaction,+ type CanvasCompositeTransactionResult,planComposites,planControlComposites,planRegionalMaskComposites,-} from '@workbench/generation/canvas/compositePlan';-import { getControlValidationReason } from '@workbench/generation/canvas/controlValidation';-import { resolveGenerateSeed } from '@workbench/generation/graph';-import { normalizeGenerateWidgetValues, syncGenerateWidgetValuesWithModels } from '@workbench/generation/settings';-import { DEFAULT_CANVAS_COMPOSITING } from '@workbench/widgets/canvas/invoke/canvasCompositing';+} from '@workbench/canvas-operations/api';+import {+ DEFAULT_CANVAS_COMPOSITING,+ type CanvasCompositingSettings,+} from '@workbench/widgets/canvas/invoke/canvasCompositing';/** Title on every canvas-invoke failure notice. */export const CANVAS_INVOKE_ERROR_TITLE = 'Canvas generation failed';-/** Engine-backed executor deps, minus the caller-owned dedupe cache. */-type CompositeExecutorDeps = Omit<ExecuteCompositePlanDeps, 'dedupe' | 'getLayerSurface'>;-/** Injected dependencies for the React-free orchestrator. */export interface RunCanvasInvocationDeps {/** The active project id (also the in-flight guard key). */@@ -95,19 +81,15 @@ export interface RunCanvasInvocationDeps {/** Captures the exact post-flush canvas contract used by immutable invocation transactions. */captureDocumentSnapshot: () => CanvasDocumentSnapshot | null;/** Detaches every layer surface required by the transaction's complete composite plan. */- captureRasterSnapshot: (+ captureCompositeTransaction: (snapshot: CanvasDocumentSnapshot,layerIds: readonly string[],options: { signal: AbortSignal }- ) => Promise<CaptureRasterSnapshotResult>;+ ) => Promise<CanvasCompositeTransactionResult>;/** Cancels cache preparation and detachment for this invocation transaction. */signal: AbortSignal;/** Paint-bitmap persistence barrier, awaited before compositing. */flushPendingUploads: () => Promise<void>;- /** Engine-backed composite executor deps (backend + rasterize-or-throw + uploader). */- executorDeps: CompositeExecutorDeps;- /** Per-engine dedupe cache (caller-owned; persists across invokes, size-capped). */- dedupe: CompositeDedupeCache;/** Project ids with a prepare currently in flight (module/registry-scoped). */inFlight: Set<string>;/** The generate widget's raw persisted values (model/prompt/steps, shared with Generate). */@@ -120,16 +102,15 @@ export interface RunCanvasInvocationDeps {strength: number;/** Persisted compositing settings (infill / coherence / mask blur), defaulted + clamped. */compositing: CanvasCompositingSettings;- /** Reducer dispatch. */- dispatch: (action: WorkbenchAction) => void;+ commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;}const recordNotice = (- dispatch: (action: WorkbenchAction) => void,+ notifications: WorkbenchNotificationCommands,kind: WorkbenchNotificationKind,message: string): void => {- dispatch({ kind, message, title: CANVAS_INVOKE_ERROR_TITLE, type: 'recordNotice' });+ notifications.add({ kind, message, title: CANVAS_INVOKE_ERROR_TITLE });};/**@@ -144,7 +125,7 @@ const collectControlLayerInputs = async (bbox: { x: number; y: number; width: number; height: number },model: GenerateModelConfig,models: readonly ModelConfig[] | undefined,- executorDeps: ExecuteCompositePlanDeps+ transaction: Pick<CanvasCompositeTransaction, 'executeControl'>): Promise<ControlLayerGraphInput[]> => {const composites = planControlComposites(document, bbox);if (composites.length === 0) {@@ -184,7 +165,7 @@ const collectControlLayerInputs = async (zImageControlCount += 1;}- const result = await executeControlComposite(entry, executorDeps);+ const result = await transaction.executeControl(entry);inputs.push({beginEndStepPct: adapter.beginEndStepPct,controlMode: adapter.controlMode,@@ -278,7 +259,7 @@ const collectRegionalGuidanceInputs = async (document: CanvasDocumentContractV2,bbox: { x: number; y: number; width: number; height: number },model: GenerateModelConfig,- executorDeps: ExecuteCompositePlanDeps+ transaction: Pick<CanvasCompositeTransaction, 'executeRegionalMask'>): Promise<RegionalGuidanceInput[]> => {if (!isRegionalGuidanceSupportedForBase(model.base)) {return [];@@ -311,7 +292,7 @@ const collectRegionalGuidanceInputs = async (continue;}- const result = await executeRegionalMaskComposite(entry, executorDeps);+ const result = await transaction.executeRegionalMask(entry);inputs.push({autoNegative: layer.autoNegative,id: layerId,@@ -331,7 +312,7 @@ const collectRegionalGuidanceInputs = async (* cleared. Returns when the graph has been dispatched (or the invoke aborted).*/export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promise<void> => {- const { dispatch, inFlight, projectId } = deps;+ const { commands, inFlight, projectId } = deps;// Concurrency guard: ignore a re-invoke while a prior prepare for this project// is still settling (the hotkey can be mashed). Cleared in `finally`.@@ -340,11 +321,11 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis}inFlight.add(projectId);- let rasterSnapshot: Extract<CaptureRasterSnapshotResult, { status: 'ok' }>['snapshot'] | null = null;+ let transaction: CanvasCompositeTransaction | null = null;try {const values = normalizeGenerateWidgetValues(deps.generateValues);if (!values) {- recordNotice(dispatch, 'error', 'Select a supported model before invoking the canvas.');+ recordNotice(commands.notifications, 'error', 'Select a supported model before invoking the canvas.');return;}@@ -366,7 +347,7 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis// The bbox can also move during a slow flush; take it from the fresh snapshot.const documentSnapshot = deps.captureDocumentSnapshot();if (!documentSnapshot) {- recordNotice(dispatch, 'error', 'The canvas has no active document to generate from.');+ recordNotice(commands.notifications, 'error', 'The canvas has no active document to generate from.');return;}const postFlushDocument = documentSnapshot.canvas.document;@@ -389,10 +370,12 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): PromisrequiredLayerIds.add(layer.id);}}- const capture = await deps.captureRasterSnapshot(documentSnapshot, [...requiredLayerIds], { signal: deps.signal });+ const capture = await deps.captureCompositeTransaction(documentSnapshot, [...requiredLayerIds], {+ signal: deps.signal,+ });if (capture.status !== 'ok') {recordNotice(- dispatch,+ commands.notifications,'error',capture.status === 'stale'? 'The canvas changed while generation was being prepared. Please invoke again.'@@ -400,40 +383,27 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis);return;}- rasterSnapshot = capture.snapshot;- const canvasSnapshot = rasterSnapshot.canvas;- const getLayerSurface = (layerId: string) => {- const detached = rasterSnapshot?.layerSurfaces.get(layerId);- if (!detached) {- return Promise.reject(new Error(`Canvas raster snapshot is missing layer ${layerId}.`));- }- return Promise.resolve(detached);- };- const transactionDedupe: CompositeDedupeCache = {- byHash: new Map(deps.dedupe.byHash),- byKey: new Map(deps.dedupe.byKey),- };+ transaction = capture.transaction;+ const canvasSnapshot = transaction.canvas;// Bounds-only pre-pass (pure geometry, no upload): content that does not// overlap the bbox is txt2img no matter the coverage. Also naturally skips a// zero-area bbox (rectsIntersect is false), which validation rejects anyway.const contentBounds = computeCompositeContentBounds(plan);- const executorDeps = { ...deps.executorDeps, dedupe: transactionDedupe, getLayerSurface };-let mode: CanvasCompileMode = 'txt2img';let compositeImageName: string | null = null;let maskImageName: string | null = null;let noiseMaskImageName: string | null = null;if (contentBounds && rectsIntersect(contentBounds, bbox)) {- const result = await executeCompositePlan(plan, executorDeps);+ const result = await transaction.executePlan(plan);compositeImageName = result.base.imageName;// The grayscale denoise-limit mask (when enabled inpaint masks exist) both// decides inpaint-vs-img2img (its coverage) and feeds the graph. Legacy// parity: raster opaque + mask has content → inpaint; else img2img.const maskEntry = plan.entries.find((entry) => entry.kind === 'inpaint-mask');- const maskResult = maskEntry ? await executeMaskComposite(maskEntry, executorDeps) : null;+ const maskResult = maskEntry ? await transaction.executeMask(maskEntry) : null;const detected = detectCanvasMode({bbox,@@ -449,18 +419,18 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): PromismaskImageName = maskResult?.hasContent ? maskResult.imageName : null;const noiseEntry = plan.entries.find((entry) => entry.kind === 'noise-mask');if (noiseEntry) {- noiseMaskImageName = (await executeMaskComposite(noiseEntry, executorDeps)).imageName;+ noiseMaskImageName = (await transaction.executeMask(noiseEntry)).imageName;}}}// Control layers apply in every mode, independent of the base composite —// composite + resolve them regardless of whether raster content overlaps.- const controlLayers = await collectControlLayerInputs(postFlushDocument, bbox, model, deps.models, executorDeps);+ const controlLayers = await collectControlLayerInputs(postFlushDocument, bbox, model, deps.models, transaction);// Regional guidance also applies in every mode, independent of the base// composite — composite + resolve each region regardless of raster overlap.- const regionalGuidance = await collectRegionalGuidanceInputs(postFlushDocument, bbox, model, executorDeps);+ const regionalGuidance = await collectRegionalGuidanceInputs(postFlushDocument, bbox, model, transaction);const compiled = compileCanvasGraph({bbox,@@ -478,7 +448,7 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promisstrength: deps.strength,});- dispatch({+ commands.generation.submitCanvas({backendSupportsCancellation: true,destination: deps.destination,generate: {@@ -490,72 +460,18 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promisgraph: compiled.graph,canvas: canvasSnapshot,projectId,- type: 'submitCanvasInvocationSnapshot',});- for (const [key, value] of transactionDedupe.byHash) {- deps.dedupe.byHash.set(key, value);- }- for (const [key, value] of transactionDedupe.byKey) {- deps.dedupe.byKey.set(key, value);- }+ transaction.commit();} catch (error) {- recordNotice(dispatch, 'error', error instanceof Error ? error.message : String(error));+ recordNotice(commands.notifications, 'error', error instanceof Error ? error.message : String(error));} finally {- rasterSnapshot?.release();+ transaction?.release();inFlight.delete(projectId);}};-// ---- Command-layer wiring (per-engine caches + in-flight guard) ---------------/** The dedupe cache's per-map entry cap (bounds unbounded growth across invokes). */-const DEDUPE_CACHE_CAPACITY = 16;--/**- * A {@link Map} that evicts its oldest (insertion-order) entry once it exceeds- * `capacity`, so a long-lived dedupe cache can't grow without bound across many- * invokes with distinct plans/pixels.- */-class BoundedMap<K, V> extends Map<K, V> {- constructor(private readonly capacity: number) {- super();- }-- override set(key: K, value: V): this {- if (!this.has(key) && this.size >= this.capacity) {- const oldest = this.keys().next().value;- if (oldest !== undefined) {- this.delete(oldest);- }- }- return super.set(key, value);- }-}--/** A size-capped {@link CompositeDedupeCache}. */-export const createBoundedCompositeDedupeCache = (capacity = DEDUPE_CACHE_CAPACITY): CompositeDedupeCache => ({- byHash: new BoundedMap(capacity),- byKey: new BoundedMap(capacity),-});-// Project ids with a prepare in flight (survives across the async orchestrator).const inFlightProjects = new Set<string>();-type CanvasInvocationEngine = {- readonly document: CanvasDocumentCapability;- readonly exports: CanvasExportCapability;- readonly lifecycle: CanvasLifecycleCapability;-};-// Per-engine dedupe caches, dropped when the engine is disposed and GC'd.-const dedupeCachesByEngine = new WeakMap<CanvasInvocationEngine, CompositeDedupeCache>();--const getEngineDedupeCache = (engine: CanvasInvocationEngine): CompositeDedupeCache => {- let cache = dedupeCachesByEngine.get(engine);- if (!cache) {- cache = createBoundedCompositeDedupeCache();- dedupeCachesByEngine.set(engine, cache);- }- return cache;-};/** Arguments for the thin command-layer {@link prepareCanvasInvocation}. */export interface PrepareCanvasInvocationArgs {@@ -572,7 +488,7 @@ export interface PrepareCanvasInvocationArgs {* (`readCanvasCompositingSettings`). Falls back to legacy defaults when omitted.*/compositing?: CanvasCompositingSettings;- dispatch: (action: WorkbenchAction) => void;+ commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;}/**@@ -580,21 +496,20 @@ export interface PrepareCanvasInvocationArgs {* Fire-and-track: the caller does not await it (the Invoke command stays sync).*/export const prepareCanvasInvocation = async (args: PrepareCanvasInvocationArgs): Promise<void> => {- const engine = getEngine(args.projectId);+ const engine = getCanvasEngine(args.projectId);if (!engine) {- recordNotice(args.dispatch, 'error', 'Open the canvas before invoking it.');+ recordNotice(args.commands.notifications, 'error', 'Open the canvas before invoking it.');return;}+ const operations = getCanvasOperations(engine);await runCanvasInvocation({compositing: args.compositing ?? DEFAULT_CANVAS_COMPOSITING,- dedupe: getEngineDedupeCache(engine),destination: args.destination,- dispatch: args.dispatch,- executorDeps: engine.exports.getCompositeExecutorDeps(),+ commands: args.commands,captureDocumentSnapshot: () => engine.document.captureSnapshot(),- captureRasterSnapshot: (snapshot, layerIds, options) =>- engine.exports.captureRasterSnapshot(snapshot, layerIds, options),+ captureCompositeTransaction: (snapshot, layerIds, options) =>+ operations.captureCompositeTransaction(snapshot, layerIds, options),flushPendingUploads: () => engine.lifecycle.flushPendingUploads(),generateValues: args.generateValues,inFlight: inFlightProjects,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.tsindex e976c4e189..58fa0e6c1f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.ts@@ -5,8 +5,7 @@* so the candidate-vs-progress decision is unit-testable in node.*/-import type { StagedPreviewInput } from '@workbench/canvas-engine/engine';-import type { CanvasPlacementContract } from '@workbench/types';+import type { CanvasPlacementContract, StagedPreviewInput } from '@workbench/canvas-engine/api';/** Inputs to {@link selectStagedPreviewSource}. */export interface StagedPreviewSelection {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BboxOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BboxOptions.tsxindex 409dc58cea..2255b499df 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BboxOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BboxOptions.tsx@@ -1,8 +1,8 @@import type { SelectValueChangeDetails } from '@chakra-ui/react';import { createListCollection, HStack } from '@chakra-ui/react';-import { constrainBboxToRatio } from '@workbench/canvas-engine/tools/bboxHitTest';-import { Select, ToggleDot } from '@workbench/components/ui';+import { Select, ToggleDot } from '@platform/ui';+import { constrainBboxToRatio } from '@workbench/canvas-engine/api';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -62,10 +62,10 @@ export const BboxOptions = ({ engine }: ToolOptionsComponentProps) => {return;}if (preset.ratio === null) {- engine.stores.bboxOptions.set({ ...options, aspectLocked: false });+ engine.interaction.set('bboxOptions', { ...options, aspectLocked: false });return;}- engine.stores.bboxOptions.set({ aspectLocked: true, aspectRatio: preset.ratio });+ engine.interaction.set('bboxOptions', { aspectLocked: true, aspectRatio: preset.ratio });commitBbox(constrainBboxToRatio(bbox, preset.ratio, grid));},[bbox, commitBbox, engine, grid, options]@@ -79,7 +79,7 @@ export const BboxOptions = ({ engine }: ToolOptionsComponentProps) => {: options.aspectRatio > 0? options.aspectRatio: 1;- engine.stores.bboxOptions.set({ aspectLocked: checked, aspectRatio });+ engine.interaction.set('bboxOptions', { aspectLocked: checked, aspectRatio });},[bbox, engine, options.aspectRatio]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsxindex 6e393280f0..a89f0d32f3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx@@ -1,8 +1,8 @@import type { NumberInput as ChakraNumberInput, SliderValueChangeDetails } from '@chakra-ui/react';import { HStack, NumberInput } from '@chakra-ui/react';-import { MAX_BRUSH_SIZE, MIN_BRUSH_SIZE } from '@workbench/canvas-engine/engineStores';-import { ColorPicker, Slider, ToggleDot } from '@workbench/components/ui';+import { ColorPicker, Slider, ToggleDot } from '@platform/ui';+import { MAX_BRUSH_SIZE, MIN_BRUSH_SIZE } from '@workbench/canvas-engine/api';import { useBrushOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -31,7 +31,7 @@ export const BrushOptions = ({ engine }: ToolOptionsComponentProps) => {const numberInputValue = useMemo(() => String(Math.round(options.size)), [options.size]);const setSize = useCallback(- (size: number) => engine.stores.brushOptions.set({ ...options, size }),+ (size: number) => engine.interaction.set('brushOptions', { ...options, size }),[engine, options]);@@ -58,19 +58,19 @@ export const BrushOptions = ({ engine }: ToolOptionsComponentProps) => {({ value }: SliderValueChangeDetails) => {const next = value[0];if (next !== undefined && Number.isFinite(next)) {- engine.stores.brushOptions.set({ ...options, opacity: next / 100 });+ engine.interaction.set('brushOptions', { ...options, opacity: next / 100 });}},[engine, options]);const onColorChange = useCallback(- (hex: string) => engine.stores.brushOptions.set({ ...options, color: hex }),+ (hex: string) => engine.interaction.set('brushOptions', { ...options, color: hex }),[engine, options]);const onPressureToggle = useCallback(- (checked: boolean) => engine.stores.brushOptions.set({ ...options, pressureSensitivity: checked }),+ (checked: boolean) => engine.interaction.set('brushOptions', { ...options, pressureSensitivity: checked }),[engine, options]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/CanvasOperationBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/CanvasOperationBar.tsxindex 162ec837c6..265d81df70 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/CanvasOperationBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/CanvasOperationBar.tsx@@ -1,4 +1,4 @@-import type { CanvasOperationState } from '@workbench/canvas-operations/operationController';+import type { CanvasOperationState } from '@workbench/canvas-operations/api';import type { CanvasOperationUIEngine } from './operationUIEngine';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/EraserOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/EraserOptions.tsxindex 12c1c881d4..757a981f0d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/EraserOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/EraserOptions.tsx@@ -1,8 +1,8 @@import type { NumberInput as ChakraNumberInput, SliderValueChangeDetails } from '@chakra-ui/react';import { HStack, NumberInput } from '@chakra-ui/react';-import { MAX_BRUSH_SIZE, MIN_BRUSH_SIZE } from '@workbench/canvas-engine/engineStores';-import { Slider } from '@workbench/components/ui';+import { Slider } from '@platform/ui';+import { MAX_BRUSH_SIZE, MIN_BRUSH_SIZE } from '@workbench/canvas-engine/api';import { useEraserOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -27,7 +27,7 @@ export const EraserOptions = ({ engine }: ToolOptionsComponentProps) => {const numberInputValue = useMemo(() => String(Math.round(options.size)), [options.size]);const setSize = useCallback(- (size: number) => engine.stores.eraserOptions.set({ ...options, size }),+ (size: number) => engine.interaction.set('eraserOptions', { ...options, size }),[engine, options]);@@ -54,7 +54,7 @@ export const EraserOptions = ({ engine }: ToolOptionsComponentProps) => {({ value }: SliderValueChangeDetails) => {const next = value[0];if (next !== undefined && Number.isFinite(next)) {- engine.stores.eraserOptions.set({ ...options, opacity: next / 100 });+ engine.interaction.set('eraserOptions', { ...options, opacity: next / 100 });}},[engine, options]diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsxindex 47769d4b40..fe2bdb21c8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx@@ -1,15 +1,15 @@/* oxlint-disable react-perf/jsx-no-new-function-as-prop */-import type { FilterOperationSessionState } from '@workbench/canvas-operations/filterOperationSession';import { Flex, Group, HStack, IconButton, Menu, Portal, Text, VisuallyHidden } from '@chakra-ui/react';-import { getCanvasOperations } from '@workbench/canvas-operations/createCanvasEngine';-import { Button, MenuContent, Tooltip } from '@workbench/components/ui';-import { makeImageDurable } from '@workbench/gallery/api';+import { galleryDurability } from '@features/gallery';+import { Button, MenuContent, Tooltip } from '@platform/ui';import {buildFilterDefaults,+ getCanvasOperations,getFilterDefinition,isFilterConfigValid,-} from '@workbench/generation/canvas/filterGraphs';+ type FilterOperationSessionState,+} from '@workbench/canvas-operations/api';import { CanvasFloatingBar, CanvasFloatingBarDivider } from '@workbench/widgets/canvas/CanvasFloatingBar';import { useFilterSession } from '@workbench/widgets/canvas/engineStoreHooks';import { LayerFilterControls } from '@workbench/widgets/layers/LayerFilterControls';@@ -86,13 +86,13 @@ export const FilterOptionsBar = ({});};const setSettings = (settings: Record<string, unknown>) => {- const current = getCanvasOperations(engine).stores.filterSession.get();+ const current = getCanvasOperations(engine).getFilterSessionState();if (current) {getCanvasOperations(engine).updateFilterOperation({ settings, type: current.draft.type });}};const reset = () => {- const current = getCanvasOperations(engine).stores.filterSession.get();+ const current = getCanvasOperations(engine).getFilterSessionState();if (!current) {return;}@@ -170,7 +170,9 @@ export const FilterOptionsBar = ({loading={session.status === 'committing'}roundedEnd="none"size="xs"- onClick={() => void getCanvasOperations(engine).commitFilterOperation('apply', makeImageDurable)}+ onClick={() =>+ void getCanvasOperations(engine).commitFilterOperation('apply', galleryDurability.makeDurable)+ }>{t('common.apply')}</Button>@@ -194,14 +196,18 @@ export const FilterOptionsBar = ({<Menu.Itemdisabled={!saveTargetEligibility.raster}value="raster"- onClick={() => void getCanvasOperations(engine).commitFilterOperation('raster', makeImageDurable)}+ onClick={() =>+ void getCanvasOperations(engine).commitFilterOperation('raster', galleryDurability.makeDurable)+ }><Menu.ItemText>{t('widgets.layers.selectObject.saveAs_raster')}</Menu.ItemText></Menu.Item><Menu.Itemdisabled={!saveTargetEligibility.control}value="control"- onClick={() => void getCanvasOperations(engine).commitFilterOperation('control', makeImageDurable)}+ onClick={() =>+ void getCanvasOperations(engine).commitFilterOperation('control', galleryDurability.makeDurable)+ }><Menu.ItemText>{t('widgets.layers.selectObject.saveAs_control')}</Menu.ItemText></Menu.Item>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsxindex 7233a5810d..958ee5ccee 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx@@ -1,9 +1,8 @@import type { NumberInput as ChakraNumberInput, SelectValueChangeDetails } from '@chakra-ui/react';-import type { GradientStop, GradientToolOptions } from '@workbench/canvas-engine/engineStores';-import type { CanvasLayerSourceContract } from '@workbench/types';+import type { CanvasLayerSourceContract, GradientStop, GradientToolOptions } from '@workbench/canvas-engine/api';import { createListCollection, HStack, NumberInput, Text } from '@chakra-ui/react';-import { ColorPicker, Select } from '@workbench/components/ui';+import { ColorPicker, Select } from '@platform/ui';import { useGradientOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useCallback, useMemo } from 'react';@@ -88,7 +87,7 @@ export const GradientOptions = ({ engine }: ToolOptionsComponentProps) => {const applyGradient = useCallback((next: { kind: GradientKind; angle: number; stops: GradientStop[] }, commit: boolean) => {- engine.stores.gradientOptions.set({ angle: next.angle, kind: next.kind, stops: next.stops });+ engine.interaction.set('gradientOptions', { angle: next.angle, kind: next.kind, stops: next.stops });if (selected && commit) {const before = selected.source;const after: GradientSource = { ...before, angle: next.angle, kind: next.kind, stops: next.stops };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.test.tsxindex 1f87656704..49e493da70 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.test.tsx@@ -1,5 +1,6 @@+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';-import type { CanvasLayerContract, Project } from '@workbench/types';+import type { Project } from '@workbench/projectContracts';import type { ReactNode } from 'react';import { ChakraProvider } from '@chakra-ui/react';@@ -21,7 +22,7 @@ const { activeProject, buttons } = vi.hoisted(() => ({buttons: new Map<string, CapturedButton>(),}));-vi.mock('@workbench/components/ui', () => ({+vi.mock('@platform/ui', () => ({Button: (props: CapturedButton) => {buttons.set(String(props.children), props);return <button disabled={props.disabled}>{props.children}</button>;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsxindex b6443911e0..d6707d1e20 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx@@ -1,9 +1,8 @@-import type { CanvasCoreStoreCapability, CanvasSelectionCapability } from '@workbench/canvas-engine/api';-import type { SelectionOp } from '@workbench/canvas-engine/types';+import type { CanvasCoreStoreCapability, CanvasSelectionCapability, SelectionOp } from '@workbench/canvas-engine/api';import { HStack, Text } from '@chakra-ui/react';-import { isLayerPixelEditEligible } from '@workbench/canvas-engine/editing/controlPixelEdit';-import { Button } from '@workbench/components/ui';+import { Button } from '@platform/ui';+import { isLayerPixelEditEligible } from '@workbench/canvas-engine/api';import { useCanvasHasSelection, useLassoOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useCallback } from 'react';@@ -25,7 +24,7 @@ type LassoEngine = CanvasCoreStoreCapability & { readonly selection: CanvasSelec/** One op-mode button with a stable click handler (avoids a per-render closure in the map). */const OpModeButton = ({ engine, mode, active }: { engine: LassoEngine; mode: SelectionOp; active: boolean }) => {const { t } = useTranslation();- const onClick = useCallback(() => engine.stores.lassoOptions.set({ mode }), [engine, mode]);+ const onClick = useCallback(() => engine.interaction.set('lassoOptions', { mode }), [engine, mode]);return (<Button aria-pressed={active} size="xs" variant={active ? 'solid' : 'ghost'} onClick={onClick}>{t(OP_MODE_LABEL_KEYS[mode])}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationStatusSlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationStatusSlot.tsxindex 61d34810d0..661addbc4a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationStatusSlot.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationStatusSlot.tsx@@ -1,7 +1,7 @@import type { CSSProperties } from 'react';import { Flex, IconButton, Spinner } from '@chakra-ui/react';-import { Tooltip } from '@workbench/components/ui';+import { Tooltip } from '@platform/ui';import { InfoIcon } from 'lucide-react';const ERROR_CLAMP_STYLE: CSSProperties = {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsxindex 4b1fe052b2..46bac515a6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx@@ -1,11 +1,4 @@/* oxlint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { CanvasOperationCapability, SelectObjectSaveTarget } from '@workbench/canvas-operations/api';-import type {- SamSessionError,- SamSessionErrorCode,- SamSessionSnapshot,-} from '@workbench/canvas-operations/operationTypes';-import type { SamModel } from '@workbench/generation/canvas/samGraph';import type { ChangeEvent } from 'react';import {@@ -23,9 +16,17 @@ import {Text,VisuallyHidden,} from '@chakra-ui/react';-import { getCanvasOperations } from '@workbench/canvas-operations/createCanvasEngine';-import { Button, MenuContent, Tooltip } from '@workbench/components/ui';-import { isSamDocumentInputValid } from '@workbench/generation/canvas/samGraph';+import { Button, MenuContent, Tooltip } from '@platform/ui';+import {+ getCanvasOperations,+ isSamDocumentInputValid,+ type CanvasOperationCapability,+ type SamSessionError,+ type SamSessionErrorCode,+ type SamSessionSnapshot,+ type SamModel,+ type SelectObjectSaveTarget,+} from '@workbench/canvas-operations/api';import { CanvasFloatingBar, CanvasFloatingBarDivider } from '@workbench/widgets/canvas/CanvasFloatingBar';import { useSamSession } from '@workbench/widgets/canvas/engineStoreHooks';import { ChevronDownIcon, SettingsIcon } from 'lucide-react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsxindex ef7025156d..a54b872e46 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx@@ -1,10 +1,9 @@import type { NumberInput as ChakraNumberInput, SelectValueChangeDetails } from '@chakra-ui/react';-import type { ShapeToolOptions } from '@workbench/canvas-engine/engineStores';-import type { CanvasLayerSourceContract } from '@workbench/types';+import type { CanvasLayerSourceContract, ShapeToolOptions } from '@workbench/canvas-engine/api';import { createListCollection, HStack, NumberInput, Text } from '@chakra-ui/react';-import { MAX_SHAPE_STROKE_WIDTH } from '@workbench/canvas-engine/engineStores';-import { ColorPicker, Select, ToggleDot } from '@workbench/components/ui';+import { ColorPicker, Select, ToggleDot } from '@platform/ui';+import { MAX_SHAPE_STROKE_WIDTH } from '@workbench/canvas-engine/api';import { useShapeOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useCallback, useMemo } from 'react';@@ -77,7 +76,7 @@ export const ShapeOptions = ({ engine }: ToolOptionsComponentProps) => {*/const applyEdit = useCallback((patch: Partial<ShapeToolOptions>, commit: boolean) => {- engine.stores.shapeOptions.set({ fill, kind, stroke, strokeWidth, ...patch });+ engine.interaction.set('shapeOptions', { fill, kind, stroke, strokeWidth, ...patch });if (selected && commit) {const before = selected.source;const after: ShapeSource = { ...before, ...patch };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsxindex 5d36fcc194..350ff15ca3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx@@ -1,15 +1,14 @@import type { NumberInput as ChakraNumberInput, SelectValueChangeDetails } from '@chakra-ui/react';-import type { TextToolOptions } from '@workbench/canvas-engine/engineStores';-import type { CanvasLayerSourceContract } from '@workbench/types';+import type { CanvasLayerSourceContract, TextToolOptions } from '@workbench/canvas-engine/api';import { createListCollection, HStack, NumberInput } from '@chakra-ui/react';+import { ColorPicker, IconButton, Select } from '@platform/ui';import {MAX_TEXT_FONT_SIZE,MIN_TEXT_FONT_SIZE,TEXT_FONT_FAMILIES,TEXT_FONT_WEIGHTS,-} from '@workbench/canvas-engine/engineStores';-import { ColorPicker, IconButton, Select } from '@workbench/components/ui';+} from '@workbench/canvas-engine/api';import { useTextEditSession, useTextOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon } from 'lucide-react';@@ -134,7 +133,7 @@ export const TextOptions = ({ engine }: ToolOptionsComponentProps) => {*/const applyEdit = useCallback((patch: Partial<TextToolOptions>, commit: boolean) => {- engine.stores.textOptions.set({ align, color, fontFamily, fontSize, fontWeight, lineHeight, ...patch });+ engine.interaction.set('textOptions', { align, color, fontFamily, fontSize, fontWeight, lineHeight, ...patch });if (session) {engine.layers.updateTextEditStyle(patch);return;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsxindex cd67441158..18650e44a9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx@@ -1,5 +1,5 @@-import type { ToolId } from '@workbench/canvas-engine/types';-import type { CanvasOperationState } from '@workbench/canvas-operations/operationController';+import type { ToolId } from '@workbench/canvas-engine/api';+import type { CanvasOperationState } from '@workbench/canvas-operations/api';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { ComponentType } from 'react';@@ -23,7 +23,7 @@ import { TransformOptions } from './TransformOptions';export type CanvasToolOptionsEngine = Pick<CanvasEngineHandle,- 'document' | 'layers' | 'projectId' | 'selection' | 'stores' | 'tools' | 'viewport'+ 'document' | 'interaction' | 'layers' | 'projectId' | 'selection' | 'tools' | 'viewport'>;/** Props every per-tool options component receives — just the shared engine handle. */@@ -64,7 +64,7 @@ export const resolveCanvasOptionsContent = (* dimensions / zoom read-out on the right (absorbed from the former floating HUD).* Tool options read and write the engine's* transient option stores directly (`useBrushOptions` / `useEraserOptions` +- * `engine.stores.*.set(...)`) — there is no React state mirror. Positioned by+ * `engine.interaction.set(...)`) — there is no React state mirror. Positioned by* {@link CanvasWidgetView}; shares its look with the staging bar via* {@link CanvasFloatingBar}.*/diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TransformOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TransformOptions.tsxindex 1f8b35d89b..a5967357f4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TransformOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TransformOptions.tsx@@ -1,8 +1,8 @@import type { NumberInput as ChakraNumberInput } from '@chakra-ui/react';-import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';+import type { LayerTransform } from '@workbench/canvas-engine/api';import { HStack, NumberInput, Text } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';+import { Button } from '@platform/ui';import { useTransformSession } from '@workbench/widgets/canvas/engineStoreHooks';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/operationUIEngine.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/operationUIEngine.tsindex 9e84b09f25..f8bb7078d8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/operationUIEngine.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/operationUIEngine.ts@@ -1,4 +1,4 @@import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';/** Narrow UI view of application-owned filter and Select Object coordination. */-export type CanvasOperationUIEngine = Pick<CanvasEngineHandle, 'projectId' | 'stores'>;+export type CanvasOperationUIEngine = Pick<CanvasEngineHandle, 'interaction' | 'projectId'>;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/useBboxEditor.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/useBboxEditor.tsindex ba0155949b..df522baba0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/useBboxEditor.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/useBboxEditor.ts@@ -1,7 +1,10 @@-import type { CanvasCoreStoreCapability, CanvasLayerCapability } from '@workbench/canvas-engine/api';-import type { Rect } from '@workbench/canvas-engine/types';--import { bboxEquals, roundBbox } from '@workbench/canvas-engine/tools/bboxHitTest';+import {+ bboxEquals,+ roundBbox,+ type CanvasCoreStoreCapability,+ type CanvasLayerCapability,+ type Rect,+} from '@workbench/canvas-engine/api';import { useBboxGrid, useBboxOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useCallback } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasEngine.tsindex 7af53db058..1e65bf301c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasEngine.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasEngine.ts@@ -1,61 +1,2 @@-/**- * Resolves the shared {@link CanvasEngine} for the active project.- *- * The engine is a per-project resource shared with the layers widget via the- * ref-counted {@link getOrCreateEngine | engine registry}. Acquisition and- * release are a genuine component-lifecycle concern keyed on the project id —- * the one place a `useEffect` is unavoidable here (there is no ref-callback for- * "this component"). The registry's grace-period disposal absorbs the- * mount/unmount churn (StrictMode double-mount, quick re-layout) so the same- * warm engine is handed back rather than rebuilt.- *- * Returns `null` for the first render (before the acquiring effect runs); the- * surface mounts once the engine is available, and its ref callback attaches- * then.- */--import type { ImageResolver } from '@workbench/canvas-engine/render/rasterizers';--import { canvasApplicationPort } from '@workbench/canvas-operations/applicationPort';-import { getOrCreateEngine, releaseEngine } from '@workbench/canvas-operations/engineRegistry';-import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';-import { getImageFullUrl } from '@workbench/gallery/api';-import { useActiveProjectId, useWorkbenchStore } from '@workbench/WorkbenchContext';-import { useEffect, useState } from 'react';--/** Registry-owned application engine handle; consumers narrow this to the capabilities they use. */-export type CanvasEngineHandle = ReturnType<typeof getOrCreateEngine>;--/** Fetches a persisted image asset to a `Blob` for the engine's rasterizers. */-const createImageResolver = (): ImageResolver => async (imageName, signal) => {- const response = await fetch(getImageFullUrl(imageName), { signal });- if (!response.ok) {- throw new Error(`Failed to load canvas image "${imageName}" (${response.status})`);- }- return response.blob();-};--/** Acquires (and releases) the active project's canvas engine. */-export const useCanvasEngine = (): CanvasEngineHandle | null => {- const store = useWorkbenchStore();- const projectId = useActiveProjectId();- const [engine, setEngine] = useState<CanvasEngineHandle | null>(null);-- useEffect(() => {- const acquired = getOrCreateEngine(projectId, {- getMainModelBase: () => canvasApplicationPort.getSelectedModelBase(store.getState(), projectId),- imageResolver: createImageResolver(),- mutationPort: createCanvasProjectMutationPort(store, projectId),- reportError: (report) => store.dispatch({ ...report, type: 'recordError' }),- });- // Surfacing an effect-acquired external resource is the one legitimate- // synchronous setState-in-effect: acquire/release must live in the effect- // (balanced ref-count, StrictMode-safe via the registry's grace period),- // and the surface can only attach once the handle reaches render.- // eslint-disable-next-line react/react-compiler- setEngine(acquired);- return () => releaseEngine(projectId);- }, [projectId, store]);-- return engine;-};+/** Canvas widget compatibility seam; engine ownership lives in the Canvas operations interface. */+export { type CanvasEngineHandle, useCanvasEngine } from '@workbench/canvas-operations/react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.tsindex f45c603b69..4ceb567f38 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts@@ -1,8 +1,8 @@import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';-import { saveCanvasToGallery, type CanvasGallerySaveRegion } from '@workbench/canvas-operations/saveCanvasToGallery';+import { saveCanvasToGallery, type CanvasGallerySaveRegion } from '@workbench/canvas-operations/api';import { useNotify } from '@workbench/useNotify';-import { useWorkbenchStore } from '@workbench/WorkbenchContext';+import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';import { useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -15,7 +15,8 @@ export const useCanvasGallerySave = (): { isSaving: boolean; save: (region: CanvasGallerySaveRegion) => Promise<void> } => {const { t } = useTranslation();const notify = useNotify();- const store = useWorkbenchStore();+ const queries = useWorkbenchQueries();+ const { gallery, notifications } = useWorkbenchCommands();const isSavingRef = useRef(false);const [isSaving, setIsSaving] = useState(false);@@ -25,7 +26,7 @@ export const useCanvasGallerySave = (return;}- const project = store.getSnapshot().activeProject;+ const project = queries.getSnapshot().activeProject;await withMatchingCanvasProject(engine, project.id, async (matchedEngine) => {isSavingRef.current = true;@@ -35,7 +36,7 @@ export const useCanvasGallerySave = (const result = await saveCanvasToGallery({ engine: matchedEngine, project, region });if (result.status === 'saved') {- store.dispatch({ projectId: project.id, type: 'touchGalleryImagesRefresh' });+ gallery.touchImages(project.id);notify.success(t('widgets.canvas.contextMenu.saved'),t('widgets.canvas.contextMenu.savedDescription', { name: result.imageName })@@ -48,14 +49,16 @@ export const useCanvasGallerySave = (notify.info(t('widgets.canvas.contextMenu.notReady'));}} catch (error: unknown) {- store.dispatch(getCanvasGallerySaveErrorAction(error, project.id, t('widgets.canvas.contextMenu.saveError')));+ notifications.reportError(+ getCanvasGallerySaveErrorAction(error, project.id, t('widgets.canvas.contextMenu.saveError'))+ );} finally {isSavingRef.current = false;setIsSaving(false);}});},- [engine, notify, store, t]+ [engine, gallery, notifications, notify, queries, t]);return { isSaving, save };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/zoomOptions.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/zoomOptions.tsindex 78e8db90cc..e3bce05911 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/zoomOptions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/zoomOptions.ts@@ -6,7 +6,7 @@* snapping always agree. No React, no side effects — unit-testable in node.*/-import { ZOOM_SNAP_CANDIDATES } from '@workbench/canvas-engine/math/snapping';+import { ZOOM_SNAP_CANDIDATES } from '@workbench/canvas-engine/api';/** Formats a zoom factor as a rounded whole-percent label (e.g. `1` → `"100%"`). */export const formatZoomPercent = (zoom: number): string => `${Math.round(zoom * 100)}%`;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsHeaderActions.tsxindex c5492af372..417d173923 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsHeaderActions.tsx@@ -1,5 +1,5 @@import { Badge } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';+import { Button } from '@platform/ui';import { clearProjectDiagnostics, useProjectDiagnostics } from '@workbench/diagnostics/logger';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { BugIcon } from 'lucide-react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsxindex dcf0e02273..f59e625988 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx@@ -1,8 +1,8 @@import type { DiagnosticEntry } from '@workbench/diagnostics/logger';-import type { WidgetViewProps } from '@workbench/types';+import type { WidgetViewProps } from '@workbench/widgetContracts';import { Badge, Box, HStack, Stack, Text } from '@chakra-ui/react';-import { Button, Panel } from '@workbench/components/ui';+import { Button, Panel } from '@platform/ui';import { clearProjectDiagnostics, useProjectDiagnostics } from '@workbench/diagnostics/logger';import { StatusWidgetChip } from '@workbench/widget-frame';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/implementation.tsnew file mode 100644index 0000000000..40c2934ec0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/implementation.ts@@ -0,0 +1,9 @@+import type { WidgetImplementation } from '@workbench/widgetContracts';++import { DiagnosticsHeaderActions } from './DiagnosticsHeaderActions';+import { DiagnosticsWidgetView } from './DiagnosticsWidgetView';++export const widgetImplementation = {+ headerActions: DiagnosticsHeaderActions,+ view: DiagnosticsWidgetView,+} satisfies WidgetImplementation;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/index.tsindex ce0f8e68a7..26564b37b8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/index.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/index.ts@@ -1,19 +1,15 @@-import type { WidgetManifest } from '@workbench/types';+import type { WidgetManifest } from '@workbench/widgetContracts';import { BugIcon } from 'lucide-react';-import { DiagnosticsHeaderActions } from './DiagnosticsHeaderActions';-import { DiagnosticsWidgetView } from './DiagnosticsWidgetView';-export const diagnosticsWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['bottom', 'right'],bottomPanel: 'expandable',failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },- headerActions: DiagnosticsHeaderActions,icon: BugIcon,id: 'diagnostics',label: (t) => t('widgets.labels.diagnostics'),+ load: () => import('./implementation').then((module) => module.widgetImplementation),version: 1,- view: DiagnosticsWidgetView,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsxdeleted file mode 100644index 033e2e09bd..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx+++ /dev/null@@ -1,282 +0,0 @@-/* eslint-disable react/react-compiler */-import type { GeneratedImageContract, WidgetViewProps } from '@workbench/types';--import { getGallerySettings, type GallerySettings } from '@workbench/gallery/settings';-import { useImageActions } from '@workbench/image-actions';-import { StatusWidgetChip } from '@workbench/widget-frame';-import { createGenerateFormValuesSelector } from '@workbench/widgets/generate/generateFormViewModel';-import {- useActiveProjectId,- useActiveProjectName,- useActiveProjectSelector,- useWidgetValuesSelector,- useWorkbenchDispatch,-} from '@workbench/WorkbenchContext';-import { areArraysEqual, createStableSelector } from '@workbench/workbenchSelectors';-import { ImageIcon } from 'lucide-react';-import { useCallback, useEffect, useMemo, useRef } from 'react';--import { GalleryPanelContent } from './GalleryPanelContent';-import {- getGalleryCompareImage,- getGalleryPage,- getGalleryProjectBoardId,- getGalleryImagesRefreshToken,- getGalleryRecentImagesKey,- getGalleryRefreshToken,- getGallerySearchTerm,- getGallerySelectedBoardId,- getGallerySelectedImageNames,- getGalleryStateView,- getGalleryTotalImages,- getGalleryView,-} from './galleryStateView';-import { GalleryWidgetContext, type GalleryWidgetContextValue } from './GalleryWidgetContext';-import { useGalleryActions } from './useGalleryActions';-import { GALLERY_PAGE_SIZE, useGalleryData } from './useGalleryData';--interface GalleryWidgetSelectedValues extends Record<string, unknown>, GallerySettings {- compareImage: GeneratedImageContract | null;- galleryImagesRefreshToken: string;- galleryPage: number;- galleryRefreshToken: string;- galleryTotalImages: number | null;- galleryView: ReturnType<typeof getGalleryView>;- projectBoardId: string | null;- recentImages: GeneratedImageContract[] | undefined;- searchTerm: string;- selectedBoardId: string;- selectedImageName: string | null;- selectedImageNames: string[];-}--const areGallerySettingsEqual = (left: GallerySettings, right: GallerySettings): boolean =>- left.boardOrderBy === right.boardOrderBy &&- left.boardOrderDir === right.boardOrderDir &&- left.imageDensityPercent === right.imageDensityPercent &&- left.imageOrderDir === right.imageOrderDir &&- left.paginationMode === right.paginationMode &&- left.showArchivedBoards === right.showArchivedBoards &&- left.showDateBoards === right.showDateBoards &&- left.showImageDimensions === right.showImageDimensions &&- left.showPendingItems === right.showPendingItems &&- left.starredFirst === right.starredFirst &&- left.thumbnailFit === right.thumbnailFit;--const areGalleryWidgetSelectedValuesEqual = (- left: GalleryWidgetSelectedValues,- right: GalleryWidgetSelectedValues-): boolean =>- left.compareImage === right.compareImage &&- left.galleryImagesRefreshToken === right.galleryImagesRefreshToken &&- left.galleryPage === right.galleryPage &&- left.galleryRefreshToken === right.galleryRefreshToken &&- left.galleryTotalImages === right.galleryTotalImages &&- left.galleryView === right.galleryView &&- left.projectBoardId === right.projectBoardId &&- left.recentImages === right.recentImages &&- left.searchTerm === right.searchTerm &&- left.selectedBoardId === right.selectedBoardId &&- left.selectedImageName === right.selectedImageName &&- areArraysEqual(left.selectedImageNames, right.selectedImageNames) &&- areGallerySettingsEqual(left, right);--const selectGalleryWidgetValues = createStableSelector(- (values: Record<string, unknown>): GalleryWidgetSelectedValues => {- const settings = getGallerySettings(values);-- return {- ...settings,- compareImage: getGalleryCompareImage(values),- galleryImagesRefreshToken: getGalleryImagesRefreshToken(values),- galleryPage: getGalleryPage(values),- galleryRefreshToken: getGalleryRefreshToken(values),- galleryTotalImages: getGalleryTotalImages(values),- galleryView: getGalleryView(values),- projectBoardId: getGalleryProjectBoardId(values),- recentImages: Array.isArray(values.recentImages) ? (values.recentImages as GeneratedImageContract[]) : undefined,- searchTerm: getGallerySearchTerm(values),- selectedBoardId: getGallerySelectedBoardId(values, []),- selectedImageName: typeof values.selectedImageName === 'string' ? values.selectedImageName : null,- selectedImageNames: getGallerySelectedImageNames(values),- };- },- areGalleryWidgetSelectedValuesEqual-);--const selectGenerateRecallValues = createGenerateFormValuesSelector();--export const shouldPublishGalleryTotal = ({- knownTotalImages,- lastPublishedTotal,- total,-}: {- knownTotalImages: number | null;- lastPublishedTotal: number | null;- total: number | null;-}): boolean =>- typeof total === 'number' && Number.isFinite(total) && total !== knownTotalImages && total !== lastPublishedTotal;--export const GalleryWidgetView = ({ presentation, region, runtime }: WidgetViewProps) => {- const dispatch = useWorkbenchDispatch();- const projectId = useActiveProjectId();- const galleryValues = useWidgetValuesSelector('gallery', selectGalleryWidgetValues);- const generateValues = useWidgetValuesSelector('generate', selectGenerateRecallValues);- const projectName = useActiveProjectName();- const queueItems = useActiveProjectSelector((project) => project.queue.items);- const galleryView = getGalleryView(galleryValues);- const searchTerm = getGallerySearchTerm(galleryValues);- const recentImagesKey = getGalleryRecentImagesKey(galleryValues);- const refreshToken = getGalleryRefreshToken(galleryValues);- const imageRefreshToken = getGalleryImagesRefreshToken(galleryValues);- const page = getGalleryPage(galleryValues);- const knownTotalImages = getGalleryTotalImages(galleryValues);- const settings = getGallerySettings(galleryValues);- const onError = useCallback(- (message: string) =>- dispatch({ area: 'gallery-data', message, namespace: 'gallery', projectId, type: 'recordError' }),- [dispatch, projectId]- );-- const data = useGalleryData({- galleryView,- imageRefreshToken,- onError,- page,- recentImagesKey,- refreshToken,- searchTerm,- selectedBoardId: getGallerySelectedBoardId(galleryValues, []),- settings,- });-- const { loadMore, patchImages, total } = data;- const selectedBoardId = getGallerySelectedBoardId(galleryValues, data.boards);- const gallery = getGalleryStateView(galleryValues, data.boards, data.images, data.isLoadingImages, queueItems);-- const onStarredChange = useCallback(- (imageNames: string[], starred: boolean) => {- patchImages((images) =>- images.map((image) => (imageNames.includes(image.imageName) ? { ...image, starred } : image))- );- },- [patchImages]- );-- const galleryImagesRef = useRef(gallery.images);- const selectedImageNameRef = useRef(gallery.selectedImageName);- const lastPublishedTotalRef = useRef<number | null>(null);- const knownTotalImagesRef = useRef(knownTotalImages);-- galleryImagesRef.current = gallery.images;- selectedImageNameRef.current = gallery.selectedImageName;- knownTotalImagesRef.current = knownTotalImages;-- // After a deletion that takes out the previewed image, move the selection to- // the image that now occupies the old index, else the one before it.- const onImagesDeleted = useCallback(- (imageNames: string[]) => {- const deletedNames = new Set(imageNames);- const images = galleryImagesRef.current;- const anchorName = selectedImageNameRef.current;-- if (!anchorName || !deletedNames.has(anchorName)) {- return;- }-- const anchorIndex = images.findIndex((image) => image.imageName === anchorName);-- if (anchorIndex === -1) {- return;- }-- const remaining = images.filter((image) => !deletedNames.has(image.imageName));- const remainingBeforeAnchor = images- .slice(0, anchorIndex)- .filter((image) => !deletedNames.has(image.imageName)).length;- const nextImage = remaining[remainingBeforeAnchor] ?? remaining[remainingBeforeAnchor - 1] ?? null;-- if (nextImage) {- dispatch({ image: nextImage, type: 'selectGalleryImage' });- }- },- [dispatch]- );-- const imageActions = useImageActions({- boards: data.boards,- dispatch,- generateValues,- onImagesDeleted,- onStarredChange,- projectId,- });-- const actions = useGalleryActions({- boards: data.boards,- dispatch,- loadMore,- projectBoardId: getGalleryProjectBoardId(galleryValues),- projectName,- selectedBoardId,- });-- const contextValue = useMemo<GalleryWidgetContextValue>(- () => ({ actions, gallery, imageActions, projectName, runtime }),- [actions, gallery, imageActions, projectName, runtime]- );-- const isWidePlacement = region === 'center' || (region === 'bottom' && presentation === 'expanded');-- // Publish the backend total into widget values so the manifest footer can- // render page navigation without its own fetch, and clamp the page when the- // query shrinks (e.g. after deletions).- //- // The effect reacts only to this instance's fetched `total` — the published- // state (`knownTotalImages`) is read through a ref on purpose. Several- // gallery views can be mounted at once (e.g. the bottom status chip plus an- // expanded gallery), and if each instance re-published whenever the shared- // state disagreed with its own in-flight total, two instances mid-refetch- // would dispatch in a loop until React aborts with "maximum update depth".- useEffect(() => {- if (typeof total !== 'number' || !Number.isFinite(total)) {- return;- }-- const lastPublishedTotal = lastPublishedTotalRef.current;-- lastPublishedTotalRef.current = total;-- if (- shouldPublishGalleryTotal({- knownTotalImages: knownTotalImagesRef.current,- lastPublishedTotal,- total,- })- ) {- dispatch({ totalImages: total, type: 'setGalleryPageInfo' });- }- }, [dispatch, total]);-- useEffect(() => {- if (settings.paginationMode !== 'paginated' || total === null) {- return;- }-- const maxPage = Math.max(0, Math.ceil(total / GALLERY_PAGE_SIZE) - 1);-- if (page > maxPage) {- dispatch({ page: maxPage, type: 'setGalleryPage' });- }- }, [dispatch, page, settings.paginationMode, total]);-- if (region === 'bottom' && presentation !== 'expanded') {- return <StatusWidgetChip icon={ImageIcon}>Gallery: {total ?? gallery.images.length}</StatusWidgetChip>;- }-- return (- <GalleryWidgetContext value={contextValue}>- <GalleryPanelContent layout={isWidePlacement ? 'wide' : 'stacked'} />- </GalleryWidgetContext>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/useGalleryData.ts b/invokeai/frontend/webv2/src/workbench/widgets/gallery/useGalleryData.tsdeleted file mode 100644index 9b858ec500..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/useGalleryData.ts+++ /dev/null@@ -1,283 +0,0 @@-/* eslint-disable react/react-compiler */-import type { GallerySettings } from '@workbench/gallery/settings';--import {- listGalleryBoards,- listGalleryDateBoards,- listGalleryImages,- type GalleryBoard,- type GalleryImage,- type GalleryView,-} from '@workbench/gallery/api';-import { useCallback, useEffect, useRef, useState } from 'react';--export const GALLERY_PAGE_SIZE = 60;--const GALLERY_CACHE_TTL_MS = 60_000;-const GALLERY_BOARDS_CACHE_LIMIT = 8;-const GALLERY_IMAGES_CACHE_LIMIT = 24;-const GALLERY_INFINITE_WINDOW_CACHE_LIMIT = 24;--interface CacheEntry<T> {- cachedAt: number;- value: T;-}--interface BoardsResult {- boards: GalleryBoard[];- key: string;-}--interface BackendImagesResult {- /** Query identity without the pagination window — results stay visible while the window changes. */- baseKey: string;- /** Full identity including the pagination window and refresh token. */- fetchKey: string;- images: GalleryImage[];- total: number;-}--const boardsCache = new Map<string, CacheEntry<GalleryBoard[]>>();-const imageResultByFetchKeyCache = new Map<string, CacheEntry<BackendImagesResult>>();-const imageResultByBaseKeyCache = new Map<string, CacheEntry<BackendImagesResult>>();-const infiniteWindowCache = new Map<string, number>();--const isCacheEntryFresh = <T>(entry: CacheEntry<T> | undefined): boolean =>- entry !== undefined && Date.now() - entry.cachedAt < GALLERY_CACHE_TTL_MS;--const setLimitedMapEntry = <T>(cache: Map<string, T>, key: string, value: T, limit: number): void => {- cache.delete(key);- cache.set(key, value);-- while (cache.size > limit) {- const oldestKey = cache.keys().next().value;-- if (oldestKey === undefined) {- return;- }-- cache.delete(oldestKey);- }-};--const cacheBoards = (key: string, boards: GalleryBoard[]): void => {- setLimitedMapEntry(boardsCache, key, { cachedAt: Date.now(), value: boards }, GALLERY_BOARDS_CACHE_LIMIT);-};--const cacheImageResult = (result: BackendImagesResult): void => {- const entry = { cachedAt: Date.now(), value: result };-- setLimitedMapEntry(imageResultByFetchKeyCache, result.fetchKey, entry, GALLERY_IMAGES_CACHE_LIMIT);- setLimitedMapEntry(imageResultByBaseKeyCache, result.baseKey, entry, GALLERY_IMAGES_CACHE_LIMIT);-};--const getCachedPageCount = (baseKey: string): number => Math.max(1, infiniteWindowCache.get(baseKey) ?? 1);--const cachePageCount = (baseKey: string, pageCount: number): void => {- setLimitedMapEntry(infiniteWindowCache, baseKey, Math.max(1, pageCount), GALLERY_INFINITE_WINDOW_CACHE_LIMIT);-};--export interface GalleryData {- boards: GalleryBoard[];- /** True while more items exist beyond the loaded infinite-scroll window. */- hasMore: boolean;- images: GalleryImage[] | null;- isLoadingImages: boolean;- /** Grow the infinite-scroll window by one page. No-op while fetching, when exhausted, or in paginated mode. */- loadMore: () => void;- /** Optimistically patch the currently loaded image list (e.g. star toggles). */- patchImages: (getImages: (images: GalleryImage[]) => GalleryImage[]) => void;- /** Backend total for the current query, or null while unknown. */- total: number | null;-}--export const useGalleryData = ({- galleryView,- imageRefreshToken,- onError,- page,- recentImagesKey,- refreshToken,- searchTerm,- selectedBoardId,- settings,-}: {- galleryView: GalleryView;- imageRefreshToken: string;- onError: (message: string) => void;- page: number;- recentImagesKey: string;- refreshToken: string;- searchTerm: string;- selectedBoardId: string;- settings: GallerySettings;-}): GalleryData => {- const {- boardOrderBy,- boardOrderDir,- imageOrderDir,- paginationMode,- showArchivedBoards,- showDateBoards,- starredFirst,- } = settings;- const boardsKey = [- String(showArchivedBoards),- boardOrderBy,- boardOrderDir,- String(showDateBoards),- refreshToken,- ].join('\0');- const cachedBoardsEntry = boardsCache.get(boardsKey);- const isBoardsCacheFresh = isCacheEntryFresh(cachedBoardsEntry);- const [boardsResult, setBoardsResult] = useState<BoardsResult | null>(() =>- cachedBoardsEntry ? { boards: cachedBoardsEntry.value, key: boardsKey } : null- );- const boards = boardsResult?.key === boardsKey ? boardsResult.boards : (cachedBoardsEntry?.value ?? []);- const boardId =- boards.length === 0 || boards.some((board) => board.id === selectedBoardId) ? selectedBoardId : 'none';- const baseKey = [galleryView, boardId, searchTerm.trim(), imageOrderDir, String(starredFirst)].join('\0');- const cachedPageCount = getCachedPageCount(baseKey);- const [infiniteWindow, setInfiniteWindow] = useState<{ baseKey: string; pageCount: number }>(() => ({- baseKey,- pageCount: cachedPageCount,- }));- const isPaginated = paginationMode === 'paginated';- const pageCount = infiniteWindow.baseKey === baseKey ? infiniteWindow.pageCount : cachedPageCount;- const offset = isPaginated ? page * GALLERY_PAGE_SIZE : 0;- const limit = isPaginated ? GALLERY_PAGE_SIZE : pageCount * GALLERY_PAGE_SIZE;- const fetchKey = [baseKey, String(offset), String(limit), imageRefreshToken, recentImagesKey].join('\0');- const exactCachedImageResultEntry = imageResultByFetchKeyCache.get(fetchKey);- const baseCachedImageResultEntry = imageResultByBaseKeyCache.get(baseKey);- const cachedImageResultEntry = exactCachedImageResultEntry ?? baseCachedImageResultEntry;- const isExactImageCacheFresh = isCacheEntryFresh(exactCachedImageResultEntry);- const [result, setResult] = useState<BackendImagesResult | null>(() => cachedImageResultEntry?.value ?? null);- const [loadingFetchKey, setLoadingFetchKey] = useState<string | null>(null);- const stateResult = result !== null && result.baseKey === baseKey ? result : null;- const visibleResult = exactCachedImageResultEntry?.value ?? stateResult ?? baseCachedImageResultEntry?.value ?? null;- const images = visibleResult !== null && visibleResult.baseKey === baseKey ? visibleResult.images : null;- const total = visibleResult !== null && visibleResult.baseKey === baseKey ? visibleResult.total : null;- const isLoadingImages = loadingFetchKey === fetchKey || (!isExactImageCacheFresh && result?.fetchKey !== fetchKey);- const hasMore = !isPaginated && total !== null && images !== null && images.length < total;- const hasMoreRef = useRef(hasMore);- const isLoadingRef = useRef(isLoadingImages);- const visibleResultRef = useRef(visibleResult);-- hasMoreRef.current = hasMore;- isLoadingRef.current = isLoadingImages;- visibleResultRef.current = visibleResult;-- useEffect(() => {- if (isBoardsCacheFresh) {- return;- }-- let isStale = false;-- Promise.all([- listGalleryBoards({ includeArchived: showArchivedBoards, orderBy: boardOrderBy, orderDir: boardOrderDir }),- showDateBoards ? listGalleryDateBoards() : Promise.resolve([]),- ])- .then(([backendBoards, dateBoards]) => {- if (!isStale) {- const nextBoards = [...backendBoards, ...dateBoards];-- cacheBoards(boardsKey, nextBoards);- setBoardsResult({ boards: nextBoards, key: boardsKey });- }- })- .catch((error: unknown) => {- onError(error instanceof Error ? error.message : String(error));- });-- return () => {- isStale = true;- };- }, [boardOrderBy, boardOrderDir, boardsKey, isBoardsCacheFresh, onError, showArchivedBoards, showDateBoards]);-- useEffect(() => {- if (isExactImageCacheFresh) {- return;- }-- let isStale = false;-- setLoadingFetchKey(fetchKey);- listGalleryImages({- boardId,- galleryView,- limit,- offset,- orderDir: imageOrderDir,- searchTerm,- starredFirst,- })- .then((backendPage) => {- if (!isStale) {- const nextResult = { baseKey, fetchKey, images: backendPage.images, total: backendPage.total };-- cacheImageResult(nextResult);- setResult(nextResult);- }- })- .catch((error: unknown) => {- if (!isStale) {- const fallbackResult = visibleResultRef.current?.baseKey === baseKey ? visibleResultRef.current : null;-- setResult(fallbackResult ? { ...fallbackResult, fetchKey } : { baseKey, fetchKey, images: [], total: 0 });- onError(error instanceof Error ? error.message : String(error));- }- })- .finally(() => {- if (!isStale) {- setLoadingFetchKey((currentFetchKey) => (currentFetchKey === fetchKey ? null : currentFetchKey));- }- });-- return () => {- isStale = true;- };- }, [- baseKey,- boardId,- fetchKey,- galleryView,- imageOrderDir,- isExactImageCacheFresh,- limit,- offset,- onError,- searchTerm,- starredFirst,- ]);-- const patchImages = useCallback((getImages: (images: GalleryImage[]) => GalleryImage[]) => {- const currentResult = visibleResultRef.current;-- if (currentResult === null) {- return;- }-- const nextResult = { ...currentResult, images: getImages(currentResult.images) };-- cacheImageResult(nextResult);- setResult(nextResult);- }, []);-- const loadMore = useCallback(() => {- if (!hasMoreRef.current || isLoadingRef.current) {- return;- }-- setInfiniteWindow((currentWindow) => {- const nextPageCount =- currentWindow.baseKey === baseKey ? currentWindow.pageCount + 1 : getCachedPageCount(baseKey) + 1;-- cachePageCount(baseKey, nextPageCount);-- return { baseKey, pageCount: nextPageCount };- });- }, [baseKey]);-- return { boards, hasMore, images, isLoadingImages, loadMore, patchImages, total };-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptHistoryNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptHistoryNavigation.tsdeleted file mode 100644index c86b6d76d1..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptHistoryNavigation.ts+++ /dev/null@@ -1,135 +0,0 @@-import type { GenerateModelConfig } from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';-import type { Project } from '@workbench/types';-import type { WorkbenchAction } from '@workbench/workbenchState';-import type { Dispatch } from 'react';--import { getPromptPolicy, isSupportedGenerateModel } from '@workbench/generation/baseGenerationPolicies';-import { normalizeGenerateSettings } from '@workbench/generation/settings';-import { getProjectWidgetValues } from '@workbench/widgetState';--import { isPositivePromptFocused } from './promptFocus';--type NavigationState = {- projectId: string;- historyIndex: number;- stashedPrompts: {- negativePrompt: string;- negativePromptEnabled: boolean;- positivePrompt: string;- };-};--let navigationState: NavigationState | null = null;--export const resetPromptHistoryNavigation = (): void => {- navigationState = null;-};--const getSelectedGenerateModel = (- settings: ReturnType<typeof normalizeGenerateSettings>,- models: readonly ModelConfig[] | undefined-): GenerateModelConfig | undefined => {- if (!settings || !models) {- return undefined;- }-- return models.filter(isSupportedGenerateModel).find((model) => model.key === settings.modelKey);-};--const applyPromptHistoryIndex = ({- dispatch,- models,- project,-}: {- dispatch: Dispatch<WorkbenchAction>;- models: readonly ModelConfig[] | undefined;- project: Project;-}): void => {- if (!navigationState) {- return;- }-- const prompt = project.promptHistory[navigationState.historyIndex];- const settings = normalizeGenerateSettings(getProjectWidgetValues(project, 'generate'));-- if (!prompt || !settings) {- return;- }-- const selectedModel = getSelectedGenerateModel(settings, models);- const promptPolicy = getPromptPolicy(selectedModel, settings);- const values: Record<string, unknown> = { positivePrompt: prompt.positivePrompt };-- if (promptPolicy.negativeVisible) {- values.negativePrompt = prompt.negativePrompt ?? '';- values.negativePromptEnabled = prompt.negativePrompt ? true : settings.negativePromptEnabled;- }-- dispatch({ projectId: project.id, type: 'patchWidgetValues', values, widgetId: 'generate' });-};--export const navigatePromptHistory = ({- direction,- dispatch,- models,- project,-}: {- direction: -1 | 1;- dispatch: Dispatch<WorkbenchAction>;- models: readonly ModelConfig[] | undefined;- project: Project;-}): void => {- if (navigationState?.projectId !== project.id) {- navigationState = null;- }-- if (!isPositivePromptFocused() || project.promptHistory.length === 0) {- return;- }-- const settings = normalizeGenerateSettings(getProjectWidgetValues(project, 'generate'));-- if (!settings) {- return;- }-- if (direction === -1) {- if (!navigationState) {- navigationState = {- historyIndex: 0,- projectId: project.id,- stashedPrompts: {- negativePrompt: settings.negativePrompt,- negativePromptEnabled: settings.negativePromptEnabled,- positivePrompt: settings.positivePrompt,- },- };- } else if (navigationState.historyIndex < project.promptHistory.length - 1) {- navigationState = { ...navigationState, historyIndex: navigationState.historyIndex + 1 };- }-- applyPromptHistoryIndex({ dispatch, models, project });- return;- }-- if (!navigationState) {- return;- }-- const nextHistoryIndex = navigationState.historyIndex - 1;-- if (nextHistoryIndex < 0) {- dispatch({- projectId: project.id,- type: 'patchWidgetValues',- values: navigationState.stashedPrompts,- widgetId: 'generate',- });- navigationState = null;- return;- }-- navigationState = { ...navigationState, historyIndex: nextHistoryIndex };- applyPromptHistoryIndex({ dispatch, models, project });-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsxindex 06971e4dc2..c6d4e32ce9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx@@ -1,11 +1,11 @@import type { SliderValueChangeDetails } from '@chakra-ui/react';-import type { CanvasAdjustmentsContract, CanvasRasterLayerContractV2 } from '@workbench/types';+import type { CanvasAdjustmentsContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/api';import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';import type { PointerEvent as ReactPointerEvent } from 'react';import { createListCollection, HStack, Stack, Text } from '@chakra-ui/react';-import { DEFAULT_ADJUSTMENTS, buildCurveLut } from '@workbench/canvas-engine/render/adjustments';-import { Button, Field, Select, Slider } from '@workbench/components/ui';+import { Button, Field, Select, Slider } from '@platform/ui';+import { DEFAULT_ADJUSTMENTS, buildCurveLut } from '@workbench/canvas-engine/api';import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsxindex 0f5a61fe24..2dd911f18f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx@@ -3,19 +3,23 @@ import type {SelectValueChangeDetails,SliderValueChangeDetails,} from '@chakra-ui/react';-import type { CanvasDocumentCapability } from '@workbench/canvas-engine/api';-import type { ControlAdapterKind } from '@workbench/generation/canvas/addControlLayers';-import type { CanvasControlAdapterContract, CanvasControlLayerContract } from '@workbench/types';+import type {+ CanvasControlAdapterContract,+ CanvasControlLayerContract,+ CanvasDocumentCapability,+} from '@workbench/canvas-engine/api';import type { LayerFilterOperationEngine } from '@workbench/widgets/layers/LayerFilterOperationButton';import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';import { createListCollection, HStack, NumberInput, Stack, Switch, Text } from '@chakra-ui/react';-import { getCanvasOperations } from '@workbench/canvas-operations/createCanvasEngine';-import { Field, Select, Slider } from '@workbench/components/ui';-import { isControlKindSupportedForBase } from '@workbench/generation/canvas/addControlLayers';-import { resolveDefaultFilterForModel } from '@workbench/generation/canvas/controlRecommendations';-import { getControlValidationReason } from '@workbench/generation/canvas/controlValidation';-import { useModelsSelector } from '@workbench/models/modelsStore';+import {+ getControlValidationReason,+ isControlKindSupportedForBase,+ type ControlAdapterKind,+} from '@features/generation/canvas';+import { useModelsSelector } from '@features/models';+import { Field, Select, Slider } from '@platform/ui';+import { getCanvasOperations, resolveDefaultFilterForModel } from '@workbench/canvas-operations/api';import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsxindex 6897fc3a6a..d3c7e4f757 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx@@ -1,9 +1,9 @@import type { SelectValueChangeDetails, SliderValueChangeDetails } from '@chakra-ui/react';-import type { CanvasInpaintMaskLayerContract, CanvasMaskFillContract } from '@workbench/types';+import type { CanvasInpaintMaskLayerContract, CanvasMaskFillContract } from '@workbench/canvas-engine/api';import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';import { createListCollection, HStack, Stack } from '@chakra-ui/react';-import { Button, ColorPicker, Field, Select, Slider } from '@workbench/components/ui';+import { Button, ColorPicker, Field, Select, Slider } from '@platform/ui';import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex f07aab7ca7..e011963696 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -1,21 +1,25 @@-import type { BooleanRasterOperation } from '@workbench/canvas-engine/engine';+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasMaskContract,+ BooleanRasterOperation,+ RegionalGuidanceReferenceImage,+} from '@workbench/canvas-engine/api';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { RegionalGuidanceReferenceImage } from '@workbench/generation/types';-import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasMaskContract } from '@workbench/types';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { LucideIcon } from 'lucide-react';import type { ComponentProps, Dispatch, ReactNode } from 'react';import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';-import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';-import { getCanvasOperations } from '@workbench/canvas-operations/createCanvasEngine';+import { galleryTransfers } from '@features/gallery';+import { IconButton, MenuContent, RenameDialog, Tooltip } from '@platform/ui';+import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/api';+import { getCanvasOperations } from '@workbench/canvas-operations/api';import { deleteLayerActions, duplicateLayerActions } from '@workbench/canvasLayerOps';-import { IconButton, MenuContent, RenameDialog, Tooltip } from '@workbench/components/ui';-import { uploadGalleryImage } from '@workbench/gallery/api';import { useNotify } from '@workbench/useNotify';import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';import { useCanvasDocumentEditingLocked, useLayerThumbnailVersion } from '@workbench/widgets/canvas/engineStoreHooks';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import {ArrowRightLeftIcon,ArrowUpDownIcon,@@ -28,7 +32,10 @@ import {import { Fragment, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-export type LayerContextMenuEngine = Pick<CanvasEngineHandle, 'exports' | 'layers' | 'projectId' | 'stores' | 'tools'>;+export type LayerContextMenuEngine = Pick<+ CanvasEngineHandle,+ 'exports' | 'interaction' | 'layers' | 'projectId' | 'tools'+>;import type {LayerContextMenuItem,@@ -202,7 +209,7 @@ const LayerMenu = ({showGroupLabels,}: LayerMenuProps) => {const { t } = useTranslation();- const workbenchDispatch = useWorkbenchDispatch();+ const { widgets } = useWorkbenchCommands();const notify = useNotify();const base = useSelectedModelBase();const workflowAvailability = useLayerWorkflowAvailability();@@ -462,7 +469,7 @@ const LayerMenu = ({throw makeStatusError(result.status);}const file = new File([result.blob], `layer-${layer.id}.png`, { type: result.blob.type || 'image/png' });- await uploadGalleryImage(file, 'none');+ await galleryTransfers.upload(file, 'none');}, [engine, layer.id, makeStatusError]);const handleCopyToClipboard = useCallback(async () => {@@ -514,10 +521,10 @@ const LayerMenu = ({const handleOpenProperties = useCallback((section: LayerPropertiesSection) => {- workbenchDispatch({ region: 'right', type: 'openRegionWidget', widgetId: 'layers' });+ widgets.open({ region: 'right', widgetId: 'layers' });requestLayerProperties(layer.id, section);},- [layer.id, workbenchDispatch]+ [layer.id, widgets]);const handleBooleanRaster = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.tsxindex 7f5cb01fc2..31e797788e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.tsx@@ -3,19 +3,19 @@ import type {SelectValueChangeDetails,SliderValueChangeDetails,} from '@chakra-ui/react';-import type { FilterParamSpec } from '@workbench/generation/canvas/filterGraphs';-import type { ModelConfig, ModelTaxonomyType } from '@workbench/models/types';+import type { ModelConfig, ModelTaxonomyType } from '@features/models';+import type { FilterParamSpec } from '@workbench/canvas-operations/api';import type { ChangeEvent } from 'react';import { Box, createListCollection, HStack, Input, NumberInput, Switch, Text } from '@chakra-ui/react';-import { Field, Select, Slider } from '@workbench/components/ui';+import { ModelSelect } from '@features/models/react';+import { Field, Select, Slider } from '@platform/ui';import {CONTROL_FILTERS,getFilterDefinition,getFilterNumberBounds,isSpandrelModelIdentifier,-} from '@workbench/generation/canvas/filterGraphs';-import { ModelSelect } from '@workbench/models/components/ModelSelect';+} from '@workbench/canvas-operations/api';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.test.tsxindex aa06a8cb68..2a97155b9f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.test.tsx@@ -1,5 +1,5 @@+import type * as WorkbenchUI from '@platform/ui';import type { StartFilterOperationResult } from '@workbench/canvas-operations/api';-import type * as WorkbenchUI from '@workbench/components/ui';import type { ReactNode } from 'react';import { ChakraProvider } from '@chakra-ui/react';@@ -31,7 +31,7 @@ const { captured, notifyError, thumbnailSubscription } = vi.hoisted(() => ({thumbnailSubscription: vi.fn(),}));-vi.mock('@workbench/components/ui', async (importOriginal) => {+vi.mock('@platform/ui', async (importOriginal) => {const actual = await importOriginal<typeof WorkbenchUI>();return {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.tsxindex ec17094be8..26146e1cf6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.tsx@@ -1,9 +1,9 @@+import type { CanvasControlLayerContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/api';import type { CanvasOperationCapability } from '@workbench/canvas-operations/api';-import type { CanvasControlLayerContract, CanvasRasterLayerContractV2 } from '@workbench/types';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import { Box } from '@chakra-ui/react';-import { Button, Tooltip } from '@workbench/components/ui';+import { Button, Tooltip } from '@platform/ui';import { useNotify } from '@workbench/useNotify';import { useLayerThumbnailVersion } from '@workbench/widgets/canvas/engineStoreHooks';import { useCallback } from 'react';@@ -16,7 +16,7 @@ import {runLayerFilterOperation,} from './layerPropertiesOperation';-export type LayerFilterOperationEngine = Pick<CanvasEngineHandle, 'exports' | 'projectId' | 'stores'>;+export type LayerFilterOperationEngine = Pick<CanvasEngineHandle, 'exports' | 'interaction' | 'projectId'>;interface LayerFilterOperationButtonProps {engine: LayerFilterOperationEngine | null;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationDelegation.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationDelegation.test.tsxindex bf6c1568d1..1ab4b84059 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationDelegation.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationDelegation.test.tsx@@ -1,5 +1,8 @@-import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';-import type { CanvasControlLayerContract, CanvasRasterLayerContractV2 } from '@workbench/types';+import type {+ CanvasControlLayerContract,+ CanvasEngine,+ CanvasRasterLayerContractV2,+} from '@workbench/canvas-engine/api';import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';@@ -17,8 +20,7 @@ interface SharedLaunchProps {operations: unknown;}-const { dispatch, operations, renderSharedLaunch } = vi.hoisted(() => ({- dispatch: vi.fn(),+const { operations, renderSharedLaunch } = vi.hoisted(() => ({operations: { startFilterOperation: vi.fn() },renderSharedLaunch: vi.fn(),}));@@ -33,17 +35,16 @@ vi.mock('./LayerFilterOperationButton', () => ({return <span>shared filter launch</span>;},}));-vi.mock('@workbench/canvas-operations/createCanvasEngine', () => ({+vi.mock('@workbench/canvas-operations/api', () => ({getCanvasOperations: () => operations,}));-vi.mock('@workbench/models/modelsStore', () => ({+vi.mock('@features/models', () => ({useModelsSelector: (selector: (snapshot: { models: never[] }) => unknown) => selector({ models: [] }),}));vi.mock('@workbench/WorkbenchContext', () => ({useActiveProjectId: () => 'project',useActiveProjectSelector: () => null,- useWorkbenchDispatch: () => dispatch,- useWorkbenchStore: () => ({ dispatch, getState: vi.fn() }),+ useWorkbenchCommands: () => ({ canvas: { apply: vi.fn() } }),}));vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsxindex 23177a8abb..b5165b8d7f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx@@ -1,6 +1,6 @@import type { DragEndEvent } from '@dnd-kit/core';+import type { CanvasLayerContract } from '@workbench/canvas-engine/api';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasLayerContract } from '@workbench/types';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { LucideIcon } from 'lucide-react';import type { Dispatch } from 'react';@@ -9,8 +9,8 @@ import { Collapsible, HStack, Icon, Stack, Text } from '@chakra-ui/react';import { closestCenter, DndContext, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiers';import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';-import { canMergeVisibleRasters } from '@workbench/canvas-engine/document/mergeVisible';-import { IconButton, toaster, Tooltip } from '@workbench/components/ui';+import { IconButton, toaster, Tooltip } from '@platform/ui';+import { canMergeVisibleRasters } from '@workbench/canvas-engine/api';import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';import { useActiveProjectName } from '@workbench/WorkbenchContext';import { ChevronDownIcon, EyeIcon, EyeOffIcon, FileDownIcon, LayersIcon, PlusIcon } from 'lucide-react';@@ -28,7 +28,7 @@ import { applyStructural } from './layerOps';import { getPsdExportNoticeKey } from './psdExportNotice';import { useAddLayer } from './useAddLayer';-type LayerGroupEngine = LayerListItemEngine & Pick<CanvasEngineHandle, 'exports' | 'layers' | 'stores'>;+type LayerGroupEngine = LayerListItemEngine & Pick<CanvasEngineHandle, 'exports' | 'interaction' | 'layers'>;const DND_MODIFIERS = [restrictToVerticalAxis, restrictToParentElement];const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 6 } } as const;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsxindex d8a2f84918..80ed22134f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx@@ -1,12 +1,12 @@+import type { CanvasLayerContract } from '@workbench/canvas-engine/api';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasLayerContract } from '@workbench/types';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { Dispatch, KeyboardEvent, MouseEvent } from 'react';import { Badge, Box, HStack, Input, Stack, Text } from '@chakra-ui/react';import { useSortable } from '@dnd-kit/sortable';import { CSS } from '@dnd-kit/utilities';-import { IconButton, Row, ToggleDot } from '@workbench/components/ui';+import { IconButton, Row, ToggleDot } from '@platform/ui';import { LockIcon, LockOpenIcon } from 'lucide-react';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsxindex 7ae0ccd5f3..f68adfb307 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsx@@ -1,10 +1,10 @@+import type { CanvasLayerContract } from '@workbench/canvas-engine/api';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasLayerContract } from '@workbench/types';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { Dispatch } from 'react';import { Box, Popover, Portal, Stack, Switch, Text } from '@chakra-ui/react';-import { IconButton } from '@workbench/components/ui';+import { IconButton } from '@platform/ui';import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { SlidersHorizontalIcon } from 'lucide-react';@@ -28,7 +28,7 @@ import { RegionalGuidanceSettings } from './RegionalGuidanceSettings';export type LayerPropertiesEngine = Pick<CanvasEngineHandle,- 'document' | 'exports' | 'layers' | 'projectId' | 'stores'+ 'document' | 'exports' | 'interaction' | 'layers' | 'projectId'>;const POPOVER_POSITIONING = { placement: 'left-start' } as const;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerThumbnail.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerThumbnail.tsxindex 1a149e144a..7c4c691977 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerThumbnail.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerThumbnail.tsx@@ -1,16 +1,19 @@/* oxlint-disable react-perf/jsx-no-new-function-as-prop -- the canvas ref callback is memoized on [engine, layerId, version]; it is intentionally re-created when the layer's thumbnail version bumps so the cache is re-blitted. */-import type { CanvasCoreStoreCapability, CanvasPreviewCapability } from '@workbench/canvas-engine/api';-import type { LayerThumbnailFallbackStage } from '@workbench/canvas-engine/render/thumbnail';-import type { CanvasLayerContract } from '@workbench/types';+import type {+ CanvasCoreStoreCapability,+ CanvasLayerContract,+ CanvasPreviewCapability,+ LayerThumbnailFallbackStage,+} from '@workbench/canvas-engine/api';import type { CSSProperties } from 'react';import { Box, Icon, IconButton } from '@chakra-ui/react';+import { galleryImages } from '@features/gallery';import {getLayerThumbnailFallbackRenderState,nextLayerThumbnailFallbackStage,resolveLayerThumbnailImageRef,-} from '@workbench/canvas-engine/render/thumbnail';-import { getImageFullUrl, getImageThumbnailUrl } from '@workbench/gallery/api';+} from '@workbench/canvas-engine/api';import { useLayerThumbnailStatus, useLayerThumbnailVersion } from '@workbench/widgets/canvas/engineStoreHooks';import { ImageOffIcon, RefreshCwIcon } from 'lucide-react';import { useCallback, useState } from 'react';@@ -82,8 +85,8 @@ const LayerThumbnailContent = ({const fallbackUrl =fallbackImage && fallbackStage !== 'failed'? fallbackStage === 'thumbnail'- ? getImageThumbnailUrl(fallbackImage.imageName)- : getImageFullUrl(fallbackImage.imageName)+ ? galleryImages.thumbnailUrl(fallbackImage.imageName)+ : galleryImages.fullUrl(fallbackImage.imageName): null;const { showFallback, showRetry } = getLayerThumbnailFallbackRenderState(drawn, fallbackStage, status === 'error');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersHeaderActions.tsxindex f287d4d10e..b938f500ce 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersHeaderActions.tsx@@ -1,7 +1,7 @@import type { LucideIcon } from 'lucide-react';import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';-import { IconButton, MenuContent } from '@workbench/components/ui';+import { IconButton, MenuContent } from '@platform/ui';import {BrushIcon,ImagePlusIcon,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsxindex 5b45cd4818..db0bc48445 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx@@ -3,13 +3,15 @@ import type {SelectValueChangeDetails,SliderValueChangeDetails,} from '@chakra-ui/react';+import type { CanvasBlendMode, CanvasLayerContract, CanvasMaskFillContract } from '@workbench/canvas-engine/api';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasBlendMode, CanvasLayerContract, CanvasMaskFillContract } from '@workbench/types';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { Dispatch } from 'react';import { Box, createListCollection, Flex, HStack, NumberInput, Stack } from '@chakra-ui/react';-import { ColorPicker, Field, Select, Slider } from '@workbench/components/ui';+import { useDebouncedDraftValue } from '@features/generation/draft-values';+import { useRegisterGenerateDraftFlusher } from '@features/generation/drafts';+import { ColorPicker, Field, Select, Slider } from '@platform/ui';import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';import {@@ -20,17 +22,15 @@ import {readCanvasDenoisingStrength,} from '@workbench/widgets/canvas/invoke/canvasStrength';import { useCanvasEngine } from '@workbench/widgets/canvas/useCanvasEngine';-import { useRegisterGenerateDraftFlusher } from '@workbench/widgets/generate/generateDraftRegistry';-import { useDebouncedDraftValue } from '@workbench/widgets/generate/useDebouncedDraftValue';import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { DenoisingStrengthWave } from './DenoisingStrengthWave';import { applyStructural, applyStructuralPreview, CANVAS_BLEND_MODES } from './layerOps';-type LayersPanelHeaderEngine = Pick<CanvasEngineHandle, 'layers' | 'stores'>;+type LayersPanelHeaderEngine = Pick<CanvasEngineHandle, 'interaction' | 'layers'>;const STRENGTH_DEBOUNCE_MS = 250;const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: true } as const;@@ -357,19 +357,15 @@ const selectCanvasStrength = (project: Parameters<typeof getProjectWidgetValues>const DenoisingStrengthControl = () => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();+ const { widgets } = useWorkbenchCommands();const projectId = useActiveProjectSelector((project) => project.id);const strength = useActiveProjectSelector(selectCanvasStrength);const commitStrength = useCallback((value: number) => {- dispatch({- type: 'patchWidgetValues',- values: { [CANVAS_DENOISING_STRENGTH_KEY]: clampCanvasDenoisingStrength(value) },- widgetId: 'canvas',- });+ widgets.patchValues('canvas', { [CANVAS_DENOISING_STRENGTH_KEY]: clampCanvasDenoisingStrength(value) });},- [dispatch]+ [widgets]);const {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RasterLayerFilterSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RasterLayerFilterSection.tsxindex 80d058a205..7f1931d55f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RasterLayerFilterSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RasterLayerFilterSection.tsx@@ -1,7 +1,7 @@-import type { CanvasRasterLayerContractV2 } from '@workbench/types';+import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/api';import type { LayerFilterOperationEngine } from '@workbench/widgets/layers/LayerFilterOperationButton';-import { getCanvasOperations } from '@workbench/canvas-operations/createCanvasEngine';+import { getCanvasOperations } from '@workbench/canvas-operations/api';import { LayerFilterOperationButton } from './LayerFilterOperationButton';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsxindex 43ce0bffc2..fb586419b3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx@@ -1,25 +1,26 @@import type { SelectValueChangeDetails, SliderValueChangeDetails } from '@chakra-ui/react';+import type { ModelConfig } from '@features/models';import type {- IPAdapterMethod,+ CanvasMaskContract,+ CanvasMaskFillContract,+ CanvasRegionalGuidanceLayerContract,+ RegionalGuidanceIPAdapterMethod,RegionalGuidanceReferenceImage,RegionalGuidanceReferenceImageAsset,-} from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';-import type { CanvasMaskContract, CanvasMaskFillContract, CanvasRegionalGuidanceLayerContract } from '@workbench/types';+} from '@workbench/canvas-engine/api';import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';import type { ChangeEvent, CSSProperties, FocusEvent, KeyboardEvent } from 'react';import { Box, createListCollection, HStack, IconButton, Input, Stack, Switch, Text } from '@chakra-ui/react';import { useDndMonitor, useDroppable } from '@dnd-kit/core';-import { Button, ColorPicker, Field, Select, Slider } from '@workbench/components/ui';-import { getGalleryImagesByNames, uploadGalleryImage } from '@workbench/gallery/api';-import { useModelsSelector } from '@workbench/models/modelsStore';+import { galleryImages, galleryTransfers } from '@features/gallery';+import { isGalleryImageDragData } from '@features/gallery/utility';+import { PROMPT_ATTENTION_TARGET_PROPS, PromptTextarea } from '@features/generation/prompt-ui';+import { FluxReduxControls } from '@features/generation/reference-ui';+import { useModelsSelector } from '@features/models';+import { Button, ColorPicker, Field, Select, Slider } from '@platform/ui';import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';-import { isGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';-import { PROMPT_ATTENTION_TARGET_PROPS } from '@workbench/widgets/generate/promptFields/promptAttentionHotkeys';-import { PromptTextarea } from '@workbench/widgets/generate/promptFields/PromptTextarea';-import { FluxReduxControls } from '@workbench/widgets/generate/reference-images/ReferenceImageControls';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { ImageIcon, PlusIcon, XIcon } from 'lucide-react';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -46,7 +47,7 @@ const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = ['vertical',];-const IP_ADAPTER_METHODS: readonly IPAdapterMethod[] = [+const IP_ADAPTER_METHODS: readonly RegionalGuidanceIPAdapterMethod[] = ['full','style','composition',@@ -88,7 +89,7 @@ interface RegionalGuidanceSettingsProps {export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettingsProps) => {const { t } = useTranslation();const dispatch = useCanvasProjectMutationDispatch();- const workbenchDispatch = useWorkbenchDispatch();+ const { gallery, notifications } = useWorkbenchCommands();const models = useModelsSelector((snapshot) => snapshot.models);const base = useSelectedModelBase();const showSyntaxHighlighting = useActiveProjectSelector((project) => project.settings.showPromptSyntaxHighlighting);@@ -263,19 +264,18 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettconst uploadReferenceImageAsset = useCallback(async (refId: string, file: File) => {try {- const uploaded = await uploadGalleryImage(file, 'none');+ const uploaded = await galleryTransfers.upload(file, 'none');setReferenceImageAsset(refId, uploaded);- workbenchDispatch({ type: 'touchGalleryImagesRefresh' });+ gallery.touchImages();} catch (error) {- workbenchDispatch({+ notifications.reportError({area: 'regional-guidance',message: error instanceof Error ? error.message : String(error),namespace: 'generation',- type: 'recordError',});}},- [setReferenceImageAsset, workbenchDispatch]+ [gallery, notifications, setReferenceImageAsset]);// A single monitor routes gallery-image drops to the region's ref slot the drop@@ -293,7 +293,7 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett}const refId = overId.slice(prefix.length);const [first] = data.images;- void getGalleryImagesByNames([first.imageName]).then((images) => {+ void galleryImages.resolveMany([first.imageName]).then((images) => {if (images[0]) {setReferenceImageAsset(refId, images[0]);}@@ -529,7 +529,7 @@ const ReferenceImageRow = ({if (config.type !== 'ip_adapter') {return;}- const method = value[0] as IPAdapterMethod | undefined;+ const method = value[0] as RegionalGuidanceIPAdapterMethod | undefined;if (method) {replaceRef({ ...referenceImage, config: { ...config, method } });}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.test.tsindex 8f9115ada3..c1e5296080 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.test.ts@@ -1,4 +1,4 @@-import type { WorkflowImageBinding } from '@workbench/workflows/layerWorkflow';+import type { WorkflowImageBinding } from '@features/workflow/graph';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsxindex e5d1e75e9e..8e53eafc6d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx@@ -1,15 +1,11 @@import type { SelectValueChangeDetails } from '@chakra-ui/react';+import type { ProjectGraphState } from '@features/workflow/contracts';import type { CanvasExportCapability, CanvasLayerCapability } from '@workbench/canvas-engine/api';-import type { ProjectGraphState } from '@workbench/workflows/types';import type { FormEvent } from 'react';import { chakra, createListCollection, Dialog, Portal, Stack, Text } from '@chakra-ui/react';-import { socketHub } from '@workbench/backend/socketHub';-import { runUtilityGraph } from '@workbench/canvas-operations/backend/utilityQueue';-import { Button, CloseButton, Field, Select } from '@workbench/components/ui';-import { getGalleryImageByName, makeImageDurable, saveImageToGallery } from '@workbench/gallery/api';-import { useNotify } from '@workbench/useNotify';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { galleryDurability, galleryImages } from '@features/gallery';+import { runUtilityGraph } from '@features/queue/utility';import {buildLayerWorkflowGraph,getDefaultLayerWorkflowSelection,@@ -20,8 +16,13 @@ import {type GetRunnableLayerWorkflowInputs,type LayerWorkflowSelection,type WorkflowImageBinding,-} from '@workbench/workflows/layerWorkflow';-import { useInvocationTemplatesSnapshot, type InvocationTemplatesSnapshot } from '@workbench/workflows/templates';+} from '@features/workflow/graph';+import { useInvocationTemplatesSnapshot, type InvocationTemplatesSnapshot } from '@features/workflow/react';+import { socketHub } from '@platform/transport/socketHub';+import { Button, CloseButton, Field, Select } from '@platform/ui';+import { getCanvasOperations } from '@workbench/canvas-operations/api';+import { useNotify } from '@workbench/useNotify';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -189,7 +190,7 @@ export const RunLayerWorkflowDialog = ({}: RunLayerWorkflowDialogProps) => {const { t } = useTranslation();const notify = useNotify();- const dispatch = useWorkbenchDispatch();+ const { canvas, gallery } = useWorkbenchCommands();const projectId = useActiveProjectSelector((project) => project.id);const [session] = useState(createLayerActionSession);const [selectionState, setSelectionState] = useState<SelectionState>(() => ({@@ -318,20 +319,22 @@ export const RunLayerWorkflowDialog = ({() => ({availability,close,- dispatch,+ canvas,engine,layerId,notify,+ gallery,projectId,selection,session,t,}),- [availability, close, dispatch, engine, layerId, notify, projectId, selection, session, t]+ [availability, canvas, close, engine, gallery, layerId, notify, projectId, selection, session, t]);const run = useCallback(async (): Promise<void> => {- const { availability, close, dispatch, engine, layerId, notify, projectId, selection, session, t } = runContext;+ const { availability, canvas, close, engine, gallery, layerId, notify, projectId, selection, session, t } =+ runContext;const { input, output } = selection;if (!engine || !input || !output) {@@ -349,31 +352,26 @@ export const RunLayerWorkflowDialog = ({setIsRunning(true);try {- const executorDeps = engine.exports.getCompositeExecutorDeps();+ const operations = getCanvasOperations(engine);const result = await runLayerWorkflow({deps: {appendStaging: (targetProjectId, candidate) =>- dispatch({ candidate, projectId: targetProjectId, type: 'appendCanvasStagingCandidate' }),+ canvas.appendStagingCandidate({ candidate, projectId: targetProjectId }),buildGraph: buildLayerWorkflowGraph,commitGenerated: (options) => engine.layers.commitGeneratedImageResult(options),createRequestId: () => crypto.randomUUID(),exportLayer: (targetLayerId) => engine.exports.exportBakedLayerBlob(targetLayerId, { includeDisabled: true }),- getImage: getGalleryImageByName,+ getImage: galleryImages.resolve,isGuardCurrent: (guard) => engine.exports.isLayerExportGuardCurrent(guard),- makeDurable: makeImageDurable,+ makeDurable: galleryDurability.makeDurable,runGraph: (options) => runUtilityGraph({ ...options, hub: socketHub }),- saveToGallery: saveImageToGallery,- touchGallery: (targetProjectId) =>- dispatch({ projectId: targetProjectId, type: 'touchGalleryImagesRefresh' }),- uploadIntermediate: async (blob, signal) => {- if (signal?.aborted) {- throw new DOMException('Layer workflow aborted', 'AbortError');- }- const uploaded = await executorDeps.uploadImage(blob);+ saveToGallery: galleryDurability.save,+ touchGallery: (targetProjectId) => gallery.touchImages(targetProjectId),+ uploadIntermediate: (blob, signal) => {if (signal?.aborted) {throw new DOMException('Layer workflow aborted', 'AbortError');}- return { imageName: uploaded.imageName };+ return operations.uploadIntermediate(blob, signal);},},destination,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.test.tsindex d33e766c0d..fcd1eddf69 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.test.ts@@ -1,4 +1,4 @@-import type { ModelConfig } from '@workbench/models/types';+import type { ModelConfig } from '@features/models';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.tsindex e3b3250861..fb78fe7fa9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.ts@@ -1,5 +1,5 @@-import type { ControlAdapterKind } from '@workbench/generation/canvas/controlValidation';-import type { ModelConfig } from '@workbench/models/types';+import type { ControlAdapterKind } from '@features/generation/canvas';+import type { ModelConfig } from '@features/models';export const getCompatibleControlModels = (models: readonly ModelConfig[],diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/curveEditorMath.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/curveEditorMath.test.tsindex 075f4affc2..c1d1f78e23 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/curveEditorMath.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/curveEditorMath.test.ts@@ -1,4 +1,4 @@-import type { CanvasAdjustmentsContract } from '@workbench/types';+import type { CanvasAdjustmentsContract } from '@workbench/canvas-engine/contracts';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/curveEditorMath.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/curveEditorMath.tsindex 75058957c6..daed6d6cf3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/curveEditorMath.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/curveEditorMath.ts@@ -1,4 +1,4 @@-import type { CanvasAdjustmentsContract } from '@workbench/types';+import type { CanvasAdjustmentsContract } from '@workbench/canvas-engine/api';export const CURVE_SIZE = 180;export const CURVE_PADDING = 6;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/implementation.tsnew file mode 100644index 0000000000..3348b9386f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/implementation.ts@@ -0,0 +1,9 @@+import type { WidgetImplementation } from '@workbench/widgetContracts';++import { LayersHeaderActions } from './LayersHeaderActions';+import { LayersWidgetView } from './LayersWidgetView';++export const widgetImplementation = {+ headerActions: LayersHeaderActions,+ view: LayersWidgetView,+} satisfies WidgetImplementation;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/index.tsindex 680ae2cf89..06bf4e8702 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/index.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/index.ts@@ -1,18 +1,14 @@-import type { WidgetManifest } from '@workbench/types';+import type { WidgetManifest } from '@workbench/widgetContracts';import { LayersIcon } from 'lucide-react';-import { LayersHeaderActions } from './LayersHeaderActions';-import { LayersWidgetView } from './LayersWidgetView';-export const layersWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['right'],failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },- headerActions: LayersHeaderActions,icon: LayersIcon,id: 'layers',label: (t) => t('widgets.labels.layers'),+ load: () => import('./implementation').then((module) => module.widgetImplementation),version: 1,- view: LayersWidgetView,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex b64a5f73b2..24f88f6a9d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -1,4 +1,8 @@-import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/types';+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasRasterLayerContractV2,+} from '@workbench/canvas-engine/contracts';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex 9b42b7d527..6659fbc4be 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -1,8 +1,11 @@-import type { BooleanRasterOperation } from '@workbench/canvas-engine/engine';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';+import type {+ BooleanRasterOperation,+ CanvasDocumentContractV2,+ CanvasLayerContract,+} from '@workbench/canvas-engine/api';import type { LucideIcon } from 'lucide-react';-import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';+import { getSourceContentRect } from '@workbench/canvas-engine/api';import {ArrowDownIcon,ArrowDownToLineIcon,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.tsindex b9ea945dfc..67770699bf 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts@@ -1,4 +1,8 @@-import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/types';+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasRasterLayerContractV2,+} from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.test.tsindex db1ea118b0..9ff001c918 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.test.ts@@ -2,7 +2,7 @@ import type {CanvasInpaintMaskLayerContract,CanvasLayerSourceContract,CanvasRasterLayerContractV2,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.tsindex b6ff82edd0..6c91dbd338 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.ts@@ -1,15 +1,4 @@-/**- * Pure logic for the layers-panel type-group header actions (round-3 restructure).- *- * Each type group renders a right-aligned action cluster. The set of actions per- * group is data (`getGroupActions`), so a new action — e.g. Task 44's PSD export —- * is added by extending one array, not by threading a new prop through the header.- * The visibility-toggle planning lives here as pure functions so it is- * unit-testable in node (no React, no engine); merge-visible planning lives in- * the engine's `document/mergeVisible` (shared with the engine op).- */--import type { CanvasLayerContract } from '@workbench/types';+import type { CanvasLayerContract } from '@workbench/canvas-engine/api';import type { LayerGroupKey } from './layerGroups';@@ -88,5 +77,4 @@ export const planGroupVisibilityToggle = (};// Merge-visible contributor selection lives in the engine's document layer-// (`@workbench/canvas-engine/document/mergeVisible`) so button enablement and-// execution use the same legacy-parity eligibility rules.+// Canvas execution uses the same legacy-parity eligibility rules.diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.test.tsindex 86fa892d3f..30ddfc6698 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.test.ts@@ -3,7 +3,7 @@ import type {CanvasInpaintMaskLayerContract,CanvasLayerContract,CanvasRegionalGuidanceLayerContract,-} from '@workbench/types';+} from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.tsindex 48fe10e9c7..482d07ec96 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.ts@@ -1,17 +1,4 @@-/**- * Pure grouping + within-group reorder mapping for the layers panel.- *- * The reducer keeps ONE z-ordered `layers` array (index 0 = top). The panel- * renders it as type groups (inpaint masks, regional guidance, control, raster- * — legacy display order), which are filtered *views* preserving each layer's- * global relative order. Reordering happens WITHIN a group only: moving layer A- * relative to same-group layer B rewrites A's slot in the GLOBAL array while- * every other layer stays put. Cross-group moves are rejected (null → no-op).- *- * Kept free of React / dnd-kit so the mapping is unit-testable in node.- */--import type { CanvasLayerContract } from '@workbench/types';+import type { CanvasLayerContract } from '@workbench/canvas-engine/api';import { moveItem } from './layersDnd';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.tsindex 9d1f7fbf69..c65934da8e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts@@ -1,5 +1,5 @@+import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/types';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.tsindex 199e67c370..81245209f9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts@@ -5,10 +5,6 @@* attached) or as a plain reducer dispatch (when it is not).*/-import type { CanvasLayerCapability } from '@workbench/canvas-engine/api';-import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { RegionalGuidanceReferenceImage } from '@workbench/generation/types';import type {CanvasBlendMode,CanvasControlLayerContract,@@ -16,18 +12,22 @@ import type {CanvasImageRef,CanvasInpaintMaskLayerContract,CanvasLayerBaseContract,+ CanvasLayerCapability,CanvasLayerContract,CanvasLayerSourceContract,CanvasMaskContract,CanvasMaskFillContract,CanvasRasterLayerContractV2,CanvasRegionalGuidanceLayerContract,-} from '@workbench/types';+ RegionalGuidanceReferenceImage,+ Rect,+} from '@workbench/canvas-engine/api';+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import type { Dispatch } from 'react';export type CanvasStructuralEngine = { readonly layers: CanvasLayerCapability };-import { getSourceContentRect, isMergeableRasterLayer } from '@workbench/canvas-engine/document/sources';+import { getSourceContentRect, isMergeableRasterLayer } from '@workbench/canvas-engine/api';import { CONTROL_ADAPTER_DEFAULTS } from '@workbench/controlAdapters';type LayerTransform = CanvasLayerBaseContract['transform'];diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.tsindex 83d8e31871..3a041f6a8a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.ts@@ -1,6 +1,6 @@-import type { CanvasLayerContract } from '@workbench/types';+import type { CanvasLayerContract } from '@workbench/canvas-engine/api';-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';export type LayerPropertiesSection = 'filter' | 'adjustments';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.test.tsindex 97342e4b10..8fd770f2b2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.test.ts@@ -1,8 +1,8 @@+import type { GalleryImage } from '@features/gallery';+import type { ProjectGraphState } from '@features/workflow/contracts';+import type { WorkflowImageBinding } from '@features/workflow/graph';+import type { InvocationTemplatesSnapshot } from '@features/workflow/react';import type { CommitGeneratedImageResult, LayerExportGuard } from '@workbench/canvas-engine/engine';-import type { GalleryImage } from '@workbench/gallery/api';-import type { WorkflowImageBinding } from '@workbench/workflows/layerWorkflow';-import type { InvocationTemplatesSnapshot } from '@workbench/workflows/templates';-import type { ProjectGraphState } from '@workbench/workflows/types';import { describe, expect, it, vi } from 'vitest';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.tsindex cd3e04c530..237cffaa6c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts@@ -1,22 +1,22 @@-import type {- CommitGeneratedImageOptions,- CommitGeneratedImageResult,- ExportBakedLayerBlobResult,- LayerExportGuard,-} from '@workbench/canvas-engine/engine';-import type { RunUtilityGraphOptions, UtilityGraphResult } from '@workbench/canvas-operations/backend/utilityQueue';-import type { GalleryImage } from '@workbench/gallery/api';-import type { CanvasStagingCandidateContract } from '@workbench/types';+import type { GalleryImage } from '@features/gallery';+import type { RunUtilityGraphOptions, UtilityGraphResult } from '@features/queue/utility';+import type { ProjectGraphState } from '@features/workflow/contracts';import type {BuildLayerWorkflowGraphOptions,BuiltLayerWorkflowGraph,LayerWorkflowDestination,WorkflowImageBinding,-} from '@workbench/workflows/layerWorkflow';-import type { InvocationTemplatesSnapshot } from '@workbench/workflows/templates';-import type { ProjectGraphState } from '@workbench/workflows/types';+} from '@features/workflow/graph';+import type { InvocationTemplatesSnapshot } from '@features/workflow/react';+import type {+ CanvasStagingCandidateContract,+ CommitGeneratedImageOptions,+ CommitGeneratedImageResult,+ ExportBakedLayerBlobResult,+ LayerExportGuard,+} from '@workbench/canvas-engine/api';-export type { LayerWorkflowDestination } from '@workbench/workflows/layerWorkflow';+export type { LayerWorkflowDestination } from '@features/workflow/graph';export type LayerWorkflowFailureStage =| 'export'diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectedModel.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectedModel.tsindex bcd3489d09..9b4ca55332 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectedModel.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectedModel.ts@@ -1,4 +1,4 @@-import type { Project } from '@workbench/types';+import type { Project } from '@workbench/projectContracts';import { getProjectWidgetValues } from '@workbench/widgetState';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsHeaderActions.tsxindex c4110ef46d..6c3bf3c69d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsHeaderActions.tsx@@ -1,21 +1,18 @@import { HStack } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';-import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { useCallback } from 'react';+import { Button } from '@platform/ui';+import { useWorkbenchCommands } from '@workbench/WorkbenchContext';import { useTranslation } from 'react-i18next';export const NotificationsHeaderActions = () => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();- const markAllRead = useCallback(() => dispatch({ type: 'markAllNotificationsRead' }), [dispatch]);- const clearNotifications = useCallback(() => dispatch({ type: 'clearNotifications' }), [dispatch]);+ const { notifications } = useWorkbenchCommands();return (<HStack gap="2">- <Button size="2xs" variant="outline" onClick={markAllRead}>+ <Button size="2xs" variant="outline" onClick={notifications.markAllRead}>{t('notifications.markRead')}</Button>- <Button size="2xs" variant="outline" onClick={clearNotifications}>+ <Button size="2xs" variant="outline" onClick={notifications.clear}>{t('common.clear')}</Button></HStack>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsxindex 38ab8a934a..7fd6c24252 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx@@ -1,4 +1,5 @@-import type { WidgetViewProps, WorkbenchNotificationKind } from '@workbench/types';+import type { WorkbenchNotificationKind } from '@workbench/projectContracts';+import type { WidgetViewProps } from '@workbench/widgetContracts';import { Badge, HStack, Icon, Stack, Text } from '@chakra-ui/react';import { StatusWidgetChip } from '@workbench/widget-frame';@@ -21,9 +22,9 @@ const kindIcon = {export const NotificationsWidgetView = ({ presentation, region }: WidgetViewProps) => {const { t } = useTranslation();const { errorCount, totalCount, unreadCount } = useWorkbenchSelector((snapshot) => ({- errorCount: snapshot.state.notifications.filter((notification) => notification.kind === 'error').length,- totalCount: snapshot.state.notifications.length,- unreadCount: snapshot.state.notifications.filter((notification) => !notification.isRead).length,+ errorCount: snapshot.notifications.filter((notification) => notification.kind === 'error').length,+ totalCount: snapshot.notifications.length,+ unreadCount: snapshot.notifications.filter((notification) => !notification.isRead).length,}));const label =unreadCount > 0@@ -40,7 +41,7 @@ export const NotificationsWidgetView = ({ presentation, region }: WidgetViewPropconst NotificationsPanel = () => {const { t } = useTranslation();- const notifications = useWorkbenchSelector((snapshot) => snapshot.state.notifications);+ const notifications = useWorkbenchSelector((snapshot) => snapshot.notifications);return (<Stack flex="1" gap="3" minH="0" p="2">diff --git a/invokeai/frontend/webv2/src/workbench/widgets/notifications/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/notifications/implementation.tsnew file mode 100644index 0000000000..c71feb6fd3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/notifications/implementation.ts@@ -0,0 +1,9 @@+import type { WidgetImplementation } from '@workbench/widgetContracts';++import { NotificationsHeaderActions } from './NotificationsHeaderActions';+import { NotificationsWidgetView } from './NotificationsWidgetView';++export const widgetImplementation = {+ headerActions: NotificationsHeaderActions,+ view: NotificationsWidgetView,+} satisfies WidgetImplementation;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/notifications/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/notifications/index.tsindex a979808c1e..fc77311f6f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/notifications/index.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/notifications/index.ts@@ -1,19 +1,15 @@-import type { WidgetManifest } from '@workbench/types';+import type { WidgetManifest } from '@workbench/widgetContracts';import { BellIcon } from 'lucide-react';-import { NotificationsHeaderActions } from './NotificationsHeaderActions';-import { NotificationsWidgetView } from './NotificationsWidgetView';-export const notificationsWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['bottom'],bottomPanel: 'expandable',failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },- headerActions: NotificationsHeaderActions,icon: BellIcon,id: 'notifications',label: (t) => t('widgets.labels.notifications'),+ load: () => import('./implementation').then((module) => module.widgetImplementation),version: 1,- view: NotificationsWidgetView,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsxindex 7f4bcedca6..eed028fd20 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx@@ -1,8 +1,8 @@-import type { GalleryImage } from '@workbench/gallery/api';+import type { GalleryImage } from '@features/gallery';import type { ImageActions } from '@workbench/image-actions';import { HStack, Icon } from '@chakra-ui/react';-import { IconButton, Tooltip } from '@workbench/components/ui';+import { IconButton, Tooltip } from '@platform/ui';import { CopyIcon, DownloadIcon, EllipsisVerticalIcon, ImagesIcon, StarIcon, type LucideIcon } from 'lucide-react';import { useCallback, type MouseEvent } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsxindex 1217412a14..26a00c4934 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsx@@ -1,10 +1,10 @@-/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { GeneratedImageContract, WidgetRuntimeApi } from '@workbench/types';+import type { GeneratedImageContract } from '@features/gallery';+import type { WidgetRuntimeApi } from '@workbench/widgetContracts';import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';import { createInstance } from 'i18next';-import { act, useState } from 'react';+import { act, useCallback, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -14,6 +14,16 @@ import type { PreviewComparisonMode } from './previewSettings';import { PreviewCompare } from './PreviewCompare';const i18n = createInstance();+const commandHandlers = new Map<string, () => void>();+const previewRuntime = {+ commands: {+ register: ({ handler, id }: { handler: () => void; id: string }) => {+ commandHandlers.set(id, handler);+ return () => commandHandlers.delete(id);+ },+ },+ hotkeys: { register: () => () => undefined },+} as unknown as WidgetRuntimeApi;void i18n.use(initReactI18next).init({fallbackLng: 'en',initImmediate: false,@@ -75,34 +85,26 @@ const renderComparison = async ({baseImage?: GeneratedImageContract;initialMode?: PreviewComparisonMode;} = {}) => {- const commandHandlers = new Map<string, () => void>();+ commandHandlers.clear();const onExit = vi.fn();const onModeChange = vi.fn();const onSwap = vi.fn();- const runtime = {- commands: {- register: ({ handler, id }: { handler: () => void; id: string }) => {- commandHandlers.set(id, handler);- return () => commandHandlers.delete(id);- },- },- hotkeys: { register: () => () => undefined },- } as unknown as WidgetRuntimeApi;const compareImage = createImage('compare', 800, 1200);const Harness = () => {const [mode, setMode] = useState(initialMode);+ const handleModeChange = useCallback((nextMode: PreviewComparisonMode) => {+ setMode(nextMode);+ onModeChange(nextMode);+ }, []);return (<PreviewComparebaseImage={baseImage}compareImage={compareImage}mode={mode}- runtime={runtime}+ runtime={previewRuntime}onExit={onExit}- onModeChange={(nextMode) => {- setMode(nextMode);- onModeChange(nextMode);- }}+ onModeChange={handleModeChange}onSwap={onSwap}/>);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsxindex 426be3e2d1..c809eeba8c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx@@ -1,7 +1,8 @@-import type { GeneratedImageContract, WidgetRuntimeApi } from '@workbench/types';+import type { GeneratedImageContract } from '@features/gallery';+import type { WidgetRuntimeApi } from '@workbench/widgetContracts';import { Badge, Box, Flex, HStack, SegmentGroup, Stack, type SystemStyleObject } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';+import { Button } from '@platform/ui';import { ArrowLeftRightIcon, XIcon } from 'lucide-react';import {useCallback,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.browser.test.tsxindex 81cb62bcbe..679cf5f6b6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.browser.test.tsx@@ -9,9 +9,9 @@ import {useSensors,type DragEndEvent,} from '@dnd-kit/core';+import { getGalleryImageDragData, getGalleryImageDragId } from '@features/gallery/utility';import { system } from '@theme/system';import { widgetCollisionDetection } from '@workbench/widgetDnd';-import { getGalleryImageDragData, getGalleryImageDragId } from '@workbench/widgets/gallery/galleryDnd';import { createInstance } from 'i18next';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsxindex a5f07043e3..6acd1131ec 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsx@@ -1,6 +1,6 @@import { Badge, Flex } from '@chakra-ui/react';import { useDndContext, useDroppable } from '@dnd-kit/core';-import { isGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';+import { isGalleryImageDragData } from '@features/gallery/utility';import { useTranslation } from 'react-i18next';import { PREVIEW_COMPARE_DROP_DATA, PREVIEW_COMPARE_DROP_ID } from './previewCompareDnd';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsxindex f16f0fbe52..3aea67e1ca 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx@@ -1,8 +1,8 @@-import type { GeneratedImageContract } from '@workbench/types';+import type { GeneratedImageContract } from '@features/gallery';import { Box, HStack, ScrollArea } from '@chakra-ui/react';import { useDraggable } from '@dnd-kit/core';-import { getGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';+import { getGalleryImageDragData } from '@features/gallery/utility';import { useCallback, useMemo } from 'react';import type { PreviewDensity } from './previewDensity';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsxindex a60e9fcea8..0d8adf0eac 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx@@ -1,9 +1,8 @@-import type { GalleryImage } from '@workbench/gallery/api';+import type { GalleryImage, GeneratedImageContract } from '@features/gallery';import type { ImageActions } from '@workbench/image-actions';-import type { GeneratedImageContract } from '@workbench/types';import { HStack, Stack, Text } from '@chakra-ui/react';-import { Button } from '@workbench/components/ui';+import { Button } from '@platform/ui';import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsxindex 0457e6534a..c2145ea36d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx@@ -1,10 +1,10 @@+import type { GalleryImageDragImage } from '@features/gallery/utility';/* eslint-disable react/react-compiler */-import type { StreamingImageSource } from '@workbench/images/streamingImageSource';-import type { GalleryImageDragImage } from '@workbench/widgets/gallery/galleryDnd';+import type { StreamingImageSource } from '@platform/ui/streaming-image/streamingImageSource';import { Badge, Box, Flex, type SystemStyleObject } from '@chakra-ui/react';import { useDraggable } from '@dnd-kit/core';-import { getGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';+import { getGalleryImageDragData } from '@features/gallery/utility';import { useCallback, useMemo, type CSSProperties, type MouseEvent, type ReactNode, type Ref } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsxindex 4e7d0acf51..444c27127f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx@@ -1,5 +1,5 @@/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { StreamingImageSource } from '@workbench/images/streamingImageSource';+import type { StreamingImageSource } from '@platform/ui/streaming-image/streamingImageSource';import { ChakraProvider } from '@chakra-ui/react';import {@@ -11,9 +11,9 @@ import {useSensors,type DragEndEvent,} from '@dnd-kit/core';+import { isGalleryImageDragData } from '@features/gallery/utility';import { system } from '@theme/system';import { widgetCollisionDetection } from '@workbench/widgetDnd';-import { isGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';import { createInstance } from 'i18next';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsxindex 5c0bf7b7ff..4ea0db77fc 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx@@ -1,10 +1,10 @@-import type { WidgetViewProps } from '@workbench/types';+import type { WidgetViewProps } from '@workbench/widgetContracts';import { Box, HStack, Icon } from '@chakra-ui/react';-import { useProgressImage } from '@workbench/backend/progressImageStore';-import { IconButton } from '@workbench/components/ui';+import { useProgressImage } from '@features/queue/react';+import { IconButton } from '@platform/ui';import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { GalleryThumbnailsIcon, HourglassIcon } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -27,23 +27,18 @@ export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {const isFilmstripVisible = useActiveProjectSelector((project) =>getPreviewFilmstripVisible(getProjectWidgetValues(project, 'preview')));- const dispatch = useWorkbenchDispatch();+ const { account, widgets } = useWorkbenchCommands();const label = showProgressImagesInViewer? t('widgets.preview.hideInProgressDiffusion'): t('widgets.preview.showInProgressDiffusion');const filmstripLabel = isFilmstripVisible ? t('widgets.preview.hideFilmstrip') : t('widgets.preview.showFilmstrip');const toggleProgressImages = useCallback(- () =>- dispatch({- settings: { showProgressImagesInViewer: !showProgressImagesInViewer },- type: 'setActiveProjectSettings',- }),- [dispatch, showProgressImagesInViewer]+ () => account.updateProjectPreferences({ showProgressImagesInViewer: !showProgressImagesInViewer }),+ [account, showProgressImagesInViewer]);const toggleFilmstrip = useCallback(- () =>- dispatch({ type: 'patchWidgetValues', values: { filmstripVisible: !isFilmstripVisible }, widgetId: 'preview' }),- [dispatch, isFilmstripVisible]+ () => widgets.patchValues('preview', { filmstripVisible: !isFilmstripVisible }),+ [isFilmstripVisible, widgets]);return (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewLiveReadout.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewLiveReadout.tsxindex 0048e3b11d..c0ca9e0feb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewLiveReadout.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewLiveReadout.tsx@@ -1,5 +1,5 @@import { Badge, Box, Text } from '@chakra-ui/react';-import { useQueueItemProgress, type QueueItemProgress } from '@workbench/backend/progressStore';+import { useQueueItemProgress, type QueueItemProgress } from '@features/queue/react';import { useMemo, type CSSProperties } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsxindex 4f5210a3e8..9a9d7895db 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx@@ -1,8 +1,8 @@-import type { GalleryImage, GalleryImageMetadata } from '@workbench/gallery/api';+import type { GalleryImage, GalleryImageMetadata } from '@features/gallery';import { Box, DataList, HStack, Icon, Stack, Text } from '@chakra-ui/react';-import { IconButton, Tooltip } from '@workbench/components/ui';-import { getGalleryImageMetadata } from '@workbench/gallery/api';+import { galleryImages } from '@features/gallery';+import { IconButton, Tooltip } from '@platform/ui';import {EMPTY_IMAGE_RECALL_CAPABILITIES,RecallActionButtons,@@ -56,7 +56,7 @@ export const PreviewMetadataPanel = ({let isStale = false;- Promise.all([getGalleryImageMetadata(image.imageName), actions.getImageRecallCapabilities(image)])+ Promise.all([galleryImages.metadata(image.imageName), actions.getImageRecallCapabilities(image)]).then(([metadata, capabilities]) => {if (!isStale) {setLoaded({ capabilities, imageName: image.imageName, metadata });diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetChrome.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetChrome.tsxindex 2c399141c2..0e5c931d6d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetChrome.tsx@@ -1,4 +1,4 @@-import type { WidgetLabelProps } from '@workbench/types';+import type { WidgetLabelProps } from '@workbench/widgetContracts';import { HStack, Text } from '@chakra-ui/react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex c362f710b3..cf2f8c1c67 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -1,40 +1,42 @@-/* eslint-disable react/react-compiler */-import type { GeneratedImageContract, WidgetViewProps } from '@workbench/types';+import type { WidgetViewProps } from '@workbench/widgetContracts';import { Box, Stack, Text } from '@chakra-ui/react';import { useDndMonitor, type DragEndEvent } from '@dnd-kit/core';-import { useProgressImage, type LatestProgressImageSnapshot } from '@workbench/backend/progressImageStore';-import { useRevealHold } from '@workbench/backend/revealHoldStore';import {- getGalleryImageByName,- listGalleryBoards,- listGalleryImages,+ galleryImages,type GalleryBoard,type GalleryImage,type GalleryView,-} from '@workbench/gallery/api';-import { getGallerySettings } from '@workbench/gallery/settings';+ type GeneratedImageContract,+} from '@features/gallery';+import {+ getGalleryCompareImage,+ getGalleryImagesRefreshToken,+ getGalleryRecentImagesKey,+ getGalleryRefreshToken,+ getGallerySettings,+} from '@features/gallery/contracts';+import { galleryBoardsOptions, galleryImagesOptions } from '@features/gallery/queries';+import { createGenerateFormValuesSelector } from '@features/generation/form';+import { useProgressImage, useRevealHold, type LatestProgressImageSnapshot } from '@features/queue/react';+import {+ imageUrlToStreamingSource,+ progressImageToStreamingSource,+} from '@platform/ui/streaming-image/streamingImageSource';+import { useStreamingImageSource } from '@platform/ui/streaming-image/useStreamingImageSource';+import { useQuery } from '@tanstack/react-query';import {ImageContextMenu,useImageActions,type ImageActions,type ImageContextMenuTarget,} from '@workbench/image-actions';-import { imageUrlToStreamingSource, progressImageToStreamingSource } from '@workbench/images/streamingImageSource';-import { useStreamingImageSource } from '@workbench/images/useStreamingImageSource';-import {- getGalleryCompareImage,- getGalleryImagesRefreshToken,- getGalleryRecentImagesKey,- getGalleryRefreshToken,-} from '@workbench/widgets/gallery/galleryStateView';-import { createGenerateFormValuesSelector } from '@workbench/widgets/generate/generateFormViewModel';import { getProjectWidgetValues } from '@workbench/widgetState';import {useActiveProjectId,useActiveProjectSelector,useWidgetValuesSelector,- useWorkbenchDispatch,+ useWorkbenchCommands,} from '@workbench/WorkbenchContext';import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState, type KeyboardEvent, type Ref } from 'react';import { useTranslation } from 'react-i18next';@@ -56,6 +58,7 @@ import {} from './previewSettings';type PreviewImage = GeneratedImageContract & Partial<Pick<GalleryImage, 'boardId' | 'imageCategory' | 'starred'>>;+const EMPTY_PREVIEW_IMAGES: PreviewImage[] = [];const fallbackBoards: GalleryBoard[] = [{ archived: false, assetCount: 0, id: 'none', imageCount: 0, kind: 'uncategorized', name: 'Uncategorized' },@@ -144,7 +147,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {(project) => project.settings);const progressImage = useProgressImage();- const dispatch = useWorkbenchDispatch();+ const { gallery, notifications, widgets } = useWorkbenchCommands();const { density, rootRef } = usePreviewDensity(region);const selectedImage = useMemo(() => getSelectedImage(galleryValues), [galleryValues]);const compareImage = getGalleryCompareImage(galleryValues);@@ -160,127 +163,46 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const boardRefreshToken = getGalleryRefreshToken(galleryValues);const imageRefreshToken = getGalleryImagesRefreshToken(galleryValues);const recentImagesKey = getGalleryRecentImagesKey(galleryValues);- const [boards, setBoards] = useState<GalleryBoard[]>(fallbackBoards);- const [boardImages, setBoardImages] = useState<PreviewImage[]>(localImages);- const [isLoadingBoard, setIsLoadingBoard] = useState(false);const { t } = useTranslation();- const selectedIndex = selectedImage- ? boardImages.findIndex((image) => image.imageName === selectedImage.imageName)- : -1;- const boardName = getBoardName(- boards,- displayBoardId,- t('widgets.gallery.uncategorized'),- t('widgets.gallery.unknownBoard')- );- const selectedImageRef = useRef(selectedImage);- const boardImagesRef = useRef(boardImages);const loupeControlsRef = useRef<PreviewLoupeControls | null>(null);- selectedImageRef.current = selectedImage;- boardImagesRef.current = boardImages;-const boardsRequestKey = getPreviewBoardsRequestKey({hasSelectedImage,isBackendImage,refreshToken: boardRefreshToken,});-- useEffect(() => {- if (boardsRequestKey === null) {- setBoards(fallbackBoards);- return;- }-- let isStale = false;-- listGalleryBoards()- .then((nextBoards) => {- if (!isStale) {- setBoards(nextBoards);- }- })- .catch(() => {- if (!isStale) {- setBoards(fallbackBoards);- }- });-- return () => {- isStale = true;- };- }, [boardsRequestKey]);-- // Deliberately NOT keyed on the selected image object or the gallery's- // board selection/sort: the board context only refetches when the image's- // own board, the view, the image ordering, or backend contents change.- useEffect(() => {- if (!hasSelectedImage) {- setBoardImages([]);- setIsLoadingBoard(false);- return;- }-- if (!isBackendImage) {- setBoardImages(localImages);- setIsLoadingBoard(false);- return;- }-- let isStale = false;-- setIsLoadingBoard(true);- listGalleryImages({+ const boardImagesRequestKey = `${imageBoardId}:${selectedGalleryView}:${imageOrderDir}:${starredFirst}:${imageRefreshToken}:${recentImagesKey}`;+ const boardsQuery = useQuery({+ ...galleryBoardsOptions({ revision: boardsRequestKey ?? undefined }),+ enabled: boardsRequestKey !== null,+ });+ const boardImagesQuery = useQuery({+ ...galleryImagesOptions({boardId: imageBoardId,galleryView: selectedGalleryView,orderDir: imageOrderDir,+ revision: boardImagesRequestKey,searchTerm: '',starredFirst,- })- .then((nextImagesPage) => {- if (isStale) {- return;- }-- const fallbackImage = selectedImageRef.current;-- setBoardImages(nextImagesPage.images.length ? nextImagesPage.images : fallbackImage ? [fallbackImage] : []);- })- .catch((error: unknown) => {- if (!isStale) {- dispatch({- area: 'preview-board-images',- message: error instanceof Error ? error.message : String(error),- namespace: 'gallery',- type: 'recordError',- });-- const fallbackImage = selectedImageRef.current;-- setBoardImages(fallbackImage ? [fallbackImage] : []);- }- })- .finally(() => {- if (!isStale) {- setIsLoadingBoard(false);- }- });-- return () => {- isStale = true;- };- }, [- dispatch,- hasSelectedImage,- imageBoardId,- imageOrderDir,- imageRefreshToken,- isBackendImage,- localImages,- recentImagesKey,- selectedGalleryView,- starredFirst,- ]);+ }),+ enabled: hasSelectedImage && isBackendImage,+ });+ const boards = boardsQuery.data ?? fallbackBoards;+ const boardImages = !hasSelectedImage+ ? EMPTY_PREVIEW_IMAGES+ : !isBackendImage+ ? localImages+ : (boardImagesQuery.data?.images ?? EMPTY_PREVIEW_IMAGES);+ const isLoadingBoard = isBackendImage && boardImagesQuery.isFetching;+ const selectedIndex = selectedImage+ ? boardImages.findIndex((image) => image.imageName === selectedImage.imageName)+ : -1;+ const boardName = getBoardName(+ boards,+ displayBoardId,+ t('widgets.gallery.uncategorized'),+ t('widgets.gallery.unknownBoard')+ );const selectByOffset = useCallback((offset: -1 | 1) => {@@ -291,45 +213,41 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const nextImage = boardImages[selectedIndex + offset];if (nextImage) {- dispatch({ image: nextImage, type: 'selectGalleryImage' });+ gallery.selectImage(nextImage);}},- [boardImages, dispatch, selectedIndex]+ [boardImages, gallery, selectedIndex]);const [contextMenuTarget, setContextMenuTarget] = useState<ImageContextMenuTarget | null>(null);- const onImagesDeleted = useCallback(- (imageNames: string[]) => {- const deletedNames = new Set(imageNames);- const images = boardImagesRef.current;- const anchorName = selectedImageRef.current?.imageName ?? null;+ const onImagesDeleted = useEffectEvent((imageNames: string[]) => {+ const deletedNames = new Set(imageNames);+ const images = boardImages;+ const anchorName = selectedImage?.imageName ?? null;- if (!anchorName || !deletedNames.has(anchorName)) {- return;- }+ if (!anchorName || !deletedNames.has(anchorName)) {+ return;+ }- const anchorIndex = images.findIndex((image) => image.imageName === anchorName);+ const anchorIndex = images.findIndex((image) => image.imageName === anchorName);- if (anchorIndex === -1) {- return;- }+ if (anchorIndex === -1) {+ return;+ }- const remaining = images.filter((image) => !deletedNames.has(image.imageName));- const remainingBeforeAnchor = images- .slice(0, anchorIndex)- .filter((image) => !deletedNames.has(image.imageName)).length;- const nextImage = remaining[remainingBeforeAnchor] ?? remaining[remainingBeforeAnchor - 1] ?? null;+ const remaining = images.filter((image) => !deletedNames.has(image.imageName));+ const remainingBeforeAnchor = images+ .slice(0, anchorIndex)+ .filter((image) => !deletedNames.has(image.imageName)).length;+ const nextImage = remaining[remainingBeforeAnchor] ?? remaining[remainingBeforeAnchor - 1] ?? null;- if (nextImage) {- dispatch({ image: nextImage, type: 'selectGalleryImage' });- }- },- [dispatch]- );+ if (nextImage) {+ gallery.selectImage(nextImage);+ }+ });const projectId = useActiveProjectId();const imageActions = useImageActions({boards,- dispatch,generateValues,onImagesDeleted,projectId,@@ -355,28 +273,24 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const isRevealHolding = useRevealHold();const shouldShowProgressImage =showProgressImagesInViewer && progressImage !== null && !isComparing && !isRevealHolding;- const exitCompare = useCallback(() => dispatch({ image: null, type: 'setGalleryCompareImage' }), [dispatch]);+ const exitCompare = useCallback(() => gallery.setCompareImage(null), [gallery]);const swapCompareImages = useCallback(() => {if (selectedImage && compareImage) {- dispatch({ image: compareImage, type: 'selectGalleryImage' });- dispatch({ image: selectedImage, type: 'setGalleryCompareImage' });+ gallery.selectImage(compareImage);+ gallery.setCompareImage(selectedImage);}- }, [compareImage, dispatch, selectedImage]);+ }, [compareImage, gallery, selectedImage]);const setComparisonMode = useCallback(- (comparisonMode: PreviewComparisonMode) =>- dispatch({ type: 'patchWidgetValues', values: { comparisonMode }, widgetId: 'preview' }),- [dispatch]+ (comparisonMode: PreviewComparisonMode) => widgets.patchValues('preview', { comparisonMode }),+ [widgets]);const isMetadataOpen = getPreviewMetadataOpen(previewValues);const toggleMetadata = useCallback(- () => dispatch({ type: 'patchWidgetValues', values: { metadataOpen: !isMetadataOpen }, widgetId: 'preview' }),- [dispatch, isMetadataOpen]+ () => widgets.patchValues('preview', { metadataOpen: !isMetadataOpen }),+ [isMetadataOpen, widgets]);const isFilmstripVisible = getPreviewFilmstripVisible(previewValues);- const selectImage = useCallback(- (image: GeneratedImageContract) => dispatch({ image, type: 'selectGalleryImage' }),- [dispatch]- );+ const selectImage = useCallback((image: GeneratedImageContract) => gallery.selectImage(image), [gallery]);// Drop-to-compare: any gallery-image drag dropped on the frame's drop zone// arms that image for comparison. The drag payload only carries names, so@@ -391,28 +305,26 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {// Prefer images we already hold (board context includes fresh local// generations that would 404 on a backend by-name fetch).const localImage =- boardImagesRef.current.find((image) => image.imageName === resolution.imageName) ??- (selectedImageRef.current?.imageName === resolution.imageName ? selectedImageRef.current : null);+ boardImages.find((image) => image.imageName === resolution.imageName) ??+ (selectedImage?.imageName === resolution.imageName ? selectedImage : null);if (localImage) {- dispatch({ image: localImage, type: 'setGalleryCompareImage' });+ gallery.setCompareImage(localImage);return;}- getGalleryImageByName(resolution.imageName)- .then((image) => dispatch({ image, type: 'setGalleryCompareImage' }))+ galleryImages+ .resolve(resolution.imageName)+ .then((image) => gallery.setCompareImage(image)).catch((error: unknown) => {- dispatch({+ notifications.reportError({area: 'preview-compare-drop',message: error instanceof Error ? error.message : String(error),namespace: 'gallery',- type: 'recordError',});});});- const onCompareDragEnd = useCallback((event: DragEndEvent) => handleCompareDrop(event), []);-- useDndMonitor({ onDragEnd: onCompareDragEnd });+ useDndMonitor({ onDragEnd: handleCompareDrop });const openImageContextMenu = useCallback((x: number, y: number) => {if (contextMenuImage) {@@ -461,8 +373,8 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {}if (commandId === 'viewer.swapImages' && selectedImage && compareImage) {- dispatch({ image: compareImage, type: 'selectGalleryImage' });- dispatch({ image: selectedImage, type: 'setGalleryCompareImage' });+ gallery.selectImage(compareImage);+ gallery.setCompareImage(selectedImage);return;}@@ -482,11 +394,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {}if (commandId === 'viewer.toggleFilmstrip') {- dispatch({- type: 'patchWidgetValues',- values: { filmstripVisible: !getPreviewFilmstripVisible(previewValues) },- widgetId: 'preview',- });+ widgets.patchValues('preview', { filmstripVisible: !getPreviewFilmstripVisible(previewValues) });}});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/implementation.tsnew file mode 100644index 0000000000..704abd0e35--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/implementation.ts@@ -0,0 +1,11 @@+import type { WidgetImplementation } from '@workbench/widgetContracts';++import { PreviewHeaderActions } from './PreviewHeaderActions';+import { PreviewWidgetLabel } from './PreviewWidgetChrome';+import { PreviewWidgetView } from './PreviewWidgetView';++export const widgetImplementation = {+ headerActions: PreviewHeaderActions,+ headerLabel: PreviewWidgetLabel,+ view: PreviewWidgetView,+} satisfies WidgetImplementation;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/index.tsindex ea84aef991..55a26a5a52 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/index.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/index.ts@@ -1,20 +1,14 @@-import type { WidgetManifest } from '@workbench/types';+import type { WidgetManifest } from '@workbench/widgetContracts';import { EyeIcon } from 'lucide-react';-import { PreviewHeaderActions } from './PreviewHeaderActions';-import { PreviewWidgetLabel } from './PreviewWidgetChrome';-import { PreviewWidgetView } from './PreviewWidgetView';-export const previewWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['center', 'right'],failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },- headerActions: PreviewHeaderActions,- headerLabel: PreviewWidgetLabel,icon: EyeIcon,id: 'preview',label: (t) => t('widgets.labels.preview'),+ load: () => import('./implementation').then((module) => module.widgetImplementation),version: 1,- view: PreviewWidgetView,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.test.tsindex 5170119f32..ddf5959844 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.test.ts@@ -1,4 +1,4 @@-import { getGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';+import { getGalleryImageDragData } from '@features/gallery/utility';import { describe, expect, it } from 'vitest';import { PREVIEW_COMPARE_DROP_DATA, resolvePreviewCompareDrop } from './previewCompareDnd';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.tsindex b3c354d299..ea5e634755 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.ts@@ -1,4 +1,4 @@-import { isGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';+import { isGalleryImageDragData } from '@features/gallery/utility';/*** dnd-kit contract for the preview's drop-to-compare target: dropping anydiff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewDensity.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewDensity.tsindex 0d6cefd246..9b19c27e17 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewDensity.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewDensity.ts@@ -1,4 +1,4 @@-import type { WorkbenchRegion } from '@workbench/types';+import type { WorkbenchRegion } from '@workbench/widgetContracts';import { useEffectEvent, useState, type Ref } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.tsindex 10489446a3..b4064f71b6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts@@ -1,7 +1,7 @@-import type { GalleryImage } from '@workbench/gallery/api';+import type { GalleryImage } from '@features/gallery';import type { ImageActions } from '@workbench/image-actions';-import { createExternalStore } from '@workbench/externalStore';+import { createExternalStore } from '@platform/state/externalStore';/*** Header context published by the preview view so the widget frame's chromediff --git a/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsxindex d167001559..775cb2770b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx@@ -1,15 +1,15 @@-import type { Project } from '@workbench/types';+import type { Project } from '@workbench/projectContracts';import { HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';-import { Button, IconButton, ConfirmDialog, Field, FieldLabel, Panel } from '@workbench/components/ui';+import { flushGenerateDrafts } from '@features/generation/drafts';+import { Button, IconButton, ConfirmDialog, Field, FieldLabel, Panel } from '@platform/ui';import { useProjectSyncSelector } from '@workbench/projects/syncStore';import { useProjectActions } from '@workbench/projects/useProjectActions';import { useNotify } from '@workbench/useNotify';-import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';import {shallowEqual,useActiveProjectSelector,- useWorkbenchDispatch,+ useWorkbenchCommands,useWorkbenchSelector,} from '@workbench/WorkbenchContext';import { ArrowRightIcon, CopyIcon, History as HistoryIcon, Trash2Icon } from 'lucide-react';@@ -55,17 +55,17 @@ type ProjectPanelViewModel = Pick<const NameSection = ({ project }: { project: ProjectPanelViewModel }) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();+ const { projects } = useWorkbenchCommands();const commitName = useCallback((value: string) => {const name = value.trim();if (name && name !== project.name) {- dispatch({ name, projectId: project.id, type: 'renameProject' });+ projects.rename(project.id, name);}},- [dispatch, project.id, project.name]+ [project.id, project.name, projects]);const handleBlur = useCallback((event: React.FocusEvent<HTMLInputElement>) => commitName(event.currentTarget.value),@@ -105,8 +105,8 @@ const formatTimestamp = (timestamp: string | undefined, unknownTime: string): stconst RecoverySection = ({ project }: { project: ProjectPanelViewModel }) => {const { t } = useTranslation();- const projects = useWorkbenchSelector((snapshot) => snapshot.state.projects);- const dispatch = useWorkbenchDispatch();+ const projects = useWorkbenchSelector((snapshot) => snapshot.projects);+ const { projects: projectCommands } = useWorkbenchCommands();const { deleteProject } = useProjectActions();const [deleteTarget, setDeleteTarget] = useState<Project | null>(null);const rootId = getRecoveryRootId(project);@@ -117,9 +117,9 @@ const RecoverySection = ({ project }: { project: ProjectPanelViewModel }) => {const handleOpenOriginal = useCallback(() => {if (original) {flushGenerateDrafts();- dispatch({ projectId: original.id, type: 'switchProject' });+ projectCommands.switchTo(original.id);}- }, [dispatch, original]);+ }, [original, projectCommands]);const handleCloseDeleteDialog = useCallback(() => setDeleteTarget(null), []);const handleConfirmDelete = useCallback(async () => {if (deleteTarget) {@@ -180,11 +180,11 @@ const RecoveryRow = ({onDelete: React.Dispatch<React.SetStateAction<Project | null>>;}) => {const { t } = useTranslation();- const dispatch = useWorkbenchDispatch();+ const { projects } = useWorkbenchCommands();const handleOpen = useCallback(() => {flushGenerateDrafts();- dispatch({ projectId: recovery.id, type: 'switchProject' });- }, [dispatch, recovery.id]);+ projects.switchTo(recovery.id);+ }, [projects, recovery.id]);const handleDelete = useCallback(() => onDelete(recovery), [onDelete, recovery]);return (@@ -222,8 +222,8 @@ const RecoveryRow = ({const DetailsSection = ({ project }: { project: ProjectPanelViewModel }) => {const { t } = useTranslation();- const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);- const lastSavedAt = useWorkbenchSelector((snapshot) => snapshot.state.autosave.lastSavedAt);+ const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.backendConnection.status);+ const lastSavedAt = useWorkbenchSelector((snapshot) => snapshot.autosave.lastSavedAt);const projectSync = useProjectSyncSelector((snapshot) => snapshot.projects[project.id]);const notify = useNotify();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/project/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/project/implementation.tsnew file mode 100644index 0000000000..57b9659113--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/project/implementation.ts@@ -0,0 +1,5 @@+import type { WidgetImplementation } from '@workbench/widgetContracts';++import { ProjectWidgetView } from './ProjectWidgetView';++export const widgetImplementation = { view: ProjectWidgetView } satisfies WidgetImplementation;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/project/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/project/index.tsindex 70eeaae357..5cab1253ba 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/project/index.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/project/index.ts@@ -1,9 +1,7 @@-import type { WidgetManifest } from '@workbench/types';+import type { WidgetManifest } from '@workbench/widgetContracts';import { FolderCogIcon } from 'lucide-react';-import { ProjectWidgetView } from './ProjectWidgetView';-export const projectWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['left', 'right'],@@ -11,6 +9,6 @@ export const projectWidgetManifest: WidgetManifest = {icon: FolderCogIcon,id: 'project',label: (t) => t('widgets.labels.project'),+ load: () => import('./implementation').then((module) => module.widgetImplementation),version: 1,- view: ProjectWidgetView,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueDataRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueDataRuntime.test.tsdeleted file mode 100644index 8111be0aa7..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueDataRuntime.test.ts+++ /dev/null@@ -1,151 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--const mocks = vi.hoisted(() => ({- clearAllProgress: vi.fn(),- clearProgress: vi.fn(),- setProgress: vi.fn(),- onConnectionChange: vi.fn(),- refreshModelCacheStats: vi.fn(),- refreshQueue: vi.fn(),- socketOn: vi.fn(),-}));--vi.mock('@workbench/backend/events', () => ({- isTerminalBackendStatus: (status: string) => status === 'completed' || status === 'failed' || status === 'canceled',-}));--vi.mock('@workbench/backend/itemProgressStore', () => ({- itemProgressStore: {- clear: mocks.clearProgress,- clearAll: mocks.clearAllProgress,- set: mocks.setProgress,- },-}));--vi.mock('@workbench/backend/socketHub', () => ({- socketHub: {- on: mocks.socketOn,- onConnectionChange: mocks.onConnectionChange,- },-}));--vi.mock('./modelCacheStore', () => ({- refreshModelCacheStats: mocks.refreshModelCacheStats,-}));--vi.mock('./queueDataStore', () => ({- ensureQueueLoaded: vi.fn(),- refreshQueue: mocks.refreshQueue,- setQueueScope: vi.fn(),- useCurrentBatchItems: vi.fn(() => []),- useQueueCounts: vi.fn(() => ({- canceled: 0,- completed: 0,- failed: 0,- in_progress: 0,- pending: 0,- queue_id: 'default',- total: 0,- })),- useRecentItems: vi.fn(() => []),-}));--vi.mock('@workbench/settings/store', () => ({- useWorkbenchPreferences: vi.fn(() => ({ queueJobsScope: 'all' })),-}));--vi.mock('@workbench/WorkbenchContext', () => ({- useOptionalWorkbenchSelector: vi.fn((_selector: unknown, fallback: unknown) => fallback),-}));--describe('QueueDataRuntime queue refresh events', () => {- beforeEach(() => {- mocks.clearAllProgress.mockReset();- mocks.clearProgress.mockReset();- mocks.onConnectionChange.mockReset();- mocks.refreshModelCacheStats.mockReset();- mocks.refreshQueue.mockReset();- mocks.setProgress.mockReset();- mocks.socketOn.mockReset();- mocks.socketOn.mockReturnValue(vi.fn());- mocks.onConnectionChange.mockReturnValue(vi.fn());- });-- it('refreshes queue data for all queue mutation socket events', async () => {- const { attachQueueDataRuntime } = await import('./QueueDataRuntime');-- attachQueueDataRuntime();-- const handlersByEvent = new Map<string, (payload: never) => void>(- mocks.socketOn.mock.calls.map((call) => [call[0] as string, call[1] as (payload: never) => void])- );-- handlersByEvent.get('batch_enqueued')?.({} as never);- handlersByEvent.get('queue_cleared')?.({} as never);- handlersByEvent.get('queue_items_retried')?.({} as never);-- expect(mocks.refreshQueue).toHaveBeenCalledTimes(3);- });-- it('stores live denoise preview images by backend queue item id', async () => {- const { attachQueueDataRuntime } = await import('./QueueDataRuntime');-- attachQueueDataRuntime();-- const handlersByEvent = new Map<string, (payload: never) => void>(- mocks.socketOn.mock.calls.map((call) => [call[0] as string, call[1] as (payload: never) => void])- );-- handlersByEvent.get('invocation_progress')?.({- image: { dataURL: 'data:image/png;base64,preview', height: 32, width: 64 },- item_id: 42,- message: 'Denoising',- percentage: 0.5,- } as never);-- expect(mocks.setProgress).toHaveBeenCalledWith(42, {- image: { dataUrl: 'data:image/png;base64,preview', height: 32, width: 64 },- message: 'Denoising',- percentage: 0.5,- });- });-- it('does not clear the last live preview when later invocations start for the same queue item', async () => {- const { attachQueueDataRuntime } = await import('./QueueDataRuntime');-- attachQueueDataRuntime();-- const handlersByEvent = new Map<string, (payload: never) => void>(- mocks.socketOn.mock.calls.map((call) => [call[0] as string, call[1] as (payload: never) => void])- );-- handlersByEvent.get('invocation_progress')?.({- image: { dataURL: 'data:image/png;base64,last-denoise', height: 32, width: 64 },- item_id: 42,- message: 'Denoising',- percentage: 1,- } as never);- handlersByEvent.get('invocation_started')?.({ item_id: 42 } as never);-- expect(mocks.setProgress).toHaveBeenLastCalledWith(42, {- message: '',- percentage: null,- });- });-- it('keeps completed item progress images until the refreshed queue item has a final result', async () => {- const { attachQueueDataRuntime } = await import('./QueueDataRuntime');-- attachQueueDataRuntime();-- const handlersByEvent = new Map<string, (payload: never) => void>(- mocks.socketOn.mock.calls.map((call) => [call[0] as string, call[1] as (payload: never) => void])- );-- handlersByEvent.get('queue_item_status_changed')?.({ item_id: 42, status: 'completed' } as never);- handlersByEvent.get('queue_item_status_changed')?.({ item_id: 43, status: 'failed' } as never);-- expect(mocks.clearProgress).not.toHaveBeenCalledWith(42);- expect(mocks.clearProgress).toHaveBeenCalledWith(43);- });-});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueDataRuntime.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueDataRuntime.tsxdeleted file mode 100644index 22e7593aff..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueDataRuntime.tsx+++ /dev/null@@ -1,102 +0,0 @@-import type {- InvocationProgressEvent,- InvocationStartedEvent,- QueueItemStatusChangedEvent,-} from '@workbench/backend/events';--import { isTerminalBackendStatus } from '@workbench/backend/events';-import { itemProgressStore } from '@workbench/backend/itemProgressStore';-import { socketHub } from '@workbench/backend/socketHub';-import { ConfirmDialog } from '@workbench/components/ui';-import { useEffect } from 'react';--import { refreshModelCacheStats } from './modelCacheStore';-import { clearQueueConfirmation, useQueueConfirmation } from './queueConfirmationStore';-import { ensureQueueLoaded, refreshQueue, setQueueScope } from './queueDataStore';-import { useQueueQueryScope } from './queueScope';--/**- * Singleton runtime for the Queue widget (mounted via `manifest.host`). It owns- * the live wiring: socket lifecycle events refresh the server-queue store and- * feed per-item progress, replacing the RTK Query tag-invalidation the legacy v6- * app used. Pure side effects — renders nothing.- */-export const attachQueueDataRuntime = (): (() => void) => {- ensureQueueLoaded();- void refreshModelCacheStats();-- const refresh = () => {- void refreshQueue();- };- const detachers = [- socketHub.on('queue_item_status_changed', (payload: never) => {- const event = payload as unknown as QueueItemStatusChangedEvent;-- if (isTerminalBackendStatus(event.status) && event.status !== 'completed') {- itemProgressStore.clear(event.item_id);- }-- refresh();- }),- socketHub.on('batch_enqueued', refresh),- socketHub.on('queue_cleared', refresh),- socketHub.on('queue_items_retried', refresh),- socketHub.on('invocation_started', (payload: never) => {- const event = payload as unknown as InvocationStartedEvent;- itemProgressStore.set(event.item_id, { message: '', percentage: null });- }),- socketHub.on('invocation_progress', (payload: never) => {- const event = payload as unknown as InvocationProgressEvent;- itemProgressStore.set(event.item_id, {- image: event.image?.dataURL- ? { dataUrl: event.image.dataURL, height: event.image.height, width: event.image.width }- : undefined,- message: event.message,- percentage: event.percentage,- });- }),- socketHub.on('model_load_complete', () => {- void refreshModelCacheStats();- }),- ];-- const detachConnection = socketHub.onConnectionChange((status) => {- if (status === 'connected') {- itemProgressStore.clearAll();- void refreshQueue();- void refreshModelCacheStats();- }- });-- return () => {- for (const detach of detachers) {- detach();- }-- detachConnection();- };-};--export const QueueDataRuntime = () => {- const scope = useQueueQueryScope();- const confirmation = useQueueConfirmation();-- useEffect(() => {- setQueueScope(scope);- }, [scope, scope.originPrefix]);-- useEffect(() => {- return attachQueueDataRuntime();- }, []);-- return confirmation ? (- <ConfirmDialog- body={confirmation.body}- confirmLabel={confirmation.confirmLabel}- isOpen={true}- title={confirmation.title}- onClose={clearQueueConfirmation}- onConfirm={confirmation.onConfirm}- />- ) : null;-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/currentBatchItems.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/currentBatchItems.tsdeleted file mode 100644index f494480517..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/currentBatchItems.ts+++ /dev/null@@ -1,40 +0,0 @@-import type { QueueServerItem } from './queueServerApi';--const isCurrentBatchStatus = (status: QueueServerItem['status']): boolean =>- status === 'pending' || status === 'in_progress';--export const getCurrentBatchItems = ({- current,- items,- next,-}: {- current: QueueServerItem | null;- items: QueueServerItem[];- next: QueueServerItem | null;-}): QueueServerItem[] => {- const batchId = current?.batch_id ?? next?.batch_id ?? null;-- if (!batchId) {- return [];- }-- const itemsById = new Map<number, QueueServerItem>();-- for (const item of [current, next, ...items]) {- if (item && item.batch_id === batchId && isCurrentBatchStatus(item.status)) {- itemsById.set(item.item_id, item);- }- }-- return [...itemsById.values()].sort((left, right) => {- if (left.status === 'in_progress' && right.status !== 'in_progress') {- return -1;- }-- if (left.status !== 'in_progress' && right.status === 'in_progress') {- return 1;- }-- return left.item_id - right.item_id;- });-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/index.tsdeleted file mode 100644index 34251c79eb..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/index.ts+++ /dev/null@@ -1,30 +0,0 @@-import type { WidgetManifest } from '@workbench/types';--import { ListOrderedIcon } from 'lucide-react';--import { ModelCacheFooter } from './ModelCacheFooter';-import { QueueDataRuntime } from './QueueDataRuntime';-import { QueueHeaderActions } from './QueueHeaderActions';-import { QueueHeaderLabel } from './QueueHeaderLabel';-import { QueueHeaderMenu } from './QueueHeaderMenu';-import { QueueWidgetView } from './QueueWidgetView';--export const queueWidgetManifest: WidgetManifest = {- allowMultiple: false,- allowedRegions: ['right'],- failurePolicy: {- isolateRenderFailure: true,- onRegistrationFailure: 'disable',- },- footer: ModelCacheFooter,- headerActions: QueueHeaderActions,- headerMenu: QueueHeaderMenu,- host: QueueDataRuntime,- icon: ListOrderedIcon,- id: 'queue',- headerLabel: QueueHeaderLabel,- label: (t) => t('widgets.labels.queue'),- settingsSection: 'queue',- version: 1,- view: QueueWidgetView,-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueDataStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueDataStore.tsdeleted file mode 100644index d0058d60ee..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueDataStore.ts+++ /dev/null@@ -1,165 +0,0 @@-import { getApiErrorMessage } from '@workbench/backend/http';-import { createExternalStore } from '@workbench/externalStore';-import { shallowEqual } from '@workbench/workbenchSelectors';--import type { QueueAndProcessorStatus, QueueQueryScope, QueueServerItem, QueueStatusCounts } from './queueServerApi';--import { getCurrentBatchItems } from './currentBatchItems';-import { clearProgressForQueueItemsWithResults } from './queueProgressCleanup';-import {- getCurrentQueueItem,- getNextQueueItem,- getQueueItemIds,- getQueueItemsByIds,- getQueueStatus,-} from './queueServerApi';--/**- * Read model for the whole backend session queue, shared by the Queue widget's- * header, stats, CURRENT BATCH, and RECENT sections. A single external store fed by- * one debounced `refreshQueue()` keeps every section consistent and lets each- * subscribe to just the slice it renders (composition: one lifted store, many- * thin readers). Socket events drive refresh via `QueueDataRuntime`.- */--/** How many of the most-recent items we hydrate for the RECENT list. */-export const RECENT_WINDOW = 50;-const REFRESH_DEBOUNCE_MS = 300;--const EMPTY_COUNTS: QueueStatusCounts = {- canceled: 0,- completed: 0,- failed: 0,- in_progress: 0,- pending: 0,- queue_id: 'default',- total: 0,-};--interface QueueDataSnapshot {- status: QueueAndProcessorStatus | null;- current: QueueServerItem | null;- next: QueueServerItem | null;- items: QueueServerItem[];- scope: QueueQueryScope;- loadState: 'idle' | 'loading' | 'loaded' | 'error';- error: string | null;-}--const store = createExternalStore<QueueDataSnapshot>({- current: null,- error: null,- items: [],- loadState: 'idle',- next: null,- scope: {},- status: null,-});--let inflight: Promise<void> | null = null;-let refreshTimer: ReturnType<typeof setTimeout> | null = null;-let needsRefresh = false;-let refreshSequence = 0;--const runRefresh = async (): Promise<void> => {- const scope = store.getSnapshot().scope;- const sequence = ++refreshSequence;-- if (store.getSnapshot().loadState === 'idle') {- store.patchSnapshot({ loadState: 'loading' });- }-- try {- // Independent reads run together to avoid a request waterfall; the window- // fetch is the only one that must wait (it needs the ordered ids first).- const [status, current, next, idsResult] = await Promise.all([- getQueueStatus(scope),- getCurrentQueueItem(scope),- getNextQueueItem(scope),- getQueueItemIds('desc', scope),- ]);- const items = await getQueueItemsByIds(idsResult.item_ids.slice(0, RECENT_WINDOW));-- if (sequence === refreshSequence) {- clearProgressForQueueItemsWithResults([current, next, ...items].filter((item) => item !== null));- store.patchSnapshot({ current, error: null, items, loadState: 'loaded', next, status });- }- } catch (error) {- if (sequence === refreshSequence) {- store.patchSnapshot({ error: getApiErrorMessage(error, 'Failed to load queue'), loadState: 'error' });- }- }-};--const runRefreshLoop = async (): Promise<void> => {- do {- needsRefresh = false;- await runRefresh();- } while (needsRefresh);-};--/** Coalesced refresh — many socket events in a burst collapse into one fetch. */-export const refreshQueue = (): Promise<void> => {- if (inflight !== null && refreshTimer === null) {- needsRefresh = true;- return inflight;- }-- if (refreshTimer !== null) {- return inflight ?? Promise.resolve();- }-- inflight = new Promise<void>((resolve) => {- refreshTimer = setTimeout(() => {- refreshTimer = null;- void runRefreshLoop().finally(() => {- inflight = null;- resolve();- });- }, REFRESH_DEBOUNCE_MS);- });-- return inflight;-};--export const setQueueScope = (scope: QueueQueryScope): void => {- const previous = store.getSnapshot().scope;- const isSameScope = previous.originPrefix === scope.originPrefix;-- if (isSameScope) {- return;- }-- store.patchSnapshot({ current: null, error: null, items: [], loadState: 'loading', next: null, scope, status: null });- void refreshQueue();-};--/** First load — idempotent; safe to call from every mounting surface. */-export const ensureQueueLoaded = (): void => {- if (store.getSnapshot().loadState === 'idle') {- void refreshQueue();- }-};--// --- Selectors / hooks -------------------------------------------------------export const useQueueCounts = (): QueueStatusCounts =>- store.useSelector((snapshot) => snapshot.status?.queue ?? EMPTY_COUNTS, shallowEqual);--/** The processor is "paused" when it has been stopped (`is_started` false). */-export const useIsProcessorPaused = (): boolean =>- store.useSelector((snapshot) => snapshot.status?.processor.is_started === false);--export const useNowNextItems = (): { current: QueueServerItem | null; next: QueueServerItem | null } =>- store.useSelector((snapshot) => ({ current: snapshot.current, next: snapshot.next }), shallowEqual);--export const useCurrentBatchItems = (): QueueServerItem[] =>- store.useSelector(- (snapshot) => getCurrentBatchItems({ current: snapshot.current, items: snapshot.items, next: snapshot.next }),- shallowEqual- );--export const useRecentItems = (): QueueServerItem[] => store.useSelector((snapshot) => snapshot.items);--export const useQueueLoadState = (): { loadState: QueueDataSnapshot['loadState']; error: string | null } =>- store.useSelector((snapshot) => ({ error: snapshot.error, loadState: snapshot.loadState }), shallowEqual);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueProgressCleanup.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueProgressCleanup.tsdeleted file mode 100644index 00dfc40566..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueProgressCleanup.ts+++ /dev/null@@ -1,23 +0,0 @@-import { itemProgressStore } from '@workbench/backend/itemProgressStore';--import type { QueueServerItem } from './queueServerApi';--import { getResultImageName } from './fieldValues';--export const getQueueItemIdsWithResultImages = (items: QueueServerItem[]): number[] => {- const itemIds: number[] = [];-- for (const item of items) {- if (getResultImageName(item)) {- itemIds.push(item.item_id);- }- }-- return itemIds;-};--export const clearProgressForQueueItemsWithResults = (items: QueueServerItem[]): void => {- for (const itemId of getQueueItemIdsWithResultImages(items)) {- itemProgressStore.clear(itemId);- }-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueScope.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueScope.tsdeleted file mode 100644index f2358803f0..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueScope.ts+++ /dev/null@@ -1,48 +0,0 @@-import type { Project, WorkbenchPreferences } from '@workbench/types';--import { buildProjectQueueItemOriginPrefix, parseQueueItemOrigin } from '@workbench/backend/events';-import { useWorkbenchPreferences } from '@workbench/settings/store';-import { useOptionalWorkbenchSelector } from '@workbench/WorkbenchContext';-import { useMemo } from 'react';--import type { QueueQueryScope, QueueServerItem } from './queueServerApi';--import { useCurrentBatchItems, useQueueCounts, useRecentItems } from './queueDataStore';--export type QueueJobsScope = WorkbenchPreferences['queueJobsScope'];--export const isQueueServerItemInProject = (serverItem: QueueServerItem, project: Pick<Project, 'queue'>): boolean => {- const localQueueItemId = parseQueueItemOrigin(serverItem.origin);-- if (localQueueItemId && project.queue.items.some((item) => item.id === localQueueItemId)) {- return true;- }-- return project.queue.items.some((item) => item.backendItemIds?.includes(serverItem.item_id) ?? false);-};--export const useQueueJobsScope = (): QueueJobsScope => useWorkbenchPreferences().queueJobsScope;--export const getQueueQueryScope = ({- projectId,- queueJobsScope,-}: {- projectId: string | null;- queueJobsScope: QueueJobsScope;-}): QueueQueryScope =>- queueJobsScope === 'active-project' && projectId- ? { originPrefix: buildProjectQueueItemOriginPrefix(projectId) }- : {};--export const useQueueQueryScope = (): QueueQueryScope => {- const queueJobsScope = useQueueJobsScope();- const projectId = useOptionalWorkbenchSelector((snapshot) => snapshot.activeProject.id, null);-- return useMemo(() => getQueueQueryScope({ projectId, queueJobsScope }), [projectId, queueJobsScope]);-};--export const useScopedQueueCounts = useQueueCounts;--export const useScopedCurrentBatchItems = useCurrentBatchItems;--export const useScopedRecentItems = useRecentItems;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueServerApi.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueServerApi.test.tsdeleted file mode 100644index 65105d004d..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueServerApi.test.ts+++ /dev/null@@ -1,50 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--const mocks = vi.hoisted(() => ({- apiFetchJson: vi.fn(),-}));--vi.mock('@workbench/backend/http', () => ({- apiFetchJson: mocks.apiFetchJson,-}));--describe('queueServerApi', () => {- beforeEach(() => {- mocks.apiFetchJson.mockReset();- mocks.apiFetchJson.mockResolvedValue({ item_ids: [], total_count: 0 });- });-- it('uses backend SQLiteDirection values for queue item ordering', async () => {- const { getQueueItemIds } = await import('./queueServerApi');-- await getQueueItemIds('desc');-- expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/queue/default/item_ids?order_dir=DESC');- });-- it('deletes only failed queue items when clearing failed items', async () => {- mocks.apiFetchJson.mockImplementation((url: string) => {- if (url === '/api/v1/queue/default/item_ids?order_dir=DESC') {- return Promise.resolve({ item_ids: [3, 2, 1], total_count: 3 });- }-- if (url === '/api/v1/queue/default/items_by_ids') {- return Promise.resolve([- { item_id: 3, status: 'completed' },- { item_id: 2, status: 'failed' },- { item_id: 1, status: 'pending' },- ]);- }-- return Promise.resolve({});- });-- const { clearFailedQueueItems } = await import('./queueServerApi');-- await clearFailedQueueItems();-- expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/queue/default/i/2', { method: 'DELETE' });- expect(mocks.apiFetchJson).not.toHaveBeenCalledWith('/api/v1/queue/default/i/1', { method: 'DELETE' });- expect(mocks.apiFetchJson).not.toHaveBeenCalledWith('/api/v1/queue/default/i/3', { method: 'DELETE' });- });-});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/server-status/ServerStatusWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/server-status/ServerStatusWidgetView.tsxindex ce87140596..42485ead36 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/server-status/ServerStatusWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/server-status/ServerStatusWidgetView.tsx@@ -1,4 +1,4 @@-import type { WidgetViewProps } from '@workbench/types';+import type { WidgetViewProps } from '@workbench/widgetContracts';import { Stack, Text } from '@chakra-ui/react';import { StatusWidgetChip } from '@workbench/widget-frame';@@ -8,7 +8,7 @@ import { useTranslation } from 'react-i18next';export const ServerStatusWidgetView = ({ presentation }: WidgetViewProps) => {const { t } = useTranslation();- const backendConnection = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection);+ const backendConnection = useWorkbenchSelector((snapshot) => snapshot.backendConnection);const isConnected = backendConnection.status === 'connected';const isDisconnected = backendConnection.status === 'disconnected';const label = isConnecteddiff --git a/invokeai/frontend/webv2/src/workbench/widgets/server-status/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/server-status/implementation.tsnew file mode 100644index 0000000000..cc3ad9663f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/server-status/implementation.ts@@ -0,0 +1,5 @@+import type { WidgetImplementation } from '@workbench/widgetContracts';++import { ServerStatusWidgetView } from './ServerStatusWidgetView';++export const widgetImplementation = { view: ServerStatusWidgetView } satisfies WidgetImplementation;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/server-status/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/server-status/index.tsindex eefa02b2dd..c8fa240d94 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/server-status/index.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/server-status/index.ts@@ -1,9 +1,7 @@-import type { WidgetManifest } from '@workbench/types';+import type { WidgetManifest } from '@workbench/widgetContracts';import { PlugZapIcon } from 'lucide-react';-import { ServerStatusWidgetView } from './ServerStatusWidgetView';-export const serverStatusWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['bottom'],@@ -12,6 +10,6 @@ export const serverStatusWidgetManifest: WidgetManifest = {icon: PlugZapIcon,id: 'server-status',label: (t) => t('widgets.labels.serverStatus'),+ load: () => import('./implementation').then((module) => module.widgetImplementation),version: 1,- view: ServerStatusWidgetView,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/version-status/VersionStatusWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/version-status/VersionStatusWidgetView.tsxindex 5717a7af10..fb61ebde07 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/version-status/VersionStatusWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/version-status/VersionStatusWidgetView.tsx@@ -1,4 +1,4 @@-import type { WidgetViewProps } from '@workbench/types';+import type { WidgetViewProps } from '@workbench/widgetContracts';import { Stack, Text } from '@chakra-ui/react';import { StatusWidgetChip } from '@workbench/widget-frame';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/version-status/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/version-status/implementation.tsnew file mode 100644index 0000000000..e7262b8afa--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/version-status/implementation.ts@@ -0,0 +1,5 @@+import type { WidgetImplementation } from '@workbench/widgetContracts';++import { VersionStatusWidgetView } from './VersionStatusWidgetView';++export const widgetImplementation = { view: VersionStatusWidgetView } satisfies WidgetImplementation;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/version-status/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/version-status/index.tsindex 3e4e95fb71..30d2c1351a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/version-status/index.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/version-status/index.ts@@ -1,9 +1,7 @@-import type { WidgetManifest } from '@workbench/types';+import type { WidgetManifest } from '@workbench/widgetContracts';import { InfoIcon } from 'lucide-react';-import { VersionStatusWidgetView } from './VersionStatusWidgetView';-export const versionStatusWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['bottom'],@@ -12,6 +10,6 @@ export const versionStatusWidgetManifest: WidgetManifest = {icon: InfoIcon,id: 'version-status',label: (t) => t('widgets.labels.versionStatus'),+ load: () => import('./implementation').then((module) => module.widgetImplementation),version: 1,- view: VersionStatusWidgetView,};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchAggregateInterface.type-test.ts b/invokeai/frontend/webv2/src/workbench/workbenchAggregateInterface.type-test.tsnew file mode 100644index 0000000000..b489f934d9--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workbenchAggregateInterface.type-test.ts@@ -0,0 +1,19 @@+// @ts-expect-error Reducer actions are private; tests use workbenchState.testing explicitly.+import type { WorkbenchAction } from './workbenchState';+import type { WorkbenchInternalStore } from './workbenchStore';++// @ts-expect-error The reducer implementation is not exported under a public API name.+import { workbenchReducer } from './workbenchState';++declare const store: WorkbenchInternalStore;++// @ts-expect-error Raw reducer dispatch is not part of the aggregate interface.+store.dispatch({ type: 'createProject' });++// @ts-expect-error The public query snapshot does not expose the full aggregate state.+const fullState = store.queries.getSnapshot().state;++void store;+void fullState;+void (null as unknown as WorkbenchAction);+void workbenchReducer;diff --git a/invokeai/frontend/webv2/src/workbench/workbenchAutosave.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchAutosave.test.tsdeleted file mode 100644index 7b9f0a09f9..0000000000--- a/invokeai/frontend/webv2/src/workbench/workbenchAutosave.test.ts+++ /dev/null@@ -1,94 +0,0 @@-import { describe, expect, it } from 'vitest';--import { getAutosaveScheduleDecision, isAutosaveCompletionCurrent } from './workbenchAutosave';--describe('getAutosaveScheduleDecision', () => {- it('does not schedule already-saved or already-scheduled state', () => {- expect(- getAutosaveScheduleDecision({- failedPersistedRevision: null,- lastSavedPersistedRevision: 1,- persistedRevision: 1,- scheduledPersistedRevision: null,- })- ).toEqual({ failedPersistedRevision: null, shouldSchedule: false });-- expect(- getAutosaveScheduleDecision({- failedPersistedRevision: null,- lastSavedPersistedRevision: 1,- persistedRevision: 2,- scheduledPersistedRevision: 2,- })- ).toEqual({ failedPersistedRevision: null, shouldSchedule: false });- });-- it('holds a failed state key until a new durable edit happens', () => {- expect(- getAutosaveScheduleDecision({- failedPersistedRevision: 2,- lastSavedPersistedRevision: 1,- persistedRevision: 2,- scheduledPersistedRevision: null,- })- ).toEqual({ failedPersistedRevision: 2, shouldSchedule: false });-- expect(- getAutosaveScheduleDecision({- failedPersistedRevision: 2,- lastSavedPersistedRevision: 1,- persistedRevision: 3,- scheduledPersistedRevision: null,- })- ).toEqual({ failedPersistedRevision: null, shouldSchedule: true });- });-- it('clears a failed state key after returning to the last saved state', () => {- expect(- getAutosaveScheduleDecision({- failedPersistedRevision: 2,- lastSavedPersistedRevision: 1,- persistedRevision: 1,- scheduledPersistedRevision: null,- })- ).toEqual({ failedPersistedRevision: null, shouldSchedule: false });-- expect(- getAutosaveScheduleDecision({- failedPersistedRevision: null,- lastSavedPersistedRevision: 1,- persistedRevision: 2,- scheduledPersistedRevision: null,- })- ).toEqual({ failedPersistedRevision: null, shouldSchedule: true });- });-});--describe('isAutosaveCompletionCurrent', () => {- it('rejects stale save completions after a newer durable revision exists', () => {- expect(- isAutosaveCompletionCurrent({- completedPersistedRevision: 2,- currentPersistedRevision: 3,- })- ).toBe(false);- });-- it('accepts save completions for the current durable revision', () => {- expect(- isAutosaveCompletionCurrent({- completedPersistedRevision: 2,- currentPersistedRevision: 2,- })- ).toBe(true);- });-- it('does not require serializing full workbench state to compare completions', () => {- expect(- isAutosaveCompletionCurrent({- completedPersistedRevision: 4,- currentPersistedRevision: 4,- })- ).toBe(true);- });-});diff --git a/invokeai/frontend/webv2/src/workbench/workbenchAutosave.ts b/invokeai/frontend/webv2/src/workbench/workbenchAutosave.tsdeleted file mode 100644index 5d87de9103..0000000000--- a/invokeai/frontend/webv2/src/workbench/workbenchAutosave.ts+++ /dev/null@@ -1,40 +0,0 @@-interface AutosaveScheduleDecisionInput {- failedPersistedRevision: number | null;- lastSavedPersistedRevision: number;- persistedRevision: number;- scheduledPersistedRevision: number | null;-}--interface AutosaveScheduleDecision {- failedPersistedRevision: number | null;- shouldSchedule: boolean;-}--export const getAutosaveScheduleDecision = ({- failedPersistedRevision,- lastSavedPersistedRevision,- persistedRevision,- scheduledPersistedRevision,-}: AutosaveScheduleDecisionInput): AutosaveScheduleDecision => {- if (persistedRevision === lastSavedPersistedRevision) {- return { failedPersistedRevision: null, shouldSchedule: false };- }-- if (persistedRevision === scheduledPersistedRevision) {- return { failedPersistedRevision, shouldSchedule: false };- }-- if (persistedRevision === failedPersistedRevision) {- return { failedPersistedRevision, shouldSchedule: false };- }-- return { failedPersistedRevision: null, shouldSchedule: true };-};--export const isAutosaveCompletionCurrent = ({- completedPersistedRevision,- currentPersistedRevision,-}: {- completedPersistedRevision: number;- currentPersistedRevision: number;-}): boolean => completedPersistedRevision === currentPersistedRevision;diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex ce2f64891a..6d66a34b9d 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -1,22 +1,22 @@-import { describe, expect, it } from 'vitest';--import type { CanvasProjectMutation } from './canvasProjectMutations';-import type { GenerateWidgetValues, MainModelConfig } from './generation/types';+import type { GeneratedImageContract } from '@features/gallery';+import type { GenerateWidgetValues, MainModelConfig } from '@features/generation/contracts';import type {CanvasControlLayerContract,CanvasInpaintMaskLayerContract,CanvasLayerContract,CanvasRasterLayerContractV2,CanvasStagingCandidateContract,- GeneratedImageContract,- GraphContract,- Project,- WorkbenchState,-} from './types';+} from '@workbench/canvas-engine/contracts';+import type { GraphContract } from '@workbench/graphContracts';+import type { Project, WorkbenchState } from '@workbench/projectContracts';++import { MAX_PROMPT_HISTORY } from '@features/generation/prompt';+import { describe, expect, it } from 'vitest';++import type { CanvasProjectMutation } from './canvasProjectMutations';import { createEmptyCanvasDocumentV2 } from './canvasMigration';import { getCanvasStagingCandidateFingerprint, getCanvasStagingSlots } from './canvasStagingView';-import { MAX_PROMPT_HISTORY } from './generation/promptHistory';import { DEFAULT_PROJECT_SETTINGS } from './settings/store';import { getProjectWidgetValues } from './widgetState';import {@@ -24,7 +24,7 @@ import {nextLayerName,type WorkbenchAction,workbenchReducer as reduceWorkbench,-} from './workbenchState';+} from './workbenchState.testing';type LegacyCanvasMutation = CanvasProjectMutation & { projectId?: string };const CANVAS_MUTATION_TYPES = new Set<CanvasProjectMutation['type']>([@@ -2914,6 +2914,7 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =it('submitCanvasInvocationSnapshot enqueues a pre-compiled graph bound for the canvas', () => {const graph: GraphContract = {+ backendGraph: { edges: [], id: 'canvas-backend-graph', nodes: {} },edges: [],id: 'canvas-graph',label: 'Canvas',@@ -2960,6 +2961,18 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =seed: 42,shouldRandomizeSeed: false,});+ expect(queueItem?.snapshot.backendSubmission).toMatchObject({+ batchCount: 1,+ kind: 'generate',+ negativePrompt: 'avoid blur',+ negativePromptNodeId: 'negative_prompt',+ positivePrompt: 'inpaint prompt',+ positivePromptNodeId: 'positive_prompt',+ seed: 42,+ seedNodeId: 'seed',+ shouldRandomizeSeed: false,+ });+ expect(queueItem?.snapshot.resultNodeIds).toEqual(['canvas_output']);expect(getActiveProject(state).invocation.sourceId).toBe('canvas');});diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.testing.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.testing.tsnew file mode 100644index 0000000000..47a066c33b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.testing.ts@@ -0,0 +1,13 @@+/**+ * Reducer-level compatibility facade for invariant tests only.+ *+ * Production code must use Workbench commands and queries. Keeping this facade+ * separate makes reducer coupling visible and lets those tests be retired as+ * command-level coverage replaces them.+ */+export {+ __workbenchReducerInternal as workbenchReducer,+ createInitialWorkbenchState,+ nextLayerName,+} from './workbenchState';+export type { __WorkbenchReducerActionInternal as WorkbenchAction } from './workbenchState';diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 9054ff4895..90dd81586c 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -1,92 +1,85 @@-import type { GallerySettings } from './gallery/settings';-import type { GenerateWidgetValues } from './generation/types';-import type { ModelConfig } from './models/types';+import type { GallerySettings, GeneratedImageContract } from '@features/gallery/contracts';+import type { GenerateWidgetValues } from '@features/generation/contracts';+import type { ModelConfig } from '@features/models';+import type { QueueCompiledSubmission, QueueHistoryItemStatus } from '@features/queue/contracts';+import type { ProjectGraphState } from '@features/workflow/contracts';import type {CanvasDocumentContractV2,CanvasPlacementContract,CanvasStateContractV2,- CenterViewId,CanvasStagingCandidateContract,- DeveloperLogNamespace,- GeneratedImageContract,- GraphContract,- GraphHistorySnapshot,- InvocationRoute,- InvocationSourceId,+} from '@workbench/canvas-engine/api';+import type { DeveloperLogNamespace } from '@workbench/diagnostics/contracts';+import type { GraphContract } from '@workbench/graphContracts';+import type { InvocationRoute, InvocationSourceId, ResultDestination } from '@workbench/invocationContracts';+import type {+ CenterViewId,LayoutPreset,LayoutPresetId,LayoutPresetSnapshot,- Project,ProjectLayoutState,- ProjectSettings,+ WidgetRegion,+ WidgetRegionState,+} from '@workbench/layoutContracts';+import type {+ GraphHistorySnapshot,+ Project,ProjectUndoSnapshot,PromptHistoryItem,- QueueItem,- QueueItemStatus,- ResultDestination,+ WorkbenchNotification,+ WorkbenchNotificationKind,+ WorkbenchState,+} from '@workbench/projectContracts';+import type { ProjectSettings } from '@workbench/settings/contracts';+import type {WidgetFailure,WidgetId,WidgetInstanceContract,WidgetInstanceId,- WidgetRegion,- WidgetRegionState,WidgetStateContract,WidgetStateMap,WidgetTypeId,- WorkbenchNotification,- WorkbenchNotificationKind,- WorkbenchState,-} from './types';-import type { UpscaleWidgetValues } from './upscale/types';-import type { ProjectGraphState } from './workflows/types';+} from '@workbench/widgetContracts';++import type { WorkbenchQueueItem as QueueItem } from './queueHistoryContracts';import { createNewCanvasStateV2, migrateCanvasStateToV2 } from './canvasMigration';import { applyCanvasProjectMutation, type CanvasProjectMutation } from './canvasProjectMutations';+import { getProjectWidgetValues } from './widgetState';export { nextLayerName } from './canvasProjectMutations';-import {- getCanvasStagingSlotCount,- getCanvasStagingSlots,- getFirstCanvasPlaceholderSlotIndex,-} from './canvasStagingView';-import { getGenerationModelAvailabilityReasons } from './generation/baseGenerationPolicies';-import { sanitizeBatchCount } from './generation/batch';-import { compileGenerateGraph, resolveGenerateSeed } from './generation/graph';-import {- applyProjectPromptDraft,- getProjectPromptDraft,- migrateProjectPromptDraft,- type ProjectPromptDraftPatch,-} from './generation/projectPromptDraft';+import { sanitizeBatchCount } from '@features/generation/batch';+import { compileGenerateGraph, resolveGenerateSeed } from '@features/generation/graph';import {addPromptHistoryItem,getPromptHistoryItemFromGenerateSettings,removePromptHistoryItem,-} from './generation/promptHistory';+} from '@features/generation/prompt';import {cloneGenerateWidgetValues,+ getGenerationModelAvailabilityReasons,normalizeGenerateSettings,normalizeGenerateWidgetValues,syncGenerateWidgetValuesWithModels,-} from './generation/settings';+} from '@features/generation/settings';import {- defaultInvocationRoute,- isInvocationRouteValid,- isInvocationSourceAvailable,- resolveInvocationRoute,-} from './invocation';-import { defaultLayoutPreset, getLayoutPreset } from './layoutPresets';-import { cloneLayoutPresetWidgetRegions, createLayoutPresetSnapshot } from './layoutPresetSnapshots';-import { normalizeProjectSettings } from './settings/store';-import { compileUpscaleGraph } from './upscale/graph';+ applyProjectPromptDraft,+ getPromptDraftFromValues,+ migrateProjectPromptDraft,+ type ProjectPromptDraftPatch,+} from '@features/generation/utility';import {clearDeletedUpscaleInput,cloneUpscaleWidgetValues,+ compileUpscaleGraph,+ getUpscaleOutputDimensions,getUpscaleValidationReasons,normalizeUpscaleWidgetValues,resolveUpscaleSeed,syncUpscaleWidgetValuesWithModels,-} from './upscale/settings';-import { compileProjectGraph } from './workflows/buildGraph';+ type UpscaleWidgetValues,+} from '@features/upscale';+import { compileProjectGraph } from '@features/workflow/graph';+import { getInvocationTemplatesSnapshot } from '@features/workflow/react';import {cloneProjectGraph,createProjectGraph,@@ -95,8 +88,22 @@ import {normalizeProjectGraph,projectGraphReducer,type ProjectGraphAction,-} from './workflows/document';-import { getInvocationTemplatesSnapshot } from './workflows/templates';+} from '@features/workflow/utility';++import {+ getCanvasStagingSlotCount,+ getCanvasStagingSlots,+ getFirstCanvasPlaceholderSlotIndex,+} from './canvasStagingView';+import {+ defaultInvocationRoute,+ isInvocationRouteValid,+ isInvocationSourceAvailable,+ resolveInvocationRoute,+} from './invocation';+import { defaultLayoutPreset, getLayoutPreset } from './layoutPresets';+import { cloneLayoutPresetWidgetRegions, createLayoutPresetSnapshot } from './layoutPresetSnapshots';+import { normalizeProjectSettings } from './settings/store';type QueueGenerateSnapshot = NonNullable<QueueItem['snapshot']['generate']>;@@ -185,7 +192,7 @@ type WorkbenchReducerAction =type: 'setQueueItemStatus';projectId: string;queueItemId: string;- status: QueueItemStatus;+ status: QueueHistoryItemStatus;error?: string;notify?: boolean;}@@ -1407,7 +1414,10 @@ const compileInvocationSnapshot = (}const syncedValues = models ? syncUpscaleWidgetValuesWithModels(values, models) : values;- const currentValues: UpscaleWidgetValues = { ...syncedValues, ...getProjectPromptDraft(project) };+ const currentValues: UpscaleWidgetValues = {+ ...syncedValues,+ ...getPromptDraftFromValues(getProjectWidgetValues(project, 'generate')),+ };if (getUpscaleValidationReasons(currentValues, models).length > 0) {return null;@@ -1563,7 +1573,7 @@ const mergeBackendItemId = (ids: number[] | undefined, backendItemId: number): nconst getQueueItemStatusAfterBackendCancellation = (item: QueueItem,cancelledBackendItemIds: number[]-): QueueItemStatus => {+): QueueHistoryItemStatus => {if (!item.backendItemIds?.length) {return item.status;}@@ -1685,15 +1695,69 @@ const enqueueCompiledSnapshot = (route.sourceId === 'generate' ? normalizeGenerateSettings(widgetStates.generate.values) : null;const upscaleSettings =route.sourceId === 'upscale' ? normalizeUpscaleWidgetValues(widgetStates.upscale.values) : null;+ const backendGraph = graph.backendGraph;+ const sourceGenerateSettings =+ route.sourceId === 'canvas'+ ? normalizeGenerateSettings(generate?.values)+ : route.sourceId === 'generate'+ ? generateSettings+ : route.sourceId === 'upscale'+ ? upscaleSettings+ : null;+ const backendSubmission: QueueCompiledSubmission = !backendGraph+ ? { error: `${route.sourceId} queue item is missing a compiled backend graph.`, kind: 'invalid' }+ : route.sourceId === 'workflow'+ ? {+ batchCount: sanitizeBatchCount(widgetStates.generate?.values.batchCount),+ graph: backendGraph,+ kind: 'workflow',+ }+ : sourceGenerateSettings+ ? {+ batchCount: sourceGenerateSettings.batchCount,+ graph: backendGraph,+ kind: 'generate',+ negativePrompt: sourceGenerateSettings.negativePromptEnabled ? sourceGenerateSettings.negativePrompt : '',+ negativePromptNodeId: generate?.negativePromptNodeId ?? 'negative_prompt',+ positivePrompt: sourceGenerateSettings.positivePrompt,+ positivePromptNodeId: generate?.positivePromptNodeId ?? 'positive_prompt',+ seed: sourceGenerateSettings.seed,+ seedNodeId: generate?.seedNodeId ?? 'seed',+ shouldRandomizeSeed: sourceGenerateSettings.shouldRandomizeSeed,+ }+ : { error: `${route.sourceId} queue item is missing source submission metadata.`, kind: 'invalid' };+ const selectedGalleryBoardId = widgetStates.gallery?.values.selectedBoardId;+ const generatePresentationSettings = normalizeGenerateSettings(widgetStates.generate?.values);+ const presentationDimensions =+ route.sourceId === 'upscale' && upscaleSettings?.inputImage+ ? getUpscaleOutputDimensions(upscaleSettings.inputImage, upscaleSettings.scale)+ : {+ height: generatePresentationSettings?.height ?? project.canvas.document.height,+ width: generatePresentationSettings?.width ?? project.canvas.document.width,+ };const queueItem: QueueItem = {cancellable: backendSupportsCancellation,id: queueItemId,snapshot: {+ backendSubmission,canvas: canvasSnapshot ? structuredClone(canvasSnapshot) : cloneCanvas(project.canvas),destination: route.destination,+ filterIntermediateResults: route.sourceId === 'workflow',+ galleryBoardId: typeof selectedGalleryBoardId === 'string' ? selectedGalleryBoardId : null,...(generate ? { generate: cloneQueueGenerateSnapshot(generate) } : {}),graph,+ presentation: {+ batchCount: backendSubmission.kind === 'invalid' ? 1 : backendSubmission.batchCount,+ height: presentationDimensions.height,+ ...(sourceGenerateSettings?.positivePrompt ? { positivePrompt: sourceGenerateSettings.positivePrompt } : {}),+ width: presentationDimensions.width,+ },sourceId: route.sourceId,+ ...(route.sourceId === 'generate' || route.sourceId === 'canvas'+ ? { resultNodeIds: ['canvas_output'] }+ : route.sourceId === 'upscale'+ ? { resultNodeIds: ['upscale_output'] }+ : {}),submittedAt,widgetInstances: cloneWidgetInstances(project.widgetInstances),widgetStates,@@ -1769,7 +1833,7 @@ export const createInitialWorkbenchState = (): WorkbenchState => {};};-export const workbenchReducer = (state: WorkbenchState, action: WorkbenchReducerAction): WorkbenchState => {+export const __workbenchReducerInternal = (state: WorkbenchState, action: WorkbenchReducerAction): WorkbenchState => {switch (action.type) {case 'createProject': {const project = createDraftProject(state.projects);@@ -2919,5 +2983,4 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchReducer}};-export type WorkbenchAction = WorkbenchReducerAction;-export type { WorkbenchReducerAction };+export type __WorkbenchReducerActionInternal = WorkbenchReducerAction;diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.tsindex 2318864b85..64e481b5dd 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts@@ -1,14 +1,15 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import type { WorkbenchSnapshot, WorkbenchStore } from './workbenchStore';+import type { WorkbenchInternalStore, WorkbenchSnapshot } from './workbenchStore';import { clearProjectDiagnostics, configureDiagnostics, getProjectDiagnostics } from './diagnostics/logger';import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from './widgetPlacementMeta';import { getProjectWidgetValues } from './widgetState';+import { createInitialWorkbenchState } from './workbenchState';import { createWorkbenchStore } from './workbenchStore';const watchSelector = <Selected>(- store: WorkbenchStore,+ store: WorkbenchInternalStore,selector: (snapshot: WorkbenchSnapshot) => Selected,isEqual: (left: Selected, right: Selected) => boolean = Object.is) => {@@ -45,14 +46,14 @@ describe('createWorkbenchStore', () => {});});- it('exposes a stable dispatch and initializes snapshot metadata', () => {+ it('exposes stable capability interfaces and initializes snapshot metadata', () => {const store = createWorkbenchStore();const snapshot = store.getSnapshot();- expect(store.dispatch).toBe(store.dispatch);- expect(snapshot.state.activeProjectId).toBe(snapshot.activeProject.id);+ expect(store.commands).toBe(store.commands);+ expect(store.queries).toBe(store.queries);expect(snapshot.hasHydrated).toBe(false);- expect(snapshot.state.projects).toHaveLength(1);+ expect(snapshot.projects).toHaveLength(1);});it('notifies subscribers once for reducer changes and not for no-op reducer results', () => {@@ -63,12 +64,12 @@ describe('createWorkbenchStore', () => {const projectId = store.getSnapshot().activeProject.id;- store.dispatch({ name: 'Renamed', projectId, type: 'renameProject' });+ store.commands.projects.rename(projectId, 'Renamed');expect(listener).toHaveBeenCalledTimes(1);expect(store.getSnapshot().activeProject.name).toBe('Renamed');- store.dispatch({ name: ' ', projectId, type: 'renameProject' });+ store.commands.projects.rename(projectId, ' ');expect(listener).toHaveBeenCalledTimes(1);expect(store.getSnapshot().activeProject.name).toBe('Renamed');@@ -98,29 +99,55 @@ describe('createWorkbenchStore', () => {const store = createWorkbenchStore();const initialPersistedRevision = store.getPersistedRevision();- store.dispatch({ status: 'connected', type: 'setBackendConnectionStatus' });+ store.commands.queue.setConnectionStatus({ status: 'connected' });expect(store.getPersistedRevision()).toBe(initialPersistedRevision);- store.dispatch({ kind: 'info', title: 'Global notice', type: 'recordNotice' });+ store.commands.notifications.add({ kind: 'info', title: 'Global notice' });expect(store.getPersistedRevision()).toBe(initialPersistedRevision);- store.dispatch({- name: 'Persisted rename',- projectId: store.getSnapshot().activeProject.id,- type: 'renameProject',- });+ store.commands.projects.rename(store.getSnapshot().activeProject.id, 'Persisted rename');expect(store.getPersistedRevision()).toBe(initialPersistedRevision + 1);});+ it('forwards payload-form commands into reducer actions', () => {+ const store = createWorkbenchStore();++ store.commands.notifications.add({ kind: 'info', title: 'Payload form' });++ expect(store.getSnapshot().notifications[0]?.title).toBe('Payload form');+ });++ it('maps positional-form commands onto their action payloads', () => {+ const store = createWorkbenchStore();+ const projectId = store.getSnapshot().activeProject.id;++ store.commands.gallery.setSearchTerm('positional form', projectId);++ expect(getProjectWidgetValues(store.getSnapshot().activeProject, 'gallery').searchTerm).toBe('positional form');+ });++ it('dispatches nullary commands with no payload', () => {+ const store = createWorkbenchStore();++ store.commands.notifications.add({ kind: 'info', title: 'To clear' });+ store.commands.notifications.clear();++ expect(store.getSnapshot().notifications).toHaveLength(0);+ });+it('records recordError actions into project diagnostics', () => {const store = createWorkbenchStore();const projectId = store.getSnapshot().activeProject.id;clearProjectDiagnostics(projectId);- store.dispatch({ area: 'queue-runtime', message: 'Queue failed', namespace: 'queue', type: 'recordError' });+ store.commands.notifications.reportError({+ area: 'queue-runtime',+ message: 'Queue failed',+ namespace: 'queue',+ });expect(getProjectDiagnostics(projectId)).toMatchObject([{@@ -130,7 +157,7 @@ describe('createWorkbenchStore', () => {source: { area: 'queue-runtime', kind: 'workbench', projectId },},]);- expect(store.getSnapshot().state.notifications[0]?.title).toBe('Error');+ expect(store.getSnapshot().notifications[0]?.title).toBe('Error');});it('records accepted widget failures into diagnostics once', () => {@@ -144,8 +171,8 @@ describe('createWorkbenchStore', () => {};clearProjectDiagnostics(projectId);- store.dispatch({ failure, type: 'recordWidgetFailure' });- store.dispatch({ failure, type: 'recordWidgetFailure' });+ store.commands.notifications.recordWidgetFailure(failure);+ store.commands.notifications.recordWidgetFailure(failure);expect(getProjectDiagnostics(projectId)).toMatchObject([{@@ -164,7 +191,7 @@ describe('createWorkbenchStore', () => {const unsubscribe = store.subscribe(listener);unsubscribe();- store.dispatch({ type: 'createProject' });+ store.commands.projects.create();expect(listener).not.toHaveBeenCalled();});@@ -173,9 +200,9 @@ describe('createWorkbenchStore', () => {const store = createWorkbenchStore();const activeProjectWatcher = watchSelector(store, (snapshot) => snapshot.activeProject);const activeProjectIdWatcher = watchSelector(store, (snapshot) => snapshot.activeProject.id);- const notificationCountWatcher = watchSelector(store, (snapshot) => snapshot.state.notifications.length);+ const notificationCountWatcher = watchSelector(store, (snapshot) => snapshot.notifications.length);- store.dispatch({ kind: 'info', title: 'Global notice', type: 'recordNotice' });+ store.commands.notifications.add({ kind: 'info', title: 'Global notice' });expect(notificationCountWatcher.current).toBe(1);expect(notificationCountWatcher.changeCount).toBe(1);@@ -185,14 +212,14 @@ describe('createWorkbenchStore', () => {it('lets narrow selectors observe only their own state changes', () => {const store = createWorkbenchStore();- const backendStatusWatcher = watchSelector(store, (snapshot) => snapshot.state.backendConnection.status);+ const backendStatusWatcher = watchSelector(store, (snapshot) => snapshot.backendConnection.status);const activeProjectIdWatcher = watchSelector(store, (snapshot) => snapshot.activeProject.id);- const projectCountWatcher = watchSelector(store, (snapshot) => snapshot.state.projects.length);+ const projectCountWatcher = watchSelector(store, (snapshot) => snapshot.projects.length);const batchCountWatcher = watchSelector(store, (snapshot) =>Number(getProjectWidgetValues(snapshot.activeProject, 'generate').batchCount ?? 1));- store.dispatch({ status: 'connected', type: 'setBackendConnectionStatus' });+ store.commands.queue.setConnectionStatus({ status: 'connected' });expect(backendStatusWatcher.current).toBe('connected');expect(backendStatusWatcher.changeCount).toBe(1);@@ -200,7 +227,7 @@ describe('createWorkbenchStore', () => {expect(projectCountWatcher.changeCount).toBe(0);expect(batchCountWatcher.changeCount).toBe(0);- store.dispatch({ batchCount: 3, type: 'setGenerateBatchCount' });+ store.commands.generation.setBatchCount(3);expect(batchCountWatcher.current).toBe(3);expect(batchCountWatcher.changeCount).toBe(1);@@ -208,7 +235,7 @@ describe('createWorkbenchStore', () => {expect(activeProjectIdWatcher.changeCount).toBe(0);expect(projectCountWatcher.changeCount).toBe(0);- store.dispatch({ type: 'createProject' });+ store.commands.projects.create();expect(projectCountWatcher.current).toBe(2);expect(projectCountWatcher.changeCount).toBe(1);@@ -221,16 +248,16 @@ describe('createWorkbenchStore', () => {const store = createWorkbenchStore();const statusObjectWatcher = watchSelector(store,- (snapshot) => ({ status: snapshot.state.backendConnection.status }),+ (snapshot) => ({ status: snapshot.backendConnection.status }),(left, right) => left.status === right.status);- store.dispatch({ kind: 'info', title: 'Unrelated notice', type: 'recordNotice' });+ store.commands.notifications.add({ kind: 'info', title: 'Unrelated notice' });expect(statusObjectWatcher.current).toEqual({ status: 'connecting' });expect(statusObjectWatcher.changeCount).toBe(0);- store.dispatch({ status: 'connected', type: 'setBackendConnectionStatus' });+ store.commands.queue.setConnectionStatus({ status: 'connected' });expect(statusObjectWatcher.current).toEqual({ status: 'connected' });expect(statusObjectWatcher.changeCount).toBe(1);@@ -245,7 +272,7 @@ describe('createWorkbenchStore', () => {);const widgetInstancesWatcher = watchSelector(store, (snapshot) => snapshot.activeProject.widgetInstances);- store.dispatch({ instanceId: 'generate', type: 'patchWidgetInstanceValues', values: { prompt: 'updated' } });+ store.commands.widgets.patchInstanceValues('generate', { prompt: 'updated' });expect(widgetInstancesWatcher.changeCount).toBe(1);expect(placementWatcher.changeCount).toBe(0);@@ -260,7 +287,7 @@ describe('createWorkbenchStore', () => {);const firstProjectId = placementWatcher.current.projectId;- store.dispatch({ type: 'createProject' });+ store.commands.projects.create();expect(placementWatcher.current.projectId).not.toBe(firstProjectId);expect(placementWatcher.changeCount).toBe(1);@@ -272,16 +299,12 @@ describe('createWorkbenchStore', () => {store.subscribe(listener);- store.dispatch({ batchCount: 1, type: 'setGenerateBatchCount' });- store.dispatch({ settings: { useCpuNoise: true }, type: 'setActiveProjectSettings' });- store.dispatch({ isCollapsed: false, region: 'left', type: 'setRegionWidgetCollapsed' });- store.dispatch({- region: 'left',- sizePx: store.getSnapshot().activeProject.widgetRegions.left.sizePx,- type: 'setRegionWidgetSize',- });- store.dispatch({ type: 'patchWidgetValues', values: {}, widgetId: 'generate' });- store.dispatch({ status: 'connecting', type: 'setBackendConnectionStatus' });+ store.commands.generation.setBatchCount(1);+ store.commands.account.updateProjectPreferences({ useCpuNoise: true });+ store.commands.layout.setRegionCollapsed('left', false);+ store.commands.layout.setRegionSize('left', store.getSnapshot().activeProject.widgetRegions.left.sizePx);+ store.commands.widgets.patchValues('generate', {});+ store.commands.queue.setConnectionStatus({ status: 'connecting' });expect(listener).not.toHaveBeenCalled();});@@ -293,17 +316,92 @@ describe('createWorkbenchStore', () => {store.subscribe(listener);- store.dispatch({- projectId: project.id,- queueItemId: 'missing-queue-item',- status: 'pending',- type: 'setQueueItemStatus',- });+ store.commands.queue.setStatus({ projectId: project.id, queueItemId: 'missing-queue-item', status: 'pending' });expect(listener).not.toHaveBeenCalled();});- it('keeps placement selectors stable across generate, queue, and settings changes', () => {+ it('exposes queue behavior through namespaced commands', () => {+ const initialState = createInitialWorkbenchState();+ const initialProject = initialState.projects[0];+ const store = createWorkbenchStore({+ ...initialState,+ projects: [+ {+ ...initialProject,+ queue: {+ items: [+ {+ cancellable: true,+ id: 'queue-item-1',+ snapshot: {} as (typeof initialProject.queue.items)[number]['snapshot'],+ status: 'pending',+ },+ {+ cancellable: false,+ id: 'queue-item-complete',+ snapshot: {} as (typeof initialProject.queue.items)[number]['snapshot'],+ status: 'completed',+ },+ ],+ },+ },+ ],+ });+ const projectId = store.getSnapshot().activeProject.id;++ store.commands.queue.setConnectionStatus({ status: 'connected' });+ store.commands.queue.cancel(projectId, 'queue-item-1');++ expect(store.getState().backendConnection.status).toBe('connected');+ expect(store.getSnapshot().activeProject.queue.items[0]?.status).toBe('cancelled');+ expect(store.getSnapshot().notifications[0]).toMatchObject({+ kind: 'info',+ title: 'Invocation cancellation requested',+ });++ store.commands.queue.clearCompleted();++ expect(store.getSnapshot().activeProject.queue.items.map((item) => item.id)).toEqual(['queue-item-1']);+ });++ it('enforces project lifecycle invariants through observable command results', () => {+ const store = createWorkbenchStore();+ const firstProjectId = store.getSnapshot().activeProject.id;++ expect(store.commands.projects.switchTo('missing')).toEqual({ ok: false, reason: 'project-not-found' });+ expect(store.getSnapshot().activeProject.id).toBe(firstProjectId);++ const secondProject = store.commands.projects.create();++ expect(store.getSnapshot().activeProject.id).toBe(secondProject.id);+ expect(store.commands.projects.switchTo(firstProjectId)).toEqual({ ok: true });+ expect(store.getSnapshot().activeProject.id).toBe(firstProjectId);+ expect(store.commands.projects.close(firstProjectId)).toEqual({ ok: true });+ expect(store.getSnapshot().activeProject.id).toBe(secondProject.id);+ expect(store.commands.projects.close(secondProject.id)).toEqual({ ok: false, reason: 'last-project' });+ expect(store.getSnapshot().notifications[0]).toMatchObject({+ kind: 'error',+ title: 'Project close blocked',+ });+ });++ it('applies Canvas and Workflow edits without exposing aggregate reducer actions', () => {+ const store = createWorkbenchStore();+ const project = store.getSnapshot().activeProject;+ const bbox = project.canvas.document.bbox;++ expect(store.commands.canvas.apply(project.id, { bbox: { ...bbox, x: bbox.x + 10 }, type: 'setCanvasBbox' })).toBe(+ true+ );+ expect(store.getSnapshot().activeProject.canvas.document.bbox.x).toBe(bbox.x + 10);++ store.commands.workflows.editGraph({ patch: { name: 'Command-owned workflow' }, type: 'setMetadata' });++ expect(store.getSnapshot().activeProject.projectGraph.name).toBe('Command-owned workflow');+ });++ it('keeps placement selectors stable across generate and settings changes', () => {const store = createWorkbenchStore();const placementWatcher = watchSelector(store,@@ -311,9 +409,8 @@ describe('createWorkbenchStore', () => {areWidgetPlacementProjectsEqual);- store.dispatch({ batchCount: 2, type: 'setGenerateBatchCount' });- store.dispatch({ backendSupportsCancellation: true, type: 'submitInvocationSnapshot' });- store.dispatch({ settings: { useCpuNoise: false }, type: 'setActiveProjectSettings' });+ store.commands.generation.setBatchCount(2);+ store.commands.account.updateProjectPreferences({ useCpuNoise: false });expect(placementWatcher.changeCount).toBe(0);});diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex 467e293476..db0d4e6b56 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -1,24 +1,377 @@-import type { Dispatch } from 'react';+import type { ProjectGraphAction } from '@features/workflow/utility';+import type { Project, WorkbenchState } from '@workbench/projectContracts';-import type { Project, WorkbenchState } from './types';+import { createExternalStore } from '@platform/state/externalStore';++import type { CanvasProjectMutation } from './canvasProjectMutations';import { recordDiagnosticEntry } from './diagnostics/logger';-import { createExternalStore } from './externalStore';-import { createInitialWorkbenchState, workbenchReducer, type WorkbenchReducerAction } from './workbenchState';+import {+ createInitialWorkbenchState,+ __workbenchReducerInternal,+ type __WorkbenchReducerActionInternal,+} from './workbenchState';++type WorkbenchAction = __WorkbenchReducerActionInternal;+type ActionPayload<Type extends WorkbenchAction['type']> = Omit<Extract<WorkbenchAction, { type: Type }>, 'type'>;+type WorkbenchDispatch = (action: WorkbenchAction) => void;++type MechanicalCommand<Type extends WorkbenchAction['type']> = keyof ActionPayload<Type> extends never+ ? () => void+ : (payload: ActionPayload<Type>) => void;++/**+ * Mechanical commands forward one action to the reducer; their public types derive+ * from the reducer's action union so the two cannot drift. The action union itself+ * stays private — callers only ever see the named command.+ */+const createCommandFactory = (dispatch: WorkbenchDispatch) => {+ function command<Type extends WorkbenchAction['type']>(type: Type): MechanicalCommand<Type>;+ function command<Type extends WorkbenchAction['type'], Args extends unknown[]>(+ type: Type,+ toPayload: (...args: Args) => ActionPayload<Type>+ ): (...args: Args) => void;+ function command(+ type: WorkbenchAction['type'],+ toPayload?: (...args: unknown[]) => Record<string, unknown>+ ): (...args: unknown[]) => void {+ return (...args) => {+ const payload = toPayload ? toPayload(...args) : ((args[0] ?? {}) as Record<string, unknown>);+ dispatch({ ...payload, type } as WorkbenchAction);+ };+ }++ return command;+};++export type ProjectCommandResult =+ | { ok: true }+ | { ok: false; reason: 'invalid-name' | 'last-project' | 'project-not-found' };++const createCommands = (dispatch: WorkbenchDispatch, getState: () => WorkbenchState) => {+ const command = createCommandFactory(dispatch);++ return {+ account: {+ updateProjectPreferences: command(+ 'setActiveProjectSettings',+ (settings: ActionPayload<'setActiveProjectSettings'>['settings']) => ({ settings })+ ),+ },+ canvas: {+ apply: (projectId: string, mutation: CanvasProjectMutation): boolean => {+ const before = getState().projects.find((project) => project.id === projectId)?.canvas;+ if (!before) {+ return false;+ }-type WorkbenchAction = WorkbenchReducerAction;+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' });+ return getState().projects.find((project) => project.id === projectId)?.canvas !== before;+ },+ appendStagingCandidate: command('appendCanvasStagingCandidate'),+ },+ gallery: {+ removeImages: command('removeGalleryImages', (imageNames: string[], projectId?: string) => ({+ imageNames,+ projectId,+ })),+ selectBoard: command('selectGalleryBoard', (boardId: string, projectId?: string) => ({ boardId, projectId })),+ selectImage: command(+ 'selectGalleryImage',+ (image: ActionPayload<'selectGalleryImage'>['image'], projectId?: string) => ({ image, projectId })+ ),+ setCompareImage: command(+ 'setGalleryCompareImage',+ (image: ActionPayload<'setGalleryCompareImage'>['image'], projectId?: string) => ({ image, projectId })+ ),+ setMultiSelection: command(+ 'setGalleryMultiSelection',+ (+ imageNames: string[],+ primaryImage: ActionPayload<'setGalleryMultiSelection'>['primaryImage'],+ projectId?: string+ ) => ({ imageNames, primaryImage, projectId })+ ),+ setPage: command('setGalleryPage', (page: number, projectId?: string) => ({ page, projectId })),+ setPageInfo: command('setGalleryPageInfo', (totalImages: number, projectId?: string) => ({+ projectId,+ totalImages,+ })),+ setProjectBoard: command('setGalleryProjectBoardId', (boardId: string, projectId?: string) => ({+ boardId,+ projectId,+ })),+ setSearchTerm: command('setGallerySearchTerm', (searchTerm: string, projectId?: string) => ({+ projectId,+ searchTerm,+ })),+ setView: command(+ 'setGalleryView',+ (galleryView: ActionPayload<'setGalleryView'>['galleryView'], projectId?: string) => ({+ galleryView,+ projectId,+ })+ ),+ toggleImageSelection: command(+ 'toggleGalleryImageInSelection',+ (image: ActionPayload<'toggleGalleryImageInSelection'>['image'], projectId?: string) => ({+ image,+ projectId,+ })+ ),+ touch: command('touchGalleryRefresh', (projectId?: string) => ({ projectId })),+ touchImages: command('touchGalleryImagesRefresh', (projectId?: string) => ({ projectId })),+ updateSettings: command(+ 'updateGallerySettings',+ (settings: ActionPayload<'updateGallerySettings'>['settings'], projectId?: string) => ({+ projectId,+ settings,+ })+ ),+ },+ generation: {+ clearPromptHistory: command('clearPromptHistory', (projectId?: string) => ({ projectId })),+ patchPromptDraft: command(+ 'patchProjectPromptDraft',+ (values: ActionPayload<'patchProjectPromptDraft'>['values'], projectId?: string) => ({ projectId, values })+ ),+ patchSettings: command(+ 'patchGenerateSettings',+ (values: ActionPayload<'patchGenerateSettings'>['values'], projectId?: string) => ({ projectId, values })+ ),+ removePromptFromHistory: command(+ 'removePromptFromHistory',+ (prompt: ActionPayload<'removePromptFromHistory'>['prompt'], projectId?: string) => ({ projectId, prompt })+ ),+ setBatchCount: command('setGenerateBatchCount', (batchCount: number, projectId?: string) => ({+ batchCount,+ projectId,+ })),+ setDestination: command(+ 'setInvocationDestination',+ (destination: ActionPayload<'setInvocationDestination'>['destination']) => ({ destination })+ ),+ setSettings: command(+ 'setGenerateSettings',+ (values: ActionPayload<'setGenerateSettings'>['values'], projectId?: string) => ({ projectId, values })+ ),+ setSource: command('setInvocationSource', (sourceId: ActionPayload<'setInvocationSource'>['sourceId']) => ({+ sourceId,+ })),+ submitCanvas: command('submitCanvasInvocationSnapshot'),+ submitResolved: command('submitResolvedInvocationSnapshot'),+ toggleDestinationLock: command('toggleDestinationLock'),+ toggleSourceLock: command('toggleSourceLock'),+ },+ layout: {+ applyPreset: command('applyPreset', (presetId: ActionPayload<'applyPreset'>['presetId']) => ({ presetId })),+ createPreset: command(+ 'addLayoutPreset',+ (presetId: ActionPayload<'addLayoutPreset'>['presetId'], label: string) => ({+ label,+ presetId,+ })+ ),+ deletePreset: command('deleteLayoutPreset', (presetId: ActionPayload<'deleteLayoutPreset'>['presetId']) => ({+ presetId,+ })),+ recover: command('recoverShellLayout'),+ renamePreset: command(+ 'renameLayoutPreset',+ (presetId: ActionPayload<'renameLayoutPreset'>['presetId'], label: string) => ({ label, presetId })+ ),+ reset: command('resetActiveLayout'),+ setCenterView: command('setCenterView', (centerViewId: ActionPayload<'setCenterView'>['centerViewId']) => ({+ centerViewId,+ })),+ setRegionCollapsed: command(+ 'setRegionWidgetCollapsed',+ (region: ActionPayload<'setRegionWidgetCollapsed'>['region'], isCollapsed: boolean) => ({+ isCollapsed,+ region,+ })+ ),+ setRegionSize: command(+ 'setRegionWidgetSize',+ (region: ActionPayload<'setRegionWidgetSize'>['region'], sizePx: number) => ({ region, sizePx })+ ),+ },+ notifications: {+ add: command('recordNotice'),+ clear: command('clearNotifications'),+ markAllRead: command('markAllNotificationsRead'),+ recordWidgetFailure: command(+ 'recordWidgetFailure',+ (failure: ActionPayload<'recordWidgetFailure'>['failure']) => ({ failure })+ ),+ reportError: command('recordError'),+ },+ projects: {+ close: (projectId: string): ProjectCommandResult => {+ if (!getState().projects.some((project) => project.id === projectId)) {+ return { ok: false, reason: 'project-not-found' };+ }++ if (getState().projects.length === 1) {+ dispatch({ projectId, type: 'closeProject' });+ return { ok: false, reason: 'last-project' };+ }++ dispatch({ projectId, type: 'closeProject' });+ return { ok: true };+ },+ create: (): Project => {+ dispatch({ type: 'createProject' });+ return getActiveProject(getState());+ },+ open: command('openProject', (project: Project) => ({ project })),+ rename: (projectId: string, name: string): ProjectCommandResult => {+ if (!getState().projects.some((project) => project.id === projectId)) {+ return { ok: false, reason: 'project-not-found' };+ }+ if (!name.trim()) {+ return { ok: false, reason: 'invalid-name' };+ }++ dispatch({ name, projectId, type: 'renameProject' });+ return { ok: true };+ },+ switchTo: (projectId: string): ProjectCommandResult => {+ if (!getState().projects.some((project) => project.id === projectId)) {+ return { ok: false, reason: 'project-not-found' };+ }++ dispatch({ projectId, type: 'switchProject' });+ return { ok: true };+ },+ },+ queue: {+ cancel: command('cancelQueueItem', (projectId: string | undefined, queueItemId: string) => ({+ projectId,+ queueItemId,+ })),+ cancelAll: command('cancelAllQueueItems', (projectId?: string) => ({ projectId })),+ cancelAllExceptCurrent: command(+ 'cancelAllQueueItemsExceptCurrent',+ (projectId?: string, currentQueueItemId?: string | null) => ({ currentQueueItemId, projectId })+ ),+ clearCompleted: command('clearCompletedQueueItems'),+ markBackendCancelled: command('markQueueItemBackendCancelled'),+ markBackendSubmitted: command('markQueueItemBackendSubmitted'),+ refreshBackendData: command('refreshBackendData'),+ routePartialResults: command('routeQueueItemPartialResults'),+ routeResults: command('routeQueueItemResults'),+ setConnectionStatus: command('setBackendConnectionStatus'),+ setStatus: command('setQueueItemStatus'),+ },+ widgets: {+ move: command('moveWidgetInstance'),+ open: command('openRegionWidget'),+ patchInstanceValues: command(+ 'patchWidgetInstanceValues',+ (instanceId: string, values: Record<string, unknown>, projectId?: string) => ({+ instanceId,+ projectId,+ values,+ })+ ),+ patchValues: command(+ 'patchWidgetValues',+ (+ widgetId: ActionPayload<'patchWidgetValues'>['widgetId'],+ values: Record<string, unknown>,+ projectId?: string+ ) => ({+ projectId,+ values,+ widgetId,+ })+ ),+ reorder: command('reorderWidgetInstances'),+ select: command('selectRegionWidget'),+ setInstanceValues: command(+ 'setWidgetInstanceValues',+ (instanceId: string, values: Record<string, unknown>, projectId?: string) => ({+ instanceId,+ projectId,+ values,+ })+ ),+ toggle: command('toggleRegionWidget'),+ },+ workflows: {+ bindLibraryWorkflow: command('setProjectGraphLibraryBinding', (libraryWorkflowId: string) => ({+ libraryWorkflowId,+ })),+ editGraph: command('applyProjectGraphAction', (action: ProjectGraphAction) => ({ action })),+ replace: command(+ 'replaceProjectGraph',+ (document: ActionPayload<'replaceProjectGraph'>['document'], label: string) => ({ document, label })+ ),+ redo: command('redoProjectChange'),+ restoreSnapshot: command('restoreProjectGraphSnapshot', (snapshotId: string) => ({ snapshotId })),+ saveSnapshot: command('saveProjectGraphSnapshot'),+ undo: command('undoProjectChange'),+ },+ };+};++const createPersistenceAdapter = (dispatch: WorkbenchDispatch, getState: () => WorkbenchState) => {+ const command = createCommandFactory(dispatch);++ return {+ getState,+ hydrate: command('hydrateWorkbench', (state: WorkbenchState) => ({ state })),+ reconcileConflict: command('reconcileProjectConflict'),+ saveFailed: command('autosaveFailed', (error: string) => ({ error })),+ saveStarted: command('autosaveStarted'),+ saveSucceeded: command('autosaveSucceeded', (savedAt: string) => ({ savedAt })),+ };+};++export type WorkbenchCommands = ReturnType<typeof createCommands>;+export type WorkbenchAccountCommands = WorkbenchCommands['account'];+export type WorkbenchCanvasCommands = WorkbenchCommands['canvas'];+export type WorkbenchGalleryCommands = WorkbenchCommands['gallery'];+export type WorkbenchGenerationCommands = WorkbenchCommands['generation'];+export type WorkbenchLayoutCommands = WorkbenchCommands['layout'];+export type WorkbenchNotificationCommands = WorkbenchCommands['notifications'];+export type WorkbenchProjectCommands = WorkbenchCommands['projects'];+export type WorkbenchQueueCommands = WorkbenchCommands['queue'];+export type WorkbenchWidgetCommands = WorkbenchCommands['widgets'];+export type WorkbenchWorkflowCommands = WorkbenchCommands['workflows'];++export type WorkbenchPersistenceCommands = ReturnType<typeof createPersistenceAdapter>;++export interface WorkbenchInternalAdapters {+ persistence: WorkbenchPersistenceCommands;+}export interface WorkbenchSnapshot {- state: WorkbenchState;activeProject: Project;+ account: WorkbenchState['account'];+ autosave: WorkbenchState['autosave'];+ backendConnection: WorkbenchState['backendConnection'];hasHydrated: boolean;+ notifications: WorkbenchState['notifications'];+ projects: WorkbenchState['projects'];}-export interface WorkbenchStore {- dispatch: Dispatch<WorkbenchAction>;+/** Imperative, read-only views for event handlers that must observe post-flush state. */+export interface WorkbenchQueries {+ getProject(projectId: string): Project | null;+ getSnapshot(): WorkbenchSnapshot;+ isActiveProject(projectId: string): boolean;+}++export interface WorkbenchInternalStore {+ commands: WorkbenchCommands;getPersistedRevision: () => number;getSnapshot: () => WorkbenchSnapshot;getState: () => WorkbenchState;+ /** Privileged implementation adapters; never exposed through React hooks. */+ internal: WorkbenchInternalAdapters;+ queries: WorkbenchQueries;setHasHydrated: (hasHydrated: boolean) => void;subscribe: (listener: () => void) => () => void;}@@ -27,9 +380,13 @@ const getActiveProject = (state: WorkbenchState): Project =>state.projects.find((project) => project.id === state.activeProjectId) ?? state.projects[0];const createSnapshot = (state: WorkbenchState, hasHydrated: boolean): WorkbenchSnapshot => ({+ account: state.account,activeProject: getActiveProject(state),+ autosave: state.autosave,+ backendConnection: state.backendConnection,hasHydrated,- state,+ notifications: state.notifications,+ projects: state.projects,});const hasPersistedStateChanged = (previous: WorkbenchState, next: WorkbenchState): boolean =>@@ -105,7 +462,7 @@ const recordDiagnosticForAction = (}};-export const createWorkbenchStore = (initialState = createInitialWorkbenchState()): WorkbenchStore => {+export const createWorkbenchStore = (initialState = createInitialWorkbenchState()): WorkbenchInternalStore => {let state = initialState;let hasHydrated = false;let persistedRevision = 0;@@ -125,20 +482,30 @@ export const createWorkbenchStore = (initialState = createInitialWorkbenchState(snapshotStore.setSnapshot(createSnapshot(state, hasHydrated));};- return {- dispatch(action) {- const previousState = state;- const nextState = workbenchReducer(state, action);+ const dispatch = (action: WorkbenchAction): void => {+ const previousState = state;+ const nextState = __workbenchReducerInternal(state, action);- setSnapshotState(nextState);- recordDiagnosticForAction(action, previousState, nextState);- },+ setSnapshotState(nextState);+ recordDiagnosticForAction(action, previousState, nextState);+ };++ const getState = (): WorkbenchState => state;++ return {+ commands: createCommands(dispatch, getState),getPersistedRevision: () => persistedRevision,getSnapshot: snapshotStore.getSnapshot,- getState: () => state,+ getState,+ internal: {+ persistence: createPersistenceAdapter(dispatch, getState),+ },+ queries: {+ getProject: (projectId) => state.projects.find((project) => project.id === projectId) ?? null,+ getSnapshot: snapshotStore.getSnapshot,+ isActiveProject: (projectId) => state.activeProjectId === projectId,+ },setHasHydrated: (nextHasHydrated) => setSnapshotState(state, nextHasHydrated),subscribe: snapshotStore.subscribe,};};--export type { WorkbenchAction };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/index.ts b/invokeai/frontend/webv2/src/workbench/workflowWidgetManifest.tssimilarity index 57%rename from invokeai/frontend/webv2/src/workbench/widgets/workflow/index.tsrename to invokeai/frontend/webv2/src/workbench/workflowWidgetManifest.tsindex d9c9afa37d..3a3442b31d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/index.ts+++ b/invokeai/frontend/webv2/src/workbench/workflowWidgetManifest.ts@@ -1,15 +1,8 @@-import type { WidgetManifest } from '@workbench/types';+import type { WidgetManifest } from '@workbench/widgetContracts';+import { loadWorkflowWidgetImplementation } from '@features/workflow/widget';import { WorkflowIcon } from 'lucide-react';-import {- WorkflowDialogHost,- WorkflowHeaderActions,- WorkflowMenuItems,- WorkflowWidgetLabel,-} from './WorkflowWidgetChrome';-import { WorkflowWidgetView } from './WorkflowWidgetView';-export const workflowWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['center', 'left', 'bottom'],@@ -20,14 +13,11 @@ export const workflowWidgetManifest: WidgetManifest = {sourceId: 'workflow',surfaces: ['center', 'left', 'bottom'],},- host: WorkflowDialogHost,- headerActions: WorkflowHeaderActions,- headerMenu: WorkflowMenuItems,+ hasHost: true,icon: WorkflowIcon,id: 'workflow',- headerLabel: WorkflowWidgetLabel,label: (t) => t('widgets.labels.workflow'),+ load: loadWorkflowWidgetImplementation,settingsSection: 'workflow',version: 1,- view: WorkflowWidgetView,};diff --git a/invokeai/frontend/webv2/tsconfig.json b/invokeai/frontend/webv2/tsconfig.jsonindex 48f8b3974a..2c88a1a3b9 100644--- a/invokeai/frontend/webv2/tsconfig.json+++ b/invokeai/frontend/webv2/tsconfig.json@@ -20,8 +20,14 @@"@/*": ["./src/*"],"@assets": ["./src/assets"],"@assets/*": ["./src/assets/*"],- "@theme": ["./src/theme"],- "@theme/*": ["./src/theme/*"],+ "@app": ["./src/app"],+ "@app/*": ["./src/app/*"],+ "@features": ["./src/features"],+ "@features/*": ["./src/features/*"],+ "@platform": ["./src/platform"],+ "@platform/*": ["./src/platform/*"],+ "@theme": ["./src/platform/ui/theme"],+ "@theme/*": ["./src/platform/ui/theme/*"],"@workbench": ["./src/workbench"],"@workbench/*": ["./src/workbench/*"]}diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex 8cab295849..2de1b27be2 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -11,6 +11,7 @@ const BACKEND_WS_URL = BACKEND_URL.replace(/^http/, 'ws');export default defineConfig({base: './',build: {+ manifest: true,rollupOptions: {output: {manualChunks(id) {@@ -52,8 +53,11 @@ export default defineConfig({resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url)),+ '@app': fileURLToPath(new URL('./src/app', import.meta.url)),'@assets': fileURLToPath(new URL('./src/assets', import.meta.url)),- '@theme': fileURLToPath(new URL('./src/theme', import.meta.url)),+ '@features': fileURLToPath(new URL('./src/features', import.meta.url)),+ '@platform': fileURLToPath(new URL('./src/platform', import.meta.url)),+ '@theme': fileURLToPath(new URL('./src/platform/ui/theme', import.meta.url)),'@workbench': fileURLToPath(new URL('./src/workbench', import.meta.url)),},},diff --git a/invokeai/frontend/webv2/vitest.browser.config.mts b/invokeai/frontend/webv2/vitest.browser.config.mtsindex d2e6b12c46..aaef995817 100644--- a/invokeai/frontend/webv2/vitest.browser.config.mts+++ b/invokeai/frontend/webv2/vitest.browser.config.mts@@ -7,9 +7,10 @@ import viteConfig from './vite.config.mts';export default mergeConfig(viteConfig,defineConfig({- // dnd-kit must share the app's React instance in the browser-test module- // graph, or its hooks dispatch against a second React copy and crash.- optimizeDeps: { include: ['@dnd-kit/core'] },+ // Hook-bearing dependencies must be prebundled into the initial browser-test+ // graph. An optimization reload can otherwise leave the running suite with+ // two React instances and produce invalid-hook failures.+ optimizeDeps: { include: ['@dnd-kit/core', '@tanstack/react-query'] },test: {browser: {enabled: true,