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
feat(ui): redesign workbench topbar
joshistoastb7fb03205c12
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex f0ce49adfb..835088bfda 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -2,17 +2,17 @@"build": {"launchpad": {"baseline": {- "brotliBytes": 803553,+ "brotliBytes": 809141,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 803395,+ "gzipBytes": 808482,"imageRawBytes": 156376,- "initialRawBytes": 1845221,+ "initialRawBytes": 1856269,"largestAssetRawBytes": 738008,"otherAssetRawBytes": 0,- "ownedRawBytes": 57941,- "requestCount": 31,- "scriptRequestCount": 15,+ "ownedRawBytes": 34127,+ "requestCount": 38,+ "scriptRequestCount": 22,"sourceOwners": ["package:@ark-ui/react","package:@chakra-ui/react",@@ -136,6 +136,7 @@"source:src/features/identity/session.ts","source:src/features/identity/transportAdapter.ts","source:src/features/identity/ui/AccountMenu.tsx",+ "source:src/features/identity/ui/AccountMenuSection.tsx","source:src/features/identity/ui/AuthScreen.tsx","source:src/features/identity/ui/AuthUnavailableScreen.tsx","source:src/features/identity/ui/LoginScreen.tsx",@@ -187,6 +188,7 @@"source:src/platform/ui/ConfirmDialog.tsx","source:src/platform/ui/DropZone.tsx","source:src/platform/ui/Field.tsx",+ "source:src/platform/ui/Group.tsx","source:src/platform/ui/InvokeMark.tsx","source:src/platform/ui/JsonPreview.tsx","source:src/platform/ui/Menu.tsx",@@ -232,26 +234,26 @@"source:src/workbench/projects/api.ts","source:src/workbench/projects/ids.ts","source:src/workbench/projects/library.ts",- "source:src/workbench/projects/projectDocument.ts","source:src/workbench/projects/projectFile.ts","source:src/workbench/projects/session.ts","source:src/workbench/settings/SettingsButton.tsx",+ "source:src/workbench/settings/SettingsDialogHost.tsx","source:src/workbench/settings/settingsDialogStore.ts","source:src/workbench/settings/store.ts"]},"limits": {- "brotliBytes": 811589,+ "brotliBytes": 817233,"cssRawBytes": 2181,"fontRawBytes": 221675,- "gzipBytes": 811429,+ "gzipBytes": 816567,"imageRawBytes": 157940,- "initialRawBytes": 1863674,+ "initialRawBytes": 1874832,"largestAssetRawBytes": 745389,"otherAssetRawBytes": 0,- "ownedRawBytes": 57941,- "requestCount": 31,- "scriptRequestCount": 15+ "ownedRawBytes": 34127,+ "requestCount": 38,+ "scriptRequestCount": 22},"owner": "app","remediationTicket": "set-performance-budgets",@@ -259,17 +261,17 @@},"editor": {"baseline": {- "brotliBytes": 992202,+ "brotliBytes": 991733,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 990803,+ "gzipBytes": 989455,"imageRawBytes": 156376,- "initialRawBytes": 2423190,+ "initialRawBytes": 2417497,"largestAssetRawBytes": 738008,"otherAssetRawBytes": 0,- "ownedRawBytes": 110967,- "requestCount": 73,- "scriptRequestCount": 57,+ "ownedRawBytes": 118082,+ "requestCount": 79,+ "scriptRequestCount": 63,"sourceOwners": ["package:@ark-ui/react","package:@chakra-ui/react",@@ -380,24 +382,15 @@"package:use-sync-external-store","package:zod","package:zustand",- "source:index.html",- "source:src/app/App.tsx",- "source:src/app/AppProviders.tsx","source:src/app/GalleryUiAdapter.tsx","source:src/app/GenerateWidgetSyncRuntime.tsx","source:src/app/GenerationUiAdapter.tsx",- "source:src/app/I18nController.tsx","source:src/app/ModelsUiAdapter.tsx","source:src/app/QueueRuntimeAdapter.tsx","source:src/app/QueueUiAdapter.tsx",- "source:src/app/SocketHubRuntime.tsx",- "source:src/app/ThemeController.tsx","source:src/app/UpscaleUiAdapter.tsx","source:src/app/WorkbenchApp.tsx","source:src/app/WorkflowUiAdapter.tsx",- "source:src/app/accountLifecycle.ts",- "source:src/app/main.tsx",- "source:src/app/router.tsx","source:src/app/workbenchPorts.tsx","source:src/assets/SplashImage.webp","source:src/features/gallery/contracts.ts",@@ -466,6 +459,7 @@"source:src/features/identity/session.ts","source:src/features/identity/transportAdapter.ts","source:src/features/identity/ui/AccountMenu.tsx",+ "source:src/features/identity/ui/AccountMenuSection.tsx","source:src/features/identity/ui/AuthScreen.tsx","source:src/features/identity/ui/AuthUnavailableScreen.tsx","source:src/features/identity/ui/LoginScreen.tsx",@@ -548,7 +542,6 @@"source:src/features/workflow/utility.ts","source:src/features/workflow/widget.ts","source:src/platform/browser/downloadBlob.ts",- "source:src/platform/browser/knownBrowserIssues.ts","source:src/platform/core/json.ts","source:src/platform/i18n/client.ts","source:src/platform/i18n/languages.ts",@@ -577,6 +570,7 @@"source:src/platform/ui/ConfirmDialog.tsx","source:src/platform/ui/DropZone.tsx","source:src/platform/ui/Field.tsx",+ "source:src/platform/ui/Group.tsx","source:src/platform/ui/InvokeMark.tsx","source:src/platform/ui/JsonPreview.tsx","source:src/platform/ui/Menu.tsx",@@ -634,6 +628,7 @@"source:src/workbench/focusRegions.tsx","source:src/workbench/graphPreviewInvocation.ts","source:src/workbench/graphSurfaces.ts",+ "source:src/workbench/graphWidgets.ts","source:src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx","source:src/workbench/hotkeys/catalog.ts","source:src/workbench/hotkeys/extensionHotkeys.ts",@@ -646,20 +641,9 @@"source:src/workbench/iconResolver.tsx","source:src/workbench/invocation.ts","source:src/workbench/invocationSubmit.ts",- "source:src/workbench/launchpad/KnownBrowserIssuesAlert.tsx",- "source:src/workbench/launchpad/Launchpad.tsx",- "source:src/workbench/launchpad/LaunchpadNav.tsx",- "source:src/workbench/launchpad/LaunchpadTopBar.tsx",- "source:src/workbench/launchpad/NewProjectCard.tsx",- "source:src/workbench/launchpad/ProjectCard.tsx",- "source:src/workbench/launchpad/ProjectsGrid.tsx",- "source:src/workbench/launchpad/ResourceLinks.tsx","source:src/workbench/launchpad/formatRelativeTime.ts",- "source:src/workbench/launchpad/pages/ProjectsPage.tsx","source:src/workbench/layoutPresetSnapshots.ts","source:src/workbench/layoutPresets.ts",- "source:src/workbench/palette/LaunchpadCommandPalette.tsx",- "source:src/workbench/palette/PaletteButton.tsx","source:src/workbench/palette/WorkbenchCommandPalette.tsx","source:src/workbench/palette/paletteStore.ts","source:src/workbench/palette/settingsEntryDeps.ts",@@ -668,7 +652,6 @@"source:src/workbench/persistenceRuntime.ts","source:src/workbench/projects/api.ts","source:src/workbench/projects/components/OpenProjectDialog.tsx",- "source:src/workbench/projects/components/ProjectTabs.tsx","source:src/workbench/projects/components/index.ts","source:src/workbench/projects/ids.ts","source:src/workbench/projects/library.ts",@@ -680,7 +663,7 @@"source:src/workbench/projects/syncedPersistence.ts","source:src/workbench/projects/useProjectActions.ts","source:src/workbench/queueHistoryNormalization.ts",- "source:src/workbench/settings/SettingsButton.tsx",+ "source:src/workbench/settings/SettingsDialogHost.tsx","source:src/workbench/settings/settingsDialogStore.ts","source:src/workbench/settings/store.ts","source:src/workbench/shell/BottomPanel.tsx",@@ -691,17 +674,29 @@"source:src/workbench/shell/index.ts","source:src/workbench/shell/notifications/WorkbenchNotificationToaster.tsx","source:src/workbench/shell/notifications/index.ts",- "source:src/workbench/shell/topbar/BatchCountField.tsx",- "source:src/workbench/shell/topbar/InvokeControl.tsx",- "source:src/workbench/shell/topbar/LayoutPresetMenu.tsx",- "source:src/workbench/shell/topbar/ModelManagerButton.tsx",- "source:src/workbench/shell/topbar/NodeManagerButton.tsx",- "source:src/workbench/shell/topbar/QueueActions.tsx",- "source:src/workbench/shell/topbar/QueueInfo.tsx",+ "source:src/workbench/shell/topbar/AppMenu.tsx",+ "source:src/workbench/shell/topbar/InvocationCluster.tsx",+ "source:src/workbench/shell/topbar/InvokeButton.tsx",+ "source:src/workbench/shell/topbar/IterationsField.tsx",+ "source:src/workbench/shell/topbar/LayoutPresetDialog.tsx",+ "source:src/workbench/shell/topbar/LayoutPresetManagerDialog.tsx",+ "source:src/workbench/shell/topbar/LayoutPresetStrip.tsx",+ "source:src/workbench/shell/topbar/ProjectSwitcher.tsx",+ "source:src/workbench/shell/topbar/QueueCluster.tsx",+ "source:src/workbench/shell/topbar/RoutingControl.tsx","source:src/workbench/shell/topbar/TopBar.tsx","source:src/workbench/shell/topbar/index.ts",+ "source:src/workbench/shell/topbar/layoutPresetIcons.ts",+ "source:src/workbench/shell/topbar/layoutPresetManagerStore.ts",+ "source:src/workbench/shell/topbar/layoutPresetPresentation.ts",+ "source:src/workbench/shell/topbar/projectSwitcherStore.ts",+ "source:src/workbench/shell/topbar/topbarBreakpoints.ts",+ "source:src/workbench/shell/topbar/useInvocationState.ts",+ "source:src/workbench/shell/topbar/useLayoutDrift.ts",+ "source:src/workbench/shell/topbar/useTopbarShortcut.ts","source:src/workbench/useNotify.ts","source:src/workbench/useOpenWorkbenchWidget.ts",+ "source:src/workbench/useWidgetSurfaceFocus.ts","source:src/workbench/widget-frame/WidgetActionsMenu.tsx","source:src/workbench/widget-frame/WidgetBar.tsx","source:src/workbench/widget-frame/WidgetEnableMenu.tsx",@@ -713,6 +708,7 @@"source:src/workbench/widget-frame/WidgetLoadingFallback.tsx","source:src/workbench/widget-frame/WidgetRegionDropOverlay.tsx","source:src/workbench/widget-frame/WidgetRenderer.tsx",+ "source:src/workbench/widget-frame/WidgetSourceLockBadge.tsx","source:src/workbench/widget-frame/WidgetStrip.tsx","source:src/workbench/widget-frame/createWidgetRuntime.ts","source:src/workbench/widget-frame/index.ts",@@ -749,24 +745,24 @@]},"limits": {- "brotliBytes": 1002125,+ "brotliBytes": 1001651,"cssRawBytes": 2181,"fontRawBytes": 221675,- "gzipBytes": 1000712,+ "gzipBytes": 999350,"imageRawBytes": 157940,- "initialRawBytes": 2447422,+ "initialRawBytes": 2441672,"largestAssetRawBytes": 745389,"otherAssetRawBytes": 0,- "ownedRawBytes": 110967,- "requestCount": 73,- "scriptRequestCount": 57+ "ownedRawBytes": 118082,+ "requestCount": 79,+ "scriptRequestCount": 63},"owner": "workbench","remediationTicket": "deepen-widget-registry-loading","source": "src/app/WorkbenchApp.tsx"}},- "capturedAt": "2026-07-31",+ "capturedAt": "2026-08-01","developmentInvalidation": {"platformUiBarrel": {"specifier": "@platform/ui",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 21c7426128..e620217f91 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -305,6 +305,96 @@},"markRead": "Mark Read"},+ "topbar": {+ "appMenu": {+ "documentation": "Documentation",+ "manage": "Manage",+ "open": "Open menu"+ },+ "invoke": {+ "addToQueue": "Add to queue",+ "addingImagesTo": "Adding images to {{destination}}",+ "expandingPrompts": "Expanding prompts…",+ "invoke": "Invoke",+ "noNodes": "No nodes in graph",+ "unavailable": "Invoke unavailable: {{reason}}",+ "unrunnable": "route is not runnable",+ "unableToQueue": "Unable to queue"+ },+ "iterations": {+ "label": "Iterations",+ "tooltip_one": "{{count}} iteration per invoke",+ "tooltip_other": "{{count}} iterations per invoke"+ },+ "presets": {+ "builtIn": "Built-in",+ "custom": "Custom",+ "customLayouts": "Custom layouts",+ "delete": "Delete preset",+ "deleteBody": "Delete “{{name}}”? This only removes the saved preset.",+ "deleteNamed": "Delete {{name}}",+ "deleteQuestion": "Delete layout preset?",+ "deleteWithEllipsis": "Delete preset…",+ "edit": "Edit layout preset",+ "editNamed": "Edit {{name}}",+ "editWithEllipsis": "Edit preset…",+ "icon": "Icon",+ "iconPicker": "Layout preset icon",+ "layoutPreset": "Layout preset",+ "manage": "Manage presets",+ "more": "More layout presets",+ "moreAvailable": "More layout presets, {{count}} available",+ "name": "Preset name",+ "none": "No custom presets yet. Arrange the dock, then choose Save as new preset.",+ "restore": "Restore the shipped arrangement",+ "restoreNamed": "Restore {{name}} default",+ "revert": "Revert to saved layout",+ "save": "Save preset",+ "saveAs": "Save as new preset",+ "saveAsTooltip": "Save this layout as a new preset",+ "saveChanges": "Save changes",+ "switch": "Switch to this layout",+ "unsaved": "Unsaved changes"+ },+ "projectSwitcher": {+ "trigger": "Switch project. Current project: {{name}}"+ },+ "queue": {+ "actions": "Queue actions",+ "backendBatch": "Backend batch {{id}}",+ "backendItem": "backend item {{id}}",+ "batchImage": "Batch image {{current}}/{{total}}",+ "currentImageProgress": "Current image progress",+ "idle": "Queue idle",+ "imageProgress": "Image {{current}} of {{total}}",+ "imageProgressPercent": "Image {{current}} of {{total}}, {{percent}} percent",+ "loadingImage": "Loading image {{current}}/{{total}}",+ "loadingModels": "Loading models",+ "loadingModelsCount_one": "Loading {{count}} model",+ "loadingModelsCount_other": "Loading {{count}} models",+ "more": "{{count}} more…",+ "noActiveBatches": "No active or pending generation batches.",+ "queuedImages_one": "{{count}} image queued.",+ "queuedImages_other": "{{count}} images queued.",+ "queueItem": "Queue item {{id}}",+ "remaining_one": "{{count}} image remaining. Open queue",+ "remaining_other": "{{count}} images remaining. Open queue",+ "route": "{{source}} to {{destination}} · {{graph}}",+ "waitingForProgress": "Backend accepted batch; waiting for progress event.",+ "waitingToStart": "Waiting to start"+ },+ "routing": {+ "change": "Change routing",+ "destination": "Destination",+ "lockDestination": "Lock output destination",+ "lockRouting": "Lock routing",+ "lockSource": "Lock source",+ "source": "Source",+ "unlockDestination": "Unlock output destination",+ "unlockRouting": "Unlock routing",+ "unlockSource": "Unlock source"+ }+ },"projects": {"allSavedAlreadyOpen": "All saved projects are already open.","closeProjectLabel": "Close {{name}}",diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjsindex 1080744044..1db35049c2 100644--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs@@ -47,7 +47,7 @@ const waitForSettledDocument = async (page) => {});};-const openRepresentativePage = async (browser, path) => {+const openRepresentativePage = async (browser, path, viewport = { height: 1_000, width: 1_440 }) => {const resetResponse = await fetch(`${backendOrigin}/__reset?profile=representative`, { method: 'POST' });if (!resetResponse.ok) {@@ -57,7 +57,7 @@ const openRepresentativePage = async (browser, path) => {const context = await browser.newContext({colorScheme: 'dark',reducedMotion: 'reduce',- viewport: { height: 1_000, width: 1_440 },+ viewport,});const page = await context.newPage();const pageErrors = [];@@ -89,20 +89,42 @@ const waitForNodes = async (page) => {await page.getByText('fixture-pack-01', { exact: true }).waitFor();};+const presetStrip = (page) => page.getByRole('tablist', { exact: true, name: 'Layout preset' });+const waitForWorkbench = async (page) => {await page.getByRole('main', { exact: true, name: 'Fixture Project 001' }).waitFor();- await page.getByRole('button', { name: /^Layout preset:/ }).waitFor();+ await presetStrip(page).waitFor();};const centerViewTrigger = (page, label) => page.getByRole('button', { exact: true, name: `Center view: ${label}` });-const selectLayoutPreset = async (page, preset) => {- const trigger = page.getByRole('button', { name: /^Layout preset:/ });+/**+ * Presets are a segmented radio group, and they name an arrangement rather than+ * a widget — so the center view a preset lands on is passed explicitly instead+ * of being assumed to share its name.+ */+const selectLayoutPreset = async (page, preset, centerView) => {+ // Anchored at both ends, because custom presets share the strip: a loose+ // `^Edit` also matches a user's "Edit copy". The optional suffix is the drift+ // marker the tab folds into its own accessible name.+ const name = new RegExp(`^${preset}(, unsaved changes)?$`);+ const selected = page.getByRole('tab', { name, selected: true });++ if ((await selected.count()) === 0) {+ await page.getByRole('tab', { name }).click();+ }++ await selected.waitFor();+ await centerViewTrigger(page, centerView).waitFor();+};++/** Compose keeps a Gallery in the right rail too, so gallery locators are scoped. */+const centerRegion = (page) => page.getByRole('region', { exact: true, name: 'Center view' });- await trigger.click();- await page.getByRole('menuitem', { exact: true, name: preset }).click();- await page.getByRole('button', { exact: true, name: `Layout preset: ${preset}` }).waitFor();- await centerViewTrigger(page, preset).waitFor();+const selectCenterView = async (page, from, to) => {+ await centerViewTrigger(page, from).click();+ await page.getByRole('menuitemradio', { exact: true, name: to }).click();+ await centerViewTrigger(page, to).waitFor();};const surfaces = [@@ -134,16 +156,19 @@ const surfaces = [path: representativeProjectPath,ready: async (page) => {await waitForWorkbench(page);- await selectLayoutPreset(page, 'Canvas');+ await selectLayoutPreset(page, 'Edit', 'Canvas');},},{id: 'workbench-gallery-representative',path: representativeProjectPath,ready: async (page) => {+ // Gallery is a widget, not an arrangement, so it is reached through the+ // center area's own picker rather than by loading a preset named after it.await waitForWorkbench(page);- await selectLayoutPreset(page, 'Gallery');- await page.getByRole('list', { exact: true, name: 'Gallery items' }).waitFor();+ await selectLayoutPreset(page, 'Compose', 'Preview');+ await selectCenterView(page, 'Preview', 'Gallery');+ await centerRegion(page).getByRole('list', { exact: true, name: 'Gallery items' }).waitFor();},},{@@ -151,7 +176,7 @@ const surfaces = [path: representativeProjectPath,ready: async (page) => {await waitForWorkbench(page);- await selectLayoutPreset(page, 'Workflow');+ await selectLayoutPreset(page, 'Automate', 'Workflow');await page.getByText('Fixture Node 001', { exact: true }).waitFor();},},@@ -190,7 +215,19 @@ const expectFocused = async (locator, message) => {}if (Date.now() >= deadline) {- assert.fail(message);+ const activeElement = await locator.page().evaluate(() => {+ const active = document.activeElement;++ return active instanceof HTMLElement+ ? {+ ariaLabel: active.getAttribute('aria-label'),+ role: active.getAttribute('role'),+ tagName: active.tagName,+ text: active.innerText.slice(0, 200),+ }+ : null;+ });+ assert.fail(`${message} Active element: ${JSON.stringify(activeElement)}.`);}await new Promise((resolveWait) => {@@ -244,26 +281,272 @@ const runKeyboardJourney = async (browser) => {await previewTrigger.focus();await previewTrigger.press('Enter');+ const previewItem = page.getByRole('menuitemradio', { exact: true, name: 'Preview' });const canvasItem = page.getByRole('menuitemradio', { exact: true, name: 'Canvas' });+ const centerViewMenu = page.getByRole('menu');await canvasItem.waitFor();- assert.equal(- await page.getByRole('menuitemradio', { exact: true, name: 'Preview' }).getAttribute('aria-checked'),- 'true'+ assert.equal(await previewItem.getAttribute('aria-checked'), 'true');+ await expectFocused(centerViewMenu, 'Opening the center view menu should focus its composite.');+ assert.equal(await centerViewMenu.getAttribute('aria-activedescendant'), await previewItem.getAttribute('id'));+ await centerViewMenu.press('ArrowDown');+ assert.equal(await centerViewMenu.getAttribute('aria-activedescendant'), await canvasItem.getAttribute('id'));+ await centerViewMenu.press('Enter');+ const canvasTrigger = centerViewTrigger(page, 'Canvas');+ await canvasTrigger.waitFor();+ await expectFocused(canvasTrigger, 'Selecting a center view should restore focus to the view selector.');++ if (pageErrors.length > 0) {+ throw new AggregateError(pageErrors, 'keyboard-critical-journey raised uncaught browser errors.');+ }++ return { id: 'keyboard-critical-journey', status: 'passed' };+ } finally {+ await context.close();+ }+};++const runResponsiveTopbarJourney = async (browser) => {+ const { context, page, pageErrors } = await openRepresentativePage(browser, representativeProjectPath, {+ height: 900,+ width: 1_024,+ });+ const id = 'workbench-topbar-responsive';++ try {+ await waitForWorkbench(page);+ await page.getByRole('button', { exact: true, name: '0 images remaining. Open queue' }).waitFor();++ for (const width of [1_024, 900]) {+ await page.setViewportSize({ height: 900, width });+ await waitForSettledDocument(page);++ const metrics = await page.locator('header').evaluate((header) => {+ const bounds = header.getBoundingClientRect();+ const zones = [...header.children].map((element) => element.getBoundingClientRect());+ const centerZone = zones[1];++ return {+ centerOffset: Math.abs(bounds.left + bounds.width / 2 - (centerZone.left + centerZone.width / 2)),+ clientWidth: header.clientWidth,+ controlsInsideHeader: [...header.querySelectorAll('button')].every((button) => {+ const controlBounds = button.getBoundingClientRect();++ return controlBounds.left >= bounds.left && controlBounds.right <= bounds.right;+ }),+ scrollWidth: header.scrollWidth,+ zonesDoNotOverlap: zones.every((zone, index) => index === 0 || zones[index - 1].right <= zone.left),+ };+ });++ assert.equal(metrics.scrollWidth, metrics.clientWidth, `The topbar must not overflow at ${width}px.`);+ assert.equal(metrics.controlsInsideHeader, true, `Every topbar control must remain visible at ${width}px.`);+ assert.equal(metrics.zonesDoNotOverlap, true, `Topbar zones must not overlap at ${width}px.`);+ assert.ok(+ metrics.centerOffset <= 0.5,+ `The preset strip must be centered at ${width}px (offset: ${metrics.centerOffset.toFixed(2)}px).`+ );+ }++ if (pageErrors.length > 0) {+ throw new AggregateError(pageErrors, `${id} raised uncaught browser errors.`);+ }++ return { id, status: 'passed' };+ } finally {+ await context.close();+ }+};++const runTopbarMenuJourney = async (browser) => {+ const { context, page, pageErrors } = await openRepresentativePage(browser, representativeProjectPath);+ const id = 'workbench-topbar-menus';++ try {+ await waitForWorkbench(page);++ const leftWidgetRail = page.getByRole('navigation', { exact: true, name: 'Left widget visibility' });+ const upscaleWidget = leftWidgetRail.getByRole('button', { exact: true, name: 'Upscale' });+ await upscaleWidget.click({ button: 'right' });+ await page.getByRole('menuitem', { exact: true, name: 'Remove Upscale' }).click();+ assert.equal(await upscaleWidget.count(), 0);+ const activeLeftWidget = leftWidgetRail.getByRole('button', { pressed: true });+ const activeLeftWidgetName = await activeLeftWidget.getAttribute('aria-label');+ assert.ok(activeLeftWidgetName);++ const routingTrigger = page.getByRole('button', { name: /^Invoke from/ });+ await routingTrigger.hover();+ const routingTooltip = page.getByRole('tooltip', { exact: true, name: 'Change routing' });+ await routingTooltip.waitFor({ timeout: 2_000 });+ const [routingTriggerBounds, routingTooltipBounds] = await Promise.all([+ routingTrigger.boundingBox(),+ routingTooltip.boundingBox(),+ ]);+ assert.ok(routingTriggerBounds);+ assert.ok(routingTooltipBounds);+ assert.ok(+ routingTooltipBounds.x < routingTriggerBounds.x + routingTriggerBounds.width &&+ routingTooltipBounds.x + routingTooltipBounds.width > routingTriggerBounds.x,+ 'The routing tooltip should be anchored to and horizontally overlap its trigger.');+ await routingTrigger.click();+ const routingMenu = page.getByRole('menu');+ const sourceHeading = routingMenu.getByText('Source', { exact: true });+ const destinationHeading = routingMenu.getByText('Destination', { exact: true });+ const lockRouting = routingMenu.getByRole('menuitem', { exact: true, name: 'Lock routing' });+ await sourceHeading.waitFor();+ await destinationHeading.waitFor();+ await lockRouting.waitFor();+ assert.equal(await routingMenu.getByRole('button', { name: /^(?:Lock|Unlock)/ }).count(), 0);+ assert.equal(await routingMenu.getByText('Opens', { exact: true }).count(), 0);+ assert.equal(await routingMenu.getByText('Selected', { exact: true }).count(), 0);++ await lockRouting.click();+ const lockedRoutingTrigger = page.getByRole('button', {+ exact: true,+ name: 'Invoke from workflow, output to gallery, source locked, destination locked',+ });+ await lockedRoutingTrigger.waitFor();+ await lockedRoutingTrigger.click();+ const unlockRouting = page.getByRole('menu').getByRole('menuitem', { exact: true, name: 'Unlock routing' });+ await unlockRouting.click();+ await page+ .getByRole('button', {+ exact: true,+ name: 'Invoke from workflow, output to gallery, following edits',+ })+ .waitFor();++ await routingTrigger.click();++ await routingMenu.getByRole('menuitemradio', { name: /^Upscale/ }).click();+ await page.getByRole('button', { name: /^No source widget open/ }).waitFor();+ await centerViewTrigger(page, 'Preview').waitFor();+ assert.equal(await upscaleWidget.count(), 0);+ assert.equal(await activeLeftWidget.getAttribute('aria-label'), activeLeftWidgetName);++ await page.getByRole('button', { exact: true, name: 'Open menu' }).click();+ const appMenu = page.getByRole('menu', { exact: true, name: 'Open menu' });+ const commandPaletteItem = page.getByRole('menuitem', { name: /^Command palette/ });+ const settingsItem = page.getByRole('menuitem', { exact: true, name: 'Settings' });+ const documentationItem = page.getByRole('menuitem', { exact: true, name: 'Documentation' });+ const discordItem = page.getByRole('menuitem', { exact: true, name: 'Discord' });+ await commandPaletteItem.waitFor();+ await settingsItem.waitFor();+ await documentationItem.waitFor();+ await discordItem.waitFor();++ const footerMetrics = await appMenu.evaluate((menu) => {+ const menuBounds = menu.getBoundingClientRect();+ const footerItems = [...menu.querySelectorAll('[role="menuitem"]')].slice(-4);++ return {+ itemsFit: footerItems.every((item) => {+ const bounds = item.getBoundingClientRect();++ return bounds.left >= menuBounds.left && bounds.right <= menuBounds.right && bounds.width <= 32.5;+ }),+ menuClientWidth: menu.clientWidth,+ menuScrollWidth: menu.scrollWidth,+ };+ });+ assert.equal(footerMetrics.itemsFit, true);+ assert.equal(footerMetrics.menuScrollWidth, footerMetrics.menuClientWidth);++ await expectFocused(appMenu, 'Opening the app menu should focus its composite.');+ assert.notEqual(await appMenu.getAttribute('aria-activedescendant'), await commandPaletteItem.getAttribute('id'));+ await new Promise((resolveWait) => {+ setTimeout(resolveWait, 750);+ });+ assert.equal(await page.getByRole('tooltip', { name: /^Command palette/ }).count(), 0);- await canvasItem.click();- await centerViewTrigger(page, 'Canvas').waitFor();- await expectFocused(- centerViewTrigger(page, 'Canvas'),- 'Selecting a center view should restore focus to the view selector.'+ await appMenu.press('End');+ assert.equal(await appMenu.getAttribute('aria-activedescendant'), await discordItem.getAttribute('id'));+ for (const item of [documentationItem, settingsItem, commandPaletteItem]) {+ await appMenu.press('ArrowUp');+ assert.equal(await appMenu.getAttribute('aria-activedescendant'), await item.getAttribute('id'));+ }+ await page.keyboard.press('Escape');++ const projectSwitcher = page.getByRole('button', { name: /^Switch project\./ });+ await projectSwitcher.click();+ await page.getByRole('menuitem', { exact: true, name: 'New project' }).click();+ await page.getByRole('main', { name: /^Project Name #\d+$/ }).waitFor();++ await projectSwitcher.click();+ const openProjects = page.getByRole('menuitemradio');+ assert.ok((await openProjects.count()) >= 2);+ assert.equal(await page.getByRole('menuitemradio', { checked: true }).count(), 1);++ const textOffsets = await openProjects.evaluateAll((items) =>+ items.map((item) => item.querySelector('[data-part="item-text"]')?.getBoundingClientRect().left ?? null));+ assert.equal(+ textOffsets.every((offset) => offset !== null),+ true+ );+ assert.ok(Math.max(...textOffsets) - Math.min(...textOffsets) <= 0.5);++ const otherProject = page.getByRole('menuitemradio', { checked: false }).first();+ const otherProjectName = (await otherProject.locator('[data-part="item-text"]').textContent())?.trim();+ assert.ok(otherProjectName);+ await otherProject.click();+ await page.getByRole('main', { exact: true, name: otherProjectName }).waitFor();++ const customPresetNames = ['Custom One', 'Custom Two', 'Custom Three', 'Custom Four', 'Custom Five', 'Custom Six'];+ for (const presetName of customPresetNames) {+ await page.getByRole('button', { exact: true, name: 'Save this layout as a new preset' }).click();+ const savePresetDialog = page.getByRole('dialog', { exact: true, name: 'Save as new preset' });+ await savePresetDialog.getByRole('textbox', { exact: true, name: 'Preset name' }).fill(presetName);+ await savePresetDialog.getByRole('button', { exact: true, name: 'Save preset' }).click();+ await savePresetDialog.waitFor({ state: 'hidden' });+ }+ for (const presetName of customPresetNames) {+ await page.getByRole('tab', { exact: true, name: presetName }).waitFor();+ }+ assert.equal(await page.getByRole('button', { name: /^More layout presets/ }).count(), 0);+ const presetScroller = page.locator('[data-layout-preset-scroll]');+ await presetScroller.waitFor();+ const presetScrollerMetrics = await presetScroller.evaluate((scroller) => ({+ clientWidth: scroller.clientWidth,+ scrollWidth: scroller.scrollWidth,+ }));+ assert.ok(presetScrollerMetrics.scrollWidth > presetScrollerMetrics.clientWidth);+ const savePresetButton = page.getByRole('button', { exact: true, name: 'Save this layout as a new preset' });+ const [scrollerBounds, savePresetBounds] = await Promise.all([+ presetScroller.boundingBox(),+ savePresetButton.boundingBox(),+ ]);+ assert.ok(scrollerBounds);+ assert.ok(savePresetBounds);+ assert.ok(savePresetBounds.x >= scrollerBounds.x + scrollerBounds.width);+ assert.ok(savePresetBounds.x + savePresetBounds.width <= 1_440);+ const horizontalScroll = await presetScroller.evaluate(async (scroller) => {+ scroller.scrollLeft = scroller.scrollWidth;+ await new Promise((resolveFrame) => {+ requestAnimationFrame(resolveFrame);+ });++ return scroller.scrollLeft;+ });+ assert.ok(horizontalScroll > 0);+ const presetLayoutMetrics = await page.getByRole('banner').evaluate((header) => ({+ clientWidth: header.clientWidth,+ scrollWidth: header.scrollWidth,+ }));+ assert.equal(presetLayoutMetrics.scrollWidth, presetLayoutMetrics.clientWidth);++ await page.getByRole('tab', { name: /^Edit(?:, unsaved changes)?$/ }).click({ button: 'right' });+ const switchLayout = page.getByRole('menuitem', { exact: true, name: 'Switch to this layout' });+ await switchLayout.waitFor();+ assert.equal(await switchLayout.locator('svg.lucide-check').count(), 0);+ assert.equal(await switchLayout.locator('svg.lucide-arrow-right').count(), 1);if (pageErrors.length > 0) {- throw new AggregateError(pageErrors, 'keyboard-critical-journey raised uncaught browser errors.');+ throw new AggregateError(pageErrors, `${id} raised uncaught browser errors.`);}- return { id: 'keyboard-critical-journey', status: 'passed' };+ return { id, status: 'passed' };} finally {await context.close();}@@ -274,11 +557,14 @@ const runVideoPreviewJourney = async (browser) => {const id = 'workbench-video-preview-representative';try {+ // Compose puts the Gallery in the right rail and the Preview in the centre,+ // so the video is picked on the right and plays in the middle.await waitForWorkbench(page);- await selectLayoutPreset(page, 'Gallery');+ await selectLayoutPreset(page, 'Compose', 'Preview');- const gallery = page.getByRole('list', { exact: true, name: 'Gallery items' });- const selectVideo = page.getByRole('button', {+ const rightPanel = page.getByRole('complementary', { exact: true, name: 'right widget panel' });+ const gallery = rightPanel.getByRole('list', { exact: true, name: 'Gallery items' });+ const selectVideo = rightPanel.getByRole('button', {exact: true,name: `Select video ${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}, duration 0:01, for preview`,});@@ -297,9 +583,7 @@ const runVideoPreviewJourney = async (browser) => {assert.equal(await selectVideo.locator('xpath=..').locator('svg.lucide-play').getAttribute('aria-hidden'), 'true');await selectVideo.press('Enter');- const video = page- .getByRole('complementary', { exact: true, name: 'right widget panel' })- .locator(`video[aria-label="Video ${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}"]`);+ const video = centerRegion(page).locator(`video[aria-label="Video ${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}"]`);try {await video.waitFor();@@ -360,6 +644,12 @@ try {if (!requestedJourney || requestedJourney === 'keyboard-critical-journey') {reports.push(await runKeyboardJourney(browser));}+ if (!requestedJourney || requestedJourney === 'workbench-topbar-responsive') {+ reports.push(await runResponsiveTopbarJourney(browser));+ }+ if (!requestedJourney || requestedJourney === 'workbench-topbar-menus') {+ reports.push(await runTopbarMenuJourney(browser));+ }if (!requestedJourney || requestedJourney === 'workbench-video-preview-representative') {reports.push(await runVideoPreviewJourney(browser));}diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.jsonindex 21182373cb..ed6d1bca83 100644--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json@@ -80,6 +80,7 @@"WorkbenchRuntime.tsx": "workbench","WorkbenchSessionController.tsx": "workbench","WorkbenchWidgetRegistryContext.tsx": "workbench",+ "activeInvocationSubmission.ts": "workbench","autoRoutePolicy.ts": "workbench","canvasDimsSync.ts": "workbench","canvasLayerContent.ts": "workbench",@@ -92,16 +93,18 @@"controlLayerChecks.ts": "workbench","focusRegions.tsx": "workbench","generationSettingsOrchestration.ts": "workbench",+ "graphContracts.ts": "workbench","graphPreviewInvocation.ts": "workbench","graphSurfaces.ts": "workbench",- "graphContracts.ts": "workbench",+ "graphWidgets.ts": "workbench","iconResolver.tsx": "workbench","invocation.ts": "workbench","invocationContracts.ts": "workbench","invocationSubmit.ts": "workbench",+ "layoutContracts.ts": "workbench",+ "layoutPresetActivation.ts": "workbench","layoutPresetSnapshots.ts": "workbench","layoutPresets.ts": "workbench",- "layoutContracts.ts": "workbench","panZoom.ts": "workbench","performanceMarks.ts": "workbench","persistence.ts": "workbench",@@ -114,9 +117,9 @@"useCanvasProjectMutationDispatch.ts": "workbench","useNotify.ts": "workbench","useOpenWorkbenchWidget.ts": "workbench",+ "widgetContracts.ts": "workbench","widgetDnd.ts": "workbench","widgetImplementationResource.ts": "workbench",- "widgetContracts.ts": "workbench","widgetLabels.ts": "workbench","widgetPlacementCommands.ts": "workbench","widgetPlacementMeta.ts": "workbench",diff --git a/invokeai/frontend/webv2/src/features/identity/index.ts b/invokeai/frontend/webv2/src/features/identity/index.tsindex 11181bdf3a..416930aa8b 100644--- a/invokeai/frontend/webv2/src/features/identity/index.ts+++ b/invokeai/frontend/webv2/src/features/identity/index.ts@@ -33,6 +33,7 @@ export {type UserUpdateRequest,} from './data/api';export { AccountMenu } from './ui/AccountMenu';+export { AccountMenuSection, useHasAccountSection } from './ui/AccountMenuSection';export { AuthUnavailableScreen } from './ui/AuthUnavailableScreen';export { LoginScreen } from './ui/LoginScreen';export { SetupScreen } from './ui/SetupScreen';diff --git a/invokeai/frontend/webv2/src/features/identity/ui/AccountMenuSection.tsx b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenuSection.tsxnew file mode 100644index 0000000000..2d00be651f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenuSection.tsx@@ -0,0 +1,91 @@+import { Avatar, Badge, Box, HStack, Icon, Menu, Stack, Text } from '@chakra-ui/react';+import { logoutSession, useAuthSession } from '@features/identity/session';+import { useNavigate } from '@tanstack/react-router';+import { LogOutIcon, UserRoundCogIcon, UsersIcon } from 'lucide-react';+import { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { ProfileDialog } from './ProfileDialog';++/**+ * The signed-in user's rows — identity header, account settings, user+ * management, sign-out — as menu items rather than a menu of their own, so a+ * host menu can embed them instead of nesting a second popover inside itself.+ *+ * Renders nothing in a single-user session, where there is no account to manage.+ */+export const AccountMenuSection = () => {+ const { t } = useTranslation();+ const session = useAuthSession();+ const navigate = useNavigate();+ const [isProfileOpen, setIsProfileOpen] = useState(false);++ // User management is a Launchpad page (`/users`), not a workbench widget —+ // so this navigates there, working the same from Home and the editor.+ const openUserManagement = useCallback(() => {+ void navigate({ to: '/users' });+ }, [navigate]);++ const signOut = useCallback(() => {+ void logoutSession();+ }, []);++ const openProfile = useCallback(() => setIsProfileOpen(true), []);+ const closeProfile = useCallback(() => setIsProfileOpen(false), []);++ if (!session.multiuserEnabled || session.user === null) {+ return null;+ }++ const user = session.user;+ const label = user.display_name?.trim() || user.email;++ return (+ <>+ <Box px="3" py="2">+ <HStack justify="space-between">+ <HStack gap="2" minW="0">+ <Avatar.Root bg="accent.subtle" color="fg" size="2xs">+ <Avatar.Fallback fontSize="2xs" name={label} />+ </Avatar.Root>+ <Stack gap="0" minW="0">+ <Text fontSize="xs" fontWeight="600" truncate>+ {label}+ </Text>+ <Text color="fg.muted" fontSize="2xs" truncate>+ {user.email}+ </Text>+ </Stack>+ </HStack>+ {user.is_admin ? (+ <Badge colorPalette="purple" fontSize="2xs" variant="surface">+ {t('users.admin')}+ </Badge>+ ) : null}+ </HStack>+ </Box>+ <Menu.Item value="account" onClick={openProfile}>+ <Icon as={UserRoundCogIcon} boxSize="3.5" />+ <Menu.ItemText>{t('auth.accountSettings')}</Menu.ItemText>+ </Menu.Item>+ {user.is_admin ? (+ <Menu.Item value="users" onClick={openUserManagement}>+ <Icon as={UsersIcon} boxSize="3.5" />+ <Menu.ItemText>{t('users.manageUsers')}</Menu.ItemText>+ </Menu.Item>+ ) : null}+ <Menu.Item value="sign-out" onClick={signOut}>+ <Icon as={LogOutIcon} boxSize="3.5" />+ <Menu.ItemText>{t('auth.signOut')}</Menu.ItemText>+ </Menu.Item>+ <ProfileDialog isOpen={isProfileOpen} user={user} onClose={closeProfile} />+ </>+ );+};++/** True when {@link AccountMenuSection} has anything to render. */+export const useHasAccountSection = (): boolean => {+ const session = useAuthSession();++ return session.multiuserEnabled && session.user !== null;+};diff --git a/invokeai/frontend/webv2/src/features/queue/core/historySummary.test.ts b/invokeai/frontend/webv2/src/features/queue/core/historySummary.test.tsindex ea85f341a9..dde75f53e3 100644--- a/invokeai/frontend/webv2/src/features/queue/core/historySummary.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/historySummary.test.ts@@ -53,7 +53,7 @@ describe('getQueueSummary', () => {}),]);- expect(summary).toEqual({ current: 1, runningQueueItemId: 'batch-1', total: 4 });+ expect(summary).toEqual({ current: 1, remaining: 4, runningQueueItemId: 'batch-1', total: 4 });});it('keeps the running ordinal stable when newer work is queued', () => {@@ -73,7 +73,7 @@ describe('getQueueSummary', () => {}),]);- expect(summary).toEqual({ current: 1, runningQueueItemId: 'batch-1', total: 8 });+ expect(summary).toEqual({ current: 1, remaining: 8, runningQueueItemId: 'batch-1', total: 8 });});it('uses live progress to advance within a batch', () => {@@ -103,7 +103,7 @@ describe('getQueueSummary', () => {progress);- expect(summary).toEqual({ current: 2, runningQueueItemId: 'batch-1', total: 8 });+ expect(summary).toEqual({ current: 2, remaining: 7, runningQueueItemId: 'batch-1', total: 8 });});it('returns zeroes when all batches are terminal', () => {@@ -111,7 +111,7 @@ describe('getQueueSummary', () => {createQueueItem({ batchCount: 4, id: 'batch-1', status: 'completed', submittedAt: '2026-06-10T00:00:00.000Z' }),]);- expect(summary).toEqual({ current: 0, runningQueueItemId: null, total: 0 });+ expect(summary).toEqual({ current: 0, remaining: 0, runningQueueItemId: null, total: 0 });});it('uses the global batch count for workflow-sourced queue items', () => {@@ -125,7 +125,7 @@ describe('getQueueSummary', () => {}),]);- expect(summary).toEqual({ current: 0, runningQueueItemId: null, total: 2 });+ expect(summary).toEqual({ current: 0, remaining: 2, runningQueueItemId: null, total: 2 });});it('does not cap oversized batch counts', () => {@@ -138,7 +138,37 @@ describe('getQueueSummary', () => {}),]);- expect(summary).toEqual({ current: 0, runningQueueItemId: null, total: 10_000 });+ expect(summary).toEqual({ current: 0, remaining: 10_000, runningQueueItemId: null, total: 10_000 });+ });++ it('includes the active image and later batches in the countdown', () => {+ const progress: QueueItemProgress = {+ activeItemIndex: 4,+ completedItemCount: 3,+ message: '',+ percentage: null,+ totalItemCount: 4,+ };+ const summary = getQueueSummary(+ [+ createQueueItem({+ backendItemIds: [1, 2, 3, 4],+ batchCount: 4,+ id: 'batch-1',+ status: 'running',+ submittedAt: '2026-06-10T00:00:00.000Z',+ }),+ createQueueItem({+ batchCount: 4,+ id: 'batch-2',+ status: 'pending',+ submittedAt: '2026-06-10T00:01:00.000Z',+ }),+ ],+ progress+ );++ expect(summary.remaining).toBe(5);});});diff --git a/invokeai/frontend/webv2/src/features/queue/core/historySummary.ts b/invokeai/frontend/webv2/src/features/queue/core/historySummary.tsindex 36a132e445..0e82082889 100644--- a/invokeai/frontend/webv2/src/features/queue/core/historySummary.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/historySummary.ts@@ -5,6 +5,7 @@ import { getQueueItemSnapshotBatchCount } from '@features/queue/core/historySnapexport interface QueueSummary {current: number;+ remaining: number;runningQueueItemId: string | null;total: number;}@@ -83,13 +84,13 @@ export const getQueueSummary = (items: QueueItem[], progress: QueueItemProgressconst total = openItems.reduce((sum, item) => sum + getQueueItemExpectedImageCount(item), 0);if (total === 0) {- return { current: 0, runningQueueItemId: null, total: 0 };+ return { current: 0, remaining: 0, runningQueueItemId: null, total: 0 };}const runningItem = openItems.find((item) => item.status === 'running');if (!runningItem) {- return { current: 0, runningQueueItemId: null, total };+ return { current: 0, remaining: total, runningQueueItemId: null, total };}let current = 0;@@ -103,7 +104,11 @@ export const getQueueSummary = (items: QueueItem[], progress: QueueItemProgresscurrent += getQueueItemExpectedImageCount(item);}- return { current: Math.min(current, total), runningQueueItemId: runningItem.id, total };+ current = Math.min(current, total);++ // `current` is the one-based ordinal of the active image, so that image+ // remains in the countdown until it completes.+ return { current, remaining: Math.max(0, total - current + 1), runningQueueItemId: runningItem.id, total };};export const getProjectQueueIndicatorState = ({diff --git a/invokeai/frontend/webv2/src/features/queue/react.ts b/invokeai/frontend/webv2/src/features/queue/react.tsindex 99f191f6ed..8edaae0bce 100644--- a/invokeai/frontend/webv2/src/features/queue/react.ts+++ b/invokeai/frontend/webv2/src/features/queue/react.ts@@ -10,3 +10,4 @@ export {} from './data/progressImageStore';export { type QueueItemProgressSink, useQueueItemProgress } from './data/progressStore';export { getQueueItemAccess } from './ui/queueOwnership';+export { useIsProcessorPaused } from './ui/queueDataStore';diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsxindex 36c6a83669..d3650ec355 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx@@ -41,6 +41,24 @@ const render = async (nodeOpacity: number) => {});};+/**+ * The painted pixels, not the serialized colour string.+ *+ * One of these buttons resolves its fill straight from a token and the other+ * through a `color-mix()`, so Chrome reports the same grey as `oklch(l 0 0)` for+ * one and `oklab(l 0 0)` for the other. Rasterising both settles the question+ * the assertion is actually asking: do they fill the same?+ */+const paintedFill = (element: Element): string => {+ const canvas = document.createElement('canvas');+ const context = canvas.getContext('2d', { willReadFrequently: true })!;++ context.fillStyle = getComputedStyle(element).backgroundColor;+ context.fillRect(0, 0, 1, 1);++ return [...context.getImageData(0, 0, 1, 1).data].join(',');+};+const buttonBoxes = (): string[] =>[...host!.querySelectorAll('[role="toolbar"] button')].map((button) => {const rect = button.getBoundingClientRect();@@ -77,7 +95,7 @@ describe('editor toolbar', () => {)!;expect(opacity.getAttribute('aria-pressed')).toBe('true');- expect(getComputedStyle(opacity).backgroundColor).toBe(getComputedStyle(activeTool).backgroundColor);+ expect(paintedFill(opacity)).toBe(paintedFill(activeTool));expect(new Set(buttonBoxes())).toEqual(new Set(['32x32']));});});diff --git a/invokeai/frontend/webv2/src/platform/ui/Group.tsx b/invokeai/frontend/webv2/src/platform/ui/Group.tsxnew file mode 100644index 0000000000..097a6e933b--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/Group.tsx@@ -0,0 +1,55 @@+import type { ComponentProps } from 'react';++import { Group as ChakraGroup } from '@chakra-ui/react';+import { useMemo } from 'react';++type GroupProps = ComponentProps<typeof ChakraGroup>;++/**+ * Chakra's `Group`, with `attached` made to work structurally.+ *+ * Upstream, `attached` clones each *React* child with `data-first` /+ * `data-between` / `data-last` and styles `& > *[data-first]`. That only reaches+ * the DOM when the child forwards unknown props to its root element — so the+ * moment a group holds a component of ours rather than a bare Chakra control,+ * the attributes are dropped on the floor and the seam silently renders as a row+ * of separately-rounded buttons. Nothing errors; it just looks wrong.+ *+ * Selecting on position instead of on an attribute removes the dependency: the+ * browser knows which child is first and last whether or not React told it. The+ * declarations mirror upstream's exactly, `!important` included, so this only+ * ever adds the cases upstream misses.+ */+const attachedCss = {+ horizontal: {+ '& > * + *': {+ borderEndStartRadius: '0 !important',+ borderStartStartRadius: '0 !important',+ },+ '& > *:not(:last-child)': {+ borderEndEndRadius: '0 !important',+ borderStartEndRadius: '0 !important',+ marginEnd: '-1px',+ },+ },+ vertical: {+ '& > * + *': {+ borderStartEndRadius: '0 !important',+ borderStartStartRadius: '0 !important',+ },+ '& > *:not(:last-child)': {+ borderEndEndRadius: '0 !important',+ borderEndStartRadius: '0 !important',+ marginBottom: '-1px',+ },+ },+} as const;++export const Group = ({ attached, css, orientation, ...props }: GroupProps) => {+ const mergedCss = useMemo(+ () => (attached ? [attachedCss[orientation === 'vertical' ? 'vertical' : 'horizontal'], css] : css),+ [attached, css, orientation]+ );++ return <ChakraGroup attached={attached} css={mergedCss} orientation={orientation} {...props} />;+};diff --git a/invokeai/frontend/webv2/src/platform/ui/index.ts b/invokeai/frontend/webv2/src/platform/ui/index.tsindex 562fc819f7..9e0888766d 100644--- a/invokeai/frontend/webv2/src/platform/ui/index.ts+++ b/invokeai/frontend/webv2/src/platform/ui/index.ts@@ -5,6 +5,7 @@ export * from './Combobox';export * from './ConfirmDialog';export * from './DropZone';export * from './Field';+export * from './Group';export * from './JsonPreview';export * from './Menu';export * from './Panel';diff --git a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.tsnew file mode 100644index 0000000000..712d121cf0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts@@ -0,0 +1,60 @@+import type { AccountScope } from '@platform/state/accountLifecycle';++import { describe, expect, it } from 'vitest';++import type { WorkbenchCommands, WorkbenchQueries } from './workbenchStore';++import { submitActiveInvocation, type ActiveInvocationSubmissionRuntime } from './activeInvocationSubmission';+import { createInitialWorkbenchState } from './workbenchState.testing';++const owner = { signal: new AbortController().signal } as AccountScope;++const createArgs = () => {+ const state = createInitialWorkbenchState();++ return {+ commands: {} as WorkbenchCommands,+ getModels: () => undefined,+ queries: {+ getSnapshot: () => ({+ account: state.account,+ activeProject: state.projects[0],+ autosave: state.autosave,+ backendConnection: state.backendConnection,+ hasHydrated: true,+ notifications: state.notifications,+ projects: state.projects,+ }),+ } as WorkbenchQueries,+ };+};++describe('active invocation submission', () => {+ it('swallows an asynchronous failure after the initiating account becomes stale', async () => {+ const events: string[] = [];+ const runtime: ActiveInvocationSubmissionRuntime = {+ assertCurrent: () => undefined,+ capture: () => owner,+ flushDrafts: () => events.push('flushed'),+ isCurrent: () => false,+ loadPrepareCanvasInvocation: () => Promise.reject(new Error('stale failure')),+ submit: () => events.push('submitted'),+ };++ await expect(submitActiveInvocation(createArgs(), runtime)).resolves.toBeUndefined();+ expect(events).toEqual(['flushed']);+ });++ it('rethrows an asynchronous failure for the current account', async () => {+ const runtime: ActiveInvocationSubmissionRuntime = {+ assertCurrent: () => undefined,+ capture: () => owner,+ flushDrafts: () => undefined,+ isCurrent: () => true,+ loadPrepareCanvasInvocation: () => Promise.reject(new Error('current failure')),+ submit: () => undefined,+ };++ await expect(submitActiveInvocation(createArgs(), runtime)).rejects.toThrow('current failure');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.tsnew file mode 100644index 0000000000..5b20902536--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts@@ -0,0 +1,85 @@+import type { ModelConfig } from '@features/models';+import type { AccountScope } from '@platform/state/accountLifecycle';++import { flushGenerateDrafts } from '@features/generation/react';+import {+ assertAccountScopeCurrent,+ captureAccountScope,+ isAccountScopeCurrent,+} from '@platform/state/accountLifecycle';++import type { ResultDestination } from './invocationContracts';+import type { SubmitResolvedInvocationDeps } from './invocationSubmit';+import type { PrepareCanvasInvocationArgs } from './widgets/canvas/invoke/prepareCanvasInvocation';+import type { WorkbenchCommands, WorkbenchQueries } from './workbenchStore';++import { isInvocationRouteValid, resolveInvocationRoute } from './invocation';+import { submitResolvedInvocation } from './invocationSubmit';++export interface ActiveInvocationSubmissionArgs {+ commands: WorkbenchCommands;+ destinationOverride?: ResultDestination;+ formatControlLayerError?: PrepareCanvasInvocationArgs['formatControlLayerError'];+ getModels: () => readonly ModelConfig[] | undefined;+ queries: WorkbenchQueries;+}++export interface ActiveInvocationSubmissionRuntime {+ assertCurrent: (owner: AccountScope) => void;+ capture: () => AccountScope;+ flushDrafts: () => void;+ isCurrent: (owner: AccountScope) => boolean;+ loadPrepareCanvasInvocation: () => Promise<{+ prepareCanvasInvocation: SubmitResolvedInvocationDeps['prepareCanvasInvocation'];+ }>;+ submit: (args: SubmitResolvedInvocationDeps) => void;+}++const runtime: ActiveInvocationSubmissionRuntime = {+ assertCurrent: assertAccountScopeCurrent,+ capture: captureAccountScope,+ flushDrafts: flushGenerateDrafts,+ isCurrent: isAccountScopeCurrent,+ loadPrepareCanvasInvocation: () => import('./widgets/canvas/invoke/prepareCanvasInvocation'),+ submit: submitResolvedInvocation,+};++export const submitActiveInvocation = async (+ { commands, destinationOverride, formatControlLayerError, getModels, queries }: ActiveInvocationSubmissionArgs,+ activeRuntime: ActiveInvocationSubmissionRuntime = runtime+): Promise<void> => {+ const owner = activeRuntime.capture();+ activeRuntime.flushDrafts();++ try {+ const { prepareCanvasInvocation } = await activeRuntime.loadPrepareCanvasInvocation();++ activeRuntime.assertCurrent(owner);+ const snapshot = queries.getSnapshot();+ const invocation = destinationOverride+ ? { ...snapshot.activeProject.invocation, destination: destinationOverride }+ : snapshot.activeProject.invocation;+ const models = getModels();+ const route = resolveInvocationRoute(snapshot.activeProject, 'global', invocation, models);++ if (!isInvocationRouteValid(route) || snapshot.backendConnection.status !== 'connected') {+ return;+ }++ activeRuntime.submit({+ commands,+ formatControlLayerError,+ models,+ owner,+ prepareCanvasInvocation,+ project: snapshot.activeProject,+ route,+ });+ } catch (error) {+ if (!activeRuntime.isCurrent(owner)) {+ return;+ }++ throw error;+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/graphWidgets.test.ts b/invokeai/frontend/webv2/src/workbench/graphWidgets.test.tsnew file mode 100644index 0000000000..88df00e023--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/graphWidgets.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from 'vitest';++import {+ describeRoute,+ getNaturalDestination,+ getPlacedWidgetTypeIds,+ getSourceIdForWidgetTypeId,+ getVisibleWidgetTypeIds,+ getWidgetTypeIdForSourceId,+ graphWidgetSources,+ isGraphWidgetTypeId,+} from './graphWidgets';+import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';++const applyPreset = (presetId: string) => {+ const state = workbenchReducer(createInitialWorkbenchState(), { presetId, type: 'applyPreset' });++ return state.projects.find((candidate) => candidate.id === state.activeProjectId)!;+};++describe('graph widget sources', () => {+ it('recognises only the graph-bearing widget types', () => {+ expect(isGraphWidgetTypeId('generate')).toBe(true);+ expect(isGraphWidgetTypeId('canvas')).toBe(true);+ expect(isGraphWidgetTypeId('upscale')).toBe(true);+ expect(isGraphWidgetTypeId('workflow')).toBe(true);+ expect(isGraphWidgetTypeId('gallery')).toBe(false);+ expect(isGraphWidgetTypeId('preview')).toBe(false);+ expect(getSourceIdForWidgetTypeId('gallery')).toBeNull();+ expect(getSourceIdForWidgetTypeId('workflow')).toBe('workflow');+ expect(getWidgetTypeIdForSourceId('upscale')).toBe('upscale');+ });++ // Every source stays pickable. Hiding the ones the layout does not happen to+ // be showing turns the menu into a dead end: the user can see that Workflow+ // exists but has no way to route to it without rearranging the dock first.+ it('offers every graph widget as a source', () => {+ expect(graphWidgetSources.map((source) => source.sourceId)).toEqual(['generate', 'canvas', 'upscale', 'workflow']);+ });++ it('separates what the layout is showing from what it has placed', () => {+ const project = applyPreset('edit');++ // Edit shows Generate on the left and Canvas in the centre...+ expect([...getVisibleWidgetTypeIds(project)]).toEqual(expect.arrayContaining(['generate', 'canvas']));+ expect(getVisibleWidgetTypeIds(project).has('workflow')).toBe(false);++ // ...while Upscale and Workflow are still placed in the same left rail, so+ // routing to them needs no new placement, only revealing.+ expect([...getPlacedWidgetTypeIds(project)]).toEqual(+ expect.arrayContaining(['generate', 'canvas', 'upscale', 'workflow'])+ );+ });++ it('maps each source to its natural output target', () => {+ expect(getNaturalDestination('canvas')).toBe('canvas');+ expect(getNaturalDestination('generate')).toBe('gallery');+ expect(getNaturalDestination('workflow')).toBe('gallery');+ });++ // The indicator is icon-only, so the whole route — including whether it is+ // pinned — has to live in its accessible name.+ it('describes the whole route for assistive technology', () => {+ expect(+ describeRoute({+ destination: 'gallery',+ destinationLocked: false,+ hasSource: true,+ sourceId: 'generate',+ sourceLocked: false,+ })+ ).toBe('Invoke from generate, output to gallery, following edits');++ expect(+ describeRoute({+ destination: 'canvas',+ destinationLocked: true,+ hasSource: true,+ sourceId: 'workflow',+ sourceLocked: true,+ })+ ).toBe('Invoke from workflow, output to canvas, source locked, destination locked');++ expect(+ describeRoute({+ destination: 'gallery',+ destinationLocked: false,+ hasSource: false,+ sourceId: 'generate',+ sourceLocked: false,+ })+ ).toBe('No source widget open, output to gallery, following edits');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/graphWidgets.ts b/invokeai/frontend/webv2/src/workbench/graphWidgets.tsnew file mode 100644index 0000000000..c6af8f5c0f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/graphWidgets.ts@@ -0,0 +1,134 @@+import type { InvocationSourceId, ResultDestination } from '@workbench/invocationContracts';+import type { Project } from '@workbench/projectContracts';+import type { WidgetTypeId } from '@workbench/widgetContracts';++import { autoSwitchDestinations } from './autoRoutePolicy';+import { getDestinationLabel, getSourceLabel, isInvocationSourceAvailable } from './invocation';++/**+ * The invocation source model behind the topbar's routing control.+ *+ * A *graph widget* is a widget that can expose a generation graph and can+ * therefore act as a source. Which ones are open is a property of the live+ * layout, not of the layout preset — a preset routinely places two or three of+ * them at once, which is exactly why a preset can never determine the source.+ */++/** Widget type ids that carry a graph, in the order the routing menu lists them. */+const graphWidgetTypeIds = ['generate', 'canvas', 'upscale', 'workflow'] as const;++export type GraphWidgetTypeId = (typeof graphWidgetTypeIds)[number];++/**+ * Source id and widget type id are the same string for every graph widget today.+ * They are still distinct concepts — one names a route, the other names a+ * dockable surface — so the mapping is written out rather than assumed.+ */+const sourceIdsByWidgetTypeId: Record<GraphWidgetTypeId, InvocationSourceId> = {+ canvas: 'canvas',+ generate: 'generate',+ upscale: 'upscale',+ workflow: 'workflow',+};++const widgetTypeIdsBySourceId: Record<InvocationSourceId, GraphWidgetTypeId> = {+ canvas: 'canvas',+ generate: 'generate',+ upscale: 'upscale',+ workflow: 'workflow',+};++export const isGraphWidgetTypeId = (typeId: WidgetTypeId): typeId is GraphWidgetTypeId =>+ (graphWidgetTypeIds as readonly string[]).includes(typeId);++export const getSourceIdForWidgetTypeId = (typeId: WidgetTypeId): InvocationSourceId | null =>+ isGraphWidgetTypeId(typeId) ? sourceIdsByWidgetTypeId[typeId] : null;++export const getWidgetTypeIdForSourceId = (sourceId: InvocationSourceId): GraphWidgetTypeId =>+ widgetTypeIdsBySourceId[sourceId];++/** Where a source's output naturally lands when the destination is not locked. */+export const getNaturalDestination = (sourceId: InvocationSourceId): ResultDestination =>+ autoSwitchDestinations[sourceId];++export interface GraphWidgetSource {+ sourceId: InvocationSourceId;+ typeId: GraphWidgetTypeId;+ label: string;+}++/** Every graph widget, in the order the routing menu lists them. */+export const graphWidgetSources: GraphWidgetSource[] = graphWidgetTypeIds+ .map((typeId) => ({+ label: getSourceLabel(sourceIdsByWidgetTypeId[typeId]),+ sourceId: sourceIdsByWidgetTypeId[typeId],+ typeId,+ }))+ .filter((source) => isInvocationSourceAvailable(source.sourceId));++/**+ * The widget type each region is currently showing.+ *+ * This is what "visible" means in the routing menu — a surface the current+ * layout is showing. It is deliberately *not* what the menu lists:+ * every source stays selectable, because being unable to pick Workflow just+ * because the centre happens to show Canvas is a dead end, not a safeguard.+ *+ * A collapsed region still counts. Collapsing a panel is a viewing choice, not+ * a statement about what should run.+ */+export const getVisibleWidgetTypeIds = (project: Project): Set<WidgetTypeId> => {+ const typeIds = new Set<WidgetTypeId>();++ for (const region of Object.values(project.widgetRegions)) {+ const typeId = project.widgetInstances[region.activeInstanceId]?.typeId;++ if (typeId) {+ typeIds.add(typeId);+ }+ }++ return typeIds;+};++/** Widget types placed anywhere in the project, whether or not they are showing. */+export const getPlacedWidgetTypeIds = (project: Project): Set<WidgetTypeId> => {+ const typeIds = new Set<WidgetTypeId>();++ for (const region of Object.values(project.widgetRegions)) {+ for (const instanceId of region.instanceIds) {+ const typeId = project.widgetInstances[instanceId]?.typeId;++ if (typeId) {+ typeIds.add(typeId);+ }+ }+ }++ return typeIds;+};++/**+ * The routing indicator is icon-only, so it carries the whole route in its+ * accessible name — including whether the route is pinned or follows edits.+ */+export const describeRoute = ({+ destination,+ destinationLocked,+ hasSource,+ sourceId,+ sourceLocked,+}: {+ destination: ResultDestination;+ destinationLocked: boolean;+ hasSource: boolean;+ sourceId: InvocationSourceId;+ sourceLocked: boolean;+}): string => {+ const from = hasSource ? `Invoke from ${getSourceLabel(sourceId).toLowerCase()}` : 'No source widget open';+ const to = `output to ${getDestinationLabel(destination).toLowerCase()}`;+ const mode = sourceLocked ? 'source locked' : 'following edits';+ const destinationMode = destinationLocked ? ', destination locked' : '';++ return `${from}, ${to}, ${mode}${destinationMode}`;+};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.tsindex 377a0811c7..4517d1b25b 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts@@ -5,8 +5,10 @@ import { firstPartyHotkeyCatalog, OPEN_COMMAND_PALETTE_HOTKEY } from './catalog'describe('firstPartyHotkeyCatalog', () => {it('keeps legacy default hotkey parity', () => {// 91 legacy-parity entries + `canvas.newSession` (webv2 new-canvas command,- // no default keys — Task 46) + `app.openCommandPalette` (webv2-only, mod+k).- expect(firstPartyHotkeyCatalog).toHaveLength(93);+ // no default keys — Task 46) + `app.openCommandPalette` (webv2-only, mod+k)+ // + the six top-bar redesign commands (alt+mod+enter, mod+p, an unbound save,+ // and alt+1..3).+ expect(firstPartyHotkeyCatalog).toHaveLength(99);expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.invoke');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.openCommandPalette');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('canvas.mergeDown');@@ -15,6 +17,10 @@ describe('firstPartyHotkeyCatalog', () => {expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('gallery.galleryNavLeft');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('gallery.remix');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('viewer.deleteImage');+ expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.invokeToOtherDestination');+ expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.openProjectSwitcher');+ expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.saveLayoutPreset');+ expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.selectComposePreset');});it('uses the exported command-palette definition as the catalog entry', () => {@@ -22,4 +28,10 @@ describe('firstPartyHotkeyCatalog', () => {OPEN_COMMAND_PALETTE_HOTKEY);});++ it('keeps layout saving explicit and out of editable controls', () => {+ const saveLayout = firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === 'app.saveLayoutPreset');++ expect(saveLayout).toMatchObject({ allowInEditable: false, defaultKeys: [] });+ });});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.tsindex 396118f0f8..e34c2726fc 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts@@ -1,3 +1,5 @@+import { builtInLayoutPresetDescriptors } from '@workbench/layoutPresets';+import type { HotkeyCategory, HotkeyDefinition } from './types';const categoryScopes = {@@ -15,12 +17,18 @@ const implemented = new Set(['app.focusPrompt','app.invoke','app.invokeFront',+ 'app.invokeToOtherDestination',+ 'app.openProjectSwitcher','app.promptHistoryNext','app.promptHistoryPrev','app.promptWeightDown','app.promptWeightUp','app.resetPanelLayout',+ 'app.saveLayoutPreset',+ 'app.selectAutomatePreset','app.selectCanvasTab',+ 'app.selectComposePreset',+ 'app.selectEditPreset','app.selectGenerateTab','app.selectModelsTab','app.selectQueueTab',@@ -68,10 +76,19 @@ const implemented = new Set(['workflows.undo',]);+/**+ * Hotkeys that must fire with the caret inside a text field or numeric input.+ *+ * There is no second Invoke button anywhere in the application, so `app.invoke`+ * and its variants are load-bearing: a prompt textarea that swallows ⌘↵ leaves+ * the user with no way to submit at all.+ */const editableAppHotkeys = new Set(['app.focusPrompt','app.invoke','app.invokeFront',+ 'app.invokeToOtherDestination',+ 'app.openProjectSwitcher','app.promptHistoryNext','app.promptHistoryPrev','app.promptWeightDown',@@ -121,7 +138,14 @@ export const OPEN_COMMAND_PALETTE_HOTKEY: HotkeyDefinition = {export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [OPEN_COMMAND_PALETTE_HOTKEY,hotkey('app', 'invoke', ['mod+enter']),+ // "Just this once, send it to the gallery" is the single most common reason+ // to open the routing menu; this makes it a keystroke instead of a round trip+ // through a popover, and it does not change the saved destination.+ hotkey('app', 'invokeToOtherDestination', ['alt+mod+enter']),hotkey('app', 'invokeFront', ['mod+shift+enter']),+ hotkey('app', 'openProjectSwitcher', ['mod+p']),+ hotkey('app', 'saveLayoutPreset', []),+ ...builtInLayoutPresetDescriptors.map(({ defaultKeys, hotkeyId }) => hotkey('app', hotkeyId, [...defaultKeys])),hotkey('app', 'cancelQueueItem', ['shift+x']),hotkey('app', 'clearQueue', ['mod+shift+x']),hotkey('app', 'selectGenerateTab', ['1']),diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.tsindex bb8c4ed10d..56dcda36b0 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts@@ -1,4 +1,5 @@import type { ImageRecallKind } from '@workbench/image-actions/imageRecall';+import type { ResultDestination } from '@workbench/invocationContracts';import { invalidateGallery } from '@features/gallery/queries';import {@@ -16,16 +17,24 @@ import {captureAccountScope,isAccountScopeCurrent,} from '@platform/state/accountLifecycle';-import { getConnectionStatus } from '@platform/transport/connectionStore';import { useQueryClient } from '@tanstack/react-query';-import { isInvocationRouteValid, resolveInvocationRoute } from '@workbench/invocation';-import { submitResolvedInvocation } from '@workbench/invocationSubmit';+import { submitActiveInvocation } from '@workbench/activeInvocationSubmission';+import { createLayoutPresetActivator, loadLayoutPresetWidgets } from '@workbench/layoutPresetActivation';+import { builtInLayoutPresetDescriptors, getLayoutPreset } from '@workbench/layoutPresets';import { toggleCommandPalette } from '@workbench/palette/paletteStore';+import { openProjectSwitcher } from '@workbench/shell/topbar/projectSwitcherStore';import { openWidgetPlacement } from '@workbench/widgetPlacementCommands';import { getWidgetsForRegion } from '@workbench/widgetRegistry';import { getProjectWidgetValues } from '@workbench/widgetState';import { useWorkbenchCommands, useWorkbenchExtensions, useWorkbenchQueries } from '@workbench/WorkbenchContext';-import { useEffect, useEffectEvent } from 'react';+import { useEffect, useEffectEvent, useMemo } from 'react';++/** ⌥1 / ⌥2 / ⌥3 — the three shipped layout presets, in strip order. */+const layoutPresetCommands = builtInLayoutPresetDescriptors.map(({ hotkeyId, preset }) => ({+ id: `app.${hotkeyId}`,+ presetId: preset.id,+ title: `${preset.label} layout`,+}));const imageRecallCommands: Record<string, ImageRecallKind> = {'gallery.remix': 'remix',@@ -39,7 +48,11 @@ const imageRecallCommands: Record<string, ImageRecallKind> = {export const FIRST_PARTY_APP_COMMAND_IDS = ['app.invoke','app.invokeFront',+ 'app.invokeToOtherDestination','app.openCommandPalette',+ 'app.openProjectSwitcher',+ 'app.saveLayoutPreset',+ ...layoutPresetCommands.map(({ id }) => id),'app.cancelQueueItem','app.clearQueue','app.selectGenerateTab',@@ -73,48 +86,23 @@ export const useRegisterFirstPartyCommands = () => {const queries = useWorkbenchQueries();const queryClient = useQueryClient();const { layout, notifications, queue, widgets } = commands;+ const activateLayoutPreset = useMemo(+ () => createLayoutPresetActivator({ apply: layout.applyPreset, load: loadLayoutPresetWidgets }),+ [layout.applyPreset]+ );useInvocationTemplatesSelector((snapshot) => snapshot.status);useMountEffect(() => {void ensureModelsLoaded();});- const submitInvocation = useEffectEvent(async () => {- const owner = captureAccountScope();- flushGenerateDrafts();-- try {- const { prepareCanvasInvocation } = await import('@workbench/widgets/canvas/invoke/prepareCanvasInvocation');-- assertAccountScopeCurrent(owner);- const activeProject = queries.getSnapshot().activeProject;- const resolvedRoute = resolveInvocationRoute(- activeProject,- 'global',- activeProject.invocation,- getAvailableModels()- );- const { status } = getConnectionStatus();-- if (!isInvocationRouteValid(resolvedRoute) || status !== 'connected') {- return;- }-- submitResolvedInvocation({- commands,- models: getAvailableModels(),- owner,- prepareCanvasInvocation,- project: activeProject,- route: resolvedRoute,- });- } catch (error) {- if (!isAccountScopeCurrent(owner)) {- return;- }-- throw error;- }+ /**+ * Submits the active route. `destinationOverride` applies to this run only and+ * is never written back to the project — "just this once, send it to the+ * gallery" must not silently retarget every subsequent invoke.+ */+ const submitInvocation = useEffectEvent(async (destinationOverride?: ResultDestination) => {+ await submitActiveInvocation({ commands, destinationOverride, getModels: getAvailableModels, queries });});const recallSelectedImage = useEffectEvent(async (kind: ImageRecallKind) => {@@ -177,8 +165,30 @@ export const useRegisterFirstPartyCommands = () => {useEffect(() => {const disposers = [- commandApi.register({ handler: submitInvocation, id: 'app.invoke', title: 'Invoke' }),- commandApi.register({ handler: submitInvocation, id: 'app.invokeFront', title: 'Invoke front' }),+ commandApi.register({ handler: () => submitInvocation(), id: 'app.invoke', title: 'Invoke' }),+ commandApi.register({ handler: () => submitInvocation(), id: 'app.invokeFront', title: 'Invoke front' }),+ commandApi.register({+ handler: () => {+ const { destination } = queries.getSnapshot().activeProject.invocation;++ void submitInvocation(destination === 'canvas' ? 'gallery' : 'canvas');+ },+ id: 'app.invokeToOtherDestination',+ title: 'Invoke to the other destination',+ }),+ commandApi.register({+ handler: openProjectSwitcher,+ id: 'app.openProjectSwitcher',+ title: 'Open project switcher',+ }),+ commandApi.register({+ handler: () => layout.savePreset(queries.getSnapshot().activeProject.layout.presetId),+ id: 'app.saveLayoutPreset',+ title: 'Save changes to the active layout preset',+ }),+ ...layoutPresetCommands.map(({ id, presetId, title }) =>+ commandApi.register({ handler: () => void activateLayoutPreset(getLayoutPreset(presetId)), id, title })+ ),commandApi.register({handler: () => {const owner = captureAccountScope();@@ -357,5 +367,5 @@ export const useRegisterFirstPartyCommands = () => {return () => {disposers.forEach((dispose) => dispose());};- }, [commandApi, commands, layout, notifications, queries, queryClient, queue, widgets]);+ }, [activateLayoutPreset, commandApi, commands, layout, notifications, queries, queryClient, queue, widgets]);};diff --git a/invokeai/frontend/webv2/src/workbench/layoutContracts.ts b/invokeai/frontend/webv2/src/workbench/layoutContracts.tsindex 5cad4c79d8..32b63d5e53 100644--- a/invokeai/frontend/webv2/src/workbench/layoutContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutContracts.ts@@ -1,6 +1,12 @@import type { WidgetInstanceId, WidgetTypeId } from './widgetContracts';-export type BuiltInLayoutPresetId = 'canvas-default' | 'gallery' | 'workflow' | 'canvas';+/**+ * The three shipped layout presets. A preset names an *arrangement*, never a+ * widget — `edit` opens Canvas but is not "the Canvas view", and a preset may+ * have several graph widgets open at once. Source resolution is a separate+ * concern (see `graphWidgets.ts`).+ */+export type BuiltInLayoutPresetId = 'compose' | 'edit' | 'automate';export type LayoutPresetId = BuiltInLayoutPresetId | (string & {});@@ -43,5 +49,18 @@ export interface LayoutPreset {id: LayoutPresetId;label: string;isBuiltIn?: boolean;+ /**+ * Icon identifier, not a component: presets are persisted verbatim, so this+ * has to survive a round trip through storage. Resolved against the picker's+ * registry, which falls back for ids it no longer knows.+ */+ iconId?: string;snapshot: LayoutPresetSnapshot;}++/**+ * Per-account edits to a preset's saved arrangement, keyed by preset id. Built-in+ * preset bodies are code, so "Save changes" cannot mutate them in place; the+ * override is what the drift comparison and `Revert to saved layout` read.+ */+export type LayoutPresetOverrides = Record<string, LayoutPresetSnapshot>;diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.tsnew file mode 100644index 0000000000..54cd3b6f3b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { createLayoutPresetActivator } from './layoutPresetActivation';+import { layoutPresets } from './layoutPresets';++const createDeferred = () => {+ let resolve!: () => void;+ const promise = new Promise<void>((next) => {+ resolve = next;+ });++ return { promise, resolve };+};++describe('layout preset activation', () => {+ it('applies only the most recently requested preset when loads finish out of order', async () => {+ const composeLoad = createDeferred();+ const editLoad = createDeferred();+ const appliedPresetIds: string[] = [];+ const activate = createLayoutPresetActivator({+ apply: (presetId) => appliedPresetIds.push(presetId),+ load: (preset) => (preset.id === 'compose' ? composeLoad.promise : editLoad.promise),+ });++ const composeActivation = activate(layoutPresets[0]);+ const editActivation = activate(layoutPresets[1]);++ editLoad.resolve();+ await editActivation;+ composeLoad.resolve();+ await composeActivation;++ expect(appliedPresetIds).toEqual(['edit']);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.tsnew file mode 100644index 0000000000..ca6010dc05--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.ts@@ -0,0 +1,41 @@+import type { LayoutPreset, LayoutPresetId } from './layoutContracts';++import { loadWidget, preloadWidget } from './widgetRegistry';++interface LayoutPresetActivatorDependencies {+ apply: (presetId: LayoutPresetId) => void;+ load: (preset: LayoutPreset) => Promise<unknown>;+}++export const createLayoutPresetActivator = ({ apply, load }: LayoutPresetActivatorDependencies) => {+ let latestRequestId = 0;++ return async (preset: LayoutPreset): Promise<void> => {+ const requestId = ++latestRequestId;+ await load(preset);++ if (requestId === latestRequestId) {+ apply(preset.id);+ }+ };+};++export const preloadLayoutPresetWidgets = (preset: LayoutPreset): void => {+ for (const region of Object.values(preset.snapshot.widgetRegions)) {+ const typeId = preset.snapshot.widgetInstances[region.activeInstanceId]?.typeId;++ if (typeId) {+ preloadWidget(typeId);+ }+ }+};++export const loadLayoutPresetWidgets = (preset: LayoutPreset): Promise<unknown> =>+ Promise.allSettled(+ Object.values(preset.snapshot.widgetRegions).flatMap((region) => {+ const typeId = preset.snapshot.widgetInstances[region.activeInstanceId]?.typeId;+ const pending = typeId ? loadWidget(typeId) : null;++ return pending ? [pending] : [];+ })+ );diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.tsindex 5636bc6615..fc5b696e9b 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts@@ -1,15 +1,38 @@import type {LayoutPreset,+ LayoutPresetId,LayoutPresetSnapshot,LayoutPresetWidgetInstanceSnapshot,WidgetRegion,WidgetRegionState,} from '@workbench/layoutContracts';-import type { Project } from '@workbench/projectContracts';+import type { AccountState, Project } from '@workbench/projectContracts';import type { WidgetInstanceId } from '@workbench/widgetContracts';+import { getLayoutPreset } from '@workbench/layoutPresets';+const widgetRegions: WidgetRegion[] = ['left', 'right', 'bottom', 'center'];+/**+ * The preset as saved *for this account*: a custom preset, or a built-in with+ * the account's saved edits layered over it. Everything that answers "what does+ * this preset look like" — applying it, reverting to it, and the drift+ * comparison behind the strip's dot — reads through here, or `Save changes`+ * would appear to do nothing.+ */+export const resolveSavedLayoutPreset = (account: AccountState, presetId: LayoutPresetId): LayoutPreset => {+ const customPreset = account.customLayoutPresets?.find((preset) => preset.id === presetId);++ if (customPreset) {+ return customPreset;+ }++ const builtInPreset = getLayoutPreset(presetId);+ const override = account.layoutPresetOverrides?.[builtInPreset.id];++ return override ? { ...builtInPreset, snapshot: override } : builtInPreset;+};+export const cloneLayoutPresetWidgetRegions = (widgetRegionState: Record<WidgetRegion, WidgetRegionState>): Record<WidgetRegion, WidgetRegionState> => ({diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.test.tsnew file mode 100644index 0000000000..4f32b3271b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';++import { builtInLayoutPresetDescriptors, layoutPresets } from './layoutPresets';++describe('built-in layout preset descriptors', () => {+ it('owns the preset, presentation, and command metadata in strip order', () => {+ expect(+ builtInLayoutPresetDescriptors.map(({ defaultKeys, hotkeyId, iconId, preset, tooltip }) => ({+ defaultKeys,+ hotkeyId,+ iconId,+ label: preset.label,+ presetId: preset.id,+ tooltip,+ }))+ ).toEqual([+ {+ defaultKeys: ['alt+1'],+ hotkeyId: 'selectComposePreset',+ iconId: 'type',+ label: 'Compose',+ presetId: 'compose',+ tooltip: 'Text to image',+ },+ {+ defaultKeys: ['alt+2'],+ hotkeyId: 'selectEditPreset',+ iconId: 'layers',+ label: 'Edit',+ presetId: 'edit',+ tooltip: 'Canvas editing',+ },+ {+ defaultKeys: ['alt+3'],+ hotkeyId: 'selectAutomatePreset',+ iconId: 'workflow',+ label: 'Automate',+ presetId: 'automate',+ tooltip: 'Node workflows',+ },+ ]);+ expect(layoutPresets).toEqual(builtInLayoutPresetDescriptors.map(({ preset }) => preset));+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.tsindex a4f73f7fc0..83cbc33354 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts@@ -90,31 +90,63 @@ const createSnapshot = ({widgetRegions,});-const createPreset = ({+export interface BuiltInLayoutPresetDescriptor {+ defaultKeys: readonly string[];+ hotkeyId: string;+ iconId: string;+ preset: LayoutPreset;+ tooltip: string;+}++const createPresetDescriptor = ({centerViewId,+ defaultKeys,+ hotkeyId,id,+ iconId,label,panels,+ tooltip,widgetRegions,}: {centerViewId: CenterViewId;+ defaultKeys: readonly string[];+ hotkeyId: string;id: BuiltInLayoutPresetId;+ iconId: string;label: string;panels: PanelState;+ tooltip: string;widgetRegions: Record<WidgetRegion, WidgetRegionState>;-}): LayoutPreset => ({- id,- isBuiltIn: true,- label,- snapshot: createSnapshot({ centerViewId, panels, presetId: id, widgetRegions }),+}): BuiltInLayoutPresetDescriptor => ({+ defaultKeys,+ hotkeyId,+ iconId,+ preset: {+ id,+ isBuiltIn: true,+ label,+ snapshot: createSnapshot({ centerViewId, panels, presetId: id, widgetRegions }),+ },+ tooltip,});-export const layoutPresets: LayoutPreset[] = [- createPreset({+/**+ * The three shipped presets. Each is an arrangement, named for the work it+ * supports rather than the widget it happens to open — several graph widgets+ * are placed in every one of them, which is exactly why a preset can never+ * imply an invocation source.+ */+export const builtInLayoutPresetDescriptors: BuiltInLayoutPresetDescriptor[] = [+ createPresetDescriptor({centerViewId: 'preview',- id: 'canvas-default',- label: 'Default',+ defaultKeys: ['alt+1'],+ hotkeyId: 'selectComposePreset',+ id: 'compose',+ iconId: 'type',+ label: 'Compose',panels: { isBottomOpen: false, isLeftOpen: true, isRightOpen: true },+ tooltip: 'Text to image',widgetRegions: {bottom: createRegion({activeInstanceId: 'gallery:bottom',@@ -139,40 +171,15 @@ export const layoutPresets: LayoutPreset[] = [}),},}),- createPreset({- centerViewId: 'workflow',- id: 'workflow',- label: 'Workflow',- panels: { isBottomOpen: false, isLeftOpen: true, isRightOpen: true },- widgetRegions: {- bottom: createRegion({- activeInstanceId: 'workflow:bottom',- instanceIds: defaultBottomInstanceIds,- isCollapsed: true,- sizePx: 180,- }),- center: createRegion({- activeInstanceId: 'workflow:center',- instanceIds: ['workflow:center', 'canvas', 'preview', 'gallery:center'],- sizePx: 0,- }),- left: createRegion({- activeInstanceId: 'workflow',- instanceIds: ['workflow', 'generate', 'upscale'],- sizePx: 450,- }),- right: createRegion({- activeInstanceId: 'queue',- instanceIds: ['queue', 'gallery', 'layers', 'preview', 'diagnostics', 'project'],- sizePx: 450,- }),- },- }),- createPreset({+ createPresetDescriptor({centerViewId: 'canvas',- id: 'canvas',- label: 'Canvas',+ defaultKeys: ['alt+2'],+ hotkeyId: 'selectEditPreset',+ id: 'edit',+ iconId: 'layers',+ label: 'Edit',panels: { isBottomOpen: false, isLeftOpen: true, isRightOpen: true },+ tooltip: 'Canvas editing',widgetRegions: {bottom: createRegion({activeInstanceId: 'gallery:bottom',@@ -197,39 +204,66 @@ export const layoutPresets: LayoutPreset[] = [}),},}),- createPreset({- centerViewId: 'gallery',- id: 'gallery',- label: 'Gallery',+ createPresetDescriptor({+ centerViewId: 'workflow',+ defaultKeys: ['alt+3'],+ hotkeyId: 'selectAutomatePreset',+ id: 'automate',+ iconId: 'workflow',+ label: 'Automate',panels: { isBottomOpen: false, isLeftOpen: true, isRightOpen: true },+ tooltip: 'Node workflows',widgetRegions: {bottom: createRegion({- activeInstanceId: 'gallery:bottom',+ activeInstanceId: 'workflow:bottom',instanceIds: defaultBottomInstanceIds,isCollapsed: true,sizePx: 180,}),center: createRegion({- activeInstanceId: 'gallery:center',- instanceIds: ['gallery:center', 'preview', 'canvas', 'workflow:center'],+ activeInstanceId: 'workflow:center',+ instanceIds: ['workflow:center', 'canvas', 'preview', 'gallery:center'],sizePx: 0,}),left: createRegion({- activeInstanceId: 'generate',- instanceIds: ['generate', 'workflow', 'upscale', 'gallery'],- isCollapsed: true,+ activeInstanceId: 'workflow',+ instanceIds: ['workflow', 'generate', 'upscale'],sizePx: 450,}),right: createRegion({- activeInstanceId: 'preview',- instanceIds: ['preview', 'gallery', 'queue', 'layers', 'diagnostics', 'project'],+ activeInstanceId: 'queue',+ instanceIds: ['queue', 'gallery', 'layers', 'preview', 'diagnostics', 'project'],sizePx: 450,}),},}),];+export const layoutPresets: LayoutPreset[] = builtInLayoutPresetDescriptors.map(({ preset }) => preset);+export const defaultLayoutPreset = layoutPresets[0];+/**+ * Preset ids persisted before the three-preset model. `gallery` had no successor+ * arrangement of its own — it was Compose with the center view swapped — so it+ * resolves there rather than becoming a fourth entry.+ */+const legacyLayoutPresetIds: Record<string, BuiltInLayoutPresetId> = {+ canvas: 'edit',+ 'canvas-default': 'compose',+ gallery: 'compose',+ workflow: 'automate',+};++/**+ * Rewrites a persisted preset id onto the current set. Custom preset ids pass+ * through untouched — they are resolved against the account's own list, and only+ * the built-in ids were ever renamed.+ */+export const resolveLayoutPresetId = (presetId: string): string => legacyLayoutPresetIds[presetId] ?? presetId;+export const getLayoutPreset = (presetId: string) =>- layoutPresets.find((preset) => preset.id === presetId) ?? defaultLayoutPreset;+ layoutPresets.find((preset) => preset.id === resolveLayoutPresetId(presetId)) ?? defaultLayoutPreset;++export const isBuiltInLayoutPresetId = (presetId: string): presetId is BuiltInLayoutPresetId =>+ layoutPresets.some((preset) => preset.id === presetId);diff --git a/invokeai/frontend/webv2/src/workbench/projectContracts.ts b/invokeai/frontend/webv2/src/workbench/projectContracts.tsindex 60eec739b4..68cca86418 100644--- a/invokeai/frontend/webv2/src/workbench/projectContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/projectContracts.ts@@ -7,6 +7,7 @@ import type { InvocationControllerState } from './invocationContracts';import type {LayoutPreset,LayoutPresetId,+ LayoutPresetOverrides,ProjectLayoutState,WidgetRegion,WidgetRegionState,@@ -128,4 +129,6 @@ export interface AutosaveState {export interface AccountState {activeLayoutPresetId: LayoutPresetId;customLayoutPresets?: LayoutPreset[];+ /** Saved edits to a built-in preset's arrangement; see {@link LayoutPresetOverrides}. */+ layoutPresetOverrides?: LayoutPresetOverrides;}diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.browser.test.tsxdeleted file mode 100644index 2c35fabf8d..0000000000--- a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.browser.test.tsx+++ /dev/null@@ -1,113 +0,0 @@-/* oxlint-disable react-perf/jsx-no-new-function-as-prop */-import type { Project } from '@workbench/projectContracts';--import { ChakraProvider } from '@chakra-ui/react';-import { system } from '@theme/system';-import { getProjectTabId, PROJECT_CONTENT_PANEL_ID } from '@workbench/projects/projectTabsA11y';-import { act } from 'react';-import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--const mocks = vi.hoisted(() => {- const project = {- id: 'project-one',- name: 'Project one',- queue: { items: [] },- } as unknown as Project;-- return {- closeProject: vi.fn(),- project,- snapshot: {- backendConnection: { status: 'connected' },- projects: [project],- },- switchTo: vi.fn(),- };-});--vi.mock('@features/generation/react', () => ({ flushGenerateDrafts: vi.fn() }));-vi.mock('@features/models', () => ({ useModelLoads: () => [] }));-vi.mock('@features/queue/react', () => ({ useQueueItemProgress: () => null }));-vi.mock('@workbench/projects/projectFile', () => ({ exportOpenProject: vi.fn() }));-vi.mock('@workbench/projects/useProjectActions', () => ({- useProjectActions: () => ({ closeProject: mocks.closeProject, deleteProject: vi.fn() }),-}));-vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => vi.fn() }));-vi.mock('@workbench/WorkbenchContext', () => ({- useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(mocks.project),- useWorkbenchCommands: () => ({- projects: { create: vi.fn(), rename: vi.fn(), switchTo: mocks.switchTo },- }),- useWorkbenchQueries: () => ({ getProject: () => mocks.project }),- useWorkbenchSelector: (selector: (snapshot: typeof mocks.snapshot) => unknown) => selector(mocks.snapshot),-}));-vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string, options?: { name?: string }) =>- key === 'projects.openProjects'- ? 'Open projects'- : key === 'projects.closeProjectLabel'- ? `Close ${options?.name ?? ''}`- : key,- }),-}));-vi.mock('./OpenProjectDialog', () => ({ OpenProjectDialog: () => null }));--import { ProjectTabs } from './ProjectTabs';--let host: HTMLDivElement | null = null;-let root: Root | null = null;-(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;--beforeEach(() => {- mocks.closeProject.mockClear();- mocks.switchTo.mockClear();-});--afterEach(async () => {- await act(() => root?.unmount());- host?.remove();- host = null;- root = null;-});--describe('ProjectTabs accessibility', () => {- it('keeps actions outside the tablist and closes the focused tab from the keyboard', async () => {- host = document.createElement('div');- document.body.append(host);- root = createRoot(host);-- await act(() => {- root?.render(- <ChakraProvider value={system}>- <>- <ProjectTabs />- <main>- <div aria-labelledby={getProjectTabId(mocks.project.id)} id={PROJECT_CONTENT_PANEL_ID} role="tabpanel" />- </main>- </>- </ChakraProvider>- );- });-- const tabList = host.querySelector<HTMLElement>('[role="tablist"]')!;- const tab = tabList.querySelector<HTMLButtonElement>('[role="tab"]')!;- expect(Array.from(tabList.children).every((child) => child.getAttribute('role') === 'tab')).toBe(true);- expect(tab.getAttribute('aria-controls')).toBe(PROJECT_CONTENT_PANEL_ID);- expect(document.getElementById(tab.getAttribute('aria-controls')!)).toHaveAttribute('role', 'tabpanel');- expect(document.getElementById(PROJECT_CONTENT_PANEL_ID)).toHaveAttribute('aria-labelledby', tab.id);- expect(tab).toHaveAttribute('aria-keyshortcuts', 'Delete Backspace');-- await act(() => tab.focus());- await act(() => tab.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Delete' })));- expect(mocks.closeProject).toHaveBeenCalledWith(mocks.project);-- mocks.closeProject.mockClear();- await act(() => tab.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Backspace' })));- expect(mocks.closeProject).toHaveBeenCalledWith(mocks.project);-- expect(tab.querySelector('[role="button"]')).toBeNull();- expect(tabList.querySelectorAll('[role="tab"]')).toHaveLength(1);- });-});diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsxdeleted file mode 100644index d8b9d5d859..0000000000--- a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsx+++ /dev/null@@ -1,484 +0,0 @@-import type { WidgetRegion } from '@workbench/layoutContracts';-import type { Project } from '@workbench/projectContracts';--import { Box, Flex, Icon, Menu, Portal, ScrollArea, Separator } from '@chakra-ui/react';-import { flushGenerateDrafts } from '@features/generation/react';-import { useModelLoads } from '@features/models';-import { getProjectQueueIndicatorState, type QueueItem } from '@features/queue/contracts';-import { useQueueItemProgress } from '@features/queue/react';-import { IconButton, ConfirmDialog, MenuContent, RenameDialog, Tabs, Tooltip } from '@platform/ui';-import { QueueCircularProgress } from '@workbench/components/QueueProgressIndicator';-import { exportOpenProject } from '@workbench/projects/projectFile';-import { getProjectTabId, PROJECT_CONTENT_PANEL_ID } from '@workbench/projects/projectTabsA11y';-import { useProjectActions } from '@workbench/projects/useProjectActions';-import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';-import {- useActiveProjectSelector,- useWorkbenchCommands,- useWorkbenchQueries,- useWorkbenchSelector,-} from '@workbench/WorkbenchContext';-import {- FileDownIcon,- FolderCogIcon,- FolderIcon,- FolderOpenIcon,- PencilIcon,- PlusIcon,- Trash2Icon,- XIcon,-} from 'lucide-react';-import { useCallback, useMemo, useState, type KeyboardEvent, type MouseEvent } from 'react';-import { useTranslation } from 'react-i18next';--import { OpenProjectDialog } from './OpenProjectDialog';--interface ProjectTabSummary {- id: string;- name: string;- queueItems: QueueItem[];-}--const areProjectTabSummariesEqual = (- left: readonly ProjectTabSummary[],- right: readonly ProjectTabSummary[]-): boolean =>- left.length === right.length &&- left.every(- (summary, index) =>- summary.id === right[index]?.id &&- summary.name === right[index]?.name &&- summary.queueItems === right[index]?.queueItems- );--const selectProjectTabSummaries = (projects: readonly Project[]): ProjectTabSummary[] =>- projects.map(({ id, name, queue }) => ({ id, name, queueItems: queue.items }));--const deleteMenuItemHover = { bg: 'bg.error', color: 'fg.error' } as const;-const projectTabCloseHover = { bg: 'bg.emphasized' } 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- * it from the session — the project stays saved and reopens through the- * folder button's Open Project dialog. Closing the last tab lands on Home.- *- * The tab list owns tabs only; pinned project actions live beside it. The- * close glyph is part of the tab's pointer target, while Delete/Backspace is- * the equivalent keyboard command. Right-clicking a tab opens a context menu- * with rename, details, export, close, and delete.- */-export const ProjectTabs = () => {- const { t } = useTranslation();- const projectTabSummaries = useWorkbenchSelector(- (snapshot) => selectProjectTabSummaries(snapshot.projects),- areProjectTabSummariesEqual- );- const activeProjectId = useActiveProjectSelector((project) => project.id);- const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.backendConnection.status);- const modelLoads = useModelLoads();- 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 => queries.getProject(projectId), [queries]);-- const onSwitchProject = useCallback(- (projectId: string) => {- flushGenerateDrafts();- projects.switchTo(projectId);- },- [projects]- );-- const openContextMenu = useCallback((project: ProjectTabSummary, event: MouseEvent) => {- event.preventDefault();- setMenuTarget({ project, x: event.clientX, y: event.clientY });- }, []);-- const createProject = useCallback(() => {- flushGenerateDrafts();- projects.create();- }, [projects]);-- const showOpenDialog = useCallback(() => setIsOpenDialogVisible(true), []);- const hideOpenDialog = useCallback(() => setIsOpenDialogVisible(false), []);-- const closeMenu = useCallback(() => setMenuTarget(null), []);- const closeRenameDialog = useCallback(() => setRenameTarget(null), []);- const closeDeleteDialog = useCallback(() => setDeleteTarget(null), []);-- const startRename = useCallback((project: ProjectTabSummary) => setRenameTarget(project), []);- const startDelete = useCallback((project: ProjectTabSummary) => setDeleteTarget(project), []);-- const closeProjectBySummary = useCallback(- (project: ProjectTabSummary) => {- const currentProject = getProject(project.id);-- if (currentProject) {- closeProject(currentProject);- }- },- [closeProject, getProject]- );-- const renameProject = useCallback(- (name: string) => {- if (renameTarget) {- projects.rename(renameTarget.id, name);- }- },- [projects, renameTarget]- );-- const confirmDeleteProject = useCallback(async () => {- if (deleteTarget) {- const currentProject = getProject(deleteTarget.id);-- if (currentProject) {- await deleteProject(currentProject);- }- }- }, [deleteProject, deleteTarget, getProject]);-- return (- <>- <Tabs.Root minW="0" variant="subtle" value={activeProjectId} h="full" w="full">- <Flex 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 h="full" w="full">- <ScrollArea.Content>- <Tabs.List aria-label={t('projects.openProjects')} h="full" gap="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.List>- </ScrollArea.Content>- </ScrollArea.Viewport>- <ScrollArea.Scrollbar orientation="horizontal">- <ScrollArea.Thumb />- </ScrollArea.Scrollbar>- </ScrollArea.Root>-- <Separator orientation="vertical" h={5} mx="1" alignSelf="center" />-- <Tooltip content={t('projects.createNewProject')} showArrow>- <IconButton- aria-label={t('projects.createNewProject')}- flexShrink={0}- size="xs"- variant="ghost"- alignSelf="center"- onClick={createProject}- >- <PlusIcon />- </IconButton>- </Tooltip>-- <Tooltip content={t('projects.openProject')} showArrow>- <IconButton- aria-label={t('projects.openProject')}- flexShrink={0}- size="xs"- variant="ghost"- alignSelf="center"- onClick={showOpenDialog}- >- <FolderOpenIcon />- </IconButton>- </Tooltip>- </Flex>- </Tabs.Root>-- <ProjectTabContextMenu- target={menuTarget}- onClose={closeMenu}- onCloseProject={closeProjectBySummary}- onDelete={startDelete}- onRename={startRename}- />- <RenameDialog- initialName={renameTarget?.name ?? ''}- isOpen={renameTarget !== null}- onClose={closeRenameDialog}- onSubmit={renameProject}- />- <ConfirmDialog- body={t('projects.deleteProjectTabBody', { name: deleteTarget?.name ?? '' })}- confirmLabel={t('projects.deleteProject')}- isOpen={deleteTarget !== null}- title={t('projects.deleteProjectQuestion')}- onClose={closeDeleteDialog}- onConfirm={confirmDeleteProject}- />- {isOpenDialogVisible ? <OpenProjectDialog isOpen onClose={hideOpenDialog} /> : null}- </>- );-};--const ProjectTab = ({- backendConnectionStatus,- isActive,- loadingModelsCount,- onCloseProject,- onContextMenu,- onSwitchProject,- project,-}: {- backendConnectionStatus: string;- isActive: boolean;- loadingModelsCount: number;- onCloseProject: (project: ProjectTabSummary) => void;- onContextMenu: (project: ProjectTabSummary, event: MouseEvent) => void;- onSwitchProject: (projectId: string) => void;- project: ProjectTabSummary;-}) => {- const baseIndicatorState = getProjectQueueIndicatorState({- isConnected: backendConnectionStatus === 'connected',- loadingModelsCount,- progress: null,- queueItems: project.queueItems,- });- const progress = useQueueItemProgress(baseIndicatorState.runningQueueItemId ?? '');- const { progressState } = getProjectQueueIndicatorState({- isConnected: backendConnectionStatus === 'connected',- loadingModelsCount,- progress,- queueItems: project.queueItems,- });- 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 handleClick = useCallback(- (event: MouseEvent) => {- if (event.target instanceof Element && event.target.closest('[data-project-close]')) {- onCloseProject(project);- return;- }-- onSwitchProject(project.id);- },- [onCloseProject, onSwitchProject, project]- );- const handleKeyDown = useCallback(- (event: KeyboardEvent) => {- if (event.key !== 'Delete' && event.key !== 'Backspace') {- return;- }-- event.preventDefault();- onCloseProject(project);- },- [onCloseProject, project]- );-- return (- <Tabs.Trigger- ref={scrollIntoViewWhenActive}- aria-controls={PROJECT_CONTENT_PANEL_ID}- aria-keyshortcuts="Delete Backspace"- id={getProjectTabId(project.id)}- value={project.id}- fontSize="xs"- flexShrink={0}- h="full"- onClick={handleClick}- onContextMenu={openContextMenu}- onKeyDown={handleKeyDown}- >- {progressState.kind === 'idle' ? (- <Icon as={isActive ? FolderOpenIcon : FolderIcon} boxSize="4" />- ) : (- <QueueCircularProgress size="2xs" state={progressState} />- )}-- {project.name}-- <Box- aria-hidden="true"- as="span"- data-project-close=""- display="inline-flex"- me="-2"- p="1"- rounded="sm"- title={t('projects.closeProjectLabel', { name: project.name })}- _hover={projectTabCloseHover}- >- <XIcon size={12} />- </Box>- </Tabs.Trigger>- );-};--const ProjectTabContextMenu = ({- onClose,- onCloseProject,- onDelete,- onRename,- target,-}: {- onClose: () => void;- onCloseProject: (project: ProjectTabSummary) => void;- onDelete: (project: ProjectTabSummary) => void;- onRename: (project: ProjectTabSummary) => void;- target: { project: ProjectTabSummary; x: number; y: number } | null;-}) => {- const { projects } = useWorkbenchCommands();- const queries = useWorkbenchQueries();- const openWorkbenchWidget = useOpenWorkbenchWidget();- const { t } = useTranslation();-- const positioning = useMemo(- () => ({- getAnchorRect: () => {- 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 = queries.getProject(projectSummary.id);-- if (!project) {- return;- }-- flushGenerateDrafts();- 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- // project, which the switch above just made this one.- const { left, right } = project.widgetRegions;- const region = right.instanceIds.some((instanceId) => project.widgetInstances[instanceId]?.typeId === 'project')- ? 'right'- : left.instanceIds.some((instanceId) => project.widgetInstances[instanceId]?.typeId === 'project')- ? 'left'- : null;- const preferredRegions: WidgetRegion[] = [region ?? 'right'];-- openWorkbenchWidget('project', { preferredRegions });- },- [openWorkbenchWidget, projects, queries]- );-- const handleOpenChange = useCallback(- (event: { open: boolean }) => {- if (!event.open) {- onClose();- }- },- [onClose]- );-- const renameTarget = useCallback(() => {- if (target) {- onRename(target.project);- }- }, [onRename, target]);-- const showDetails = useCallback(() => {- if (target) {- openProjectDetails(target.project);- }- }, [openProjectDetails, target]);-- const exportProject = useCallback(() => {- const project = target ? queries.getProject(target.project.id) : null;-- if (project) {- exportOpenProject(project);- }- }, [queries, target]);-- const closeTargetProject = useCallback(() => {- if (target) {- onCloseProject(target.project);- }- }, [onCloseProject, target]);-- const deleteTargetProject = useCallback(() => {- if (target) {- onDelete(target.project);- }- }, [onDelete, target]);-- return (- <Menu.Root- key={target?.project.id ?? 'closed'}- lazyMount- open={target !== null}- positioning={positioning}- unmountOnExit- onOpenChange={handleOpenChange}- >- <Portal>- <Menu.Positioner>- {target ? (- <MenuContent minW="44">- <Menu.Item value="rename" onClick={renameTarget}>- <Icon as={PencilIcon} boxSize="3.5" />- {t('projects.renameWithEllipsis')}- </Menu.Item>- <Menu.Item value="details" onClick={showDetails}>- <Icon as={FolderCogIcon} boxSize="3.5" />- {t('projects.projectDetails')}- </Menu.Item>- <Menu.Item value="export" onClick={exportProject}>- <Icon as={FileDownIcon} boxSize="3.5" />- {t('common.export')}- </Menu.Item>- <Menu.Separator />- <Menu.Item value="close" onClick={closeTargetProject}>- <Icon as={XIcon} boxSize="3.5" />- {t('common.close')}- </Menu.Item>- <Menu.Separator />- <Menu.Item color="fg.error" value="delete" _hover={deleteMenuItemHover} onClick={deleteTargetProject}>- <Icon as={Trash2Icon} boxSize="3.5" />- {t('projects.deleteProjectWithEllipsis')}- </Menu.Item>- </MenuContent>- ) : null}- </Menu.Positioner>- </Portal>- </Menu.Root>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/index.ts b/invokeai/frontend/webv2/src/workbench/projects/components/index.tsindex 178087dfee..55ddb7bc60 100644--- a/invokeai/frontend/webv2/src/workbench/projects/components/index.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/components/index.ts@@ -1,2 +1 @@export { OpenProjectDialog } from './OpenProjectDialog';-export { ProjectTabs } from './ProjectTabs';diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectTabsA11y.ts b/invokeai/frontend/webv2/src/workbench/projects/projectTabsA11y.tsindex ea7bd4bebd..700aab6192 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectTabsA11y.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectTabsA11y.ts@@ -1,3 +1,2 @@+/** Id of the workbench's project content region, referenced by shell landmarks. */export const PROJECT_CONTENT_PANEL_ID = 'workbench-project-content';--export const getProjectTabId = (projectId: string): string => `workbench-project-tab-${projectId}`;diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.tsindex 35a7db2c29..78513fe03d 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts@@ -1,6 +1,12 @@import type { Project } from '@workbench/projectContracts';import { flushGenerateDrafts } from '@features/generation/react';+import {+ assertAccountScopeCurrent,+ captureAccountScope,+ isAccountScopeCurrent,+} from '@platform/state/accountLifecycle';+import { getApiErrorMessage } from '@platform/transport/http';import { useNavigate } from '@tanstack/react-router';import { useNotify } from '@workbench/useNotify';import {@@ -11,11 +17,15 @@ import {} from '@workbench/WorkbenchContext';import { useTranslation } from 'react-i18next';-import { deleteLibraryProject } from './library';+import { deleteLibraryProject, refreshProjectLibrary } from './library';/**- * Close and delete for projects that are open in the editor, shared by the- * tab bar and the Project panel so the semantics stay in one place:+ * Open, close, and delete for projects, shared by the top bar and the Project+ * panel so the semantics stay in one place:+ *+ * - Open switches to the project when the session already has it, and otherwise+ * hydrates it from the server first. Callers name a project; whether it is+ * already loaded is not their problem.** - Close flushes the document, drops the tab, and keeps the project in the* library. Closing the last tab persists the empty session and lands on@@ -26,6 +36,7 @@ import { deleteLibraryProject } from './library';export const useProjectActions = (): {closeProject: (project: Project) => void;deleteProject: (project: Project) => Promise<void>;+ openProject: (projectId: string, name: string) => Promise<void>;} => {const queries = useWorkbenchQueries();const persistence = useWorkbenchPersistenceAdapter();@@ -47,6 +58,42 @@ export const useProjectActions = (): {return true;};+ const openProject = async (projectId: string, name: string): Promise<void> => {+ const owner = captureAccountScope();++ flushGenerateDrafts();++ if (queries.getSnapshot().projects.some((project) => project.id === projectId)) {+ commands.projects.switchTo(projectId);++ return;+ }++ try {+ const project = await persistenceService.hydrateProjectFromServer(projectId);++ assertAccountScopeCurrent(owner);++ if (!project) {+ notify.error(t('projects.couldNotOpen'), t('projects.couldNotOpenDescription', { name }));+ void refreshProjectLibrary();++ return;+ }++ commands.projects.open(project);+ } catch (error) {+ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ notify.error(+ t('projects.couldNotOpen'),+ getApiErrorMessage(error, t('projects.couldNotOpenDescription', { name }))+ );+ }+ };+const closeProject = (project: Project): void => {flushGenerateDrafts();@@ -85,5 +132,5 @@ export const useProjectActions = (): {commands.projects.close(project.id);};- return { closeProject, deleteProject };+ return { closeProject, deleteProject, openProject };};diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsButton.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsButton.tsxindex fca351cca5..a7b4d0b6f2 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsButton.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsButton.tsx@@ -1,23 +1,17 @@import { IconButton } from '@platform/ui/Button';import { Tooltip } from '@platform/ui/Tooltip';import { SettingsIcon } from 'lucide-react';-import { lazy, Suspense, useCallback } from 'react';+import { useCallback } from 'react';-import { closeWorkbenchSettings, openWorkbenchSettings, settingsDialogStore } from './settingsDialogStore';+import { SettingsDialogHost } from './SettingsDialogHost';+import { openWorkbenchSettings } from './settingsDialogStore';/**- * The top bar's settings entry point, kept deliberately thin.- *- * The dialog body reaches into workbench commands, the persistence service, and- * every settings section, so importing it eagerly made the Launchpad pay for- * the whole editor composition — aggregate project state included — before the- * user had opened a project. The trigger owns nothing but the store- * subscription; the body arrives on first open.+ * The Launchpad's settings entry point, kept deliberately thin. The workbench+ * shell opens settings from its app menu instead and mounts+ * {@link SettingsDialogHost} on its own.*/-const LazySettingsDialog = lazy(() => import('./SettingsDialog'));-export const SettingsButton = () => {- const isOpen = settingsDialogStore.useSelector((snapshot) => snapshot.isOpen);const handleOpen = useCallback(() => openWorkbenchSettings(), []);return (@@ -27,11 +21,7 @@ export const SettingsButton = () => {<SettingsIcon /></IconButton></Tooltip>- {isOpen ? (- <Suspense fallback={null}>- <LazySettingsDialog isOpen onClose={closeWorkbenchSettings} />- </Suspense>- ) : null}+ <SettingsDialogHost /></>);};diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.tsxnew file mode 100644index 0000000000..b139d2339a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.tsx@@ -0,0 +1,26 @@+import { lazy, Suspense } from 'react';++import { closeWorkbenchSettings, settingsDialogStore } from './settingsDialogStore';++/**+ * Mounts the settings dialog wherever it is placed, driven entirely by the+ * store. Every surface that can open settings — the app menu, a widget header+ * gear, a command — writes to the same store, so the dialog body must not be+ * owned by any one trigger.+ *+ * The body reaches into workbench commands, the persistence service, and every+ * settings section, so importing it eagerly made the Launchpad pay for the whole+ * editor composition — aggregate project state included — before the user had+ * opened a project. It arrives on first open.+ */+const LazySettingsDialog = lazy(() => import('./SettingsDialog'));++export const SettingsDialogHost = () => {+ const isOpen = settingsDialogStore.useSelector((snapshot) => snapshot.isOpen);++ return isOpen ? (+ <Suspense fallback={null}>+ <LazySettingsDialog isOpen onClose={closeWorkbenchSettings} />+ </Suspense>+ ) : null;+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsxindex ff8ca1df27..4bbb3e6503 100644--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx@@ -15,6 +15,7 @@ import { WidgetIcon } from '@workbench/iconResolver';import {WidgetChromeSlotById,WidgetRendererById,+ WidgetSourceLockBadge,useWidgetIntentPreloadProps,type WidgetEnableMenuItem,} from '@workbench/widget-frame';@@ -29,7 +30,7 @@ import {import { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchSelector } from '@workbench/WorkbenchContext';import { CheckIcon, ChevronDownIcon, XIcon } from 'lucide-react';-import { Suspense, useCallback, useMemo, type ReactNode } from 'react';+import { Suspense, useCallback, useMemo, useRef, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';type CenterWidgetItem = PlacedWidgetRegionItem<WidgetPlacementInstanceMeta>;@@ -59,7 +60,6 @@ export const CenterArea = () => {const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.backendConnection.status);const modelLoads = useModelLoads();const { widgets } = useWorkbenchCommands();- const focusRegionProps = useFocusRegionProps('center');const getWidgetLabel = useCallback((manifest: Parameters<typeof resolveWidgetLabel>[0]) => resolveWidgetLabel(manifest, t),[t]@@ -94,6 +94,7 @@ export const CenterArea = () => {? centerRegion.activeInstanceId: centerViewItems[0]?.id;const activeItem = centerViewItems.find((item) => item.id === activeCenterViewId);+ const focusRegionProps = useFocusRegionProps('center');const openCenterWidget = useCallback((item: WidgetEnableMenuItem) =>@@ -201,9 +202,12 @@ export const CenterArea = () => {onSelect={selectCenterView}/>{activeItem ? (- <Suspense fallback={null}>- <WidgetChromeSlotById instanceId={activeItem.id} slot="label" widget={activeItem.widget} />- </Suspense>+ <>+ <WidgetSourceLockBadge typeId={activeItem.typeId} />+ <Suspense fallback={null}>+ <WidgetChromeSlotById instanceId={activeItem.id} slot="label" widget={activeItem.widget} />+ </Suspense>+ </>) : null}</ChromeIsland>@@ -276,11 +280,22 @@ const CenterViewMenu = ({}) => {const { t } = useTranslation();const label = activeItem?.label ?? t('widgets.centerViewEmpty');+ const triggerRef = useRef<HTMLButtonElement>(null);+ const selectAndRestoreFocus = useCallback(+ (instanceId: string) => {+ onSelect(instanceId);+ requestAnimationFrame(() => {+ triggerRef.current?.focus({ preventScroll: true });+ });+ },+ [onSelect]+ );return (<Menu.Root positioning={CENTER_MENU_POSITIONING}><Menu.Trigger asChild><IconButton+ ref={triggerRef}aria-label={t('widgets.centerViewLabel', { label })}color="fg"minW="0"@@ -312,7 +327,7 @@ const CenterViewMenu = ({key={item.id}isActive={item.id === activeItem?.id}item={item}- onSelect={onSelect}+ onSelect={selectAndRestoreFocus}/>))}</Menu.ItemGroup>diff --git a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsxindex c5179d6485..7d076fd85d 100644--- a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx@@ -14,7 +14,7 @@ import { sortableKeyboardCoordinates } from '@dnd-kit/sortable';import { useMountEffect } from '@platform/react/useMountEffect';import { FocusRegionProvider } from '@workbench/focusRegions';import { WidgetIcon } from '@workbench/iconResolver';-import { getProjectTabId, PROJECT_CONTENT_PANEL_ID } from '@workbench/projects/projectTabsA11y';+import { PROJECT_CONTENT_PANEL_ID } from '@workbench/projects/projectTabsA11y';import { WidgetBar } from '@workbench/widget-frame';import {getRegionDropState,@@ -51,7 +51,6 @@ export const WorkbenchShell = () => {const { notifications, widgets } = useWorkbenchCommands();const { t } = useTranslation();const panels = useActiveProjectSelector((project) => project.layout.panels);- const projectId = useActiveProjectSelector((project) => project.id);const projectName = useActiveProjectSelector((project) => project.name);const leftRegion = useActiveProjectSelector((project) => project.widgetRegions.left);const rightRegion = useActiveProjectSelector((project) => project.widgetRegions.right);@@ -229,13 +228,16 @@ export const WorkbenchShell = () => {<VisuallyHidden as="h1" id="workbench-project-heading">{projectName}</VisuallyHidden>+ {/* Not a tab panel any more: the project tab strip became a+ dropdown, so there is no tab list for this to belong to. It is+ the project's content region, named by the heading above it. */}<Flex- aria-labelledby={getProjectTabId(projectId)}+ aria-labelledby="workbench-project-heading"flex="1"id={PROJECT_CONTENT_PANEL_ID}minH="0"overflow="hidden"- role="tabpanel"+ role="region"><WidgetBaractiveId={panels.isLeftOpen && !leftRegion.isCollapsed ? leftRegion.activeInstanceId : null}diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsxnew file mode 100644index 0000000000..6781e72340--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsx@@ -0,0 +1,237 @@+import { Badge, Box, chakra, HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';+import { AccountMenuSection, useCapabilities, useHasAccountSection } from '@features/identity';+import { getQueueSummary } from '@features/queue/contracts';+import { APP_VERSION } from '@platform/runtime/appMetadata';+import { IconButton } from '@platform/ui/Button';+import { InvokeMark } from '@platform/ui/InvokeMark';+import { MenuContent } from '@platform/ui/Menu';+import { Tooltip } from '@platform/ui/Tooltip';+import { useNavigate } from '@tanstack/react-router';+import { OPEN_COMMAND_PALETTE_HOTKEY } from '@workbench/hotkeys/catalog';+import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';+import { applyCustomHotkeys } from '@workbench/hotkeys/resolve';+import { openCommandPalette } from '@workbench/palette/paletteStore';+import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';+import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';+import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';+import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';+import {+ BookOpenTextIcon,+ BlocksIcon,+ BoxIcon,+ ListOrderedIcon,+ MenuIcon,+ MessagesSquareIcon,+ SearchIcon,+ SettingsIcon,+ type LucideIcon,+} from 'lucide-react';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++const MENU_POSITIONING = { placement: 'bottom-start' } as const;+const DOCS_URL = 'https://invoke-ai.github.io/InvokeAI/';+const DISCORD_URL = 'https://discord.gg/ZmtBAhwWhy';++/**+ * The application menu. The bar carries no wordmark any more, so the menu header+ * is the only place the product name and version now appear.+ *+ * It deliberately holds no widget navigation. Generate, Canvas, Upscale, and+ * Workflow are widgets, and every dock area already has its own widget picker —+ * listing them here would be a second, worse copy of a control that exists.+ */+export const AppMenu = () => {+ const { t } = useTranslation();+ const { canManageModels, canManageNodes } = useCapabilities();+ const hasAccount = useHasAccountSection();+ const navigate = useNavigate();+ const projectId = useActiveProjectId();+ const openWorkbenchWidget = useOpenWorkbenchWidget();+ const queuedCount = useActiveProjectSelector((project) => getQueueSummary(project.queue.items).total);++ const openModels = useCallback(() => {+ void navigate({ search: { project: projectId }, to: '/models' });+ }, [navigate, projectId]);+ const openNodes = useCallback(() => {+ void navigate({ to: '/nodes' });+ }, [navigate]);+ const openQueue = useCallback(() => openWorkbenchWidget('queue'), [openWorkbenchWidget]);+ const openSettings = useCallback(() => openWorkbenchSettings(), []);++ return (+ <Menu.Root positioning={MENU_POSITIONING}>+ <Menu.Trigger asChild>+ <IconButton aria-label={t('topbar.appMenu.open')} className="group" size="sm" variant="ghost">+ <AppMenuGlyph />+ </IconButton>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="15rem">+ <HStack justify="space-between" px="3" py="2">+ <Text fontSize="xs" fontWeight="800">+ Invoke+ </Text>+ <Text color="fg.subtle" fontSize="2xs">+ v{APP_VERSION}+ </Text>+ </HStack>+ <Menu.Separator />+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">+ {t('topbar.appMenu.manage')}+ </Menu.ItemGroupLabel>+ {canManageModels ? (+ <Menu.Item value="models" onClick={openModels}>+ <Icon as={BoxIcon} boxSize="3.5" />+ <Menu.ItemText>{t('models.manager')}</Menu.ItemText>+ </Menu.Item>+ ) : null}+ {canManageNodes ? (+ <Menu.Item value="nodes" onClick={openNodes}>+ <Icon as={BlocksIcon} boxSize="3.5" />+ <Menu.ItemText>{t('nodes.manager')}</Menu.ItemText>+ </Menu.Item>+ ) : null}+ <Menu.Item value="queue" onClick={openQueue}>+ <Icon as={ListOrderedIcon} boxSize="3.5" />+ <Menu.ItemText>{t('widgets.labels.queue')}</Menu.ItemText>+ {queuedCount > 0 ? (+ <Badge colorPalette="accent" fontSize="2xs" ms="auto" variant="surface">+ {queuedCount}+ </Badge>+ ) : null}+ </Menu.Item>+ </Menu.ItemGroup>+ {hasAccount ? (+ <>+ <Menu.Separator />+ <AccountMenuSection />+ </>+ ) : null}+ <Menu.Separator />+ <HStack gap="0.5" px="1" py="0.5">+ <SearchMenuAction />+ <AppMenuAction icon={SettingsIcon} label={t('common.settings')} value="settings" onClick={openSettings} />+ <AppMenuLink+ href={DOCS_URL}+ icon={BookOpenTextIcon}+ label={t('topbar.appMenu.documentation')}+ value="documentation"+ />+ <AppMenuLink href={DISCORD_URL} icon={MessagesSquareIcon} label="Discord" value="discord" />+ </HStack>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};++/**+ * The mark at rest, a hamburger once you reach for it.+ *+ * The bar carries no other branding, so this slot does double duty: it is the+ * app's identity when idle, and admits to being a menu the moment a pointer or+ * keyboard focus arrives. Both glyphs occupy the same box, so nothing shifts on+ * the swap — only the crossfade reads as a change.+ */+const MARK_SWAP_PROPS = { opacity: 0 } as const;+const GLYPH_SWAP_PROPS = { opacity: 1 } as const;++const AppMenuGlyph = () => (+ <Box boxSize="4" position="relative" role="presentation">+ <Box+ alignItems="center"+ display="flex"+ inset="0"+ justifyContent="center"+ position="absolute"+ transition="opacity var(--wb-motion-duration-fast) ease"+ _groupHover={MARK_SWAP_PROPS}+ _groupFocusVisible={MARK_SWAP_PROPS}+ _groupExpanded={MARK_SWAP_PROPS}+ >+ <InvokeMark size={14} />+ </Box>+ <Box+ alignItems="center"+ display="flex"+ inset="0"+ justifyContent="center"+ opacity="0"+ position="absolute"+ transition="opacity var(--wb-motion-duration-fast) ease"+ _groupHover={GLYPH_SWAP_PROPS}+ _groupFocusVisible={GLYPH_SWAP_PROPS}+ _groupExpanded={GLYPH_SWAP_PROPS}+ >+ <Icon as={MenuIcon} boxSize="4" />+ </Box>+ </Box>+);++const SearchMenuAction = () => {+ const { t } = useTranslation();+ const customHotkeys = useWorkbenchPreferenceSelector((preferences) => preferences.customHotkeys);+ const firstHotkey = applyCustomHotkeys(OPEN_COMMAND_PALETTE_HOTKEY, customHotkeys).keys[0];+ const hotkeyLabel = firstHotkey ? formatHotkeyForPlatform(firstHotkey).join('+') : null;+ const label = hotkeyLabel+ ? t('commandPalette.buttonTooltip', { hotkey: hotkeyLabel })+ : t('commandPalette.buttonLabel');++ return <AppMenuAction icon={SearchIcon} label={label} value="command-palette" onClick={openCommandPalette} />;+};++const FOOTER_ITEM_PROPS = {+ alignItems: 'center',+ flex: '0 0 auto',+ h: '8',+ justifyContent: 'center',+ minW: '8',+ p: '0',+ w: '8',+} as const;++const AppMenuAction = ({+ icon,+ label,+ onClick,+ value,+}: {+ icon: LucideIcon;+ label: string;+ onClick: () => void;+ value: string;+}) => (+ <Menu.Item {...FOOTER_ITEM_PROPS} aria-label={label} value={value} onClick={onClick}>+ <Tooltip content={label} showArrow>+ <Box alignItems="center" display="flex" h="full" justifyContent="center" w="full">+ <Icon as={icon} boxSize="3.5" />+ </Box>+ </Tooltip>+ </Menu.Item>+);++const AppMenuLink = ({+ href,+ icon,+ label,+ value,+}: {+ href: string;+ icon: LucideIcon;+ label: string;+ value: string;+}) => (+ <Menu.Item {...FOOTER_ITEM_PROPS} aria-label={label} asChild value={value}>+ <chakra.a href={href} rel="noreferrer" target="_blank">+ <Tooltip content={label} showArrow>+ <Box alignItems="center" display="flex" h="full" justifyContent="center" w="full">+ <Icon as={icon} boxSize="3.5" />+ </Box>+ </Tooltip>+ </chakra.a>+ </Menu.Item>+);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsxdeleted file mode 100644index f26643e9cb..0000000000--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx+++ /dev/null@@ -1,51 +0,0 @@-import { NumberInput } from '@chakra-ui/react';-import { MIN_BATCH_COUNT, sanitizeBatchCount } from '@features/generation/settings';-import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';-import { useCallback } from 'react';--const getBatchCount = (values: Record<string, unknown>): number => {- const batchCount = values.batchCount;-- return sanitizeBatchCount(batchCount);-};--export const BatchCountField = () => {- const { batchCount, sourceId } = useActiveProjectSelector(- (project) => {- const sourceId = project.invocation.sourceId;- const typeId = sourceId === 'upscale' ? 'upscale' : 'generate';- const instance = Object.values(project.widgetInstances).find((candidate) => candidate.typeId === typeId);-- return { batchCount: getBatchCount(instance?.state.values ?? {}), sourceId };- },- (left, right) => left.batchCount === right.batchCount && left.sourceId === right.sourceId- );- const { generation, widgets } = useWorkbenchCommands();- const handleValueChange = useCallback(- ({ valueAsNumber }: { valueAsNumber: number }) => {- if (Number.isFinite(valueAsNumber)) {- if (sourceId === 'upscale') {- widgets.patchValues('upscale', { batchCount: valueAsNumber });- } else {- generation.setBatchCount(valueAsNumber);- }- }- },- [generation, sourceId, widgets]- );-- return (- <NumberInput.Root- allowMouseWheel- flexShrink={0}- min={MIN_BATCH_COUNT}- size="sm"- value={String(batchCount)}- w="14"- onValueChange={handleValueChange}- >- <NumberInput.Control />- <NumberInput.Input paddingStart="2.5" aria-label="Batch count" />- </NumberInput.Root>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvocationCluster.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvocationCluster.tsxnew file mode 100644index 0000000000..2932492d3d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvocationCluster.tsx@@ -0,0 +1,32 @@+import { HStack } from '@chakra-ui/react';+import { Group } from '@platform/ui/Group';++import { InvokeButton } from './InvokeButton';+import { IterationsField } from './IterationsField';+import { QueueCluster } from './QueueCluster';+import { RoutingControl } from './RoutingControl';+import { useInvocationState } from './useInvocationState';++/**+ * The right zone: two grouped controls.+ *+ * The split is semantic, not decorative. The first group is everything about+ * *dispatching* work — how many, run it, where from and to. The second is+ * everything about work already *dispatched*. Reading the bar left to right+ * therefore reads the lifecycle in order, and progress never lands on a control+ * whose job is to start something new.+ */+export const InvocationCluster = () => {+ const state = useInvocationState();++ return (+ <HStack flexShrink={0} gap="2" justify="end">+ <Group attached>+ <IterationsField />+ <InvokeButton state={state} />+ <RoutingControl state={state} />+ </Group>+ <QueueCluster />+ </HStack>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsxnew file mode 100644index 0000000000..45a9efe19d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx@@ -0,0 +1,122 @@+import { HStack, Icon, Kbd, Separator, Stack, Text } from '@chakra-ui/react';+import { Button } from '@platform/ui/Button';+import { Tooltip } from '@platform/ui/Tooltip';+import { getDestinationLabel } from '@workbench/invocation';+import { PlayIcon } from 'lucide-react';+import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import type { InvocationState } from './useInvocationState';++import { HIDE_BELOW_HINT_WIDTH } from './topbarBreakpoints';+import { useTopbarShortcutBinding } from './useTopbarShortcut';++const TOOLTIP_CONTENT_PROPS = { p: '0' };++const compactBlockingReason = (reason: string, noNodesLabel: string): string => {+ if (reason === 'The project graph has no nodes. Add nodes in the Workflow view.') {+ return noNodesLabel;+ }++ return reason.replace(/^The /, '').replace(/project graph/i, 'workflow');+};++const plural = (count: number, noun: string): string => `${count} ${noun}${count === 1 ? '' : 's'}`;++/**+ * The single Invoke action for the whole application.+ *+ * Its appearance, width, and enabled state never change while a batch runs.+ * Invoke queues further items on top of a running batch, so a button that+ * morphed into a progress bar would read as unavailable at exactly the moment+ * it is most useful. Progress belongs to the queue group. (§5.1, contract §9.4.)+ */+export const InvokeButton = ({ state }: { state: InvocationState }) => {+ const { t } = useTranslation();+ const { blockingReasons, invoke, isValid } = state;+ const shortcutBinding = useTopbarShortcutBinding('app.invoke');+ const shortcut = shortcutBinding?.display ?? null;+ const handleClick = useCallback(() => void invoke(), [invoke]);+ const tooltipContent = useMemo(() => <InvokeTooltipContent shortcut={shortcut} state={state} />, [shortcut, state]);++ return (+ <Tooltip content={tooltipContent} contentProps={TOOLTIP_CONTENT_PROPS} openDelay={200} showArrow>+ <Button+ aria-disabled={!isValid}+ aria-keyshortcuts={shortcutBinding?.aria}+ aria-label={+ isValid+ ? t('topbar.invoke.invoke')+ : t('topbar.invoke.unavailable', {+ reason: blockingReasons[0] ?? t('topbar.invoke.unrunnable'),+ })+ }+ colorPalette="brand"+ cursor={isValid ? undefined : 'not-allowed'}+ flexShrink={0}+ opacity={isValid ? undefined : 0.55}+ size="sm"+ onClick={isValid ? handleClick : undefined}+ zIndex="2"+ >+ <Icon as={PlayIcon} />+ {t('topbar.invoke.invoke')}+ {shortcut ? (+ <Kbd css={HIDE_BELOW_HINT_WIDTH} variant="outline" color="bg" size="sm">+ {shortcut}+ </Kbd>+ ) : null}+ </Button>+ </Tooltip>+ );+};++const InvokeTooltipContent = ({ shortcut, state }: { shortcut: string | null; state: InvocationState }) => {+ const { t } = useTranslation();+ const { batchCount, blockingReasons, invocation, isValid, promptExpansion } = state;+ const destination = getDestinationLabel(invocation.destination);+ const promptCount = promptExpansion.count;+ const summary =+ invocation.sourceId === 'generate' || invocation.sourceId === 'upscale'+ ? promptExpansion.isLoading+ ? t('topbar.invoke.expandingPrompts')+ : `${plural(promptCount, 'prompt')} × ${plural(batchCount, 'iteration')} → ${plural(promptCount * batchCount, 'generation')}`+ : `Workflow × ${plural(batchCount, 'run')} → ${plural(batchCount, 'generation')}`;++ return (+ <Stack gap="1.5" minW="14rem" p="2">+ <HStack justify="space-between">+ <Text fontSize="xs" fontWeight="800">+ {isValid ? t('topbar.invoke.addToQueue') : t('topbar.invoke.unableToQueue')}+ </Text>+ {shortcut ? (+ <Kbd size="sm" variant="subtle">+ {shortcut}+ </Kbd>+ ) : null}+ </HStack>+ <Text color="fg.muted" fontSize="xs">+ {summary}+ </Text>+ <Separator borderColor="border.subtle" />+ {blockingReasons.length > 0 ? (+ <Stack gap="1">+ {blockingReasons.map((reason) => (+ <HStack key={reason} align="start" gap="1.5">+ <Text color="fg.subtle" fontSize="xs" lineHeight="1.35">+ •+ </Text>+ <Text color="fg.muted" fontSize="xs" lineHeight="1.35">+ {compactBlockingReason(reason, t('topbar.invoke.noNodes'))}+ </Text>+ </HStack>+ ))}+ </Stack>+ ) : (+ <Text color="fg.muted" fontSize="xs">+ {t('topbar.invoke.addingImagesTo', { destination })}+ </Text>+ )}+ </Stack>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsxdeleted file mode 100644index 1b97a275ad..0000000000--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx+++ /dev/null@@ -1,364 +0,0 @@-import type { InvocationRoute, InvocationSourceId, ResultDestination } from '@workbench/invocationContracts';--import { Flex, Group, HStack, Icon, Menu, Portal, Separator, Stack, Text, VStack } from '@chakra-ui/react';-import { flushGenerateDrafts, useDynamicPrompts, type DynamicPromptsExpansion } from '@features/generation/react';-import {- getEffectivePrompts,- normalizeGenerateSettings,- sanitizeBatchCount,- sanitizeDynamicPromptsConfig,-} from '@features/generation/settings';-import { ensureModelsLoaded, useModelsSelector } from '@features/models';-import { useInvocationTemplatesSelector } from '@features/workflow/react';-import { useMountEffect } from '@platform/react/useMountEffect';-import {- assertAccountScopeCurrent,- captureAccountScope,- isAccountScopeCurrent,-} from '@platform/state/accountLifecycle';-import { Button, IconButton, Tooltip } from '@platform/ui';-import {- formatRoute,- createInvocationRouteInputSelector,- getDestinationLabel,- invocationSources,- isInvocationRouteValid,- resolveInvocationRoute,- resolveInvocationRouteInput,- resultDestinations,-} from '@workbench/invocation';-import { submitResolvedInvocation } from '@workbench/invocationSubmit';-import {- useActiveProjectSelector,- useWorkbenchCommands,- useWorkbenchQueries,- useWorkbenchSelector,-} from '@workbench/WorkbenchContext';-import { CheckIcon, ChevronDownIcon, LockKeyholeIcon, SparklesIcon } from 'lucide-react';-import { useCallback, useMemo } from 'react';-import { useTranslation } from 'react-i18next';--const CONTROL_WIDTH = '10rem';-const selectInvocationRouteInput = createInvocationRouteInputSelector();-const MENU_POSITIONING = { placement: 'bottom-end' } as const;-const TOOLTIP_CONTENT_PROPS = { p: '0' };-const DISABLED_PROPS = { opacity: 0.4 };--/** Reads the persisted dynamic prompt fields off untyped widget values. */-const readDynamicPromptsConfig = (values: Record<string, unknown>) => ({- combinatorial: values.dynamicPromptsCombinatorial,- maxPrompts: values.dynamicPromptsMaxPrompts,- sampleSeed: values.dynamicPromptsSampleSeed,- seedBehaviour: values.dynamicPromptsSeedBehaviour,-});--/**- * The prompt that will actually be expanded and submitted — the authored text- * wrapped by the active template, since a template can introduce `{a|b}` the- * authored prompt never had.- */-const readEffectivePositivePrompt = (values: Record<string, unknown>): string => {- const settings = normalizeGenerateSettings(values);-- return settings ? getEffectivePrompts(settings).positivePrompt : '';-};--const getBatchCount = (values: Record<string, unknown>): number => {- const batchCount = values.batchCount;-- return sanitizeBatchCount(batchCount);-};--const compactBlockingReason = (reason: string): string => {- if (reason === 'The project graph has no nodes. Add nodes in the Workflow view.') {- return 'No nodes in graph';- }-- return reason.replace(/^The /, '').replace(/project graph/i, 'workflow');-};--const plural = (count: number, noun: string): string => `${count} ${noun}${count === 1 ? '' : 's'}`;--const InvokeTooltipContent = ({- blockingReasons,- sourceValues,- invocation,- isValid,- promptExpansion,-}: {- blockingReasons: string[];- sourceValues: Record<string, unknown>;- invocation: InvocationRoute;- isValid: boolean;- promptExpansion: DynamicPromptsExpansion;-}) => {- const batchCount = getBatchCount(sourceValues);- const destination = getDestinationLabel(invocation.destination);- const promptCount = promptExpansion.count;- const summary =- invocation.sourceId === 'generate' || invocation.sourceId === 'upscale'- ? promptExpansion.isLoading- ? 'Expanding prompts…'- : `${plural(promptCount, 'prompt')} × ${plural(batchCount, 'iteration')} → ${plural(promptCount * batchCount, 'generation')}`- : `Workflow × ${plural(batchCount, 'run')} → ${plural(batchCount, 'generation')}`;-- return (- <Stack gap="1.5" minW="14rem" p="2">- <Text fontSize="xs" fontWeight="800">- {isValid ? 'Add to Queue' : 'Unable to Queue'}- </Text>- <Text color="fg.muted" fontSize="xs">- {summary}- </Text>- {blockingReasons.length > 0 ? (- <>- <Separator borderColor="border.subtle" />- <Stack gap="1">- {blockingReasons.map((reason) => (- <HStack key={reason} align="start" gap="1.5">- <Text color="fg.subtle" fontSize="xs" lineHeight="1.35">- •- </Text>- <Text color="fg.muted" fontSize="xs" lineHeight="1.35">- {compactBlockingReason(reason)}- </Text>- </HStack>- ))}- </Stack>- </>- ) : (- <>- <Separator borderColor="border.subtle" />- <Text color="fg.muted" fontSize="xs">- Adding images to {destination}- </Text>- </>- )}- </Stack>- );-};--export const InvokeControl = () => {- const { t } = useTranslation();- const routeInput = useActiveProjectSelector(selectInvocationRouteInput);- 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;- const { invocation } = routeInput;-- // Project-graph route validation reads the invocation templates imperatively;- // subscribing here keeps the resolved route live while they load.- useInvocationTemplatesSelector((snapshot) => snapshot.status);-- const resolvedRoute = resolveInvocationRouteInput(routeInput, 'global', routeInput.invocation, availabilityModels);- const isLocked = invocation.sourceLocked || invocation.destinationLocked;- const isConnected = backendConnectionStatus === 'connected';-- // Observing the shared expansion cache here keeps the count honest and costs- // nothing extra: the Generate preview and the submit path use the same key.- const promptExpansion = useDynamicPrompts(- readEffectivePositivePrompt(routeInput.generateValues),- invocation.sourceId === 'generate' || invocation.sourceId === 'canvas'- ? sanitizeDynamicPromptsConfig(readDynamicPromptsConfig(routeInput.generateValues))- : null- );- // A prompt that will not expand cannot be submitted — the alternative is putting- // the literal `{a|b}` in front of the model — so this blocks rather than just- // annotating. `submitResolvedInvocation` enforces the same rule for the hotkey.- const expansionReason = promptExpansion.isError- ? 'The prompt could not be expanded.'- : (promptExpansion.error ?? null);- const blockingReasons = useMemo(- () => [- ...(isConnected ? [] : ['The backend is disconnected.']),- ...(expansionReason === null ? [] : [expansionReason]),- ...resolvedRoute.validationReasons,- ],- [expansionReason, isConnected, resolvedRoute.validationReasons]- );- const isValid = isInvocationRouteValid(resolvedRoute) && isConnected && expansionReason === null;- const routeLabel = isValid ? formatRoute(resolvedRoute) : (blockingReasons[0] ?? formatRoute(resolvedRoute));- useMountEffect(() => {- void ensureModelsLoaded();- });-- const onInvoke = useCallback(async () => {- const owner = captureAccountScope();- flushGenerateDrafts();-- try {- const { prepareCanvasInvocation } = await import('@workbench/widgets/canvas/invoke/prepareCanvasInvocation');-- assertAccountScopeCurrent(owner);- const snapshot = queries.getSnapshot();- const postFlushRoute = resolveInvocationRoute(- snapshot.activeProject,- 'global',- snapshot.activeProject.invocation,- availabilityModels- );-- if (!isInvocationRouteValid(postFlushRoute) || snapshot.backendConnection.status !== 'connected') {- return;- }-- submitResolvedInvocation({- commands,- formatControlLayerError: (code, layerName) =>- t('widgets.layers.control.invalidLayer', {- name: layerName,- reason: t(`widgets.layers.control.validation.${code}`),- }),- models: availabilityModels,- owner,- prepareCanvasInvocation,- project: snapshot.activeProject,- route: postFlushRoute,- });- } catch (error) {- if (!isAccountScopeCurrent(owner)) {- return;- }-- throw error;- }- }, [availabilityModels, commands, queries, t]);- const tooltipContent = useMemo(- () => (- <InvokeTooltipContent- blockingReasons={blockingReasons}- sourceValues={- routeInput.invocation.sourceId === 'upscale' ? routeInput.upscaleValues : routeInput.generateValues- }- invocation={invocation}- isValid={isValid}- promptExpansion={promptExpansion}- />- ),- [- blockingReasons,- invocation,- isValid,- promptExpansion,- routeInput.generateValues,- routeInput.invocation.sourceId,- routeInput.upscaleValues,- ]- );- const handleSourceChange = useCallback(- (event: { value: string }) => generation.setSource(event.value as InvocationSourceId),- [generation]- );- const handleDestinationChange = useCallback(- (event: { value: string }) => generation.setDestination(event.value as ResultDestination),- [generation]- );- return (- <Flex>- <Menu.Root positioning={MENU_POSITIONING}>- <Group attached>- <Tooltip content={tooltipContent} contentProps={TOOLTIP_CONTENT_PROPS} openDelay={200} showArrow>- <Button- aria-disabled={!isValid}- colorPalette="brand"- cursor={isValid ? undefined : 'not-allowed'}- opacity={isValid ? undefined : 0.6}- size="sm"- roundedEnd="none"- onClick={onInvoke}- w={CONTROL_WIDTH}- minW="0"- justifyContent="start"- >- <Icon as={SparklesIcon} boxSize="4" flexShrink={0} />- <VStack align="start" gap="0" minW="0">- <Text fontSize="sm" fontWeight="700" lineHeight="1">- Invoke- </Text>- <HStack gap="1" maxW="full" mb="-0.5">- <Text fontSize="0.58rem" lineHeight="1.1" opacity="0.85" truncate>- {routeLabel}- </Text>- {isLocked ? <Icon as={LockKeyholeIcon} boxSize="2.5" flexShrink={0} /> : null}- </HStack>- </VStack>- </Button>- </Tooltip>- <Menu.Trigger asChild>- <IconButton- aria-label="Choose invocation source and destination"- colorPalette="brand"- minW="0"- size="sm"- w="7"- >- <ChevronDownIcon />- </IconButton>- </Menu.Trigger>- </Group>- <Portal>- <Menu.Positioner>- <Menu.Content minW="14rem">- <Menu.RadioItemGroup value={invocation.sourceId} onValueChange={handleSourceChange}>- <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">- Source- </Menu.ItemGroupLabel>- {invocationSources.map((source) => (- <Menu.RadioItem- key={source.id}- value={source.id}- disabled={!source.available}- _disabled={DISABLED_PROPS}- >- <Menu.ItemText>{source.label}</Menu.ItemText>- {source.available ? null : (- <Text color="fg.subtle" fontSize="2xs" ms="auto">- Soon- </Text>- )}- <Menu.ItemIndicator>- <Icon as={CheckIcon} boxSize="3" />- </Menu.ItemIndicator>- </Menu.RadioItem>- ))}- </Menu.RadioItemGroup>-- <Menu.Separator borderColor="border.subtle" />-- <Menu.RadioItemGroup value={invocation.destination} onValueChange={handleDestinationChange}>- <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">- Destination- </Menu.ItemGroupLabel>- {resultDestinations.map((destination) => (- <Menu.RadioItem key={destination.id} value={destination.id}>- <Menu.ItemText>{destination.label}</Menu.ItemText>- <Menu.ItemIndicator>- <Icon as={CheckIcon} boxSize="3" />- </Menu.ItemIndicator>- </Menu.RadioItem>- ))}- </Menu.RadioItemGroup>-- <Menu.Separator borderColor="border.subtle" />-- <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={generation.toggleDestinationLock}>- <Icon as={LockKeyholeIcon} boxSize="3" opacity={invocation.destinationLocked ? 1 : 0.35} />- <Menu.ItemText>- {invocation.destinationLocked ? 'Unlock destination' : 'Lock destination'}- </Menu.ItemText>- </Menu.Item>- </Menu.Content>- </Menu.Positioner>- </Portal>- </Menu.Root>- </Flex>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsxnew file mode 100644index 0000000000..ab6e2b1b5f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsx@@ -0,0 +1,64 @@+import { NumberInput } from '@chakra-ui/react';+import { MIN_BATCH_COUNT } from '@features/generation/settings';+import { Tooltip } from '@platform/ui/Tooltip';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { getBatchCount } from './useInvocationState';++/**+ * How many times the current graph runs per Invoke.+ *+ * A plain `NumberInput` with its stepper — typing, arrow keys, and the wheel all+ * behave the way they do everywhere else in the app, because it is the same+ * control everywhere else in the app uses.+ */+export const IterationsField = () => {+ const { t } = useTranslation();+ const { batchCount, sourceId } = useActiveProjectSelector(+ (project) => {+ const sourceId = project.invocation.sourceId;+ const typeId = sourceId === 'upscale' ? 'upscale' : 'generate';+ const instance = Object.values(project.widgetInstances).find((candidate) => candidate.typeId === typeId);++ return { batchCount: getBatchCount(instance?.state.values ?? {}), sourceId };+ },+ (left, right) => left.batchCount === right.batchCount && left.sourceId === right.sourceId+ );+ const { generation, widgets } = useWorkbenchCommands();+ const handleValueChange = useCallback(+ ({ valueAsNumber }: { valueAsNumber: number }) => {+ if (!Number.isFinite(valueAsNumber)) {+ return;+ }++ if (sourceId === 'upscale') {+ widgets.patchValues('upscale', { batchCount: valueAsNumber });+ } else {+ generation.setBatchCount(valueAsNumber);+ }+ },+ [generation, sourceId, widgets]+ );++ return (+ <Tooltip content={t('topbar.iterations.tooltip', { count: batchCount })} showArrow>+ <NumberInput.Root+ allowMouseWheel+ flexShrink={0}+ min={MIN_BATCH_COUNT}+ rounded="l2"+ size="sm"+ value={String(batchCount)}+ w="14"+ onValueChange={handleValueChange}+ >+ <NumberInput.Control />+ {/* The visible surface is the inner control, so it inherits the root's+ radius — that is the corner an attached `Group` adjusts. */}+ <NumberInput.Input aria-label={t('topbar.iterations.label')} paddingStart="2" rounded="inherit" />+ </NumberInput.Root>+ </Tooltip>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsxnew file mode 100644index 0000000000..14dbedda60--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx@@ -0,0 +1,60 @@+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';+import { useWorkbenchCommands, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { LayoutPresetDialog } from './LayoutPresetDialog';+import { closeLayoutPresetAdmin, layoutPresetManagerStore } from './layoutPresetManagerStore';++/**+ * Hosts the edit and delete dialogs shared by every preset-management surface.+ * The trigger only writes a preset id to the store, which avoids mounting a+ * second copy of these dialogs in both the strip and the manager.+ */+export const LayoutPresetAdminDialogs = () => {+ const { t } = useTranslation();+ const { layout } = useWorkbenchCommands();+ const customPresets = useWorkbenchSelector((snapshot) => snapshot.account.customLayoutPresets ?? []);+ const { deletePresetId, editPresetId } = layoutPresetManagerStore.useSelector((snapshot) => snapshot);+ const editTarget = customPresets.find((preset) => preset.id === editPresetId) ?? null;+ const deleteTarget = customPresets.find((preset) => preset.id === deletePresetId) ?? null;++ const submitEdit = useCallback(+ ({ iconId, name }: { iconId: string; name: string }) => {+ if (editTarget) {+ layout.renamePreset(editTarget.id, name);+ layout.setPresetIcon(editTarget.id, iconId);+ }+ },+ [editTarget, layout]+ );+ const confirmDelete = useCallback(() => {+ if (deleteTarget) {+ layout.deletePreset(deleteTarget.id);+ }+ }, [deleteTarget, layout]);++ return (+ <>+ {editTarget ? (+ <LayoutPresetDialog+ iconId={editTarget.iconId}+ isOpen+ name={editTarget.label}+ submitLabel={t('topbar.presets.save')}+ title={t('topbar.presets.edit')}+ onClose={closeLayoutPresetAdmin}+ onSubmit={submitEdit}+ />+ ) : null}+ <ConfirmDialog+ body={t('topbar.presets.deleteBody', { name: deleteTarget?.label ?? t('topbar.presets.layoutPreset') })}+ confirmLabel={t('topbar.presets.delete')}+ isOpen={deleteTarget !== null}+ title={t('topbar.presets.deleteQuestion')}+ onClose={closeLayoutPresetAdmin}+ onConfirm={confirmDelete}+ />+ </>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.tsxnew file mode 100644index 0000000000..95bc6bb229--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.tsx@@ -0,0 +1,203 @@+import type { FormEvent, KeyboardEvent } from 'react';++import { chakra, Dialog, Icon, Input, Portal, SimpleGrid, Stack, Text } from '@chakra-ui/react';+import { Button, CloseButton, IconButton } from '@platform/ui/Button';+import { Field } from '@platform/ui/Field';+import { Tooltip } from '@platform/ui/Tooltip';+import { useCallback, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { getNextIconId } from './layoutPresetDialogModel';+import { DEFAULT_LAYOUT_PRESET_ICON_ID, layoutPresetIconGroups } from './layoutPresetIcons';++const layoutPresetIconIds = layoutPresetIconGroups.flatMap((group) => group.options.map((option) => option.id));++/**+ * Name and icon for a custom layout preset.+ *+ * Custom presets sit in the same strip as the built-ins and collapse to+ * icon-only below 1280px, so an icon is not decoration — without one every+ * custom preset would be an identical anonymous square at that width. The+ * picker offers a curated set for exactly that reason: the job is to tell your+ * own layouts apart at a glance, not to browse an icon library.+ */+export const LayoutPresetDialog = ({+ iconId: initialIconId,+ isOpen,+ name: initialName,+ onClose,+ onSubmit,+ submitLabel,+ title,+}: {+ iconId?: string;+ isOpen: boolean;+ name: string;+ onClose: () => void;+ onSubmit: (value: { iconId: string; name: string }) => void;+ submitLabel: string;+ title: string;+}) => {+ const { t } = useTranslation();+ const [name, setName] = useState(initialName);+ const [iconId, setIconId] = useState(initialIconId ?? DEFAULT_LAYOUT_PRESET_ICON_ID);+ const nameRef = useRef<HTMLInputElement>(null);++ // Without this the focus trap lands on the header's close button, so opening+ // the dialog and typing does nothing. `initialFocusEl` rather than `autoFocus`+ // so the trap itself does the focusing, at the point it is ready to.+ const initialFocusEl = useCallback(() => nameRef.current, []);++ const handleOpenChange = useCallback(+ (event: { open: boolean }) => {+ if (!event.open) {+ onClose();+ }+ },+ [onClose]+ );+ const handleNameChange = useCallback(+ (event: { currentTarget: { value: string } }) => setName(event.currentTarget.value),+ []+ );+ const handleSubmit = useCallback(+ (event: FormEvent) => {+ event.preventDefault();+ const trimmed = name.trim();++ if (!trimmed) {+ onClose();++ return;+ }++ onSubmit({ iconId, name: trimmed });+ onClose();+ },+ [iconId, name, onClose, onSubmit]+ );+ const handleIconKeyDown = useCallback(+ (event: KeyboardEvent<HTMLDivElement>) => {+ const nextIconId = getNextIconId(layoutPresetIconIds, iconId, event.key);++ if (!nextIconId) {+ return;+ }++ event.preventDefault();+ setIconId(nextIconId);+ const nextButton = [...event.currentTarget.querySelectorAll<HTMLButtonElement>('[role="radio"]')].find(+ (button) => button.dataset.iconId === nextIconId+ );+ nextButton?.focus();+ },+ [iconId]+ );++ return (+ <Dialog.Root initialFocusEl={initialFocusEl} open={isOpen} lazyMount unmountOnExit onOpenChange={handleOpenChange}>+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content asChild maxW="26rem">+ <chakra.form onSubmit={handleSubmit}>+ <Dialog.Header>+ <Dialog.Title>{title}</Dialog.Title>+ <Dialog.CloseTrigger asChild>+ <CloseButton size="sm" type="button" />+ </Dialog.CloseTrigger>+ </Dialog.Header>+ <Dialog.Body>+ <Stack gap="4">+ <Field label={t('topbar.presets.name')}>+ <Input+ ref={nameRef}+ autoComplete="off"+ name="layout-preset-name"+ size="sm"+ value={name}+ onChange={handleNameChange}+ />+ </Field>+ <Stack+ aria-label={t('topbar.presets.iconPicker')}+ gap="3"+ role="radiogroup"+ tabIndex={-1}+ onKeyDown={handleIconKeyDown}+ >+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">+ {t('topbar.presets.icon')}+ </Text>+ {layoutPresetIconGroups.map((group) => (+ <Stack key={group.label} gap="1.5">+ <Text color="fg.muted" fontSize="2xs">+ {group.label}+ </Text>+ <SimpleGrid columns={8} gap="1">+ {group.options.map((entry) => (+ <IconOption+ key={entry.id}+ icon={entry.icon}+ iconId={entry.id}+ isSelected={entry.id === iconId}+ label={entry.label}+ onSelect={setIconId}+ />+ ))}+ </SimpleGrid>+ </Stack>+ ))}+ </Stack>+ </Stack>+ </Dialog.Body>+ <Dialog.Footer>+ <Button size="sm" type="button" variant="outline" onClick={onClose}>+ {t('common.cancel')}+ </Button>+ <Button disabled={name.trim().length === 0} size="sm" type="submit">+ {submitLabel}+ </Button>+ </Dialog.Footer>+ </chakra.form>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ );+};++const IconOption = ({+ icon,+ iconId,+ isSelected,+ label,+ onSelect,+}: {+ icon: (typeof layoutPresetIconGroups)[number]['options'][number]['icon'];+ iconId: string;+ isSelected: boolean;+ label: string;+ onSelect: (iconId: string) => void;+}) => {+ const handleClick = useCallback(() => onSelect(iconId), [iconId, onSelect]);++ return (+ <Tooltip content={label} showArrow>+ <IconButton+ aria-checked={isSelected}+ aria-label={label}+ colorPalette={isSelected ? 'accent' : undefined}+ data-icon-id={iconId}+ role="radio"+ size="sm"+ tabIndex={isSelected ? 0 : -1}+ type="button"+ variant={isSelected ? 'solid' : 'ghost'}+ onClick={handleClick}+ >+ <Icon as={icon} />+ </IconButton>+ </Tooltip>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialog.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialog.tsxnew file mode 100644index 0000000000..2a749fbfad--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialog.tsx@@ -0,0 +1,22 @@+import { lazy, Suspense } from 'react';++import { layoutPresetManagerStore } from './layoutPresetManagerStore';++/**+ * Mounts the preset manager on demand. Managing presets is a rare, deliberate+ * trip, so its dialog — three list sections plus a rename and a confirm dialog —+ * has no business in the editor's initial payload.+ */+const LazyLayoutPresetManagerDialogBody = lazy(() =>+ import('./LayoutPresetManagerDialogBody').then((module) => ({ default: module.LayoutPresetManagerDialogBody }))+);++export const LayoutPresetManagerDialog = () => {+ const isOpen = layoutPresetManagerStore.useSelector((snapshot) => snapshot.isOpen);++ return isOpen ? (+ <Suspense fallback={null}>+ <LazyLayoutPresetManagerDialogBody />+ </Suspense>+ ) : null;+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsxnew file mode 100644index 0000000000..a103abc390--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsx@@ -0,0 +1,169 @@+import type { LayoutPreset } from '@workbench/layoutContracts';++import { Dialog, HStack, Icon, Portal, Stack, Text } from '@chakra-ui/react';+import { Button, CloseButton, IconButton } from '@platform/ui/Button';+import { Tooltip } from '@platform/ui/Tooltip';+import { layoutPresets } from '@workbench/layoutPresets';+import { useWorkbenchCommands, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { PencilIcon, RotateCcwIcon, Trash2Icon } from 'lucide-react';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { closeLayoutPresetManager, openLayoutPresetDelete, openLayoutPresetEdit } from './layoutPresetManagerStore';+import { getLayoutPresetPresentation } from './layoutPresetPresentation';++/**+ * The long tail of preset administration, moved off the top bar.+ *+ * The strip itself only ever offers the three switch targets and the active+ * preset's own menu; renaming, deleting, and undoing a saved edit to a built-in+ * are rare enough that putting them in the bar would cost more than they return+ * — which is also why this body is only fetched once someone opens it.+ */+export const LayoutPresetManagerDialogBody = () => {+ const { t } = useTranslation();+ const customPresets = useWorkbenchSelector((snapshot) => snapshot.account.customLayoutPresets ?? []);+ const overriddenPresetIds = useWorkbenchSelector((snapshot) =>+ Object.keys(snapshot.account.layoutPresetOverrides ?? {})+ );++ const handleOpenChange = useCallback((event: { open: boolean }) => {+ if (!event.open) {+ closeLayoutPresetManager();+ }+ }, []);++ return (+ <Dialog.Root open lazyMount unmountOnExit onOpenChange={handleOpenChange}>+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content maxW="30rem">+ <Dialog.Header>+ <Dialog.Title>{t('topbar.presets.manage')}</Dialog.Title>+ <Dialog.CloseTrigger asChild>+ <CloseButton size="sm" />+ </Dialog.CloseTrigger>+ </Dialog.Header>+ <Dialog.Body>+ <Stack gap="4">+ <Stack gap="1.5">+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">+ {t('topbar.presets.builtIn')}+ </Text>+ {layoutPresets.map((preset) => (+ <BuiltInPresetRow+ key={preset.id}+ isOverridden={overriddenPresetIds.includes(preset.id)}+ preset={preset}+ />+ ))}+ </Stack>+ <Stack gap="1.5">+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">+ {t('topbar.presets.custom')}+ </Text>+ {customPresets.length === 0 ? (+ <Text color="fg.muted" fontSize="xs">+ {t('topbar.presets.none')}+ </Text>+ ) : (+ customPresets.map((preset) => (+ <CustomPresetRow+ key={preset.id}+ preset={preset}+ onDelete={openLayoutPresetDelete}+ onEdit={openLayoutPresetEdit}+ />+ ))+ )}+ </Stack>+ </Stack>+ </Dialog.Body>+ <Dialog.Footer>+ <Button size="sm" variant="outline" onClick={closeLayoutPresetManager}>+ {t('common.done')}+ </Button>+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ );+};++const BuiltInPresetRow = ({ isOverridden, preset }: { isOverridden: boolean; preset: LayoutPreset }) => {+ const { t } = useTranslation();+ const { layout } = useWorkbenchCommands();+ const { icon, tooltip } = getLayoutPresetPresentation(preset);+ // Clearing the override restores the shipped arrangement. Saving the shipped+ // snapshot back is exactly that, and needs no second reducer path.+ const restoreDefault = useCallback(() => layout.restorePresetDefault(preset.id), [layout, preset.id]);++ return (+ <HStack borderColor="border.subtle" borderWidth="1px" gap="2" px="3" py="2" rounded="md">+ <Icon as={icon} boxSize="4" color="fg.muted" flexShrink={0} />+ <Stack flex="1" gap="0" minW="0">+ <Text fontSize="xs" fontWeight="600">+ {preset.label}+ </Text>+ <Text color="fg.subtle" fontSize="2xs">+ {isOverridden ? `${tooltip} · edited` : tooltip}+ </Text>+ </Stack>+ {isOverridden ? (+ <Tooltip content={t('topbar.presets.restore')} showArrow>+ <IconButton+ aria-label={t('topbar.presets.restoreNamed', { name: preset.label })}+ size="2xs"+ variant="ghost"+ onClick={restoreDefault}+ >+ <Icon as={RotateCcwIcon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ ) : null}+ </HStack>+ );+};++const CustomPresetRow = ({+ onDelete,+ onEdit,+ preset,+}: {+ preset: LayoutPreset;+ onDelete: (presetId: string) => void;+ onEdit: (presetId: string) => void;+}) => {+ const { t } = useTranslation();+ const { icon } = getLayoutPresetPresentation(preset);+ const handleEdit = useCallback(() => onEdit(preset.id), [onEdit, preset.id]);+ const handleDelete = useCallback(() => onDelete(preset.id), [onDelete, preset.id]);++ return (+ <HStack borderColor="border.subtle" borderWidth="1px" gap="2" px="3" py="2" rounded="md">+ <Icon as={icon} boxSize="4" color="fg.muted" flexShrink={0} />+ <Text flex="1" fontSize="xs" fontWeight="600" minW="0" truncate>+ {preset.label}+ </Text>+ <IconButton+ aria-label={t('topbar.presets.editNamed', { name: preset.label })}+ size="2xs"+ variant="ghost"+ onClick={handleEdit}+ >+ <Icon as={PencilIcon} boxSize="3.5" />+ </IconButton>+ <IconButton+ aria-label={t('topbar.presets.deleteNamed', { name: preset.label })}+ color="fg.error"+ size="2xs"+ variant="ghost"+ onClick={handleDelete}+ >+ <Icon as={Trash2Icon} boxSize="3.5" />+ </IconButton>+ </HStack>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetMenu.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetMenu.tsxdeleted file mode 100644index 1704211393..0000000000--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetMenu.tsx+++ /dev/null@@ -1,421 +0,0 @@-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 '@platform/ui';-import { layoutPresets } from '@workbench/layoutPresets';-import { areLayoutPresetSnapshotsEqual, createLayoutPresetSnapshot } from '@workbench/layoutPresetSnapshots';-import { loadWidget, 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';--interface PresetActionTarget {- preset: LayoutPreset;- x?: number;- y?: number;-}--const getDefaultCustomPresetName = (presets: LayoutPreset[]): string => `Custom layout ${presets.length + 1}`;--const createCustomPresetId = (): string =>- `custom-layout-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;--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);- }- }-};--/**- * Resolves once every widget the preset will show is loaded.- *- * Applying a preset used to dispatch immediately after kicking off a preload,- * so the widgets it revealed rendered against a pending promise and suspended.- * That is what cost the switch its time — not the download, which is already- * finished by then, but React withholding the resolved tree for 300ms- * (`FALLBACK_THROTTLE_MS`) once a fallback has been shown. Waiting here instead- * keeps the previous layout on screen for the few ms the modules actually need- * and lets the new one commit immediately.- *- * `allSettled`, not `all`: a widget that fails to load must still be placed, so- * its own failure boundary can report it.- */-const loadLayoutPreset = (preset: LayoutPreset): Promise<unknown> =>- Promise.allSettled(- Object.values(preset.snapshot.widgetRegions).flatMap((region) => {- const typeId = preset.snapshot.widgetInstances[region.activeInstanceId]?.typeId;- const pending = typeId ? loadWidget(typeId) : null;-- return pending ? [pending] : [];- })- );--/** Global layout preset registry surfaced as a menu. */-export const LayoutPresetMenu = () => {- const activeLayoutSnapshot = useActiveProjectSelector(createLayoutPresetSnapshot, areLayoutPresetSnapshotsEqual);- 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);- const [actionTarget, setActionTarget] = useState<PresetActionTarget | null>(null);- const allPresets = useMemo(() => [...layoutPresets, ...customPresets], [customPresets]);- const matchingPreset = allPresets.find((preset) =>- areLayoutPresetSnapshotsEqual(activeLayoutSnapshot, preset.snapshot)- );- const canAddCurrentLayout = !matchingPreset;- const triggerLabel = matchingPreset?.label ?? 'Custom';-- const addPreset = useCallback(- (label: string) => {- layout.createPreset(createCustomPresetId(), label);- },- [layout]- );-- const renamePreset = useCallback(- (preset: LayoutPreset, label: string) => {- layout.renamePreset(preset.id, label);- },- [layout]- );-- const deletePreset = useCallback(- (preset: LayoutPreset) => {- layout.deletePreset(preset.id);- },- [layout]- );- const applyPreset = useCallback(- (preset: LayoutPreset) => {- void loadLayoutPreset(preset).then(() => {- layout.applyPreset(preset.id);- });- },- [layout]- );- const openActionMenu = useCallback((preset: LayoutPreset, event: MouseEvent<HTMLElement>) => {- event.preventDefault();- event.stopPropagation();- setActionTarget({ preset, x: event.clientX, y: event.clientY });- }, []);- const handleAddCurrentLayout = useCallback(() => {- if (canAddCurrentLayout) {- setIsAddOpen(true);- }- }, [canAddCurrentLayout]);- const closeActionMenu = useCallback(() => setActionTarget(null), []);- const openDeleteDialog = useCallback((preset: LayoutPreset) => setDeleteTarget(preset), []);- const openRenameDialog = useCallback((preset: LayoutPreset) => setRenameTarget(preset), []);- const closeAddDialog = useCallback(() => setIsAddOpen(false), []);- const closeRenameDialog = useCallback(() => setRenameTarget(null), []);- const submitRename = useCallback(- (label: string) => {- if (renameTarget) {- renamePreset(renameTarget, label);- }- },- [renamePreset, renameTarget]- );- const closeDeleteDialog = useCallback(() => setDeleteTarget(null), []);- const confirmDelete = useCallback(() => {- if (deleteTarget) {- deletePreset(deleteTarget);- }- }, [deletePreset, deleteTarget]);-- return (- <>- <Menu.Root positioning={MENU_POSITIONING}>- <Menu.Trigger asChild>- <Button- aria-label={`Layout preset: ${triggerLabel}`}- bg="bg.subtle"- borderWidth="1px"- borderColor="border.emphasized"- color="fg"- fontSize="xs"- fontWeight="500"- justifyContent="space-between"- size="xs"- variant="outline"- w="9rem"- _hover={TRIGGER_HOVER_PROPS}- >- {triggerLabel}- <Icon as={ChevronDownIcon} boxSize="3" />- </Button>- </Menu.Trigger>- <Portal>- <Menu.Positioner>- <MenuContent maxW="20rem" minW="18rem">- <PresetGroup- label="Built-in presets"- matchingPreset={matchingPreset}- presets={layoutPresets}- onApply={applyPreset}- onPreload={preloadLayoutPreset}- />- {customPresets.length ? (- <>- <Menu.Separator />- <PresetGroup- isCustom- label="Custom presets"- matchingPreset={matchingPreset}- presets={customPresets}- onAction={openActionMenu}- onApply={applyPreset}- onContextMenu={openActionMenu}- onPreload={preloadLayoutPreset}- />- </>- ) : null}- <Menu.Separator />- <Menu.Item- value="add-current-layout"- disabled={!canAddCurrentLayout}- _disabled={DISABLED_PROPS}- onClick={handleAddCurrentLayout}- >- <Icon as={PlusIcon} boxSize="3.5" />- <Menu.ItemText>Add current layout...</Menu.ItemText>- {!canAddCurrentLayout ? (- <Text color="fg.subtle" fontSize="2xs" ms="auto">- Saved- </Text>- ) : null}- </Menu.Item>- </MenuContent>- </Menu.Positioner>- </Portal>- </Menu.Root>- <PresetActionMenu- target={actionTarget}- onClose={closeActionMenu}- onDelete={openDeleteDialog}- onRename={openRenameDialog}- />- <RenameDialog- initialName={getDefaultCustomPresetName(customPresets)}- isOpen={isAddOpen}- label="Preset name"- submitLabel="Add preset"- submitUnchanged- title="Add layout preset"- onClose={closeAddDialog}- onSubmit={addPreset}- />- {renameTarget ? (- <RenameDialog- initialName={renameTarget.label}- isOpen={renameTarget !== null}- label="Preset name"- title="Rename layout preset"- onClose={closeRenameDialog}- onSubmit={submitRename}- />- ) : null}- <ConfirmDialog- body={`Delete "${deleteTarget?.label ?? 'this layout preset'}"? This only removes the saved preset.`}- confirmLabel="Delete preset"- isOpen={deleteTarget !== null}- title="Delete layout preset?"- onClose={closeDeleteDialog}- onConfirm={confirmDelete}- />- </>- );-};--const PresetGroup = ({- isCustom = false,- label,- matchingPreset,- onAction,- onApply,- onContextMenu,- onPreload,- presets,-}: {- isCustom?: boolean;- label: string;- matchingPreset?: LayoutPreset;- 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>- <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">- {label}- </Menu.ItemGroupLabel>- {presets.map((preset) => (- <PresetMenuItem- key={preset.id}- isCustom={isCustom}- isSelected={preset.id === matchingPreset?.id}- preset={preset}- onAction={onAction}- onApply={onApply}- onContextMenu={onContextMenu}- onPreload={onPreload}- />- ))}- </Menu.ItemGroup>-);--const PresetMenuItem = ({- isCustom,- isSelected,- onAction,- onApply,- onContextMenu,- onPreload,- preset,-}: {- isCustom: boolean;- isSelected: boolean;- preset: LayoutPreset;- 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(- (event: MouseEvent<HTMLElement>) => onContextMenu?.(preset, event),- [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}- onFocus={handlePreload}- onPointerEnter={handlePreload}- >- <Stack gap="0" flex="1" minW="0">- <Text fontSize="xs" fontWeight="600">- {preset.label}- </Text>- </Stack>- <HStack flexShrink={0} gap="1">- {isSelected ? <Icon as={CheckIcon} boxSize="3" color="accent.solid" /> : null}- {isCustom ? (- <IconButton- aria-label={`Actions for ${preset.label}`}- color="fg.muted"- size="2xs"- variant="ghost"- onClick={handleAction}- >- <EllipsisVerticalIcon />- </IconButton>- ) : null}- </HStack>- </Menu.Item>- );-};--const PresetActionMenu = ({- onClose,- onDelete,- onRename,- target,-}: {- target: PresetActionTarget | null;- onClose: () => void;- onDelete: (preset: LayoutPreset) => void;- onRename: (preset: LayoutPreset) => void;-}) => {- const positioning = useMemo(- () =>- target?.x !== undefined && target.y !== undefined- ? {- getAnchorRect: () => ({ height: 1, width: 1, x: target.x as number, y: target.y as number }),- placement: 'bottom-start' as const,- }- : MENU_POSITIONING,- [target]- );- const handleOpenChange = useCallback(- (event: { open: boolean }) => {- if (!event.open) {- onClose();- }- },- [onClose]- );-- return (- <Menu.Root- key={target?.preset.id ?? 'closed'}- lazyMount- open={target !== null}- positioning={positioning}- unmountOnExit- onOpenChange={handleOpenChange}- >- <Portal>- <Menu.Positioner>- {target ? (- <MenuContent minW="12rem">- <PresetActionMenuItem action="rename" preset={target.preset} onDelete={onDelete} onRename={onRename} />- <PresetActionMenuItem action="delete" preset={target.preset} onDelete={onDelete} onRename={onRename} />- </MenuContent>- ) : null}- </Menu.Positioner>- </Portal>- </Menu.Root>- );-};--const PresetActionMenuItem = ({- action,- onDelete,- onRename,- preset,-}: {- action: 'delete' | 'rename';- preset: LayoutPreset;- onDelete: (preset: LayoutPreset) => void;- onRename: (preset: LayoutPreset) => void;-}) => {- const handleClick = useCallback(() => {- if (action === 'rename') {- onRename(preset);- } else {- onDelete(preset);- }- }, [action, onDelete, onRename, preset]);-- if (action === 'rename') {- return (- <Menu.Item value="rename-preset" onClick={handleClick}>- <Icon as={PencilIcon} boxSize="3.5" />- <Menu.ItemText>Rename...</Menu.ItemText>- </Menu.Item>- );- }-- return (- <Menu.Item color="fg.error" value="delete-preset" onClick={handleClick}>- <Icon as={Trash2Icon} boxSize="3.5" />- <Menu.ItemText>Delete...</Menu.ItemText>- </Menu.Item>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsxnew file mode 100644index 0000000000..8b10bc4626--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx@@ -0,0 +1,422 @@+import type { LayoutPreset } from '@workbench/layoutContracts';+import type { KeyboardEvent, MouseEvent } from 'react';++import { Box, HStack, Icon, Menu, Portal, Text, VisuallyHidden } from '@chakra-ui/react';+import { IconButton } from '@platform/ui/Button';+import { MenuContent } from '@platform/ui/Menu';+import { Tabs } from '@platform/ui/Tabs';+import { Tooltip } from '@platform/ui/Tooltip';+import {+ createLayoutPresetActivator,+ loadLayoutPresetWidgets,+ preloadLayoutPresetWidgets,+} from '@workbench/layoutPresetActivation';+import { layoutPresets } from '@workbench/layoutPresets';+import { useWorkbenchCommands, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import {+ ArrowRightIcon,+ ChevronDownIcon,+ PencilIcon,+ PlusIcon,+ RotateCcwIcon,+ SaveIcon,+ SettingsIcon,+ Trash2Icon,+} from 'lucide-react';+import { useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { LayoutPresetDialog } from './LayoutPresetDialog';+import { openLayoutPresetDelete, openLayoutPresetEdit, openLayoutPresetManager } from './layoutPresetManagerStore';+import { getLayoutPresetPresentation } from './layoutPresetPresentation';+import { getPresetAccessibleName, getTopbarPresetTabs } from './layoutPresetStripModel';+import { HIDE_BELOW_PRESET_LABEL_WIDTH } from './topbarBreakpoints';+import { useLayoutDrift } from './useLayoutDrift';+import { useTopbarShortcut } from './useTopbarShortcut';++/** Marks the chevron inside a tab, so the tab's own click handler can tell them apart. */+const PRESET_MENU_ATTRIBUTE = 'data-preset-menu';+const PRESET_SCROLL_CSS = { '&::-webkit-scrollbar': { display: 'none' }, scrollbarWidth: 'none' } as const;++const createCustomPresetId = (): string =>+ `custom-layout-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;++/**+ * The centre of the top bar: the layout presets as a tab strip.+ *+ * Tabs rather than a segmented control because the active preset carries its own+ * menu, and a tab is a container we can put that chevron inside — so the menu+ * belongs to the preset visually as well as conceptually, instead of floating+ * beside the group.+ *+ * A preset is an arrangement, never a widget, which is why the strip carries no+ * source or routing marker, and why a customised layout is not a separate entry+ * but the active entry with unsaved changes.+ */+export const LayoutPresetStrip = () => {+ const { t } = useTranslation();+ const { activePreset, hasDrifted } = useLayoutDrift();+ const { layout } = useWorkbenchCommands();+ const [isSaveAsOpen, setIsSaveAsOpen] = useState(false);+ const [menuTarget, setMenuTarget] = useState<{ anchor: DOMRect; preset: LayoutPreset } | null>(null);++ const customPresets = useWorkbenchSelector((snapshot) => snapshot.account.customLayoutPresets ?? []);+ const presets = useMemo(() => getTopbarPresetTabs(customPresets), [customPresets]);+ const activatePreset = useMemo(+ () => createLayoutPresetActivator({ apply: layout.applyPreset, load: loadLayoutPresetWidgets }),+ [layout.applyPreset]+ );++ const applyPreset = useCallback(+ (preset: LayoutPreset) => {+ if (preset.id !== activePreset.id) {+ void activatePreset(preset);+ }+ },+ [activatePreset, activePreset.id]+ );+ const handleValueChange = useCallback(+ (event: { value: string }) => {+ const preset = presets.find((candidate) => candidate.id === event.value);++ if (preset) {+ applyPreset(preset);+ }+ },+ [applyPreset, presets]+ );+ const openSaveAsDialog = useCallback(() => setIsSaveAsOpen(true), []);+ const closeSaveAsDialog = useCallback(() => setIsSaveAsOpen(false), []);+ const saveAsNewPreset = useCallback(+ ({ iconId, name }: { iconId: string; name: string }) => layout.createPreset(createCustomPresetId(), name, iconId),+ [layout]+ );+ const closeMenu = useCallback(() => setMenuTarget(null), []);+ const requestEdit = useCallback((preset: LayoutPreset) => openLayoutPresetEdit(preset.id), []);+ const requestDelete = useCallback((preset: LayoutPreset) => openLayoutPresetDelete(preset.id), []);++ return (+ <>+ <HStack gap="1" justify="center" maxW="min(36vw, 44rem)" minW="0">+ <Box css={PRESET_SCROLL_CSS} data-layout-preset-scroll="" maxW="full" minW="0" overflowX="auto">+ <Tabs.Root+ minW="max-content"+ size="sm"+ value={activePreset.id}+ variant="subtle"+ onValueChange={handleValueChange}+ >+ {/* The name belongs on the tablist, not the root — the root is a plain+ container and carries no role for it to name. */}+ <Tabs.List aria-label={t('topbar.presets.layoutPreset')} gap="0.5">+ {presets.map((preset) => (+ <PresetTab+ key={preset.id}+ hasDrifted={hasDrifted}+ isActive={preset.id === activePreset.id}+ preset={preset}+ onOpenMenu={setMenuTarget}+ />+ ))}+ </Tabs.List>+ {/* The real "panel" is the dock itself, which lives outside this+ component and is shared by every preset. These stand in for it so+ each tab's `aria-controls` resolves to something that describes+ what selecting it did. */}+ {presets.map((preset) => (+ <Tabs.Content key={preset.id} value={preset.id} asChild>+ <VisuallyHidden>{getLayoutPresetPresentation(preset).tooltip}</VisuallyHidden>+ </Tabs.Content>+ ))}+ </Tabs.Root>+ </Box>++ {/* Saving the live arrangement as a new preset is the one preset action+ frequent enough to earn a place in the bar itself. */}+ <Tooltip content={t('topbar.presets.saveAsTooltip')} showArrow>+ <IconButton+ aria-label={t('topbar.presets.saveAsTooltip')}+ size="sm"+ variant="ghost"+ onClick={openSaveAsDialog}+ >+ <Icon as={PlusIcon} boxSize="4" />+ </IconButton>+ </Tooltip>+ </HStack>++ <PresetMenu+ isActive={menuTarget?.preset.id === activePreset.id}+ hasDrifted={hasDrifted}+ target={menuTarget}+ onApply={applyPreset}+ onClose={closeMenu}+ onDelete={requestDelete}+ onEdit={requestEdit}+ />++ <LayoutPresetDialog+ isOpen={isSaveAsOpen}+ name={`${activePreset.label} copy`}+ submitLabel={t('topbar.presets.save')}+ title={t('topbar.presets.saveAs')}+ onClose={closeSaveAsDialog}+ onSubmit={saveAsNewPreset}+ />+ </>+ );+};++const PresetTab = ({+ hasDrifted,+ isActive,+ onOpenMenu,+ preset,+}: {+ hasDrifted: boolean;+ isActive: boolean;+ preset: LayoutPreset;+ onOpenMenu: (target: { anchor: DOMRect; preset: LayoutPreset }) => void;+}) => {+ const { t } = useTranslation();+ const { icon, tooltip } = getLayoutPresetPresentation(preset);+ const handlePreload = useCallback(() => preloadLayoutPresetWidgets(preset), [preset]);+ const showDrift = isActive && hasDrifted;++ // A tab is a `<button>`, so the chevron cannot be one — nesting buttons is+ // invalid and the browser hoists the inner one out of the tab entirely. It is+ // a span the tab's own handler recognises, the same way the project tabs used+ // to carry their close affordance.+ const handleClick = useCallback(+ (event: MouseEvent<HTMLButtonElement>) => {+ const trigger = event.target instanceof Element ? event.target.closest(`[${PRESET_MENU_ATTRIBUTE}]`) : null;++ if (trigger) {+ event.preventDefault();+ event.stopPropagation();+ onOpenMenu({ anchor: trigger.getBoundingClientRect(), preset });+ }+ },+ [onOpenMenu, preset]+ );++ // Right-click opens the same menu, on whichever preset was under the pointer —+ // including inactive ones, so a custom preset can be renamed or deleted+ // without first switching into it.+ const handleContextMenu = useCallback(+ (event: MouseEvent<HTMLButtonElement>) => {+ event.preventDefault();+ onOpenMenu({+ anchor: new DOMRect(event.clientX, event.clientY, 1, 1),+ preset,+ });+ },+ [onOpenMenu, preset]+ );++ // Keyboard parity for the chevron. Left/Right already move between tabs, so+ // Down is free and is the usual "open this control's menu" key.+ const handleKeyDown = useCallback(+ (event: KeyboardEvent<HTMLButtonElement>) => {+ if (!isActive || event.key !== 'ArrowDown') {+ return;+ }++ event.preventDefault();+ onOpenMenu({ anchor: event.currentTarget.getBoundingClientRect(), preset });+ },+ [isActive, onOpenMenu, preset]+ );++ return (+ <Tooltip content={`${preset.label} — ${tooltip}`} showArrow>+ <Tabs.Trigger+ aria-label={getPresetAccessibleName(preset, showDrift, t('topbar.presets.unsaved'))}+ aria-keyshortcuts={isActive ? 'ArrowDown' : undefined}+ gap="1.5"+ value={preset.id}+ onClick={handleClick}+ onContextMenu={handleContextMenu}+ onFocus={handlePreload}+ onKeyDown={handleKeyDown}+ onPointerEnter={handlePreload}+ >+ <Icon as={icon} boxSize="3.5" flexShrink={0} />+ {/* The explicit aria-label above keeps the tab named when this visible+ text is removed from the accessibility tree below 1280px. */}+ <Text as="span" css={HIDE_BELOW_PRESET_LABEL_WIDTH}>+ {preset.label}+ </Text>+ {/* The dot is the whole signal that a layout has diverged, so it has to+ reach screen readers too — as part of the tab's name. */}+ {showDrift ? <DriftDot /> : null}+ {isActive ? (+ <Box+ {...{ [PRESET_MENU_ATTRIBUTE]: '' }}+ alignItems="center"+ aria-hidden="true"+ as="span"+ color="fg.subtle"+ display="inline-flex"+ me="-1"+ p="0.5"+ rounded="sm"+ _hover={MENU_AFFORDANCE_HOVER_PROPS}+ >+ <Icon as={ChevronDownIcon} boxSize="3.5" />+ </Box>+ ) : null}+ </Tabs.Trigger>+ </Tooltip>+ );+};++const MENU_AFFORDANCE_HOVER_PROPS = { bg: 'bg.emphasized', color: 'fg' } as const;++/** Filled accent dot: this preset is loaded, but the live layout has moved on. */+const DriftDot = () => <Box aria-hidden="true" bg="accent.solid" boxSize="1.5" flexShrink={0} rounded="full" />;++const PresetMenu = ({+ hasDrifted,+ isActive,+ onApply,+ onClose,+ onDelete,+ onEdit,+ target,+}: {+ hasDrifted: boolean;+ isActive: boolean;+ target: { anchor: DOMRect; preset: LayoutPreset } | null;+ onApply: (preset: LayoutPreset) => void;+ onClose: () => void;+ onDelete: (preset: LayoutPreset) => void;+ onEdit: (preset: LayoutPreset) => void;+}) => {+ const { t } = useTranslation();+ const { layout } = useWorkbenchCommands();+ const saveShortcut = useTopbarShortcut('app.saveLayoutPreset');+ const preset = target?.preset;+ const isCustom = preset ? !layoutPresets.some((builtIn) => builtIn.id === preset.id) : false;+ const showDrift = isActive && hasDrifted;++ const apply = useCallback(() => {+ if (preset) {+ onApply(preset);+ }+ }, [onApply, preset]);+ const revert = useCallback(() => layout.reset(), [layout]);+ const save = useCallback(() => {+ if (preset) {+ layout.savePreset(preset.id);+ }+ }, [layout, preset]);+ const edit = useCallback(() => {+ if (preset) {+ onEdit(preset);+ }+ }, [onEdit, preset]);+ const remove = useCallback(() => {+ if (preset) {+ onDelete(preset);+ }+ }, [onDelete, preset]);+ const handleOpenChange = useCallback(+ (event: { open: boolean }) => {+ if (!event.open) {+ onClose();+ }+ },+ [onClose]+ );++ // Anchored to a measured rect rather than a trigger element: the chevron lives+ // inside the tab button and cannot be a `Menu.Trigger` of its own without+ // nesting buttons, and a right-click anchors at the pointer.+ const anchor = target?.anchor ?? null;+ const positioning = useMemo(+ () => ({+ getAnchorRect: () => (anchor ? { height: anchor.height, width: anchor.width, x: anchor.x, y: anchor.y } : null),+ placement: 'bottom-end' as const,+ }),+ [anchor]+ );++ return (+ <Menu.Root lazyMount open={target !== null} positioning={positioning} unmountOnExit onOpenChange={handleOpenChange}>+ <Portal>+ <Menu.Positioner>+ {preset ? (+ <MenuContent minW="16rem">+ <HStack justify="space-between" px="3" py="2">+ <Text fontSize="xs" fontWeight="700" truncate>+ {preset.label}+ </Text>+ {showDrift ? (+ <Text color="fg.muted" fontSize="2xs" flexShrink={0}>+ {t('topbar.presets.unsaved')}+ </Text>+ ) : null}+ </HStack>+ <Menu.Separator />++ {/* Right-clicking a preset you are not in should still offer the+ thing left-clicking it does, the way any list does. */}+ {isActive ? null : (+ <Menu.Item value="apply-preset" onClick={apply}>+ <Icon as={ArrowRightIcon} boxSize="3.5" />+ <Menu.ItemText>{t('topbar.presets.switch')}</Menu.ItemText>+ </Menu.Item>+ )}++ {/* Revert and Save act on the *live* layout, so they only make+ sense for the preset you are currently in. */}+ {isActive ? (+ <>+ {showDrift ? (+ <Menu.Item value="revert-layout" onClick={revert}>+ <Icon as={RotateCcwIcon} boxSize="3.5" />+ <Menu.ItemText>{t('topbar.presets.revert')}</Menu.ItemText>+ </Menu.Item>+ ) : null}+ <Menu.Item value="save-layout" onClick={save}>+ <Icon as={SaveIcon} boxSize="3.5" />+ <Menu.ItemText>{t('topbar.presets.saveChanges')}</Menu.ItemText>+ {saveShortcut ? (+ <Text color="fg.subtle" fontSize="2xs" ms="auto">+ {saveShortcut}+ </Text>+ ) : null}+ </Menu.Item>+ </>+ ) : null}++ {/* Renaming, re-iconing, and deleting belong to the preset itself,+ so they work on any custom preset without switching into it. */}+ {isCustom ? (+ <>+ <Menu.Item value="edit-preset" onClick={edit}>+ <Icon as={PencilIcon} boxSize="3.5" />+ <Menu.ItemText>{t('topbar.presets.editWithEllipsis')}</Menu.ItemText>+ </Menu.Item>+ <Menu.Item color="fg.error" value="delete-preset" _hover={DELETE_HOVER_PROPS} onClick={remove}>+ <Icon as={Trash2Icon} boxSize="3.5" />+ <Menu.ItemText>{t('topbar.presets.deleteWithEllipsis')}</Menu.ItemText>+ </Menu.Item>+ </>+ ) : null}++ <Menu.Separator />+ <Menu.Item value="manage-presets" onClick={openLayoutPresetManager}>+ <Icon as={SettingsIcon} boxSize="3.5" />+ <Menu.ItemText>{t('topbar.presets.manage')}</Menu.ItemText>+ </Menu.Item>+ </MenuContent>+ ) : null}+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};++const DELETE_HOVER_PROPS = { bg: 'bg.error', color: 'fg.error' } as const;diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/ModelManagerButton.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/ModelManagerButton.tsxdeleted file mode 100644index 34cf8e909a..0000000000--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/ModelManagerButton.tsx+++ /dev/null@@ -1,22 +0,0 @@-import { IconButton, Tooltip } from '@platform/ui';-import { Link } from '@tanstack/react-router';-import { useActiveProjectId } from '@workbench/WorkbenchContext';-import { BoxIcon } from 'lucide-react';-import { useMemo } from 'react';-import { useTranslation } from 'react-i18next';--export const ModelManagerButton = () => {- const { t } = useTranslation();- const projectId = useActiveProjectId();- const search = useMemo(() => ({ project: projectId }), [projectId]);-- return (- <Tooltip content={t('models.manager')} showArrow>- <IconButton aria-label={t('models.manager')} asChild size="sm" variant="ghost">- <Link search={search} to="/models">- <BoxIcon />- </Link>- </IconButton>- </Tooltip>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/NodeManagerButton.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/NodeManagerButton.tsxdeleted file mode 100644index 2d3ce1dc9a..0000000000--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/NodeManagerButton.tsx+++ /dev/null@@ -1,19 +0,0 @@-import { Icon } from '@chakra-ui/react';-import { IconButton, Tooltip } from '@platform/ui';-import { Link } from '@tanstack/react-router';-import { BlocksIcon } from 'lucide-react';-import { useTranslation } from 'react-i18next';--export const NodesManagerButton = () => {- const { t } = useTranslation();-- return (- <Tooltip content={t('nodes.manager')} showArrow>- <IconButton aria-label={t('nodes.manager')} asChild size="sm" variant="ghost">- <Link to="/nodes">- <Icon as={BlocksIcon} />- </Link>- </IconButton>- </Tooltip>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsxnew file mode 100644index 0000000000..124c63f84e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx@@ -0,0 +1,326 @@+import type { Project } from '@workbench/projectContracts';+import type { ProjectSummary } from '@workbench/projects/library';++import { Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';+import { flushGenerateDrafts } from '@features/generation/react';+import { useModelLoads } from '@features/models';+import { getProjectQueueIndicatorState } from '@features/queue/contracts';+import { useQueueItemProgress } from '@features/queue/react';+import { Button } from '@platform/ui/Button';+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';+import { MenuContent } from '@platform/ui/Menu';+import { RenameDialog } from '@platform/ui/RenameDialog';+import { QueueCircularProgress } from '@workbench/components/QueueProgressIndicator';+import { formatRelativeTime } from '@workbench/launchpad/formatRelativeTime';+import { OpenProjectDialog } from '@workbench/projects/components';+import { refreshProjectLibrary, useProjectLibrarySelector } from '@workbench/projects/library';+import { exportOpenProject } from '@workbench/projects/projectFile';+import { useProjectActions } from '@workbench/projects/useProjectActions';+import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';+import {+ useActiveProjectSelector,+ useWorkbenchCommands,+ useWorkbenchQueries,+ useWorkbenchSelector,+} from '@workbench/WorkbenchContext';+import {+ CheckIcon,+ ChevronsUpDownIcon,+ FileDownIcon,+ FolderCogIcon,+ FolderOpenIcon,+ PencilIcon,+ PlusIcon,+ Trash2Icon,+ XIcon,+} from 'lucide-react';+import { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { getProjectSwitcherSections } from './projectSwitcherModel';+import { projectSwitcherStore, setProjectSwitcherOpen } from './projectSwitcherStore';+import { HIDE_BELOW_PROJECT_NAME_WIDTH } from './topbarBreakpoints';++const MENU_POSITIONING = { placement: 'bottom-start' } as const;+const DELETE_HOVER_PROPS = { bg: 'bg.error', color: 'fg.error' } as const;+const RECENT_PROJECT_LIMIT = 5;++/**+ * The project you are in, and the ones you would plausibly go to next.+ *+ * The old tab strip put a variable-width run of tabs in the middle of the bar,+ * so everything beside it moved whenever a project opened or closed. A single+ * fixed-shape trigger does not, which is what lets the preset strip stay+ * optically centred.+ *+ * Open session projects come first, followed by saved recents that are not+ * already open. This preserves document/session visibility without putting a+ * variable-width tab strip back into the topbar.+ */+export const ProjectSwitcher = () => {+ const { t } = useTranslation();+ const activeProjectId = useActiveProjectSelector((project) => project.id);+ const activeProjectName = useActiveProjectSelector((project) => project.name);+ const librarySummaries = useProjectLibrarySelector((snapshot) => snapshot.summaries);+ const openProjects = useWorkbenchSelector((snapshot) => snapshot.projects);+ const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.backendConnection.status);+ const modelLoads = useModelLoads();+ const queries = useWorkbenchQueries();+ const { projects } = useWorkbenchCommands();+ const { closeProject, deleteProject, openProject } = useProjectActions();+ const openWorkbenchWidget = useOpenWorkbenchWidget();+ const [renameTarget, setRenameTarget] = useState<{ id: string; name: string } | null>(null);+ const [deleteTarget, setDeleteTarget] = useState<{ id: string; name: string } | null>(null);+ const [isOpenDialogVisible, setIsOpenDialogVisible] = useState(false);++ const isMenuOpen = projectSwitcherStore.useSelector((snapshot) => snapshot.isOpen);+ const handleMenuOpenChange = useCallback((event: { open: boolean }) => {+ setProjectSwitcherOpen(event.open);++ if (event.open) {+ // The recents list is only worth a request when someone opens the menu.+ void refreshProjectLibrary();+ }+ }, []);++ const getProject = useCallback((projectId: string): Project | null => queries.getProject(projectId), [queries]);++ const createProject = useCallback(() => {+ flushGenerateDrafts();+ projects.create();+ }, [projects]);+ const showOpenDialog = useCallback(() => setIsOpenDialogVisible(true), []);+ const hideOpenDialog = useCallback(() => setIsOpenDialogVisible(false), []);+ const closeRenameDialog = useCallback(() => setRenameTarget(null), []);+ const closeDeleteDialog = useCallback(() => setDeleteTarget(null), []);+ const renameProject = useCallback(+ (name: string) => {+ if (renameTarget) {+ projects.rename(renameTarget.id, name);+ }+ },+ [projects, renameTarget]+ );+ const confirmDeleteProject = useCallback(async () => {+ const project = deleteTarget ? getProject(deleteTarget.id) : null;++ if (project) {+ await deleteProject(project);+ }+ }, [deleteProject, deleteTarget, getProject]);+ const renameActiveProject = useCallback(+ () => setRenameTarget({ id: activeProjectId, name: activeProjectName }),+ [activeProjectId, activeProjectName]+ );+ const deleteActiveProject = useCallback(+ () => setDeleteTarget({ id: activeProjectId, name: activeProjectName }),+ [activeProjectId, activeProjectName]+ );+ const showActiveProjectDetails = useCallback(() => openWorkbenchWidget('project'), [openWorkbenchWidget]);+ const exportActiveProject = useCallback(() => {+ const project = getProject(activeProjectId);++ if (project) {+ exportOpenProject(project);+ }+ }, [activeProjectId, getProject]);+ const closeActiveProject = useCallback(() => {+ const project = getProject(activeProjectId);++ if (project) {+ closeProject(project);+ }+ }, [activeProjectId, closeProject, getProject]);+ const selectOpenProject = useCallback(+ (event: { value: string }) => {+ const project = getProject(event.value);++ if (project) {+ void openProject(project.id, project.name);+ }+ },+ [getProject, openProject]+ );++ const { open: openProjectSummaries, recent: recentSummaries } = getProjectSwitcherSections(+ openProjects,+ librarySummaries,+ RECENT_PROJECT_LIMIT+ );++ return (+ <>+ <Menu.Root open={isMenuOpen} positioning={MENU_POSITIONING} onOpenChange={handleMenuOpenChange}>+ {/* No tooltip on a menu trigger: wrapping `Menu.Trigger` swallows the+ anchor ref, and the menu then renders in the page corner instead of+ under the control. The label already names it. */}+ <Menu.Trigger asChild>+ <Button+ aria-label={t('topbar.projectSwitcher.trigger', { name: activeProjectName })}+ size="sm"+ variant="ghost"+ >+ {/* Only the name truncates. The selector glyph is what makes this+ legible as a switcher, so it holds its width all the way down+ to the narrowest breakpoint. */}+ <Text css={HIDE_BELOW_PROJECT_NAME_WIDTH} fontWeight="500" minW="0" truncate>+ {activeProjectName}+ </Text>+ <Icon as={ChevronsUpDownIcon} boxSize="3" color="fg.subtle" flexShrink={0} />+ </Button>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent maxW="22rem" minW="18rem">+ <Stack gap="0" px="3" py="2">+ <Text color="fg.subtle" fontSize="2xs" textTransform="uppercase">+ {t('projects.projectDetails')}+ </Text>+ <Text fontSize="xs" fontWeight="700" truncate>+ {activeProjectName}+ </Text>+ </Stack>+ <Menu.Item value="rename-project" onClick={renameActiveProject}>+ <Icon as={PencilIcon} boxSize="3.5" />+ <Menu.ItemText>{t('projects.renameWithEllipsis')}</Menu.ItemText>+ </Menu.Item>+ <Menu.Item value="project-details" onClick={showActiveProjectDetails}>+ <Icon as={FolderCogIcon} boxSize="3.5" />+ <Menu.ItemText>{t('common.details')}</Menu.ItemText>+ </Menu.Item>+ <Menu.Item value="export-project" onClick={exportActiveProject}>+ <Icon as={FileDownIcon} boxSize="3.5" />+ <Menu.ItemText>{t('common.export')}</Menu.ItemText>+ </Menu.Item>+ <Menu.Item value="close-project" onClick={closeActiveProject}>+ <Icon as={XIcon} boxSize="3.5" />+ <Menu.ItemText>{t('common.close')}</Menu.ItemText>+ </Menu.Item>+ <Menu.Item+ color="fg.error"+ value="delete-project"+ _hover={DELETE_HOVER_PROPS}+ onClick={deleteActiveProject}+ >+ <Icon as={Trash2Icon} boxSize="3.5" />+ <Menu.ItemText>{t('projects.deleteProjectWithEllipsis')}</Menu.ItemText>+ </Menu.Item>++ <Menu.Separator />+ <Menu.RadioItemGroup value={activeProjectId} onValueChange={selectOpenProject}>+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">+ {t('projects.openProjects')}+ </Menu.ItemGroupLabel>+ {openProjectSummaries.map((project) => (+ <OpenProjectRow+ key={project.id}+ backendConnectionStatus={backendConnectionStatus}+ loadingModelsCount={modelLoads.length}+ project={project}+ />+ ))}+ </Menu.RadioItemGroup>++ {recentSummaries.length > 0 ? (+ <>+ <Menu.Separator />+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">+ {t('common.recent')}+ </Menu.ItemGroupLabel>+ {recentSummaries.map((summary) => (+ <RecentProjectRow key={summary.id} summary={summary} onOpen={openProject} />+ ))}+ </Menu.ItemGroup>+ </>+ ) : null}++ <Menu.Separator />+ {/* The `+` and folder glyphs that used to sit loose in the top+ right; they belong with the projects they act on. */}+ <Menu.Item value="new-project" onClick={createProject}>+ <Icon as={PlusIcon} boxSize="3.5" />+ <Menu.ItemText>{t('projects.newProject')}</Menu.ItemText>+ </Menu.Item>+ <Menu.Item value="open-project" onClick={showOpenDialog}>+ <Icon as={FolderOpenIcon} boxSize="3.5" />+ <Menu.ItemText>{t('projects.openProject')}</Menu.ItemText>+ </Menu.Item>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>++ {renameTarget ? (+ <RenameDialog initialName={renameTarget.name} isOpen onClose={closeRenameDialog} onSubmit={renameProject} />+ ) : null}+ <ConfirmDialog+ body={t('projects.deleteProjectTabBody', { name: deleteTarget?.name ?? '' })}+ confirmLabel={t('projects.deleteProject')}+ isOpen={deleteTarget !== null}+ title={t('projects.deleteProjectQuestion')}+ onClose={closeDeleteDialog}+ onConfirm={confirmDeleteProject}+ />+ {isOpenDialogVisible ? <OpenProjectDialog isOpen onClose={hideOpenDialog} /> : null}+ </>+ );+};++const OpenProjectRow = ({+ backendConnectionStatus,+ loadingModelsCount,+ project,+}: {+ backendConnectionStatus: string;+ loadingModelsCount: number;+ project: Project;+}) => {+ const baseState = getProjectQueueIndicatorState({+ isConnected: backendConnectionStatus === 'connected',+ loadingModelsCount,+ progress: null,+ queueItems: project.queue.items,+ });+ const progress = useQueueItemProgress(baseState.runningQueueItemId ?? '');+ const { progressState } = getProjectQueueIndicatorState({+ isConnected: backendConnectionStatus === 'connected',+ loadingModelsCount,+ progress,+ queueItems: project.queue.items,+ });+ return (+ <Menu.RadioItem value={project.id}>+ <Menu.ItemIndicator color="accent.fg">+ <Icon as={CheckIcon} boxSize="3.5" />+ </Menu.ItemIndicator>+ <Menu.ItemText flex="1" minW="0" truncate>+ {project.name}+ </Menu.ItemText>+ <QueueCircularProgress state={progressState} />+ </Menu.RadioItem>+ );+};++/** One recent project. Loaded or not, selecting it lands you in it. */+const RecentProjectRow = ({+ onOpen,+ summary,+}: {+ summary: ProjectSummary;+ onOpen: (projectId: string, name: string) => Promise<void>;+}) => {+ const { t } = useTranslation();+ const handleSelect = useCallback(() => void onOpen(summary.id, summary.name), [onOpen, summary]);++ return (+ <Menu.Item value={summary.id} onClick={handleSelect}>+ <Menu.ItemText flex="1" minW="0" truncate>+ {summary.name}+ </Menu.ItemText>+ <Text color="fg.subtle" flexShrink={0} fontSize="2xs">+ {t('projects.editedRelative', { time: formatRelativeTime(summary.updatedAt) })}+ </Text>+ </Menu.Item>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsxdeleted file mode 100644index 9e985dc4a0..0000000000--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsx+++ /dev/null@@ -1,52 +0,0 @@-import { Group, Menu, Portal } from '@chakra-ui/react';-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. */-export const QueueActions = () => {- const actions = useQueueMenuActions();- const cancelCurrent = actions[0];-- return (- <Menu.Root>- <Group attached>- <Tooltip content="Cancel current item" showArrow>- <IconButton- aria-label="Cancel current queue item"- disabled={cancelCurrent?.disabled}- variant="outline"- size="sm"- roundedEnd="none"- borderColor="border.subtle"- onClick={cancelCurrent?.onClick}- >- <XIcon />- </IconButton>- </Tooltip>- <Menu.Trigger asChild>- <IconButton- aria-label="Queue actions"- variant="outline"- size="sm"- roundedStart="none"- borderStartWidth="0"- aspectRatio="unset"- minW="0"- w="6"- borderColor="border.subtle"- >- <ChevronDownIcon />- </IconButton>- </Menu.Trigger>- </Group>- <Portal>- <Menu.Positioner>- <Menu.Content>- <QueueMenuItems actions={actions} />- </Menu.Content>- </Menu.Positioner>- </Portal>- </Menu.Root>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.tsxnew file mode 100644index 0000000000..55fec9a625--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.tsx@@ -0,0 +1,358 @@+import type { ModelLoadInfo } from '@features/models';+import type { QueueItem } from '@features/queue/contracts';+import type { QueueItemProgress } from '@features/queue/react';+import type { ReactNode } from 'react';++import { Badge, Box, chakra, HStack, Icon, Menu, Portal, Progress, Stack, Text } from '@chakra-ui/react';+import { useModelLoads } from '@features/models';+import {+ getQueueItemExpectedImageCount,+ getQueueItemSnapshotPositivePrompt,+ getQueueSummary,+} from '@features/queue/contracts';+import { QueueMenuItems, useQueueMenuActions } from '@features/queue/menu';+import { useIsProcessorPaused, useQueueItemProgress } from '@features/queue/react';+import { Button, IconButton } from '@platform/ui/Button';+import { Group } from '@platform/ui/Group';+import { MenuContent } from '@platform/ui/Menu';+import { Tooltip } from '@platform/ui/Tooltip';+import { getDestinationLabel, getSourceLabel } from '@workbench/invocation';+import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';+import { useActiveProjectSelector, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { ChevronDownIcon, ListOrderedIcon, PauseIcon, XIcon } from 'lucide-react';+import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++const TOOLTIP_CONTENT_PROPS = { maxW: '22rem', p: '0' };++type QueueTone = 'idle' | 'running' | 'paused';++const tonePalettes: Record<QueueTone, string | undefined> = {+ idle: undefined,+ paused: 'orange',+ running: 'accent',+};++/**+ * Everything about work already dispatched: the counter, a cancel control that+ * only exists when there is something to cancel, and the processor menu.+ *+ * This is where generation progress lives — deliberately not on the Invoke+ * button, which stays static so that queueing onto a running batch never looks+ * unavailable.+ */+export const QueueCluster = () => {+ const { t } = useTranslation();+ const queueItems = useActiveProjectSelector((project) => project.queue.items);+ const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.backendConnection.status);+ const modelLoads = useModelLoads();+ const openWorkbenchWidget = useOpenWorkbenchWidget();+ const actions = useQueueMenuActions();+ const cancelCurrent = actions[0];++ const baseSummary = getQueueSummary(queueItems);+ const runningProgress = useQueueItemProgress(baseSummary.runningQueueItemId ?? '');+ const summary = getQueueSummary(queueItems, runningProgress);+ const { current, remaining, total } = summary;+ const runningItem = summary.runningQueueItemId+ ? queueItems.find((item) => item.id === summary.runningQueueItemId)+ : undefined;++ const isConnected = backendConnectionStatus === 'connected';+ const isPaused = useIsProcessorPaused();+ const hasOpenWork = total > 0;+ const tone: QueueTone = isPaused && hasOpenWork ? 'paused' : hasOpenWork && isConnected ? 'running' : 'idle';+ const progressValue = runningProgress?.percentage ?? null;+ const isCancellable = !cancelCurrent?.disabled;++ const handleOpenQueue = useCallback(() => openWorkbenchWidget('queue'), [openWorkbenchWidget]);++ return (+ <Menu.Root>+ {/* The cancel button is simply absent when idle. Reserving its width left+ a hole in the middle of the group that read as a broken control. */}+ <Group attached colorPalette={tonePalettes[tone]} flexShrink={0}>+ <QueueButtonTooltip+ current={current}+ item={runningItem}+ modelLoads={modelLoads}+ progress={runningProgress}+ total={total}+ >+ <Button+ aria-label={t('topbar.queue.remaining', { count: remaining })}+ fontVariantNumeric="tabular-nums"+ overflow="hidden"+ position="relative"+ size="sm"+ variant={tone === 'idle' ? 'outline' : 'subtle'}+ onClick={handleOpenQueue}+ >+ {/* Progress fills behind the label rather than replacing it: the+ counter is the thing people read, and it must stay readable. */}+ {tone === 'running' && progressValue !== null ? (+ <Box+ aria-hidden="true"+ bg="colorPalette.solid"+ bottom="0"+ left="0"+ opacity="0.35"+ position="absolute"+ top="0"+ transition="width var(--wb-motion-duration-fast) linear"+ width={`${Math.round(progressValue * 100)}%`}+ />+ ) : null}+ <Icon as={isPaused ? PauseIcon : ListOrderedIcon} position="relative" zIndex="1" />+ {/* Tabular figures and a reserved minimum: the counter is watched+ continuously, and digits that change width would nudge the+ controls beside it on every step of a run. */}+ <chakra.span fontVariantNumeric="tabular-nums" position="relative" textAlign="center" zIndex="1">+ {remaining}+ </chakra.span>+ </Button>+ </QueueButtonTooltip>++ {isCancellable && cancelCurrent ? (+ <Tooltip content={cancelCurrent.label} showArrow>+ <IconButton+ aria-label={cancelCurrent.label}+ color="fg.error"+ size="sm"+ variant="outline"+ onClick={cancelCurrent.onClick}+ >+ <Icon as={XIcon} />+ </IconButton>+ </Tooltip>+ ) : null}++ <Menu.Trigger asChild>+ <IconButton+ aria-label={t('topbar.queue.actions')}+ color="fg.subtle"+ size="sm"+ minW="0"+ w="6"+ variant="outline"+ >+ <Icon as={ChevronDownIcon} />+ </IconButton>+ </Menu.Trigger>+ </Group>++ <QueueProgressAnnouncement current={current} progress={progressValue} total={total} />++ <Portal>+ <Menu.Positioner>+ <MenuContent>+ <QueueMenuItems actions={actions} />+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};++const QueueButtonTooltip = ({+ children,+ current,+ item,+ modelLoads,+ progress,+ total,+}: {+ children: ReactNode;+ current: number;+ item?: QueueItem;+ modelLoads: ModelLoadInfo[];+ progress: QueueItemProgress | null;+ total: number;+}) => {+ const content = useMemo(+ () => <QueueTooltip current={current} item={item} modelLoads={modelLoads} progress={progress} total={total} />,+ [current, item, modelLoads, progress, total]+ );++ return (+ <Tooltip content={content} contentProps={TOOLTIP_CONTENT_PROPS} openDelay={200} showArrow>+ {children}+ </Tooltip>+ );+};++/**+ * Progress for screen readers, quantised to ten percent.+ *+ * A 30-step run emits progress continuously; announcing every event would make+ * the whole page unusable while generating, so the live region only changes+ * when the rounded decile does.+ */+const QueueProgressAnnouncement = ({+ current,+ progress,+ total,+}: {+ current: number;+ progress: number | null;+ total: number;+}) => {+ const { t } = useTranslation();+ const decile = progress === null ? null : Math.round(progress * 10) * 10;+ const message =+ total === 0+ ? t('topbar.queue.idle')+ : decile === null+ ? t('topbar.queue.imageProgress', { current, total })+ : t('topbar.queue.imageProgressPercent', { current, percent: decile, total });++ return (+ <chakra.span aria-live="polite" srOnly>+ {message}+ </chakra.span>+ );+};++const QueueTooltip = ({+ current,+ item,+ modelLoads,+ progress,+ total,+}: {+ current: number;+ item?: QueueItem;+ modelLoads: ModelLoadInfo[];+ progress: QueueItemProgress | null;+ total: number;+}) => {+ const { t } = useTranslation();+ if (modelLoads.length > 0 && total === 0) {+ return <ModelLoadsTooltipContent modelLoads={modelLoads} />;+ }++ if (total === 0) {+ return (+ <Stack gap="1" p="3">+ <Text fontSize="xs" fontWeight="800" fontVariantNumeric="tabular-nums">+ {t('topbar.queue.idle')}+ </Text>+ <Text color="fg.subtle" fontSize="2xs">+ {t('topbar.queue.noActiveBatches')}+ </Text>+ </Stack>+ );+ }++ if (!item) {+ return (+ <Stack gap="2" p="3">+ <Text fontSize="xs" fontWeight="800" fontVariantNumeric="tabular-nums">+ {modelLoads.length ? t('topbar.queue.loadingModels') : t('topbar.queue.waitingToStart')}+ </Text>+ <Text color="fg.subtle" fontSize="2xs">+ {t('topbar.queue.queuedImages', { count: total })}+ </Text>+ {modelLoads.length ? <ModelLoadList modelLoads={modelLoads} /> : null}+ </Stack>+ );+ }++ const prompt = getQueueItemSnapshotPositivePrompt(item).trim();+ const expectedCount = getQueueItemExpectedImageCount(item);+ const activeItemIndex = Math.min(+ expectedCount,+ Math.max(1, progress?.activeItemIndex ?? (progress?.completedItemCount ?? 0) + 1)+ );+ const activeBackendItemId = item.backendItemIds?.[activeItemIndex - 1];+ const progressLabel = modelLoads.length+ ? t('topbar.queue.loadingModelsCount', { count: modelLoads.length })+ : progress?.message?.trim() || t('topbar.queue.waitingForProgress');++ return (+ <Stack gap="2" p="3" minW="18rem">+ <HStack justify="space-between" gap="3">+ <Text fontSize="xs" fontWeight="800">+ {t('topbar.queue.loadingImage', { current, total })}+ </Text>+ <Badge colorPalette="blue" fontSize="2xs">+ {item.status}+ </Badge>+ </HStack>+ <Stack gap="1">+ <Text color="fg.subtle" fontSize="2xs">+ {progressLabel}+ </Text>+ {modelLoads.length ? <ModelLoadList modelLoads={modelLoads} /> : null}+ {progress?.percentage !== null && progress?.percentage !== undefined ? (+ <Progress.Root+ aria-label={t('topbar.queue.currentImageProgress')}+ max={1}+ size="xs"+ value={progress.percentage}+ >+ <Progress.Track>+ <Progress.Range />+ </Progress.Track>+ </Progress.Root>+ ) : null}+ </Stack>+ <Stack gap="1" color="fg.subtle" fontSize="2xs">+ <Text fontVariantNumeric="tabular-nums">+ {t('topbar.queue.batchImage', { current: activeItemIndex, total: expectedCount })}+ {activeBackendItemId !== undefined ? ` · ${t('topbar.queue.backendItem', { id: activeBackendItemId })}` : ''}+ </Text>+ <Text fontFamily="mono" truncate>+ {t('topbar.queue.queueItem', { id: item.id })}+ </Text>+ {item.backendBatchId ? (+ <Text fontFamily="mono" truncate>+ {t('topbar.queue.backendBatch', { id: item.backendBatchId })}+ </Text>+ ) : null}+ {/* Queue items snapshot their route at enqueue time (contract §9.2), so+ this reads the item's own snapshot, never the live route. */}+ <Text truncate>+ {t('topbar.queue.route', {+ destination: getDestinationLabel(item.snapshot.destination),+ graph: item.snapshot.graph.label || item.snapshot.graph.id,+ source: getSourceLabel(item.snapshot.sourceId),+ })}+ </Text>+ </Stack>+ {prompt ? (+ <Text color="fg.muted" fontSize="2xs" lineClamp={2}>+ {prompt}+ </Text>+ ) : null}+ </Stack>+ );+};++const ModelLoadsTooltipContent = ({ modelLoads }: { modelLoads: ModelLoadInfo[] }) => {+ const { t } = useTranslation();++ return (+ <Stack gap="2" p="3" minW="18rem">+ <Text fontSize="xs" fontWeight="800">+ {t('topbar.queue.loadingModelsCount', { count: modelLoads.length })}+ </Text>+ <ModelLoadList modelLoads={modelLoads} />+ </Stack>+ );+};++const ModelLoadList = ({ modelLoads }: { modelLoads: ModelLoadInfo[] }) => {+ const { t } = useTranslation();++ return (+ <Stack gap="0.5" color="fg.muted" fontSize="2xs">+ {modelLoads.slice(0, 3).map((modelLoad, index) => (+ <Text key={`${modelLoad.label}:${index}`} truncate>+ {modelLoad.label}+ </Text>+ ))}+ {modelLoads.length > 3 ? <Text>{t('topbar.queue.more', { count: modelLoads.length - 3 })}</Text> : null}+ </Stack>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsxdeleted file mode 100644index 5a430ed9fd..0000000000--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsx+++ /dev/null@@ -1,224 +0,0 @@-import { Badge, HStack, Icon, Progress, Stack, Text } from '@chakra-ui/react';-import { useModelLoads, type ModelLoadInfo } from '@features/models';-import {- getQueueItemExpectedImageCount,- getQueueItemSnapshotPositivePrompt,- getQueueProgressBarState,- getQueueSummary,- type QueueItem,-} 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 { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';-import { useActiveProjectSelector, useWorkbenchSelector } from '@workbench/WorkbenchContext';-import { ListOrderedIcon } from 'lucide-react';-import { useCallback, useMemo } from 'react';--const TOOLTIP_CONTENT_PROPS = { maxW: '22rem', p: '0' };--export const QueueInfo = () => {- const queueItems = useActiveProjectSelector((project) => project.queue.items);- 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;-- const progressState = getQueueProgressBarState({- isConnected: backendConnectionStatus === 'connected',- isRunning: Boolean(runningItem),- loadingModelsCount: modelLoads.length,- progress: runningProgress,- });-- const tooltipContent = useMemo(- () => (- <QueueInfoTooltip- item={runningItem}- modelLoads={modelLoads}- progress={runningProgress}- total={total}- current={current}- />- ),- [current, modelLoads, runningItem, runningProgress, total]- );-- const handleOpenQueue = useCallback(() => openWorkbenchWidget('queue'), [openWorkbenchWidget]);-- return (- <Tooltip content={tooltipContent} contentProps={TOOLTIP_CONTENT_PROPS} openDelay={200} showArrow>- <Button- aria-label={`Queue progress ${summary.current} of ${summary.total}`}- variant="outline"- h="9"- borderColor="border.subtle"- fontSize="xs"- fontWeight="700"- gap="1"- overflow="hidden"- position="relative"- px="2"- onClick={handleOpenQueue}- >- <Icon as={ListOrderedIcon} boxSize="4" flexShrink="0" />- {summary.current}/{summary.total}- <QueueBadgeProgressBar state={progressState} />- </Button>- </Tooltip>- );-};--const QueueBadgeProgressBar = ({ state }: { state: ReturnType<typeof getQueueProgressBarState> }) => {- const isIdle = state.kind === 'idle';-- return (- <Progress.Root- aria-label={isIdle ? 'Invoke progress idle' : 'Invoke progress'}- bottom="0"- colorPalette="accent"- h={1}- insetInline={0}- max={1}- pointerEvents="none"- position="absolute"- value={state.value}- visibility={state.kind !== 'idle' ? 'visible' : 'hidden'}- >- <Progress.Track bg={isIdle ? 'border.subtle' : 'bg.emphasized'} h="full">- <Progress.Range bg="accent.solid" />- </Progress.Track>- </Progress.Root>- );-};--const QueueInfoTooltip = ({- current,- item,- modelLoads,- progress,- total,-}: {- current: number;- item?: QueueItem;- modelLoads: ModelLoadInfo[];- progress: QueueItemProgress | null;- total: number;-}) => {- if (modelLoads.length > 0 && total === 0) {- return <ModelLoadsTooltipContent modelLoads={modelLoads} />;- }-- if (total === 0) {- return (- <Stack gap="1" p="3">- <Text fontSize="xs" fontWeight="800">- Queue idle- </Text>- <Text color="fg.subtle" fontSize="2xs">- No active or pending generation batches.- </Text>- </Stack>- );- }-- if (!item) {- return (- <Stack gap="2" p="3">- <Text fontSize="xs" fontWeight="800">- {modelLoads.length ? 'Loading models' : 'Waiting to start'}- </Text>- <Text color="fg.subtle" fontSize="2xs">- {total} image{total === 1 ? '' : 's'} queued.- </Text>- {modelLoads.length ? <ModelLoadList modelLoads={modelLoads} /> : null}- </Stack>- );- }-- const prompt = getQueueItemSnapshotPositivePrompt(item).trim();- const expectedCount = getQueueItemExpectedImageCount(item);- const activeItemIndex = Math.min(- expectedCount,- Math.max(1, progress?.activeItemIndex ?? (progress?.completedItemCount ?? 0) + 1)- );- const activeBackendItemId = item.backendItemIds?.[activeItemIndex - 1];- const progressLabel = modelLoads.length- ? `Loading ${modelLoads.length} model${modelLoads.length === 1 ? '' : 's'}.`- : progress?.message?.trim() || 'Backend accepted batch; waiting for progress event.';-- return (- <Stack gap="2" p="3" minW="18rem">- <HStack justify="space-between" gap="3">- <Text fontSize="xs" fontWeight="800">- Loading image {current}/{total}- </Text>- <Badge colorPalette="blue" fontSize="2xs">- {item.status}- </Badge>- </HStack>- <Stack gap="1">- <Text color="fg.subtle" fontSize="2xs">- {progressLabel}- </Text>- {modelLoads.length ? <ModelLoadList modelLoads={modelLoads} /> : null}- {progress?.percentage !== null && progress?.percentage !== undefined ? (- <Progress.Root aria-label="Current image progress" max={1} size="xs" value={progress.percentage}>- <Progress.Track>- <Progress.Range />- </Progress.Track>- </Progress.Root>- ) : null}- </Stack>- <Stack gap="1" color="fg.subtle" fontSize="2xs">- <Text>- Batch image {activeItemIndex}/{expectedCount}- {activeBackendItemId !== undefined ? ` · backend item ${activeBackendItemId}` : ''}- </Text>- <Text fontFamily="mono" truncate>- Queue item {item.id}- </Text>- {item.backendBatchId ? (- <Text fontFamily="mono" truncate>- Backend batch {item.backendBatchId}- </Text>- ) : null}- <Text truncate>- {getSourceLabel(item.snapshot.sourceId)} to {getDestinationLabel(item.snapshot.destination)} ·{' '}- {item.snapshot.graph.label || item.snapshot.graph.id}- </Text>- </Stack>- {prompt ? (- <Text color="fg.muted" fontSize="2xs" lineClamp={2}>- {prompt}- </Text>- ) : null}- </Stack>- );-};--const ModelLoadsTooltipContent = ({ modelLoads }: { modelLoads: ModelLoadInfo[] }) => (- <Stack gap="2" p="3" minW="18rem">- <Text fontSize="xs" fontWeight="800">- Loading {modelLoads.length} model{modelLoads.length === 1 ? '' : 's'}- </Text>- <ModelLoadList modelLoads={modelLoads} />- </Stack>-);--const ModelLoadList = ({ modelLoads }: { modelLoads: ModelLoadInfo[] }) => (- <Stack gap="0.5" color="fg.muted" fontSize="2xs">- {modelLoads.slice(0, 3).map((modelLoad, index) => (- <Text key={`${modelLoad.label}:${index}`} truncate>- {modelLoad.label}- </Text>- ))}- {modelLoads.length > 3 ? <Text>{modelLoads.length - 3} more...</Text> : null}- </Stack>-);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/RoutingControl.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/RoutingControl.tsxnew file mode 100644index 0000000000..042ceaa287--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/RoutingControl.tsx@@ -0,0 +1,182 @@+import type { GraphWidgetSource } from '@workbench/graphWidgets';+import type { InvocationSourceId, ResultDestination } from '@workbench/invocationContracts';++import { Box, Icon, Menu, Portal, SegmentGroup, Stack, Text } from '@chakra-ui/react';+import { Button } from '@platform/ui/Button';+import { MenuContent } from '@platform/ui/Menu';+import { Tooltip } from '@platform/ui/Tooltip';+import { describeRoute, getWidgetTypeIdForSourceId } from '@workbench/graphWidgets';+import { WidgetIcon } from '@workbench/iconResolver';+import { getDestinationLabel, resultDestinations } from '@workbench/invocation';+import { getWidgetById } from '@workbench/widgetRegistry';+import { useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { ArrowRightIcon, Link2Icon, LockKeyholeIcon, UnlockKeyholeIcon } from 'lucide-react';+import { useCallback, useId, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import type { InvocationState } from './useInvocationState';++import { getRoutingRelationship } from './routingPresentation';++const MENU_POSITIONING = { placement: 'bottom-end' } as const;++const destinationWidgetTypeIds: Record<ResultDestination, 'canvas' | 'gallery'> = {+ canvas: 'canvas',+ gallery: 'gallery',+};++/**+ * Where the next Invoke reads from and writes to — always visible, never+ * collapsed, at any width.+ *+ * It is the only thing standing between a user pressing ⌘↵ and generating from+ * a widget they were not thinking about (contract §9.5), so it cannot be the+ * control that gives way when the bar gets tight. In the common auto case it is+ * two muted glyphs on the plain button surface: a permanently accented pill on+ * a bar people stare at for hours becomes noise, and noise is not information.+ *+ * The whole control is one target that opens the menu. Splitting it so that the+ * source glyph focused its widget made a small, ambiguous hit area out of what+ * should read as a single indicator.+ */+export const RoutingControl = ({ state }: { state: InvocationState }) => {+ const { t } = useTranslation();+ const { generation } = useWorkbenchCommands();+ const triggerId = useId();+ const triggerIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);+ const { invocation, placedTypeIds, sources } = state;+ const isLocked = invocation.sourceLocked || invocation.destinationLocked;+ const relationship = getRoutingRelationship(invocation);+ const hasSource = placedTypeIds.has(getWidgetTypeIdForSourceId(invocation.sourceId));+ const sourceTypeId = getWidgetTypeIdForSourceId(invocation.sourceId);+ const destinationTypeId = destinationWidgetTypeIds[invocation.destination];+ const accessibleName = describeRoute({+ destination: invocation.destination,+ destinationLocked: invocation.destinationLocked,+ hasSource,+ sourceId: invocation.sourceId,+ sourceLocked: invocation.sourceLocked,+ });+ const glyphColor = isLocked ? 'accent.fg' : 'fg.muted';+ const lockActionLabel = t(isLocked ? 'topbar.routing.unlockRouting' : 'topbar.routing.lockRouting');++ return (+ <Menu.Root ids={triggerIds} positioning={MENU_POSITIONING}>+ <Tooltip content={t('topbar.routing.change')} ids={triggerIds}>+ <Menu.Trigger asChild>+ <Button+ aria-label={accessibleName}+ colorPalette={isLocked ? 'accent' : undefined}+ flexShrink={0}+ px="2"+ size="sm"+ gap="1.5"+ variant={isLocked ? 'subtle' : 'outline'}+ >+ {hasSource ? (+ <WidgetIcon boxSize="3.5" color={glyphColor} icon={getWidgetById(sourceTypeId)?.manifest.icon} />+ ) : (+ // Empty source slot rather than a hidden control: the shape of the+ // indicator must not change when nothing is open.+ <Box borderColor="border.emphasized" borderStyle="dashed" borderWidth="1px" boxSize="3.5" rounded="xs" />+ )}+ <Icon+ as={relationship === 'link' ? Link2Icon : ArrowRightIcon}+ boxSize="3"+ color={isLocked ? 'accent.fg' : 'fg.subtle'}+ />+ <WidgetIcon boxSize="3.5" color={glyphColor} icon={getWidgetById(destinationTypeId)?.manifest.icon} />+ </Button>+ </Menu.Trigger>+ </Tooltip>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="17rem">+ <RoutingSectionHeader label={t('topbar.routing.source')} />+ <SourceRadioGroup sourceId={invocation.sourceId} sources={sources} />+ <Menu.Separator />+ <RoutingSectionHeader label={t('topbar.routing.destination')} />+ <Stack px="3" pb="2">+ <DestinationSegments destination={invocation.destination} />+ </Stack>+ <Menu.Separator />+ <Menu.Item value={isLocked ? 'unlock-routing' : 'lock-routing'} onClick={generation.toggleRoutingLock}>+ <Icon as={isLocked ? UnlockKeyholeIcon : LockKeyholeIcon} boxSize="3.5" color="fg.subtle" />+ <Menu.ItemText>{lockActionLabel}</Menu.ItemText>+ </Menu.Item>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};++const RoutingSectionHeader = ({ label }: { label: string }) => (+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" px="3" pt="2" pb="1" textTransform="uppercase">+ {label}+ </Text>+);++const SourceRadioGroup = ({+ sourceId,+ sources,+}: {+ sourceId: InvocationSourceId;+ sources: readonly GraphWidgetSource[];+}) => {+ const { generation } = useWorkbenchCommands();+ const handleChange = useCallback(+ (event: { value: string }) => generation.setSource(event.value as InvocationSourceId),+ [generation]+ );++ return (+ <Menu.RadioItemGroup value={sourceId} onValueChange={handleChange}>+ {sources.map((source) => (+ <SourceRow key={source.sourceId} source={source} />+ ))}+ </Menu.RadioItemGroup>+ );+};++/** One graph source. Choosing it changes routing without changing the layout. */+const SourceRow = ({ source }: { source: GraphWidgetSource }) => (+ <Menu.RadioItem value={source.sourceId}>+ <Menu.ItemIndicator />+ <WidgetIcon boxSize="3.5" icon={getWidgetById(source.typeId)?.manifest.icon} />+ <Menu.ItemText flex="1">{source.label}</Menu.ItemText>+ </Menu.RadioItem>+);++const DestinationSegments = ({ destination }: { destination: ResultDestination }) => {+ const { generation } = useWorkbenchCommands();+ const { t } = useTranslation();+ const handleChange = useCallback(+ (event: { value: string | null }) => {+ if (event.value) {+ generation.setDestination(event.value as ResultDestination);+ }+ },+ [generation]+ );++ return (+ <SegmentGroup.Root+ aria-label={t('topbar.routing.destination')}+ size="xs"+ value={destination}+ onValueChange={handleChange}+ >+ <SegmentGroup.Indicator />+ {resultDestinations.map((option) => (+ <SegmentGroup.Item key={option.id} flex="1" justifyContent="center" value={option.id}>+ <SegmentGroup.ItemHiddenInput />+ <SegmentGroup.ItemText display="flex" alignItems="center" gap="1.5">+ <WidgetIcon boxSize="3.5" icon={getWidgetById(destinationWidgetTypeIds[option.id])?.manifest.icon} />+ {getDestinationLabel(option.id)}+ </SegmentGroup.ItemText>+ </SegmentGroup.Item>+ ))}+ </SegmentGroup.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsxindex 928a0154e5..fac5013be2 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx@@ -1,66 +1,59 @@-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 { PaletteButton } from '@workbench/palette/PaletteButton';-import { ProjectTabs } from '@workbench/projects/components';-import { SettingsButton } from '@workbench/settings/SettingsButton';-import { useTranslation } from 'react-i18next';+import { Grid, HStack, Separator } from '@chakra-ui/react';+import { SettingsDialogHost } from '@workbench/settings/SettingsDialogHost';-import { BatchCountField } from './BatchCountField';-import { InvokeControl } from './InvokeControl';-import { LayoutPresetMenu } from './LayoutPresetMenu';-import { ModelManagerButton } from './ModelManagerButton';-import { NodesManagerButton } from './NodeManagerButton';-import { QueueActions } from './QueueActions';-import { QueueInfo } from './QueueInfo';+import { AppMenu } from './AppMenu';+import { InvocationCluster } from './InvocationCluster';+import { LayoutPresetAdminDialogs } from './LayoutPresetAdminDialogs';+import { LayoutPresetManagerDialog } from './LayoutPresetManagerDialog';+import { LayoutPresetStrip } from './LayoutPresetStrip';+import { ProjectSwitcher } from './ProjectSwitcher';-const HOME_LINK_STYLE = {- alignItems: 'center',- aspectRatio: '1/1',- display: 'flex',- flexShrink: 0,- height: '100%',- justifyContent: 'center',-};+/**+ * The workbench top bar.+ *+ * Three columns, not a flex row: the `1fr` sides let the preset strip stay+ * geometrically centred no matter how long the project name is. A flex layout moves+ * the strip horizontally every time the user switches projects, which is highly+ * visible on a bar that is always on screen. `minmax(0, 1fr)` rather than `1fr`+ * so the left column can actually shrink and truncate instead of pushing the+ * grid wider than its container.+ *+ * The zones degrade from the left: labels, then the project name, before+ * anything in the invocation cluster gives way. The routing indicator and the+ * queue readout never collapse at any width (§10).+ */+const TOPBAR_COLUMNS = 'minmax(0, 1fr) auto minmax(0, 1fr)';-/** Workbench top bar: brand, global Invoke command cluster, project tabs, layout + account controls. */-export const TopBar = () => {- const { canManageModels, canManageNodes } = useCapabilities();- const { t } = useTranslation();-- return (- <Flex- align="center"+export const TopBar = () => (+ <>+ <Grid+ alignItems="center"as="header"bg="bg.subtle"borderBottomWidth="1px"borderColor="border.subtle"flexShrink={0}gap="2"- h="12"- ps="0.5"- pe="1.5"+ gridTemplateColumns={TOPBAR_COLUMNS}+ h="46px"+ px="1.5"w="full">- <Link aria-label={t('commandPalette.launchpad.goToProjects')} to="/" style={HOME_LINK_STYLE}>- <InvokeMark size={20} />- </Link>- <Separator orientation="vertical" h={5} ms="-2" />- <InvokeControl />- <BatchCountField />- <QueueInfo />- <QueueActions />- <Separator orientation="vertical" h={5} />- <ProjectTabs />- <LayoutPresetMenu />- <HStack gap="0.5">- {canManageNodes ? <NodesManagerButton /> : null}- {canManageModels ? <ModelManagerButton /> : null}- <PaletteButton />- <SettingsButton />+ <HStack gap="1" minW="0">+ <AppMenu />+ <Separator borderColor="border.subtle" h="5" orientation="vertical" />+ <ProjectSwitcher /></HStack>- <AccountMenu />- </Flex>- );-};++ <LayoutPresetStrip />++ <InvocationCluster />+ </Grid>+ {/* Dialog hosts, not controls: every surface that can open one writes to a+ store, so the body cannot belong to whichever trigger happens to be+ mounted. */}+ <LayoutPresetManagerDialog />+ <LayoutPresetAdminDialogs />+ <SettingsDialogHost />+ </>+);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetDialogModel.test.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetDialogModel.test.tsnew file mode 100644index 0000000000..f6133bd210--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetDialogModel.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';++import { getNextIconId } from './layoutPresetDialogModel';++describe('layout preset icon keyboard navigation', () => {+ const iconIds = ['grid', 'text', 'image'];++ it.each([+ ['grid', 'ArrowRight', 'text'],+ ['text', 'ArrowDown', 'image'],+ ['image', 'ArrowRight', 'grid'],+ ['grid', 'ArrowLeft', 'image'],+ ['text', 'Home', 'grid'],+ ['text', 'End', 'image'],+ ])('moves from %s with %s to %s', (current, key, expected) => {+ expect(getNextIconId(iconIds, current, key)).toBe(expected);+ });++ it('ignores unrelated keys', () => {+ expect(getNextIconId(iconIds, 'text', 'Enter')).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetDialogModel.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetDialogModel.tsnew file mode 100644index 0000000000..7cdf1ece13--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetDialogModel.ts@@ -0,0 +1,22 @@+export const getNextIconId = (iconIds: readonly string[], currentIconId: string, key: string): string | null => {+ if (iconIds.length === 0) {+ return null;+ }+ if (key === 'Home') {+ return iconIds[0] ?? null;+ }+ if (key === 'End') {+ return iconIds.at(-1) ?? null;+ }++ const direction = key === 'ArrowRight' || key === 'ArrowDown' ? 1 : key === 'ArrowLeft' || key === 'ArrowUp' ? -1 : 0;++ if (direction === 0) {+ return null;+ }++ const currentIndex = iconIds.indexOf(currentIconId);+ const nextIndex = (Math.max(currentIndex, 0) + direction + iconIds.length) % iconIds.length;++ return iconIds[nextIndex] ?? null;+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetIcons.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetIcons.tsnew file mode 100644index 0000000000..97cad6133e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetIcons.ts@@ -0,0 +1,134 @@+import type { LucideIcon } from 'lucide-react';++import {+ ApertureIcon,+ BlocksIcon,+ BookmarkIcon,+ BoxIcon,+ BrushIcon,+ CameraIcon,+ Columns2Icon,+ CompassIcon,+ CropIcon,+ FilmIcon,+ FlagIcon,+ FlaskConicalIcon,+ FrameIcon,+ HeartIcon,+ ImageIcon,+ ImagesIcon,+ LayersIcon,+ LayoutDashboardIcon,+ LayoutGridIcon,+ LayoutPanelLeftIcon,+ LayoutPanelTopIcon,+ PaletteIcon,+ PanelsTopLeftIcon,+ PenToolIcon,+ RocketIcon,+ Rows2Icon,+ ShapesIcon,+ SlidersHorizontalIcon,+ SparklesIcon,+ SquareStackIcon,+ StarIcon,+ TypeIcon,+ WandSparklesIcon,+ WorkflowIcon,+ ZapIcon,+} from 'lucide-react';++/**+ * The icons a custom layout preset can be given.+ *+ * A curated set rather than all of Lucide: the picker is a glance-and-choose+ * grid, and a thousand icons would make it a search problem. These are chosen+ * to cover how people actually name a workspace — by its arrangement, by the+ * craft it supports, or by a plain marker when neither applies.+ *+ * Ids are persisted with the preset, so they are stable strings and must not be+ * renamed. Dropping an icon from this list is safe: unknown ids fall back.+ */+export interface LayoutPresetIconOption {+ id: string;+ icon: LucideIcon;+ label: string;+}++export interface LayoutPresetIconGroup {+ label: string;+ options: LayoutPresetIconOption[];+}++const option = (id: string, icon: LucideIcon, label: string): LayoutPresetIconOption => ({ icon, id, label });++export const layoutPresetIconGroups: LayoutPresetIconGroup[] = [+ {+ label: 'Arrangement',+ options: [+ option('layout-grid', LayoutGridIcon, 'Grid'),+ option('layout-dashboard', LayoutDashboardIcon, 'Dashboard'),+ option('layout-panel-left', LayoutPanelLeftIcon, 'Left panel'),+ option('layout-panel-top', LayoutPanelTopIcon, 'Top panel'),+ option('columns', Columns2Icon, 'Columns'),+ option('rows', Rows2Icon, 'Rows'),+ option('panels', PanelsTopLeftIcon, 'Panels'),+ option('square-stack', SquareStackIcon, 'Stack'),+ ],+ },+ {+ label: 'Craft',+ options: [+ option('type', TypeIcon, 'Text'),+ option('brush', BrushIcon, 'Brush'),+ option('pen-tool', PenToolIcon, 'Pen'),+ option('palette', PaletteIcon, 'Palette'),+ option('layers', LayersIcon, 'Layers'),+ option('crop', CropIcon, 'Crop'),+ option('shapes', ShapesIcon, 'Shapes'),+ option('sliders', SlidersHorizontalIcon, 'Settings'),+ ],+ },+ {+ label: 'Subject',+ options: [+ option('image', ImageIcon, 'Image'),+ option('images', ImagesIcon, 'Gallery'),+ option('camera', CameraIcon, 'Camera'),+ option('film', FilmIcon, 'Film'),+ option('frame', FrameIcon, 'Frame'),+ option('aperture', ApertureIcon, 'Aperture'),+ option('workflow', WorkflowIcon, 'Workflow'),+ option('blocks', BlocksIcon, 'Nodes'),+ ],+ },+ {+ label: 'Marker',+ options: [+ option('sparkles', SparklesIcon, 'Sparkles'),+ option('wand', WandSparklesIcon, 'Wand'),+ option('zap', ZapIcon, 'Fast'),+ option('rocket', RocketIcon, 'Rocket'),+ option('flask', FlaskConicalIcon, 'Experiment'),+ option('compass', CompassIcon, 'Explore'),+ option('star', StarIcon, 'Star'),+ option('heart', HeartIcon, 'Favourite'),+ option('bookmark', BookmarkIcon, 'Bookmark'),+ option('flag', FlagIcon, 'Flag'),+ option('box', BoxIcon, 'Box'),+ ],+ },+];++const iconsById = new Map(+ layoutPresetIconGroups.flatMap((group) => group.options.map((entry) => [entry.id, entry.icon]))+);++export const DEFAULT_LAYOUT_PRESET_ICON_ID = 'layout-grid';++/** Unknown or missing ids fall back, so a retired icon never breaks a saved preset. */+export const resolveLayoutPresetIcon = (iconId: string | undefined): LucideIcon =>+ (iconId ? iconsById.get(iconId) : undefined) ?? LayoutGridIcon;++export const isLayoutPresetIconId = (iconId: unknown): iconId is string =>+ typeof iconId === 'string' && iconsById.has(iconId);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetManagerStore.test.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetManagerStore.test.tsnew file mode 100644index 0000000000..fa84875633--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetManagerStore.test.ts@@ -0,0 +1,23 @@+import { afterEach, describe, expect, it } from 'vitest';++import {+ closeLayoutPresetAdmin,+ layoutPresetManagerStore,+ openLayoutPresetDelete,+ openLayoutPresetEdit,+} from './layoutPresetManagerStore';++describe('layout preset administration store', () => {+ afterEach(closeLayoutPresetAdmin);++ it('opens one edit or delete target at a time and clears both on close', () => {+ openLayoutPresetEdit('custom-1');+ expect(layoutPresetManagerStore.getSnapshot()).toMatchObject({ deletePresetId: null, editPresetId: 'custom-1' });++ openLayoutPresetDelete('custom-2');+ expect(layoutPresetManagerStore.getSnapshot()).toMatchObject({ deletePresetId: 'custom-2', editPresetId: null });++ closeLayoutPresetAdmin();+ expect(layoutPresetManagerStore.getSnapshot()).toMatchObject({ deletePresetId: null, editPresetId: null });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetManagerStore.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetManagerStore.tsnew file mode 100644index 0000000000..a0162d01cb--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetManagerStore.ts@@ -0,0 +1,50 @@+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';+import { createExternalStore } from '@platform/state/externalStore';++/**+ * Open/close state for the layout preset manager. Addressable from anywhere the+ * `Manage presets` entry appears; the dialog itself is hosted once by the top+ * bar so opening it never depends on which menu is currently mounted.+ */+interface LayoutPresetManagerSnapshot {+ deletePresetId: string | null;+ editPresetId: string | null;+ isOpen: boolean;+}++const INITIAL_SNAPSHOT: LayoutPresetManagerSnapshot = { deletePresetId: null, editPresetId: null, isOpen: false };++export const layoutPresetManagerStore = createExternalStore<LayoutPresetManagerSnapshot>(INITIAL_SNAPSHOT);++registerAccountOwnedResource({+ clear: () => {+ layoutPresetManagerStore.setSnapshot(INITIAL_SNAPSHOT);+ },+ name: 'layout-preset-manager',+});++export const openLayoutPresetManager = (): void =>+ layoutPresetManagerStore.setSnapshot({ ...layoutPresetManagerStore.getSnapshot(), isOpen: true });++export const closeLayoutPresetManager = (): void => layoutPresetManagerStore.setSnapshot(INITIAL_SNAPSHOT);++export const openLayoutPresetEdit = (presetId: string): void =>+ layoutPresetManagerStore.setSnapshot({+ ...layoutPresetManagerStore.getSnapshot(),+ deletePresetId: null,+ editPresetId: presetId,+ });++export const openLayoutPresetDelete = (presetId: string): void =>+ layoutPresetManagerStore.setSnapshot({+ ...layoutPresetManagerStore.getSnapshot(),+ deletePresetId: presetId,+ editPresetId: null,+ });++export const closeLayoutPresetAdmin = (): void =>+ layoutPresetManagerStore.setSnapshot({+ ...layoutPresetManagerStore.getSnapshot(),+ deletePresetId: null,+ editPresetId: null,+ });diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetPresentation.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetPresentation.tsnew file mode 100644index 0000000000..2d56e975b7--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetPresentation.ts@@ -0,0 +1,34 @@+import type { LayoutPreset } from '@workbench/layoutContracts';+import type { LucideIcon } from 'lucide-react';++import { builtInLayoutPresetDescriptors } from '@workbench/layoutPresets';++import { resolveLayoutPresetIcon } from './layoutPresetIcons';++/**+ * Icon and tooltip for a preset. Deliberately not on `LayoutPreset` itself: that+ * type is persisted verbatim for custom presets, and a component reference has+ * no place in a serialized snapshot — which is why custom presets store an icon+ * *id* and resolve it here.+ *+ * The built-in tooltips say what the arrangement is *for*, since the labels name+ * a mode of working rather than a widget — "Automate" has to earn its name+ * somewhere.+ */+export interface LayoutPresetPresentation {+ icon: LucideIcon;+ tooltip: string;+}++const builtInPresentation = new Map(+ builtInLayoutPresetDescriptors.map(({ iconId, preset, tooltip }) => [+ preset.id,+ { icon: resolveLayoutPresetIcon(iconId), tooltip },+ ])+);++export const getLayoutPresetPresentation = (preset: LayoutPreset): LayoutPresetPresentation =>+ builtInPresentation.get(preset.id) ?? {+ icon: resolveLayoutPresetIcon(preset.iconId),+ tooltip: 'Custom layout',+ };diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetStripModel.test.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetStripModel.test.tsnew file mode 100644index 0000000000..4c93b8e110--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetStripModel.test.ts@@ -0,0 +1,32 @@+import type { LayoutPreset } from '@workbench/layoutContracts';++import { layoutPresets } from '@workbench/layoutPresets';+import { describe, expect, it } from 'vitest';++import { getPresetAccessibleName, getTopbarPresetTabs } from './layoutPresetStripModel';++const customPreset = (id: string, label: string): LayoutPreset => ({+ ...layoutPresets[0],+ id,+ isBuiltIn: false,+ label,+});++describe('topbar preset strip model', () => {+ it('keeps every custom preset in the tab strip', () => {+ const customPresets = [customPreset('custom-1', 'One'), customPreset('custom-2', 'Two')];++ expect(getTopbarPresetTabs(customPresets)).toMatchObject([+ { id: 'compose' },+ { id: 'edit' },+ { id: 'automate' },+ { id: 'custom-1' },+ { id: 'custom-2' },+ ]);+ });++ it('keeps the visible label in the accessible name when visual text is hidden', () => {+ expect(getPresetAccessibleName(layoutPresets[0], false)).toBe('Compose');+ expect(getPresetAccessibleName(layoutPresets[0], true)).toBe('Compose, unsaved changes');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetStripModel.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetStripModel.tsnew file mode 100644index 0000000000..4d99f761b5--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetStripModel.ts@@ -0,0 +1,14 @@+import type { LayoutPreset } from '@workbench/layoutContracts';++import { layoutPresets } from '@workbench/layoutPresets';++export const getTopbarPresetTabs = (customPresets: LayoutPreset[]): LayoutPreset[] => [+ ...layoutPresets,+ ...customPresets,+];++export const getPresetAccessibleName = (+ preset: LayoutPreset,+ hasUnsavedChanges: boolean,+ unsavedChangesLabel = 'unsaved changes'+): string => (hasUnsavedChanges ? `${preset.label}, ${unsavedChangesLabel}` : preset.label);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/projectSwitcherModel.test.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/projectSwitcherModel.test.tsnew file mode 100644index 0000000000..6118320ef3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/projectSwitcherModel.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { getProjectSwitcherSections } from './projectSwitcherModel';++describe('project switcher sections', () => {+ it('lists every open project and excludes them from recents', () => {+ const openProjects = [+ { id: 'open-1', name: 'First' },+ { id: 'open-2', name: 'Second' },+ ];+ const libraryProjects = [+ { id: 'open-2', name: 'Second', updatedAt: 2 },+ { id: 'saved-1', name: 'Saved', updatedAt: 1 },+ ];++ expect(getProjectSwitcherSections(openProjects, libraryProjects, 5)).toEqual({+ open: openProjects,+ recent: [{ id: 'saved-1', name: 'Saved', updatedAt: 1 }],+ });+ });++ it('limits only the recent library section', () => {+ const openProjects = Array.from({ length: 7 }, (_, index) => ({ id: `open-${index}`, name: `${index}` }));+ const libraryProjects = Array.from({ length: 7 }, (_, index) => ({+ id: `saved-${index}`,+ name: `${index}`,+ updatedAt: index,+ }));++ const sections = getProjectSwitcherSections(openProjects, libraryProjects, 5);++ expect(sections.open).toHaveLength(7);+ expect(sections.recent).toHaveLength(5);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/projectSwitcherModel.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/projectSwitcherModel.tsnew file mode 100644index 0000000000..12e3fa4675--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/projectSwitcherModel.ts@@ -0,0 +1,17 @@+interface OpenProjectSummary {+ id: string;+ name: string;+}++export const getProjectSwitcherSections = <TOpen extends OpenProjectSummary, TRecent extends OpenProjectSummary>(+ openProjects: TOpen[],+ libraryProjects: TRecent[],+ recentLimit: number+) => {+ const openProjectIds = new Set(openProjects.map((project) => project.id));++ return {+ open: openProjects,+ recent: libraryProjects.filter((project) => !openProjectIds.has(project.id)).slice(0, recentLimit),+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/projectSwitcherStore.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/projectSwitcherStore.tsnew file mode 100644index 0000000000..08d9e4139c--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/projectSwitcherStore.ts@@ -0,0 +1,21 @@+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';+import { createExternalStore } from '@platform/state/externalStore';++/**+ * Open state for the project switcher menu, so `⌘P` can reach it without the+ * hotkey runtime holding a ref to the trigger.+ */+const INITIAL_SNAPSHOT = { isOpen: false };++export const projectSwitcherStore = createExternalStore<{ isOpen: boolean }>(INITIAL_SNAPSHOT);++registerAccountOwnedResource({+ clear: () => {+ projectSwitcherStore.setSnapshot(INITIAL_SNAPSHOT);+ },+ name: 'project-switcher',+});++export const openProjectSwitcher = (): void => projectSwitcherStore.setSnapshot({ isOpen: true });++export const setProjectSwitcherOpen = (isOpen: boolean): void => projectSwitcherStore.setSnapshot({ isOpen });diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/routingPresentation.test.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/routingPresentation.test.tsnew file mode 100644index 0000000000..1b9a979fd8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/routingPresentation.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from 'vitest';++import { getRoutingRelationship } from './routingPresentation';++describe('routing preview relationship', () => {+ it.each([+ [{ destinationLocked: false, sourceLocked: false }, 'arrow'],+ [{ destinationLocked: false, sourceLocked: true }, 'link'],+ [{ destinationLocked: true, sourceLocked: false }, 'link'],+ [{ destinationLocked: true, sourceLocked: true }, 'link'],+ ] as const)('maps route locks to the preview relationship', (locks, expected) => {+ expect(getRoutingRelationship(locks)).toBe(expected);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/routingPresentation.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/routingPresentation.tsnew file mode 100644index 0000000000..d4bf4cbd27--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/routingPresentation.ts@@ -0,0 +1,6 @@+export type RoutingRelationship = 'arrow' | 'link';++export const getRoutingRelationship = (locks: {+ destinationLocked: boolean;+ sourceLocked: boolean;+}): RoutingRelationship => (locks.destinationLocked || locks.sourceLocked ? 'link' : 'arrow');diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/topbarBreakpoints.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/topbarBreakpoints.tsnew file mode 100644index 0000000000..e3b8d62b47--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/topbarBreakpoints.ts@@ -0,0 +1,23 @@+/**+ * The top bar's own widths, as raw media queries.+ *+ * The theme's breakpoint scale (992 / 1280 / 1536) is about page layout; this+ * bar degrades at the points where its *own* content stops fitting, which are+ * not the same numbers. Rather than bend the shared scale for one component, the+ * three thresholds live here as conditions.+ *+ * Order of sacrifice: the ⌘↵ hint, then the preset labels, then the project+ * name. The routing indicator and the queue readout never collapse at any width+ * — the first is the only thing telling a user what ⌘↵ is about to run, and the+ * second is the only thing telling them whether it started.+ */+const hideBelow = (px: number) => ({ [`@media (max-width: ${px - 1}px)`]: { display: 'none' } }) as const;++/** The `⌘↵` hint on the Invoke button face; the tooltip keeps it below this. */+export const HIDE_BELOW_HINT_WIDTH = hideBelow(1440);++/** Preset labels; the names move to their tooltips below this. */+export const HIDE_BELOW_PRESET_LABEL_WIDTH = hideBelow(1280);++/** The project name; the count badge and selector glyph always stay. */+export const HIDE_BELOW_PROJECT_NAME_WIDTH = hideBelow(1024);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.tsnew file mode 100644index 0000000000..634b58ada5--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts@@ -0,0 +1,163 @@+import type { DynamicPromptsExpansion } from '@features/generation/react';+import type { GraphWidgetSource } from '@workbench/graphWidgets';+import type { InvocationRoute, ResultDestination } from '@workbench/invocationContracts';+import type { WidgetTypeId } from '@workbench/widgetContracts';++import { useDynamicPrompts } from '@features/generation/react';+import {+ getEffectivePrompts,+ normalizeGenerateSettings,+ sanitizeBatchCount,+ sanitizeDynamicPromptsConfig,+} from '@features/generation/settings';+import { ensureModelsLoaded, useModelsSelector } from '@features/models';+import { useInvocationTemplatesSelector } from '@features/workflow/react';+import { useMountEffect } from '@platform/react/useMountEffect';+import { submitActiveInvocation } from '@workbench/activeInvocationSubmission';+import { getPlacedWidgetTypeIds, getVisibleWidgetTypeIds, graphWidgetSources } from '@workbench/graphWidgets';+import {+ createInvocationRouteInputSelector,+ isInvocationRouteValid,+ resolveInvocationRouteInput,+} from '@workbench/invocation';+import {+ useActiveProjectSelector,+ useWorkbenchCommands,+ useWorkbenchQueries,+ useWorkbenchSelector,+} from '@workbench/WorkbenchContext';+import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++const selectInvocationRouteInput = createInvocationRouteInputSelector();+const areTypeIdSetsEqual = (left: ReadonlySet<WidgetTypeId>, right: ReadonlySet<WidgetTypeId>): boolean =>+ left.size === right.size && [...left].every((typeId) => right.has(typeId));++/** Reads the persisted dynamic prompt fields off untyped widget values. */+const readDynamicPromptsConfig = (values: Record<string, unknown>) => ({+ combinatorial: values.dynamicPromptsCombinatorial,+ maxPrompts: values.dynamicPromptsMaxPrompts,+ sampleSeed: values.dynamicPromptsSampleSeed,+ seedBehaviour: values.dynamicPromptsSeedBehaviour,+});++/**+ * The prompt that will actually be expanded and submitted — the authored text+ * wrapped by the active template, since a template can introduce `{a|b}` the+ * authored prompt never had.+ */+const readEffectivePositivePrompt = (values: Record<string, unknown>): string => {+ const settings = normalizeGenerateSettings(values);++ return settings ? getEffectivePrompts(settings).positivePrompt : '';+};++export const getBatchCount = (values: Record<string, unknown>): number => sanitizeBatchCount(values.batchCount);++export interface InvocationState {+ batchCount: number;+ blockingReasons: string[];+ invocation: InvocationRoute;+ isValid: boolean;+ /** Every graph widget — all of them stay selectable in the routing menu. */+ sources: GraphWidgetSource[];+ /** Widget types the layout is showing right now. */+ visibleTypeIds: ReadonlySet<WidgetTypeId>;+ /** Widget types placed in some rail; picking one of these needs no new placement. */+ placedTypeIds: ReadonlySet<WidgetTypeId>;+ promptExpansion: DynamicPromptsExpansion;+ /** The values the batch count and prompt summary belong to (generate or upscale). */+ sourceValues: Record<string, unknown>;+ /** Submits the current route. Pass a destination to override it for this run only. */+ invoke: (destinationOverride?: ResultDestination) => Promise<void>;+}++/**+ * Everything the invocation cluster needs to render and to fire, in one place.+ *+ * The Invoke button, the routing indicator, and the iterations stepper all+ * depend on the same resolved route; splitting the resolution across three+ * components would let them disagree about whether the route is runnable, which+ * is exactly the failure the redesign exists to prevent.+ */+export const useInvocationState = (): InvocationState => {+ const { t } = useTranslation();+ const routeInput = useActiveProjectSelector(selectInvocationRouteInput);+ const visibleTypeIds = useActiveProjectSelector(getVisibleWidgetTypeIds, areTypeIdSetsEqual);+ const placedTypeIds = useActiveProjectSelector(getPlacedWidgetTypeIds, areTypeIdSetsEqual);+ const commands = useWorkbenchCommands();+ 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;+ const { invocation } = routeInput;++ // Project-graph route validation reads the invocation templates imperatively;+ // subscribing here keeps the resolved route live while they load.+ useInvocationTemplatesSelector((snapshot) => snapshot.status);+ useMountEffect(() => {+ void ensureModelsLoaded();+ });++ const resolvedRoute = resolveInvocationRouteInput(routeInput, 'global', invocation, availabilityModels);+ const isConnected = backendConnectionStatus === 'connected';+ const sourceValues = invocation.sourceId === 'upscale' ? routeInput.upscaleValues : routeInput.generateValues;++ // Observing the shared expansion cache here keeps the count honest and costs+ // nothing extra: the Generate preview and the submit path use the same key.+ const promptExpansion = useDynamicPrompts(+ readEffectivePositivePrompt(routeInput.generateValues),+ invocation.sourceId === 'generate' || invocation.sourceId === 'canvas'+ ? sanitizeDynamicPromptsConfig(readDynamicPromptsConfig(routeInput.generateValues))+ : null+ );+ // A prompt that will not expand cannot be submitted — the alternative is putting+ // the literal `{a|b}` in front of the model — so this blocks rather than just+ // annotating. `submitResolvedInvocation` enforces the same rule for the hotkey.+ const expansionReason = promptExpansion.isError+ ? 'The prompt could not be expanded.'+ : (promptExpansion.error ?? null);++ // Whether the source widget is *placed* is already part of route validation+ // ("The X widget is not mounted in this project"), so there is no separate+ // openness gate here — a source that is merely not on screen still runs.+ const blockingReasons = useMemo(+ () => [+ ...(isConnected ? [] : ['The backend is disconnected.']),+ ...(expansionReason === null ? [] : [expansionReason]),+ ...resolvedRoute.validationReasons,+ ],+ [expansionReason, isConnected, resolvedRoute.validationReasons]+ );+ const isValid = isInvocationRouteValid(resolvedRoute) && isConnected && expansionReason === null;++ const invoke = useCallback(+ (destinationOverride?: ResultDestination) =>+ submitActiveInvocation({+ commands,+ destinationOverride,+ formatControlLayerError: (code, layerName) =>+ t('widgets.layers.control.invalidLayer', {+ name: layerName,+ reason: t(`widgets.layers.control.validation.${code}`),+ }),+ getModels: () => availabilityModels,+ queries,+ }),+ [availabilityModels, commands, queries, t]+ );++ return {+ batchCount: getBatchCount(sourceValues),+ blockingReasons,+ invocation,+ invoke,+ isValid,+ placedTypeIds,+ promptExpansion,+ sourceValues,+ sources: graphWidgetSources,+ visibleTypeIds,+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useLayoutDrift.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useLayoutDrift.tsnew file mode 100644index 0000000000..8074e95648--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useLayoutDrift.ts@@ -0,0 +1,48 @@+import type { LayoutPreset } from '@workbench/layoutContracts';+import type { WorkbenchSnapshot } from '@workbench/workbenchStore';++import {+ areLayoutPresetSnapshotsEqual,+ createLayoutPresetSnapshot,+ resolveSavedLayoutPreset,+} from '@workbench/layoutPresetSnapshots';+import { useDebouncedWorkbenchSelector } from '@workbench/WorkbenchContext';++/** How long the live layout must hold still before the drift dot reacts. */+const DRIFT_SETTLE_MS = 250;++export interface LayoutDriftState {+ activePreset: LayoutPreset;+ hasDrifted: boolean;+}++const areDriftStatesEqual = (left: LayoutDriftState, right: LayoutDriftState): boolean =>+ left.hasDrifted === right.hasDrifted &&+ left.activePreset.id === right.activePreset.id &&+ left.activePreset.label === right.activePreset.label;++// Module scope, not an inline closure: the comparison serialises the whole+// arrangement, and a selector whose identity changed every render would defeat+// `useSyncExternalStoreWithSelector`'s memoization and re-run it on each one.+const selectLayoutDrift = (snapshot: WorkbenchSnapshot): LayoutDriftState => {+ const activePreset = resolveSavedLayoutPreset(snapshot.account, snapshot.activeProject.layout.presetId);++ return {+ activePreset,+ hasDrifted: !areLayoutPresetSnapshotsEqual(+ createLayoutPresetSnapshot(snapshot.activeProject),+ activePreset.snapshot+ ),+ };+};++/**+ * Whether the live dock layout has diverged from the preset it was loaded from.+ *+ * Debounced rather than read live: a drop that lands a widget, resizes its+ * region, and reveals it arrives as several dispatches in a row, and a dot that+ * blinks part-way through a gesture reads as a glitch rather than as+ * information. Settling first means the user only ever sees the resting answer.+ */+export const useLayoutDrift = (): LayoutDriftState =>+ useDebouncedWorkbenchSelector(selectLayoutDrift, DRIFT_SETTLE_MS, areDriftStatesEqual);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.test.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.test.tsnew file mode 100644index 0000000000..be25585754--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.test.ts@@ -0,0 +1,22 @@+import { IS_MAC_OS } from '@workbench/hotkeys/keys';+import { describe, expect, it } from 'vitest';++import { formatTopbarShortcut, formatTopbarShortcutForAria } from './useTopbarShortcut';++/**+ * The bar prints its own bindings on control faces, so it has to print the ones+ * this keyboard actually has. `⌘↵` on Linux names a key that is not there, which+ * is worse than showing nothing.+ */+describe('topbar shortcut labels', () => {+ it('renders modifiers for the running platform', () => {+ expect(formatTopbarShortcut('mod+enter')).toBe(IS_MAC_OS ? '⌘↵' : 'Ctrl+Enter');+ expect(formatTopbarShortcut('mod+s')).toBe(IS_MAC_OS ? '⌘S' : 'Ctrl+S');+ expect(formatTopbarShortcut('alt+mod+enter')).toBe(IS_MAC_OS ? '⌘⌥↵' : 'Ctrl+Alt+Enter');+ });++ it('formats the configured binding for aria-keyshortcuts', () => {+ expect(formatTopbarShortcutForAria('mod+enter')).toBe(IS_MAC_OS ? 'Meta+Enter' : 'Control+Enter');+ expect(formatTopbarShortcutForAria('alt+mod+s')).toBe(IS_MAC_OS ? 'Meta+Alt+S' : 'Control+Alt+S');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.tsnew file mode 100644index 0000000000..7ce812652b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.ts@@ -0,0 +1,79 @@+import type { HotkeyDefinition } from '@workbench/hotkeys/types';++import { firstPartyHotkeyCatalog } from '@workbench/hotkeys/catalog';+import { formatHotkeyForPlatform, IS_MAC_OS } from '@workbench/hotkeys/keys';+import { applyCustomHotkeys } from '@workbench/hotkeys/resolve';+import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';++/**+ * Glyphs for the compact hints printed on control faces and menu rows.+ *+ * macOS spells modifiers as symbols and runs them together; everywhere else+ * they are words joined by `+`. Printing `⌘↵` on Linux would name a key that+ * keyboard does not have, which is worse than printing nothing.+ */+const MAC_GLYPHS: Record<string, string> = {+ alt: '⌥',+ cmd: '⌘',+ ctrl: '⌃',+ enter: '↵',+ option: '⌥',+ shift: '⇧',+};++const OTHER_LABELS: Record<string, string> = {+ alt: 'Alt',+ ctrl: 'Ctrl',+ enter: 'Enter',+ meta: 'Win',+ shift: 'Shift',+};++const formatPart = (part: string): string =>+ IS_MAC_OS ? (MAC_GLYPHS[part] ?? part.toUpperCase()) : (OTHER_LABELS[part] ?? part.toUpperCase());++export const formatTopbarShortcut = (hotkey: string): string =>+ formatHotkeyForPlatform(hotkey)+ .map(formatPart)+ .join(IS_MAC_OS ? '' : '+');++const ARIA_LABELS: Record<string, string> = {+ alt: 'Alt',+ cmd: 'Meta',+ ctrl: 'Control',+ enter: 'Enter',+ option: 'Alt',+ shift: 'Shift',+};++export const formatTopbarShortcutForAria = (hotkey: string): string =>+ formatHotkeyForPlatform(hotkey)+ .map((part) => ARIA_LABELS[part] ?? (part.length === 1 ? part.toUpperCase() : part))+ .join('+');++const findDefinition = (commandId: string): HotkeyDefinition | undefined =>+ firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === commandId);++/**+ * The binding a command is *actually* on, formatted for this platform, or null+ * when the user has unbound it. Reading the effective binding rather than the+ * default means a remapped Invoke does not advertise a key that no longer works.+ */+export const useTopbarShortcut = (commandId: string): string | null => {+ const binding = useTopbarShortcutBinding(commandId);++ return binding?.display ?? null;+};++export interface TopbarShortcutBinding {+ aria: string;+ display: string;+}++export const useTopbarShortcutBinding = (commandId: string): TopbarShortcutBinding | null => {+ const customHotkeys = useWorkbenchPreferenceSelector((preferences) => preferences.customHotkeys);+ const definition = findDefinition(commandId);+ const firstKey = definition ? applyCustomHotkeys(definition, customHotkeys).keys[0] : undefined;++ return firstKey ? { aria: formatTopbarShortcutForAria(firstKey), display: formatTopbarShortcut(firstKey) } : null;+};diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsxindex 21c13757dc..33f604a152 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx@@ -29,6 +29,7 @@ import { useTranslation } from 'react-i18next';import { WidgetActionsMenu } from './WidgetActionsMenu';import { WidgetIdentityIcon } from './WidgetIdentityIcon';+import { WidgetSourceLockBadge } from './WidgetSourceLockBadge';const PANEL_SIZE_STEP_PX = 16;const MIN_PANEL_SIZE_PX = 180;@@ -283,6 +284,7 @@ export const WidgetHeader = ({{label}</Text>)}+ <WidgetSourceLockBadge typeId={manifest.id} /></HStack><WidgetHeaderActionsGroupHeaderMenu={HeaderMenu}diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetSourceLockBadge.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetSourceLockBadge.tsxnew file mode 100644index 0000000000..4c418d00b5--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetSourceLockBadge.tsx@@ -0,0 +1,32 @@+import type { WidgetTypeId } from '@workbench/widgetContracts';++import { Icon } from '@chakra-ui/react';+import { Tooltip } from '@platform/ui/Tooltip';+import { getSourceIdForWidgetTypeId } from '@workbench/graphWidgets';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { LockKeyholeIcon } from 'lucide-react';++/**+ * Marks the widget the invoke source is pinned to.+ *+ * Only the widget itself carries this. The preset strip does not: presets are+ * arrangements, not widgets, and marking one would put back exactly the+ * conflation between "which layout am I in" and "what will run" that the+ * routing model exists to remove.+ */+export const WidgetSourceLockBadge = ({ typeId }: { typeId?: WidgetTypeId }) => {+ const sourceId = typeId ? getSourceIdForWidgetTypeId(typeId) : null;+ const isLockedSource = useActiveProjectSelector(+ (project) => project.invocation.sourceLocked && project.invocation.sourceId === sourceId+ );++ if (!isLockedSource) {+ return null;+ }++ return (+ <Tooltip content="Invoke is locked to this widget. Unlock it from the routing menu." showArrow>+ <Icon as={LockKeyholeIcon} aria-label="Locked invoke source" boxSize="3" color="accent.fg" flexShrink={0} />+ </Tooltip>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/index.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/index.tsindex 2ded4e1110..c2d76c6a60 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/index.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/index.ts@@ -6,6 +6,7 @@ export { FieldPlaceholder, WidgetHeader, WidgetHeaderActionsGroup, WidgetPanelFrexport { StatusWidgetChip } from '@platform/ui';export { WidgetInstanceContextMenu, type WidgetInstanceContextMenuTarget } from './WidgetInstanceContextMenu';export { WidgetRegionDropOverlay } from './WidgetRegionDropOverlay';+export { WidgetSourceLockBadge } from './WidgetSourceLockBadge';export { WidgetStrip } from './WidgetStrip';export { MissingWidgetFrame, WidgetChromeSlotById, WidgetRenderer, WidgetRendererById } from './WidgetRenderer';export { useWidgetIntentPreloadProps } from './useWidgetIntentPreload';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 a4b18bb59e..2a46b826cb 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,8 +1,9 @@/* oxlint-disable react-perf/jsx-no-new-function-as-prop */-import { Flex, Group, HStack, IconButton, Menu, Portal, Text, VisuallyHidden } from '@chakra-ui/react';+import { Flex, HStack, IconButton, Menu, Portal, Text, VisuallyHidden } from '@chakra-ui/react';import { galleryDurability } from '@features/gallery';import { Button, MenuContent, Tooltip } from '@platform/ui';+import { Group } from '@platform/ui/Group';import {buildFilterDefaults,getCanvasOperations,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 7d71c137e4..f837c629cd 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@@ -4,7 +4,6 @@ import type { ChangeEvent } from 'react';import {createListCollection,Flex,- Group,HStack,IconButton,Input,@@ -17,6 +16,7 @@ import {VisuallyHidden,} from '@chakra-ui/react';import { Button, MenuContent, Select, Tooltip } from '@platform/ui';+import { Group } from '@platform/ui/Group';import {getCanvasOperations,isSamDocumentInputValid,diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 00318f953c..0203d1380f 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -594,10 +594,10 @@ describe('workbench widget state updates', () => {});describe('workbench layout presets', () => {- it('applies the Default preset as a full widget-region layout', () => {+ it('applies the Compose preset as a full widget-region layout', () => {let state = createInitialWorkbenchState();- state = workbenchReducer(state, { presetId: 'canvas-default', type: 'applyPreset' });+ state = workbenchReducer(state, { presetId: 'compose', type: 'applyPreset' });const project = getActiveProject(state);@@ -673,11 +673,97 @@ describe('workbench layout presets', () => {presetId: 'custom-layout-1',type: 'renameLayoutPreset',});- state = workbenchReducer(state, { presetId: 'canvas-default', type: 'renameLayoutPreset', label: 'Nope' });+ state = workbenchReducer(state, { presetId: 'compose', type: 'renameLayoutPreset', label: 'Nope' });state = workbenchReducer(state, { presetId: 'custom-layout-1', type: 'deleteLayoutPreset' });expect(state.account.customLayoutPresets).toEqual([]);});++ it('moves every project off a deleted custom layout preset', () => {+ let state = createInitialWorkbenchState();+ const firstProjectId = state.activeProjectId;++ state = workbenchReducer(state, {+ label: 'Shared custom layout',+ presetId: 'custom-layout-1',+ type: 'addLayoutPreset',+ });+ state = workbenchReducer(state, { presetId: 'custom-layout-1', type: 'applyPreset' });+ state = workbenchReducer(state, { type: 'createProject' });+ const secondProjectId = state.activeProjectId;+ state = workbenchReducer(state, { presetId: 'custom-layout-1', type: 'applyPreset' });++ state = workbenchReducer(state, { presetId: 'custom-layout-1', type: 'deleteLayoutPreset' });++ expect(getProject(state, firstProjectId).layout.presetId).toBe('compose');+ expect(getProject(state, secondProjectId).layout.presetId).toBe('compose');+ expect(state.account.activeLayoutPresetId).toBe('compose');+ });++ // Contract §9.1 of the top-bar redesign. If switching presets loses work,+ // users stop switching them and the whole centre strip becomes dead weight,+ // so this is a correctness requirement rather than polish.+ it('preserves widget state across a Compose to Edit to Compose round trip', () => {+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'compose', type: 'applyPreset' });++ state = workbenchReducer(state, {+ type: 'patchGenerateSettings',+ values: { positivePrompt: 'a lighthouse at dusk', steps: 42 },+ });+ state = workbenchReducer(state, {+ instanceId: 'gallery',+ type: 'patchWidgetInstanceValues',+ values: { scrollOffset: 1280 },+ });++ state = workbenchReducer(state, { presetId: 'edit', type: 'applyPreset' });+ state = workbenchReducer(state, { presetId: 'compose', type: 'applyPreset' });++ const generateValues = getProjectWidgetValues(getActiveProject(state), 'generate');++ expect(generateValues.positivePrompt).toBe('a lighthouse at dusk');+ expect(generateValues.steps).toBe(42);+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').scrollOffset).toBe(1280);+ });++ it('saves the live arrangement onto a built-in preset and restores its shipped default', () => {+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'compose', type: 'applyPreset' });++ state = workbenchReducer(state, { region: 'right', sizePx: 320, type: 'setRegionWidgetSize' });+ state = workbenchReducer(state, { presetId: 'compose', type: 'saveLayoutPreset' });++ expect(state.account.layoutPresetOverrides?.compose?.widgetRegions.right.sizePx).toBe(320);++ // Reverting now lands on the saved edit, not on the shipped arrangement.+ state = workbenchReducer(state, { region: 'right', sizePx: 500, type: 'setRegionWidgetSize' });+ state = workbenchReducer(state, { type: 'resetActiveLayout' });++ expect(getActiveProject(state).widgetRegions.right.sizePx).toBe(320);++ state = workbenchReducer(state, { presetId: 'compose', type: 'restoreLayoutPresetDefault' });+ state = workbenchReducer(state, { type: 'resetActiveLayout' });++ expect(state.account.layoutPresetOverrides?.compose).toBeUndefined();+ expect(getActiveProject(state).widgetRegions.right.sizePx).toBe(450);+ });++ it('resolves retired built-in preset ids onto the three shipped presets', () => {+ const initial = createInitialWorkbenchState();+ const hydrated = workbenchReducer(initial, {+ state: {+ ...initial,+ account: { activeLayoutPresetId: 'workflow' },+ projects: initial.projects.map((project) => ({+ ...project,+ layout: { ...project.layout, presetId: 'canvas' },+ })),+ } as unknown as WorkbenchState,+ type: 'hydrateWorkbench',+ });++ expect(hydrated.account.activeLayoutPresetId).toBe('automate');+ expect(getActiveProject(hydrated).layout.presetId).toBe('edit');+ });});describe('workbenchReducer Phase 5 generation flow', () => {@@ -2351,7 +2437,7 @@ describe('workbench account and project settings', () => {it('starts with the default layout preset and legacy-matching project settings', () => {const state = createInitialWorkbenchState();- expect(state.account).toEqual({ activeLayoutPresetId: 'canvas-default' });+ expect(state.account).toEqual({ activeLayoutPresetId: 'compose' });expect(getActiveProject(state).settings).toEqual(DEFAULT_PROJECT_SETTINGS);});@@ -2364,7 +2450,13 @@ describe('workbench account and project settings', () => {const state = workbenchReducer(initial, { state: legacy, type: 'hydrateWorkbench' });- expect(state.account).toEqual({ activeLayoutPresetId: 'gallery', customLayoutPresets: [] });+ // `gallery` was retired with the three-preset model; it resolves to Compose,+ // the arrangement it was a center-view variant of.+ expect(state.account).toEqual({+ activeLayoutPresetId: 'compose',+ customLayoutPresets: [],+ layoutPresetOverrides: {},+ });});it('heals hydrated accounts that are missing a layout preset', () => {@@ -2373,7 +2465,7 @@ describe('workbench account and project settings', () => {const state = workbenchReducer(initial, { state: legacy, type: 'hydrateWorkbench' });- expect(state.account.activeLayoutPresetId).toBe('canvas-default');+ expect(state.account.activeLayoutPresetId).toBe('compose');});it('updates project settings on the active project only', () => {@@ -4151,6 +4243,23 @@ describe('auto invocation route switching', () => {expect(getRoute(destinationLockedState)).toMatchObject({ destination: 'canvas', sourceId: 'upscale' });});+ it('toggles both routing locks together and normalizes a mixed lock state', () => {+ let unlockedState = createInitialWorkbenchState();++ unlockedState = workbenchReducer(unlockedState, { type: 'toggleRoutingLock' });+ expect(getRoute(unlockedState)).toMatchObject({ destinationLocked: true, sourceLocked: true });++ unlockedState = workbenchReducer(unlockedState, { type: 'toggleRoutingLock' });+ expect(getRoute(unlockedState)).toMatchObject({ destinationLocked: false, sourceLocked: false });++ let mixedState = createInitialWorkbenchState();+ mixedState = workbenchReducer(mixedState, { type: 'toggleSourceLock' });+ expect(getRoute(mixedState)).toMatchObject({ destinationLocked: false, sourceLocked: true });++ mixedState = workbenchReducer(mixedState, { type: 'toggleRoutingLock' });+ expect(getRoute(mixedState)).toMatchObject({ destinationLocked: false, sourceLocked: false });+ });+it('never remaps the destination on a manual source change or a same-source edit', () => {let state = createInitialWorkbenchState();diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 57bf13c9e9..22c33ac29b 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -15,6 +15,7 @@ import type {CenterViewId,LayoutPreset,LayoutPresetId,+ LayoutPresetOverrides,LayoutPresetSnapshot,ProjectLayoutState,WidgetRegion,@@ -126,8 +127,12 @@ import {isInvocationSourceAvailable,resolveInvocationRoute,} from './invocation';-import { defaultLayoutPreset, getLayoutPreset } from './layoutPresets';-import { cloneLayoutPresetWidgetRegions, createLayoutPresetSnapshot } from './layoutPresetSnapshots';+import { defaultLayoutPreset, isBuiltInLayoutPresetId, resolveLayoutPresetId } from './layoutPresets';+import {+ cloneLayoutPresetWidgetRegions,+ createLayoutPresetSnapshot,+ resolveSavedLayoutPreset,+} from './layoutPresetSnapshots';import { normalizeWorkbenchQueueHistory } from './queueHistoryNormalization';import { normalizeProjectSettings } from './settings/store';@@ -145,13 +150,17 @@ type WorkbenchReducerAction =| { type: 'switchProject'; projectId: string }| { type: 'setCenterView'; centerViewId: CenterViewId }| { type: 'applyPreset'; presetId: LayoutPresetId }- | { type: 'addLayoutPreset'; presetId: LayoutPresetId; label: string }+ | { type: 'addLayoutPreset'; presetId: LayoutPresetId; label: string; iconId?: string }+ | { type: 'setLayoutPresetIcon'; presetId: LayoutPresetId; iconId: string }+ | { type: 'saveLayoutPreset'; presetId: LayoutPresetId }+ | { type: 'restoreLayoutPresetDefault'; presetId: LayoutPresetId }| { type: 'renameLayoutPreset'; presetId: LayoutPresetId; label: string }| { type: 'deleteLayoutPreset'; presetId: LayoutPresetId }| { type: 'resetActiveLayout' }| { type: 'recoverShellLayout' }| { type: 'setInvocationSource'; sourceId: InvocationSourceId }| { type: 'setInvocationDestination'; destination: ResultDestination }+ | { type: 'toggleRoutingLock' }| { type: 'toggleSourceLock' }| { type: 'toggleDestinationLock' }| {@@ -1289,6 +1298,10 @@ export const normalizeWorkbenchProject = (project: Project): Project => {// canvas can still be v1-shaped, malformed, or missing — migrate before cloning.canvas,graphHistory: normalizeGraphHistory((project as Partial<Project>).graphHistory),+ // Built-in preset ids were renamed for the three-preset model; a project+ // saved under an old id must still resolve to the arrangement it names,+ // otherwise every restored project reads as drifted from Compose.+ layout: { ...project.layout, presetId: resolveLayoutPresetId(project.layout.presetId) },projectGraph: normalizeProjectGraph(project.projectGraph),promptHistory: normalizePromptHistory((project as Partial<Project>).promptHistory),queue: normalizeWorkbenchQueueHistory(project.queue, { canvas, widgetInstances }),@@ -1491,6 +1504,7 @@ const normalizeCustomLayoutPresets = (presets: unknown): LayoutPreset[] => {return [{+ ...(typeof record.iconId === 'string' ? { iconId: record.iconId } : {}),id: record.id,label: record.label,snapshot: cloneLayoutPresetSnapshot(record.snapshot),@@ -1499,9 +1513,22 @@ const normalizeCustomLayoutPresets = (presets: unknown): LayoutPreset[] => {});};+const normalizeLayoutPresetOverrides = (overrides: unknown): LayoutPresetOverrides => {+ if (!overrides || typeof overrides !== 'object') {+ return {};+ }++ return Object.fromEntries(+ Object.entries(overrides as Record<string, unknown>).flatMap(([presetId, snapshot]) =>+ isLayoutPresetSnapshot(snapshot) ? [[resolveLayoutPresetId(presetId), cloneLayoutPresetSnapshot(snapshot)]] : []+ )+ );+};+const normalizeAccount = (account: Partial<WorkbenchState['account']> | undefined): WorkbenchState['account'] => ({- activeLayoutPresetId: account?.activeLayoutPresetId ?? defaultLayoutPreset.id,+ activeLayoutPresetId: resolveLayoutPresetId(account?.activeLayoutPresetId ?? defaultLayoutPreset.id),customLayoutPresets: normalizeCustomLayoutPresets(account?.customLayoutPresets),+ layoutPresetOverrides: normalizeLayoutPresetOverrides(account?.layoutPresetOverrides),});const normalizeWorkbenchState = (state: WorkbenchState): WorkbenchState => ({@@ -1537,7 +1564,7 @@ const updateActiveLayout = (});const getAvailableLayoutPreset = (state: WorkbenchState, presetId: LayoutPresetId): LayoutPreset =>- state.account.customLayoutPresets?.find((preset) => preset.id === presetId) ?? getLayoutPreset(presetId);+ resolveSavedLayoutPreset(state.account, presetId);const applyLayoutPresetToProject = (project: Project, preset: LayoutPreset): Project => {const snapshot = preset.snapshot;@@ -2463,6 +2490,7 @@ export const __workbenchReducerInternal = (}const preset: LayoutPreset = {+ iconId: action.iconId,id: action.presetId,label: action.label.trim() || 'Custom layout',snapshot: createLayoutPresetSnapshot(normalizeWorkbenchProject(activeProject)),@@ -2477,6 +2505,50 @@ export const __workbenchReducerInternal = (account: { ...state.account, activeLayoutPresetId: preset.id, customLayoutPresets },};}+ case 'saveLayoutPreset': {+ const activeProject = state.projects.find((project) => project.id === state.activeProjectId);++ if (!activeProject) {+ return state;+ }++ const snapshot = createLayoutPresetSnapshot(normalizeWorkbenchProject(activeProject));++ // Built-in preset bodies are code, so their saved form lives in an+ // override map; custom presets own their snapshot outright.+ if (isBuiltInLayoutPresetId(action.presetId)) {+ const layoutPresetOverrides: LayoutPresetOverrides = {+ ...state.account.layoutPresetOverrides,+ [action.presetId]: { ...snapshot, layout: { ...snapshot.layout, presetId: action.presetId } },+ };++ return { ...state, account: { ...state.account, layoutPresetOverrides } };+ }++ const customLayoutPresets = (state.account.customLayoutPresets ?? []).map((preset) =>+ preset.id === action.presetId+ ? { ...preset, snapshot: { ...snapshot, layout: { ...snapshot.layout, presetId: preset.id } } }+ : preset+ );++ return { ...state, account: { ...state.account, customLayoutPresets } };+ }+ case 'restoreLayoutPresetDefault': {+ const { [action.presetId]: removed, ...layoutPresetOverrides } = state.account.layoutPresetOverrides ?? {};++ return removed ? { ...state, account: { ...state.account, layoutPresetOverrides } } : state;+ }+ case 'setLayoutPresetIcon': {+ return {+ ...state,+ account: {+ ...state.account,+ customLayoutPresets: (state.account.customLayoutPresets ?? []).map((preset) =>+ preset.id === action.presetId ? { ...preset, iconId: action.iconId } : preset+ ),+ },+ };+ }case 'renameLayoutPreset': {const label = action.label.trim();@@ -2498,6 +2570,11 @@ export const __workbenchReducerInternal = (const customLayoutPresets = (state.account.customLayoutPresets ?? []).filter((preset) => preset.id !== action.presetId);+ const projects = state.projects.map((project) =>+ project.layout.presetId === action.presetId+ ? { ...project, layout: { ...project.layout, presetId: defaultLayoutPreset.id } }+ : project+ );return {...state,@@ -2509,6 +2586,7 @@ export const __workbenchReducerInternal = (: state.account.activeLayoutPresetId,customLayoutPresets,},+ projects,};}case 'resetActiveLayout': {@@ -2536,6 +2614,13 @@ export const __workbenchReducerInternal = (case 'setInvocationDestination': {return updateActiveInvocation(state, (invocation) => ({ ...invocation, destination: action.destination }));}+ case 'toggleRoutingLock': {+ return updateActiveInvocation(state, (invocation) => {+ const isLocked = invocation.sourceLocked || invocation.destinationLocked;++ return { ...invocation, destinationLocked: !isLocked, sourceLocked: !isLocked };+ });+ }case 'toggleSourceLock': {return updateActiveInvocation(state, (invocation) => ({ ...invocation, sourceLocked: !invocation.sourceLocked }));}diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex a7bd722f4a..23eccefbdd 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -236,17 +236,23 @@ const createCommands = (dispatch: WorkbenchDispatch, getState: () => WorkbenchStsubmitCanvas: command('submitCanvasInvocationSnapshot'),submitResolved: command('submitResolvedInvocationSnapshot'),toggleDestinationLock: command('toggleDestinationLock'),+ toggleRoutingLock: command('toggleRoutingLock'),toggleSourceLock: command('toggleSourceLock'),},layout: {applyPreset: command('applyPreset', (presetId: ActionPayload<'applyPreset'>['presetId']) => ({ presetId })),createPreset: command('addLayoutPreset',- (presetId: ActionPayload<'addLayoutPreset'>['presetId'], label: string) => ({+ (presetId: ActionPayload<'addLayoutPreset'>['presetId'], label: string, iconId?: string) => ({+ iconId,label,presetId,})),+ setPresetIcon: command(+ 'setLayoutPresetIcon',+ (presetId: ActionPayload<'setLayoutPresetIcon'>['presetId'], iconId: string) => ({ iconId, presetId })+ ),deletePreset: command('deleteLayoutPreset', (presetId: ActionPayload<'deleteLayoutPreset'>['presetId']) => ({presetId,})),@@ -256,6 +262,15 @@ const createCommands = (dispatch: WorkbenchDispatch, getState: () => WorkbenchSt(presetId: ActionPayload<'renameLayoutPreset'>['presetId'], label: string) => ({ label, presetId })),reset: command('resetActiveLayout'),+ /** Writes the live arrangement back onto the named preset. */+ savePreset: command('saveLayoutPreset', (presetId: ActionPayload<'saveLayoutPreset'>['presetId']) => ({+ presetId,+ })),+ /** Drops saved edits to a built-in preset, restoring its shipped arrangement. */+ restorePresetDefault: command(+ 'restoreLayoutPresetDefault',+ (presetId: ActionPayload<'restoreLayoutPresetDefault'>['presetId']) => ({ presetId })+ ),setCenterView: command('setCenterView', (centerViewId: ActionPayload<'setCenterView'>['centerViewId']) => ({centerViewId,})),diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex d679d0db9c..0fd20ba3b1 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -30,6 +30,21 @@ export default defineConfig({return 'shared';}+ // Shell modules that both route shells reach but no longer reach+ // *through each other*. The two top bars used to share their whole+ // control set, so these rode along inside one chunk; now that the+ // workbench bar owns its own controls, each would otherwise be+ // emitted as a separate request on both routes for no byte saving.+ if (+ id.endsWith('/platform/i18n/client.ts') ||+ id.endsWith('/platform/react/useMountEffect.ts') ||+ id.endsWith('/platform/ui/theme/system.ts') ||+ id.endsWith('/workbench/hotkeys/resolve.ts') ||+ id.endsWith('/workbench/settings/settingsDialogStore.ts')+ ) {+ return 'shell-shared';+ }+// Mixed-gallery item helpers cross the eager editor shell and its// lazy Gallery/Preview chunks. Keep them with the already-eager// gallery state projection instead of emitting one extra request.