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
docs(webv2): compress the longest rationale comments
joshistoast675b5289676e
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 880f29b3cc..fb79141af2 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -25,11 +25,11 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 114.39999999850988,+ "domContentLoadedMedianMs": 112.59999999997672,"id": "launchpad","layoutSwitchMedianMs": 0,- "loadMedianMs": 114.39999999850988,- "longestTaskMaxMs": 74,+ "loadMedianMs": 112.59999999997672,+ "longestTaskMaxMs": 70,"owner": "app","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:launchpad",@@ -56,7 +56,7 @@"scriptRequestCount": 32,"totalRawBytes": 1784521},- "routeReadyMedianMs": 255.90000000596046,+ "routeReadyMedianMs": 249.5,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "empty"},@@ -83,11 +83,11 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 112.10000000149012,+ "domContentLoadedMedianMs": 112,"id": "launchpad","layoutSwitchMedianMs": 0,- "loadMedianMs": 112.10000000149012,- "longestTaskMaxMs": 68,+ "loadMedianMs": 112,+ "longestTaskMaxMs": 67,"owner": "app","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:launchpad",@@ -114,7 +114,7 @@"scriptRequestCount": 32,"totalRawBytes": 1784521},- "routeReadyMedianMs": 267.40000000596046,+ "routeReadyMedianMs": 262.9000000000233,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "representative"},@@ -141,13 +141,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 114.10000000149012,+ "domContentLoadedMedianMs": 115.79999999993015,"id": "editor-minimal","layoutSwitchMedianMs": 0,- "loadMedianMs": 114.10000000149012,- "longestTaskMaxMs": 106,+ "loadMedianMs": 115.89999999990687,+ "longestTaskMaxMs": 94,"owner": "workbench",- "projectSwitchMedianMs": 36.80000000447035,+ "projectSwitchMedianMs": 32.40000000002328,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {@@ -172,7 +172,7 @@"scriptRequestCount": 107,"totalRawBytes": 3736702},- "routeReadyMedianMs": 661.7000000029802,+ "routeReadyMedianMs": 635.5999999999767,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -199,13 +199,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 115,+ "domContentLoadedMedianMs": 113.59999999997672,"id": "editor-minimal","layoutSwitchMedianMs": 0,- "loadMedianMs": 115,- "longestTaskMaxMs": 104,+ "loadMedianMs": 113.59999999997672,+ "longestTaskMaxMs": 114,"owner": "workbench",- "projectSwitchMedianMs": 52.29999999701977,+ "projectSwitchMedianMs": 52.5,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {@@ -230,7 +230,7 @@"scriptRequestCount": 107,"totalRawBytes": 3736702},- "routeReadyMedianMs": 712.7999999970198,+ "routeReadyMedianMs": 696.6999999999534,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"},@@ -257,11 +257,11 @@"scriptRequestCount": 5,"totalRawBytes": 286746},- "domContentLoadedMedianMs": 116.5,+ "domContentLoadedMedianMs": 112.90000000002328,"id": "editor-canvas",- "layoutSwitchMedianMs": 62.80000000447035,- "loadMedianMs": 116.5,- "longestTaskMaxMs": 94,+ "layoutSwitchMedianMs": 63.40000000002328,+ "loadMedianMs": 112.90000000002328,+ "longestTaskMaxMs": 90,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -288,7 +288,7 @@"scriptRequestCount": 112,"totalRawBytes": 4023447},- "routeReadyMedianMs": 1096.3999999985099,+ "routeReadyMedianMs": 1085.1000000000931,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "empty"},@@ -315,11 +315,11 @@"scriptRequestCount": 5,"totalRawBytes": 286746},- "domContentLoadedMedianMs": 112,+ "domContentLoadedMedianMs": 115.30000000004657,"id": "editor-canvas",- "layoutSwitchMedianMs": 195,- "loadMedianMs": 112,- "longestTaskMaxMs": 371,+ "layoutSwitchMedianMs": 191.29999999993015,+ "loadMedianMs": 115.40000000002328,+ "longestTaskMaxMs": 383,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -346,7 +346,7 @@"scriptRequestCount": 112,"totalRawBytes": 4023447},- "routeReadyMedianMs": 1263.1000000014901,+ "routeReadyMedianMs": 1269.7000000000698,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "representative"},@@ -373,11 +373,11 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 111.59999999403954,+ "domContentLoadedMedianMs": 120.30000000004657,"id": "editor-workflow",- "layoutSwitchMedianMs": 55.400000005960464,- "loadMedianMs": 111.59999999403954,- "longestTaskMaxMs": 91,+ "layoutSwitchMedianMs": 61.60000000009313,+ "loadMedianMs": 120.30000000004657,+ "longestTaskMaxMs": 111,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -404,7 +404,7 @@"scriptRequestCount": 107,"totalRawBytes": 3736702},- "routeReadyMedianMs": 1051.1000000014901,+ "routeReadyMedianMs": 1096.5999999999767,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -431,11 +431,11 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 114.79999999701977,+ "domContentLoadedMedianMs": 112.5,"id": "editor-workflow",- "layoutSwitchMedianMs": 113.60000000149012,- "loadMedianMs": 114.79999999701977,- "longestTaskMaxMs": 387,+ "layoutSwitchMedianMs": 115.19999999995343,+ "loadMedianMs": 112.5,+ "longestTaskMaxMs": 377,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -462,7 +462,7 @@"scriptRequestCount": 107,"totalRawBytes": 3736702},- "routeReadyMedianMs": 1183.2000000029802,+ "routeReadyMedianMs": 1190.5,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"},@@ -489,11 +489,11 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 112.29999999701977,+ "domContentLoadedMedianMs": 113.80000000004657,"id": "editor-gallery",- "layoutSwitchMedianMs": 22.80000000447035,- "loadMedianMs": 112.29999999701977,- "longestTaskMaxMs": 94,+ "layoutSwitchMedianMs": 25,+ "loadMedianMs": 113.80000000004657,+ "longestTaskMaxMs": 97,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -520,7 +520,7 @@"scriptRequestCount": 107,"totalRawBytes": 3736702},- "routeReadyMedianMs": 1312.2000000029802,+ "routeReadyMedianMs": 1332,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -547,11 +547,11 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 114,+ "domContentLoadedMedianMs": 116.09999999997672,"id": "editor-gallery",- "layoutSwitchMedianMs": 96.30000000447035,- "loadMedianMs": 114,- "longestTaskMaxMs": 147,+ "layoutSwitchMedianMs": 96.79999999993015,+ "loadMedianMs": 116.09999999997672,+ "longestTaskMaxMs": 142,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -578,7 +578,7 @@"scriptRequestCount": 107,"totalRawBytes": 3736702},- "routeReadyMedianMs": 1457.3999999985099,+ "routeReadyMedianMs": 1467.0999999999767,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex 4fc39e07f4..f2697eb360 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -227,17 +227,12 @@ export const getGallerySearchTerm = (values: Record<string, unknown>): string =>/*** Where new results land, resolved against the boards this install actually has.*- * A saved selection survives whenever it still resolves — it is a deliberate choice, and a project- * opened where its destination still exists should keep using it. When it does not resolve the- * project's own board is the better answer than Uncategorized: a project arriving from another- * install, or one whose pre-migration board was rejected as ambiguous, names a board id that means- * nothing here, and dropping it to Uncategorized would quietly scatter that project's output.+ * A saved selection survives whenever it still resolves, since it is a deliberate choice. When it+ * does not — a project from another install, or one whose pre-migration board was ambiguous — the+ * project's own board beats Uncategorized, which would quietly scatter that project's output. No+ * saved selection at all is the same case rather than a choice of Uncategorized.*- * No saved selection at all is the same case, not a choice of Uncategorized. A project saved before- * it owned a board — or by a build that never wrote a destination — should still work on its own- * board, which is where everything else it has made already lives.- *- * An empty board list means "still loading", not "no such board", so nothing is resolved yet.+ * An empty board list means "still loading", not "no such board", so nothing resolves yet.*/export const getGallerySelectedBoardId = (values: Record<string, unknown>, backendBoards: GalleryBoard[]): string => {const selectedBoardId = typeof values.selectedBoardId === 'string' ? values.selectedBoardId : null;diff --git a/invokeai/frontend/webv2/src/features/queue/core/progressRail.ts b/invokeai/frontend/webv2/src/features/queue/core/progressRail.tsindex 003ee01280..3b7569944f 100644--- a/invokeai/frontend/webv2/src/features/queue/core/progressRail.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/progressRail.ts@@ -3,15 +3,11 @@ import type { QueueItem } from './historyTypes';import { isOpenQueueItem } from './historySummary';/**- * The read model behind the top bar's progress rail — the one full-width,- * always-present generation indicator.+ * The read model behind the top bar's progress rail.*- * It is deliberately a *list* of segments rather than a single value. With- * `generation_devices` (default `auto`) the backend runs one session per GPU,- * so several images render at once; every other progress surface in the app- * collapses to `runningQueueItemId` and therefore reports one of them as if it- * were the whole story. The rail gives each live session its own segment, the- * way the legacy progress bar did.+ * Deliberately a *list* of segments: with `generation_devices` the backend runs+ * one session per GPU, and every other progress surface collapses to+ * `runningQueueItemId` and reports one of them as the whole story.*/export type ProgressRailModel =diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.test.ts b/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.test.tsindex 945629429d..ddf4ba3202 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.test.ts@@ -21,13 +21,10 @@ const image = (overrides: Partial<{ height: number; image_name: string; width: n({ height: 512, image_name: 'a.png', width: 512, ...overrides }) as UpscaleWidgetValues['inputImage'];describe('areStringArraysEqual', () => {- it('accepts the same reference without walking it', () => {+ it('compares by content and position, short-circuiting on identity', () => {const phrases = ['alpha', 'beta'];expect(areStringArraysEqual(phrases, phrases)).toBe(true);- });-- it('compares by content and by position', () => {expect(areStringArraysEqual(['alpha', 'beta'], ['alpha', 'beta'])).toBe(true);expect(areStringArraysEqual(['alpha', 'beta'], ['beta', 'alpha'])).toBe(false);expect(areStringArraysEqual(['alpha'], ['alpha', 'beta'])).toBe(false);@@ -35,12 +32,9 @@ describe('areStringArraysEqual', () => {});describe('getModelTriggerPhrases', () => {- it('is empty for a missing model or a model that declares none', () => {+ it('is empty without a model, and drops non-string entries a foreign config could carry', () => {expect(getModelTriggerPhrases(null)).toEqual([]);expect(getModelTriggerPhrases(model({ trigger_phrases: undefined }))).toEqual([]);- });-- it('drops non-string entries a hand-edited or foreign config could carry', () => {expect(getModelTriggerPhrases(model({ trigger_phrases: ['alpha', 7, null] as unknown as string[] }))).toEqual(['alpha',]);diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.ts b/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.tsindex cdd4abd064..7624793253 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.ts+++ b/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.ts@@ -4,18 +4,13 @@ import type { UpscaleWidgetValues } from '@features/upscale/core/types';/*** Content comparators for the Upscale widget's memo boundaries.*- * `values` is re-derived from the raw widget state on every patch. Its nested- * members are mostly identity-stable — `normalizeUpscaleWidgetValues` preserves- * them across a patch that didn't touch them — but that's an incidental- * property of the normalizer, not a contract the widget should lean on. These- * compare by content instead, so no section depends on that incidental- * stability to avoid re-rendering (e.g. the prompt editors on a scale edit).+ * `values` is re-derived on every patch. Its members happen to be+ * identity-stable, but that is a property of the normalizer rather than a+ * contract, so these compare by content instead.*- * They live apart from the components that pass them to `memo` because that is- * the only way they can be tested directly: a comparator that is wrong in the- * conservative direction merely re-renders, while one that is wrong in the- * permissive direction silently shows stale data, and only the second is a bug- * you can miss by looking at the screen.+ * Kept apart from the components that pass them to `memo` so they can be tested+ * directly: a comparator wrong in the permissive direction silently shows stale+ * data, which you cannot catch by looking at the screen.*/export const areStringArraysEqual = (left: readonly string[], right: readonly string[]): boolean =>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxindex 87c20d2def..92c63b400c 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -312,26 +312,19 @@ export const WorkflowDialogHost = () => {const isNewWorkflowConfirmOpen = workflowUiStore.useSelector((snapshot) => snapshot.isNewWorkflowConfirmOpen);const lastImportRequestRef = useRef(importRequestCount);- // Library autosave: bound project graphs save themselves back to the- // library after edits settle. This host is always mounted alongside the- // workflow widget, so one autosaver instance tracks the graph for the- // widget's whole lifetime — but that instance is created AND disposed- // within a single mount effect (held in a ref, not a `useState`- // initializer). A `useState` initializer only runs once per fiber, while- // its disposal lived in a separate effect's cleanup; React StrictMode's- // dev-only mount→cleanup→mount simulation ran that cleanup once without- // ever re-running the initializer, permanently disposing the one instance- // still in use (autosave silently no-oped for the rest of the session).- // Creating and disposing in the same effect makes the simulation produce a- // fresh, live instance instead. `read()` pulls straight from the project- // store's synchronous snapshot (`projectStore.getSnapshot()`, the same- // accessor `useWorkflowProjectSelector` subscribes through) rather than a- // component-owned ref, so it is always current whenever the autosaver's- // debounce timer or `flush()` calls it. The same effect subscribes- // directly to the project store to notify the autosaver of edits (skipping- // the initial snapshot so loading a workflow does not itself count as an- // edit) — a plain subscription rather than a selector, since nothing here- // needs to re-render on graph edits, only to poke the autosaver.+ // Library autosave: bound graphs save themselves back after edits settle.+ //+ // The autosaver is created AND disposed inside one mount effect, held in a+ // ref. A `useState` initializer runs once per fiber while its disposal lived+ // in a separate effect's cleanup, so StrictMode's mount→cleanup→mount+ // simulation disposed the one live instance without recreating it — autosave+ // silently no-oped for the rest of the session.+ //+ // `read()` pulls from `projectStore.getSnapshot()` rather than a+ // component-owned ref, so it is current whenever the debounce or `flush()`+ // calls it. The same effect subscribes to the store to poke the autosaver+ // (skipping the initial snapshot, so loading is not an edit) — a plain+ // subscription, since nothing here re-renders on graph edits.//// `hostScope` guards `onStatus`: account rotation aborts the in-flight// save's signal and synchronously resets the (account-owned)diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsxindex ba329da840..5af3ad25bf 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx@@ -19,15 +19,10 @@ import { PanelModeToggle } from './WorkflowLinearPanel';(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-// This app is built with the React Compiler (`vite.config.mts`), which-// auto-memoizes plain value computations inside components based on their-// detected dependencies — so a spy on a pure helper a card's render calls-// (e.g. `isFormDescendantOrSelf`) can't be trusted as a "did this card's-// render function run" probe: the compiler can (and does) skip re-running-// such a call even when the surrounding component *was* invoked. `dnd-kit`'s-// `useDroppable` is a hook, and hook calls can never be skipped by the-// compiler (they must run unconditionally, in order, every render), so a-// real passthrough spy on it is a reliable per-card render probe instead.+// The React Compiler auto-memoizes plain value computations, so a spy on a pure+// helper a card renders through is not a reliable "did this render" probe — the+// compiler can skip the call even when the component did run. Hooks can never be+// skipped, so a passthrough spy on `useDroppable` is the reliable probe.vi.mock('@dnd-kit/core', async (importOriginal) => {const actual = await importOriginal<typeof DndKitCoreModule>();@@ -99,13 +94,10 @@ describe('Workflow Linear panel mode toggle', () => {});/**- * Regression coverage for the native-DnD bug: dropping a card into a- * container reparents it, React remounts the card under its new parent, and- * the native `dragend` event (bound to the old node) never fires — leaving- * the module's dragging state stuck and killing every drag after it. The- * dnd-kit port resolves moves only in `onDragEnd` at the `DndContext` level,- * which fires regardless of node unmounts, so a second drag right after a- * reparenting drop must still work.+ * Regression coverage for the native-DnD bug: a reparenting drop remounts the+ * card, so `dragend` (bound to the old node) never fired and every later drag+ * died. dnd-kit resolves in `onDragEnd` at the `DndContext` level, which fires+ * regardless of unmounts, so a second drag straight after must still work.*/describe('Form builder drag and drop (dnd-kit)', () => {let host: HTMLDivElement;@@ -208,11 +200,9 @@ describe('Form builder drag and drop (dnd-kit)', () => {target.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, code }));};- // dnd-kit's continuous droppable re-measuring (`MeasuringStrategy.Always`)- // and sensor activation run on their own rAF-scheduled updates outside- // React's synchronous event handling, so each step needs a real tick to- // settle before the next one — a bare `act(() => pointer(...))` leaves- // `over` stale and the drop resolves against the wrong (or no) target.+ // Re-measuring and sensor activation run on rAF outside React's synchronous+ // event handling, so each step needs a real tick — a bare `act()` leaves+ // `over` stale and the drop resolves against the wrong target.const interact = (action: () => void): Promise<void> =>act(async () => {action();@@ -231,23 +221,16 @@ describe('Form builder drag and drop (dnd-kit)', () => {await interact(() => pointer('pointerdown', handle, startX, startY));await interact(() => pointer('pointermove', handle.ownerDocument, startX + 8, startY));await interact(() => pointer('pointermove', handle.ownerDocument, x, y));- // A `MeasuringStrategy.Always` remeasure lands one tick after the move- // that triggered it, so the move's own `onDragMove` can still report a- // stale `over`. A no-op settle move re-runs collision detection against- // the now-current rects before the drop.+ // The remeasure lands a tick after the move that triggered it, so a no-op+ // settle move re-runs collision detection against current rects.await interact(() => pointer('pointermove', handle.ownerDocument, x, y + 1));await interact(() => pointer('pointerup', handle.ownerDocument, x, y + 1));};/**- * Drags `sourceTitle`'s title bar to vertical position `targetCenterY` via- * the keyboard: `Space` lifts, `ArrowDown`/`ArrowUp` steps 25px at a time- * toward the target (dnd-kit's `defaultKeyboardCoordinateGetter`), `Space`- * drops. Ends with a net-zero nudge in the same direction as the last real- * step — the keyboard analogue of `dragTo`'s no-op settle move:- * `MeasuringStrategy.Always`'s remeasure lands one tick after the arrow- * press that triggered it, so the last press's own `onDragMove` can still- * report a stale `over`.+ * Keyboard drag: `Space` lifts, arrows step 25px toward the target, `Space`+ * drops. Ends with a net-zero nudge — the keyboard analogue of `dragTo`'s+ * settle move, for the same one-tick remeasure lag.*/const dragToWithKeyboard = async (sourceTitle: string, targetCenterY: number): Promise<void> => {const handle = titleBarFor(sourceTitle);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.ts b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.tsindex fe12f9e6d2..a42a8caa7d 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.ts@@ -89,24 +89,15 @@ const formContainerDepth = (form: WorkflowForm, containerId: string): number =>};/**- * Innermost-wins tiebreak for overlapping droppables — restores the native-DnD- * `stopPropagation` semantics the port lost. A container's own `edge:X` and- * `into:X` are the same ambiguity dnd-kit's rect-based collision can't avoid:- * `into:X` is DOM-nested inside `edge:X`'s box, so hovering its dropzone- * always matches both. Comparing by landing container resolves it the same- * way as any other nesting — the deeper one wins, so `into:X` (lands inside- * `X`) beats `edge:X` (lands inside `X`'s parent).+ * Innermost-wins tiebreak for overlapping droppables, restoring the native-DnD+ * `stopPropagation` semantics the port lost. `into:X` is DOM-nested inside+ * `edge:X`'s box, so hovering it always matches both; the deeper landing+ * container wins, and among equal depths an edge beats an into (a specific+ * insertion point is more precise intent than "append here").*- * The rule, precisely: every candidate's landing container has a *depth*- * (its distance from the form root); the candidate with the greatest depth- * wins outright, and among candidates tied on depth, an edge wins over an- * into (a specific insertion point next to a sibling is a more precise- * intent than "append to this container"). Depth is computed independently- * per candidate — not by comparing each new candidate only against the- * current winner — so the result doesn't depend on the order `collisions`- * arrives in: two incomparable siblings (say containers `C` and `B`, neither- * nested under the other) plus a deeper `D` nested under `B` must still pick- * `D`, even if `C` happened to be evaluated first.+ * Depth is computed per candidate rather than against the running winner, so+ * the result does not depend on collision order — two incomparable siblings+ * plus a deeper third must still pick the deepest.*/export const pickInnermostFormCollision = (collisions: { id: string }[], form: WorkflowForm): string | null => {if (collisions.length === 0) {diff --git a/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.test.ts b/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.test.tsindex e9910dff30..ef0afb61bb 100644--- a/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.test.ts+++ b/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.test.ts@@ -11,17 +11,12 @@ describe('isSlotUnclaimed', () => {expect(isSlotUnclaimed({ id: 'newer' }, painted)).toBe(false);});- it('rejects an unknown slot by default', () => {- // `undefined` may be a value a newer writer set, so reverting over it- // would be the data loss the rule exists to prevent.+ it('rejects an unknown slot unless the caller says unknown means absent', () => {+ // By default `undefined` may be a value a newer writer set, so reverting+ // over it would be the data loss the rule exists to prevent. Opting in+ // still does not excuse a slot someone else actually claimed.expect(isSlotUnclaimed(undefined, 'painted')).toBe(false);- });-- it('accepts an unknown slot only when the caller says unknown means absent', () => {expect(isSlotUnclaimed(undefined, 'painted', { treatUnknownAsUnclaimed: true })).toBe(true);- });-- it('still rejects a slot a newer writer claimed, even when unknown is allowed', () => {expect(isSlotUnclaimed('newer', 'painted', { treatUnknownAsUnclaimed: true })).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.ts b/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.tsindex 5f3ab3e7f2..66288ac90c 100644--- a/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.ts+++ b/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.ts@@ -1,22 +1,15 @@/**- * The one rule for undoing an optimistic write: put a slot back only if it- * still holds exactly what this mutation painted there.+ * The one rule for undoing an optimistic write: restore a slot only if it still+ * holds exactly what this mutation painted there.*- * An optimistic mutation writes a value, the server rejects it, and the- * rollback wants the old value back. Between those two moments anything may- * have written to the same slot — a generation completing, a refetch landing,- * the person re-selecting, a second mutation on the same item. Restoring- * unconditionally would throw that newer work away, and the failure is silent:- * the UI shows stale state that no longer corresponds to anything.+ * Between the optimistic write and the server's rejection, anything may have+ * written to the same slot — a generation completing, a refetch landing, a+ * second mutation on the same item. Restoring unconditionally throws that newer+ * work away, and it fails silently.*- * So the restore is a compare-and-swap. `after` is what we painted; if the slot- * still reads as `after`, we are the last writer and may safely revert. If it- * reads as anything else, someone newer owns it and we leave it alone.- *- * This lived in three separate places — the gallery query cache, the per-project- * widget-value snapshot, and the per-item board/starred rollback — each with its- * own copy of the check and a comment pointing at the other two. One wrong copy- * is a data-loss bug, so there is one copy.+ * This lived in four places (twice in the gallery query cache, plus the widget-+ * value snapshot and the per-item rollback), each with a comment pointing at the+ * others. One wrong copy is data loss, so there is one copy.*//** What a rollback needs to know about a slot: what was there, and what we put there. */diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/system.ts b/invokeai/frontend/webv2/src/platform/ui/theme/system.tsindex bdd2294f9a..374b208e35 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/system.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/system.ts@@ -23,28 +23,20 @@ import { DEFAULT_THEME, DEFAULT_THEME_ID, type NeutralStep, THEMES, type ThemeDe/*** Workbench design system.*- * Each theme (`themes.ts`) is authored as one neutral ramp (`neutral.50…neutral.950`,- * lightest → darkest) plus a few seeds (brand, accent, status) and four off-ramp- * neutrals (`inset`, `fill`, `grid`, `control`). This module turns that into two- * token layers:+ * Each theme is one neutral ramp (`neutral.50…950`) plus seeds and four+ * off-ramp neutrals, turned into two token layers:*- * 1. The **ramp** is emitted verbatim as conditional semantic tokens- * (`neutral.*`), one value per theme keyed on a custom `[data-theme=<id>]`- * condition. Chakra base `tokens.colors` only hold plain strings, so anything- * that varies per theme must live in `semanticTokens`.- * 2. The **semantic contract** (`bg`, `fg.muted`, `border.emphasized`, the- * `gray`/`brand`/`accent` palettes, …) is theme-agnostic: it references ramp- * steps and flips by light/dark mode only. `bg` is `neutral.950` in dark mode and- * `neutral.200` in light — the light ramp is not a mirror of the dark one, because- * light panels go *whiter* than the app background.+ * 1. The **ramp** emits as conditional semantic tokens keyed on+ * `[data-theme=<id>]`. Chakra's base `tokens.colors` hold plain strings, so+ * anything varying per theme must live in `semanticTokens`.+ * 2. The **semantic contract** (`bg`, `fg.muted`, …) is theme-agnostic and+ * flips by light/dark only. Light is not a mirror of dark — light panels go+ * *whiter* than the app background.*- * `ThemeController` sets `data-theme` (and the `.dark`/`.light` class) on `<html>`,- * so switching themes is a single attribute change with zero React re-render.- * Components reference only the semantic tokens — never the ramp or a theme.- *- * Re-pointing Chakra's neutral `gray` palette at the ramp makes every built-in- * component (Dialog, Menu, Input, Button, Tooltip, Badge) follow the active theme- * with no per-component overrides.+ * `ThemeController` sets `data-theme` on `<html>`, so switching is one attribute+ * change with zero re-render. Components reference only semantic tokens.+ * Re-pointing Chakra's `gray` at the ramp makes every built-in component follow+ * the theme without per-component overrides.*/const NON_DEFAULT_THEMES = THEMES.filter((theme) => theme.id !== DEFAULT_THEME_ID);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.tsindex a51e53e9eb..6390ba8207 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts@@ -1,49 +1,30 @@/**- * The bitmap store: paint persistence via content-hashed server images.+ * Paint persistence via content-hashed server images.*- * Painting bakes strokes straight into a layer's raster cache surface (see- * `strokeSession`/`paintTool`), but nothing persists — a reload would lose the- * strokes. This store closes that loop: on each committed stroke it marks the- * layer dirty, and after a short idle window it encodes the layer's full cache- * surface to a PNG, content-hashes it (SHA-256), dedupes against already- * uploaded bitmaps, uploads new ones, and — only once the upload succeeds —- * dispatches `updateCanvasLayerSource` so the reducer-owned document points its- * paint layer at the persisted image name. The reducer stays pixel-free: only a- * `CanvasImageRef` (name + dims + hash) ever crosses the boundary.+ * Strokes bake into a layer's raster cache surface but nothing persists. On each+ * committed stroke this marks the layer dirty; after an idle window it encodes+ * the cache surface to PNG, SHA-256s it, dedupes, uploads, and only on success+ * dispatches `updateCanvasLayerSource`. The reducer stays pixel-free — only a+ * `CanvasImageRef` crosses the boundary.*- * Key invariants:- * - **Swap-on-success**: the contract keeps its previous ref until the upload- * resolves. A failed upload never dispatches; the layer stays dirty and the- * old ref stays valid, so a reload still shows the last persisted pixels.- * - **Debounce per layer** (~1.5 s idle): a new stroke resets the timer, so a- * burst of strokes uploads once.- * - **Content-hash dedupe**: identical pixels reuse the previously uploaded- * image name and skip the upload entirely. This is what makes undo cheap- * (restoring old pixels re-hashes to the already-uploaded image).- * - **Self-echo guard**: the dispatch round-trips back through the document- * mirror as a source change for the layer. {@link BitmapStore.isSelfEcho}- * lets the engine skip re-rasterizing/invalidating the cache for the exact- * bitmap ref this store just applied (the pixels already match).- * - **Source-type guard**: a layer's cache surface survives a source-type- * change (e.g. rasterize's paint bake, then an undo back to shape/gradient)- * — only the document's source pointer changes, not the cache. So every- * flush re-checks `getLayerSource` (at entry AND again right before the- * dispatch, since encode/hash/upload all await) and drops the pending work- * without dispatching if the layer is no longer `paint` (or no longer- * exists). Otherwise a stale debounced flush would silently convert a- * parametric layer back to `paint` with wrong-extent pixels.- * - **Redundant-dispatch skip is ground-truth, not memory**: right before- * dispatching, a flush skips if the DOCUMENT's current bitmap ref (via- * `getLayerSource`) already equals the resolved image name — not if- * `lastApplied` (this store's memory of what it last dispatched) does. A- * round trip through a non-`paint` source and back (rasterize → undo →- * redo) leaves `lastApplied` pointing at a name the document no longer- * references (the redo lands on `{ bitmap: null }`); comparing against that- * stale memory would suppress the re-dispatch forever. Comparing against- * the document itself self-heals regardless of how it drifted.+ * Invariants:+ * - **Swap-on-success**: a failed upload never dispatches, so the layer stays+ * dirty and a reload still shows the last persisted pixels.+ * - **Debounce per layer** (~1.5 s): a stroke burst uploads once.+ * - **Content-hash dedupe**: identical pixels skip the upload, which is what+ * makes undo cheap.+ * - **Self-echo guard**: the dispatch round-trips back as a source change;+ * {@link BitmapStore.isSelfEcho} lets the engine skip re-rasterizing it.+ * - **Source-type guard**: a cache surface survives a source-type change, so+ * every flush re-checks `getLayerSource` both at entry and again before+ * dispatching (encode/hash/upload all await). Otherwise a stale flush would+ * convert a parametric layer back to `paint` with wrong-extent pixels.+ * - **Redundant-dispatch skip reads the document, not `lastApplied`**: a round+ * trip through a non-`paint` source (rasterize → undo → redo) leaves+ * `lastApplied` naming an image the document no longer references, and+ * comparing against it would suppress the re-dispatch forever.*- * Every side-effecting dependency (encode, upload, hash, dispatch, timers) is- * injectable, so this runs in node tests with fakes. Zero React.+ * Every side effect is injectable, so this runs in node tests. Zero React.*/import type { CanvasImageRef, CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';@@ -346,33 +327,20 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {};/**- * One failure bookkeeping path shared by both ways a flush can fail: an- * upload/dispatch throwing (a real network/server error) and a decline- * (`accepted !== true` — not an error, but still bounded by the same- * breaker). Always advances `failureCounts` and re-dirties the layer with- * reason `'failure'`, so `runFlush`'s `finally` schedules the next attempt- * with growing backoff — or, once `failures` reaches- * `maxConsecutiveFailures`, stops rescheduling entirely (a fresh stroke via- * `markLayerDirty` is the only way back in).+ * Shared bookkeeping for both ways a flush fails: a throw, and a decline+ * (`accepted !== true` — not an error, but bounded by the same breaker).+ * Advances `failureCounts` and re-dirties the layer, so `runFlush` reschedules+ * with backoff until `maxConsecutiveFailures`, after which only a fresh stroke+ * gets back in.*- * Reporting policy: the FIRST non-silent failure of a streak `reportedStreaks`- * hasn't already reported, plus — unconditionally — the failure that opens- * the circuit, even when that one is itself a silent decline: once the- * circuit is open, strokes stop persisting at all, and that transition must- * be heard no matter how the streak got there. Everything else (silent- * declines that don't open the circuit, and any retry after the streak's- * first report) stays quiet — an unreachable server would otherwise toast- * once per retry, including barrier-driven retries `flushPendingUploads`- * still attempts against an already-open circuit on every Generate/export/- * blur, forever. `reportedStreaks` is cleared everywhere `failureCounts` is- * (a fresh stroke, a successful flush, `discardLayer`, `reset`, `dispose`),- * so the next streak reports its own first failure again.+ * Reports the first non-silent failure of a streak, plus — unconditionally —+ * the failure that opens the circuit, even a silent decline: once open,+ * strokes stop persisting entirely and that has to be heard. Everything else+ * stays quiet, or an unreachable server would toast once per retry forever,+ * including the barrier retries every Generate/export/blur attempts.*- * Bookkeeping is committed BEFORE the `reportError` call: an injected- * observer may itself call back into this store (e.g. `reset`/- * `discardLayer`), and its outcome must be the final word, not overwritten- * by a bookkeeping write landing after it returns. Observer exceptions are- * caught and ignored — ancillary to the store's own retry state.+ * Bookkeeping commits BEFORE `reportError`, because an observer may call back+ * into this store and its outcome must be the final word.*/const recordFlushFailure = (layerId: string, error: unknown, options: { silent: boolean }): void => {const failures = (failureCounts.get(layerId) ?? 0) + 1;@@ -483,32 +451,17 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {if (!sourceNow || sourceNow.type !== 'paint') {return;}- // The DOCUMENT already points at this exact image (e.g. a re-flush of- // identical pixels that hash-deduped to an already-applied ref): skip a- // redundant dispatch and its self-echo round-trip.+ // The document already points at this image, so skip the dispatch and its+ // self-echo round-trip.//- // This is checked against `sourceNow` (the document's CURRENT bitmap ref),- // not `lastApplied` (this store's memory of what it last dispatched) — the- // two can diverge. `lastApplied` is never cleared when a layer's source is- // converted away from `paint` and back (e.g. `rasterizeLayer` → undo →- // redo: the document round-trips through a parametric source and back to- // `paint`, landing on `{ bitmap: null }`, while `lastApplied` still holds- // the previously-uploaded name from before the undo). Comparing against- // `lastApplied` in that case would suppress the dispatch forever, leaving- // the document permanently pointed at `bitmap: null` even though the- // dedupe correctly resolved the identical baked pixels back to the prior- // image. Comparing against the document's actual current ref is the- // ground truth for "is this dispatch a no-op" and self-heals regardless- // of how the document's source got out of sync with this store's memory.+ // Compared against `sourceNow`, not `lastApplied`: a round trip away from+ // `paint` and back (rasterize → undo → redo) lands the document on+ // `{ bitmap: null }` while `lastApplied` still names the pre-undo image, so+ // comparing against memory would suppress the dispatch forever.//- // The OFFSET must match too: a pure-translation transform (drag + Apply)- // bakes byte-identical pixels → same hash → dedupe resolves to the- // already-referenced image, but the paint offset moved. Comparing only- // `imageName` would skip the dispatch that persists the new offset, so the- // translation would be silently lost on reload (and every re-flush would- // re-skip it forever). Compare the captured `offset` (which travels with- // this dispatch) against the document's current offset — absent offsets are- // the legacy origin `{ x: 0, y: 0 }`.+ // The offset must match too. A pure translation bakes byte-identical pixels+ // that dedupe to the same image, so comparing `imageName` alone would skip+ // the dispatch that persists the new offset and lose the move on reload.const currentOffset = sourceNow.bitmap ? (sourceNow.offset ?? { x: 0, y: 0 }) : null;if (sourceNow.bitmap?.imageName === result.imageName &&diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 61169b2135..4041666a62 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -599,23 +599,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC* The pixel-write bridge shared by undo and redo: put the patch's pixels back* into the layer's live cache surface, propagate the edit, and re-persist.*- * ## Undo ↔ bitmap-store convergence (P2.2 reviewer note)- *- * Undo writes the OLD pixels into the cache and marks the layer dirty while an- * upload of the NEW pixels may still be in flight. The sequence converges:- *- * 1. The in-flight upload finishes and dispatches `updateCanvasLayerSource`- * with the NEW bitmap ref. Because the store recorded that name in- * `lastApplied` before dispatching, the engine's mirror sees it as a- * self-echo ({@link BitmapStore.isSelfEcho}) and does NOT re-rasterize — so- * the cache keeps the OLD pixels this undo just wrote (never clobbered).- * The contract now *transiently* points at the NEW ref.- * 2. This `markLayerDirty` schedules a follow-up flush. The bitmap store- * serializes per layer, so it runs after the in-flight upload settles. It- * encodes the cache (now the OLD pixels), hashes it, and the content-hash- * dedupe reuses the OLD pixels' already-uploaded image name — no re-upload.- * 3. That flush dispatches the OLD ref, moving `lastApplied` back and pointing- * the contract at the OLD pixels: cache and contract have re-converged.+ * Undo writes the OLD pixels while an upload of the NEW ones may still be in+ * flight, and the two converge: the in-flight dispatch reads as a self-echo+ * ({@link BitmapStore.isSelfEcho}) so the cache keeps the OLD pixels, then+ * this `markLayerDirty` schedules a flush that (serialized per layer, so it+ * runs after) re-encodes them, hash-dedupes to their already-uploaded name,+ * and dispatches the OLD ref back.*/const applyImagePatch: ImagePatchApply = (layerId, rect, pixels) => {if (!layerCache.get(layerId)) {diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex c8d944897c..68de586526 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -171,15 +171,11 @@ export const useImageActions = ({return project ? getProjectWidgetValues(project, 'generate') : {};};- // A deleted item can be visible only through a project's `gallery` widget- // values (e.g. the `recentImages` overlay for a just-generated image that- // hasn't reached the backend query cache yet) or the `upscale` widget's- // locked input, none of which `patchGalleryItemCaches` can restore.- // Snapshot the fields `removeGalleryItems` can touch, across every open- // project (images aren't project-scoped), diffed before/after so the- // restore can apply the same "still current" conflict rule- // `patchGalleryItemCaches`'s own rollback uses instead of clobbering- // whatever a concurrent generation or selection wrote in the meantime.+ // A deleted item can be visible only through widget values — the+ // `recentImages` overlay, or upscale's locked input — which the cache patch+ // cannot restore. Snapshot those fields across every open project (images+ // aren't project-scoped), diffed before/after so the restore applies the+ // shared compare-and-swap rule rather than clobbering concurrent writes.const applyGalleryItemRemoval = (itemKeys: GalleryItemKey[]): GalleryWidgetKeySnapshotEntry[] => {const before = captureGalleryWidgetKeyValues(queries.getSnapshot().projects);@@ -284,13 +280,11 @@ export const useImageActions = ({reportMutationOutcome(action, requested.length, result, boardId);};const deleteItemsConfirmed = (items: GalleryItemRef[]): Promise<void> => {- // Optimistic: the items vanish immediately. Capture the action context- // first — successor selection reasons about the pre-removal item list —- // and keep a snapshot rollback so a failed delete resurrects the lists- // before the confirmed subset is re-applied. On a partial failure, the- // trailing invalidation is left to bring a failed ref's recent-image- // overlay entry back from the backend list; on a total failure it can't- // be relied on, so the gallery widget snapshot restores it directly.+ // Optimistic: items vanish immediately. Capture the action context first+ // (successor selection reasons about the pre-removal list) and keep a+ // snapshot rollback. A partial failure leans on the trailing invalidation+ // to restore overlay entries; a total failure cannot, so the widget+ // snapshot restores them directly.const deletionContext = getItemActionContext?.() ?? null;let orderedRefs: GalleryItemRef[] | null = null;const isDeletionContextCurrent = (): boolean => {@@ -445,15 +439,11 @@ export const useImageActions = ({? requestDeletionConfirmation(items, () => deleteItemsConfirmed(items)): deleteItemsConfirmed(items);const moveItemsToBoard = (items: GalleryItemRef[], boardId: string): Promise<void> => {- // Optimistic: the items leave the current board view immediately. A- // vanished item cannot be restored by another patch, so the failure- // path rolls the lists back wholesale and re-applies the confirmed- // subset; the trailing invalidation reconciles anything the rollback- // had to skip as conflicted. `getGalleryItemBoardIdsFromCaches` only- // sees items a list query has already fetched, so a just-generated- // image known only through the recent-image overlay would otherwise- // have no prior board to restore — read that from the store too, cache- // taking precedence where both know the item.+ // Optimistic: items leave the board view immediately, so the failure path+ // rolls back wholesale and re-applies the confirmed subset, with the+ // trailing invalidation reconciling whatever the rollback skipped as+ // conflicted. The cache only knows items a list query fetched, so prior+ // boards also come from the store, cache winning where both know.const previousBoardIds = new Map<GalleryItemKey, string>([...collectGalleryStoreKnownItemFields(queries.getSnapshot().projects, items)].map(([key, fields]) => [key,@@ -482,14 +472,11 @@ export const useImageActions = ({cachesRolledBack = true;rollbackCaches();};- // The cache rollback above is already CAS-guarded per query- // (`patchGalleryItemCaches`'s own `if (current === after)` rule), but- // the store patch below is a separate, unconditional write: a second- // move that painted this item onto yet another board while the first- // request was still hanging offline must not get clobbered back to the- // first move's prior board. Only restore items still on the board- // *this* move painted them onto, and group survivors by prior board id- // to dispatch one store patch per group instead of one per item.+ // The cache rollback is CAS-guarded per query, but this store patch is a+ // separate write: a second move that painted the item onto another board+ // while the first request hung must not be clobbered back. Restore only+ // items still on the board *this* move painted, grouped by prior board so+ // each group is one patch.const restorePreviousBoardIds = () => {const currentStoreBoardIds = collectGalleryStoreKnownItemFields(queries.getSnapshot().projects, items);const safeKeys = new Set(@@ -574,14 +561,10 @@ export const useImageActions = ({gallery.patchItems(keys, { starred });};const setItemsStarred = (items: GalleryItemRef[], starred: boolean): Promise<void> => {- // Optimistic: a star toggle's outcome is the request itself except for- // the rare rejected ref, so paint the whole selection immediately and- // flip back only what the backend refuses. The trailing gallery- // invalidation reconciles either path with the server. A total failure- // can't rely on that invalidation, so capture each item's actual prior- // flag up front (cache, falling back to the store overlay for items a- // list query hasn't fetched) — blanket-inverting the whole batch would- // wrongly flip items that already matched the target flag beforehand.+ // Optimistic: paint the whole selection and flip back only what the+ // backend refuses. A total failure cannot lean on the trailing+ // invalidation, so capture each item's actual prior flag up front — a+ // blanket invert would wrongly flip items that already matched.const previousStarred = new Map<GalleryItemKey, boolean>([...collectGalleryStoreKnownItemFields(queries.getSnapshot().projects, items)].map(([key, fields]) => [key,@@ -600,15 +583,11 @@ export const useImageActions = ({applyConfirmed: (result) => patchItemsStarred(result.failed, !starred),mutate: (signal) => galleryItemOrganization.setStarred(items, starred, signal),requested: items,- // Total failure: nothing was confirmed. Restore each item to its- // actual prior flag rather than blanket-inverting the batch. An item- // with no known prior flag is left as painted — there's nothing safe- // to revert it to. Unlike the cache half of delete/move,- // `patchGalleryItemCaches` here is a fresh forward patch with no- // built-in CAS of its own (star's optimistic apply is a value flip,- // not a snapshot/restore pair) — so both the cache and the store- // writes need their own "still painted, nothing moved on" check- // before a concurrent single-item toggle gets clobbered.+ // Total failure: restore each item's actual prior flag, leaving items+ // with no known prior as painted. Star's optimistic apply is a value+ // flip rather than a snapshot/restore pair, so unlike delete/move the+ // patch carries no CAS of its own — both the cache and store writes+ // need their own "still painted" check.rollback: () => {const requestedKeys = items.map(toGalleryItemKey);const currentCacheStarred = getGalleryItemStarredFromCaches(queryClient, items);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsxindex 00f3e722f2..5d369bf82c 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx@@ -12,16 +12,14 @@ import { TopbarProgressRail } from './TopbarProgressRail';/*** 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.+ * Three columns, not a flex row: the `1fr` sides keep the preset strip+ * geometrically centred whatever the project name's length, where flex would+ * shift it on every project switch — highly visible on an always-on-screen bar.+ * `minmax(0, 1fr)` so the left column truncates instead of widening the grid.*- * 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).+ * Zones degrade from the left: labels, then the project name, before anything in+ * the invocation cluster gives way. The routing indicator and queue readout+ * never collapse at any width (§10).*/const TOPBAR_COLUMNS = 'minmax(0, 1fr) auto minmax(0, 1fr)';diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopbarProgressRail.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopbarProgressRail.tsxindex 3a82d1a575..68872e3b20 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopbarProgressRail.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopbarProgressRail.tsx@@ -14,27 +14,21 @@ import { useActiveProjectSelector, useWorkbenchSelector } from '@workbench/Workbimport { useMemo } from 'react';/**- * The application's primary generation indicator: a hairline that lights up- * along the whole bottom edge of the top bar while work is in flight.+ * The primary generation indicator: a hairline lighting up along the top bar's+ * bottom edge while work is in flight.*- * Everything else that shows progress — the Invoke icon ring, the queue- * readout, the preview overlay, the gallery placeholders — is small, and most- * of it only exists if the user happens to have that widget on screen. A rail- * spanning the viewport is detectable without being looked at, and it is- * present in every layout, which is what the legacy bar under the Invoke button- * had and this app lost.+ * Every other progress surface is small and most only exists if that widget is+ * on screen. A rail spanning the viewport is detectable without being looked+ * at, and it is present in every layout.*- * It sits *over* the top bar's 1px divider rather than below it, so appearing- * and disappearing costs no reflow and reads as the existing line lighting up- * rather than as a new element shoving the workspace down.+ * It sits *over* the 1px divider rather than below it, so appearing costs no+ * reflow and reads as the existing line lighting up.*- * Sessions divide the width instead of stacking: a 2px rail cannot stack to- * four GPUs without either growing into the workspace or shrinking below- * visibility, and side-by-side segments filling in parallel say "four things are- * running" at a glance.+ * Sessions divide the width instead of stacking — 2px cannot stack to four GPUs+ * without growing into the workspace or dropping below visibility.*- * Not exposed to assistive tech — the queue cluster already owns a throttled- * live region for this, and a second announcer would only double the chatter.+ * Not exposed to assistive tech: the queue cluster already owns a throttled+ * live region, and a second announcer would double the chatter.*/const RAIL_SX: SystemStyleObject = {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex d68c6306cf..0f1b662d6e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -180,18 +180,14 @@ interface LayerMenuProps {}/**- * The shared layer context menu — ONE source of truth for the per-layer items and- * their handlers, used by both the layers panel (a ⋯ trigger button) and the- * canvas surface (right-click, anchored at the cursor). All actions operate on- * `layer.id`, so they behave identically from either surface.+ * The shared layer context menu: one source of truth for the per-layer items,+ * used by both the layers panel (⋯ trigger) and the canvas surface (right-click).+ * All actions operate on `layer.id`, so they behave identically from either.*- * Legacy-parity items (scoped to what webv2 supports today): rename, duplicate,- * rasterize, raster↔control convert, group-aware z-arrange (move to front /- * forward / backward / to back — within the layer's type group), merge-down,- * visibility + lock toggles, and delete. Merge-down uses global z-adjacency- * (compositing order); the arrange actions map to a splice inside the global array.+ * Arrange actions are group-aware (within the layer's type group) and map to a+ * splice inside the global array, while merge-down uses global z-adjacency.*- * Sibling dialogs live beside `Menu.Root` (not inside its portal) so they+ * Sibling dialogs live beside `Menu.Root` rather than inside its portal, so they* survive the menu closing after their action is chosen.*/const LayerMenu = ({diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsxindex 744432907d..02eafcc30a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsx@@ -3,14 +3,13 @@ import type { Ref } from 'react';import { Box, Flex, type BoxProps, type FlexProps, type SystemStyleObject } from '@chakra-ui/react';/**- * The two pieces of chrome every preview surface shares, extracted so the- * image, video, live, and empty branches stop carrying their own copies:+ * The chrome every preview surface shares, so the image, video, live, and empty+ * branches stop carrying their own copies:*- * - `PreviewStage` — the dot-grid floor. Centers its content, establishes the- * size container that `getFittedFrameCss` measures against, and reserves top- * clearance for the centre region's floating chrome islands.- * - `FittedFrame` — the media card: aspect-fitted, bordered, rounded, with the- * deep drop shadow that lifts it off the grid.+ * - `PreviewStage` — the dot-grid floor. Centres content, is the size container+ * `getFittedFrameCss` measures against, and reserves top clearance for the+ * centre region's floating islands.+ * - `FittedFrame` — the media card: aspect-fitted, bordered, shadowed.*/export const previewGridCss = {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.tsindex 2f8762e8d3..aa610f3669 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts@@ -237,17 +237,14 @@ export const usePreviewNavigation = ({[queueItems]);const navigationLocalItems = useMemo(() => {- // recentImages exists precisely to bridge the gap between "generation- // finished" and "the backend list has the row" — the refetch is coalesced- // and takes time, and dropping a completed batch from the merge for that- // window made arrow keys skip the images just generated. So local items- // stay in the sequence unconditionally, with two exceptions where the- // backend window is a *subset* of the board and the dedupe cannot save us:- // under an active search (the backend list is search-filtered, local items- // are not) and in paginated mode (the window anchors mid-board, so settled- // recents from the board's top would splice in permanently — the gallery- // grid guards this the same way via `shouldOverlayRecentItems`). There,- // only in-flight work and the selected item itself may merge.+ // recentImages bridges "generation finished" to "the backend list has the+ // row"; dropping a completed batch during that window made arrow keys skip+ // the images just generated. So local items stay unconditionally, except+ // where the backend window is a *subset* of the board and dedupe cannot+ // help: an active search (backend-filtered, local items are not) and+ // paginated mode (the window anchors mid-board, so settled recents would+ // splice in permanently). There, only in-flight work and the selection+ // merge.const hasActiveSearch =!shouldFollowLive && (selectedImageSearch.text.trim() !== '' || selectedImageSearch.range !== undefined);const isPaginatedWindow = !shouldFollowLive && selectedImageQuery.paginationMode === 'paginated';diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex fa1ca98ae6..6df961f90e 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -517,50 +517,6 @@ describe('workbench widget region defaults', () => {]);});- it('leaves a floated queue-status floating instead of re-docking it every load', () => {- // A rail whose queue-status was floated back out is byte-identical to the- // pre-branch default, so the migration re-adds it. Reconciliation runs on- // the migration's output and must win, or the widget re-docks on every- // reload and the layout reads as permanently drifted.- const initial = createInitialWorkbenchState();- const migrated = workbenchReducer(initial, {- state: {- ...initial,- projects: initial.projects.map((project) => ({- ...project,- floatingWidgets: {- 'queue-status': {- heightPx: 180,- mode: 'windowed',- returnIndex: 1,- returnRegion: 'bottom',- stackOrder: 1,- widthPx: 320,- x: 64,- y: 64,- },- },- widgetRegions: {- ...project.widgetRegions,- bottom: {- ...project.widgetRegions.bottom,- instanceIds: ['server-status', 'gallery:bottom', 'notifications', 'autosave-status'],- },- },- })),- },- type: 'hydrateWorkbench',- });-- expect(getActiveProject(migrated).widgetRegions.bottom.instanceIds).toEqual([- 'server-status',- 'gallery:bottom',- 'notifications',- 'autosave-status',- ]);- expect(getActiveProject(migrated).floatingWidgets?.['queue-status']?.returnRegion).toBe('bottom');- });-it('migrates a legacy Upscale prompt only when Generate has no prompt content', () => {const initial = createInitialWorkbenchState();const withPrompts = (generatePrompt: string): WorkbenchState => ({diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex a528315b2a..acb43c5a2d 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -1408,13 +1408,6 @@ const isFloatingWidgetMode = (value: unknown): value is FloatingWidgetMode =>const isWidgetRegionId = (value: unknown): value is WidgetRegion => WIDGET_REGION_IDS.includes(value as WidgetRegion);-/**- * Persisted floating windows are an unsafe-cast boundary like every other- * sub-shape here. An entry naming a region that does not exist crashes the- * reducer the moment it is docked, and a non-numeric geometry reaches the- * window's fixed-position CSS, so anything malformed is dropped rather than- * carried: the widget then reappears docked instead of not at all.- *//*** Put a docking widget back where it was, not on the end.*@@ -1439,6 +1432,13 @@ const insertAtReturnIndex = (return next;};+/**+ * Persisted floating windows are an unsafe-cast boundary like every other+ * sub-shape here: an entry naming a region that does not exist crashes the+ * reducer the moment it is docked, and non-numeric geometry reaches the+ * window's fixed-position CSS. Anything malformed is dropped, so the widget+ * reappears docked rather than not at all.+ */const normalizeFloatingWidgets = (value: unknown,widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>@@ -1676,19 +1676,16 @@ export const withAuthoritativeProjectBoard = (project: Project, boardId: string)/*** The project a recovery fork should become, preferring live content over the snapshot.*- * A fork is created by the sync engine from the document it was *pushing* — serialized when the- * save began. By the time the answer comes back, anything typed since is newer than that snapshot- * and is what the person is looking at. Adopting the snapshot would therefore delete precisely the- * edits the fork exists to rescue, and do it in the case the mechanism is most likely to fire: a- * save is stale exactly when a keystroke landed while it was in flight.+ * The fork is serialized when the save begins, so anything typed since is newer than it. Adopting+ * the snapshot would delete precisely the edits the fork exists to rescue, in the case the+ * mechanism most often fires: a save is stale exactly when a keystroke landed mid-flight.** So the live project is re-labelled instead. The server-side fork already holds the older document- * under this identity, and the sync entry recorded for it says as much, so the next push sees a- * difference and sends the current content up its revision chain. Nothing is lost and nothing has- * to be merged.+ * under this identity, so the next push sees a difference and sends the current content up its+ * revision chain — nothing lost, nothing to merge.*- * The snapshot is still the answer when there is no live project — a tab closed while the save was- * in flight — because then it is the only copy of that work left anywhere local.+ * The snapshot still wins when there is no live project (a tab closed mid-save), because then it is+ * the only local copy of that work.*/const recoverProjectUnderNewIdentity = (localProject: Project | undefined,