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): trim narrative comments
Josh Corbett3b2c53008e54
diff --git a/invokeai/frontend/webv2/.oxlintrc.json b/invokeai/frontend/webv2/.oxlintrc.jsonindex 4d3180a47b..9286dc94b0 100644--- a/invokeai/frontend/webv2/.oxlintrc.json+++ b/invokeai/frontend/webv2/.oxlintrc.json@@ -33,13 +33,6 @@"radix": "error","no-restricted-exports": "error",- // "eslint/complexity": [- // "error",- // {- // "max": 3- // }- // ],-"react/jsx-curly-brace-presence": ["error",{@@ -53,13 +46,8 @@"react/jsx-no-useless-fragment": "error","react/exhaustive-deps": "error",- // React Compiler diagnostics, split per category since oxlint 1.79.- // Left off: `todo` (dynamic import / try-finally merely skip optimization),- // `rule-suppression` (would flag every suppression below),- // `exhaustive-effect-dependencies` and `memo-dependencies` (this codebase- // deliberately lists identity-trigger deps next to useEffectEvent and- // ref-only closures; `react/exhaustive-deps` above stays the dependency- // gate).+ // Omit optimization-only todo and suppression diagnostics. Identity-trigger/ref-only dependencies use+ // react/exhaustive-deps rather than compiler dependency rules."react/capitalized-calls": "error","react/error-boundaries": "error","react/globals": "error",@@ -82,11 +70,8 @@"react-hooks/exhaustive-deps": "error","react-hooks/rules-of-hooks": "error",- // Invoke's Chakra/Ark composites deliberately use ARIA listbox, option,- // separator, and status semantics on polymorphic primitives. Replacing- // those primitives with the rule's suggested native tags would break the- // owning composite's keyboard/focus contract; Axe journeys validate the- // resulting accessibility tree instead.+ // Chakra/Ark polymorphic composites own keyboard semantics; native-tag substitutions can break them. Axe+ // checks the resulting tree."jsx-a11y/prefer-tag-over-role": "off","react-perf/jsx-no-new-object-as-prop": [@@ -147,9 +132,7 @@},"overrides": [{- // These are focus-managed entry points. Autofocus is intentional and- // scoped to an opened dialog, an auth screen, or an inline rename so- // keyboard users land on the only immediate task.+ // Allow scoped autofocus for task-entry dialogs, authentication, and inline rename."files": ["src/features/gallery/ui/GalleryBoardMenu.tsx","src/features/identity/ui/LoginScreen.tsx",@@ -166,9 +149,8 @@}},{- // Oxlint cannot see the focusable DOM produced by Chakra Button/Input/- // Menu primitives. Palette options are the other intentional case:- // focus stays on their aria-activedescendant combobox by design.+ // Chakra primitives supply focusable DOM; palette options retain focus on the aria-activedescendant+ // combobox."files": ["src/features/models/ui/components/ModelSelect.tsx","src/features/models/ui/shared/ModelFilterMenu.tsx",diff --git a/invokeai/frontend/webv2/index.html b/invokeai/frontend/webv2/index.htmlindex ad2393cdd2..87c2ce44e3 100644--- a/invokeai/frontend/webv2/index.html+++ b/invokeai/frontend/webv2/index.html@@ -8,10 +8,7 @@<link rel="icon" href="./invoke-icon.svg" type="image/svg+xml" /><link rel="manifest" href="./manifest.webmanifest" /><script>- // Apply the saved theme before first paint so non-default themes don't- // flash the default dark surfaces. ThemeController re-applies it on mount.- // The theme hint key is user-agnostic (the workbench snapshot is per-user- // on multi-user backends); the snapshot read is a legacy fallback.+ // Apply account-independent appearance hints before paint; use the legacy snapshot only as fallback.(function () {try {var themeColorSchemes = {diff --git a/invokeai/frontend/webv2/patches/react-hook-tanstack-virtual.patch b/invokeai/frontend/webv2/patches/react-hook-tanstack-virtual.patchindex 31b3710594..ca01485a9f 100644--- a/invokeai/frontend/webv2/patches/react-hook-tanstack-virtual.patch+++ b/invokeai/frontend/webv2/patches/react-hook-tanstack-virtual.patch@@ -11,7 +11,7 @@ diff --git a/dist/useVirtualizerBase-K4A1fZan.cjs b/dist/useVirtualizerBase-K4A1index 69494e5c083f991a4b7417cd2b6a216be3bf00e6..df02f4d2032b807b6b2c2fc3881051254a55fb71 100644--- a/dist/useVirtualizerBase-K4A1fZan.cjs+++ b/dist/useVirtualizerBase-K4A1fZan.cjs-@@ -1 +1 @@+@@ -1,1 +1,1 @@-var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("@tanstack/virtual-core"),l=require("react");l=s(l,1);let u=require("react-dom");const d=(e,...t)=>e,f=(e,t)=>{if(e.size!==t.size)return!1;for(let[n,r]of e){let e=t.get(n);if(r!==e||!Object.is(r,e))return!1}return!0},p=(e,t)=>{if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0},m=(e,t)=>{if(e===t||Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Map&&t instanceof Map)return f(e,t);if(e instanceof Set&&t instanceof Set)return p(e,t);let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r of n){if(!Object.hasOwn(t,r))return!1;let{[r]:n}=e,{[r]:i}=t;if(n!==i||!Object.is(n,i))return!1}return!0},h=typeof document<`u`?l.useLayoutEffect:()=>{},g=e=>{let[t,n]=(0,l.useState)(e);return m(t,e)||n(e),t};let _=1,v=!1;const y=new Map,b=({callback:e,args:t})=>e.apply(void 0,t),x=e=>{if(v){C(x,e);return}let t=y.get(e);if(t){v=!0;try{b(t)}finally{w(e),v=!1}}},S=`scheduler`in globalThis?{setImmediate:(e,...t)=>{let n=_++;return y.set(n,{callback:e,args:t}),scheduler.postTask(()=>x(n),{priority:`user-blocking`}),n},clearImmediate:e=>{y.delete(e)}}:(()=>{let e=new MessageChannel;e.port1.onmessage=function(e){let t=e.data;x(t)};let t=e.port2;return{setImmediate:(e,...n)=>{let r=_++;return y.set(r,{callback:e,args:n}),t.postMessage(r),r},clearImmediate:e=>{y.delete(e)}}})(),C=S.setImmediate,w=S.clearImmediate;let T=1;const E=new Map,D=({callback:e,args:t})=>e.apply(void 0,t),O=e=>{let t=E.get(e);if(t)try{D(t)}finally{A(e)}},k=(e,...t)=>{let n=T++;return E.set(n,{callback:e,args:t}),requestAnimationFrame(()=>C(()=>O(n))),n},A=e=>{E.delete(e)};function j(e){let[t,n]=(0,l.useState)(e);return[t,(0,l.useCallback)(e=>(n(e),()=>{n(null)}),[])]}const M=({getVirtualItems:e,getVirtualIndexes:t,getTotalSize:n,...r})=>({...r,virtualItems:e(),virtualIndexes:t(),totalSize:n()}),N=({options:e,virtualIndexes:t,virtualItems:n,...r},{options:i,virtualIndexes:a,virtualItems:o,...s})=>m(e,i)&&m(t,a)&&m(n,o)&&m(r,s),P=({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n=`transform`,...r},i=d,a=m)=>{"use no memo";let o=g(r),{horizontal:s=!1,scrollMargin:f=0}=o,p=s?`width`:`height`,_=n===`transform`,[v,y]=(0,l.useState)(null),[b,x]=j(null),[S]=(0,l.useState)(()=>new WeakMap),[C]=(0,l.useState)(()=>new WeakMap),[w]=(0,l.useState)(()=>new c.Virtualizer(o)),T=(0,l.useMemo)(()=>Object.assign(w,{containerRef:x}),[w,x]);h(()=>{if(!t||!b||v==null)return;let e=``,n=k(()=>{e=b.style.getPropertyValue(p),n=requestAnimationFrame(()=>{b.style.setProperty(p,`${v}px`)})});return()=>{y(null),cancelAnimationFrame(n),A(n),requestAnimationFrame(()=>{b?.style.setProperty(p,e)})}},[p,b,t,v]),h(()=>{if(!(!t||!b))return()=>{requestAnimationFrame(()=>{let e=T.getVirtualItems();for(let t of e){let e=T.elementsCache.get(t.key);if(!e)continue;S.delete(e);let n=C.get(e);n!=null&&(C.delete(e),_?e.style.setProperty(`transform`,n):e.style.setProperty(p,n))}})}},[p,b,t,T,S,C,_]);let E=(0,l.useRef)({hasValue:!1,value:null}),[D]=(0,l.useState)(()=>new Set),O=(0,l.useCallback)(e=>(D.add(e),()=>{D.delete(e)}),[D]),P=(0,l.useMemo)(()=>{let e=!1,t,n;return()=>{let r=M(T);if(!e){e=!0,t=r;let o=i(r,T);if(E.current.hasValue){let e=E.current.value;if(a(e,o))return n=e,e}return n=o,o}let o=t,s=n;if(N(o,r))return s;let c=i(r,T);return a!==void 0&&a(s,c)?(t=r,s):(t=r,n=c,c)}},[i,a,T]),F=(0,l.useCallback)(e=>{if(!t||!b)return;y(e.getTotalSize());let n=e.getVirtualItems();for(let t of n){let n=t.start-f,r=e.elementsCache.get(t.key);r&&S.get(r)!==n&&(C.has(r)||(_?C.set(r,r.style.getPropertyValue(`transform`)):C.set(r,r.style.getPropertyValue(p))),S.set(r,n),_?r.style.setProperty(`transform`,s?`translate3d(${n}px, 0, 0)`:`translate3d(0, ${n}px, 0)`):r.style.setProperty(p,`${n}px`))}},[p,b,t,s,S,C,f,_]),I=(0,l.useCallback)((t,n)=>{if(F(t),e&&n)(0,u.flushSync)(()=>{for(let e of D)e()});else for(let e of D)e();o.onChange?.call(void 0,t,n)},[F,D,o.onChange,e]),L=(0,l.useMemo)(()=>({...o,onChange:I}),[I,o]);h(()=>{T.setOptions(L)},[T,L]),h(()=>T._didMount(),[T]),h(()=>T._willUpdate()),h(()=>{F(T)});let R=(0,l.useSyncExternalStore)(O,P);return(0,l.useInsertionEffect)(()=>{E.current.hasValue=!0,E.current.value=R},[R]),R};Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return P}});\ No newline at end of file+var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("@tanstack/virtual-core"),l=require("react");l=s(l,1);let u=require("react-dom");const d=(e,...t)=>e,f=(e,t)=>{if(e.size!==t.size)return!1;for(let[n,r]of e){let e=t.get(n);if(r!==e||!Object.is(r,e))return!1}return!0},p=(e,t)=>{if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0},m=(e,t)=>{if(e===t||Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Map&&t instanceof Map)return f(e,t);if(e instanceof Set&&t instanceof Set)return p(e,t);let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r of n){if(!Object.hasOwn(t,r))return!1;let{[r]:n}=e,{[r]:i}=t;if(n!==i||!Object.is(n,i))return!1}return!0},h=typeof document<`u`?l.useLayoutEffect:()=>{},g=e=>{let[t,n]=(0,l.useState)(e);return m(t,e)||n(e),t};let _=1,v=!1;const y=new Map,b=({callback:e,args:t})=>e.apply(void 0,t),x=e=>{if(v){C(x,e);return}let t=y.get(e);if(t){v=!0;try{b(t)}finally{w(e),v=!1}}},S=`scheduler`in globalThis?{setImmediate:(e,...t)=>{let n=_++;return y.set(n,{callback:e,args:t}),scheduler.postTask(()=>x(n),{priority:`user-blocking`}),n},clearImmediate:e=>{y.delete(e)}}:(()=>{let e=new MessageChannel;e.port1.onmessage=function(e){let t=e.data;x(t)};let t=e.port2;return{setImmediate:(e,...n)=>{let r=_++;return y.set(r,{callback:e,args:n}),t.postMessage(r),r},clearImmediate:e=>{y.delete(e)}}})(),C=S.setImmediate,w=S.clearImmediate;let T=1;const E=new Map,D=({callback:e,args:t})=>e.apply(void 0,t),O=e=>{let t=E.get(e);if(t)try{D(t)}finally{A(e)}},k=(e,...t)=>{let n=T++;return E.set(n,{callback:e,args:t}),requestAnimationFrame(()=>C(()=>O(n))),n},A=e=>{E.delete(e)};function j(e){let[t,n]=(0,l.useState)(e);return[t,(0,l.useCallback)(e=>(n(e),()=>{n(null)}),[])]}const M=({getVirtualItems:e,getVirtualIndexes:t,getTotalSize:n,...r})=>({...r,virtualItems:e(),virtualIndexes:t(),totalSize:n()}),N=({options:e,virtualIndexes:t,virtualItems:n,...r},{options:i,virtualIndexes:a,virtualItems:o,...s})=>m(e,i)&&m(t,a)&&m(n,o)&&m(r,s),P=({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n=`transform`,...r},i=d,a=m)=>{"use no memo";let o=g(r),{horizontal:s=!1,scrollMargin:f=0}=o,p=s?`width`:`height`,_=n===`transform`,[v,y]=(0,l.useState)(null),[b,x]=j(null),[S]=(0,l.useState)(()=>new WeakMap),[C]=(0,l.useState)(()=>new WeakMap),[w]=(0,l.useState)(()=>new c.Virtualizer(o)),T=(0,l.useMemo)(()=>Object.assign(w,{containerRef:x}),[w,x]);h(()=>{if(!t||!b||v==null)return;let e=``,n=k(()=>{e=b.style.getPropertyValue(p),n=requestAnimationFrame(()=>{b.style.setProperty(p,`${v}px`)})});return()=>{y(null),cancelAnimationFrame(n),A(n),requestAnimationFrame(()=>{b?.style.setProperty(p,e)})}},[p,b,t,v]),h(()=>{if(!(!t||!b))return()=>{requestAnimationFrame(()=>{let e=T.getVirtualItems();for(let t of e){let e=T.elementsCache.get(t.key);if(!e)continue;S.delete(e);let n=C.get(e);n!=null&&(C.delete(e),_?e.style.setProperty(`transform`,n):e.style.setProperty(p,n))}})}},[p,b,t,T,S,C,_]);let E=(0,l.useRef)({hasValue:!1,value:null}),[D]=(0,l.useState)(()=>new Set),O=(0,l.useCallback)(e=>(D.add(e),()=>{D.delete(e)}),[D]),P=(0,l.useMemo)(()=>{let e=!1,t,n;return()=>{let r=M(T);if(!e){e=!0,t=r;let o=i(r,T);if(E.current.hasValue){let e=E.current.value;if(a(e,o))return n=e,e}return n=o,o}let o=t,s=n;if(N(o,r))return s;let c=i(r,T);return a!==void 0&&a(s,c)?(t=r,s):(t=r,n=c,c)}},[i,a,T]),F=(0,l.useCallback)(e=>{if(!t||!b)return;y(e.getTotalSize());let n=e.getVirtualItems();for(let t of n){let n=t.start-f,r=e.elementsCache.get(t.key);r&&S.get(r)!==n&&(C.has(r)||(_?C.set(r,r.style.getPropertyValue(`transform`)):C.set(r,r.style.getPropertyValue(p))),S.set(r,n),_?r.style.setProperty(`transform`,s?`translate3d(${n}px, 0, 0)`:`translate3d(0, ${n}px, 0)`):r.style.setProperty(p,`${n}px`))}},[p,b,t,s,S,C,f,_]),I=(0,l.useCallback)((t,n)=>{if(F(t),e&&n)(0,u.flushSync)(()=>{for(let e of D)e()});else for(let e of D)e();o.onChange?.call(void 0,t,n)},[F,D,o.onChange,e]),L=(0,l.useMemo)(()=>({...o,onChange:I}),[I,o]);h(()=>{T.setOptions(L),T.maybeNotify()},[T,L]),h(()=>T._didMount(),[T]),h(()=>{const e=T._willUpdate(),t=T.scrollElement;if(t&&`scrollTop`in t&&!T.isScrolling){const e=T.options.horizontal?t.scrollLeft*(T.options.isRtl?-1:1):t.scrollTop;T.scrollOffset!==null&&Math.abs(T.scrollOffset-e)>1&&(T.scrollOffset=e,T.scrollAdjustments=0,T.maybeNotify())}return e}),h(()=>{F(T)});let R=(0,l.useSyncExternalStore)(O,P);return(0,l.useInsertionEffect)(()=>{E.current.hasValue=!0,E.current.value=R},[R]),R};Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return P}});@@ -20,15 +20,12 @@ diff --git a/src/lib/useVirtualizerBase.ts b/src/lib/useVirtualizerBase.tsindex 59f46c47fe9bf8c09b482e110a623fbff5e65da3..1cb263dbc0c5f39c30f380886b4a7c19d6cee1b5 100644--- a/src/lib/useVirtualizerBase.ts+++ b/src/lib/useVirtualizerBase.ts-@@ -364,14 +364,61 @@ export const useVirtualizerBase = <+@@ -364,14 +364,42 @@ export const useVirtualizerBase = <useLayoutEffect(() => {instance.setOptions(resolvedOptions)-+ // Patched (InvokeAI): virtual-core's setOptions never notifies, so an-+ // option change that alters the range (e.g. `count` growing) left-+ // useSyncExternalStore serving the stale snapshot until the next-+ // scroll/resize/measure notification. maybeNotify recalculates the-+ // range and notifies exactly when it changed — a no-op otherwise.++ // InvokeAI patch: notify after setOptions because range changes otherwise leave the external-++ // store snapshot stale.+ ;(instance as unknown as { maybeNotify: () => void }).maybeNotify()}, [instance, resolvedOptions])@@ -36,17 +33,8 @@ index 59f46c47fe9bf8c09b482e110a623fbff5e65da3..1cb263dbc0c5f39c30f380886b4a7c19return instance._didMount()}, [instance])-+ // Patched (InvokeAI): the browser can move an element's scroll position-+ // WITHOUT firing a scroll event — most importantly by clamping scrollTop-+ // when the content shrinks (a list swapping to far fewer rows), including-+ // right after virtual-core restores the cached offset onto a freshly-+ // remounted scroll element. virtual-core never reads the position back,-+ // so it kept serving the range computed at the stale offset — with the-+ // range clamped to the LAST item, rendered far below the viewport: a-+ // blank list until the first real scroll event. Reconcile the cached-+ // offset with the element's actual position after every commit; guarded-+ // to a real divergence outside active scrolling, so it is a no-op on-+ // every normal render and never fights live scroll events.++ // InvokeAI patch: reconcile actual offset after commits when not scrolling; content shrink/remount++ // can clamp position without a scroll event.useLayoutEffect(() => {- return instance._willUpdate()+ const result = instance._willUpdate()@@ -68,15 +56,8 @@ index 59f46c47fe9bf8c09b482e110a623fbff5e65da3..1cb263dbc0c5f39c30f380886b4a7c19+ instance.scrollOffset = actualOffset+ mutable.scrollAdjustments = 0+ mutable.maybeNotify()-+ // `_intendedScrollOffset` is deliberately LEFT ALONE. virtual-core's-+ // offset observer ignores an incoming scroll event when-+ // `isScrolling && _intendedScrollOffset === null && offset ===-+ // scrollOffset` — a guard whose whole purpose is to let a-+ // programmatic scroll's own event through. Clearing it here while-+ // also writing scrollOffset satisfies all three conditions, so every-+ // scrollToIndex would swallow its own event and leave `isScrolling`-+ // false and `scrollDirection` stale, which in turn misdirects dynamic-+ // re-measurement. Left set, the next real event clears it itself.++ // Preserve _intendedScrollOffset until its real event arrives; clearing it while++ // updating scrollOffset suppresses programmatic scroll notifications.+ }+ }+ return resultdiff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yamlindex 47d868b650..48d454ecb3 100644--- a/invokeai/frontend/webv2/pnpm-lock.yaml+++ b/invokeai/frontend/webv2/pnpm-lock.yaml@@ -6,7 +6,7 @@ settings:patchedDependencies:react-hook-tanstack-virtual:- hash: b6a17ea8d00a392cd605ab76cfed12fb181d6230d3187ad063c9053e0da05b79+ hash: 2d69c3f291348e61b3d4e3f96732527872259fee1c4df92376fff4ebc8432072path: patches/react-hook-tanstack-virtual.patchimporters:@@ -81,7 +81,7 @@ importers:version: 19.3.0([email protected])react-hook-tanstack-virtual:specifier: ^0.0.4- version: 0.0.4(patch_hash=b6a17ea8d00a392cd605ab76cfed12fb181d6230d3187ad063c9053e0da05b79)(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@tanstack/[email protected])([email protected]([email protected]))([email protected])+ version: 0.0.4(patch_hash=2d69c3f291348e61b3d4e3f96732527872259fee1c4df92376fff4ebc8432072)(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@tanstack/[email protected])([email protected]([email protected]))([email protected])react-i18next:specifier: ^17.0.14version: 17.0.14([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])@@ -3896,7 +3896,7 @@ snapshots:react: 19.3.0scheduler: 0.28.0- [email protected](patch_hash=b6a17ea8d00a392cd605ab76cfed12fb181d6230d3187ad063c9053e0da05b79)(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@tanstack/[email protected])([email protected]([email protected]))([email protected]):+ [email protected](patch_hash=2d69c3f291348e61b3d4e3f96732527872259fee1c4df92376fff4ebc8432072)(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@tanstack/[email protected])([email protected]([email protected]))([email protected]):dependencies:'@tanstack/virtual-core': 3.17.11diff --git a/invokeai/frontend/webv2/scripts/browser-test-console.ts b/invokeai/frontend/webv2/scripts/browser-test-console.tsindex 2331bd138e..17f574b420 100644--- a/invokeai/frontend/webv2/scripts/browser-test-console.ts+++ b/invokeai/frontend/webv2/scripts/browser-test-console.ts@@ -1,18 +1,7 @@/* eslint-disable no-console -- this module exists to intercept and re-emit console output */import { afterAll, beforeAll } from 'vitest';-/**- * Collapses React's "not wrapped in act(...)" warning in browser runs.- *- * The warning is ~10 lines of identical boilerplate and fires once per unwrapped update, so a full- * run emitted over a thousand copies of the same text -- enough to bury the actual failure at the- * bottom of a CI log. Nearly all of them come from third-party components whose resize-driven- * state updates we do not control (Chakra's ScrollArea is the bulk of them), so the individual- * copies carry no information a count does not.- *- * The signal is kept rather than silenced: every occurrence is counted per component and reported- * once per test file. Anything that is not this specific warning passes through untouched.- */+/** Count React act warnings per component and report once per file; preserve every other console message unchanged. */const ACT_WARNING = 'was not wrapped in act(';const COMPONENT = /An update to (\S+)/;const PLACEHOLDER = /%[sdifoOc]/g;diff --git a/invokeai/frontend/webv2/scripts/chunk-source-manifest.mjs b/invokeai/frontend/webv2/scripts/chunk-source-manifest.mjsindex 957ffcd75e..a5a51b6dd5 100644--- a/invokeai/frontend/webv2/scripts/chunk-source-manifest.mjs+++ b/invokeai/frontend/webv2/scripts/chunk-source-manifest.mjs@@ -21,13 +21,8 @@ const getPackageOwner = (moduleId) => {};/**- * Converts a bundler module id into a stable ownership id.- *- * First-party modules retain their repo-relative source path. Dependency- * internals collapse to the package that owns them, so a lockfile refresh does- * not rewrite the graph merely because pnpm's content-addressed path changed.- * Virtual/runtime modules are intentionally excluded: they have no source- * owner and their emitted bytes are still covered by the outcome budgets.+ * Keep first-party paths; collapse dependencies to package IDs to ignore pnpm layout changes. Exclude ownerless+ * virtual modules; byte budgets still cover them.*/export const getModuleSourceOwner = (moduleId, projectRoot) => {if (typeof moduleId !== 'string' || moduleId.length === 0 || moduleId.startsWith(VIRTUAL_MODULE_PREFIX)) {diff --git a/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs b/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjsindex e1f1b3f257..66578ff6f5 100644--- a/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs+++ b/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs@@ -243,13 +243,7 @@ const getMaximumResourceSummary = (samples, key) =>BROWSER_RESOURCE_METRIC_KEYS.map((metric) => [metric, Math.max(...samples.map((sample) => sample[key][metric]))]));-/**- * Waits for the main thread to go quiet. A semantic-ready mark says the widget- * mounted, not that the switch finished: the away switch leaves hundreds of- * milliseconds of work behind it, and pressing the next tab straight into that- * measures the tail of the previous switch as if it belonged to the next one.- * Idle callbacks are the browser's own answer to "is anything still running".- */+/** Wait for main-thread idle between switches so the next sample excludes the previous switch's work. */const settleMainThread = (page) =>page.evaluate(() =>@@ -268,17 +262,7 @@ const settleMainThread = (page) =>}));-/**- * Measures a *repeat* layout switch: away to a second preset, then back to the- * fixture's own. Every other sample here gets a fresh context and page load and- * presses a preset tab exactly once, so `layoutSwitchMs` can only ever describe- * a cold, first switch. A return to a layout the session has already shown is- * the switch keeping widgets mounted is supposed to make near-free, and nothing- * else in this harness can see it.- *- * Runs after every resource, source-owner and timing figure has been captured,- * so the detour cannot perturb them.- */+/** Measure a warm return switch after all other samples, without perturbing their resources or timings. */const measureLayoutReturnSwitch = async (page, fixture) => {if (!fixture.layoutReturnPreset) {return 0;@@ -524,9 +508,7 @@ const runSample = async (browser, fixture, sample) => {(name) => document.querySelector('button[aria-label^="Switch project."]')?.textContent?.trim() !== name,originalProjectName);- // A new tab is server-backed on its first autosave. Let that response assign its board and- // reach a paint before timing the unrelated switch back; otherwise the sample randomly- // includes the reconciliation depending on where the 500 ms autosave lands.+ // Wait for first autosave reconciliation and paint so layout-switch timing excludes board assignment.const newProjectSaveResponse = await newProjectSave;await newProjectSaveResponse.finished();await page.evaluate(@@ -620,8 +602,7 @@ const runSample = async (browser, fixture, sample) => {}};-// The measurement is hermetic: the preview proxy targets a disposable-// in-memory mock backend, never a live InvokeAI instance with real data.+// Use only the disposable mock backend for measurements.const mockBackend = await startMockBackend(backendPort);const preview = spawnPreview({diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjsindex f06397959d..91501746ec 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs@@ -1,11 +1,4 @@-/**- * Deterministic synthetic data for browser release and performance journeys.- *- * Keep this module free of browser and server dependencies: harnesses can- * import the same builders to validate their workload without starting HTTP.- * Every generated value is derived from an index and a fixed epoch, so resets- * are byte-identical and checked-in baselines never depend on wall-clock time.- */+/** Keep builders dependency-free and derive fixtures from indices and a fixed epoch for repeatable baselines. */export const MOCK_BACKEND_PROFILE_NAMES = Object.freeze(['empty', 'representative']);@@ -54,17 +47,8 @@ export const assertMockBackendProfileName = (value) => {};/**- * What Fixture Project 002's own board holds, and what sits just outside it.- *- * The project-file journey is the only place the whole board path runs end to end, and it can only- * prove the interesting rules if the fixture actually contains them: a result the canvas draws with- * *and* the board owns (so a restore must copy it and rewrite the layer), a result the document- * never mentions (which is the entire reason `.invk` carries a board at all), assets under each- * visible category, media that must be excluded, and references that live outside the board and so- * must be deduplicated rather than copied.- *- * Every name here is an existing fixture image reassigned to the project's board — the image count- * is a pinned dimension of the representative profile, so this composition must not change it.+ * Cover board-only/shared references, visible/excluded categories, and external references. Reassign existing+ * images without changing the pinned image count.*/export const PROJECT_FILE_BOARD = Object.freeze({/** Generated, on the board, and drawn by the canvas: the overlap case. */@@ -220,8 +204,7 @@ const createVideos = () => [workflow: null,},{- // On Fixture Project 002's own board: videos are a separate namespace with their own copy and- // upload routes, so a project file that only ever carried images would prove half the path.+ // Include board-owned video to exercise its separate copy/upload routes.board_id: 'fixture-project-board-02',created_at: timestampAt(5),duration: 1,@@ -280,17 +263,9 @@ const createVideos = () => [},];-/**- * The board a project owns. Every project has exactly one, and only project APIs may rename or- * delete it — the generic board routes refuse a claimed board.- */+/** Only project APIs may rename/delete a project-owned board. */export const projectBoardId = (index) => `fixture-project-board-${ordinal(index, 2)}`;-/**- * The board owned by Fixture Project 002 — the project the project-file journey exports, imports- * and duplicates. Declared here rather than inlined so the composition above and the journey's- * assertions cannot drift from the project they describe.- */export const PROJECT_FILE_BOARD_ID = projectBoardId(1);const buildBoard = (boardId, boardName, images, videos, createdAt) => {@@ -553,11 +528,7 @@ const createProjectFileWorkflowNodes = () => {];};-/**- * The canvas leaves of a v3 document, stacks in composition order, each forest in preorder. The- * order mirrors `LAYER_STACK_ORDER` in `src/workbench/canvas-engine/contracts.ts`, which a plain- * module cannot import; keep the two in step.- */+/** Match LAYER_STACK_ORDER and preorder within each forest; plain JS cannot import the TypeScript constant. */export const collectCanvasLeaves = (document) => {const leaves = [];const visit = (nodes) => {@@ -575,10 +546,7 @@ export const collectCanvasLeaves = (document) => {return leaves;};-/**- * The representative raster forest: 64 leaves, of which 24 sit in three groups (one nested two- * deep), so the tree exercises indentation, ancestor-effective state and folder export.- */+/** Use 64 leaves, including 24 in three groups with two-level nesting, to exercise forest behavior. */const createRasterForest = (layers) => {if (layers.length < 32) {return layers;diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjsindex 52e48a0376..287220659a 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs@@ -111,9 +111,8 @@ test('Fixture Project 002 carries the image and video references used by the pro});/**- * The board path can only be proved end to end if the fixture contains the cases: an item that is- * both board membership and a canvas reference, one that is only membership, each visible category,- * the two kinds of media that must be excluded, and references that live outside the board.+ * Cover board-only and referenced media, all visible categories, exclusions, and external references in the+ * round-trip fixture.*/test('Fixture Project 002 owns a board carrying every case the project-file journey exercises', () => {const fixture = createMockBackendFixture('representative');@@ -134,8 +133,7 @@ test('Fixture Project 002 owns a board carrying every case the project-file jourPROJECT_FILE_BOARD_ID);- // The canvas draws with these, and no project owns them: on import they deduplicate against the- // destination, and on duplication they are not copied at all.+ // External references deduplicate on import and remain shared on duplication.const layerNames = collectCanvasLeaves(project.data.canvas.document).map((layer) => layer.source.image.imageName);for (const name of PROJECT_FILE_BOARD.externalImages) {@@ -185,8 +183,7 @@ test('the HTTP reset contract selects profiles explicitly and restores the startassert.deepEqual(generationDevices, [{ device: 'cpu', name: 'CPU' }]);assert.equal(images.items.length, 17);- // One of the thousand is an intermediate on Fixture Project 002's board, which every gallery- // listing hides — it exists so the project-file journey can prove it never travels.+ // One of the 1,000 fixture images is intermediate and excluded from gallery/export counts.assert.equal(images.total, 999);assert.equal(itemIds.item_ids.length, 500);assert.equal(models.models.length, 100);@@ -726,8 +723,6 @@ test('the image map serves videos only on request and keeps its two endpoints coconst imagesOnly = await getJson(backend, '/api/v1/image_map/points');const withVideos = await getJson(backend, '/api/v1/image_map/points?include_videos=true');- // The opt-in gate, which is the contract the real backend enforces: a- // client that cannot render videos must not be sent any.assert.equal(imagesOnly.points.some((point) => point.kind === 'video'),false@@ -741,16 +736,12 @@ test('the image map serves videos only on request and keeps its two endpoints coassert.equal(withVideos.point_count, withVideos.points.length);assert.equal(withVideos.points.length > imagesOnly.points.length, true);- // The client discards a label set whose projection or visible set differs- // from the points it is holding, so a mock that answers inconsistently- // silently shows an unlabelled map.+ // Labels must match the points' projection and visible set or the client discards them.const labels = await getJson(backend, '/api/v1/image_map/cluster_labels?include_videos=true');assert.equal(labels.updated_at, withVideos.updated_at);assert.equal(labels.visible_hash, withVideos.visible_hash);- // Every point names a real item of the kind it claims. Deliberately a- // video whose name is in no image: the fixtures include a video named like- // an image, and the cross-namespace assertion below needs a genuine miss.+ // Use a video name absent from images so the cross-namespace lookup genuinely misses.const imageNames = new Set(imagesOnly.points.map((point) => point.image_name));const video = withVideos.points.find((point) => point.kind === 'video' && !imageNames.has(point.image_name));assert.equal((await getJson(backend, `/api/v1/videos/i/${video.image_name}`)).video_name, video.image_name);diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjsindex 028997cdcb..618636f532 100644--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -27,14 +27,7 @@ const schemaUnsupported = (minimum, maximum) =>const clientMaximum = (value) => (Number.isInteger(value) && value >= 1 ? value : DEFAULT_CANVAS_SCHEMA_VERSION);-/**- * Disposable in-memory InvokeAI backend for browser release/performance tests.- *- * `empty` and `representative` are explicit workload profiles. A reset without- * a profile restores the profile selected at server startup; callers may switch- * deterministically with `POST /__reset?profile=representative`. No socket.io- * server is provided, so realtime transport remains stably disconnected.- */+/** In-memory test backend; no Socket.IO. POST /__reset restores the startup profile unless ?profile= overrides it. */const FIXED_EPOCH_MS = Date.parse(MOCK_BACKEND_FIXED_EPOCH);const TINY_PNG = Buffer.from(@@ -43,9 +36,7 @@ const TINY_PNG = Buffer.from();const FIXTURE_VIDEO = readFileSync(resolve(import.meta.dirname, 'mock-assets/fixture-video.mp4'));const FIXTURE_VIDEO_POSTER = readFileSync(resolve(import.meta.dirname, 'mock-assets/fixture-video.webp'));-// Served verbatim from the same file the backend pins in-// `tests/backend/architectures/test_capabilities_fixture.py`, so the journey tests exercise the-// payload the real route returns rather than a stand-in that can drift from it.+// Share the backend-pinned capabilities fixture to keep journey payloads aligned with the real API.const ARCHITECTURE_CAPABILITIES = JSON.parse(readFileSync(resolve(import.meta.dirname, '../src/features/generation/core/__fixtures__/architectureCapabilities.json'),@@ -53,14 +44,7 @@ const ARCHITECTURE_CAPABILITIES = JSON.parse());-/**- * Fault switches, orthogonal to the workload profiles.- *- * The Generate panel gates its entire form on `GET /api/v2/models/capabilities`, so its outage,- * retry and recovery states are unreachable while that route always succeeds. `POST /__faults`- * (`{"capabilities": "error" | "empty" | "ok"}`, also accepted as a query parameter) makes the- * route fail for the rest of the session; `POST /__reset` clears the faults with the state.- */+/** POST /__faults sets capabilities to error, empty, or ok until POST /__reset; independent of workload profile. */const CAPABILITY_FAULTS = new Set(['ok', 'error', 'empty']);const createFaults = () => ({ capabilities: 'ok' });@@ -69,11 +53,7 @@ const MOCK_USER_ID = 'fixture-user';const clone = (value) => structuredClone(value);-/**- * Two starter bundles, so the Launchpad's "no models installed" onboarding can- * actually be exercised. An empty response renders no call to action at all,- * which made the most important path on a fresh install unverifiable.- */+/** Starter bundles keep fresh-install onboarding reachable in journeys. */const STARTER_MODEL = {base: 'sd-1',description: 'Fixture starter model',@@ -100,8 +80,7 @@ const createState = (profile) => {return {boards: new Map(fixture.boards.map((board) => [board.board_id, clone(board)])),- // An existing account: the one-time alpha notice was dismissed already, so- // journeys and verification scripts land on the page, not a modal.+ // Dismiss the alpha notice so journeys start on the requested page.clientState: new Map([['webv2:workbench-settings', JSON.stringify({ alphaNoticeAcknowledged: true })]]),images: new Map(fixture.images.map((image) => [image.image_name, clone(image)])),models: new Map(fixture.models.map((model) => [model.key, clone(model)])),@@ -120,15 +99,7 @@ const createState = (profile) => {};};-/**- * Put media back under names a fresh state does not have, without its projects or boards.- *- * A restore has to be provably free of name adoption: board media must take a new identity even- * when the destination already holds an image with the archived name — on the same server it always- * does, and reusing it would move a stranger's picture onto the restored board. Reset alone cannot- * express that, because it clears everything, so the journey names the collisions it wants kept.- * The media lands unboarded, exactly as media whose board was deleted would.- */+/** Seed unboarded name collisions to verify imports copy board media instead of adopting existing items. */const seedCollisionMedia = (state, names) => {const source = createMockBackendFixture('representative');const requested = new Set(names);@@ -154,22 +125,10 @@ const timestamp = (state) => {return value;};-/**- * The projection's timestamp. Fixed, and deliberately NOT `timestamp(state)`:- * that advances the fixture's mutation clock on every call, so the map's two- * endpoints would answer with different `updated_at` values and the client- * would discard every cluster-label response as belonging to another- * projection — and it would drift the clock on plain GETs besides.- */+/** Keep both map endpoints on one fixed projection timestamp; timestamp(state) advances on every call. */const IMAGE_MAP_UPDATED_AT = '2026-01-01 00:00:00.000';-/**- * One map point per gallery item, at deterministic coordinates so the map is- * comparable across runs. Cluster ids are assigned round-robin rather than- * derived from position — nothing here runs DBSCAN, and the client only needs- * ids that are stable and non-empty. Videos plot beside images, which is the- * whole point of the kind field.- */+/** Use deterministic coordinates and round-robin cluster IDs; this fixture does not run clustering. */const imageMapPoints = (state, includeVideos) => {const items = [...[...state.images.keys()].map((name) => ({ kind: 'image', name })),@@ -268,8 +227,7 @@ const getOptionalBoolean = (url, name) => {return value === null ? undefined : value === 'true';};-// `media_origin` is the one metadata key the DTO surfaces (the real server projects it out-// of the metadata blob in SQL); the rest of a fixture's metadata stays behind /metadata.+// Only media_origin belongs in the DTO; other metadata is served by /metadata.const toVideoDto = (video) => ({board_id: video.board_id,created_at: video.created_at,@@ -476,10 +434,7 @@ const listVideos = (state, url) => {const projectIdForBoard = (state, boardId) =>[...state.projects.values()].find((project) => project.board_id === boardId)?.project_id ?? null;-/**- * Visible board membership, matching `GET /projects/{id}/board-snapshot`: intermediates and the- * canvas's private `other` category are excluded, and the result is sorted by kind then name.- */+/** Match /board-snapshot visibility and ordering: exclude intermediate/other items, sort by kind then name. */const boardSnapshotItems = (state, boardId) => {const visible = (category) => ['general', 'control', 'mask', 'user'].includes(category);const items = [@@ -750,11 +705,6 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {});}- // --- Image map -------------------------------------------------------- // Enough of the semantic map for the widget to render: every fixture- // item gets a point, laid out on a deterministic spiral so clusters are- // stable across runs. Videos are served only when the client asks for- // them, exactly as the backend does.if (method === 'GET' && path === '/api/v1/image_map/points') {const includeVideos = url.searchParams.get('include_videos') === 'true';const points = imageMapPoints(state, includeVideos);@@ -773,8 +723,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {if (method === 'GET' && path === '/api/v1/image_map/cluster_labels') {return json(200, {labels: { 0: { alternates: ['sunset', 'coastline'], label: 'beaches' } },- // Same value and same kind filter as /points: the client compares- // both before it will use a label set.+ // Labels must match /points on both projection timestamp and visible set.updated_at: IMAGE_MAP_UPDATED_AT,visible_hash: `visible-${String(url.searchParams.get('include_videos') === 'true')}`,});@@ -785,9 +734,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {const isVideo = url.searchParams.get('kind') === 'video';const exists = isVideo ? state.videos.has(name) : state.images.has(name);- // 404 for an item this namespace does not hold, like the real route —- // which is what lets the label cache's definitive-miss path be- // exercised against the mock at all.+ // Match the real route's 404 so tests can exercise definitive label-cache misses.if (!exists) {return json(404, { detail: 'This item has no stored embedding to label' });}@@ -840,9 +787,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {const projectNumber = state.nextProjectNumber;const name = requested.name ?? `Project Name #${projectNumber}`;- // Creating a project either adopts the board it was given or makes one. Adopting is what- // lets an import upload its media before the project exists, so that creating the project- // is the import's single commit point.+ // Adopting a prepopulated board makes project creation the import commit point.let boardId = requested.board_id ?? null;if (boardId === null) {boardId = `mock-project-board-${projectNumber}`;@@ -1127,9 +1072,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {});}- // Dynamic prompt expansion. Enough of the `{a|b}` grammar for journeys to- // exercise the preview and the batch dimension; the real generator lives- // in the backend.+ // Implements only the {a|b} subset needed by journeys.if (method === 'POST' && path === '/api/v1/utilities/dynamicprompts') {const requested = await readJsonBody(request);const prompt = typeof requested?.prompt === 'string' ? requested.prompt : '';@@ -1372,8 +1315,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {const now = timestamp(state);state.nextImageNumber += 1;- // A genuinely new identity: `board_images` keys on the name, so a copy must own its own.- // Category and provenance travel; starring does not (callers use /images/star).+ // Copies need a new board_images key; retain category/provenance, but set starring separately.state.images.set(imageName, {...clone(source),board_id: boardId,diff --git a/invokeai/frontend/webv2/scripts/performance-budgets.mjs b/invokeai/frontend/webv2/scripts/performance-budgets.mjsindex 84dec47fac..3d9e259edd 100644--- a/invokeai/frontend/webv2/scripts/performance-budgets.mjs+++ b/invokeai/frontend/webv2/scripts/performance-budgets.mjs@@ -160,23 +160,8 @@ export const validateChunkSourceManifest = (value) => {};/**- * A route's ceiling is derived from a baseline measurement rather than committed alongside it, so- * the recorded file states only what was measured and a re-record touches one number per metric.- *- * Two bounds apply and the lower wins:- *- * - The allowance, `max(1%, 4 KB)` over the higher of the reference and committed measurement.- * Re-recording the committed baseline deliberately accepts growth such as a dependency upgrade,- * even before the base branch contains it. Previously recorded higher sizes stay allowed until- * a downward re-record protects the savings. Neither allowance term works alone: 1% of- * 2 KB of CSS is 22 bytes, and a flat floor is meaningless against a 3 MB route.- * - The hard ceiling, `max(10%, 32 KB)` over the *committed* baseline. In CI the allowance is taken- * over at least the base branch's own measurement, which moves with every merge. Without this- * second bound, allowance-sized pull requests could compound without limit. The ceiling keeps- * the committed file the outer bound a person has- * reviewed, and a deliberate downward re-record takes effect on the next pull request.- *- * Request counts are capped exactly by both: an extra initial request is structural, not growth.+ * Use the lower byte bound: b + max(b × 1%, 4 KB), where b = max(reference, committed), or committed ++ * max(committed × 10%, 32 KB). The committed hard bound prevents cumulative growth; request counts remain exact.*/export const GROWTH_ALLOWANCE_PERCENT = 0.01;export const GROWTH_ALLOWANCE_FLOOR_BYTES = 4096;@@ -201,22 +186,9 @@ export const deriveLimits = (baseline, keys, committed = baseline) =>Object.fromEntries(keys.map((key) => [key, deriveLimit(key, baseline[key], committed[key])]));/**- * The base branch's own measurements, handed to a pull-request run by CI so the byte budgets are- * judged against growth main has accepted since the committed baseline was captured, while a- * higher committed baseline can explicitly accept new growth in the pull request. `sourceOwners`- * and every structural rule still come from the committed baseline, which is the deliberate record- * and is meant to keep failing until someone updates it.- *- * Each gate writes its reference file next to its report, before it checks anything, so a failing- * main still records what it measured. The file is deliberately small and versioned: it is read by- * a *different* commit's copy of these scripts, so a version or metric-set mismatch is an expected- * event that falls back to the committed baseline with the reason logged, not a wiring fault.- * A set directory that lacks the file, or a file that carries no other integer `schemaVersion` and- * is not this shape, is a wiring fault and fails with the variable and path named.- *- * Unset locally and on pushes to main. There the committed baseline is the reference, so a main- * that has outgrown the allowance since its last capture fails, which is the signal that a- * deliberate re-record is due, rather than its ceiling ratcheting up unreviewed.+ * CI references carry measurements from the base branch; committed baselines still own structural rules and hard+ * ceilings. Write references before checking. Version/metric drift falls back; missing or malformed configured+ * references fail. Without a reference, use the committed baseline.*/export const PERFORMANCE_REFERENCE_DIR_VARIABLE = 'WEBV2_PERF_REFERENCE_DIR';/** Whatever CI wants the reference called in logs and reports -- the cache key it restored. */@@ -292,8 +264,8 @@ export const referenceIncompatibility = (reference, kind, metricKeys) => {};/**- * Reads the reference CI restored. Any problem short of an expected version or metric-set drift- * is thrown with the variable and path named, so a broken restore never passes as "no reference".+ * Only expected version/metric drift may fall back; other reference errors fail with the configured variable and+ * path.*/export const loadPerformanceReference = async ({ directory, fileName, kind, metricKeys, root }) => {const path = resolve(root, directory, fileName);@@ -311,10 +283,7 @@ export const loadPerformanceReference = async ({ directory, fileName, kind, metr} catch (error) {throw new Error(`${path} is not valid JSON: ${error.message}`);}- // Judged before the shape is validated: a reference from a checkout with a different schema- // version may legitimately have a different shape, and that is the drift the fallback is for.- // Only an integer version that differs is drift; a file with no version at all was never- // written by any checkout and stays a wiring fault.+ // Check integer version drift before validating shape; a missing version is malformed, not drift.const version = parsed?.schemaVersion;if (Number.isInteger(version) && version !== PERFORMANCE_REFERENCE_SCHEMA_VERSION) {return {@@ -327,17 +296,12 @@ export const loadPerformanceReference = async ({ directory, fileName, kind, metrreturn { reason: referenceIncompatibility(reference, kind, metricKeys), reference };};-/**- * Whether a failure line is a byte or request budget being exceeded, as opposed to a source-owner- * graph or importer-count change. Only the former is answered by re-recording a baseline; for an- * owner-graph leak that advice would erase the very signal the pin exists to give.- */+/** Suggest re-recording only for resource budgets; it must not hide structural graph regressions. */export const isBudgetFailure = (message) => / reached \d+ .*\(limit /.test(message);/**- * Committed route budgets with their byte baselines replaced by the reference's, keeping the- * committed numbers alongside for the hard ceiling and for failure messages. Routes the reference- * does not cover keep the committed baseline and are reported so the log can say so.+ * Apply reference byte measurements while retaining committed ceilings; report uncovered routes and use their+ * committed baselines.*/export const applyBuildReference = (build, reference) => {if (!reference) {@@ -351,8 +315,7 @@ export const applyBuildReference = (build, reference) => {uncovered.push(routeId);return [routeId, budget];}- // A malformed route must fail here: an undefined metric would derive a NaN ceiling, and- // every comparison against NaN is false, which would wave the whole route through.+ // Reject missing metrics before deriving ceilings: comparisons against NaN would silently pass.validateMetricObject(metrics, BUILD_METRIC_KEYS, `reference build route ${routeId}`);return [diff --git a/invokeai/frontend/webv2/scripts/performance-budgets.test.mjs b/invokeai/frontend/webv2/scripts/performance-budgets.test.mjsindex 3d671ad7b3..61bfdbae83 100644--- a/invokeai/frontend/webv2/scripts/performance-budgets.test.mjs+++ b/invokeai/frontend/webv2/scripts/performance-budgets.test.mjs@@ -506,8 +506,6 @@ describe('browser performance sampling and policy', () => {describe('derived growth allowance', () => {it('absorbs ordinary growth instead of failing on a handful of bytes', () => {- // The regression this replaces: a route whose captured ceiling equalled its measurement, so- // any byte of growth failed and every PR paid a re-record for whatever main had drifted.const measurement = createSyntheticBuild(1_000);const budget = createArchitectureBaseline(measurement).build.launchpad;const grown = { ...measurement, ownedRawBytes: measurement.ownedRawBytes + 64 };@@ -533,8 +531,7 @@ describe('derived growth allowance', () => {});it('allows the floor over a zero baseline, which the exact request counts bound', () => {- // Six committed browser routes have all-zero activated resources; "zero" now means "up to the- // floor", and it is the exact request cap that keeps a new asset from arriving unnoticed.+ // Zero-byte baselines still get the byte floor; exact request caps catch new assets.assert.equal(deriveLimit('otherAssetRawBytes', 0), GROWTH_ALLOWANCE_FLOOR_BYTES);assert.equal(deriveLimit('requestCount', 0), 0);});@@ -558,8 +555,7 @@ describe('derived growth allowance', () => {describe('hard ceiling over the committed baseline', () => {it('bounds a moving reference by the committed baseline', () => {- // A run of allowance-sized merges moves the reference; the committed file must still be the- // outer bound, or the budgets would be advisory before a merge.+ // Keep the committed baseline as a hard bound so allowance-sized merges cannot compound indefinitely.const committed = 100_000;const reference = committed + HARD_CEILING_FLOOR_BYTES - 1000;@@ -598,9 +594,7 @@ describe('base-branch reference', () => {});it('judges bytes against the reference while the committed source-owner pin still fails a leak', () => {- // The committed baseline is stale by 20 KB of growth that main has already accepted. Against- // it the pull request would fail for main's drift; against the reference it answers only for- // its own bytes -- and a module that leaked into the graph still fails at zero bytes.+ // Use the reference for accepted byte drift; structural leaks must still fail at zero added bytes.const committed = createSyntheticBuild(1_000);const mainNow = {...createSyntheticBuild(21_000),@@ -675,8 +669,7 @@ describe('base-branch reference', () => {});it('is judged incompatible, not broken, when written by a checkout with a different metric set', () => {- // The reference is read by a different commit's copy of these scripts. A pull request that- // adds or removes a metric must fall back with a reason, not wedge its own CI.+ // References may come from another commit; schema or metric drift must fall back with a reason.const reference = buildReference([createSyntheticBuild(1_000)]);assert.equal(referenceIncompatibility(reference, 'build', BUILD_METRIC_KEYS), null);diff --git a/invokeai/frontend/webv2/scripts/preview-server.mjs b/invokeai/frontend/webv2/scripts/preview-server.mjsindex 1349c1617b..bfbf8dc629 100644--- a/invokeai/frontend/webv2/scripts/preview-server.mjs+++ b/invokeai/frontend/webv2/scripts/preview-server.mjs@@ -1,17 +1,6 @@/**- * The `vite preview` server the browser-driving scripts measure against.- *- * Three scripts need it — the architecture performance measurement, the accessibility journeys and- * the project-file journey — and each needs the same two things: start a preview server on a fixed- * port, and take it down again along with anything it spawned. Both halves are platform-sensitive- * in ways that are easy to get subtly wrong, so they live here once.- *- * Starting it as `pnpm exec vite preview` does not work on Windows: `pnpm` there is a `.cmd` shim,- * and Node refuses to exec one without `shell: true`. Adding a shell would start it, but it also- * puts `cmd.exe` between the script and vite — teardown signals the process it spawned, which would- * then be the shell rather than the server, leaving the port bound and the next run failing on- * `--strictPort`. Running vite's own entry under this same Node keeps the child a plain process- * everywhere and needs no shell at all.+ * Run Vite's entry directly under Node: Windows cannot exec pnpm's .cmd shim without a shell, whose PID would+ * prevent reliable server-tree teardown.*/import { spawn, spawnSync } from 'node:child_process';@@ -21,40 +10,25 @@ import process from 'node:process';const isWindows = process.platform === 'win32';-// Resolved through `package.json` rather than `vite/bin/vite.js` directly: vite's `exports` map-// does not expose the bin path, so asking for it by subpath throws ERR_PACKAGE_PATH_NOT_EXPORTED.+// Resolve via vite/package.json because the exports map hides bin/vite.js.const viteBin = join(dirname(createRequire(import.meta.url).resolve('vite/package.json')), 'bin', 'vite.js');-/**- * Start a preview server on `port`, bound to loopback and refusing to drift to another port.- *- * Every option other than `port` is passed through to `spawn`, so callers keep control of `cwd`,- * `env` and `stdio` — they differ between the three scripts.- */+/** Bind preview to a fixed loopback port; forward other options to spawn. */export const spawnPreview = ({ port, ...options }) =>spawn(process.execPath, [viteBin, 'preview', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], {- // What puts the child in its own process group, so `killPreview` can signal the whole tree.- // Windows has no process groups, and `detached` there means "own console window" instead —- // not useful, and it flashes one up on every run.+ // Use a separate POSIX process group for tree teardown; on Windows detached would open a console instead.detached: !isWindows,...options,});-/**- * Stop a preview server started by `spawnPreview`, including any child processes of its own.- *- * Throws the way `process.kill` does — notably `ESRCH` when the server has already exited, which- * callers distinguish from a real failure.- */+/** Stop the preview process tree; preserve ESRCH for callers handling an already-exited server. */export const killPreview = (pid, signal) => {if (!isWindows) {process.kill(-pid, signal);return;}- // No process groups here, so the tree walk is taskkill's `/T`. `/F` because the signal argument- // has no Windows equivalent: a graceful stop would need a console control event, which cannot be- // sent to a process that does not share this one's console.+ // Windows needs taskkill /T /F; a graceful console event is unavailable without a shared console.const result = spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' });// taskkill reports 128 for "no such process", which is what ESRCH means to every caller here.diff --git a/invokeai/frontend/webv2/scripts/preview-server.test.mjs b/invokeai/frontend/webv2/scripts/preview-server.test.mjsindex 466673c0aa..4c78e79da5 100644--- a/invokeai/frontend/webv2/scripts/preview-server.test.mjs+++ b/invokeai/frontend/webv2/scripts/preview-server.test.mjs@@ -1,13 +1,4 @@-/**- * `killPreview` has to report an already-dead process the same way on every platform.- *- * The project-file journey tears the preview down in two steps — SIGTERM, wait, SIGKILL — and lets- * `ESRCH` through as "it already exited" while rethrowing anything else. On POSIX that code comes- * from `process.kill`. On Windows there is no process group to signal, so the tree kill is- * `taskkill /T`, and its "no such process" exit status is translated by hand. A hand-written- * translation is exactly the kind of thing that stops matching when the tool changes, and the- * symptom would be a journey that fails during cleanup after passing.- */+/** Verify Windows taskkill's missing-process result maps to ESRCH, matching POSIX cleanup behavior. */import assert from 'node:assert/strict';import { spawn } from 'node:child_process';@@ -33,11 +24,9 @@ test('reports an already-exited process as ESRCH', async () => {});test('starts a preview server without a shell and stops it again', async (t) => {- // Deliberately not one of the three ports the journeys bind, so running this beside them cannot- // make either fail on `--strictPort`.+ // Use a separate port so parallel journeys cannot conflict under --strictPort.const port = 4199;- // `import.meta.dirname`, not a URL pathname: on Windows the latter is '/D:/...', which is not- // a directory any process can start in.+ // URL pathnames contain an invalid leading slash for Windows drive paths; use import.meta.dirname.const preview = spawnPreview({cwd: resolve(import.meta.dirname, '..'),port,@@ -54,8 +43,8 @@ test('starts a preview server without a shell and stops it again', async (t) =>}});- // The point of the assertion: a `.cmd` shim spawned without a shell fails here with ENOENT, which- // is what this module exists to avoid, and a shell wrapper would make `preview.pid` the shell's.+ // Verify the child is Vite itself: Windows .cmd shims fail without a shell, and shell wrappers obscure the+ // server PID.const spawned = await new Promise((resolve) => {preview.once('spawn', () => resolve(true));preview.once('error', () => resolve(false));diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjsindex b5bcd78c26..a350e550e5 100644--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs@@ -42,12 +42,8 @@ const waitForPreview = async () => {const waitForSettledDocument = async (page) => {await page.evaluate(async () => {await document.fonts.ready;- // Every audit below reads rendered appearance, and a surface still animating in composites- // its text over whatever is behind it -- a dialog caught mid fade-in audits as a contrast- // failure its palette does not have. Two frames do not cover a 200ms fade, so wait on the- // animations themselves. Mirrors `settleAnimations` in- // `src/platform/browser/settleAnimations.testing.ts`, re-expressed here because this body is- // serialised into the page and cannot import it; the two must change together.+ // Wait for animations to finish before contrast audits. Keep this serialized helper aligned with+ // settleAnimations.testing.ts.await Promise.allSettled(document.getAnimations({ subtree: true })@@ -105,12 +101,7 @@ const waitForHome = async (page) => {await page.getByText('Generate from text', { exact: true }).waitFor();};-/**- * `/projects` is the library itself, which is where the grid lives. The- * heading is matched at level 2 because the shell also renders a visually- * hidden level-1 heading naming the active section, which on this page is the- * same word.- */+/** Use the level-2 library heading; the shell has a hidden level-1 heading with the same name. */const waitForProjects = async (page) => {await page.getByRole('heading', { exact: true, level: 2, name: 'Projects' }).waitFor();await page.getByRole('link', { exact: true, name: 'Open Fixture Project 001' }).waitFor();@@ -135,18 +126,10 @@ const waitForWorkbench = async (page) => {const centerViewTrigger = (page, label) => page.getByRole('button', { exact: true, name: `Center view: ${label}` });-/**- * 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.- */+/** Preset names need not match their center views; pass the expected view explicitly. */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.- //- // Scoped to the strip: the Automate layout's workflow panel has its own "Edit"- // tab, so an unscoped tab lookup is ambiguous the moment a journey visits it.+ // Match the full preset name plus optional drift marker within the strip; custom presets and Workflow tabs can+ // share prefixes.const name = new RegExp(`^${preset}(, unsaved changes)?$`);const strip = presetStrip(page);const selected = strip.getByRole('tab', { name, selected: true });@@ -220,8 +203,6 @@ const surfaces = [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, 'Compose', 'Preview');await selectCenterView(page, 'Preview', 'Gallery');@@ -237,8 +218,7 @@ const surfaces = [await waitForWorkbench(page);await selectLayoutPreset(page, 'Automate', 'Workflow');await page.getByText('Fixture Node 001', { exact: true }).waitFor();- // The fixture starts at y=0, under the floating editor toolbar. Pan the- // graph into view before measuring its targets, just as a user would.+ // Pan the y=0 fixture clear of the floating toolbar before measuring targets.const pane = await page.locator('.react-flow__pane').boundingBox();assert.ok(pane);const x = pane.x + pane.width / 2;@@ -279,12 +259,7 @@ const runAxeSurface = async (browser, surface) => {}};-/**- * Roving-tabindex and focus-restore moves land on a later task than the key- * press that causes them, so sampling `document.activeElement` once races the- * behaviour under test. Poll to a deadline instead: the assertion is unchanged- * (focus must reach this element) but it no longer depends on scheduling.- */+/** Poll focus because roving tabindex and focus restoration run after the initiating key event. */const expectFocused = async (locator, message) => {const deadline = Date.now() + 5_000;@@ -325,8 +300,7 @@ const runKeyboardJourney = async (browser) => {const fontsTab = page.getByRole('tab', { exact: true, name: 'Fonts' });const modelsTab = page.getByRole('tab', { exact: true, name: 'Models' });- // The rail is grouped, but it is still one tablist: arrowing off the last- // Workspace tab has to land on the first Manage tab, skipping the headings.+ // Arrow navigation must cross rail groups while skipping headings.await projectsTab.focus();await projectsTab.press('ArrowDown');await expectFocused(fontsTab, 'ArrowDown should move focus from Projects to Fonts.');@@ -360,8 +334,6 @@ const runKeyboardJourney = async (browser) => {await projectLink.press('Enter');await waitForWorkbench(page);- // The center view selector is a menu button: it opens on the keyboard,- // exposes each view as a radio item, and restores focus to itself on close.const previewTrigger = centerViewTrigger(page, 'Preview');await previewTrigger.focus();@@ -452,8 +424,7 @@ const runTopbarMenuJourney = async (browser) => {try {await waitForWorkbench(page);- // The fixture routes from Workflow, but Compose does not place that widget. Open it before- // auditing a present source, then return to Preview for the missing-source checks below.+ // Open Workflow first: the fixture routes from it, but Compose does not mount it by default.await centerViewTrigger(page, 'Preview').click();await page.getByRole('menuitem', { exact: true, name: 'Workflow' }).click();await centerViewTrigger(page, 'Workflow').waitFor();@@ -661,8 +632,6 @@ 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, 'Compose', 'Preview');@@ -705,8 +674,7 @@ const runVideoPreviewJourney = async (browser) => {await page.getByText(/Duration 0:01/).waitFor();await waitForSettledDocument(page);- // Generated media has no caption track, so only this video-specific surface- // disables axe's caption rule. Every other release surface keeps it enabled.+ // Disable the caption rule only for generated video, which has no caption track.await assertNoAxeViolations(page, id, { rules: { 'video-caption': { enabled: false } } });if (pageErrors.length > 0) {@@ -720,30 +688,16 @@ const runVideoPreviewJourney = async (browser) => {};/**- * State, not nodes.- *- * The shell keeps widgets mounted across layout switches so returning to a- * preset is cheap *and* lands where you left it. Node identity is the easy half- * and the automated suites already cover it; the half that actually regressed is- * the state those nodes carry. An unconditional `fitToView()` on surface attach- * and a scroll container that stops being rendered both throw it away, and- * neither is visible to a test that asserts the element is still there.- *- * Runs the real virtualized gallery and the real canvas engine, because that is- * where the loss happens.+ * Verify retained scroll and canvas state across layout switches; mounted-node identity alone cannot detect state+ * loss.*/const runKeepAliveStateJourney = async (browser) => {const { context, page, pageErrors } = await openRepresentativePage(browser, representativeProjectPath);const id = 'workbench-keep-alive-state';/**- * Every scroll offset in the panel, in DOM order, on both axes. Restricted- * to real scroll containers — an overflow-clipped label is technically- * taller than its box and would otherwise wander into the comparison as- * noise. Both `overflowX` and `overflowY` are checked: `Scrollable`- * installs `usePreservedScrollOffset` regardless of its own `orientation`- * prop, and a horizontal-only strip like the preview filmstrip would- * otherwise never be exercised here.+ * Capture both axes of actual scroll containers; clipped text is not scroll state, and filmstrips may overflow+ * only horizontally.*/const SCROLLER_QUERY = `(element) => [...element.querySelectorAll('*')].filter((node) => {const style = getComputedStyle(node);@@ -784,10 +738,7 @@ const runKeepAliveStateJourney = async (browser) => {const galleryItems = rightPanel.getByRole('list', { exact: true, name: 'Gallery items' });await galleryItems.waitFor();- // The preview filmstrip only renders once an item is selected — with- // nothing selected the centre view is a "No gallery selection" empty- // state, filmstrip included. Use the unstarred listing: the starred strip's- // smaller navigation list fits without overflowing at this viewport.+ // Select an unstarred item so the filmstrip exists and has enough entries to overflow.await galleryItems.locator('[data-gallery-section="regular"]').getByRole('button', { name: /for preview$/ })@@ -802,15 +753,8 @@ const runKeepAliveStateJourney = async (browser) => {`The representative gallery must have scrollable boards and items; got ${JSON.stringify(scrolledOffsets)}.`);- // The preview filmstrip is a horizontal-only `Scrollable` living in the- // centre region, not either side panel. `usePreservedScrollOffset` is- // installed unconditionally inside `Scrollable` regardless of its- // `orientation`, so this is the one axis the panel assertions above never- // exercise. The filmstrip's items come from the widget's own board-scoped- // fetch, a separate round trip from the gallery panel's list, so it is- // not necessarily painted yet the instant the panel assertions above are —- // waiting for the overflow condition itself, rather than a fixed delay,- // is what actually pins that race rather than papering over it.+ // Wait for filmstrip overflow: its board-scoped fetch completes independently of the gallery and exercises+ // horizontal scroll retention.const centerPanel = centerRegion(page);await page.waitForFunction(() => {@@ -888,11 +832,8 @@ const runKeepAliveStateJourney = async (browser) => {};/**- * The layers panel's fixed panes: every pane block switches by pointer and by- * keyboard (arrows rove, Enter selects — SegmentTabs is manual-activation),- * tool switches reshape the Properties pane without losing it, and axe passes- * with the non-default panes (Swatches/History/Overview) active — states the- * static canvas surface never reaches.+ * Exercise pane switching by pointer and keyboard, tool-dependent Properties, and accessibility of non-default+ * panes.*/const LAYERS_PANEL_SCOPE = { include: ['[data-hotkey-widget-type-id="layers"]'] };@@ -921,10 +862,7 @@ const runLayersPanesJourney = async (browser) => {await page.getByRole('tabpanel', { exact: true, name: 'Swatches' }).waitFor();await waitForSettledDocument(page);- // Scoped to the layers widget: this journey certifies the panel's states;- // the page-wide sweep belongs to the canvas surface scan, and the left- // rail's lazily mounted generation sections would otherwise leak into the- // result nondeterministically depending on load timing.+ // Scope this audit to Layers so unrelated lazy generation panels cannot change its result.await assertNoAxeViolations(page, 'workbench-layers-panes', LAYERS_PANEL_SCOPE);// Keyboard: arrows rove within the block's tablist, Enter activates.@@ -937,8 +875,6 @@ const runLayersPanesJourney = async (browser) => {await page.getByRole('tabpanel', { exact: true, name: 'Transform' }).waitFor();assert.equal(await transformTab.getAttribute('aria-selected'), 'true');- // Second scan: the Transform pane's states are distinct from the first- // scan's Swatches/History/Overview set and must pass on their own.await waitForSettledDocument(page);await assertNoAxeViolations(page, 'workbench-layers-panes:transform', LAYERS_PANEL_SCOPE);@@ -962,8 +898,7 @@ const runSettingsJourney = async (browser) => {await waitForWorkbench(page);const gear = page.getByRole('button', { exact: true, name: 'Gallery settings' });await gear.click();- // The lazy quick-settings body moves the footer when it arrives. Wait for- // its controls before clicking the footer so pointer-down/up hit one target.+ // Wait for lazy settings controls; their arrival moves the footer's click target.await page.getByRole('slider', { exact: true, name: 'Image size' }).waitFor();await waitForSettledDocument(page);await page.getByRole('button', { exact: true, name: 'All Gallery settings…' }).click();diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjsindex 317535780c..83baf3e3a7 100644--- a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs@@ -81,9 +81,7 @@ const observeBrowserErrors = (page, phase, errors) => {if (message.type() === 'error') {const location = message.location();- // Every release harness deliberately uses the HTTP-only mock backend, so- // Socket.IO's transport probe is expected to stay disconnected. Ignore- // only that browser-generated 404; application console errors still fail.+ // The HTTP-only mock has no Socket.IO; ignore only its expected transport 404.if (location.url.includes('/ws/socket.io/') &&message.text().includes('the server responded with a status of 404')@@ -91,8 +89,7 @@ const observeBrowserErrors = (page, phase, errors) => {return;}- // Video existence has no bulk endpoint. Import deliberately probes the- // archived name and treats this exact 404 as the signal to restore it.+ // Import probes archived video names; this 404 triggers restoration.if (phase.endsWith('import') &&location.url &&@@ -150,11 +147,7 @@ const waitForProjectCover = async (projectId, restoredImageNames) => {assert.fail(`The project cover index never mapped ${projectId} to a restored image.`);};-/**- * What Fixture Project 002's board holds, as the snapshot describes it: kind, category and- * starring, with the names left out. Names are exactly what may not survive a transfer — every- * board item gets a new identity — so the shape is the part that has to round-trip.- */+/** Compare membership attributes, excluding names because board media receives new identities on import. */const boardShape = (items) => items.map((item) => `${item.kind}:${item.category}:${String(item.starred)}`).sort();const EXPECTED_BOARD_SHAPE = [@@ -226,15 +219,8 @@ const importArchive = async ({ archivePath, browser, contexts, errors, phase })};/**- * The complete round trip: export a project *and its board*, restore it somewhere that has none of- * its media, then duplicate the result.- *- * The rules under test are the ones that distinguish a project file from a folder of pictures.- * Board media is copied, never adopted — the destination is deliberately seeded with images under- * the archived names, and a restore that reused one would be pointing at somebody else's picture.- * Document references outside the board are the opposite: an identity the destination already has- * satisfies them, so it is reused rather than duplicated. And the things a board holds but no- * gallery shows — intermediates and the canvas's private `other` category — never travel at all.+ * Verify imports copy board media despite name collisions, reuse external references, and exclude+ * intermediate/other items.*/const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectory }) => {const sourceBoard = await getBoardSnapshot(sourceProjectId);@@ -250,14 +236,10 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectoryawait exportPage.goto(`${origin}${sourceProjectPath}`, { waitUntil: 'domcontentloaded' });await exportPage.getByRole('main', { exact: true, name: sourceProjectName }).waitFor();- // The board the server says this project owns is the one the gallery points at, without the- // document having to name it.const selectedBoardRow = exportPage.locator('button[aria-current="true"]').filter({ hasText: sourceProjectName });await selectedBoardRow.first().waitFor();- // A project's board offers the whole project as a file, alongside the media-only download that- // predates it. Both, because they are different things: one is the project, one is its pixels.await exportPage.getByRole('button', { exact: true, name: `Board actions for ${sourceProjectName}` }).click();await exportPage.getByRole('menuitem', { exact: true, name: 'Export project (.invk)' }).waitFor();await exportPage.getByRole('menuitem', { name: /^Download Board/ }).waitFor();@@ -293,8 +275,7 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectoryassert.equal(archivedBoard.version, 1);assert.deepEqual(boardShape(archivedBoard.items), EXPECTED_BOARD_SHAPE);assert.deepEqual(archivedBoard.items.map((item) => item.name).sort(), [...ARCHIVED_BOARD_NAMES].sort());- // Board membership plus the canvas's own references, each carried once: five board items, three- // external images the document draws with, and one external video a workflow node names.+ // Expect five board items plus three external images and one external video, deduplicated across references.assert.deepEqual(bundledImages.sort(),[...ARCHIVED_BOARD_NAMES.filter((name) => name.endsWith('.png')), ...PROJECT_FILE_BOARD.externalImages]@@ -309,8 +290,7 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectoryassert.equal(entries[`images/${PROJECT_FILE_BOARD.intermediateImage}`], undefined);assert.equal(entries[`images/${PROJECT_FILE_BOARD.canvasOwnedImage}`], undefined);- // Two collisions survive the reset: one name the restore must *not* adopt because the board owns- // it, and one it *must* reuse because the document only points at it.+ // Preserve two collisions: board-owned media must be copied; an external reference must be reused.const collide = [PROJECT_FILE_BOARD.referencedImage, PROJECT_FILE_BOARD.video, PROJECT_FILE_BOARD.externalImages[0]];const reset = await fetchJson(`/__reset?profile=empty&collide=${collide.map(encodeURIComponent).join(',')}`, {method: 'POST',@@ -355,8 +335,6 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectoryconst importedLayers = getLayerImageNames(imported);const [firstExternal, ...otherExternals] = PROJECT_FILE_BOARD.externalImages;- // The layer whose image the board owned follows the copy; the ones it did not keep pointing- // outside the board — the collided name is reused verbatim, the rest were uploaded.assert.equal(importedLayers.filter((name) => importedBoardNames.includes(name)).length, 1);assert.equal(importedLayers.includes(PROJECT_FILE_BOARD.referencedImage), false);assert.equal(importedLayers.includes(firstExternal), true, 'an existing identity must satisfy a reference');@@ -372,8 +350,7 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectoryassert.notEqual(importedVideoName, MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME);assert.equal(importedVideoNames.has(importedVideoName), true);- // The media the destination already held under an archived name is untouched: still there, still- // on no board. A restore that had adopted it would have moved it onto the project's board.+ // Adopting the collision would move it onto the restored board; assert it stays unboarded.const collidedVideo = importedVideos.items.find((video) => video.video_name === PROJECT_FILE_BOARD.video);const collidedImage = await fetchJson(`/api/v1/images/i/${encodeURIComponent(PROJECT_FILE_BOARD.referencedImage)}`);@@ -415,11 +392,7 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectory};};-/**- * Duplicating the imported project. The copy owns its board media outright — no name is shared with- * the project it came from — while the references that live outside both boards are simply reused,- * because both projects are on this one server.- */+/** Duplication copies board media but reuses external references on the same server. */const runDuplication = async ({ browser, contexts, errors, imported, importedBoardNames }) => {const context = await browser.newContext();@@ -427,8 +400,7 @@ const runDuplication = async ({ browser, contexts, errors, imported, importedBoaconst page = await context.newPage();observeBrowserErrors(page, 'duplicate', errors);- // Through Home rather than straight at the deep link: a cold context has to finish authenticating- // before the library will list anything, and landing on the settled shell is how a person arrives.+ // Enter through Home so authentication settles before opening the library.await page.goto(`${origin}/#/`, { waitUntil: 'domcontentloaded' });await page.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();await page.goto(`${origin}/#/projects`, { waitUntil: 'domcontentloaded' });@@ -477,11 +449,7 @@ const runDuplication = async ({ browser, contexts, errors, imported, importedBoaassertNoBrowserErrors(errors);};-/**- * An archive missing some of its bytes. The two losses are counted apart because they cost- * different things: a board item is a result still findable elsewhere, a document reference is a- * hole in the canvas.- */+/** Count missing board media separately from missing document references. */const runMissingBinaryImport = async ({ browser, contexts, entries, errors, tempDirectory }) => {const damagedPath = await writeArchiveWithout(entries,@@ -543,11 +511,6 @@ const getDefaultDependencies = () => ({waitForPreview: ({ getPreviewExit }) => waitForPreview(getPreviewExit),});-/**- * Owns the complete journey deadline and every disposable resource. Dependencies- * are injectable so timeout and teardown behavior can be tested without- * launching a browser or binding a port.- */export const executeProjectFileJourney = async ({cleanupTimeoutMs: teardownLimitMs = cleanupTimeoutMs,dependencies: dependencyOverrides = {},diff --git a/invokeai/frontend/webv2/scripts/service-worker-plugin.mjs b/invokeai/frontend/webv2/scripts/service-worker-plugin.mjsindex 1f06a03943..d764efcd54 100644--- a/invokeai/frontend/webv2/scripts/service-worker-plugin.mjs+++ b/invokeai/frontend/webv2/scripts/service-worker-plugin.mjs@@ -5,11 +5,8 @@ import { resolve } from 'node:path';const MANIFEST_PLACEHOLDER = 'self.__SW_MANIFEST__';/**- * Emits `sw.js` at the bundle root from the source worker in- * `src/platform/pwa/sw.js`, injecting the build's asset manifest: the emitted- * `assets/*` file names plus a version hash derived from them. The worker uses- * the list for cache-first serving and stale-entry pruning; deriving the- * version from the same list keeps rebuilds of identical output byte-stable.+ * Inject emitted asset names and their content-derived version into sw.js; identical output must produce the same+ * version.*/export const serviceWorkerPlugin = ({ projectRoot }) => ({apply: 'build',@@ -22,8 +19,7 @@ export const serviceWorkerPlugin = ({ projectRoot }) => ({const source = await readFile(resolve(projectRoot, 'src/platform/pwa/sw.js'), 'utf8');const occurrences = source.split(MANIFEST_PLACEHOLDER).length - 1;- // Exactly one: zero means the placeholder was renamed away, more than one- // means a stray mention (e.g. in a comment) would swallow the injection.+ // Require one placeholder so injection cannot silently miss or replace a stray occurrence.if (occurrences !== 1) {throw new Error(`Service worker source must contain ${MANIFEST_PLACEHOLDER} exactly once, found ${occurrences}.`);}diff --git a/invokeai/frontend/webv2/scripts/widget-sources.mjs b/invokeai/frontend/webv2/scripts/widget-sources.mjsindex b84caa2e2c..25ffd62819 100644--- a/invokeai/frontend/webv2/scripts/widget-sources.mjs+++ b/invokeai/frontend/webv2/scripts/widget-sources.mjs@@ -1,9 +1,6 @@/**- * Single source of truth for the deferred first-party widget implementation- * chunks. `check-architecture-performance.mjs` asserts every entry splits into- * its own chunk and that no manifest source matching WIDGET_IMPLEMENTATION_PATTERN- * is missing from this registry; `measure-architecture-performance.mjs` derives- * stable `widget:<id>` script ids from it.+ * Registry for deferred widget chunks; the architecture gate checks completeness and measurements derive+ * widget:<id> identifiers.*/export const WIDGET_IMPLEMENTATION_PATTERN = /^src\/workbench\/widgets\/([^/]+)\/implementation\.ts$/;diff --git a/invokeai/frontend/webv2/src/app/AccountLifecycleCoordinator.browser.test.tsx b/invokeai/frontend/webv2/src/app/AccountLifecycleCoordinator.browser.test.tsxindex 996c5ad552..5397adb8bb 100644--- a/invokeai/frontend/webv2/src/app/AccountLifecycleCoordinator.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/AccountLifecycleCoordinator.browser.test.tsx@@ -75,9 +75,7 @@ const sessionStore = vi.hoisted(() => {vi.mock('@features/identity', async () => {const React = await import('react');- // Modules outside this test's mock map (reached via other import specifiers)- // still bind real identity exports — spread them so the mock only overrides- // what the test drives instead of rotting on every new identity export.+ // Preserve real identity exports; override only those driven by this test.const actual = await vi.importActual<typeof identityModule>('@features/identity');return {@@ -211,9 +209,8 @@ describe('authenticated route account lifecycle', () => {sessionStore.setSnapshot(signedInSession(1));const { router } = await import('./router');- // The provider drives this load. It installs the router's transition hook- // and leaves it in place on unmount, so a pre-render `router.load()` on the- // router the previous test rendered would wait for a commit that never comes.+ // Let RouterProvider load: a reused router's retained transition hook would wait forever for a pre-render+ // commit.host = document.createElement('div');document.body.append(host);root = createRoot(host);diff --git a/invokeai/frontend/webv2/src/app/App.tsx b/invokeai/frontend/webv2/src/app/App.tsxindex e9b6b2325e..3d3016dd63 100644--- a/invokeai/frontend/webv2/src/app/App.tsx+++ b/invokeai/frontend/webv2/src/app/App.tsx@@ -15,10 +15,7 @@ const AlphaNoticeDialog = lazy(() =>import('@workbench/shell/AlphaNoticeDialog').then((module) => ({ default: module.AlphaNoticeDialog })));-/**- * The one-time alpha notice loads only for an account that has not dismissed- * it: every other start pays neither the module nor a request for it.- */+/** Load the alpha notice only for accounts that have not dismissed it. */const AlphaNoticeGate = () => {const isDue = useWorkbenchSettingsSelector((snapshot) => snapshot.status === 'ready' && !snapshot.preferences.alphaNoticeAcknowledgeddiff --git a/invokeai/frontend/webv2/src/app/BootWidgetHintController.tsx b/invokeai/frontend/webv2/src/app/BootWidgetHintController.tsxindex 5c4ddf4e7a..6d8664c01e 100644--- a/invokeai/frontend/webv2/src/app/BootWidgetHintController.tsx+++ b/invokeai/frontend/webv2/src/app/BootWidgetHintController.tsx@@ -3,13 +3,7 @@ import { getLayoutWidgetTypeIds } from '@workbench/layoutWidgetSet';import { shallowEqual, useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useEffect } from 'react';-/**- * Persists the active layout's widget set so the next boot can start those- * chunk downloads in parallel with project hydration (`preloadBootWidgets`).- * Mirrors the theme hint in `ThemeController`: a dedicated key, written after- * the store has the real layout, read before anyone knows who is signed in.- * Renders nothing.- */+/** Persist resolved widget hints for pre-hydration chunk loading on the next boot, before identity is known. */export const BootWidgetHintController = () => {const typeIds = useActiveProjectSelector(getLayoutWidgetTypeIds, shallowEqual);diff --git a/invokeai/frontend/webv2/src/app/FeatureHintsProvider.tsx b/invokeai/frontend/webv2/src/app/FeatureHintsProvider.tsxindex 3f2a1d4c28..4c1ae151db 100644--- a/invokeai/frontend/webv2/src/app/FeatureHintsProvider.tsx+++ b/invokeai/frontend/webv2/src/app/FeatureHintsProvider.tsx@@ -7,11 +7,7 @@ import { patchWorkbenchPreferences, useWorkbenchPreferenceSelector } from '@workimport { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-/**- * Production binding of the feature-hints port. Platform may not read Workbench- * preferences, so App supplies both the enabled flag and the write that the- * card's "don't show me these" action needs.- */+/** App supplies preferences because Platform cannot import Workbench. */export const FeatureHintsAdapterProvider = ({ children }: { children: ReactNode }) => {const { t } = useTranslation();const enabled = useWorkbenchPreferenceSelector((preferences) => preferences.enableInformationalPopovers);diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsxindex 74bbec2d74..c4b24f9f56 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx@@ -20,10 +20,6 @@ const GalleryImageContextMenu = lazy(() =>import('./GalleryImageActionsBridge').then((module) => ({ default: module.GalleryImageContextMenu })));-/**- * Production binding of Gallery's UI port: translates Gallery UI intents into- * the Workbench aggregate. No second adapter is expected.- */export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode }) => {const { projectId, projectName, galleryValues, generateValues, antialiasProgressImages, liveFollowEnabled } =useActiveProjectSelector((project) => ({@@ -40,10 +36,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })const accountScope = captureAccountScope();const exportProject = useExportLibraryProject();const openWorkbenchWidget = useOpenWorkbenchWidget();- // These are `lazy()` children of an adapter that only ever mounts in the- // editor, and the gallery widget needs them as soon as it renders a row.- // Left to Suspense they were fetched at ~476ms — a full round trip after the- // boot widget wave had already finished.+ // Preload row dependencies here to avoid a second fetch wave after the gallery mounts.useMountEffect(() => {void import('./GalleryImageActionsBridge');});diff --git a/invokeai/frontend/webv2/src/app/GenerateWidgetSyncRuntime.tsx b/invokeai/frontend/webv2/src/app/GenerateWidgetSyncRuntime.tsxindex 5a0f325864..526d89bc33 100644--- a/invokeai/frontend/webv2/src/app/GenerateWidgetSyncRuntime.tsx+++ b/invokeai/frontend/webv2/src/app/GenerateWidgetSyncRuntime.tsx@@ -43,8 +43,7 @@ export const GenerateWidgetSyncRuntime = () => {queryClient,});- // Kicked here, at app boot, so the gate's window is one round trip rather than "whenever the- // Generate panel is first opened".+ // Fetch capabilities at boot so generation does not wait for the panel's first mount.void ensureArchitectureCapabilitiesLoaded();void ensureModelsLoaded();return () => runtime.dispose();diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsxindex d95e7e5304..b06fae01cc 100644--- a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx@@ -44,11 +44,8 @@ const SEED_HISTORY_LIMIT = 6;const selectQueueItems = (model: QueueReadModel): QueueItemReadModel[] => model.items;/**- * Seeds and durations of recent completed Generate runs, derived from the- * project-scoped backend queue read model. Backend items map to a local queue- * item to prove they came from the Generate source (canvas, workflow, and- * upscale runs share the same backend queue); the executed seed comes from the- * backend item's session meta, which is authoritative for randomized runs.+ * Join backend items to local Generate items to exclude other queue sources; use executed session-meta seeds for+ * randomized runs.*/const useGenerationQueueInsights = (projectId: string): GenerationUiAdapter['queueInsights'] => {const localQueueItems = useActiveProjectSelector((activeProject) => activeProject.queue.items);@@ -106,15 +103,8 @@ const useGenerationQueueInsights = (projectId: string): GenerationUiAdapter['que}, [backendItems, localQueueItems]);};-/**- * Production binding of Generation's UI port: builds each sub-port from- * Workbench, Models, and Gallery state. No second adapter is expected.- */export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode }) => {- // The generate widget needs its model picker as soon as it renders. Left to- // Suspense, `ModelSelect` was fetched in a second wave after the boot- // widget wave had already finished. `GenerateCanvasSections` is- // canvas-only and stays lazy — warming it would add bytes to every boot.+ // Preload the always-needed model picker; leave canvas-only sections lazy.useMountEffect(() => {void import('@features/models/react');});@@ -123,8 +113,7 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNodegenerateValues: getProjectWidgetValues(activeProject, 'generate'),invocationSourceId: activeProject.invocation.sourceId,}));- // Syntax highlighting is a per-user preference, not a property of the- // project, so it is joined here rather than read off the document.+ // Syntax highlighting is an account preference, not project data.const showPromptSyntaxHighlighting = useWorkbenchPreferenceSelector((preferences) => preferences.showPromptSyntaxHighlighting);@@ -144,10 +133,7 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNodeconst queryClient = useQueryClient();const notify = useNotify();const findGalleryItem = useFindGalleryItem();- // Hoisted out of the group: the group's identity turns over on every gallery- // selection change, and the reference-image cards are memoized against- // exactly that — a fresh handler per selection would re-render the whole- // stack, model pickers and all, on every click in the grid.+ // Keep this handler stable across gallery selection changes so memoized reference cards do not all rerender.const findImage = useCallback<GenerationUiAdapter['gallery']['findImage']>((imageName) => findGalleryItem({ kind: 'image', name: imageName }),[findGalleryItem]@@ -168,13 +154,8 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNodeerror: modelsError,getBaseColorPalette: getModelBaseColorPalette,getBaseLabel: getModelBaseLabel,- // Hash navigation, matching the app.selectModelsTab command. Going through- // useNavigate or the models UI store would pull either the router hooks or- // the store into the editor/launchpad initial bundles (architecture budget).- // The manager opens on Add Models by default, which is where this link- // wants to land; a model type seeds its catalog filter through the same- // dynamic-import seam `WorkflowUiAdapter.openAddModels` uses, before the- // navigation, so the first paint is already filtered.+ // Use hash navigation and lazy filter seeding to keep router/manager code out of initial bundles; set the+ // filter before navigation.openManager: (options) => {const navigateToManager = () => {window.location.hash = `#/models?project=${encodeURIComponent(project.activeProjectId)}`;@@ -226,9 +207,7 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNodeconst krea2RebalancePresets = useWorkbenchPreferenceSelector((preferences) => preferences.krea2RebalancePresets);const rebalancePresetsGroup = useMemo<GenerationUiAdapter['rebalancePresets']>(() => ({- // Settings persists these shape-checked only; a curve whose weights no longer parse- // (hand-edited storage, a future backend tap count) is dropped here rather than- // handed to the picker.+ // Stored curves are only shape-checked; discard weights incompatible with the current parser.presets: normalizeRebalancePresets(krea2RebalancePresets),remove: (presetId) => {void patchWorkbenchPreferences({@@ -259,8 +238,7 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNodeconst generatePresets = useWorkbenchPreferenceSelector((preferences) => preferences.generatePresets);const presetsGroup = useMemo<GenerationUiAdapter['presets']>(() => ({- // Settings persists these shape-checked only; the feature re-normalizes the- // snapshot against the current model catalog when a preset is applied.+ // Presets are shape-checked in storage and normalized against current models on application.presets: generatePresets,remove: (presetId) => {void patchWorkbenchPreferences({diff --git a/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsx b/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsxindex bed87aa109..ee1756b0f0 100644--- a/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsx@@ -6,10 +6,6 @@ import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';import { useActiveProjectId } from '@workbench/WorkbenchContext';import { useMemo } from 'react';-/**- * Production binding of Models' UI port: supplies Workbench preferences and- * the active project. No second adapter is expected.- */export const ModelsUiAdapterProvider = ({ children }: { children: ReactNode }) => {const enableModelDescriptions = useWorkbenchPreferenceSelector((value) => value.enableModelDescriptions);const managerProjectId = useActiveProjectId();diff --git a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsxindex 5d5cab78ce..d71da75d7e 100644--- a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx@@ -73,9 +73,8 @@ export const QueueRuntimeAdapter = () => {assertAccountScopeCurrent(owner);const { galleryItemOrganization, isGalleryBoardAttachable } = await import('@features/gallery');- // Virtual destinations (date buckets, `generated`/`assets`) cannot hold- // attachments: the transport no-ops for them, which would otherwise read- // back as every video failing. The image path ignores this the same way.+ // Skip virtual destinations: attachment transport no-ops would otherwise be reported as video+ // failures.if (!isGalleryBoardAttachable(boardId)) {return;}@@ -87,9 +86,7 @@ export const QueueRuntimeAdapter = () => {owner.signal);assertAccountScopeCurrent(owner);- // The video transport confirms per item and never throws on non-fatal errors;- // surface unconfirmed refs so the queue runtime can record the failure instead- // of leaving the videos silently in Uncategorized (e.g. board deleted mid-run).+ // Report unconfirmed video attachments; transport does not throw non-fatal failures.if (result.failed.length > 0) {throw new Error(`${result.failed.length} of ${videoNames.length} video(s) could not be added to the board.`@@ -153,8 +150,6 @@ export const QueueRuntimeAdapter = () => {locks: createQueueRunLockPort(owner.storageSuffix),modelLoads: modelLoadActivitySink,nodeExecution: nodeExecutionStore,- // Closes the loop on a library-bound run: its final output becomes the- // workflow's cover image and stamps `last_run_at` on the record.workflowRuns: createWorkflowRunCaptureSink(),});runtime.start();diff --git a/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsxindex e1882bca33..2f3b596596 100644--- a/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx@@ -9,10 +9,6 @@ import { lazy, useMemo, type ReactNode } from 'react';const importQueueItemActions = () => import('@workbench/queue-integration/QueueItemActions');const QueueItemActions = lazy(() => importQueueItemActions().then((module) => ({ default: module.QueueItemActions })));-/**- * Production binding of Queue's UI port: adapts the Workbench-owned concerns- * Queue's UI depends on. No second adapter is expected.- */export const QueueUiAdapterProvider = ({ children }: { children: ReactNode }) => {const notify = useNotify();const activeProjectId = useActiveProjectSelector((project) => project.id);diff --git a/invokeai/frontend/webv2/src/app/SocketHubRuntime.tsx b/invokeai/frontend/webv2/src/app/SocketHubRuntime.tsxindex 5d883d71cb..b0479477a9 100644--- a/invokeai/frontend/webv2/src/app/SocketHubRuntime.tsx+++ b/invokeai/frontend/webv2/src/app/SocketHubRuntime.tsx@@ -2,13 +2,8 @@ import { useMountEffect } from '@platform/react/useMountEffect';import { socketHub } from '@platform/transport/socketHub';/**- * Renders nothing. Mounted once above both the Launchpad and the editor: opens- * the single backend socket for the authenticated session. Feature-specific- * runtimes attach listeners where needed so this base runtime stays lightweight.- *- * It intentionally does NOT disconnect on unmount — that keeps it StrictMode- * safe and lets the socket persist across Launchpad↔editor navigation. The- * App-composed account lifecycle tears it down before an identity epoch changes.+ * Connect once per authenticated account. Account lifecycle owns teardown; unmount cleanup would disconnect during+ * StrictMode or route changes.*/export const SocketHubRuntime = () => {useMountEffect(() => {diff --git a/invokeai/frontend/webv2/src/app/ThemeController.tsx b/invokeai/frontend/webv2/src/app/ThemeController.tsxindex eb2376f327..951011bd79 100644--- a/invokeai/frontend/webv2/src/app/ThemeController.tsx+++ b/invokeai/frontend/webv2/src/app/ThemeController.tsx@@ -4,20 +4,8 @@ import { DEFAULT_THEME, THEMES_BY_ID } from '@theme/system';import { useWorkbenchSettingsSelector } from '@workbench/settings/store';import { useLayoutEffect } from 'react';-/**- * Applies the persisted appearance preferences to the document root.- *- * Theme switching is intentionally a DOM-attribute flip rather than a React- * re-theme: the semantic-token conditions in `theme/system.ts` key off- * `<html data-theme>`, so changing the attribute restyles the whole shell with- * no component re-render. `data-reduce-motion` is read by global CSS motion- * tokens. Renders nothing.- */-/**- * Read by the pre-paint script in index.html. Dedicated hint keys (rather than- * the workbench snapshot, which is per-user on multi-user backends) let first- * paint apply last-used appearance without knowing who is signed in.- */+/** Root data attributes drive theme and motion CSS without React rerenders. */+/** Pre-paint hints are account-independent because identity is unknown at first paint. */const THEME_HINT_STORAGE_KEY = 'invokeai:v7:webv2:theme';const REDUCE_MOTION_HINT_STORAGE_KEY = 'invokeai:v7:webv2:reduce-motion';const HIGH_CONTRAST_HINT_STORAGE_KEY = 'invokeai:v7:webv2:high-contrast';@@ -51,8 +39,7 @@ export const ThemeController = () => {}),shallowEqual);- // Until the settings store has resolved, the pre-paint hint script owns the- // theme; applying the store's defaults here would flash and clobber it.+ // Keep pre-paint hints until settings resolve; applying defaults would flash the theme.const hasResolved = status === 'ready' || status === 'error';useLayoutEffect(() => {diff --git a/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsxindex 5345ef0cc2..c0ecb64292 100644--- a/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx@@ -8,10 +8,6 @@ import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { useCallback, useMemo } from 'react';-/**- * Production binding of Upscale's UI port: maps the upscale widget instance- * and prompt drafts out of the Workbench aggregate. No second adapter is expected.- */export const UpscaleUiAdapterProvider = ({ children }: { children: ReactNode }) => {const project = useActiveProjectSelector((activeProject) => {@@ -28,15 +24,12 @@ export const UpscaleUiAdapterProvider = ({ children }: { children: ReactNode })areProjectPromptDraftsEqual(left.promptDraft, right.promptDraft) &&left.rawValues === right.rawValues);- // Syntax highlighting is a per-user preference, not a property of the- // project, so it is joined here rather than read off the document.+ // Syntax highlighting is an account preference, not project data.const showPromptSyntaxHighlighting = useWorkbenchPreferenceSelector((preferences) => preferences.showPromptSyntaxHighlighting);const commands = useWorkbenchCommands();- // The port's callbacks are keyed to the project, not to its contents: rebuilding- // them whenever `rawValues` changes would hand every consumer new function- // identities on each keystroke, re-rendering memoized fields that did not change.+ // Key actions by project, not values, to preserve callback identity while typing.const { projectId } = project;const patchPromptDraft = useCallback<UpscaleUiAdapter['patchPromptDraft']>((values) => commands.generation.patchPromptDraft(values, 'upscale', projectId),diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsxindex 5cd9fd3978..c876190f72 100644--- a/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx@@ -18,13 +18,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { VideoUiAdapterProvider } from './VideoUiAdapter';/**- * The panel's play button is one gesture spread over three subsystems — the Preview- * widget's placement, gallery selection, and the span request the player reads — and this- * adapter is the only place they are put in order. What it has to protect is the user's- * gallery selection: it is theirs, it persists, and moving it is not undoable.- *- * A browser test because the provider has to render, and the unit config carries no DOM —- * the same reason `GalleryUiAdapter.browser.test.tsx` lives there.+ * Verify ordering across Preview placement, selection, and span requests; failed play must not change persisted+ * selection.*/let adapter: VideoUiAdapter;@@ -47,8 +42,6 @@ vi.mock('@features/video', () => ({},}));vi.mock('@features/gallery/queries', () => ({ invalidateGallery: vi.fn() }));-// What a landed reveal does to the grid belongs to `useSelectMapImage.browser.test.tsx`;-// this file is about which gestures move the user's selection at all.vi.mock('@workbench/image-actions/revealGalleryItem', () => ({ revealGalleryItem }));vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({}) }));vi.mock('@workbench/settings/store', () => ({ useWorkbenchPreferenceSelector: () => false }));@@ -136,12 +129,8 @@ describe('findInGallery', () => {it('raises the grid where it already lives, not where the manifest would place it', async () => {act(() => adapter.findInGallery({ kind: 'video', name: 'clip.mp4' }));- // Unlike a play press, a find IS a request to rearrange the workspace: the- // panel is the far side of the app from the grid, and a selection the user- // cannot see is not a find. But an unqualified open resolves to `center`- // off the manifest and the reducer ADOPTS the existing instance there- // without vacating the right panel, listing one grid in two regions.- // Preview goes first so the grid wins a region they might share.+ // Find must relocate Gallery explicitly; an unqualified open can leave it listed in two regions. Raise Preview+ // first so Gallery wins a shared region.expect(openWorkbenchWidget.mock.calls).toEqual([['preview', { preferredRegions: ['center'], requireCenterView: true }],['gallery', { preferredRegions: ['right'] }],@@ -162,11 +151,8 @@ describe('findInGallery', () => {});it('describes the press, not the moment its chunk lands', async () => {- // The reveal module is fetched lazily; the image map's, statically imported- // inside an already-loaded chunk, claims synchronously. A ticket minted- // after the import would let a map click made AFTER this press supersede- // it, and would fence the reveal to whichever project the user had reached- // by then — the exact write the fence exists to stop.+ // Claim the reveal ticket before lazy import so later gestures win and the request retains its originating+ // project fence.const before = claimGalleryNavigationSequence();act(() => adapter.findInGallery({ kind: 'image', name: 'still.png' }));@@ -187,8 +173,7 @@ describe('findInGallery', () => {act(() => adapter.findInGallery({ kind: 'image', name: 'deleted.png' }));- // The widgets are already raised by then, so a silent failure leaves a- // rearranged workspace and no account of why the grid did not move.+ // Report reveal failure because the widgets have already moved.await vi.waitFor(() =>expect(reportError).toHaveBeenCalledWith({area: 'find-in-gallery',@@ -228,9 +213,7 @@ describe('playVideoSpanInPreview', () => {});// The button keeps the token to recognise the player's report on this request.expect(token).toBe(getVideoSpanPlaybackRequest()?.token);- // Deliberately no reveal: auditioning a trim must not scroll the gallery grid out- // from under a user who is browsing it, and the gallery's own "open in Preview"- // does not reveal either.+ // Auditioning a trim must not scroll the gallery.expect(getGalleryRevealRequest()?.token).toBe(revealBefore);});@@ -242,9 +225,8 @@ describe('playVideoSpanInPreview', () => {token = adapter.playVideoSpanInPreview(span);});- // A press that cannot play must not cost the user their selection — that is a change- // they did not ask for and cannot undo. And a span nothing is there to read would sit- // until the next player showed this clip, starting audio out of nowhere.+ // Failed play must change neither selection nor pending span, which a future player could consume+ // unexpectedly.expect(selectItem).not.toHaveBeenCalled();expect(getVideoSpanPlaybackRequest()).toBeNull();// Nothing was asked, so there is no report to wait for.@@ -252,9 +234,7 @@ describe('playVideoSpanInPreview', () => {});it('drops a press whose lookup landed after the user switched projects', async () => {- // The button resolves its gallery item over the network and calls back with the- // callback it captured. Writing that selection now would land it in the project the- // user just left, where it persists.+ // A clip resolved after a project switch must not update the previous project's persisted selection.const stalePress = adapter.playVideoSpanInPreview;activeProjectId = 'project-2';diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsxindex c3067b4559..01c6b45cbc 100644--- a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx@@ -17,12 +17,7 @@ import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { useCallback, useEffect, useMemo, useRef } from 'react';-/**- * Production binding of Video's UI port: maps the video widget instance out of- * the Workbench aggregate. No second adapter is expected. Video's prompt is one- * of those widget values — it is not the project draft Generate and Upscale- * share — so nothing but `rawValues` is joined here.- */+/** Video owns its prompt in widget values; do not join the draft shared by Generate/Upscale. */export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) => {const project = useActiveProjectSelector((activeProject) => {@@ -35,21 +30,17 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>},(left, right) => left.projectId === right.projectId && left.rawValues === right.rawValues);- // Syntax highlighting is a per-user preference, not a property of the- // project, so it is joined here rather than read off the document.+ // Syntax highlighting is an account preference, not project data.const showPromptSyntaxHighlighting = useWorkbenchPreferenceSelector((preferences) => preferences.showPromptSyntaxHighlighting);- // Uploads from the video panel land where generation results do — the same- // destination the queue snapshots as galleryBoardId.+ // Use the queue's galleryBoardId destination for panel uploads too.const uploadBoardId = useActiveProjectSelector((activeProject) => getGalleryDestinationBoardId(getProjectWidgetValues(activeProject, 'gallery')) ?? 'none');- // Ref-backed so the port's actions keep their stable-for-the-project identity: a- // board click must not re-render every useVideoUiActions consumer in the panel.+ // Read the current board through a ref so board selection does not recreate project actions.const uploadBoardIdRef = useRef(uploadBoardId);- // The live project, for callbacks that outlive the render that built them: a play press- // resolves its clip over the network and can land after a project switch.+ // Async clip resolution can outlive a project switch; callbacks must check the live project.const activeProjectIdRef = useRef(project.projectId);useEffect(() => {uploadBoardIdRef.current = uploadBoardId;@@ -57,9 +48,7 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>}, [project.projectId, uploadBoardId]);const commands = useWorkbenchCommands();const queryClient = useQueryClient();- // The port's callbacks are keyed to the project, not to its contents: rebuilding- // them whenever `rawValues` changes would hand every consumer new function- // identities on each keystroke, re-rendering memoized fields that did not change.+ // Key actions by project, not values, to preserve callback identity while typing.const { projectId } = project;const patchValues = useCallback<VideoUiAdapter['patchValues']>((values, origin) => commands.widgets.patchValues('video', values, projectId, origin),@@ -71,20 +60,11 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>);const touchGalleryImages = useCallback(() => void invalidateGallery(queryClient), [queryClient]);const openWorkbenchWidget = useOpenWorkbenchWidget();- // Preview renders the gallery selection, so putting a reference clip in front of the user- // is the gallery's own "open in Preview" gesture: select the item, raise the widget into- // the center view. Deliberately WITHOUT that gesture's sibling reveal — auditioning a- // trim should not also scroll the gallery grid out from under a browsing user, and- // `openItemInPreview` does not reveal either.- //- // Raising Preview comes first so a refusal costs the user nothing: the selection is- // theirs, and moving it for a press that cannot play would be a change they did not ask- // for and cannot undo. The span request goes last, once the widget is on its way.+ // Raise Preview before changing selection; refusal must leave selection untouched. Request the span last and do+ // not reveal/scroll the gallery.const playVideoSpanInPreview = useCallback<VideoUiAdapter['playVideoSpanInPreview']>(({ endSeconds, item, startSeconds }) => {- // The press resolved its gallery item over the network, and the user can have- // switched projects in that window. This callback still carries the project it was- // built for, so writing a selection now would land it in the project they left.+ // Discard a resolved clip if its originating project is no longer active.if (activeProjectIdRef.current !== projectId) {return null;}@@ -128,8 +108,7 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>return <VideoUiProvider adapter={adapter}>{children}</VideoUiProvider>;};-// The player's report is module-scoped in the Preview widget, so the port is one constant-// object: subscribing to it never re-renders on a project switch.+// The module-scoped player report permits one stable port across project switches.const VIDEO_SPAN_PLAYBACK_PORT: VideoUiAdapter['videoSpanPlayback'] = {getState: getVideoSpanPlaybackState,subscribe: subscribeVideoSpanPlaybackState,diff --git a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsxindex 22a6788cd6..a7a2d4e8ca 100644--- a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx+++ b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx@@ -23,14 +23,8 @@ import { RecallParametersRuntime } from './RecallParametersRuntime';import { WorkbenchUiPorts } from './workbenchPorts';/**- * The authenticated editor: providers, editor-only runtimes, and the shell.- * The shared backend socket is mounted above this route; `WorkbenchRuntime`- * attaches the generation queue listeners while the editor is open.- *- * The route's search params shape the boot: ?project deep-links a library- * project into the session, ?new starts a fresh draft. Both are consumed by- * the persistence load; the session controller handles params that change- * while the editor is already mounted.+ * Editor-only composition. Persistence handles initial ?project/?new; the session controller handles later search+ * changes.*/export const WorkbenchApp = () => {const search = useSearch({ strict: false }) as WorkbenchSearch;@@ -39,9 +33,7 @@ export const WorkbenchApp = () => {[search.new, search.project]);- // Start widget chunk downloads now, while project hydration is still in- // flight — the provider below withholds the shell until hydration, and- // without this the first widget byte doesn't move until after it.+ // Preload widget chunks during hydration; the provider withholds the shell until hydration finishes.useMountEffect(preloadBootWidgets);return (diff --git a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsxindex a6a92c4c55..1ac542bea6 100644--- a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx@@ -107,9 +107,7 @@ const WorkflowGraphPreviewAdapterProvider = ({ children }: { children: ReactNode}},openDocumentInNewProject: (document, label) => {- // `create` activates the new project, so `replace` (which always- // targets the active project) lands the document there, not in the- // project the preview was opened from.+ // Create first: replace targets the active project.commands.projects.create();commands.workflows.replace(document, label);openWidget('workflow');@@ -182,12 +180,7 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })getProjectGraph: () => queries.getSnapshot().activeProject.projectGraph,nodeExecution: { get: nodeExecutionStore.get, subscribe: nodeExecutionStore.subscribe },notifications: { error: notify.error, info: notify.info, success: notify.success },- // Hash navigation and a dynamic import, matching `GenerationUiAdapter`'s- // `openManager`: `useNavigate` would pull the router hooks and- // `@features/models/launchpad` would pull the manager's UI store into the- // editor's initial bundle, for a link most sessions never click. The seed- // lands before the navigation, so Add Models' first paint is already- // showing what was asked for.+ // Lazy-load manager filter state to preserve editor bundle boundaries; seed it before hash navigation.openAddModels: (query) => {void import('@features/models/launchpad').then(({ requestAddModelsSearch }) => {requestAddModelsSearch(query);diff --git a/invokeai/frontend/webv2/src/app/accountLifecycle.ts b/invokeai/frontend/webv2/src/app/accountLifecycle.tsindex 533be526bb..c03303f78c 100644--- a/invokeai/frontend/webv2/src/app/accountLifecycle.ts+++ b/invokeai/frontend/webv2/src/app/accountLifecycle.ts@@ -5,11 +5,7 @@ import { socketHub } from '@platform/transport/socketHub';let isConfigured = false;-/**- * App composition for resources whose implementations Identity must not know.- * Lazy feature modules register their own account-owned caches with the same- * lifecycle when they load.- */+/** App composes cross-owner account cleanup; lazy features register their caches when loaded. */export const configureAppAccountLifecycle = (): void => {if (isConfigured) {return;@@ -18,8 +14,7 @@ export const configureAppAccountLifecycle = (): void => {registerAccountOwnedResource({clear: () => {- // QueryClient.clear() synchronously destroys queries, which cancels their- // retryers before removing both query and mutation caches.+ // clear() cancels query retryers synchronously before removing caches.queryClient.clear();},name: 'query-client',diff --git a/invokeai/frontend/webv2/src/app/router.tsx b/invokeai/frontend/webv2/src/app/router.tsxindex 81c2f3811e..2c100debc6 100644--- a/invokeai/frontend/webv2/src/app/router.tsx+++ b/invokeai/frontend/webv2/src/app/router.tsx@@ -34,27 +34,13 @@ import { Fragment } from 'react';import { SocketHubRuntime } from './SocketHubRuntime';/**- * Code-based route tree. The authenticated layout route owns the auth guard,- * which resolves the backend's multi-user status once per app load:- *- * - multi-user off → authenticated routes render directly; /login + /setup bounce home- * - setup required → everything funnels to /setup- * - signed out → authenticated routes redirect to /login- *- * Under it, `/` is the Launchpad (project library, model manager, profile,- * resources) and `/app` is the editor. The editor bundle — canvas, workflow,- * widgets — is code-split behind `lazyRouteComponent`, so the Launchpad stays- * light; `defaultPreload: 'intent'` starts fetching that chunk the moment a- * project card is hovered.- *- * Hash history is used because the bundle is served with a relative base- * (`./`), so the app cannot rely on server-side fallback for deep paths.+ * The authenticated layout owns setup/login guards; lazy /app keeps editor code out of Launchpad. Hash history+ * supports the relative base without server deep-path fallback.*/const RouterError = ({ error }: ErrorComponentProps) => {'use no memo';- // Cold-path boundary: Compiler's memo cache costs more than this render.- // The browser retry test and production build budget guard its behavior.+ // Skip compiler memoization on this cold path; retry tests and build budgets guard it.const router = useRouter();return error instanceof AuthSessionUnavailableError ? (@@ -67,11 +53,8 @@ const RouterError = ({ error }: ErrorComponentProps) => {const rootRoute = createRootRoute({ component: Outlet, errorComponent: RouterError });/**- * Wraps every authenticated route with the shared backend socket transport- * and the model-install runtime — installs must progress and toast no matter- * which surface started them. Heavier feature runtimes still attach their own- * listeners only where needed, keeping the light Launchpad bundle free of- * editor/model-manager view code.+ * Keep socket and install progress alive across authenticated routes; mount heavier feature listeners only where+ * needed.*/const AuthenticatedLayout = () => {'use no memo';@@ -128,8 +111,6 @@ const requireLaunchpadCapability = async (capability: keyof Capabilities): Promi}};-// `/` plus a deep-link alias per Launchpad section. All render the same shell;-// it reads the path to pick the active page.const launchpadRouteOptions = {component: Launchpad,getParentRoute: () => authenticatedRoute,@@ -173,21 +154,12 @@ const fontsHomeRoute = createRoute({const workbenchRoute = createRoute({beforeLoad: async ({ cause, search }) => {- // Warm the editor bundle while the guard's session peek is in flight. The- // module loader dedupes against `lazyRouteComponent`'s own import, so on a- // cold deep link the chunk downloads in parallel with the peek instead of- // after it.+ // Preload the editor during the session peek; the module loader deduplicates the lazy-route import.void import('./WorkbenchApp');- // Photoshop semantics: the editor without documents is Home. A definite- // empty session redirects unless the URL explicitly asks for a project or- // a fresh draft; an unknowable session (first run, legacy blob, backend- // unreachable) falls through and the editor boots from what it can find.- //- // Only actual entries are checked: search-only changes ('stay', e.g. the- // session controller stripping ?new before the draft has autosaved) must- // not re-evaluate a blob that is still catching up, and hover preloads- // should not hit the session endpoint at all.+ // Redirect a definitively empty session to Home unless ?project/?new is supplied. Unknown sessions fall+ // through. Check only entries: search changes can precede autosave, and hover preloads must not fetch the+ // session.if (cause !== 'enter' || search.project || search.new) {return;}diff --git a/invokeai/frontend/webv2/src/architecture/axeAudits.test.ts b/invokeai/frontend/webv2/src/architecture/axeAudits.test.tsindex f2813785cf..c9754f8f2b 100644--- a/invokeai/frontend/webv2/src/architecture/axeAudits.test.ts+++ b/invokeai/frontend/webv2/src/architecture/axeAudits.test.ts@@ -1,19 +1,8 @@import { describe, expect, it } from 'vitest';/**- * An accessibility audit must read settled UI.- *- * `axe.run` on a surface that is still animating in measures contrast against a- * half-composited backdrop and reports colour failures that do not exist. Whether an audit- * lands inside that window depends on machine load — in a browser run, on how many other test- * files the suite is scheduling — so the failure surfaces for whoever next adds an unrelated- * test file, in a test they did not touch. That is expensive to diagnose and easy to- * misattribute, which is why the pairing is enforced here rather than left to a comment.- *- * Scope is the `src/` tree, which is what this glob can reach. The release journey runner- * (`scripts/run-accessibility-journeys.mjs`) audits from Node against a Playwright page and- * cannot import the helper — its body is serialised into the browser — so it carries the same- * wait inside `waitForSettledDocument` and is not covered here.+ * Require settled UI before axe to avoid transient contrast failures. This scans src only; serialized release+ * journeys must implement the same wait separately.*/const sources = import.meta.glob('../**/*.{ts,tsx}', {eager: true,diff --git a/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.tsindex c3fabd952b..5a2d72ce9f 100644--- a/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts+++ b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts@@ -31,9 +31,8 @@ const SEAM_MODULES = [];/**- * Mutations that restructure the stack forests. Controllers build some as forward/inverse pairs for- * prepared raster dispatch, while paint creates and rolls back its pointer-down layer by design.- * Every current owner is enumerated below; the scan matches the formatted literal `type: '…'`.+ * Enumerate structural-mutation constructors, including prepared inverse pairs and paint rollback; scanning+ * matches formatted type literals.*/const STRUCTURAL_MUTATION_TYPES = ['addCanvasLayer',@@ -50,10 +49,7 @@ const STRUCTURAL_MUTATION_TYPES = ['setCanvasLayersHidden','updateCanvasLayerSource',];-/**- * The finite set of modules that construct structural mutations directly. Keeping this explicit- * prevents new bypasses of the prepared-edit seam.- */+/** Explicitly allowlist structural-mutation owners to prevent bypassing the prepared-edit seam. */const STRUCTURAL_MUTATION_OWNER_PATHS = new Set(['workbench/canvasProjectMutations.ts','workbench/canvas-engine/controllers/booleanMergeController.ts',diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.tsindex 16706c53bd..0c641ba5e2 100644--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts@@ -233,8 +233,6 @@ describe('feature public-interface registry', () => {expect(checkDependency('features/gallery/ui/View.tsx', '@features/queue/publicApi')).toMatchObject([{ rule: 'feature-public-interface' },]);- // Workbench resolves prompt expansion before submitting, so it reads- // Generation's prompt cache through the public entry module.expect(checkDependency('workbench/invocationSubmit.ts', '@features/generation/prompts')).toEqual([]);expect(checkDependency('app/GenerateWidgetSyncRuntime.tsx', '@features/generation/runtime')).toEqual([]);expect(checkDependency('workbench/widgets/canvas/invoke.ts', '@features/generation/canvasGraph')).toEqual([]);diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.tsindex 799844ef6d..590208a379 100644--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts@@ -54,12 +54,7 @@ const normalizePath = (path: string): string => {return parts.join('/');};-/**- * Loads a whole corpus into the parser in one round trip. Call this before- * sweeping a tree with {@link collectImportReferences} or {@link checkSource};- * the entries must be the same `[fileName, source]` pairs the sweep passes, so- * each later call is served from the already-loaded program.- */+/** Preload the exact [fileName, source] pairs before a sweep so subsequent checks reuse one parsed program. */export const primeImportSources = (entries: Iterable<readonly [string, string]>): void => {primeSourceAnalysis(entries, { jsx: true });};@@ -186,17 +181,10 @@ const DOCUMENT_MODEL_DEPENDENCY_MODULES = ['workbench/canvas-engine/document/selectionRepair',];-/**- * Test-support suffixes, matched with or without a file extension so the same predicate classifies- * both a source path and a resolved (extensionless) import target.- */+/** Accept extensionless targets as well as source filenames. */const TEST_SUPPORT_SUFFIX = /\.(?:test|type-test|testing|stories)(?:\.[^.]+)?$/;-/**- * Production sources: everything the architecture rules scan. Tests, type tests, stories and the- * `.testing` helpers they share are not -- those import test runners and fixtures, so a production- * module reaching one pulls both into every bundle that route touches.- */+/** Exclude test support from production; importing it would pull runners and fixtures into application bundles. */export const isProductionSourcePath = (path: string): boolean => !TEST_SUPPORT_SUFFIX.test(path);/** The pure document model may only reach pure document facts, math, and contracts. */diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.tsindex c7617b018a..6e1a582dfc 100644--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts@@ -1,8 +1,6 @@/**- * Fail-closed public-surface registry. A feature absent from this map has NO- * public modules; a top-level module absent from its list is private.- * `index` is implicitly public for every registered feature.- * To publish a new entry module, add it here and cover it in dependencyPolicy.test.ts.+ * Unregistered features and unlisted modules are private; index is public for registered features. Cover new+ * entries in dependencyPolicy.test.ts.*/export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string[]>> = {gallery: [diff --git a/invokeai/frontend/webv2/src/architecture/migrationExceptions.ts b/invokeai/frontend/webv2/src/architecture/migrationExceptions.tsindex 0dc535d70a..aaf7af3621 100644--- a/invokeai/frontend/webv2/src/architecture/migrationExceptions.ts+++ b/invokeai/frontend/webv2/src/architecture/migrationExceptions.ts@@ -1,7 +1,4 @@import type { MigrationException } from './dependencyPolicy';-/**- * Temporary, owned migration debt. The completion gate requires this list to be- * empty; entries may only point at an open architecture-wayfinder removal ticket.- */+/** Temporary exceptions require an open removal ticket; the completion gate requires none. */export const migrationExceptions: readonly MigrationException[] = [] as const;diff --git a/invokeai/frontend/webv2/src/architecture/secureContextApis.test.ts b/invokeai/frontend/webv2/src/architecture/secureContextApis.test.tsindex 1d82dd22f3..52b814e0e6 100644--- a/invokeai/frontend/webv2/src/architecture/secureContextApis.test.ts+++ b/invokeai/frontend/webv2/src/architecture/secureContextApis.test.ts@@ -1,9 +1,6 @@import { describe, expect, it } from 'vitest';-/**- * `crypto.randomUUID` and `crypto.subtle` are undefined outside secure contexts,- * so filter these calls out when running over plain HTTP.- */+/** Guard secure-context APIs: randomUUID and subtle are unavailable over insecure HTTP. */const sources = import.meta.glob('../**/*.{ts,tsx}', {eager: true,import: 'default',diff --git a/invokeai/frontend/webv2/src/features/fonts/core/types.ts b/invokeai/frontend/webv2/src/features/fonts/core/types.tsindex fe3af307b4..5b43ee5d95 100644--- a/invokeai/frontend/webv2/src/features/fonts/core/types.ts+++ b/invokeai/frontend/webv2/src/features/fonts/core/types.ts@@ -17,11 +17,7 @@ export interface FontInstance {export type FontScope = 'private' | 'shared';export type FontSource = 'uploaded' | 'directory';-/**- * The frontend read model for one indexed font file/face. `id` and- * `contentHash` are stable identity fields; the readable family and filename- * are presentation metadata only.- */+/** id and contentHash identify a font face; family and filename are display metadata. */export interface FontRecord {id: string;family: string;diff --git a/invokeai/frontend/webv2/src/features/fonts/data/queries.ts b/invokeai/frontend/webv2/src/features/fonts/data/queries.tsindex 5cd4e4b95e..20e5a4f40c 100644--- a/invokeai/frontend/webv2/src/features/fonts/data/queries.ts+++ b/invokeai/frontend/webv2/src/features/fonts/data/queries.ts@@ -18,12 +18,7 @@ export const fontsQueryOptions = (params: FontListParams = {}) =>staleTime: 30_000,});-/**- * A bounded transport page assembled as an infinite query for controls that- * need to append catalog results. Every request remains offset based, so the- * server never sends an unbounded response and callers can stop at the real- * catalog total.- */+/** Infinite-query catalog pagination uses bounded offset requests and stops at the server total. */export const fontsInfiniteQueryOptions = (params: FontListParams = {}) => {const { offset: initialOffset = 0, ...filters } = params;const limit = params.limit ?? FONT_PAGE_SIZE;diff --git a/invokeai/frontend/webv2/src/features/fonts/react.tsx b/invokeai/frontend/webv2/src/features/fonts/react.tsxindex d683204a84..99bbbe7db6 100644--- a/invokeai/frontend/webv2/src/features/fonts/react.tsx+++ b/invokeai/frontend/webv2/src/features/fonts/react.tsx@@ -28,12 +28,7 @@ const createAbortError = (): Error => {return error;};-/**- * Keeps the provider/context seam small enough for the authenticated shell.- * The browser registry and authenticated transport are loaded only after the- * route mounts, while callers can still retain faces and queue ensures during- * that short handoff.- */+/** Loads the browser registry after mount; callers may retain faces and queue ensures during initialization. */const createDeferredFontRuntime = (): DeferredFontRuntime => {const listeners = new Set<() => void>();const pendingRetains = new Set<PendingRetain>();@@ -65,9 +60,7 @@ const createDeferredFontRuntime = (): DeferredFontRuntime => {resolveDelegate = resolve;rejectDelegate = reject;});- // The provider creates this promise before any consumer necessarily asks- // for a face. Mark a disposal/import failure as handled while preserving- // the rejection for callers that are waiting on it.+ // Handle failures before consumers attach, while preserving rejection for waiting callers.void delegatePromise.catch(() => undefined);return delegatePromise;};diff --git a/invokeai/frontend/webv2/src/features/fonts/runtime.ts b/invokeai/frontend/webv2/src/features/fonts/runtime.tsindex 42282dad1c..411e81b1ae 100644--- a/invokeai/frontend/webv2/src/features/fonts/runtime.ts+++ b/invokeai/frontend/webv2/src/features/fonts/runtime.ts@@ -55,15 +55,12 @@ export interface CreateFontRuntimeOptions {}const downloadDefaultFont = async (reference: FontDownloadReference, signal?: AbortSignal): Promise<Uint8Array> => {- // Keep the authenticated route shell and editor boot free of catalog/query- // code. The transport is only needed after a custom face is requested.+ // Load catalog transport only when a custom face is requested.const { downloadFont } = await import('./data/api');return downloadFont(reference, signal);};const getDefaultFont = async (id: string, signal?: AbortSignal): Promise<FontRecord> => {- // Metadata validation is an output boundary too, but catalog code should- // stay out of the authenticated shell until a face is actually used.const { getFont } = await import('./data/api');return getFont(id, signal);};@@ -238,12 +235,8 @@ const fontFaceDescriptors = (face: FontRecord, reference: FontDownloadReference)const axes = new Set(face.axes.map((axis) => axis.tag));const requestedAxes = reference.axes ?? {};- // The download endpoint returns a pinned static instance when coordinates are- // present. Its CSS descriptor must describe that instance, otherwise a- // requested wght=900 face is registered as the metadata's default 400 face- // and the browser may synthesize another bold pass over the already-bold- // outline. Static files (and requests without the corresponding axis) keep- // their catalog descriptor so CSS bold synthesis remains available.+ // Pinned axes must set the CSS descriptor to avoid synthesizing bold over an already-bold instance. Otherwise+ // retain catalog descriptors for browser synthesis.if (axes.has('wght') && Number.isFinite(requestedAxes.wght)) {weight = requestedAxes.wght!;}@@ -264,12 +257,8 @@ const createSnapshot = (generation: number, states: ReadonlyMap<string, FontLoadObject.freeze({ generation, states });/**- * Creates a session-owned browser font registry. Every request is keyed by the- * persisted resource identity and normalized variation coordinates, so two- * consumers cannot race to register the same bytes under different names.- * Requested CSS style and weight stay outside the key: they describe how a- * consumer uses a static face, while the face's catalog metadata owns the- * registration descriptor and the browser performs any requested synthesis.+ * Registration identity includes resource and normalized axes, but excludes requested CSS style/weight: catalog+ * descriptors own static-face synthesis.*/export const createFontRuntime = (options: CreateFontRuntimeOptions = {}): FontRuntime => {const runtimeId = nextRuntimeId++;@@ -422,10 +411,7 @@ export const createFontRuntime = (options: CreateFontRuntimeOptions = {}): FontR}released = true;request.consumers.delete(token);- // The shared request belongs to the loader/runtime, while each caller- // owns only its consumer. Abort the transport only after every caller- // has gone away; this keeps one canceled raster job from canceling a- // still-live text editor or another layer using the same instance.+ // Abort shared transport only after its last consumer releases it.if (request.consumers.size === 0 && inflight.get(request.key) === request) {request.requestController.abort(createAbortError());}diff --git a/invokeai/frontend/webv2/src/features/gallery/core/items.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/items.test.tsindex b23ee06588..aa5d43e623 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/items.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/items.test.ts@@ -285,11 +285,8 @@ describe('classifyGalleryUpload', () => {});describe('getGalleryUploadAccept', () => {- // Spelled out rather than derived, and deliberately not sampled: this list is the- // frontend's copy of ACCEPTED_VIDEO_EXTENSIONS + ACCEPTED_AUDIO_EXTENSIONS in- // invokeai/app/api/routers/videos.py, and the picker greying out a file the route would- // have taken is the bug this exists to catch. A "trim to the common formats" edit must- // fail here, so an arrayContaining sample will not do.+ // Assert every accepted video/audio extension from videos.py; sampled expectations would miss picker+ // restrictions.it('offers every container and audio format the video upload route ingests', () => {expect(getGalleryUploadAccept(['video']).split(',')).toEqual(['video/*',diff --git a/invokeai/frontend/webv2/src/features/gallery/core/items.ts b/invokeai/frontend/webv2/src/features/gallery/core/items.tsindex 4af3efb8cb..07d66c6538 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/items.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/items.ts@@ -35,11 +35,7 @@ export interface GalleryVideoItem extends GalleryItemBase {durationSeconds: number;fps?: number;kind: 'video';- /**- * How the video entered the gallery, when the server marked it. `'audio_upload'` means an- * uploaded audio file the ingest converter wrapped into a rendered-waveform video — its- * frames are a picture of the sound, not footage.- */+ /** `audio_upload` identifies audio converted into a waveform video rather than footage. */mediaOrigin?: string;}@@ -91,12 +87,8 @@ export const assertNeverGalleryItem = (item: never): never => {const compareSqliteBinaryText = (a: string, b: string): number => (a === b ? 0 : a < b ? -1 : 1);/**- * Chronological comparison across the two timestamp shapes the gallery mixes:- * backend rows carry SQLite's `created_at` ("2026-08-29 13:01:20.649") while- * overlaid recents carry the queue's `submittedAt` (ISO, "2026-08-29T02:28:40.566Z").- * Comparing the raw strings reads the 'T' separator as later than every- * space-separated time on the same day, so an older overlaid recent would sort- * above every newer backend image (and below them, with ascending order).+ * Normalize SQLite and ISO timestamps before comparing; their space/T separators otherwise misorder same-day+ * items.*/const compareCreatedAt = (a: string, b: string): number =>compareSqliteBinaryText(normalizeServerTimestamp(a), normalizeServerTimestamp(b));@@ -172,30 +164,11 @@ export const formatGalleryVideoDuration = (durationSeconds: number): string => {return `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;};-/**- * The media formats a gallery upload accepts, and the two things every upload surface needs- * from them: the file input's `accept` list and the kind a picked or dropped file uploads as.- *- * Both derive from one table so a picker cannot offer less than the upload route takes — the- * `accept` list and the classifier drifting apart is what left the gallery picker MP4-only- * while the video panel's reference picker took every format the server ingests.- *- * It lives here rather than in a module of its own on purpose: every upload surface is in the- * editor's initial graph, and a separate module is shared across enough chunk boundaries that- * Rolldown emits it standalone — an extra initial request, which the architecture budget pins- * exactly and refuses at any size. `items.ts` is already in that graph's `gallery-state` chunk.- */+/** Share upload acceptance and classification here to prevent drift without adding an initial bundle request. *//**- * Accepted for each kind in the browser's own terms. The server normalizes every accepted- * upload to H.264 MP4 at ingest — foreign containers/codecs (.mov, HEVC, …) are remuxed or- * transcoded and audio files are wrapped into waveform videos — so audio uploads as 'video'.- *- * Video and audio use wildcards, which the server backs with its own prefix check. Images do- * not: the image route takes anything PIL can open and re-encodes it, but offering only the- * three formats the app round-trips losslessly is a deliberate (and unchanged) narrowing. The- * extension lists mirror the video upload route's and are the fallback for a file whose type- * the OS could not map, which the browser then offers as application/octet-stream.+ * Audio uploads become waveform videos. Video/audio MIME wildcards mirror server checks; extensions cover unknown+ * MIME types. Images deliberately offer only round-trippable formats.*/const GALLERY_UPLOAD_FORMATS: Record<GalleryItemKind, { extensions: readonly string[]; mimes: readonly string[] }> = {image: {@@ -232,11 +205,8 @@ const GALLERY_UPLOAD_FORMATS: Record<GalleryItemKind, { extensions: readonly str};/**- * Ordered so a kind added later classifies after the existing ones. Kept as a literal- * rather than `Object.keys`: everything at this module's top level must stay a plain- * declaration the bundler can drop, or the barrels that re-export `items.ts` are retained- * in the editor's initial chunks. That is also why nothing here is precomputed into a Map —- * classification runs once per picked file, so a scan of ~30 entries costs nothing.+ * Keep top-level declarations tree-shakeable; scanning the small format table avoids retaining this module's+ * barrels.*/const GALLERY_UPLOAD_KINDS = ['image', 'video'] as const;diff --git a/invokeai/frontend/webv2/src/features/gallery/core/selection.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/selection.test.tsindex 78dd96563f..12e57d2a71 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/selection.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/selection.test.ts@@ -168,8 +168,7 @@ describe('getGalleryDeletionSuccessor', () => {});it('stays in the regular block when starred-first names lead the list', () => {- // Regression: the old earlier-first walk crossed the section boundary, so- // deleting the first regular item selected the LAST STARRED item.+ // Deleting a section's first item must not select the preceding section's last starred item.const orderedRefs = [ref('starred-1'), ref('starred-2'), ref('regular-1'), ref('regular-2')];expect(selection.getGalleryDeletionSuccessor(orderedRefs, 'image:regular-1', keys('regular-1'))).toEqual(@@ -191,9 +190,7 @@ describe('getGalleryNavigationStep', () => {const item = (name: string, starred = false): GalleryItem => ({ ...imageItem, name, starred });const session = (id: string, navigable = true) => ({ id, kind: 'session' as const, navigable });const entry = (name: string, starred = false) => ({ item: item(name, starred), kind: 'item' as const });- // Three columns: two in-progress rows (the second one a lone running tile- // beside nothing), a strip of five (a full row plus a partial one), then- // four listing items.+ // Sections have partial rows: four in-progress, five starred, then four listing items across three columns.const sections = [[session('p0'), session('p1', false), session('p2'), session('p3')],['s0', 's1', 's2', 's3', 's4'].map((name) => entry(name, true)),diff --git a/invokeai/frontend/webv2/src/features/gallery/core/selection.ts b/invokeai/frontend/webv2/src/features/gallery/core/selection.tsindex 2835ed7008..a6629948e8 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/selection.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/selection.ts@@ -131,20 +131,8 @@ export const getGalleryDeletionSuccessor = (};/*- * Reveal requests: an explicit "scroll this item into view" signal from- * surfaces outside the grid (the image map's reveal). Deliberately NOT derived- * from the selection, which also changes when a finished generation- * auto-selects its image — scrolling on that yanked the grid out from under a- * browsing user. A reveal is a deliberate gesture, so it gets its own channel,- * and a token, so repeating the same gesture (re-clicking the same map point- * after scrolling away) reveals again even though the selection is unchanged.- *- * Module-scoped rather than persisted: a reveal is an ephemeral intent for the- * currently mounted grid, and persisting it would replay a stale scroll in the- * next session. It lives here, beside the selection helpers it travels with,- * rather than in a module of its own — a separate one becomes a separate chunk- * and an extra request in the gallery widget's load, which the performance- * budgets police.+ * Explicit, tokenized reveals can repeat without selection changes. Keep them ephemeral to avoid replaying stale+ * scrolls; colocating avoids another gallery chunk.*/export interface GalleryRevealRequest {@@ -176,18 +164,8 @@ export const subscribeGalleryRevealRequests = (listener: () => void): (() => voi};/*- * Navigation ordering. A reveal resolves its item over the network before it- * touches anything, so two gestures in flight can land out of order; the newer- * one must win. The counter is module-scoped for the same reason the reveal- * channel above is: the thing it guards — the gallery selection — is global, so- * a per-mount ref leaves a hole whenever a caller unmounts with a hydrate in- * flight (switching the right-panel tab away and back), where the abandoned- * closure compares against its own dead ref, passes, and overwrites the newer- * mount's selection. One counter spans every surface that navigates the grid.- *- * It lives here rather than beside the reveal that uses it because that module- * is loaded on demand, and a caller which defers it still has to take its place- * in the ordering at the moment of the press.+ * Order navigation gestures across mounts and surfaces before async hydration; only the latest may update the+ * shared selection.*/let navigationSequence = 0;@@ -199,11 +177,8 @@ export const claimGalleryNavigationSequence = (): number => ++navigationSequenceexport const isGalleryNavigationCurrent = (sequence: number): boolean => sequence === navigationSequence;/*- * Sectioned navigation. The gallery lays out three sections in one visual- * order — the in-progress tiles, the starred strip, the listing — and Preview- * walks the same order, so one sequence model serves both: left/right walk the- * flat order across the seams, up/down keep the column across them. The cursor- * is a key: a followed session's, or the selected item's.+ * Grid and Preview share section order; horizontal navigation crosses seams while vertical navigation preserves+ * columns.*/export type GalleryNavigationEntry =@@ -221,12 +196,8 @@ const isNavigable = (entry: GalleryNavigationEntry | undefined): entry is Gallerentry !== undefined && (entry.kind === 'item' || entry.navigable);/**- * The entry an arrow key lands on, or null when there is nowhere to go. Each- * section chunks its own rows, so a vertical step across a seam keeps its- * column instead of drifting by the previous section's partial last row; a- * row whose landing cell is not navigable yields its nearest navigable cell,- * and a row with none is skipped. Without a cursor, any key lands on the- * first navigable entry.+ * Each section starts its own rows. Vertical navigation preserves columns, selects the nearest navigable cell, and+ * skips empty rows; no cursor starts at the first entry.*/export const getGalleryNavigationStep = (sections: readonly (readonly GalleryNavigationEntry[])[],diff --git a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.tsindex 0c4c88bb98..227a14ba55 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts@@ -40,10 +40,8 @@ describe('image cluster registry', () => {});it('prunes a deleted video member, which is why the delete patch keys by kind', () => {- // Video deletions used to be filtered out of the prune, so a cluster kept- // counting a clip that no longer existed: the member list is client-owned,- // so no refetch reconciles it, and the trailing page holds a cell that can- // never hydrate.+ // Video deletions must prune client-owned cluster members; refetching cannot repair their counts or trailing+ // pages.const clusterId = registerImageCluster(['image:a.png', 'video:clip.mp4'], 'beaches');const rollback = pruneImageClusterMembers(['video:clip.mp4']);diff --git a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.tsindex f2aff69513..d2471bf1a4 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts@@ -1,10 +1,5 @@import type { GalleryItemKey } from './items';-/**- * Identity of a semantic gallery search: a text prompt, a gallery image, a- * web image URL, a dropped file held in the external-image registry, or an- * image-map cluster held in the cluster registry.- */export type GallerySemanticQuery =| { kind: 'text'; query: string }| { kind: 'image'; imageName: string }@@ -12,10 +7,6 @@ export type GallerySemanticQuery =| { kind: 'file'; fileId: string }| { kind: 'cluster'; clusterId: string };-/**- * A persisted semantic search: a text prompt, a gallery image, a web URL, a- * dropped file, or an image-map cluster.- */export type GallerySemanticReference =| { kind: 'text'; query: string }| { kind: 'image'; imageName: string }@@ -47,10 +38,7 @@ export const gallerySemanticReferenceKey = (reference: GallerySemanticReference}};-/**- * The reference a semantic-search field commits for its text: whitespace is- * not a query, so blank text reads as no search at all.- */+/** Blank or whitespace-only text means no semantic search. */export const toGallerySemanticTextReference = (text: string): GallerySemanticReference | null => {const query = text.trim();@@ -74,11 +62,8 @@ export const toGallerySemanticQuery = (reference: GallerySemanticReference): Gal};/*- * In-memory registry for externally dropped reference images (OS file drops).- * Blobs cannot live in persisted widget values, so the persisted value keeps a- * registry key; a key that no longer resolves (e.g. after a reload) reads as a- * cleared search. Only one external query is active at a time, so registering- * a new file evicts the previous one.+ * Persist only a registry key for dropped blobs. New files evict the previous entry; unresolved keys clear the+ * search.*/let nextId = 0;@@ -101,16 +86,8 @@ export const registerExternalImageFile = (blob: Blob, label: string): string =>export const getExternalImageFile = (fileId: string): { blob: Blob; label: string } | null => files.get(fileId) ?? null;/*- * In-memory registry for image-map cluster queries, mirroring the file- * registry above: a cluster's member list (which can run to thousands of- * items) cannot live in persisted widget values, so the persisted value keeps- * a registry key, and a key that no longer resolves (e.g. after a reload)- * reads as a cleared search. Only one cluster query is active at a time, so- * registering a new cluster evicts the previous one.- *- * Members are item keys rather than bare names: a cluster on the map can hold- * videos as well as images, and the gallery resolves each member through the- * endpoint its kind names.+ * Keep large cluster membership lists in memory under one persisted key. Members include media kinds; new+ * registrations evict old ones and unresolved keys clear search.*/let nextClusterId = 0;@@ -119,9 +96,8 @@ const clusters = new Map<string, { itemKeys: GalleryItemKey[]; label: string }>(export const registerImageCluster = (itemKeys: GalleryItemKey[], label: string): string => {nextClusterId += 1;- // Same shape as file ids: the random token keeps a persisted id from a- // previous JS realm (another tab, a reload) from resolving to this realm's- // unrelated cluster.+ // Per-realm random tokens prevent persisted keys from resolving to unrelated clusters after reload or in another+ // tab.const clusterId = `cluster-${String(nextClusterId)}-${Math.random().toString(36).slice(2, 10)}`;clusters.clear();@@ -134,11 +110,8 @@ export const getImageCluster = (clusterId: string): { itemKeys: GalleryItemKey[]clusters.get(clusterId) ?? null;/**- * Drops deleted items from the registered cluster, in step with the gallery's- * optimistic cache patch: the member list is client-owned, so without this the- * cluster view's total (and its trailing page) would keep counting items that- * no longer exist. Returns a rollback that puts back exactly the members THIS- * call removed — a no-op once a different registration owns the slot.+ * Prune deleted members from the client-owned cluster. Rollback restores only this call's removals and only while+ * the same registration owns the slot.*/export const pruneImageClusterMembers = (itemKeys: readonly GalleryItemKey[]): (() => void) => {const entry = [...clusters.entries()].at(0);@@ -170,12 +143,7 @@ export const pruneImageClusterMembers = (itemKeys: readonly GalleryItemKey[]): (return;}- // Rebuilt from the pre-prune order rather than swapped back wholesale, so- // that a concurrent deletion's prune (or its rollback) landing in between- // survives: whatever this call did not remove keeps whatever state the- // other call left it in. Restoring the captured array instead would either- // resurrect that deletion's items or — guarded on identity — skip the- // restore entirely and strand a failed deletion's item outside the list.+ // Restore only this call's removals in their original order, preserving concurrent prunes and rollbacks.const restored = new Set([...current.itemKeys, ...removedKeys]);clusters.set(clusterId, {@@ -191,14 +159,8 @@ export const pruneImageClusterMembers = (itemKeys: readonly GalleryItemKey[]): (* in the registry as no search at all.*//**- * A reference that only this session can resolve — a dropped file or an- * image-map cluster.- *- * Both kinds name an entry in an in-memory registry, and their ids carry a- * per-realm token, so a persisted one can never resolve again: a reload, or a- * second tab, reads it as no search at all. Anything set against the ranking- * it named — the page the footer was on, above all — describes a list that- * will not exist there either.+ * File and cluster references resolve only in their originating realm; positions within their rankings cannot+ * survive reload or cross-tab restoration.*/const isSessionScopedGallerySemanticReference = (value: unknown): boolean =>!!value &&@@ -206,18 +168,8 @@ const isSessionScopedGallerySemanticReference = (value: unknown): boolean =>((value as Record<string, unknown>).kind === 'file' || (value as Record<string, unknown>).kind === 'cluster');/**- * The same values with every position that was set against a ranking the- * caller's test rejects, or null when there is nothing to drop.- *- * While a similarity search is on screen the footer paginates the RANKING, so- * the gallery's page and the page stamped on the selection are both indexes- * into it. Left behind by a search that is gone, they are read as board pages- * and answer with an unrelated slice. Only keys that are actually carrying a- * position are rewritten: normalizing must not mint state that was never- * stored.- *- * The test differs by caller, and the difference matters. See- * `stripSessionScopedGallerySearch` and `stripUnresolvableGallerySearch`.+ * Drop existing positions tied to rejected rankings so they cannot become unrelated board-page offsets. Do not+ * create absent state.*/const stripGallerySearchPositions = (values: Record<string, unknown>,@@ -250,16 +202,8 @@ const stripGallerySearchPositions = (};/**- * The same values with an infinite window's mid-board anchor dropped, or null- * when there is none.- *- * In infinite mode `galleryPage` is not a page number but the anchor of a- * mid-board window, set by a reveal from the image map. That is a "you are- * here" for the session that made it: restored anywhere else it opens the- * gallery stranded in the middle of a board, with no page control (the- * footer's is paginated-only) and no way back to the top short of switching- * boards. Paginated pages stay — there the value really is the page the user- * was reading.+ * Drop infinite-window anchors on restoration to avoid stranding users mid-board without pagination controls.+ * Preserve actual paginated page numbers.*/export const stripInfiniteWindowAnchor = (values: Record<string, unknown>): Record<string, unknown> | null =>values.paginationMode !== 'paginated' && typeof values.galleryPage === 'number' && values.galleryPage > 0@@ -267,12 +211,8 @@ export const stripInfiniteWindowAnchor = (values: Record<string, unknown>): Reco: null;/**- * For the SAVE path: drop what the realm reading this back will not have.- *- * A dropped file or an image-map cluster names an entry in an in-memory- * registry, and its id carries a per-realm token, so it resolves here and- * nowhere else — the test has to be what the value IS, not whether it works- * right now, because right now it does.+ * Saving strips all realm-scoped references, even those that currently resolve, because another realm cannot use+ * them.*/export const stripSessionScopedGallerySearch = (values: Record<string, unknown>): Record<string, unknown> | null =>stripGallerySearchPositions(@@ -282,16 +222,7 @@ export const stripSessionScopedGallerySearch = (values: Record<string, unknown>)(value !== null && value !== undefined && parseGallerySemanticReference(value) === null));-/**- * For the ADOPTION path: drop only what this realm cannot resolve.- *- * `normalizeWorkbenchProject` runs on projects that never left — closing and- * reopening one, a conflict fork rescuing the live copy, an export re-imported- * into the same session. There the registry entry is still live and the- * ranking is still on screen, so asking what the value IS would delete the- * search the user is looking at. Asking whether it resolves HERE answers both- * cases with one test.- */+/** Adoption strips only unresolved references: same-session reopen, fork, or import can retain a live ranking. */export const stripUnresolvableGallerySearch = (values: Record<string, unknown>): Record<string, unknown> | null =>stripGallerySearchPositions(values,@@ -320,8 +251,6 @@ export const parseGallerySemanticReference = (value: unknown): GallerySemanticRe}if (record.kind === 'file' && typeof record.fileId === 'string' && record.fileId) {- // Dropped files live in an in-memory registry; a persisted key that no- // longer resolves (e.g. after a reload) reads as no search at all.if (getExternalImageFile(record.fileId) === null) {return null;}@@ -334,8 +263,6 @@ export const parseGallerySemanticReference = (value: unknown): GallerySemanticRe}if (record.kind === 'cluster' && typeof record.clusterId === 'string' && record.clusterId) {- // Cluster members live in an in-memory registry; a persisted key that- // no longer resolves (e.g. after a reload) reads as no search at all.const cluster = getImageCluster(record.clusterId);if (cluster === null) {@@ -357,11 +284,8 @@ export const parseGallerySemanticReference = (value: unknown): GallerySemanticReconst APP_IMAGE_PATH = /\/api\/v\d+\/images\/i\/([^/]+)\//;/**- * Interpret a native drop for image-similarity search. Files win over URLs;- * a URL pointing at this app's own image endpoint becomes a by-name query- * (dragging the preview image in must not round-trip through the server's- * URL downloader — it would be refused as a private-address fetch); anything- * else http(s) is searched as a web image. Returns null for unusable drops.+ * Files take precedence over URLs. Resolve this app's image URLs by name to avoid private-address download+ * rejection; other HTTP(S) URLs use web-image search.*/export const semanticReferenceFromDataTransfer = (dataTransfer: {files: ArrayLike<File>;diff --git a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts b/invokeai/frontend/webv2/src/features/gallery/core/settings.tsindex 1b04415c5b..42a71db2e2 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/settings.ts@@ -31,11 +31,7 @@ export interface GallerySettings {showArchivedBoards: boolean;showDateBoards: boolean;showImageDimensions: boolean;- /**- * Boards owned by another project. They are readable and already labelled- * with a project badge; this hides them for anyone who wants the panel to- * be about the project they have open.- */+ /** Hide readable, project-labelled boards belonging to other projects. */showOtherProjectBoards: boolean;showPendingItems: boolean;progressSectionCollapsed: boolean;diff --git a/invokeai/frontend/webv2/src/features/gallery/core/types.ts b/invokeai/frontend/webv2/src/features/gallery/core/types.tsindex e94145323f..2614f5aea1 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/types.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/types.ts@@ -40,13 +40,8 @@ export interface GalleryBoard {createdAt?: string | null;ownerName?: string | null;/**- * The project that owns this board, or `null` for an ordinary one.- *- * A project's board is part of that project: it takes its name from it, is- * deleted with it, and the generic board routes refuse to rename, archive or- * delete it. The UI hides those actions for *any* project-owned board, not just- * the open project's — the server is authoritative either way, so a stale- * client is refused rather than obeyed.+ * Project ownership controls naming and deletion; generic board actions must exclude all project-owned boards.+ * Null denotes an ordinary board.*/projectId: string | null;}diff --git a/invokeai/frontend/webv2/src/features/gallery/core/videoPaths.ts b/invokeai/frontend/webv2/src/features/gallery/core/videoPaths.tsindex dd610c9807..173b623da8 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/videoPaths.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/videoPaths.ts@@ -1,9 +1,6 @@/**- * Backend-relative video media paths, mirroring {@link ./imagePaths}.- *- * Both routes authenticate with the path-scoped media cookie rather than a bearer header,- * because `<video>` and `<img>` cannot set request headers. The full route additionally- * serves HTTP Range requests, which the `<video>` element issues on its own for seeking.+ * Media cookies authenticate video routes because elements cannot set bearer headers. The full route supports+ * native Range requests for seeking.*/export const getGalleryVideoThumbnailPath = (videoName: string): string =>diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.tsindex 959bacd2c5..c6e9c608de 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts@@ -653,14 +653,11 @@ describe('imageMakeDurableChanges', () => {describe('imageMakeCanvasAssetChanges', () => {it('makes the image durable AND moves it out of the gallery images view', () => {- // A node's output is `general` — precisely what the Images view lists — so- // durability alone published every ControlNet preprocess into the gallery.+ // Durability alone leaves node outputs in `general`, publishing preprocess results to Images.expect(imageMakeCanvasAssetChanges()).toEqual({ image_category: 'other', is_intermediate: false });});it('uses the same category the canvas uploads its own paint bitmaps under', () => {- // Layer pixels are layer pixels however they were produced; a filtered- // control map must not be classified differently from a painted one.expect(imageMakeCanvasAssetChanges().image_category).toBe('other');});@@ -683,10 +680,7 @@ describe('gallery category queries', () => {};it('never asks the assets view for the canvas-owned category', async () => {- // The regression this guards: canvas paint bitmaps, composites and adopted- // filter results all upload as `other`. While `other` was an assets- // category, every brush stroke and every generation put an image in the- // user's Assets tab.+ // Canvas-owned `other` images must stay out of Assets, including brush strokes and adopted filter results.expect(await categoriesFor('assets')).not.toContain('other');});diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.tsindex bf9f8048c3..25a798ef37 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts@@ -130,12 +130,7 @@ interface ListImagesResponse {total: number;}-/**- * Mirrors the backend's `IMAGE_CATEGORIES` / `ASSETS_CATEGORIES`- * (`image_records_common.py`). `'other'` is in neither: it is the private- * category for images a canvas layer owns, which are layer pixels rather than- * gallery content and so belong to neither view.- */+/** Mirror backend gallery categories; canvas-owned `other` pixels belong to neither Images nor Assets. */const imageCategories = ['general'];const assetCategories = ['control', 'mask', 'user'];@@ -213,11 +208,7 @@ const getGalleryTotal = async ({return body.total;};-/**- * Counts non-intermediate videos on a board, optionally restricted to a category set —- * the same general/asset split the images use (uploaded videos are 'user', generated- * are 'general').- */+/** Count non-intermediate videos with the same general/asset category split as images. */const getGalleryVideoTotal = async ({boardId,categories,@@ -248,11 +239,7 @@ const mapImage = (image: BackendImageDTO): GalleryImage => ({width: image.width,});-/**- * The `media_origin` marker as a string, or absent. The server coerces this, but the mapper- * validates what it is handed here the same way it validates `duration` -- a marker of any- * other shape means the same thing as no marker.- */+/** Treat non-string media_origin markers as absent. */const mediaOriginOf = (value: string | null | undefined): { mediaOrigin?: string } =>typeof value === 'string' && value ? { mediaOrigin: value } : {};@@ -390,10 +377,7 @@ export const listGalleryBoards = async ({];};-/**- * Date boards are now derived from the polymorphic gallery service, so a date can exist- * because of videos alone — its `image_count` may be 0 while the board is non-empty.- */+/** Date boards can contain only videos; zero image_count does not imply an empty board. */interface VirtualDateBoardDTO {virtual_board_id: string;board_name: string;@@ -538,8 +522,7 @@ const listPaletteDateBoardImageNames = async ({searchTerm: string;signal?: AbortSignal;}): Promise<PaletteDateBoardImageNames> => {- // Palette results remain intentionally image-only, but derive from the- // polymorphic item_names endpoint so no webv2 path regresses to image_names.+ // Keep palette results image-only while using the polymorphic item_names endpoint.const result = await listGalleryDateBoardItemNames({boardId,createdFrom,@@ -785,23 +768,16 @@ export interface GallerySemanticResult {type SemanticSearchBody = { results: { image_name: string; kind?: string; score: number }[] };const toSemanticResults = (body: SemanticSearchBody): GallerySemanticResult[] =>- // `image_name` carries the name whatever the kind is; `kind` says which- // namespace it belongs to. Only `video` names the other namespace — anything- // else reads as an image, which is the kind every hit used to be.+ // `image_name` serves both namespaces; only kind `video` selects videos, preserving image fallback for other+ // values.body.results.map((result) => ({ref: { kind: result.kind === 'video' ? 'video' : 'image', name: result.image_name },score: result.score,}));/**- * Ranks the caller's accessible gallery items by similarity to the query. Text- * and gallery-image queries hit the GET endpoint; URLs and dropped files POST- * to the by-image endpoint (the file as multipart from the external-image- * registry).- *- * `include_videos` is what opts this client into video results: the backend- * indexes them either way and serves them only to clients that say they can- * resolve each hit through the endpoint its kind names, which this one does.+ * Text and gallery-image searches use GET; URLs and registered files use POST. include_videos opts into kind-aware+ * result hydration.*/export const searchGallerySemantic = async (query: Exclude<GallerySemanticQuery, { kind: 'cluster' }>,@@ -850,10 +826,6 @@ export const searchGallerySemantic = async (return toSemanticResults(await apiFetchJson<SemanticSearchBody>(`/api/v1/image_map/search?${params}`, { signal }));};-/**- * Whether the server can rank a text query: not configured at all, configured- * but without its embedding model, or ready.- */export interface ImageIndexAvailability {state: 'disabled' | 'model_missing' | 'ready';/** The configured embedding model's name; set only while it is missing. */@@ -866,11 +838,8 @@ interface ImageIndexStatusBody {}/**- * Read from the map's status endpoint, whose `enabled` is "the index has its- * model": text search needs exactly that and the stored embeddings, and never- * the map's projection, so the projection half of the response is not read.- * `model_name` is set only when indexing is configured and the model is- * missing, which is what separates that case from a disabled index.+ * Search requires indexed embeddings and their model, not map projection. model_name distinguishes a missing+ * configured model from a disabled index.*/export const fetchImageIndexAvailability = async (signal: AbortSignal): Promise<ImageIndexAvailability> => {const body = await apiFetchJson<ImageIndexStatusBody>('/api/v1/image_map/status', { signal });@@ -884,12 +853,7 @@ export const fetchImageIndexAvailability = async (signal: AbortSignal): Promise<: { modelName: null, state: 'disabled' };};-/**- * The ranked result set as item refs, in relevance order. Pages hydrate- * slices of this list (`hydrateGalleryDateBoardItemPage`), and range- * selection / deletion neighbors read it directly. Results carry both media- * kinds: an indexed gallery is its images plus its videos.- */+/** Kind-qualified refs retain relevance order for page hydration, range selection, and deletion neighbors. */export const listSemanticGalleryItemNames = async ({query,signal,@@ -966,11 +930,8 @@ export const listPaletteImages = async ({};/**- * The `ImageRecordChanges` body that promotes a staged canvas candidate (an- * intermediate image) into a durable, gallery-visible image: clearing- * `is_intermediate` stops it being garbage-collected, and `image_category:- * 'general'` surfaces it in the gallery's images view. Pure so the request- * shape can be unit-tested without a fetch.+ * Promote staged candidates by clearing is_intermediate and setting category general, making them durable and+ * gallery-visible.*/export const imageSaveToGalleryChanges = (): { is_intermediate: false; image_category: 'general' } => ({image_category: 'general',@@ -978,30 +939,16 @@ export const imageSaveToGalleryChanges = (): { is_intermediate: false; image_cat});/**- * The `ImageRecordChanges` body that makes an intermediate image durable without- * changing its category. Clearing `is_intermediate` stops garbage collection;- * where the image appears is determined by its existing category.- *- * NOT for adopting a graph result as canvas pixels — a node's output is- * `general`, so this alone publishes it to the gallery's Images view. Use- * {@link imageMakeCanvasAssetChanges} there.+ * Clear is_intermediate without changing category. Canvas adoption must use {@link imageMakeCanvasAssetChanges} to+ * avoid publishing general outputs.*/export const imageMakeDurableChanges = (): { is_intermediate: false } => ({is_intermediate: false,});/**- * The `ImageRecordChanges` body that adopts a utility result as CANVAS-OWNED- * pixels: durable (so it is not garbage-collected out from under the layer that- * now points at it) and `image_category: 'other'`, the category the canvas- * already uploads its own paint bitmaps under.- *- * A node's output is `general` by default, which is exactly what the gallery's- * Images view lists — so promoting a control-layer filter result with- * {@link imageMakeDurableChanges} alone published every ControlNet preprocess- * into the user's gallery. These are layer pixels, not gallery images, and- * `'other'` belongs to neither {@link imageCategories} nor- * {@link assetCategories}, so they surface in neither view.+ * Adopt utility results as durable `other` pixels, excluded from both gallery views; durability alone leaves+ * general outputs visible.*/export const imageMakeCanvasAssetChanges = (): { is_intermediate: false; image_category: 'other' } => ({image_category: 'other',@@ -1009,10 +956,8 @@ export const imageMakeCanvasAssetChanges = (): { is_intermediate: false; image_c});/**- * Makes a single intermediate image durable (survives GC) without changing its- * category, via `PATCH /api/v1/images/i/{image_name}`. Resolves once the PATCH- * succeeds; the caller commits the layer-source swap only after this settles so a- * failed PATCH never strands the layer pointing at a soon-to-be-collected image.+ * Await the durability PATCH before committing a layer-source swap; failed promotion must not leave a layer+ * referencing collectible pixels.*/export const makeImageDurable = async (imageName: string): Promise<void> => {await apiFetchJson<BackendImageDTO>(`/api/v1/images/i/${encodeURIComponent(imageName)}`, {@@ -1022,10 +967,8 @@ export const makeImageDurable = async (imageName: string): Promise<void> => {};/**- * Adopts a utility result as canvas-owned pixels — durable AND out of the- * gallery's Images view. Used wherever a graph result becomes a layer's- * persisted source; {@link makeImageDurable} remains for callers that must keep- * whatever category the image already had.+ * Adopt graph results as durable canvas pixels outside Images; {@link makeImageDurable} instead preserves the+ * current category.*/export const makeImageCanvasAsset = async (imageName: string): Promise<void> => {await apiFetchJson<BackendImageDTO>(`/api/v1/images/i/${encodeURIComponent(imageName)}`, {@@ -1034,10 +977,7 @@ export const makeImageCanvasAsset = async (imageName: string): Promise<void> =>});};-/**- * Promotes a single image (e.g. a staged canvas candidate) into the gallery via- * `PATCH /api/v1/images/i/{image_name}` and returns the updated {@link GalleryImage}.- */+/** Promote an image into the gallery and return its updated {@link GalleryImage}. */export const saveImageToGallery = async (imageName: string): Promise<GalleryImage> => {const body = await apiFetchJson<BackendImageDTO>(`/api/v1/images/i/${encodeURIComponent(imageName)}`, {body: JSON.stringify(imageSaveToGalleryChanges()),@@ -1267,14 +1207,7 @@ export const deleteGalleryImageItems = async (};};-/**- * Deletes images and reports the outcome per name.- *- * The backend deletes each name independently and no longer aborts the batch on the first- * failure, so a request can partly succeed. Callers must evict only `deletedImageNames` from- * their caches — treating the whole request as successful would hide a still-present image- * until the next full refresh.- */+/** Deletion can partially succeed. Evict only deletedImageNames; other names may still exist on the server. */export const deleteGalleryImages = async (imageNames: string[],signal?: AbortSignal@@ -1441,11 +1374,7 @@ export const moveGalleryVideoItemsToBoard = async (const BULK_DOWNLOAD_POLL_INTERVAL_MS = 2000;const BULK_DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;-/**- * Starts a bulk download (a zip prepared in a backend background task) and- * polls the artifact endpoint until it exists. Returns the archive blob and- * its file name.- */+/** Poll the background bulk-download artifact until ready, then return its blob and filename. */export const downloadGalleryArchive = async ({boardId,imageNames,diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.tsindex 3ac4692d3f..449e1f5184 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts@@ -242,9 +242,7 @@ describe('Gallery item query read model', () => {});it('anchors an infinite window at its offset, sharing the base key only at offset 0', async () => {- // A zero-offset window must keep the historical key so every existing- // consumer shares one cache entry; a deep window (a reveal past the base- // reach) is its own transient entry starting at its own page.+ // Base windows retain shared historical keys; deep reveals receive distinct transient window entries.expect(galleryItemsInfiniteOptions(baseFilter, { kind: 'infinite', offset: 0 }).queryKey).toEqual(galleryItemsInfiniteOptions(baseFilter).queryKey);@@ -278,11 +276,8 @@ describe('Gallery item query read model', () => {});it('never grows an anchored infinite window above its anchor, but still lets paginated anchors', () => {- // The grid shares the anchored entry and cannot request earlier pages- // itself, so a prepend would splice 60 items in above its viewport and- // shift the content under the user. Paginated consumers slice out the one- // page they want by pageParam, so prepending is invisible there — and- // Preview walks backwards through exactly that mechanism.+ // Infinite windows must not prepend and shift the viewport. Paginated consumers select by pageParam, allowing+ // Preview to load backward safely.const page: GalleryItemsPage = { items: [], total: 20_000 };const onePage = [page];const anchored = galleryItemsInfiniteOptions(baseFilter, { kind: 'infinite', offset: 6000 });@@ -419,11 +414,8 @@ describe('canonicalizeGalleryItemsFilter under a semantic query', () => {const reference = { fileId: 'external-1-abc', kind: 'file', label: 'shot.png' } as const;it('ignores the controls a ranked result set does not answer to', () => {- // The semantic branch sends only the reference, so board, view, order,- // the starred filter and the date range change nothing about the response.- // While they stayed in the key, clicking a board minted a fresh key and- // re-ran the search — re-uploading the dropped blob, or making the server- // re-download a remote URL, to render byte-identical results.+ // Semantic results depend only on the reference; unrelated filters must not repeat blob uploads or remote+ // downloads.const base = canonicalizeGalleryItemsFilter({boardId: 'board-a',galleryView: 'images',@@ -499,9 +491,7 @@ describe('imageIndexAvailabilityOptions', () => {};it('polls only while the answer can still change on its own', () => {- // A model the server keeps re-checking for, or a call that failed, are- // worth asking again; a settled answer is not, so a ready index does not- // cost a status call every half minute for the whole session.+ // Retry missing-model and failed statuses; settled readiness must not poll for the whole session.expect(pollFor({ data: { modelName: 'clip', state: 'model_missing' }, status: 'success' })).toBe(IMAGE_INDEX_UNAVAILABLE_POLL_MS);diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.tsindex 6b7d0626e1..4f372c28bc 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts@@ -82,11 +82,8 @@ export interface CanonicalGalleryItemsFilter {}/**- * An infinite window can start below the top of the listing: `offset` (a row- * offset, normalized to a page multiple, default 0) anchors where the window- * begins, and the `GALLERY_MAX_ROWS` reach applies from there. This is what- * lets a reveal land the gallery on an image deeper than the base window- * could ever load — every board/search/view change resets the anchor to 0.+ * Offset anchors a page-aligned infinite window with GALLERY_MAX_ROWS reach. Board, search, and view changes reset+ * it to zero.*/export type GalleryItemsWindow = { kind: 'anchor'; offset: number } | { kind: 'infinite'; offset?: number };@@ -124,16 +121,8 @@ export const canonicalizeGalleryItemsFilter = (filter: GalleryItemsFilter): Canoconst semantic = filter.semanticQuery ? toGallerySemanticQuery(filter.semanticQuery) : undefined;if (semantic) {- // A ranked result set answers to the reference alone: the semantic branch- // of `galleryItemNamesOptionsForOwner` sends only the query, so board,- // view, order, the starred filter and the date range change nothing about- // the response. Keeping them in the key made clicking a board — or toggling- // the starred filter, or switching the images/assets tab — mint a fresh key and- // re-run the search for byte-identical results, which for a dropped file- // means re-uploading the blob and for a URL reference means the server- // re-downloads the remote image. Pinned rather than omitted so the shape- // stays a `CanonicalGalleryItemsFilter`; the values are never read on this- // path, only compared.+ // Pin irrelevant filter fields to canonical values: semantic rankings depend only on the query, and distinct+ // keys would repeat uploads or downloads.return {boardId: '',galleryView: 'images',@@ -168,8 +157,7 @@ const getWindowKey = (if (window.kind === 'infinite') {const offset = normalizePageOffset(window.offset ?? 0);- // A zero offset keeps the historical key shape, so every existing- // consumer of the base window shares one cache entry with it.+ // Preserve the zero-offset key so base-window consumers share one cache entry.return offset === 0 ? [] : (['infinite', offset] as const);}@@ -307,10 +295,8 @@ const fetchSharedDateBoardNames = (};/**- * One range read of a filter's listing, shared by the per-page queryFn and- * the window rebuild so the two cannot diverge. Name-list filters hydrate a- * slice of one shared name fetch — re-running a semantic search re-uploads a- * dropped file's blob. The result is clamped to `limit`.+ * Share one range reader between pages and rebuilds. Name-list filters hydrate slices of a shared fetch to avoid+ * repeating semantic uploads; clamp to limit.*/export const fetchGalleryItemsRange = async (client: QueryClient,@@ -340,11 +326,8 @@ export const fetchGalleryItemsRange = async (};/**- * Polled only while the answer is "not yet": a missing model that the server- * re-checks for on its own, or a status call that failed outright. A settled- * answer is re-read only when a fresh consumer mounts after the stale time,- * so a model removed mid-session is noticed on the next layout change- * without the field polling a ready index for the whole session.+ * Poll missing-model and failed statuses only. Settled status refreshes on a new stale consumer, including after+ * layout changes.*/export const IMAGE_INDEX_UNAVAILABLE_POLL_MS = 30_000;const IMAGE_INDEX_STALE_MS = 5 * 60_000;@@ -431,13 +414,8 @@ export const galleryItemsInfiniteOptions = (? undefined: getNextPageParam(normalizedWindow, lastPage, lastPageParam),getPreviousPageParam: (_firstPage, allPages, firstPageParam) => {- // An anchored INFINITE window must not grow upward past its anchor: its- // cache key names that start offset, and the grid — which shares the- // entry and cannot request earlier pages itself — would have 60 items- // spliced in above its viewport, shifting the content under the user.- // Paginated anchors keep growing freely: their consumer slices out the- // one page it wants by pageParam, so a prepend is invisible there, and- // Preview walks backwards through exactly this mechanism.+ // Infinite windows cannot prepend above their anchor without shifting the viewport. Paginated windows may+ // prepend because consumers select by pageParam.const lowestPageParam = normalizedWindow.kind === 'infinite' ? normalizedWindow.offset : 0;return allPages.length < GALLERY_MAX_INFINITE_PAGES && firstPageParam - GALLERY_PAGE_SIZE >= lowestPageParamdiff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.tsindex eb09c7be5b..5170b3b308 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts@@ -198,10 +198,7 @@ describe('Gallery item cache patches', () => {});it('prunes a deleted video from the active cluster filter, and restores it on rollback', () => {- // The cluster's member list is client-owned, so nothing on the server can- // reconcile it: a video deletion that skipped the prune would leave the- // cluster view counting a clip that no longer exists, with a trailing page- // cell that can never hydrate.+ // Prune deleted videos from client-owned cluster membership; server refetches cannot repair its count.const client = createClient();const clusterId = registerImageCluster(['image:kept.png', 'video:gone.mp4'], 'beaches');diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.tsindex 27a04609e0..383209f66a 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts@@ -97,12 +97,7 @@ const mapPageItems = (};};-/**- * Whether a patch takes matching items out of a listing with this filter.- * Ranked similarity windows are board-agnostic (a move never changes- * membership); a starred-only listing — the strip, or the grid under the- * starred filter — loses an item the moment it is unstarred.- */+/** Ranked windows ignore board moves; starred-only listings lose items immediately when unstarred. */const patchRemovesItems = (filter: CanonicalGalleryItemsFilter, patch: GalleryItemCachePatch): boolean => {if (patch.kind === 'delete') {return true;@@ -246,11 +241,7 @@ export const patchGalleryItemCaches = (client: QueryClient, patch: GalleryItemCa};};-/**- * Reads the board each requested item currently sits on, from whichever list- * cache holds it. Optimistic moves capture this before patching so a rejected- * ref can be put back without waiting for the reconciling refetch.- */+/** Capture cached source boards before optimistic moves so rejected refs can be restored before refetch. */export const getGalleryItemBoardIdsFromCaches = (client: QueryClient,refs: readonly GalleryItemRef[]@@ -278,10 +269,8 @@ export const getGalleryItemBoardIdsFromCaches = (};/**- * Reads the starred flag each requested item currently has, from whichever- * list cache holds it. Optimistic star/unstar captures this before patching- * so a totally-failed batch can restore each item's actual prior flag rather- * than blanket-inverting the whole request.+ * Capture each cached starred flag before mutation; failed batches must restore actual prior values rather than+ * invert the request.*/export const getGalleryItemStarredFromCaches = (client: QueryClient,@@ -493,9 +482,8 @@ const runGalleryInvalidation = async (const rebuiltQueryHashes = new Set<string>();- // An ACTIVE multi-page window swaps in one span read — collapsing it- // rearranges the rows under the user; unwatched windows just collapse to- // their pinned page and regrow on the next mount.+ // Rebuild active windows in one span to preserve viewport rows; unobserved windows collapse to their pinned+ // page.for (const query of getGalleryItemListQueries(client, owner)) {const data = query.state.data;@@ -530,9 +518,8 @@ interface GalleryInvalidationState {const galleryInvalidations = new WeakMap<QueryClient, Map<string, GalleryInvalidationState>>();/**- * Coalesces same-tick mutation/result bursts and performs at most one trailing- * pass when another request arrives during an active invalidation. This avoids- * repeatedly cancelling and restarting the same observed Gallery refetch.+ * Coalesce same-tick invalidations with at most one trailing pass to avoid cancelling and restarting observed+ * refetches.*/const scheduleGalleryInvalidation = (client: QueryClient,diff --git a/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.ts b/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.tsindex 5eee51f8e7..9f6d34bbed 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.ts@@ -13,16 +13,8 @@ export interface GalleryRealtimeRuntime {}/**- * Refreshes the Gallery read model for content that arrives without a queue- * event: uploads through the API from scripts, other clients, or other tabs,- * and anything that landed while the socket was down.- *- * Uploads are not paced by generation the way queue events are, and every- * invalidation pass cancels the page fetches under the user. So passes are held- * at least `minIntervalMs` apart: an event arriving while one is pending rides- * along, and one arriving after a pass waits out the rest of the interval, so a- * trailing pass is always guaranteed. Uploads spaced wider than that interval- * still get a pass each, which is the point -- each one is new media to show.+ * Refresh external uploads and reconnects at least minIntervalMs apart. Coalesce pending events and guarantee a+ * trailing pass without repeatedly cancelling page fetches.*/export const createGalleryRealtimeRuntime = ({backend,@@ -47,10 +39,8 @@ export const createGalleryRealtimeRuntime = ({return;}- // `performance.now()` rather than `Date.now()`: a wall clock that steps backwards (NTP- // correction after resume, VM resync) would otherwise push this delay out by the size of- // the step, and the guard above means that one pending timer absorbs every event until it- // fires.+ // Use monotonic time so wall-clock corrections cannot extend the pending timer and delay all subsequent+ // events.const delay = Math.max(coalesceMs, lastInvalidatedAt + minIntervalMs - performance.now());invalidationTimer = setTimeout(() => {@@ -70,11 +60,8 @@ export const createGalleryRealtimeRuntime = ({isStarted = true;- // The hub replays the current status synchronously on subscribe. A boot that- // reaches 'connected' from 'connecting' has missed nothing, so it must not- // cancel and refetch pages that are still loading. A hub that is already- // 'disconnected' when this mounts is the other case: events were missed, so- // its next 'connected' is a genuine reconnect.+ // Initial connection misses no events; only reconnects after disconnection should invalidate in-flight pages.+ // Subscription immediately replays status.let previousStatus: BackendConnectionStatus | null = null;detachers.push(diff --git a/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.tsindex edd9cf4141..762099e380 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts@@ -163,15 +163,11 @@ describe('listSemanticGalleryItemNames', () => {await expect(listSemanticGalleryItemNames({ query: { clusterId, kind: 'cluster' } })).resolves.toEqual({items: [{ kind: 'image', name: 'near.png' },- // A clip clustered with the images it resembles is listed as a video,- // so the gallery hydrates it through the videos endpoint.{ kind: 'video', name: 'clip.mp4' },],total: 2,});- // An evicted key (another cluster registered, or a reload) degrades to an- // empty list rather than an error — the parse layer clears the reference- // before the UI would ever show that.+ // Evicted cluster keys yield empty results; parsing clears the stale reference before display.registerImageCluster(['image:other.png'], 'newer');await expect(listSemanticGalleryItemNames({ query: { clusterId, kind: 'cluster' } })).resolves.toEqual({items: [],diff --git a/invokeai/frontend/webv2/src/features/gallery/index.ts b/invokeai/frontend/webv2/src/features/gallery/index.tsindex 70ed032177..c079c02932 100644--- a/invokeai/frontend/webv2/src/features/gallery/index.ts+++ b/invokeai/frontend/webv2/src/features/gallery/index.ts@@ -252,10 +252,6 @@ export const galleryDestinations = {list: listGalleryBoards,} as const;-/**- * Whether a board id can actually receive item attachments. Virtual destinations- * (date buckets, `generated`/`assets`) and `none` cannot: the organization- * transports no-op for them rather than calling the backend.- */+/** Virtual boards and none cannot receive attachments; organization transports no-op for these destinations. */export const isGalleryBoardAttachable = (boardId: string): boolean =>boardId !== 'none' && !isInvalidGalleryBoardDestination(boardId);diff --git a/invokeai/frontend/webv2/src/features/gallery/launchpad.ts b/invokeai/frontend/webv2/src/features/gallery/launchpad.tsindex 2a132cb2ca..b597350212 100644--- a/invokeai/frontend/webv2/src/features/gallery/launchpad.ts+++ b/invokeai/frontend/webv2/src/features/gallery/launchpad.ts@@ -1,5 +1,2 @@-/**- * Gallery surface for the Launchpad. Exported eagerly — see the note in the- * Launchpad's `livePanels` module about the single shared lazy boundary.- */+/** Export eagerly; Launchpad livePanels owns the shared lazy boundary. */export { RecentOutputs } from './ui/launchpad/RecentOutputs';diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/FindInGalleryButton.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/FindInGalleryButton.tsxindex 221b6c41c0..d40634b756 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/FindInGalleryButton.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/FindInGalleryButton.tsx@@ -5,24 +5,12 @@ import { Tooltip } from '@platform/ui/Tooltip';import { CrosshairIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';-/**- * "Find in gallery", for the panels that condition on media they did not pick- * from the grid they are looking at. The mark is the same crosshair the- * workflow form's pinned fields use to locate their node: "take me to it".- *- * Presentation is the caller's: this owns the icon, the accessible name, and- * the tooltip, which are what must not drift between the four thumbnails that- * offer the gesture.- */+/** Share the reveal icon, accessible name, and tooltip across media thumbnails; callers own presentation. */export type FindInGalleryButtonProps = Omit<IconButtonProps,'aria-label' | 'aria-labelledby' | 'children' | 'onClick'> & {- /**- * The media's file name. A field can show several of these at once (a clip's- * two trim bounds, a stack of references), which as bare "Find in Gallery"- * buttons are indistinguishable to a screen reader.- */+ /** Include the media filename so assistive technology distinguishes simultaneous reveal buttons. */name?: string;onFind: () => void;};@@ -43,21 +31,13 @@ export const FindInGalleryButton = ({ name, onFind, ...buttonProps }: FindInGall);};-// Keyboard users never see a hover, so focus has to reveal it too — and the-// control is only a tab stop worth having once it is visible, hence the-// pointer-events pair rather than `display`, which would drop it from the tab-// order entirely.+// Reveal on keyboard focus as well as hover; opacity and pointer-events preserve tab access that display:none+// would remove.const REVEALED = { opacity: 1, pointerEvents: 'auto' } as const;/**- * The same gesture pinned to the bottom-right corner of a thumbnail and- * revealed with it. The host thumbnail supplies `className="group"` and a- * positioning context; the solid neutral chip is the workbench's treatment for- * a control that has to stay legible over arbitrary imagery.- *- * The inset is the focus ring's own reach (2px outline, 2px offset): thumbnails- * clip their overflow, so anything tighter crops the ring rather than the chip,- * and takes the focus indicator with it.+ * Host with className="group" and positioned layout. Inset the overlay by the focus ring's reach to prevent+ * thumbnail clipping.*/export const FindInGalleryThumbnailButton = (buttonProps: FindInGalleryButtonProps) => (<FindInGalleryButtondiff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsxindex e2541cd5be..c5e2299080 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsx@@ -4,10 +4,7 @@ import { useCallback, useRef } from 'react';import { forwardGalleryBoardDrop, isGalleryItemDragData, resolveGallerySemanticSearchDrop } from './galleryDnd';import { useGalleryWidget } from './GalleryWidgetContext';-/**- * Owns board-drop forwarding and the temporary disclosure needed to make- * board targets available when an item drag begins from a collapsed gallery.- */+/** Forward board drops and temporarily expose collapsed board targets during item drags. */export const GalleryBoardDragMonitor = () => {const { actions, gallery, itemActions } = useGalleryWidget();const dragOpenedPanelRef = useRef(false);@@ -38,8 +35,6 @@ export const GalleryBoardDragMonitor = () => {const semanticDrop = resolveGallerySemanticSearchDrop(event.active.data.current, event.over?.id);if (semanticDrop) {- // Dropping a gallery image on the search field ranks the gallery by- // visual similarity to it.actions.setSemanticImageQuery({ imageName: semanticDrop.imageName, kind: 'image' });restoreDisclosure();return;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardFilters.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardFilters.tsxindex 817c769df7..67eaf0f65d 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardFilters.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardFilters.tsx@@ -23,12 +23,6 @@ import { useGalleryWidget } from './GalleryWidgetContext';const SEARCH_START_ELEMENT = <Icon as={SearchIcon} size="xs" />;const SORT_MENU_POSITIONING = { placement: 'bottom-end' } as const;-/**- * Board search plus one options menu covering both list controls: what the- * panel shows, and how it is ordered. A single icon-only trigger — the wide- * sidebar has no room for labels, and two adjacent unlabelled icon buttons- * read as noise you had to hover to tell apart.- */export const GalleryBoardFilters = ({ref,searchTerm,@@ -46,8 +40,7 @@ export const GalleryBoardFilters = ({const { actions, gallery } = useGalleryWidget();const { boardOrderBy, boardOrderDir, showArchivedBoards, showDateBoards, showOtherProjectBoards } = gallery.settings;const menuTriggerIds = useMenuTriggerIds();- // Any non-default visibility lifts the trigger out of `fg.muted`, so a- // filtered panel is legible without opening the menu.+ // Highlight non-default visibility so filtering is apparent with the menu closed.const isVisibilityFiltered =showArchivedBoards !== DEFAULT_GALLERY_SETTINGS.showArchivedBoards ||showDateBoards !== DEFAULT_GALLERY_SETTINGS.showDateBoards ||@@ -193,12 +186,7 @@ export const GalleryBoardFilters = ({);};-/**- * A checkable visibility row. Chakra ships no `Menu.CheckboxItem`, and the- * codebase expresses checked state either as a radio group or as a zero-opacity- * check that holds its own gutter; these are independent toggles, so it is the- * latter.- */+/** Independent toggles use a reserved check gutter rather than mutually exclusive radio items. */const BoardVisibilityItem = ({icon,isChecked,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsxindex 77fb3ec661..390754e2a5 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx@@ -15,12 +15,7 @@ export interface GalleryBoardMenuTarget {y: number;}-/**- * Cursor-anchored actions menu for a single board row (download, rename,- * archive, delete) so boards can be managed without selecting them first.- * Opened from the board dropdown via right-click or the row's hover actions- * button; the dropdown stays open underneath.- */+/** Keep the board dropdown open beneath its cursor-anchored actions menu; actions need not select the board. */export const GalleryBoardMenu = ({target,onClose,@@ -39,13 +34,8 @@ export const GalleryBoardMenu = ({targetRef.current = target;const board = target?.board ?? null;- // A project's board can be downloaded but never renamed, archived, or deleted: those follow- // the project. This covers every project's board, not just the open one — the server refuses- // all of them, so offering the action anywhere would only produce a 409.- //- // The open project's own board is checked locally as well. `project_id` is omitted rather than- // nulled by the backend's DTO, so a response that has lost it would make the project's board- // look ordinary — offering a rename that 409s and dropping the badge that explains why.+ // Protect every project-owned board from rename/archive/delete. Also check the active project's board ID because+ // omitted project_id must not expose invalid actions.const isManagedBoard =board !== null && board.kind === 'board' && board.projectId === null && board.id !== gallery.projectBoardId;const positioning = useMemo(@@ -236,11 +226,7 @@ export const GalleryBoardMenu = ({);};-/**- * A project's board sits inside a project, so its menu offers both: the whole project as an- * `.invk`, and the board's media on its own. The media-only download is the existing action and- * keeps its video-omission warning; this one carries the document too.- */+/** Project export includes the document; the separate media-only download retains its video-omission warning. */const BoardExportProjectMenuItem = ({ board }: { board: GalleryBoard }) => {const { t } = useTranslation();const { actions } = useGalleryWidget();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsxindex 22fe7eedfa..8e3a87434d 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx@@ -129,8 +129,7 @@ export const GalleryBoardRow = ({return (<Box- // An outline rather than a border, so the drop affordance never reflows- // the list; over the row it steps up to a solid inset ring.+ // Use outlines to avoid reflow during drag highlighting; the active row gets an inset ring.bg={isOver ? 'accent.muted' : undefined}outline={isOver ? '2px solid' : canDropItems ? '1px dashed' : undefined}outlineColor={canDropItems ? 'accent.solid' : undefined}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsxindex 4cadfa1c04..726581e466 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsx@@ -20,11 +20,7 @@ const SELECTED_CONTAINER_CSS: SystemStyleObject = {color: 'accent.contrast',} as const;-/**- * While a compatible drag targets the row, the container's own hover fill- * stands down: it would paint over the accent drop tint the row draws behind- * it, flashing it out right as the drag arrives.- */+/** Suppress hover fill during compatible drags so it cannot obscure the row's drop tint. */const DROP_TARGET_CONTAINER_CSS: SystemStyleObject = {...ROW_CONTAINER_CSS,_hover: { bg: 'transparent' },@@ -33,11 +29,7 @@ const DROP_TARGET_CONTAINER_CSS: SystemStyleObject = {/** The container owns the fill, so the button contributes only its focus ring. */const ROW_BUTTON_CSS = { _hover: { bg: 'transparent' }, bg: 'transparent' } as const;-/**- * The one row shape every board-panel entry uses. `actions` is a flex sibling- * of the row button, never a child: nested buttons are invalid markup, and an- * overlaid one carves the row's touch target into unhittable slivers.- */+/** Keep action buttons beside the row button to avoid invalid nesting and fragmented touch targets. */export const GalleryBoardRowShell = ({actions,ariaLabel,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsxindex 43897db56c..e19e76fdf0 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx@@ -175,11 +175,7 @@ describe('GalleryBoardsPanel', () => {expect(text).toContain('GORL');});- /**- * The badge follows board ownership, not the open project: the server tells every board whose- * project it belongs to, and one that belongs to a project the user is not in is protected the- * same way. Only the *hoisting* is about the active project.- */+ /** Badges and protection follow every board's owner; only hoisting depends on the active project. */it('marks every project-owned board with a Project badge', async () => {const ownedBoards = boards.map((board) => (board.id === 'cats' ? { ...board, projectId: 'p1' } : board));@@ -288,8 +284,7 @@ describe('GalleryBoardsPanel', () => {await click(trigger!);};- // Each row stays a checkbox rather than closing the menu, so the three- // groups and the sort can be set in one visit.+ // Checkbox actions keep the menu open for multiple visibility and sort changes.await openMenu();const row = (value: string) => document.querySelector<HTMLElement>(`[data-scope="menu"] [data-value="${value}"]`);@@ -300,8 +295,6 @@ describe('GalleryBoardsPanel', () => {await click(row('archived-boards')!);expect(actions.updateSettings).toHaveBeenCalledWith({ showArchivedBoards: false });- // The fixture leaves other-project boards on the hidden-by-default setting,- // so the toggle turns them on.await click(row('other-project-boards')!);expect(actions.updateSettings).toHaveBeenCalledWith({ showOtherProjectBoards: true });diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsxindex d1c99564a0..6e1b6f7626 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx@@ -23,11 +23,6 @@ import { useGalleryWidget } from './GalleryWidgetContext';const SCROLL_CONTENT_PROPS = { py: '1' } as const;const CREATE_ROW_COVER = <BoardCoverIcon icon={PlusIcon} />;-/**- * The board browser: search and list controls above a grouped, collapsible- * list of boards. Identical in both layouts — the shells only decide whether it- * sits above the items area or beside it.- */export const GalleryBoardsPanel = () => {const { t } = useTranslation();const { actions, gallery, projectName } = useGalleryWidget();@@ -82,16 +77,13 @@ export const GalleryBoardsPanel = () => {void actions.createBoard(trimmedSearchTerm);}, [actions, groups.canCreateFromSearch, trimmedSearchTerm]);- // Enter only creates when nothing matched; with matches on screen it would- // be far too easy to make a near-duplicate board by reflex.+ // Enter creates only with no matches, avoiding accidental near-duplicate boards.const handleSubmitSearch = useCallback(() => {if (!groups.hasAnyMatch) {createBoardFromSearch();}}, [createBoardFromSearch, groups.hasAnyMatch]);- // "+" creates straight away when the field already names the board; with an- // empty field there is nothing to name it, so it hands over the caret.const handleAddBoard = useCallback(() => {if (groups.canCreateFromSearch) {createBoardFromSearch();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryDragCursor.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryDragCursor.tsxindex 486111e3eb..68226db338 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryDragCursor.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryDragCursor.tsx@@ -4,11 +4,8 @@ import { useEffect } from 'react';import { isGalleryItemDragData } from './galleryDnd';/**- * Marks `<body data-gallery-drag>` while any gallery-item drag is in flight;- * the theme's global rule turns the whole app's cursor into the closed hand- * for the duration (a body-level cursor alone would lose to every element- * that sets its own — buttons, textareas — flickering arrow/I-beam back as- * the pointer crosses them mid-drag). Mount once inside the DndContext.+ * Mount once inside DndContext. The body marker enables global drag cursors that override element-specific button+ * and textarea cursors.*/export const GalleryDragCursor = () => {const { active } = useDndContext();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsxindex 5927130a61..a0cac08449 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx@@ -526,10 +526,7 @@ const pointer = (type: string, target: EventTarget, clientX: number, clientY: nu};beforeEach(() => {- // The reveal channel is a module singleton, so a request from a previous- // test would otherwise be adopted by the next mount (grids deliberately- // honor a request that predates them). Drain it with one that can never- // match an item here.+ // Drain singleton reveal intent with an unmatchable request so later tests cannot adopt it.requestGalleryItemReveal('image:__drained__');accountLifecycle.activate('grid-user');vi.clearAllMocks();@@ -653,8 +650,6 @@ describe('GalleryImageGrid mixed item cells', () => {expect(getComputedStyle(pinned).borderBottomWidth).toBe('1px');expect(listingTop() - pinned.getBoundingClientRect().bottom).toBeCloseTo(GALLERY_PINNED_FOOTER_PX - 1, 0);- // The disclosure is a persisted setting, so collapsing goes through the- // owner and comes back as the next render's settings.await click(getButton('Collapse starred items'));expect(actionMocks.updateSettings).toHaveBeenCalledExactlyOnceWith({ starredSectionCollapsed: true });await renderGallery({ ...gallery, settings: { ...DENSE_SETTINGS, starredSectionCollapsed: true } });@@ -1152,15 +1147,11 @@ describe('GalleryImageGrid upload drop zone', () => {const accept = host?.querySelector<HTMLInputElement>('input[type="file"]')?.accept.split(',');- // The gallery once offered video/mp4 alone, so the OS picker greyed out every clip- // and audio file the server ingests. Parity with the video panel's reference upload.+ // Picker acceptance must include the video and audio formats supported by reference uploads.expect(accept).toEqual(expect.arrayContaining(['image/png', 'video/*', 'audio/*', '.mov', '.mkv', '.mp3', '.wav']));});- // Not a fix for the accept-list bug -- the drop path never consulted `accept` and already- // forwarded every format. This pins that: the handler must stay a pass-through, because- // filtering here by the picker's list would re-hide exactly what the picker just stopped- // hiding, and the classifier downstream is the single place that decides.+ // Drops bypass the accept list; downstream classification alone decides media kind.it('hands a dropped audio file to the upload action', async () => {await renderGallery(createGallery({ items: [] }));@@ -1211,9 +1202,8 @@ describe('GalleryImageGrid reveal requests', () => {});it('never scrolls on selection changes alone', async () => {- // The selection also changes when a finished generation auto-selects its- // image; scrolling on that would yank the grid out from under a browsing- // user. Only the explicit reveal channel may scroll.+ // Only explicit reveal intent may scroll; generation-driven selection must preserve the user's browsing+ // position.const gallery = createGallery();await renderGallery(gallery);@@ -1254,10 +1244,7 @@ describe('GalleryImageGrid reveal requests', () => {});it('honors a reveal requested before this grid mounted, while its item is still selected', async () => {- // The gallery is frequently opened (or swapped between its stacked and- // wide layouts, which remounts the grid) in response to the very reveal- // that is outstanding, so a grid must not ignore a request just because- // it arrived before the mount.+ // A grid mounted by a reveal must honor the request that preceded its mount.await interact(() => requestGalleryItemReveal('image:last.png'));expect(mocks.scrollToIndex).not.toHaveBeenCalled();@@ -1416,15 +1403,12 @@ describe('GalleryImageGrid virtualization', () => {await renderGallery(gallery);- // Collapsing starred keeps the visible range identical, so without an- // explicit measure() the virtualizer would keep serving the expanded- // offsets — the new rows would paint below a stale starred-sized hole.+ // Collapsing starred requires measurement even if visible indices stay unchanged, or stale offsets leave a+ // gap.mocks.measure.mockClear();await renderGallery({ ...gallery, settings: { ...DENSE_SETTINGS, starredSectionCollapsed: true } });expect(mocks.measure).toHaveBeenCalled();- // Swapping the item list (e.g. the media/assets view switch) is the same- // structural change arriving through props.mocks.measure.mockClear();await renderGallery(createGallery({ items: [createItem('image', 'other.png')] }));expect(mocks.measure).toHaveBeenCalled();@@ -1446,9 +1430,7 @@ describe('GalleryImageGrid virtualization', () => {);await vi.waitFor(() => expect(actionMocks.loadMore).toHaveBeenCalled());- // Columns follow the measured viewport width now, so pinning a row count- // would just re-encode the harness width. The invariant that matters is- // that the rows the virtualizer is asked for cover every cell exactly once.+ // Assert every cell is covered once; measured viewport width determines row count.const renderedRows = host?.querySelectorAll('[role="list"] [role="presentation"]').length ?? 0;const renderedCells = host?.querySelectorAll('[role="listitem"]').length ?? 0;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex 891e367e64..a6c98a6f77 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -63,11 +63,7 @@ let lastPageFollowedRevealToken = 0;const dragEventContainsFiles = (event: DragEvent): boolean => Array.from(event.dataTransfer.types).includes('Files');-/**- * The disclosure row above the starred strip, styled to match board rows.- * "Show all" appears only while the board holds more starred items than the- * strip shows; it switches the listing to the starred-only filter.- */+/** Show all appears only when starred items exceed the strip and activates the starred-only listing. */const GalleryStarredSectionHeader = ({isOpen,onShowAll,@@ -140,10 +136,8 @@ const GalleryStarredSectionHeader = ({};/**- * The pinned starred strip: bounded (three rows at most), so it renders as- * plain rows above the virtualized listing rather than inside it. Its cells- * sit between the in-progress tiles and the listing in the arrow-key- * sequence, so the keys cross both seams.+ * Render the bounded starred strip outside virtualization while preserving its place in cross-section keyboard+ * navigation.*/const GalleryStarredSection = ({cells,@@ -200,11 +194,7 @@ const GalleryStarredSection = ({);};-/**- * The virtualized thumbnail grid. Column count comes from the measured- * viewport width, so the grid is layout-blind: both shells render it the same- * way and it simply fills whatever box it is handed.- */+/** Measure viewport width for columns so both layouts share the same grid. */export const GalleryImageGrid = () => {const { t } = useTranslation();const { actions, gallery, isWindowTruncated, itemActions, region, starredStrip } = useGalleryWidget();@@ -256,11 +246,8 @@ export const GalleryImageGrid = () => {() => getGalleryStarredStripItems(starredStrip.items, columnCount),[columnCount, starredStrip.items]);- // The arrow keys' sections in visual order; a collapsed section has no- // tiles to land on, so it contributes none. A starred selection the strip- // does not show (beyond its three rows, or under a collapsed disclosure)- // still belongs to the strip section, so the keys step out of it instead- // of resetting — Preview places such a selection the same way.+ // Exclude collapsed tiles from navigation, but retain hidden starred selections' section identity so arrows can+ // step out.const isProgressOpen = showPendingItems && !progressSectionCollapsed;const navigationSections = useMemo((): GalleryNavigationEntry[][] => {const shownStripItems = isStarredOpen ? starredCells : [];@@ -321,8 +308,6 @@ export const GalleryImageGrid = () => {shownCount: starredCells.length,tileSize: cellSizePx,});- // In progress and starred share one pinned block above the listing; the- // virtualizer scrolls beneath it.const pinnedHeight = getGalleryPinnedHeightPx(progressLayout.height, starredLayout.height);const virtualizer = useVirtualizer({count: rowCount,@@ -337,10 +322,8 @@ export const GalleryImageGrid = () => {virtualizer.measure();});- // Deliberately unmemoized: the hotkey hook only ever calls this from inside- // an effect event, which always sees the latest render's closure, so a stable- // identity would buy nothing and pinning the mutable virtualizer into a- // dependency array defeats the compiler's own memoization.+ // The hotkey callback reads current state when invoked; stabilizing its identity adds no value and interferes+ // with compiler memoization./** Returns whether the item had somewhere to scroll to — a collapsed strip has none. */const scrollToItemKey = (itemKey: GalleryItemKey): boolean => {const rowIndex = getGalleryGridRowIndexForItemKey(gallery.items, itemKey, columnCount);@@ -375,22 +358,11 @@ export const GalleryImageGrid = () => {scrollToEntry,});- // Reveals from outside the grid (the image map's click-to-reveal) must land- // in view. This listens to the explicit reveal channel, NOT the selection:- // the selection also changes when a finished generation auto-selects its- // image, and scrolling on that would yank the grid out from under a- // browsing user — while re-clicking the already-selected map point changes- // no selection at all yet must still reveal. A reveal whose page is still- // loading stays pending until the item materializes (each row-model change- // retries), and is dropped as soon as some other selection supersedes it.+ // Only explicit reveals scroll. Retry while the item loads; retire the request when another selection supersedes+ // it.const revealRequest = useSyncExternalStore(subscribeGalleryRevealRequests, getGalleryRevealRequest);const pendingRevealRef = useRef<GalleryRevealRequest | null>(null);- // Seeded below any real token so a grid that mounts AFTER the request still- // honors it: the gallery is often opened (or swapped between its stacked and- // wide layouts, which remounts this component) in response to the very- // reveal that is outstanding. Staleness is judged by the selection guard- // below rather than by age — a request whose item is no longer the selection- // retires without scrolling.+ // Honor requests preceding mount; selection mismatch, rather than request age, determines staleness.const consumedRevealTokenRef = useRef(0);const settlePendingReveal = useEffectEvent(() => {const pending = pendingRevealRef.current;@@ -432,8 +404,6 @@ export const GalleryImageGrid = () => {}});- // Re-run on every change to what can be scrolled to — a page landing, the- // strip opening — so a pending reveal settles as soon as its item can.useEffect(() => {if (revealRequest && revealRequest.token !== consumedRevealTokenRef.current) {consumedRevealTokenRef.current = revealRequest.token;@@ -473,13 +443,8 @@ export const GalleryImageGrid = () => {return () => observer.disconnect();}, [isEmpty, region]);- // The virtualizer only recomputes offsets lazily and only notifies- // subscribers when the visible index range changes, so a row-model change- // that keeps the range identical — collapsing the starred section, items- // moving between sections, a view switch swapping the item list — would- // paint the new rows at the previous rows' offsets. measure() recomputes- // from the current estimates and notifies unconditionally; running it as a- // layout effect keeps the stale frame from ever reaching the screen.+ // Measure before paint after row-model changes: unchanged visible indices otherwise leave stale offsets despite+ // new row estimates.useLayoutEffect(() => {measureVirtualizer();}, [rowHeightPx, rows, pinnedHeight]);diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsxindex a8c621824f..35e94cb412 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx@@ -95,11 +95,7 @@ interface HarnessGallery {semanticSearchText: string | null;}-/**- * Stands in for the workbench store: the two text intents write back into- * the values the field reads, so a controlled input behaves as it does in the- * app, while every intent is still recorded on the spies.- */+/** Write text intents back into controlled values to model the workbench while recording calls. */const Harness = ({ initial }: { initial: Partial<HarnessGallery> }) => {const [gallery, setGallery] = useState<HarnessGallery>({searchTerm: '',diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsxindex b2e4dd4ab5..b84a68024d 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx@@ -22,11 +22,7 @@ import { useGalleryWidget } from './GalleryWidgetContext';const SEARCH_HINT_ID = 'gallery-search-hint';const HELP_POSITIONING = { placement: 'bottom-end' } as const;-/**- * Typing pause before the semantic text becomes the ranking. Each commit is a- * server-side embedding plus a full re-rank, so keystrokes must coalesce; a- * pause this short still reads as "live" rather than as a submit.- */+/** Debounce typing because each semantic commit embeds and reranks on the server. */export const SEMANTIC_SEARCH_COMMIT_DEBOUNCE_MS = 300;/** The `key:value` forms `parseDateTokens` accepts, as shown in the help popover. */@@ -83,11 +79,8 @@ export const GalleryItemSearch = () => {const { data: indexAvailability } = useQuery(imageIndexAvailabilityOptions());const isSemanticMode = gallery.semanticSearchText !== null;const semanticText = gallery.semanticSearchText ?? '';- // Offered whenever indexing is configured, model or index present or not:- // the field is where a user finds out the feature exists, and the hint- // below it says what is still missing. The toggle also stays reachable- // for a persisted semantic field on an install without indexing, so the- // mode can always be left.+ // Offer semantic mode whenever indexing is configured; keep the toggle reachable for persisted mode so users can+ // exit it.const isIndexConfigured = indexAvailability !== undefined && indexAvailability.state !== 'disabled';const showSemanticToggle = isIndexConfigured || isSemanticMode;@@ -114,10 +107,8 @@ export const GalleryItemSearch = () => {actions.setSemanticSearchText(value);cancelPendingCommit();- // The ranking always follows the text, model or no model: a search the- // server cannot run is reported by the listing's own error channel,- // beside the hint that says why, and there is no text left behind to- // reconcile once the model arrives.+ // Commit text even without the model; listing errors explain unavailable search without leaving deferred+ // text to reconcile.commitTimerRef.current = window.setTimeout(() => {commitTimerRef.current = null;actions.commitSemanticSearch(value);@@ -155,9 +146,7 @@ export const GalleryItemSearch = () => {// The next keystrokes are what the toggle was for.inputRef.current?.focus();- // The sparkle is offered without the model on purpose, so this click is- // where a user learns what the feature needs: the hint under the field- // stays while the mode does, the toast says what to do about it.+ // Explain missing prerequisites on activation while retaining the inline hint for the active mode.if (indexAvailability?.state === 'model_missing') {notifications.add({kind: 'info',@@ -181,8 +170,7 @@ export const GalleryItemSearch = () => {id: GALLERY_SEMANTIC_SEARCH_DROP_ID,});- // Native HTML5 drops reach here for anything dnd-kit does not manage: files- // from the OS and images dragged in from other pages (URL drags).+ // Native drops handle OS files and external image URLs outside dnd-kit.const [isNativeDropOver, setIsNativeDropOver] = useState(false);const handleNativeDragOver = useCallback((event: React.DragEvent<HTMLDivElement>) => {@@ -225,9 +213,7 @@ export const GalleryItemSearch = () => {const isDropTargetActive = isItemDragOver || isNativeDropOver;- // Valid tokens are legible as chips in the field itself, so only the failure- // case still needs words — and it is positioned out of flow. As a sibling it- // grew the field's row and knocked the wide header out of vertical centre.+ // Position failure text outside flow so it cannot enlarge or misalign the search row.const invalidHint = useMemo(() => {if (isSemanticMode) {return null;@@ -239,8 +225,6 @@ export const GalleryItemSearch = () => {return invalid ? t('widgets.gallery.dateFilterInvalid', { value: invalid.raw }) : null;}, [gallery.searchTerm, isSemanticMode, t]);- // The same out-of-flow slot explains a semantic field the server cannot- // answer, before the first search fails.const semanticHint =isSemanticMode && indexAvailability?.state === 'model_missing'? t('widgets.gallery.semanticSearchModelMissing', { model: indexAvailability.modelName ?? '' })@@ -324,11 +308,10 @@ export const GalleryItemSearch = () => {onDragOver={handleNativeDragOver}onDrop={handleNativeDrop}>- {/* In semantic mode the field IS the text query; a chip stands for a- reference the field cannot type (an image, a file, a cluster), and- every path that sets one leaves semantic mode. A text chip is only a- project saved before the mode existed. The toggle stays beside the- chip: pressing it there trades the reference for a typed query. */}+ {/*+ * Image/file/cluster chips replace semantic text mode. Legacy text chips remain readable; toggling switches+ * a chip to typed search.+ */}{!isSemanticMode && gallery.semanticImageQuery ? (<GallerySemanticChipreference={gallery.semanticImageQuery}@@ -380,11 +363,7 @@ export const GalleryItemSearch = () => {);};-/**- * The active semantic query — a text prompt or an image-similarity- * reference — rendered in place of the search input. Clearing it restores- * metadata search.- */+/** Clearing the active semantic reference restores metadata search. */const GallerySemanticChip = ({onClear,reference,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSortMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSortMenu.tsxindex 6ae56bb63e..05b5b62f69 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSortMenu.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSortMenu.tsx@@ -12,10 +12,6 @@ import { useGalleryWidget } from './GalleryWidgetContext';const SORT_POSITIONING = { placement: 'bottom-end' } as const;-/**- * Grid ordering, promoted out of the settings popover: which end of the board- * you are looking at is a decision made constantly, not a preference set once.- */export const GalleryItemSortMenu = () => {const { t } = useTranslation();const { actions, gallery } = useGalleryWidget();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.tsxindex b4293435d1..ffb6102e74 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.tsx@@ -6,12 +6,6 @@ import { useGalleryLayout } from './galleryDensity';import { GalleryStackedLayout } from './GalleryStackedLayout';import { GalleryWideLayout } from './GalleryWideLayout';-/**- * The single place in the gallery that knows how much room it has. Everything- * below is layout-blind: the two shells arrange one identical set of slot- * components, so swapping between them is a rendering decision rather than a- * behavioural one.- */export const GalleryLayout = ({ region }: { region: GalleryWidgetProps['region'] }) => {const { layout, rootRef } = useGalleryLayout(region);diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsxindex e9d463208d..0ae2ae9a65 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx@@ -64,13 +64,8 @@ const MIRROR_CHIP_CSS = {} as const;/**- * Search input that draws date tokens as chips. The mirror and the input share- * one zero-padded cell, so they align by construction rather than by matching- * padding; the input's own text is transparent and only its caret shows.- *- * In semantic mode the text is a free-form description, so no token is a chip,- * and the frame is tinted so the mode reads at a glance — the tint holds- * through hover and focus, which recolor only the border.+ * Share a zero-padded cell to align date chips with transparent input text. Semantic descriptions remain plain+ * text with persistent mode tint.*/export const GallerySearchField = ({ariaLabel,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsxindex 7bf73b06e8..42123250e5 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsx@@ -16,11 +16,6 @@ import { useGalleryWidget } from './GalleryWidgetContext';const MOVE_MENU_POSITIONING = { placement: 'top-end' } as const;-/**- * Bulk actions for the current multi-selection. Until now these lived only in- * the right-click menu, which made them invisible to anyone who did not think- * to look for them.- */export const GallerySelectionBar = () => {const { t } = useTranslation();const { gallery, itemActions, loadedItems } = useGalleryWidget();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySplitHandle.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySplitHandle.tsxindex 893108dac1..4016e3677b 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySplitHandle.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySplitHandle.tsx@@ -11,8 +11,6 @@ const HANDLE_FOCUS_PROPS = {outlineOffset: '-1px',} as const;-// An 8px target painting a 1px line: a divider as thick as its grab area reads-// as a gap in the layout.const HORIZONTAL_PROPS = {cursor: 'row-resize',h: `${GALLERY_SPLIT_HANDLE_SIZE_PX}px`,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsxindex cb238fcb89..0ad5d7d013 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsx@@ -19,11 +19,6 @@ import { GalleryUploadButton } from './GalleryUploadButton';import { GalleryViewTabs } from './GalleryViewTabs';import { useGalleryWidget } from './GalleryWidgetContext';-/**- * Narrow arrangement: board panel above the items area. Pure arrangement —- * every child here is the same component the wide shell renders. The board- * panel's disclosure lives in the widget frame's header label, not here.- */export const GalleryStackedLayout = () => {const { t } = useTranslation();const { actions, gallery } = useGalleryWidget();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsxindex 742273ba15..5f24186f43 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx@@ -14,11 +14,7 @@ import { useTranslation } from 'react-i18next';import { getGalleryItemDragData, getGalleryItemDragId } from './galleryDnd';import { GalleryTileFrame } from './GalleryTileFrame';-/**- * Desaturation is the touch drag cue: the tile while dragged, or while a- * sustained hold has armed the drag gate (`data-drag-armed`, set by the- * hold-to-drag sensor). The portalled preview carries the same filter.- */+/** Desaturate armed and active touch drags, including the portalled preview. */const THUMBNAIL_DRAG_CSS = { filter: 'saturate(0)' } as const;const THUMBNAIL_ARMED_CSS = { '&[data-drag-armed=true]': { filter: 'saturate(0)' } } as const;@@ -79,10 +75,7 @@ const GalleryThumbnail = ({id: getGalleryItemDragId(toGalleryItemRef(item), 'gallery-grid', dragScope),});- // The preview is portalled from where the tile started rather than moved in- // place: the grid scrolls inside `overflow: hidden` and its virtual rows carry- // their own transform, so a moved tile is clipped as soon as it leaves the- // grid — which is most of the way to any board.+ // Portal the drag preview to escape the grid's overflow clipping and transformed virtual rows.const tileRef = useRef<HTMLDivElement | null>(null);const [dragOrigin, setDragOrigin] = useState<DOMRect | null>(null);@@ -174,11 +167,7 @@ const GalleryThumbnail = ({item={item}opacity={isDragging ? 0.4 : undefined}role="listitem"- // Pan, don't drag: `none` would hand every touch-drag to the drag- // sensor before the browser could scroll the grid. Allowing the pan- // lets a moving finger scroll (the hold-to-drag sensor releases the- // gesture when the browser claims it); dragging still works after a- // sustained hold.+ // Allow touch panning; the hold sensor yields to scrolling and arms drag only after a sustained hold.touchAction="pan-y"onContextMenu={handleContextMenu}>@@ -248,10 +237,7 @@ const GalleryThumbnail = ({);};-/**- * Resolves the drag payload per item so the grid can hand down one stable- * callback rather than an array prop that changes identity every render.- */+/** Resolve payloads per item so the grid passes one stable callback rather than recreated arrays. */export const GalleryThumbnailCell = ({getDragItems,item,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryTileFrame.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryTileFrame.tsxindex 6a250a3271..a55084066a 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryTileFrame.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryTileFrame.tsx@@ -23,11 +23,7 @@ export interface GalleryTileFrameProps extends Omit<BoxProps, 'children'> {ref?: Ref<HTMLDivElement>;}-/**- * The thumbnail shell shared by every gallery surface: square, accent border- * when selected, hover-revealed dimensions badge, video duration badge.- * Caller `css` composes on top; the shell's own props are invariants.- */+/** Caller CSS composes with shared tile styling; shell props remain invariant. */export const GalleryTileFrame = ({alwaysShowDimensions = false,children,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex 5bdc747235..f12391ebf7 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -18,12 +18,8 @@ export interface GalleryItemActions {export interface GalleryItemActionContext {filterIdentity: string;/**- * The page a selection of `item` should be stamped with, when the host- * navigates from a window of its own. A selection made without one is- * stamped with the gallery grid's page, which names the grid's window; a- * host walking a different window — Preview anchored deep in a board the- * grid shows from the top — would have its selection filed outside the- * window it came from, with nowhere for the arrow keys to go.+ * Stamp selections with the host window's page; using the grid's unrelated page would break navigation from deep+ * Preview windows.*/getItemSelectionPage?(item: GalleryItem): number;items: GalleryItem[];@@ -93,10 +89,7 @@ export interface GalleryWidgetProps {runtime: GalleryWidgetRuntime;}-/**- * Gallery's UI port. The context is a dependency-direction port (the feature- * may not import workbench), not a test seam; no second adapter is expected.- */+/** This UI port preserves dependency direction: Gallery cannot import Workbench. */export interface GalleryUiAdapter {ItemActionsProvider: ComponentType<GalleryItemActionsOptions & { children: ReactNode }>;ImageContextMenu: ComponentType<GalleryItemContextMenuProps>;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.tsxindex 218285bfff..8f93d2fd35 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryViewTabs.tsx@@ -13,12 +13,7 @@ const GALLERY_VIEW_TABS = [{ labelKey: 'common.assets', value: 'assets' },] satisfies { labelKey: string; value: GalleryView }[];-/**- * Media / Assets, each carrying `board`'s count for that view so the split is- * legible before you switch. The same `SegmentTabs` strip the layer panes use;- * the caller wires the tabpanel by putting `segmentTabsPanelId(idBase)` on its- * grid container.- */+/** Wire the caller's grid to segmentTabsPanelId(idBase); tab counts distinguish Media and Assets before switching. */export const GalleryViewSegmentTabs = ({activeView,board,@@ -54,8 +49,6 @@ export const GalleryViewSegmentTabs = ({<Text as="span" display="flex" gap="1.5">{t(labelKey)}{count === null ? null : (- // Dimmed from the tab's own text colour, so it tracks the- // shown/idle swap; 0.8 stays comfortably legible on both.<Text as="span" color="currentColor" fontVariantNumeric="tabular-nums" opacity="0.8">{count}</Text>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsxindex 5e70eac747..b109bcbdb7 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx@@ -17,11 +17,6 @@ import { useGalleryWidget } from './GalleryWidgetContext';const CHROME_INSET_PADDING_TOP = 'calc(var(--chakra-spacing-2) + var(--wb-center-chrome-inset, 0px))';-/**- * Roomy arrangement: board panel beside the items area, always open, with the- * header controls on one row. Pure arrangement — every child here is the same- * component the stacked shell renders.- */export const GalleryWideLayout = () => {const { t } = useTranslation();const { actions, gallery } = useGalleryWidget();@@ -63,9 +58,6 @@ export const GalleryWideLayout = () => {</>)}<Stack flex="1" gap="0" minH="0" minW="0">- {/* Tabs anchor the start of the row; everything you reach for while- looking at the grid — find, order, add, configure — collects at the- end, so the eye has one place to go. */}<HStack gap="1" minW="0" pb="2" pe="3" ps="3" pt={CHROME_INSET_PADDING_TOP}><GalleryViewTabs idBase={viewTabsIdBase} /><Spacer />diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsxindex 1fbed3067b..c0bf91d452 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx@@ -64,8 +64,6 @@ export const GalleryWidgetLabel = ({ region }: GalleryChromeProps) => {return (<HStack flex="1" gap="1" minW="0" pe={region === 'center' ? undefined : '2'}>{region === 'center' ? null : (- // `pe` evens out the "/": the board button's own start padding already- // holds the name 8px off the slash, so the title matches it.<Text flexShrink={0} fontSize="xs" fontWeight="700" pe="2">{t('widgets.labels.gallery')}</Text>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsxindex b5255d7b80..905785ec06 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx@@ -10,10 +10,8 @@ import type { GalleryStateView } from './galleryStateView';import type { GalleryItemActions, GalleryWidgetProps, GalleryWidgetRuntime } from './GalleryUiContext';/**- * Gallery-widget intents. The provider (GalleryWidgetView) is the only place- * that knows whether an intent maps to a workbench dispatch, a backend call,- * or both. Image-level operations (star, delete, move, ...) live in the shared- * ImageActions contract instead so other widgets reuse them.+ * The provider maps widget intents to workbench/backend actions; shared ImageActions owns cross-widget item+ * operations.*/export interface GalleryActions {archiveBoard: (boardId: string, archived: boolean) => Promise<void>;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetFooter.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetFooter.tsxindex 3888e5ef3a..4135591eb9 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetFooter.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetFooter.tsx@@ -11,11 +11,7 @@ import { useGalleryUi } from './GalleryUiContext';const PAGINATION_ITEM_VARIANT = { _selected: 'outline', base: 'ghost' } as const;-/**- * Widget-chrome footer: page navigation for the gallery's paginated mode.- * Reads everything from the gallery widget's persisted values so it stays- * decoupled from the view's data fetching.- */+/** Read persisted widget values so footer pagination needs no separate fetch. */export const GalleryWidgetFooter = () => {const { t } = useTranslation();const { gallery, galleryValues } = useGalleryUi();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsxindex c41bbace65..afe087f62b 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx@@ -104,9 +104,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgstarred: starredOnly,});- // A failed similarity search renders exactly like an empty one ("no images- // match"), so the failure must reach the user some other way. Scoped to- // semantic mode: the board listing kept its pre-existing quiet behavior.+ // Report semantic failures separately so failed searches cannot masquerade as empty results.const semanticError = semanticQuery ? data.queryError : null;useEffect(() => {@@ -153,9 +151,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgconst itemActionContextRef = useRef<GalleryItemActionContext | null>(null);const galleryLocationRef = useRef({ galleryView, selectedBoardId });- // This ref is a live read port for an in-flight deletion. An effect would- // leave a commit-sized stale window, while the action must compare against- // the exact filter and selection from the latest render.+ // In-flight deletion must read the latest rendered filter and selection without an effect-sized stale window.// eslint-disable-next-line react/refsitemActionContextRef.current = {filterIdentity: itemActionFilterIdentity,@@ -163,9 +159,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgloadOrderedRefs: loadOrderedItemRefs,selectedItemKey: gallery.selectedItemKey,};- // This is the matching live read port for in-flight uploads. The upload- // target is captured at launch, while completion visibility must use the- // board and view from the latest render.+ // Capture upload destination at launch; judge completion visibility against the latest rendered board and view.// eslint-disable-next-line react/refsgalleryLocationRef.current = { galleryView, selectedBoardId };@@ -179,16 +173,8 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgselectedBoardId,});- // Publish the backend total into widget values so the manifest footer can- // render page navigation without its own fetch, and clamp the page when the- // query shrinks (e.g. after deletions).- //- // The effect reacts only to this instance's fetched `total` — the published- // state (`knownTotalImages`) is read through a ref on purpose. Several- // gallery views can be mounted at once (e.g. the bottom status chip plus an- // expanded gallery), and if each instance re-published whenever the shared- // state disagreed with its own in-flight total, two instances mid-refetch- // would dispatch in a loop until React aborts with "maximum update depth".+ // Publish fetched totals for footer pagination. React only to this instance's total; reacting to shared totals+ // can make simultaneous views dispatch indefinitely.const publishGalleryTotal = useEffectEvent((nextTotal: number) => {const lastPublishedTotal = lastPublishedTotalRef.current;@@ -207,12 +193,8 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgpublishGalleryTotal(total);}, [total]);- // Runs in BOTH modes: `page` is the paginated page number and also the- // infinite window's anchor, so either way a page past the end of a shrunken- // listing renders an empty grid — which, with no search active, reads as an- // empty board (the upload dropzone) rather than as a stale position.- // Clamping to the last real page keeps the user near where they were and- // always shows something that exists.+ // Clamp both paginated pages and infinite anchors after shrinkage so stale positions cannot appear as empty+ // boards.useEffect(() => {if (total === null) {return;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/dropAffordances.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/dropAffordances.browser.test.tsxindex cce1eb0867..0970fa0e5c 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/dropAffordances.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/dropAffordances.browser.test.tsx@@ -21,10 +21,8 @@ import {import { GalleryDragCursor } from './GalleryDragCursor';/**- * The drag-in-flight affordances: while a compatible gallery drag is active- * ANYWHERE, a target advertises itself (overlay + label) and the body carries- * the closed-hand cursor flag; incompatible payloads (wrong kind, multi-item- * on a single-item target, non-gallery drags) advertise nothing.+ * Advertise compatible drags anywhere in flight; incompatible kinds, counts, and non-gallery payloads expose no+ * affordance.*/let host: HTMLDivElement | null = null;@@ -200,9 +198,7 @@ describe('drag-in-flight drop affordances', () => {// Still a gallery drag: the cursor flag applies even with no eligible target.expect(document.body.hasAttribute('data-gallery-drag')).toBe(true);- // Released over the frame target: the droppable stays armed (a dead drop,- // matching pre-affordance behavior) rather than disappearing from the- // collision candidates and handing the release to whatever is underneath.+ // Keep ignored payloads as dead drops so release cannot fall through to an underlying target.await release(multiThumb, 280, 260);expect(onDragEnd).toHaveBeenCalled();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.tsindex 5243440265..a16e9505de 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts@@ -110,10 +110,7 @@ describe('getGalleryBoardGroups', () => {expect(groupsOf({ searchTerm: 'Uncategorized' }).canCreateFromSearch).toBe(false);});- /**- * The board is not in the list yet — it is still loading — but it exists, and offering to create- * one under its own name would be offering to make a second.- */+ /** A loading project board still exists; its name must not offer duplicate creation. */it('treats the project board name as an exact match even before the board arrives', () => {expect(groupsOf({ searchTerm: 'Project' }).canCreateFromSearch).toBe(false);});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.tsindex fdcb920fbc..f09add1607 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts@@ -15,13 +15,8 @@ export interface GalleryBoardGroups {}/**- * Splits the flat board list into the panel's three sections.- *- * Pure and total: it filters on `showArchived`/`showDates`/`showOtherProjects`- * itself rather than trusting the query to have excluded them, so grouping can- * be reasoned about (and tested) without a fetch in the picture. The- * other-projects filter has to happen here in any case — `GET /boards/` takes- * no project parameter, so the list always arrives complete.+ * Apply visibility filters while grouping; GET /boards/ cannot filter other projects and returns the complete+ * list.*/export const getGalleryBoardGroups = ({boards,@@ -52,8 +47,7 @@ export const getGalleryBoardGroups = ({const projectBoard = fetchedProjectBoard ? { ...fetchedProjectBoard, name: projectName } : null;const matchesBoardSearch = (board: GalleryBoard) => matchesSearch(getGalleryBoardLabel(board, t));- // The open project's own board is never "another project's", whatever the- // setting says — hiding the board you are working in would be nonsense.+ // Always retain the active project's board regardless of the other-projects filter.const belongsToVisibleProject = (board: GalleryBoard) =>showOtherProjects || board.projectId === null || board.id === projectBoard?.id;const regularBoards = boards.filter(@@ -66,8 +60,7 @@ export const getGalleryBoardGroups = ({const dateBoards = showDates ? boards.filter((board) => board.kind === 'date' && matchesBoardSearch(board)) : [];const archivedBoards = showArchived ? regularBoards.filter((board) => board.archived) : [];- // The one fixed system row keeps a fixed seat at the top (legacy-gallery- // parity) instead of drifting down as boards accumulate.+ // Keep the fixed system row first as boards accumulate.const yourBoards = [...(uncategorizedBoard && matchesBoardSearch(uncategorizedBoard) ? [uncategorizedBoard] : []),...(projectBoard && matchesBoardSearch(projectBoard) ? [projectBoard] : []),diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.tsindex 9dedc92fdb..4a46c35233 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.ts@@ -2,17 +2,11 @@ import type { GalleryBoard, GalleryView } from '@features/gallery/core/types';import { getBoardCounts } from './galleryStateView';-/**- * How many items the active tab would show for a board, so a count always- * answers "how many of what I'm looking at".- */export const getGalleryCountForView = (board: GalleryBoard, galleryView: GalleryView): number => {const counts = getBoardCounts(board);- // Videos split across the views the same way images do: uploaded ('user') videos are- // assets, generated ('general') videos are media. Clamped: the uncategorized- // pseudo-board's counts come from parallel requests, so a delete landing between- // them can transiently report more asset videos than videos.+ // Uploaded videos count as Assets and generated videos as Media. Clamp parallel-request counts because+ // intervening deletions can temporarily invert totals.return galleryView === 'assets'? counts.assetCount + counts.assetVideoCount: Math.max(0, counts.imageCount + counts.videoCount - counts.assetVideoCount);diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.tsindex cfff72cf38..9b80ef82b3 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.ts@@ -4,11 +4,7 @@ import type { GalleryWidgetProps } from './GalleryUiContext';type GalleryRegion = GalleryWidgetProps['region'];-/**- * The gallery's two arrangements of one component set. Only the two shell- * components read it: every slot renders one way, so a size-dependent- * difference must be expressible as "which shell puts this where".- */+/** Only shells interpret arrangement; shared slots must work in either placement. */const isRailRegion = (region: string): boolean => region === 'left' || region === 'right';export type GalleryLayoutMode = 'stacked' | 'wide';@@ -16,12 +12,7 @@ export type GalleryLayoutMode = 'stacked' | 'wide';/** Below this the board column's ~240px leaves too little grid to scan. */export const GALLERY_WIDE_MIN_WIDTH_PX = 560;-/**- * Side panels are always stacked, whatever they measure: a docked inspector- * keeps one arrangement so it does not reflow as the user drags its edge.- * (Their maximum is 720px, so the threshold below is reachable there — the- * branch is the reason they never take it, not the width.)- */+/** Keep docked side panels stacked across resizing to avoid layout switches while dragging their edge. */export const getGalleryLayout = ({region,widthPx,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.tsindex 7471d9271a..2a5e71ba88 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts@@ -46,11 +46,7 @@ export const getGalleryBoardDropId = (boardId: string): string => `gallery-board/** Droppable id for the search field: dropping a gallery image there searches by similarity. */export const GALLERY_SEMANTIC_SEARCH_DROP_ID = 'gallery-semantic-search-drop';-/**- * Resolves an item drag released over the search field to an image-similarity- * reference. Semantic search is image-only, so a video-only drag resolves to- * nothing rather than to a broken query.- */+/** Only image refs support similarity queries; video-only drags yield no query. */export const resolveGallerySemanticSearchDrop = (activeData: unknown,overId: unknown@@ -94,19 +90,8 @@ export const isSingleGalleryVideoDragData = (value: unknown): value is GalleryItisGalleryItemDragData(value) && value.items.length === 1 && value.items[0]?.kind === 'video';/**- * A droppable that only participates while a drag matching `shields` is in- * flight. `acceptsActiveDrag` is the "potential target" bit the drop- * affordances render from (a drag the field's handler would consume exists- * ANYWHERE — legacy dnd's `potential` state); `isOver` narrows it to- * "hovering this target". `accepts` must match what the drop handler- * actually consumes, or the affordance advertises a drop that would no-op.- *- * `shields` (default: `accepts`) keeps the droppable armed for a WIDER- * payload family the handler merely ignores: a single-image field stays a- * dead drop for multi-image drags, exactly as before the affordances —- * disabling it instead would hand the release to whatever droppable sits- * underneath (the collision pipeline is z-blind), e.g. a board row hidden- * under a floated widget.+ * accepts controls affordances; shields keeps wider ignored payloads as dead drops, preventing z-blind collision+ * handling from dropping onto hidden targets underneath.*/export const useGalleryItemDroppable = (accepts: (data: unknown) => boolean,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.tsindex d0fbb76bf9..e2702107ea 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts@@ -48,8 +48,6 @@ describe('getGalleryColumnCountForCell', () => {describe('getGalleryColumnCount', () => {it('gives the same answer at the same width regardless of placement', () => {- // The whole point of measuring rather than branching on layout: a 600px- // gallery is a 600px gallery whether it sits in a panel or the center.const stacked = getGalleryColumnCount({ imageDensityPercent: 50, widthPx: 600 });const wide = getGalleryColumnCount({ imageDensityPercent: 50, widthPx: 600 });diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.tsindex e789dfd1db..bd5677ebbb 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts@@ -9,27 +9,14 @@ export const GALLERY_STARRED_HEADER_HEIGHT_PX = 24;export const GALLERY_PINNED_FOOTER_PX = 9;const GALLERY_MIN_COLUMN_COUNT = 2;-/**- * High enough that the minimum cell size, not this cap, bounds a wide- * placement: at 12 the bottom panel ignored the density slider below ~92px- * cells, while the side panel kept shrinking.- */+/** Keep the column cap high enough that minimum cell size governs wide layouts at every density. */const GALLERY_MAX_COLUMN_COUNT = 48;/** Cell size the density slider interpolates between: 0% is largest, 100% smallest. */const GALLERY_MAX_CELL_PX = 192;const GALLERY_MIN_CELL_PX = 48;-/**- * Density picks a target thumbnail size, and the available width decides how- * many of those fit.- *- * Keying off width rather than placement is what lets the two layouts share- * one grid: at equal pixel width the same density produces the same columns- * whether the gallery sits in a side panel or the center. The old- * layout-keyed maximum meant 50% density meant ~90px cells stacked and ~200px- * cells wide.- */+/** Density selects target cell size; measured width determines columns consistently across placements. */export const getGalleryTargetCellPx = (imageDensityPercent: number): number => {const percent = Math.min(100, Math.max(0, imageDensityPercent));@@ -94,12 +81,7 @@ export const mergeGalleryLoadedItems = (return [...starredItems, ...items.filter((item) => !seen.has(toGalleryItemKey(item)))];};-/**- * Rows are keyed by their leading cell rather than their index so that- * structural changes above a row (a placeholder resolving, the strip- * changing) move the row without recreating it: the virtualizer and React- * both track the row by key, so its thumbnails keep their DOM.- */+/** Key rows by their first cell so changes above them preserve thumbnail DOM identity. */export const chunkGalleryCellsIntoRows = (cells: readonly GalleryItem[],columnCount: number,@@ -121,11 +103,7 @@ export const chunkGalleryCellsIntoRows = (return rows;};-/**- * The listing's row model in one pure pass. The starred strip is pinned above- * the virtualized listing (see `getGalleryStarredLayout`), so only the listing- * chunks into rows.- */+/** Only listing items form virtual rows; the starred strip remains pinned above them. */export const buildGalleryGridRows = (items: readonly GalleryItem[], columnCount: number): GalleryGridRow[] =>chunkGalleryCellsIntoRows(items, columnCount, 'regular');@@ -191,9 +169,6 @@ export const getGalleryStarredLayout = ({};};-/**- * In progress and starred share one pinned block above the listing, closed by- * a rule and a margin; the virtualizer's scroll margin is the block's height.- */+/** The shared in-progress/starred block height defines the virtualizer's scroll margin. */export const getGalleryPinnedHeightPx = (progressHeight: number, starredHeight: number): number =>progressHeight + starredHeight > 0 ? progressHeight + starredHeight + GALLERY_PINNED_FOOTER_PX : 0;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryMenuIds.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryMenuIds.tsindex 68a1aed7df..b4b0ccc7ca 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryMenuIds.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryMenuIds.ts@@ -1,10 +1,7 @@import { useId, useMemo } from 'react';/**- * Shared trigger id for a menu whose trigger a `Tooltip` wraps. Both machines- * render onto one element and each wants to own its id; without this the menu- * has no anchor and opens at the viewport origin.- *+ * Share the trigger ID between menu and Tooltip to preserve anchoring.* @see workbench/shell/topbar/RoutingControl.tsx*/export const useMenuTriggerIds = (): { trigger: string } => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tsindex 72afda45ab..3dbab8eed9 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -86,9 +86,8 @@ describe('gallery state view', () => {});/**- * A project arriving from another install — or one whose pre-migration board was rejected as- * ambiguous — names a destination that does not exist here. Its own board is a better answer- * than Uncategorized, which would quietly scatter the project's output.+ * Missing imported destinations fall back to the project's board instead of scattering output into+ * Uncategorized.*/it('falls back to the project board before uncategorized', () => {const projectBoards = [...boards, { ...boards[1]!, id: 'project-board', name: 'My Project', projectId: 'p1' }];@@ -111,10 +110,7 @@ describe('gallery state view', () => {expect(getGallerySelectedBoardId(values, boards)).toBe('none');});- /**- * Never having chosen a destination is not a choice of Uncategorized. A project saved before it- * owned a board should still work on its own board, where everything else it has made lives.- */+ /** An absent saved destination is not an explicit choice of Uncategorized; use the project's board. */it('uses the project board when nothing was ever selected', () => {const projectBoards = [...boards, { ...boards[1]!, id: 'project-board', name: 'My Project', projectId: 'p1' }];diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex 5865b11e55..24bc6bb332 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -19,11 +19,7 @@ import {} from '@features/gallery/core/semanticImageQuery';import { getGallerySettings, type GallerySettings } from '@features/gallery/core/settings';-/**- * Stand-in shown before any board has loaded. `name` is intentionally empty:- * the UI labels uncategorized boards from `kind` through `getGalleryBoardLabel`,- * so there is no English string to invent here.- */+/** Leave the placeholder name empty; getGalleryBoardLabel localizes it from kind. */const UNCATEGORIZED_BOARD: GalleryBoard = {archived: false,assetCount: 0,@@ -38,10 +34,8 @@ const UNCATEGORIZED_BOARD: GalleryBoard = {export interface GalleryStateView {/**- * Page the infinite window starts at, when a reveal has anchored it- * mid-board; 0 whenever the window covers the top of the listing (always so- * in paginated mode). Non-zero means the grid cannot scroll above its first- * row, so the surface owes the user both an explanation and a way back.+ * A nonzero infinite anchor prevents scrolling to earlier rows; the surface must explain it and provide a return+ * to the top.*/anchoredWindowPage: number;boards: GalleryBoard[];@@ -93,9 +87,8 @@ export const getGalleryRawSelectedBoardId = (values: Record<string, unknown>): stypeof values.selectedBoardId === 'string' ? values.selectedBoardId : null;/**- * Where new results and uploads land: the board the person picked, else the- * project's own board. A date bucket cannot hold items, so it defers to the- * project board too; an explicit Uncategorized (`'none'`) choice is kept.+ * Use the chosen destination or project board; date buckets defer to the project, while explicit none remains+ * Uncategorized.*/export const getGalleryDestinationBoardId = (values: Record<string, unknown>): string | null => {const selectedBoardId = getGalleryRawSelectedBoardId(values);@@ -106,14 +99,8 @@ export const getGalleryDestinationBoardId = (values: Record<string, unknown>): s};/**- * Where new results land, resolved against the boards this install actually has.- *- * 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.- *- * An empty board list means "still loading", not "no such board", so nothing resolves yet.+ * Preserve valid destinations, otherwise use the project board. An empty board list means loading, so defer+ * resolution.*/export const resolveGallerySelectedBoardId = ({ projectBoardId, selectedBoardId }: { projectBoardId: string | null; selectedBoardId: string | null },@@ -217,11 +204,7 @@ export const getGalleryAnchoredWindowPage = (values: Record<string, unknown>): nreturn getGallerySettings(values).paginationMode === 'infinite' && page > 0 ? page : 0;};-/**- * `starredStripItems` are the strip the grid pins above the listing: a- * starred selection lives there, never in the unstarred listing, and still- * counts as visible.- */+/** Starred selections remain visible in the pinned strip rather than the unstarred listing. */export const getGalleryStateView = (values: Record<string, unknown>,backendBoards: GalleryBoard[],diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/launchpad/RecentOutputs.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/launchpad/RecentOutputs.tsxindex 519b3f2741..329a9cc757 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/launchpad/RecentOutputs.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/launchpad/RecentOutputs.tsx@@ -8,14 +8,7 @@ import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accoimport { useState } from 'react';import { useTranslation } from 'react-i18next';-/**- * The last few images this account produced, across every project.- *- * The gallery's own "recent images" is per-project widget state, so a- * cross-project strip has to read the backend directly. It uses the same- * cancellable read the command palette does, which is the entry point built- * for exactly this kind of deferred cross-feature surface.- */+/** Read account-wide recent output directly from the backend; widget recents are project-scoped. */const OUTPUT_COUNT = 8;const GRID_COLUMNS = { base: 4, md: 8 } as const;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsxindex 6bde943ee8..c160f5a679 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx@@ -336,13 +336,8 @@ describe('GalleryMediaSlot', () => {expect(find).not.toBeNull();- // Hidden until the slot is hovered or holds focus. A mouse hover cannot be- // synthesised, but both come from the same `.group` ancestor, so focus- // proves the wiring the badge depends on entirely.- //- // `pointer-events` rather than `opacity`: the reveal sets both under one- // selector, but only opacity is transitioned, so opacity answers for where- // the animation has got to rather than for whether the badge is revealed.+ // Assert focus-based reveal via pointer-events; opacity transitions cannot reliably indicate whether the badge+ // is revealed.expect(getComputedStyle(find!).pointerEvents).toBe('none');expect(getComputedStyle(find!).opacity).toBe('0');@@ -352,9 +347,7 @@ describe('GalleryMediaSlot', () => {expect(getComputedStyle(find!).pointerEvents).toBe('auto');- // The badge is a SIBLING of the slot's face — the face is a <button> and- // may not contain one — so its position is hand-mirrored from the value- // row's box metrics. Nothing but this ties the two together.+ // The badge must remain beside the button face; its copied box metrics must align it with the thumbnail.const tile = host?.querySelector('img')?.parentElement?.getBoundingClientRect();const badge = find!.getBoundingClientRect();@@ -371,9 +364,7 @@ describe('GalleryMediaSlot', () => {it('leaves the badge off a slot with nothing to reveal', async () => {const value: GalleryMediaSlotValue = { height: 96, kind: 'image', name: 'chosen.png', width: 128 };- // A slot whose media the gallery does not own (the prompt-template editor- // holds its own upload) passes no `onFind`, and an empty slot has nothing- // to find — neither may show the badge.+ // Empty slots and media outside the gallery must not expose reveal badges.await renderSlot({ value });expect(host?.querySelector('button[aria-label^="widgets.gallery.findNamedInGallery"]')).toBeNull();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsxindex 66a2f6edb3..0f8f8cd202 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx@@ -67,13 +67,8 @@ const getThumbnailUrl = (value: GalleryMediaSlotValue): string =>value.kind === 'video' ? getGalleryVideoThumbnailUrl(value.name) : getGalleryImageThumbnailUrl(value.name);/**- * A single-item media field: click opens the gallery picker (which carries the- * gallery upload), and a gallery drag can be dropped on it. Owns the async- * resolve work and its busy and error states; the consumer only sees- * `onChange` with a full item (or null when cleared). A consumer that stores- * the file itself — media the gallery does not hold — takes it through- * `onUploadFile`, which adds a file action to the row, and can show its own- * `thumbnail` for such a value.+ * Own async resolution and report complete items through onChange. onUploadFile and custom thumbnails support+ * media stored outside the gallery.*/export const GalleryMediaSlot = ({accept,@@ -98,11 +93,7 @@ export const GalleryMediaSlot = ({thumbnail?: ReactNode;value: GalleryMediaSlotValue | null;onChange: (item: GalleryItem | null) => void;- /**- * Reveals the current value in the Gallery grid. Given, the thumbnail carries- * a find badge on hover; omitted, it stays a plain preview — a slot holding- * media the gallery does not own has nothing to reveal.- */+ /** Provide onFind only for gallery-owned media; it enables the thumbnail reveal badge. */onFind?: () => void;/** Takes a file the consumer stores itself; gallery-backed slots upload through the picker instead. */onUploadFile?: (file: File) => void;@@ -291,12 +282,10 @@ export const GalleryMediaSlot = ({</DropZone></GalleryPickerPopover>{value && onFind ? (- /* A sibling of the slot's face, not a child of it: that face is a- <button>, which may not contain another. The row repeats the value- row's own box metrics — its height, padding, and tile size — so the- badge lands on the thumbnail's corner without measuring anything.- It rides a pixel high, by the face's border; nothing a corner badge- can show. */+ /*+ * Keep the badge beside the button face to avoid nested buttons; matching row metrics align it without+ * measurement.+ */<HStack gap="3" h="20" insetInline="0" p="2" pointerEvents="none" position="absolute" top="0"><Box boxSize="16" flexShrink="0" position="relative"><FindInGalleryThumbnailButton name={value.name} onFind={onFind} />diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerBoards.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerBoards.tsxindex 185547999e..f94383a7f6 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerBoards.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerBoards.tsx@@ -45,10 +45,7 @@ const GalleryPickerBoardRow = memo(function GalleryPickerBoardRow({);});-/**- * The grouped board list the picker swaps in for its grid. Arrow keys walk the- * rows; leaving the top row hands focus back to the search field.- */+/** Arrow navigation leaving the top board row returns focus to search. */export const GalleryPickerBoards = ({emptyMessage,galleryView,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsxindex 72904444ea..a5203c78c5 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsx@@ -72,8 +72,7 @@ const GalleryPickerTile = memo(function GalleryPickerTile({? t(item.kind === 'video' ? 'widgets.gallery.picker.unsupportedVideo' : 'widgets.gallery.picker.unsupportedImage'): undefined;- // Ref callbacks re-run when `isActive` changes, so the keyboard highlight- // stays in view without an effect; pointer hover never moves it.+ // Active-state ref callbacks reveal keyboard highlights; pointer hover must not scroll.const scrollIntoView = useCallback((node: HTMLDivElement | null) => {if (node && isActive) {@@ -131,10 +130,8 @@ const GalleryPickerTile = memo(function GalleryPickerTile({});/**- * The picker's tile grid: the column count follows the measured width, one- * delegated click serves every tile, and a sentinel at the end asks for the- * next page. Not virtualized — the base infinite window bounds the rows and- * lazy images keep the network idle until scrolled.+ * The bounded infinite window limits nonvirtualized rows; lazy images defer requests and the sentinel loads+ * further pages.*/export const GalleryPickerGrid = ({activeKey,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsxindex a116e05b26..abff4a8c17 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx@@ -446,9 +446,8 @@ describe('GalleryPickerPopover', () => {expect(galleryCommands.selectBoard).not.toHaveBeenCalled();});- // The video-kind picker is the surface the widened accept list exists for: it is what the- // "Initial video" upload button opens. Asserted through a rendered picker because the- // narrowing that caused the bug lived in the view's `accept` wiring, not in the builder.+ // Assert video acceptance through the rendered picker; the regression was view wiring rather than the+ // accept-list builder.it('offers the full video and audio list on a video-kind picker', async () => {const { dialog } = await openPicker(<GalleryPickerPopover accept={['video']} label="Choose video" onPick={onPick}>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsxindex a7d55a635d..905d7964de 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsx@@ -35,10 +35,7 @@ export interface GalleryPickerPopoverProps {onPick: (item: GalleryItem) => void;}-/**- * A compact gallery anchored to an image slot. The view mounts on open and- * unmounts on close, so every open starts from the Gallery widget's scope.- */+/** Mount on open and unmount on close so each opening starts from the Gallery widget's scope. */export const GalleryPickerPopover = ({accept,children,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsxindex 2a01d276dd..5dbe710301 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx@@ -73,13 +73,10 @@ export const GalleryPickerView = ({const [activeKey, setActiveKey] = useState<ActiveKeyState>(undefined);const [columnCount, setColumnCount] = useState(GALLERY_PICKER_MIN_COLUMNS);const [isUploading, setIsUploading] = useState(false);- // Live read ports: an upload resolves after an await and must judge capacity- // against the selection as it stands then; the sentinel observer wants one- // stable callback rather than a rebuild per fetched page.+ // Async uploads need current selection capacity; the sentinel needs a stable callback across page fetches.const selectionRef = useRef(selection);const loadMoreRef = useRef(data.loadMore);- // The previous scope's items stay on screen, dimmed, while a new board or- // search loads; skeletons only ever show before anything has loaded.+ // Keep prior items dimmed during scope changes; show skeletons only before the first result.const [lastItems, setLastItems] = useState<GalleryItem[] | null>(null);// eslint-disable-next-line react/refsdiff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/galleryPicker.ts b/invokeai/frontend/webv2/src/features/gallery/ui/picker/galleryPicker.tsindex f0150fb229..2c2aca3951 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/galleryPicker.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/galleryPicker.ts@@ -110,11 +110,7 @@ export type GalleryPickerStatusPart =| { count: number; kind: 'boardCount' | 'itemCount' | 'matchCount' | 'remainingCount' | 'windowLimit' }| { kind: 'remainingNone' | 'unsupportedImage' | 'unsupportedVideo' };-/**- * The footer line, most specific first: the boards pane counts boards; a- * highlighted tile the slot cannot take explains itself; otherwise capacity,- * then either the window cap or the listing size.- */+/** Footer priority: board count, incompatible-highlight explanation, capacity, then window cap or listing size. */export const getGalleryPickerStatus = ({accept,activeItem,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.ts b/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.tsindex 58cd523d6f..dd4af68437 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.ts@@ -24,10 +24,8 @@ export interface GalleryPickerScope {}/**- * The picker's local view of the gallery: seeded from the Gallery widget's- * values when the picker mounts (the popover unmounts on close, so mounting is- * opening) and never written back. The search field serves whichever pane is- * showing, so a pane switch clears it.+ * Seed local scope on open without writing back. Clear search when switching panes because each pane interprets it+ * differently.*/export const useGalleryPickerScope = () => {const { galleryValues } = useGalleryUi();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsxindex b4b331d109..6bae550f5d 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx@@ -671,10 +671,7 @@ describe('mixed gallery upload', () => {describe('setSemanticImageQuery', () => {it('applies the reference while resetting pagination and clearing the text term', () => {- // Paginated mode with the user on a later page: applying a semantic query- // replaces the result set, so the page must snap back to the first one- // (mirroring setGallerySearchTerm) and the term the chip replaces must not- // keep filtering invisibly.+ // Replacing the ranking resets pagination and clears the hidden metadata term.actionsRef.current?.setSemanticImageQuery({ imageName: 'ref.png', kind: 'image' });expect(patchGalleryValues).toHaveBeenCalledOnce();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.tsindex e96a3ba459..687afc5f33 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts@@ -59,8 +59,6 @@ export const useGalleryActions = ({return {archiveBoard: async (boardId, archived) => {const owner = captureAccountScope();- // Optimistic: the board moves between sections immediately, and- // archiving the board being viewed steps off it right away.const rollback = patchGalleryBoardCaches(queryClient, boardId, { archived });const movedSelectionAway = archived && boardId === selectedBoardId;@@ -181,8 +179,6 @@ export const useGalleryActions = ({refresh,renameBoard: async (boardId, boardName) => {const owner = captureAccountScope();- // Optimistic: the new name paints everywhere at once; the refresh- // re-sorts name-ordered lists once the backend confirms.const rollback = patchGalleryBoardCaches(queryClient, boardId, { name: boardName });try {@@ -210,17 +206,8 @@ export const useGalleryActions = ({setSemanticSearchText: gallery.setSemanticSearchText,commitSemanticSearch: gallery.commitSemanticSearch,clearSearch: gallery.clearSearch,- // The similarity reference is widget state rather than a workbench- // command: it patches the gallery widget's persisted values, the same- // surface the parsed query is read back from. Changing the query resets- // pagination (mirroring setGallerySearchTerm) and clears the text term- // the chip visually replaces — left behind, a stale term would keep- // filtering invisibly and poison the preview widget's navigation query.- // A reference also ends semantic text mode: the chip replaces the- // field, and the field must not come back holding text for a ranking- // the chip's clear has just dismissed.- // Filmstrip/preview navigation under semantic ranking still follows- // board chronology, not similarity rank — an inherited limitation.+ // Store references in widget values, reset pagination, and clear replaced text/mode so hidden filters cannot+ // affect listing or Preview navigation.setSemanticImageQuery: (reference) =>widgets.patchGalleryValues({galleryPage: 0,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.tsindex dd01f943cf..9f287f41fe 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts@@ -150,10 +150,8 @@ describe('mergeGalleryItemWindow', () => {});it('places an overlaid recent by its instant, not by timestamp shape, against backend items', () => {- // Backend rows carry SQLite `created_at` ("2026-08-29 13:01:20.649"); the- // overlay carries the queue's ISO `submittedAt`. The overlaid recent is- // older than every loaded backend row and absent from the window: with- // Newest first it must sort below them, not above them.+ // SQLite and ISO timestamps must sort chronologically; an older recent cannot outrank newer backend rows by+ // separator.const backendItems = [createBackendItem('newer.png', '2026-08-29 13:01:20.649'),createBackendItem('middle.png', '2026-08-29 12:00:00.000'),@@ -182,8 +180,7 @@ describe('mergeGalleryItemWindow', () => {});it('places a completed batch image by its creation time, not the batch submission time', () => {- // Overlaid recents must sort by creation time, or each fresh completion- // lands below its already-listed siblings until the refetch catches up.+ // Sort overlaid completions by creation time while awaiting backend refetch.const backendItems = [createBackendItem('batch-2.png', '2026-08-29 13:05:00.000'),createBackendItem('batch-1.png', '2026-08-29 13:04:00.000'),diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.tsindex 4afc199156..0cce9f773e 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts@@ -27,13 +27,7 @@ export interface GalleryData {isLoadingItems: boolean;/** The resolved board the items were fetched for. */selectedBoardId: string;- /**- * True when the infinite window is full *and* the board holds more images- * than it can reach. `hasMore` is false in that case exactly as it is at the- * true end of a board, so the two must be distinguishable: stopping at the- * end is complete, stopping at the cap is not, and only one of them owes the- * user an explanation.- */+ /** Distinguish reaching the window cap from reaching the board end; only truncation needs an explanation. */isWindowTruncated: boolean;items: GalleryItem[] | null;loadMore: () => void;@@ -58,9 +52,7 @@ const useGalleryBoards = ({ settings }: { settings: GallerySettings }) => {};const isRecentItemVisible = (item: GalleryItem, filter: GalleryItemsFilter): boolean => {- // A recent belongs to the unstarred listing (the grid); the starred-only- // listing has no slot for it — exactly like a text search — and a recent- // starred since it landed has moved to the strip.+ // Overlay recents only in the unstarred listing; newly starred recents belong to the strip.if (filter.searchTerm !== '' ||filter.createdFrom !== undefined ||@@ -121,15 +113,7 @@ export const mergeGalleryItemWindow = ({return mergedItems.slice(0, maxRows);};-/**- * Distinguishes "this board has no more images" from "this board has more- * images than the infinite window can reach".- *- * Both leave `hasNextPage` false, but only the second one is incomplete, and a- * gallery that silently stops scrolling with a thousand images on the server- * reads as a bug. Paginated mode is never truncated: every page is reachable- * by asking for it.- */+/** A false hasNextPage can mean either completion or truncation. Paginated mode remains fully reachable. */export const isGalleryWindowTruncated = ({hasNextPage,isPaginated,@@ -207,10 +191,7 @@ export const useGalleryData = ({} = useInfiniteQuery(galleryItemsInfiniteOptions(filter,- // In infinite mode `page` anchors where the window starts — 0 in normal- // browsing (every board/search/view change resets it). A reveal to an- // image deeper than the base window's reach sets it, so the grid can- // show that part of the listing at all.+ // Infinite page values anchor deep reveals; board/search/view changes reset them to zero.isPaginated? { kind: 'anchor', offset: page * GALLERY_PAGE_SIZE }: { kind: 'infinite', offset: page * GALLERY_PAGE_SIZE }diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.tsindex 1caa91568d..4efba3b6bd 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.ts@@ -26,11 +26,8 @@ const GALLERY_HOTKEYS = [] as const satisfies readonly (readonly [string, string, GalleryNavigationDirection | null, readonly string[]])[];/**- * Registers the grid's commands and their default keys.- *- * Handlers run through `useEffectEvent` so registration depends only on the- * runtime and the translator: re-registering every command on each selection- * change would churn the palette and the hotkey map on every click.+ * Read current handler state without re-registering commands on selection changes, avoiding palette and hotkey+ * churn.*/export const useGalleryGridHotkeys = ({actionSelectionRefs,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.tsindex b06f1fbfe9..b6aacc8312 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.ts@@ -35,14 +35,8 @@ const getGalleryItemRange = (};/**- * Click semantics for grid tiles — plain select, shift-range, ctrl/cmd-toggle,- * alt-compare — plus the context-menu target.- *- * Range selection can span beyond the loaded window, so it fetches the full- * ordered name list. That is asynchronous, and the user can keep interacting- * while it is in flight, hence the captured-context guard: a range only applies- * if the account, the query filter, and the anchor are all still what they were- * when the click happened.+ * Async range selection fetches beyond the loaded window; apply only if account, filter, and anchor still match+ * the captured context.*/export const useGalleryGridSelection = () => {// `loadedItems` includes the strip, whose starred items the listing windowdiff --git a/invokeai/frontend/webv2/src/features/generation/canvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/canvasGraph.tsindex 487c1fb24f..b3e866d3ad 100644--- a/invokeai/frontend/webv2/src/features/generation/canvasGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/canvasGraph.ts@@ -1,10 +1,3 @@-/**- * Canvas graph compilation's lazy-load interface.- *- * Keep this separate from the shared `graph` interface: the Canvas invocation- * runtime is loaded on demand, while generate graph helpers are needed during- * workbench startup. Mixing both compilers in one interface pulls Canvas-only- * processing code into the initial editor graph.- */+/** Keep canvas compilation separate from startup graph helpers to preserve lazy loading. */export { compileCanvasGraph } from './core/canvas/compileCanvasGraph';export type { CanvasCompileMode } from './core/canvas/types';diff --git a/invokeai/frontend/webv2/src/features/generation/canvasProcessingSize.ts b/invokeai/frontend/webv2/src/features/generation/canvasProcessingSize.tsindex 7c39bbdf78..bc253096de 100644--- a/invokeai/frontend/webv2/src/features/generation/canvasProcessingSize.ts+++ b/invokeai/frontend/webv2/src/features/generation/canvasProcessingSize.ts@@ -1,7 +1,2 @@-/**- * The canvas processing-size policy, on its own lazy interface: its only- * consumers (the canvas graph compiler and the Generate form's canvas- * section) load on demand, so it must not ride the eager `graph` entry into- * the initial editor graph.- */+/** Load processing-size policy lazily to keep canvas dependencies out of the initial bundle. */export { resolveCanvasProcessingSize } from './core/canvas/canvasProcessingSize';diff --git a/invokeai/frontend/webv2/src/features/generation/components.ts b/invokeai/frontend/webv2/src/features/generation/components.tsindex 2895e7ff4f..992d1dc5b1 100644--- a/invokeai/frontend/webv2/src/features/generation/components.ts+++ b/invokeai/frontend/webv2/src/features/generation/components.ts@@ -1,8 +1,3 @@-/**- * Generation's reusable UI components: prompt fields, reference-image controls,- * and the settings section shell shared with other widgets.- * Curated, caller-driven export list — add a symbol only when a consumer needs it.- */export {AspectRatioLockButton,AspectRatioSelect,diff --git a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.test.ts b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.test.tsindex fb4d700878..4a6bacb466 100644--- a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.test.ts@@ -1,9 +1,6 @@/**- * The mapper, driven by the real response body.- *- * `__fixtures__/architectureCapabilities.json` is pinned against the backend by- * `tests/backend/architectures/test_capabilities_fixture.py`, so these assertions are about the- * payload the app actually receives rather than a hand-written stand-in.+ * __fixtures__/architectureCapabilities.json is pinned to the backend by+ * tests/backend/architectures/test_capabilities_fixture.py.*/import { afterEach, describe, expect, it } from 'vitest';@@ -43,9 +40,7 @@ describe('the wire contract', () => {describe('toBaseGenerationConfig', () => {it('reads the guidance field for a guidance-labelled architecture', () => {- // dev is FLUX's base row -- variant rows exist only where they differ. It records cfg_scale- // 1.0 ("CFG off") alongside guidance 3.5, and buildFluxGraph wires this value into the node's- // `guidance`. Preferring cfg_scale would generate at 1.0.+ // guidance 3.5 is distinct from cfg_scale 1.0, which disables CFG.expect(toBaseGenerationConfig(row('flux')).defaults.cfgScale).toBe(3.5);expect(toBaseGenerationConfig(row('flux', 'dev_fill')).defaults.cfgScale).toBe(30);});@@ -64,8 +59,7 @@ describe('toBaseGenerationConfig', () => {});it('derives the optimal side from the declared area, not from width alone', () => {- // Square today for every generatable architecture, so this is the identity -- but MiniMax H3- // is 1344x768, so the area form is what keeps a non-square canvas from being squashed.+ // Nonsquare defaults verify that optimum derives from area.expect(toBaseGenerationConfig(row('sd-1')).dimensions.optimalSide).toBe(512);expect(toBaseGenerationConfig(row('sd-2')).dimensions.optimalSide).toBe(768);expect(toBaseGenerationConfig(row('minimax-h3')).dimensions.optimalSide).toBe(1016); // sqrt(1344*768)@@ -144,10 +138,7 @@ describe('the registry', () => {describe('publishing the table', () => {it('stays empty when a malformed row makes the mapping throw', () => {- // The wire type is applied by an unchecked `as` in the api module, so a row the backend never- // meant to serve is reachable. Publishing the rows before mapping them left the registry- // saying "loaded" over an empty config map: the widget would show the load error while every- // fail-closed gate elsewhere opened onto fallback policy for every architecture.+ // Validate before publication so malformed rows cannot mark fallback policy loaded.const malformed = [...rows, { base: 'broken', variant: null } as unknown as ArchitectureCapabilitiesRow];expect(() => setArchitectureCapabilities(malformed)).toThrow();@@ -168,8 +159,7 @@ describe('publishing the table', () => {});it('notifies subscribers when the table is replaced or dropped', () => {- // The single subscription contract behind every imperative reader: renders, the bbox grid, the- // Invoke gate and the bbox <-> dims sync all re-read on this.+ // One registry subscription serves all synchronous policy readers.const seen: number[] = [];const unsubscribe = onArchitectureCapabilitiesChanged(() => seen.push(getArchitectureCapabilitiesRevision()));diff --git a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.testing.ts b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.testing.tsindex 187bfabb05..dd3ddf0e51 100644--- a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.testing.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.testing.ts@@ -1,13 +1,4 @@-/**- * Seeds the architecture capability registry for tests.- *- * Generation policy comes from the backend now, and the resolver fails closed without it, so any- * test that touches policy needs the table present -- the way it always is in a running app, where- * app boot fetches it before the Generate widget renders.- *- * Explicit rather than a global setup file: a test that wants to observe the *unloaded* behaviour- * should be able to see that it is unloaded.- */+/** Seed fixtures explicitly so tests can still exercise unloaded policy. */import { afterEach, beforeEach } from 'vitest';diff --git a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.tsindex d5ae040e91..fdae256b51 100644--- a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts@@ -1,18 +1,6 @@/**- * What the backend says each architecture supports, and how it reaches generation policy.- *- * `GET /api/v2/models/capabilities` serves one row per architecture plus a row per variant that- * answers differently -- the same table `invokeai/backend/architectures/defs/<base>.py` declares.- * Adding an architecture to the backend should not mean editing a table here too.- *- * webv2 has no generated OpenAPI types, so the wire shape below is hand-written and unguarded by- * the compiler. `tests/backend/architectures/test_capabilities_fixture.py` is what guards it: it- * pins `__fixtures__/architectureCapabilities.json` against what the backend actually renders, and- * that same fixture feeds these tests and the mock backend.- *- * This module is deliberately push-based. `feature-core-purity` forbids `core/` from importing- * `data/` or transport, so the store calls `setArchitectureCapabilities` rather than being read- * from here -- the same shape `configureHttpAuth` uses in `platform/transport/http.ts`.+ * Backend architecture/variant rows are authoritative. Handwritten DTOs are fixture-pinned; push updates into this+ * React-free registry.*/import { createListenerChannel } from '@platform/state/externalStoreCore';@@ -60,12 +48,7 @@ export interface ArchitectureCapabilitiesRow {cpu_only: boolean | null;fp8_storage: boolean | null;} | null;- /**- * Which VAEs this architecture's decode accepts beyond its own base, or null where it accepts- * only its own. `latent_channels` is null unless the base ships VAEs of more than one width;- * today only `wan` does, and its two are different decoders -- which is why the `ti2v_5b` row- * carries its own list.- */+ /** Null restricts VAE compatibility to the model's own base; channel restrictions are optional. */vae: {accepted: { base: string; latent_channels: number | null }[];} | null;@@ -76,26 +59,12 @@ const FALLBACK_CFG_SCALE = 7;const FALLBACK_SCHEDULER = 'euler_a';const FALLBACK_OPTIMAL_SIDE = 1024;-/**- * The value the single guidance slider takes.- *- * There is one control, labelled from `guidance_label`, and two fields behind it. A- * guidance-distilled architecture records `cfg_scale: 1.0` meaning "CFG off" *and* the guidance it- * samples with, so reading `cfg_scale` first would present the off-switch as the setting.- */+/** guidance_label selects the field; CFG-off markers are not guidance values. */const guidanceValue = (defaults: NonNullable<ArchitectureCapabilitiesRow['defaults']>, label: GuidanceLabel): number =>(label === 'Guidance' ? (defaults.guidance ?? defaults.cfg_scale) : (defaults.cfg_scale ?? defaults.guidance)) ??FALLBACK_CFG_SCALE;-/**- * The optimal canvas as a side length.- *- * `optimalSide` is squared back into an area by its consumers (`importGalleryImages` passes- * `optimal ** 2` to `calculateNewSize`), so deriving it from the area rather than from `width`- * alone survives an architecture whose default canvas is not square. Every architecture webv2- * generates images with is square today; MiniMax H3 is 1344x768, which is why this is not just- * `width`.- */+/** Derive optimal side from pixel area, including nonsquare defaults. */const optimalSide = (defaults: NonNullable<ArchitectureCapabilitiesRow['defaults']>): number => {const { width, height } = defaults;if (width && height) {@@ -123,9 +92,7 @@ export const toBaseGenerationConfig = (row: ArchitectureCapabilitiesRow): BaseGeschedulerSet: features.scheduler_set ?? 'standard',schedulerAppliesToGraph: features.scheduler_applies_to_graph,guidanceLabel,- // `??` like every sibling here: a backend that predates these fields would otherwise put- // `undefined` into a `number`, and `Math.max(undefined, value)` is NaN -- a broken thumb rather- // than the unbounded control this had before the fields existed.+ // Nullish fallbacks support older backend fields without producing NaN bounds.guidance: { min: features.guidance_min ?? 1, max: features.guidance_max ?? null },negativePrompt: features.negative_prompt,ui: {@@ -147,14 +114,7 @@ let byKey = new Map<string, ArchitectureCapabilitiesRow>();let configByKey = new Map<string, BaseGenerationConfig>();let revision = 0;-/**- * Fires whenever the table below is replaced or dropped.- *- * Everything here is synchronous module state, read during render and at enqueue time from all over- * the app. Without a change signal a reader that answered before the table arrived keeps its- * fallback answer for the rest of the session -- it has nothing to re-read on. `data/` mirrors this- * into its snapshot, so React and non-React readers subscribe to one signal.- */+/** Synchronous readers observe the registry revision signal. */const channel = createListenerChannel();/** Subscribe to table replacements. Returns an unsubscribe function. */@@ -165,10 +125,7 @@ export const getArchitectureCapabilitiesRevision = (): number => revision;/** Called by `data/` once the table has been fetched. */export const setArchitectureCapabilities = (next: readonly ArchitectureCapabilitiesRow[]): void => {- // Built into locals, then swapped in one step. Assigning `rows` first would publish a table that- // `hasArchitectureCapabilities` reports as present while the rows are still being mapped: a- // malformed row's throw would then leave every fail-closed gate open over an empty config map,- // so the widget would show the load error while the canvas and topbar used fallback policy.+ // Validate and map before atomic publication; errors must not expose a loaded empty map.const nextByKey = new Map(next.map((row) => [key(row.base, row.variant), row]));// Memoised so policy accessors stay O(1) and hand back referentially stable objects.const nextConfigByKey = new Map(next.map((row) => [key(row.base, row.variant), toBaseGenerationConfig(row)]));@@ -219,13 +176,7 @@ export const getArchitectureGenerationConfig = (base: string, variant?: unknown)return configByKey.get(key(base, null));};-/**- * The `features` block for an architecture, preferring a variant row where the backend serves one.- *- * Most flags repeat unchanged on every variant row, but not all: `dimension_grid` is 16 for Wan- * A14B and 32 for TI2V-5B, and `guidance_min`/`guidance_max` sit in the same block. Callers that- * know the variant should pass it; omitting it asks for the architecture's own row.- */+/** Look up the variant first; omitting it uses the base row. */export const getArchitectureFeatures = (base: string,variant?: unknowndiff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tsindex 53b081b3cb..3b81f6509d 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts@@ -121,8 +121,6 @@ describe('architecture policy, read from the backend capability table', () => {});it('matches expected defaults per base', () => {- // These now come from the architecture facets rather than a table maintained here, so several- // moved to the values the model cards recommend. See the PR description for the full list.expect(getDefaultGenerateSettings(createModel('sdxl'))).toMatchObject({steps: 30,cfgScale: 7,@@ -130,8 +128,7 @@ describe('architecture policy, read from the backend capability table', () => {width: 1024,height: 1024,});- // FLUX's base row is dev: 28 steps at guidance 3.5. The old single row carried Schnell's step- // count for every variant, which is what the variant rows below now express properly.+ // The FLUX base row describes dev.expect(getDefaultGenerateSettings(createModel('flux'))).toMatchObject({steps: 28,cfgScale: 3.5,@@ -156,8 +153,6 @@ describe('architecture policy, read from the backend capability table', () => {});it('answers per variant where the architecture does', () => {- // The gain the single-row table could not express: Schnell and dev want different step counts,- // and Fill wants a guidance an order of magnitude higher.expect(getDefaultGenerateSettings(createModel('flux', { variant: 'schnell' }))).toMatchObject({ steps: 4 });expect(getDefaultGenerateSettings(createModel('flux', { variant: 'dev_fill' }))).toMatchObject({steps: 50,@@ -268,8 +263,7 @@ describe('architecture policy, read from the backend capability table', () => {expect(isSupportedGenerateModel(createModel('sdxl-refiner'))).toBe(false);expect(isSupportedGenerateModel(createModel('unknown'))).toBe(false);expect(isSupportedGenerateModel(createModel('made-up'))).toBe(false);- // 'external' is the pseudo-base of external image generators; they are supported through- // `type === 'external_image_generator'`, not by having an architecture row.+ // Handle external pseudo-bases through model type, not architecture rows.expect(isSupportedGenerateModel(createModel('external'))).toBe(false);});@@ -289,27 +283,18 @@ describe('architecture policy, read from the backend capability table', () => {const conditional = createModel('ideogram-4', { branch: 'conditional', format: 'checkpoint' });it('keeps a model that cannot run on its own out of every picker', () => {- // Ideogram 4's unconditional branch is the thing the conditional one is guided against. It is- // a `main` model on a generatable base, so the loose predicate accepts it and the user can- // assemble a complete-looking selection that the backend refuses at enqueue.+ // An unconditional Ideogram branch is not independently generatable despite its main type.expect(isSupportedGenerateModel(unconditional)).toBe(true);expect(isGenerateModelSelectable(unconditional)).toBe(false);expect(isGenerateModelSelectable(conditional)).toBe(true);expect(isGenerateModelSelectable(createModel('ideogram-4', { format: 'diffusers' }))).toBe(true);- // Wan's low-noise expert is deliberately still selectable: without it the high-noise expert- // runs the whole schedule and still produces a video.+ // Wan's low-noise expert remains selectable because the other expert can span the schedule.expect(isGenerateModelSelectable(createModel('wan', { variant: 'a14b' }))).toBe(true);});it('is what every path that offers or picks a model filters with', () => {- // The exclusion is only worth anything where models are *chosen*. `GenerateModelCard` had it- // and the palette, the widget fallback and the default resolver did not, so the same dead end- // stayed reachable — the resolver worst of all, since the user never picks that model.- //- // Asserted on the call, not on the identifier: an earlier version of this test looked for the- // name anywhere in the file and passed with the filter reverted, because the import line- // still mentioned it. The default resolver additionally has a behavioural test of its own.+ // Check actual selection calls across entry points, not merely their imports.const callSites = {'../../../workbench/palette/paletteProviders.ts': '.filter(isGenerateModelSelectable)','./resolveGenerateWidgetValues.ts': 'models.filter(isGenerateModelSelectable)',@@ -589,8 +574,7 @@ describe('component policies', () => {});it('offers only the PiD slots for a PiD-capable base with no other components', () => {- // SDXL needs no encoders or VAE of its own, but it can decode through PiD, so the two- // PiD slots are offered (and are only *required* once PiD is switched on).+ // SDXL exposes PiD slots before enabling PiD; they become required only when enabled.const model = createModel('sdxl');expect(getComponentSectionPolicy(model, createSettings(model)).slots.map((slot) => slot.key)).toEqual([@@ -1002,8 +986,7 @@ describe('component policies', () => {});it('validates the reference image count against the served limit, not a local default', () => {- // Every image base serves 5 today, which is also the old local default -- so a table that serves- // a different number is the only way to tell "reads the table" from "happens to agree with it".+ // A nondefault served limit distinguishes table reads from hardcoded policy.setArchitectureCapabilities(architectureCapabilitiesFixture.map((row) =>row.base === 'sdxl' ? { ...row, features: { ...row.features, max_reference_images: 2 } } : row@@ -1134,11 +1117,7 @@ describe('Krea-2, Ideogram 4 and Wan policies', () => {});it('rejects Ideogram 4 step and mu overrides outside what its denoise node accepts', () => {- // `steps` is ge=2 (the node keeps a polish step and a main step) and `mu` is ge=-4/le=4 -- the- // mu control used to offer 0..10, so more than half its track was rejected at enqueue and the- // whole negative half was unreachable.- // Diffusers: this is about the numeric ranges, and a single-file main would also report its- // unfilled component slots.+ // Use valid bounds and a Diffusers bundle to isolate scalar validation from missing components.const model = createModel('ideogram-4', { format: 'diffusers' });expect(getGenerationValidationReasons(model, createSettings(model, { ideogram4Steps: 1 }))).toContain(@@ -1153,9 +1132,7 @@ describe('Krea-2, Ideogram 4 and Wan policies', () => {});it('rejects an Ideogram 4 guidance override outside what its denoise node accepts', () => {- // `ideogram4_denoise.guidance_scale` is ge=1/le=20, and graph.ts forwards the override verbatim- // whenever it is not null. Normalization only checks finiteness, so a value stored before the- // control was bounded survives a reload and fails at enqueue.+ // Finite persisted Ideogram values still need range validation.const model = createModel('ideogram-4');const message = 'Ideogram 4 guidance must be between 1 and 20.';@@ -1175,9 +1152,7 @@ describe('Krea-2, Ideogram 4 and Wan policies', () => {});it('accepts a Qwen-Image VAE registered under the anima base, as the backend loader does', () => {- // The same physical Qwen-Image VAE is registered as `anima` or `qwen-image` depending on- // which family it was installed for, and krea2_model_loader declares- // ui_model_base=[QwenImage, Anima]. Accepting only `qwen-image` hid a working VAE.+ // Accept the same Qwen VAE under anima and qwen-image registrations.const animaRegisteredVae: VaeModelConfig = {base: 'anima',key: 'anima-qwen-vae',@@ -1195,8 +1170,7 @@ describe('Krea-2, Ideogram 4 and Wan policies', () => {const slots = getComponentSectionPolicy(checkpoint, settings).slots;const vaeSlotPolicy = slots.find((slot) => slot.key === 'vae');- // The picker filter and the validator must agree, or the dropdown hides a VAE that- // validation would then demand.+ // Picker and validator must share compatibility rules.expect(vaeSlotPolicy?.filter?.(animaRegisteredVae, {model: checkpoint,@@ -1336,9 +1310,7 @@ describe('Krea-2, Ideogram 4 and Wan policies', () => {});describe('the guidance slider value from a model record', () => {- // MainModelDefaultSettings has separate cfg_scale and guidance fields; the UI has one control.- // Which field feeds it depends on guidanceLabel, and getting that backwards reads a distilled- // model's "CFG off" marker as its guidance setting.+ // guidanceLabel selects guidance or cfg_scale so CFG-off markers cannot become guidance.it('prefers guidance over cfg_scale for a guidance-labelled architecture', () => {const model = createModel('flux', {variant: 'dev',@@ -1365,10 +1337,7 @@ describe('the guidance slider value from a model record', () => {});it('ignores a guidance a CFG-labelled model also records', () => {- // `default_settings.guidance` is editable on *every* main model — it is in MAIN_FIELDS- // unconditionally (`defaultSettingsFields.ts`), not gated on base. So an SDXL record can carry- // one, and it must not displace the cfg_scale that base actually generates with. The case above- // has only cfg_scale set and would pass either way round.+ // Provide both defaults to expose wrong-field precedence even for non-guidance models.const model = createModel('sdxl', {default_settings: { cfg_scale: 7, guidance: 4, steps: 30 },} as Partial<MainModelConfig>);@@ -1377,10 +1346,7 @@ describe('the guidance slider value from a model record', () => {});it('reads the right field for every base in the table', () => {- // Swept rather than sampled: a base added to the capability table with the wrong label picks- // the wrong field silently, and the three cases above only name three bases.- // Both probes sit inside every architecture's served guidance range, so the clamp in- // `getGenerationDefaults` cannot mask a wrong field read (flux2's ceiling is 20).+ // Probe every architecture within bounds so clamping cannot hide wrong-field reads.for (const base of SUPPORTED_GENERATE_BASES) {const model = createModel(base, {default_settings: { cfg_scale: 7, guidance: 9 },@@ -1397,18 +1363,14 @@ describe('the guidance slider value from a model record', () => {describe('the guidance range the architecture declares', () => {seedArchitectureCapabilities();- /**- * Only the bound messages: the point is which end was violated, not whatever else a bare model- * record is missing (`createModel('flux')` has no encoders, for instance).- */+ /** Isolate bound errors from unrelated missing components. */const guidanceReasons = (model: MainModelConfig, cfgScale: number): string[] =>getGenerationValidationReasons(model, createSettings(model, { cfgScale })).filter((reason) =>/^(CFG|Guidance) must be at (least|most) /.test(reason));it('rejects a persisted guidance above the ceiling the node enforces', () => {- // The reported failure: a project saved at FLUX Fill's recommended 30 that then selects a- // FLUX.2 model. `flux2_denoise.guidance` is `le=20`, so the queue rejected it at enqueue.+ // FLUX Fill guidance 30 exceeds FLUX.2's maximum of 20.const model = createModel('flux2');expect(guidanceReasons(model, 30)).toEqual(['Guidance must be at most 20 for flux2 model.']);@@ -1429,9 +1391,7 @@ describe('the guidance range the architecture declares', () => {});it('clamps a model record whose stored default the architecture would reject', () => {- // `default_settings.cfg_scale` is editable up to 200 on every main model, and a Guidance-labelled- // record with no `guidance` of its own falls back to it. Unclamped, the field's reset button and- // "reset all to model defaults" would both restore a value the gate then blocks.+ // Clamp editable record defaults before reset can restore blocked values.const model = createModel('flux2', { default_settings: { cfg_scale: 50 } } as Partial<MainModelConfig>);expect(getDefaultGenerateSettings(model).cfgScale).toBe(20);@@ -1443,9 +1403,7 @@ describe('the guidance range the architecture declares', () => {});it('clamps the carried-over guidance when a model is selected, and says so', () => {- // The reported journey end to end: a project holding FLUX Fill's 30 picks a FLUX.2 model. The- // canonical transition repairs it the way it already repairs dimensions and CLIP skip, so the- // panel is usable rather than merely blocked -- and the cleared-label toast names the field.+ // Model selection repairs guidance and reports the cleared field.const result = getGenerateModelSelectionResult({currentValues: createSettings(createModel('flux', { variant: 'dev_fill' }), { cfgScale: 30 }),model: createModel('flux2'),@@ -1468,12 +1426,9 @@ describe('the guidance range the architecture declares', () => {});it('enforces the served bound for every architecture in the table', () => {- // Swept rather than sampled: the three cases above name three bases, and a base whose bound is- // served but never consulted fails only at enqueue. Expected values come from the fixture --- // the backend's own answer -- not from the policy that is under test.+ // Derive expectations for every base from served fixtures, independently of implementation.for (const row of architectureCapabilitiesFixture) {- // Variant rows included: the bounds are served per `(base, variant)`, and a regression to a- // base-only lookup would pass a sweep that skipped them.+ // Include variant rows to catch base-only lookup regressions.const model = createModel(row.base, { variant: row.variant ?? undefined } as Partial<MainModelConfig>);if (!isSupportedGenerateModel(model)) {@@ -1498,13 +1453,7 @@ describe('the guidance range the architecture declares', () => {});describe('without the capability table', () => {- /**- * The gate has to sit where every enqueue path passes, not only where the Generate widget looks.- * `getGenerationValidationReasons` is that place: graph.ts, compileCanvasGraph.ts and- * previewGraph.ts all call it. Gating only the widget's resolver left the canvas and the topbar- * compiling against FALLBACK_GENERATION_CONFIG — a grid of 8 for bases that reject anything but- * 16, which is the enqueue failure this feature exists to prevent.- */+ /** Shared validation must gate every compile path, not only the widget. */it('blocks every model, including ones that are otherwise fine', () => {const model = createModel('flux', { variant: 'dev' });const settings = createSettings(model);@@ -1515,8 +1464,7 @@ describe('without the capability table', () => {const reasons = getGenerationValidationReasons(model, settings);expect(reasons.length).toBeGreaterThan(0);- // Not "needs a supported model": that is the answer the fallback gives, and it sends the reader- // looking at their model instead of at the backend.+ // Missing-capability errors must identify backend data, not misreport model support.expect(reasons[0]).toMatch(/capabilities/i);});@@ -1534,13 +1482,7 @@ describe('without the capability table', () => {});describe('with a table that omits this architecture', () => {- /**- * A served table is not the same as a described architecture. `isSupportedGenerateModel` answers- * from a static list of bases webv2 can build a graph for; a backend build that does not serve a- * row for one of them used to fall straight through to `FALLBACK_GENERATION_CONFIG` -- grid 8,- * 30 steps, CFG 7, euler_a -- and compile. Reference images already failed closed on a missing- * row; the rest of policy does now too.- */+ /** A loaded table may still lack the selected architecture; fail closed for missing rows. */const withoutBase = (base: string) => architectureCapabilitiesFixture.filter((row) => row.base !== base);it('blocks a supported base the backend did not describe', () => {@@ -1571,11 +1513,7 @@ describe('with a table that omits this architecture', () => {describe('getGenerationDimensions and the variant it dispatches on', () => {it('answers from the variant row when one differs, which its parameter type now admits', () => {- // `getBaseGenerationConfig` prefers a variant row and `optimalSide` comes from that row's- // default canvas, so the answer is variant-specific -- but the signature used to accept only- // `{ base, type }`, so a caller that built one of those type-checked and silently got the- // architecture's row. Every served variant declares 1024x1024 today, so the divergence has to- // be constructed to be observed at all.+ // Construct variant-specific dimensions because current fixtures otherwise hide a dropped variant.const schnell = architectureCapabilitiesFixture.find((row) => row.base === 'flux' && row.variant === 'schnell')!;setArchitectureCapabilities([diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 063c60129b..0f0ad5cf5a 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -82,8 +82,7 @@ import {normalizeGenerateSettings,} from './settings';-// Generation policy registry keyed by model base. Display identity stays in @features/models;-// graph topology stays explicit in graph.ts.+// Models owns display identity; graph.ts owns graph topology.export interface SchedulerOption {value: string;@@ -219,24 +218,13 @@ const FALLBACK_GENERATION_CONFIG: BaseGenerationConfig = {schedulerSet: 'standard',schedulerAppliesToGraph: false,guidanceLabel: 'CFG',- // Deliberately the widest range, not the narrowest: without a table `getGenerationValidationReasons`- // already blocks generation outright, so tightening the control here would only clamp a persisted- // value the user legitimately had -- FLUX Fill's 30 -- away while the capabilities are still in flight.- // 1 is "no guidance" on every sampler; nothing offers less.+ // Use permissive display bounds while generation is blocked so loading cannot clamp persisted values.guidance: { min: 1, max: null },negativePrompt: { visible: true, usage: 'never' },ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },};-/**- * What the backend says about this model's architecture.- *- * The variant matters: FLUX Schnell wants 4 steps where dev wants 28, and the endpoint answers per- * variant where they differ. Falling back keeps UI selectors crash-safe for external generators and- * for an architecture the backend does not know. It is not a licence to generate with fallback- * policy: `isArchitectureDescribed` is what blocks invocation for a supported base the served table- * omits, and `resolveGenerateWidgetValues` will not even select such a model.- */+/** Variant-first display fallbacks prevent crashes but do not establish invocation eligibility. */const getBaseGenerationConfig = (model: (Pick<GenerateModelConfig, 'base' | 'type'> & { variant?: unknown }) | undefined): BaseGenerationConfig => {@@ -247,34 +235,13 @@ const getBaseGenerationConfig = (return getArchitectureGenerationConfig(model.base, model.variant) ?? FALLBACK_GENERATION_CONFIG;};-/**- * The pixel grid generation dimensions must land on, or `null` if the backend has no row for this- * architecture.- *- * Variant-dependent: Wan A14B enforces multiples of 16 on its denoise node, TI2V-5B multiples of- * 32 in the reference-image encoder. Passing the variant is how the canvas offers a size that- * survives enqueue; omitting it falls back to the architecture's own row.- *- * `null` rather than a default so callers keep owning their own "nothing selected" behaviour --- * the canvas has a different sensible answer there than a generation graph does.- *- * External generators are the exception: the backend describes the architectures it runs, not a- * provider's API, so no row will ever arrive for them. They keep the generic grid, as they did- * before the table existed -- answering `null` would stop recall and the canvas size sync for good.- */+/** Use variant-aware grids; return null for undescribed local architectures. External providers use a generic grid. */export const getDimensionGrid = (base: string, variant?: unknown): number | null =>base === 'external'? FALLBACK_GENERATION_CONFIG.dimensions.grid: (getArchitectureFeatures(base, variant)?.dimension_grid ?? null);-/**- * Whether the served table actually describes this model's architecture.- *- * `isSupportedGenerateModel` answers from a static list of bases webv2 can build a graph for, which- * says nothing about whether the *backend* described that base in this build. Generating on a base- * the table omits would silently use `FALLBACK_GENERATION_CONFIG` -- grid 8, 30 steps, CFG 7 -- for- * an architecture whose denoise node may enforce something else entirely.- */+/** A served architecture row does not imply frontend graph support. */export const isArchitectureDescribed = (model: Pick<GenerateModelConfig, 'base' | 'type'>): boolean =>model.type === 'external_image_generator' || getArchitectureFeatures(model.base) !== undefined;@@ -285,18 +252,9 @@ const getNumber = (value: number | null | undefined, fallback: number): number =const clampGuidance = (value: number, guidance: BaseGenerationConfig['guidance']): number =>Math.min(guidance.max ?? Number.POSITIVE_INFINITY, Math.max(guidance.min, value));-/**- * The dimension rules for a model, optionally adjusted for PiD.- *- * `pidMode` is optional so the many callers that only care about the model keep- * working unchanged. In PiD native mode the requested size is the 4x decode target, so- * the grid is multiplied by 4 (keeping requested / 4 on the model's own grid) and the- * optimal side becomes PiD's 2048 rather than the model's 1024.- */+/** Native PiD uses model grid × 4 and a 2048 target optimum. */export const getGenerationDimensions = (- // `variant` participates: `getBaseGenerationConfig` prefers a variant row where the backend- // answers differently, and `optimalSide` comes from that row's default canvas. Optional because- // an architecture always has its own row; omitting it asks for the architecture's answer.+ // Use the variant-specific optimum, or the base row when no variant is supplied.model: (Pick<GenerateModelConfig, 'base' | 'type'> & { variant?: unknown }) | undefined,pidMode: PidMode = 'off') => {@@ -316,16 +274,7 @@ export const getGenerationDimensions = (};};-/**- * The value the single guidance slider takes from a model record.- *- * `MainModelDefaultSettings` carries `cfg_scale` and `guidance` as separate fields, but the UI has- * one control -- `guidanceLabel` is the whole difference between them. Which field feeds it depends- * on the label: a guidance-distilled model records `cfg_scale: 1.0` meaning "CFG off" *and* the- * guidance value it actually samples with, so preferring `cfg_scale` reads the off-switch as the- * setting. FLUX dev records `{cfg_scale: 1.0, guidance: 3.5}` and `buildFluxGraph` wires- * `guidance: settings.cfgScale`, so the old order generated at guidance 1.0 instead of 3.5.- */+/** guidanceLabel selects between guidance and cfg_scale defaults. */const getRecordGuidanceValue = (defaults: GenerateDefaultSettings | undefined,guidanceLabel: GuidanceLabel@@ -340,10 +289,7 @@ export const getGenerationDefaults = (model: GenerateModelConfig | undefined) =>return {cfgRescaleMultiplier: getNumber(defaults?.cfg_rescale_multiplier, 0),- // Clamped like `steps` below and like the canvas size in `getDefaultGenerateSettings`: the- // model record's CFG field is editable up to 200 for every main model, so a Guidance-labelled- // architecture with a ceiling can be handed a default it would reject. Unclamped, the reset- // affordance and "reset all to model defaults" would both restore a blocked value.+ // Clamp editable model defaults so reset cannot restore blocked values.cfgScale: clampGuidance(getNumber(getRecordGuidanceValue(defaults, config.guidanceLabel), config.defaults.cfgScale),config.guidance@@ -454,8 +400,7 @@ export const getGenerationUiPolicy = (sdVaeVisible: config.ui.sdVaeOverride,vaePrecisionVisible: config.ui.vaePrecision,seedVisible,- // Shown for any base with a PiD decode node, whether or not PiD is currently on, so- // it can be turned on without hunting for the control.+ // Show PiD controls on supported bases even while PiD is disabled.pidVisible: getIsPidSupportedBase(model?.base),};};@@ -467,20 +412,8 @@ export const isSupportedGenerateModel = <T extends { base: string; type: string(model.type === 'external_image_generator' && model.base === 'external');/**- * Whether a model can be picked as *the* model to generate with.- *- * Narrower than `isSupportedGenerateModel`, which answers whether Generate understands the base at- * all: Ideogram 4's unconditional branch is a `main` model of a supported base and can never run on- * its own -- it is the thing the conditional branch is guided against, and it fills a component- * slot. Offering it in the main picker would let a user assemble a complete-looking selection that- * the backend refuses at enqueue. (Wan's low-noise expert is deliberately not excluded here: it is- * a second expert of a model that still generates without it.)- *- * Every path that *offers or picks* a model uses this one: the picker, the command palette, and the- * resolver that chooses a default when a project has no usable stored model -- that last one being- * the worst place to land on an unrunnable model, since the user never chose it. Paths that merely- * *look up* a model already selected (recall, save, the presets popover) keep using- * `isSupportedGenerateModel`; narrowing those would make an already-chosen model unrenderable.+ * Exclude unconditional Ideogram branches from selection but retain lookup support. Wan's other expert can span+ * the full schedule.*/export const isGenerateModelSelectable = <T extends ModelConfig>(model: T): model is T & GenerateModelConfig =>isSupportedGenerateModel(model) && !isIdeogram4UnconditionalBranch(model);@@ -764,14 +697,7 @@ const qwen3VlEncoderSlot = (helpText: string, filter: GenerateComponentFilter):filter,});-/**- * PiD's decoder and caption encoder.- *- * Both are only *required* while PiD is on, but the slots are always offered for a- * PiD-capable base so the models can be chosen before switching PiD on. The decoder is- * filtered to the base whose checkpoints are valid for the selected model — Z-Image- * shows FLUX decoders, since it shares FLUX's VAE and ships none of its own.- */+/** Expose PiD slots before enabling it; Z-Image uses FLUX's decoder. */const pidDecoderSlot = (): ComponentSlotPolicy =>slot({key: 'pidDecoderModel',@@ -810,10 +736,7 @@ const wanT5EncoderSlot = (helpText: string): ComponentSlotPolicy =>filter: (candidate) => candidate.type === 'wan_t5_encoder',});-/**- * The second (low-noise) expert of a Wan A14B mixture-of-experts pair. Never required: the- * loader falls back to running the high-noise expert across the whole schedule.- */+/** The low-noise expert is optional; the selected expert can span the full schedule. */const wanLowNoiseSlot = (helpText: string): ComponentSlotPolicy =>slot({key: 'wanLowNoiseModel',@@ -824,10 +747,7 @@ const wanLowNoiseSlot = (helpText: string): ComponentSlotPolicy =>filter: (candidate) => candidate.type === 'main' && candidate.base === 'wan',});-/**- * Ideogram 4's second transformer. Unlike Wan's low-noise expert this is not optional where it- * applies: both branches run at every step, so a single-file main cannot generate without it.- */+/** Standalone Ideogram models require the second branch. */const ideogram4UnconditionalSlot = (helpText: string): ComponentSlotPolicy =>slot({key: 'ideogram4UnconditionalModel',@@ -1093,8 +1013,7 @@ const getBaseComponentSectionPolicy = (},]);case 'krea-2':- // A non-diffusers Krea-2 (single-file checkpoint / GGUF) carries only the transformer, so- // both submodels must be selected. Diffusers models bundle them, hence optional there.+ // Bundled Krea models supply components; standalone models need a separate encoder and VAE.return createPolicy(model.format !== 'diffusers', [{...vaeSlot(@@ -1111,8 +1030,7 @@ const getBaseComponentSectionPolicy = (},]);case 'ernie-image':- // A single-file ERNIE-Image transformer carries only itself, so its encoder and VAE are- // selected here; a diffusers pipeline directory bundles both and the loader reads them out.+ // Bundled ERNIE models supply components; standalone models need explicit components.return createPolicy(model.format !== 'diffusers', [{...mistralEncoderSlot(@@ -1132,8 +1050,7 @@ const getBaseComponentSectionPolicy = (},]);case 'ideogram-4':- // Comfy-Org's single files hold one transformer branch each, so a checkpoint main needs the- // other branch, the Qwen3-VL 8B encoder and the VAE. A diffusers pipeline bundles all three.+ // Standalone Ideogram needs the other branch, encoder, and VAE.return createPolicy(model.format !== 'diffusers', [{...ideogram4UnconditionalSlot(@@ -1163,8 +1080,7 @@ const getBaseComponentSectionPolicy = (},]);case 'wan':- // A GGUF Wan main carries only the transformer; the VAE and UMT5-XXL encoder must come- // from standalone models or a Diffusers component source.+ // GGUF Wan needs external component sources.return createPolicy(model.format !== 'diffusers', [componentSourceSlot((candidate) => isDiffusersMainForBase('wan')(candidate),@@ -1203,14 +1119,7 @@ const getBaseComponentSectionPolicy = (}};-/**- * The component slots for a model, plus PiD's two slots on any PiD-capable base.- *- * Appended in a wrapper rather than written into each base's case: PiD supports six- * bases, one of which (SDXL) has no component case at all, and each existing case keeps- * its own bespoke validation untouched this way. Only the PiD slots are validated here- * — the inner policy validates its own.- */+/** Add and validate PiD slots; each base policy retains ownership of its other component validation. */export const getComponentSectionPolicy = (model: GenerateModelConfig | undefined,settings: GenerateSettings@@ -1309,11 +1218,7 @@ const isFluxKontextModel = (model: GenerateModelConfig | undefined): model is Mamodel.name.toLowerCase().includes('kontext'));-/**- * Whether the model can consume reference images at all. Kept strict so the UI- * only offers reference images where `getGenerationValidationReasons` would- * accept them (e.g. Qwen Image requires the `edit` variant).- */+/** Picker and validation must agree on compatibility, including required variants. */export const isReferenceImageSupported = (model: GenerateModelConfig | undefined): boolean => {if (!model) {return false;@@ -1329,9 +1234,7 @@ export const isReferenceImageSupported = (model: GenerateModelConfig | undefinedreturn false;}- // Qwen-Image accepts reference images only as the `edit` variant -- the one feature the backend- // qualifies by variant, which is why it says so on the architecture row rather than inventing a- // variant row for it.+ // The backend declares which reference-image features require a specific variant.return (features.reference_images_require_variant === null || model.variant === features.reference_images_require_variant);@@ -1431,10 +1334,8 @@ export const isReferenceImageCompatibleWithModel = (};/**- * Reference images carried over to `model`: dropped entirely when the model- * does not support reference images, and re-targeted to a default config for- * the new model (keeping the image and enabled state) when incompatible.- * Returns the input array untouched when nothing changes.+ * Drop unsupported references; retarget incompatible ones while preserving image/enabled state. No changes return+ * the same array.*/export const getCompatibleReferenceImages = (referenceImages: GenerateReferenceImage[],@@ -1513,11 +1414,7 @@ const getSettingsWithCompatibleModelSelections = (}}- // Beside CLIP skip, and for the same reason: the value carried over from the previous model can- // be outside what this one's denoise node accepts, and every model-selection entry point passes- // here. The cleared-label toast names it, so the move is reported rather than silent.- // `getGuidanceBoundReason` still guards the paths that do not transition through here -- a- // project reopened on a model whose bounds changed, metadata recall, settings written by API.+ // Clamp and report during selection; validation remains the backstop for other write paths.const clampedGuidance = clampGuidance(nextSettings.cfgScale, getBaseGenerationConfig(model).guidance);if (clampedGuidance !== nextSettings.cfgScale) {@@ -1566,11 +1463,7 @@ const getSettingsWithCompatibleModelSelections = (return { settings: nextSettings, clearedLabels };};-/**- * Canonical transition for every Generate model-selection entry point.- * Normalizes persisted values, reconciles incompatible selections, and applies- * automatic component-source policy before callers persist the result.- */+/** Normalize, reconcile, and apply component policy before persisting model selection. */export const getGenerateModelSelectionResult = ({currentValues,model,@@ -1641,8 +1534,7 @@ export const getGenerationModelAvailabilityReasons = (const getDimensionValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {const reasons: string[] = [];- // The PiD-adjusted grid: in native mode the requested size is the 4x target, so it must- // be a multiple of grid * 4 for requested / 4 to land on the model's own grid.+ // Native target dimensions must be divisible by model grid × 4.const dimensions = getGenerationDimensions(model, settings.pidMode);if (!Number.isFinite(settings.width) || settings.width < dimensions.min || settings.width > dimensions.max) {@@ -1660,13 +1552,7 @@ const getDimensionValidationReasons = (model: GenerateModelConfig, settings: Genreturn reasons;};-/**- * PiD guards beyond "are the models selected", which the component slots already cover.- *- * PiD is only wired for text-to-image here, so a mode left on for an unsupported base is- * reported rather than silently ignored — otherwise the user would get an ordinary decode- * and wonder why the image is not 4x.- */+/** Reject unsupported PiD instead of silently using ordinary decode. */const getPidValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {if (settings.pidMode === 'off') {return [];@@ -1688,8 +1574,8 @@ const getPidValidationReasons = (model: GenerateModelConfig, settings: GenerateSconst getReferenceImageValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {const reasons: string[] = [];const enabled = settings.referenceImages.filter((referenceImage) => referenceImage.isEnabled);- // The limit the reference-image panel enforces, so validation cannot pass what the panel refuses.- // A model without reference images is reported per image below rather than as "at most 0".+ // Use the shared reference limit, but report unsupported images individually rather than a misleading maximum of+ // zero.const maxReferenceImages = getMaxReferenceImages(model);if (isReferenceImageSupported(model) && enabled.length > maxReferenceImages) {@@ -1730,18 +1616,7 @@ const getReferenceImageValidationReasons = (model: GenerateModelConfig, settingsreturn reasons;};-/**- * How this guidance value breaks the bound the denoise node behind it enforces, or `null`.- *- * Model selection already clamps, so this is the backstop for everything that does not transition- * through it: a project reopened after its model's bounds changed, metadata recall (which carries- * any `cfg_scale >= 1`), or settings written straight to the record. Without it the graph compiles- * and the queue rejects it with a node-level error the user cannot act on -- `flux2_denoise.guidance`- * is `le=20`, and FLUX Fill's recommended 30 is a value a project genuinely holds.- *- * Returned as one message rather than a list: the two bounds cannot both be broken, and the Generate- * widget shows it on the field itself, where a list has nowhere to go.- */+/** Validate guidance for writes bypassing model selection; return null or one error message. */export const getGuidanceBoundReason = (model: Pick<GenerateModelConfig, 'base' | 'name' | 'type'> & { variant?: unknown },cfgScale: number@@ -1759,15 +1634,11 @@ export const getGuidanceBoundReason = (return null;};-/**- * Rules that belong to one model family and have no home in the component-slot policies:- * the slot machinery validates model selections, not scalar parameters or LoRA pairings.- */+/** Scalar/LoRA family rules are separate from component-slot validation. */const getModelFamilyValidationReasons = (model: MainModelConfig, settings: GenerateSettings): string[] => {const reasons: string[] = [];- // The rebalance weights are free text forwarded straight to the backend's _parse_weights().- // Catching a malformed string here beats failing mid-generation on a queued item.+ // Parse raw rebalance strings before forwarding them to the backend.if (model.base === 'krea-2' &&settings.krea2RebalanceEnabled &&@@ -1776,9 +1647,7 @@ const getModelFamilyValidationReasons = (model: MainModelConfig, settings: Generreasons.push(`Krea-2 rebalance weights must be ${KREA2_REBALANCE_WEIGHT_COUNT} comma-separated numbers.`);}- // Each Ideogram 4 override is forwarded verbatim whenever it is set, and normalization only- // checks that a persisted value is finite -- a value stored before these controls were bounded- // survives a reload and fails `ideogram4_denoise` at enqueue.+ // Finite persisted Ideogram overrides still need range validation.if (model.base === 'ideogram-4') {for (const [label, value, min, max] of [['steps', settings.ideogram4Steps, IDEOGRAM4_STEPS_MIN, IDEOGRAM4_STEPS_MAX],@@ -1792,8 +1661,7 @@ const getModelFamilyValidationReasons = (model: MainModelConfig, settings: Gener}}- // A14B and 5B Wan LoRAs are not interchangeable — the layer patcher fails on a tensor-shape- // mismatch. getActiveCompatibleLoras would silently drop a mismatched one, so say so instead.+ // Report Wan LoRA family mismatches rather than silently drop selected LoRAs.if (model.base === 'wan') {for (const lora of settings.loras) {if (lora.isEnabled && !isWanLoraTargetingMain(lora.model.variant, model.variant)) {@@ -1806,16 +1674,9 @@ const getModelFamilyValidationReasons = (model: MainModelConfig, settings: Gener};export const getGenerationValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {- // Before anything else, and before the unsupported-model reason: without the capability table- // every answer below is the fallback's, not the architecture's -- a grid of 8 for a base that- // rejects anything but 16, and "no supported model" for a model that is perfectly supported.- // This is the one function all three compile paths share (graph.ts, compileCanvasGraph.ts,- // previewGraph.ts), so gating here is what makes the canvas and the topbar fail closed too,- // rather than only the Generate widget's own resolver.+ // All compilers share this validator; check capabilities before model-specific policy.if (!hasArchitectureCapabilities()) {- // Deliberately not state-aware: `core` cannot reach the store that knows loading from- // failed. Saying "not yet" would be a promise this cannot keep -- after a failed fetch- // nothing re-kicks it except the Generate panel's retry, so name that instead.+ // Keep core independent of the load-state store; failures direct callers to retry.return ['Model capabilities are not available. Generation is blocked until they load; if this persists, retry from the Generate panel.',];@@ -1825,9 +1686,7 @@ export const getGenerationValidationReasons = (model: GenerateModelConfig, settireturn ['Generate needs a supported model before it can be invoked.'];}- // A loaded table is not the same as a described architecture: a base inside `SUPPORTED_GENERATE_BASES`- // that this backend build does not serve a row for would otherwise compile against the fallback- // config. Reference images already fail closed this way; so does everything else now.+ // Reject supported bases missing from the loaded table rather than compile fallback policy.if (!isArchitectureDescribed(model)) {return [`The backend does not describe the ${model.base} architecture, so it cannot be generated with.`];}diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.tsindex b0feea80ef..0c29d2a104 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.ts@@ -15,10 +15,6 @@ import {isControlKindSupportedForBase,} from './addControlLayers';-// ----------------------------------------------------------------------------// Test helpers-// ----------------------------------------------------------------------------interface TestGraph {id: string;nodes: Record<string, { id: string; type: string; [key: string]: unknown }>;@@ -66,10 +62,6 @@ const run = (options: AddControlLayersOptions) => {const edgesTo = (graph: TestGraph, nodeId: string, field: string) =>graph.edges.filter((e) => e.destination.node_id === nodeId && e.destination.field === field);-// ----------------------------------------------------------------------------// 1. isControlKindSupportedForBase full matrix-// ----------------------------------------------------------------------------seedArchitectureCapabilities();describe('isControlKindSupportedForBase', () => {@@ -96,20 +88,12 @@ describe('isControlKindSupportedForBase', () => {});});-// ----------------------------------------------------------------------------// CONTROL_DENOISE_NODE_ID sanity-// ----------------------------------------------------------------------------describe('CONTROL_DENOISE_NODE_ID', () => {it('is the deterministic denoise node id', () => {expect(CONTROL_DENOISE_NODE_ID).toBe('denoise_latents');});});-// ----------------------------------------------------------------------------// 2. controlnet on sd-1-// ----------------------------------------------------------------------------describe('addControlLayers — controlnet on sd-1', () => {it('creates a controlnet node with exact fields and wires the collector to denoise.control', () => {const m = model('sd-1');@@ -175,10 +159,6 @@ describe('addControlLayers — controlnet on sd-1', () => {});});-// ----------------------------------------------------------------------------// 3. controlnet on flux-// ----------------------------------------------------------------------------describe('addControlLayers — controlnet on flux', () => {it('uses flux_controlnet type and omits control_mode entirely', () => {const m = model('flux');@@ -208,10 +188,6 @@ describe('addControlLayers — controlnet on flux', () => {});});-// ----------------------------------------------------------------------------// 4. t2i_adapter on sdxl-// ----------------------------------------------------------------------------describe('addControlLayers — t2i_adapter on sdxl', () => {it('creates a t2i_adapter node with exact fields and wires collector to denoise.t2i_adapter', () => {const m = model('sdxl', 't2i_adapter');@@ -269,10 +245,6 @@ describe('addControlLayers — t2i_adapter on sdxl', () => {});});-// ----------------------------------------------------------------------------// 5. control_lora on flux-// ----------------------------------------------------------------------------describe('addControlLayers — control_lora on flux', () => {it('creates a flux_control_lora_loader wired directly to denoise.control_lora with no collector', () => {const m = model('flux', 'control_lora');@@ -306,10 +278,6 @@ describe('addControlLayers — control_lora on flux', () => {});});-// ----------------------------------------------------------------------------// 6. control_lora limits: second skipped; dev_fill skips-// ----------------------------------------------------------------------------describe('addControlLayers — control_lora limits', () => {it('rejects a second control_lora with the shared reason code', () => {expect(() =>@@ -384,10 +352,6 @@ describe('addControlLayers — Z-Image control', () => {});});-// ----------------------------------------------------------------------------// 7. Two controlnet layers → distinct nodes, one shared collector-// ----------------------------------------------------------------------------describe('addControlLayers — per-layer separation', () => {it('creates two distinct adapter nodes feeding one shared collector', () => {const graph = run({@@ -416,10 +380,6 @@ describe('addControlLayers — per-layer separation', () => {});});-// ----------------------------------------------------------------------------// 8. Unsupported kind for base is silently skipped-// ----------------------------------------------------------------------------describe('addControlLayers — unsupported kind rejected', () => {it('rejects a t2i_adapter layer on flux', () => {expect(() =>@@ -451,10 +411,6 @@ describe('addControlLayers — unsupported kind rejected', () => {});});-// ----------------------------------------------------------------------------// 9. throws when denoise node missing-// ----------------------------------------------------------------------------describe('addControlLayers — missing denoise node', () => {it('throws when the base graph has no denoise node', () => {const graph: TestGraph = { id: 'g', nodes: {}, edges: [] };@@ -464,10 +420,6 @@ describe('addControlLayers — missing denoise node', () => {});});-// ----------------------------------------------------------------------------// 10. getControlLayerRejectionReason branches-// ----------------------------------------------------------------------------describe('getControlLayerRejectionReason', () => {const validParams = {layerName: 'My Layer',diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.tsindex 00491a6e75..14a4bb2247 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.ts@@ -1,24 +1,4 @@-/**- * Pure control-layer graph grafting (legacy parity).- *- * {@link addControlLayers} wires each enabled, valid control layer's uploaded- * composite into a base-appropriate control adapter node, collects same-kind- * nodes, and connects the collector (or, for Control LoRA, the node directly) to- * the canvas graph's denoise node. It mutates the graph in place using the same- * `addNode`/`addEdge` helpers the base builders use — no fetch, no engine, no- * React. Node types + args mirror legacy- * `features/nodes/util/graph/generation/addControlAdapters.ts`.- *- * Per-base + per-kind support (legacy `getControlLayerWarnings` + the graph- * builders): controlnet on sd-1 / sdxl (`controlnet`) and flux (`flux_controlnet`);- * t2i_adapter on sd-1 / sdxl; control_lora on flux only (single layer, and never- * with a FLUX Fill main model); z_image_control on Z-Image only (single layer).- * Everything else is rejected upstream.- *- * The executor composites each control layer SEPARATELY (never blended) and- * passes its own uploaded image name in — so each adapter node references a- * distinct control image, exactly like legacy.- */+/** Graft separately composited controls into the graph in place. */import type { SupportedGenerateBase } from '@features/generation/core/baseGenerationPolicies';import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';@@ -58,10 +38,7 @@ export interface ControlLayerGraphInput {controlMode: 'balanced' | 'more_prompt' | 'more_control' | 'unbalanced' | null;}-/**- * True when `base` supports control adapters of `kind` (legacy support matrix).- * `controlMode` and adapter-model base compatibility are validated separately.- */+/** Kind support is separate from control-mode/model compatibility. */export { isControlKindSupportedForBase } from './controlValidation';/** Options for {@link addControlLayers}. */@@ -77,15 +54,7 @@ export interface AddControlLayersOptions {/** Resolves the backend node type for a controlnet layer on `base`. */const controlNetNodeType = (base: string): string => (base === 'flux' ? 'flux_controlnet' : 'controlnet');-/**- * Grafts control layers onto a built canvas base graph. Revalidates support,- * model compatibility, the Control LoRA limit, and FLUX Fill restrictions so a- * caller cannot bypass the same shared validation used by invoke and UI. Wires:- * - controlnet → `control_net_collector` (collect) → `denoise.control`;- * - t2i_adapter → `t2i_adapter_collector` (collect) → `denoise.t2i_adapter`;- * - control_lora → `denoise.control_lora` directly (FLUX, first layer only).- * - z_image_control → `denoise.control` directly (Z-Image, first layer only).- */+/** Validate defensively through the shared policy before graph wiring. */export const addControlLayers = (graph: BackendGraphContract, options: AddControlLayersOptions): void => {const { base, layers, modelVariant } = options;const denoise = graph.nodes[CONTROL_DENOISE_NODE_ID];@@ -181,15 +150,7 @@ export const addControlLayers = (graph: BackendGraphContract, options: AddContro}};-/**- * Returns the legacy-parity rejection reason for a control layer, or `null` when- * it is valid for generation. Mirrors `getControlLayerWarnings`:- * - no drawn/composited content → "no control";- * - no adapter model selected → "no model";- * - main base unsupported (sd-2 / sd-3 / anima / …) → "unsupported model";- * - adapter model base ≠ main base → "incompatible base";- * - FLUX Fill + Control LoRA → "incompatible".- */+/** Return null when valid, otherwise the rejection reason. */export const getControlLayerRejectionReason = (params: {layerName: string;hasContent: boolean;diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.tsindex edcfd0e54c..b19ff7454c 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts@@ -192,10 +192,7 @@ describe('isRegionalGuidanceSupportedForBase', () => {});describe('the support matrix and the served capabilities', () => {- // isRegionalGuidanceSupportedForBase asserts `base is RegionalGuidanceBase` from the backend's- // answer, and getRegionalGuidanceSupport then indexes the matrix on that assertion. A base the- // backend declares supported but the matrix has no row for would hand callers an undefined typed- // as present -- so every served `true` must have a row.+ // Every backend-supported regional base needs a local graph row.it('give every base the backend declares supported a row in the matrix', () => {const declaredSupported = architectureCapabilitiesFixture.filter((row) => row.features.supports_regional_guidance)@@ -203,8 +200,7 @@ describe('the support matrix and the served capabilities', () => {expect(declaredSupported.length).toBeGreaterThan(0);for (const base of declaredSupported) {- // `toBeTruthy`, not `not.toBeNull`: a base with no row reaches this as `undefined`, which- // passes a null check and made this guard inert for exactly the drift it exists to catch.+ // toBeTruthy also rejects undefined; not.toBeNull would miss it.expect(getRegionalGuidanceSupport(base), base).toBeTruthy();}});@@ -250,8 +246,7 @@ describe('addRegionalGuidance — Z-Image / Anima', () => {expect(hasEdge(g, 'model_loader', 'qwen3_encoder', 'rg_pos_cond_r1', 'qwen3_encoder')).toBe(true);expect(hasEdge(g, 'rg_mask_to_tensor_r1', 'mask', 'rg_pos_cond_r1', 'mask')).toBe(true);expect(hasEdge(g, 'rg_pos_cond_r1', 'conditioning', 'pos_cond_collect', 'item')).toBe(true);- // The backend discards masks on negative conditioning for these bases, so nothing reaches the- // negative collector even though the graph has one.+ // These backends discard negative masks even when a negative collector exists.expect(g.nodes.rg_neg_cond_r1).toBeUndefined();expect(g.nodes.rg_pos_cond_inverted_r1).toBeUndefined();expect(g.edges.some((e) => e.destination.node_id === 'neg_cond_collect')).toBe(false);diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.tsindex ba2ead1170..b8891ab0af 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts@@ -29,11 +29,7 @@ export interface RegionalGuidanceSupport {referenceImages: RegionalReferenceImageKind | null;}-/**- * The graph half of the support matrix: what a region's reference images become, and what to call- * the base. Whether a region's negative is masked is the backend's answer (`regional_negative`), not- * this table's -- see {@link getRegionalGuidanceSupport}.- */+/** Graph code owns node mapping; the backend owns regional-negative support. */const REGIONAL_GUIDANCE_SUPPORT: Record<RegionalGuidanceBase,Pick<RegionalGuidanceSupport, 'label' | 'referenceImages'>@@ -48,30 +44,12 @@ const REGIONAL_GUIDANCE_SUPPORT: Record<anima: { label: 'Anima', referenceImages: null },};-/**- * True when `base` supports regional guidance at all.- *- * The narrowing to `RegionalGuidanceBase` stays: everything below this point dispatches on the- * literal to pick node types and field names, and that is graph knowledge the backend has no say- * in. Only the *answer* comes from the capability table now.- */+/** Frontend graph keys are narrower than backend capability answers. */export const isRegionalGuidanceSupportedForBase = (base: string): base is RegionalGuidanceBase =>- // Both halves, or the predicate is unsound: it narrows to the key set of the matrix below, while- // the backend's answer is what decides. A base the backend newly declares supported but that has- // no row here would satisfy the old check, and `REGIONAL_GUIDANCE_SUPPORT[base]` would then hand- // back `undefined` typed as a support object. Requiring the row keeps the type honest and makes- // the drift a missing feature rather than a crash.+ // Require both backend support and a local graph row before narrowing the type.(getArchitectureFeatures(base)?.supports_regional_guidance ?? false) && base in REGIONAL_GUIDANCE_SUPPORT;-/**- * What a base's regions honour, or `null` for a base with no regional path.- *- * Negatives come from the capability table: the SD family's `compel` path masks both polarities,- * while the FLUX / FLUX.2 / Krea-2 / Z-Image / Anima denoisers mask positive conditioning only --- * Z-Image and Anima accept a negative list but discard its masks, so a "regional" negative there- * would act globally. Auto-negative re-encodes the positive prompt as a masked negative, so it needs- * the same path. The rest of the row is graph knowledge the backend has no say in.- */+/** Auto-negative requires negative-mask support. */export const getRegionalGuidanceSupport = (base: string | null): RegionalGuidanceSupport | null => {if (base === null || !isRegionalGuidanceSupportedForBase(base)) {return null;@@ -167,11 +145,7 @@ const conditioningNodeType = (base: RegionalGuidanceBase, modelVariant?: stringconst promptFields = (base: RegionalGuidanceBase): readonly string[] =>base === 'sdxl' ? ['prompt', 'style'] : ['prompt'];-/**- * The encoder-input fields to COPY from the global conditioning node onto a- * regional one, so the region shares the same CLIP / T5 encoders (legacy copies- * the CLIP/T5 edges verbatim). `mask` is wired separately, so it's excluded here.- */+/** Copy global encoder fields; wire masks separately. */const copyEncoderFields = (base: RegionalGuidanceBase, modelVariant?: string | null): readonly string[] => {switch (base) {case 'sdxl':@@ -191,11 +165,6 @@ const copyEncoderFields = (base: RegionalGuidanceBase, modelVariant?: string | n}};-/**- * Copies every edge feeding `sourceNodeId`'s `fields` onto `target` (same source,- * same field). Used to share the global conditioning node's CLIP/T5 encoder- * inputs with a per-region conditioning node.- */const copyEncoderEdges = (graph: BackendGraphContract,sourceNodeId: string,@@ -252,19 +221,7 @@ const addRegionalConditioning = (return node;};-/**- * Grafts regional guidance onto a built canvas base graph. Assumes every input is- * already validated for `base` (supported base, non-empty region, resolved- * reference-image models) — use {@link getRegionalGuidanceRejectionReason} to- * filter first. Wires, per enabled region:- * - `alpha_mask_to_tensor` from the uploaded region mask;- * - positive prompt → regional conditioning → `pos_cond_collect`;- * - negative prompt → regional conditioning → `neg_cond_collect`;- * - autoNegative → `invert_tensor_mask` + positive prompt re-encoded →- * `neg_cond_collect` (push the positive prompt away outside the region);- * - reference images → mask-scoped `ip_adapter` (SD) / `flux_redux` (FLUX);- * each gated by the base's {@link RegionalGuidanceSupport}.- */+/** Inputs must be prevalidated and gated by regional support. */export const addRegionalGuidance = (graph: BackendGraphContract, options: AddRegionalGuidanceOptions): void => {const { base, modelVariant, regions, transformRegionalPositiveConditioning } = options;const denoise = graph.nodes[DENOISE_NODE_ID];@@ -320,8 +277,7 @@ export const addRegionalGuidance = (graph: BackendGraphContract, options: AddRegaddEdge(graph, negCond, 'conditioning', negCondCollect, 'item');}- // autoNegative: re-encode the POSITIVE prompt over the INVERTED mask into the- // negative collector — pushes the region's prompt away everywhere outside it.+ // Auto-negative encodes positive text over the inverted region mask.if (region.autoNegative && region.positivePrompt && support.autoNegative && negCondCollect) {const invert = addNode(graph, { id: `rg_invert_mask_${region.id}`, type: 'invert_tensor_mask' });addEdge(graph, maskToTensor, 'mask', invert, 'mask');@@ -381,19 +337,8 @@ export const addRegionalGuidance = (graph: BackendGraphContract, options: AddReg};/**- * Returns the rejection reason for a regional-guidance region, or `null` when it- * can contribute to generation:- * - a base with no regional path (sd-3 / cogview / …) → "unsupported model";- * - no drawn mask content → "no region";- * - nothing the base's {@link RegionalGuidanceSupport} honours → "empty".- *- * A negative prompt or reference images the base does not honour are simply not- * submitted (the layer keeps them for other models); the region still- * contributes whatever the base does honour. Auto-negative never decides on its- * own: it only re-encodes an existing positive prompt.- *- * `referenceImageCount` counts references the caller has already resolved to a- * usable image + model, matching how control layers work.+ * Omit unsupported content without erasing stored values. Count resolved references; auto-negative requires+ * positive text.*/export const getRegionalGuidanceRejectionReason = (params: {layerName: string;diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.test.tsindex 8b1201f3bc..9602f44b41 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.test.ts@@ -45,10 +45,7 @@ describe('detectCanvasMode', () => {});it('stays txt2img for a new canvas seeded with only an empty inpaint mask', () => {- // A brand-new canvas carries one empty inpaint mask (see- // `createNewCanvasState`). An empty mask contributes no raster content- // (`contentBounds` stays null) and has no content (`hasActiveInpaintMask`- // is false), so mode detection must NOT flip to inpaint.+ // Default empty masks are not active inpaint content.expect(detectCanvasMode(input({ contentBounds: null, hasActiveInpaintMask: false }))).toBe('txt2img');});});diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.tsindex d9ca60fb12..07ed4dc0e6 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.ts@@ -1,18 +1,6 @@/**- * Pure canvas generation-mode detection.- *- * Given only plain geometry/coverage facts the engine + composite executor- * already computed, {@link detectCanvasMode} reproduces the legacy canvas- * behavior of picking txt2img / img2img / inpaint / outpaint. It touches no- * pixels and imports nothing from the engine — every input is precomputed and- * passed in, so the whole decision table is exhaustively node-testable.- *- * Rules (legacy parity):- * - No enabled raster content intersects the bbox → `txt2img`.- * - Content opaquely covers the whole bbox, no active inpaint mask → `img2img`.- * - Content opaquely covers the whole bbox, active inpaint mask → `inpaint`.- * - The bbox extends past content, or has transparent holes inside it (i.e.- * content intersects but does not fully cover) → `outpaint`.+ * Mode detection uses precomputed geometry/coverage only. No intersection means txt2img; full opaque coverage+ * means img2img or inpaint when a mask is active; partial coverage or holes means outpaint.*/import type { CanvasGenerationMode, Rect } from './types';@@ -21,31 +9,15 @@ import type { CanvasGenerationMode, Rect } from './types';export interface CanvasModeInput {/** The generation bounding box, in document space. */bbox: Rect;- /**- * Union of enabled raster-layer content bounds in document space, or `null`- * when no enabled raster content exists.- */+ /** Document-space union; null means no enabled content. */contentBounds: Rect | null;- /**- * Whether enabled raster content opaquely covers the entire bbox (no- * transparent holes) — the alpha scan of the composited bbox surface.- */+ /** Opaque coverage is alpha-scanned and contains no holes. */bboxFullyCovered: boolean;- /**- * Whether an enabled inpaint-mask layer with content exists. Always `false`- * in Phase 4.2 (the contract type exists but no mask is produced yet).- */+ /** True when an active mask contains inpaint content. */hasActiveInpaintMask: boolean;}-/**- * True when two rects share interior area. Edge-touching or a shared corner is- * NOT an intersection (strict `<`), matching the engine's `rect.intersect`- * semantics, so a 1px edge overlap counts but a flush edge does not.- *- * Exported so the invoke orchestrator can run a bounds-only pre-pass: content- * that doesn't overlap the bbox means txt2img, which needs no composite upload.- */+/** Require interior overlap. The txt2img prepass avoids uploading unused content. */export const rectsIntersect = (a: Rect, b: Rect): boolean => {if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0) {return false;@@ -72,7 +44,5 @@ export const detectCanvasMode = (input: CanvasModeInput): CanvasGenerationMode =return hasActiveInpaintMask ? 'inpaint' : 'img2img';}- // Content intersects but leaves the bbox partly transparent (extends past- // content, or has holes): outpaint.return 'outpaint';};diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.test.tsindex 3ee7d4da4a..b29d7bf78b 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.test.ts@@ -85,8 +85,7 @@ describe('resolveCanvasProcessingSize', () => {});it('snaps on the grid the model variant declares, not the one its base declares', () => {- // Wan TI2V-5B takes multiples of 32 where A14B takes 16. 720 is on the one grid and not the- // other, so a caller that drops the variant shows a size the graph then re-snaps.+ // 720 distinguishes 32-pixel grids from 16-pixel grids.const bbox = { height: 720, width: 1280 };const a14b = { base: 'wan', type: 'main' } as GenerateModelConfig;const ti2v = { base: 'wan', type: 'main', variant: 'ti2v_5b' } as GenerateModelConfig;diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.tsindex ed42aa9e37..a3ea9431b4 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.ts@@ -1,9 +1,6 @@/**- * The size a canvas generation is denoised at, before the result is resized- * back to the exact bbox footprint. Legacy's "Scale Before Processing":- * `none` keeps the bbox (snapped to the model grid), `auto` grows a small bbox- * along its aspect ratio until it reaches the model's optimal pixel area, and- * `manual` uses the user's own size. Pure data; no React, no transport.+ * None snaps the bbox to the model grid; auto grows undersized content toward optimal area at its aspect ratio;+ * manual uses the selected size. Restore final output to the exact bbox.*/import type { GenerateModelConfig, PidMode } from '@features/generation/core/types';@@ -49,10 +46,7 @@ const isSdxlTrainingSize = (base: string, { height, width }: CanvasSize): booleabase === 'sdxl' &&SDXL_TRAINING_DIMENSIONS.some(([a, b]) => (a === width && b === height) || (a === height && b === width));-/**- * Grows `size` in grid steps along its aspect ratio until it covers the- * optimal area; a bbox already at or above that area is left alone.- */+/** Auto grows only below optimal area, preserving aspect ratio on the model grid. */const growToOptimalArea = (size: CanvasSize, optimal: number, grid: number): CanvasSize => {const width = snap(size.width, grid);const height = snap(size.height, grid);@@ -80,8 +74,7 @@ const growToOptimalArea = (size: CanvasSize, optimal: number, grid: number): Can};export const resolveCanvasProcessingSize = (- // The variant participates: Wan TI2V-5B snaps to 32 where A14B snaps to 16, and a caller that- // dropped it would show one processing size while the graph compiles another.+ // Keep the variant: Wan 5B and A14B use different grids.model: Pick<GenerateModelConfig, 'base' | 'type'> & { variant?: unknown },pidMode: PidMode,bbox: CanvasSize,diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.tsindex bd770a11aa..ac74117db1 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts@@ -336,8 +336,6 @@ describe('compileCanvasGraph', () => {expect(getEdge(backendGraph, encode!.id, 'vae')).toBeDefined();expect(getEdge(backendGraph, 'denoise_latents', 'latents')?.source.node_id).toBe(encode?.id);- // denoising_start follows the base's strength curve (linear, or the- // exponent-0.2 optimized curve for sd-3 / flux / flux2).expect(backendGraph.nodes.denoise_latents?.type).toBe(denoiseType);expect(backendGraph.nodes.denoise_latents?.denoising_start).toBeCloseTo(expectedDenoisingStart(0.6, optimizedDenoising),@@ -418,9 +416,7 @@ describe('compileCanvasGraph', () => {});it('rejects PiD with an actionable message rather than an internal VAE error', () => {- // Canvas compilation resolves the VAE from a `canvas_output.vae` edge and renames- // that node when compositing back; a PiD chain has neither, so without the guard- // this surfaces as "could not resolve a VAE source in the base graph".+ // PiD lacks the VAE seam expected by canvas compilation, so reject it explicitly.for (const mode of ['txt2img', 'img2img'] as const) {expect(() =>compile(sdxlModel, mode, {@@ -856,12 +852,7 @@ describe('compileCanvasGraph — outpaint per base', () => {});});-// Review fix (Task 38, finding 2): `addControlLayers` has its own isolated unit-// coverage (addControlLayers.test.ts), but nothing previously drove control-// layers through the REAL `compileCanvasGraph` entry point — so a wiring-// regression at the seam between the two (e.g. the wrong denoise node id, or a-// base graph that no longer exposes `denoise_latents`) could pass every-// existing test here while breaking a real canvas invoke.+// Exercise control grafting through the real compiler entry point.describe('compileCanvasGraph — control layers (integration)', () => {const controlNetLayer: ControlLayerGraphInput = {beginEndStepPct: [0.1, 0.85],@@ -888,15 +879,11 @@ describe('compileCanvasGraph — control layers (integration)', () => {expect(controlNode?.control_mode).toBe('more_control');expect(controlNode?.image).toEqual({ image_name: 'control-composite.png' });- // The control node feeds the collector, whose own output is what- // `denoise_latents.control` actually reads.expect(backendGraph.nodes.control_net_collector?.type).toBe('collect');expect(getEdge(backendGraph, 'control_net_collector', 'item')?.source.node_id).toBe('control_net_control-layer-1');expect(getEdge(backendGraph, 'denoise_latents', 'control')?.source.node_id).toBe('control_net_collector');- // The base img2img graph is untouched by the control graft: prompts, seed,- // the encode → denoise plumbing, and the composite-back output are all- // still present and wired exactly as they would be with no control layers.+ // Canvas grafting must preserve unaffected base-graph wiring.expect(backendGraph.nodes.positive_prompt).toBeDefined();expect(backendGraph.nodes.negative_prompt).toBeDefined();expect(backendGraph.nodes.seed).toBeDefined();diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.tsindex d2790d0841..8155895bd1 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts@@ -1,28 +1,6 @@/**- * Pure canvas generation-graph compiler.- *- * {@link compileCanvasGraph} builds the backend graph a canvas invoke submits by- * grafting image-to-image plumbing onto the existing per-base txt2img builders- * (`../graph.ts`). It is deliberately pure: no fetch, no engine imports, no- * React. The executor (Task 16) has already composited + uploaded the bbox- * source image and passes its name in; this module only shapes nodes/edges.- *- * ## Grafting strategy- *- * 1. Build the base txt2img graph via `GRAPH_BUILDERS[model.base]` with the- * canvas destination (`outputIsIntermediate = true`) and a settings copy whose- * width/height are snapped to the model's processing grid. The bbox remains- * the exact final canvas footprint; off-grid inputs are resized before- * processing and outputs are resized back before staging or saving.- * 2. For `img2img`, add a base-appropriate image-to-latents encode node fed by- * the composite image + the graph's VAE source, wire its latents into- * `denoise_latents.latents`, and set `denoising_start = 1 - strength`.- * 3. Update `core_metadata` (`generation_mode` → the `img2img` variant, plus- * `strength`).- *- * Every base in `GRAPH_BUILDERS` has a backend image-to-latents node, so all ten- * families support img2img (see `CANVAS_I2L_NODE_TYPES`). External image- * generators have no latent img2img path and are rejected for every canvas mode.+ * Pure canvas compiler over uploaded inputs. Resize through the processing grid and restore the bbox; reject+ * external models and unsupported encode modes.*/import type { SupportedGenerateBase } from '@features/generation/core/baseGenerationPolicies';@@ -46,12 +24,7 @@ import { addControlLayers } from './addControlLayers';import { addRegionalGuidance, isRegionalGuidanceSupportedForBase } from './addRegionalGuidance';import { type CanvasSize, resolveCanvasProcessingSize } from './canvasProcessingSize';-/**- * The backend image-to-latents (encode) node type per supported base. sd-1 /- * sd-2 / sdxl share the SD `i2l` node. Evidence: `invokeai/app/invocations/`- * and the legacy per-base builders under- * `features/nodes/util/graph/generation/`.- */+/** Map bases to encode nodes; SD families share i2l. */const CANVAS_I2L_NODE_TYPES: Partial<Record<SupportedGenerateBase, string>> = {'sd-1': 'i2l','sd-2': 'i2l',@@ -66,24 +39,10 @@ const CANVAS_I2L_NODE_TYPES: Partial<Record<SupportedGenerateBase, string>> = {'krea-2': 'qwen_image_i2l',anima: 'anima_i2l',wan: 'wan_i2l',- // Ideogram 4 is deliberately absent: it ships no image-to-latents node, so canvas- // img2img/inpaint is impossible. requireI2lType turns the missing entry into an- // actionable "Canvas generation is not supported" error.+ // Ideogram lacks an encode node; reject these modes with an actionable error.};-/**- * The `denoising_start` for a canvas img2img graft, mirroring legacy- * `getDenoisingStartAndEnd` (web `graphBuilderUtils.ts`):- * - sd-3 / flux / flux2 rescale strength with an exponent of 0.2 so the slider's- * full (0, 1] range is usable — without it nearly all perceptible change is- * crammed into strength > 0.9 (e.g. strength 0.75 → start 0.056, not 0.25).- * - A FLUX Fill model (`flux` / `dev_fill`) always denoises fully (start = 0).- * - Every other base stays linear (`start = 1 - strength`).- *- * Legacy gates the exponent on an `optimizedDenoisingEnabled` user setting that- * defaults to `true`; webv2 exposes no such toggle, so the optimized curve is- * always applied for the eligible bases.- */+/** SD-3, FLUX, and FLUX.2 use start = 1 - strength^0.2. FLUX Fill always starts at 0; other bases use 1 - strength. */const canvasDenoisingStart = (model: GenerateModelConfig, strength: number): number => {if (model.base === 'flux' && model.variant === 'dev_fill') {return 0;@@ -108,10 +67,7 @@ const getCanvasValidationReasons = (input: CompileCanvasGraphInput): string[] =>return reasons;}- // PiD is wired for text-to-image only. Canvas compilation finds the VAE by looking for- // a `canvas_output.vae` edge and renames that node when compositing back; a PiD chain- // has neither, so without this guard the user would get an internal- // "could not resolve a VAE source" error instead of an actionable one.+ // Reject canvas PiD because its graph lacks the expected VAE/decode seam.if (input.settings.pidMode !== 'off' && getIsPidSupportedBase(model.base)) {reasons.push('PiD decoding is not supported on the canvas yet. Turn PiD off to generate here.');}@@ -170,11 +126,7 @@ const requireVaeSource = (graph: BackendGraphContract): { node: BackendInvocatioreturn source;};-/**- * Renames a node in place: moves its map key, updates its `id`, and rewires every- * edge referencing the old id. Used to demote the base `canvas_output` decode to- * an intermediate `canvas_l2i` so the composite-back node can claim `canvas_output`.- */+/** Rename every matching node ID and edge reference. */const renameNode = (graph: BackendGraphContract, oldId: string, newId: string): BackendInvocationContract => {const node = graph.nodes[oldId];if (!node) {@@ -358,12 +310,7 @@ const addInfillNode = (}};-/**- * Shared inpaint/outpaint tail: gradient denoise mask → denoise, expand-with-fade,- * and the final `canvas_output`. The output either retains transparency outside- * the generated region or composites back over the source image, depending on- * `outputOnlyMaskedRegions`.- */+/** outputOnlyMaskedRegions selects transparent output versus compositing with the original. */const graftMaskTail = (graph: BackendGraphContract,args: {@@ -386,8 +333,7 @@ const graftMaskTail = (const { compositing, denoise, destination, i2lType, initialImageName, settings, vaeSource } = args;const needsResize = !sizesMatch(args.bbox, args.processingSize);- // Demote the base decode to an intermediate `canvas_l2i`; the final mask or- // composite node claims `canvas_output`.+ // The final output owns canvas_output; the base decoder becomes intermediate.const l2i = renameNode(graph, 'canvas_output', 'canvas_l2i');l2i.is_intermediate = true;@@ -463,10 +409,7 @@ const graftMaskTail = (addEdge(graph, generatedImageSource, 'image', output, compositing.outputOnlyMaskedRegions ? 'image' : 'layer_upper');addEdge(graph, outputMaskSource, 'image', output, 'mask');- // The base builder wired core_metadata → the decode's `metadata`; `renameNode`- // followed it onto the (now intermediate) canvas_l2i. Re-point it to the final- // output so the saved image carries generation metadata. Both possible output- // nodes are WithMetadata; board fields, when present, ride the same node.+ // Move metadata to the final saved output after renaming.const metadataEdge = graph.edges.find((edge) => edge.destination.node_id === 'canvas_l2i' && edge.destination.field === 'metadata');@@ -601,8 +544,8 @@ const graftOutpaint = (infill.image = { image_name: initialImageName };}- // Derive a mask from the initial image alpha (transparent → generate), combined- // with the inpaint mask when one exists.+ // Derive the mask from image alpha (transparent means generate), combining an explicit inpaint mask when+ // present.const alphaToMask = addNode(graph, {id: 'image_alpha_to_mask',image: { image_name: initialImageName },@@ -665,11 +608,7 @@ const graftOutpaint = (setMetadataMode(graph, 'outpaint', strength);};-/**- * Compiles a canvas invoke into a backend graph. Throws a validation `Error`- * (message = first offending reason) for unsupported models/modes or bad- * geometry, mirroring `compileGenerateGraph`.- */+/** Throw the first validation reason. */export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanvasGraph => {const { bbox, compositeImageName, destination, mode, model, projectSettings, strength } = input;const processingSize = resolveCanvasProcessingSize(model, input.settings.pidMode, bbox, input.scaling);@@ -687,8 +626,7 @@ export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanvthrow new Error(`${model.name} does not support canvas generation.`);}- // Mirror compileGenerateGraph: only a `canvas` destination stages an- // intermediate output; `gallery` produces a durable image.+ // Canvas outputs are intermediate; gallery outputs are durable.const outputIsIntermediate = destination === 'canvas';const runtimeProjectSettings = {...projectSettings,@@ -706,9 +644,7 @@ export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanvgraftOutpaint(backendGraph, input, compositing, processingSize);}- // Control layers apply in every mode (legacy allows control with all). The- // executor already composited + uploaded each layer separately and resolved- // its model; the caller passes only valid layers.+ // Every mode accepts already-resolved, separately uploaded control inputs.if (input.controlLayers && input.controlLayers.length > 0) {addControlLayers(backendGraph, {base: model.base as SupportedGenerateBase,@@ -717,9 +653,7 @@ export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanv});}- // Regional guidance applies in every mode too. The executor already composited- // + uploaded each region's mask and resolved its reference-image models; it- // passes only regions valid for the base's regional-guidance support matrix.+ // Regional masks and models must already be validated.if (input.regionalGuidance && input.regionalGuidance.length > 0 && isRegionalGuidanceSupportedForBase(model.base)) {addRegionalGuidance(backendGraph, {base: model.base,diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.tsindex a7988a0345..f8bfeae1a0 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.ts@@ -16,13 +16,7 @@ export type ControlValidationReason =| 'z_image_control_limit'| 'flux_fill_control_lora';-/**- * Which control adapters an architecture accepts, as the backend declares it.- *- * Only the base-to-kinds mapping comes from there. The limit rules further down -- one control- * LoRA, one Z-Image control, and FLUX Fill rejecting control LoRAs entirely -- have no column in- * the capability table and stay here.- */+/** The backend owns kind support; count and Fill constraints are frontend policy. */export const isControlKindSupportedForBase = (base: string, kind: ControlAdapterKind): boolean =>getArchitectureFeatures(base)?.control_kinds.includes(kind) ?? false;@@ -52,8 +46,7 @@ export const getControlValidationReason = (params: {if (!adapterModel) {return 'missing_model';}- // Without the table every kind reads as unsupported. Report that the answer is not in yet rather- // than calling a valid adapter unsupported.+ // Unavailable capability data is distinct from unsupported adapters.if (!hasArchitectureCapabilities()) {return 'capabilities_unavailable';}diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/types.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/types.tsindex abd8bea034..dff9009d49 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/types.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/types.ts@@ -48,11 +48,7 @@ export type CanvasGenerationMode = 'txt2img' | 'img2img' | 'inpaint' | 'outpaint/** The generation modes the pure canvas graph compiler supports (full matrix). */export type CanvasCompileMode = CanvasGenerationMode;-/**- * Everything {@link import('./compileCanvasGraph').compileCanvasGraph} needs to- * build a canvas generation graph. Pure data: the executor (Task 16) supplies- * the already-uploaded `compositeImageName`; no pixels or engine state leak in.- */+/** Pure compiler inputs reference already-uploaded media. */export interface CompileCanvasGraphInput {/** Prompts / steps / model-adjacent settings, reused verbatim from Generate. */settings: GenerateSettings;@@ -62,24 +58,18 @@ export interface CompileCanvasGraphInput {randDevice?: string;/** The resolved canvas mode (from `canvasMode.ts`). */mode: CanvasCompileMode;- /**- * The resolved result destination. `canvas` marks the output node intermediate- * (staging); `gallery` makes it a durable image, matching `compileGenerateGraph`.- */+ /** Destination selects intermediate canvas output or durable gallery output. */destination: ResultDestination;/** The generation bounding box, in document space. Its size overrides settings dims. */bbox: Rect;/** The uploaded bbox composite (executor result). Required for image-referencing modes. */compositeImageName: string | null;/**- * The uploaded grayscale denoise-limit mask (white = keep, dark = inpaint).- * Required for `inpaint` / `outpaint`.+ * Uploaded grayscale mask: white keeps, dark inpaints. Required for inpaint; outpaint can derive its mask from+ * image alpha.*/maskImageName?: string | null;- /**- * The uploaded grayscale noise mask, present only when at least one enabled- * mask layer defines a `noiseLevel`. Adds an `img_noise` node before encode.- */+ /** An optional noise-level mask adds image noise before encoding. */noiseMaskImageName?: string | null;/** Denoising strength in (0, 1]. Consulted for `img2img` / `inpaint` / `outpaint`. */strength: number;@@ -87,27 +77,13 @@ export interface CompileCanvasGraphInput {compositing: CanvasCompositingSettings;/** Processing-size policy; absent means the bbox snapped to the model grid. */scaling?: CanvasScalingSettings;- /**- * Valid, already-resolved control layers (each with its own uploaded composite- * image name). The executor filters + composites these; the compiler only- * grafts adapter nodes. Present in every mode (control works with all).- */+ /** Prevalidated per-layer composites, each uploaded separately. */controlLayers?: readonly ControlLayerGraphInput[];- /**- * Valid, already-resolved regional-guidance regions (each with its own uploaded- * mask image name + resolved reference-image models). The executor filters +- * composites these; the compiler only grafts the mask-tensor + conditioning- * nodes into the base graph's `pos_cond_collect` / `neg_cond_collect`. Applied- * only for supported bases (sd-1 / sdxl / flux).- */+ /** Resolved inputs for each supported region. */regionalGuidance?: readonly RegionalGuidanceInput[];}-/**- * Mirrors {@link import('../types').CompiledGenerateGraph} with the resolved- * canvas mode attached so downstream (Task 18) can label / branch without- * re-deriving it.- */+/** Carry the resolved mode so consumers do not recompute it. */export interface CompiledCanvasGraph {backendGraph: BackendGraphContract;graph: GraphContract;diff --git a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.tsindex f1846b68c2..5c6ad975ae 100644--- a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts@@ -144,9 +144,7 @@ describe('Generate component compatibility', () => {});it('keeps each Mistral-family encoder out of the other family slot', () => {- // Both install as `mistral_encoder` and both load in the other's slot without complaint --- // Ministral 3B is a different architecture, so the wrong one conditions off-distribution with no- // error anywhere. The variant is the only thing separating them, on both sides.+ // Filter variants even when they share a model type.const ministral = candidate({ type: 'mistral_encoder', variant: 'ministral3_3b' });const mistralSmall3 = candidate({ type: 'mistral_encoder', variant: 'cow_mistral3_small' });const mistral24b = candidate({ type: 'mistral_encoder', variant: 'mistral3_24b' });@@ -205,9 +203,7 @@ describe('Generate component compatibility', () => {});it('offers each Wan variant only the VAE width its decode accepts', () => {- // `wan_model_loader` refuses a 48-channel VAE for A14B and a 16-channel one for TI2V-5B. The- // served base row used to accept both widths for every variant, so both pickers offered a VAE- // that failed at enqueue.+ // Wan A14B and 5B require compatible VAE channel widths.const wanMain = (variant: string) =>({ base: 'wan', key: `wan-${variant}`, name: `Wan ${variant}`, type: 'main', variant }) as GenerateModelConfig;const wanVae = (latentChannels: number) =>@@ -227,8 +223,7 @@ describe('Generate component compatibility', () => {});describe('the VAE filters and the backend declarations', () => {- // With the row's variant: a variant row states what *that* variant accepts, which for Wan TI2V-5B- // is a different VAE from the one its base row names.+ // Exercise each variant row with its own variant.const mainOf = (base: string, variant: string | null = null) =>({base,@@ -249,13 +244,7 @@ describe('the VAE filters and the backend declarations', () => {const ALL_BASES = [...new Set(architectureCapabilitiesFixture.map((row) => row.base))];- /**- * webv2 kept its own copy of which VAE bases a model accepts, and the backend declares the same- * fact in `VaeFacet`. Two copies drift: this PR widened qwen-image to accept the anima- * registration and the picker kept refusing it, so a VAE the backend would have loaded could not- * be selected. Reading the served table is what makes the next widening show up here instead of- * in a user's model list.- */+ /** Check parity with served VAE policy instead of duplicating frontend rules. */it('accepts every VAE base the backend declares for that architecture', () => {const declared = architectureCapabilitiesFixture.filter((row) => row.vae);expect(declared.length).toBeGreaterThan(0);@@ -274,11 +263,7 @@ describe('the VAE filters and the backend declarations', () => {}});- /**- * The half a one-directional check cannot see. This PR's headline VAE bug was a *narrowing* —- * Klein silently losing `flux` — and a filter that returned `true` for everything would satisfy- * the loop above while offering VAEs that decode to noise.- */+ /** Negative parity cases must reject an always-true filter. */it('rejects every VAE base the backend does not declare for that architecture', () => {for (const row of architectureCapabilitiesFixture) {const accepted = row.vae?.accepted ?? [{ base: row.base, latent_channels: null }];@@ -294,8 +279,7 @@ describe('the VAE filters and the backend declarations', () => {).toBe(false);}- // A width constraint is a real constraint: wan ships a 16- and a 48-channel VAE under one- // base, and only one of them belongs to the family an architecture decodes with.+ // Same-base VAEs are still constrained by channel width.for (const entry of accepted) {if (entry.latent_channels === null) {continue;diff --git a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.tsindex 84142f6701..b0c1762263 100644--- a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts@@ -77,12 +77,7 @@ export const isAnimaQwen3Encoder: GenerateComponentFilter = (model) =>export const isNonAnimaQwen3Encoder: GenerateComponentFilter = (model) =>model.type === 'qwen3_encoder' && model.variant !== 'qwen3_06b';-/**- * ERNIE-Image's encoder is recorded as a `mistral_encoder` too, but it is a different architecture- * (Ministral 3B, hidden 3072) from the Mistral Small 3 encoders FLUX.2 was trained against. Offering- * either one to the other family produces a shape error deep in denoise, so the variant separates- * them on both sides.- */+/** Ministral and Mistral encoders require distinct variants. */const MINISTRAL_3B_VARIANT = 'ministral3_3b';export const isFlux2MistralEncoder: GenerateComponentFilter = (model) =>@@ -91,21 +86,14 @@ export const isFlux2MistralEncoder: GenerateComponentFilter = (model) =>export const isErnieImageMistralEncoder: GenerateComponentFilter = (model) =>model.type === 'mistral_encoder' && model.variant === MINISTRAL_3B_VARIANT;-/**- * The two Qwen3-VL encoders install under one model type and are not interchangeable: Krea-2 needs- * the 4B (hidden 2560), Ideogram 4 the 8B, whose 13 tapped layers make a 53248-wide feature vector.- * Offering the wrong one produces a shape mismatch inside the first denoising step.- */+/** Krea's 4B encoder is incompatible with Ideogram's 8B encoder. */export const isKrea2Qwen3VlEncoder: GenerateComponentFilter = (model) =>model.type === 'qwen3_vl_encoder' && model.variant === 'qwen3_vl_4b';export const isIdeogram4Qwen3VlEncoder: GenerateComponentFilter = (model) =>model.type === 'qwen3_vl_encoder' && model.variant === 'qwen3_vl_8b';-/**- * Ideogram 4's unconditional branch. Only a single file can be one: a diffusers pipeline holds both- * branches, and the conditional file is the one selected as the main model.- */+/** Exclude only single-file unconditional branches; Diffusers bundles both branches. */export const isIdeogram4UnconditionalBranch: GenerateComponentFilter = (model) =>model.type === 'main' &&model.base === 'ideogram-4' &&@@ -173,19 +161,7 @@ export const getCompatibleDiffusersComponentSource = <T extends GenerateComponen): T | undefined =>source && isCompatibleDiffusersComponentSourceForModel(selectedModel, source) ? source : undefined;-/**- * Whether an architecture's decode accepts this VAE, as the backend declares it.- *- * The single reader of `vae.accepted` from the served capability table — the same `VaeFacet` the- * loaders and `accepts_vae()` read in `architectures/defs/<base>.py`. Which VAE families a base can- * decode used to be hand-written here as a `switch` over literal base lists, and that copy drifted:- * it offered Anima a FLUX VAE, which decodes a WAN21_16 latent in FLUX's basis and returns a- * magenta smear rather than an error (6.10 dB PSNR, measured).- *- * Fail closed, like `resolveGenerateWidgetValues` and `getGenerationValidationReasons`: with no- * table, or no row for this base, nothing is offered. Choosing a VAE the graph then rejects is- * worse than an empty picker that fills in as soon as the table lands.- */+/** Backend rows own VAE compatibility; missing rows fail closed. */const acceptsVae = (base: string, model: GenerateComponentCandidate, variant?: unknown): boolean => {if (model.type !== 'vae') {return false;@@ -216,12 +192,7 @@ export const isVaeAcceptedByBase =(model) =>acceptsVae(base, model, variant);-/**- * The one VAE rule for a Generate model. The component picker and its validation filter with- * `isVaeAcceptedByBase(model.base, model.variant)` and the graph builder with this, so a VAE the user can select is- * always one the graph sends -- the served row decides for both, including cross-base families such- * as a Qwen-Image VAE installed under `anima`.- */+/** Picker, validator, and compiler share the served VAE rule. */export const isVaeCompatibleWithGenerateModel = (model: GenerateModelConfig, vae: VaeModelConfig): boolean => {if (model.type === 'external_image_generator') {return false;diff --git a/invokeai/frontend/webv2/src/features/generation/core/conditioningRebalance.test.ts b/invokeai/frontend/webv2/src/features/generation/core/conditioningRebalance.test.tsindex 81774613d6..8ba57267ce 100644--- a/invokeai/frontend/webv2/src/features/generation/core/conditioningRebalance.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/conditioningRebalance.test.ts@@ -48,8 +48,7 @@ describe('parseRebalanceWeights', () => {});it('rejects hex, which Number() accepts but Python float() does not', () => {- // The string is forwarded verbatim to the node, so accepting it here would only- // move the failure to mid-generation.+ // Reject malformed values before forwarding them verbatim to the backend.expect(parseRebalanceWeights('0x10,1,1,1,1,1,1,1,1,1,1,1')).toBeNull();expect(parseRebalanceWeights('0b11,1,1,1,1,1,1,1,1,1,1,1')).toBeNull();expect(parseRebalanceWeights('0o17,1,1,1,1,1,1,1,1,1,1,1')).toBeNull();diff --git a/invokeai/frontend/webv2/src/features/generation/core/conditioningRebalance.ts b/invokeai/frontend/webv2/src/features/generation/core/conditioningRebalance.tsindex f2a86ddf25..2427ad583c 100644--- a/invokeai/frontend/webv2/src/features/generation/core/conditioningRebalance.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/conditioningRebalance.ts@@ -1,15 +1,4 @@-/**- * Krea-2 conditioning rebalance: the per-tap weight vector, its presets, and the- * geometry the bar editor drags against.- *- * Krea-2 stacks twelve Qwen3-VL hidden-state layers per token into- * `prompt_embeds (B, seq, 12, hidden)`, and the backend node applies- * `embeds * gains * multiplier` — a flat elementwise gain, not a frequency- * decomposition. Weighting the shallow taps favours the prompt's literal wording;- * weighting the deep taps favours its meaning and composition.- *- * Pure module: no React, no Chakra, no transport (see `src/architecture/dependencyPolicy.ts`).- */+/** Twelve elementwise gains, ordered from shallow to deep encoder taps. *//*** The encoder layers tapped into the conditioning, shallow to deep.@@ -24,10 +13,7 @@ export const DEFAULT_KREA2_REBALANCE_WEIGHTS = '1.0,1.0,1.0,1.0,1.0,1.0,1.0,2.5,export const DEFAULT_KREA2_REBALANCE_MULTIPLIER = 4;export const REBALANCE_WEIGHT_MIN = 0;-/**- * The drag track's nominal ceiling. Values above it are still legal — the track- * rescales to fit them (`getRebalanceBarScale`) rather than clipping the bars.- */+/** The nominal track ceiling does not cap legal weights; the display rescales automatically. */export const REBALANCE_WEIGHT_TRACK_MAX = 8;/** Weights read as "no change" here; the editor draws a rule at this level. */export const REBALANCE_NEUTRAL_WEIGHT = 1;@@ -36,11 +22,7 @@ export const REBALANCE_NEUTRAL_WEIGHT = 1;const WEIGHT_QUANTUM = 10;export const REBALANCE_WEIGHT_STEP = 1 / WEIGHT_QUANTUM;-/**- * Accepts exactly what Python's `float()` accepts. `Number()` additionally parses- * hex/binary/octal literals, so `0x10` would pass a `Number.isFinite` check here and- * then fail inside the node's `_parse_weights()` mid-generation.- */+/** Accept signed decimal values with optional fraction/exponent; reject JS-only hex, binary, and octal syntax. */const DECIMAL_NUMBER_RE = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;/** Parses the stored comma string, or null when the backend would reject it. */@@ -82,22 +64,14 @@ const formatWeight = (weight: number): string => {export const serializeRebalanceWeights = (weights: readonly number[]): string => weights.map(formatWeight).join(',');-/**- * Krea-2 rebalance weights are free text forwarded straight to the backend's- * `_parse_weights()`. Validating here keeps an unparseable string from reaching a node- * that would fail mid-generation.- */+/** Validate backend-compatible numeric syntax before forwarding raw weights. */export const isValidKrea2RebalanceWeights = (value: string): boolean => parseRebalanceWeights(value) !== null;const snapWeight = (weight: number): number => Math.round(weight * WEIGHT_QUANTUM) / WEIGHT_QUANTUM;const clampWeight = (weight: number, scale: number): number => Math.min(scale, Math.max(REBALANCE_WEIGHT_MIN, weight));-/**- * The track's full-scale value: the nominal ceiling, or the tallest weight when a preset- * or typed value overshoots it. Rescaling beats clipping — a clipped bar reads as a- * different value than it holds.- */+/** Scale to the larger of the nominal ceiling and actual maximum. */export const getRebalanceBarScale = (weights: readonly number[]): number =>weights.reduce((scale, weight) => Math.max(scale, weight), REBALANCE_WEIGHT_TRACK_MAX);@@ -118,10 +92,7 @@ export const adjustRebalanceWeight = (weight: number, delta: number, scale: numbconst SPARKLINE_INSET = 1;-/**- * An SVG path for the collapsed row's preview of the current curve. Rendered into a- * `preserveAspectRatio="none"` viewBox, so the inset only keeps the stroke off the edges.- */+/** Inset the path so preserveAspectRatio=none does not clip its stroke. */export const getRebalanceSparklinePath = (weights: readonly number[], width: number, height: number): string => {if (weights.length === 0) {return '';@@ -156,12 +127,7 @@ export const NEUTRAL_KREA2_REBALANCE_WEIGHTS = Array.from({ length: KREA2_REBALA',');-/**- * Built-ins are described by their shape, not by a tuning claim: the node's own- * defaults, a neutral pass, the default curve scaled toward or away from- * neutral, and curves that lean on the early or late taps. Nothing here- * measures a look — users save their own curves for that.- */+/** Preset labels describe curve shapes, not measured tuning outcomes. */export const BUILTIN_REBALANCE_PRESETS: readonly RebalancePreset[] = [{id: REBALANCE_PRESET_DEFAULT_ID,@@ -222,10 +188,7 @@ export const isRebalancePreset = (value: unknown): value is RebalancePreset => {);};-/**- * Coerces the persisted array back into shape. Entries that no longer parse — or that- * collide with a built-in id — are dropped rather than surfaced as broken pickers.- */+/** Discard invalid persisted curves and IDs colliding with built-ins. */export const normalizeRebalancePresets = (value: unknown): RebalancePreset[] => {if (!Array.isArray(value)) {return [];diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.tsindex 87fc1834ab..b4c654247f 100644--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts@@ -28,8 +28,7 @@ describe('hasDynamicPromptSyntax', () => {expect(hasDynamicPromptSyntax('a __colou?__ __animals/[dc]ogs__ ball')).toBe(true);});- // A comment is only stripped by going through the expander, and upstream has- // no escape for `#`, so any prompt containing one has to take the trip.+ // # requires backend expansion even without braces.it('detects a comment', () => {expect(hasDynamicPromptSyntax('a red ball # for now')).toBe(true);expect(hasDynamicPromptSyntax('a red ball \\# for now')).toBe(true);@@ -38,8 +37,7 @@ describe('hasDynamicPromptSyntax', () => {it('ignores prompts with neither a variant nor a wildcard', () => {expect(hasDynamicPromptSyntax('a red ball')).toBe(false);expect(hasDynamicPromptSyntax('unclosed { brace')).toBe(false);- // Not a reference: a name may not start or end with an underscore, so this- // cannot round-trip through the `__` delimiters.+ // Disallow leading/trailing underscores in wildcard names so delimiters round-trip.expect(hasDynamicPromptSyntax('snake__case word')).toBe(false);});});@@ -176,8 +174,7 @@ describe('matchesKnownWildcard', () => {});it('anchors both ends, so the two cannot share characters', () => {- // `ab*ba` needs four characters; matching `ab` and `ba` onto the same `b`- // is what a naive prefix/suffix check gets wrong.+ // Prefix and suffix cannot overlap: ab*ba requires at least four characters.expect(matchesKnownWildcard('ab*ba', new Set(['aba']))).toBe(false);expect(matchesKnownWildcard('ab*ba', new Set(['abba']))).toBe(true);});@@ -189,9 +186,7 @@ describe('matchesKnownWildcard', () => {expect(matchesKnownWildcard('a**c', new Set(['abc']))).toBe(true);});- // Regression: translating the path to `^a.*.*.*…$` backtracks exponentially,- // and the path is whatever the user has typed so far. Twelve stars against one- // name used to take about a minute.+ // Avoid regex backtracking on user-entered repeated stars.it('does not backtrack on a path full of stars', () => {const names = new Set(Array.from({ length: 50 }, (_, index) => `colours/warm-autumn-palette-${index}`));const started = performance.now();@@ -202,9 +197,7 @@ describe('matchesKnownWildcard', () => {});describe('normalizeWildcardValues', () => {- // What the editor stores has to be what an export writes and a re-import- // reads back. Blank lines used to survive into the catalog and then vanish on- // the next round trip, so the two disagreed.+ // Normalize ingress so storage, export, and reimport agree.it('drops blank lines and trims the rest', () => {expect(normalizeWildcardValues(['red', '', ' green ', ' ', 'blue'])).toEqual(['red', 'green', 'blue']);});@@ -213,9 +206,7 @@ describe('normalizeWildcardValues', () => {expect(normalizeWildcardValues(['red', 'green'])).toEqual(['red', 'green']);});- // Verified against dynamicprompts itself: a value of `poster #1` expands to- // `poster `, and `#ff0000 glow` expands to nothing. There is no escape for it,- // so a stored `#` is text that silently never reaches the model.+ // # starts an unescapable comment, including inside a value such as red#blue.it('drops a comment, and the value that is nothing but one', () => {expect(normalizeWildcardValues(['poster #1', 'red # a colour', '#ff0000 glow', 'blue'])).toEqual(['poster',diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.tsindex 146cfa7fe2..7404853b37 100644--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts@@ -267,16 +267,7 @@ export const getWildcardNameError = (return null;};-/**- * Whether a prompt is worth sending to the expansion route at all. A prompt with- * no dynamic syntax in it is its own single expansion, so the round trip is- * skipped entirely.- *- * `#` counts, because upstream treats it as a comment to end of line and strips- * it — with no way to escape it. Leaving it out would make whether a `#` reaches- * the model depend on whether the prompt happened to contain a `{…}` elsewhere,- * which is a worse surprise than the round trip.- */+/** # is expansion syntax because the backend strips comments without an escape, even without other dynamic syntax. */export const hasDynamicPromptSyntax = (prompt: string): boolean =>/\{[\s\S]*\}/.test(prompt) || prompt.includes('#') || scanWildcardReferences(prompt).length > 0;diff --git a/invokeai/frontend/webv2/src/features/generation/core/generationConfig.ts b/invokeai/frontend/webv2/src/features/generation/core/generationConfig.tsindex 8b98546d08..599b4bc56c 100644--- a/invokeai/frontend/webv2/src/features/generation/core/generationConfig.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/generationConfig.ts@@ -1,10 +1,4 @@-/**- * The shape generation policy speaks about an architecture.- *- * Split out of `baseGenerationPolicies.ts` so that `architectureCapabilities.ts` -- which maps the- * backend's wire rows onto this shape -- and the policy accessors that consume it can both refer to- * it without importing each other.- */+/** Shared types avoid a mapper/policy circular dependency. */export type SchedulerSetId = 'standard' | 'flow' | 'flow-no-lcm' | 'anima';@@ -15,11 +9,7 @@ export type GuidanceLabel = 'CFG' | 'Guidance';export interface BaseGenerationConfig {dimensions: {grid: number;- /**- * The side of the model's optimal square canvas. Consumers square it back into an area- * (`importGalleryImages` passes `optimal ** 2` to `calculateNewSize`), so it is derived from- * the declared area rather than from width alone.- */+ /** optimal is the square root of pixel area, not source width. */optimalSide: number;};defaults: {@@ -31,11 +21,7 @@ export interface BaseGenerationConfig {schedulerSet: SchedulerSetId;schedulerAppliesToGraph: boolean;guidanceLabel: GuidanceLabel;- /**- * What the denoise node behind the single guidance control actually validates, not what the- * slider's track shows: `min` is a floor the node enforces (`0` where it enforces none, since no- * sampler here reads a negative guidance), `max` a ceiling, or `null` where the node has none.- */+ /** Denoise validation bounds differ from the slider track; max=null means unbounded. */guidance: {min: number;max: number | null;diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex c5a952b77c..789d05819c 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@ -330,9 +330,7 @@ describe('compileGenerateGraph', () => {});it('keeps an SD3 VAE override its picker would hide out of the graph', () => {- // The slot is optional, so validation never looks at it and the picker only hides a stale- // selection. The builder used to send whatever was stored -- a FLUX VAE left over from a model- // switch reached `sd3_model_loader`.+ // Builders must filter stale optional overrides that required-slot validation never sees.const graph = compile(sd3Model, { vae: fluxVae });expect(graph.nodes.model_loader?.vae_model).toBeUndefined();@@ -342,9 +340,7 @@ describe('compileGenerateGraph', () => {});it('sends the Qwen Image loader every VAE its picker offers', () => {- // Regression: the picker read the served row, which lists Qwen-Image VAEs installed under- // `anima`, while the builder filtered to base `qwen-image`. A checkpoint model then failed to- // compile, and a Diffusers model silently dropped the override the user had selected.+ // Picker and compiler must agree for a Qwen VAE registered under anima.const animaRegisteredVae: VaeModelConfig = {base: 'anima',key: 'anima-qwen-vae',@@ -856,8 +852,7 @@ describe('Krea-2, Ideogram 4 and Wan graphs', () => {});it('sends an anima-registered Qwen-Image VAE to the Krea-2 loader', () => {- // Regression: the builder filtered VAEs to base `qwen-image`, so a Qwen-Image VAE- // installed under the `anima` base was dropped and the loader got no VAE at all.+ // Graph compilation accepts compatible cross-registration VAEs.const animaRegisteredVae: VaeModelConfig = {base: 'anima',key: 'anima-qwen-vae',@@ -873,8 +868,7 @@ describe('Krea-2, Ideogram 4 and Wan graphs', () => {});it('refuses to compile a non-diffusers Krea-2 with a missing submodel', () => {- // Validation runs ahead of the builder, so the user-facing reason surfaces rather than the- // builder's internal guard. Both layers exist; this pins which one the user actually sees.+ // User validation errors must precede internal builder errors.expect(() => compile(krea2Checkpoint, { qwen3VLEncoderModel: qwen3VlEncoder })).toThrow('Generate needs a VAE for non-Diffusers Krea-2 models.');@@ -949,8 +943,7 @@ describe('Krea-2, Ideogram 4 and Wan graphs', () => {});it('wires both Ideogram 4 branches and its standalone components for a single-file transformer', () => {- // Every step runs both branches, so a single-file main that reached denoise without the second- // one would fail at the node -- the loader emits it and the builder must connect it.+ // Wire both Ideogram branches for every denoise step.const graph = compile(ideogram4Conditional, {ideogram4UnconditionalModel: ideogram4Unconditional,qwen3VLEncoderModel: qwen3Vl8bEncoder,@@ -974,17 +967,14 @@ describe('Krea-2, Ideogram 4 and Wan graphs', () => {});it('drops a component selection that does not suit the Ideogram 4 model about to run', () => {- // Component settings survive a main-model switch and an optional slot is never validated, so a- // Krea-2 4B encoder left over from an earlier session used to be forwarded as an override and- // then rejected by the loader node — breaking a bundled pipeline that needs no components.+ // Filter stale optional encoder overrides for bundled models.const graph = compile(ideogram4Model, { qwen3VLEncoderModel: qwen3VlEncoder });expect(graph.nodes.model_loader?.qwen3_vl_encoder_model).toBeUndefined();});it('leaves the Ideogram 4 unconditional input unconnected for a diffusers pipeline', () => {- // That pipeline's Transformer submodel is both branches; connecting a second one is an error- // on the node, not a no-op.+ // The bundled transformer already contains both branches; another branch is invalid.const graph = compile(ideogram4Model);expect(getEdge(graph, 'denoise_latents', 'unconditional_transformer')).toBeUndefined();@@ -1013,8 +1003,7 @@ describe('Krea-2, Ideogram 4 and Wan graphs', () => {});it('passes the optional Wan low-noise expert through and leaves it unset otherwise', () => {- // Unset optional model fields stay `undefined` here, matching every other builder; they- // drop out when the graph is serialized rather than reaching the backend as null.+ // Omit undefined optional fields instead of serializing null.expect(compile(wanDiffusers).nodes.model_loader?.transformer_low_noise_model).toBeUndefined();expect(compile(wanDiffusers, { wanLowNoiseModel: wanLowNoise }).nodes.model_loader).toMatchObject({transformer_low_noise_model: wanLowNoise,@@ -1056,9 +1045,7 @@ describe('ERNIE-Image graphs', () => {};it('encodes the negative prompt only while CFG is on', () => {- // `negative_conditioning` is required when guidance_scale != 1 and unused otherwise, and the- // coverage suite only ever compiles at the base default of 4 — so the CFG-off branch is- // compiled nowhere else. ERNIE-Image-Turbo ships `guidance=1.0`, which is how a user gets there.+ // Exercise explicit CFG-off wiring: negative conditioning is required only above 1.const withCfg = compile(ernieModel, { cfgScale: 4 });expect(withCfg.nodes.neg_cond?.type).toBe('ernie_image_text_encoder');@@ -1075,8 +1062,7 @@ describe('ERNIE-Image graphs', () => {});it('wires a single-file transformer to the encoder and VAE it was given', () => {- // A single-file ERNIE transformer carries only itself. Nothing downstream would notice the two- // component fields being swapped -- both are model identifiers -- so the wiring is pinned here.+ // Assert encoder/VAE edges because their identifier types permit accidental swapping.const singleFile: MainModelConfig = { ...ernieModel, format: 'checkpoint', key: 'ernie-image-single' };const graph = compile(singleFile, { mistralEncoderModel: ministralEncoder, vae: flux2Vae });@@ -1088,10 +1074,7 @@ describe('ERNIE-Image graphs', () => {});it('keeps a FLUX.2 Mistral encoder its picker would hide out of the graph', () => {- // For a bundled pipeline the slot is optional, so validation never looks at it and only the- // picker hides the stale selection. Mistral Small 3 and Ministral 3B both install as- // `mistral_encoder` and each loads in the other's slot without error, so forwarding one here- // would degrade conditioning silently rather than fail.+ // Filter optional encoder variants even when required-slot validation skips them.const graph = compile(ernieModel, { mistralEncoderModel: mistralEncoder });expect(graph.nodes.model_loader?.text_encoder_model).toBeUndefined();@@ -1103,11 +1086,9 @@ describe('ERNIE-Image graphs', () => {expect(graph.nodes.canvas_output?.type).toBe('ernie_image_vae_decode');expect(getEdge(graph, 'canvas_output', 'vae')?.source.node_id).toBe('model_loader');expect(getEdge(graph, 'denoise_latents', 'transformer')?.source.node_id).toBe('model_loader');- // The loader can hold a prompt enhancer resident, which cannot be idle-offloaded; Generate- // never surfaces it, so the graph has to keep asking for it to stay unloaded.+ // Unload the unused prompt enhancer because it cannot idle-offload.expect(graph.nodes.model_loader?.use_prompt_enhancer).toBe(false);- // The node's scheduler is a euler/heun/lcm Literal, so a standard-set value left over from- // another model has to be coerced before it reaches the graph.+ // Coerce to ERNIE's supported scheduler set.expect(graph.nodes.denoise_latents?.scheduler).toBe('euler');});});@@ -1262,8 +1243,7 @@ describe('PiD decode', () => {});it('refuses to compile PiD on an unsupported base rather than silently ignoring it', () => {- // CogView4 has no PiD decode node. Falling back to an ordinary decode would leave the- // user wondering why the output is not 4x.+ // Reject unsupported PiD rather than silently use ordinary decode.expect(() => compile(cogView4Model, { pidMode: 'fit' })).toThrow(/PiD is not supported/);});diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.tsindex 9f184a0b03..67a55c7b40 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts@@ -63,14 +63,7 @@ const getCompatibleComponentSource = (const getCompatibleVae = (settings: GenerateSettings, model: MainModelConfig) =>settings.vae && isVaeCompatibleWithGenerateModel(model, settings.vae) ? settings.vae : null;-/**- * A component selection is only sent when it suits the model that is about to run.- *- * Component settings survive a main-model switch, and an optional slot is not validated at all- * (`validateSlots` returns early for one), so a selection made for another architecture would- * otherwise be forwarded as an override and rejected by the loader node — turning a bundled- * pipeline that needs no components into a failed enqueue.- */+/** Filter stale optional selections that required-slot validation skips. */const getCompatibleComponent = (component: ComponentModelConfig | null,filter: GenerateComponentFilter@@ -427,8 +420,7 @@ const buildSDGraph = (addEdge(graph, negCondCollect, 'collection', denoise, 'negative_conditioning');addEdge(graph, seed, 'value', noise, 'seed');- // Seamless slots in between the model loader and the denoise/decode nodes,- // patching both the UNet and the (possibly overridden) VAE.+ // Seamless wrapping covers both the selected UNet and overridden VAE.if (seamless) {addEdge(graph, modelLoader, 'unet', seamless, 'unet');addEdge(graph, vaeLoader ?? modelLoader, 'vae', seamless, 'vae');@@ -437,8 +429,7 @@ const buildSDGraph = (addEdge(graph, unetSource, 'unet', denoise, 'unet');addEdge(graph, noise, 'noise', denoise, 'noise');addIPAdapterReferenceImages(graph, settings, model, denoise);- // Created here rather than with the other nodes because the decode's VAE source is- // only settled once the seamless / VAE-override nodes above are known.+ // Create decode only after resolving the final VAE source.const output = addDecodeOutput({denoise,graph,@@ -478,13 +469,7 @@ const addPromptAndSeedNodes = (graph: BackendGraphContract) => ({const addImageOutputNode = (graph: BackendGraphContract, type: string, outputIsIntermediate: boolean) =>addNode(graph, { id: 'canvas_output', is_intermediate: outputIsIntermediate, type, use_cache: false });-/**- * The decode that turns the denoised latents into the output image: either the base's- * ordinary VAE decode, or PiD's 4x super-resolution decode when PiD is on.- *- * Both branches wire `latents` (and the VAE where the node needs it) and return the- * terminal `canvas_output` node, so callers attach metadata to the result either way.- */+/** Both decode branches return canvas_output for metadata attachment. */const addDecodeOutput = ({graph,settings,@@ -542,14 +527,9 @@ const addDecodeOutput = ({return output;};-/**- * The width/height to denoise at. Identical to the requested size unless PiD is in- * native mode, where the requested size is the 4x decode target and generation runs at- * a quarter of it.- */+/** Native PiD denoises at one quarter of the requested target dimensions. */const getDenoiseSize = (settings: GenerateSettings, model: MainModelConfig): { width: number; height: number } =>- // Deliberately the model's OWN grid (the default `off` mode), not the PiD-scaled grid- // the dimension fields present: requested / 4 must land on the model's grid.+ // Use the model-native grid for divided dimensions, not the UI's PiD-scaled grid.getPidDenoiseSize(settings, model.base, getGenerationDimensions(model).grid);const buildSD3Graph = (@@ -861,9 +841,7 @@ const buildErnieImageGraph = (outputIsIntermediate: boolean,projectSettings: GenerationProjectSettings): BackendGraphContract => {- // A diffusers pipeline directory carries every submodel, so the loader reads them out of it. A- // single-file transformer carries only itself: its Ministral encoder and FLUX.2 VAE are selected- // in the component section and sent here, the same shape Krea-2 uses.+ // Bundles supply submodels; single-file models need explicit encoder/VAE selections.const isDiffusers = model.format === 'diffusers';const vaeModel = getCompatibleVae(settings, model);const mistralEncoderModel = getCompatibleComponent(settings.mistralEncoderModel, isErnieImageMistralEncoder);@@ -882,8 +860,7 @@ const buildErnieImageGraph = (model,text_encoder_model: mistralEncoderModel ?? undefined,type: 'ernie_image_model_loader',- // The enhancer is a separate node with its own prompt rewriting and cannot be idle-offloaded;- // Generate does not surface it, so the loader is told not to hold it resident.+ // Unload the unused enhancer because it cannot idle-offload.use_prompt_enhancer: false,vae_model: vaeModel ?? undefined,});@@ -1211,9 +1188,7 @@ const buildKrea2Graph = (outputIsIntermediate: boolean,projectSettings: GenerationProjectSettings): BackendGraphContract => {- // Krea-2 has no component-source concept: a non-diffusers transformer (single-file checkpoint- // or GGUF) bundles neither VAE nor encoder, so both must be selected. A diffusers model- // carries them, and the loader extracts them when these are omitted.+ // Standalone Krea needs a separate VAE/encoder without a component source.const isDiffusers = model.format === 'diffusers';const vaeModel = getCompatibleVae(settings, model);const qwen3VlEncoderModel = getCompatibleComponent(settings.qwen3VLEncoderModel, isKrea2Qwen3VlEncoder);@@ -1298,8 +1273,7 @@ const buildIdeogram4Graph = (outputIsIntermediate: boolean,projectSettings: GenerationProjectSettings): BackendGraphContract => {- // A single-file Ideogram 4 main is one of two transformer branches and carries neither encoder- // nor VAE, so all three are selected as components. A diffusers pipeline bundles them.+ // Standalone Ideogram needs its other branch, encoder, and VAE; bundles supply them.const isDiffusers = model.format === 'diffusers';const unconditionalModel = settings.ideogram4UnconditionalModel;const qwen3VlEncoderModel = getCompatibleComponent(settings.qwen3VLEncoderModel, isIdeogram4Qwen3VlEncoder);@@ -1322,8 +1296,6 @@ const buildIdeogram4Graph = (unconditional_model: isDiffusers ? undefined : (unconditionalModel ?? undefined),vae_model: vaeModel ?? undefined,});- // The caption builder turns the prompt (plus optional colour terms) into Ideogram's own- // caption format before encoding.const captionBuilder = addNode(graph, {color_palette: settings.ideogram4ColorPalette,id: 'caption_builder',@@ -1333,8 +1305,7 @@ const buildIdeogram4Graph = (const denoise = addNode(graph, {height: settings.height,id: 'denoise_latents',- // Steps, guidance and mu are preset-derived unless explicitly overridden — sending null- // would override the preset with nothing, so unset values are omitted entirely.+ // Omit unset overrides; null would replace preset defaults....(settings.ideogram4Steps === null ? {} : { steps: settings.ideogram4Steps }),...(settings.ideogram4GuidanceScale === null ? {} : { guidance_scale: settings.ideogram4GuidanceScale }),...(settings.ideogram4Mu === null ? {} : { mu: settings.ideogram4Mu }),@@ -1346,8 +1317,7 @@ const buildIdeogram4Graph = (addEdge(graph, modelLoader, 'transformer', denoise, 'transformer');if (!isDiffusers) {- // Only a single-file main emits a second branch; connecting it for a bundled pipeline is an- // error on the node, because that pipeline's Transformer submodel already holds both.+ // Wire the second branch only for standalone models; bundles already contain both.addEdge(graph, modelLoader, 'unconditional_transformer', denoise, 'unconditional_transformer');}addEdge(graph, modelLoader, 'qwen3_encoder', posCond, 'qwen3_encoder');@@ -1363,8 +1333,7 @@ const buildIdeogram4Graph = (ideogram4_mu: settings.ideogram4Mu ?? undefined,ideogram4_sampler_preset: settings.ideogram4SamplerPreset,ideogram4_steps: settings.ideogram4Steps ?? undefined,- // Two files made this image, so recording only the main model would not identify what ran —- // the same reason `minimax_h3_transformer_model` exists.+ // Record both transformer files in provenance.ideogram4_unconditional_model: isDiffusers ? undefined : (unconditionalModel ?? undefined),qwen3_vl_encoder: qwen3VlEncoderModel ?? undefined,vae: vaeModel ?? undefined,@@ -1379,8 +1348,7 @@ const buildWanGraph = (outputIsIntermediate: boolean,projectSettings: GenerationProjectSettings): BackendGraphContract => {- // A GGUF Wan main carries only the transformer, so the VAE and UMT5-XXL encoder come from- // standalone models or a Diffusers component source.+ // GGUF Wan sources encoder/VAE from standalone selections or a bundle.const sourceModel = getDiffusersSource(settings, model);const vaeModel = getCompatibleVae(settings, model);const wanT5EncoderModel = settings.wanT5EncoderModel;diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.tsindex 201649b95d..0a51e4cf1d 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts@@ -1,30 +1,4 @@-/**- * Every supported base compiles a graph — the systematic counterpart to `graph.test.ts`.- *- * `graph.test.ts` asserts *what* individual families wire up, one hand-written case at a time. That- * leaves a base added to `SUPPORTED_GENERATE_BASES` and `GRAPH_BUILDERS` but never given a case silently- * untested. This file instead iterates `SUPPORTED_GENERATE_BASES`, so a new architecture is covered- * the moment it is registered, and asserts the properties that hold for *all* of them: the- * component policy is satisfiable, the builder runs, and the resulting graph is structurally sound.- *- * It also checks the node types and fields each base emits against a committed fixture. That- * fixture is the frontend half of a cross-stack contract — `tests/app/invocations/- * test_frontend_graph_node_types.py` reads it and checks every type and field against the backend's- * `InvocationRegistry`. A node moved between modules and accidentally renamed shows up there, which- * no frontend-only assertion can see.- *- * Edges are only half of what a builder writes. The other half is what it sets *literally* on a- * node — `use_prompt_enhancer: false`, a scheduler string, `denoising_start: 0` — which no edge- * records. Those inputs are the ones nothing could check: the frontend never sees a backend schema,- * so it cannot know that `ernie_image_denoise.scheduler` is a three-value `Literal`. Recording the- * literal names *and* their values lets the Python half validate each against the field's real- * annotation, turning a renamed input or an out-of-range scheduler into a test failure instead of- * an enqueue-time error on a graph the user cannot edit.- *- * The snapshot file is written by this test and by nothing else — `.oxfmtrc.json` excludes it for- * that reason. Letting the formatter reflow a generated file too would leave both in charge of the- * same bytes, and `format:check` would fail on whichever layout the other one wrote last.- */+/** Cover every builder against backend-validated node/field/literal fixtures; tests own snapshot formatting. */import type { BackendGraphContract } from '@features/generation/core/contracts';@@ -47,13 +21,7 @@ import {} from './baseGenerationPolicies';import { compileGenerateGraph, GRAPH_BUILDERS } from './graph';-/**- * Main-model shapes to compile per base.- *- * `diffusers` bundles its submodels, so the component slots go optional and the builder takes the- * bundled path; a quantized single-file main carries only the transformer and forces the standalone- * -component path. Both paths produce different graphs, so both are worth compiling.- */+/** Compile both bundled and standalone component paths. */interface ModelShape {label: string;overrides: Partial<MainModelConfig>;@@ -64,19 +32,14 @@ const DEFAULT_SHAPES: readonly ModelShape[] = [{ label: 'standalone-components', overrides: { format: 'gguf_quantized' } },];-/**- * Bases whose builder needs more than a format to pick a path. Keys are checked against- * `SUPPORTED_GENERATE_BASES` below, so a renamed or removed base cannot leave a stale entry here.- */+/** Check per-base shape overrides against supported bases. */const SHAPE_OVERRIDES: Partial<Record<SupportedGenerateBase, readonly ModelShape[]>> = {- // Ideogram 4 has no GGUF build: its standalone shape is Comfy-Org's single-file checkpoint, and- // the main model is always the conditional branch -- the other one fills a component slot.+ // Ideogram's standalone fixture is a conditional checkpoint, not GGUF.'ideogram-4': [{ label: 'diffusers', overrides: { format: 'diffusers' } },{ label: 'standalone-components', overrides: { branch: 'conditional', format: 'checkpoint' } },],- // The two FLUX.2 lines take different encoders: [dev] wants Mistral, Klein wants a Qwen3 whose- // variant is pinned to the Klein size by KLEIN_TO_QWEN3_VARIANT.+ // FLUX.2 dev and Klein need distinct encoder variants.flux2: [{ label: 'dev-diffusers', overrides: { format: 'diffusers', variant: 'dev' } },{ label: 'dev-standalone', overrides: { format: 'gguf_quantized', variant: 'dev' } },@@ -86,14 +49,7 @@ const SHAPE_OVERRIDES: Partial<Record<SupportedGenerateBase, readonly ModelShapeconst shapesForBase = (base: SupportedGenerateBase): readonly ModelShape[] => SHAPE_OVERRIDES[base] ?? DEFAULT_SHAPES;-/**- * Candidate components the slot filters get to choose from.- *- * Deliberately a search over a pool rather than a hand-written model per slot: the filters- * (`isAnimaQwen3Encoder`, `isVaeAcceptedByBase`, `isFlux2Qwen3EncoderForModel`, ...) encode which base and- * variant a component must carry, and duplicating that knowledge here would make the test agree- * with itself instead of with the policy.- */+/** Search component candidates through policy rather than copy compatibility rules. */const CANDIDATE_BASES = ['any', ...SUPPORTED_GENERATE_BASES] as const;const CANDIDATE_VARIANTS = [undefined,@@ -124,10 +80,7 @@ const candidatesForSlot = (slot: ComponentSlotPolicy): ModelIdentifierConfig[] =for (const branch of type === 'main' ? CANDIDATE_BRANCHES : [undefined]) {candidates.push({base,- // A component source is a main model, and only a bundled one can stand in for the- // slots it satisfies — `isDiffusersMainForBase` and `isBundledMainForBase` both- // demand it. A branch, on the other hand, only exists on a single file, and its- // slot's filter says so, so the two main-model slots need different formats.+ // Distinguish bundled component sources from single-file branch formats.format: slot.valueKind === 'main' ? (branch ? 'checkpoint' : 'diffusers') : undefined,key: `${base}-${type}-${variant ?? 'novariant'}${latentChannels ? `-${latentChannels}` : ''}${branch ? `-${branch}` : ''}`,name: `${base} ${type} ${variant ?? ''} ${branch ?? ''}`.trim(),@@ -150,8 +103,7 @@ const buildContext = (settings: GenerateSettings,slots: readonly ComponentSlotPolicy[]): ComponentPolicyContext => {- // Derived from the slots rather than from a hand-kept key list: a new slot key is picked up here- // automatically, and a key that no slot uses cannot go stale.+ // Derive keys from slots so new slots enter coverage automatically.const keys = new Set<GenerateComponentValueKey>(slots.map((slot) => slot.key));const selectedComponents = {} as ComponentPolicyContext['selectedComponents'];@@ -162,12 +114,7 @@ const buildContext = (return { model, settings, selectedComponents };};-/**- * Fill every required component slot with something the slot's own filter accepts.- *- * Iterated to a fixpoint because slots are interdependent: selecting a component source can make- * the VAE and encoder slots stop being required, so one pass is not enough to reach a stable answer.- */+/** Fill to a fixed point: selecting a component source can change required slots. */const satisfyRequiredComponents = (model: MainModelConfig,initial: GenerateSettings@@ -230,9 +177,7 @@ const compileForShape = (): { filled: GenerateComponentValueKey[]; graph: BackendGraphContract } => {const { filled, model, settings } = satisfiedSettingsFor(base, shape);- // Compiling an invalid selection throws the first reason, which makes for a poor failure message.- // Asserting here reports every unmet requirement at once, and doubles as the check that the- // base's component policy is satisfiable at all.+ // Assert every requirement before compilation for complete diagnostics.expect(getGenerationValidationReasons(model, settings), `${base}/${shape.label} is not satisfiable`).toEqual([]);return { filled, graph: compileGenerateGraph(settings, model, 'gallery', { useCpuNoise: true }).backendGraph };@@ -277,12 +222,7 @@ describe('generate graph coverage', () => {});it('sends every VAE the picker offers into the graph wherever a VAE is required', () => {- // The slots above are filled with their *first* accepted candidate, which is how a builder that- // re-filtered VAEs by its own base list -- dropping a Qwen-Image VAE installed under `anima` --- // passed this suite. One VAE per accepted (base, width) is enough to see every rule a row has.- //- // Deliberately one test iterating the cases rather than `it.each` over a pre-filtered list: which- // shapes require a VAE is answered by the capability table, and that is only seeded once tests run.+ // Enumerate accepted VAE families at runtime after fixture seeding.const checked: string[] = [];for (const { base, shape } of cases) {@@ -317,8 +257,7 @@ describe('generate graph coverage', () => {}}- // Guards against this test passing vacuously -- it did, while the list was computed before seeding.- // The cross-base rows must each have been exercised with a VAE from another base.+ // Require nonempty cross-base coverage after runtime seeding.expect(checked).toEqual(expect.arrayContaining(['anima/standalone-components:qwen-image/undefined',@@ -353,8 +292,7 @@ describe('generate graph coverage', () => {const { literals } = fieldsFor(node.type);for (const [field, value] of Object.entries(node)) {- // `id` and `type` address the node rather than feed it, and an undefined value is not- // serialized into the request at all — the builders use it to mean "leave the default".+ // Node identity and undefined values are excluded from serialized input contracts.if (field === 'id' || field === 'type' || value === undefined) {continue;}@@ -362,10 +300,7 @@ describe('generate graph coverage', () => {const values = literals.get(field) ?? new Map<string, unknown>();literals.set(field, values);- // Values are recorded for scalars only, so the name is always checked but the value is- // checked where checking it means something. The object-valued inputs are model- // identifiers and LoRA lists built from this file's synthetic fixtures, which carry no- // `hash`; validating those would assert something about the fixture, not the contract.+ // Check scalar values, not only object names, for synthetic unhashed model fixtures.if (value === null || typeof value !== 'object') {values.set(JSON.stringify(value), value);}diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphProvenance.ts b/invokeai/frontend/webv2/src/features/generation/core/graphProvenance.tsindex 817dcf599b..01f3add1fb 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphProvenance.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphProvenance.ts@@ -1,11 +1,6 @@import type { GenerateSettings } from './types';-/**- * Best-effort provenance for generate-compiled graphs: which Generate-panel- * setting produced a node input. Keyed by the builders' fixed node ids- * (graph.ts:313-328) — deliberately not exhaustive; unmapped fields simply- * show no "Set by" entry in the preview inspector.- */+/** Best-effort provenance from fixed graph nodes; unmapped fields remain unavailable. */export interface GenerateProvenanceEntry {labelKey: string;diff --git a/invokeai/frontend/webv2/src/features/generation/core/krea2Conditioning.ts b/invokeai/frontend/webv2/src/features/generation/core/krea2Conditioning.tsindex 42fd8fb388..2a9ae6ba4b 100644--- a/invokeai/frontend/webv2/src/features/generation/core/krea2Conditioning.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/krea2Conditioning.ts@@ -13,10 +13,7 @@ type Krea2ConditioningSettings = Pick<| 'krea2SeedVarianceStrength'>;-/**- * Applies Krea-2's optional conditioning transforms in their required order.- * `idPrefix` makes the same chain safe for any number of regional prompts.- */+/** Preserve transform order and unique prefixes for regional chains. */export const addKrea2ConditioningEnhancers = ({conditioning,graph,diff --git a/invokeai/frontend/webv2/src/features/generation/core/pid.ts b/invokeai/frontend/webv2/src/features/generation/core/pid.tsindex 741eb35db6..76b900dd31 100644--- a/invokeai/frontend/webv2/src/features/generation/core/pid.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/pid.ts@@ -2,12 +2,7 @@ import type { KnownGenerationModelBase as KnownModelBase } from '@features/generimport type { PidMode } from './types';-/**- * PiD (Pixel Diffusion Decoder) — NVIDIA's few-step pixel-diffusion decoder that- * replaces the VAE decode with a caption-conditioned 4x super-resolution decode.- *- * Pure geometry and base-compatibility rules; the graph wiring lives in `graph.ts`.- */+/** Pure PiD geometry and compatibility; pidGraph.ts owns graph wiring. *//** PiD's fixed super-resolution factor. Every released checkpoint is 4x. */export const PID_SCALE = 4;@@ -17,11 +12,7 @@ export const DEFAULT_PID_STEPS = 4;export const MIN_PID_STEPS = 1;export const MAX_PID_STEPS = 16;-/**- * PiD res2k decoders are trained 512 -> 2048. In native mode the user-facing- * dimensions are the 4x target, so the optimal *target* side is 2048 regardless of the- * main model's own optimum.- */+/** The decoder trains from 512 to 2048, making 2048 the native target optimum. */const PID_NATIVE_OPTIMAL_SIDE = 512 * PID_SCALE;export const PID_MODES: readonly PidMode[] = ['off', 'fit', 'native'];@@ -29,19 +20,10 @@ export const PID_MODES: readonly PidMode[] = ['off', 'fit', 'native'];export const isPidMode = (value: unknown): value is PidMode =>typeof value === 'string' && (PID_MODES as readonly string[]).includes(value);-/**- * The generation scale the dimension helpers must account for: 4 in native mode (the- * requested size is the 4x target), 1 otherwise.- */+/** Native PiD scales the target by 4; other modes use 1. */export const getPidScale = (mode: PidMode): number => (mode === 'native' ? PID_SCALE : 1);-/**- * The base whose PiD decoder checkpoints are valid for a given main-model base.- *- * Decoders are trained per backbone, so only a base-matching decoder may be used.- * Z-Image is the exception: it shares FLUX.1's 16-channel VAE and ships no decoder of- * its own, so it reuses the FLUX decoder. Returns null for bases with no PiD support.- */+/** Z-Image reuses FLUX's decoder; unsupported bases return null. */export const getPidDecoderBaseForMainBase = (base: string | null | undefined): KnownModelBase | null => {switch (base) {case 'z-image':@@ -67,14 +49,7 @@ export const getIsPidActive = (mode: PidMode, base: string | null | undefined):const roundDownToMultiple = (value: number, multiple: number): number => Math.floor(value / multiple) * multiple;-/**- * The resolution to actually denoise at.- *- * In native mode the requested size is the 4x target, so generation runs at size / 4,- * floored onto the model's own grid. Callers snap the requested size to grid * 4 (see- * `getGenerationDimensions`), so the division lands exactly on the grid; the floor and- * the `max` only guard hand-entered values.- */+/** Divide native target dimensions by four and floor defensively to the model grid. */export const getPidGenerationSize = (requested: { width: number; height: number },mode: PidMode,@@ -90,12 +65,7 @@ export const getPidGenerationSize = (};};-/**- * The dimension grid and optimal side to present for a PiD mode.- *- * Native multiplies the grid by 4 so that requested / 4 stays on the model grid, and- * reports PiD's own 2048 target as optimal rather than the model's 1024.- */+/** Native PiD uses grid × 4 and target optimum 2048. */export const getPidDimensionOverrides = (mode: PidMode,base: string | null | undefined,diff --git a/invokeai/frontend/webv2/src/features/generation/core/pidGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/pidGraph.tsindex 04b06a69b2..e59c47937c 100644--- a/invokeai/frontend/webv2/src/features/generation/core/pidGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/pidGraph.ts@@ -5,12 +5,7 @@ import type { GenerateSettings, PidMode } from './types';import { addEdge, addNode, createId } from './graphBuilder';import { getIsPidActive, getPidGenerationSize } from './pid';-/**- * PiD decode wiring: replaces a base's VAE decode with the caption-conditioned 4x- * super-resolution decode.- *- * The geometry rules live in `pid.ts`; this module only builds nodes and edges.- */+/** pid.ts owns geometry; this wiring replaces VAE decode with caption-conditioned 4× output. *//** The per-base PiD decode node types. One per base whose builder wires PiD. */export const PID_DECODE_NODE_TYPES = {@@ -24,11 +19,7 @@ export const PID_DECODE_NODE_TYPES = {export type PidDecodeNodeType = (typeof PID_DECODE_NODE_TYPES)[keyof typeof PID_DECODE_NODE_TYPES];-/**- * Decode nodes that read scaling constants off the VAE at runtime, so the VAE must be- * wired even though PiD replaces the decode. FLUX.1 and SD3 use fixed constants and- * take no `vae` input.- */+/** Retain VAE edges for runtime scaling constants even though PiD replaces decode. */const PID_DECODE_NODES_WITH_VAE_INPUT: ReadonlySet<string> = new Set(['flux2_pid_decode','qwen_image_pid_decode',@@ -39,13 +30,7 @@ const PID_DECODE_NODES_WITH_VAE_INPUT: ReadonlySet<string> = new Set([export const getPidDecodeNodeType = (base: string | null | undefined): PidDecodeNodeType | null =>base && base in PID_DECODE_NODE_TYPES ? PID_DECODE_NODE_TYPES[base as keyof typeof PID_DECODE_NODE_TYPES] : null;-/**- * Whether this build should decode through PiD: the mode is on, the base supports it,- * and both required models are selected.- *- * Readiness rejects a half-configured PiD before compilation, so a false here after- * readiness has passed means PiD is genuinely off rather than broken.- */+/** Readiness must reject incomplete PiD first; false is safe only after that validation. */export const shouldUsePidDecode = (settings: Pick<GenerateSettings, 'pidMode' | 'pidDecoderModel' | 'gemma2EncoderModel'>,base: string | null | undefined@@ -84,14 +69,7 @@ interface AddPidDecodeArg {outputIsIntermediate: boolean;}-/**- * Builds the PiD decode chain and returns the terminal image node.- *- * The terminal node is always `canvas_output`: result hydration looks the output up by- * that exact id (`resultNodeIds: ['canvas_output']`). In fit mode that is the- * downscaling `img_resize`; in native mode PiD's 4x output is the result, so the decode- * node itself takes the id.- */+/** Result hydration requires canvas_output on the terminal node: resize for fit, decode for native. */export const addPidDecode = ({graph,settings,@@ -121,8 +99,7 @@ export const addPidDecode = ({type: 'pid_decoder_loader',});const pidDecode = addNode(graph, {- // In native mode this node IS the output, so it claims the id and the caller's- // intermediate flag; in fit mode the resize downstream is the output.+ // In fit mode, move output ownership from decode to resize and mark decode intermediate.id: isNative ? 'canvas_output' : createId('pid_decode'),is_intermediate: isNative ? outputIsIntermediate : true,num_inference_steps: settings.pidSteps,@@ -144,8 +121,7 @@ export const addPidDecode = ({return pidDecode;}- // Fit mode: PiD decoded 4x, so downscale back to the requested size. Keeps the result- // exactly the size the user asked for, which is what makes it compositing-safe.+ // Fit returns the exact requested dimensions after 4× decode.const resize = addNode(graph, {height: settings.height,id: 'canvas_output',diff --git a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.tsindex 20210137d9..a9f8d2c127 100644--- a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts@@ -40,8 +40,7 @@ const storedValues = createGenerateValues({width: 1024,});-// The resolver fails closed without the backend's architecture table, so seed the registry with the-// same fixture the backend pins. Reset afterwards so registry state cannot leak between files.+// Seed authoritative fixtures and clear the registry for test isolation.beforeEach(() => {setArchitectureCapabilities(capabilitiesFixture as ArchitectureCapabilitiesRow[]);});diff --git a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.tsindex 3d24d83f6d..105177ac79 100644--- a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.ts@@ -6,20 +6,10 @@ import { compileGenerateGraph } from './graph';import { resolveGenerateWidgetValues } from './resolveGenerateWidgetValues';import { normalizeGenerateSettings } from './settings';-/**- * Preview-only compile: deterministic where the submit path is intentionally- * random. Ids from `createId` (`prefix_<b36 time>_<6 rand>`) collapse to- * `prefix`, `prefix_2`, … in insertion order so selection and layout survive- * live recompiles, and the seed stays the stored literal (the dialog labels it- * "regenerated each run" when randomization is on).- */+/** Stable preview IDs and literal seeds make recompilation deterministic. */const NO_SUPPORTED_MODEL = 'Generate needs a supported model before it can be invoked.';-// `getDefaultGenerateSettings` (the fallback `resolveGenerateWidgetValues` reaches for-// when `storedValues` doesn't parse — first run, cleared storage, corrupted state) sets-// `seed: Math.floor(Math.random() * SEED_MAX)`. A stored seed is always kept verbatim;-// this placeholder only stands in for the synthesized-default case, so the preview is-// deterministic even before Generate settings have ever been persisted.+// Use the deterministic placeholder only for synthesized defaults; preserve stored seeds.const UNINITIALIZED_SEED_PLACEHOLDER = 0;export interface GeneratePreviewInput {@@ -115,9 +105,7 @@ export const compileGeneratePreviewGraph = (input: GeneratePreviewInput): Generaconst compiled = compileGenerateGraph(settings, settings.model, input.destination, {useCpuNoise: input.useCpuNoise,});- // The submit path leaves the seed node's `value` unset and injects the- // resolved seed via queue batch data instead (see `promptBatch.ts`). The- // preview has no batch step, so bake the literal, unresolved seed in here.+ // Preview graphs bake a literal seed because they have no queue-batch injection step.const seedNode = compiled.backendGraph.nodes[compiled.seedNodeId];const backendGraphWithSeed: BackendGraphContract = seedNode? {diff --git a/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.ts b/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.tsindex 197e4ebef5..d14c15ba2f 100644--- a/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.ts@@ -35,10 +35,7 @@ export const applyProjectPromptDraft = (const hasPromptContent = (draft: ProjectPromptDraft): boolean =>draft.positivePrompt.trim().length > 0 || draft.negativePrompt.trim().length > 0;-/**- * Generate owns the project prompt draft. Older projects may have prompt text stored only in- * Upscale, so seed Generate from it when Generate has no prompt content of its own.- */+/** Seed Generate from Upscale only when Generate has no prompt. */export const migrateProjectPromptDraft = (generateValues: Record<string, unknown>,legacyUpscaleValues: Record<string, unknown>diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.tsindex a2274bba74..a1a58ef3d7 100644--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.ts@@ -103,8 +103,7 @@ const flattenNodes = (nodes: PromptAstNode[], leaves: WeightedLeaf[], weight = NflattenNodes(node.children, leaves, inherited);} else {const previous = leaves.at(-1);- // Compel separates fragments at parentheses even without literal whitespace.- // Keep that word boundary when the delimiters disappear during regrouping.+ // Preserve Compel's implicit word boundaries when removing parentheses.if (previous?.node.type === 'word' && node.type === 'word' && previous.node.range.end < node.range.start) {leaves.push({node: { type: 'whitespace', value: ' ', range: { start: previous.node.range.end, end: node.range.start } },@@ -124,8 +123,7 @@ const selectLeaves = (leaves: WeightedLeaf[], selection: PromptRange): void => {}return;}- // At a token boundary prefer content over punctuation/whitespace, then the token- // starting at the caret. A collapsed selection must never edit both neighbours.+ // Prefer content over punctuation/whitespace, then the token starting at the caret; edit only one neighbor.let best: WeightedLeaf | undefined;let bestRank = -1;for (const leaf of leaves) {diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.test.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.test.tsindex 6754e68f29..db29adf281 100644--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.test.ts@@ -82,8 +82,6 @@ describe('scanDynamicPromptSyntax', () => {]);});- // Regression: globs, sampler overrides and parameters are all valid, and all- // read as ordinary text — or worse, as errors — before this.it('annotates the looser reference forms the backend accepts', () => {expect(annotate('__artists/*__ __artist?__ __animals/[dc]ogs__ __~colours__ __@colours__ __outfit(mood=warm)__')@@ -112,8 +110,7 @@ describe('scanDynamicPromptSyntax', () => {expect(scan('__colours__')).toEqual(['wildcard']);expect(scan('__nope__')).toEqual(['error']);- // A glob is known when anything matches it, and `*` crosses `/` as it does- // on the backend.+ // may cross slashes and must resolve to at least one catalog match.expect(scan('__animals/*__')).toEqual(['wildcard']);expect(scan('__*s__')).toEqual(['wildcard']);expect(scan('__nope/*__')).toEqual(['error']);@@ -189,8 +186,7 @@ describe('scanDynamicPromptSyntax', () => {expect(annotate('a cat # {unclosed __nope__')).toEqual([['comment', '# {unclosed __nope__']]);});- // `\#` is not an escape upstream — it comments from the `#` and leaves the- // backslash in the prompt — so the scanner must not treat it as one either.+ // Backslash does not escape # in backend syntax.it('comments from a backslash-escaped hash too', () => {expect(annotate('a \\# b')).toEqual([['comment', '# b']]);});diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.tsindex c4e32c082e..e1d7af861e 100644--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts@@ -83,8 +83,7 @@ describe('prompt highlight segments', () => {expect(dynamicKindForText(`\${lens}`, `\${lens}`)).toBe('promptVariable');});- // The comment wins over the error the unknown wildcard would otherwise be:- // upstream strips the comment before it ever looks the name up.+ // Strip comments before wildcard lookup.it('dims a comment over everything inside it', () => {const known = new Set(['colors']);const segments = buildPromptHighlightSegments('a cat # __nope__ {unclosed', {@@ -106,8 +105,7 @@ describe('prompt highlight segments', () => {expect(kindWithCatalog('a __colors__ ball', '__colors__')).toBe('wildcard');expect(kindWithCatalog('a __nope__ ball', '__nope__')).toBe('error');- // A glob resolves against the catalog rather than being flagged for not- // being a name of its own.+ // Resolve globs against catalog matches, not literal wildcard names.expect(kindWithCatalog('a __colo*__ ball', '__colo*__')).toBe('wildcard');expect(kindWithCatalog('a __nope/*__ ball', '__nope/*__')).toBe('error');// Without a catalog nothing is known to be missing, so neither is an error.@@ -125,11 +123,7 @@ describe('prompt highlight segments', () => {});});-// The annotation lookup used to filter and sort every annotation for every-// token. Dynamic prompts made that bite: a variant-heavy prompt now carries an-// annotation per brace, separator, weight, sampler, variable and wildcard, so-// the annotation count became proportional to the token count. This ran to-// 469ms on the prompt below, synchronously inside a render, on every keystroke.+// A variant-heavy fixture exposes quadratic annotation lookup.describe('buildPromptHighlightSegments on a large prompt', () => {// eslint-disable-next-line no-template-curly-in-string -- `${v=1}` is dynamic-prompts syntax, not interpolationconst prompt = '{a|b|c} __colours__ ${v=1} '.repeat(700);diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.tsindex 54151e7030..8ea378d600 100644--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts@@ -25,12 +25,7 @@ export type PromptHighlightKind =| 'error';export interface PromptHighlightOptions {- /**- * Annotate dynamic prompting syntax. Only surfaces whose prompt is actually- * batch-expanded enable this — a `{a|b}` in a regional guidance or negative- * prompt is literal text, and colouring it would promise an expansion that- * never happens.- */+ /** Enable dynamic highlighting only on surfaces that actually expand syntax. */dynamicPrompts?: boolean;/** Resolvable wildcard names; omitted leaves every `__name__` neutral. */knownWildcards?: ReadonlySet<string>;@@ -49,8 +44,7 @@ interface HighlightAnnotation {}const ANNOTATION_PRIORITY = {- // A comment outranks even an error: the parser strips it before it sees the- // syntax inside, so nothing in there can be wrong.+ // Comments outrank syntax errors because stripping precedes parsing.comment: 110,error: 100,promptVariableOperator: 46,@@ -112,29 +106,13 @@ const tokenKind = (token: PromptToken): PromptHighlightKind => {const covers = (outer: PromptRange, inner: PromptRange): boolean =>outer.start <= inner.start && outer.end >= inner.end;-/**- * Walks the tokens and the annotations together, keeping only the annotations- * that could still cover the token in hand.- *- * This replaced a `filter().sort()` over every annotation for every token. That- * is quadratic, and dynamic-prompt highlighting made it bite: a prompt full of- * `{a|b|c}` now produces an annotation per brace, separator, weight, range,- * sampler, variable, operator, comment and wildcard, so the annotation count- * grew to be proportional to the token count. At the 20 000-character ceiling- * the highlighter allows, that was tens of milliseconds of blocked main thread- * on every keystroke.- *- * Both inputs are in document order, and an annotation that ends before the- * current token cannot reach any later one either, so it is dropped for good.- * What is left is the nesting depth at that point, which is small.- */+/** Sweep in order and drop expired annotations to avoid rescanning them for every token. */const forEachTokenAnnotation = (tokens: readonly PromptToken[],annotations: readonly HighlightAnnotation[],visit: (token: PromptToken, annotation: HighlightAnnotation | undefined) => void): void => {- // Ties are broken by the order the annotations were collected in, which the- // stable sort this replaced preserved by accident and callers may rely on.+ // Break ties by collection order.const ordered = annotations.map((annotation, index) => ({ annotation, index })).sort((left, right) => left.annotation.range.start - right.annotation.range.start || left.index - right.index);diff --git a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.tsindex 215bad3d31..98ddb77487 100644--- a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts@@ -32,8 +32,7 @@ const applySystemPatch = (systemPatch: Partial<GenerateWidgetValues>): Record<string, unknown> => ({ ...storedValues, ...systemPatch });-// The resolver fails closed without the backend's architecture table, so seed the registry with the-// same fixture the backend pins. Reset afterwards so registry state cannot leak between files.+// Seed backend fixtures and clean up the registry to isolate policy tests.beforeEach(() => {setArchitectureCapabilities(capabilitiesFixture as ArchitectureCapabilitiesRow[]);});@@ -51,9 +50,7 @@ describe('resolveGenerateWidgetValues', () => {});it('never defaults to a model that cannot run on its own', () => {- // Ideogram 4's unconditional branch is a `main` model on a generatable base, so it sorts into- // the catalog like any other. Landing on it here is the worst version of that: the user never- // picked it, and the component section it opens with can only ever be filled with itself.+ // Default resolution excludes unconditional Ideogram branches that cannot generate independently.const unconditional = createModel('ideogram4-uncond', {base: 'ideogram-4',branch: 'unconditional',@@ -238,9 +235,7 @@ describe('resolveGenerateWidgetValues', () => {describe('without the backend capability table', () => {it('resolves nothing rather than falling back to generic defaults', () => {- // Its `systemPatch` is persisted into the project, so a fallback grid or step count would be- // written to disk. Returning null is already how "no usable models" is signalled, and every- // caller handles it.+ // Return null before capabilities load rather than persist fallback defaults.resetArchitectureCapabilities();const model: MainModelConfig = { base: 'sdxl', key: 'model', name: 'model', type: 'main' };@@ -253,9 +248,7 @@ describe('resolveGenerateWidgetValues and an architecture the table omits', () =const rows = capabilitiesFixture as ArchitectureCapabilitiesRow[];it('will not select a model whose architecture the backend did not describe', () => {- // The resolver's patch is persisted. Selecting a model with no row would write the fallback's- // grid, optimal size, step count and scheduler into the project file -- the same reason the- // whole resolver waits for the table in the first place, one level finer.+ // Reject missing rows to protect persisted settings from generic defaults.setArchitectureCapabilities(rows.filter((row) => row.base !== 'cogview4'));expect(diff --git a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.ts b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.tsindex fe0e2e8ec4..37f2417af0 100644--- a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.ts@@ -32,10 +32,7 @@ export interface ResolveGenerateWidgetValuesInput {export interface ResolvedGenerateWidgetValues {/** Canonical values for rendering and user commits. */values: GenerateWidgetValues;- /**- * The complete canonical system-owned patch, or null at the fixed point.- * `batchCount` is deliberately omitted because the Workbench topbar owns it.- */+ /** A fixed point returns null; batchCount belongs to the topbar and is excluded. */systemPatch: Partial<GenerateWidgetValues> | null;}@@ -58,29 +55,18 @@ const createSystemPatch = (values: GenerateWidgetValues): Partial<GenerateWidgetreturn systemPatch;};-/**- * Resolves persisted Generate widget state against backend-owned catalogs.- *- * This is the sole owner of default-model selection and denormalized snapshot- * reconciliation. Applying `systemPatch` reaches a fixed point: the next call- * returns the same canonical values with a null patch.- */+/** This resolver owns reconciliation; applying systemPatch must reach a fixed point. */export const resolveGenerateWidgetValues = ({models,promptTemplates,storedValues,}: ResolveGenerateWidgetValuesInput): ResolvedGenerateWidgetValues | null => {- // Fail closed until the backend's architecture table has arrived. Resolving without it would- // fall back to generic defaults -- and this resolver's `systemPatch` is *persisted* into the- // project, so a fallback grid or step count would be written to disk rather than merely shown.+ // Gate reconciliation to prevent persisting fallback defaults.if (!hasArchitectureCapabilities()) {return null;}- // Described, not merely supported: `getDefaultGenerateSettings` below reads the architecture's- // grid, optimal size, steps and scheduler, and this resolver's patch is persisted. Selecting a- // base the served table omits would write `FALLBACK_GENERATION_CONFIG` into the project file --- // the same reason the whole resolver waits for the table in the first place.+ // Require a described architecture before selecting defaults for persistence.const supportedModels = models.filter(isGenerateModelSelectable).filter(isArchitectureDescribed);if (supportedModels.length === 0) {diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.test.tsindex 1059cde02b..708d483563 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts@@ -73,8 +73,7 @@ describe('normalizeGenerateSettings', () => {});it('never lets the strict guard pass a record whose seed mode still needs inventing', () => {- // Stored values that pass the guard are reused as-is by the widget resolver, so a legacy- // record with only the random toggle would reach the seed menu with `seedMode` undefined.+ // The normalized guard must cover every field because accepted records bypass normalization.const normalized = normalizeGenerateSettings(legacyStoredValues);expect(normalized && isGenerateSettings(normalized)).toBe(true);@@ -481,14 +480,12 @@ describe('dimension helpers', () => {expect(idsOf(moveReferenceImage(referenceImages, 'c', -1))).toEqual(['a', 'c', 'b']);expect(idsOf(moveReferenceImage(referenceImages, 'a', 1))).toEqual(['b', 'a', 'c']);- // Order IS conditioning order, so a move must reorder and nothing else:- // entries keep their identity rather than being rebuilt.+ // Reordering preserves item identities and changes conditioning order.const moved = moveReferenceImage(referenceImages, 'a', 1);expect(moved[1]).toBe(referenceImages[0]);- // Out-of-range moves and an unknown id return the SAME array, which is how- // the caller knows to skip the settings write entirely.+ // Return the same array for no-ops so callers can skip persistence.expect(moveReferenceImage(referenceImages, 'a', -1)).toBe(referenceImages);expect(moveReferenceImage(referenceImages, 'c', 1)).toBe(referenceImages);expect(moveReferenceImage(referenceImages, 'missing', 1)).toBe(referenceImages);diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.tsindex a1a32646c9..e2ac67b108 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts@@ -193,13 +193,7 @@ const isVaePrecision = (value: unknown): value is VaePrecision => value === 'fp1/** Backend defaults from `Ideogram4DenoiseInvocation` / `Krea2*Invocation`. */export const IDEOGRAM4_SAMPLER_PRESETS: Ideogram4SamplerPreset[] = ['V4_QUALITY_48', 'V4_DEFAULT_20', 'V4_TURBO_12'];export const DEFAULT_IDEOGRAM4_SAMPLER_PRESET: Ideogram4SamplerPreset = 'V4_QUALITY_48';-/**- * `Ideogram4DenoiseInvocation.guidance_scale` is `Optional[float]` with `ge=1, le=20` -- the- * constraints sit on the numeric branch of its `anyOf`, which is why a naive schema read misses- * them. Not served through the capability table: the shared guidance slider never reaches this- * field (`NO_GUIDANCE_SLIDER` in `tests/backend/architectures/test_guidance_range.py` records why),- * so it is a local bound on a local, preset-overriding control.- */+/** Ideogram guidance_scale bounds live on the numeric anyOf branch, outside the shared capability-table slider. */export const IDEOGRAM4_GUIDANCE_MIN = 1;export const IDEOGRAM4_GUIDANCE_MAX = 20;/** `steps` is `ge=2`: the node keeps a polish step and a main step, so 1 is not a schedule. */@@ -221,8 +215,6 @@ const getOptionalNumber = (value: unknown): number | null =>const getStringArray = (value: unknown): string[] =>Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : [];-// Re-exported so existing `core/settings` callers keep one import site; the rebalance-// vector, its presets, and its geometry all live in `conditioningRebalance.ts`.export {DEFAULT_KREA2_REBALANCE_MULTIPLIER,DEFAULT_KREA2_REBALANCE_WEIGHTS,@@ -364,14 +356,7 @@ export const cloneReferenceImages = (config: cloneReferenceImageConfig(referenceImage.config),}));-/**- * Moves one reference image a single step through the stack. Array order IS- * conditioning order — the graph builders chain `reference_images` in it — so- * this is the whole of what reordering means. Returns the same array identity- * when the move is a no-op (unknown id, or already at the end it is moving- * toward), so an updater built on it leaves the settings untouched and the- * committed patch comes out empty.- */+/** Array order is conditioning order; no-op reorders return the same array. */export const moveReferenceImage = (referenceImages: readonly GenerateReferenceImage[],id: string,@@ -619,15 +604,7 @@ export const isLoraCompatibleWithModel = (return true;};-/**- * Wan 2.2 main-model variants (`t2v_a14b` / `i2v_a14b` / `ti2v_5b`) and LoRA variants- * (`a14b` / `5b`) name the same families with different strings, so plain variant equality- * would reject every Wan LoRA. The families are also not interchangeable — A14B LoRAs have- * `inner_dim=5120` and 5B `inner_dim=3072`, and applying one to the wrong main crashes the- * layer patcher on a tensor-shape mismatch — so the mapping must be explicit rather than- * permissive. An unknown variant on either side stays allowed: the backend probe is the- * authority, and blocking here would hide a LoRA the backend would have accepted.- */+/** Map main/LoRA families explicitly; unknown variants remain permissive for backend validation. */const WAN_LORA_VARIANT_MAIN_VARIANTS: Record<string, readonly string[]> = {'5b': ['ti2v_5b'],a14b: ['t2v_a14b', 'i2v_a14b'],@@ -646,28 +623,8 @@ export const isWanLoraTargetingMain = (return compatibleMainVariants ? compatibleMainVariants.includes(mainVariant) : true;};-/**- * Validate stored widget values and fill in fields that older persisted- * projects predate. The core fields must be present and well-typed; newer- * fields fall back to their defaults so old projects keep their prompts and- * dimensions instead of being reset wholesale.- */-/**- * The fields of `GenerateSettings` that describe how the panel is arranged- * rather than what will be generated.- *- * They live in the same object because they are saved with the project, and- * separating the two is a change to the persisted shape rather than a- * rearrangement — worth doing, but not here. What can be stated once is which- * is which, and this is it: `satisfies` ties the set to the interface, so a key- * that stops existing, or is spelled wrong, fails to compile.- *- * Everything else is generation intent. Changing one of these is not: dragging- * a prompt box taller or looking at the merged template must not be mistaken- * for the kind of edit that reroutes the workbench. Applying a template *is*- * intent, which is why `promptTemplate` is absent and `promptTemplateViewMode`- * is present.- */+/** Require core fields but default newer fields to preserve older project content. */+/** Exclude arrangement keys from generation-intent routing, including template view but not template application. */export const GENERATE_UI_STATE_KEYS = {aspectRatioIsLocked: true,batchCount: true,@@ -762,10 +719,7 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | nMAX_POSITIVE_PROMPT_HEIGHT_PX,DEFAULT_POSITIVE_PROMPT_HEIGHT_PX),- // Reuse the stored object when it is already canonical. Callers diff settings- // with `Object.is`, so re-sanitizing into a fresh object every pass would make- // every commit look like a template change and loop the sync in- // `GenerateWidgetView`.+ // Preserve canonical object identity to avoid false Object.is changes and reconciliation loops.promptTemplate,promptTemplateViewMode: promptTemplate !== null && values.promptTemplateViewMode === true,referenceImages: normalizeReferenceImages(values.referenceImages),@@ -837,12 +791,7 @@ export const normalizeGenerateWidgetValues = (values: unknown): GenerateWidgetVareturn { ...settings, model: values.model };};-/**- * Canonical means normalize is the identity: every key it would write already- * holds that value. Defined that way rather than as a key list so a field- * normalize learns to invent (a seed mode from the old random toggle, PiD- * defaults) can never pass the guard unhealed and be reused as-is.- */+/** Canonical values normalize to the same identity so newly defaulted fields cannot bypass migration. */export const isGenerateSettings = (values: unknown): values is GenerateSettings => {const normalized = normalizeGenerateSettings(values);diff --git a/invokeai/frontend/webv2/src/features/generation/core/supportedBases.test.ts b/invokeai/frontend/webv2/src/features/generation/core/supportedBases.test.tsindex aea901e553..43f5a3be6d 100644--- a/invokeai/frontend/webv2/src/features/generation/core/supportedBases.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/supportedBases.test.ts@@ -1,11 +1,4 @@-/**- * The list of architectures this build can generate images with.- *- * It used to be `Object.keys(BASE_GENERATION)`, so this assertion doubled as a check on that- * table. With the policy data moving to the backend, the list stands on its own: it is the- * frontend's half of the contract -- the architectures we have a graph builder for. The pin stays- * because adding one must be a deliberate act that a reviewer sees.- */+/** Cover every supported graph builder explicitly. */import { describe, expect, it } from 'vitest';@@ -32,8 +25,7 @@ describe('SUPPORTED_GENERATE_BASES', () => {});it('excludes architectures the backend serves but this build cannot generate with', () => {- // Both have capability rows on `/api/v2/models/capabilities`. Neither has an image graph- // builder: the refiner is a second pass over an SDXL latent, and MiniMax H3 is video-only.+ // Refiner/video-only capability rows are not image graph support.expect(isSupportedGenerateBase('sdxl-refiner')).toBe(false);expect(isSupportedGenerateBase('minimax-h3')).toBe(false);});diff --git a/invokeai/frontend/webv2/src/features/generation/core/supportedBases.ts b/invokeai/frontend/webv2/src/features/generation/core/supportedBases.tsindex 6a46825ac5..031063253f 100644--- a/invokeai/frontend/webv2/src/features/generation/core/supportedBases.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/supportedBases.ts@@ -1,16 +1,4 @@-/**- * The architectures this build can compile an image-generation graph for.- *- * Frontend-owned on purpose, and the one thing in generation policy that cannot come from the- * server: `GRAPH_BUILDERS` in `graph.ts` must have an entry for each of these, and the `satisfies`- * there is what enforces it. The capabilities endpoint advertises more architectures than this --- * `sdxl-refiner` is never run on its own, and `minimax-h3` is video-only with no image graph -- so- * "the server knows about it" and "we can generate with it" are different questions.- *- * Previously derived as `keyof typeof BASE_GENERATION`, which tied the set to the key order of a- * table that is about to be served from the backend. Written out here, adding an architecture stays- * a deliberate act with a test that notices it.- */+/** Frontend graph-builder support is separate from backend architecture awareness. */import type { KnownGenerationModelBase } from '@features/generation/core/contracts';diff --git a/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.test.ts b/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.test.tsindex 09c8d44c8b..59a849a738 100644--- a/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.test.ts@@ -33,8 +33,7 @@ describe('classifySystemPrompts', () => {});it('treats everything as personal in single-user mode', () => {- // The backend seeds built-ins under the user id `system`, which is also the synthetic id- // every single-user request carries — so ownership must not be decided by comparing to it.+ // The synthetic system identity also owns ordinary single-user records.const seeded = record('a', 'system', true);const created = record('b', 'system', false);@@ -84,8 +83,7 @@ describe('resolveSelectedSystemPromptId', () => {});it('falls back when the stored id no longer exists', () => {- // Deleted in another tab, or a shared prompt whose owner unshared it. Resolving on read- // means no corrective write is needed to recover.+ // Recover selection at read time after deletion/unsharing without corrective persistence.expect(resolveSelectedSystemPromptId(prompts, 'deleted')).toBe('a');});@@ -132,8 +130,7 @@ describe('canEditSystemPrompt', () => {});it('never lets a manager edit another user’s private prompt', () => {- // The REST layer does allow an admin to write this one. Offering it in the UI would turn a- // moderation capability into an everyday button, so the client refuses regardless of rights.+ // Private-prompt moderation rights do not grant everyday editing controls.const privateOfOther = record('c', 'someone', false);expect(canEditSystemPrompt(privateOfOther, MANAGER)).toBe(false);diff --git a/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.ts b/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.tsindex 5196842f15..4170db874e 100644--- a/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.ts@@ -1,13 +1,4 @@-/**- * System prompts steer the Expand Prompt LLM. They are user-owned named records that may be- * shared with everyone on the install.- *- * Ownership mirrors prompt templates, with one deliberate difference: there is no "default"- * flag. The backend seeds its built-ins under the user id `system`, but that same id is what- * *every* request carries in single-user mode, so an install that later switched to multiuser- * has ordinary user-created prompts owned by `system` too. Visibility and editability are- * therefore decided by `is_public` and ownership alone — never by comparing against `system`.- */+/** The system ID is ambiguous across installation modes; use visibility and ownership to identify editable records. */export interface SystemPromptAccount {currentUserId: string | null;@@ -53,14 +44,7 @@ export interface SystemPromptEditAuthority extends SystemPromptAccount {canManageSharedPrompts: boolean;}-/**- * Own prompts always; shared ones when the viewer may manage them.- *- * Deliberately never true for another user's private prompt: the REST layer does let an admin- * write one, but offering it here would turn a moderation capability into an everyday button.- * `classifySystemPrompts` already keeps those records out of the list, and this is the second- * guard so that a change to the first cannot silently expose them.- */+/** The client forbids editing another user's private prompt, including for admins. */export const canEditSystemPrompt = (record: SystemPromptOwnershipRecord,authority: SystemPromptEditAuthority@@ -82,13 +66,7 @@ export const requireEditableSystemPrompt = (}};-/**- * A name for a copy that does not collide with one already in the list.- *- * Duplicating twice gives "... (copy)" then "... (copy 2)". A source that is itself a copy keeps- * its suffix rather than being parsed apart, so the chain stays readable and the rule stays one- * anyone can predict from the name they are looking at.- */+/** Suffix collisions while preserving an existing copy suffix. */export const buildDuplicateName = (sourceName: string, existingNames: Iterable<string>): string => {const taken = new Set(existingNames);const base = `${sourceName} (copy)`;@@ -105,15 +83,7 @@ export const buildDuplicateName = (sourceName: string, existingNames: Iterable<s}};-/**- * The selection that should actually be in effect.- *- * The stored id outlives the record it points at — another tab can delete it, and a shared- * prompt stops being visible when its owner unshares it. Rather than persist a corrective- * write, the selection is resolved on read: a stale id falls back to the first visible prompt,- * which is also what an install with no selection yet gets. Returns null only when there is- * nothing to select.- */+/** Fall back to the first visible prompt without corrective writes; return null only for an empty list. */export const resolveSelectedSystemPromptId = (prompts: readonly { id: string }[],selectedId: string | null@@ -125,11 +95,7 @@ export const resolveSelectedSystemPromptId = (return prompts[0]?.id ?? null;};-/**- * Bounds the Expand Prompt endpoint enforces on a per-prompt output-token cap- * (`ExpandPromptRequest.max_tokens`). Kept here so the editor can reject a bad value in place- * rather than surfacing a 422.- */+/** Token bounds match the expansion endpoint. */export const SYSTEM_PROMPT_MAX_TOKENS_MIN = 1;export const SYSTEM_PROMPT_MAX_TOKENS_MAX = 2048;/** What the backend uses when a prompt names no cap of its own. Shown as the field's placeholder. */@@ -138,12 +104,7 @@ export const SYSTEM_PROMPT_MAX_TOKENS_DEFAULT = 300;/** `null` = leave it to the backend default; `'invalid'` = not saveable. */export type ParsedMaxTokens = number | null | 'invalid';-/**- * Reads the editor's max-tokens input.- *- * The draft holds the raw string rather than a number so a half-typed value is never clamped- * out from under the user; the result is only interpreted on save.- */+/** Keep raw drafts until save so half-typed input survives. */export const parseMaxTokensInput = (raw: string): ParsedMaxTokens => {const trimmed = raw.trim();@@ -151,8 +112,7 @@ export const parseMaxTokensInput = (raw: string): ParsedMaxTokens => {return null;}- // Deliberately strict: `Number('12e3')` and `Number(' 12 ')` both parse, and neither is a- // token count anyone meant to type.+ // Accept decimal integers only.if (!/^\d+$/.test(trimmed)) {return 'invalid';}diff --git a/invokeai/frontend/webv2/src/features/generation/core/types.ts b/invokeai/frontend/webv2/src/features/generation/core/types.tsindex 23bbfc5bac..35f5da8832 100644--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts@@ -151,12 +151,7 @@ export type AspectRatioId =| '9:21'| '1:8';-/**- * Which of the fields below are panel arrangement rather than generation- * intent is stated once, as `GENERATE_UI_STATE_KEYS` in `./settings` — beside- * the normalization that already enumerates them, and where it costs no module- * of its own. This interface stays type-only.- */+/** GENERATE_UI_STATE_KEYS defines the UI-only keys; this module owns their types. */export interface GenerateSettings {batchCount: number;modelKey: string;@@ -165,11 +160,7 @@ export interface GenerateSettings {negativePromptEnabled: boolean;negativePrompt: string;negativePromptHeightPx: number;- /**- * The active prompt template, copied rather than referenced by id so the pure- * submit reducer can resolve prompts with no catalog lookup. See- * `core/promptTemplates.ts`.- */+ /** Stored template snapshots allow pure submission without catalog lookup. */promptTemplate: PromptTemplateSnapshot | null;/** Show the merged prompt read-only instead of the authored text. */promptTemplateViewMode: boolean;@@ -219,10 +210,7 @@ export interface GenerateSettings {qwen3VLEncoderModel: ComponentModelConfig | null;/** Wan 2.2's UMT5-XXL text encoder. */wanT5EncoderModel: ComponentModelConfig | null;- /**- * The low-noise expert of a Wan 2.2 A14B mixture-of-experts pair. Optional: without it the- * high-noise expert runs the whole schedule, which still produces an image at lower quality.- */+ /** The low-noise expert is optional; the selected expert can span the full schedule. */wanLowNoiseModel: MainModelConfig | null;/*** Ideogram 4's unconditional transformer branch. Required with a single-file main, which holds@@ -249,11 +237,7 @@ export interface GenerateSettings {krea2SeedVarianceEnabled: boolean;krea2SeedVarianceStrength: number;krea2SeedVarianceRandomizePercent: number;- /**- * PiD (Pixel Diffusion Decoder) replaces the VAE decode with a caption-conditioned- * 4x super-resolution decode. Off by default; requires a PiD decoder and a Gemma-2- * caption encoder.- */+ /** PiD replaces VAE decode with caption-conditioned 4× output; requires a PiD decoder and Gemma-2 encoder. */pidMode: PidMode;/** PiD decoder checkpoint. Trained per backbone, so it must match the main model's base. */pidDecoderModel: ComponentModelConfig | null;@@ -270,10 +254,7 @@ export interface GenerateSettings {*/export type PidMode = 'off' | 'fit' | 'native';-/**- * Ideogram 4 sampler presets. Each fixes a step count and guidance schedule; the explicit- * step / guidance / mu overrides are applied on top when set.- */+/** Use preset defaults unless steps, guidance, or mu is explicitly overridden. */export type Ideogram4SamplerPreset = 'V4_QUALITY_48' | 'V4_DEFAULT_20' | 'V4_TURBO_12';export interface GenerateWidgetValues extends GenerateSettings {diff --git a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesApi.ts b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesApi.tsindex b6cdf30bab..ff7a90369e 100644--- a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesApi.ts+++ b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesApi.ts@@ -2,13 +2,7 @@ import type { ArchitectureCapabilitiesRow } from '@features/generation/core/archimport { apiFetchJson } from '@platform/transport/http';-/**- * The architecture capability table.- *- * A static list -- the same for every install and every user -- describing what each model- * architecture supports. Lives under the model-manager router because that is where architectures- * are addressed, but it is not model-record data: nothing here depends on what is installed.- */+/** The architecture table is static per backend build and independent of installed models. */const CAPABILITIES_PATH = '/api/v2/models/capabilities';export const getArchitectureCapabilities = (signal?: AbortSignal): Promise<ArchitectureCapabilitiesRow[]> =>diff --git a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.test.ts b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.test.tsindex 86e8853caf..dcc0f121bf 100644--- a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.test.ts@@ -14,8 +14,7 @@ describe('architecture capabilities store', () => {});it('fills the core registry rather than the snapshot', async () => {- // The rows have exactly one home: policy accessors read them synchronously from all over the- // app, including graph builders at enqueue time.+ // The core registry is the sole synchronous table authority.api.getArchitectureCapabilities.mockResolvedValue(rows);const store = await import('./architectureCapabilitiesStore');const registry = await import('@features/generation/core/architectureCapabilities');@@ -68,8 +67,7 @@ describe('architecture capabilities store', () => {});it('clears the registry as well as the snapshot when the account changes', async () => {- // The addition to the starters-store template: the rows live outside this store, so clearing- // only the snapshot would leave the previous account's table readable behind an idle status.+ // Clear registry rows with store status so previous-account data cannot survive.api.getArchitectureCapabilities.mockResolvedValue(rows);const lifecycle = await import('@platform/state/accountLifecycle');const store = await import('./architectureCapabilitiesStore');@@ -85,9 +83,7 @@ describe('architecture capabilities store', () => {});it('publishes the registry rather than its own request state', async () => {- // The subscription contract for every imperative policy reader. It has to follow the registry,- // not this store's fetch: `status` would miss a table that arrived by any other route, and a- // reader gated on it would keep answering from the fallback config.+ // Subscribe to the registry, not fetch status, so every table writer notifies readers.api.getArchitectureCapabilities.mockResolvedValue(rows);const store = await import('./architectureCapabilitiesStore');const registry = await import('@features/generation/core/architectureCapabilities');@@ -107,9 +103,7 @@ describe('architecture capabilities store', () => {});it('reloads the table for the account that replaces the one it was cleared for', async () => {- // The boot kick lives in a mount effect that does not re-run, and the long-lived subscribers- // (the bbox <-> dims sync, the topbar) never re-subscribe. Without this re-arm a table cleared- // on an account change would stay `idle` forever and every gate would stay closed.+ // Rearm after account changes; boot effects and subscribers do not remount.api.getArchitectureCapabilities.mockResolvedValue(rows);const lifecycle = await import('@platform/state/accountLifecycle');const store = await import('./architectureCapabilitiesStore');diff --git a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.ts b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.tsindex 803d5c81a5..3d8f231630 100644--- a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.ts+++ b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.ts@@ -15,37 +15,19 @@ import { getApiErrorMessage } from '@platform/transport/http';import { getArchitectureCapabilities } from './architectureCapabilitiesApi';-/**- * Load state for the architecture capability table.- *- * The rows themselves live in the core registry, not in this snapshot: generation policy is read- * from synchronous accessors all over the app, including from graph builders at enqueue time, so- * there must be exactly one place holding the table. This store owns only *whether* it is there.- *- * Fetched once. The table is static per backend build -- it is derived from- * `invokeai/backend/architectures/defs/`, not from installed models -- so nothing revalidates it.- */+/** Fetch status is separate from authoritative core rows; the table is static per backend build. */export interface ArchitectureCapabilitiesSnapshot {status: 'idle' | 'loading' | 'loaded' | 'error';error: string | null;- /**- * Identity of the table in the core registry; `0` while there is none.- *- * This is the whole subscription contract for the many readers that call the synchronous policy- * accessors during render or at enqueue time: subscribe to this, and re-read when it changes.- * `status` cannot serve that purpose -- it describes this store's request, not the registry, and- * a reader gated on it would miss a table seeded by anything but a fetch.- */+ /** Revision zero means absent; observe registry identity rather than request status. */revision: number;}const EMPTY_SNAPSHOT: ArchitectureCapabilitiesSnapshot = { error: null, revision: 0, status: 'idle' };const store = createExternalStore<ArchitectureCapabilitiesSnapshot>(EMPTY_SNAPSHOT);-// The registry is the authority; this store publishes it. Mirroring here rather than alongside each-// write means every path that fills or drops the table reaches subscribers, including tests that-// seed it directly.+// Publish from registry changes so direct seeds and clears also notify subscribers.onArchitectureCapabilitiesChanged(() => store.patchSnapshot({ revision: getArchitectureCapabilitiesRevision() }));const refreshFlight = createTrailingSingleFlight();@@ -56,16 +38,11 @@ let isRequested = false;registerAccountOwnedResource({clear: () => {refreshFlight.reset();- // The registry is module state outside this store, so clearing the snapshot alone would leave- // the previous account's table readable behind a status that says nothing is loaded. Dropped- // before the snapshot, so no subscriber is ever woken to read the old table at revision 0.+ // Clear the registry before publishing revision zero to prevent old-account reads.resetArchitectureCapabilities();store.setSnapshot(EMPTY_SNAPSHOT);- // `activate` rotates the scope *before* clearing, so the incoming account is already current- // here. Re-arm rather than wait to be asked again: the app kicks the fetch once, at boot, from- // a mount effect that does not re-run, and the long-lived subscribers below never re-subscribe.- // A boot-time load that raced sign-in was aborted by that rotation; this is what replaces it.+ // Refetch after account rotation; the one-time boot mount cannot replace aborted work.if (isRequested && captureAccountScope().accountId !== null) {void refreshArchitectureCapabilities();}@@ -99,10 +76,7 @@ export const refreshArchitectureCapabilities = (): Promise<void> =>});});-/**- * Fetch on first use or retry after an error, so one failed load never sticks. Settles when the load- * it started or joined does; it never rejects -- the outcome is the snapshot's status.- */+/** This promise never rejects; inspect snapshot status after the joined or started load settles. */export const ensureArchitectureCapabilitiesLoaded = (): Promise<void> => {isRequested = true;diff --git a/invokeai/frontend/webv2/src/features/generation/data/dynamicPromptsQueries.test.ts b/invokeai/frontend/webv2/src/features/generation/data/dynamicPromptsQueries.test.tsindex 05e4e2d7f1..d714f38e97 100644--- a/invokeai/frontend/webv2/src/features/generation/data/dynamicPromptsQueries.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/data/dynamicPromptsQueries.test.ts@@ -25,9 +25,7 @@ describe('resolveDynamicPrompts', () => {expect(parseDynamicPrompts).toHaveBeenCalledTimes(1);});- // Regression: `ensureQueryData` hands back cached data whenever it exists,- // invalidated or not, so editing a wildcard left the submit path enqueueing an- // expansion built from the old values.+ // Invalidated infinite-stale cache entries must refetch.it('re-expands after the wildcard catalog is invalidated', async () => {await expect(resolveDynamicPrompts(queryClient, request)).resolves.toMatchObject({ prompts: ['a red ball'] });diff --git a/invokeai/frontend/webv2/src/features/generation/data/dynamicPromptsQueries.ts b/invokeai/frontend/webv2/src/features/generation/data/dynamicPromptsQueries.tsindex 8c7cd34d39..6a8f8694f2 100644--- a/invokeai/frontend/webv2/src/features/generation/data/dynamicPromptsQueries.ts+++ b/invokeai/frontend/webv2/src/features/generation/data/dynamicPromptsQueries.ts@@ -1,14 +1,4 @@-/**- * The one cache for prompt expansion. The preview popover and the Invoke tooltip- * observe it through `useQuery`; the enqueue path reads it through- * `resolveDynamicPrompts`. Because all three address the same key, invoking- * normally costs no extra round trip, and invoking before the preview has- * settled still enqueues the prompts the backend actually produces rather than a- * stale list.- *- * Expansion is deterministic for a given request — combinatorial by- * construction, and seeded when random — so entries never go stale on their own.- */+/** Share deterministic expansion queries and prevent stale results across consumers. */import type {ParseDynamicPromptsRequest,@@ -53,15 +43,7 @@ export const dynamicPromptsQueryOptions = (request: ParseDynamicPromptsRequest)});})();-/**- * Cache-first expansion for the enqueue path, which cannot render a loading state.- *- * `fetchQuery` rather than `ensureQueryData`: the latter returns whatever is in- * the cache the moment it holds data, invalidated or not. Under `staleTime:- * Infinity` that means an edited wildcard would keep serving its old expansion- * to the submit path. `fetchQuery` consults staleness, which invalidation drives,- * so an untouched entry still costs no round trip.- */+/** Use fetchQuery: ensureQueryData can return invalidated entries despite infinite staleTime. */export const resolveDynamicPrompts = (queryClient: QueryClient,request: ParseDynamicPromptsRequestdiff --git a/invokeai/frontend/webv2/src/features/generation/data/promptUtilities.ts b/invokeai/frontend/webv2/src/features/generation/data/promptUtilities.tsindex 64cef8fb89..5f5fb9518e 100644--- a/invokeai/frontend/webv2/src/features/generation/data/promptUtilities.ts+++ b/invokeai/frontend/webv2/src/features/generation/data/promptUtilities.ts@@ -49,10 +49,7 @@ export interface ParseDynamicPromptsRequest {export interface ParseDynamicPromptsResponse {prompts: string[];- /**- * A soft failure. The route still returns usable prompts alongside a parse- * message or a "No values found for wildcard(s)" notice.- */+ /** Soft expansion errors can still return usable prompts. */error?: string | null;}diff --git a/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.test.ts b/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.test.tsindex 025b67b961..2e29b67a59 100644--- a/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.test.ts@@ -61,8 +61,7 @@ describe('system prompt max_tokens', () => {});it('sends an explicit null on update so a cap can be cleared', async () => {- // The backend distinguishes a present null ("back to the default") from an omitted key- // ("leave it alone"), so the key must survive JSON.stringify.+ // Explicit null clears the value; omission preserves it.await updateSystemPrompt('prompt-1', { content: dto.content, maxTokens: null, name: dto.name });const body = sentBody();diff --git a/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.ts b/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.tsindex 0e477825d4..08c1f81457 100644--- a/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.ts+++ b/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.ts@@ -75,8 +75,7 @@ export const createSystemPrompt = async (draft: SystemPromptDraft): Promise<Systexport const updateSystemPrompt = async (id: string, draft: SystemPromptDraft): Promise<SystemPromptRecord> =>mapSystemPrompt(await apiFetchJson<SystemPromptDTO>(`${SYSTEM_PROMPTS_BASE}/i/${encodeURIComponent(id)}`, {- // `max_tokens` is sent on every update, including as an explicit null: the backend reads a- // present-but-null as "clear the cap", and an omitted key as "leave it alone".+ // Null clears max_tokens; omission preserves it.body: JSON.stringify({ content: draft.content, max_tokens: draft.maxTokens, name: draft.name }),method: 'PATCH',})diff --git a/invokeai/frontend/webv2/src/features/generation/data/wildcards.ts b/invokeai/frontend/webv2/src/features/generation/data/wildcards.tsindex 18f4c8d9ec..b076f4ad68 100644--- a/invokeai/frontend/webv2/src/features/generation/data/wildcards.ts+++ b/invokeai/frontend/webv2/src/features/generation/data/wildcards.ts@@ -1,11 +1,4 @@-/**- * The current user's wildcards: named value lists that `__name__` expands to.- *- * The catalog feeds three consumers — the `__` autocomplete, the highlighter's- * known/unknown distinction, and the wildcards editor — so it is fetched once- * and shared. Mutations must invalidate the dynamic prompts cache as well; see- * `invalidateWildcardDependents`.- */+/** Catalog edits invalidate shared expansion queries too. */import type { QueryClient } from '@tanstack/react-query';@@ -54,15 +47,7 @@ export const deleteWildcard = async (id: string): Promise<void> => {await apiFetch(`/api/v1/wildcards/${encodeURIComponent(id)}`, { method: 'DELETE' });};-/**- * Editing a wildcard changes what a prompt expands to without changing the- * prompt, and the expansion cache is keyed only on the request (with- * `staleTime: Infinity`). Both caches must therefore be dropped together, or the- * preview and the submitted batch would both keep serving the old expansion.- *- * Invalidation is the whole mechanism, so every reader has to consult staleness- * — see the `fetchQuery` note in `resolveDynamicPrompts`.- */+/** Infinite staleTime and request-only keys require dependent invalidation and staleness-aware readers. */export const invalidateWildcardDependents = async (queryClient: QueryClient): Promise<void> => {await Promise.all([queryClient.invalidateQueries({ queryKey: wildcardKeys.all }),diff --git a/invokeai/frontend/webv2/src/features/generation/graph.ts b/invokeai/frontend/webv2/src/features/generation/graph.tsindex 97c82e7e98..c09ff43859 100644--- a/invokeai/frontend/webv2/src/features/generation/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/graph.ts@@ -1,9 +1,4 @@-/**- * Generation's eagerly shared graph surface: the generate compiler, Canvas- * validation policies, and graph-builder primitives used by other invocation- * sources. Canvas compilation lives in the lazy `canvasGraph` interface.- * Curated, caller-driven export list — add a symbol only when a consumer needs it.- */+/** Keep ordinary graph compilation eager and canvasGraph lazy. */export {addLoraCollectionLoader,addTransformerLoraCollectionLoader,diff --git a/invokeai/frontend/webv2/src/features/generation/preview.ts b/invokeai/frontend/webv2/src/features/generation/preview.tsindex 1c493277c2..3d98a734e2 100644--- a/invokeai/frontend/webv2/src/features/generation/preview.ts+++ b/invokeai/frontend/webv2/src/features/generation/preview.ts@@ -1,9 +1,4 @@-/**- * Generation's preview-only public surface, kept separate from `graph.ts` so- * consumers behind a lazy chunk boundary (the graph preview dialog) never- * pull the preview compiler into `graph.ts`'s eager importers — mirrors- * `@features/workflow/preview`.- */+/** Isolate preview compilation from eager graph importers. */export { compileGeneratePreviewGraph, stabilizeBackendGraphIds } from './core/previewGraph';export type { GeneratePreviewInput, GeneratePreviewResult } from './core/previewGraph';export { getGenerateNodeProvenance } from './core/graphProvenance';diff --git a/invokeai/frontend/webv2/src/features/generation/prompts.ts b/invokeai/frontend/webv2/src/features/generation/prompts.tsindex da84d8d29a..9d0610c96b 100644--- a/invokeai/frontend/webv2/src/features/generation/prompts.ts+++ b/invokeai/frontend/webv2/src/features/generation/prompts.ts@@ -1,10 +1,3 @@-/**- * Generation's prompt-expansion transport surface: the shared dynamic prompts- * cache used by the Generate preview, the Invoke tooltip, and Queue's- * submission. The pure policy (`hasDynamicPromptSyntax`,- * `buildGeneratePromptBatchPlan`, bounds and config sanitization) lives on- * `@features/generation/settings`.- * Curated, caller-driven export list — add a symbol only when a consumer needs it.- */+/** Keep transport entries separate from pure policy entries. */export { dynamicPromptsKeys, dynamicPromptsQueryOptions, resolveDynamicPrompts } from './data/dynamicPromptsQueries';export type { ParseDynamicPromptsRequest, ParseDynamicPromptsResponse } from './data/promptUtilities';diff --git a/invokeai/frontend/webv2/src/features/generation/react.ts b/invokeai/frontend/webv2/src/features/generation/react.tsindex 58157a60b1..bf0fb9e653 100644--- a/invokeai/frontend/webv2/src/features/generation/react.ts+++ b/invokeai/frontend/webv2/src/features/generation/react.ts@@ -1,8 +1,3 @@-/**- * Generation's React integration surface: the UI port provider, draft- * registry/flushing, form view-model selectors, and prompt hotkey handlers.- * Curated, caller-driven export list — add a symbol only when a consumer needs it.- */export { GenerationUiProvider, type GenerationUiAdapter } from './ui/GenerationUiContext';export { flushGenerateDrafts, useRegisterGenerateDraftFlusher } from './ui/generateDraftRegistry';export { useDebouncedDraftValue } from './ui/useDebouncedDraftValue';diff --git a/invokeai/frontend/webv2/src/features/generation/runtime.test.ts b/invokeai/frontend/webv2/src/features/generation/runtime.test.tsindex d6a22a4fdd..745ab11f10 100644--- a/invokeai/frontend/webv2/src/features/generation/runtime.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/runtime.test.ts@@ -113,8 +113,7 @@ beforeEach(() => {templateQuery.queryFn.mockResolvedValue([]);});-// The resolver fails closed without the backend's architecture table, so seed the registry with the-// same fixture the backend pins. Reset afterwards so registry state cannot leak between files.+// Seed the shared capability fixture and clear it after each test.beforeEach(() => {setArchitectureCapabilities(capabilitiesFixture as ArchitectureCapabilitiesRow[]);});@@ -259,9 +258,7 @@ describe('createGenerateWidgetSyncRuntime', () => {});describe('the architecture-capabilities gate', () => {- // reconcile() writes its result into the project via patchValues, so it must not run on fallback- // policy: the values are persisted, not merely displayed. This is why the gate lives here and- // not only in the widget -- the runtime reconciles at construction, before anything renders.+ // Constructor reconciliation persists values, so it must wait for authoritative capabilities.it('writes nothing until the capability table has arrived', () => {const { capabilitiesLoaded, patches } = setup({capabilitiesLoaded: false,diff --git a/invokeai/frontend/webv2/src/features/generation/runtime.ts b/invokeai/frontend/webv2/src/features/generation/runtime.tsindex 25afb42e2c..a041c65039 100644--- a/invokeai/frontend/webv2/src/features/generation/runtime.ts+++ b/invokeai/frontend/webv2/src/features/generation/runtime.ts@@ -16,13 +16,7 @@ export interface GenerateWidgetSyncProjectSnapshot {}export interface GenerateWidgetSyncRuntimeDeps {- /**- * Whether the backend's architecture capability table has arrived.- *- * `reconcile` writes its result into the project, so it must not run on fallback policy: the- * values would be persisted, not just displayed. Subscribed like the other read models so the- * first reconcile happens as soon as the table lands.- */+ /** Wait for authoritative capabilities before reconciliation can persist fallback values. */capabilitiesLoaded: ReadonlyStore<boolean>;models: ReadonlyStore<readonly GenerationModelCatalogItem[]>;patchValues(values: Partial<GenerateWidgetValues>, projectId: string, origin: 'system'): void;@@ -34,11 +28,7 @@ export interface GenerateWidgetSyncRuntime {dispose(): void;}-/**- * Keeps the active project's persisted Generate values at the resolver's fixed- * point. The runtime owns every external subscription and is deliberately- * React-free; App supplies the two read models and the one aggregate command.- */+/** The runtime owns subscriptions and reconciles settings to a fixed point. */export const createGenerateWidgetSyncRuntime = (deps: GenerateWidgetSyncRuntimeDeps): GenerateWidgetSyncRuntime => {const promptTemplateOptions = promptTemplatesQueryOptions();const promptTemplateObserver = new QueryObserver(deps.queryClient, {diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsindex defd2c6e68..acb3c2ec5e 100644--- a/invokeai/frontend/webv2/src/features/generation/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -1,8 +1,4 @@-/**- * Generation's React-free values/policy surface: settings normalization, base- * policies, batch limits, prompt history, prompt drafts, and reference images.- * Curated, caller-driven export list — add a symbol only when a consumer needs it.- */+/** Keep this public entry React-free. */export {ASPECT_RATIO_MAP,calculateNewSize,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsxindex 74c9710ccd..f2ef2cd190 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx@@ -93,8 +93,7 @@ export const GenerateAdvancedFields = ({return null;}- // The closed section reports deviation, not detail: each user-level decision- // that is off its default counts once.+ // Count user decisions, not modified settings keys.const overrideCount = [customVae,modelDefaults !== null && settings.vaePrecision !== modelDefaults.vaePrecision,@@ -305,8 +304,7 @@ export const GenerateAdvancedFields = ({const mode = value[0];if (isPidMode(mode)) {- // Committed immediately: switching to or from native changes the dimension- // grid, and a debounced write would let a now-invalid size linger.+ // Commit immediately because native mode changes the valid dimension grid.onCommitImmediate({ pidMode: mode });}}}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsxindex d0e7191d9e..e428287918 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx@@ -45,10 +45,6 @@ const LORA_WEIGHT_DEBOUNCE_MS = 250;const isCompatibleLora = (lora: GenerateLora, selectedModel: GenerateModelConfig | undefined): boolean =>Boolean(selectedModel && isLoraCompatibleWithModel(lora.model, selectedModel));-/**- * Concept (LoRA) conditioning, rendered inside the Guidance section (the- * section chrome and combined badges live in `GenerateGuidanceSection`).- */export const GenerateConceptsContent = ({loraModels,onCommit,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.browser.test.tsxindex 05661fffaa..20379493d4 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.browser.test.tsx@@ -65,10 +65,6 @@ const removePreset = vi.fn();let customPresets: RebalancePreset[] = [];-/**- * The field reads exactly one sub-port and three settings keys. Building the whole- * adapter would only couple this test to parts of the port it never touches.- */const buildAdapter = (): GenerationUiAdapter =>({rebalancePresets: {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.tsxindex 05bebd62f7..adf195fafe 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.tsx@@ -13,8 +13,7 @@ import {REBALANCE_PRESET_DEFAULT_ID,serializeRebalanceWeights,} from '@features/generation/core/conditioningRebalance';-// Imported by subpath rather than from the `@platform/ui` barrel: the barrel is at its-// direct-importer budget, so each call site here would otherwise cost against it.+// Use subpath imports to stay within the direct-importer budget.import { IconButton } from '@platform/ui/Button';import { ConfirmDialog } from '@platform/ui/ConfirmDialog';import { Field } from '@platform/ui/Field';@@ -58,14 +57,7 @@ interface GenerateConditioningRebalanceFieldProps {onCommitImmediate: (patch: Partial<GenerateSettings>) => void;}-/**- * Krea-2's per-tap conditioning gains.- *- * The twelve bars weight the twelve Qwen3-VL encoder layers stacked into the- * conditioning, shallow (the prompt's literal wording) to deep (its meaning and- * composition); Gain scales the result. Collapsed, the row is a switch and a preview of- * the current curve.- */+/** Twelve elementwise encoder gains, ordered shallow to deep. */export const GenerateConditioningRebalanceField = ({onCommit,onCommitImmediate,@@ -73,8 +65,7 @@ export const GenerateConditioningRebalanceField = ({}: GenerateConditioningRebalanceFieldProps) => {const { t } = useTranslation();const { rebalancePresets } = useGenerationUi();- // The switch shares the Field.Root with the controls below; an explicit id keeps its- // label bound to its own hidden input rather than the Field's control id.+ // Give sibling switches explicit IDs inside a shared Field.const switchInputId = useId();const [previewWeights, setPreviewWeights] = useState<number[] | null>(null);@@ -140,8 +131,7 @@ export const GenerateConditioningRebalanceField = ({(value: string) => {setWeightsDraft(value);- // Only a vector the backend would accept reaches the settings; the draft holds- // everything in between so the field does not fight the cursor.+ // Commit only valid vectors; intermediate text stays in the draft.if (parseRebalanceWeights(value) !== null) {onCommitImmediate({ krea2RebalanceWeights: value });}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsxindex 18ac9e79dd..c05dbc6fad 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx@@ -117,8 +117,7 @@ describe('GenerateDimensionFields aspect ratio', () => {});it('shows the lock engaged while a preset is selected and unlocking returns to Free', async () => {- // A preset with the flag off is what a recalled image can leave behind; the ratio is still- // enforced, so the lock must say so rather than contradict the preset beside it.+ // A preset implies ratio lock even when the stored flag is false.const onCommit = await render({aspectRatioId: '16:9',aspectRatioIsLocked: false,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsxindex 966fa1293a..75df22daa7 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx@@ -45,12 +45,7 @@ const DIMENSION_SLIDER_MAX = 2048;/** Vertical gap between the width and height rows; the lock bracket's geometry assumes it. */const DIMENSION_ROW_GAP = '2';-/**- * One continuous line leaves the width row, runs behind the lock, and returns- * to the height row: the coupling is drawn, and it lights up with the button- * when locked. Geometry assumes `xs` rows (28px), an 8px row gap, a 4px column- * gap, and the `2xs` button (24px).- */+/** Geometry assumes 28px rows, an 8px row gap, a 4px column gap, and a 24px lock button. */const LOCK_BRACKET_PATH = 'M0 14H12a4 4 0 0 1 4 4v28a4 4 0 0 1-4 4H0';const LOCK_BRACKET_CSS = {alignItems: 'center',@@ -81,12 +76,7 @@ const PREVIEW_PAD_PX = 10;const clampToRange = (value: number): number => Math.min(MAX_DIMENSION, Math.max(MIN_DIMENSION, value));-/**- * The preview IS a control: the solid rectangle is the current size, the dashed- * ghost is the model-recommended size at the same scale, and the corner handle- * resizes by direct manipulation — grid-snapped on release, ratio-lock- * respected while dragging. Arrow keys nudge by one grid step.- */+/** Respect ratio lock during drag and snap to the grid on release; arrow keys move by one grid step. */const SizePreview = ({current,grid,@@ -126,11 +116,7 @@ const SizePreview = ({};};- // The rectangle stays centered, so the corner moves at half the size delta —- // the factor of two keeps the handle tracking the pointer. The scale is the- // one captured at drag start: the live scale shrinks as the rectangle grows,- // and reading it mid-drag turns each pointer step into a larger size step — a- // runaway feedback loop.+ // Centered resize doubles pointer displacement; freeze the drag-start scale to avoid feedback.const dimsFromPointer = (event: { clientX: number; clientY: number }): Dimensions | null => {const drag = dragRef.current;@@ -359,9 +345,7 @@ export const GenerateDimensionFields = ({});};- // The lock shows whether the ratio is held at all, preset or captured, so a- // chosen preset reads as locked and unlocking always returns to Free. Locking- // captures the current ratio, named by its preset when it matches one.+ // Presets imply a lock; free ratios capture the current ratio. Unlocking selects Free.const toggleLock = () => {if (isRatioConstrained) {commitSettings({@@ -406,8 +390,7 @@ export const GenerateDimensionFields = ({commitSettings(calculateNewSize(ratio, optimal * optimal, dimensionGrid));};- // "Recommended" is what the optimize action would produce for the live ratio:- // the model's optimal pixel budget reshaped to the current proportions.+ // The recommendation reshapes the model's pixel budget to the live aspect ratio.const recommendedDimensions = calculateNewSize(dimensionRatio,dimensions.optimal * dimensions.optimal,@@ -431,8 +414,7 @@ export const GenerateDimensionFields = ({</>);- // The model's optimal side is the stop worth landing on; the recommended- // size for the live ratio is what "Set optimal size" would produce.+ // The optimal-side stop is scalar; recommended dimensions preserve the live ratio.const dimensionField = (key: 'height' | 'width') => (<ScrubberFielddefaultValue={modelDefaults?.[key]}@@ -483,8 +465,7 @@ export const GenerateDimensionFields = ({</Box></HStack></GenerateFieldContextMenu>- {/* The preset row mirrors the dimension rows: the select fills the value- column and the swap sits in the lock's column beneath it. */}+<HStack alignItems="center" gap="1"><AspectRatioSelectfallbackRatio={dimensionRatio}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsxindex 391f576f35..3f4ae4cdcd 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsx@@ -24,11 +24,6 @@ interface GenerateGuidanceSectionProps {onCommitImmediate: (patch: Partial<GenerateSettings>) => void;}-/**- * Creative conditioning in one place: reference images and concepts (LoRAs) are- * the same kind of decision — a visual influence with a weight and a toggle —- * so they share a section instead of two sibling accordions.- */export const GenerateGuidanceSection = ({loraModels,models,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.tsxindex 6f0b38fdc3..33e53bd9fb 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.tsx@@ -19,11 +19,6 @@ import {settingsMatchModelDefaults,} from './shared/modelDefaultSettings';-/**- * Widget-header actions: the preset library (save/apply/rename/delete named- * settings snapshots) and reset-every-model-governed-setting-to-model-defaults.- * They sit in the header because they act on the whole panel, not one zone.- */export const GenerateHeaderActions = () => {const { t } = useTranslation();const ui = useGenerationUi();@@ -49,8 +44,7 @@ export const GenerateHeaderActions = () => {return;}- // Flush pending debounced edits first so this patch lands on top of them;- // the patch only carries model-governed keys, so flushed prompt edits survive.+ // Flush before patching so reset preserves pending prompt edits.flushGenerateDrafts();ui.settings.patchGenerateSettings(getModelDefaultsPatch(settings, selectedModel, vaeModels), projectId);};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateModelCard.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateModelCard.tsxindex 2b5bd675a1..a894ca69eb 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateModelCard.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateModelCard.tsx@@ -28,13 +28,7 @@ interface GenerateModelCardProps {onCommitSettings: (nextSettings: GenerateSettings) => void;}-/**- * The panel's tier-1 surface: the model choice, what that model offers, and- * every model-availability state — loading, backend errors, and the empty- * catalog — local to the choice that causes them. Readiness/validation is- * deliberately absent here (the invocation controls own it), and the preset- * library and reset-all live in the widget header.- */+/** This owner checks model availability; invocation readiness is validated elsewhere. */export const GenerateModelCard = ({isLoadingModels,loadError,@@ -48,9 +42,7 @@ export const GenerateModelCard = ({const ui = useGenerationUi();const { openManager } = ui.models;const openManagerForMainModels = useCallback(() => openManager({ modelType: 'main' }), [openManager]);- // A switch that clears incompatible settings waits behind a confirm. Only the- // model is held; the transition is recomputed against live settings on- // confirm, and the labels shown come from a preview run of the same move.+ // Retain only the selected model and recompute against live settings on confirmation.const [pendingSwitchModel, setPendingSwitchModel] = useState<GenerateModelConfig | null>(null);const pendingSwitchClearedLabels = useMemo(() => {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsxindex 0331f222dc..5e7263f8c6 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx@@ -40,12 +40,7 @@ const SEARCH_VISIBLE_MIN_PRESETS = 6;type PresetDialogState = { mode: 'save' } | { mode: 'rename'; preset: GeneratePresetRecord };-/**- * "These settings are still this preset" must ignore what applying a preset- * does not write (`getGenerateFormCommitPatch` drops `batchCount`) and what is- * presentation or volatile: prompt-box heights, the template view mode, and- * the seed unless it is held fixed — random draws it, stepping moves it.- */+/** Ignore presentation and non-applied keys, including seed unless its mode is fixed. */const getPresetComparisonKey = (settings: GenerateSettings): string => {const comparable: Record<string, unknown> = { ...settings };@@ -98,8 +93,7 @@ const PresetRow = ({<Text flex="1" fontSize="xs" fontWeight={isActive ? '600' : undefined} minW="0" textAlign="start" truncate>{preset.label}</Text>- {/* The applied marker: a check, not a filled row — the popover- surface stays quiet and the accent stays an accent. */}+{isActive ? <Icon as={CheckIcon} boxSize="3.5" color="accent.fg" flexShrink={0} /> : null}</button></Row>@@ -128,11 +122,7 @@ const PresetRow = ({);};-/**- * The preset library, treated like the wildcards panel: a searchable managed- * list rather than a bare menu. Applying reconciles the snapshot against the- * current model catalog through the widget's own resolve + patch path.- */+/** Catalog changes use the same resolve/patch path as model selection. */export const GeneratePresetsPopover = () => {const { i18n, t } = useTranslation();const ui = useGenerationUi();@@ -140,8 +130,7 @@ export const GeneratePresetsPopover = () => {const [searchTerm, setSearchTerm] = useState('');const [dialog, setDialog] = useState<PresetDialogState | null>(null);const [pendingDelete, setPendingDelete] = useState<GeneratePresetRecord | null>(null);- // The Tooltip and the Popover share the trigger element, and each machine- // wants to own its id; sharing one keeps the popover anchored.+ // Tooltip and Popover must share the trigger ID to preserve anchoring.const triggerId = useId();const triggerIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);@@ -158,8 +147,7 @@ export const GeneratePresetsPopover = () => {return term ? presets.filter((preset) => preset.label.toLowerCase().includes(term)) : presets;}, [presets, searchTerm]);- // Normalization builds its object in one code path, so serialized equality- // of the comparison keys is a faithful match test.+ // Serialized equality requires canonical key order.const presetKeys = useMemo(() =>presets.map((preset) => {@@ -208,9 +196,6 @@ export const GeneratePresetsPopover = () => {return;}- // Reconcile against the current catalog (models installed or removed- // since the preset was saved), then commit through the same resolve +- // patch path the widget's own model selection takes.const result = getGenerateModelSelectionResult({ currentValues: normalized, model, models });const resolved = resolveGenerateWidgetValues({ models, storedValues: { ...result.settings, model } });@@ -278,8 +263,6 @@ export const GeneratePresetsPopover = () => {><Tooltip content={triggerLabel} ids={triggerIds}><Popover.Trigger asChild>- {/* The applied preset's name rides beside the icon while the- current settings still match it, like the dynamic-prompts count. */}<IconButtonaria-label={triggerLabel}color="fg.muted"diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsxindex 2f86a4b5a9..ae631e078c 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx@@ -54,9 +54,7 @@ void i18n.use(initReactI18next).init({},widgets: {generate: {- // Verbatim from `public/locales/en.json`: Ideogram 4's overrides really are labelled- // "Steps" and "Guidance", the same as the shared controls beside them. Inventing- // distinct names here would hide that from the one test that renders both at once.+ // Retain duplicate labels in fixtures so tests expose real naming collisions.ideogram4ColorHelp: 'Comma-separated color terms folded into the caption.',ideogram4ColorPalette: 'Color palette',ideogram4GuidanceScale: 'Guidance',@@ -80,12 +78,7 @@ void i18n.use(initReactI18next).init({},});-/**- * FLUX Fill's own recommendation is `guidance=30`, well past the guidance slider's practical top of- * 10. That is the case the scrubber's looser `inputMax` exists for: without it the field- * clamps to the slider's bound the first time it loses focus, and the model's own default is gone- * before the user has touched anything.- */+/** FLUX Fill defaults to guidance 30, above its track ceiling of 10. */const fluxFillModel: MainModelConfig = {base: 'flux',default_settings: { cfg_scale: 1, guidance: 30 },@@ -260,10 +253,7 @@ describe('GenerateRenderSection seed field', () => {});});-/**- * The shared steps and guidance controls are scrubbers, whose slider is named by `aria-labelledby`;- * Ideogram 4's overrides are still sliders named by `aria-label`. One resolver reads both.- */+/** Resolve names through both aria-labelledby and aria-label. */const sliderName = (slider: Element): string | null => {const labelId = slider.getAttribute('aria-labelledby');@@ -296,8 +286,7 @@ const pressOnSlider = (label: string, key: string) =>settle(() => guidanceSlider(label)?.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key })));describe('GenerateRenderSection guidance field', () => {- // The guidance label and the model's stored guidance both come from the served table now,- // and the resolver returns nothing without it -- the field would render empty.+ // Seed capabilities so policy resolution is nonempty.seedArchitectureCapabilities();it('does not clamp a model default above the slider track when the editor closes', async () => {@@ -307,26 +296,21 @@ describe('GenerateRenderSection guidance field', () => {await openAndBlurEditor();- // The commit is the observable, not the shown value: the field is controlled, so the value- // prop puts 30 back either way and only the caller sees the clamp. Dropping inputMax makes- // this a commit of 10, which is then the value every subsequent graph is compiled with.+ // Assert committed values; controlled props can hide unintended clamping.expect(onCommit).not.toHaveBeenCalled();});it('still holds the guidance track itself to its practical range', async () => {const onCommit = await render(fluxFillModel);- // The track ends at 10 even while the value sits past it: End lands on the track's end, not- // on the input ceiling the model default needed.+ // End targets the slider track, not the input ceiling.await pressOnSlider('Guidance', 'End');expect(onCommit).toHaveBeenCalledWith({ cfgScale: 10 });});it('clamps a typed guidance to the ceiling the architecture declares', async () => {- // The reported failure, from the other side: a project that stored FLUX Fill's 30 and then- // selected a FLUX.2 model. With a fixed input maximum of 100 the 30 persisted and was submitted- // to `flux2_denoise.guidance` (le=20), which rejects it at enqueue with nothing said in the UI.+ // Exercise the FLUX Fill-to-FLUX.2 bound transition.const onCommit = await render(flux2Model, { cfgScale: 30 });await openAndBlurEditor();@@ -335,8 +319,7 @@ describe('GenerateRenderSection guidance field', () => {});it('starts the guidance track at the floor the architecture declares', async () => {- // `ernie_image_denoise.guidance_scale` is ge=1: scrubbing to 0, or typing 0.5, used to persist- // and be forwarded unchanged by graph.ts.+ // ERNIE guidance has a minimum of 1.const onCommit = await render(ernieModel, { cfgScale: 0.5 });await openAndBlurEditor('CFG');@@ -351,16 +334,12 @@ describe('GenerateRenderSection guidance field', () => {});it('holds the Ideogram 4 overrides to their own node bounds', async () => {- // Not the shared control: `ideogram4_denoise` takes preset-derived optional overrides whose- // constraints sit on the numeric branch of an `anyOf` -- guidance ge=1/le=20, steps ge=2, mu- // ge=-4/le=4. The guidance control offered 0 and the mu control 0..10, both forwarded verbatim.+ // Ideogram override bounds come from numeric anyOf branches.await render(ideogram4Model, { ideogram4GuidanceScale: 5, ideogram4Mu: 1, ideogram4Steps: 48 });const ranges = (label: string) =>slidersNamed(label).map((slider) => [slider.getAttribute('aria-valuemin'), slider.getAttribute('aria-valuemax')]);- // Two per name: the shared control first, then Ideogram's override. They carry the same- // accessible name in the product, which is its own (pre-existing) problem — asserting both- // ranges at once is what keeps this test honest about which is which.+ // Address shared guidance before the override; both controls have the same accessible label.expect(ranges('Guidance')).toEqual([['1', '10'],['1', '20'],@@ -373,9 +352,7 @@ describe('GenerateRenderSection guidance field', () => {});it('names the broken bound on the field, not only in the Invoke button tooltip', async () => {- // Model selection clamps, so this is what a recalled or previously persisted value looks like:- // the field shows 30, Invoke is disabled elsewhere, and without this the only explanation is a- // tooltip on a button in another panel.+ // Show local errors for persisted/recalled values that bypass selection clamps.await render(flux2Model, { cfgScale: 30 });expect(host?.querySelector('[role="alert"]')?.textContent).toBe('Guidance must be at most 20 for FLUX.2 dev.');@@ -390,8 +367,7 @@ describe('GenerateRenderSection guidance field', () => {});it('drops the model-default mark the guidance track cannot place', async () => {- // FLUX Fill's default of 30 has no position on a track that stops at 10. Steps keeps its own- // mark (30 of 100), so this is the out-of-range mark going, not marks in general.+ // Exclude off-track default marks while retaining in-range marks.await render(fluxFillModel);const [stepsFrame, guidanceFrameElement] = [...(host?.querySelectorAll('[data-scope="scrubber"]') ?? [])];@@ -401,9 +377,7 @@ describe('GenerateRenderSection guidance field', () => {});describe('GenerateRenderSection before the capability table arrives', () => {- // No `seedArchitectureCapabilities()` here on purpose. Generation is blocked outright without the- // table, so the fallback guidance range is deliberately the widest one: tightening it would clamp- // a stored value the user legitimately had while the capabilities are still in flight.+ // Use wide fallback bounds while generation is gated to avoid premature destructive clamps.it('keeps the guidance field permissive rather than guessing a bound', async () => {const onCommit = await render(fluxFillModel, { cfgScale: 30 });diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsxindex 4b0f80189f..f3a8a073d5 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsx@@ -39,14 +39,10 @@ import { useDynamicPrompts } from './useDynamicPrompts';const STEPS_SLIDER_MAX = 100;const formatPercent = (value: number): string => `${value}%`;-/** The guidance/CFG slider's practical range — a UI choice about the track, not a rule. FLUX Fill- * recommends 30, which is off the track but a real value, so the number input keeps its own looser- * bound; without it the field clamps the model's own default away the first time it is focused.- *- * Where the architecture declares a ceiling (`policy.ui.guidanceMax`, e.g. `flux2_denoise.guidance`- * is `le=20`) that ceiling wins over this local cap, and where it declares none the local cap stays- * — `flux_denoise.guidance` genuinely has no upper bound. The floor comes from the architecture- * either way: 0 for most, 1 for the samplers whose node is `ge=1`. */+/**+ * Slider tracks are practical ranges, distinct from input/validation bounds; FLUX Fill's default 30 exceeds its+ * track.+ */const GUIDANCE_SLIDER_MAX = 10;const GUIDANCE_INPUT_MAX = 100;@@ -57,10 +53,7 @@ interface GenerateRenderSectionProps {onCommitImmediate: (patch: Partial<GenerateSettings>) => void;}-/**- * Ideogram 4 presets fix a step count and guidance schedule. The labels carry the step count- * because the backend's identifiers (`V4_QUALITY_48`) are otherwise opaque in a picker.- */+/** Labels expose step counts hidden in backend preset IDs. */const IDEOGRAM4_PRESET_LABELS: Record<Ideogram4SamplerPreset, string> = {V4_DEFAULT_20: 'Default (20 steps)',V4_QUALITY_48: 'Quality (48 steps)',@@ -71,10 +64,6 @@ const IDEOGRAM4_PRESET_COLLECTION = createListCollection({items: IDEOGRAM4_SAMPLER_PRESETS.map((value) => ({ label: IDEOGRAM4_PRESET_LABELS[value], value })),});-/**- * Family-specific sampling parameters, co-located with the shared sampling- * controls they modify rather than segregated into a "model family" bucket.- */const Ideogram4SamplingFields = ({ onCommit, settings }: Pick<GenerateRenderSectionProps, 'onCommit' | 'settings'>) => {const { t } = useTranslation();@@ -95,10 +84,7 @@ const Ideogram4SamplingFields = ({ onCommit, settings }: Pick<GenerateRenderSect}}/></Field>- {/*- Steps, guidance and mu override the preset. Null means "let the preset decide", so each- keeps its own enable switch rather than using a sentinel value in the slider's range.- */}+ {/* Null inherits the preset; switches avoid numeric sentinels. */}<Field label={t('widgets.generate.ideogram4Steps')} helpText={t('widgets.generate.ideogram4PresetDerived')}><GenerateToggleSwitchchecked={settings.ideogram4Steps !== null}@@ -174,10 +160,7 @@ const Ideogram4SamplingFields = ({ onCommit, settings }: Pick<GenerateRenderSect);};-/**- * A14B runs two experts across the schedule. Null reuses the main guidance for the- * low-noise half, which is the backend's own default.- */+/** Null low-noise guidance inherits main guidance. */const WanLowNoiseGuidanceField = ({onCommit,settings,@@ -245,16 +228,11 @@ const Krea2SeedVarianceFields = ({ onCommit, settings }: Pick<GenerateRenderSect);};-/**- * The shared seed row, with the executed seeds of recent runs underneath —- * each behind its result, so a seed stops being a magic number and becomes- * "that image's recipe". Clicking one pins it, switching to fixed mode.- */+/** Clicking an executed seed switches to fixed mode. */const SeedField = ({ onCommit, settings }: Pick<GenerateRenderSectionProps, 'onCommit' | 'settings'>) => {const { t } = useTranslation();const { seedHistory } = useGenerationUi().queueInsights;- // The same query the topbar observes, so a prompt set counts its seeds the- // way the batch will without a second expansion request or cache entry.+ // Share expansion queries so seed counts match submission without duplicate fetches.const expansion = useDynamicPrompts(getEffectivePrompts(settings).positivePrompt, getDynamicPromptsConfig(settings));return (@@ -299,11 +277,6 @@ const SeedField = ({ onCommit, settings }: Pick<GenerateRenderSectionProps, 'onC);};-/**- * Sampling and variation — split out of the model zone because how a model- * samples is not which model it is. Family-specific parameters render beside- * the shared control they modify.- */export const GenerateRenderSection = ({onCommit,onCommitImmediate,@@ -315,15 +288,10 @@ export const GenerateRenderSection = ({const policy = getGenerationModelPolicy(selectedModel, settings);const familyBase = selectedModel && selectedModel.type !== 'external_image_generator' ? selectedModel.base : null;- // The node's ceiling caps the number input where the architecture declares one; the slider's own- // track never grows past its practical range, but it does shrink if an architecture ever declares- // a ceiling below it -- and never below its own floor, since the bounds are served and can change- // without a frontend release.+ // Cap both input and track at the architecture ceiling without crossing the floor.const guidanceInputMax = policy.ui.guidanceMax ?? GUIDANCE_INPUT_MAX;const guidanceSliderMax = Math.max(policy.ui.guidanceMin, Math.min(GUIDANCE_SLIDER_MAX, guidanceInputMax));- // A value the model switch did not clamp -- recalled from an image, or persisted before the- // architecture's bounds changed. Invoke is already disabled for it; without this the only cue is- // that button's tooltip, three collapsed sections away from the field holding the bad value.+ // Validate recalled/persisted values inline because they bypass model-selection clamps.const guidanceError = selectedModel ? getGuidanceBoundReason(selectedModel, settings.cfgScale) : null;const commitNumber = (key: 'cfgScale' | 'steps', value: number) => {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.browser.test.tsxindex f3d2f654fa..d07e660daa 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.browser.test.tsx@@ -23,10 +23,6 @@ vi.mock('react-i18next', () => {return { useTranslation: () => ({ t: (key: string) => messages[key] ?? key }) };});-/**- * The form has its own suite; what this view owns is the capability gate and the values it hands- * down, so the stub reports exactly those two.- */vi.mock('./GenerateSettingsForm', () => ({GenerateSettingsForm: ({selectedModel,@@ -68,11 +64,7 @@ const STORED_MODEL: GenerationModelCatalogItem = {type: 'main',} as GenerationModelCatalogItem;-/**- * Catalog and stored values are pinned module constants on purpose: the project store hands the- * view the same references on every render, which is what let a resolve attempted before the- * capability table arrived stay cached after the retry that fixed it.- */+/** Stable fixture references preserve memoization across capability arrival. */const CATALOG: readonly GenerationModelCatalogItem[] = [OTHER_MODEL, STORED_MODEL];const STORED_VALUES = {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsxindex e092a4f8b5..c95bf29c19 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx@@ -39,10 +39,7 @@ export const GenerateWidgetView = () => {() => models.filter((model): model is ModelConfig & LoraModelConfig => isLoraModelConfig(model)),[models]);- // The resolver reads the architecture table from the core registry and fails closed while it is- // absent, so the load status is a real input here: without it a resolve attempted before the- // table arrives would be cached as `null` and survive the retry that fixed it, leaving a saved- // project with an empty model picker.+ // Include capability revision/status so a cached null resolves again after loading.const resolved = useMemo(() => (capabilitiesStatus === 'loaded' ? resolveGenerateWidgetValues({ models, storedValues }) : null),[capabilitiesStatus, models, storedValues]@@ -50,8 +47,7 @@ export const GenerateWidgetView = () => {const settings =resolved?.values ?? normalizeGenerateSettings(storedValues) ?? getDefaultGenerateSettings(supportedModels[0]);const selectedModel = resolved?.values.model;- // The click flips the status to `loading` synchronously. Keeping the failure surface mounted for- // the retry it started is what keeps the button -- and the user's focus -- in place.+ // Keep the failure surface mounted during retry to preserve button focus.const isRetrying = hasRequestedRetry && capabilitiesStatus === 'loading';// Set by the click, consumed when the form the retry revealed mounts.@@ -64,9 +60,7 @@ export const GenerateWidgetView = () => {focusHandoffPending.current = true;setHasRequestedRetry(true);- // The request belongs to this retry. Once it settles, a later reload -- an account switch, a- // retry started from another panel -- is not this widget's: no failure surface while it loads,- // and no focus taken when it lands. The form may already have mounted and taken the handoff.+ // Only the initiating retry owns focus; unrelated later reloads must not take it.void ensureArchitectureCapabilitiesLoaded().then(() => {focusHandoffPending.current &&= getArchitectureCapabilitiesSnapshot().status === 'loaded';setHasRequestedRetry(false);@@ -107,10 +101,7 @@ export const GenerateWidgetView = () => {[projectId, ui]);- // Every field below is prefilled from architecture policy and is editable, so rendering the form- // before the backend's table arrives would offer generic fallbacks as if they were the model's- // own -- and a single keystroke would commit them. App boot kicks the fetch, so this is one round- // trip in practice.+ // Gate the form so edits cannot persist fallback architecture defaults.if (capabilitiesStatus !== 'loaded') {if (capabilitiesStatus === 'error' || isRetrying) {return (diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsxindex 7dc250d223..2458073116 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx@@ -40,11 +40,7 @@ export interface GeneratePresetRecord {values: Record<string, unknown>;}-/**- * Generation's UI port, grouped into sub-ports by backing concern. The context- * is a dependency-direction port (the feature may not import workbench), not a- * test seam; no second adapter is expected.- */+/** This port keeps Generation independent of Workbench. */export interface GenerationUiAdapter {CanvasGenerationSections: ComponentType;account: {@@ -58,11 +54,7 @@ export interface GenerationUiAdapter {canManageSharedSystemPrompts: boolean;};gallery: {- /**- * Locate one image in the Gallery grid and put it in front of the user:- * the Gallery and Preview widgets come on screen and the grid lands on the- * image's board, page, and cell.- */+ /** Raise Gallery/Preview and locate the image's board, page, and cell. */findImage(imageName: string): void;selectedImage: GenerationSelectedImage | null;touchImages(): void;@@ -74,10 +66,7 @@ export interface GenerationUiAdapter {error: string | null;getBaseColorPalette(base: string): string;getBaseLabel(base: string): string;- /**- * Navigates to the model manager, which opens on Add Models by default;- * `modelType` pre-filters its starter catalog to the missing kind.- */+ /** Apply the optional model-type filter when opening Add Models. */openManager(options?: { modelType?: string }): void;status: 'error' | 'idle' | 'loaded' | 'loading';};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/generateDebounce.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/generateDebounce.test.tsindex f145f113ca..a0c390e6ee 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/generateDebounce.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/generateDebounce.test.ts@@ -5,16 +5,7 @@ import { describe, expect, it } from 'vitest';import { applyGenerateSettingsUpdate, mergeGenerateSettingsUpdate } from './generateDebounce';-/**- * A pending update is an updater FUNCTION, and the form runs it twice: once- * against the draft the user sees (`commit`), then again against the freshly- * committed settings when the debounce flushes. That is what lets a pending- * edit survive a concurrent external write — but it also means an updater has- * to be pure. An updater that mints an id inside its own body produces a- * DIFFERENT id on each run, so the entry the user is looking at is not the- * entry that gets committed, and any later edit keyed to the rendered id is- * silently dropped at flush.- */+/** Updaters run for both draft and flush; mint IDs outside them. */const buildSettings = (referenceImages: GenerateReferenceImage[] = []): GenerateSettings =>({ referenceImages }) as unknown as GenerateSettings;@@ -41,8 +32,7 @@ describe('pending generate settings updates', () => {expect(idsOf(draft)).toEqual(['a', 'minted-1']);expect(idsOf(committed)).toEqual(['a', 'minted-2']);- // The hazard this guards: a reorder queued behind that append is keyed to- // the id the CARD renders under, which no longer exists at flush time.+ // The rendered ID must match the flushed ID for reordering to work.const chained = mergeGenerateSettingsUpdate(pending, (settings) => ({...settings,referenceImages: [...moveReferenceImage(settings.referenceImages, 'minted-1', -1)],@@ -63,8 +53,6 @@ describe('pending generate settings updates', () => {referenceImages: [...moveReferenceImage(settings.referenceImages, 'hoisted', -1)],}));- // Same chain, applied to draft and to the committed settings: both agree,- // and the queued reorder actually lands.expect(idsOf(applyGenerateSettingsUpdate(buildSettings([entry('a')]), chained))).toEqual(['hoisted', 'a']);expect(idsOf(applyGenerateSettingsUpdate(buildSettings([entry('a')]), chained))).toEqual(['hoisted', 'a']);});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/generateDraftRegistry.ts b/invokeai/frontend/webv2/src/features/generation/ui/generateDraftRegistry.tsindex 971465fd4a..2229c6c469 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/generateDraftRegistry.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/generateDraftRegistry.ts@@ -1,8 +1,4 @@-/**- * @deprecated Import the source-agnostic Platform registry from- * `@platform/react/draftRegistry`. This wrapper only preserves Generation's- * established public names while callers migrate.- */+/** @deprecated Import the source-agnostic registry from @platform/react/draftRegistry. */export {flushWorkbenchDrafts as flushGenerateDrafts,useRegisterDraftFlusher as useRegisterGenerateDraftFlusher,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsxindex 8b58962a3d..ffa496fda5 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx@@ -108,8 +108,6 @@ describe('dynamic prompts in the positive prompt field', () => {});it('is a labeled primary at rest, and widens only to carry a count', async () => {- // A labeled button rather than a bare icon; the expansion count appears- // beside the label once the prompt is dynamic.await render('a plain cat');const plain = findButton().getBoundingClientRect();diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsxindex 09700e76c1..b4305e0446 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx@@ -65,8 +65,6 @@ export const DynamicPromptsButton = ({const tooltip = expansion.isDynamic? t('widgets.generate.dynamicPrompts.showPrompts'): t('widgets.generate.dynamicPrompts.noDynamicSyntax');- // Quiet states only: an em-dash while the expansion is in flight, an error tint- // when it failed. No spinner, no animation on a control this small.const countLabel = !expansion.isDynamic ? null : expansion.isLoading ? '—' : String(expansion.count);return (@@ -80,8 +78,6 @@ export const DynamicPromptsButton = ({><Tooltip content={tooltip} ids={popoverIds}><Popover.Trigger asChild>- {/* A labeled primary rather than a bare icon; the expansion count- rides beside the label once the prompt is dynamic. */}<IconButtonaria-label={t('widgets.generate.dynamicPrompts.showPrompts')}color={expansion.isError ? 'fg.error' : undefined}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsxindex 6fce82308c..d0c31ceded 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx@@ -13,8 +13,7 @@ import { userEvent } from 'vitest/browser';const parseDynamicPrompts = vi.hoisted(() => vi.fn());vi.mock('@features/generation/data/promptUtilities', () => ({ parseDynamicPrompts }));-// The wildcards tab reports delete failures through Generation's UI port, which-// only the app composes.+// Provide the Generation UI port for wildcard error reporting.vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({...(await importOriginal<object>()),useGenerationUi: () => ({ notifications: { error: vi.fn(), info: vi.fn(), reportError: vi.fn() } }),@@ -39,10 +38,7 @@ const BASE_CONFIG: DynamicPromptsConfig = {seedBehaviour: 'per-iteration',};-/**- * Renders with real state, so a control that reflects its own value (a segmented- * control does) can actually be toggled back and forth.- */+/** Use stateful controlled values so toggles can round-trip. */const render = async (onChange: (patch: Partial<DynamicPromptsConfig>) => void = vi.fn(), isSeedFixed = false) => {host = document.createElement('div');document.body.append(host);@@ -81,8 +77,7 @@ const openPopover = async () => {await act(async () => {await userEvent.click([...host!.querySelectorAll('button')].at(-1)!);});- // The popover opens with a scale transform, and getBoundingClientRect includes- // transforms — measuring before it settles reports every box ~5% short.+ // Wait for scale animation before measuring geometry.await act(async () => {await new Promise((resolve) => {window.setTimeout(resolve, 300);@@ -133,10 +128,7 @@ describe('dynamic prompts popover controls', () => {});it('switches seed behaviour without tearing down the widget', async () => {- // Regression: a Chakra Select here threw `r.options is not iterable` from- // syncSelectElement as the popover opened, taking the Generate widget down- // with it. The seed choice is a switch now, which has no hidden native- // select to sync.+ // Cover hidden native-select synchronization failures.const onChange = vi.fn();await render(onChange);@@ -158,9 +150,7 @@ describe('dynamic prompts popover controls', () => {});it('sends a click on the seed label to the switch, not the number input', async () => {- // Regression: Chakra derives the switch's label `for` from its own id- // counter, which collided with the number input beside it, so clicking the- // label focused Max prompts instead of toggling the switch.+ // Clicking the label must toggle its own switch, not a sibling number input.const onChange = vi.fn();await render(onChange);@@ -171,10 +161,7 @@ describe('dynamic prompts popover controls', () => {const hiddenInput = switchRoot.querySelector<HTMLInputElement>('input[type="checkbox"]')!;const numberInput = document.querySelector<HTMLInputElement>('[data-scope="number-input"][data-part="input"]')!;- // Whether the generated ids actually collide depends on how many other- // controls rendered first, so this asserts the condition that caused it —- // two controls sharing an id — rather than relying on the ordering that- // happened to trip it in the app.+ // Assert ID uniqueness directly, independently of prior render order.expect(hiddenInput.id).toBeTruthy();expect(hiddenInput.id).not.toBe(numberInput.id);@@ -187,8 +174,7 @@ describe('dynamic prompts popover controls', () => {});it('keeps the settings row the same height in either mode', async () => {- // The shuffle button only applies to a random sample, so it is always- // rendered and merely hidden; switching modes must not reflow the row.+ // Hidden shuffle still reserves space across modes.const onChange = vi.fn();await render(onChange);@@ -201,8 +187,8 @@ describe('dynamic prompts popover controls', () => {await act(async () => {await userEvent.click(document.querySelector<HTMLElement>('[data-scope="menu"][data-part="trigger"]')!);});- // A dispatched click rather than userEvent: the menu animates open, and- // userEvent waits for the element to be "stable" before it will click.+ // Dispatch clicks to test wiring without animation-stability waits; this does not test real pointer+ // actionability.await act(async () => {([...document.querySelectorAll('[data-scope="menu"][data-part="item"]')].at(-1) as HTMLElement).click();await Promise.resolve();@@ -220,13 +206,10 @@ describe('dynamic prompts popover controls', () => {const numberInput = popover.querySelector<HTMLInputElement>('[data-scope="number-input"][data-part="input"]')!;const numberLabel = popover.querySelector<HTMLLabelElement>(`label[for="${numberInput.id}"]`);- // The visible label is wired to the input rather than a detached bit of- // text with an aria-label duplicating it.expect(numberLabel, 'number input should have an associated label').toBeTruthy();expect(numberInput.getAttribute('aria-label')).toBeNull();- // A <label for> cannot name a button, so the trigger is named by the field- // label plus its own value.+ // The accessible name combines the field label and selected value.const trigger = popover.querySelector<HTMLElement>('[data-scope="menu"][data-part="trigger"]')!;const namedBy = (trigger.getAttribute('aria-labelledby') ?? '').split(' ')@@ -236,9 +219,7 @@ describe('dynamic prompts popover controls', () => {});it('anchors the mode menu to its trigger', async () => {- // Regression: setting an explicit id on the trigger left zag unable to find- // the element, so the positioner had nothing to anchor to and the menu- // rendered at the top-left of the screen.+ // Supply IDs through Zag so popup anchoring resolves the trigger.await render();await openPopover();@@ -278,8 +259,7 @@ describe('dynamic prompts popover controls', () => {await userEvent.click(tabButton('wildcards')!);});- // The summary badge and the "New wildcard" button sit in the same slot on- // either tab, so switching tabs must not change the header's shape.+ // Header geometry must remain equal across tabs.expect(headerControl()).toBe(summaryHeight);});});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsxindex 3d3b3038a3..3333dc5ffc 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx@@ -23,11 +23,9 @@ import { useTranslation } from 'react-i18next';/** Rendering every row of a 10,000-prompt expansion would cost more than it tells the user. */const MAX_PREVIEW_ROWS = 200;const TABULAR_NUMS = { fontVariantNumeric: 'tabular-nums' } as const;-// The rows sit on the popover's `bg.muted` surface, where the row recipe's-// `bg.muted/60` hover is invisible — hover needs the next surface step.+// Use a hover fill distinct from the popover's muted surface.const PROMPT_ROW_HOVER_PROPS = { bg: 'bg.emphasized/60' } as const;-// The preview text is the row's whole point; a disabled row loses its-// affordances (row-recipe hover, dimming, not-allowed cursor), not its ink.+// Keep preview text readable while interactions are disabled.const DISABLED_PROMPT_ROW_PROPS = { cursor: 'default', opacity: 1 } as const;const NO_HOVER_PROPS = { bg: 'transparent' } as const;const MENU_POSITIONING = { placement: 'bottom-start' } as const;@@ -54,14 +52,11 @@ export const DynamicPromptsPanel = ({}) => {const { t } = useTranslation();const { onChange } = config;- // Chakra derives the switch's label/input ids from its own counter, which can- // collide with the number input beside it and send label clicks to the wrong- // control. Explicit ids keep them apart.+ // Explicit sibling input IDs prevent labels from targeting the wrong control.const seedSwitchId = useId();const modeFieldId = useId();const modeTriggerId = useId();- // A <label for> cannot name a button, so the trigger is named by the field's- // label plus its own text: "Mode" + "All combinations".+ // aria-labelledby combines the field label and value for the composite trigger's accessible name.const modeLabelledBy = `${modeFieldId}-label ${modeTriggerId}`;const modeMenuIds = useMemo(() => ({ trigger: modeTriggerId }), [modeTriggerId]);const seedSwitchIds = useMemo(() => ({ hiddenInput: seedSwitchId, label: `${seedSwitchId}-label` }), [seedSwitchId]);@@ -103,9 +98,7 @@ export const DynamicPromptsPanel = ({return (<Stack gap="2.5"><PromptPanelHeader label={t('widgets.generate.dynamicPrompts.title')}>- {/* Monospace rather than inline icons: lucide's X is a close glyph, not a- times sign, and there is no arithmetic multiply in the set. Mono with- tabular figures also stops the badge jittering as the counts change. */}+ {/* Use a literal multiplication sign and tabular figures. */}<Badgecolor="fg.muted"css={TABULAR_NUMS}@@ -128,8 +121,7 @@ export const DynamicPromptsPanel = ({<HStack align="end" gap="2"><Field id={modeFieldId} label={t('widgets.generate.dynamicPrompts.mode')}>- {/* A menu rather than a Select: Chakra's Select renders a hidden native- select whose sync throws inside this popover. */}+ {/* Use a menu to avoid Select's hidden-native synchronization failure. */}<Menu.Root ids={modeMenuIds} positioning={MENU_POSITIONING}><Menu.Trigger asChild><Button@@ -227,8 +219,7 @@ export const DynamicPromptsPanel = ({<DynamicPromptRowkey={`${index}-${prompt}`}index={index}- // Pulling the only expansion in would paste back what the prompt- // box already says; the row stays a plain preview then.+ // A single unchanged expansion is read-only because applying it is a no-op.isDisabled={expansion.prompts.length === 1}prompt={prompt}showSyntaxHighlighting={showSyntaxHighlighting}@@ -285,8 +276,7 @@ const DynamicPromptRow = ({{index + 1}</Text><Text as="span" color="fg" fontFamily="mono" fontSize="0.72rem" textAlign="start" wordBreak="break-word">- {/* An expanded prompt has no dynamic syntax left in it, so the useful- colouring here is attention and embeddings — the defaults. */}+ {/* Expanded prompts highlight attention/embeddings only; dynamic syntax has already been consumed. */}<HighlightedPrompt enabled={showSyntaxHighlighting} prompt={prompt} /></Text></button>diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsxindex bc9f379f50..1d9dd65031 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx@@ -82,9 +82,7 @@ export const GeneratePromptFields = ({[onCommitImmediate]);- // View mode is a way of reading one particular template, so it does not carry- // over to the next one. Left on, applying a template made the prompt box go- // read-only the instant it was picked, with no interaction to explain it.+ // Reset view mode when the template changes so prompts do not become unexpectedly read-only.const applyPromptTemplate = useCallback((promptTemplate: PromptTemplateSnapshot | null) =>onCommitImmediate({ promptTemplate, promptTemplateViewMode: false }),@@ -181,8 +179,7 @@ export const GeneratePromptFields = ({onTemplateViewModeChange={setTemplateViewMode}onUsePrompt={usePromptHistoryItem}/>- {/* Active prompt machinery surfaces as a dismissible chip instead of- hidden state that only shows once its panel is opened. */}+{settings.promptTemplate ? (<HStack><Tag.Root size="sm" variant="surface">diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.browser.test.tsxindex 87c93aaff6..a5e02b8466 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.browser.test.tsx@@ -85,9 +85,7 @@ describe('the negative prompt in template view mode', () => {expect(textarea.value).toBe('lowres, blurry');});- // Most templates carry no negative side at all. Treating that empty string as- // something to view made this field read-only for no reason, showing the- // authored text with the merge's trailing space hanging off the end of it.+ // Empty negative templates remain editable.it('stays editable when the template has none', async () => {const textarea = await render('');diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsxindex df3ba13db0..cc305ff78f 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx@@ -79,15 +79,7 @@ export const NegativePromptField = ({[setDraftValue]);- // Same textarea, read-only, as on the positive side — swapping in a different- // component would reset the resizer's mounted height.- //- // An empty string here is a template that carries no negative side, which is- // most of them: `null` means no template at all. Neither has anything to show,- // and treating the empty one as something to view turned this field read-only- // and rendered the authored text with the merge's trailing space hanging off- // it. Gating on the toggle alone would be worse still — view mode can be on- // with no template applied, which leaves the prompt perfectly editable.+ // Preserve textarea identity; read-only requires nonempty negative template content.const viewedTemplatePrompt = isTemplateViewMode && templateNegativePrompt ? templateNegativePrompt : null;const isViewingMerged = viewedTemplatePrompt !== null;@@ -167,10 +159,7 @@ export const NegativePromptField = ({);const exitViewMode = useCallback(() => onTemplateViewModeChange?.(false), [onTemplateViewModeChange]);- // Collapsed, the field is a quiet affordance rather than an empty editor: a- // ghost "Negative prompt…" row, carrying a truncated preview when disabled text exists- // so switched-off terms stay discoverable. Presence reads as enablement while- // `negativePromptEnabled` persists unchanged underneath.+ // Keep collapsed previews discoverable without changing persisted negativePromptEnabled.if (!isEnabled) {return (<Buttondiff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.browser.test.tsxindex 340d9e6688..0be2561cde 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.browser.test.tsx@@ -84,16 +84,13 @@ describe('PromptTriggerPopover', () => {throw new Error('prompt-trigger empty state did not render');}- // With nothing to search or scroll, the popover hugs its empty state: no- // disabled search input, no fixed-height list region holding space open.expect(document.querySelector('[aria-label="Prompt trigger options"]')).toBeNull();expect(document.querySelector('input')).toBeNull();const messageBounds = message.getBoundingClientRect();const actionBounds = action.getBoundingClientRect();- // The hover pill's edge is what reads as the button's edge, so the box —- // not the padded text — lines up with the copy.+ // Measure the hover button box, not padded text, for alignment.expect(Math.abs(messageBounds.left - actionBounds.left)).toBeLessThanOrEqual(1);// One `2.5` stack step, the same rhythm as the image-to-prompt popover.expect(actionBounds.top - messageBounds.bottom).toBeLessThanOrEqual(12);diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsxindex 6bf02ae87e..38ce80fc33 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx@@ -45,11 +45,7 @@ import { useTranslation } from 'react-i18next';const POPOVER_POSITIONING_BOTTOM_END = { placement: 'bottom-end' } as const;const TEXT_LLM_MODEL_TYPES = ['text_llm'];const LLAVA_MODEL_TYPES = ['llava_onevision'];-/**- * The way out of an empty state that needs a model installed. Availability is- * explained inside the popover rather than by disabling the trigger, so the- * dead end always has a door.- */+/** Keep triggers available so missing-model states can explain recovery. */const OpenModelManagerButton = ({ modelType }: { modelType?: string }) => {const { t } = useTranslation();const { openManager } = useGenerationUi().models;@@ -65,15 +61,6 @@ const OpenModelManagerButton = ({ modelType }: { modelType?: string }) => {);};-/**- * Everything the prompt actions know about the applied template, in one prop.- *- * These arrived as six flat props among nineteen, three of them optional and- * one — `hasPromptTemplate` — restating `activeTemplate !== null` at every call- * site. Grouping them says what they are: not six settings but one state, which- * either exists or does not, and which the buttons around it read to decide- * whether the authored prompt is theirs to rewrite.- */export interface PromptTemplateState {/** The applied template, or null when none is. */active: PromptTemplateSnapshot | null;@@ -133,14 +120,11 @@ export const PositivePromptActions = ({positivePrompt={effectivePositivePrompt}showSyntaxHighlighting={showSyntaxHighlighting}onInsertText={onInsertText}- // Picking one expansion writes already-merged text into the authored- // field, so the template has to come off in the same commit or the next- // Invoke would wrap it again.+ // Applying merged expansion text must remove its template atomically.onUsePrompt={template.active ? template.onFlatten : onPositivePromptChangeImmediate}/>) : null}- {/* These three rewrite the authored prompt, which view mode is hiding, so- they stay out of reach until the user is looking at their own text. */}+ {/* Disable authored-text rewrites while merged view hides the authored text. */}<AddPromptTriggerButtonisOpen={isPromptTriggerPickerOpen || template.isViewMode}onOpenPromptTriggerPicker={onOpenPromptTriggerPicker}@@ -162,11 +146,7 @@ export const PositivePromptActions = ({);};-/**- * Picking a template, and switching between the authored text and the merged- * result. The second button appears only once there is a template to look- * through — with nothing applied the two views are the same text.- */+/** Show the view toggle only for an applied template. */const PromptTemplateControls = ({showSyntaxHighlighting,template,@@ -188,10 +168,6 @@ const PromptTemplateControls = ({</>);-/**- * Swaps the prompt box between the authored text and the merged result. Quiet- * states only — the icon changes, nothing tints or animates.- */const TemplateViewModeButton = ({isViewMode,onChange,@@ -222,9 +198,7 @@ export const AddPromptTriggerButton = ({onOpenPromptTriggerPicker: (anchorElement: HTMLElement) => void;}) => {const { t } = useTranslation();- // Not disabled while open like it used to be: the greyed button read as- // broken next to the other action popovers' expanded tint. The guard keeps- // the dismiss-then-click sequence from immediately reopening.+ // Guard dismiss-then-click so the same gesture cannot immediately reopen the popup.const handleClick = useCallback((event: MouseEvent<HTMLButtonElement>) => {if (!isOpen) {@@ -299,8 +273,6 @@ export const PromptTriggerPopover = ({<Popover.Positioner><PopoverContent w="22rem"><Popover.Body p="2.5">- {/* With nothing to search or scroll, the popover hugs its empty- state instead of holding the full list height open. */}{options.length === 0 ? (<PromptTriggerEmptyState />) : (@@ -348,8 +320,6 @@ export const PromptTriggerPopover = ({const PromptTriggerEmptyState = () => {const { t } = useTranslation();- // The same anatomy as the image-to-prompt popover's no-model branch:- // uppercase title, one subtle line, the model-manager button.return (<Stack align="start" gap="2.5"><Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">@@ -419,8 +389,7 @@ const ExpandPromptButton = ({const selectedModel = selectedModelKey ? textLlmModels.find((model) => model.key === selectedModelKey) : null;// The list is behind the popover, so a closed button has nothing to fetch.const systemPrompts = useSystemPrompts({ isEnabled: isOpen });- // Resolved rather than stored: the id outlives the record it points at, and an unselected- // picker should still expand with the first available prompt rather than none at all.+ // Resolve selection at read time after deletion or without an explicit choice.const effectiveSystemPromptId = resolveSelectedSystemPromptId(systemPrompts.prompts, selectedSystemPromptId);const selectedSystemPrompt = systemPrompts.prompts.find((prompt) => prompt.id === effectiveSystemPromptId);@@ -442,8 +411,7 @@ const ExpandPromptButton = ({try {const result = await expandPrompt({- // A structured prompt needs more room than the endpoint's default allows, so the- // selected prompt's own cap travels with it. Omitted when it has none.+ // Forward the selected prompt's optional token cap to expansion.max_tokens: selectedSystemPrompt?.maxTokens ?? undefined,model_key: selectedModel.key,prompt: positivePrompt,@@ -577,8 +545,7 @@ const ImageToPromptButton = ({const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);const llavaModels = models.filter((model) => model.type === 'llava_onevision');const selectedModel = selectedModelKey ? llavaModels.find((model) => model.key === selectedModelKey) : null;- // A drop names the image outright, which is the whole point of dropping one:- // it is how you describe something other than what the gallery has selected.+ // Dropped images take precedence over gallery selection.const image = droppedImage.image ?? selectedImage;const droppedImageName = droppedImage.image?.imageName ?? null;const clearDroppedImage = droppedImage.onClear;@@ -590,10 +557,7 @@ const ImageToPromptButton = ({void ensureModelsLoaded();});- // Dropping onto the prompt box is the gesture that opens this popover. Keyed- // on the name rather than the object so a re-render cannot reopen a popover- // the user has just dismissed; closing clears the drop, so the same image- // dropped twice still reads as two separate gestures.+ // Key gestures by image name and clear on close so repeated drops work without rerenders reopening the popup.useEffect(() => {if (droppedImageName !== null) {// eslint-disable-next-line react/set-state-in-effect@@ -601,9 +565,7 @@ const ImageToPromptButton = ({}}, [droppedImageName]);- // Closing hands the popover back to the gallery selection. Every close route- // goes through here, including the one after a successful run — a controlled- // `open` does not fire `onOpenChange` when it is the code that closes it.+ // Clear dropped input on every close path; controlled close bypasses onOpenChange.const close = useCallback(() => {setIsOpen(false);clearDroppedImage();diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsxindex c9c1f29e9a..c8fb982e40 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx@@ -55,8 +55,7 @@ it('keeps positive prompt actions enabled when stale view mode has no active tem<I18nextProvider i18n={i18n}><QueryClientProvider client={new QueryClient()}><ChakraProvider value={system}>- {/* The prompt box is a gallery-image drop target, so it lives inside- the shell's DndContext wherever it is really rendered. */}+ {/* Match production image-drop ownership with DndContext. */}<DndContext><PositivePromptFieldheightPx={96}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsxindex c15cccce1d..a90eb576a2 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx@@ -41,10 +41,7 @@ interface PositivePromptFieldProps {showSyntaxHighlighting: boolean;value: string;onChange: (value: string) => void;- /**- * Replace the authored prompt with already-merged text and drop the template in- * one commit. Absent on surfaces with no template concept.- */+ /** Replace the prompt and remove its template atomically; omit this action on non-template surfaces. */onFlattenPromptTemplate?: (prompt: string) => void;/** Apply or clear the active template. Absent on surfaces with no templates. */onApplyPromptTemplate?: (template: PromptTemplateSnapshot | null) => void;@@ -101,22 +98,10 @@ export const PositivePromptField = ({[commitDraftValue]);- // View mode keeps the same textarea rather than swapping in a preview- // component: `ResizableTextarea` reads its height once on mount, and the- // element is also what `focusPositivePrompt` and the attention hotkeys target,- // so unmounting it would reset the height and break both.- //- // Note the `&&`: view mode with no template applied leaves the prompt fully- // editable, so gating anything on the toggle alone silently disables it while- // the user is still typing.+ // Preserve textarea identity for sizing/hotkeys; only an actual template makes it read-only.const isViewingMerged = isTemplateViewMode && promptTemplate !== null;- // View mode hides the authored prompt, and the actions that would rewrite it- // are out of reach there — so is the drop that opens one of them.- //- // Destructured rather than kept whole: passing `imageDrop.setNodeRef` straight- // to `ref` makes the compiler read the object it came from as a ref too, and- // every other field of it then counts as a ref access during render.+ // Disable drops while merged view hides authored text. Destructure the ref to keep compiler analysis safe.const {droppedImage,isDragActive: isImageDragActive,@@ -176,9 +161,7 @@ export const PositivePromptField = ({[commitPromptChange, draftValue]);- // Merged against the *draft*, not the committed value: the template lives in the- // store but the draft runs 250ms ahead of it, and reading the store here would- // leave the expansion count a debounce behind what the user is typing.+ // Merge against the live draft so expansion counts do not lag behind debounce.const effectivePositivePrompt = useMemo(() => (promptTemplate ? applyPromptTemplate(promptTemplate.positivePrompt, draftValue) : draftValue),[draftValue, promptTemplate]@@ -287,10 +270,7 @@ export const PositivePromptField = ({onKeyDown={handlePromptKeyDown}onResizeEnd={onResizeEnd}/>- {/* Only while a compatible drag is in flight — a prompt box wearing a- permanent dashed border would read as an upload area, not a field.- `pointerEvents` stays off so the textarea underneath is unaffected;- dnd-kit hit-tests the wrapper's rect, not this overlay. */}+ {/* Keep pointer events off; dnd-kit targets the wrapper. */}{isImageDragActive ? (<DropZonealignItems="center"diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptHighlight.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptHighlight.tsxindex 4ee5490560..c8b529530d 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptHighlight.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptHighlight.tsx@@ -1,11 +1,3 @@-/**- * The one place prompt highlight kinds become colours.- *- * Shared by the prompt textarea's underlay and the dynamic prompts preview, so a- * weight or an embedding reads the same whether you are writing the prompt or- * looking at what it expanded into.- */-import type { PromptHighlightKind, PromptHighlightOptions } from '@features/generation/core/prompt/highlight';import { Box } from '@chakra-ui/react';@@ -30,15 +22,12 @@ export const HIGHLIGHT_STYLE_BY_KIND: Record<promptFunctionArg: { bg: 'accent.subtle/20', color: 'fg' },promptFunctionMethod: { color: 'accent.fg' },promptVariable: { color: 'accent.fg' },- // Muted like a variant's `|`: structure, not content. Its presence is what- // separates `${lens=85mm}` defining a variable from `${lens}` using one.+ // Assignment markers distinguish variable definitions from uses.promptVariableOperator: { color: 'fg.muted' },punctuation: { color: 'fg.subtle' },text: { color: 'fg' },variantBrace: { color: 'accent.fg' },variantRange: { color: 'fg.success' },- // A sampler override changes how many/which alternatives come out, so it sits- // with the other count modifiers rather than earning a colour of its own.variantSampler: { color: 'fg.success' },variantSeparator: { color: 'fg.muted' },variantWeight: { color: 'fg.success' },@@ -71,10 +60,7 @@ export const PromptHighlightSpan = ({ kind, text }: { kind: PromptHighlightKind;);};-/**- * Renders a prompt as coloured spans, falling back to plain text when- * highlighting is off or the prompt is too long to be worth colouring.- */+/** Fall back to plain text when highlighting is disabled or oversized. */export const HighlightedPrompt = ({enabled = true,options = EMPTY_OPTIONS,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.browser.test.tsxindex 0da4fbca20..ca09c26ed3 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.browser.test.tsx@@ -50,9 +50,7 @@ afterEach(async () => {describe('prompt line numbers', () => {it('indents the text clear of the gutter so numbers never overlap it', async () => {- // Regression: the gutter offset was a calc() over a Chakra spacing var whose- // generated name does not resolve for fractional tokens, so the declaration- // was dropped and the numbers rendered on top of the first characters.+ // Fractional Chakra spacing variables are invalid inside calc.await render('toyota+\nhonda\nacura--');const textarea = host!.querySelector('textarea')!;@@ -83,8 +81,7 @@ describe('prompt line numbers', () => {const heights = gutterEntries().map((entry) => entry.getBoundingClientRect().height);expect(gutterEntries().map((entry) => entry.textContent)).toEqual(['1', '2', '3']);- // The wrapped line keeps a single number but occupies several rows, so its- // gutter entry has to be taller than its unwrapped neighbours.+ // Wrapped lines need taller gutter entries but only one logical line number.expect(heights[1]).toBeGreaterThan(heights[0] * 2);expect(heights[2]).toBeCloseTo(heights[0], 1);});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.tsxindex 0c036a7f96..5d39c13c6f 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.tsx@@ -1,11 +1,4 @@-/**- * A line-number gutter for `PromptTextarea`.- *- * A textarea gives no way to ask where its soft wraps fall, so the heights come- * from a hidden mirror that lays the same text out at the same width with the- * same metrics. Numbering follows *logical* lines: a wrapped line keeps one- * number and the gutter entry grows to match, the way an editor behaves.- */+/** A hidden mirror measures soft-wrap heights while numbering each logical line once. */import type { BoxProps } from '@chakra-ui/react';import type { CSSProperties } from 'react';@@ -37,8 +30,6 @@ export const PromptLineNumbers = ({ metrics, value }: { metrics: PromptLineNumbeconst [lineHeights, setLineHeights] = useState<number[]>([]);const lines = useMemo(() => value.split('\n'), [value]);const gutterWidth = `${getLineNumberGutterCh(lines.length)}ch`;- // The numbers occupy the same lane the text is indented by, so they end just- // short of where the first character starts.const gutterLaneWidth = `calc(${metrics.paddingInline} + ${gutterWidth})`;useLayoutEffect(() => {@@ -75,8 +66,7 @@ export const PromptLineNumbers = ({ metrics, value }: { metrics: PromptLineNumbereturn (<>- {/* Measured, never seen. `visibility: hidden` still participates in layout,- which is exactly what makes it measurable. */}+ {/* visibility:hidden preserves measurable layout. */}<Box aria-hidden="true" inset="0" overflow="hidden" pointerEvents="none" position="absolute" visibility="hidden"><Boxref={mirrorRef}@@ -96,8 +86,7 @@ export const PromptLineNumbers = ({ metrics, value }: { metrics: PromptLineNumbe</Box></Box>- {/* The font metrics have to be on this box too: `ch` in its width resolves- against its own font size, not the numbers' inside it. */}+ {/* ch units use the gutter container's own font metrics. */}<Boxaria-hidden="true"bottom="0"diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptPanelHeader.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptPanelHeader.tsxindex 60f95bcf15..d37959c28e 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptPanelHeader.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptPanelHeader.tsx@@ -2,11 +2,6 @@ import type { ReactNode } from 'react';import { HStack, Text } from '@chakra-ui/react';-/**- * Height of a trailing header control, shared so the summary badge on one tab- * and the "New wildcard" button on the other line up rather than happening to- * agree.- */export const PANEL_HEADER_CONTROL_HEIGHT = '6';export const PromptPanelHeader = ({ children, label }: { label: string; children?: ReactNode }) => (diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsxindex 9efcf17514..a22929dae5 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplateEditor.tsx@@ -77,13 +77,7 @@ export const PromptTemplateEditor = ({const objectUrlRef = useRef<string | null>(null);const galleryFetchRef = useRef<AbortController | null>(null);- /**- * Swaps in a preview URL for a picked file, releasing the previous one.- *- * A blob URL pins the whole file for the document's lifetime, so re-picking- * ten images held on to all ten. Stored images are owned by the shared image- * resource; only local replacement previews are tracked here.- */+ /** Revoke replaced local blob URLs; shared stored-image resources own their own lifetime. */const takeObjectUrl = useCallback((file: Blob | null): string | null => {if (objectUrlRef.current) {URL.revokeObjectURL(objectUrlRef.current);@@ -131,18 +125,14 @@ export const PromptTemplateEditor = ({saved = await catalog.create(nextDraft);}} catch (caught) {- // `ApiError.message` is the raw response body, so the backend's own- // explanation only reads properly once it is unwrapped.+ // Unwrap raw ApiError bodies for display.setError(getApiErrorMessage(caught, t('widgets.generate.promptTemplates.couldNotSave')));return;} finally {setIsSaving(false);}- // Deliberately outside the `try`. Handing the saved record back is the- // caller's business, and a failure there is not a failure to save — inside,- // it was reported as "could not save this template" about a template that- // had just been saved. It reaches the caller's own reporting instead.+ // Run post-save callbacks outside save error handling so callback failure cannot misreport the save.onSaved(saved);}, [catalog, draft, onSaved, t, template, trimmedName]);@@ -157,9 +147,7 @@ export const PromptTemplateEditor = ({[]);- // The value has to be read before `setDraft`, not inside the updater: React- // nulls `currentTarget` once the handler returns, and an updater can run after- // that.+ // Read currentTarget before deferred state updates; React clears it after dispatch.const updateDraftField = useCallback((field: 'name' | 'negativePrompt' | 'positivePrompt', value: string) =>setDraft((current) => ({ ...current, [field]: value })),@@ -182,9 +170,7 @@ export const PromptTemplateEditor = ({[takeObjectUrl]);- // A gallery pick fetches the full image so it is uploaded like a local file.- // Only the latest pick may land: a later local file, gallery pick, clear, or- // unmount aborts an in-flight fetch.+ // Only the latest pick owns the result; abort on replacement, clear, or unmount.const handleGalleryPick = useCallback((item: GalleryItem) => {const controller = abortGalleryFetch();@@ -322,9 +308,7 @@ export const PromptTemplateEditor = ({</Field><Field label={t('common.prompt')} labelEnd={insertPlaceholderControl}>- {/* `highlightDynamicPrompts` stays off here: `{prompt}` is a template- placeholder, and colouring it as a dynamic-prompt group would promise- an expansion that the merge consumes before one could happen. */}+ {/* Exclude template placeholders from dynamic highlighting because merging consumes them first. */}<PromptTextareaaria-label={t('widgets.generate.promptTemplates.positivePrompt')}defaultHeightPx={80}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.browser.test.tsxindex 16960a0763..20c1150d3a 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.browser.test.tsx@@ -108,8 +108,6 @@ describe('the prompt templates button', () => {});it('is a labeled primary at rest, swapping the label for the applied name', async () => {- // A labeled button rather than a bare icon: "Templates" until a template is- // applied, then the applied template's name in its place.await render(null);const restLabel = [...host!.querySelectorAll('span')].find((span) => span.textContent === 'widgets.generate.templatesButton'diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsxindex bec90638c9..5d3d14c63f 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx@@ -24,10 +24,7 @@ interface PromptTemplatesButtonProps {onApply: (template: PromptTemplateSnapshot | null) => void;}-/**- * `record: null` means the editor is composing a new template; `prefill` carries- * the prompts handed over from the gallery's "save as prompt template".- */+/** A null record creates a template; gallery input may prefill it. */type EditorTarget = { record: PromptTemplateRecord | null; prefill?: PendingPromptTemplateDraft };export const PromptTemplatesButton = ({@@ -39,11 +36,7 @@ export const PromptTemplatesButton = ({const triggerId = useId();const [isOpen, setIsOpen] = useState(false);const [editorTarget, setEditorTarget] = useState<EditorTarget | null>(null);- // The list is behind the popover, so a closed button has nothing to show —- // but an applied template still has to be re-read, both to refresh its text- // and to notice it has been deleted. Without this the widget's own gating did- // nothing: react-query enables a query if any one observer wants it, and this- // observer always did.+ // Enable the catalog query only for an open panel or applied template; any enabled observer triggers fetching.const catalog = usePromptTemplates({ isEnabled: isOpen || activeTemplate !== null });const popoverIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);// A draft handed over from the gallery opens the editor straight away.@@ -57,8 +50,7 @@ export const PromptTemplatesButton = ({const handleOpenChange = useCallback((event: { open: boolean }) => {setIsOpen(event.open);- // Reopening should land on the list rather than resuming a half-written- // template the user walked away from.+ // Reopen at the list rather than resume abandoned drafts.if (!event.open) {setEditorTarget(null);}@@ -79,10 +71,7 @@ export const PromptTemplatesButton = ({const startEdit = useCallback((record: PromptTemplateRecord) => setEditorTarget({ record }), []);const closeEditor = useCallback(() => setEditorTarget(null), []);- /**- * Editing the template that is currently applied has to refresh the snapshot,- * or the panel would show the new text while the old one keeps generating.- */+ /** Refresh the applied snapshot after edits so displayed and generated text agree. */const handleSaved = useCallback((saved: PromptTemplateRecord) => {if (activeTemplate?.id === saved.id) {@@ -94,9 +83,7 @@ export const PromptTemplatesButton = ({[activeTemplate?.id, onApply]);- // Deleted in another tab, or by another session of this one. It keeps- // applying — that policy is deliberate — so the only thing wrong is that- // nothing said so.+ // Deleted templates still apply their stored snapshot with an explicit notification.const isMissing = isPromptTemplateMissing(catalog, activeTemplate);const tooltip = activeTemplate@@ -114,8 +101,6 @@ export const PromptTemplatesButton = ({><Tooltip content={tooltip} ids={popoverIds}><Popover.Trigger asChild>- {/* A labeled primary rather than a bare icon: the label is the word- "Templates" until one is applied, then the applied template's name. */}<IconButtonaria-label={t('widgets.generate.promptTemplates.title')}// Quiet states only: dimmed while nothing is applied. No accent, no motion.@@ -127,8 +112,6 @@ export const PromptTemplatesButton = ({><LayoutTemplateIcon />{activeTemplate ? (- // Dimmed when it is gone, the same way the button dims when nothing- // is applied — one vocabulary for "not fully live", no new colour.<MiddleTruncateas="span"fontSize="2xs"@@ -150,11 +133,7 @@ export const PromptTemplatesButton = ({<Popover.Body p="2.5">{editorTarget ? (<PromptTemplateEditor- // The editor seeds its draft on mount. Every other way in goes- // through the panel first, which unmounts it — but the gallery- // handover swaps the target in place, so without this a draft- // opened over an existing template kept that template's text- // and saved a duplicate of it.+ // Remount on handover target changes because editor drafts seed only on mount.key={editorTarget.record?.id ?? 'new'}catalog={catalog}prefill={editorTarget.prefill}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsxindex 38054ff184..4bba475414 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx@@ -27,8 +27,7 @@ import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';const THUMBNAIL_SIZE = '7';-// The rows sit on the popover's `bg.muted` surface, where the row recipe's-// `bg.muted/60` hover is invisible — hover needs the next surface step.+// Use a distinct hover fill on bg.muted surfaces.const TEMPLATE_ROW_HOVER_PROPS = { bg: 'bg.emphasized/60' };const TEMPLATE_THUMBNAIL_FALLBACK = (<Box@@ -51,10 +50,7 @@ interface PromptTemplatesPanelProps {/** The applied template is no longer in the catalog — deleted elsewhere. */isActiveTemplateMissing: boolean;onApply: (template: PromptTemplateSnapshot | null) => void;- /**- * Stop applying the active template without dismissing the panel — for when it- * has just been deleted, which is not the same intent as choosing to clear it.- */+ /** Detach a deleted active template without closing the manager. */onDetach: () => void;onEdit: (template: PromptTemplateRecord) => void;onCreate: () => void;@@ -102,10 +98,7 @@ export const PromptTemplatesPanel = ({const clearActiveTemplate = useCallback(() => onApply(null), [onApply]);const closeDeleteDialog = useCallback(() => setPendingDelete(null), []);- /**- * The dialog closes either way, so a failure has nowhere inline to land — it- * goes to the notification centre like the other Generation errors.- */+ /** Report errors through notifications because confirmation closes on failure. */const confirmDelete = useCallback(async () => {if (!pendingDelete) {return;@@ -114,10 +107,7 @@ export const PromptTemplatesPanel = ({try {await catalog.remove(pendingDelete);- // Deleting the template that is applied would otherwise leave it silently- // shaping every prompt with no way to reach it. Detached rather than- // cleared: the user is in the middle of managing the list, and closing the- // panel out from under them is not what they asked for.+ // Deleting the active template detaches it while keeping the manager open.if (activeTemplate?.id === pendingDelete.id) {onDetach();}@@ -194,9 +184,7 @@ export const PromptTemplatesPanel = ({</Button>) : null}</HStack>- {/* The list above cannot explain an absence, so this says it in- words: the template is gone but still shaping the prompt, and the- button beside it is how to stop that. */}+{activeTemplate && isActiveTemplateMissing ? (<Text color="fg.subtle" fontSize="2xs">{t('widgets.generate.promptTemplates.appliedMissingHelp', { name: activeTemplate.name })}@@ -217,11 +205,7 @@ export const PromptTemplatesPanel = ({);};-/**- * Bulk transfer, admin-only on the backend. Export streams CSV and import accepts- * the CSV/JSON shapes the backend's parser documents. Both go through the- * transport rather than an anchor download, which would carry no auth header.- */+/** Use authenticated transport for admin CSV/JSON transfers; ordinary anchors omit bearer headers. */const PromptTemplateTransferActions = ({ catalog }: { catalog: PromptTemplateCatalog }) => {const { t } = useTranslation();const { notifications } = useGenerationUi();@@ -382,8 +366,6 @@ const TemplateRow = ({const handleApply = useCallback(() => onApply(toPromptTemplateSnapshot(template)), [onApply, template]);const handleEdit = useCallback(() => onEdit?.(template), [onEdit, template]);const handleDelete = useCallback(() => onDelete?.(template), [onDelete, template]);- // The prompt with its placeholder is the whole content of a template, so the- // row shows it rather than a name alone.const summary = template.positivePrompt || PROMPT_TEMPLATE_PLACEHOLDER;return (@@ -410,8 +392,7 @@ const TemplateRow = ({{summary}</Text></Stack>- {/* The applied marker: a check, not a filled row — the popover- surface stays quiet and the accent stays an accent. */}+{isActive ? <Icon as={CheckIcon} boxSize="3.5" color="accent.fg" flexShrink={0} /> : null}</button></Row>diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsxindex 5bbc196d07..74d1e4527d 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx@@ -7,10 +7,7 @@ import { getLineNumberGutterCh, PromptLineNumbers } from '@features/generation/uimport { ResizableTextarea } from '@platform/ui';import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';const PROMPT_TEXTAREA_LINE_HEIGHT = '1.6';-// Literal lengths rather than spacing tokens: the gutter offset is a `calc()`,-// and Chakra's generated var name for a fractional token does not resolve inside-// one, which silently invalidates the whole declaration. These are the `2.5` and-// `2` spacing tokens.+// Use literal lengths; fractional Chakra spacing variables fail inside calc.const PROMPT_TEXTAREA_PX = '0.625rem';const PROMPT_TEXTAREA_PY = '0.5rem';@@ -26,23 +23,14 @@ const PROMPT_TEXTAREA_HIGHLIGHTED_CSS = {};interface PromptTextareaProps extends Omit<ResizableTextareaProps, 'underlay'> {- /**- * Annotate `{a|b}` syntax. Only surfaces whose prompt is batch-expanded set- * this — elsewhere the braces are literal text and colouring them would- * promise an expansion that never happens.- */+ /** Enable dynamic highlighting only for prompts that actually expand syntax. */highlightDynamicPrompts?: boolean;/** Resolvable wildcard names; an unknown `__name__` is underlined as an error. */knownWildcards?: ReadonlySet<string>;showSyntaxHighlighting: boolean;/** Number logical lines in a leading gutter, the way an editor does. */showLineNumbers?: boolean;- /**- * `[before, authored, after]` from `getPromptTemplateChunks`. When set, the- * mirror dims the outer chunks so the template's own words read as context- * around the user's text. `value` must be the concatenation of the three, and- * the textarea is expected to be `readOnly` — this is a view, not an editor.- */+ /** value must equal the concatenated chunks, and the input must be readOnly. */templateChunks?: [string, string, string] | null;value: string;}@@ -78,8 +66,7 @@ export const PromptTextarea = ({const [scroll, setScroll] = useState({ left: 0, top: 0 });const [textareaClientWidth, setTextareaClientWidth] = useState<number | null>(null);const isWithinHighlightBudget = value.length > 0 && value.length <= MAX_HIGHLIGHTED_PROMPT_LENGTH;- // Template chunks are a legibility device, not a syntax preference, so they- // render whether or not highlighting is switched on.+ // Template chunk emphasis is independent of the syntax-highlighting preference.const shouldHighlight = (showSyntaxHighlighting || templateChunks !== null) && isWithinHighlightBudget;const effectiveFontSize = fontSize ?? '0.82rem';const effectiveLineHeight = lineHeight ?? PROMPT_TEXTAREA_LINE_HEIGHT;diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsxindex 3dd045802a..976ad1e47a 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx@@ -50,8 +50,7 @@ const render = async (isTemplateViewMode = false) => {root?.render(<QueryClientProvider client={new QueryClient()}><ChakraProvider value={system}>- {/* The prompt box is a gallery-image drop target, so it lives inside- the shell's DndContext wherever it is really rendered. */}+ {/* Match the prompt box's production drop-target environment with DndContext. */}<DndContext><PositivePromptFieldheightPx={TEXTAREA_HEIGHT_PX}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsxindex 041dbc20d1..b4b07b0cf0 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsx@@ -216,10 +216,7 @@ describe('ResizableTextarea', () => {await expect.poll(() => textarea.value).toBe('(hello world)+++');});- // Regression: the write goes through the native value setter and a synthetic- // `input` event, which React honours even on a read-only textarea. In template- // view mode that wrote the merged text back as the authored prompt, and the- // next submit merged it a second time.+ // Synthetic input must not mutate a read-only prompt.it('leaves a read-only prompt alone', async () => {const ReadOnlyHarness = () => (<PromptTextareadiff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/SystemPromptsField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/SystemPromptsField.tsxindex 71f9176c34..9a456d783f 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/SystemPromptsField.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/SystemPromptsField.tsx@@ -10,9 +10,7 @@ import {SYSTEM_PROMPT_MAX_TOKENS_MIN,} from '@features/generation/core/systemPrompts';import { PANEL_HEADER_CONTROL_HEIGHT, PromptPanelHeader } from '@features/generation/ui/promptFields/PromptPanelHeader';-// Imported by subpath rather than from the `@platform/ui` barrel, which is at its-// direct-importer budget (a dev-invalidation limit) — depending on the components-// actually used means this module only rebuilds when those change.+// Use subpaths to respect the importer budget.import { getApiErrorMessage } from '@platform/transport/http';import { Button, IconButton } from '@platform/ui/Button';import { ConfirmDialog } from '@platform/ui/ConfirmDialog';@@ -65,8 +63,7 @@ const SystemPromptRow = ({<HStack justify="space-between" px="1" py="0.5"><MiddleTruncate fontSize="xs" minW="0" text={prompt.name} /><HStack gap="0.5">- {/* Copying needs no rights over the source, so it is the one control every row has --- it is how someone adapts a prompt they cannot edit. */}+ {/* Copying remains available without edit rights over the source. */}<Tooltip content={t('widgets.generate.systemPrompts.duplicate')}><IconButtonaria-label={t('widgets.generate.systemPrompts.duplicate')}@@ -101,11 +98,6 @@ const SystemPromptRow = ({);};-/**- * The system-prompt control inside the Expand Prompt popover: a picker over the prompts this- * account can see, and — behind the manage toggle — the list that creates, edits and deletes- * them. Both live in one component because the popover shows exactly one of them at a time.- */export const SystemPromptsField = ({ catalog, onSelect, selectedId }: SystemPromptsFieldProps) => {const { canEdit, prompts } = catalog;const { t } = useTranslation();@@ -153,8 +145,7 @@ export const SystemPromptsField = ({ catalog, onSelect, selectedId }: SystemPromconst maxTokens = parseMaxTokensInput(draft.maxTokens);- // Save is disabled while the field is invalid, so this only catches a submit that raced the- // keystroke that broke it.+ // Validate on submit to cover races after the disabled-button render.if (maxTokens === 'invalid') {setError(t('widgets.generate.systemPrompts.maxTokensInvalid', {@@ -175,8 +166,7 @@ export const SystemPromptsField = ({ catalog, onSelect, selectedId }: SystemPromtry {saved = editorTarget.record ? await catalog.update(editorTarget.record, payload) : await catalog.create(payload);} catch (caught) {- // `ApiError.message` is the raw response body, so the backend's own explanation only- // reads properly once unwrapped. Reported in place — the popover has no toast surface.+ // Unwrap errors inline; this popover has no toast surface.setError(getApiErrorMessage(caught, t('widgets.generate.systemPrompts.couldNotSave')));return;} finally {@@ -227,8 +217,7 @@ export const SystemPromptsField = ({ catalog, onSelect, selectedId }: SystemPromsetPendingDelete(null);}- // The selection resolves against the visible list on read, so a deleted prompt needs no- // corrective write here — but clearing it avoids one render with a dangling id.+ // Clear selection to avoid a transient dangling ID even though reads have a fallback.if (selectedId === pendingDelete.id) {onSelect(null);}@@ -253,8 +242,6 @@ export const SystemPromptsField = ({ catalog, onSelect, selectedId }: SystemPromconst handleSelectChange = useCallback(({ value }: { value: string[] }) => onSelect(value[0] ?? null), [onSelect]);const isMaxTokensInvalid = parseMaxTokensInput(draft.maxTokens) === 'invalid';- // Reported under the field as it is typed rather than only on save, since an out-of-range- // cap is the one thing here the backend would reject with a bare 422.const maxTokensError = isMaxTokensInvalid? t('widgets.generate.systemPrompts.maxTokensInvalid', {max: SYSTEM_PROMPT_MAX_TOKENS_MAX,@@ -263,9 +250,7 @@ export const SystemPromptsField = ({ catalog, onSelect, selectedId }: SystemProm: null;const selectValue = useMemo(() => (selectedId ? [selectedId] : []), [selectedId]);- // The Select primitive renders `valueText` verbatim in the closed trigger, so- // it must carry the selected prompt's name — a static string would mask the- // selection ("None" while a prompt is active).+ // Keep valueText tied to selection because Select renders overrides verbatim.const selectedName = useMemo(() => (selectedId ? (prompts.find((prompt) => prompt.id === selectedId)?.name ?? null) : null),[prompts, selectedId]@@ -309,8 +294,7 @@ export const SystemPromptsField = ({ catalog, onSelect, selectedId }: SystemProm><Inputid={maxTokensFieldId}- // `inputMode` rather than `type="number"`: the spinner and the browser's own- // out-of-range handling would fight the empty-means-default reading of this field.+ // Use inputMode instead of number input so empty-means-default drafts survive.inputMode="numeric"placeholder={String(SYSTEM_PROMPT_MAX_TOKENS_DEFAULT)}size="xs"diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.browser.test.tsxindex 4849d677d1..33318eb5ac 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.browser.test.tsx@@ -103,8 +103,6 @@ describe('wildcard import dialog', () => {expect(onConfirm).toHaveBeenCalledWith({ colours: 'skip', moods: 'replace' });});- // A count that said "3 imported" while quietly dropping the fourth would be- // the worst version of this dialog.it('names what it cannot import, and why', async () => {await renderDialog();diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsxindex f528917bf0..ee98f154ea 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsx@@ -28,14 +28,7 @@ const REJECTION_KEY: Record<WildcardImportRejection, string> = {valueTooLong: 'widgets.generate.dynamicPrompts.importRejectedValueTooLong',};-/**- * What an import is about to do, one clashing name at a time.- *- * Import is the one action here that can overwrite a hand-typed list, so nothing- * is decided on the user's behalf: every clash defaults to being left alone, and- * anything the backend would refuse is listed with its reason rather than- * dropped behind a count that says everything worked.- */+/** Default conflicts to skip and show explicit rejection reasons. */export const WildcardImportDialog = ({entries,onCancel,@@ -47,10 +40,7 @@ export const WildcardImportDialog = ({}) => {const { t } = useTranslation();const [resolutions, setResolutions] = useState<Record<string, WildcardImportResolution>>({});- // The set-all row is a control in its own right, so it has to hold what it was- // last set to. Rendered without a value it read as nothing selected however- // often it was used, which invited a second click — and that reapplied the- // choice over every per-row override made in between.+ // Control set-all state so it cannot accidentally overwrite later per-row choices.const [allResolution, setAllResolution] = useState<WildcardImportResolution | null>(null);const conflicts = useMemo(@@ -82,8 +72,7 @@ export const WildcardImportDialog = ({const handleConfirm = useCallback(() => onConfirm(resolutions), [onConfirm, resolutions]);- // `ConfirmDialog` takes its body as a node. This one is rebuilt on every- // resolution change regardless, so memoizing it would save nothing.+ // The body changes on every resolution edit.// oxlint-disable-next-line react-perf/jsx-no-jsx-as-propconst body = (<Stack gap="3">@@ -121,9 +110,7 @@ export const WildcardImportDialog = ({<Text fontSize="xs" fontWeight="600">{t('widgets.generate.dynamicPrompts.importCannotImport')}</Text>- {/* Bounded like the conflicts above it. Pointed at a folder where most- files are unusable, this list grew past the viewport and pushed the- dialog's own buttons out of reach. */}+ {/* Bound rejected-file lists so dialog actions remain reachable. */}<Scrollable maxH="8rem" label={t('widgets.generate.dynamicPrompts.importCannotImport')}><Stack gap="1" pr="1">{rejected.map((entry, index) => (diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsxindex 26c004e9f2..ade8c5862d 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx@@ -34,14 +34,7 @@ const IMPORT_SOURCES = ['files', 'folder'] as const;/** Not in React's DOM typings, and `multiple` comes along with it implicitly. */const DIRECTORY_INPUT_PROPS = { directory: '', webkitdirectory: '' } as unknown as { webkitdirectory: string };-/**- * Import and export for the whole catalog.- *- * Both directions are pure client work — wildcards are per-user CRUD, so an- * import is a run of ordinary creates and updates rather than a route of its- * own. Writes go one at a time and stop at the first failure, so a half-finished- * import says how far it got instead of reporting success over a silent error.- */+/** Import CRUD operations sequentially; stop at the first failure and report completed writes. */export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalog }) => {const { t } = useTranslation();const { notifications } = useGenerationUi();@@ -85,9 +78,7 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalogreturn;}- // Writes go one at a time, so a failure part-way leaves real wildcards- // behind. Saying only that the import failed sent people back for a- // second run that then clashed with everything the first one had made.+ // Report partial success so retries do not duplicate completed writes.const done = caught instanceof WildcardWriteError ? caught.done : 0;reportError(@@ -117,9 +108,7 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalogconst entries = planWildcardImport(parsed, catalog.wildcards);assertAccountScopeCurrent(owner);- // Nothing to decide and nothing to explain — the file pick was the- // confirmation, so a dialog with only an Import button would be a click- // that tells the user what they already know.+ // Import directly when file selection leaves no conflicts or other decisions.if (entries.every((entry) => entry.rejection === null && entry.conflictId === null)) {await applyImport(entries, {}, owner);return;@@ -175,8 +164,7 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalog[startImport]);- // A folder hands over everything in it, so the readmes and `.DS_Store` are- // dropped here rather than failing the import the way a named file would.+ // Ignore unrelated directory files, but reject explicitly selected invalid files.const handleDirectoryChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {const files = [...(event.currentTarget.files ?? [])].filter(isSupportedWildcardFile);@@ -262,9 +250,7 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalogtype="file"onChange={handleFileChange}/>- {/* A second input, because one cannot be both. The a1111 layout nests- wildcards in folders, and only a directory pick supplies the relative- path that turns `animals/dogs.txt` into `animals/dogs`. */}+ {/* Use a separate directory input to preserve relative wildcard paths. */}<input {...DIRECTORY_INPUT_PROPS} hidden ref={directoryInputRef} type="file" onChange={handleDirectoryChange} />{pendingImport ? (<WildcardImportDialog entries={pendingImport.entries} onCancel={cancelImport} onConfirm={confirmImport} />diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsxindex 5852e78b34..8ae6bf4dc5 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx@@ -27,9 +27,7 @@ import { useTranslation } from 'react-i18next';/** One value per line: the same shape the user is editing a variant in. */const toValuesText = (values: string[]): string => values.join('\n');-// Normalized on the way in, so what is stored is what an export writes and a-// re-import reads back. A stray blank line used to survive into the catalog and-// then vanish on the next round trip.+// Normalize ingress so export and reimport preserve values.const fromValuesText = (text: string): string[] => normalizeWildcardValues(text.split('\n'));const VALUES_ERROR_KEY = {@@ -70,16 +68,13 @@ export const WildcardsPanel = ({() => groupWildcardsByPrefix(filterWildcards(catalog.wildcards, searchTerm)),[catalog.wildcards, searchTerm]);- // Renaming to your own current name is not a clash, so the wildcard being- // edited is excluded from the taken-names set.+ // Exclude the current wildcard from rename collision checks.const nameError = draft? getWildcardNameError(draft.name, new Set(catalog.wildcards.filter((w) => w.id !== draft.id).map((w) => w.name))): null;- // Pre-flighted here as well as on the import path, which is where these bounds- // used to live — the editor discovered them as a raw error from the server.+ // Keep editor and import bounds consistent.const valuesError = draft ? getWildcardValuesError(fromValuesText(draft.valuesText)) : null;- // The server's own explanation wins when there is one; otherwise say which- // bound the draft is over before it is sent.+ // Prefer the server explanation over local bound errors.const draftError = error ?? (valuesError ? t(VALUES_ERROR_KEY[valuesError]) : null);const startCreate = useCallback(() => {@@ -113,8 +108,7 @@ export const WildcardsPanel = ({setDraft(null);setError(null);} catch (caught) {- // `ApiError.message` is the raw response body, so the backend's own- // explanation only reads properly once it is unwrapped.+ // Unwrap raw ApiError bodies before display.setError(getApiErrorMessage(caught, t('widgets.generate.dynamicPrompts.couldNotSaveWildcard')));}}, [catalog, draft, t]);@@ -126,10 +120,7 @@ export const WildcardsPanel = ({const closeDeleteDialog = useCallback(() => setPendingDelete(null), []);- /**- * The dialog closes whether or not this throws, so a failure has nowhere inline- * to land — it goes to the notification centre like the other Generation errors.- */+ /** Notify on failure because the confirmation dialog closes. */const confirmDelete = useCallback(async () => {if (!pendingDelete) {return;@@ -156,8 +147,7 @@ export const WildcardsPanel = ({: t('widgets.generate.dynamicPrompts.editWildcard')}/>- {/* An empty name is the starting state rather than a mistake, so it- disables Save without being called out. */}+ {/* Empty initial names disable save without premature validation errors. */}<Fielderror={nameError === null || nameError === 'empty' ? null : t(NAME_ERROR_KEY[nameError])}id={nameFieldId}@@ -171,9 +161,7 @@ export const WildcardsPanel = ({onChange={(event: ChangeEvent<HTMLInputElement>) => setDraft({ ...draft, name: event.currentTarget.value })}/></Field>- {/* Values are expanded by dynamicprompts too, so a nested `{a|b}` or- `__other__` is live syntax here and is coloured as such. The gutter- numbers the values, which is what a line means in this editor. */}+ {/* Wildcard values may contain nested dynamic syntax. */}<PromptTextareaaria-label={t('widgets.generate.dynamicPrompts.wildcardValues')}defaultHeightPx={144}@@ -220,8 +208,6 @@ export const WildcardsPanel = ({</Button></PromptPanelHeader>- {/* Searching an empty catalog would only offer a way to find nothing, so- the input appears once there is something to search. */}{catalog.wildcards.length > 0 ? (<><Input@@ -252,9 +238,7 @@ export const WildcardsPanel = ({</Text>)}{group.wildcards.map((wildcard) => (- // The row shows the whole `__animals/dogs__`, header or not:- // it is the exact text you would type, so trimming the prefix- // to match the header above would make it a lie.+ // Show full wildcard paths because rows display exact insertion syntax.<WildcardRowkey={wildcard.id}wildcard={wildcard}@@ -272,8 +256,7 @@ export const WildcardsPanel = ({<Separator /><WildcardTransferActions catalog={catalog} />- {/* A wildcard's values are typed by hand and there is no undo, so deleting- one asks first — as every other destructive action here does. */}+ {/* Confirm irreversible deletion of handwritten values. */}<ConfirmDialogbody={t('widgets.generate.dynamicPrompts.deleteWildcardBody', { name: pendingDelete?.name ?? '' })}confirmLabel={t('common.delete')}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptAttentionHotkeys.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptAttentionHotkeys.tsindex 1a18f8ae08..45dd63c78e 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptAttentionHotkeys.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptAttentionHotkeys.ts@@ -5,13 +5,7 @@ import { adjustPromptAttention } from '@features/generation/core/prompt/attentioexport const PROMPT_ATTENTION_TARGET_ATTR = 'data-prompt-attention-target';export const PROMPT_ATTENTION_TARGET_PROPS = { [PROMPT_ATTENTION_TARGET_ATTR]: 'true' } as const;-/**- * `readOnly` is part of the test, not an afterthought. Writing here goes through- * the native value setter and a synthetic `input` event, which React accepts on- * a read-only textarea — so in template view mode the hotkeys wrote the *merged*- * text back as the authored prompt, and the next submit merged it again.- * Clicking the box leaves view mode, but tabbing into it does not.- */+/** Guard readOnly explicitly: native setters and synthetic input bypass it and could merge templates twice. */const isPromptAttentionTarget = (element: Element | null): element is HTMLTextAreaElement =>element instanceof HTMLTextAreaElement &&element.getAttribute(PROMPT_ATTENTION_TARGET_ATTR) === 'true' &&diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.tsindex 6f0e662883..838d898fc8 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.ts@@ -71,9 +71,7 @@ describe('getActiveTriggerQuery', () => {expect(query('a __col our')).toBeNull();});- // Embedding names routinely have spaces in them — `bad hands 5`, `Negative- // Hand` — so ending the attempt at the first space put a whole class of them- // out of reach inline, even though the filter would have matched.+ // Embedding names may contain spaces, such as <my embedding>.it('reads on through spaces inside an unclosed angle bracket', () => {expect(query('a photo of <bad hands')).toEqual({ key: '<', query: 'bad hands', range: { end: 21, start: 11 } });});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptImageDrop.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptImageDrop.browser.test.tsxindex a18d95be83..10c53963b4 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptImageDrop.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptImageDrop.browser.test.tsx@@ -23,8 +23,7 @@ const stubs = vi.hoisted(() => ({vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({...(await importOriginal<object>()),- // Stubbed alongside the hook: the real one reads the context from its own- // unmocked module instance, which no provider in this harness fills.+ // Mock the context-bearing component and hook together to avoid unmatched module instances.GenerationModelSelect: stubs.ModelSelect,useGenerationUi: () => ({capabilities: { canManagePromptTemplates: false, canManageSharedSystemPrompts: false },diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptTriggerOptions.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptTriggerOptions.test.tsindex 33c29e42d1..9693f0c72b 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptTriggerOptions.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptTriggerOptions.test.ts@@ -52,8 +52,7 @@ describe('getPromptTriggerOptions', () => {});describe('getInlineTriggerOptions', () => {- // `<` opens an embedding token and `__` a wildcard reference, so offering the- // other kind under either is offering something the user cannot have meant.+ // The trigger restricts completion kind: < for embeddings, __ for wildcards.it('offers only wildcards for `__`', () => {expect(getInlineTriggerOptions(OPTIONS, '_', '').map((option) => option.label)).toEqual(['colours', 'moods']);});@@ -74,8 +73,7 @@ describe('getInlineTriggerOptions', () => {expect(getInlineTriggerOptions(OPTIONS, '_', 'MO').map((option) => option.label)).toEqual(['moods']);});- // `__w` matching every wildcard on the strength of the word "Wildcards" is- // what folding the group into the query would do.+ // Exclude group labels from matching so __w cannot match every entry under Wildcards.it('ignores the group name, unlike the browse search', () => {expect(getInlineTriggerOptions(OPTIONS, '_', 'wildcard')).toEqual([]);expect(filterPromptTriggerOptions(OPTIONS, 'wildcard')).toHaveLength(2);diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/useDismissOnViewportChange.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/useDismissOnViewportChange.tsindex cf9acdaf13..7b4c97ee1b 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/useDismissOnViewportChange.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/useDismissOnViewportChange.ts@@ -1,10 +1,6 @@import { useMountEffect } from '@platform/react/useMountEffect';-/**- * Dismisses a rect-anchored surface once scrolling or resizing makes its stored- * viewport coordinates stale. Scrolls inside a popover don't count: the anchor- * lives in the page, and the surface scrolling its own list moves nothing.- */+/** Dismiss stale page-space anchors on scrolling, excluding the popover's own scroll. */export const useDismissOnViewportChange = (enabled: boolean, dismiss: () => void): void => {useMountEffect(() => {if (!enabled) {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptImageDrop.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptImageDrop.tsindex 6f342af248..f0048178aa 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptImageDrop.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptImageDrop.ts@@ -6,10 +6,6 @@ import { useCallback, useId, useMemo, useState } from 'react';const DROP_DATA = { kind: 'prompt-image' } as const;-/**- * An image handed to the prompt box by a drag, waiting for the image-to-prompt- * popover to pick it up.- */export interface DroppedPromptImage {/** The dropped image, or null when the popover should follow the gallery selection. */image: GenerationSelectedImage | null;@@ -25,12 +21,7 @@ export interface PromptImageDrop {setNodeRef: (element: HTMLElement | null) => void;}-/**- * Makes an element a drop target for a gallery image and holds what landed on- * it. Dropping is the direct way to describe an image that is not the gallery's- * current selection — the popover reads this in preference to that selection,- * until it is done and clears it.- */+/** Dropped images override gallery selection until consumed and cleared. */export const usePromptImageDrop = ({ disabled = false }: { disabled?: boolean } = {}): PromptImageDrop => {const dropId = useId();const [image, setImage] = useState<GenerationSelectedImage | null>(null);diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerPicker.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerPicker.tsindex 8fa9b91b9f..9fb8f42da9 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerPicker.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerPicker.ts@@ -1,14 +1,4 @@-/**- * The `+` button's browsable trigger popover.- *- * Distinct from the caret autocomplete beside it: this one is opened- * deliberately, takes focus, and browses every trigger there is. Both prompt- * fields wire it up identically, so it lives here rather than twice.- *- * The popover is positioned by rect rather than by element so it can anchor to- * the button that opened it, wherever that sits, without the field having to- * hand its own DOM to a child.- */+/** Browsing takes focus; autocomplete does not. Anchor both to the supplied rectangle. */import type { PromptTextRange } from '@features/generation/ui/promptFields/promptFocus';import type { ReactNode } from 'react';diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/useSystemPrompts.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/useSystemPrompts.tsindex a85faeb04c..af620f35dd 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/useSystemPrompts.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/useSystemPrompts.ts@@ -62,9 +62,7 @@ export const useSystemPrompts = ({ isEnabled = true }: { isEnabled?: boolean } =const update = useCallback((prompt: SystemPromptRecord, draft: SystemPromptDraft) => {- // Mirrors the affordance so a mis-rendered edit control fails here rather than as a 403 --- // and so the one case the API would allow but this UI does not, another user's private- // prompt, cannot be reached from the client at all.+ // Enforce UI privacy policy at mutation time even when admin API rights are broader.requireEditableSystemPrompt(prompt, authority);return runAndInvalidate(() => updateSystemPrompt(prompt.id, draft));},@@ -77,8 +75,7 @@ export const useSystemPrompts = ({ isEnabled = true }: { isEnabled?: boolean } =createSystemPrompt({content: prompt.content,maxTokens: prompt.maxTokens,- // Taken from the list the viewer can see, which is the same list the new name has to- // be distinguishable in.+ // Resolve duplicate names within the viewer's visible list.name: buildDuplicateName(prompt.name,classified.prompts.map((visible) => visible.name)diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.browser.test.tsxindex 49843de157..900ee3d054 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.browser.test.tsx@@ -102,8 +102,7 @@ describe('useOnPendingPromptTemplateDraft', () => {expect(onDraft).not.toHaveBeenCalled();- // Drain the still-pending one-shot so the module store cannot leak into a- // later test if the runner changes declaration order.+ // Drain pending module-store work to avoid cross-test leakage.await act(() => root.render(<Probe onDraft={vi.fn()} />));});});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsxindex f8c9366073..c468e04213 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx@@ -42,10 +42,6 @@ interface GenerateReferenceImagesContentProps {onCommitImmediate: (patch: Partial<GenerateSettings>) => void;}-/**- * Reference-image conditioning, rendered inside the Guidance section (the- * section chrome and combined badges live in `GenerateGuidanceSection`).- */export const GenerateReferenceImagesContent = ({models,onCommit,@@ -68,12 +64,7 @@ export const GenerateReferenceImagesContent = ({const appendReferenceImages = useCallback((images: GenerateReferenceImageAsset[]) => {- // Ids are minted HERE rather than inside the updater. A pending updater- // is applied twice — once against the draft the user sees, then again- // against the freshly committed settings when the debounce flushes — so- // an id created inside it differs between the two. Any later edit keyed- // to the id the card renders under (a reorder, a patch) would then find- // nothing at flush and be silently dropped.+ // Mint IDs outside replayed updaters so draft and flushed identities match.const ids = images.map(() => createReferenceImageId());onCommit((currentSettings) => {@@ -121,9 +112,7 @@ export const GenerateReferenceImagesContent = ({[onCommit]);- // Card order is conditioning order, so a move is just a reorder of the- // settings array — the same gesture the video panel's reference stack uses.- // The updater form keeps it correct against a concurrent debounced commit.+ // Use functional reorder updates to preserve concurrent debounced changes.const handleMoveReferenceImage = useCallback((id: string, direction: -1 | 1) => {onCommit((currentSettings) => {@@ -210,8 +199,7 @@ export const GenerateReferenceImagesContent = ({return null;}- // Leftover reference images on a model that cannot use them (e.g. a persisted- // project). No editable cards, no add paths — just the way out.+ // Unsupported-model references remain read-only with removal as recovery.if (!isSupported) {return (<HStack gap="2" justify="space-between">@@ -227,8 +215,6 @@ export const GenerateReferenceImagesContent = ({return (<Stack ref={setNodeRef} gap="2" position="relative">- {/* The droppable is this whole content block (drops land anywhere on- it), so the in-flight affordance covers the same rect. */}<DropTargetOverlayisActive={acceptsActiveDrag}isOver={isOver}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsxindex e52b2f7631..b9d15560ed 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx@@ -93,11 +93,7 @@ const ReferenceImageCardBase = ({const handleRemove = useCallback(() => onRemove(referenceImage.id), [onRemove, referenceImage.id]);- // A move that lands on either end disables the very button that was just- // activated, and a disabled element cannot hold focus — a keyboard user- // would be dropped to <body> on the last step of walking a card to the top.- // The card's DOM nodes survive the reorder (the list is keyed by id), so- // handing focus to the arrow that stays live keeps their place in the stack.+ // Hand off focus when reordering disables the activated arrow.const handleMoveUp = useCallback(() => {onMove(referenceImage.id, -1);@@ -161,8 +157,7 @@ const ReferenceImageCardBase = ({)}<HStack gap="0.5">- {/* Card order is conditioning order, so the stack is reordered in- place — the same arrow pair the video panel's references use. */}+ {/* Array order is conditioning order. */}<Tooltip content={t('widgets.generate.moveReferenceImageUp')}><IconButtonref={moveUpRef}@@ -389,9 +384,7 @@ const ReferenceImageThumbnail = ({}}, [image, onUseSize]);- // The ORIGINAL, not the effective image: a crop is uploaded as an- // intermediate, so the derivative this thumbnail shows has no cell in the- // grid to land on.+ // Reveal original media; crop intermediates have no gallery cell.const originalImageName = image?.original.image.image_name;const handleFindInGallery = useCallback(() => {if (originalImageName !== undefined) {@@ -401,9 +394,7 @@ const ReferenceImageThumbnail = ({return (<>- {/* 24 rather than 20: the action row now holds three controls, and three- `2xs` buttons plus their gaps overflowed an 80px tile — `overflow:- hidden` then clipped the outer two and, with them, their focus ring. */}+ {/* Reserve width for all three buttons and their focus rings. */}<Boxbg="bg.muted"borderWidth="1px"@@ -436,8 +427,6 @@ const ReferenceImageThumbnail = ({style={OVERLAY_GRADIENT_STYLE}transition="opacity var(--wb-motion-duration-fast)">- {/* Leads the row: locating the source is what you do BEFORE- deciding to crop it or take its size. */}<FindInGalleryButton name={originalImageName} variant="ghost" onFind={handleFindInGallery} /><Tooltip content={t('common.crop')}><IconButtondiff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsxindex e184b7efe5..e88b1e3b7d 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsx@@ -104,10 +104,7 @@ export const FieldHeader = ({);};-/**- * Controls for `ip_adapter` reference image configs. `children` renders inside- * the Advanced section (the card passes the model selector through here).- */+/** Render children inside Advanced. */export const IPAdapterControls = ({children,config,@@ -139,9 +136,7 @@ export const IPAdapterControls = ({[config.method]);- // No "unchanged" guard: a drag keeps the handler it started with, so `config.weight`- // here is the press value and a drag back to it must still commit. The scrubber- // already dedupes per step.+ // Do not compare against captured drag-start values; returning to the start still needs a commit.const handleWeightChange = useCallback((weight: number) => onChange({ ...config, weight }), [config, onChange]);const commitBeginEndStepPct = useCallback(diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFindInGallery.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFindInGallery.browser.test.tsxindex b10eb66002..be7a29d237 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFindInGallery.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFindInGallery.browser.test.tsx@@ -10,12 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ReferenceImageCard } from './ReferenceImageCard';-/**- * A cropped reference image is TWO gallery records: the original the user- * picked, and the intermediate upload the crop produced. The card shows the- * crop, so the naive wiring sends the crop's name — and an intermediate is- * never listed in the grid, leaving the badge silently inert.- */+/** Crop intermediates have separate identities and stay out of the gallery; retain the original for reveal. */const i18n = i18next.createInstance();await i18n.use(initReactI18next).init({fallbackLng: 'en',@@ -77,8 +72,7 @@ const renderCard = async (referenceImage: GenerateReferenceImage) => {);};-// Named after the media, not a bare "Find in Gallery": a stack of reference-// cards otherwise renders N controls a screen reader cannot tell apart.+// Use media-specific action names to distinguish repeated cards accessibly.const findButton = (): HTMLButtonElement | null =>document.querySelector<HTMLButtonElement>('button[aria-label="Find original.png in Gallery"]');@@ -109,8 +103,7 @@ describe('reference image find-in-gallery badge', () => {it('stays available while the reference is toggled off', async () => {await renderCard({ ...CROPPED_REFERENCE, isEnabled: false });- // Crop and Use size are edits and go dead with the reference; locating its- // source changes nothing about the generation, so it must not.+ // Locate stays enabled for disabled references because it does not edit generation.expect(findButton()?.disabled).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsxindex 140739381a..669881595d 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsx@@ -11,13 +11,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ReferenceImageCard } from './ReferenceImageCard';-/**- * The reference-image stack is ordered conditioning: the array order reaches- * the graph as `reference_images`, so the arrows are the only way a user can- * say "this one first". This mounts the real cards to pin the wiring the unit- * test on `moveReferenceImage` cannot see — which arrow sends which direction,- * and that the ends of the stack are disabled rather than silently inert.- */+/** Browser coverage verifies arrow wiring and disabled endpoints beyond pure reorder tests. */const i18n = i18next.createInstance();await i18n.use(initReactI18next).init({fallbackLng: 'en',@@ -147,8 +141,7 @@ describe('reference image reorder arrows', () => {it('hands focus to the arrow that stays live when a move lands on an end', async () => {await renderStack(['first', 'second', 'third']);- // Walking the middle card to the top disables the button being activated,- // so without the handoff a keyboard user is dropped to <body>.+ // Hand off keyboard focus when the activated endpoint arrow becomes disabled.const up = buttons('Move reference image up')[1];await act(() => up?.focus());diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioSelect.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioSelect.tsxindex e38f081528..a975af9168 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioSelect.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/AspectRatioSelect.tsx@@ -30,11 +30,7 @@ export interface AspectRatioSelectProps {onChange: (id: AspectRatioId) => void;}-/**- * The aspect-ratio preset dropdown, with a proportion thumbnail beside each- * option. Presentational: callers own what a preset change does to their- * dimensions, which differs between a free-floating size and a placed frame.- */+/** Callers own dimension changes. */export const AspectRatioSelect = ({fallbackRatio,size = 'xs',diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/ConditioningRebalanceBars.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/ConditioningRebalanceBars.browser.test.tsxindex dd264ca619..ed282df195 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/ConditioningRebalanceBars.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/ConditioningRebalanceBars.browser.test.tsx@@ -70,19 +70,7 @@ const lastPreview = (): number[] => (onPreview.mock.calls.at(-1)?.[0] as number[const lastCommit = (): number[] => (onCommit.mock.calls.at(-1)?.[0] as number[] | undefined) ?? [];-/**- * Puts the pointer somewhere harmless and undoes any scroll a previous test- * left behind.- *- * Every tap here is a synthetic PointerEvent at a computed coordinate, but the- * *real* cursor keeps whatever position the last test gave it. Left over the- * track, it emits its own pointer events at its own location, and the component- * dutifully reports that index — an instrumented failure showed the intended- * `7` arriving and then a spurious `6` after it, which is what breaks- * `toHaveBeenLastCalledWith`. The same run showed the track's `left` at -393- * rather than 0, i.e. the document had been scrolled sideways by another test,- * which moves which bar the stationary cursor is over.- */+/** Reset real pointer and scroll state to prevent interference from synthetic events. */const resetPointerAndScroll = async (): Promise<void> => {const parking = document.createElement('div');@@ -149,9 +137,7 @@ describe('ConditioningRebalanceBars', () => {track.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, ...target }));});- // Deliberately loose about the value: pointing high up the track must raise that- // column well clear of its neighbours, but the exact pixel-to-weight mapping shifts- // with the track's padding and border and is not what this is guarding.+ // Assert value ranges independently of incidental padding/border pixel mapping.const previewed = lastPreview()[3] ?? 0;expect(previewed).toBeGreaterThan(REBALANCE_NEUTRAL_WEIGHT);@@ -173,14 +159,11 @@ describe('ConditioningRebalanceBars', () => {await interact(() => {track.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, ...pointAt(track, 0, 0) }));});- // One large move from the first column to the last: the columns in between get- // no pointer sample of their own and must still be filled in.+ // One large pointer move must interpolate unsampled columns.await interact(() => window.dispatchEvent(new PointerEvent('pointermove', pointAt(track, 11, 8))));const painted = lastPreview();- // The sweep ran bottom-left to top-right, so the ends should sit near the extremes- // and every column between them should rise. Ranges, not exact values.expect(painted[0] ?? 0).toBeLessThan(REBALANCE_NEUTRAL_WEIGHT);expect(painted[11] ?? 0).toBeGreaterThan(SCALE / 2);diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/ConditioningRebalanceBars.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/ConditioningRebalanceBars.tsxindex e2da15d9d4..ac4f1db391 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/ConditioningRebalanceBars.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/ConditioningRebalanceBars.tsx@@ -15,14 +15,7 @@ import { useCallback, useRef, type KeyboardEvent, type PointerEvent } from 'reacexport const REBALANCE_TRACK_HEIGHT_PX = 80;-/**- * One continuous recessed track rather than twelve gapped wells.- *- * Twelve flexed columns divide a fluid width into fractional positions, so a 1px gap- * between them lands mid-device-pixel and antialiases to a different apparent width in- * every column — the separators visibly drift. Spacing the *fills* inside flush columns- * puts every edge against the same background, so the bars read evenly at any width.- */+/** Fractional-pixel gaps make separators uneven; use a continuous track. */const TRACK_PROPS: SystemStyleObject = {bg: 'bg.subtle',borderRadius: 'md',@@ -64,10 +57,7 @@ const getColumnIndex = (clientX: number, rect: DOMRect, count: number): number =const getWeightAt = (clientY: number, rect: DOMRect, scale: number): number =>rect.height <= 0 ? scale : weightFromTrackFraction((clientY - rect.top) / rect.height, scale);-/**- * Fills the columns a fast sweep skipped over, so the committed vector matches the- * stroke the pointer actually drew rather than only its sample points.- */+/** Interpolate columns skipped by pointer sampling. */const strokeBetween = (weights: number[],fromIndex: number,@@ -106,14 +96,7 @@ interface ConditioningRebalanceBarsProps {onCommit: (weights: number[]) => void;}-/**- * The twelve per-tap gains as draggable vertical bars.- *- * Pointer input is absolute — a bar jumps to wherever you point, and a horizontal sweep- * paints across every column it passes, which is what makes drawing a curve feel direct.- * The parent holds `onPreview`'s live vector so a drag renders without writing settings on- * every move; `onCommit` fires once, on release.- */+/** Emit onPreview during interaction and one onCommit on release. */export const ConditioningRebalanceBars = ({activeIndex,disabled,@@ -147,8 +130,7 @@ export const ConditioningRebalanceBars = ({isDraggingRef.current = true;onActiveIndexChange(lastIndex);onPreview([...working]);- // preventDefault above suppressed the implicit focus; without this a click- // would leave the bar unfocusable by the arrow keys that just edited it.+ // Restore focus suppressed by preventDefault so keyboard editing remains available.barRefs.current[lastIndex]?.focus();const handlePointerMove = (moveEvent: globalThis.PointerEvent) => {@@ -223,8 +205,7 @@ export const ConditioningRebalanceBars = ({}}, [onActiveIndexChange]);- // The track takes `css` rather than a spread: SystemStyleObject carries the CSS- // `direction` property, which collides with Flex's flex-direction prop of that name.+ // CSS direction conflicts with Flex's direction prop.return (<Flexalign="stretch"@@ -274,15 +255,10 @@ export const ConditioningRebalanceBars = ({><BoxalignSelf="flex-end"- // Bars at or below neutral are holding the prompt rather than pushing it;- // the quieter fill is what makes that readable without a legend. `muted` is- // too close to the well to see at these heights, so the step is to- // `emphasized`.bg={weight > REBALANCE_NEUTRAL_WEIGHT ? 'accent.solid' : 'accent.emphasized'}borderRadius="xs"h={`${barFillFraction(weight, scale) * 100}%`}- // A zero tap keeps a stub so every slot stays visible and hittable now that- // the track no longer draws a well behind each one.+ // Zero-value stubs must remain hittable without separate wells.minH="2px"w="full"/>diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/ConditioningRebalanceSparkline.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/ConditioningRebalanceSparkline.tsxindex b6ba6a36db..7b4b906791 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/ConditioningRebalanceSparkline.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/ConditioningRebalanceSparkline.tsx@@ -7,23 +7,15 @@ const SPARKLINE_RENDER_WIDTH = 56;const SPARKLINE_STYLE = { display: 'block', flexShrink: 0, pointerEvents: 'none' } as const;-// Chakra-factory'd so `stroke` resolves through the theme, as the curve editor does.-// A raw `var(--chakra-colors-*)` only happens to work for palette tokens; a plain-// semantic token like `fg.muted` emits no such variable and the stroke silently-// resolves to `none`.+// Resolve Chakra tokens before using them as SVG strokes.const SparklineSvg = chakra('svg');const SparklinePath = chakra('path');-/**- * The current curve at a glance, for the collapsed row. Decorative — the bar editor- * below carries the accessible values, so this stays out of the accessibility tree.- */+/** Decorative: the editor supplies accessible values. */export const ConditioningRebalanceSparkline = ({ muted, weights }: { muted?: boolean; weights: readonly number[] }) => (<SparklineSvgaria-hidden- // Sized with `h`/`w`, not the SVG `height`/`width` attributes: on a chakra-factory- // element those are style props, and a bare `56` resolves to the spacing token- // (14rem), not 56px.+ // Set explicit CSS dimensions to avoid numeric Chakra spacing-token interpretation.h={`${SPARKLINE_VIEW_HEIGHT}px`}preserveAspectRatio="none"style={SPARKLINE_STYLE}@@ -33,8 +25,6 @@ export const ConditioningRebalanceSparkline = ({ muted, weights }: { muted?: boo<SparklinePathd={getRebalanceSparklinePath(weights, SPARKLINE_VIEW_WIDTH, SPARKLINE_VIEW_HEIGHT)}fill="none"- // Switched off, the curve is still worth reading — just not in the accent colour,- // which is reserved for controls that are actually doing something.stroke={muted ? 'fg.muted' : 'accent.solid'}strokeWidth="1.5"vectorEffect="non-scaling-stroke"diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.browser.test.tsxindex 6254140aae..52f9504a2b 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.browser.test.tsx@@ -36,8 +36,7 @@ const render = async (children: React.ReactNode) => {describe('GenerateCollapsibleSection', () => {it('styles by DOM state so uncontrolled sections (no sectionId) still read as cards', async () => {- // Upscale's sections pass only defaultOpen — openness never reaches the- // component as a prop, so any prop-driven styling is blind to them.+ // defaultOpen-only consumers require DOM-state styling.await render(<GenerateCollapsibleSection defaultOpen label="Uncontrolled"><div>body</div>diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsxindex 9f1af98b1d..c13400dbc5 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsx@@ -15,30 +15,7 @@ type Props = {const COLLAPSIBLE_INDICATOR_OPEN_STYLES = { transform: 'rotate(90deg)' };-/**- * Closed: a quiet hairline row in the list. Open: a card — background, radius,- * breathing room — with no separators of its own.- *- * Three invariants make it feel right:- *- * - Everything keys off the DOM's `data-state`, not React state: sections- * without a `sectionId` (Upscale passes only `defaultOpen`) run uncontrolled,- * so their openness never reaches this component as a prop — the browser- * always has it.- * - The geometry is constant. The hosting Stack keeps a fixed `gap="1"`- * between rows in every state, so opening a section never adds a margin or a- * border — nothing below shifts by even a pixel.- * - The separators are pseudo-element overlays, not borders on the box, and- * exactly ONE line is painted per boundary, only BETWEEN rows: a section's- * `::before` (a 1px border-top centered in the gap) shows only when the- * element above it is another section — so nothing renders above the first- * row (even mid-stack, after non-section siblings) or below the last, and- * two overlapping halves never stack the translucent border color into a- * heavier line. Around an open card the touching lines fade out — the- * card's own via `data-state`, the one below it via `A + B`, since no- * section can see its neighbor's state on its own. Only opacity and- * background ever animate.- */+/** Style uncontrolled sections from DOM state; preserve geometry and draw one overlay separator per boundary. */const SECTION_OPEN_STYLES = { bg: 'bg.muted', rounded: 'sm' };const SECTION_STYLES = {'&::before': {@@ -52,8 +29,7 @@ const SECTION_STYLES = {transition: 'opacity var(--wb-motion-duration-slow) ease',},'.generate-section + &::before': { opacity: 1 },- // Order matters against the rule above: at equal specificity, an open- // section's own state must win over its predecessor's presence.+ // With equal specificity, open-state rules must follow preceding-section rules.'&[data-state="open"]::before': { opacity: 0 },'.generate-section[data-state="open"] + &::before': { opacity: 0 },} as const;diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsxindex 4a46cd305f..e233a726b8 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx@@ -17,11 +17,6 @@ interface GenerateFieldContextMenuProps {resetLabel?: string;}-/**- * Desktop-grade right-click on a model-governed field: Reset to model default- * and Copy value, anchored at the pointer. Wraps the field without affecting- * its layout; left-click behavior is untouched.- */export const GenerateFieldContextMenu = ({children,copyValue,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateToggleSwitch.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateToggleSwitch.tsxindex f34895b170..2e20ac2014 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateToggleSwitch.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateToggleSwitch.tsx@@ -11,11 +11,7 @@ interface GenerateToggleSwitchProps {onCheckedChange: (checked: boolean) => void;}-/**- * The one switch used across the Generate panel. Always owns its hidden-input- * ids: sibling switches inside a shared Field.Root would otherwise receive the- * same control id and a label click would toggle the wrong one.- */+/** Sibling switches sharing a Field need unique hidden-input IDs. */export const GenerateToggleSwitch = ({checked,disabled = false,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultSettings.ts b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultSettings.tsindex 39d18eff7b..43f2a25609 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultSettings.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultSettings.ts@@ -44,11 +44,7 @@ export const getModelDefaultsPatch = (return patch;};-/**- * The model-governed keys grouped into user-level decisions, so the override- * count reads as "3 overrides" the way a person made them: changing the size- * touches five keys but is one decision.- */+/** Multi-key decisions such as size count as one override. */const MODEL_DEFAULT_DECISION_GROUPS: readonly (readonly (typeof MODEL_DEFAULT_VALUE_KEYS)[number][])[] = [['aspectRatioId', 'aspectRatioIsLocked', 'aspectRatioValue', 'height', 'width'],['steps'],@@ -58,10 +54,7 @@ const MODEL_DEFAULT_DECISION_GROUPS: readonly (readonly (typeof MODEL_DEFAULT_VA['vaePrecision'],];-/**- * How many model-governed decisions deviate from the model's defaults. The VAE- * override and the LoRA set each count once.- */+/** Count each VAE or LoRA set once. */export const countModelDefaultOverrides = (settings: GenerateSettings,modelDefaultSettings: GenerateSettingsdiff --git a/invokeai/frontend/webv2/src/features/generation/ui/useDynamicPrompts.ts b/invokeai/frontend/webv2/src/features/generation/ui/useDynamicPrompts.tsindex 96596151f2..669527b345 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/useDynamicPrompts.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/useDynamicPrompts.ts@@ -5,10 +5,7 @@ import { dynamicPromptsQueryOptions } from '@features/generation/data/dynamicProimport { useQuery } from '@tanstack/react-query';import { useEffect, useState } from 'react';-/**- * On top of the Generate form's 250ms commit debounce, so a burst of typing- * settles before it costs a round trip.- */+/** This debounce follows the form commit debounce. */const DYNAMIC_PROMPTS_DEBOUNCE_MS = 500;const useDebouncedValue = <Value>(value: Value, delayMs: number): Value => {@@ -37,16 +34,11 @@ export interface DynamicPromptsExpansion {isDynamic: boolean;}-/**- * Reads the shared expansion cache. The Generate preview, the Invoke tooltip,- * and the submit path all address the same query key, so observing here neither- * duplicates a request nor goes stale relative to what is submitted.- */+/** Preview, tooltip, and submit share query identity. */export const useDynamicPrompts = (prompt: string, config: DynamicPromptsConfig | null): DynamicPromptsExpansion => {const isDynamic = Boolean(config) && hasDynamicPromptSyntax(prompt);const debouncedPrompt = useDebouncedValue(prompt, DYNAMIC_PROMPTS_DEBOUNCE_MS);- // A prompt that changed since the last debounce tick has a stale expansion, so- // report loading rather than a count the user is about to see change.+ // Remain loading while the current prompt differs from the debounced expansion.const isSettled = debouncedPrompt === prompt;const query = useQuery({...dynamicPromptsQueryOptions({diff --git a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.tsindex 191bb22941..564b53b050 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts@@ -20,13 +20,7 @@ export interface WildcardWrite {id?: string;}-/**- * A run of writes that stopped part-way, carrying how many had landed.- *- * The count is the point: the ones already written are real, and a caller that- * reports only "it failed" sends the user back for a second run that then- * clashes with everything the first one made.- */+/** Report completed writes on partial success so retries do not duplicate them. */export class WildcardWriteError extends Error {constructor(readonly done: number,@@ -45,38 +39,22 @@ export interface WildcardCatalog {create: (wildcard: { name: string; values: string[] }) => Promise<void>;update: (id: string, changes: { name?: string; values?: string[] }) => Promise<void>;remove: (id: string) => Promise<void>;- /**- * A run of writes with a single invalidation at the end.- *- * Resolves with how many landed, and rethrows whatever stopped it — the caller- * needs both to say "stopped after 6 of 40". Ordinary edits go through the- * single-write methods above; this exists for import, where doing it one call- * at a time meant re-fetching the whole catalog, plus every dynamic-prompt- * expansion, between each write and the next.- */+ /** Invalidate once after the batch; failures include the completed-write count. */applyWrites: (writes: readonly WildcardWrite[], owner: AccountScope) => Promise<number>;}-/**- * The shared wildcard catalog. Every mutation invalidates the dynamic prompts- * cache too, because editing a wildcard changes what an unchanged prompt expands- * to and that cache never goes stale on its own.- */+/** Wildcard edits invalidate otherwise permanent expansion entries. */export const useWildcards = (): WildcardCatalog => {const queryClient = useQueryClient();const query = useQuery(wildcardsQueryOptions());const wildcards = useMemo(() => query.data ?? [], [query.data]);- // Only a wildcard with values resolves; the backend omits empty ones from its- // manager, so an empty one must read as unknown here too.+ // The backend omits empty wildcards, so they must remain unknown.const knownNames = useMemo(() => new Set(wildcards.filter((wildcard) => wildcard.values.length > 0).map((wildcard) => wildcard.name)),[wildcards]);- // Each mutation captures the identity that started it, so a sign-out mid-flight- // does not invalidate the next account's caches on the way back. Stated once,- // as `usePromptTemplates` does — three copies of it was three chances for the- // next mutation added here to forget a step.+ // Capture identity separately for every mutation.const runAndInvalidate = useCallback(async (run: () => Promise<unknown>): Promise<void> => {const owner = captureAccountScope();@@ -122,10 +100,7 @@ export const useWildcards = (): WildcardCatalog => {failure = caught;}- // Whatever landed before the failure is real, so the caches are stale- // either way — invalidate on the strength of that rather than on the run- // having finished. The scope check stays where it is for every other- // mutation: a sign-out mid-run must not drop the next account's caches.+ // Invalidate after partial success, fenced to the originating account.if (done > 0) {assertAccountScopeCurrent(owner);await invalidateWildcardDependents(queryClient);diff --git a/invokeai/frontend/webv2/src/features/identity/capabilities.ts b/invokeai/frontend/webv2/src/features/identity/capabilities.tsindex 0e9302c8f0..7ec13c751b 100644--- a/invokeai/frontend/webv2/src/features/identity/capabilities.ts+++ b/invokeai/frontend/webv2/src/features/identity/capabilities.ts@@ -42,8 +42,7 @@ export const getCapabilities = (session: AuthSession): Capabilities => {// Matches the routers' `AdminUserOrDefault`: everyone qualifies in// single-user mode, only admins once multiuser is on.canManagePromptTemplates: isAdmin,- // The router lets an admin write any prompt; the UI offers it only for shared ones, so an- // admin never edits another user's private prompt by accident.+ // Offer admin edits only for shared prompts to avoid accidental edits to another user's private content.canManageSharedSystemPrompts: isAdmin,canManageUsers: session.multiuserEnabled && session.user?.is_admin === true,};diff --git a/invokeai/frontend/webv2/src/features/identity/core/schemas.ts b/invokeai/frontend/webv2/src/features/identity/core/schemas.tsindex d1ee8bc4ed..62825df71d 100644--- a/invokeai/frontend/webv2/src/features/identity/core/schemas.ts+++ b/invokeai/frontend/webv2/src/features/identity/core/schemas.ts@@ -1,11 +1,6 @@import { z } from 'zod';-/**- * Form schemas for the auth surfaces. Password rules mirror the backend's- * `validate_password_strength`: 8+ characters with an uppercase letter, a- * lowercase letter, and a digit. When strict checking is off the backend- * accepts any non-empty password, so the schemas relax to match.- */+/** Strict passwords mirror backend strength checks; relaxed mode accepts any nonempty password. */export type PasswordStrength = 'weak' | 'moderate' | 'strong';@@ -91,11 +86,7 @@ export const createProfileSchema = (strict: boolean) =>export type ProfileFormValues = z.infer<ReturnType<typeof createProfileSchema>>;-/**- * One shape serves both admin user-form modes. Creating requires email and- * password; editing ignores the email field and treats an empty password as- * "leave unchanged".- */+/** Creation requires email/password; editing ignores email and treats an empty password as unchanged. */export const createUserFormSchema = (strict: boolean, requireCredentials: boolean) =>z.object({displayName: z.string(),diff --git a/invokeai/frontend/webv2/src/features/identity/data/api.ts b/invokeai/frontend/webv2/src/features/identity/data/api.tsindex 36c68fd457..6ad2526169 100644--- a/invokeai/frontend/webv2/src/features/identity/data/api.ts+++ b/invokeai/frontend/webv2/src/features/identity/data/api.ts@@ -1,10 +1,6 @@import { apiFetch, apiFetchJson } from '@platform/transport/http';-/**- * REST surface for the backend's multi-user endpoints (`/api/v1/auth`). Field- * names mirror the backend DTOs verbatim; the session store and components own- * any reshaping.- */+/** Keep auth transport DTO field names unchanged; session state and components own reshaping. */const AUTH_BASE = '/api/v1/auth';@@ -73,13 +69,8 @@ export const logout = (): Promise<{ success: boolean }> =>apiFetchJson<{ success: boolean }>(`${AUTH_BASE}/logout`, { method: 'POST' });/**- * Re-issues the HttpOnly cookie that authenticates `<img>` / `<video>` media requests.- *- * Login sets the cookie, but a session restored from stored-token state has a valid JWT and- * no cookie — it may predate the cookie, or the cookie may have been cleared while the token- * survived. Media elements cannot send an Authorization header, so such a session loads every- * other API call fine while showing blank thumbnails. In single-user mode the backend returns- * success without setting anything, so this is a safe no-op there.+ * Restore the media cookie for stored-token sessions before elements load; they cannot send bearer headers.+ * Single-user backends safely no-op.*/export const refreshMediaCookie = (signal?: AbortSignal): Promise<{ success: boolean }> =>apiFetchJson<{ success: boolean }>(`${AUTH_BASE}/media-cookie`, { method: 'POST', signal });diff --git a/invokeai/frontend/webv2/src/features/identity/session.test.ts b/invokeai/frontend/webv2/src/features/identity/session.test.tsindex c1a53268ae..c165583156 100644--- a/invokeai/frontend/webv2/src/features/identity/session.test.ts+++ b/invokeai/frontend/webv2/src/features/identity/session.test.ts@@ -440,8 +440,7 @@ describe('media cookie recovery on restore', () => {await session.ensureAuthSession();- // A restored session has a valid JWT but no media cookie, so every <img> would 401- // without this call. Login needs no equivalent — the backend sets the cookie there.+ // Restored JWT sessions need a media cookie refresh; login already sets it.expect(api.refreshMediaCookie).toHaveBeenCalledTimes(1);expect(session.getAuthSession()).toMatchObject({ phase: 'ready', user });});diff --git a/invokeai/frontend/webv2/src/features/identity/session.ts b/invokeai/frontend/webv2/src/features/identity/session.tsindex c3fd2ea0e8..5392e2766a 100644--- a/invokeai/frontend/webv2/src/features/identity/session.ts+++ b/invokeai/frontend/webv2/src/features/identity/session.ts@@ -15,11 +15,8 @@ import {} from './data/api';/**- * Session-lived auth state shared by the router guards and shell chrome. When- * multi-user is disabled on the backend, the resolved snapshot keeps the- * entire auth surface — login screen, user menu, expiry handling — dormant.- * Until that mode is known, `phase` keeps the otherwise conservative boolean- * defaults from being interpreted as a single-user grant.+ * Keep auth surfaces dormant in single-user mode; unresolved phase must never interpret conservative defaults as a+ * grant.*/export interface AuthSession {/** Remount key for every authenticated lifetime, including same-user logins. */@@ -67,11 +64,7 @@ const getAccountLifecycle = (): IdentityAccountLifecycle => {export const useAuthSession = (): AuthSession => store.useSnapshot();-/**- * Imperative read for non-reactive callers (e.g. the widget registry). Safe- * inside the workbench: the route guard resolves the session before mounting,- * and a user change remounts the whole workbench route.- */+/** Workbench imperative reads follow route-guard resolution; changing users remounts the route. */export const getAuthSession = (): AuthSession => store.getSnapshot();/** Stable subscription for App-composed capability read ports. */@@ -98,11 +91,7 @@ const activateResolvedAccount = (multiuserEnabled: boolean, user: UserDTO | null: getAccountLifecycle().invalidate().epoch;};-/**- * Suffix for localStorage keys holding user-owned state (projects, account- * preferences, personal API keys — see the spec's State Ownership section).- * Empty in single-user mode, so existing keys keep working unchanged.- */+/** Scope user-owned storage keys by account; single-user mode preserves existing unsuffixed keys. */export const getUserStorageScope = (): string => {const session = store.getSnapshot();@@ -190,9 +179,8 @@ const resolveSession = async (): Promise<AuthSession> => {try {status = await getAuthStatus();} catch {- // A network failure says nothing about the backend's auth mode. Publishing- // an unavailable state keeps every authenticated route and storage owner- // unmounted while allowing a later route retry to resolve the session.+ // Network failure cannot establish auth mode; keep routes and storage owners unmounted until a successful+ // retry.return publishUnavailableSession();}@@ -202,19 +190,15 @@ const resolveSession = async (): Promise<AuthSession> => {if (status.multiuser_enabled && !status.setup_required && browserIdentityTokenAdapter.get()) {try {user = await getCurrentUser();- // This branch is the restore-from-stored-token path, the one case that holds a valid JWT- // without the media cookie login would have set. Re-issue it before anything renders an- // <img>, or every thumbnail 401s. Awaited (a small POST) so the first paint already has- // the cookie, but never fatal: failing here leaves media broken, not the session.+ // Await restored-session media cookies before rendering. Refresh failure breaks media but must not+ // invalidate the authenticated session.await refreshMediaCookie().catch(() => undefined);} catch (error) {if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {browserIdentityTokenAdapter.clear();sessionExpired = true;} else {- // The auth mode is known, but the principal is not. Treat this like a- // status outage instead of incorrectly presenting the user as signed- // out and making unscoped storage reachable.+ // Unknown principal remains unavailable rather than signed out, preventing access to unscoped storage.return publishUnavailableSession();}}diff --git a/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsx b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsxindex 87355c89d3..0eee4d8132 100644--- a/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsx@@ -11,20 +11,13 @@ import { ProfileDialog } from './ProfileDialog';const MENU_POSITIONING = { placement: 'bottom-end' } as const;const TRIGGER_HOVER = { bg: 'bg.subtle' } as const;-/**- * The signed-in user's avatar menu — account settings, user management, and- * sign-out — shown on both the Launchpad and the workbench shell. Renders only- * in a multi-user session; the settings gear is a separate control that each- * surface's top bar places alongside it.- */+/** Show account actions only for multi-user sessions; each host places its separate settings control. */export const AccountMenu = () => {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]);diff --git a/invokeai/frontend/webv2/src/features/identity/ui/AccountMenuSection.tsx b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenuSection.tsxindex 3a45c72520..d3c33e00a3 100644--- a/invokeai/frontend/webv2/src/features/identity/ui/AccountMenuSection.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenuSection.tsx@@ -8,21 +8,13 @@ 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.- */+/** Embed account actions directly in host menus to avoid nested popovers; render nothing in single-user mode. */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]);diff --git a/invokeai/frontend/webv2/src/features/identity/ui/AuthScreen.tsx b/invokeai/frontend/webv2/src/features/identity/ui/AuthScreen.tsxindex d07590fcbd..ba9243d7fb 100644--- a/invokeai/frontend/webv2/src/features/identity/ui/AuthScreen.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/AuthScreen.tsx@@ -3,11 +3,7 @@ import type { ReactNode } from 'react';import { Alert, Flex, Heading, Stack, Text } from '@chakra-ui/react';import { InvokeMark } from '@platform/ui/InvokeMark';-/**- * Centered scaffold shared by the login and first-run setup screens. These- * render outside the workbench shell (and its providers), so they rely only on- * semantic tokens.- */+/** Auth screens live outside workbench providers and rely only on semantic tokens. */export const AuthScreen = ({children,footer,diff --git a/invokeai/frontend/webv2/src/features/identity/ui/AuthUnavailableScreen.tsx b/invokeai/frontend/webv2/src/features/identity/ui/AuthUnavailableScreen.tsxindex 355f1f24e2..c5c58ee22f 100644--- a/invokeai/frontend/webv2/src/features/identity/ui/AuthUnavailableScreen.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/AuthUnavailableScreen.tsx@@ -4,11 +4,7 @@ import { useTranslation } from 'react-i18next';import { AuthScreen } from './AuthScreen';-/**- * Fail-closed authentication availability boundary. This deliberately lives- * outside the workbench shell so no account-owned provider mounts before a- * retry has resolved the backend's auth mode and principal.- */+/** Keep account-owned providers unmounted until auth mode and principal resolve successfully. */export const AuthUnavailableScreen = ({ onRetry }: { onRetry: () => Promise<void> | void }) => {const { t } = useTranslation();const handleRetry = useCallback(() => {diff --git a/invokeai/frontend/webv2/src/features/identity/ui/LoginScreen.tsx b/invokeai/frontend/webv2/src/features/identity/ui/LoginScreen.tsxindex a69a869afc..1412c596b3 100644--- a/invokeai/frontend/webv2/src/features/identity/ui/LoginScreen.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/LoginScreen.tsx@@ -24,9 +24,8 @@ export const LoginScreen = () => {try {await loginWithCredentials(values.email, values.password, values.rememberMe);} catch (error) {- // A second submit, logout, or expiry owns the newer identity- // transition. The stale submit should neither navigate nor flash an- // error over the winning transition.+ // A newer identity transition supersedes this submit; stale completion must neither navigate nor report+ // an error.if (isLoginAttemptSupersededError(error)) {return;}diff --git a/invokeai/frontend/webv2/src/features/identity/ui/SetupScreen.tsx b/invokeai/frontend/webv2/src/features/identity/ui/SetupScreen.tsxindex 66594a637f..cafdad192c 100644--- a/invokeai/frontend/webv2/src/features/identity/ui/SetupScreen.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/SetupScreen.tsx@@ -13,10 +13,6 @@ import { PasswordInput, PasswordStrengthMeter } from './PasswordInput';const INITIAL_VALUES: SetupFormValues = { confirmPassword: '', displayName: '', email: '', password: '' };-/**- * First-run screen for multi-user mode: creates the administrator account and- * signs straight into it.- */export const SetupScreen = () => {const { t } = useTranslation();const session = useAuthSession();diff --git a/invokeai/frontend/webv2/src/features/identity/ui/UserFormDialog.tsx b/invokeai/frontend/webv2/src/features/identity/ui/UserFormDialog.tsxindex 0e716f46e7..81823d8f00 100644--- a/invokeai/frontend/webv2/src/features/identity/ui/UserFormDialog.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/UserFormDialog.tsx@@ -24,11 +24,7 @@ const getTargetKey = (target: UserFormTarget): string => (target.mode === 'edit'const SWITCH_CHECKED_STYLES = { bg: 'accent.solid' };-/**- * Create/edit user form for the users widget. The dialog root stays mounted- * and is driven by `target` (null = closed); the inner form is keyed by the- * target so each open starts from a fresh state.- */+/** Keep the dialog root mounted; key its form by target to reset state on each opening. */export const UserFormDialog = ({onClose,onSaved,diff --git a/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx b/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsxindex 6da40dff98..495952871e 100644--- a/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx@@ -14,12 +14,7 @@ const ROW_HOVER_STYLES = { bg: 'bg.muted' };const SWITCH_CHECKED_STYLES = { bg: 'accent.solid' };const DELETE_BUTTON_HOVER_STYLES = { color: 'fg.error' };-/**- * Admin-only center view: the workspace user directory with create, edit,- * activate/deactivate, and delete. The widget is already hidden for- * non-admins via `requiresAdmin`; the inline guard covers stale persisted- * layouts that still point at it.- */+/** Guard admin access inline as well as in the widget manifest to cover stale persisted layouts. */export const UserManagement = () => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsx b/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsxindex 4e9e709430..f179c586dc 100644--- a/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsx@@ -3,11 +3,6 @@ import { useTranslation } from 'react-i18next';import { UsersManagementPanel } from './UserManagement';-/**- * Admin-only section: create, edit, and remove users. Shares the Launchpad's- * page chrome, so it carries the same heading, measure, and self-scroll as the- * project library instead of its own copy of them.- */export const UsersPage = () => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/features/models/core/library.test.ts b/invokeai/frontend/webv2/src/features/models/core/library.test.tsindex e1bfdc59bb..b53b4d79f1 100644--- a/invokeai/frontend/webv2/src/features/models/core/library.test.ts+++ b/invokeai/frontend/webv2/src/features/models/core/library.test.ts@@ -106,8 +106,7 @@ describe('getModelPickerGroups', () => {expect(result.groups.map((group) => group.base)).toEqual(['sd-1', 'sdxl']);});- // Type is not a grouping axis: a cross-type picker would otherwise repeat a- // "Main Models" header above every base section.+ // Group by base alone so cross-type pickers do not repeat type headings.it('groups by base alone, in base display order', () => {const result = getModelPickerGroups(library, {modelTypes: ['main', 'lora', 'vae'],diff --git a/invokeai/frontend/webv2/src/features/models/core/library.ts b/invokeai/frontend/webv2/src/features/models/core/library.tsindex 048cb35750..f45f00c5fc 100644--- a/invokeai/frontend/webv2/src/features/models/core/library.ts+++ b/invokeai/frontend/webv2/src/features/models/core/library.ts@@ -3,11 +3,6 @@ import type { ModelConfig, ModelTaxonomyType } from './types';import { getModelBaseLabel, KNOWN_MODEL_BASES } from './baseIdentity';import { getModelCategoryRank, getModelTypePluralLabel } from './taxonomy';-/**- * Pure filtering/grouping/sorting for the model library. Kept free of React so- * the list views stay thin and this logic is unit-testable.- */-export type ModelSortField = 'default' | 'name' | 'base' | 'size' | 'format' | 'type' | 'path';export interface ModelLibraryFilters {@@ -49,11 +44,7 @@ export interface ModelPickerOptions {relatedKeys?: ReadonlySet<string>;}-/**- * Picker list group: one per base. Type is deliberately NOT a grouping axis —- * a cross-type picker would otherwise repeat "Main Models" above every base- * section. Rows in a multi-type picker carry their own type badge instead.- */+/** Group by base; multi-type rows carry badges rather than repeated type section headings. */export interface ModelPickerGroup {key: string;base: string;@@ -169,8 +160,6 @@ export const getModelPickerGroups = (models: ModelConfig[], options: ModelPicker// sibling picker's choice) must not filter everything out behind a hidden chip.const baseFilter = new Set(availableBases.filter((base) => options.baseFilter?.has(base)));const { relatedKeys } = options;- // Bases order the groups; within a group, related models lead, then category- // rank keeps main models above LoRAs in a cross-type picker, then name.const visibleModels = candidates.filter((model) => baseFilter.size === 0 || baseFilter.has(String(model.base))).sort(@@ -210,11 +199,7 @@ export const collectBases = (models: Pick<ModelConfig, 'base'>[]): string[] =>/** Bases that exist but carry no architecture meaning, sorted after the rest. */const DEPRIORITIZED_BASES: ReadonlySet<string> = new Set(['any', 'external', 'unknown']);-/**- * Distinct bases present, ordered for display: known bases follow the- * registry order from `baseIdentity`, unknown bases come next, and the- * meaningless `any`/`external`/`unknown` bases are pushed to the very end.- */+/** Order known bases by registry, then unfamiliar bases, with any/external/unknown last. */const KNOWN_BASE_RANKS = new Map<string, number>(KNOWN_MODEL_BASES.map((base, index) => [base, index]));/** Display rank for a base: registry order, unknown bases next, meaningless bases last. */diff --git a/invokeai/frontend/webv2/src/features/models/core/modelSettingsIO.ts b/invokeai/frontend/webv2/src/features/models/core/modelSettingsIO.tsindex 8f01e09847..e43a789929 100644--- a/invokeai/frontend/webv2/src/features/models/core/modelSettingsIO.ts+++ b/invokeai/frontend/webv2/src/features/models/core/modelSettingsIO.ts@@ -1,12 +1,6 @@import type { ModelConfig } from './types';-/**- * Pure logic for exporting a model's user-editable settings to JSON and- * validating/partitioning an import. The file format is shared with the- * legacy frontend: `{name?, description?, source_url?, default_settings?,- * trigger_phrases?, cpu_only?, cover_image? (data URL)}`. Anything that- * fetches or writes lives in the UI layer.- */+/** Keep JSON settings compatible with legacy exports; pure validation partitions imports while UI owns transport. */export const sanitizeFilename = (name: string): string => name.replace(/[<>:"/\\|?*]/g, '_');@@ -135,12 +129,7 @@ export const validateImportData = (data: unknown): data is Record<string, unknowreturn true;};-/**- * Split validated import data into a PATCH body of fields the target model's- * config actually carries, and the fields skipped as incompatible (e.g.- * cpu_only imported onto a main model). The cover image is not part of the- * body — it uploads through its own endpoint.- */+/** PATCH only supported config fields and report incompatible ones; upload cover images separately. */export const partitionImportableFields = (data: Record<string, unknown>,model: ModelConfigdiff --git a/invokeai/frontend/webv2/src/features/models/core/relationships.ts b/invokeai/frontend/webv2/src/features/models/core/relationships.tsindex 87aba45561..cc7c156b84 100644--- a/invokeai/frontend/webv2/src/features/models/core/relationships.ts+++ b/invokeai/frontend/webv2/src/features/models/core/relationships.ts@@ -1,28 +1,17 @@import type { ModelBase, ModelConfig, ModelTaxonomyType } from './types';-/**- * Compatibility rules for the bidirectional "related models" links. A link is- * a curation hint ("this LoRA pairs well with this checkpoint"), so the rule- * only permits pairs that can actually appear in one pipeline.- */+/** Related-model links are symmetric curation hints and permit only models usable in one pipeline. *//** The two fields the compatibility rule reads. */export type RelatableModel = Pick<ModelConfig, 'base' | 'type'>;/**- * Bases that carry no architecture meaning. `any` is the backend's null value- * for models with no base association (encoders, CLIP, Spandrel, ...), NOT a- * universal-compatibility wildcard; `external` and `unknown` say nothing- * about what a model pairs with.+ * any denotes no base association, not universal compatibility; external and unknown convey no architecture+ * compatibility.*/export const NULL_BASES: ReadonlySet<string> = new Set(['any', 'external', 'unknown']);-/**- * Curated allowances: `any`-based helper types mapped to the concrete bases- * whose pipelines actually consume them. Each entry cites the backend- * invocation(s) that take the helper as an input — configs over- and- * under-state real usage, so invocations are the source of truth here.- */+/** Cite consuming backend invocations for each any-based helper allowance; config metadata alone is insufficient. */export const NULL_BASE_ALLOWANCES: Readonly<Partial<Record<ModelTaxonomyType, ReadonlySet<ModelBase>>>> = {/** CLIP text encoders (flux_model_loader, sd3_model_loader). */clip_embed: new Set(['flux', 'sd-3']),@@ -46,11 +35,7 @@ export const NULL_BASE_ALLOWANCES: Readonly<Partial<Record<ModelTaxonomyType, Rewan_t5_encoder: new Set(['wan']),};-/**- * Curated cross-base allowances for concrete-based helper types: helper base- * mapped to the host bases whose pipelines consume it. Same sourcing rule as- * `NULL_BASE_ALLOWANCES` — each entry cites the backend invocation(s).- */+/** Cross-base helper allowances cite consuming backend invocations, like NULL_BASE_ALLOWANCES. */export const CROSS_BASE_ALLOWANCES: Readonly<Partial<Record<ModelTaxonomyType, Readonly<Partial<Record<ModelBase, ReadonlySet<ModelBase>>>>>>> = {@@ -71,10 +56,6 @@ export const CROSS_BASE_ALLOWANCES: Readonly<},};-/**- * Types offered when linking related models. The concrete-based helper types,- * plus every `any`-based type with a curated allowance.- */export const LINKABLE_TYPES: readonly ModelTaxonomyType[] = ['main','lora',@@ -93,11 +74,7 @@ const LINKABLE_TYPE_SET: ReadonlySet<ModelTaxonomyType> = new Set(LINKABLE_TYPESexport const isLinkableType = (type: ModelTaxonomyType): boolean => LINKABLE_TYPE_SET.has(type);-/**- * Whether any candidate could ever be compatible with this model: a concrete- * base, or an `any` base whose type has a curated allowance. `external` and- * `unknown` subjects can never take new links.- */+/** Only concrete bases or explicitly allowed any-based helper types can receive new links. */export const hasLinkableBase = (model: RelatableModel): boolean =>!NULL_BASES.has(String(model.base)) || (model.base === 'any' && NULL_BASE_ALLOWANCES[model.type] !== undefined);@@ -110,10 +87,8 @@ const isAllowedCrossBaseHelperFor = (helper: RelatableModel, host: RelatableModeCROSS_BASE_ALLOWANCES[helper.type]?.[helper.base]?.has(host.base) ?? false;/**- * Symmetric base-compatibility for related-model links: concrete bases must- * match exactly unless the helper's type has a curated cross-base allowance;- * a null base never wildcards — an `any`-based model links only to concrete- * bases its type has a curated allowance for.+ * Match concrete bases unless a helper allowance permits crossing; any-based models require explicit concrete-host+ * allowances.*/export const isBaseCompatible = (a: RelatableModel, b: RelatableModel): boolean => {if (!NULL_BASES.has(String(a.base)) && !NULL_BASES.has(String(b.base))) {@@ -123,13 +98,7 @@ export const isBaseCompatible = (a: RelatableModel, b: RelatableModel): booleanreturn isAllowedHelperFor(a, b) || isAllowedHelperFor(b, a);};-/**- * Types that occupy exactly one slot in a pipeline, so linking two of them is- * never a meaningful "used together" hint. Mirrors legacy's- * `DISALLOWED_RELATIONSHIPS` self-pairs, extended to the single-slot helper- * types made linkable since. Stackable types (lora, embedding, ip_adapter,- * t2i_adapter) stay self-linkable.- */+/** Single-slot types cannot meaningfully link to their own type; stackable adapters, LoRAs, and embeddings can. */const SINGLETON_LINK_TYPES: ReadonlySet<ModelTaxonomyType> = new Set<ModelTaxonomyType>(['main','vae',diff --git a/invokeai/frontend/webv2/src/features/models/core/schemas.test.ts b/invokeai/frontend/webv2/src/features/models/core/schemas.test.tsindex ea392b3045..509d3b7b46 100644--- a/invokeai/frontend/webv2/src/features/models/core/schemas.test.ts+++ b/invokeai/frontend/webv2/src/features/models/core/schemas.test.ts@@ -51,9 +51,7 @@ describe('resolveModelAbsolutePath', () => {describe('mainDefaultSettingsSchema', () => {it('accepts the guidance this app itself stores for FLUX.1 Fill', () => {- // `defs/flux.py` declares `guidance=30.0` for the dev_fill variant, so a newly identified- // FLUX Fill model carries it. The ceiling here used to be 20, which meant opening such a- // model and saving any field was refused with a message about a value the user never typed.+ // FLUX Fill defaults to guidance 30; editing unrelated fields must accept that stored value.const result = mainDefaultSettingsSchema.safeParse({cfgRescaleMultiplier: null,cfgScale: 1,diff --git a/invokeai/frontend/webv2/src/features/models/core/schemas.ts b/invokeai/frontend/webv2/src/features/models/core/schemas.tsindex 0009013758..06ffb813a4 100644--- a/invokeai/frontend/webv2/src/features/models/core/schemas.ts+++ b/invokeai/frontend/webv2/src/features/models/core/schemas.ts@@ -1,12 +1,5 @@import { z } from 'zod';-/**- * Zod schemas for the model-manager forms with structured validation (edit,- * default settings, trigger phrases). User input goes through these before- * touching the API, so error states are consistent and the API layer can- * assume well-formed values.- */-const trimmed = z.string().trim();export const modelEditSchema = z.object({@@ -30,18 +23,12 @@ const optionalBoundedNumber = (min: number, max: number, label: string) =>.max(max, `${label} must be at most ${max}.`).nullable();-/**- * Per-model generation defaults. Every field is nullable — null means "no- * default, use the app-level setting" and maps to an unchecked toggle.- */+/** Null means inherit the app default and corresponds to an unchecked field toggle. */export const mainDefaultSettingsSchema = z.object({cfgRescaleMultiplier: optionalBoundedNumber(0, 0.99, 'CFG rescale multiplier'),cfgScale: optionalBoundedNumber(1, 200, 'CFG scale'),- // Mirrors `MainModelDefaultSettings.guidance` on the record, which is `ge=1` with no ceiling.- // The ceiling used to be 20, which is below a value the app itself stores: FLUX.1 Fill's- // declared default is 30, so opening such a model and saving any field was refused. The real- // per-architecture ceiling is served as `features.guidance_max` and belongs to the generation- // feature, not here -- this schema only guards against nonsense, like cfgScale's 200 above.+ // Record validation permits guidance >=1 without an architecture ceiling; generation owns guidance_max. Accept+ // FLUX Fill's stored default of 30.guidance: optionalBoundedNumber(1, 200, 'Guidance'),height: optionalBoundedNumber(64, 8192, 'Height').refine((value) => value === null || value % 8 === 0,@@ -61,9 +48,7 @@ export const mainDefaultSettingsSchema = z.object({export type MainDefaultSettingsFormValues = z.infer<typeof mainDefaultSettingsSchema>;-// Mirrors the backend validator (configs/lora.py): the effective slider range-// falls back to [-1, 2], min must stay below max, and an enabled weight must-// sit inside the effective range — otherwise the save 409s.+// Mirror backend LoRA validation: default range [-1, 2], min < max, and enabled weight within the effective range.export const loraDefaultSettingsSchema = z.object({weight: optionalBoundedNumber(-10, 10, 'Weight'),diff --git a/invokeai/frontend/webv2/src/features/models/core/taxonomy.test.ts b/invokeai/frontend/webv2/src/features/models/core/taxonomy.test.tsindex b8ff9d2025..c44e556442 100644--- a/invokeai/frontend/webv2/src/features/models/core/taxonomy.test.ts+++ b/invokeai/frontend/webv2/src/features/models/core/taxonomy.test.ts@@ -63,12 +63,10 @@ describe('variant options', () => {});it('offers both Qwen3-VL sizes, because the field is required on the config', () => {- // With no entry the edit form renders "None" plus the current value, and saving "None" sends- // `variant: null` into a required field — a 500 on a choice the form itself offered.+ // Required variants must not offer None, which would send invalid null during save.expect(getVariantOptionsFor('any', 'qwen3_vl_encoder')).toEqual(['qwen3_vl_4b', 'qwen3_vl_8b']);expect(getModelVariantLabel('qwen3_vl_8b')).toBe('Qwen3-VL 8B (Ideogram 4)');- // MiniMax H3's Qwen3-VL-32B shares the type under its own base and has no variant field, so- // offering the two sizes there would offer a save that can only fail.+ // MiniMax H3 shares the encoder type but lacks a variant field; size choices would fail saving.expect(getVariantOptionsFor('minimax-h3', 'qwen3_vl_encoder')).toEqual([]);});diff --git a/invokeai/frontend/webv2/src/features/models/core/taxonomy.ts b/invokeai/frontend/webv2/src/features/models/core/taxonomy.tsindex ff686a324f..8bf13d0601 100644--- a/invokeai/frontend/webv2/src/features/models/core/taxonomy.ts+++ b/invokeai/frontend/webv2/src/features/models/core/taxonomy.ts@@ -2,11 +2,7 @@ import type { ModelFileFormat, ModelTaxonomyType } from './types';import { toTitleCase } from './baseIdentity';-/**- * Display metadata for the model taxonomy. Open-union friendly: unknown bases,- * types, and formats fall back to readable generic labels so a backend that- * ships a new architecture never renders a blank or broken library.- */+/** Use readable fallback labels for unknown taxonomy values so new backend architectures remain usable. */interface CategoryDefinition {type: ModelTaxonomyType;@@ -83,13 +79,7 @@ const FORMAT_LABELS: Record<string, string> = {export const getModelFormatLabel = (format: ModelFileFormat): string => FORMAT_LABELS[format] ?? toTitleCase(format);-/**- * Formats a user may assign in the edit form (repairing a mis-detected- * model). `unknown` is not a repair target and `external_api` would misroute- * a local model, mirroring the base select's `external` exclusion. The PATCH- * re-validates through the config factory, so an invalid combination is- * rejected server-side rather than silently accepted.- */+/** Exclude unknown/external_api as repair formats; the config factory validates remaining combinations server-side. */export const EDITABLE_MODEL_FORMATS: readonly string[] = Object.keys(FORMAT_LABELS).filter((format) => format !== 'unknown' && format !== 'external_api');@@ -174,9 +164,7 @@ const VARIANTS_BY_TYPE: Record<string, readonly string[]> = {mistral_encoder: ['cow_mistral3_small', 'mistral3_24b', 'ministral3_3b'],pid_decoder: ['res2k_sr4x', 'res2kto4k_sr4x'],qwen3_encoder: ['qwen3_4b', 'qwen3_8b', 'qwen3_06b'],- // Required on the config, so the edit form must offer both: without an entry here it would show- // only "None" plus the current value, and saving "None" fails validation on the way into the- // database.+ // Required variant configs need explicit choices; a fallback None would fail database validation.qwen3_vl_encoder: ['qwen3_vl_4b', 'qwen3_vl_8b'],};@@ -194,9 +182,7 @@ export const getVariantOptionsFor = (base: string, type: string): readonly strin}if (type === 'qwen3_vl_encoder') {- // MiniMax H3's truncated Qwen3-VL-32B shares this model type under its own base and its config- // has no `variant` field at all, so offering the two sizes there would be offering a save that- // can only fail. The encoders that carry the field are base-agnostic components.+ // Only base-agnostic encoders carry variant; MiniMax H3's same-type encoder does not support size selection.return base === 'any' ? (VARIANTS_BY_TYPE[type] ?? []) : [];}diff --git a/invokeai/frontend/webv2/src/features/models/core/types.ts b/invokeai/frontend/webv2/src/features/models/core/types.tsindex 22c5d25896..9a64332dcc 100644--- a/invokeai/frontend/webv2/src/features/models/core/types.ts+++ b/invokeai/frontend/webv2/src/features/models/core/types.ts@@ -1,9 +1,6 @@/**- * Contracts for the backend model manager (`/api/v2/models/*`). Shapes mirror- * the pydantic models in `invokeai/backend/model_manager` and- * `invokeai/app/services/model_install` (serialized as snake_case). Unions are- * kept open (`| (string & {})`) so new backend architectures appear in the UI- * without a frontend release — unknown values fall back to generic labels.+ * Mirror snake_case backend model contracts with open unions so unknown architectures display generic labels+ * without a frontend release.*//** Known model base architectures. Open union: new bases still render. */diff --git a/invokeai/frontend/webv2/src/features/models/data/apiKeys.ts b/invokeai/frontend/webv2/src/features/models/data/apiKeys.tsindex 941fad8182..ace37fd564 100644--- a/invokeai/frontend/webv2/src/features/models/data/apiKeys.ts+++ b/invokeai/frontend/webv2/src/features/models/data/apiKeys.ts@@ -1,11 +1,8 @@import { getUserStorageScope } from '@features/identity';/**- * Client-side API key storage for remote model sources. The HuggingFace token- * lives on the backend (`/api/v2/models/hf_login`); the Civitai key has no- * backend home, so it is kept in this browser's localStorage and passed as the- * `access_token` query param when installing from a matching URL. The key is- * personal, so it is scoped per signed-in user on multi-user backends.+ * HuggingFace credentials live server-side; Civitai keys are account-scoped browser storage and become+ * access_token only on matching install URLs.*/const CIVITAI_KEY_BASE_STORAGE_KEY = 'invokeai-webv2-civitai-api-key';diff --git a/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.ts b/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.tsindex e56fb7fcf7..721fdfced5 100644--- a/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.ts+++ b/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.ts@@ -14,12 +14,7 @@ import {type ExternalProviderConfig,} from './api';-/**- * Shared cache of external image-provider configs. One store keeps every- * consumer consistent: saving a key on the Keys tab immediately flips the- * Configure/Installed affordances in the add-models starter list, with no- * remount or refetch.- */+/** Share provider config state so credential saves immediately update installation affordances. */export interface ExternalProvidersSnapshot {/** null = not fetched yet. */diff --git a/invokeai/frontend/webv2/src/features/models/data/installsStore.ts b/invokeai/frontend/webv2/src/features/models/data/installsStore.tsindex 6f4ea9e5c8..9a06f0c8ec 100644--- a/invokeai/frontend/webv2/src/features/models/data/installsStore.ts+++ b/invokeai/frontend/webv2/src/features/models/data/installsStore.ts@@ -15,12 +15,8 @@ import { refreshModels } from './modelsStore';import { refreshStartersIfLoaded } from './startersStore';/**- * Live store for model install jobs. The job list itself is REST-owned- * (`/api/v2/models/install`) and refreshed on lifecycle socket events;- * download progress is high-frequency transient data that bypasses the list- * (and the workbench reducer) entirely — each queue row subscribes to its own- * job id and only re-renders when that job's bytes move. This mirrors the- * generation `progressStore` pattern.+ * REST owns install jobs; lifecycle events refresh them. High-frequency progress bypasses the list and subscribes+ * per job to limit renders.*/export interface InstallsSnapshot {@@ -45,11 +41,8 @@ export interface InstallOutcome {}/**- * Human-readable source for an install job or install socket payload. Accepts- * `unknown` so untyped socket payloads and typed job sources produce the SAME- * string — active-install matching compares these labels. Lives here rather- * than in `core/taxonomy` so the eagerly-loaded data layer does not pull the- * taxonomy module out of the lazy UI chunks (the initial-graph byte budget).+ * Normalize typed and socket source labels identically for matching; colocate here to keep taxonomy out of eager+ * chunks.*/export const getInstallSourceLabel = (source: unknown): string => {if (typeof source === 'string') {@@ -72,8 +65,7 @@ export const getInstallSourceLabel = (source: unknown): string => {};const REFRESH_COALESCE_MS = 250;-// Display cap and eviction margin in one: comfortably above any completion-// burst that could land between two toast-effect flushes.+// Bound display history with room for completion bursts between toast flushes.const OUTCOME_LIMIT = 64;const EMPTY_INSTALLS_SNAPSHOT: InstallsSnapshot = { error: null, jobs: [], status: 'idle' };@@ -162,11 +154,7 @@ const scheduleRefresh = (): void => {}, REFRESH_COALESCE_MS);};-/**- * Revalidate the library + starter flags after installs land. Coalesced like- * `scheduleRefresh`: a bundle whose jobs complete in a burst triggers one- * full-library refetch, not one per completion event.- */+/** Coalesce install-completion bursts into one library/starter revalidation. */const scheduleCatalogRefresh = (): void => {if (catalogRefreshTimer !== null) {return;@@ -260,8 +248,7 @@ export const handleModelInstallSocketEvent = (}if (event === 'model_install_complete' || event === 'model_install_error' || event === 'model_install_cancelled') {- // The settled job stays listed until "Clear finished", but its byte- // progress is dead weight the moment it stops downloading.+ // Retain settled jobs until cleared, but release their inactive byte-progress state.progressByJobId.delete(data.id);}@@ -303,10 +290,7 @@ export const useInstallsSelector = store.useSelector;export const getInstallsSnapshot = (): InstallsSnapshot => store.getSnapshot();-/**- * Source strings (URL, repo id, or path) of jobs currently in flight, cached- * per jobs-array so list rows can show an "installing" state by source.- */+/** Cache active source strings by jobs-array identity for installing affordances. */const areSetsEqual = <Value>(left: ReadonlySet<Value>, right: ReadonlySet<Value>): boolean =>left.size === right.size && Array.from(left).every((value) => right.has(value));diff --git a/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts b/invokeai/frontend/webv2/src/features/models/data/modelsStore.tsindex 67b148e8fa..6c2279dc7c 100644--- a/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts@@ -13,12 +13,8 @@ import { getApiErrorMessage } from '@platform/transport/http';import { getModelsDir, listMissingModels, listModels } from './api';/**- * Shared library store for installed model configs. Lives outside the- * workbench reducer because the list is backend-owned server state shared by- * every model surface (manager, detail views, pickers); a single- * module store keeps them consistent and avoids re-fetch storms. Mutations go- * through the API layer and then either patch the snapshot in place (fast- * path) or trigger a refresh.+ * Share backend-owned model state outside the workbench reducer; mutations patch snapshots or refresh to keep all+ * surfaces consistent.*/export interface ModelsSnapshot {@@ -139,11 +135,7 @@ export const removeModelsFromStore = (keys: string[]): void => {store.patchSnapshot(withModels(store.getSnapshot().models.filter((model) => !removed.has(model.key))));};-/**- * Record a cover image upload/removal without refetching: keeps the truthy- * `cover_image` marker in sync for thumbnails and bumps the version that- * cache-busts their URLs (the backend serves the image at a stable URL).- */+/** Update cover presence and URL version without refetching; backend cover URLs remain stable. */export const markCoverImageChanged = (key: string, hasImage: boolean): void => {const { coverImageVersions, models } = store.getSnapshot();diff --git a/invokeai/frontend/webv2/src/features/models/data/relationshipsApi.ts b/invokeai/frontend/webv2/src/features/models/data/relationshipsApi.tsindex 3b974212c5..7a03f6b98a 100644--- a/invokeai/frontend/webv2/src/features/models/data/relationshipsApi.ts+++ b/invokeai/frontend/webv2/src/features/models/data/relationshipsApi.ts@@ -1,11 +1,6 @@import { apiFetch, apiFetchJson } from '@platform/transport/http';-/**- * REST client for `/api/v1/model_relationships`, kept separate from `api.ts`- * so the lazily-loaded relationships store is a self-contained chunk: sharing- * the models api module with the eager modelsStore would split that module- * into an extra eagerly-fetched chunk (the initial-request budget).- */+/** Keep relationships transport independent so its lazy store does not create another eager shared API chunk. */const RELATIONSHIPS_BASE = '/api/v1/model_relationships';diff --git a/invokeai/frontend/webv2/src/features/models/data/relationshipsStore.ts b/invokeai/frontend/webv2/src/features/models/data/relationshipsStore.tsindex ab02ecc529..e2636055de 100644--- a/invokeai/frontend/webv2/src/features/models/data/relationshipsStore.ts+++ b/invokeai/frontend/webv2/src/features/models/data/relationshipsStore.ts@@ -12,17 +12,8 @@ import { getModelsSnapshot, subscribeModels } from './modelsStore';import { addModelRelationship, getRelatedModelKeys, removeModelRelationship } from './relationshipsApi';/**- * Shared cache of bidirectional "related model" links, keyed by model key.- * One store keeps the detail pane and every open picker consistent: link and- * unlink patch both cached directions instead of refetching. Cache writes are- * ordered: per pair, only the latest mutation's response commits, and a- * response that settles after its models were deleted is dropped.- *- * The backend's batch endpoint (`POST /model_relationships/batch`) is- * deliberately unused — it returns a flat de-duplicated union across the input- * keys, which cannot populate a per-key cache. Per-key fetches through- * `ensureRelatedModelKeysLoaded` stay attributable and dedupe on the inflight- * map.+ * Patch both relationship directions; only latest per-pair mutations may commit, and deleted models discard late+ * responses. Fetch per key because batch unions lose attribution.*/export interface ModelRelationshipsSnapshot {@@ -43,12 +34,7 @@ const inflightByKey = new Map<string, Promise<void>>();/** Keys whose last settled fetch rejected; `ensure` revalidates these. */const failedFetchKeys = new Set<string>();-/**- * Mutation responses outlive the component that issued them (the section- * remounts per model key), so link/unlink ordering cannot rely on UI pending- * state. Each pair's latest in-flight mutation holds a stamp here; a response- * whose stamp has been superseded must not write to the cache.- */+/** Order mutations per pair outside component lifetimes; superseded responses must not update cache. */let nextMutationStamp = 1;const latestPairMutation = new Map<string, number>();@@ -72,13 +58,8 @@ registerAccountOwnedResource({});/**- * Library-driven pruning: when a loaded library snapshot no longer contains a- * model we hold an entry for (deleted by another surface, or gone after a- * refresh), drop the entry and scrub the key from siblings. Entries for- * still-present models stay cache-first; freshness of links edited elsewhere- * is out of scope by design. This store subscribes to the library — not the- * other way around — so the eagerly-loaded modelsStore never pulls this lazy- * chunk into the entry graph.+ * Prune missing models and sibling links on library updates. Subscribe from this lazy store to preserve the eager+ * library boundary; external link freshness is excluded.*/let lastLoadedModels: readonly ModelConfig[] | null = null;@@ -130,9 +111,8 @@ const fetchRelatedKeys = (modelKey: string): Promise<void> => {}}).catch((error: unknown) => {- // Leave an empty entry so consumers stop showing a spinner, but still- // reject so callers that care (the detail pane) can surface the error.- // A superseded fetch writes nothing and does not mark the key failed.+ // Set an empty entry to stop spinners while rejecting for error-aware callers; superseded fetches write+ // nothing.if (isAccountScopeCurrent(owner) && inflightByKey.get(modelKey) === fetch) {failedFetchKeys.add(modelKey);@@ -192,11 +172,8 @@ const patchBothDirections = (modelKey: string, otherKey: string, patch: EntryPat};/**- * Apply a successful mutation to the cache: patch the entries that exist, and- * for any key with a GET inflight, evict it (a request issued before the- * mutation is stale) and refetch so the entry converges on server truth. This- * also covers a link made while the entry's first fetch is still inflight —- * the refetch was issued after the POST, so it includes the new link.+ * Patch existing entries, but invalidate and refetch GETs started before mutation so stale responses cannot erase+ * new links.*/const commitMutation = (modelKey: string, otherKey: string, patch: EntryPatch): void => {// A response that outlived its models' deletion must not resurrect them.@@ -284,11 +261,7 @@ export const removeModelsFromRelationships = (keys: readonly string[]): void =>export const getRelationshipsSnapshot = (): ModelRelationshipsSnapshot => store.getSnapshot();-/**- * Low-level change subscription for callers that must load this module- * lazily (the editor's pickers) and so cannot use the `useRelatedModelKeys`- * hook. Returns the unsubscribe function.- */+/** Manual subscription supports lazy consumers that cannot statically import the hook; return unsubscribe. */export const subscribeToRelationships = (listener: () => void): (() => void) => store.subscribe(listener);/** Related keys for one model; `null` means not fetched yet (or no model). */diff --git a/invokeai/frontend/webv2/src/features/models/data/startersStore.ts b/invokeai/frontend/webv2/src/features/models/data/startersStore.tsindex 1d66813c43..b1d8811d3e 100644--- a/invokeai/frontend/webv2/src/features/models/data/startersStore.ts+++ b/invokeai/frontend/webv2/src/features/models/data/startersStore.ts@@ -11,11 +11,7 @@ import { getApiErrorMessage } from '@platform/transport/http';import { getStarterModels } from './api';-/**- * Cached starter-models catalog. The list is large and rarely changes, so it- * is fetched once and served from memory on revisits; installs revalidate it- * in the background (the `is_installed` flags shift) without blanking the UI.- */+/** Cache the large starter catalog across revisits; install refreshes update flags without blanking the UI. */export interface StartersSnapshot {response: StarterModelResponse | null;diff --git a/invokeai/frontend/webv2/src/features/models/launchpad.ts b/invokeai/frontend/webv2/src/features/models/launchpad.tsindex 5b3e2a81d1..4d0a9aa860 100644--- a/invokeai/frontend/webv2/src/features/models/launchpad.ts+++ b/invokeai/frontend/webv2/src/features/models/launchpad.ts@@ -1,13 +1,4 @@-/**- * Models surface for the Launchpad. Exported eagerly: the Launchpad puts one- * dynamic-import boundary in front of every live panel at once, so a second- * one here would only fragment that chunk.- */+/** Export eagerly because Launchpad already shares one lazy boundary across live panels. */export { ModelsNotice } from './ui/launchpad/ModelsNotice';-/**- * The Add Models search seam. Exported here rather than from the feature index- * because the index is a *static* import of the editor bundle — this module is- * only ever reached by `import()`, so seeding a search from the editor costs- * the editor nothing until someone clicks.- */+/** Expose search through this dynamic entry so editor imports do not eagerly load the manager. */export { requestAddModelsSearch, requestAddModelsTypeFilter } from './ui/uiStore';diff --git a/invokeai/frontend/webv2/src/features/models/ui/ModelInstallRuntime.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelInstallRuntime.tsxindex 0c708351e8..32cc4dfbe2 100644--- a/invokeai/frontend/webv2/src/features/models/ui/ModelInstallRuntime.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelInstallRuntime.tsx@@ -13,11 +13,8 @@ import { socketHub } from '@platform/transport/socketHub';import { useInstallOutcomeToasts } from './useInstallOutcomeToasts';/**- * App-wide install runtime: install socket events, reconnect refresh, and- * outcome toasts. Mounted once in the authenticated layout so installs- * progress, refresh the library, and announce completion no matter which- * surface queued them. Exactly one instance may exist — the outcome toasts- * keep per-instance seen state.+ * Mount exactly one authenticated install runtime; per-instance toast history would otherwise duplicate completion+ * announcements.*/export const ModelInstallRuntime = () => {useMountEffect(() => {@@ -40,10 +37,8 @@ export const ModelInstallRuntime = () => {return;}- // Only revalidate stores something already read — an app-wide mount- // must not fetch model data for sessions that never open a models- // surface. An install finishing while a store is idle still lands via- // the socket handler's scheduled refresh.+ // Reconnect only refreshes previously read stores; install completions separately schedule refreshes for+ // idle stores.if (getModelsSnapshot().status !== 'idle') {void refreshModels();}diff --git a/invokeai/frontend/webv2/src/features/models/ui/ModelsPage.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelsPage.tsxindex 5f8750e1cc..f4c05040d4 100644--- a/invokeai/frontend/webv2/src/features/models/ui/ModelsPage.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelsPage.tsx@@ -1,17 +1,7 @@import { Center, Spinner } from '@chakra-ui/react';import { lazy, Suspense } from 'react';-/**- * The Launchpad's model manager: full library, add-models flow, credentials,- * and install queue. It is the widest page, so it runs full-bleed (the view owns- * its own padding and internal master-detail scroll).- *- * The manager pulls in ~6k lines of model UI and stores, none of which the- * Launchpad needs at first paint, so it is code-split: the chunk loads the- * first time this tab is opened (the shell's `lazyMount` keeps it off the- * critical path until then) and stays warm afterwards. All model state lives in- * external stores, so the view needs no workbench providers here.- */+/** Lazy-load the full-bleed manager on first tab visit. External stores preserve state without workbench providers. */const ModelManagerView = lazy(() =>import('@features/models/ui/ModelManagerView').then((module) => ({ default: module.ModelManagerView })));diff --git a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsxindex 94c3470185..9a528e082b 100644--- a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx@@ -2,10 +2,7 @@ import type { ReactNode } from 'react';import { createContext, use } from 'react';-/**- * Models' UI port. The context is a dependency-direction port (the feature- * may not import workbench), not a test seam; no second adapter is expected.- */+/** This UI port preserves dependency direction: Models cannot import Workbench. */export interface ModelsUiAdapter {enableModelDescriptions: boolean;managerProjectId: string | null;diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsxindex 6e0d4b5498..c8c6af1845 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx@@ -12,11 +12,8 @@ import { userEvent } from 'vitest/browser';import { AddModelsView } from './AddModelsView';/**- * The Add Models box is local state seeded once from the models UI store, so a- * requirement link elsewhere in the app can open this view already searching —- * without that search outliving the view the way account-scoped store state- * would. This suite owns exactly that handover; everything else the view does- * is stubbed out.+ * Verify one-shot external search handover into local input state; the seed must not become account-lived+ * filtering.*/vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));@@ -131,8 +128,7 @@ describe('AddModelsView search seed', () => {await unmount();await mount();- // A tab switch used to reset the box, and still does: the seed was- // one-shot, not account-lived state that keeps filtering hours later.+ // Unmount resets local search; consumed seeds must not reappear on later visits.expect(searchBox()?.value).toBe('');await unmount();diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsxindex 7981324409..217ca7555d 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx@@ -65,12 +65,6 @@ const SOURCE_KIND_ICONS: Record<string, ElementType> = {*/const FP8_STORAGE_INSTALL_CONFIG: ModelRecordChanges = { default_settings: { fp8_storage: true } };-/**- * One box to add any model. The same field searches the curated starter- * catalog and accepts a URL, local path, or HuggingFace repo to install- * directly. Source-specific result panels live under `add-models/` so this file- * stays focused on state and install orchestration.- */export const AddModelsView = () => {const { t } = useTranslation();const notify = useNotify();@@ -90,10 +84,8 @@ export const AddModelsView = () => {left.selectedBundleName === right.selectedBundleName);- // Local state, so the box empties when the view unmounts (a tab switch) — but- // seeded once from whatever asked to search here on the way in. The read is- // pure, because StrictMode double-invokes this initializer; the consuming- // clear is the mount effect below.+ // Read the one-shot seed purely for StrictMode initialization; consume it after mount and keep subsequent input+ // state local.const [query, setQuery] = useState(getAddModelsSeed);const [accessToken, setAccessToken] = useState('');const [inplace, setInplace] = useState(true);@@ -139,15 +131,12 @@ export const AddModelsView = () => {const trimmed = query.trim();const deferredTrimmed = useDeferredValue(trimmed);- // A pull/scan results panel is showing: focus on the results and hide the- // browse-only chrome (bundles, filter menu, starter catalog).const hasResults = hfLookup !== null || scan !== null;const kind = useMemo(() => classifySource(trimmed), [trimmed]);const searchIcon = (kind.labelKey ? SOURCE_KIND_ICONS[kind.labelKey] : undefined) ?? SearchIcon;const token = accessToken.trim() === '' ? undefined : accessToken.trim();const installConfig = fp8Storage ? FP8_STORAGE_INSTALL_CONFIG : undefined;- // The primary action depends on the detected input: folders are scanned for- // models; files, URLs, and HF repos are pulled. Access tokens only apply to URLs.+ // Folders scan; files, URLs, and repos install. Access tokens apply only to URLs.const canScan = kind.localKind === 'folder';const canPull = kind.isInstallable && !canScan;@@ -212,9 +201,7 @@ export const AddModelsView = () => {}};- // Install-all from a results panel: silent per-model queueing with one- // summary toast, the same shape the bundle path uses — never a toast per- // file for a 40-file repo.+ // Bulk installs queue silently and emit one summary notice rather than per-file toasts.const installAllSources = async (requests: InstallModelRequest[]) => {const owner = captureAccountScope();const queued = await installMany(requests);@@ -254,8 +241,7 @@ export const AddModelsView = () => {return;}- // A single-file repo has nothing to choose from — install it directly,- // mirroring the diffusers path, instead of showing a one-row list.+ // Install single-file repositories directly because no selection is needed.const [onlyUrl] = lookup.urls;if (lookup.urls.length === 1 && onlyUrl) {diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.browser.test.tsxindex 573e2d9411..db6237e44f 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.browser.test.tsx@@ -76,12 +76,8 @@ describe('BundleChips overflow', () => {// (a) the chip row overflows the viewport horizontally.expect(viewport!.scrollWidth).toBeGreaterThan(viewport!.clientWidth);- // (b) a horizontal scrollbar part is rendered (asserted above via the- // non-null query; also confirm zag hasn't hidden it via data attrs).expect(horizontalScrollbar!.getAttribute('data-orientation')).toBe('horizontal');- // (c) the trailing element is not part of the scrolling content — it- // lives outside the viewport entirely, so it never scrolls with the chips.expect(viewport!.contains(trailing)).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/HuggingFaceFiles.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/HuggingFaceFiles.tsxindex 04922f8500..33137e1e28 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/HuggingFaceFiles.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/HuggingFaceFiles.tsx@@ -32,8 +32,6 @@ export const HuggingFaceFiles = ({}) => {const { t } = useTranslation();const { filter, filteredItems: filteredUrls, setFilter } = useSourceNameFilter(lookup.urls, urlOf);- // A model's recorded install source is the URL it was pulled from, so this- // marks rows Installed live once the library refresh lands.const installedSourceKeys = useInstalledSourceKeys();const installAll = () => {diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.browser.test.tsxindex 8080d44b64..8ceb3af5bd 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.browser.test.tsx@@ -85,8 +85,6 @@ describe('ScanResults install badge lifecycle', () => {expect(host.textContent).toContain('models.install');expect(host.textContent).not.toContain('models.installing');- // The install POST resolved: the queued job (backend-shaped source) lands- // in the installs store.await act(async () => {addInstallJob(queuedJob);await Promise.resolve();diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/sourceClassifier.ts b/invokeai/frontend/webv2/src/features/models/ui/add-models/sourceClassifier.tsindex f9b8995ee8..5536282365 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/sourceClassifier.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/sourceClassifier.ts@@ -10,11 +10,7 @@ const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9]{1,12}$/;const MODEL_FILE_EXTENSION_PATTERN = /\.(safetensors|ckpt|pt|pth|bin|gguf|onnx|pkl)$/i;const RELATIVE_PATH_PATTERN = /^\.{1,2}[\\/]/;-/**- * Discriminated on `isInstallable`: an installable source always carries a- * label key, and a search never looks like any source shape — so consumers- * need no null fallbacks inside an installable branch.- */+/** isInstallable narrows to a source with a label key; searches never share installable source shapes. */export type SourceKind =| {isInstallable: true;@@ -48,10 +44,8 @@ const classifyLocalPath = (value: string): 'file' | 'folder' => {export const classifySource = (value: string): SourceKind => {const looksLocal = value.startsWith('/') || /^[A-Za-z]:[\\/]/.test(value);const looksUrl = /^https?:\/\//i.test(value);- // "models/foo.safetensors" and "./repo" satisfy the HF repo shape but are- // clearly path-like; they fall through to search, since a relative path is- // not an installable source. The extension check runs on the pre-colon- // portion so "owner/repo:fp16:path/file.safetensors" stays a repo.+ // Relative paths fall through to search even if repo-shaped; inspect extensions before colon qualifiers so valid+ // repo file selectors remain installable.const looksRelativePath =RELATIVE_PATH_PATTERN.test(value) || MODEL_FILE_EXTENSION_PATTERN.test(value.split(':', 1)[0] ?? '');const looksRepo = !looksLocal && !looksUrl && !looksRelativePath && HF_REPO_PATTERN.test(value);diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/starterModelInstallSources.ts b/invokeai/frontend/webv2/src/features/models/ui/add-models/starterModelInstallSources.tsindex 43007cbcc5..648e2f70aa 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/starterModelInstallSources.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/starterModelInstallSources.ts@@ -12,10 +12,8 @@ export interface StarterModelInstallSourceOptions {}/**- * The curated metadata a starter carries: passed as the install `config` so the- * model is registered with its known name/base/type instead of relying purely on- * server-side probing (matches the legacy install path). Built per-model, so a- * dependency gets its own metadata rather than the parent's.+ * Pass each starter dependency's own curated config so installation preserves known identity instead of relying+ * entirely on probing.*/const buildStarterConfig = (model: StarterModel | Omit<StarterModel, 'dependencies'>): ModelRecordChanges => ({base: model.base,diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/useInstallActions.ts b/invokeai/frontend/webv2/src/features/models/ui/add-models/useInstallActions.tsindex 4136fdf5c6..5437ce7482 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/useInstallActions.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/useInstallActions.ts@@ -12,11 +12,8 @@ import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';/**- * Shared install entry point: queues an install job, optimistically adds it to- * the install store, and surfaces a notification. A saved Civitai API key is- * attached automatically for civitai.com URLs unless the caller supplies an- * explicit token. Bulk flows pass `silent` and emit one summary notice instead- * of a toast per model; failures always notify.+ * Attach saved Civitai tokens unless explicitly overridden. Bulk callers suppress success toasts and summarize;+ * failures always notify.*/export const useInstallActions = () => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsxindex 52868ff13f..fc8d0c3f1a 100644--- a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx@@ -135,8 +135,7 @@ describe('ModelSelect loading states', () => {const optionTexts = (): string[] =>[...document.querySelectorAll('[role="option"]')].map((option) => option.textContent ?? '');- // The bug that prompted the rewrite: grouping by (type, base) printed "Main- // Models" above every base section of a cross-type picker.+ // Cross-type pickers must not repeat Main Models headings for every base.it('groups a cross-type picker by base alone, with no type header', async () => {setModelsSnapshotForTests({ error: null, models: [model, loraModel], status: 'loaded' });await renderPicker({ id: 'test-cross-type', modelTypes: CROSS_TYPE_MODEL_TYPES });diff --git a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsxindex 99e8a59b8f..fd85d942fa 100644--- a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx@@ -36,12 +36,7 @@ const EMPTY_KEYS: ReadonlySet<string> = new Set();const getOptionId = (model: ModelConfig): string => model.key;-/**- * Related-model pinning for an open picker. The generation form mounts- * pickers during the editor's initial paint, so the relationships store must- * stay out of the eager graph (the architecture browser budget) — it is- * imported on first open and subscribed to manually instead of via its hook.- */+/** Load and subscribe to relationships only when the picker opens to keep it outside the editor's initial graph. */const useLazyRelatedModelKeys = (modelKey: string | null): readonly string[] | null => {const [relatedKeys, setRelatedKeys] = useState<readonly string[] | null>(null);@@ -139,8 +134,7 @@ export const ModelSelect = ({void ensureModelsLoaded();});- // Nothing to offer once the library is known: the trigger disables and says- // so, rather than opening an empty list. A stale selection stays clearable.+ // Disable empty-library triggers after loading; preserve clearing for stale selections.const hasCandidates = useMemo(() => loadStatus !== 'loaded' || hasModelPickerCandidates(models, { excludeKeys, filter, modelTypes }),[excludeKeys, filter, loadStatus, modelTypes, models]diff --git a/invokeai/frontend/webv2/src/features/models/ui/credentials/ApiKeysSection.tsx b/invokeai/frontend/webv2/src/features/models/ui/credentials/ApiKeysSection.tsxindex 3509c2c910..a7936a5f8c 100644--- a/invokeai/frontend/webv2/src/features/models/ui/credentials/ApiKeysSection.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/credentials/ApiKeysSection.tsx@@ -24,10 +24,8 @@ import { useState } from 'react';import { useTranslation } from 'react-i18next';/**- * Credentials for every model source, as one uniform grid of key cards:- * HuggingFace (server-stored, verified), Civitai (browser-local), and the- * external image providers (server config). Each card shares the same- * edit/display anatomy: icon, status, prefix-hinted input, save/clear.+ * Credential cards share controls while preserving storage ownership: HuggingFace/providers on the server, Civitai+ * in this browser.*/export const ApiKeysSection = () => {const notify = useNotify();diff --git a/invokeai/frontend/webv2/src/features/models/ui/credentials/ExternalProviderKeyCards.tsx b/invokeai/frontend/webv2/src/features/models/ui/credentials/ExternalProviderKeyCards.tsxindex f8bbd12b16..e1490bfbe0 100644--- a/invokeai/frontend/webv2/src/features/models/ui/credentials/ExternalProviderKeyCards.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/credentials/ExternalProviderKeyCards.tsx@@ -62,8 +62,7 @@ export const ExternalProviderKeyCards = ({ onError }: { onError: (title: string,);}- // A server with no external providers is a normal state, not a blank one.- // Nothing renders while loading — no flicker on the happy path.+ // Show an explicit no-provider state after loading; suppress loading flicker.if (status === 'loaded' && (configs ?? []).length === 0) {return (<Text color="fg.subtle" fontSize="2xs">@@ -118,11 +117,7 @@ const ExternalProviderKeyCard = ({title: string;}) => {const { t } = useTranslation();- // The request is consumed once; the outline it produces is local so it- // survives that clearing and stays up while the user works in the card.- // Its lifetime is the tab's — `DetailPane` renders the Keys body only while- // the tab is active, so leaving and returning lands on a quiet grid without- // anyone having to schedule the fade.+ // Consume the reveal request once; keep the highlight local until the Keys tab unmounts.const [isRevealed, setIsRevealed] = useState(false);// A callback ref rather than an effect: the provider list loads async, so// the card can mount well after the request, and this fires exactly when thediff --git a/invokeai/frontend/webv2/src/features/models/ui/credentials/KeyCardShell.tsx b/invokeai/frontend/webv2/src/features/models/ui/credentials/KeyCardShell.tsxindex 8dbc2a8413..4f30a8f219 100644--- a/invokeai/frontend/webv2/src/features/models/ui/credentials/KeyCardShell.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/credentials/KeyCardShell.tsx@@ -7,15 +7,6 @@ export interface KeyStatusBadge {palette: string;}-/**- * Shared chrome for credential cards: icon tile, title + status badge,- * description, body.- *- * `isHighlighted` is how a card answers "this is the one you asked for" after- * a jump from elsewhere. One neutral step — the stroke it already has, brought- * up a stop — rather than a tint or a flash: the grid is a settings surface,- * and the card still has to be readable while the user types a key into it.- */export const KeyCardShell = ({children,description,diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.tsxindex 09e1314e8a..8fe8340cef 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.tsx@@ -11,11 +11,7 @@ import { useTranslation } from 'react-i18next';export type CpuOnlyModel = Pick<ModelConfig, 'cpu_only' | 'key' | 'name' | 'type'>;-/**- * Every type whose backend config class carries a top-level `cpu_only` field.- * The PATCH silently drops the field elsewhere (notably qwen_vl_encoder and- * pid_decoder), so the toggle is only offered where it acts.- */+/** Offer cpu_only only where backend config accepts it; other model types silently discard the field. */const CPU_ONLY_TYPES: ReadonlySet<string> = new Set(['vae','clip_embed',diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsxindex b63dbc6d2a..6cef59fd1d 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx@@ -16,12 +16,7 @@ import type { DefaultSettingsControl, DefaultSettingsModel } from './defaultSettimport { getFieldsForModel, validateDefaults } from './defaultSettingsFields';-/**- * Per-model generation defaults ("use these settings when this model is- * selected"). Every field is individually toggleable: off = inherit the app- * default (stored as null). Field policy and validation live in- * `defaultSettingsFields.ts`; this file only renders and saves.- */+/** Disabled defaults persist null to inherit app settings; defaultSettingsFields owns field policy and validation. */interface DefaultSettingsDraft {modelKey: string;diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsxindex 99fd254e30..5b24c2c767 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx@@ -124,12 +124,7 @@ const selectCpuOnlyModel = (snapshot: ModelsSnapshot, modelKey: string): CpuOnlyconst areTriggerPhrasesModelsEqual = (left: TriggerPhrasesModel | null, right: TriggerPhrasesModel | null): boolean =>left?.key === right?.key && areArraysEqual(left?.trigger_phrases ?? [], right?.trigger_phrases ?? []);-/**- * Full detail pane for one model: identity (view/edit), per-model default- * settings, related models, trigger phrases, and lifecycle actions (convert,- * re-identify, delete). Mount keyed by model key so per-model form state never- * leaks between models.- */+/** Mount keyed by model key so detail forms cannot leak state between models. */export const ModelDetail = ({ modelKey, onDeleted }: { modelKey: string; onDeleted: () => void }) => {const { t } = useTranslation();const model = useModelsSelector((snapshot) => selectModelShell(snapshot, modelKey));@@ -410,8 +405,7 @@ const ModelAttributes = ({ isMissing, model }: { isMissing: boolean; model: Mode// Managed models store paths relative to the models directory; show the// resolved absolute path so it can be found on disk.const fullPath = resolveModelAbsolutePath(model.path, modelsDir);- // In-place installs (absolute paths) may be repointed after the file moves;- // a missing model gets the affordance too — that is exactly when it helps.+ // Allow repointing absolute-path installs, including missing files.const canUpdatePath = isAbsoluteModelPath(model.path) || isMissing;const attributes: { action?: ReactNode; href?: string; label: string; value: string }[] = [@@ -438,9 +432,7 @@ const ModelAttributes = ({ isMissing, model }: { isMissing: boolean; model: Modelabel: t('models.source'),value: model.source,},- // The user-editable page link (e.g. a Civitai listing); only visible in- // the edit form until now. Old records may predate the http(s)- // validation, so unlinkable values still render as text.+ // Render legacy non-HTTP(S) source links as text rather than unsafe anchors....(model.source_url? [{diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.tsxindex 8a65fbadf0..4186cf9eba 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.tsx@@ -102,8 +102,7 @@ export const ModelEditForm = ({items: formats.map((format) => ({ label: getModelFormatLabel(format), value: format })),});}, [model.format]);- // Reacts to base/type edits so the offered variants always match the- // combination being saved; an unknown current value stays selectable.+ // Update variant choices with edited base/type while retaining unknown current values.const { variantCollection, variantOptions } = useMemo(() => {const options = getVariantOptionsFor(form.values.base, form.values.type);const withCurrent =diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsxindex ffe246450a..44a7246295 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx@@ -16,11 +16,6 @@ const ACCEPTED_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);const dragContainsFiles = (event: DragEvent): boolean => Array.from(event.dataTransfer.types).includes('Files');-/**- * The model's cover image as one large dropzone: click anywhere on the tile- * or drop an image file onto it to upload. The remove button sits in the top- * corner and is hover/focus-revealed (and inert while hidden).- */interface ModelImageUploadProps {model: Pick<ModelConfig, 'cover_image' | 'key' | 'name'>;onError: (message: string) => void;diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelSettingsMenuItems.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelSettingsMenuItems.tsxindex 658d3e82e6..00058151f6 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelSettingsMenuItems.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelSettingsMenuItems.tsx@@ -17,12 +17,7 @@ import { DownloadIcon, UploadIcon } from 'lucide-react';import { useRef, type ChangeEvent } from 'react';import { useTranslation } from 'react-i18next';-/**- * Export/import a model's user-editable settings as JSON (format shared with- * the legacy frontend). Rendered inside the detail pane's overflow menu; the- * full config is read from the store at action time so the menu itself only- * needs a key.- */+/** Share the legacy JSON settings format; read full config at action time so menu props need only a model key. */export const ModelSettingsMenuItems = ({ modelKey }: { modelKey: string }) => {const { t } = useTranslation();const notify = useNotify();diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsxindex 96f2c72b6b..d5e600d963 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx@@ -22,12 +22,6 @@ import { Link2OffIcon } from 'lucide-react';import { useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-/**- * Bidirectional "related models" links — e.g. attach the LoRAs and VAE that- * pair well with a checkpoint so other surfaces can suggest them together.- * One grouped, compatibility-filtered picker searches every linkable type at- * once; linked models render as rows with an unlink action.- */interface RelatedModelsSectionProps {model: Pick<ModelConfig, 'base' | 'key' | 'type'>;onError: (message: string) => void;diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsxindex bf5c6121b3..819c982795 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsx@@ -17,12 +17,7 @@ interface TriggerPhrasesEditorState {value: string[];}-/**- * Tag editor for a model's trigger phrases: type + Enter adds, Backspace or- * the tag's control removes, double-click (or Enter on a highlighted tag)- * edits in place. Every change persists immediately — there is no separate- * save step — and a failed save puts the list back as it was.- */+/** Persist trigger-phrase edits immediately and restore the prior list on save failure. */export const TriggerPhrasesEditor = ({modelKey,onError,@@ -39,8 +34,7 @@ export const TriggerPhrasesEditor = ({phrases,value: [...phrases],}));- // Render-phase adjustment (not an effect): a new prop list — another model,- // or a save that landed — replaces the local value wholesale.+ // Replace local phrases during render when the prop list changes, including model switches and completed saves.if (editor.modelKey !== modelKey || editor.phrases !== phrases) {setEditor({ error: null, modelKey, phrases, value: [...phrases] });}diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsxindex 3a21de7307..798ca51acb 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsx@@ -12,11 +12,7 @@ import { Button, CloseButton, Field } from '@platform/ui';import { useState } from 'react';import { useTranslation } from 'react-i18next';-/**- * Repoints a model whose file moved on disk. The file itself is not moved or- * copied — only the record's path changes, and only absolute paths are- * accepted (managed models store paths relative to the models directory).- */+/** Update only the record's absolute path; never move files or repoint managed relative paths. */export const UpdatePathDialog = ({model,onClose,diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.test.ts b/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.test.tsindex f39412c3b9..a936583e1e 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.test.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.test.ts@@ -12,8 +12,7 @@ const fieldKeys = (candidate: Pick<ModelConfig, 'base' | 'type'>): string[] =>describe('supportsFp8Storage', () => {it('offers the toggle for main models', () => {- // Z-Image included: the backend casts it, and FP8 checkpoints get the setting when installed, so- // hiding the row would leave a setting nobody can see or turn off.+ // Expose Z-Image FP8 defaults so installed settings can be inspected and disabled.for (const base of ['sdxl', 'flux', 'krea-2', 'qwen-image', 'wan', 'ideogram-4', 'z-image']) {expect(supportsFp8Storage(model(base, 'main'))).toBe(true);}diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.ts b/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.tsindex f3572b457a..e6db84d7e3 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.ts@@ -3,13 +3,6 @@ import type { TFunction } from 'i18next';import { loraDefaultSettingsSchema, mainDefaultSettingsSchema } from '@features/models/core/schemas';-/**- * The pure policy behind per-model default settings: which model types get the- * section, which fields each type shows, and how drafts validate. The section- * component renders these specs; control descriptors here stay declarative so- * this module needs no React.- */-export type DefaultSettingsModel = Pick<ModelConfig, 'base' | 'default_settings' | 'key' | 'type'>;const CONTROL_ADAPTER_TYPES = new Set(['controlnet', 't2i_adapter', 'control_lora']);@@ -95,14 +88,8 @@ export interface FieldSpec {}/**- * Stores model weights as fp8 on the compute device, trading a little quality for VRAM.- *- * No body control: `_should_use_fp8` only acts on `fp8_storage is True`, so an explicit `false`- * and an absent value behave identically. The row's enable switch already covers the two states- * that differ, and a second switch inside the card would imply a distinction that does not exist.- *- * The backend gates availability in `_should_use_fp8`; `supportsFp8Storage` mirrors those- * exclusions so the toggle is never offered where it would be silently ignored.+ * Only fp8_storage=true changes backend behavior; the row toggle covers it without a redundant body switch. Mirror+ * backend exclusions.*/const FP8_STORAGE_FIELD: FieldSpec = {defaultValue: true,@@ -213,12 +200,7 @@ const CONTROL_ADAPTER_FIELDS: FieldSpec[] = [},];-/**- * Mirrors the backend's `_should_use_fp8` exclusions:- * - LoRA / ControlLoRA: patched into a base model rather than run as their own forward pass, so- * the casting hooks would never fire.- * VAEs are excluded too, but they have no default-settings section at all.- */+/** Exclude LoRA/ControlLoRA: patched weights lack their own forward hooks. VAEs have no defaults section. */export const supportsFp8Storage = (model: Pick<ModelConfig, 'base' | 'type'>): boolean =>model.type === 'main' || model.type === 'controlnet' || model.type === 't2i_adapter';diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts b/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.tsindex 45448245dd..757793d4b1 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts@@ -10,19 +10,13 @@ import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';-/**- * Lifecycle actions for a single model, shared by the detail page and the- * library row context menu so behavior and notifications stay identical.- * Confirmation UI is the caller's job; these just act and notify.- */+/** Share lifecycle actions and notifications across surfaces; callers own confirmation UI. */type ModelActionTarget = Pick<ModelConfig, 'key' | 'name'>;export const useModelActions = () => {const { t } = useTranslation();const notify = useNotify();- // Separate instances: `run` ignores calls while its own action is in- // flight, so sharing one would let a slow convert swallow a remove.- // The busy flags stay unused.+ // Use independent action guards so a slow conversion cannot swallow a delete.const { run: runRemove } = useScopedAction();const { run: runConvert } = useScopedAction();const { run: runReidentify } = useScopedAction();diff --git a/invokeai/frontend/webv2/src/features/models/ui/launchpad/ModelsNotice.tsx b/invokeai/frontend/webv2/src/features/models/ui/launchpad/ModelsNotice.tsxindex 41f6902cae..ee5a9b0413 100644--- a/invokeai/frontend/webv2/src/features/models/ui/launchpad/ModelsNotice.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/launchpad/ModelsNotice.tsx@@ -13,13 +13,8 @@ import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';/**- * The first-run gap this closes: a fresh install used to show an empty project- * grid and a "New project" button that dropped you into an editor which could- * not generate anything, with no mention that models were the missing piece.- *- * It renders only while that is actually true — no models installed, or a- * starter bundle still downloading — and disappears for good once the library- * has something in it.+ * Explain missing models during first-run setup or starter downloads; hide the notice once usable library content+ * exists.*/const EMPTY_BUNDLES: Record<string, StarterModelBundle> = {};@@ -48,8 +43,7 @@ export const ModelsNotice = () => {ensureInstallsLoaded();});- // Nothing to say until the library has actually been read; guessing "you- // have no models" during the first fetch would be a lie half the time.+ // Wait for authoritative library data before claiming no models are installed.if (modelsStatus !== 'loaded' || modelCount > 0) {return activeInstallCount > 0 ? <InstallProgress count={activeInstallCount} /> : null;}@@ -108,8 +102,6 @@ const StarterBundles = ({ bundles }: { bundles: Record<string, StarterModelBundlconst StarterBundleButton = ({ bundle, bundleKey }: { bundle: StarterModelBundle; bundleKey: string }) => {const navigate = useNavigate();- // Opens the bundle in the model manager rather than installing blind — the- // user sees what the pack contains and installs from there.const handleOpen = useCallback(() => {openAddModelsWithBundle(bundle.name || bundleKey);void navigate({ to: '/models' });diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsxindex 737d589924..c86afb4fb4 100644--- a/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/library/MaintenanceMenu.tsx@@ -11,10 +11,6 @@ import { BrushCleaningIcon, FolderSearchIcon, MoreHorizontalIcon, RefreshCcwIconimport { useState } from 'react';import { useTranslation } from 'react-i18next';-/**- * Library maintenance: refresh, clean up orphaned model folders (files on disk- * with no database record), and empty the in-memory model cache.- */export const MaintenanceMenu = () => {const { t } = useTranslation();const notify = useNotify();diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/ModelFilterBar.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/ModelFilterBar.tsxindex 4f7a9a1819..f075327a66 100644--- a/invokeai/frontend/webv2/src/features/models/ui/library/ModelFilterBar.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/library/ModelFilterBar.tsx@@ -11,10 +11,7 @@ import { useTranslation } from 'react-i18next';const isFiltering = (filters: ModelLibraryFilters): boolean =>filters.typeFilter !== null || filters.baseFilter !== null || filters.missingOnly;-/**- * Search box plus a combined filter/sort menu. The menu reflects only values- * present in the current library so it never offers dead filters.- */+/** Offer taxonomy filters only for values present in the library. */export const ModelFilterBar = ({availableBases,availableTypes,diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsxindex 3a2d88b6fb..d783376f02 100644--- a/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsx@@ -25,13 +25,8 @@ const HEADER_ROW_HEIGHT_PX = 30;const MODEL_ROW_HEIGHT_PX = 56;/**- * Virtualized, grouped model library. Group headers and model rows share one- * flat virtualized list (smooth at thousands of models). The current group's- * header is rendered as a pinned overlay above the scroll viewport — CSS- * sticky positioning is unreliable inside ScrollArea's content wrapper — and- * the virtual content lives in ScrollArea.Content so the scrollbar thumb is- * measured correctly. Rows carry a thumbnail, a right-click action menu, and- * bulk-select checkboxes.+ * Virtualize headers and rows together; overlay the current header because ScrollArea wrappers break sticky+ * positioning. Keep content inside ScrollArea.Content for scrollbar sizing.*/export const ModelLibraryList = ({activeModelKey,@@ -138,9 +133,7 @@ export const ModelLibraryList = ({);}- // The visible range, not `virtualItems[0]`: the virtual window starts- // `overscan` rows above the fold, which held the previous group's header- // pinned ~450px past its last row.+ // Choose the header from visible indices, not overscan, which can retain the previous group past its end.const firstVisibleIndex = virtualizer.range?.startIndex ?? 0;const pinnedHeaderIndex = headerIndexes.reduce<number | null>((pinnedIndex, index) => (firstVisibleIndex >= index ? index : pinnedIndex),@@ -195,8 +188,7 @@ export const ModelLibraryList = ({<ScrollArea.Thumb /></ScrollArea.Scrollbar></ScrollArea.Root>- {/* Pinned copy of the current group's header, above the viewport.- aria-hidden: it duplicates a header already in the list. */}+ {/* Hide this duplicate pinned header from assistive technology. */}{pinnedRow?.kind === 'header' ? (<Boxaria-hiddendiff --git a/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsxindex 01850f018e..f8a91fcf21 100644--- a/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsx@@ -15,11 +15,6 @@ export interface ModelContextMenuTarget {y: number;}-/**- * Right-click menu for library rows, anchored to the cursor via a virtual- * rect. Mirrors the detail page's action menu (re-identify, convert, delete)- * through the shared `ModelActionMenuItems`.- */export const ModelRowContextMenu = ({onClose,target,diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/OrphanedModelsDialog.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/OrphanedModelsDialog.tsxindex 6c723396fd..d925fd7c0a 100644--- a/invokeai/frontend/webv2/src/features/models/ui/library/OrphanedModelsDialog.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/library/OrphanedModelsDialog.tsx@@ -20,11 +20,7 @@ import { Panel } from '@platform/ui/Panel';import { useState } from 'react';import { useTranslation } from 'react-i18next';-/**- * Scan-and-delete flow for orphaned model folders (files on disk with no- * database record). Partial failures keep the dialog open on a rescanned- * remainder so the user can see which paths are left and retry.- */+/** Rescan after partial orphan deletion and keep the dialog open for retrying remaining paths. */export const OrphanedModelsDialog = ({ onClose }: { onClose: () => void }) => {const { t } = useTranslation();const notify = useNotify();@@ -85,8 +81,6 @@ export const OrphanedModelsDialog = ({ onClose }: { onClose: () => void }) => {failed: errorCount,}));- // Keep the dialog open on the rescanned remainder so the user can- // see which paths are left and retry.const deleted = new Set(result.deleted);setSelectedPaths((current) => new Set([...current].filter((path) => !deleted.has(path))));diff --git a/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx b/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsxindex ce2ee415c4..b1bcb46721 100644--- a/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx@@ -56,12 +56,8 @@ export const LibraryColumn = () => {const hasSelection = selectedKeys.size > 0;const canSelectAll = models.length > 0;const deferredFilters = useDeferredValue(filters);- // The same filter logic the list renders with (deferred identically), so- // "Select all" matches exactly what the user sees (search, type/base,- // missing-only). Still gated on there being a selection: with none, the- // checkbox reads unchecked whatever the filter says, and the click path- // below filters on demand — so an empty selection costs nothing on every- // search keystroke.+ // Match Select all to the list's deferred filters. Avoid filtering on every keystroke when nothing is selected;+ // compute on click instead.const filteredKeys = useMemo(() =>hasSelection ? filterModels(models, deferredFilters, missingModelKeys).map((model) => model.key) : EMPTY_KEYS,@@ -78,9 +74,7 @@ export const LibraryColumn = () => {return;}- // Filtered here rather than read from the memo: with nothing selected the- // memo is deliberately empty, and this is the one moment the full filtered- // set is actually needed.+ // Compute on click because the selection memo intentionally stays empty with no selection.const keys = filterModels(models, filters, missingModelKeys).map((model) => model.key);// Union: selections made under a previous filter survive, so the delete@@ -185,18 +179,11 @@ export const LibraryColumn = () => {onChange={(nextFilters) => updateModelsUi({ filters: nextFilters })}/>- {/* Docked under the search rather than floating over the list: the- selection controls belong to the same block as the filter that- decides what "all" means, and a bar that appeared over the last two- rows hid the models it was about to act on. Always mounted so- starting a selection never shifts the list under the pointer. */}+ {/* Keep controls mounted below search to prevent selection-induced layout shifts or obscured model rows. */}<HStack borderBottomWidth={1} flexShrink={0} gap="2" minH="8" px="3" py="1.5"><Checkbox.Rootaria-label={t('models.selectAll')}- // A filter matching nothing must not read "all selected" — with a- // selection held entirely out of view, indeterminate is the honest- // state, and the click clears it (the only act left with nothing- // visible to add).+ // No visible matches means indeterminate, not all selected; clicking clears the hidden selection.checked={hasSelection ? (hasUnselectedFiltered || filteredKeys.length === 0 ? 'indeterminate' : true) : false}colorPalette="accent"disabled={!canSelectAll}diff --git a/invokeai/frontend/webv2/src/features/models/ui/manager/layoutConstants.ts b/invokeai/frontend/webv2/src/features/models/ui/manager/layoutConstants.tsindex 0b9da7d015..59badf0e0a 100644--- a/invokeai/frontend/webv2/src/features/models/ui/manager/layoutConstants.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/layoutConstants.ts@@ -1,8 +1,4 @@-// Keep both values in sync with src/features/nodes/ui/manager/layoutConstants.ts —-// the two managers share their layout rhythm, but cross-feature imports are-// forbidden, so the values are duplicated by convention.+// Keep values aligned with nodes/ui/manager/layoutConstants.ts; cross-feature imports are forbidden.export const LIBRARY_WIDTH = 'clamp(22rem, 32vw, 28rem)';-// Both column headers share a min height so the library title bar lines up with-// the detail tab bar.export const HEADER_MIN_HEIGHT = '2.75rem';diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/ModelActionsMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelActionsMenu.tsxindex 116fce3d8e..7d93efac24 100644--- a/invokeai/frontend/webv2/src/features/models/ui/shared/ModelActionsMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelActionsMenu.tsx@@ -11,12 +11,8 @@ import { RefreshCcwIcon, Trash2Icon } from 'lucide-react';import { useTranslation } from 'react-i18next';/**- * The reidentify/convert/delete action set for one model, shared by the- * library row context menu and the detail header menu so copy, icons, and- * confirm semantics cannot drift. Items and dialog are separate components- * because the dialog must outlive the menu (menus unmount their content on- * close); the caller holds the pending state that bridges them, with the- * target model captured so the confirm survives the source row disappearing.+ * Keep confirmation dialogs outside menus so they survive menu closure; capture targets so disappearing source+ * rows cannot change pending actions.*/export type ModelActionsModel = Pick<ModelConfig, 'base' | 'format' | 'key' | 'name' | 'type'>;diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsxindex 9de963a96d..fd224c253a 100644--- a/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx@@ -38,11 +38,7 @@ export const SORT_FIELD_OPTIONS: readonly ModelFilterSortOption[] = [{ field: 'path', labelKey: 'models.sort.path' },];-/**- * Shared taxonomy filter + sort menu for installed and starter model lists.- * Generic over the sort-field subset so a menu fed a narrowed `sortFields`- * list reports only those fields to `onSortChange`.- */+/** Narrow sort callbacks to the supplied sort-field subset. */export const ModelFilterMenu = <Field extends ModelSortField>({ariaLabel,availableBases,@@ -74,11 +70,7 @@ export const ModelFilterMenu = <Field extends ModelSortField>({sortFields: readonly ModelFilterSortOption<Field>[];typeAllChecked?: boolean;typeFilter: ModelTaxonomyType | null;- /**- * What the Model Type row should read when the filter is neither "all" nor- * one of `availableTypes` — the caller's own pseudo-type from- * `extraTypeItems`, which this component cannot name for itself.- */+ /** Caller-supplied label for pseudo-types outside availableTypes. */typeSummary?: string;}) => {const { t } = useTranslation();@@ -161,16 +153,7 @@ export const ModelFilterMenu = <Field extends ModelSortField>({);};-/**- * One filter dimension, folded away behind its own row.- *- * The three groups used to stack in a single panel that scrolled at 70vh — on- * a library with a dozen base architectures, choosing a sort order meant- * scrolling past every one of them. Folding each into a submenu costs a- * hover, so the row carries its current value: the state stays readable- * without opening anything, which is the only reason the flat list was worth- * keeping.- */+/** Submenus prevent long taxonomy lists from hiding sort controls; show current values on closed rows. */const FilterSubMenu = ({children,icon,diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/ResultsListHeader.tsx b/invokeai/frontend/webv2/src/features/models/ui/shared/ResultsListHeader.tsxindex ee96297c65..1a8e19a362 100644--- a/invokeai/frontend/webv2/src/features/models/ui/shared/ResultsListHeader.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/ResultsListHeader.tsx@@ -6,12 +6,6 @@ import { useTranslation } from 'react-i18next';const SEARCH_ICON = <Icon as={SearchIcon} boxSize="3" color="fg.subtle" />;-/**- * Shared header for an installable-source results panel (HuggingFace files,- * folder-scan results): a summary line with an optional extra control and a- * dismiss, over a filter box and an Install All action. Presentational only —- * each consumer owns its own filter state, Install All predicate, and rows.- */export const ResultsListHeader = ({extra,installAllDisabled,diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/SourceListItem.tsx b/invokeai/frontend/webv2/src/features/models/ui/shared/SourceListItem.tsxindex 271a4f82b5..5de965d3e4 100644--- a/invokeai/frontend/webv2/src/features/models/ui/shared/SourceListItem.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/SourceListItem.tsx@@ -9,11 +9,6 @@ import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { DownloadIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';-/**- * The shared row used by every installable-source list (starter models,- * HuggingFace files, folder-scan results, related models): title + badges on- * top, optional description below, action on the right.- */export const SourceListItem = ({badges,description,@@ -45,11 +40,6 @@ export const SourceListItem = ({</Panel>);-/**- * Install action with live state: idle → Install button; queuing/active →- * disabled "Installing…" with a jump to the install queue; done → badge with a- * jump to the installed model's page when the library knows which one it is.- */export const InstallSourceButton = ({installedModelKey = null,isInstalled = false,diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/useInstalledSources.ts b/invokeai/frontend/webv2/src/features/models/ui/shared/useInstalledSources.tsindex fd2234c813..c6e4a3ba62 100644--- a/invokeai/frontend/webv2/src/features/models/ui/shared/useInstalledSources.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/useInstalledSources.ts@@ -7,9 +7,7 @@ import { useModelsSelector } from '@features/models/data/modelsStore';const areMapsEqual = (left: ReadonlyMap<string, string>, right: ReadonlyMap<string, string>): boolean =>left.size === right.size && [...left].every(([source, key]) => right.get(source) === key);-// Selectors run on every store notification for every subscriber; cache by the-// inputs' identities so repeat notifications reuse one map (and pass equality-// by reference instead of a member-by-member scan).+// Cache by input identity so repeated store notifications reuse the same map across subscribers.let lastModels: ModelsSnapshot['models'] | null = null;let lastModelsDir: string | null = null;let lastSources: ReadonlyMap<string, string> = new Map<string, string>();@@ -32,11 +30,8 @@ const selectInstalledSourceKeys = (snapshot: ModelsSnapshot): ReadonlyMap<string};/**- * Every string under which a library model is reachable as an install source- * — its recorded install source plus its resolved absolute file path — mapped- * to that model's key. Source rows (folder scan, HuggingFace files) derive- * "installed" from this live map and link to the model it names; a scan-time- * snapshot would keep offering Install after the job finishes.+ * Map both recorded install sources and resolved paths to live model keys; scan-time snapshots would keep offering+ * Install after completion.*/export const useInstalledSourceKeys = (): ReadonlyMap<string, string> =>useModelsSelector(selectInstalledSourceKeys, areMapsEqual);diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/useSourceNameFilter.ts b/invokeai/frontend/webv2/src/features/models/ui/shared/useSourceNameFilter.tsindex 56a9613de7..6241b88d9f 100644--- a/invokeai/frontend/webv2/src/features/models/ui/shared/useSourceNameFilter.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/useSourceNameFilter.ts@@ -3,11 +3,7 @@ import { useDeferredValue, useMemo, useState } from 'react';/** Last path/URL segment: install sources display and filter by file name. */export const sourceFileName = (source: string): string => source.split(/[\\/]/).at(-1) ?? source;-/**- * Search-box state plus deferred file-name filtering, shared by the install- * results panels (folder scan, HuggingFace files). Pass a module-level- * `sourceOf` so the memo stays keyed on the items alone.- */+/** Pass a module-stable sourceOf so deferred filename filtering stays keyed on items. */export const useSourceNameFilter = <Item>(items: readonly Item[], sourceOf: (item: Item) => string) => {const [filter, setFilter] = useState('');const deferredFilter = useDeferredValue(filter);diff --git a/invokeai/frontend/webv2/src/features/models/ui/uiStore.test.ts b/invokeai/frontend/webv2/src/features/models/ui/uiStore.test.tsindex 5340169a2f..f0dbdd3afd 100644--- a/invokeai/frontend/webv2/src/features/models/ui/uiStore.test.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/uiStore.test.ts@@ -37,8 +37,7 @@ describe('models ui store', () => {const snapshot = store.getModelsUiSnapshotForTests();- // Add Models, showing the starter catalog filtered to the request — a- // leftover scan/HF panel or bundle would hide the catalog entirely.+ // Clear prior scan, repo, and bundle results so the requested starter catalog remains visible.expect(snapshot.activeTab).toBe('add');expect(store.getAddModelsSeed()).toBe('Juggernaut XL');expect(snapshot.hfLookup).toBeNull();diff --git a/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts b/invokeai/frontend/webv2/src/features/models/ui/uiStore.tsindex 69f552e47c..04733c9a8c 100644--- a/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts@@ -5,19 +5,10 @@ import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore } from '@platform/state/externalStore';/**- * Session-lived UI state for the model manager. Views unmount whenever the user- * switches launchpad tabs or detail tabs; keeping selection,- * filters, and in-progress source forms here means nothing is forgotten when- * they come back. Deliberately not persisted to localStorage — it resets with- * the page, like a scroll position.+ * Preserve manager selection, filters, and forms across view unmounts for the session; intentionally reset on page+ * reload.*/-/**- * The detail-pane tabs. The library list is now a persistent left column, so it- * is no longer a tab; the install queue is a persistent detail-pane footer. What- * remains is the selected model's detail, the unified Add Models search, and API- * keys.- */export type ModelManagerTab = 'details' | 'add' | 'keys';/** A resolved HuggingFace checkpoint-repo lookup, kept across tab switches. */@@ -28,29 +19,13 @@ export interface HFLookupState {export interface ModelsUiSnapshot {activeTab: ModelManagerTab;- /**- * A pending Add Models search, handed over by a surface outside the manager- * (see {@link requestAddModelsSearch}). Strictly one-shot: the view takes it- * at mount and {@link clearAddModelsSeeds} empties it, so the box keeps its- * own local state and still resets when the view unmounts. `null` = nothing- * pending, which is not the same as a seeded empty string.- */+ /** Consume Add Models search once on mount; null means no seed, distinct from a seeded empty string. */addModelsSeed: string | null;- /**- * A pending starter-catalog type filter, one-shot exactly like- * {@link ModelsUiSnapshot.addModelsSeed} — for links that know what *kind* of- * model is missing rather than which one.- */+ /** One-shot starter type filter for links identifying a missing model kind rather than a name. */addModelsTypeSeed: ModelTaxonomyType | null;/** Model focused in the manager library's detail pane. */activeModelKey: string | null;- /**- * Provider whose key card should be revealed on the next render of the Keys- * tab, set when the user asked to configure one specific provider. One-shot- * like {@link ModelsUiSnapshot.addModelsSeed}: the card consumes it, so- * returning to the tab later lands on a quiet grid rather than replaying a- * highlight the user did not ask for.- */+ /** Consume provider reveal once so returning to Keys does not replay an old highlight. */highlightProviderId: string | null;selectedKeys: ReadonlySet<string>;filters: ModelLibraryFilters;@@ -131,13 +106,7 @@ export const openModelDetail = (modelKey: string): void => {updateModelsUi({ activeModelKey: modelKey, activeTab: 'details' });};-/**- * Open the Keys tab pointed at one provider's card.- *- * The tab alone is not the answer to "configure this provider" — it is a grid- * of cards, and the one the user came for may be off-screen. Naming the- * provider lets the card reveal itself.- */+/** Name the requested provider so its possibly offscreen key card can reveal itself. */export const openExternalProviderKeys = (providerId: string): void => {updateModelsUi({ activeTab: 'keys', highlightProviderId: providerId });};@@ -147,26 +116,14 @@ export const clearHighlightedProvider = (): void => {updateModelsUi({ highlightProviderId: null });};-/**- * Jump to Add Models with a starter bundle preselected (e.g. from the- * Launchpad notice). Scan and HF lookup results are cleared because Add- * Models hides the bundle strip whenever either has results — the user asked- * to look at the bundle.- */+/** Clear scan/repo results when opening a bundle because those panels otherwise hide it. */export const openAddModelsWithBundle = (bundleName: string): void => {updateModelsUi({ activeTab: 'add', hfLookup: null, scan: null, selectedBundleName: bundleName });};/**- * Open Add Models searching for one model. Called just before navigating to the- * manager from elsewhere in the app (e.g. a model a workflow needs but the- * account does not have), so the page the user lands on is already offering the- * thing they clicked — the installed-models list would only confirm its absence.- *- * Scan and HuggingFace results are cleared for the same reason- * {@link openAddModelsWithBundle} clears them: Add Models hides the starter- * catalog whenever either has results, and the catalog is what this search is- * for.+ * Seed Add Models search for external requirement links and clear scan/repo results that would hide the starter+ * catalog.*/export const requestAddModelsSearch = (query: string): void => {updateModelsUi({@@ -179,12 +136,7 @@ export const requestAddModelsSearch = (query: string): void => {});};-/**- * Open Add Models with the starter catalog filtered to one model type. The same- * navigate-from-elsewhere contract as {@link requestAddModelsSearch}, for links- * that know what kind of model is missing (prompt expansion needs a `text_llm`)- * rather than which one.- */+/** Seed the starter catalog's type filter for external links identifying a missing model kind. */export const requestAddModelsTypeFilter = (typeFilter: ModelTaxonomyType): void => {updateModelsUi({activeTab: 'add',@@ -202,11 +154,7 @@ export const getAddModelsSeed = (): string => store.getSnapshot().addModelsSeed/** Pure read, like {@link getAddModelsSeed}. */export const getAddModelsTypeSeed = (): ModelTaxonomyType | null => store.getSnapshot().addModelsTypeSeed;-/**- * Consumes the pending seeds. Silent because the only reader took them in the- * same commit and nothing subscribes to them: a notify here would be a store- * write whose only effect is re-rendering the view that just read it.- */+/** Consume seeds silently; subscribers do not read them and the mounting reader already captured them. */export const clearAddModelsSeeds = (): void => {const snapshot = store.getSnapshot();diff --git a/invokeai/frontend/webv2/src/features/models/ui/useInstallOutcomeToasts.ts b/invokeai/frontend/webv2/src/features/models/ui/useInstallOutcomeToasts.tsindex 79f45ea860..7dcaf32fb0 100644--- a/invokeai/frontend/webv2/src/features/models/ui/useInstallOutcomeToasts.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/useInstallOutcomeToasts.ts@@ -3,11 +3,7 @@ import { useNotify } from '@features/models/ui/useModelsNotify';import { useEffect, useRef } from 'react';import { useTranslation } from 'react-i18next';-/**- * Turns settled install outcomes (completed/failed/cancelled) into notifications,- * while the model manager is mounted. Provider-free: `useNotify` falls back to- * global toasts off-workbench. Mounted by `ModelInstallRuntime`.- */+/** ModelInstallRuntime announces settled installs; notifications also work outside workbench providers. */export const useInstallOutcomeToasts = (): void => {const { t } = useTranslation();const notify = useNotify();diff --git a/invokeai/frontend/webv2/src/features/nodes/core/installSource.ts b/invokeai/frontend/webv2/src/features/nodes/core/installSource.tsindex 468fd1e719..709e472f54 100644--- a/invokeai/frontend/webv2/src/features/nodes/core/installSource.ts+++ b/invokeai/frontend/webv2/src/features/nodes/core/installSource.ts@@ -1,10 +1,4 @@-/**- * Client-side mirror of the backend's install-source rules- * (`invokeai/app/api/routers/custom_nodes.py`: `PACK_NAME_RE`,- * `_extract_pack_name_from_source`, and the already-exists rejection), so a- * doomed install is caught before the POST instead of surfacing as a failed- * request.- */+/** Mirror custom_nodes.py source validation and duplicate-pack rejection to catch invalid installs before POST. */const PACK_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;diff --git a/invokeai/frontend/webv2/src/features/nodes/core/library.ts b/invokeai/frontend/webv2/src/features/nodes/core/library.tsindex 8fdc74be73..93db427b36 100644--- a/invokeai/frontend/webv2/src/features/nodes/core/library.ts+++ b/invokeai/frontend/webv2/src/features/nodes/core/library.ts@@ -1,11 +1,5 @@import type { NodePackInfo } from './catalog';-/**- * Pure filter/sort policy for the pack library, mirroring the model manager's- * `core/library`. Kept out of the components so it is unit-testable and the- * list stays presentational.- */-export type NodePackSortField = 'name' | 'nodeCount' | 'path';export interface NodePackFilters {@@ -24,9 +18,8 @@ export const DEFAULT_NODE_PACK_FILTERS: NodePackFilters = {};/**- * The backend derives nodeCount from the live invocation registry, so zero- * means the pack's import failed or a reload/restart is pending — the- * strongest health signal the catalog carries.+ * Zero nodes indicates failed import or pending reload/restart because counts come from the live invocation+ * registry.*/export const isProblemPack = (pack: Pick<NodePackInfo, 'nodeCount'>): boolean => pack.nodeCount === 0;diff --git a/invokeai/frontend/webv2/src/features/nodes/data/api.ts b/invokeai/frontend/webv2/src/features/nodes/data/api.tsindex d7d8ce18a3..25d1c27e5a 100644--- a/invokeai/frontend/webv2/src/features/nodes/data/api.ts+++ b/invokeai/frontend/webv2/src/features/nodes/data/api.ts@@ -43,11 +43,8 @@ export const reloadCustomNodes = (signal?: AbortSignal): Promise<{ status: strinrequestJson<{ status: string }>(`${CUSTOM_NODES_BASE}/reload`, { method: 'POST', signal });/**- * Workflows imported by a pack, counted by its `node-pack:<name>` tag. A- * best-effort number for the uninstall confirmation: uninstall deletes by the- * manifest-recorded IDs, while this counts by tag, so retagged workflows can- * make the two diverge slightly. (Calling the workflows router from here- * follows the models feature's relationshipsApi precedent.)+ * Estimate imported workflows by pack tag for confirmation; uninstall uses manifest IDs, so retagging can change+ * the count.*/export const getPackWorkflowCount = async (packName: string, signal?: AbortSignal): Promise<number> => {const tag = `node-pack:${packName}`;diff --git a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.tsindex c41f036f2e..7f16505da2 100644--- a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts@@ -10,11 +10,8 @@ import { createKeyedTransientStore } from '@platform/state/externalStore';import { browserNodesDataPort } from './transport';/**- * Ephemeral per-node execution state, keyed by the invocation's source node id- * (the workflow editor's node id). Like the queue-item progress store, this is- * high-frequency transient data that deliberately lives outside the workbench- * reducer; the editor's nodes subscribe per id and only re-render when their- * own node's state moves.+ * Keep transient execution state outside the workbench reducer; subscribe per source node ID to isolate frequent+ * renders.*/export type NodeExecutionStatus = 'running' | 'completed' | 'failed';@@ -92,10 +89,7 @@ export const nodeExecutionStore = {status: 'running',});},- /**- * The queue item running these nodes reached a terminal state: a node still marked running- * finished with it, or never will (its failure/cancel event was lost or never sent).- */+ /** Terminal queue items end any remaining running node state, including missed failure/cancel events. */settleRunning(nodeIds: Iterable<string>, outcome: NodeExecutionOutcome): void {for (const nodeId of nodeIds) {const state = stateByNodeId.get(nodeId);diff --git a/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.test.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.test.tsindex d22e1c9562..ba71230064 100644--- a/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.test.ts+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodesStore.test.ts@@ -70,8 +70,7 @@ describe('custom node packs store', () => {await store.refreshCustomNodePacks();await store.refreshCustomNodePacks();- // Contract pinned for the maintenance menu's explicit-refresh surfacing:- // the stale list keeps rendering, the error waits in the snapshot.+ // Retain loaded packs during refetch failure and expose the error in the snapshot.expect(store.getCustomNodesSnapshot()).toMatchObject({ error: 'outage', status: 'loaded' });expect(store.getCustomNodesSnapshot().nodePacks.map((candidate) => candidate.name)).toEqual(['pack-a']);});diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/NodesPage.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/NodesPage.tsxindex 15aab6051a..ec6d39593c 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/NodesPage.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/NodesPage.tsx@@ -1,14 +1,7 @@import { Center, Spinner } from '@chakra-ui/react';import { lazy, Suspense } from 'react';-/**- * The Launchpad's nodes manager: pack library, add-nodes flow, and install- * activity. The Launchpad doesn't need any of it at first paint, so it is- * code-split: the chunk loads the first time this tab is opened (the shell's- * `lazyMount` keeps it off the critical path until then) and stays warm- * afterwards. All pack state lives in external stores, so the view needs no- * workbench providers here.- */+/** Load the manager on first tab visit; external stores preserve pack state without workbench providers. */const NodeManagerView = lazy(() =>import('@features/nodes/ui/NodeManagerView').then((module) => ({ default: module.NodeManagerView })));diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/activity/NodeInstallLog.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/activity/NodeInstallLog.tsxindex 70cd8a82dc..0a4cb6c543 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/activity/NodeInstallLog.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/activity/NodeInstallLog.tsx@@ -22,10 +22,6 @@ const STATUS_BADGES: Record<CustomNodeInstallLogEntry['status'], { labelKey: struninstalled: { labelKey: 'nodes.uninstalled', palette: 'orange' },};-/**- * Session install activity for the nodes manager. Tracks install / uninstall- * outcomes for the current session in a sticky-header table.- */export const NodeInstallLog = () => {const { t } = useTranslation();const log = useCustomNodeInstallLog();diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsxindex cb67a281da..c24b07ea03 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsx@@ -19,12 +19,8 @@ import { useMemo, type ChangeEvent, type KeyboardEvent } from 'react';import { useTranslation } from 'react-i18next';/**- * One box to add a node pack: a validated Git-URL install plus the manual- * drop-in path. The typed source lives in the nodes UI store because the- * detail tabs unmount their content — a tab flip must not lose it — and the- * busy state is derived from the shared install log so a remount mid-install- * still shows the install running. Validation mirrors the backend's rules so- * a doomed source is rejected before the POST.+ * Persist typed source and derive busy state from shared install activity so tab remounts preserve work; validate+ * before POST.*/export const AddNodesView = () => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePackDetail.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePackDetail.tsxindex 7354d3643a..a6954d92c3 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePackDetail.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePackDetail.tsx@@ -15,11 +15,8 @@ import { useTranslation } from 'react-i18next';import { NodePreviewCard } from './NodePreviewCard';/**- * Detail pane for a selected pack: a metadata header with an uninstall action,- * then a live preview of every node the pack contributes. Previews are built- * from the invocation templates the backend parsed from its OpenAPI schema —- * `pack.nodeTypes` are the exact invocation type keys, and a pack's nodes all- * share `template.nodePack === pack.name`.+ * Build previews from backend invocation templates; nodeTypes are invocation keys and nodePack identifies their+ * owning pack.*/export const NodePackDetail = ({ onUninstalled, pack }: { onUninstalled: () => void; pack: NodePackInfo }) => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.tsxindex 8201d348fc..5648751e4c 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.tsx@@ -21,14 +21,8 @@ import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { useTranslation } from 'react-i18next';/**- * A read-only, static rendering of a single node — the same visual language as- * the editor's `InvocationFlowNode` (titled header, output rows above input- * rows, colored field handles), shared via the workflow feature's node chrome- * helpers, but with none of its editor coupling. The real node depends on- * ReactFlow context (`Handle`, `useStore`) and the workbench dispatch; the- * Launchpad mounts neither, so this previews the node's shape from just its- * `InvocationTemplate`. Handles are drawn as plain dots, fields are labels- * only (no value controls), and nothing is interactive.+ * Render template-only node previews without ReactFlow or workbench dependencies; handles and fields are+ * noninteractive.*/const sortByUiOrder = <T extends { uiOrder?: number | null }>(templates: T[]): T[] =>diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackList.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackList.tsxindex 9535fa412b..22a28a102b 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackList.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackList.tsx@@ -15,12 +15,6 @@ import { useTranslation } from 'react-i18next';import { NodePackContextMenu, type NodePackContextMenuTarget } from './NodePackContextMenu';import { NodePackFilterMenu } from './NodePackFilterMenu';-/**- * Master list for the nodes manager: a search box over a scrollable column of- * selectable pack rows. Mirrors the model library list — `Row` with the- * `accent` active variant marks the open pack, and the search filters by name- * or path.- */export const NodePackList = ({activePackName,error,@@ -166,8 +160,7 @@ const PackRow = ({<Icon as={BlocksIcon} boxSize="4" color={isActive ? 'accent.contrast' : 'fg.subtle'} flexShrink={0} /><MiddleTruncate fontSize="xs" fontWeight="600" maxW="full" text={pack.name} />{isProblemPack(pack) ? (- // Zero nodes is the strongest health signal the catalog carries: the- // pack's import failed or a reload/restart is pending.+ // Zero registered nodes indicates import failure or pending reload/restart.<Tooltip content={problemHint}><Badge colorPalette="orange" flexShrink={0} fontSize="2xs" ms="auto" variant="surface">{pack.nodeCount}diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.tsxindex 1fd3675469..8cd586dccc 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/manager/ReloadNodesButton.tsx@@ -24,10 +24,8 @@ export const ReloadNodesButton = () => {await refreshCustomNodePacks(owner);assertAccountScopeCurrent(owner);- // The store records refetch failures without dropping loaded packs,- // so the stale list keeps rendering; the reload's own toast must not- // celebrate over it. (Reload is the only refresh affordance — a- // separate "refresh list" action would just duplicate this one.)+ // A retained stale list can hide refetch failure; reload must inspect the store error before announcing+ // success.const { error: refreshError } = getCustomNodesSnapshot();if (refreshError !== null) {@@ -36,10 +34,8 @@ export const ReloadNodesButton = () => {return;}- // The backend reports the outcome as prose (custom_nodes.py). Only- // its success phrasing earns a green toast; anything else — like- // "No custom nodes directory found." — surfaces as-is. Unknown- // statuses fail honest, never fail green.+ // Only recognized backend success prose earns a success toast; surface unknown statuses without claiming+ // success.if (status.startsWith('Custom nodes reloaded')) {notify.success(t('nodes.customNodesReloaded'));} else {diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/manager/layoutConstants.ts b/invokeai/frontend/webv2/src/features/nodes/ui/manager/layoutConstants.tsindex 42457dd045..0353d86a6c 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/manager/layoutConstants.ts+++ b/invokeai/frontend/webv2/src/features/nodes/ui/manager/layoutConstants.ts@@ -1,5 +1,3 @@-// Keep both values in sync with src/features/models/ui/manager/layoutConstants.ts —-// the two managers share their layout rhythm, but cross-feature imports are-// forbidden, so the values are duplicated by convention.+// Keep values aligned with models/ui/manager/layoutConstants.ts; cross-feature imports are forbidden.export const LIBRARY_WIDTH = 'clamp(22rem, 32vw, 28rem)';export const HEADER_MIN_HEIGHT = '2.75rem';diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/nodesUiStore.ts b/invokeai/frontend/webv2/src/features/nodes/ui/nodesUiStore.tsindex 8b3516ac52..3b9c104b4a 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/nodesUiStore.ts+++ b/invokeai/frontend/webv2/src/features/nodes/ui/nodesUiStore.ts@@ -2,12 +2,7 @@ import { DEFAULT_NODE_PACK_FILTERS, type NodePackFilters } from '@features/nodesimport { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore } from '@platform/state/externalStore';-/**- * Session-lived UI state for the Launchpad nodes manager. Keeping the active- * detail tab, selected pack, search term, and in-progress install source in an- * external store (the same pattern as the models UI store) means nothing- * resets while the user navigates within the manager.- */+/** Keep manager UI state session-lived so tab navigation preserves selection, search, and pending install input. */export type NodesManagerTab = 'details' | 'add';@@ -21,8 +16,7 @@ export interface NodesUiSnapshot {}const INITIAL_NODES_UI_SNAPSHOT: NodesUiSnapshot = {- // 'add' so a fresh install lands on the way to get node packs rather than- // the "select a pack" dead end (the models manager sets the same default).+ // Default to Add so empty installs offer an actionable entry point.activeTab: 'add',activePackName: null,activityExpanded: false,diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/shared/UninstallPackDialog.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/shared/UninstallPackDialog.tsxindex 1be0e1874e..1502b2ca43 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/shared/UninstallPackDialog.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/shared/UninstallPackDialog.tsx@@ -9,10 +9,8 @@ import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';/**- * Shared uninstall confirmation. Uninstalling also deletes the workflows the- * pack imported at install time, so the dialog fetches a best-effort count- * (by the pack's workflow tag) and says so — the count degrades to the- * generic copy when the fetch fails or returns zero.+ * Warn that uninstall deletes imported workflows; use a best-effort tag count and generic copy if unavailable or+ * zero.*/export const UninstallPackDialog = ({onClose,diff --git a/invokeai/frontend/webv2/src/features/queue/contracts.ts b/invokeai/frontend/webv2/src/features/queue/contracts.tsindex 50d21ca008..8730a5271c 100644--- a/invokeai/frontend/webv2/src/features/queue/contracts.ts+++ b/invokeai/frontend/webv2/src/features/queue/contracts.ts@@ -1,7 +1,6 @@/**- * Stable, implementation-free Queue contracts for owners that persist or- * present Queue state. Keeping this facade separate prevents contract-only- * consumers from loading the Queue runtime and widget implementation.+ * Keep contracts implementation-free so persistence and presentation consumers do not load Queue runtime or+ * widgets.*/export type {QueueHistoryItemStatus,diff --git a/invokeai/frontend/webv2/src/features/queue/core/deviceLabels.test.ts b/invokeai/frontend/webv2/src/features/queue/core/deviceLabels.test.tsindex ee280c5b17..57a06f6238 100644--- a/invokeai/frontend/webv2/src/features/queue/core/deviceLabels.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/deviceLabels.test.ts@@ -75,9 +75,7 @@ describe('getDeviceNameLabels', () => {});it('numbers by position in the full device set, so disabling a device does not renumber it', () => {- // The backend reports every installed CUDA device regardless of `generation_devices`, so- // cuda:2 stays #3 whether or not cuda:1 is enabled for generation. Numbering off a filtered- // list would silently promote cuda:2 to #2 and disagree with the backend's startup log.+ // Device numbering follows all reported accelerators; disabling one must not renumber the others.const allDevices = [{ device: 'cuda:0', name: 'RTX 5090' },{ device: 'cuda:1', name: 'RTX 5090' },diff --git a/invokeai/frontend/webv2/src/features/queue/core/deviceLabels.ts b/invokeai/frontend/webv2/src/features/queue/core/deviceLabels.tsindex 54740d9454..58613eaf11 100644--- a/invokeai/frontend/webv2/src/features/queue/core/deviceLabels.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/deviceLabels.ts@@ -1,11 +1,3 @@-/**- * Labels for the accelerator a queue item ran on.- *- * With `generation_devices` (default `auto`) the backend runs one session per accelerator- * concurrently, and tags each queue item and progress event with the device that- * processed it. These helpers turn `"cuda:1"` into something a person can read.- */-/** One device the backend offers for generation, from `GET /api/v1/app/generation_device_options`. */export interface GenerationDeviceOption {/** Device identifier, e.g. `cuda:0`, `xpu:0`, `mps`, `cpu`. */@@ -42,13 +34,8 @@ export const resolveRandDeviceMetadata = (useCpuNoise: boolean, options: readonl};/**- * Map device id → display label, disambiguating identically-named accelerators with a- * 1-based `#N` suffix. A uniquely-named device gets no suffix.- *- * The ordinal follows the order the options are given, and the backend returns- * every installed indexed accelerator in backend order — not just the ones enabled in- * `generation_devices`. That matters: numbering off a filtered list would renumber- * the survivors when a device is disabled, so `cuda:2` would stop being `#3`.+ * Disambiguate duplicate device names with backend-order 1-based suffixes across all installed accelerators,+ * including disabled ones.*/export const getDeviceNameLabels = (options: readonly GenerationDeviceOption[]): Record<string, string> => {const nameCounts = new Map<string, number>();@@ -77,14 +64,7 @@ export interface DeviceLabel {name: string;}-/**- * Resolve a device string to the badge + tooltip pair, or null when there is- * nothing worth showing.- *- * Null covers three cases: the device is not an indexed accelerator, only one accelerator exists (no- * ambiguity to resolve, so a badge would be noise), or the device is absent from- * the reported options.- */+/** Show badges only for reported indexed accelerators when multiple accelerators exist. */export const getDeviceLabel = (device: string | null | undefined,options: readonly GenerationDeviceOption[]diff --git a/invokeai/frontend/webv2/src/features/queue/core/generationMeta.test.ts b/invokeai/frontend/webv2/src/features/queue/core/generationMeta.test.tsindex 91d9826c27..a48e45f92e 100644--- a/invokeai/frontend/webv2/src/features/queue/core/generationMeta.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/generationMeta.test.ts@@ -22,10 +22,8 @@ describe('extractGenerationMeta', () => {});it('keeps an empty positive prompt empty instead of promoting the negative', () => {- // A video submitted in first-frame mode may legitimately carry no positive- // prompt: the image drives the clip. Reading by order would drop the blank- // and slide 'blurry, low quality' into the positive slot, so recalling it- // would put the negative text in the Video panel's subject box.+ // Preserve empty named positive prompts; positional scanning must not misread negative text as the video+ // subject.const meta = extractGenerationMeta(item([field('seed', 7), field('positive_prompt', ''), field('negative_prompt', 'blurry, low quality')]));diff --git a/invokeai/frontend/webv2/src/features/queue/core/generationMeta.ts b/invokeai/frontend/webv2/src/features/queue/core/generationMeta.tsindex 91e06729e4..0571cd5656 100644--- a/invokeai/frontend/webv2/src/features/queue/core/generationMeta.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/generationMeta.ts@@ -1,20 +1,8 @@import type { QueueItemReadModel } from '@features/queue/core/types';/**- * Best-effort recovery of the human-facing generation parameters for a queue- * item. The reliable source is the local submission snapshot (matched in the- * view by origin), but server items from other clients/sources only carry- * field values — generic node/field/value substitutions.- *- * Every batch this client submits names its nodes (`buildGeneratePromptBatchPlan`- * stamps the graph's prompt/seed node ids as `node_path`), so read by identity- * first. Order alone is not safe: a submission may legitimately carry an EMPTY- * positive prompt — the Video panel has no positive-prompt requirement at all —- * and a positional scan that skips blanks would slide the negative prompt into- * the positive slot and recall it as the subject.- *- * Unknown graphs (other clients, workflow batches naming their own nodes) fall- * back to the original by-type/by-order heuristic.+ * Prefer local snapshots, then named node fields. Preserve blank positive prompts; only unknown graph fields fall+ * back to type/order heuristics.*/export interface QueueGenerationMeta {@@ -51,8 +39,7 @@ export const extractGenerationMeta = (item: QueueItemReadModel): QueueGenerationreturn meta;}- // Fallback for graphs that name their nodes differently: recover by value- // type and order, as before. Only fills what the named pass did not.+ // Fill unresolved metadata by type/order only for graphs with unfamiliar node names.const prompts: string[] = [];for (const { value } of fieldValues) {diff --git a/invokeai/frontend/webv2/src/features/queue/core/graphInputMedia.ts b/invokeai/frontend/webv2/src/features/queue/core/graphInputMedia.tsindex 1a9d3225fa..13d1fa63d1 100644--- a/invokeai/frontend/webv2/src/features/queue/core/graphInputMedia.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/graphInputMedia.ts@@ -1,14 +1,6 @@/**- * Media names referenced by a compiled graph's node field values — the run's INPUTS- * (keyframes, source videos, reference images).- *- * Settlement collects result media by walking every node output in the backend- * session. A media primitive node echoes its input into `session.results` under the- * same name (e.g. the first-frame keyframe of an image-to-video workflow), so without- * this set the runtime would treat the user's source image as a generated result:- * board-attach it and record it on every run. Generated outputs are always saved- * server-side under fresh names, so a result name that appears in the compiled graph- * can only be an input passthrough.+ * Exclude compiled input media from results: primitive nodes echo inputs, while generated outputs receive fresh+ * server names.*/export interface GraphInputMediaNames {@@ -16,11 +8,7 @@ export interface GraphInputMediaNames {videoNames: ReadonlySet<string>;}-/**- * Collect every `image_name` / `video_name` string reachable from the compiled- * graph's nodes. `graph` is `unknown` because it comes from persisted snapshots;- * anything malformed yields empty sets (previous routing behavior).- */+/** Collect image_name/video_name strings from compiled nodes; malformed persisted graphs yield empty sets. */export const collectGraphInputMediaNames = (graph: unknown): GraphInputMediaNames => {const imageNames = new Set<string>();const videoNames = new Set<string>();diff --git a/invokeai/frontend/webv2/src/features/queue/core/progressRail.ts b/invokeai/frontend/webv2/src/features/queue/core/progressRail.tsindex 3b7569944f..5c2b92311f 100644--- a/invokeai/frontend/webv2/src/features/queue/core/progressRail.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/progressRail.ts@@ -2,13 +2,7 @@ import type { QueueItem } from './historyTypes';import { isOpenQueueItem } from './historySummary';-/**- * The read model behind the top bar's progress rail.- *- * 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.- */+/** Represent concurrent GPU sessions as separate segments rather than collapsing to one running item. */export type ProgressRailModel =| { kind: 'hidden' }@@ -29,8 +23,7 @@ export const getProgressRailModel = ({isConnected: boolean;sessionItemIds: readonly number[];}): ProgressRailModel => {- // Offline, a frozen bar would claim progress that cannot be arriving. The- // server-status widget owns saying why.+ // Hide frozen progress offline; the server-status widget explains the connection state.if (!isConnected || !hasOpenWork) {return HIDDEN;}@@ -38,15 +31,7 @@ export const getProgressRailModel = ({return sessionItemIds.length > 0 ? { itemIds: sessionItemIds, kind: 'sessions' } : PENDING;};-/**- * A determinate fill fraction, or null for the indeterminate sweep.- *- * Zero is indeterminate rather than an empty bar: the backend reports `0` for- * the span between "session started" and "first step done", which is exactly- * when models are loading and the wait feels longest. An empty determinate- * bar (or a "0%" label) reads as stalled there; the sweep reads as working.- * Every progress surface routes through this so they cannot disagree.- */+/** Treat zero as indeterminate during startup/model loading; all progress surfaces share this interpretation. */export const getDeterminateProgressFraction = (percentage: number | null | undefined): number | null =>typeof percentage === 'number' && percentage > 0 ? percentage : null;@@ -66,14 +51,7 @@ export const getProgressRailSegmentValue = ({percentage: number | null | undefined;}): number | null => (isLoadingModels ? null : getDeterminateProgressFraction(percentage));-/**- * The live sessions belonging to this project, in ascending id order.- *- * `itemProgressStore` is keyed by backend item id and spans the whole server- * queue, which on a multi-user backend includes other people's work; the rail- * sits beside a project-scoped queue readout, so it has to filter down to the- * ids this project actually enqueued.- */+/** Filter server-wide progress to this project's enqueued IDs, then order by ID. */export const selectProjectProgressItemIds = (queueItems: readonly QueueItem[],activeItemIds: readonly number[]diff --git a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.tsindex d334ae33c1..063b347327 100644--- a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts@@ -1,15 +1,6 @@/**- * The seed/prompt matrix for a generate submission.- *- * A generate graph carries one `positive_prompt` string node, so submitting- * several prompts is a batch dimension over that node rather than several- * graphs. Backend batch semantics (see- * `invokeai/app/services/session_queue/session_queue_common.py`): the outer list- * is a cartesian PRODUCT of groups, and each inner group is ZIPPED, so all of- * its items must have the same length.- *- * The prompt list arrives already expanded — Queue never talks to the expansion- * route itself.+ * Prompts arrive pre-expanded. Backend outer groups form a Cartesian product; entries within each group zip and+ * require equal lengths.*/import { SEED_MAX } from '@platform/core/seed';@@ -52,11 +43,7 @@ export interface GeneratePromptBatchDatum extends QueueBatchDatum {field_name: 'value';}-/**- * One workflow seed input that varies between runs: its first seed and the- * direction of the rest. Compact on purpose — the snapshot records the start- * the plan drew, and the runs expand from it deterministically at send time.- */+/** Persist each workflow seed's start and step; expand deterministic runs at send time. */export interface QueueWorkflowSeed {fieldName: string;nodeId: string;@@ -146,12 +133,8 @@ const generateLegacySeedSequence = (start: number, count: number): number[] =>Array.from({ length: sanitizeBatchCount(count) }, (_, index) => (start + index) % SEED_MAX);/**- * The expansion items queued before seed modes were planned with, reproduced so- * recovery replays them as recorded. Those items knew only a random toggle,- * which the runtime maps to a step of 1 or 0: the toggle decided whether one- * prompt (or per-iteration prompts) stepped or held, while several prompts with- * sharing disabled always stepped per image, and the sequence wrapped at- * `SEED_MAX` exclusive. New submissions never take this path.+ * Recovery preserves legacy random-toggle seed rules, including exclusive SEED_MAX wrapping; new submissions never+ * use this path.*/export const buildLegacyGeneratePromptBatchPlan = ({batchCount,@@ -205,18 +188,8 @@ export const buildLegacyGeneratePromptBatchPlan = ({};/**- * With a single prompt this reproduces the pre-dynamic-prompts payload exactly,- * which `promptBatch.test.ts` pins:- * - stepping seed -> one zipped group of `batchCount` seeds and repeated- * prompts, `runs: 1`- * - held seed -> one zipped group of length 1, `runs: batchCount`- *- * With several prompts the seed behaviour decides the shape, but only while the- * seed steps — a held seed is the same for every image whatever the behaviour:- * - `per-iteration` -> seeds become their own group, so the product is- * `iterations x prompts` and every prompt in an iteration shares its seed- * - `per-image` -> one distinct sequential seed per image, zipped against the- * prompt list repeated `batchCount` times, `runs: 1`+ * Held seeds reuse one value. Stepping per-iteration seeds form a product with prompts; per-image seeds zip with+ * repeated prompts.*/export const buildGeneratePromptBatchPlan = ({batchCount,diff --git a/invokeai/frontend/webv2/src/features/queue/core/submissionRules.test.ts b/invokeai/frontend/webv2/src/features/queue/core/submissionRules.test.tsindex 878ce42cf1..9de80ef2d8 100644--- a/invokeai/frontend/webv2/src/features/queue/core/submissionRules.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/submissionRules.test.ts@@ -20,9 +20,7 @@ const makeQueueItem = (sourceId: QueueSourceId, status: QueueHistoryItemStatus):describe('isBackendSubmittableSourceId', () => {it('includes canvas so canvas invocations are actually enqueued (regression: canvas→canvas stall)', () => {- // The bug: canvas snapshots carry sourceId 'canvas'; the runtime allow-list- // only had 'generate'/'workflow', so canvas items stacked as local pending- // rows forever and nothing generated.+ // Canvas source IDs must be allowed or local pending items never submit.expect(isBackendSubmittableSourceId('canvas')).toBe(true);});diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.tsindex e4a9a0c7eb..461caca164 100644--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts@@ -63,10 +63,7 @@ export interface QueueEnqueueGenerateRequest extends QueueEnqueueRequestBase {seedBehaviour?: QueuePromptSeedBehaviour;seedNodeId: string;seedStep: QueueSeedStep;- /**- * Set only when replaying an item queued before seed modes: its `seedStep` is- * the mapped random toggle, and the expansion follows that version's rules.- */+ /** Legacy recovery maps the old random toggle to seedStep and preserves its expansion rules. */legacySeedPlan?: true;}@@ -87,11 +84,7 @@ export type QueueCompiledSubmission =workflow?: Record<string, unknown>;/** The seed inputs that vary between runs, expanded into one zipped batch group at send time. */seeds?: QueueWorkflowSeed[];- /**- * The library record this run's workflow was loaded from, when the project- * graph is bound to one. Stamped at compile time so a completed run can be- * attributed back to the library record even after the editor moved on.- */+ /** Capture the bound library ID at compile time so completion attribution survives later editor changes. */libraryWorkflowId?: string;}| {@@ -146,11 +139,7 @@ export interface QueueWorkflowRunCompletedEvent {queueItemId: string;}-/**- * Optional observer for completed library-bound workflow runs. The Queue owns- * neither the workflow library nor the gallery, so the App composition root- * supplies the implementation; a missing sink simply disables the notification.- */+/** App injects optional completed-library-run capture; Queue owns neither library nor gallery. */export interface QueueWorkflowRunSink {onWorkflowRunCompleted(event: QueueWorkflowRunCompletedEvent): void;}@@ -279,16 +268,8 @@ export interface QueueFeatureCommands {resumeProcessor(): Promise<void>;}-/**- * The queue feature's backend seam. It owns both command transport and realtime- * events so runtimes never assemble HTTP calls and socket subscriptions.- */-/**- * The backend's preview snapshot (`ProgressPreviewDTO`): the fields of an- * `invocation_progress` socket event a preview consumer reads. The coordinator- * feeds it through the same handler as the socket event, where the revision- * gate drops anything the live stream already delivered.- */+/** Own command transport and realtime events together so runtimes do not assemble HTTP/socket plumbing. */+/** Feed preview snapshots through the socket handler's revision gate to reject frames already delivered live. */export interface QueueProgressPreviewPayload {queue_id: string;item_id: number;diff --git a/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.test.ts b/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.test.tsindex 4e6e851cac..71785744de 100644--- a/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.test.ts@@ -14,8 +14,7 @@ describe('activeProgressTargetStore', () => {});it('holds every concurrently-running target', () => {- // Multi-GPU runs one session per GPU, so a batch of two across two GPUs has two- // live slots. The previous single-value store dropped all but the latest.+ // Keep one live slot per concurrent GPU session; a single value loses other sessions.activeProgressTargetStore.set(target('queue-1', 1));activeProgressTargetStore.set(target('queue-1', 2));@@ -61,8 +60,7 @@ describe('activeProgressTargetStore', () => {});it('preserves start order so the followed target does not change while it runs', () => {- // The single-target accessor reads targets[0]. Following the most recent reporter- // instead is what made the preview flip between concurrent sessions.+ // Follow the oldest slot consistently rather than whichever session reports most recently.activeProgressTargetStore.set(target('queue-1', 1));activeProgressTargetStore.set(target('queue-1', 2));activeProgressTargetStore.set(target('queue-1', 1));diff --git a/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.ts b/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.tsindex 4c3e5a1930..6f67106d09 100644--- a/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.ts@@ -4,22 +4,8 @@ import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore } from '@platform/state/externalStore';/**- * The slots currently reporting progress, plus the ones settling.- *- * A list rather than a single value because of multi-GPU: with `generation_devices`- * (default `auto`) the backend runs one session per GPU, so a batch of four across- * two GPUs has two slots live at once. Holding only the most recent target meant- * concurrent sessions overwrote each other on every progress frame, and the preview- * flipped between them several times a second.- *- * Order is the order sessions started, which keeps the single-target accessor below- * stable for as long as that session runs.- *- * A *settling* slot is one whose backend item has completed but whose result has- * not landed in the gallery yet — two HTTP round trips away. Single-slot surfaces- * keep following it so the last denoise frame stays up until the finished image- * can take over; multi-slot surfaces (the tile grid) stop counting it, or a- * single-GPU batch would flash into a two-tile grid at every item boundary.+ * Track concurrent slots in start order. Settling slots preserve the final frame until results land; multi-slot+ * surfaces exclude them to avoid transient extra tiles.*/export interface ActiveProgressTargetSink {clear(target?: QueueItemProgressTarget): void;@@ -111,13 +97,8 @@ const selectFollowedTargets = ({settlingTargets.length === 0 ? targets : [...targets, ...settlingTargets];/**- * The slot to follow where a surface can only show one.- *- * The oldest still-running slot rather than the most recent to report: following the- * most recent is what made the preview flip between concurrent sessions. Behaviour is- * identical to the previous single-value store whenever one session runs at a time,- * which is every single-GPU install — except that a completed slot stays followed- * until its result lands.+ * Single-slot surfaces follow the oldest active or settling slot until its result lands, avoiding+ * concurrent-session flicker.*/export const useActiveProgressTarget = (): QueueItemProgressTarget | null =>store.useSelector((snapshot) => selectFollowedTargets(snapshot)[0] ?? null);diff --git a/invokeai/frontend/webv2/src/features/queue/data/events.ts b/invokeai/frontend/webv2/src/features/queue/data/events.tsindex cc81a6f9e4..fbd20077c0 100644--- a/invokeai/frontend/webv2/src/features/queue/data/events.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/events.ts@@ -1,11 +1,7 @@import type { QueueItemStatus, TerminalQueueItemStatus } from '@features/queue/core/types';import type { QueueStatusCountsDTO } from '@features/queue/data/serverTypes';-/**- * Typed contracts for the backend Socket.IO events webv2 consumes. Payload- * shapes mirror the pydantic models in- * `invokeai/app/services/events/events_common.py` (serialized as snake_case).- */+/** Mirror snake_case backend Socket.IO payload contracts from events_common.py. */export interface QueueItemEventBase {queue_id: string;@@ -95,16 +91,11 @@ export interface InvocationProgressEvent extends InvocationEventBase {/** Intermittent denoising preview, when the invocation produces one. */image?: { width: number; height: number; dataURL: string } | null;/**- * Monotonic per queue item, when the backend sends it: a frame at or below a- * revision already shown is stale and dropped. Absent from today's socket- * events, which arrive in order; the reconnect snapshot carries it.+ * Monotonic per queue item and session on image-bearing frames. Drop revisions at or below the latest accepted+ * frame so live and reconnect replay cannot move preview backward.*/revision?: number | null;- /**- * The accelerator running this session, e.g. `cuda:1` or `xpu:1` — null on CPU/MPS and in- * single-device mode. With `generation_devices` set (default `auto`) several- * sessions run at once, one per accelerator, so progress must be attributable.- */+ /** Device identifies concurrent accelerator sessions; null denotes CPU/MPS or single-device mode. */device?: string | null;}@@ -133,28 +124,13 @@ export interface BackendSocketEvents {export const isTerminalBackendStatus = (status: QueueItemStatus): status is TerminalQueueItemStatus =>status === 'completed' || status === 'failed' || status === 'canceled';-/**- * Queue items enqueued by webv2 carry the local queue item id in their origin- * so that submissions survive a reload: on startup the backend queue is listed- * and items are re-adopted by decoding their origin.- */+/** Encode local IDs in origins so reload reconciliation can re-adopt submitted backend items. */const QUEUE_ITEM_ORIGIN_PREFIX = 'webv2:';const PROJECT_QUEUE_ITEM_ORIGIN_PREFIX = 'webv2:p:';/**- * The origin prefix for utility-queue items — small graphs (filter previews,- * SAM, …) enqueued OUTSIDE any project's queue and awaited directly via- * `socketHub.on` (see `canvas-engine/backend/utilityQueue.ts`).- *- * The whole point of a distinct prefix is result isolation (plan Risk 4): a- * utility item must never be mistaken for a project queue item and routed into- * staging or the gallery. `parseQueueItemOrigin` therefore returns `null` for it- * — so `queueCoordinator.reconcile` and `isQueueItemReadModelInProject` never map a- * utility backend item to a local project item, and `routeQueueItemResults`- * (only ever invoked for coordinator-tracked project runs, which utility items- * are never registered as) never sees it. The `util:` segment sits under the- * shared `webv2:` namespace but is checked BEFORE the generic branch below, so- * it is not misparsed as a bare (non-project) local queue item id.+ * Utility origins isolate one-shot graphs from project adoption and result routing. Parse util before generic+ * webv2 origins to prevent accidental local IDs.*/const UTILITY_QUEUE_ITEM_ORIGIN_PREFIX = 'webv2:util:';@@ -175,10 +151,7 @@ export const isUtilityQueueItemOrigin = (origin: string | null | undefined): booorigin?.startsWith(UTILITY_QUEUE_ITEM_ORIGIN_PREFIX) ?? false;export const parseQueueItemOrigin = (origin: string | null | undefined): string | null => {- // Utility items are intentionally invisible to project routing (Risk 4): they- // resolve to no local queue item, so nothing adopts them or routes their- // results. Checked first because `webv2:util:` also matches the generic- // `webv2:` branch below.+ // Reject utility origins before the generic webv2 branch so project reconciliation cannot adopt them.if (isUtilityQueueItemOrigin(origin)) {return null;}diff --git a/invokeai/frontend/webv2/src/features/queue/data/generationDevicesStore.test.ts b/invokeai/frontend/webv2/src/features/queue/data/generationDevicesStore.test.tsindex c1dfa8ba53..fa917e0ade 100644--- a/invokeai/frontend/webv2/src/features/queue/data/generationDevicesStore.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/generationDevicesStore.test.ts@@ -62,8 +62,7 @@ describe('generationDevicesStore', () => {});it('PATCHes the runtime config and adopts the value the server echoes back', async () => {- // Shape verified against a live server: the config is nested under `config`,- // not returned at the top level.+ // Runtime config is nested under config, not returned at top level.mocks.apiFetchJson.mockResolvedValue({config: { generation_devices: ['cuda:0', 'cuda:1'] },set_fields: ['generation_devices'],diff --git a/invokeai/frontend/webv2/src/features/queue/data/generationDevicesStore.ts b/invokeai/frontend/webv2/src/features/queue/data/generationDevicesStore.tsindex a829034f06..326c21c117 100644--- a/invokeai/frontend/webv2/src/features/queue/data/generationDevicesStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/generationDevicesStore.ts@@ -10,12 +10,8 @@ import { createExternalStore } from '@platform/state/externalStore';import { apiFetchJson, getApiErrorMessage } from '@platform/transport/http';/**- * The accelerators available for generation, and which of them the server is configured to- * use. Pull-based like `modelCacheStore`: there are no socket events for app config.- *- * `generation_devices` is server-wide app config (admin-only, `PATCH- * /api/v1/app/runtime_config`) and only takes effect after a restart, so this is- * deliberately not treated as live state — nothing here re-reads on a timer.+ * Read available accelerators and server-wide generation_devices without polling; configuration takes effect only+ * after restart and has no socket updates.*//** `auto` uses every available accelerator; an explicit list pins generation to those devices. */@@ -64,11 +60,8 @@ const readGenerationDevices = (response: RuntimeConfigResponse | null): Generatiresponse?.config?.generation_devices ?? null;/**- * Load the device options and the current setting together.- *- * The options endpoint is available to any authenticated user, but the runtime- * config is admin-only. A non-admin therefore gets the options and a null setting- * rather than an error, which is what the read-only view wants.+ * Non-admins can read device options but not runtime config; return a null setting without failing the read-only+ * view.*/export const refreshGenerationDevices = (): Promise<void> => {if (inflight) {@@ -118,12 +111,7 @@ export const refreshGenerationDevices = (): Promise<void> => {return inflight;};-/**- * Persist a new `generation_devices` setting. Admin-only; takes effect on restart.- *- * The backend validates that every device actually exists on the machine and 422s- * otherwise, so a stale options list cannot write a config that fails at startup.- */+/** Admin changes take effect on restart; backend device validation rejects stale or nonexistent selections. */export const updateGenerationDevices = async (setting: GenerationDevicesSetting): Promise<void> => {const owner = captureAccountScope();diff --git a/invokeai/frontend/webv2/src/features/queue/data/itemProgressStore.ts b/invokeai/frontend/webv2/src/features/queue/data/itemProgressStore.tsindex ea4d203b78..35c1ee4cd2 100644--- a/invokeai/frontend/webv2/src/features/queue/data/itemProgressStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/itemProgressStore.ts@@ -3,15 +3,8 @@ import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore, createKeyedTransientStore } from '@platform/state/externalStore';/**- * Live progress for in-flight queue items keyed by the backend `item_id`. The- * sibling `progressStore` keys by the *local* submission id, which only exists- * for items this client enqueued; the Queue widget shows the whole server queue,- * so its NOW & NEXT card needs progress addressable by the backend id carried on- * the socket's `invocation_started`/`invocation_progress` events.- *- * Being keyed by item id is also what makes multi-GPU work: with- * `generation_devices` (default `auto`) the backend runs one session per GPU, so- * several items report progress at once and each needs its own entry.+ * Key progress by backend item ID for server-wide and concurrent GPU work; local submission IDs cannot identify+ * other clients' items.*/export interface ItemProgress {@@ -26,14 +19,8 @@ export interface ItemProgress {const progressByItemId = createKeyedTransientStore<number, ItemProgress>();/**- * The ids with live progress, ascending — a stable top-to-bottom order for stacked- * progress bars and tiled previews (ascending item id is submission order).- *- * Deliberately separate from the keyed store: consumers subscribe to *which* items- * are running here, and to a single item's progress via `useItemProgress`, so one- * session's step does not re-render another session's tile. Maintained from the- * mutation points below rather than derived from the keyed store, whose `entries()`- * allocates a fresh array per call and so cannot serve as a cached snapshot.+ * Keep a stable sorted ID snapshot separate from per-item progress so one session's steps do not rerender other+ * tiles.*/const activeItemIdsStore = createExternalStore<{ itemIds: number[] }>({ itemIds: [] });diff --git a/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.test.ts b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.test.tsindex 4f60c83945..20e0740260 100644--- a/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.test.ts@@ -45,9 +45,7 @@ describe('progressImageStore held frames', () => {});it('bridges only to the last selected output of a multi-output workflow', () => {- // Item 3 of a batch finishing must not put its denoise frame over item 1's- // image when the user clicks that one, nor over anything before routing- // has said which images the frame belongs to.+ // Only routed output names may use a held frame; another item in the same batch must not inherit it.progressImageStore.set(frame('third'), target('queue-1', 3));progressImageStore.hold(target('queue-1', 3));diff --git a/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.tsindex 11b4acea9f..d442307058 100644--- a/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts@@ -5,24 +5,8 @@ import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore, createKeyedTransientStore } from '@platform/state/externalStore';/**- * The most recent denoising preview image from `invocation_progress` events,- * as a b64 data URL. Cleared when the run settles so consumers (the editor's- * Current Image node, progress surfaces) fall back to the last real output.- *- * Next to the live frames, two small bounded sets of frames are *held* per- * local queue item when one of its backend items completes:- *- * - the bridge frame, shown while the batch's next slot is live but has not- * produced a frame of its own yet (model load, text encoding) — a sequential- * batch used to drop to an empty card between items;- * - the swap frame, shown in place of the finished image until the browser has- * decoded it, so the denoise→done boundary changes only the pixels inside- * the frame. Consumed on that first decode and expired shortly after, so- * browsing back to the image later never replays the low-resolution frame.- *- * Everything here survives a socket drop on purpose: the run continues on the- * backend and its durable outcome is reconciled over HTTP, so wiping the last- * frame on disconnect only ever produced a blank card until the next event.+ * Hold bounded bridge frames between batch slots and swap frames until image decode. Retain frames across+ * disconnects while HTTP reconciles the continuing run.*/export type ProgressImageSnapshot = QueueProgressImage;@@ -34,10 +18,7 @@ export type LatestProgressImageSnapshot = ProgressImageSnapshot & { target?: Pro/** Held frames are latent-grid JPEG data URLs, a few KB each. */const HELD_FRAME_LIMIT = 8;-/**- * Long enough to cover the finished image's fetch and decode on a slow link,- * short enough that a later deliberate visit to the image never hits it.- */+/** Allow time for slow fetch/decode without replaying held frames on later visits. */export const SWAP_FRAME_TTL_MS = 10_000;const latestSnapshotStore = createExternalStore<{ latestSnapshot: LatestProgressImageSnapshot | null }>({@@ -138,10 +119,8 @@ export const progressImageStore = {targetsByKey.delete(targetKey);if (didClearLatest) {- // Another slot may still be live: a video rendering for minutes next to a- // quick image batch. Falling to null here left the single-frame preview- // blank until the video's next step, while the gallery cell — which reads- // its own slot — kept showing the frame.+ // Fall back to another live slot's frame when one clears; concurrent long-running sessions must not go+ // blank.latestSnapshotStore.patchSnapshot({ latestSnapshot: getMostRecentSnapshot() });}},@@ -160,11 +139,7 @@ export const progressImageStore = {dropBridge(queueItemId);dropSwap(queueItemId);},- /**- * Copy the slot's current frame into both held sets. The live frame itself- * stays until the slot is cleared, so the single-slot preview keeps showing- * it while the finished image is fetched.- */+ /** Hold the final frame for bridging and swapping; retain the live slot until result fetch completes. */hold(target: ProgressImageTarget): void {const image = snapshotsByTarget.get(getTargetKey(target));diff --git a/invokeai/frontend/webv2/src/features/queue/data/progressStore.ts b/invokeai/frontend/webv2/src/features/queue/data/progressStore.tsindex 091313dfc5..745d8213b1 100644--- a/invokeai/frontend/webv2/src/features/queue/data/progressStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/progressStore.ts@@ -4,12 +4,8 @@ import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createKeyedTransientStore } from '@platform/state/externalStore';/**- * Ephemeral live-progress store for in-flight queue items, keyed by the local- * queue item id. Progress is high-frequency transient data, so it deliberately- * lives outside the workbench reducer: routing it through dispatch would- * re-render every consumer of workbench state and churn autosave on each step- * of every generation. Any widget can subscribe to a single item via- * `useQueueItemProgress` and only re-renders when that item's progress moves.+ * Store high-frequency progress outside workbench state to avoid global rerenders and autosave; subscribe per+ * local item ID.*/export interface QueueItemProgressSink {diff --git a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.ts b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.tsindex 4e3c1379fc..979d81ec30 100644--- a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.ts@@ -91,8 +91,7 @@ describe('queue realtime runtime', () => {runtime.start();vi.advanceTimersByTime(50);- // Multi-GPU emits one progress stream per running session, each tagged with its- // device. Without the tag the UI cannot label a tile or row with its GPU.+ // Preserve device tags so concurrent progress tiles can identify their accelerator.handlers.get('invocation_progress')?.({device: 'cuda:1',item_id: 42,diff --git a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.ts b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.tsindex 0abbc11d12..6c4cdcca07 100644--- a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.ts@@ -29,9 +29,8 @@ export interface QueueRealtimeRuntime {}/**- * Owns the global queue read model's one realtime subscription. Event bursts- * collapse into one invalidation; progress frames update their transient store- * directly and never force the full queue list through React state.+ * Own one realtime subscription; coalesce list invalidations while progress frames update transient stores+ * directly.*/export const createQueueRealtimeRuntime = ({backend,diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.tsindex 4446a4dac3..498b46ff59 100644--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts@@ -254,9 +254,8 @@ const collectResultVideoNames = (queueItem: QueueServerItemDTO, options?: QueueR};/**- * True when the video's DTO reports it as an intermediate. Fail-open on transport- * errors: the caller's board attach is best-effort, and a wrongly-attached- * intermediate is invisible in gallery listings (which filter intermediates).+ * Treat transport errors as non-intermediate for best-effort attachment; gallery listings still hide actual+ * intermediates.*/const isIntermediateVideo = async (videoName: string, signal: AbortSignal): Promise<boolean> => {try {@@ -275,12 +274,7 @@ const isIntermediateVideo = async (videoName: string, signal: AbortSignal): Prom}};-/**- * The names of the videos a completed backend item produced. The queue runtime only- * routes them onto the destination board, so DTOs are hydrated solely when- * `excludeIntermediate` needs the `is_intermediate` flag (the video analogue of the- * image path's filterIntermediateResults).- */+/** Fetch result video names; hydrate DTOs only when filtering intermediates requires their flags. */export const getResultVideoNames = async (itemId: number, options?: QueueResultVideoOptions): Promise<string[]> => {const owner = captureAccountScope();const item = await getQueueItem(itemId, owner.signal);diff --git a/invokeai/frontend/webv2/src/features/queue/devices.ts b/invokeai/frontend/webv2/src/features/queue/devices.tsindex 8315fafc2b..bea9005b33 100644--- a/invokeai/frontend/webv2/src/features/queue/devices.ts+++ b/invokeai/frontend/webv2/src/features/queue/devices.ts@@ -1,11 +1,4 @@-/**- * Generation-device reads, kept out of the broad `queue/react` barrel.- *- * The device options come from a server app-config endpoint that only the settings- * surface and the device labels need. Exporting them from `react` pulled the store into- * the activation payload of every widget that imports that barrel (the gallery adapter- * imports it for progress targets), which the architecture performance gate flags.- */+/** Keep device config outside queue/react so progress consumers do not load settings-only transport/store code. */export {getDeviceLabel,getDeviceNameLabels,diff --git a/invokeai/frontend/webv2/src/features/queue/launchpad.ts b/invokeai/frontend/webv2/src/features/queue/launchpad.tsindex d53af4a5e9..96b7c5c414 100644--- a/invokeai/frontend/webv2/src/features/queue/launchpad.ts+++ b/invokeai/frontend/webv2/src/features/queue/launchpad.ts@@ -1,5 +1,2 @@-/**- * Queue surface for the Launchpad. Exported eagerly — see the note in the- * Launchpad's `livePanels` module about the single shared lazy boundary.- */+/** Export eagerly; Launchpad livePanels owns the shared lazy boundary. */export { QueueStatusBand } from './ui/launchpad/QueueStatusBand';diff --git a/invokeai/frontend/webv2/src/features/queue/queries.ts b/invokeai/frontend/webv2/src/features/queue/queries.tsindex aae63e3497..17509b28bf 100644--- a/invokeai/frontend/webv2/src/features/queue/queries.ts+++ b/invokeai/frontend/webv2/src/features/queue/queries.ts@@ -1,6 +1,3 @@-/**- * Published Queue query surface for shell consumers (e.g. the command- * palette's queue search). Widget-internal data hooks stay private.- */+/** Expose shell-facing queue queries while keeping widget data hooks private. */export { getQueueReadModelOptions } from './publicApi';export { getQueueQueryScope, type QueueJobsScope } from './ui/queueScope';diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.tsindex 8ae3947ab9..d4885e288f 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts@@ -1967,8 +1967,7 @@ describe('queue runtime video board routing', () => {getItem: vi.fn(),getResultImages: options.getResultImages ?? vi.fn().mockResolvedValue([]),getResultVideoNames: options.getResultVideoNames,- // The backend already accepted and completed this run before "reload": reconcile- // adopts it and settles immediately, driving both settlement paths without sockets.+ // Reconcile an already-completed backend run to exercise both settlement paths without sockets.listItems: vi.fn().mockResolvedValue([{batchId: 'backend-batch',@@ -2105,9 +2104,7 @@ describe('queue runtime video board routing', () => {});it('never routes an input image echoed into the results (first-frame keyframe)', async () => {- // The i2v workflow's `image` primitive echoes the uploaded keyframe into- // session.results as a non-intermediate output; only the generated image may- // reach the board or the recorded results.+ // Exclude echoed i2v keyframes from result recording and board attachment.const { commands, destinations, runtime } = createHarness({getResultImages: vi.fn().mockResolvedValue([resultImage('keyframe.png'), resultImage('generated.png')]),getResultVideoNames: vi.fn().mockResolvedValue([]),diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.tsindex 35cd1bcac7..722a9da457 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts@@ -113,21 +113,13 @@ export const getQueueItemResultImageOptions = (queueItem: QueueItem): QueueResulreturn queueItem.snapshot.resultNodeIds ? { resultNodeIds: queueItem.snapshot.resultNodeIds } : undefined;};-/**- * The compiled backend graph this item submitted, or undefined for legacy/invalid- * snapshots. Used to recognize input passthroughs among collected results — see- * `collectGraphInputMediaNames`.- */+/** Read compiled graphs to identify input passthroughs; legacy or invalid snapshots may lack them. */const getQueueItemCompiledGraph = (queueItem: QueueItem): unknown => {const submission = (queueItem.snapshot as Partial<QueueItem['snapshot']>).backendSubmission;return submission && typeof submission === 'object' && 'graph' in submission ? submission.graph : undefined;};-/**- * Items queued before seed modes recorded the random toggle instead of a step;- * the mapped step plus `legacySeedPlan` lets the send path expand them with that- * version's rules, so recovery replays the seeds exactly as they were planned.- */+/** Recover legacy random-toggle submissions with their original seed expansion rules. */const readSubmissionSeedStep = (submission: { seedStep?: unknown; shouldRandomizeSeed?: unknown }) =>isQueueSeedStep(submission.seedStep)? submission.seedStep@@ -793,28 +785,16 @@ export const createQueueRuntime = ({};/**- * Land result videos on the destination board, like images. Videos are born- * unassigned server-side (the compiled graph carries no board unless a node- * sets one explicitly), so without this step every generated video sits in- * Uncategorized regardless of the active board. Only names are fetched — the- * gallery hydrates the video itself on its own refresh. Re-attaching a video- * that another settlement path already routed is a no-op server-side.- *- * Board attachment is cosmetic categorization: the run itself succeeded, so a- * failure here (transient fetch error, board deleted mid-run) is recorded as a- * queue-results error and NEVER thrown — throwing from the run-settlement path- * would mark a completed generation "failed" and skip recording its images.+ * Attach generated videos to the destination board; repeat attachment is idempotent. Categorization failures are+ * recorded but never turn successful generation into failure.*/const addResultVideosToDestination = async (projectId: string,queueItem: QueueItem,backendItemIds: number[]): Promise<void> => {- // Skip ids whose backend items were cancelled — their partial videos are not- // deliverable results (mirrors waitForResults filtering images to completed- // outcomes). The persisted set can miss a cancellation from the current- // session on the resumed path; the residual is a best-effort attach of an- // already-rendered video, not a correctness problem.+ // Skip known cancelled backend items. Resumed cancellation records can be incomplete, so remaining attachments+ // are best-effort.const deliverableItemIds = backendItemIds.filter((backendItemId) => !queueItem.cancelledBackendItemIds?.includes(backendItemId));@@ -837,8 +817,7 @@ export const createQueueRuntime = ({const namesPerItem = await mapWithConcurrency(deliverableItemIds, QUEUE_RUNTIME_CONCURRENCY, (backendItemId) =>runResultRead(() => backend.getResultVideoNames(backendItemId, options)));- // A video primitive echoes the run's INPUT video into session.results (e.g. the- // source clip of an extend-video workflow) — exclude it like input images.+ // Exclude video primitives' echoed input clips from generated results.const inputMedia = collectGraphInputMediaNames(getQueueItemCompiledGraph(queueItem));const videoNames = [...new Set(namesPerItem.flat())].filter((name) => !inputMedia.videoNames.has(name));@@ -860,11 +839,8 @@ export const createQueueRuntime = ({};/**- * Drop input passthroughs and (when the item asks) intermediates, then land what- * remains on the item's destination. Session results include every node's output,- * so a media primitive echoes the run's INPUT image under its original name — e.g.- * the first-frame keyframe of an image-to-video workflow — and routing it would- * board-attach the user's source image on every run.+ * Remove input passthroughs and requested intermediates before routing; echoed source media must not move boards+ * on every run.*/const deliverVisibleImages = async (queueItem: QueueItem,@@ -882,14 +858,8 @@ export const createQueueRuntime = ({};/**- * Reports a settled run back to whoever owns the workflow library, so it can- * capture the output as the record's thumbnail and stamp its last-run time.- * Only runs compiled from a library-BOUND workflow carry an id, so an ad-hoc- * workflow (or any generate run) is never reported.- *- * Deliberately synchronous, unawaited, and swallowing: last-run capture is- * decoration hung off a completed run, and a sink that throws must not turn- * that run into a failure or skip its gallery refresh.+ * Notify the optional library sink only for bound workflows. Capture is decoration: sink failure must not fail+ * settlement or prevent gallery refresh.*/const notifyWorkflowRunCompleted = (projectId: string, queueItem: QueueItem, images: QueueResultImage[]): void => {const submission = (queueItem.snapshot as Partial<QueueItem['snapshot']>).backendSubmission;@@ -919,10 +889,8 @@ export const createQueueRuntime = ({coordinator: QueueCoordinator,projectId: string,queueItem: QueueItem,- // The store is immutable and `queueItem` is a pre-submission closure, so callers must- // pass the run's backend item ids explicitly (enqueue result / reconcile outcome /- // persisted ids) — reading queueItem.backendItemIds here would always see undefined- // on the fresh-submit and adopted paths.+ // Pass actual backend IDs explicitly; the immutable pre-submit queueItem closure cannot contain newly assigned+ // IDs.backendItemIds: number[],attempt: RunAttempt): Promise<void> => {@@ -946,9 +914,7 @@ export const createQueueRuntime = ({}const images = await deliverVisibleImages(queueItem, allImages);- // The live path also routes videos per backend item as each completes- // (routeBackendItemResults); this run-end pass is the retry/backstop and the only- // coverage for items completed in a previous session. Never throws.+ // The run-end video pass retries live routing and covers earlier-session completions; it must never throw.await addResultVideosToDestination(projectId, queueItem, backendItemIds);if (!isAttemptCurrent(attempt)) {diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.tsindex a8bba83ee6..4e0670edd6 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts@@ -624,8 +624,7 @@ describe('queueCoordinator', () => {});it('keeps the followed slot and its last frame across a connection drop', async () => {- // The run continues on the backend; the sweep reconciles its outcome. Wiping- // the frame here only ever produced a blank card until the next event.+ // Keep the frame while disconnected; the backend continues and reconciliation finds its outcome.harness.coordinator.connect();await harness.coordinator.submitGenerate('local-1', generateRequest);harness.socket.fire('invocation_progress', {@@ -642,8 +641,7 @@ describe('queueCoordinator', () => {});it('sweeps outstanding items when the tab becomes visible again', async () => {- // A hidden tab's socket is dropped by the server and socket.io reconnects on- // its own backoff; the visibility edge itself reconciles the outcome first.+ // Visibility must reconcile immediately without waiting for socket reconnect backoff.const listeners = new Map<string, () => void>();vi.stubGlobal('document', {@@ -884,8 +882,7 @@ describe('queueCoordinator', () => {expect(harness.callbacks.onBackendItemComplete).toHaveBeenCalledWith('local-1', 1);// Held before routing started, so the finished image can swap in over it.expect(harness.progressImage.hold).toHaveBeenCalledWith({ itemIndex: 1, queueItemId: 'local-1' });- // The slot stays followed (settling) rather than dropping Preview back onto- // the previous selection while the finished image is still two round trips away.+ // Follow settling slots until finished-image routing completes instead of reverting to the old selection.expect(harness.activeProgressTarget.settle).toHaveBeenCalledWith({ itemIndex: 1, queueItemId: 'local-1' });expect(harness.activeProgressTarget.clear).not.toHaveBeenCalled();expect(harness.progressImage.clear).not.toHaveBeenCalled();@@ -1160,8 +1157,6 @@ describe('queueCoordinator', () => {await harness.coordinator.submitGenerate('local-1', generateRequest);- // No slot is executing yet, so no active index is published — queued- // items must never present as live.expect(harness.progressEntries.get('local-1')).toEqual({activeItemIndex: undefined,completedItemCount: 0,@@ -1188,8 +1183,7 @@ describe('queueCoordinator', () => {harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1 }));- // Between slots the item is idle again: completion is tracked, but no- // active index until the next progress event arrives.+ // Clear active slot index between items while preserving completion tracking.expect(harness.progressEntries.get('local-1')).toEqual({activeItemIndex: undefined,completedItemCount: 1,@@ -1417,14 +1411,8 @@ describe('queueCoordinator', () => {expect(harness.api.listItems).not.toHaveBeenCalled();});- // Review fix (Task 38, finding 3): the prior "Risk-4" coverage only asserted- // the parse primitive (`parseQueueItemOrigin(utilityOrigin) === null`) in- // isolation. This drives the REAL `reconcile` path with a completed,- // result-carrying `webv2:util:<uuid>`-origin backend item mixed into a live- // `listItems` response, proving the coordinator itself — not just the- // helper it calls — never adopts it into a project queue item (which is the- // only way a utility item's images could ever reach `routeQueueItemResults`- // and land in canvas staging or the gallery).+ // Exercise real reconciliation with a completed utility item to prove it cannot enter project adoption or+ // result routing.it('never adopts a completed, result-carrying utility-origin item into a project queue item', async () => {harness.api.listItems.mockResolvedValue([createQueueBackendItem({@@ -1437,10 +1425,7 @@ describe('queueCoordinator', () => {const outcomes = await harness.coordinator.reconcile([{ id: 'local-1', status: 'pending' }]);- // The utility item parses to no local queue item id, so it can never be- // bucketed under 'local-1' by origin: the pending project item finds no- // backend trace of its own and is asked to enqueue fresh — never- // "adopted" with the utility item's id, and never routed anywhere.+ // Utility origins cannot satisfy a pending project's backend trace; enqueue that project item fresh.expect(outcomes.get('local-1')).toEqual({ kind: 'enqueue' });expect(harness.api.getResultImages).not.toHaveBeenCalled();expect(harness.api.getItem).not.toHaveBeenCalledWith(99);@@ -1453,8 +1438,6 @@ describe('queueCoordinator', () => {await harness.coordinator.submitGenerate('local-1', generateRequest);const resultsPromise = harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');- // The completion event was lost to a disconnect; the reconnect sweep- // re-checks every outstanding item.harness.api.getItem.mockResolvedValue(createQueueBackendItem({ id: 1, status: 'completed' }));harness.socket.fire('connect', undefined);diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.tsindex f0f6cf7c59..10d0958601 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts@@ -43,9 +43,8 @@ const NODE_EVENT_BUFFER_EVENTS_PER_ITEM = 512;const BACKEND_READ_CONCURRENCY = 16;/**- * Queue's view of model-load activity derived from socket events. The- * production adapter is Models' modelLoadActivitySink, injected by the App- * composition root (see app/QueueRuntimeAdapter); tests inject a double.+ * App injects Models' model-load activity sink so Queue can report socket-derived activity without importing its+ * owner.*/export interface QueueModelLoadPort {completed(payload: unknown): void;@@ -141,21 +140,15 @@ export interface QueueCoordinator {connect(): void;detachRun(localQueueItemId: string): void;dispose(): void;- /**- * Match persisted pending/running queue items against the live backend queue- * so a reload neither double-submits nor orphans work. Adopted and resumed- * items are tracked and can be awaited with `waitForResults`.- */+ /** Reconcile persisted work with backend items to avoid duplicate submission or orphaned runs after reload. */reconcile(items: ReconcileInput[]): Promise<Map<string, ReconcileOutcome>>;/** Enqueue a generate batch and track its backend items for event-driven settlement. */submitGenerate(localQueueItemId: string, request: QueueEnqueueGenerateRequest): Promise<QueueEnqueueResult>;/** Enqueue a compiled workflow graph and track its backend items the same way. */submitWorkflow(localQueueItemId: string, request: QueueEnqueueWorkflowRequest): Promise<QueueEnqueueResult>;/**- * Resolve once every backend item of the run reaches a terminal status —- * driven by socket events, with a slow safety sweep as the only polling.- * Resolves with the result images, throws on failure, and throws- * `QueueItemCancelledError` on backend-side cancellation.+ * Await every backend item's terminal state via sockets and safety sweeps; return images or throw+ * failure/cancellation.*/waitForResults(localQueueItemId: string,@@ -249,11 +242,7 @@ export const createQueueCoordinator = (/** Enqueue requests awaiting a response; node events are only buffered while one is in flight. */let inFlightSubmissions = 0;const latestStatusSequences = new Map<number, number>();- /**- * Per backend item, the session and revision of the last accepted preview- * frame. Socket delivery is ordered, so this only bites when a second source- * — the reconnect snapshot the backend is to grow — races the live stream.- */+ /** Track accepted session/revision per backend item to reject snapshot frames overtaken by the live stream. */const latestFrameGates = new Map<number, { revision: number | null; sessionId: string }>();const detachers: Array<() => void> = [];@@ -348,10 +337,7 @@ export const createQueueCoordinator = (}};- /**- * The store follows whichever item most recently produced a live event; the backend may run items- * in any order, so only a replayed event from before the current item's takeover is a straggler.- */+ /** Backend order may vary; reject only replayed events predating the current item's takeover. */const isStaleNodeEvent = (nodeEvent: NodeEvent): boolean =>nodeExecutionItemId !== null &&nodeEvent.event.item_id !== nodeExecutionItemId &&@@ -493,17 +479,14 @@ export const createQueueCoordinator = (}if (outcome.status === 'completed') {- // Held before routing starts: the finished image swaps in over this frame- // once the browser has decoded it, and the batch's next slot shows it- // until a frame of its own arrives.+ // Hold the frame before routing so decoded results and the next frameless slot can replace it without+ // blanking.progressImage.hold(progressTarget);const routingPromise = callbacks.onBackendItemComplete?.(wait.localQueueItemId, backendItemId);if (routingPromise) {- // The slot stays followed until routing lands. Released on the terminal- // event, Preview fell out of live-follow two HTTP round trips before the- // finished image could be selected, and showed the previous selection- // in between.+ // Keep following until routing lands; terminal events precede finished-image selection by network round+ // trips.activeProgressTarget.settle(progressTarget);void Promise.resolve(routingPromise).finally(releaseProgressSlot)@@ -578,11 +561,8 @@ export const createQueueCoordinator = (};/**- * Slow safety net for events lost to disconnects; runs on reconnect, on the- * tab becoming visible, and on a long interval. A request made while one is in- * flight runs again afterwards rather than being dropped: the visibility sweep- * often fires while the network is still coming back and the reconnect sweep- * a second later is the one that can actually reach the backend.+ * Sweep on reconnect, visibility, and a slow interval. Requests during an active sweep guarantee a trailing pass+ * after network recovery.*/const sweep = async (): Promise<void> => {if (!isActive() || waits.size === 0) {@@ -626,12 +606,8 @@ export const createQueueCoordinator = (};/**- * Ask the backend for the latest preview frame of every running item and feed- * each through the socket handler, where the revision gate drops anything the- * live stream already delivered. Covers the frames lost while a hidden tab's- * socket was down, and the frames a reloaded page never saw. Best effort: the- * backend also replays them on `subscribe_queue`, and a failure here only means- * waiting for the next step.+ * Fetch current previews through the revision-gated live handler. Snapshot failure is nonfatal; replay or the+ * next step can recover.*/const refreshProgressPreviews = async (): Promise<void> => {if (!isActive() || waits.size === 0 || !backend.readProgressPreviews) {@@ -774,15 +750,8 @@ export const createQueueCoordinator = (};/**- * React to the shared socket's connection lifecycle. The Platform hub owns- * transport mechanics only; this Queue coordinator clears its transient- * per-node and model-load state and, on (re)connect, schedules a gallery- * refresh and missed-event sweep.- *- * The followed slot and its last frame deliberately survive a drop: the run- * continues on the backend and the sweep reconciles its durable outcome, so- * wiping them only ever produced a blank card — until the next event if the- * run was still going, or for good if it finished while disconnected.+ * Clear transient node/model-load state on connection changes and reconcile on reconnect. Preserve followed+ * slots/frames because backend runs continue offline.*/const handleConnectionChange = (status: BackendConnectionStatus): void => {if (!isActive()) {@@ -840,10 +809,7 @@ export const createQueueCoordinator = (// has already connected still triggers the initial clear + sweep.detachers.push(backend.onConnectionChange(handleConnectionChange));- // A hidden tab's socket is often dropped by the server (its pings are- // timer-throttled) and socket.io reconnects on its own backoff once the tab- // is back. The outcome is on the backend already, so sweep on the- // visibility edge itself rather than waiting for the reconnect edge.+ // Sweep when the tab becomes visible instead of waiting for socket reconnect backoff.if (typeof document !== 'undefined') {const visibilityDocument = document;const handleVisibilityChange = (): void => {@@ -887,10 +853,8 @@ export const createQueueCoordinator = (sweepTimer = null;}- // A disposed coordinator can never observe another event, so pending- // waits settle as canceled (raw, no completion/cancel side effects) —- // otherwise `waitForResults` awaiters hang forever. The backend run- // itself continues; a later `reconcile` re-adopts it.+ // Dispose settles local waiters as cancelled without backend side effects; later coordinators can re-adopt+ // continuing runs.for (const wait of waits.values()) {wait.settle({ status: 'canceled' });}@@ -1001,8 +965,7 @@ export const createQueueCoordinator = ();}- // A reloaded page has no frame for a run it just re-adopted; the socket only- // brings the next step's.+ // Fetch a preview for re-adopted runs rather than waiting for the next socket step.void refreshProgressPreviews();return outcomes;diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.test.tsindex 5ef62fae3e..f5fe5851ea 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.test.ts@@ -1096,14 +1096,10 @@ describe('runUtilityGraph — enqueue failures', () => {describe('runUtilityGraph — origin isolation (Risk 4)', () => {it('mints a webv2:util: origin that project routing provably ignores', () => {- // The utility origin resolves to NO local queue item, so `queueCoordinator`- // (which keys backend items by `parseQueueItemOrigin`) and `routeQueueItemResults`- // never adopt a utility item into project staging / gallery routing.+ // Utility origins must remain invisible to project adoption and staging/gallery routing.expect(isUtilityQueueItemOrigin(ORIGIN)).toBe(true);expect(parseQueueItemOrigin(ORIGIN)).toBeNull();- // A real project origin, by contrast, DOES parse to its local queue item id —- // demonstrating the coordinator adopts those but not utility items.const projectOrigin = buildQueueItemOrigin('local-1', 'project-1');expect(isUtilityQueueItemOrigin(projectOrigin)).toBe(false);expect(parseQueueItemOrigin(projectOrigin)).toBe('local-1');diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.ts b/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.tsindex e4e3a37407..0f2d26ee0a 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/utilityGraph.ts@@ -1,28 +1,6 @@/**- * The utility queue: fire-and-await small graphs OUTSIDE any project's queue.- *- * Filter previews and (later) Segment-Anything need to run a one-shot graph and- * read back its single output image WITHOUT the result ever touching project- * staging or the gallery. {@link runUtilityGraph} does exactly that:- *- * 1. Mints a fresh `webv2:util:<uuid>` origin (see `backend/events.ts`). That- * origin is deliberately invisible to project routing — `parseQueueItemOrigin`- * returns `null` for it, so `queueCoordinator.reconcile` /- * `isQueueItemReadModelInProject` never adopt it and `routeQueueItemResults`- * (only invoked for coordinator-tracked project runs, which a utility item is- * never registered as) never sees it. This is the plan's Risk-4 guard.- * 2. Attaches raw `socketHub.on` listeners (they survive socket recreation) for- * `invocation_complete` (to capture the output image name and dimensions) and- * `queue_item_status_changed` (to settle on the terminal status), matching- * events by our unique origin.- * 3. Enqueues the graph (listeners are attached first, closing the fast-finish- * race), then resolves with the output image metadata on completion, or rejects- * on failure/cancellation/timeout/abort. Abort and timeout also best-effort- * cancel every backend item accepted for this run, including when enqueue- * resolves after the local await has already rejected.- *- * Zero React, zero DOM: `hub` and `enqueue` are injected, so this runs in node- * tests against fakes. Every side-effecting dependency is a parameter.+ * Run isolated utility graphs with unique origins. Subscribe before enqueue to cover fast completion;+ * abort/timeout best-effort cancels all accepted items, including late enqueue responses.*/import type { QueueBackendGraph } from '@features/queue/core/types';@@ -212,9 +190,8 @@ export const reconcileUtilityCompletedOutput: UtilityCompletedOutputReconciler =};/**- * Runs `graph` on the utility queue and resolves with its output image metadata.- * Never routes into project state (isolated origin). Rejects with a- * {@link UtilityQueueError} on failure/cancel/timeout/abort/enqueue error.+ * Return utility output metadata without project routing; reject failures, cancellation, timeout, abort, and+ * enqueue errors as {@link UtilityQueueError}.*/export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<UtilityGraphResult> => {const { graph, hub, outputNodeId, signal } = options;diff --git a/invokeai/frontend/webv2/src/features/queue/ui/CancelQueueItemButton.tsx b/invokeai/frontend/webv2/src/features/queue/ui/CancelQueueItemButton.tsxindex 33d9e4ce69..693a7301da 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/CancelQueueItemButton.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/CancelQueueItemButton.tsx@@ -13,10 +13,8 @@ import { refreshQueue } from './queueDataStore';import { useQueueUi } from './QueueUiContext';/**- * Cancel a single queue item by its backend id. Works for any in-flight item- * regardless of which client submitted it; the coordinator settles local items- * off the resulting `queue_item_status_changed` event. `stopPropagation` keeps a- * click from also toggling the row it sits in.+ * Cancel by backend ID across clients; local coordination follows status events. Stop propagation to preserve row+ * state.*/export const CancelQueueItemButton = ({ itemId }: { itemId: number }) => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/features/queue/ui/ModelCacheFooter.tsx b/invokeai/frontend/webv2/src/features/queue/ui/ModelCacheFooter.tsxindex c8e44b8b6e..0fc81768ee 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/ModelCacheFooter.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/ModelCacheFooter.tsx@@ -28,12 +28,7 @@ const CacheStat = ({ label, value }: { label: string; value: number }) => (</Text>);-/**- * Collapsible MODEL CACHE footer (manifest `footer` slot). Collapsed: a label, a- * RAM-used / budget readout, and a fill bar. Expanded: hit/miss/loaded counts and- * a Clear action. The cache has no enable/disable endpoint, so there is no- * "Disable" toggle. Mirrors the model manager's `InstallQueueBar` collapse shape.- */+/** Model-cache footer supports statistics and clearing; no backend disable endpoint exists. */export const ModelCacheFooter = () => {const { t } = useTranslation();const { stats } = useModelCacheStats();diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsxindex 10230b8de1..2fd71d26f0 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsx@@ -15,9 +15,7 @@ export const attachQueueDataRuntime = (): (() => void) => {refreshModelCache: refreshModelCacheStats,});- // The device options never change without a restart, so one read at startup is- // enough. Every surface that labels an item or a progress tile with its GPU reads- // from this store, and on a single-GPU install the labels stay hidden.+ // Read device options once because changes require restart; hide labels for single-accelerator systems.void refreshGenerationDevices();runtime.start();diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.tsxindex 1ca4b6728f..b03754f4f0 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.tsx@@ -23,10 +23,6 @@ export const getQueueHeaderCancelState = ({itemLabel: 'widgets.queue.cancelCurrent',});-/**- * Cancel the current queue item from the manifest `headerActions` slot, so the- * most common interruption action sits inline beside the actions menu.- */export const QueueHeaderActions = () => {const { t } = useTranslation();const { canManageItem, isConnected, notify } = useQueueUi();diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderLabel.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderLabel.tsxindex a8777cfb39..ba5d24f223 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderLabel.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderLabel.tsx@@ -4,12 +4,7 @@ import { useTranslation } from 'react-i18next';import { useQueueCounts } from './queueDataStore';-/**- * The Queue widget's header title: "Queue" over a live "N generating · M waiting"- * summary. Rendered as the manifest `label`, so it sits in the standard frame- * header. Counts come straight from the server-wide status, with tabular- * numerals so the summary doesn't jitter as items move through the queue.- */+/** Use server-wide queue counts and tabular numerals to avoid header jitter. */export const QueueHeaderLabel = () => {const { t } = useTranslation();const counts = useQueueCounts();diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderMenu.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderMenu.tsxindex 4259aeb083..084305d9ef 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderMenu.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderMenu.tsx@@ -11,11 +11,7 @@ import { QueueMenuItems, useQueueMenuActions } from './queueMenuActions';import { useQueueQueryScope } from './queueScope';import { useQueueUi } from './QueueUiContext';-/**- * Queue actions contributed to the frame's shared actions menu via the manifest- * `headerMenu` slot. This intentionally uses the same action model as the- * topbar queue menu so backend mutations keep local run coordination in sync.- */+/** Share the topbar action model so backend mutations also update local run coordination. */export const QueueHeaderMenu = () => {const { t } = useTranslation();const actions = useQueueMenuActions();diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueItemThumbnail.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueItemThumbnail.tsxindex d11a5977d4..0f28d33096 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueItemThumbnail.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueItemThumbnail.tsx@@ -7,13 +7,6 @@ import {} from '@platform/ui/streaming-image/streamingImageSource';import { ImageOffIcon } from 'lucide-react';-/**- * Square result preview for a queue item. Falls back to a deterministic gradient- * derived from the item id, so items without a (yet) resolvable image still read- * as distinct tiles — and the real thumbnail cross-fades in once loaded. A- * hairline inset outline (theme border token) gives the tile consistent edge- * depth without picking up the surface color underneath.- */const QUEUE_ITEM_THUMBNAIL_SX: SystemStyleObject = {boxShadow: 'inset 0 0 0 1px {colors.border.subtle}',display: 'flex',diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueStats.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueStats.tsxindex 0aba3c16ab..024846517a 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueStats.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueStats.tsx@@ -3,11 +3,6 @@ import { useTranslation } from 'react-i18next';import { useQueueCounts } from './queueDataStore';-/**- * The four headline counts (done / failed / canceled / total) as a row of cards.- * Numbers are tabular so they stay aligned as the queue churns; the failed count- * turns danger-colored only when there's something to call out.- */const QueueStatCard = ({ value, label, danger }: { value: number; label: string; danger?: boolean }) => (<Stat.Root size="sm" colorScheme={danger ? 'red' : undefined} gap="0"><Stat.Label fontSize="xs" order="2">diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueStepProgress.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueStepProgress.tsxindex 565ffc61c4..f96e98fd63 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueStepProgress.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueStepProgress.tsx@@ -1,11 +1,7 @@import { Progress, Stack, Text } from '@chakra-ui/react';import { useTranslation } from 'react-i18next';-/**- * Thin denoising progress bar with a "step 12/30 · 39%" caption. `percentage` is- * 0..1 (null → indeterminate). The caption uses tabular numerals so the live- * step count and percent don't shift the layout as they tick.- */+/** percentage is 0..1 or null for indeterminate; tabular captions prevent live progress from shifting layout. */export const QueueStepProgress = ({ message, percentage }: { message: string; percentage: number | null }) => {const { t } = useTranslation();const percentLabel = percentage !== null ? `${Math.round(percentage * 100)}%` : '';diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsxindex fd79c2a1fc..8ec8cc678f 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx@@ -8,10 +8,7 @@ export interface QueueUiNotificationPort {success(title: string, description?: string): void;}-/**- * Queue's UI port. The context is a dependency-direction port (the feature- * may not import workbench), not a test seam; no second adapter is expected.- */+/** This UI port preserves dependency direction: Queue cannot import Workbench. */export interface QueueUiAdapter {ItemActions: ComponentType<{ item: QueueItemReadModel }>;activeProjectId: string | null;diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsxindex 97ed294033..f4d99b5130 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx@@ -14,12 +14,6 @@ import { QueueStats } from './QueueStats';import { usePendingQueueItemReveal } from './queueUiStore';import { RecentSection } from './RecentSection';-/**- * Queue console: server-wide stats, status filters, a live NOW & NEXT card, and- * the RECENT history. Header (title/Pause/menu) and the MODEL CACHE footer are- * provided through the manifest's chrome slots; this view is just the scrolling- * body. In a collapsed bottom dock it degrades to a single status chip.- */export const QueueWidgetView = ({presentation,region,@@ -51,8 +45,7 @@ const QueueContent = () => {const revealRequest = usePendingQueueItemReveal();const [handledRevealRequestId, setHandledRevealRequestId] = useState<number | null>(null);- // Render-phase adjustment (not an effect): a reveal request must not be- // hidden by the active status tab.+ // Adjust the active tab during render so it cannot hide a requested item.if (revealRequest !== null && revealRequest.requestId !== handledRevealRequestId) {setHandledRevealRequestId(revealRequest.requestId);setFilter('all');diff --git a/invokeai/frontend/webv2/src/features/queue/ui/RecentSection.tsx b/invokeai/frontend/webv2/src/features/queue/ui/RecentSection.tsxindex d3fef924f3..df32cb0399 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/RecentSection.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/RecentSection.tsx@@ -13,10 +13,7 @@ import { QueueItemRow } from './QueueItemRow';import { clearPendingQueueItemReveal, type QueueItemRevealRequest } from './queueUiStore';import { SectionHeader } from './SectionHeader';-/**- * RECENT — the windowed queue history, filtered by the active tab. The running- * and next items are excluded here since NOW & NEXT already shows them.- */+/** Exclude running and next items from recent history because NOW & NEXT already shows them. */export const RecentSection = ({filter,revealRequest = null,diff --git a/invokeai/frontend/webv2/src/features/queue/ui/formatDuration.ts b/invokeai/frontend/webv2/src/features/queue/ui/formatDuration.tsindex afb885348c..124f0c40ec 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/formatDuration.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/formatDuration.ts@@ -1,8 +1,4 @@-/**- * Compact execution-time labels for queue items ("4.37s", "1m 23s"). Computed- * from the backend's `started_at`/`completed_at` ISO timestamps; returns null- * when either is missing so callers can omit the field.- */+/** Return no duration when either backend timestamp is missing. */export const formatDuration = (startedAt?: string | null, completedAt?: string | null): string | null => {if (!startedAt || !completedAt) {return null;diff --git a/invokeai/frontend/webv2/src/features/queue/ui/launchpad/QueueStatusBand.tsx b/invokeai/frontend/webv2/src/features/queue/ui/launchpad/QueueStatusBand.tsxindex a8977efa69..c7b9f2f5d5 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/launchpad/QueueStatusBand.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/launchpad/QueueStatusBand.tsx@@ -6,29 +6,15 @@ import { HourglassIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';/**- * What the backend is doing right now, on the home screen.- *- * The Launchpad used to surface no application state at all — the home screen- * of an image generator said nothing about whether anything was generating.- * This is deliberately a single line: the Queue widget in the editor is where- * the detail lives.- *- * Scoped to every job rather than the active project, because Home is not- * inside a project.- *- * Reads `data/queries` directly rather than the feature's `publicApi`: that- * module constructs the realtime runtime and coordinator at import time, so- * going through it would pull the whole Queue runtime onto the home screen for- * two numbers.+ * Home shows server-wide activity outside project scope. Read queries directly to avoid loading Queue runtime for+ * summary counts.*/const ALL_JOBS_SCOPE = {} as const;/**- * Socket-driven invalidation lives in the editor's Queue widget runtime, and- * the query client has window-focus refetching turned off, so without this the- * band would show whatever the counts were when Home first mounted and never- * move again.+ * Refresh Home counts here because editor realtime invalidation is unmounted and query focus refetching is+ * disabled.*/const QUEUE_POLL_INTERVAL_MS = 5_000;@@ -60,8 +46,7 @@ export const QueueStatusBand = () => {py="2"rounded="lg">- {/* A real spinner while something runs; a static glyph for a queue that- is only waiting, so the band does not claim activity it cannot show. */}+ {/* Animate only running work; waiting-only queues use a static glyph. */}{inProgress > 0 ? (<Spinner color="fg.muted" size="xs" />) : (diff --git a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.tsindex d71ae36d55..548f5a3dd5 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/modelCacheStore.ts@@ -27,11 +27,7 @@ export const formatModelCacheBytes = (bytes: number | null | undefined): stringreturn `${unitIndex === 0 ? value : value.toFixed(1)} ${BYTE_UNITS[unitIndex]}`;};-/**- * RAM/VRAM model-cache statistics for the Queue widget's footer. Pull-based:- * the backend exposes `GET /api/v2/models/stats` (no socket events for cache- * stats), so we refresh on mount, after a model loads, and after a clear.- */+/** Cache statistics have no socket stream; refresh on mount, model load, and clear. */export interface ModelCacheStats {hits: number;diff --git a/invokeai/frontend/webv2/src/features/queue/ui/statusMeta.ts b/invokeai/frontend/webv2/src/features/queue/ui/statusMeta.tsindex 281ef6b6e5..f121e04280 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/statusMeta.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/statusMeta.ts@@ -1,10 +1,5 @@import type { QueueItemStatus } from '@features/queue/core/types';-/**- * Presentation metadata for each backend queue status: the human label, the- * Chakra `colorPalette` for badges, and the dot color used in list rows and the- * NOW & NEXT card. One table so status styling stays consistent everywhere.- */export interface QueueStatusMeta {labelKey: string;colorPalette: string;diff --git a/invokeai/frontend/webv2/src/features/queue/ui/useDeviceLabel.ts b/invokeai/frontend/webv2/src/features/queue/ui/useDeviceLabel.tsindex 5da97f1336..51c7bc6ebe 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/useDeviceLabel.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/useDeviceLabel.ts@@ -4,13 +4,7 @@ import { getDeviceLabel } from '@features/queue/core/deviceLabels';import { useGenerationDeviceOptions } from '@features/queue/data/generationDevicesStore';import { useMemo } from 'react';-/**- * Resolve a queue item's or progress event's device to a badge index + full name.- *- * Returns null whenever there is nothing worth showing — most importantly on a- * single-GPU install, where every item runs on the same GPU and a label would be- * pure noise. Callers can therefore render unconditionally on a non-null result.- */+/** Return device badge details only when multiple reported accelerators make identification useful. */export const useDeviceLabel = (device: string | null | undefined): DeviceLabel | null => {const options = useGenerationDeviceOptions();diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.tsindex 79c56abc97..7aa1bb8c25 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts@@ -49,8 +49,7 @@ const addUpscaleMetadata = (return;}- // getActiveCompatibleLoras reads only `loras`, so pass just that rather than fabricating a- // whole GenerateSettings whose other fields would be meaningless here.+ // Pass only loras; fabricating unrelated GenerateSettings fields would obscure the helper's actual dependency.const activeLoras = getActiveCompatibleLoras({ loras: settings.loras }, settings.model);const metadata = addNode(graph, {cfg_scale: settings.cfgScale,diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.tsindex 428459e9ac..591039696a 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.ts@@ -130,9 +130,8 @@ export const createDefaultUpscaleWidgetValues = (models: readonly ModelConfig[]};/**- * Heals older/partial persisted values without silently clamping invalid user- * input. Range checks remain invocation validation so actionable errors can be- * shown instead of changing a saved project behind the user's back.+ * Heal partial persisted values without clamping invalid user input; invocation validation supplies actionable+ * range errors.*/export const normalizeUpscaleWidgetValues = (value: unknown): UpscaleWidgetValues | null => {if (!isRecord(value)) {diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsxindex abe0797def..8fb28e0f92 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsx+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsx@@ -14,12 +14,8 @@ import { useTranslation } from 'react-i18next';import { areLorasEquivalent, areModelsEquivalent } from './upscaleComparators';/**- * The Upscale widget's prompt and LoRA controls.- *- * Both are memoised against content rather than identity (see- * `upscaleComparators`), because the widget re-derives `values` on every patch- * and these are the most expensive sections to re-render -- the prompt editors- * carry autocomplete state that a needless remount would disturb.+ * Compare prompt/LoRA content across reconstructed values to avoid costly rerenders and disturbed autocomplete+ * state.*/const SWITCH_CHECKED_PROPS = { bg: 'accent.solid' };@@ -120,11 +116,7 @@ export const UpscalePromptFields = memo(areLorasEquivalent(previous.loras, next.loras));-/**- * One LoRA row. Split out so editing a single weight re-renders that row rather- * than the whole list; the handlers bind the key here instead of at the call- * site, where they would be new closures per row per render.- */+/** Bind handlers within each memoized row so editing one weight does not rerender the whole list. */export const UpscaleLoraRow = memo(function UpscaleLoraRow({lora,onRemove,diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsxindex 0b649cf09d..0774e897ce 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx@@ -4,10 +4,7 @@ import type { ReactNode } from 'react';import { createContext, use, useMemo } from 'react';-/**- * Upscale's UI port. The context is a dependency-direction port (the feature- * may not import workbench), not a test seam; no second adapter is expected.- */+/** This UI port preserves dependency direction: Upscale cannot import Workbench. */export interface UpscaleUiAdapter {patchPromptDraft(values: ProjectPromptDraftPatch): void;patchValues(values: Partial<UpscaleWidgetValues>, origin?: 'user' | 'system'): void;@@ -22,12 +19,7 @@ export interface UpscaleUiAdapter {export type UpscaleUiActions = Pick<UpscaleUiAdapter, 'patchPromptDraft' | 'patchValues' | 'reportError'>;const UpscaleUiContext = createContext<UpscaleUiAdapter | null>(null);-/**- * Actions are published separately from the adapter because the adapter's- * identity changes on every value patch (it carries `rawValues`). Components- * that only need to *do* something — not read state — subscribe here and so are- * not re-rendered by a keystroke elsewhere in the form.- */+/** Separate stable actions from value-bearing adapters so action-only consumers do not rerender on form keystrokes. */const UpscaleUiActionsContext = createContext<UpscaleUiActions | null>(null);export const UpscaleUiProvider = ({ adapter, children }: { adapter: UpscaleUiAdapter; children: ReactNode }) => {diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsxindex 58fa558137..2df9301222 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx@@ -48,15 +48,7 @@ import { UpscaleLoraRow, UpscalePromptFields } from './UpscaleFormFields';import { UpscaleImageField } from './UpscaleImageField';import { useUpscaleUi, useUpscaleUiActions } from './UpscaleUiContext';-/**- * Every prop identity in this file is stable by construction — module-scope- * constants for literals, `useCallback`/`useMemo` for anything closing over- * state, and `memo` on each section. The widget re-renders on every keystroke- * that patches project state, so an inline `{...}`/`() => …` prop anywhere here- * re-renders the whole form (prompt editors and model pickers included) for a- * change that touched one number. The `react-perf` lint rules enforce this;- * they were previously disabled file-wide.- */+/** Keep props stable across project patches so memoized form sections do not rerender for unrelated field edits. */const VAE_PRECISION_COLLECTION = createListCollection({items: [@@ -221,9 +213,7 @@ export const UpscaleWidgetView = () => {const models = useModelsSelector((snapshot) => snapshot.models);const modelsStatus = useModelsSelector((snapshot) => snapshot.status);const { patchPromptDraft: patchDraft, patchValues, projectId, promptDraft, rawValues } = selection;- // Normalizing and reconciling against the model list is the widget's most- // expensive derivation; it must not run on unrelated re-renders, and a fresh- // `values` identity would re-render every section below.+ // Reuse normalization/reconciliation results across unrelated renders to preserve section identities.const values = useMemo(() => {const normalized = normalizeUpscaleWidgetValues(rawValues) ?? createDefaultUpscaleWidgetValues();@@ -356,8 +346,7 @@ export const UpscaleWidgetView = () => {[patch]);- // One setter per field, created once per `patch` identity: inline- // `onChange={(x) => patch({ x })}` props would defeat every `memo` below.+ // Create field setters per patch identity so inline handlers cannot defeat section memoization.const set = useMemo(() => ({cfgScale: (cfgScale: number) => patch({ cfgScale }),@@ -383,8 +372,6 @@ export const UpscaleWidgetView = () => {}),[patch]);- // Model filters close over the selected main model, so they change only when- // that model does — not on every keystroke elsewhere in the form.const loraFilter = useCallback((model: ModelConfig) =>Boolean(values.model && isLoraModelConfig(model) && isLoraCompatibleWithModel(model, values.model)),diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.test.ts b/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.test.tsindex ddf4ba3202..f7de518cc6 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.test.ts@@ -43,14 +43,11 @@ describe('getModelTriggerPhrases', () => {describe('areModelsEquivalent', () => {it('treats a fresh config under the same key as equivalent when its data matches', () => {- // A catalog refresh replaces the object without changing anything the- // prompt editors read, and re-rendering them for that is pure waste.expect(areModelsEquivalent(model(), model())).toBe(true);});it('separates models the prompt editors would render differently', () => {- // Each of these feeds a prompt-editor affordance, so matching on `key`- // alone would leave the editors showing the previous model's data.+ // Compare model metadata beyond key; prompt affordances can change under the same catalog identity.expect(areModelsEquivalent(model(), model({ key: 'model-b' }))).toBe(false);expect(areModelsEquivalent(model(), model({ base: 'sd-1' }))).toBe(false);expect(areModelsEquivalent(model(), model({ name: 'Model B' }))).toBe(false);@@ -81,8 +78,7 @@ describe('areLorasEquivalent', () => {describe('areInputImagesEquivalent', () => {it('separates images by dimensions as well as by name', () => {- // The preflight readout is computed from these, so a same-named image at- // new dimensions must not reuse the previous megapixel estimate.+ // Include dimensions in equality so same-name image updates recompute preflight estimates.expect(areInputImagesEquivalent(image(), image())).toBe(true);expect(areInputImagesEquivalent(image(), image({ width: 1024 }))).toBe(false);expect(areInputImagesEquivalent(image(), image({ height: 1024 }))).toBe(false);diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.ts b/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.tsindex 7624793253..811de644f2 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.ts+++ b/invokeai/frontend/webv2/src/features/upscale/ui/upscaleComparators.ts@@ -1,17 +1,7 @@import type { GenerateLora } from '@features/generation/contracts';import type { UpscaleWidgetValues } from '@features/upscale/core/types';-/**- * Content comparators for the Upscale widget's memo boundaries.- *- * `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.- *- * 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.- */+/** Compare normalized values by content; permissive memo comparisons would silently retain stale UI. */export const areStringArraysEqual = (left: readonly string[], right: readonly string[]): boolean =>left === right || (left.length === right.length && left.every((value, index) => value === right[index]));@@ -36,11 +26,8 @@ export const getModelTriggerPhrases = (model: UpscaleWidgetValues['model']): rea};/**- * `key` alone is not enough: a catalog refresh swaps in a fresh config under- * the same key, and the prompt editors consume per-config data (trigger- * phrases, used both to populate the autocomplete and to label its group;- * `base`, used to filter compatible embeddings). Identity short-circuits the- * common case.+ * Catalog refreshes can change trigger phrases or base under the same key; compare prompt-relevant metadata after+ * identity checks.*/export const areModelsEquivalent = (left: UpscaleWidgetValues['model'], right: UpscaleWidgetValues['model']): boolean =>left === right ||@@ -62,10 +49,6 @@ export const areInputImagesEquivalent = (left.width === right.width &&left.height === right.height);-/**- * Whole-values equality for the model reconciler, which asks only "did- * normalization change anything at all" — a question a deep structural compare- * answers correctly and cheaply enough at that one call site.- */+/** Use structural equality to detect any normalization change at the reconciler boundary. */export const valuesAreEqual = (left: UpscaleWidgetValues, right: UpscaleWidgetValues): boolean =>JSON.stringify(left) === JSON.stringify(right);diff --git a/invokeai/frontend/webv2/src/features/video/core/dimensions.ts b/invokeai/frontend/webv2/src/features/video/core/dimensions.tsindex a147a9b868..87b355b3db 100644--- a/invokeai/frontend/webv2/src/features/video/core/dimensions.ts+++ b/invokeai/frontend/webv2/src/features/video/core/dimensions.ts@@ -6,18 +6,8 @@ import type {} from './types';/**- * Client-side ports of the backend's video canvas math, so the panel can show- * and validate the exact dimensions a graph will run at without extra nodes:- *- * - Wan: `_scale_and_snap` in `invokeai/app/invocations/wan/wan_ideal_dimensions.py`- * ("nearest" rounding — the node default; the other modes are workflow-only).- * - MiniMax H3: `resolve_canvas_size` in `invokeai/backend/minimax_h3/packing.py`- * and `resolve_lowres_canvas_size` in `invokeai/backend/minimax_h3/presets.py`.- * - Ref2VA image references: `resolve_reference_image_short_edge` and- * `normalize_reference_image` in `invokeai/backend/minimax_h3/reference_conditioning.py`.- *- * Where the backend raises, these return null: the panel falls back to defaults- * and reports the problem through `getVideoValidationReasons` instead of throwing.+ * Mirror Wan _scale_and_snap, H3 canvas presets, and reference-image normalization. Return null where backend math+ * rejects input so panel validation can explain it.*/export interface VideoDimensions {@@ -25,9 +15,7 @@ export interface VideoDimensions {height: number;}-// Python's round() (used by both backend implementations) is half-to-even;-// Math.round is half-up. The ports must agree with the backend on exact .5-// quotients (e.g. 720 / 32 = 22.5) or panel and workflow dims would differ.+// Match Python half-to-even rounding; Math.round differs at exact .5 and would produce inconsistent canvas sizes.const roundHalfToEven = (value: number): number => {const floor = Math.floor(value);const diff = value - floor;@@ -58,16 +46,8 @@ export const WAN_TARGET_RESOLUTION_PX: Record<WanTargetResolution, number> = {};/**- * Scale a source W×H so its shorter side equals the preset's pixel count, then- * snap each dimension to the Wan pixel grid (nearest). Only the ratio of the- * inputs matters, so aspect-ratio parts (16, 9) work as well as real pixels.- * Null when the inputs are non-positive or non-finite.- *- * Deliberate divergence from the backend node: `_scale_and_snap` rejects- * sources whose RAW long side is under one grid cell, which would also reject- * pure ratio parts like (16, 9) on the ×32 grid. Since only the ratio matters- * and scaling happens before snapping, tiny-but-well-formed inputs are- * accepted here — the scaled long side is always ≥ the target short side.+ * Scale the ratio to the target short side and snap to Wan's grid. Unlike the backend raw-size guard, accept small+ * positive ratio parts; reject nonfinite/nonpositive inputs.*/export const scaleAndSnapWanDimensions = (width: number,@@ -95,13 +75,8 @@ export const MINIMAX_H3_MIN_ASPECT_RATIO = 1 / 4;export const MINIMAX_H3_MAX_ASPECT_RATIO = 4;/**- * The MiniMax H3 canvas for an aspect ratio. "768 highres" is the released- * pipeline's policy: short edge 768, soft area cap of 768×1344, both axes then- * rounded to the nearest multiple of 32 (so the final area may sit slightly- * above the pre-rounding budget). "768 lowres" pins the LONG edge to 768- * instead for cheaper preview renders. Only the ratio of the inputs matters.- * Null when the inputs are degenerate or the ratio is outside H3's supported- * 1:4 – 4:1 range.+ * H3 highres uses a 768 short edge and soft 768x1344 area cap before 32-pixel rounding; lowres caps the long edge+ * at 768. Reject ratios outside 1:4–4:1.*/export const resolveMiniMaxH3Canvas = (width: number,@@ -164,16 +139,8 @@ export const MINIMAX_H3_REFERENCE_IMAGE_SHORT_EDGE = 2048;export const MINIMAX_H3_ROW_PIXELS = 32 * 32;/**- * A reference image's normalized size and the rows it contributes.- *- * Those rows join the packed sequence and are re-attended at EVERY denoising step, with- * attention quadratic in the sequence length — which is the whole difference between the- * two detail settings. `'max'` pins the short edge to 2048 no matter how small the- * generation is; `'match'` scales the reference to the generation's pixel area (never- * above the 2048 rule), typically an order of magnitude fewer rows.- *- * Null when the inputs are degenerate, or when `'match'` has no target area to match —- * the panel then shows nothing rather than a wrong number.+ * Reference rows participate in every denoise step. max uses a 2048 short edge; match uses capped generation area.+ * Return null without valid geometry/target area.*/export const resolveMiniMaxH3ReferenceImage = (width: number,@@ -191,8 +158,6 @@ export const resolveMiniMaxH3ReferenceImage = (if (targetArea === null || !Number.isFinite(targetArea) || targetArea <= 0) {return null;}- // The backend rounds with Python's banker's rounding here, so `roundHalfToEven` is- // what keeps this estimate equal to the size the graph actually encodes.const matched = Math.max(MINIMAX_H3_CANVAS_MULTIPLE,roundHalfToEven(Math.min(width, height) * Math.sqrt(targetArea / (width * height)))@@ -225,10 +190,8 @@ export const invertVideoAspectRatioId = (id: VideoAspectRatioId): VideoAspectRatreturn `${height}:${width}` as VideoAspectRatioId;};-// Wan's VAE compresses 4 pixel frames into 1 latent frame, so (n - 1) % 4 == 0.-// 81 frames (5 s at 16 fps) is the training default; the slider allows up to-// twice that, but coherence degrades past 81 as temporal RoPE leaves its-// training distribution — the docs recommend chaining extends instead.+// Wan requires 4n+1 frames. The 81-frame training default supports best coherence; longer clips extend beyond the+// trained temporal range.export const WAN_NUM_FRAMES_MIN = 5;export const WAN_NUM_FRAMES_MAX = 161;export const WAN_NUM_FRAMES_STEP = 4;@@ -253,10 +216,7 @@ export const snapWanNumFrames = (numFrames: number): number => {export const MINIMAX_H3_FPS = 24;-// The 17n + 5 grid points the H3 video VAE can encode, from the accepted-// 3.75 s floor to the 15 s ceiling. Mirrors MINIMAX_H3_VIDEO_FRAME_CHOICES in-// invokeai/backend/minimax_h3/presets.py; the 5-frame still-image block is-// deliberately absent — the panel generates video, not stills.+// Mirror H3's 17n+5 video frame choices from presets.py; exclude the five-frame still-image block.export const MINIMAX_H3_NUM_FRAMES_CHOICES: readonly number[] = Array.from({ length: 16 }, (_, i) => 90 + i * 17);export const MINIMAX_H3_NUM_FRAMES_DEFAULT = 124;diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.test.ts b/invokeai/frontend/webv2/src/features/video/core/graph.test.tsindex ecc40757fc..deac8e9c77 100644--- a/invokeai/frontend/webv2/src/features/video/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/graph.test.ts@@ -211,8 +211,7 @@ describe('compileVideoGraph — Wan 2.2', () => {generation_mode: 'wan_extend_video',source_video: { video_name: 'clip.mp4' },});- // Metadata rides both the final concat and the intermediate clip, and the- // run-time conditioning frame is recorded via an edge (template behavior).+ // Record metadata on both clips and wire runtime conditioning-frame identity through an edge.expect(hasEdge(backendGraph, 'core_metadata', 'metadata', 'video_output', 'metadata')).toBe(true);expect(hasEdge(backendGraph, 'core_metadata', 'metadata', 'extension_clip', 'metadata')).toBe(true);expect(hasEdge(backendGraph, 'source_last_frame', 'image', 'core_metadata', 'first_frame_image')).toBe(true);@@ -244,8 +243,7 @@ describe('compileVideoGraph — Wan 2.2', () => {it('compiles ceiling-touching trim STARTS as negative indices too — a keep-the-tail trim survives estimate overshoot', () => {const model = wanModel('i2v_a14b');- // numFrames 81: startFrame 77 has tail offset 3 (→ -4), endFrame 79 has- // tail offset 1 (→ -2). Both inside the tail window, order preserved.+ // Near-tail bounds convert together to negative offsets while preserving order.const tailTrim = compileVideoGraph(settingsFor(model, { sourceVideo: { ...SOURCE_VIDEO, endFrame: 79, startFrame: 77 } }),model@@ -253,9 +251,7 @@ describe('compileVideoGraph — Wan 2.2', () => {expect(nodeOfType(tailTrim, 'extract_video_range')).toMatchObject({ end_frame: -2, start_frame: -4 });- // Tail offset 4 is the first index OUTSIDE the window: it stays a- // positive literal (converting it would drift mid-clip picks when the- // estimate overshoots), even when the end still converts.+ // Bounds outside tail slop remain absolute to avoid drifting mid-clip picks.const boundary = compileVideoGraph(settingsFor(model, { sourceVideo: { ...SOURCE_VIDEO, endFrame: 78, startFrame: 76 } }),model@@ -362,9 +358,7 @@ describe('compileVideoGraph — MiniMax H3', () => {const { backendGraph } = compileVideoGraph(settings, model);const denoise = nodeOfType(backendGraph, 'minimax_h3_denoise');- // The H3 canvas policy: 16:9 caps at 1344×768; frame counts are string literals.- // The H3 denoise node counts sigma grid points, so the graph passes- // panel steps (model evaluations) + 1.+ // H3 canvas follows preset policy; node steps include one terminal sigma point beyond model evaluations.expect(denoise).toMatchObject({ height: 768, num_frames: '124', steps: settings.steps + 1, width: 1344 });const output = nodeOfType(backendGraph, 'minimax_h3_latents_to_video');@@ -419,8 +413,7 @@ describe('compileVideoGraph — MiniMax H3', () => {const settings = settingsFor(model, { sourceVideo: { ...SOURCE_VIDEO, endFrame: 80 } });const { backendGraph } = compileVideoGraph(settings, model);- // H3 renders at a fixed 24 fps; the source is retimed up front so the- // concat (which inherits the first clip's rate) joins at one speed.+ // Retime source to H3's fixed 24 fps before concatenation inherits its rate.expect(nodeOfType(backendGraph, 'extract_video_range')).toMatchObject({ fps: 24 });expect(hasEdge(backendGraph, 'source_last_frame', 'image', 'pos_cond', 'first_image')).toBe(true);expect(hasEdge(backendGraph, 'source_last_frame', 'image', 'frame_conditioning', 'first_image')).toBe(true);@@ -497,9 +490,7 @@ describe('compileVideoGraph — MiniMax H3 Ref2VA', () => {expect(video.id).toBe('reference_1');expect(video.conditioning).toBe('video_audio');expect(video.start_frame).toBe(2);- // The end bound sits in the estimate's tail window, so it compiles as a negative- // index the backend resolves against the clip's REAL frame count (the panel's count- // is an estimate that can overshoot on VFR uploads) - same rule as the extend path.+ // Resolve tail-window bounds against actual backend frame counts to tolerate VFR estimate overshoot.expect(video.end_frame).toBe(-1);expect(image.id).toBe('reference_2');expect(image.detail).toBe('match');@@ -639,19 +630,14 @@ describe('compileVideoGraph — MiniMax H3 Ref2VA', () => {'minimax_h3_video_reference').start_frame;- // Both bounds convert together, flagged or not. Mixing an absolute start- // with a tail-relative end splits the window across two index spaces: the- // backend then extracts `length + (real - estimate)` frames, or -- on a- // window short enough for the error to swallow -- resolves the end BEFORE- // the start and fails the generation.+ // Convert both reference bounds together; mixed absolute/relative indices distort length or reverse short+ // windows.expect(startOf(linked({ endFrame: 400, startFrame: 260 }, false))).toBe(-142);// The inversion that mixing produced: [398,399] of an estimated 402 emitted// `398 / -3`, which against a real 400 is start 398, end 397.expect(startOf(linked({ endFrame: 399, startFrame: 398 }, false))).toBe(-4);- // A start at or inside the estimate's slop stays ABSOLUTE: the relative- // form resolves to `startFrame + (real - estimate)`, and the backend- // rejects a negative index rather than clamping, so an estimate that- // overshoots by more than `startFrame` would fail the whole generation.+ // Keep near-start bounds absolute because estimate overshoot could make a relative start negative and fail+ // extraction.expect(startOf(linked({ endFrame: 400, startFrame: 0 }))).toBe(0);expect(startOf(linked({ endFrame: 400, startFrame: 1 }))).toBe(1);expect(startOf(linked({ endFrame: 400, startFrame: 3 }))).toBe(3);@@ -696,8 +682,6 @@ describe('compileVideoGraph — MiniMax H3 Ref2VA', () => {};const { backendGraph } = compileVideoGraph(settings, model);- // The new clip is intermediate; the crossfade concat is the output, fed- // [trimmed source, new clip]; the source is retimed to H3's fixed 24 fps.expect(nodeOfType(backendGraph, 'minimax_h3_latents_to_video')).toMatchObject({id: 'extension_clip',is_intermediate: true,@@ -714,10 +698,7 @@ describe('compileVideoGraph — MiniMax H3 Ref2VA', () => {// The linked reference is an ordinary first reference; the flag never reaches metadata.const videoReferences = nodesOfType(backendGraph, 'minimax_h3_video_reference');- // Both bounds ride the SAME negative anchor, so the extracted window keeps- // its exact length whatever the clip's real frame count turns out to be.- // A positive start would have made it `tail + (real - estimate)` frames,- // and the overrun is discarded at the seam.+ // Use one tail-relative anchor for both bounds to preserve window length despite frame-count estimation error.expect(videoReferences[0]).toMatchObject({ end_frame: -2, id: 'reference_1', start_frame: -142 });expect((videoReferences[0].end_frame as number) - (videoReferences[0].start_frame as number)).toBe(140);const metadata = nodeOfType(backendGraph, 'core_metadata');diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.ts b/invokeai/frontend/webv2/src/features/video/core/graph.tsindex d71aeadc8b..90b7f97ef5 100644--- a/invokeai/frontend/webv2/src/features/video/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/video/core/graph.ts@@ -22,13 +22,7 @@ import { MINIMAX_H3_FPS } from './dimensions';import { MINIMAX_H3_HYBRID_BLOCK_RANGE, resolveVideoMode } from './settings';import { getVideoDimensions, getVideoModelPolicy, getVideoValidationReasons } from './videoPolicies';-/**- * Video graph compilation: one builder per model family, mirroring the shape- * of the bundled video workflow templates (which are the reference wiring for- * conditioning fan-out and metadata). Every graph exposes the same three fixed- * node ids so the submit pipeline can inject expanded prompts and batch seeds- * exactly as it does for image generation.- */+/** Mirror bundled template wiring per model family and expose fixed prompt/seed node IDs for submission batching. */export interface CompiledVideoGraph {backendGraph: BackendGraphContract;@@ -55,11 +49,8 @@ const MINIMAX_H3_GENERATION_MODES: Record<VideoGenerationMode, string> = {};/**- * Adds the per-reference descriptor nodes and the ordered collection feeding both the- * Reference Conditioning node and the Prompt node (the same references must reach both —- * the denoise node cross-checks them). Collect order matters: reference order is part of- * the request contract, so the collectors are CHAINED (each appends its item after the- * inherited collection), the same trick the extend scaffolding uses for its join order.+ * Feed identical ordered references to conditioning and prompt nodes; chain collectors to preserve the request's+ * rotary order.*/const addReferenceNodes = (graph: BackendGraphContract,@@ -97,8 +88,7 @@ const addReferenceNode = (type: 'minimax_h3_image_reference',});}- // Same estimate-overshoot protection as the extend path: tail-window bounds- // compile as negative indices the backend resolves against the REAL count.+ // Compile tail-window bounds relative to the actual backend frame count, as in extension graphs.const endFrame = toTailAwareIndex(reference.clip.endFrame, reference.clip.numFrames);return addNode(graph, {@@ -112,42 +102,8 @@ const addReferenceNode = (};/**- * A video reference's start bound, measured from the same end as its other bound.- *- * `toTailAwareIndex` sends a near-the-end bound out NEGATIVE, resolved against- * the clip's REAL frame count, and leaves anything further back POSITIVE, taken- * from the panel's ESTIMATE. Applied to each bound independently that splits a- * window across two index spaces: a window ENDING in the tail but starting- * further back emits a negative end beside a positive start, so the backend- * extracts `length + (real - estimate)` frames — or, when the window is short- * enough for the estimate error to swallow it, resolves the end BEFORE the- * start and fails the generation outright. (`[295,296]` of an estimated 300- * emits `295 / -4`; against a real 298 that is start 295, end 294.)- *- * So the two bounds are converted TOGETHER. Once the end has gone tail-relative- * the window is anchored to the real end anyway, and what is worth preserving- * is its LENGTH — which is also the budget the backend enforces by discarding- * the overrun from the window's end (see `deriveReferenceExtendClip`), so it- * has to survive an inexact estimate. The start rides the same anchor.- *- * Two cases stay absolute. A window far enough from the end leaves both bounds- * on the estimate already. And a start within `TAIL_INDEX_SLOP` of the clip's- * own beginning stays absolute because the relative form resolves to- * `startFrame + (real - estimate)`, which goes NEGATIVE once the estimate- * overshoots by more than `startFrame` — and `_ResolvedVideoRange` rejects an- * out-of-range START index outright rather than clamping, failing the whole- * generation. (Only the END bound is clamped there, pinning the sample length- * to the frames the clip can supply.) That can only arise when the window- * fills nearly the entire clip, where its length cannot be honoured anyway;- * below the slop the absolute form is always in range, and the drift it costs- * is the estimate error itself, a frame or two.- *- * DECIDED: the slop is not widened beyond 3. An estimate error past the slop- * can still fail the relative form, but only on a clip barely longer than the- * window (it needs `error > startFrame`), and `TAIL_INDEX_SLOP` is this file's- * declared bound on how wrong the estimate gets. A wider guard would not- * remove the cliff — it would move it, and pay for the move with silent length- * drift on every clip inside the wider margin.+ * Convert reference bounds together to preserve length near the tail. Keep starts within TAIL_INDEX_SLOP absolute+ * to avoid negative starts; larger estimate errors remain outside this guard.*/const toReferenceStartIndex = (clip: VideoSourceClip, endIndex: number): number => {if (endIndex >= 0 || clip.startFrame <= TAIL_INDEX_SLOP) {@@ -165,28 +121,9 @@ const addPromptAndSeedNodes = (graph: BackendGraphContract) => ({const toImageField = (image: { image_name: string }) => ({ image_name: image.image_name });-/**- * The extend-mode front end shared by both families, mirroring the bundled- * extend templates: trim the source clip, pull its last frame as the new- * clip's conditioning frame, and set up the concat that joins the trimmed- * source with the freshly generated clip (2-frame crossfade over the seam).- * Both intermediate video artifacts stay out of the gallery.- */-// The panel's frame count is an estimate (duration × fps; the records store-// no exact count, and VFR uploads can overshoot by a frame or two). A trim-// bound near the estimated ceiling therefore compiles as a NEGATIVE index —-// resolved by the backend against the clip's REAL count — so "keep to the-// end" can never land past it. Both bounds get the same treatment: a start-// in the tail window would otherwise stay a positive estimate-based index-// and land out of range exactly when the end's conversion saves it (the-// start is always below the end, so the pair keeps its order when both go-// negative). Mid-clip picks stay positive: a negative offset computed from-// an overshooting estimate would drift them instead.-/**- * How wrong the panel's `duration x fps` frame-count estimate is allowed to be.- * VFR containers overshoot it by a frame or two, so bounds within this many- * frames of the estimated end are emitted relative to the REAL end instead.- */+// Compile near-end trim bounds as negative indices against actual frame count; keep mid-clip bounds absolute to+// avoid estimate-induced drift.+/** Bound tolerated duration-times-fps overshoot; indices within this tail window resolve against the real end. */const TAIL_INDEX_SLOP = 3;const toTailAwareIndex = (frame: number, estimatedNumFrames: number): number => {@@ -195,11 +132,7 @@ const toTailAwareIndex = (frame: number, estimatedNumFrames: number): number =>return tailOffset <= TAIL_INDEX_SLOP ? -(tailOffset + 1) : frame;};-/**- * Trimmed source extraction + [source, new clip] crossfade join — the shared- * core of FL2VA/Wan extend and Ref2VA reference-extend. video_concat rebuilds- * the soundtrack from every input, so both clips' audio survives the join.- */+/** Extract source trim and crossfade source/new clips; video_concat reconstructs audio from both inputs. */const addSourceJoin = (graph: BackendGraphContract,sourceVideo: NonNullable<VideoSettings['sourceVideo']>,@@ -294,9 +227,7 @@ const addVideoMetadata = ({width,...(settings.firstFrameImage ? { first_frame_image: toImageField(settings.firstFrameImage) } : {}),...(settings.lastFrameImage ? { last_frame_image: toImageField(settings.lastFrameImage) } : {}),- // The trim bounds ride along as plain extras (core_metadata allows extra- // fields): without them, recall could only rebuild the clip with its- // default trim and the extension would start from the wrong frame.+ // Persist trim bounds as metadata extras so recall restores the actual extension cutpoint....(settings.sourceVideo? {source_video: { video_name: settings.sourceVideo.video_name },@@ -331,9 +262,8 @@ const buildWanVideoGraph = (settings: VideoSettings, model: MainModelConfig): Bathrow new Error('Video dimensions could not be derived from the current settings.');}- // A GGUF/checkpoint Wan main carries only the transformer; the VAE and- // UMT5-XXL encoder come from standalone models or a Diffusers component- // source. A Diffusers main bundles everything, including the second expert.+ // Standalone Wan checkpoints need external VAE/UMT5 components; Diffusers mains bundle them and the second+ // expert.const isSingleFileMain = model.format !== 'diffusers';const sourceModel = isSingleFileMain? getCompatibleDiffusersComponentSource(model, settings.componentSourceModel)@@ -350,9 +280,7 @@ const buildWanVideoGraph = (settings: VideoSettings, model: MainModelConfig): Bavae_model: settings.vae ?? undefined,wan_t5_encoder_model: settings.wanT5EncoderModel ?? undefined,});- // Wan LoRAs patch only the transformer; expert routing ('auto') reads each- // LoRA's probed high/low tag, which is how the Lightning pair lands on the- // right experts.+ // Wan LoRAs patch transformers; auto routing uses probed high/low tags to place accelerator pairs correctly.const activeLoras = getActiveCompatibleLoras(settings, model);const loraSource = activeLoras.length? addTransformerLoraCollectionLoader(graph, activeLoras, 'wan_lora_collection_loader', modelLoader, ['transformer'])@@ -383,8 +311,7 @@ const buildWanVideoGraph = (settings: VideoSettings, model: MainModelConfig): BaaddEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');addEdge(graph, seed, 'value', denoise, 'seed');- // The reference-image conditioning: the canvas and frame count must match- // the denoise exactly, so the same literals fan out to both nodes.+ // Share canvas/frame literals between reference conditioning and denoise to keep their shapes identical.const addRefEncoder = (inputs: Record<string, unknown>) => {const refEncoder = addNode(graph, {height: dimensions.height,@@ -415,8 +342,7 @@ const buildWanVideoGraph = (settings: VideoSettings, model: MainModelConfig): Bause_cache: false,});const { concat, extract, lastFrame } = addExtendScaffolding(graph, settings.sourceVideo, newClip);- // The extension inherits the source clip's frame rate, template-style, so- // the joined halves play at one speed.+ // Inherit source fps so the extension and original play at one speed.const fpsToInt = addNode(graph, { id: 'source_fps', method: 'Nearest', multiple: 1, type: 'float_to_int' });addEdge(graph, lastFrame, 'image', refEncoder, 'image');@@ -455,10 +381,7 @@ const buildWanVideoGraph = (settings: VideoSettings, model: MainModelConfig): Baconst metadata = addVideoMetadata({extras: {cfg_scale: settings.cfgScale,- // The delivered frame rate: the extension inherits the source clip's- // (rounded, mirroring the float_to_int node the graph wires), every- // other mode uses the panel's fps setting. Without this, fps would be- // the one user-settable Wan parameter recall could never restore.+ // Record delivered fps: rounded source rate for extension, panel fps otherwise.fps: extendParts && settings.sourceVideo ? Math.round(settings.sourceVideo.fps) : settings.fps,...(policy.ui.cfgLowNoiseVisible && settings.cfgScaleLowNoise !== null? { wan_guidance_scale_low_noise: settings.cfgScaleLowNoise }@@ -481,8 +404,7 @@ const buildWanVideoGraph = (settings: VideoSettings, model: MainModelConfig): Ba});if (extendParts) {- // The extracted conditioning frame is only known at run time; record it- // via an edge, like the bundled extend templates do.+ // Record runtime-extracted conditioning frames through an edge, matching bundled templates.addEdge(graph, extendParts.lastFrame, 'image', metadata, 'first_frame_image');}@@ -497,11 +419,8 @@ const buildMiniMaxH3VideoGraph = (settings: VideoSettings, model: MainModelConfithrow new Error('Video dimensions could not be derived from the current settings.');}- // A single-file H3 checkpoint carries only the transformer: the loader's- // main model is the Diffusers install from the Model Components slot, with- // the checkpoint riding the transformer-override input. A Diffusers main at- // top is the loader's main directly. Validation requires the slot for- // checkpoint mains, so the throw is a backstop for direct callers.+ // H3 checkpoints override the transformer of a required Diffusers component model; direct callers still need the+ // missing-slot guard.const isSingleFileMain = model.format !== 'diffusers';const componentSource = isSingleFileMain ? settings.componentSourceModel : null;@@ -509,11 +428,8 @@ const buildMiniMaxH3VideoGraph = (settings: VideoSettings, model: MainModelConfithrow new Error('A single-file MiniMax H3 transformer needs a Diffusers install selected under Model Components.');}- // The hybrid: the loader loads the FL2VA base, and the selected Ref2VA- // main rides the overlay node, which swaps its AdaLN projections in from- // the start block through the last and stamps the result a Ref2VA- // transformer. The policy only offers the slot on a Ref2VA checkpoint main;- // the guard keeps a stale value from silently loading the wrong file.+ // Hybrid loading overlays Ref2VA AdaLN blocks onto FL2VA; guard stale settings so unsupported mains cannot+ // silently load the wrong file.const hybridBase = isSingleFileMain && model.variant === 'ref2va' ? settings.h3HybridBaseModel : null;const graph: BackendGraphContract = { edges: [], id: createId('minimax_h3_video_graph'), nodes: {} };@@ -553,9 +469,7 @@ const buildMiniMaxH3VideoGraph = (settings: VideoSettings, model: MainModelConfi);}- // The canvas and the keyframes must match across text encoder, frame- // conditioning, and denoise — the same literals (and, in extend mode, the- // same extracted-frame edge) fan out to all of them.+ // Share canvas/keyframe inputs across text, frame conditioning, and denoise.const keyframeLiterals = {...(mode !== 'extend' && settings.firstFrameImage ? { first_image: toImageField(settings.firstFrameImage) } : {}),...(settings.lastFrameImage ? { last_image: toImageField(settings.lastFrameImage) } : {}),@@ -573,10 +487,7 @@ const buildMiniMaxH3VideoGraph = (settings: VideoSettings, model: MainModelConfiid: 'denoise_latents',// The node's frame counts are a string Literal choice list.num_frames: String(settings.numFrames),- // The H3 node counts sigma grid points (terminal zero included), so node- // steps = model evaluations + 1. The panel's steps setting means model- // evaluations — the count a distilled turbo LoRA is trained for — so add- // the terminal point here. Metadata records the panel value.+ // Add the terminal sigma point to panel model-evaluation steps; metadata retains the panel value.steps: settings.steps + 1,type: 'minimax_h3_denoise',width: dimensions.width,@@ -642,8 +553,7 @@ const buildMiniMaxH3VideoGraph = (settings: VideoSettings, model: MainModelConfiif (mode === 'extend' && settings.sourceVideo && frameConditioning) {const newClip = addLatentsToVideo('extension_clip', true);- // H3 generates at a fixed 24 fps, so the source is resampled to 24 up- // front (template behavior) and the concat inherits it from the first clip.+ // Resample source to H3's fixed 24 fps before concat inherits its rate.const { concat, lastFrame } = addExtendScaffolding(graph, settings.sourceVideo, newClip, { extractFps: 24 });addEdge(graph, lastFrame, 'image', posCond, 'first_image');@@ -651,9 +561,7 @@ const buildMiniMaxH3VideoGraph = (settings: VideoSettings, model: MainModelConfioutput = concat;extendParts = { lastFrame, newClip };} else if (mode === 'reference' && settings.sourceVideo) {- // Reference-extend: the new clip is appended to the trimmed Initial- // Video. Continuity comes from the references (typically the linked tail- // reference), not from frame conditioning, so no last frame is extracted.+ // Reference extension derives continuity from references, not extracted frame conditioning.const newClip = addLatentsToVideo('extension_clip', true);const { concat } = addSourceJoin(graph, settings.sourceVideo, newClip, { extractFps: 24 });@@ -703,8 +611,7 @@ const buildMiniMaxH3VideoGraph = (settings: VideoSettings, model: MainModelConfi});if (extendParts) {- // The extracted conditioning frame is only known at run time; record it- // via an edge, like the bundled extend templates do.+ // Record runtime-extracted conditioning frames through an edge, matching bundled templates.addEdge(graph, extendParts.lastFrame, 'image', metadata, 'first_frame_image');}diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.tsindex 7886a9ecc1..880d0083c0 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts@@ -95,8 +95,7 @@ describe('normalizeVideoSettings', () => {it('rejects non-records but heals partial records field-by-field, upscale-style', () => {expect(normalizeVideoSettings(null)).toBeNull();expect(normalizeVideoSettings(7)).toBeNull();- // A seeded partial write ("Send to Video" on a never-opened widget) keeps- // its payload instead of being nulled and wiped by the reconciler.+ // Preserve seeded partial Send to Video payloads through normalization and reconciliation.const seeded = normalizeVideoSettings({ firstFrameImage: FIRST_FRAME, sourceVideo: null });expect(seeded).not.toBeNull();@@ -194,8 +193,7 @@ describe('normalizeVideoSettings', () => {loras: [lightningLora],})).toBe(true);- // A recorded LoRA that is merely DISABLED also clears the flag: the graph- // skips disabled LoRAs, so the fast path would silently run without it.+ // Disabled accelerator LoRAs also clear intent because graph compilation omits them.const disabledLightning = { ...lightningLora, isEnabled: false };expect(@@ -255,8 +253,7 @@ describe('videoClipSpanSeconds', () => {});it('has no span to offer for a clip with no usable frame rate', () => {- // A persisted clip only has to hold a FINITE fps to hydrate, and a zero would put the- // whole clip behind a control that claims to play the selection.+ // Finite persisted fps can still be zero; playback must reject unusable rates.expect(videoClipSpanSeconds({ ...SOURCE_VIDEO, fps: 0 })).toBeNull();});});@@ -336,11 +333,7 @@ describe('getDefaultReferenceConditioning', () => {});describe('getDefaultReferenceClip', () => {- // A wrapped audio upload: the server renders it at AUDIO_WRAP_FPS (24), so- // DEFAULT_REFERENCE_SAMPLE_FRAMES lands at a little over 8 seconds of the track.- // Deliberately handed in with a narrow, offset window: were the helper to pass its clip- // through unchanged, the audio expectation below would still be satisfied by a fixture- // that already held the whole clip.+ // Use a narrow offset fixture so audio defaulting must actively expand to the whole wrapped soundtrack.const wrappedAudio = {endFrame: 199,fps: 24,@@ -373,8 +366,8 @@ describe('getDefaultReferenceClip', () => {});it('gives an audio-only reference the whole clip', () => {- // 3 minutes of audio, not the first 8 seconds of it: an audio reference is encoded as- // a soundtrack and no visual rows, and the window is what the generation gets to hear.+ // Audio references need the full soundtrack window; they add no visual rows and must not default to eight+ // seconds.expect(getDefaultReferenceClip(wrappedAudio, 'audio')).toEqual({...wrappedAudio,endFrame: 4319,@@ -465,9 +458,7 @@ describe('clearDeletedVideoMedia', () => {});it('clears a reference the exclusion masking would hide from a normalized snapshot', () => {- // A raw store can hold BOTH slots (a rollback race); normalization would- // mask the source video, so the sweep must run on the raw values or the- // masked reference dangles past the delete.+ // Sweep raw slots before normalization can hide conflicting media references from deletion.const rawBoth = { ...createSettings({ firstFrameImage: FIRST_FRAME }), sourceVideo: SOURCE_VIDEO } as Record<string,unknown@@ -484,9 +475,6 @@ describe('clearDeletedVideoMedia', () => {});});-// ----------------------------------------------------------------------------// Ref2VA references-const IMAGE_REFERENCE = {detail: 'max',image: { height: 512, image_name: 'ref.png', width: 512 },@@ -513,14 +501,11 @@ describe('references', () => {expect(normalized?.references).toEqual([IMAGE_REFERENCE]);expect(normalized?.firstFrameImage).toBeNull();- // References + source video is the Ref2VA reference-extend shape;- // validation rejects the pair on models that cannot consume it.+ // Source plus references is valid only for models supporting reference extension.expect(normalized?.sourceVideo).toEqual(SOURCE_VIDEO);});it('normalization drops malformed entries and enforces the caps, preserving order', () => {- // Videos over the cap drop the NEWEST non-anchor entries — the surplus is- // whatever arrived last. See the over-cap tests below.const tooMany = [...Array.from({ length: 4 }, (_, index) => ({...VIDEO_REFERENCE,@@ -553,9 +538,8 @@ describe('references', () => {expect(normalized?.references.map(named as never)).toEqual(['img', 'v0.mp4', 'v1.mp4', 'v2.mp4']);- // The race shape: an add slipped past the render-time cap gate while the- // Initial Video was placing its anchor. The surplus is the racing add (D),- // not the user's oldest reference (B) — a plain front-drop deleted B.+ // Discard the racing newest addition rather than the user's oldest reference when anchor insertion exceeds the+ // cap.const anchor = {...VIDEO_REFERENCE,clip: { ...VIDEO_REFERENCE.clip, video_name: 'anchor.mp4' },@@ -580,10 +564,7 @@ describe('references', () => {});it('normalization heals a panel saved with the anchor prepended', () => {- // The build before the anchor was pinned PREPENDED it, so those projects- // load with it at index 0. Normalization must move it last -- otherwise the- // generated frames continue from whatever reference follows it -- and it- // must do so BEFORE the cap trim, or the front-drop deletes the anchor.+ // Heal legacy prepended anchors by pinning last before overflow trimming.const anchor = {...VIDEO_REFERENCE,clip: { ...VIDEO_REFERENCE.clip, video_name: 'anchor.mp4' },@@ -658,8 +639,7 @@ describe('referencePromptLabels', () => {conditioning,});- // The numbering the model is handed (`build_ref2va_presentation`): one counter per- // modality, advanced in attachment order, so no label number is the card's position.+ // Mirror independent modality counters in backend attachment order; labels are not card positions.it('numbers each modality on its own counter', () => {expect(referencePromptLabels([@@ -690,8 +670,7 @@ describe('referencePromptLabels', () => {]));- // The same three references in two orders: the numbers follow the list, so the swap- // trades the two images' picture numbers and leaves the video's alone.+ // Reordering images updates picture numbering without changing the video's modality counter.expect(numbered([first, withConditioning('video_audio'), second])).toEqual({'first.png': { audio: null, picture: 1, video: null },'ref.mp4': { audio: 1, picture: null, video: 1 },@@ -738,10 +717,8 @@ describe('reference-extend anchor: audio-only references', () => {} as const;it('appends a real anchor beside an audio-only reference rather than consuming it', () => {- // Upload a soundtrack as a reference (it defaults to 'audio'), then extend that same- // clip. Adopting the audio entry would replace the user's window with the tail AND- // leave the seam with no visuals at all, since an 'audio' reference contributes no- // visual rows. Both references have a job; both survive.+ // Keep the user's audio reference and append a visual anchor; adopting audio would overwrite its trim and+ // provide no seam visuals.const linked = applyReferenceExtendSourceVideo([userAudio], source24, 3, FRAMES);expect(linked).toHaveLength(2);@@ -761,8 +738,7 @@ describe('reference-extend anchor: audio-only references', () => {} as const;const linked = applyReferenceExtendSourceVideo([userAudio, userVideo], source24, 3, FRAMES);- // The audio entry is untouched, by identity; the video one becomes the anchor and- // keeps its deliberate 'video' choice.+ // Preserve audio identity while the visual reference becomes the anchor.expect(linked).toHaveLength(2);expect(linked.find((entry) => entry === userAudio)).toBe(userAudio);expect(linked[linked.length - 1]).toMatchObject({@@ -773,9 +749,7 @@ describe('reference-extend anchor: audio-only references', () => {});it('converts an already-flagged audio anchor, re-deriving its window in the same pass', () => {- // A record written before this rule can carry one. It is healed WHOLE: the conditioning- // becomes usable and the window becomes the tail, which is why the conversion lives- // here and not in normalization.+ // Heal legacy anchors' conditioning and tail window together, outside normalization.const stale = {...userAudio,clip: { ...userAudio.clip, endFrame: 72, startFrame: 0 },@@ -791,9 +765,7 @@ describe('reference-extend anchor: audio-only references', () => {});it('converts an overridden audio anchor without disturbing the window the user picked', () => {- // Where the two rules meet. The ROLE still needs visual rows, so the conditioning is- // promoted — but the window is one the user chose FOR this anchor, not the arbitrary- // one a mis-flagged entry carries, so a cutpoint change leaves it intact.+ // Promote anchor conditioning to include visuals while preserving a deliberate trim override.const overridden = {...userAudio,clip: { ...userAudio.clip, endFrame: 219, startFrame: 100 },@@ -811,10 +783,7 @@ describe('reference-extend anchor: audio-only references', () => {});it('normalization never flags an audio-only reference as the anchor', () => {- // The recall re-derive picks the anchor by clip name. Landing on an audio-only entry- // would flag a reference whose window is NOT the tail -- once its conditioning implied- // visuals, the generation would continue from the opening of the clip. It is left as- // the plain reference it is, and no anchor is claimed.+ // Recall must not adopt audio-only same-name references as visual tail anchors.const normalized = normalizeVideoSettings(createSettings({ references: [IMAGE_REFERENCE, userAudio], sourceVideo: source24 }));@@ -840,9 +809,7 @@ describe('reference-extend anchor: audio-only references', () => {});it('leaves an audio-only reference beside a real anchor completely alone', () => {- // The rule is about the anchor's ROLE, not about audio references. With a flagged- // anchor present the re-derive does not run at all, and the user's soundtrack keeps- // its conditioning, its window and its object identity across normalization.+ // An existing anchor leaves unrelated audio conditioning, trim, and identity unchanged.const realAnchor = { ...userAudio, conditioning: 'video_audio' as const, fromSourceVideo: true } as const;const normalized = normalizeVideoSettings(createSettings({ references: [userAudio, realAnchor], sourceVideo: source24 })@@ -864,20 +831,15 @@ describe('reference-extend linkage', () => {it('anchors on video + audio -- the role needs visual rows', () => {const [ordinary] = applyReferenceExtendSourceVideo([], source24, 3, FRAMES);- // Deliberately NOT derived from whether the clip is a wrapped audio upload. The anchor- // is what the generated frames continue from, an 'audio' reference emits no visual rows- // at all, and the all-audio validation does not fire when other references are visual --- // so the seam would go silently discontinuous. `anchorReferenceConditioning` promotes in- // the other direction. (The clip carries no marker at all, so this cannot regress by- // accident.)+ // Anchors require visual conditioning regardless of upload origin; mixed references would otherwise bypass+ // all-audio validation with a broken seam.expect(ordinary).toMatchObject({ conditioning: 'video_audio', fromSourceVideo: true });});it('derives the tail trim: the window ending at the cutpoint, clamped at 0', () => {expect(deriveReferenceExtendClip(source24, FRAMES)).toMatchObject({ endFrame: 400, startFrame: 260 });- // Shorter than the tail window: fall back to the largest ON-GRID budget the- // clip supports (80 frames -> 73) so the window still ENDS on the cutpoint.- // Starting at 0 kept the same 73 frames but stopped 7 short of the seam.+ // Use the largest supported grid window ending at the cutpoint when the source is shorter than the target+ // tail.expect(deriveReferenceExtendClip({ ...SOURCE_VIDEO, fps: 24 }, FRAMES)).toMatchObject({endFrame: 79,startFrame: 7,@@ -885,9 +847,8 @@ describe('reference-extend linkage', () => {});it('budgets the window against the generated frame count', () => {- // `normalize_reference_video_frames` truncates a reference to the generated- // frame count keeping the FRONT, so a window longer than the generation- // loses its tail — the frames at the seam. It must never outrun the count.+ // Limit reference length to generated frames because backend truncation preserves the front and would discard+ // seam frames.expect(deriveReferenceExtendClip(source24, 124)).toMatchObject({ endFrame: 400, startFrame: 277 });expect(deriveReferenceExtendClip(source24, 90)).toMatchObject({ endFrame: 400, startFrame: 311 });// Above the tail window the budget stops binding: ~5s of lead-in is the cap.@@ -895,11 +856,8 @@ describe('reference-extend linkage', () => {});it('lands the window ON the 17n+5 grid the backend keeps, at every source rate', () => {- // The real test of the window: run it through ALL THREE backend rules.- // `resample_video_frame_repeats` onto 24 fps, `frames[:num_frames]`, then- // `snap_reference_num_frames` DOWN to 17n+5 — every one of which cuts the- // seam end. Rounding the fps conversion DOWN satisfied the first two and- // failed the third, losing 17 frames at 23.976 fps at every frame count.+ // Validate resampling, generated-length truncation, and 17n+5 snap-down together; floor rounding can lose a+ // full grid interval at fractional fps.const resample = (n: number, fps: number) => Math.floor((n * 24) / fps + 0.5);const snapDown = (n: number) => Math.max(1, Math.floor((n - 5) / 17)) * 17 + 5;@@ -915,11 +873,7 @@ describe('reference-extend linkage', () => {});it('a clip SHORTER than the window still ends its tail on the cutpoint', () => {- // The clamped branch used to take the whole clip, whose length is- // arbitrary: off the 17n+5 grid, so the snap-down cut the difference from- // the END. Nothing about it needs an inexact estimate — it was the common- // case for any source under ~5.9s at 24 fps, and the sweep above could not- // see it because it only runs a 402-frame clip.+ // Short clips also need grid-aligned budgets; arbitrary whole-clip windows lose their tail during snap-down.const resample = (n: number, fps: number) => Math.floor((n * 24) / fps + 0.5);const snapDown = (n: number) => Math.max(1, Math.floor((n - 5) / 17)) * 17 + 5;@@ -933,9 +887,7 @@ describe('reference-extend linkage', () => {const discarded = Math.min(resample(window, fps), numFrames) - kept;- // At most a single frame is trimmed off the seam end -- the source's- // own frame boundaries sometimes cannot land on the grid exactly (12- // fps cannot reach an odd 141 at all). The old clamp shed up to 16.+ // Allow at most one seam frame lost to source-rate granularity, not a whole grid interval.expect({ discarded: discarded <= 1, fps, numFrames, total }).toEqual({discarded: true,fps,@@ -953,16 +905,14 @@ describe('reference-extend linkage', () => {// 141 frames of 24 fps material is 94 frames of a 16 fps clip — the same// 5.875s of wall time, which is what the tail window actually means.expect(deriveReferenceExtendClip(longSource, FRAMES)).toMatchObject({ endFrame: 400, startFrame: 307 });- // A clip whose probe recorded no usable rate falls back to a no-op- // conversion rather than collapsing to the 2-frame floor.+ // Missing source rate must fall back without collapsing the sample to the two-frame floor.expect(deriveReferenceExtendClip({ ...longSource, fps: 0 }, FRAMES)).toMatchObject({ startFrame: 260 });expect(deriveReferenceExtendClip({ ...longSource, fps: -30 }, FRAMES)).toMatchObject({ startFrame: 260 });});it('appends a linked video+audio reference and re-derives it on cutpoint changes', () => {- // Appended, not prepended: request order is rotary order and the generated- // rows continue from the LAST reference block, so the continuity anchor- // has to be the final entry.+ // Append the continuity anchor last because generated rotary positions continue from the final reference+ // block.const added = applyReferenceExtendSourceVideo([IMAGE_REFERENCE], source24, 3, FRAMES);expect(added).toHaveLength(2);@@ -974,8 +924,6 @@ describe('reference-extend linkage', () => {kind: 'video',});- // The user tunes the conditioning, then moves the cutpoint: the trim- // re-derives, the position and conditioning survive.const tuned = added.map((entry, index) =>index === 1 && entry.kind === 'video' ? { ...entry, conditioning: 'video' as const } : entry);@@ -990,9 +938,7 @@ describe('reference-extend linkage', () => {});it('leaves an overridden anchor window alone across cutpoint and frame-count changes', () => {- // The fade-to-black case: the cutpoint keeps the fade in the Initial Video- // that gets concatenated, while the reference samples earlier material.- // Ref2VA has no frame-exact seam, so that choice is the user's to make.+ // Allow sampling before a fade while concatenating through it; Ref2VA provides no frame-exact seam.const linked = applyReferenceExtendSourceVideo([IMAGE_REFERENCE], source24, 3, FRAMES);const overridden = linked.map((entry, index) =>index === 1 && entry.kind === 'video'@@ -1044,11 +990,8 @@ describe('reference-extend linkage', () => {});it('normalization re-establishes the linkage recall drops, and the invariants reach it', () => {- // `fromSourceVideo` never reaches metadata, so a recalled reference-extend- // panel arrives with its anchor UNFLAGGED beside the source video. Every- // invariant keys on the flag, so before this: not pinned (the model- // continued from whatever followed it), and not re-budgeted (a Frames- // change left the window overrunning -- 2s cut off the seam at 345 -> 90).+ // Recall must restore the omitted anchor flag so pinning and generated-frame rebudgeting still protect the+ // seam.const recalled = { ...VIDEO_REFERENCE, clip: { ...VIDEO_REFERENCE.clip, video_name: 'long.mp4' } };const normalized = normalizeVideoSettings(createSettings({ references: [recalled, IMAGE_REFERENCE], sourceVideo: source24 })@@ -1088,11 +1031,7 @@ describe('reference-extend linkage', () => {});it('adopts the LAST same-name entry: the pin invariant records the anchor last', () => {- // Recorded metadata can hold a user's OWN reference to the source clip- // ahead of the anchor -- the pin forces the anchor last, so it is always- // the later same-name entry. A first-match flagged the user's reference:- // their trim got re-budgeted, the list reordered against the recording,- // and the true tail window sat unprotected at the seam.+ // Adopt the last same-name reference; the earlier one can be the user's independently trimmed reference.const userRef = {...VIDEO_REFERENCE,clip: { ...VIDEO_REFERENCE.clip, endFrame: 20, startFrame: 0, video_name: 'long.mp4' },@@ -1107,10 +1046,7 @@ describe('reference-extend linkage', () => {});it('canonicalizes the flag to at most one entry and keeps normalization stable', () => {- // Two flagged entries (a corrupt or hand-merged record) used to oscillate:- // the pin moves the FIRST flagged entry last, swapping the pair on every- // pass -- and the overflow trim exempts every flagged entry, so an- // over-cap list of them could never come back under the cap.+ // Canonicalize duplicate anchor flags to avoid normalization oscillation and unbounded exempt entries.const flaggedNamed = (video_name: string) => ({...VIDEO_REFERENCE,clip: { ...VIDEO_REFERENCE.clip, video_name },@@ -1125,8 +1061,6 @@ describe('reference-extend linkage', () => {expect(once?.references.at(-1)).toMatchObject({ clip: { video_name: 'b.mp4' }, fromSourceVideo: true });expect(twice?.references).toEqual(once?.references);- // All-flagged over the cap: the exemption can no longer make the surplus- // immortal -- the cap holds, and the surviving flag is the last one.const overCap = normalizeVideoSettings(createSettings({ references: ['a', 'b', 'c', 'd'].map((name) => flaggedNamed(`${name}.mp4`)) }));@@ -1139,18 +1073,13 @@ describe('reference-extend linkage', () => {});it('an absurd probed frame rate falls back to 24 instead of hanging', () => {- // Past ~2^53 source frames, tailSourceFrames' adjustment loops cannot even- // step (tail + 1 === tail in floats) -- fps 1e17 froze the tab. Any rate- // no real container produces now takes the same fallback as a broken one.+ // Reject unrealistic rates before floating-point increments stop advancing adjustment loops.expect(deriveReferenceExtendClip({ ...source24, fps: 1e17 }, 141)).toMatchObject({endFrame: 400,startFrame: 260,});- // Below the bound, a genuinely high-rate clip still gets its REAL window:- // 1200 fps needs 7025 source frames for 141 resampled ones. A 1000-fps- // bound sent this through the 24 fallback, and the backend -- which- // resamples at the rate it probes itself -- collapsed the 141-source-frame- // window to 3 frames and raised under text conditioning's 13-frame floor.+ // Retain legitimate high-rate timing; an overly low fallback bound can reduce resampled context below backend+ // minimums.const highRate = { ...source24, endFrame: 50000, fps: 1200, numFrames: 50001 };expect(deriveReferenceExtendClip(highRate, 141)).toMatchObject({ endFrame: 50000, startFrame: 42976 });@@ -1158,11 +1087,7 @@ describe('reference-extend linkage', () => {});it('a demoted anchor loses its override, so re-setting the clip re-derives', () => {- // The corrupt-record shape the flag canonicalization exists to heal: two- // flagged entries for the same clip. The demoted one kept `trimOverridden`,- // and adopt-by-name then honoured that stale window on the next Initial- // Video set -- the help text's "clear and re-set to get the default back"- // silently did nothing.+ // Clear override/sample intent when demoting duplicate anchors so later adoption can restore defaults.const overriddenNamed = (video_name: string) => ({...VIDEO_REFERENCE,clip: { ...VIDEO_REFERENCE.clip, endFrame: 60, startFrame: 40, video_name },@@ -1175,8 +1100,6 @@ describe('reference-extend linkage', () => {expect(healed?.references[0]).toMatchObject({ fromSourceVideo: false, trimOverridden: false });- // Setting that clip as the Initial Video adopts the demoted entry by name- // and must derive the default window, not resurrect the stale one.const adopted = applyReferenceExtendSourceVideo(healed!.references.slice(0, 1), source24, 3, FRAMES);expect(adopted[0]).toMatchObject({ clip: { endFrame: 400, startFrame: 260 }, fromSourceVideo: true });@@ -1194,9 +1117,8 @@ describe('reference-extend linkage', () => {});it('prefers the flagged entry over an earlier same-name reference on a source swap', () => {- // User: linked ref for clip A, plus their OWN hand-trimmed reference for- // clip B sitting above it. Swapping the Initial Video to clip B must- // update the FLAGGED entry — not rewrite the user's B reference.+ // Source replacement updates the flagged anchor without overwriting the user's separate reference to the new+ // clip.const linkedA = applyReferenceExtendSourceVideo([], source24, 3, FRAMES)[0];const handTrimmedB = {...VIDEO_REFERENCE,@@ -1238,9 +1160,7 @@ describe('reference-extend linkage', () => {});it('applyReferenceExtendNumFrames does not ratchet: the window re-widens', () => {- // The Frames number input emits a value per keystroke, unclamped, so typing- // "345" arrives as 3, then 34, then 345. A shrink-only rule would pin the- // window at the 3-frame budget for the rest of the session.+ // Rebudget in both directions because number-input keystrokes temporarily shrink frame counts.const linked = applyReferenceExtendSourceVideo([], source24, 3, 345);const typed = [3, 34, 345].reduce(applyReferenceExtendNumFrames, linked);@@ -1252,11 +1172,7 @@ describe('reference-extend linkage', () => {});it('an updater applied after a concurrent write keeps both changes', () => {- // The reference field hands `setReferences` an UPDATER because its add- // handlers await a gallery resolve before writing. Modelled here: the- // handler captures the list, the Initial Video field places the anchor- // during the await, then the resolve lands. A captured-array write would- // drop the anchor entirely; an updater over live state keeps both.+ // Apply async reference additions against live state so intervening source-anchor insertion survives.const captured: VideoReferenceItem[] = [];const add = (current: VideoReferenceItem[]): VideoReferenceItem[] => [...current, IMAGE_REFERENCE];@@ -1277,10 +1193,8 @@ describe('reference-extend linkage', () => {});it('pins the continuity anchor last, whatever the add or drag order', () => {- // Request order is rotary order: the generated frames continue from the- // LAST reference block. An image added after the Initial Video would- // otherwise take a rotary slot between the initial video's tail and the- // first generated frame.+ // Keep the source anchor last when adding images because generated rotary positions follow the last reference+ // block.const linked = applyReferenceExtendSourceVideo([], source24, 3, FRAMES);const anchor = linked[0]!;@@ -1375,9 +1289,7 @@ describe('reference sample window', () => {});it('moves an extend-anchor window off the cutpoint like any other', () => {- // Ref2VA has no frame-exact seam to hold, so the anchor's end is the- // user's to move -- a clip that fades to black at the cutpoint wants the- // fade concatenated but not conditioned on.+ // Allow anchor windows away from the cutpoint; Ref2VA has no frame-exact seam to preserve.const next = slideReferenceSampleWindow(clip(180, 298), 100);expect([next.startFrame, next.endFrame]).toEqual([100, 218]);});@@ -1398,10 +1310,8 @@ describe('reference sample window', () => {});it('a drag past the clip end comes back with its length intact', () => {- // A slider commits a value per pointer step, so the round trip is the- // test: without the recorded request each step would take its length from- // the already-clamped window it was handed, and one overshoot-and-back- // would leave a 200-frame sample at 1 frame.+ // Preserve requested sample length through overshoot-and-return slider updates rather than repeatedly+ // shrinking the effective window.let reference: Extract<VideoReferenceItem, { kind: 'video' }> = {clip: clip(0, 199),conditioning: 'video_audio',diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.tsindex b050e1ca23..7776aa96ae 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts@@ -39,12 +39,7 @@ const hasFiniteNumber = (record: Record<string, unknown>, key: string): booleanconst getClampedNumber = (record: Record<string, unknown>, key: string, min: number, max: number, fallback: number) =>hasFiniteNumber(record, key) ? Math.min(Math.max(record[key] as number, min), max) : fallback;-/**- * The MiniMax H3 hybrid's block range: the released transformers have 50 DiT- * blocks (0-49). The default start hands the upper half's AdaLN projections- * to Ref2VA — the reference implementation's recommended quality/adherence- * balance; blocks from the start through 49 are always overlaid.- */+/** H3 has blocks 0–49; overlay Ref2VA AdaLN from the chosen start through 49, defaulting to the upper half. */export const MINIMAX_H3_HYBRID_BLOCK_RANGE = { defaultStart: 25, max: 49, min: 0 } as const;export const VIDEO_ASPECT_RATIO_IDS: readonly VideoAspectRatioId[] = [@@ -91,10 +86,8 @@ export const VIDEO_REFERENCE_MAX_VIDEOS = 3;export const VIDEO_REFERENCE_MAX_IMAGES = 9;/**- * Default sample length (in frames) for a newly added video reference. Reference rows cost- * VRAM in every denoise step — the packed sequence grows with reference length — so the- * useful sample is a short window that captures the wanted visual/audio features, not the- * whole clip. 200 frames ≈ 8s at the models' native 24 fps.+ * Default to a short reference sample to limit rows attended at every denoise step; 200 frames is about eight+ * seconds at 24 fps.*/export const DEFAULT_REFERENCE_SAMPLE_FRAMES = 200;@@ -103,14 +96,8 @@ export const clampReferenceSampleFrames = (clip: VideoSourceClip, rawSampleFrameMath.min(Math.max(1, Math.round(rawSampleFrames)), Math.max(0, clip.numFrames - 1) + 1);/**- * The sample length a reference is asking for: its recorded intent, else its own window.- *- * The intent is what makes the two controls independent under a DRAG. A slider emits a- * value per pointer step, and each one is committed, so a window that took its length- * from the state it was handed would shrink at the clip's end and stay short on the way- * back — one overshoot and back would leave a 200-frame sample at 1 frame. The requested- * length is therefore carried on the reference (`sampleFrames`) and only the EFFECTIVE- * window is clamped.+ * Retain requested sampleFrames separately from clamped bounds so dragging past the end and back restores sample+ * length.*/export const referenceSampleFrames = (reference: Extract<VideoReferenceItem, { kind: 'video' }>): number =>clampReferenceSampleFrames(@@ -119,23 +106,8 @@ export const referenceSampleFrames = (reference: Extract<VideoReferenceItem, { k);/**- * Move a reference clip's sample window to a new start frame.- *- * The two controls are independent: the start frame reaches every frame of the clip, and- * the sample length is what gives way — the window keeps the requested length while there- * is clip left to fill it and is pinned to the remaining frames past that, so- * `start + length` never runs beyond the last frame. (The length slider's ceiling in the- * panel is the same `numFrames - startFrame`, so the control tracks what the window can- * actually hold.) Pass `requestedSampleFrames` — `referenceSampleFrames` of the reference- * BEFORE the drag — to keep a clamped window recoverable; it defaults to the window's own- * length, which is the identity only while the window still fits.- *- * Every video reference trims this way, the reference-extend anchor included: Ref2VA has- * no frame-exact seam to protect (see deriveReferenceExtendClip), so the anchor's window- * is a default the user may move off the cutpoint like any other.- *- * Self-healing by construction: the returned window always satisfies- * 0 <= start <= end <= numFrames - 1, even from a corrupt persisted trim.+ * Clamp effective bounds to 0 <= start <= end < numFrames while preserving requested sample length across drags.+ * Anchors use the same movable window policy.*/export const slideReferenceSampleWindow = (clip: VideoSourceClip,@@ -150,11 +122,8 @@ export const slideReferenceSampleWindow = (};/**- * Resize a reference clip's sample window to a new length in frames.- *- * The window grows forward from its start frame, with the end clamped to the clip. Same- * self-healing bounds as slideReferenceSampleWindow. The caller records the requested- * length on the reference as `sampleFrames`; this returns only the window it produces.+ * Grow from the current start and clamp to the clip; callers persist requested sampleFrames separately from+ * effective bounds.*/export const resizeReferenceSampleWindow = (clip: VideoSourceClip, rawSampleFrames: number): VideoSourceClip => {const maxFrame = Math.max(0, clip.numFrames - 1);@@ -167,11 +136,8 @@ export const resizeReferenceSampleWindow = (clip: VideoSourceClip, rawSampleFramconst VIDEO_REFERENCE_CONDITIONINGS = ['video_audio', 'video', 'audio'] as const;/**- * Whether a value is one of the three conditionings a video reference can carry.- *- * Exported for recall, which must tell "the run recorded this" from "the run recorded- * nothing usable" -- the two take different branches, and enumerating the literals at the- * call site is how one of them gets forgotten.+ * Share conditioning recognition with recall so valid recorded choices remain distinct from missing or unusable+ * values.*/export const isVideoReferenceConditioning = (value: unknown): value is VideoReferenceConditioning =>VIDEO_REFERENCE_CONDITIONINGS.includes(value as (typeof VIDEO_REFERENCE_CONDITIONINGS)[number]);@@ -197,19 +163,8 @@ export const isVideoReferenceItem = (value: unknown): value is VideoReferenceIte};/**- * Drops invalid entries and enforces the per-kind caps, preserving order.- *- * An over-cap list should never reach here — the add paths re-check the cap- * against the live list at apply time and the Initial Video field disables- * itself when the video slots are full — so this is the guard for a stale or- * hand-edited project record.- *- * Video overflow drops the NEWEST non-anchor entries: the surplus is whatever- * arrived last, and a plain front-drop deleted the user's OLDEST reference- * whenever a racing add slipped past the cap. The anchor is exempt whatever- * its position — request order is rotary order and the generated frames- * continue from the LAST block, so it is the one entry the extension depends- * on. Images carry no ordering role and keep the front.+ * Drop invalid/over-cap entries while preserving order. Keep the anchor and oldest video references; discard+ * newest non-anchor overflow. Images retain the front.*/const sanitizeVideoReferences = (value: unknown, sourceVideoName?: string): VideoReferenceItem[] => {if (!Array.isArray(value)) {@@ -217,13 +172,7 @@ const sanitizeVideoReferences = (value: unknown, sourceVideoName?: string): Vide}let valid = value.filter((entry) => isVideoReferenceItem(entry));- // Canonicalize the flag to AT MOST ONE entry, keeping the LAST. Only a- // corrupt or hand-merged record carries two, but two is a poisoned state:- // the pin moves the FIRST flagged entry last, so normalization oscillates- // between the pair on alternate passes, and the overflow trim below exempts- // every flagged entry, so an over-cap list of them could never be brought- // under the cap again. The last one matches the pin invariant every healthy- // record was written under.+ // Keep only the last anchor flag to prevent pinning oscillation and multiple cap-exempt entries.let flagged = -1;for (let index = valid.length - 1; index >= 0; index -= 1) {const entry = valid[index]!;@@ -235,31 +184,14 @@ const sanitizeVideoReferences = (value: unknown, sourceVideoName?: string): Vide}valid = valid.map((entry, index) =>index !== flagged && entry.kind === 'video' && entry.fromSourceVideo === true- ? // `trimOverridden` goes with the flag: it only ever means "this ANCHOR's window- // is the user's". Left behind on a demoted entry it would be honoured again the- // next time adopt-by-name picked that entry up as the anchor, and the clip's- // default window would never be derived. The recorded sample length goes with- // it — a request kept beside a window it did not produce would spring the window- // back to it on the next drag.+ ? // Clear trimOverridden and sample intent with a demoted anchor flag so future adoption can derive a coherent+ // default window.{ ...entry, fromSourceVideo: false, sampleFrames: undefined, trimOverridden: false }: entry);- // Re-establish the linkage recall drops. `fromSourceVideo` is panel state- // and never reaches metadata, so a recalled panel arrives with its anchor- // UNFLAGGED beside the source video -- and every invariant keyed on the flag- // (the pin, the frame-count re-budget, the seam-anchored start index)- // silently lapses: a Frames change left the recalled window unbudgeted and- // the backend cut 2s off the seam. The flag is derivable, not just- // storable: the video reference naming the Initial Video's clip IS the- // anchor. An already-flagged entry stays authoritative.- //- // Adopt the LAST same-name entry, not the first. The pin invariant means- // the anchor is always recorded last, and recorded metadata can hold a- // user's OWN reference to the same clip ahead of it -- a first-match- // flagged that one instead: the user's trim got re-budgeted, the list- // reordered against the recording, and the true tail window was left- // unprotected at the seam.+ // Restore omitted recall flags from the last visual same-name reference, preserving earlier user references; an+ // existing flag remains authoritative.if (flagged === -1 && sourceVideoName !== undefined) {for (let index = valid.length - 1; index >= 0; index -= 1) {const entry = valid[index]!;@@ -273,12 +205,7 @@ const sanitizeVideoReferences = (value: unknown, sourceVideoName?: string): Vide}}- // Pin BEFORE the cap trim. The front-drop below assumes the anchor is last,- // but a project saved by the build that PREPENDED it loads with the anchor- // first -- so without this the overflow rule deletes the one entry it exists- // to protect. Pinning here also heals those panels on load: normalization- // runs on every read, whereas `setReferences` only fires once the user- // touches the reference list.+ // Pin before trimming overflow so older records with prepended anchors cannot lose their continuity reference.valid = pinReferenceExtendAnchor(valid);// Keyed by INDEX, not object identity: a hand-edited record can alias the@@ -326,13 +253,8 @@ const areAcceleratorLorasPresent = (keys: readonly string[], loras: readonly Genkeys.length > 0 && keys.every((key) => loras.some((lora) => lora.model.key === key && lora.isEnabled));/**- * Which inputs are filled decides the mode; there is no mode selector. A first- * frame and a source video never coexist (normalization and the setters both- * enforce it), and a last frame refines whichever mode its partner implies:- * with a first frame it becomes FLF2V interpolation, with a source video it is- * the destination the extension should land on. References always win: with a- * source video alongside them (Ref2VA reference-extend) the mode stays- * `reference` and the graph appends the new clip to the source.+ * Inputs determine mode. First frame/source are exclusive; references win and may coexist with source video for+ * reference extension.*/export const resolveVideoMode = (settings: Pick<VideoSettings, 'firstFrameImage' | 'lastFrameImage' | 'sourceVideo' | 'references'>@@ -352,20 +274,15 @@ export const resolveVideoMode = (return settings.lastFrameImage ? 'last-frame' : 'txt2vid';};-/**- * The fields of `VideoSettings` that describe how the panel is arranged rather- * than what will be generated. Mirrors `GENERATE_UI_STATE_KEYS`.- */+/** Panel arrangement fields are UI state rather than generation parameters. */export const VIDEO_UI_STATE_KEYS = {batchCount: true,negativePromptHeightPx: true,positivePromptHeightPx: true,} satisfies Partial<Record<keyof VideoSettings, true>>;-// Model-agnostic fallbacks for healing partial records. They intentionally-// mirror the Wan fallback in the capability matrix, which cannot be imported-// here (videoPolicies imports this module); when a model is known, the-// selection transition re-snaps them to its family anyway.+// Use model-agnostic Wan fallbacks to avoid a policy import cycle; model selection subsequently snaps to family+// constraints.const SETTINGS_FALLBACKS = {aspectRatioId: '16:9',cfgScale: 5,@@ -376,20 +293,15 @@ const SETTINGS_FALLBACKS = {} as const;/**- * Heals older/partial persisted values without silently clamping invalid user- * input, upscale-style: any record normalizes field-by-field (so a seeded- * partial write — e.g. "Send to Video" landing on a never-opened widget —- * keeps its payload), while range problems stay validation reasons.+ * Normalize partial records field by field without clamping invalid user values; preserve seeded payloads and+ * report range errors through validation.*/export const normalizeVideoSettings = (values: unknown): VideoSettings | null => {if (!isRecord(values)) {return null;}- // References are mutually exclusive with the frame slots; when a stale- // record somehow holds both, the references win deterministically. A source- // video COEXISTS with references (Ref2VA reference-extend) — validation- // rejects the pair on models that cannot consume it.+ // References override stale frame slots; source video may coexist, with model support enforced by validation.const references = sanitizeVideoReferences(values.references,isVideoSourceClip(values.sourceVideo) ? values.sourceVideo.video_name : undefined@@ -401,9 +313,7 @@ export const normalizeVideoSettings = (values: unknown): VideoSettings | null =>const sourceVideo = !firstFrameImage && isVideoSourceClip(values.sourceVideo) ? values.sourceVideo : null;const loras = Array.isArray(values.loras) ? values.loras.filter(isVideoLora) : [];const acceleratorLoraKeys = getStringArray(values.acceleratorLoraKeys);- // The flag means "the accelerator LoRAs the toggle added are active": if any- // of them is gone (deleted from Concepts, dropped as incompatible), the flag- // clears rather than claiming a fast path that has nothing behind it.+ // Clear acceleration when any required accelerator LoRA disappears instead of claiming an inactive fast path.const acceleratorEnabled =values.acceleratorEnabled === true && areAcceleratorLorasPresent(acceleratorLoraKeys, loras);@@ -565,12 +475,8 @@ export const cloneVideoWidgetValues = (values: VideoWidgetValues): VideoWidgetVaexport const VIDEO_SOURCE_FALLBACK_FPS = 16;/**- * Builds the panel's source-clip record from a gallery video. The frame count- * is an estimate (duration × fps — the records store no exact count); the- * backend's extract_video_range resolves authoritative indices at run time.- * The default trim keeps everything but the final frame (the bundled extend- * templates' `end_frame: -2`): the extension starts on the trimmed clip's last- * frame, so keeping the very last one would duplicate it across the seam.+ * Estimate frames from duration/fps; backend extraction resolves exact indices. Default trim omits the final frame+ * to avoid duplicating it at the extension seam.*/export const createVideoSourceClip = (item: {durationSeconds: number;@@ -595,77 +501,30 @@ export const createVideoSourceClip = (item: {};/**- * The conditioning a video reference starts on when it is added from the gallery or an- * upload.- *- * NOT used for the reference-extend anchor: that role requires visual rows, so it takes- * `video_audio` regardless of the clip and promotes an adopted audio-only entry via- * {@link anchorReferenceConditioning}.- *- * Audio uploads are stored as videos: the server wraps an uploaded audio file into a- * rendered-waveform clip at ingest and marks it `audio_upload`. Those frames are a picture- * of the sound rather than footage anyone means to condition on — and conditioning on them- * is not free, it costs a video reference slot and roughly doubles the packed sequence — so- * such a reference defaults to its soundtrack alone. Everything else keeps video + audio.- * This is only the starting value — the card's selector still offers all three.- *- * Takes the marker rather than a metadata bag: it rides on the gallery item and on- * `VideoSourceClip`, so no caller needs a second request to decide this.+ * Audio uploads default to soundtrack-only conditioning. Extension anchors require visual conditioning and use+ * anchorReferenceConditioning instead. Read mediaOrigin from the gallery item; it is not persisted on+ * VideoSourceClip.*/export const getDefaultReferenceConditioning = (mediaOrigin: string | null | undefined): VideoReferenceConditioning =>mediaOrigin === 'audio_upload' ? 'audio' : 'video_audio';/**- * Whether a video reference can serve as the reference-extend ANCHOR.- *- * The anchor carries the tail of the Initial Video across the seam, and that is what the- * generated frames continue from. An 'audio' reference contributes soundtrack rows and no- * visual rows at all — the backend decodes a reference's frames only when its packed kind- * is `video` (`reference_kind`) — so it has nothing to offer the seam. Nor does it fail- * loudly: the all-audio validation reason needs EVERY reference to be audio-only, so one- * image reference alongside is enough to let a silently discontinuous seam queue.- *- * So an audio-only reference is never CHOSEN as the anchor. Adoption and the recall- * re-derive both skip it, and the anchor is appended fresh instead — which keeps the- * soundtrack the user actually asked for rather than overwriting it with a role it cannot- * fill. Only an entry already claiming the flag is converted, by- * {@link anchorReferenceConditioning}.+ * Audio-only references cannot anchor visual continuity. Preserve them as user references and select or append a+ * visual anchor instead.*/const canAnchorReferenceExtend = (entry: VideoReferenceItem): boolean =>entry.kind === 'video' && entry.conditioning !== 'audio';/**- * The conditioning an entry keeps once it IS the reference-extend anchor.- *- * Only reached for an entry already carrying the flag: a record written before- * {@link canAnchorReferenceExtend} existed, or a hand-edited one. Promoting keeps the- * soundtrack the choice asked for and restores the visuals the role requires; 'video' and- * 'video_audio' are the user's own answer and pass through.- *- * Deliberately applied only in `applyReferenceExtendSourceVideo`, where the window is- * either re-derived alongside it or is one the user picked for THIS anchor- * (`trimOverridden`). Promoting in normalization instead would turn an entry that was- * merely inert into one emitting visual rows from whatever window it happens to hold —- * for a mis-flagged entry, the opening of the clip rather than the tail, which is a worse- * seam than no anchor at all.+ * Promote flagged audio anchors only while deriving their tail window or preserving an explicit override;+ * normalization alone could activate unrelated opening frames.*/export const anchorReferenceConditioning = (conditioning: VideoReferenceConditioning): VideoReferenceConditioning =>conditioning === 'audio' ? 'video_audio' : conditioning;/**- * The structured-prompt labels one reference answers to, or `null` where it has none.- *- * Ref2VA presents every reference to the model under a per-MODALITY label numbered in- * attachment order — `<Picture i>` for an image, `<Video k>` for conditioned footage,- * `<Audio j>` for a soundtrack — and the prompt refers to references only by those labels.- * The three counters run independently, so a reference's label numbers are not its position- * in the list: the second card can be `<Picture 1>`, and a video contributing both streams- * claims one number from each of two counters.- *- * Mirrors the backend's `build_ref2va_presentation` numbering (audio on 'video_audio' and- * 'audio', a `<Video k>` on everything else video-kind), which is the numbering the model- * actually sees. The two must not drift: a label shown here that the prompt cannot address- * is worse than no label at all.+ * Mirror build_ref2va_presentation with independent Picture, Video, and Audio counters in attachment order;+ * video_audio advances both relevant counters.*/export type VideoReferencePromptLabels = {audio: number | null;@@ -674,11 +533,8 @@ export type VideoReferencePromptLabels = {};/**- * The labels, spelled the way the prompt must spell them.- *- * Never translated and never reformatted: these are tokens the text encoder matches- * literally, so what the badge shows is exactly what the user types into the prompt. The- * visual track leads a reference that carries both, since that is what the card depicts.+ * Display encoder tokens literally, untranslated, with visual labels first for references carrying both+ * modalities.*/export const formatReferencePromptLabels = (labels: VideoReferencePromptLabels): string[] => {const formatted: string[] = [];@@ -722,22 +578,8 @@ export const referencePromptLabels = (references: readonly VideoReferenceItem[])};/**- * The sample window a newly added video reference starts on.- *- * Footage starts on {@link DEFAULT_REFERENCE_SAMPLE_FRAMES} from the clip's head, because- * every reference frame is VAE-encoded into rows the denoiser re-attends at every step.- *- * An AUDIO-ONLY reference starts on the whole clip. It pays none of that cost: the backend- * decodes a reference's frames only when its packed kind is `video` (`reference_kind`), so- * an 'audio' reference contributes soundtrack rows and no visual rows at all — and those- * rows are bounded by the GENERATED duration, not by how long the window is. What the- * window decides is which audio the model hears: the track is sliced to the window and only- * THEN truncated to the generated duration, so a window shorter than the generation cuts- * the soundtrack off early. At 8s that is every frame count above 200 — over half of the- * ones the panel offers.- *- * Only the starting value — the card's sample-length control still trims either kind, and- * changing a card's conditioning afterwards leaves the window the user can see alone.+ * Default footage to a bounded head sample. Audio-only references use the whole clip because soundtrack rows are+ * generation-bounded and short windows cut audio early.*/export const getDefaultReferenceClip = (clip: VideoSourceClip,@@ -752,17 +594,8 @@ export const getDefaultReferenceClip = (});/**- * The detail a newly added image reference starts on.- *- * The FIRST image reference keeps upstream's rule, a 2048px short edge: it is usually the- * subject the generation is about, and that is where the extra detail earns its cost.- * Later ones match the generation size instead. Reference rows are re-attended at every- * denoising step and attention is quadratic in the sequence, so a second and third 2048px- * reference are what turn a modest surcharge into a doubling — while the marginal value of- * conditioning a supporting reference at seven times the output's pixel density is small.- *- * Only the starting value: every card's selector still offers both, and the card shows the- * size and row count each choice produces.+ * Default the first image to max detail and later images to generation-matched detail to limit repeatedly attended+ * reference rows; users may override each.*/export const getDefaultReferenceImageDetail = (references: VideoReferenceItem[]): VideoReferenceImageDetail =>references.some((entry) => entry.kind === 'image') ? 'match' : 'max';@@ -770,59 +603,21 @@ export const getDefaultReferenceImageDetail = (references: VideoReferenceItem[])/** The minimum frames a trim must keep — video_concat's crossfade consumes a 2-frame tail. */export const MIN_VIDEO_TRIM_FRAMES = 2;-/**- * The trim as playable seconds, for previewing the window a clip actually selects.- *- * The bounds are INCLUSIVE frame indices, so the window runs to the far edge of- * `endFrame`'s display interval rather than to its start — playing to `endFrame / fps`- * would cut the last selected frame. Null when the record carries no usable frame rate:- * a persisted clip only has to hold a finite `fps` to hydrate, and a zero would put the- * whole clip's length behind a play button that claims to play the selection.- */+/** Inclusive trim ends at (endFrame + 1)/fps to retain its final frame; return null for unusable rates. */export const videoClipSpanSeconds = (clip: VideoSourceClip): { endSeconds: number; startSeconds: number } | null =>Number.isFinite(clip.fps) && clip.fps > 0? { endSeconds: (clip.endFrame + 1) / clip.fps, startSeconds: clip.startFrame / clip.fps }: null;/**- * The MAXIMUM lead-in the reference-extend tail reference samples ahead of the- * cutpoint, expressed at 24 fps: ~5s, and exactly on the 17n+5 frame grid- * (17*8+5) so the backend's 24 fps resample + snap-down keeps all of it.- *- * The window is a DURATION — `deriveReferenceExtendClip` scales it to the- * source clip's own frame rate, so a 16 fps source samples 94 frames of the- * same ~5.9 s rather than 141 frames of ~8.8 s. It is also a CEILING, not a- * fixed size: the generated frame count is the other bound, and the smaller of- * the two wins.+ * Cap tail context at 141 frames of 24-fps material, about 5.9 seconds, further bounded by generated length and+ * converted to source rate.*/export const VIDEO_REFERENCE_EXTEND_TAIL_FRAMES = 141;/**- * The tail reference's DEFAULT trim: the frames right before the cutpoint,- * sized so the backend keeps ALL of them.- *- * A default, not a constraint. Ref2VA conditions on reference CONTENT — there- * is no frame-exact seam here the way FL2VA extend has one — so which frames- * the anchor samples is an editorial choice, and the cutpoint is only the- * likeliest one. A clip that fades to black at the cutpoint wants the fade- * concatenated and NOT conditioned on, so the user can move the window off the- * cutpoint (`trimOverridden`) and the panel then leaves it alone.- *- * Three backend rules bound the window, and every one of them discards from- * the END of it — where this default puts the frames nearest the cutpoint.- * `normalize_reference_video_frames` resamples onto H3's fixed- * 24 fps and truncates to the GENERATED frame count keeping the FRONT- * (`frames[:num_frames]`); `encode_reference_video` then snaps what survives- * DOWN to the `17n + 5` grid the video VAE encodes without padding.- *- * The budget is therefore `min(TAIL, numFrames)` frames of 24 fps material,- * and both of those sit ON that grid already (141 = 17*8+5; every frame choice- * is 90 + 17i). The conversion into the source clip's own frame space rounds- * UP: overshooting is free, because the truncation cuts the window back to- * exactly `numFrames` and the snap then keeps it whole, while undershooting- * lands OFF the grid and the snap eats up to 16 frames at the seam. Rounding- * down looks safer and is not — it cost 17 frames at 23.976 fps (NTSC film) at- * every frame count on offer, and 17 at 16 fps at the 124-frame default.+ * Default to grid-aligned tail context ending at the cutpoint. Account for resampling, generated-length+ * truncation, and 17n+5 snap-down; user trim overrides remain editorial choices.*/export const deriveReferenceExtendClip = (sourceVideo: VideoSourceClip, numFrames: number): VideoSourceClip => ({...sourceVideo,@@ -834,13 +629,8 @@ export const deriveReferenceExtendClip = (sourceVideo: VideoSourceClip, numFrame});/**- * The highest source frame rate the tail-window math accepts as real; see the- * fps guard below. The float plateau it guards (`tail + 1 === tail`) starts- * around fps 1.5e15, so 1e6 keeps nine orders of margin — a tighter bound of- * 1000 turned real high-rate containers (probe-reported 1200 fps decoded fine- * before) into backend hard failures: the 24 fps fallback sized a 141-SOURCE-- * frame window that the backend, resampling at the rate it probes itself,- * collapsed to 3 frames, under text conditioning's 13-frame minimum.+ * Allow real high-rate containers while bounding fps far below floating-point plateaus that would stop adjustment+ * loops advancing.*/const MAX_REFERENCE_SOURCE_FPS = 1e6;@@ -853,27 +643,14 @@ const resampledFrameCount = (sourceFrames: number, fps: number): number =>/** The tail window's start index — see `deriveReferenceExtendClip`. */const referenceExtendStartFrame = (clip: VideoSourceClip, numFrames: number): number => {- // A clip whose probe recorded no usable rate: the backend resamples at the- // rate it probes, so 24 — a no-op conversion — is the only safe assumption.- // A zero or negative rate would otherwise collapse the window to the 2-frame- // floor, which is below the 13 frames text conditioning needs. The upper- // bound is a hang guard: past ~2^53 source frames, `tailSourceFrames`'- // adjustment loops cannot even step (`tail + 1 === tail` in floats) and spin- // forever on the main thread — a hand-edited record with fps 1e17 froze the- // tab on the first Frames keystroke.+ // Use 24 fps for unusable rates; bound extreme rates to prevent nonadvancing floating-point adjustment loops.const fps =Number.isFinite(clip.fps) && clip.fps > 0 && clip.fps <= MAX_REFERENCE_SOURCE_FPS ? clip.fps : MINIMAX_H3_FPS;const requested = Number.isFinite(numFrames)? Math.min(VIDEO_REFERENCE_EXTEND_TAIL_FRAMES, Math.trunc(numFrames)): VIDEO_REFERENCE_EXTEND_TAIL_FRAMES;- // A clip shorter than the window cannot supply the whole budget, and simply- // taking what is there leaves the window OFF the 17n+5 grid — so the- // snap-down cuts the difference from the END, the frames at the cutpoint.- // (24 fps, a 120-frame clip, numFrames 345: a [0,118] window keeps 107 of- // its 119 frames and stops half a second short of the seam.) Falling back to- // the largest on-grid budget the clip DOES support keeps the same frames and- // lands them on the seam. Both bounds are already on the grid in the normal- // case, so this is an identity there.+ // For short clips choose the largest available on-grid budget ending at the cutpoint so snap-down cannot discard+ // seam context.const budget = Math.min(requested,snapReferenceFrames(Math.min(resampledFrameCount(clip.endFrame + 1, fps), requested))@@ -883,20 +660,8 @@ const referenceExtendStartFrame = (clip: VideoSourceClip, numFrames: number): nu};/**- * The fewest source frames that still resample to at least `budget` frames.- *- * `floor(t * 24/fps + 0.5) >= budget` is, for an integer budget, exactly- * `t >= (budget - 0.5) * fps / 24` — so the smallest such `t` has a closed- * form. The two bounded loops absorb the last-ulp disagreements between that- * expression and `resampledFrameCount`'s association of the same arithmetic;- * each runs at most a step or two. (An earlier version walked down from- * `ceil(budget * fps / 24)` instead, which is `~fps / 24` iterations — 124 ms- * per Frames keystroke at an absurd-but-probeable rate.)- *- * Landing short is what matters: the resample is a step function, and every- * frame past the budget is discarded from the END — the seam. The minimum- * lands on the budget exactly wherever the source's frame boundaries allow,- * and within a frame where they cannot (12 fps cannot hit an odd 141 at all).+ * Solve minimum source length from t >= (budget - 0.5)*fps/24, then correct rounding by a bounded few steps. Avoid+ * rate-proportional loops and minimize seam truncation.*/const tailSourceFrames = (budget: number, fps: number): number => {let tail = Math.max(MIN_VIDEO_TRIM_FRAMES, Math.ceil(((budget - 0.5) * fps) / MINIMAX_H3_FPS));@@ -912,21 +677,8 @@ const tailSourceFrames = (budget: number, fps: number): number => {};/**- * Re-derives the linked tail reference's window for a generated frame count.- *- * The window is a function of that count, so a frame-count change has to move- * it. This RE-DERIVES rather than shrinks-to-fit: a shrink-only rule ratchets.- * The Frames number input emits a value per keystroke, unclamped, so typing- * "345" passes through 3 — and a shrink-only window would collapse to 3 frames- * and never come back, silently, for the rest of the session. Dragging the- * slider down and back up does the same. Re-deriving is idempotent in- * `numFrames`, so the values a keystroke or a drag passes through leave no- * trace.- *- * A window the user has moved by hand (`trimOverridden`) is exempt. The budget- * still binds it — the backend discards the overrun from the window's end —- * but that is equally true of every ordinary video reference, and silently- * rewriting a deliberate editorial choice is the worse failure of the two.+ * Re-derive default windows when generated length changes so temporary input shrinkage cannot ratchet them down.+ * Preserve explicit trim overrides.*/export const applyReferenceExtendNumFrames = (references: VideoReferenceItem[],@@ -952,19 +704,8 @@ export const applyReferenceExtendNumFrames = (};/**- * Moves the linked tail reference to the end of the list.- *- * Request order is rotary order: `build_ref2va_packed_sequence` lays the- * reference blocks out in order, each advancing a shared clock, and the- * generated rows start at the position the LAST block left behind. The- * continuity anchor only anchors anything if it IS that block — an image- * dropped afterwards wedges itself (a whole rotary slot) between the initial- * video's tail and the first generated frame, and the model continues from the- * image instead.- *- * Add order and drag order must not decide that, so the anchor's position is- * derived like its trim: last, always. Identity-preserving when it is already- * last, or when there is no anchor.+ * Pin the continuity anchor last because generated rotary positions follow the final reference block; preserve+ * identity when already pinned.*/export const pinReferenceExtendAnchor = (references: VideoReferenceItem[]): VideoReferenceItem[] => {const index = references.findIndex((entry) => entry.kind === 'video' && entry.fromSourceVideo === true);@@ -978,17 +719,8 @@ export const pinReferenceExtendAnchor = (references: VideoReferenceItem[]): Vide};/**- * Whether setting `videoName` as the Initial Video could place its anchor.- *- * Mirrors `applyReferenceExtendSourceVideo`'s refusal condition so the UI gate- * cannot drift from what the setter actually does. An adoptable entry consumes- * no slot: the flagged anchor is rewritten in place, and so is an unflagged- * reference already naming the same clip -- which is exactly the shape recall- * restores, since `fromSourceVideo` is panel state and never reaches metadata.- *- * `videoName` is the clip currently set; for a clip not yet dropped its name is- * unknowable, so the answer is the conservative one -- whether a NEW anchor- * would fit.+ * Mirror setter capacity checks. Existing anchors or adoptable same-clip refs need no new slot; unknown incoming+ * clips conservatively require one.*/export const canPlaceReferenceExtendAnchor = (references: VideoReferenceItem[],@@ -1007,29 +739,9 @@ export const canPlaceReferenceExtendAnchor = (};/**- * Keeps the reference list in step with the Initial Video on a reference-extend- * panel (pure; the setter and the model-selection transition both use it):- *- * - clearing the Initial Video removes its linked reference;- * - setting or re-trimming it re-derives the linked reference's default trim- * (the tail window ending on the cutpoint), UNLESS the user has moved that- * window by hand and the clip is the same one — an override is a deliberate- * editorial choice about which frames condition the generation, and a- * cutpoint move is not a reason to discard it. Switching to a different clip- * does discard it: the bounds index frames that are no longer there;- * - with no linked entry yet, an existing video reference for the same clip- * is adopted (recall restores the pair without the linkage flag; adopting- * avoids a duplicate), else a new one is APPENDED — unless the video cap is- * already full, in which case the list is returned unchanged and the- * extension simply runs without a tail reference.- *- * Appended, not prepended, because request order IS rotary order:- * `build_ref2va_packed_sequence` lays the reference blocks out in order, each- * advancing a shared clock, and the generated rows then start at the position- * the LAST block left behind. The reference the model continues from is- * therefore the final one, so the continuity anchor belongs at the end. (The- * entry stays reorderable and keeps its place on a re-derive; only the- * default position is fixed here.)+ * Synchronizes the linked reference with Initial Video. Preserve explicit trims only for the same flagged source;+ * otherwise derive the default. Prefer the flagged anchor, then adopt a matching visual reference, or append if+ * capacity permits. Returning the original list signals capacity refusal. Keep the anchor pinned last.*/export const applyReferenceExtendSourceVideo = (references: VideoReferenceItem[],@@ -1049,10 +761,8 @@ export const applyReferenceExtendSourceVideo = (fromSourceVideo: true,kind: 'video',};- // The flagged entry is THE linked reference; adopt-by-name only when none- // exists (a recall-restored pair carries no flag). A flag-or-name findIndex- // would rewrite a user's own same-clip reference — hand trim and all —- // whenever it sat above the flagged one.+ // Prefer the flagged anchor; same-name fallback is only for unflagged recall, preserving the user's other+ // same-clip trims.const flaggedIndex = references.findIndex((entry) => entry.kind === 'video' && entry.fromSourceVideo === true);const linkedIndex =flaggedIndex >= 0@@ -1061,9 +771,8 @@ export const applyReferenceExtendSourceVideo = ((entry) =>entry.kind === 'video' &&entry.clip.video_name === sourceVideo.video_name &&- // An audio-only reference to this clip is the user's soundtrack, not a- // continuity anchor: adopting it would replace their window with the tail and- // still leave the seam with no visuals. Fall through and append instead.+ // Preserve audio-only same-clip references as soundtracks and append a visual continuity anchor+ // instead.canAnchorReferenceExtend(entry));@@ -1073,14 +782,10 @@ export const applyReferenceExtendSourceVideo = (if (index !== linkedIndex || entry.kind !== 'video') {return entry;}- // Safe to convert an audio-only entry here: it is the flagged anchor, or one just- // adopted into the role, and the role needs visual rows. See- // `anchorReferenceConditioning`.const conditioning = anchorReferenceConditioning(entry.conditioning);- // `fromSourceVideo` is required, not implied by `linkedIndex`: the adopt-by-name- // fallback above reaches UNFLAGGED entries (recall restores the pair without the- // flag), and those have never been an anchor, so they get the derived default.+ // Only flagged entries can retain anchor overrides; same-name adoption must derive its first anchor+ // window.if (entry.fromSourceVideo !== true ||entry.trimOverridden !== true ||@@ -1091,9 +796,7 @@ export const applyReferenceExtendSourceVideo = (return {...linked,- // Re-probed dimensions and frame rate come from the source record;- // the trim is the user's. Sliding the window to its own start re-- // clamps it against a frame count that may have moved with the probe.+ // Refresh probed geometry/rate while preserving and reclamping the user's trim.clip: slideReferenceSampleWindow({ ...sourceVideo, endFrame: entry.clip.endFrame, startFrame: entry.clip.startFrame },entry.clip.startFrame@@ -1112,13 +815,8 @@ export const applyReferenceExtendSourceVideo = (};/**- * Clears conditioning media that no longer exists in the gallery. Returns the- * input object untouched when nothing changes.- *- * Deliberately operates on RAW widget values rather than a normalized- * snapshot: normalization resolves the first-frame/initial-video exclusion by- * masking one slot, and a masked reference would silently survive the- * deletion sweep — a dangling media name waiting to resurface.+ * Clear deleted media from raw values before normalization can mask conflicting slots; preserve identity when+ * unchanged.*/export const clearDeletedVideoMedia = <T extends object>(values: T,diff --git a/invokeai/frontend/webv2/src/features/video/core/types.ts b/invokeai/frontend/webv2/src/features/video/core/types.tsindex c7b0569ee8..c1ea2e599e 100644--- a/invokeai/frontend/webv2/src/features/video/core/types.ts+++ b/invokeai/frontend/webv2/src/features/video/core/types.ts@@ -7,10 +7,7 @@ import type {} from '@features/generation/contracts';import type { SeedMode } from '@platform/core/seed';-/**- * How a video generation is conditioned. There is no explicit mode selector:- * the mode is inferred from which inputs are filled — see `resolveVideoMode`.- */+/** Infer conditioning mode from populated inputs through resolveVideoMode. */export type VideoGenerationMode = 'txt2vid' | 'first-frame' | 'last-frame' | 'first-last' | 'extend' | 'reference';/** A gallery video selected as the clip to extend, with the trim range to keep. */@@ -25,55 +22,31 @@ export interface VideoSourceClip {endFrame: number;}-/**- * Which streams a Ref2VA video reference conditions. The graph-literal values of the- * `minimax_h3_video_reference` node: 'audio' maps to upstream's standalone audio-reference- * kind, sourced from the video's soundtrack.- */+/** Reference conditioning maps directly to graph literals; audio uses the clip's soundtrack without visual rows. */export type VideoReferenceConditioning = 'video_audio' | 'video' | 'audio';/** Ref2VA image-reference sizing: 'max' = 2048px short edge, 'match' = generation's pixel area. */export type VideoReferenceImageDetail = 'max' | 'match';-/**- * One ordered Ref2VA reference. Order is part of the request contract — a different order- * is a different generation — so references live in a single ordered array whatever their- * kind. A video reference reuses `VideoSourceClip` for its trim bounds.- */+/** Reference order affects generation; retain one ordered mixed-kind array with video trim bounds. */export type VideoReferenceItem =| {kind: 'video';clip: VideoSourceClip;conditioning: VideoReferenceConditioning;/**- * True on the reference the panel derives from the Initial Video in- * Ref2VA extend mode: it tracks that clip's identity, and its trim- * defaults re-derive from the cutpoint (up to ~5s of lead-in at 24 fps,- * capped at the generated frame count so the backend keeps the whole- * window) whenever the Initial Video trim or the frame count changes.- * It is an ordinary reference otherwise — reorderable, trimmable,- * removable — and the flag is panel state only, never in metadata.+ * Panel-only marker for the Initial Video continuity anchor, pinned last. Its default trim follows source+ * cutpoints and generated frame count unless trimOverridden is set.*/fromSourceVideo?: boolean;/**- * True once the user has moved the anchor's OWN trim controls. The- * derived window is a default, not a constraint: Ref2VA conditions on- * reference content with no frame-exact seam to protect, so where the- * sample ends is an editorial choice (a clip that fades to black wants- * the fade concatenated but not conditioned on). From then on the panel- * stops re-deriving the window from the cutpoint and the frame count,- * and the entry is trimmed like any other reference. Clearing and- * re-setting the Initial Video drops the override. Panel state only,- * never in metadata; meaningless without `fromSourceVideo`.+ * Panel-only anchor override disables cutpoint/frame-count re-derivation after manual trim edits.+ * Clear/reset source removes it; meaningful only with fromSourceVideo.*/trimOverridden?: boolean;/**- * The sample length the user last asked for, in frames. The window stored in- * `clip` is this clamped to the frames the clip has left from its start frame —- * keeping the request separate is what lets a start-frame drag run into the end- * of the clip and come back with the length intact. Absent until a control is- * touched, where the window's own length is the request. Panel state only, never- * in metadata; read it through `referenceSampleFrames`.+ * Panel-only requested length stays separate from clamped clip bounds so drags can restore it; read through+ * referenceSampleFrames.*/sampleFrames?: number;}@@ -83,12 +56,7 @@ export type WanTargetResolution = '480p' | '720p' | '1080p';export type MiniMaxH3TargetResolution = '768 highres' | '768 lowres';export type VideoTargetResolution = WanTargetResolution | MiniMaxH3TargetResolution;-/**- * The preset ratios the video panel offers. No `Free` and no width/height- * fields: pixel dimensions are always derived — from this ratio plus the- * target-resolution preset in text-to-video, or from the conditioning media's- * own ratio once a frame or source video is set.- */+/** Derive dimensions from preset ratio/resolution or conditioning media; no free-size fields are offered. */export type VideoAspectRatioId = '21:9' | '16:9' | '3:2' | '4:3' | '1:1' | '3:4' | '2:3' | '9:16' | '9:21';/** Project-persisted settings owned by the Video widget. */@@ -103,24 +71,13 @@ export interface VideoSettings {/** Image-to-video conditioning. Mutually exclusive with `sourceVideo`. */firstFrameImage: ImageWithDims | null;/**- * The frame the clip should end on: FLF2V interpolation with a first frame,- * or the destination image when extending a source video. Combines with- * either `firstFrameImage` or `sourceVideo`.+ * Last frame supplies interpolation's endpoint or an extension destination, paired with first frame or source+ * video.*/lastFrameImage: ImageWithDims | null;- /**- * The clip to extend. Mutually exclusive with `firstFrameImage`. On an- * FL2VA model this drives extend mode; on a Ref2VA model it coexists with- * `references` (reference-extend: the new clip is appended to it, and a- * linked tail reference provides continuity).- */+ /** Source excludes first frame; FL2VA uses extend mode while Ref2VA appends using a linked tail reference. */sourceVideo: VideoSourceClip | null;- /**- * Ref2VA references, in conditioning order (up to 3 videos and 9 images).- * Mutually exclusive with `firstFrameImage`/`lastFrameImage`; `sourceVideo`- * may coexist on a Ref2VA model (reference-extend). Only a Ref2VA- * transformer consumes them — see `resolveVideoMode` and the `reference` mode.- */+ /** Ordered Ref2VA references exclude frame slots but may coexist with source video for reference extension. */references: VideoReferenceItem[];aspectRatioId: VideoAspectRatioId;targetResolution: VideoTargetResolution;@@ -131,17 +88,13 @@ export interface VideoSettings {/** Guidance for the low-noise half of a Wan A14B schedule; null reuses `cfgScale`. */cfgScaleLowNoise: number | null;/**- * The family's distillation fast path: the Lightning LoRA pair at 4 steps /- * CFG 1 for Wan A14B, the Turbo LoRA at 6 steps for MiniMax H3. Toggling it- * patches steps/CFG and the `loras` list — see `getAcceleratorToggleResult`- * — so the flag records intent, not hidden state.+ * Acceleration patches visible sampling settings and LoRAs; this flag records intent rather than hidden graph+ * state.*/acceleratorEnabled: boolean;/**- * The keys of the LoRA entries the accelerator toggle added. Turning the- * fast path off (or switching families) removes exactly these — never a- * user's own LoRA that happens to be named like one — and the enabled flag- * cannot outlive them.+ * Track exactly the toggle-added LoRA keys for removal; never remove matching user-owned entries, and clear+ * enabled intent if they disappear.*/acceleratorLoraKeys: string[];seed: number;@@ -153,28 +106,18 @@ export interface VideoSettings {wanT5EncoderModel: ModelIdentifierConfig | null;/** The low-noise expert of a Wan 2.2 A14B mixture-of-experts pair. */wanLowNoiseModel: MainModelConfig | null;- /**- * Diffusers main model used as a component source for single-file mains:- * split/quantized Wan models, and single-file MiniMax H3 transformers- * (which take tokenizer/processor/VAEs from it).- */+ /** Diffusers component source supplies missing non-transformer components for standalone Wan/H3 mains. */componentSourceModel: MainModelConfig | null;/**- * LEGACY — pre model-positions persisted shape only. The single-file H3- * transformer used to be an override slot; it is the top model selection- * now. `syncVideoWidgetValuesWithModels` promotes a stored value onto- * `model` (keeping the old main as `componentSourceModel`); nothing writes- * this field any more.+ * Legacy-only transformer override: reconciliation promotes it to model and retains the old main as+ * componentSourceModel; new writes omit it.*/h3TransformerModel: MainModelConfig | null;/** Optional single-file MiniMax H3 Qwen3-VL text-encoder override. */h3TextEncoderModel: ModelIdentifierConfig | null;/**- * MiniMax H3 hybrid: with a Ref2VA transformer selected, an FL2VA checkpoint- * that supplies every weight except the AdaLN modulation projections from- * `h3HybridStartBlock` onward, which stay Ref2VA's — FL2VA's output quality- * with the references still routed. The loader loads this base; the- * selected Ref2VA main rides the overlay node.+ * Hybrid loads FL2VA base weights and overlays selected Ref2VA AdaLN from h3HybridStartBlock onward while+ * retaining reference conditioning.*/h3HybridBaseModel: MainModelConfig | null;/** First transformer block (0-49) whose AdaLN projection stays Ref2VA's under the hybrid. */diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.tsindex 0e8de5cdd3..09464e1a05 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts@@ -92,9 +92,8 @@ describe('isSupportedVideoModel', () => {});it('offers only runnable identity-bearing H3 models in the top selector', () => {- // Checkpoints of either task variant and full FL2VA Diffusers installs are- // selectable; a components-only folder belongs in the Model Components- // slot, and a Ref2VA folder's transformer weights are not folder-loadable.+ // Only loadable transformers are selectable; components-only folders belong in components and Ref2VA folder+ // transformers are unsupported.expect(isVideoModelSelectable(h3Model('checkpoint'))).toBe(true);expect(isVideoModelSelectable({ ...h3Model('checkpoint'), variant: 'ref2va' })).toBe(true);expect(isVideoModelSelectable(h3Model('diffusers'))).toBe(true);@@ -371,8 +370,7 @@ describe('Lightning', () => {describe('MiniMax H3 Turbo', () => {const TURBO = { base: 'minimax-h3', key: 'turbo', name: 'MiniMax H3 Turbo LoRA', type: 'lora' as const };- // The second installed Turbo LoRA: same family, a different step schedule,- // and nothing but the org name in it to say so.+ // Identify the alternative Turbo schedule from its organization naming.const LIGHTX2V = {base: 'minimax-h3',key: 'lightx2v',@@ -409,8 +407,7 @@ describe('MiniMax H3 Turbo', () => {});it('never auto-picks a Ref2VA-trained turbo LoRA for FL2VA generation', () => {- // The Ref2V Turbo repack is trained against the Ref2VA transformer only; despite sorting- // before "MiniMax H3 Turbo LoRA" and matching the family+turbo patterns, it must lose.+ // Ref2V Turbo is incompatible with FL2VA despite matching broad H3/turbo name patterns.const ref2vTurbo = { base: 'minimax-h3', key: 'ref2v', name: 'MiniMax H3 Ref2V Turbo LoRA', type: 'lora' as const };const ref2vFile = {base: 'minimax-h3',@@ -446,16 +443,13 @@ describe('MiniMax H3 Turbo', () => {expect(on).toMatchObject({ acceleratorEnabled: true, steps: 8 });expect(on.acceleratorLoraKeys).toEqual([LIGHTX2V.key]);- // The help text quotes the running LoRA's count; `ui.accelerator` stays the- // family config, so callers can still resolve other counts against it.+ // Help text reflects active LoRA steps while family accelerator policy remains reusable.expect(getVideoModelPolicy(model, on).ui).toMatchObject({ acceleratorSteps: 8 });expect(getVideoModelPolicy(model, on).ui.accelerator).toMatchObject({ label: 'Turbo', steps: 6 });});it('re-anchors the fast path on the other Turbo LoRA instead of tearing it down', () => {const model = h3Model();- // Both are installed, so the toggle picks one; the user then swaps in the- // other by enabling it and switching the first off.const on = getAcceleratorToggleResult(settingsFor(model), model, H3_CATALOG, true).settings;expect(on.acceleratorLoraKeys).toEqual([LIGHTX2V.key]);@@ -474,8 +468,7 @@ describe('MiniMax H3 Turbo', () => {it('never arms an off fast path from a list edit, whatever lands in the list', () => {const model = h3Model();const turboRider = { base: 'minimax-h3', key: 'rider', name: 'Turbo Rider', type: 'lora' as const };- // A user's own H3 LoRA satisfies the family-name test as readily as a real- // repack does, and a hand-tuned step count must survive an unrelated edit.+ // Preserve hand-tuned steps for ordinary user LoRAs that merely match the family name.const own = { base: 'minimax-h3', key: 'mine', name: 'My H3 Turbo Sharpener', type: 'lora' as const };const off = settingsFor(model, { steps: 12 });@@ -544,8 +537,7 @@ describe('MiniMax H3 Turbo', () => {it('stays intact through a duplicated LoRA entry, so an unchanged value reconciles to itself', () => {const model = h3Model();const on = getDefaultVideoSettings(model, [TURBO]);- // A hand-edited project file (or metadata whose graph listed one twice)- // can hold the same key twice; the flag must not read as broken.+ // Duplicate persisted LoRA keys must not falsely break accelerator detection.const duplicated = [...on.loras, ...on.loras];const once = getAcceleratorLoraChangeResult(on, model, [TURBO], duplicated);const twice = getAcceleratorLoraChangeResult(once.settings, model, [TURBO], duplicated);@@ -556,9 +548,7 @@ describe('MiniMax H3 Turbo', () => {});it('rejects a Lightning pair that does not name the family, even with no family token to check', () => {- // The fallback variant has no variant string, so there is no token to- // demand — the list-scoped lookup must fail closed rather than accept any- // Lightning-named pair the user happens to hold.+ // Without a variant token, reject arbitrary named Lightning pairs rather than treating fallback as a wildcard.const fallbackMain = wanModel('', 'gguf_quantized', 'wan-unprobed');const mine = [lora('Personal Lightning High Detail', null, 'myh'),@@ -647,10 +637,8 @@ describe('component section policy', () => {});it('requires a component source (and a conditional text encoder) for a single-file H3 main', () => {- // The single-file checkpoint carries only the transformer; the loader- // sources tokenizer/processor/VAEs from a Diffusers install in the Model- // Components slot. A components-only source has no text-encoder weights,- // so the single-file Qwen3-VL encoder becomes required with it.+ // Standalone H3 needs Diffusers components; components-only sources additionally require a separate text+ // encoder.const checkpoint = h3Model('checkpoint');const bare = settingsFor(checkpoint);const componentsOnly = { ...h3Model('diffusers', 'h3-components'), components_only: true };@@ -719,8 +707,7 @@ describe('component section policy', () => {getVideoValidationReasons(ref2va, settingsFor(ref2va, { componentSourceModel: h3Model() }))).not.toContainEqual(expect.stringContaining('Hybrid'));- // The overlay node refuses a pruned/full mismatch, so the slot lists only same-kind FL2VA- // checkpoints — and never the selected main, a Ref2VA file, or a Diffusers install.+ // Hybrid choices must match pruned/full shape and exclude Ref2VA, Diffusers, and the selected main.expect(slot?.filter?.({ ...h3Model('checkpoint', 'fl2va-pruned'), pruned: true }, ctx)).toBe(true);expect(slot?.filter?.(h3Model('checkpoint', 'fl2va-kind-unknown'), ctx)).toBe(true);expect(slot?.filter?.({ ...h3Model('checkpoint', 'fl2va-full'), pruned: false }, ctx)).toBe(false);@@ -817,9 +804,8 @@ describe('component section policy', () => {});it('agrees with the served Wan rows on which VAE width each variant takes', () => {- // The rule is written out rather than read from the table, because this surface syncs its stored- // VAE before the table arrives. This keeps the copy honest: a Wan variant or VAE width added to- // the backend changes the served rows, and fails here until the rule follows.+ // Assert backend VAE rules independently because stored VAE synchronization runs before capability rows+ // arrive.const wanRows = architectureCapabilitiesFixture.filter((row) => row.base === 'wan');expect(wanRows.map((row) => row.variant)).toContain('ti2v_5b');@@ -880,8 +866,7 @@ describe('getWanExpertWiringWarning', () => {});it('keeps warning after a role exchange of a same-tag pair, so no swap is offered', () => {- // high+high and low+low pairs re-warn with roles exchanged — the UI uses- // this simulation to withhold the Swap button rather than loop.+ // Offer Swap only if swapping resolves warnings rather than repeating identical expert-role mismatches.const highPair = [tagged('i2v_a14b', 'high', 'm'), tagged('i2v_a14b', 'high', 'l')] as const;const lowPair = [tagged('i2v_a14b', 'low', 'm'), tagged('i2v_a14b', 'low', 'l')] as const;@@ -1085,9 +1070,7 @@ describe('getVideoValidationReasons', () => {it('rejects a Wan extension whose source clip frame rate falls outside 1-120 fps', () => {const model = wanModel('i2v_a14b', 'diffusers');- // wan_l2v/video_concat accept 1-120; an out-of-range clip would fail only- // AFTER the denoise. A slow-mo clip and an unprobeable sub-1 fps rate both- // block up front; an ordinary clip raises nothing.+ // Validate inherited Wan fps before denoising so invalid rates cannot fail only at video output.expect(getVideoValidationReasons(model, settingsFor(model, { sourceVideo: { ...SOURCE_VIDEO, fps: 240 } }))).toContainEqual(expect.stringContaining('1-120 fps'));@@ -1167,9 +1150,6 @@ describe('getVideoModelAvailabilityReasons', () => {});});-// ----------------------------------------------------------------------------// Ref2VA: model-borne variant, reference mode, transitions-const ref2vaTransformer = (key = 'h3-ref2va-ckpt'): MainModelConfig => ({...h3Model('checkpoint', key),name: 'MiniMax H3 Ref2VA Transformer (int8, pruned)',@@ -1317,9 +1297,7 @@ describe('ref2va accelerator auto-pick', () => {};it('prefers the LightX2V ref2v release over the 4-step v0.1 repack whichever order they are listed in', () => {- // The v0.1 repack pans the camera rightward whenever a video reference is used; the- // LightX2V v1.0 release superseded it as the starter model and must win when both are- // installed — by generation, not by the accident of alphabetical order.+ // Prefer the newer LightX2V release by version rather than alphabetical order.expect(findMiniMaxH3TurboLora([REF2V_TURBO, LIGHTX2V_REF2V_TURBO], { variant: 'ref2va' })).toMatchObject({key: 'lightx2v-ref2v-turbo',});@@ -1333,9 +1311,8 @@ describe('ref2va accelerator auto-pick', () => {});it('a by-URL install of the LightX2V release, named by its file, still beats the old starter-named repack', () => {- // model_on_disk names a URL install after the file stem, which carries no "LightX2V"- // token — only the org's file-name form. It must not lose to the v0.1 repack on an- // alphabetical tie (a space collates before an underscore).+ // Recognize URL-installed filename forms lacking the organization token so newer releases still outrank old+ // repacks.const rawNew = {base: 'minimax-h3',key: 'raw-new',@@ -1448,10 +1425,7 @@ describe('reference-extend policy', () => {});it('a Wan -> Ref2VA switch snaps the frame count BEFORE sizing the tail window', () => {- // Wan's grid starts at 5 frames. Deriving the window before the snap sized- // it for that count, and the repair only ever shrank — so the panel landed- // on a 90-frame H3 generation with a 5-frame anchor, below the 13 frames- // `sample_text_conditioning_frames` needs. Generate failed outright.+ // Snap H3 generation frames before deriving its anchor; Wan's small count can produce unusably short context.for (const wanFrames of [5, 9, 21, 81]) {const wan = wanModel('i2v-14b');const toRef = getVideoModelSelectionResult({@@ -1479,9 +1453,7 @@ describe('reference-extend policy', () => {expect(toRef.settings.sourceVideo).toEqual(initialVideo);expect(toRef.clearedLabels).not.toContain('Initial video');- // The window is budgeted against the frame count the switch lands on- // (H3's 124-frame default, snapped AFTER the derivation): a reference- // longer than the generation is truncated at its seam end.+ // Budget against the final snapped frame count: backend truncation removes overrun from the seam end.expect(toRef.settings.numFrames).toBe(124);expect(toRef.settings.references[0]).toMatchObject({clip: { endFrame: 400, startFrame: 277, video_name: 'long.mp4' },@@ -1506,8 +1478,6 @@ describe('reference-extend policy', () => {expect(reselected.settings.references[0]).toMatchObject({ clip: { startFrame: 300 } });- // And back: the references (linked one included) clear; the clip stays- // for FL2VA's own extend mode.const backToFl = getVideoModelSelectionResult({currentSettings: toRef.settings,model: fl2va,diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.tsindex 65cab03999..e56e40e3b7 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts@@ -46,11 +46,7 @@ import {VIDEO_ASPECT_RATIO_IDS,} from './settings';-// Video capabilities registry keyed by model base AND variant: unlike still-image-// generation, Wan's variants differ structurally (which conditioning modes exist,-// the pixel grid, whether a second expert/CFG applies), so base alone is not-// enough. Display identity stays in @features/models; graph topology will stay-// explicit in graph.ts.+// Wan variants differ in conditioning, pixel grid, and experts; key capabilities by base and variant.export type SupportedVideoBase = 'wan' | 'minimax-h3';@@ -86,13 +82,8 @@ export interface VideoFpsPolicy {}/**- * The family's distillation fast path: which LoRA(s) it runs on and the- * sampling parameters they were trained for. Wan A14B uses the Lightning- * high/low pair; MiniMax H3 uses a single Turbo LoRA.- *- * `steps` is the count the family's reference LoRA was distilled for (the- * bundled H3 templates assume the 6-step repack). Releases trained for a- * different schedule are resolved per-LoRA by `getAcceleratorSteps`.+ * Family accelerator LoRAs and sampling defaults. steps describes the reference release; getAcceleratorSteps+ * resolves release-specific schedules.*/export interface VideoAcceleratorConfig {label: 'Lightning' | 'Turbo';@@ -134,9 +125,7 @@ export const WAN_LIGHTNING_ACCELERATOR: VideoAcceleratorConfig = {steps: 4,};-// LightX2V's H3 release is distilled to 8 steps where the repack the templates-// assume is 6, and only its *file* name says so — the starter installs it as-// "MiniMax H3 LightX2V Turbo LoRA", so the org name is the signal that survives.+// LightX2V H3 uses eight steps; starter display names omit that count but retain the organization token.const LIGHTX2V_PATTERN = /(?:^|[^a-z0-9])lightx2v(?:[^a-z0-9]|$)/i;export const MINIMAX_H3_TURBO_ACCELERATOR: VideoAcceleratorConfig = {@@ -147,13 +136,7 @@ export const MINIMAX_H3_TURBO_ACCELERATOR: VideoAcceleratorConfig = {stepOverrides: [{ pattern: LIGHTX2V_PATTERN, steps: 8 }],};-/**- * The Ref2VA-trained Turbo distillations. The reference count is the 4-step v0.1- * repack's (Comfy-Org's ref2v turbo); the LightX2V 8-step v1.0 release that- * superseded it — the starter model since 2026-09-07 — states its schedule via the- * override, like its FL2VA sibling. v0.1 pans the camera rightward whenever a video- * reference is conditioned on; v1.0 does not.- */+/** Ref2VA Turbo uses a four-step reference count; LightX2V releases override it to eight. */export const MINIMAX_H3_REF2V_TURBO_ACCELERATOR: VideoAcceleratorConfig = {cfgScale: 1,cfgScaleLowNoise: null,@@ -200,13 +183,9 @@ const WAN_A14B_COMMON = {const WAN_VARIANTS: Record<string, VideoVariantConfig> = {// The T2V expert pair has no reference-image conditioning channels.t2v_a14b: { ...WAN_A14B_COMMON, modes: ['txt2vid'] },- // The I2V expert pair conditions on a reference frame (and optionally an end- // frame — FLF2V); it has no text-only mode. Extend is FLF2V machinery fed by- // the source video's last frame.+ // I2V experts require a reference frame; extension uses the source's last frame through FLF2V conditioning.i2v_a14b: { ...WAN_A14B_COMMON, modes: ['first-frame', 'first-last', 'extend'] },- // TI2V-5B does both text and image conditioning, but its ref encoder has no- // end-frame channel, and it is a single expert (no low-noise pair, no- // Lightning LoRAs).+ // TI2V-5B has text/image conditioning, no end-frame channel, and one expert.ti2v_5b: {...WAN_A14B_COMMON,accelerator: null,@@ -239,15 +218,12 @@ const MINIMAX_H3_FL2VA: VideoVariantConfig = {targetResolutions: MINIMAX_H3_TARGET_RESOLUTION_OPTIONS,};-// The Ref2VA task transformer supports ONLY reference-conditioned generation (upstream-// declares tasks: ["ref2va"]); everything else it inherits from the FL2VA panel policy.+// Upstream Ref2VA declares only reference-conditioned generation.const MINIMAX_H3_REF2VA: VideoVariantConfig = {...MINIMAX_H3_FL2VA,accelerator: MINIMAX_H3_REF2V_TURBO_ACCELERATOR,modes: ['reference'],- // `extend` = reference-extend: an Initial Video the new clip is appended to,- // with a linked tail reference for continuity (no frame conditioning — the- // panel derives a reference from the clip instead).+ // Reference extension derives a linked tail reference from Initial Video; it does not frame-condition.references: { extend: true, maxImages: 9, maxVideos: 3 },};@@ -255,8 +231,7 @@ export const VIDEO_GENERATION: Record<SupportedVideoBase,{ variants: Record<string, VideoVariantConfig>; fallback: VideoVariantConfig }> = {- // ref2va is REGISTERED, never the fallback: an unknown future variant may fall back to- // fl2va's config, but a known ref2va transformer must not silently get fl2va's modes.+ // Register Ref2VA explicitly so it never inherits FL2VA fallback modes.'minimax-h3': { fallback: MINIMAX_H3_FL2VA, variants: { fl2va: MINIMAX_H3_FL2VA, ref2va: MINIMAX_H3_REF2VA } },wan: { fallback: WAN_FALLBACK_VARIANT, variants: WAN_VARIANTS },};@@ -264,12 +239,8 @@ export const VIDEO_GENERATION: Record<export const SUPPORTED_VIDEO_BASES = Object.keys(VIDEO_GENERATION) as SupportedVideoBase[];/**- * A model the video panel can reason about at all: any Wan main, and MiniMax- * H3 mains in both shapes — the Diffusers folder install and the single-file- * transformer checkpoint. For H3 the checkpoint IS the model identity (its- * task variant decides the panel's mode); the Diffusers install supplies the- * five other submodels, either as the model itself (full install) or through- * the component-source slot (checkpoint main).+ * Supports Wan mains and H3 folder/checkpoint mains. H3 checkpoint variant owns task identity; a Diffusers source+ * supplies its remaining components.*/export const isSupportedVideoModel = <T extends { base: string; type: string; format?: string }>(model: T@@ -279,30 +250,17 @@ export const isSupportedVideoModel = <T extends { base: string; type: string; fo(model.base === 'minimax-h3' && (model.format === 'diffusers' || model.format === 'checkpoint')));/**- * What the top model selector offers — like the image Generate panel, the top- * pick is what decides the panel's UI, so it lists the identity-bearing models:- * H3 single-file transformers (either task variant) and full Diffusers- * installs. Excluded, though still "supported" for stored/recalled state:- * a components-only folder (no transformer weights — it belongs in the Model- * Components slot) and a Ref2VA Diffusers folder (its `transformer_ref`- * weights are not folder-loadable; the single-file checkpoint is the runnable- * form, with the folder serving as the component source).+ * Select runnable identity-bearing models. Components-only and Ref2VA Diffusers folders remain supported for+ * stored state but serve only as component sources, not selectable mains.*/export const isVideoModelSelectable = <T extends ModelConfig>(model: T): boolean =>isSupportedVideoModel(model) &&!isComponentsOnlyH3Main(model) &&!(model.base === 'minimax-h3' && model.format === 'diffusers' && model.variant === 'ref2va');-/**- * A slim MiniMax H3 folder install: tokenizer/processor/VAEs only, no- * transformer or text-encoder weights. The backend probe records- * `components_only` on the config precisely so the UI can require the- * single-file overrides up front instead of failing mid-generation.- */+/** components_only folders contain tokenizer/processor/VAEs but require transformer and text-encoder overrides. */export const isComponentsOnlyH3Main = (model: MainModelConfig): boolean =>- // Demand the full config, not a Pick: a narrowed object would type-check- // here but silently read `components_only` as absent — a false negative- // that re-opens the fail-mid-generation hole this helper exists to close.+ // Require full configs so narrowing cannot silently omit components_only.model.base === 'minimax-h3' && model.format === 'diffusers' && model.components_only === true;const getVideoVariantConfig = (@@ -342,8 +300,6 @@ export const getVideoTargetResolutionOptions = (): readonly VideoTargetResolutionOption[] => getVideoConfig(model).targetResolutions;export const getVideoAspectRatioOptions = (_model: MainModelConfig | undefined): readonly VideoAspectRatioId[] =>- // Both current families accept every offered ratio (H3's 1:4–4:1 bound is- // wider than the preset list); the hook stays per-model for the next family.VIDEO_ASPECT_RATIO_IDS;const coerceTargetResolution = (@@ -382,12 +338,8 @@ export interface ResolvedVideoDimensions extends VideoDimensions {}/**- * The exact pixel dimensions a graph will run at. Text-to-video derives them- * from the aspect-ratio preset; once conditioning media is set, its own ratio- * takes over (the panel's Dimensions section locks accordingly) and only the- * target-resolution preset still applies. Null when the media's ratio is- * outside the model's supported range or the inputs are degenerate — reported- * via `getVideoValidationReasons`.+ * Conditioning media overrides preset aspect ratio; target resolution still applies. Returns null for unsupported+ * ratios or degenerate inputs.*/export const getVideoDimensions = (model: MainModelConfig | undefined,@@ -427,9 +379,7 @@ export const getVideoPromptPolicy = (settings: Pick<VideoSettings, 'cfgScale' | 'cfgScaleLowNoise' | 'negativePromptEnabled' | 'wanLowNoiseModel'>) => {const config = getVideoConfig(model);- // Mirrors wan_video_denoise's do_cfg: negative conditioning is also consumed- // when the LOW-noise half runs CFG (> 1) — which needs a second expert, i.e.- // a Diffusers dual-expert main or a wired low-noise transformer.+ // Match wan_video_denoise.do_cfg: a second expert using CFG > 1 also consumes negative conditioning.const lowNoiseCfgActive =config.cfg.lowNoiseVisible &&(model?.format === 'diffusers' || settings.wanLowNoiseModel !== null) &&@@ -484,8 +434,6 @@ export interface VideoModelPolicy {}export const getVideoModelPolicy = (model: MainModelConfig | undefined, settings: VideoSettings): VideoModelPolicy => {- // The H3 task (fl2va vs ref2va) lives on the selected model itself: a- // single-file transformer checkpoint carries its own variant.const config = getVideoConfig(model);return {@@ -502,11 +450,7 @@ export const getVideoModelPolicy = (model: MainModelConfig | undefined, settingstargetResolutions: config.targetResolutions,ui: {accelerator: config.accelerator,- // The step count the help text quotes is the one the *running*- // accelerator LoRA was distilled for — with the 8-step LightX2V Turbo- // LoRA on, "6 steps" would be a lie. It is deliberately NOT folded into- // `accelerator`: that stays the family config, so callers can keep using- // it as the reference other counts are resolved against.+ // Show the active LoRA's schedule while retaining accelerator as the family reference config.acceleratorSteps: config.accelerator? getAcceleratorSteps(config.accelerator, getRecordedAcceleratorLoras(settings)): null,@@ -518,22 +462,13 @@ export const getVideoModelPolicy = (model: MainModelConfig | undefined, settings};};-// ----------------------------------------------------------------------------// Distillation fast paths (Wan Lightning, MiniMax H3 Turbo)-export interface WanLightningLoraPair {high: LoraModelConfig;low: LoraModelConfig;}export interface FindAcceleratorLoraOptions {- /**- * Accept only LoRAs that also name the model family. Used when the candidate- * list is the user's own Concepts list rather than the installed catalog:- * there is no better-named release for a look-alike to lose to, so a- * personal "Turbo …" LoRA — or a T2V Lightning pair sitting on an I2V main —- * would otherwise be mistaken for a distillation fast path.- */+ /** Require the model-family token for user-list candidates to reject look-alike or wrong-family accelerators. */requireFamilyName?: boolean;}@@ -543,23 +478,14 @@ export interface FindMiniMaxH3TurboLoraOptions extends FindAcceleratorLoraOptionvariant?: string | null;}-// "high"/"low" as standalone words. \b is useless here because release files-// use underscores ("high_noise_model") where \w breaks no boundary, while a-// plain word-suffix match swallows "Slow"/"Thigh" — so the token must be-// delimited by non-alphanumerics (or the string edge) on BOTH sides.+// Delimit both sides with non-alphanumerics: word boundaries miss underscore-separated tokens, while suffix+// matching accepts Slow/Thigh.const HIGH_NOISE_PATTERN = /(?:^|[^a-z0-9])high(?:[^a-z0-9]|$)/i;const LOW_NOISE_PATTERN = /(?:^|[^a-z0-9])low(?:[^a-z0-9]|$)/i;/**- * The installed Lightning LoRA pair for a Wan A14B main, if any. When pairs for- * more than one family are installed (e.g. T2V and I2V releases), the one- * naming the main's family wins; noise assignment comes from the model names.- *- * `requireFamilyName` drops the fallback and demands the family token, so a- * T2V pair is not read as a valid accelerator for an I2V main — the question- * asked when the candidates are LoRAs already in the panel rather than the- * catalog the toggle is free to pick from. With no family token to demand it- * matches nothing, leaving the answer to the catalog.+ * Prefer the main's family and assign experts from names. requireFamilyName rejects fallback matches, including+ * models with no known family token.*/export const findWanLightningLoraPair = (models: readonly ModelConfig[],@@ -578,10 +504,6 @@ export const findWanLightningLoraPair = (const familyToken = typeof mainVariant === 'string' ? mainVariant.split('_')[0] : undefined;const familyPattern = familyToken ? new RegExp(`(?:^|[^a-z0-9])${familyToken}(?:[^a-z0-9]|$)`, 'i') : null;const score = (model: LoraModelConfig): number => (familyPattern?.test(model.name) ? 0 : 1);- // With `requireFamilyName` and no family token to check against (an unprobed- // Wan release on the fallback variant) there is nothing to verify, so this- // fails closed rather than accepting everything — the caller falls back to- // the catalog pick, which is a real answer.const pick = (pattern: RegExp): LoraModelConfig | null =>candidates.filter((model) => pattern.test(model.name) && (!requireFamilyName || score(model) === 0))@@ -594,27 +516,16 @@ export const findWanLightningLoraPair = (};const TURBO_PATTERN = /(?:^|[^a-z0-9])turbo(?:[^a-z0-9]|$)/i;-// A LightX2V distillation release: the token the starter names carry, or the org's own-// file-name form (minimax_h3_<task>_turbo_<N>step_v<major>…), which is the name a by-URL-// install keeps — such an install must not lose the pick to an older starter-named repack.+// Recognize both starter names and raw LightX2V filenames retained by URL installs.const LIGHTX2V_RELEASE_PATTERN =/(?:^|[^a-z0-9])lightx2v(?:[^a-z0-9]|$)|minimax_h3_(?:fl2v|ref2v)_turbo_\d{1,2}step_v\d/i;const MINIMAX_H3_NAME_PATTERN = /(?:^|[^a-z0-9])(?:minimax|h3)(?:[^a-z0-9]|$)/i;-// Ref2VA-trained distillation LoRAs (delimited "ref2v"/"ref2va" token). They must never-// auto-apply to an FL2VA generation - the Ref2V Turbo repack is trained against the Ref2VA-// transformer only.+// Ref2V Turbo is Ref2VA-trained and must never auto-apply to FL2VA.const MINIMAX_H3_REF2V_PATTERN = /(?:^|[^a-z0-9])ref2va?(?:[^a-z0-9]|$)/i;/**- * The installed MiniMax H3 Turbo distillation LoRA, if any. Distillation LoRAs- * carry no dedicated taxonomy, so this is a name heuristic: a delimited- * "turbo" token, preferring names that also name the model family, then the- * LightX2V releases over the earlier repacks they superseded (the 4-step v0.1- * Ref2V repack pans the camera whenever a video reference is used; the- * LightX2V v1.0 files replaced both it and the larryvrh FL2VA v4 as starters),- * with a deterministic tie-break — a user's own "Turbo …" style LoRA loses to- * the real repack whenever one is installed. Ref2VA-trained turbo LoRAs are- * excluded: the FL2VA accelerator must not pick them.+ * Match delimited Turbo names, preferring family names then LightX2V releases with deterministic ties. Exclude+ * Ref2VA-trained releases for FL2VA.*/export const findMiniMaxH3TurboLora = (models: readonly ModelConfig[],@@ -624,10 +535,8 @@ export const findMiniMaxH3TurboLora = (// older repack still beats a LightX2V-named look-alike that omits the family.const score = (model: LoraModelConfig): number =>(MINIMAX_H3_NAME_PATTERN.test(model.name) ? 0 : 2) + (LIGHTX2V_RELEASE_PATTERN.test(model.name) ? 0 : 1);- // Within a tier the release stating the higher schedule is the later one (the 4-step- // v0.1 Ref2V repack against the 8-step v1.0 that replaced it, both under raw file names).- // The task decides which distillation qualifies: ref2va REQUIRES the ref2v-token repack,- // every other variant excludes it — the two are trained against different transformers.+ // Within a tier, higher stated schedules rank newer. Ref2VA requires Ref2V-trained releases; other tasks exclude+ // them.const matchesTask = (name: string): boolean =>variant === 'ref2va' ? MINIMAX_H3_REF2V_PATTERN.test(name) : !MINIMAX_H3_REF2V_PATTERN.test(name);@@ -649,11 +558,8 @@ export const findMiniMaxH3TurboLora = (};/**- * The complete accelerator LoRA set contained in `candidates`, or null when it- * is not all there. The candidates are the installed catalog when asking what- * the toggle *would* run, and the user's own Concepts list when asking what is- * actually running. `model` must be the EFFECTIVE model: for MiniMax H3 the- * task variant (fl2va vs ref2va) decides which Turbo distillation qualifies.+ * Return a complete candidate accelerator set or null. Pass the effective model: its H3 task variant determines+ * compatible Turbo releases.*/export const findAcceleratorLorasIn = (model: MainModelConfig,@@ -674,19 +580,13 @@ export const findAcceleratorLorasIn = (return pair ? [pair.high, pair.low] : null;};-// "4-step", "8 steps", "6step" — how a distillation release states the schedule-// it was trained for. Two digits at most, so a checkpoint tag ("step600") or a-// rank cannot be read as a step count.+// Limit schedule tokens to two digits so checkpoint tags such as step600 cannot become step counts.const STEP_COUNT_PATTERN = /(?:^|[^a-z0-9])(\d{1,2})[ _-]?steps?(?:[^a-z0-9]|$)/i;/** The schedule a distillation LoRA's name states, or 0 when it states none. */const getStatedStepCount = (name: string): number => Number(STEP_COUNT_PATTERN.exec(name)?.[1] ?? 0);-/**- * The step count one distillation LoRA was trained for. Its name is the only- * record of it: an explicit "N-step" token wins, then the family's per-release- * overrides, and failing both the family's reference count.- */+/** Resolve steps from an explicit name token, then release overrides, then family defaults. */const getLoraAcceleratorSteps = (config: VideoAcceleratorConfig, lora: LoraModelConfig): number => {const stated = getStatedStepCount(lora.name);@@ -697,12 +597,7 @@ const getLoraAcceleratorSteps = (config: VideoAcceleratorConfig, lora: LoraModelreturn config.stepOverrides?.find((override) => override.pattern.test(lora.name))?.steps ?? config.steps;};-/**- * The step count for a whole accelerator set. Both halves of a Wan Lightning- * pair state the same schedule; if a mismatched pair is ever assembled, the- * higher count is the safe pick — under-stepping is what reads as a broken- * model.- */+/** Use the higher count for mismatched expert schedules to avoid under-stepping. */export const getAcceleratorSteps = (config: VideoAcceleratorConfig, loras: readonly LoraModelConfig[]): number =>loras.reduce((steps, lora) => Math.max(steps, getLoraAcceleratorSteps(config, lora)), 0) || config.steps;@@ -722,13 +617,8 @@ const getRecordedAcceleratorLoras = (};/**- * The complete accelerator set contained in `candidates`, judged the way the- * panel has to judge LoRAs the user is holding: one that names the model's own- * family, or failing that the very set the catalog would install. The- * family-name requirement keeps a personal "Turbo …" LoRA — or a T2V Lightning- * pair left over on an I2V main — from passing as a fast path; the catalog- * pick is exempt from it because it is what the toggle itself installs, odd- * name and all.+ * Accept complete model-family matches or the exact catalog-selected set; the latter permits unusual names+ * installed by the toggle itself.*/const findAcceleratorAmong = (model: MainModelConfig,@@ -747,11 +637,8 @@ const findAcceleratorAmong = (};/**- * Whether the settings' recorded accelerator keys still name a complete set of- * enabled LoRAs that is a valid fast path *for this model* — the question both- * the model-switch reconcile and the Concepts-list reconcile turn on. Asked of- * the recorded keys alone, so with two Turbo LoRAs enabled the one the user- * anchored on keeps the fast path instead of losing it to a tie-break.+ * Validate only recorded accelerator keys so another enabled candidate cannot displace the user's anchored set+ * through tie-breaking.*/const isRecordedAcceleratorIntact = (settings: Pick<VideoSettings, 'acceleratorLoraKeys' | 'loras'>,@@ -765,10 +652,7 @@ const isRecordedAcceleratorIntact = (return false;}- // Deduplicated by key: a list holding the same LoRA twice (a hand-edited- // project file, metadata whose graph listed one twice) must not make this- // permanently false — the identity guarantee in `syncVideoWidgetValuesWithModels`- // depends on an unchanged value reaching the 'unchanged' outcome.+ // Deduplicate keys so repeated persisted LoRAs can still reach the unchanged reconciliation outcome.const live = [...new Map(getEnabledLoraModels(settings)@@ -781,11 +665,8 @@ const isRecordedAcceleratorIntact = (};/**- * The accelerator LoRA entries for a model, or null when they are not- * installed. Deliberately catalog-only: the family name test is all that- * separates a distillation LoRA from any other, and "MiniMax H3 …" is how a- * user names their OWN H3 LoRA too, so letting the panel's list steer this- * would let the toggle arm itself on a LoRA with no distillation in it.+ * Choose only from the installed catalog; user-list names cannot reliably distinguish distillation from personal+ * style LoRAs.*/const findAcceleratorLoraEntries = (model: MainModelConfig, models: readonly ModelConfig[]): GenerateLora[] | null =>findAcceleratorLorasIn(model, models)?.map((lora) => ({ isEnabled: true, model: lora, weight: 1 })) ?? null;@@ -797,9 +678,8 @@ export interface AcceleratorToggleResult {}/**- * Applies the accelerator toggle as a plain settings transition: the LoRA(s)- * appear in (or leave) the Concepts list and steps/CFG are patched, so the- * graph builder needs no hidden behavior and the user sees exactly what runs.+ * Encode acceleration through visible LoRAs and sampling settings so graph compilation needs no hidden toggle+ * behavior.*/export const getAcceleratorToggleResult = (settings: VideoSettings,@@ -870,19 +750,9 @@ export interface AcceleratorLoraChangeResult {}/**- * Re-reads the fast path from the Concepts list after it changes. The flag has- * to describe what is actually enabled, so swapping one Turbo LoRA for another- * keeps the fast path — re-anchored on the new LoRA, at the step count *it*- * was distilled for — instead of tearing it down. Only a list with no complete- * accelerator left in it turns the toggle off and restores the model's own- * sampling defaults: a silent 6-step run with no distillation LoRA behind it- * just reads as a broken model.- *- * Strictly a repair of a fast path that is already ON. An off accelerator is- * never armed by a list edit, however accelerator-shaped the LoRA that lands- * in it looks: the name heuristic cannot tell a distillation release from a- * user's own "… Turbo …" LoRA, and arming on it would silently drop a- * hand-tuned step count onto a LoRA that does not support it.+ * Repair an enabled accelerator from the edited Concepts list: reanchor a complete replacement or disable and+ * restore model defaults. Never enable from a list edit; name heuristics cannot establish that a user LoRA+ * supports distillation.*/export const getAcceleratorLoraChangeResult = (settings: VideoSettings,@@ -890,8 +760,6 @@ export const getAcceleratorLoraChangeResult = (models: readonly ModelConfig[],loras: GenerateLora[]): AcceleratorLoraChangeResult => {- // The two H3 tasks (fl2va vs ref2va) have different accelerators; the task- // lives on the selected model's own variant.const config = getVideoConfig(model);const next: VideoSettings = { ...settings, loras };@@ -936,9 +804,6 @@ export const getAcceleratorLoraChangeResult = (};};-// ----------------------------------------------------------------------------// Component slots-export type VideoComponentValueKey =| 'vae'| 'wanT5EncoderModel'@@ -1029,9 +894,8 @@ const createComponentPolicy = (const EMPTY_VIDEO_COMPONENT_POLICY = createComponentPolicy(false, []);-// wan_model_loader requires the low-noise expert to be a DIFFERENT single-file-// model of the SAME variant as the main. Unknown variants stay allowed — the-// backend probe is the authority.+// Low-noise experts must be distinct single-file models of the same variant. Allow unknown variants for backend+// probing.const isWanLowNoiseExpertCandidate = (candidate: ModelConfig, ctx: VideoComponentPolicyContext): boolean =>candidate.type === 'main' &&candidate.base === 'wan' &&@@ -1041,13 +905,8 @@ const isWanLowNoiseExpertCandidate = (candidate: ModelConfig, ctx: VideoComponentypeof ctx.model.variant !== 'string' ||candidate.variant === ctx.model.variant);-// wan_model_loader validates the standalone VAE's latent channels against the-// main: TI2V-5B needs the 48-channel Wan 2.2 VAE, A14B the 16-channel Wan 2.1-// VAE. A config without the field (open union) stays allowed.-//-// The served (wan, variant) rows say the same thing, but this surface does not-// wait for the capability table: reading it here would drop a stored VAE during-// the widget sync that runs before the table arrives, and persist the loss.+// TI2V-5B requires 48 VAE channels; A14B requires 16. Allow unspecified channels. Do not await capabilities here:+// early widget sync could otherwise delete and persist a valid stored VAE.const isWanVaeForMain = (candidate: ModelConfig, ctx: VideoComponentPolicyContext): boolean => {if (candidate.type !== 'vae' || candidate.base !== 'wan') {return false;@@ -1079,9 +938,7 @@ export const getVideoComponentSectionPolicy = (if (model.base === 'wan') {const config = getVideoConfig(model);const slots: VideoComponentSlotPolicy[] = [- // A Diffusers main is its own component source; the loader ignores the- // input for it, so the slot is only offered for single-file mains — and- // never lists the selected main itself.+ // Diffusers mains supply their own components and ignore this input; offer it only for single-file mains....(model.format === 'diffusers'? []: [@@ -1117,9 +974,7 @@ export const getVideoComponentSectionPolicy = (},];- // TI2V-5B is a single expert, and a Diffusers A14B main bundles its own- // transformer_2 (the loader ignores this input for it) — so the slot is- // only offered for single-file A14B mains.+ // TI2V-5B has one expert; Diffusers A14B bundles the second. Only single-file A14B needs this slot.if (config.cfg.lowNoiseVisible && model.format !== 'diffusers') {slots.push({filter: isWanLowNoiseExpertCandidate,@@ -1134,20 +989,11 @@ export const getVideoComponentSectionPolicy = (return createComponentPolicy(model.format !== 'diffusers', slots);}- // MiniMax H3. The top model selection carries the task identity (its variant- // decides the panel's generation mode); this section supplies what that- // selection does not bundle:- // - a single-file transformer checkpoint at top REQUIRES a Diffusers H3- // install in the Model Components slot (tokenizer/processor/VAEs come from- // it — full and components-only installs both qualify), plus the- // single-file Qwen3-VL encoder when that install is components-only;- // - a full Diffusers install at top bundles everything, so only the optional- // text-encoder override is offered.+ // H3 checkpoint mains require a Diffusers component source; components-only sources also require a Qwen3-VL+ // override. Full Diffusers mains bundle both.if (model.format === 'diffusers') {- // A components-only install can still sit at top as legacy stored state- // (it is no longer selectable); validation steers the user to pick a- // single-file transformer as the model, and the encoder slot stays- // required so the panel keeps showing what the install cannot provide.+ // Legacy components-only mains remain visible; require the missing encoder while validation requests a+ // single-file transformer main.const componentsOnly = isComponentsOnlyH3Main(model);return createComponentPolicy(componentsOnly, [@@ -1189,11 +1035,8 @@ export const getVideoComponentSectionPolicy = (required: (ctx) => !isH3TextEncoderSatisfied(ctx),valueKind: 'component',},- // The hybrid is a Ref2VA-only option: an FL2VA checkpoint stands in for- // every weight but the AdaLN projections, whose task-defining half stays- // the selected Ref2VA main's. Offered on the Ref2VA selection so the- // panel's reference mode (decided by the top model) is unaffected. Listed- // last: optional tuning sits below the slots the panel needs to run.+ // The hybrid replaces non-AdaLN weights with an FL2VA base while retaining Ref2VA task identity and+ // projections....(model.variant === 'ref2va'? [{@@ -1209,9 +1052,8 @@ export const getVideoComponentSectionPolicy = (]);};-// The overlay node refuses a pruned/full mismatch (the AdaLN projections have-// different shapes), so the slot lists only same-kind FL2VA checkpoints; a-// config without the flag (open union) stays allowed, the backend decides.+// Pruned/full AdaLN shapes differ: require matching checkpoint kinds, leaving unspecified flags to backend+// validation.const isH3HybridBaseCandidate = (candidate: ModelConfig, ctx: VideoComponentPolicyContext): boolean =>candidate.type === 'main' &&candidate.base === 'minimax-h3' &&@@ -1254,9 +1096,6 @@ const getVideoComponentPolicyContext = (settings,});-// ----------------------------------------------------------------------------// Wan A14B expert-wiring advisories-export type WanExpertWiringWarning =| { kind: 'swapped' }| { kind: 'high-as-low' }@@ -1271,10 +1110,8 @@ const getWanExpertTag = (model: MainModelConfig | null): 'high' | 'low' | 'none'};/**- * Advisory only — mirrors wan_model_loader's stance that explicit wiring is- * authoritative and the expert tag is a filename heuristic ('none' is common- * on community finetunes, and deliberate cross-wiring must stay expressible).- * The panel surfaces this as a badge with a one-click swap; nothing blocks.+ * Expert tags are advisory filename heuristics; explicit wiring remains authoritative and mismatches do not block+ * generation.*/export const getWanExpertWiringWarning = (model: MainModelConfig | null,@@ -1313,15 +1150,9 @@ export const getWanExpertWiringWarning = (return mainTag === 'low' ? { kind: 'single-low' } : null;};-// ----------------------------------------------------------------------------// Defaults & model-selection transitions-/**- * The H3 Diffusers install a single-file transformer main should draw its- * components from. A full install is preferred (it also covers the text- * encoder); a components-only folder qualifies otherwise. Used to seed- * defaults/reset and to fill an empty slot on model selection — a checkpoint- * main is un-invokable without one.+ * Prefer full H3 Diffusers installs for checkpoint components; components-only sources also qualify when no full+ * install exists.*/const findH3ComponentSource = (models: readonly ModelConfig[]): MainModelConfig | null => {const candidates = models.filter(@@ -1345,9 +1176,6 @@ export const getDefaultVideoSettings = (batchCount: 1,cfgScale: config.defaults.cfgScale,cfgScaleLowNoise: config.defaults.cfgScaleLowNoise,- // A single-file H3 main cannot run without a Diffusers install in the- // Model Components slot, so defaults (and reset, which reuses them) seed- // one from the catalog instead of starting un-invokable.componentSourceModel:model && model.base === 'minimax-h3' && model.format === 'checkpoint' ? findH3ComponentSource(models) : null,firstFrameImage: null,@@ -1376,9 +1204,7 @@ export const getDefaultVideoSettings = (wanT5EncoderModel: null,};- // The accelerator defaults ON when its LoRA(s) are installed: the plain- // 40/50-step paths are prohibitively slow as out-of-the-box defaults, and- // the bundled video templates make the same choice.+ // Enable installed accelerators by default, matching bundled templates' practical sampling schedules.if (model && config.accelerator) {const result = getAcceleratorToggleResult(base, model, models, true);@@ -1403,8 +1229,6 @@ export const getVideoSettingsWithModelDefaults = (...settings,acceleratorEnabled: modelDefaults.acceleratorEnabled,acceleratorLoraKeys: modelDefaults.acceleratorLoraKeys,- // The default-bearing layout/component choices reset too: a mispicked- // VAE or expert is exactly what a user reaches for reset to undo.aspectRatioId: modelDefaults.aspectRatioId,cfgScale: modelDefaults.cfgScale,cfgScaleLowNoise: modelDefaults.cfgScaleLowNoise,@@ -1422,10 +1246,7 @@ export const getVideoSettingsWithModelDefaults = (].map((lora) => (isLoraCompatibleWithModel(lora.model, model) ? lora : { ...lora, isEnabled: false })),modelKey: model.key,numFrames: modelDefaults.numFrames,- // A reset clears the references list along with the components: on an- // FL2VA model the orphaned list would otherwise linger for the widget- // sync to sweep away silently. (Frame/source conditioning media stay- // untouched: they remain valid under the FL2VA policy.)+ // Reset references with components while preserving valid frame/source conditioning.references: modelDefaults.references,steps: modelDefaults.steps,targetResolution: modelDefaults.targetResolution,@@ -1447,10 +1268,8 @@ const addClearedLabel = (labels: string[], label: string) => {};/**- * Canonical transition for every Video model-selection entry point: reconciles- * conditioning media against the new model's modes, snaps frames/fps/presets- * onto its constraints, and drops incompatible LoRAs and components — reporting- * what was cleared so the UI can say so.+ * Use one model-selection transition to reconcile media, sampling constraints, LoRAs, and components and report+ * cleared inputs.*/export const getVideoModelSelectionResult = ({currentSettings,@@ -1462,12 +1281,8 @@ export const getVideoModelSelectionResult = ({models: readonly ModelConfig[];}): VideoModelSelectionResult => {const config = getVideoConfig(model);- // A record without a modelKey was healed from a store the panel never- // seeded (a fresh project, or a pre-open "Send to Video" payload): its- // sampling values are the model-agnostic healing fallbacks, not user- // choices. Bootstrap the picked model's own defaults — accelerator- // included — instead of preserving fallbacks, then reconcile any seeded- // media below exactly like a normal selection.+ // Missing modelKey means healing defaults, not user choices; bootstrap selected-model defaults before+ // reconciling seeded media.const start = currentSettings.modelKey? currentSettings: getVideoSettingsWithModelDefaults(currentSettings, model, models);@@ -1485,10 +1300,8 @@ export const getVideoModelSelectionResult = ({addClearedLabel(clearedLabels, 'Initial video');}- // The frame count is snapped BEFORE the tail reference is derived: the window- // is budgeted against it, and deriving first left a Wan panel's count (as low- // as 5) sizing a window for a 90-frame H3 generation — under the 13 frames- // text conditioning needs, so Generate failed outright.+ // Snap frame count before deriving reference context so cross-family switches cannot retain an undersized Wan+ // budget.const snappedFrames = snapVideoNumFrames(model, next.numFrames);const framesChanged = snappedFrames !== next.numFrames;@@ -1497,12 +1310,7 @@ export const getVideoModelSelectionResult = ({addClearedLabel(clearedLabels, 'Frames');}- // Reference-extend: a surviving Initial Video (e.g. carried over from an- // FL2VA extend setup) gets its linked tail reference derived, so the switch- // lands on a generatable panel. Only when none exists yet: the transition- // also runs on task-neutral edits (a same-model re-selection, a component- // change), and re-deriving there would reset a hand-tuned trim the help- // text only promises to reset on cutpoint changes.+ // Derive a missing source anchor on model switch; avoid resetting hand-tuned trims on task-neutral transitions.if (config.references?.extend &&next.sourceVideo &&@@ -1516,9 +1324,7 @@ export const getVideoModelSelectionResult = ({);}- // A tail reference carried in from another model keeps a window budgeted for- // that model's frame count. Only when the count actually moved: otherwise a- // task-neutral re-selection would reset a hand-tuned trim.+ // Rebudget inherited tails only when frame count changes, preserving trims on neutral reselection.if (config.references?.extend && framesChanged) {next.references = applyReferenceExtendNumFrames(next.references, next.numFrames);}@@ -1556,13 +1362,8 @@ export const getVideoModelSelectionResult = ({}if (next.acceleratorEnabled) {- // Carry the "fast path" intent across model switches: when the LoRAs the- // user is actually running are still a valid accelerator for the new model,- // everything they may have tuned (steps, CFG, LoRA weights) is left alone.- // Only when that set no longer applies (Lightning ↔ Turbo, or a Wan pair- // aimed at the other expert family) is the toggle re-applied — and when the- // new model has no accelerator, or its LoRAs are not installed, the fast- // path turns off, restoring the model's own steps/CFG.+ // Preserve tuned acceleration when its LoRAs remain compatible. Otherwise reapply the new family's accelerator+ // or restore normal sampling if unavailable.if (!isRecordedAcceleratorIntact(next, model, models, config)) {const targetEntries = config.accelerator ? findAcceleratorLoraEntries(model, models) : null;const result = getAcceleratorToggleResult(next, model, models, targetEntries !== null);@@ -1605,10 +1406,7 @@ export const getVideoModelSelectionResult = ({}}- // A single-file H3 main is un-invokable without a component source; fill an- // empty slot from the catalog — including one the loop above just cleared- // (and reported) as incompatible. An explicit compatible pick is never- // overwritten.+ // Autofill required H3 components only when empty; preserve explicit compatible choices.if (model.base === 'minimax-h3' && model.format === 'checkpoint' && !next.componentSourceModel) {next.componentSourceModel = findH3ComponentSource(models);}@@ -1616,9 +1414,6 @@ export const getVideoModelSelectionResult = ({return { clearedLabels, settings: next };};-// ----------------------------------------------------------------------------// Validation-const VIDEO_MODE_DESCRIPTIONS: Record<VideoGenerationMode, string> = {extend: 'extending a video','first-frame': 'starting from a first frame',@@ -1664,8 +1459,7 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Videreturn ['Video needs a supported video model before it can be invoked.'];}- // Supported-but-not-selectable H3 shapes can reach the model slot as stored- // or recalled state; name the actual fix instead of failing downstream.+ // Give repair guidance for stored supported-but-unselectable H3 configurations.if (isComponentsOnlyH3Main(model)) {return [`${model.name} is a components-only install. Select a single-file MiniMax H3 transformer as the model; this install then provides its components.`,@@ -1696,8 +1490,7 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Videif (!config.modes.includes(mode)) {if (referenceOnly && settings.references.length === 0) {- // The generic message would say "does not support text-to-video", which reads as a- // model defect; the actual fix is to add a reference.+ // Explain the missing reference rather than implying a defective text-to-video model.reasons.push('Reference-to-video needs at least one image or video reference.');} else {reasons.push(`${model.name} does not support ${VIDEO_MODE_DESCRIPTIONS[mode]}.`);@@ -1788,8 +1581,7 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Vide} else if (settings.sourceVideo) {const { endFrame, numFrames, startFrame } = settings.sourceVideo;- // The crossfade join consumes a 2-frame tail from the trimmed source, so a- // 1-frame trim fails mid-encode; catch it (and out-of-range bounds) here.+ // Require valid source bounds and at least two frames for crossfade before encoding.if (startFrame < 0 || endFrame > numFrames - 1 || endFrame - startFrame + 1 < MIN_VIDEO_TRIM_FRAMES) {reasons.push('The initial video trim must keep at least two frames within the clip.');}@@ -1798,10 +1590,7 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Videreasons.push('The initial video is too short to extend.');}- // A Wan extension inherits the source clip's frame rate, and the backend's- // wan_l2v/video_concat nodes accept 1-120 fps. An out-of-range clip (a- // 240 fps slow-mo, an unprobeable sub-1 fps rate) would enqueue, run the- // whole denoise, then die assigning the fps — so block it here instead.+ // Wan extension inherits source fps; validate the backend's 1–120 range before expensive denoising.if (model.base === 'wan') {const inheritedFps = Math.round(settings.sourceVideo.fps);@@ -1822,8 +1611,8 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Vide}if (model.base === 'wan') {- // A14B and 5B Wan LoRAs are not interchangeable — the layer patcher fails- // on a tensor-shape mismatch — so say so instead of silently dropping them.+ // Report incompatible Wan expert-family LoRAs rather than silently dropping weights that would mismatch tensor+ // shapes.for (const lora of settings.loras) {if (lora.isEnabled && !isWanLoraTargetingMain(lora.model.variant, model.variant)) {reasons.push(`${lora.model.name} targets a different Wan model family than ${model.name}.`);diff --git a/invokeai/frontend/webv2/src/features/video/core/widgetValues.test.ts b/invokeai/frontend/webv2/src/features/video/core/widgetValues.test.tsindex e647479408..da4eb7dcb7 100644--- a/invokeai/frontend/webv2/src/features/video/core/widgetValues.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/widgetValues.test.ts@@ -50,8 +50,6 @@ describe('createDefaultVideoWidgetValues', () => {});it('picks a single-file MiniMax H3 checkpoint but never a components-only install', () => {- // The checkpoint is the model identity now; the components-only folder- // belongs in the Model Components slot, not the top selector.expect(createDefaultVideoWidgetValues([h3Model('checkpoint')]).model?.key).toBe(h3Model('checkpoint').key);expect(createDefaultVideoWidgetValues([{ ...h3Model(), components_only: true }]).model).toBeNull();});@@ -67,9 +65,7 @@ describe('syncVideoWidgetValuesWithModels', () => {const model = wanModel('i2v_a14b', 'gguf_quantized');it('promotes a legacy transformer override to the top model slot', () => {- // Pre model-positions persisted shape: the Diffusers install at top, the- // single-file transformer in the override slot. The transformer is the- // model identity now; the install stays on as its component source.+ // Migrate legacy transformer overrides to model identity and retain Diffusers components.const install = h3Model();const checkpoint = { ...h3Model('checkpoint', 'h3-ckpt'), name: 'MiniMax H3 Ref2VA (int8)', variant: 'ref2va' };const stored = {@@ -89,9 +85,7 @@ describe('syncVideoWidgetValuesWithModels', () => {});it('keeps the installed Diffusers main when the legacy transformer override is uninstalled', () => {- // An uninstalled override must not evict the still-installed install from- // the top slot (which would auto-pick a different family): the install- // stays, and the dead override is dropped like any uninstalled component.+ // A missing override must not displace a still-installed main or trigger a different-family fallback.const wan = wanModel('t2v_a14b');const install = h3Model();const checkpoint = { ...h3Model('checkpoint', 'h3-ckpt'), variant: 'ref2va' };@@ -116,8 +110,7 @@ describe('syncVideoWidgetValuesWithModels', () => {});it('clears the accelerator flag when no video main is left installed', () => {- // `loras` empties out with the model, so a surviving flag would record keys- // that are not in the list — a record the persistence validator rejects.+ // Clear accelerator keys with empty LoRAs so persisted state remains valid.const h3 = h3Model();const turbo = { base: 'minimax-h3', key: 'turbo', name: 'MiniMax H3 Turbo LoRA', type: 'lora' as const };const values = createDefaultVideoWidgetValues([h3, turbo as never]);@@ -181,10 +174,7 @@ describe('syncVideoWidgetValuesWithModels', () => {});it('snaps family constraints when it auto-picks a different-family model', () => {- // Wan-shaped stored values (frames 81, fps 16, 720p) with no surviving- // model, in a catalog whose only supported main is MiniMax H3: without the- // selection transition the panel would be stuck at fps 16 with no FPS- // control to fix it.+ // Auto-picked H3 must reconcile Wan sampling values, including fps with no H3 control to repair it.const stored = { ...createDefaultVideoWidgetValues([wanModel('t2v_a14b')]), model: null };const synced = syncVideoWidgetValuesWithModels(stored, [h3Model()]);@@ -196,10 +186,7 @@ describe('syncVideoWidgetValuesWithModels', () => {});it('bootstraps the picked model’s family defaults (accelerator included) for a never-seeded store', () => {- // A fresh project's widget store is `{}`; healing yields model-agnostic- // fallbacks with NO modelKey. The selection transition must bootstrap the- // picked model's own defaults instead of preserving the fallbacks —- // otherwise a fresh H3 panel opens at 40 steps / CFG 5 with Turbo off.+ // Fresh widgets use selected-model defaults, including acceleration, instead of generic healing fallbacks.const catalog = [h3Model(), lora('MiniMax H3 Turbo LoRA', 'minimax-h3', null)];const healed = normalizeVideoWidgetValues({})!;const synced = syncVideoWidgetValuesWithModels(healed, catalog);@@ -209,8 +196,6 @@ describe('syncVideoWidgetValuesWithModels', () => {// onto the H3 grid (90), which is what the preserve path would produce.expect(synced).toMatchObject({ acceleratorEnabled: true, cfgScale: 1, fps: 24, numFrames: 124, steps: 6 });- // A pre-open seeded payload ("Send to Video") keeps its media through the- // same bootstrap.const seeded = normalizeVideoWidgetValues({firstFrameImage: { height: 480, image_name: 'seed.png', width: 832 },})!;@@ -225,10 +210,8 @@ describe('syncVideoWidgetValuesWithModels', () => {const enabled = getAcceleratorToggleResult(createDefaultVideoWidgetValues([model]), model, catalog, true).settings;const values = { ...enabled, model };- // The pair vanishes from the catalog: entries drop, flag clears with them,- // and the sampling params Lightning wrote (steps 4 / CFG 1) are restored- // to the model's own defaults — clearing only the flag would leave a- // silent 4-step non-distilled setup.+ // Losing accelerator LoRAs restores normal sampling as well as clearing intent; four-step nondistilled runs+ // are invalid defaults.const synced = syncVideoWidgetValuesWithModels(values, [model]);expect(synced.loras).toEqual([]);diff --git a/invokeai/frontend/webv2/src/features/video/core/widgetValues.ts b/invokeai/frontend/webv2/src/features/video/core/widgetValues.tsindex a652a2e3ad..2c97ccacf8 100644--- a/invokeai/frontend/webv2/src/features/video/core/widgetValues.ts+++ b/invokeai/frontend/webv2/src/features/video/core/widgetValues.ts@@ -23,13 +23,6 @@ import {type VideoComponentValueKey,} from './videoPolicies';-/**- * The panel-facing layer over the pure settings: default values seeded from- * the installed catalog, catalog reconciliation (upscale-style: render-time,- * mount write-back, and compile all reuse this one function), the aggregate- * validation the invoke route consumes, and seed resolution at submit.- */-// Shared empty array, so clearing already-clear keys keeps its identity.const EMPTY_ACCELERATOR_LORA_KEYS: string[] = [];@@ -40,25 +33,15 @@ export const createDefaultVideoWidgetValues = (models: readonly ModelConfig[] =};/**- * Re-resolves every model reference against the live catalog. MUST return the- * same object when nothing changes — the mount-time reconciler and render- * memoization rely on that identity guarantee to avoid write-back loops.+ * Resolve catalog references while preserving object identity when unchanged to avoid reconciliation write-back+ * loops.*/export const syncVideoWidgetValuesWithModels = (values: VideoWidgetValues,models: readonly ModelConfig[]): VideoWidgetValues => {- // Legacy stored shape (pre model-positions): an H3 Diffusers install at top- // with the single-file transformer in the override slot. The transformer is- // the model identity now — promote it to the top slot and keep the install- // as its component source. Runs before anything reads `values.model`, so- // the whole sync (and its write-back) sees the new shape.- //- // Only a transformer that resolves in the live catalog as an H3 checkpoint- // main is promoted: an uninstalled (or corrupt) override must not evict the- // still-installed Diffusers main from the top slot — leaving it in place- // keeps a runnable H3 panel, and the component pass below drops the dead- // override (no slot offers it any more).+ // Promote only installed H3 checkpoint overrides before other reconciliation; retain the old Diffusers main as+ // components and drop invalid overrides without evicting it.if (values.model?.base === 'minimax-h3' && values.model.format === 'diffusers' && values.h3TransformerModel) {const installedTransformer = models.find((candidate) => candidate.key === values.h3TransformerModel?.key);@@ -80,21 +63,15 @@ export const syncVideoWidgetValuesWithModels = (const modelsByKey = new Map(models.map((model) => [model.key, model]));const storedMain = values.model ? modelsByKey.get(values.model.key) : undefined;- // The stored main survives on the looser `isSupportedVideoModel` check: a- // legacy non-selectable shape (components-only install at top with no- // transformer to promote) keeps its slot and shows validation guidance- // instead of being silently swapped for another model. Auto-picks use the- // stricter selectable filter.+ // Preserve supported legacy nonselectable mains for repair guidance; automatic choices use the stricter+ // selectable filter.const model: MainModelConfig | null =storedMain && isSupportedVideoModel(storedMain)? storedMain: ((models.find((candidate) => isVideoModelSelectable(candidate)) as MainModelConfig | undefined) ?? null);- // The main changed identity under us (nothing stored, or the stored model was- // uninstalled and another family got auto-picked): run the canonical- // selection transition first, or the new family would inherit the old one's- // frames/fps/resolution — an H3 main stuck at Wan's fps 16 has no working- // FPS control to fix it with.+ // Run canonical selection transitions after model replacement so family-specific fps, frames, and resolution+ // cannot remain stale.const base: VideoWidgetValues =model && model.key !== values.model?.key? { ...getVideoModelSelectionResult({ currentSettings: values, model, models }).settings, model }@@ -133,18 +110,8 @@ export const syncVideoWidgetValuesWithModels = (: [];}): [];- // Losing an accelerator LoRA through the catalog (uninstalled, dropped as- // incompatible) goes through the same reconcile the Concepts setter uses:- // another complete accelerator set still enabled in the list takes over,- // otherwise the flag goes off AND the model's own sampling defaults come- // back. Clearing only the flag would leave steps 4 / CFG 1 with no- // distillation LoRA — a silent run that reads as a broken model.- //- // The reconcile only ever repairs a fast path that is already on, so a sync- // running on every render cannot arm one behind the user's back.- //- // Reuse the stored values whenever nothing changed — the identity guarantee- // below depends on `acceleratorLoraKeys` keeping its array.+ // Repair active acceleration after catalog changes, restoring normal defaults if no complete set remains. Never+ // enable it implicitly; preserve unchanged array identities.const unchangedAccelerator = {acceleratorEnabled: base.acceleratorEnabled,acceleratorLoraKeys: base.acceleratorLoraKeys,@@ -156,9 +123,7 @@ export const syncVideoWidgetValuesWithModels = (let accelerator = unchangedAccelerator;if (!model) {- // No video main at all: `loras` above is empty, so a surviving flag would- // name keys that are not in the list — a record `isVideoSettings` rejects- // on reload. There is no model to take sampling defaults from.+ // Without a main, clear acceleration keys alongside empty LoRAs to keep persisted settings valid.if (base.acceleratorEnabled || base.acceleratorLoraKeys.length > 0) {accelerator = {...unchangedAccelerator,@@ -191,9 +156,7 @@ export const syncVideoWidgetValuesWithModels = (wanT5EncoderModel: syncComponent('wanT5EncoderModel', base.wanT5EncoderModel),};- // The model decides the task: if the Ref2VA transformer was uninstalled and- // another model got auto-picked, the stored references are orphaned — the- // policy no longer has a reference mode — so drop them, identity-preserving.+ // Drop orphaned references when the replacement model lacks reference mode, preserving identity otherwise.if (next.references.length > 0 && model && !getVideoModes(model).includes('reference')) {next.references = [];}diff --git a/invokeai/frontend/webv2/src/features/video/index.ts b/invokeai/frontend/webv2/src/features/video/index.tsindex e38d570fbc..eaa159077c 100644--- a/invokeai/frontend/webv2/src/features/video/index.ts+++ b/invokeai/frontend/webv2/src/features/video/index.ts@@ -1,9 +1,4 @@-/**- * Video generation's React-free values/policy surface: settings normalization,- * the per-base/per-variant capabilities matrix, canvas math, and model-selection- * transitions. Curated, caller-driven export list — add a symbol only when a- * consumer needs it. UI and graph compilation arrive in later modules.- */+/** React-free video settings, capabilities, canvas math, and model-selection policy. */export type {MiniMaxH3TargetResolution,VideoAspectRatioId,diff --git a/invokeai/frontend/webv2/src/features/video/ui/PlayClipSpanButton.tsx b/invokeai/frontend/webv2/src/features/video/ui/PlayClipSpanButton.tsxindex 6056f4187f..2ed8610814 100644--- a/invokeai/frontend/webv2/src/features/video/ui/PlayClipSpanButton.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/PlayClipSpanButton.tsx@@ -11,27 +11,8 @@ import { useTranslation } from 'react-i18next';import { useVideoUiActions } from './VideoUiContext';/**- * Plays a clip's trimmed window in the Preview widget, looping it — and, while that loop- * is the one running, offers to stop it.- *- * The trim rows show two still frames, which answer where the window starts and ends but- * not what is inside it — and for an audio reference, whose frames are a drawing of the- * sound, nothing at all. This is the panel's only way to hear or watch the selection- * before a generation is spent on it.- *- * The button is a pause control only for its own loop: the player reports under the token- * of the request it honoured, so a sibling card playing the same clip, or a native play of- * something else, leaves this one offering play. Pausing leaves the window armed in the- * player (the native play control resumes the selection), but the NEXT press here is a- * fresh request rather than a resume — the trim can have moved in between, and the press- * has to play what the rows now show, from its start.- *- * Never gated on the panel's edit-disabled state: playing changes nothing, and a clip the- * user can see is one they should be able to audition. The gallery record is resolved on- * press rather than held on the reference, because the panel stores a clip (name,- * dimensions, frame rate) while Preview needs the item itself — one small request against- * something the user already has open, paid for by the press rather than by every card on- * mount.+ * Controls only its own playback token. Every play requests the current trim from its start; pausing leaves the+ * loop armed for native resume. Playback remains available while editing is disabled.*/export const PlayClipSpanButton = memo(function PlayClipSpanButton({ clip }: { clip: VideoSourceClip }) {@@ -49,10 +30,7 @@ export const PlayClipSpanButton = memo(function PlayClipSpanButton({ clip }: { cconst span = useMemo(() => videoClipSpanSeconds(clip), [clip]);const videoName = clip.video_name;const handlePress = useCallback(() => {- // `aria-disabled` rather than `disabled` while the lookup is in flight: disabling a- // focused button blurs it to <body>, dropping a keyboard user out of the card mid-- // gesture — the same hazard the reference list's move arrows carry a focus handoff- // for. So the press has to be refused here instead of by the DOM.+ // Use aria-disabled plus this guard to retain keyboard focus during lookup.if (!span || isResolving) {return;}@@ -71,8 +49,7 @@ export const PlayClipSpanButton = memo(function PlayClipSpanButton({ clip }: { cif (item.kind === 'video' && isAccountScopeCurrent(owner)) {const token = playVideoSpanInPreview({ ...span, item });- // A refusal (Preview could not be raised) asked nothing of the player, so the- // loop this button last started — paused, still armed — stays its own to stop.+ // Preview refusal leaves the previous loop armed under this button's token.if (token !== null) {setRequestToken(token);}diff --git a/invokeai/frontend/webv2/src/features/video/ui/TrimBoundThumb.tsx b/invokeai/frontend/webv2/src/features/video/ui/TrimBoundThumb.tsxindex 9beea10f34..881641eb06 100644--- a/invokeai/frontend/webv2/src/features/video/ui/TrimBoundThumb.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/TrimBoundThumb.tsx@@ -3,17 +3,8 @@ import { FindInGalleryThumbnailButton } from '@features/gallery/mediaSlot';import { memo, useEffect, useRef } from 'react';/**- * Small always-visible preview of one trim bound. Same seek technique as the- * workflow editor's frame scrubber: one long-lived muted `<video>` element whose- * `currentTime` is set to the middle of the frame's display interval- * (`(frame + 0.5) / fps`), so rounding cannot show the neighbouring frame and- * browsers display the frame natively without a canvas roundtrip. Remounting per- * drag tick would spawn a range fetch per movement on multi-MB clips, hence the- * long-lived element (`key={src}` only).- *- * Sized for the trim rows it lives in — a fixed compact tile with the slider to- * its right — with the badge showing only the bound's name: the paired slider's- * number input already shows the frame number.+ * Seek to frame midpoints to avoid rounding into adjacent frames. Keep one video element per source to avoid a+ * range fetch on every drag tick.*/const PREVIEW_VIDEO_STYLE = {diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoComponentsSection.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoComponentsSection.tsxindex 1399b349b2..2026b41fb5 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoComponentsSection.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoComponentsSection.tsx@@ -24,14 +24,6 @@ import { ScrubberField } from '@platform/ui/ScrubberField';import { Fragment, memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-/**- * Model Components for the Video panel — fully policy-driven, like the- * generation panel's section: the component renders whatever slots the- * capability matrix returns (Wan: component source / VAE / Wan T5 / low-noise- * expert; MiniMax H3: the two single-file overrides), with each slot's- * compatibility filter and requiredness coming from the policy.- */-const coerceSlotValue = (slot: VideoComponentSlotPolicy,candidate: ModelConfig | null@@ -92,11 +84,7 @@ const ComponentSlotRow = memo(function ComponentSlotRow({);});-/**- * The MiniMax H3 hybrid's one tuning knob, shown under its base slot once a- * base is picked: blocks from here through the last keep the Ref2VA AdaLN- * projections, earlier blocks take the FL2VA base's.- */+/** Blocks at and above this index use Ref2VA AdaLN projections; earlier blocks use the FL2VA base. */const HybridStartBlockRow = memo(function HybridStartBlockRow({onPatch,value,@@ -107,9 +95,7 @@ const HybridStartBlockRow = memo(function HybridStartBlockRow({const { t } = useTranslation();const handleChange = useCallback((h3HybridStartBlock: number) => onPatch({ h3HybridStartBlock }), [onPatch]);- // ScrubberField, like the panel's other sliders: SliderNumberField's only other- // user is the Generate widget, and importing it here too split it into a shared- // chunk — one more request on every editor route.+ // Reuse ScrubberField to avoid adding a shared Generate-only control chunk to editor boot.return (<ScrubberFielddefaultValue={MINIMAX_H3_HYBRID_BLOCK_RANGE.defaultStart}@@ -125,11 +111,8 @@ const HybridStartBlockRow = memo(function HybridStartBlockRow({});/**- * Advisory badge for suspicious Wan A14B expert wiring (a low-tagged file in- * the main slot, a high-tagged one in the low-noise slot). The tags are a- * filename heuristic and explicit wiring stays authoritative — mirroring the- * backend loader — so this never blocks; it offers a one-click swap instead,- * keeping deliberate cross-wiring expressible.+ * Expert tags are filename heuristics; explicit wiring remains authoritative, so warn and offer a swap without+ * blocking.*/// Spelled out rather than interpolated, so the translation-key scan can see// them and fail the build if a string goes missing.@@ -149,17 +132,13 @@ const WanExpertWiringNotice = memo(function WanExpertWiringNotice({}) {const { t } = useTranslation();const models = useModelsSelector((snapshot) => snapshot.models);- // A selection transition computed against an unloaded catalog would judge- // the Lightning pair "not installed" and silently strip the accelerator.+ // Wait for catalog authority before judging the accelerator pair installed.const modelsLoaded = useModelsSelector((snapshot) => snapshot.status) === 'loaded';const warning = useMemo(() => getWanExpertWiringWarning(values.model, values.wanLowNoiseModel),[values.model, values.wanLowNoiseModel]);- // Only offer the swap when exchanging roles actually clears the warning: a- // high+high or low+low pair would just re-warn about the other file. Both- // configs must also still exist in the catalog — "models loaded" alone- // would happily relocate a just-uninstalled config into the main slot.+ // Offer only swaps that clear the warning and whose two configs still exist.const bothExpertsInstalled =Boolean(values.model && models.some((candidate) => candidate.key === values.model?.key)) &&Boolean(values.wanLowNoiseModel && models.some((candidate) => candidate.key === values.wanLowNoiseModel?.key));@@ -177,8 +156,6 @@ const WanExpertWiringNotice = memo(function WanExpertWiringNotice({return;}- // Same variant and both single-file (the slot filter guarantees it), so- // the canonical transition is a same-family no-op apart from the swap.const result = getVideoModelSelectionResult({ currentSettings: values, model: nextMain, models });onPatch({ ...result.settings, model: nextMain, wanLowNoiseModel: previousMain });diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoConceptsSection.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoConceptsSection.tsxindex 837873cc6b..93b0ffe144 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoConceptsSection.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoConceptsSection.tsx@@ -13,13 +13,7 @@ import { useTranslation } from 'react-i18next';import { areVideoLorasEquivalent, areVideoModelsEquivalent } from './videoComparators';-/**- * Concepts (LoRAs) for the Video panel. The picker is an adder (never shows a- * selection); compatibility follows the shared generation rule, which for Wan- * already encodes the A14B/5B family split. Expert routing is the graph's job- * ('auto' reads each LoRA's probed high/low tag), so rows carry no target- * control.- */+/** Graph compilation routes LoRAs to experts from their probed tags; the UI supplies no target override. */const LORA_MODEL_TYPES: readonly ModelTaxonomyType[] = ['lora'];const SWITCH_CHECKED_PROPS = { bg: 'accent.solid' };diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsxindex 4b3fd613e2..71cc3801fe 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsx@@ -8,12 +8,8 @@ import { memo, useCallback } from 'react';import { areVideoLorasEquivalent, areVideoModelsEquivalent } from './videoComparators';/**- * The Video widget's prompt block. The prompt is Video's own widget value, not- * the project draft Generate and Upscale share: a video prompt describes motion- * over time and has nothing useful to say to an image model, so the two panels- * hold independent text. Memoised against content: the widget re-derives- * `values` on every patch and the prompt editors carry autocomplete state a- * needless remount would disturb.+ * Video prompts are independent of the shared image-generation draft. Compare content because patches recreate+ * values and remounts would lose autocomplete state.*/export const VideoPromptFields = memo(function VideoPromptFields({diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoHeaderActions.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoHeaderActions.tsxindex 577dae4235..f0ae9abc30 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoHeaderActions.tsx@@ -11,12 +11,6 @@ import { useTranslation } from 'react-i18next';import { areVideoValuesEqual } from './videoComparators';import { useVideoUi } from './VideoUiContext';-/**- * Widget-header action: reset every default-bearing setting (frames, fps,- * target resolution, steps, CFG, accelerator state, aspect ratio, component- * selections) back to the selected model's defaults. Prompts and conditioning- * media are left untouched.- */const sortLorasByKey = <T extends { model: { key: string } }>(loras: readonly T[]): T[] =>[...loras].sort((a, b) => a.model.key.localeCompare(b.model.key));@@ -24,13 +18,9 @@ export const VideoHeaderActions = () => {const { t } = useTranslation();const { patchValues, rawValues } = useVideoUi();const models = useModelsSelector((snapshot) => snapshot.models);- // Defaults computed from an unloaded catalog would claim the accelerator- // pair is "not a default" and strip it as the reset — stay disabled until- // the catalog is authoritative.+ // Wait for authoritative catalog data so reset cannot remove a valid accelerator pair.const modelsLoaded = useModelsSelector((snapshot) => snapshot.status) === 'loaded';- // Sync against the catalog exactly like the panel view does: computing from- // the raw store would judge (and reset to!) a phantom model the view no- // longer shows — e.g. one uninstalled while the panel was open.+ // Match the panel's reconciled model; raw state may still reference an uninstalled model.const normalized = normalizeVideoWidgetValues(rawValues);const values = normalized && modelsLoaded ? syncVideoWidgetValuesWithModels(normalized, models) : normalized;const model = values?.model ?? null;diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsxindex abe08f5090..bc0e1668b4 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx@@ -47,19 +47,11 @@ import { PlayClipSpanButton } from './PlayClipSpanButton';import { TrimBoundThumb } from './TrimBoundThumb';import { useVideoUiActions } from './VideoUiContext';-/**- * The ordered Ref2VA reference list: one card per reference, badged with the labels the- * structured prompt addresses it by (order is part of the request — a different order is a- * different generation), one gallery drop target that accepts a single image or video,- * per-kind file uploads, a per-video conditioning selector and trim, and a per-image detail- * selector.- */+/** Reference order determines prompt labels and generation semantics. */const DROP_ID = 'video-reference-list';const IMAGE_UPLOAD_ACCEPT = getGalleryUploadAccept(['image']);-// One upload button for both media kinds: an uploaded audio file becomes a waveform video,-// so it occupies a VIDEO reference slot and shares that cap -- a separate audio button would-// grey out with this one. The gallery's video accept list is exactly that set, audio included.+// Audio uploads become waveform videos and consume the shared video-reference cap.const MEDIA_UPLOAD_ACCEPT = getGalleryUploadAccept(['video']);const DROP_ZONE_FOCUS_PROPS = {outlineColor: 'accent.focusRing',@@ -104,12 +96,8 @@ const ReferenceCard = memo(function ReferenceCard({videoLabel,}: {/**- * The card's structured-prompt label numbers, flattened to scalars rather than passed as- * the object `referencePromptLabels` returns: they are derived from the WHOLE list, so an- * object would be a fresh prop on every card on every edit to any reference. `updateReference`- * keeps the identity of the entries it did not touch, which is what lets the other cards bail- * out of a trim drag entirely; a per-card object would re-render all twelve — each one a zag- * Select and two ScrubberFields — once per pointer step.+ * Pass scalar labels: labels depend on the whole list, but fresh per-card objects would rerender every card on+ * each trim step.*/audioLabel: number | null;collections: ReferenceCollections;@@ -132,11 +120,7 @@ const ReferenceCard = memo(function ReferenceCard({const moveDownRef = useRef<HTMLButtonElement>(null);const name = reference.kind === 'video' ? reference.clip.video_name : reference.image.image_name;const kind = reference.kind;- // Never gated on `disabled`, for the same reason the play button is not:- // locating the media changes nothing about the generation. Offered once per- // card — from the poster, or from the START bound of a clip: both bounds are- // frames of one gallery record, so badging each would be two controls with- // one destination and one name for a screen reader to tell apart.+ // Finding media stays available while editing is disabled; expose one action per media record.const findReferenceInGallery = useCallback(() => findInGallery({ kind, name }), [findInGallery, kind, name]);const promptLabels = useMemo(() => formatReferencePromptLabels({ audio: audioLabel, picture: pictureLabel, video: videoLabel }),@@ -151,8 +135,7 @@ const ReferenceCard = memo(function ReferenceCard({return collections.detail;}- // The anchor is not offered 'Audio only': it is the reference the extension continues- // FROM, and an audio-only one contributes no visual rows to continue from.+ // The extension anchor needs visual rows, so Audio only is unavailable.return reference.fromSourceVideo === true ? collections.anchorConditioning : collections.conditioning;}, [collections, reference]);const handleSelect = useCallback(@@ -170,22 +153,12 @@ const ReferenceCard = memo(function ReferenceCard({},[index, onUpdate, reference]);- // The trim is presented as a sliding sample window — start frame plus length — because- // what the user is choosing is "how much" (every reference frame costs denoise VRAM) and- // "from where". Storage stays startFrame/endFrame (the request contract); the window- // math (a start that reaches every frame, with the length pinned to what the clip can- // still supply) lives in core/settings.- //- // Touching either control on the extend anchor marks its window overridden, which stops- // the panel re-deriving it from the Initial Video's cutpoint and frame count. The- // derived window is only a default: Ref2VA has no frame-exact seam to protect, so where- // the anchor samples is the user's editorial call.+ // Present start plus length while storing request bounds. Editing either control marks the anchor window+ // overridden; derivation from the initial-video cutpoint is only a default.const handleStartFrame = useCallback((rawStart: number) => {if (reference.kind === 'video') {- // Recording the length here as well as reading it is what makes a drag- // reversible: the first pointer step of the drag captures the pre-drag window's- // length, and every step after it slides that same length.+ // Capture pre-drag length once so subsequent steps slide the same window reversibly.const sampleFrames = referenceSampleFrames(reference);onUpdate(index, {@@ -211,9 +184,6 @@ const ReferenceCard = memo(function ReferenceCard({},[index, onUpdate, reference]);- // What this reference will actually cost, at the size the graph will encode it: the two- // detail settings differ by an order of magnitude in rows, and nothing else in the panel- // says so before the generation is queued.const imageCost = useMemo(() =>reference.kind === 'image'@@ -221,23 +191,15 @@ const ReferenceCard = memo(function ReferenceCard({: null,[reference, targetArea]);- // The window's length, and the seconds it represents — the label carries the seconds- // because the control is how a user hits a target sample duration (reference frames cost- // denoise VRAM every step), while its unit has to stay frames to match the trim contract.+ // Store frames for the trim contract; show seconds to make sample duration readable.const sampleFrames = reference.kind === 'video' ? reference.clip.endFrame - reference.clip.startFrame + 1 : 0;const sampleSeconds =reference.kind === 'video' && Number.isFinite(reference.clip.fps) && reference.clip.fps > 0? (sampleFrames / reference.clip.fps).toFixed(1): null;- // A move that lands on an end -- the top of the stack, or the slot above the- // pinned continuity anchor -- disables the very button that was just pressed,- // and a disabled element cannot hold focus, so a keyboard user is dropped to- // <body> mid-gesture. Which button that is depends on the anchor rule, so the- // handoff reacts to what actually came back disabled rather than predicting- // it. It is armed only when the arrow ALREADY holds focus, because pressing a- // button does not focus it in every browser (Safari, Firefox on macOS): a- // pointer press there runs this handler with the caret still in the prompt,- // and moving focus would haul the user out of what they were typing.+ // Arm focus repair only if the arrow owns focus. Reordering can disable it; inspect the committed disabled state+ // because the anchor rule determines the endpoint. Some browsers click without focusing, so never steal focus+ // from the prompt.const pendingFocusRef = useRef<'down' | 'up' | null>(null);const handleMoveUp = useCallback(() => {const arrow = moveUpRef.current;@@ -262,13 +224,8 @@ const ReferenceCard = memo(function ReferenceCard({const pressed = pending === 'up' ? moveUpRef.current : moveDownRef.current;const sibling = pending === 'up' ? moveDownRef.current : moveUpRef.current;- // Hand off only the focus this card is responsible for losing. Disabling a- // focused button blurs it to <body>, so that -- or focus still sitting on- // the arrow -- is the whole set of states worth repairing. Anywhere else and- // the user has moved on since, which happens whenever the write did not land- // in this commit: `setReferences` drops writes from a panel that is no- // longer live, and `memo` then keeps this card from rendering at all, so the- // arm survives to a later render that has nothing to do with the gesture.+ // Repair only arrow/body focus: a dropped write can leave this arm until an unrelated render, after the user+ // has focused elsewhere.const isOursToRestore = document.activeElement === document.body || document.activeElement === pressed;if (isOursToRestore && pressed?.disabled === true && sibling !== null && !sibling.disabled) {@@ -278,13 +235,9 @@ const ReferenceCard = memo(function ReferenceCard({const handleRemove = useCallback(() => onRemove(index), [index, onRemove]);return (- /* Named after the labels the prompt uses, so the twelve identical Remove/Move/trim- controls a full list can hold announce which reference they belong to. */+ /* Prompt labels disambiguate each card's repeated controls. */<Box aria-label={[...promptLabels, name].join(' ')} borderWidth="1px" p="2" role="group" rounded="md"><HStack align="start" gap="2">- {/* Leading the card, left of every thumbnail it shows: plays what the trim- below actually selected, which the two still bounds cannot convey — and for- an audio reference, whose frames are a drawing of the sound, nothing can. */}{reference.kind === 'video' ? <PlayClipSpanButton clip={reference.clip} /> : null}{reference.kind === 'image' ? (<Box@@ -303,14 +256,7 @@ const ReferenceCard = memo(function ReferenceCard({) : null}<Stack flex="1" gap="1" minW="0"><HStack gap="1">- {/* The names the prompt has to use for this reference, leading the row that- names it and standing in for the kind icon that used to sit here: the label- already says which kind it is, and for a waveform clip conditioning on its- soundtrack alone it says so more honestly than a film icon would. The number- is NOT the card's slot — the three modality counters advance independently —- so it goes beside the filename rather than in a gutter that would cost every- card a fixed 64px. Rendered verbatim, brackets and LTR order included,- because the badge is the token to type. */}+ {/* Render prompt tokens verbatim in LTR order; modality counters differ from card positions. */}{promptLabels.map((label) => (<Badge key={label} dir="ltr" flexShrink={0} size="xs" userSelect="text" variant="solid">{label}@@ -339,12 +285,7 @@ const ReferenceCard = memo(function ReferenceCard({})}</Text>) : null}- {/* One row per window edge: the live frame at left, its control at right. The- seeking thumbs replace the static gallery poster for video references — the- start-frame thumb is the card's visual identity. The second row's SLIDER is- the sample length (the quantity that costs VRAM); its THUMB still shows the- resulting end frame, badged with that frame number since the number field- beside it shows the length, not the frame. */}+ {/* The second control edits length; its thumbnail shows the resulting end frame. */}{reference.kind === 'video' ? (<Stack gap="1"><HStack gap="2">@@ -380,8 +321,6 @@ const ReferenceCard = memo(function ReferenceCard({? t('widgets.video.sampleLength'): t('widgets.video.sampleLengthWithSeconds', { seconds: sampleSeconds })}- // The window grows forward from its start, so the ceiling is what the- // clip has left from there — it falls as the start frame climbs.max={Math.max(1, reference.clip.numFrames - reference.clip.startFrame)}min={1}step={1}@@ -439,12 +378,7 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({disabled?: boolean;maxImages: number;maxVideos: number;- /**- * Accepts an UPDATER, not a snapshot. The add handlers `await` a gallery- * resolve before writing, and the Initial Video field and Frames slider both- * write references too -- a captured array would clobber whichever of those- * landed during the await.- */+ /** Accept an updater: gallery resolution awaits must not overwrite reference edits made meanwhile. */onChange: (update: (current: VideoReferenceItem[]) => VideoReferenceItem[]) => void;references: VideoReferenceItem[];/** The generation's pixel area, which sizes a 'match'-detail image reference. */@@ -457,9 +391,7 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({const [isLoading, setIsLoading] = useState(false);const [errorMessage, setErrorMessage] = useState<string | null>(null);- // The continuity anchor is pinned last, so any move that would displace it is- // reverted the moment it is written -- the button fired a patch and the list- // came back unchanged. Present those as disabled rather than inert.+ // Disable moves that would displace the pinned last anchor and therefore be reverted.const anchorIndex = references.findIndex((reference) => reference.kind === 'video' && reference.fromSourceVideo === true);@@ -513,11 +445,8 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({(image: { height: number; name: string; width: number }) => {setErrorMessage(null);- // Re-check the cap against the LIVE list: the render-time gate can be- // stale by the time a drop resolves or an upload lands, and another- // writer (a second drop, the Initial Video placing its anchor) can fill- // the slots meanwhile. An over-cap write would survive to normalization,- // whose overflow rule then has to delete SOMETHING the user placed.+ // Recheck live capacity after async resolution; normalization would otherwise discard an existing reference+ // on overflow.let declined = false;onChange((current) => {@@ -530,9 +459,7 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({return [...current,{- // Read off the LIVE list, beside the cap re-check: which default applies- // depends on whether an image reference is already placed, and another- // writer can have placed one while this add was in flight.+ // Derive defaults from the live list because another image may have arrived during the await.detail: getDefaultReferenceImageDetail(current),image: { height: image.height, image_name: image.name, width: image.width },kind: 'image',@@ -568,28 +495,18 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({);const addVideoItem = useCallback(- // The conditioning is derived here, from the marker the gallery item carries: it tells a- // wrapped audio upload from footage without a second request, so every caller gets the- // right answer synchronously.(item: GalleryVideoItem) => {- // The marker is read here and NOT stored on the clip: a clip outlives the gallery- // record it came from (it is persisted in the project and re-uploaded under a fresh- // name on import, where the server does not re-derive the marker), so a copy on the- // clip would go stale, and nothing downstream should be tempted to trust it.+ // Do not persist mediaOrigin on the clip: project import reuploads under a new name without rederiving it.const conditioning = getDefaultReferenceConditioning(item.mediaOrigin);const clip = createVideoSourceClip(item);- // Built outside the updater so the caller holds the same object the list does: it is- // the only durable handle on this entry once reordering moves it.+ // Construct once so the caller retains the same entry identity through reorders.const entry: Extract<VideoReferenceItem, { kind: 'video' }> = {- // The window depends on the conditioning -- a short sample of footage, the whole- // clip of a soundtrack. (Neither is the extend-mode 2-frame-tail trim: references- // are truncated to the generated duration, not joined.)+ // Footage defaults to a short sample; audio uses the whole clip. References are truncated, not+ // crossfade-joined.clip: getDefaultReferenceClip(clip, conditioning),conditioning,kind: 'video',};- // Same live cap re-check as the image path -- the Initial Video's- // anchor is the writer that most easily fills the slots mid-await.let declined = false;setErrorMessage(null);@@ -726,13 +643,8 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({);const addPickedVideo = useCallback((item: GalleryVideoItem) => {- // Fully synchronous, which the picker requires: it stays open and judges each click- // against the reference list as it stands, so an add that had not landed yet would- // leave the tile pickable (a second click would duplicate it), leave the remaining- // count stale, and let two picks land in whichever order their fetches finished --- // which for references is a different generation. This path used to add on the- // footage default and correct the card once a metadata fetch answered; the marker- // rides on the picked item, so there is nothing left to correct.+ // Apply picks synchronously so subsequent clicks see current capacity and cannot duplicate or reorder+ // pending selections.addVideoItem(item);},[addVideoItem]@@ -760,26 +672,14 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({},[onChange]);- // Identity for the list, and it must NOT contain the index: an index-bearing key- // changes for every card a reorder touches, so React unmounts and remounts them --- // reloading a video reference's seeking trim thumbnails and throwing away keyboard- // focus on the arrow just pressed. Media can legitimately appear twice (the same- // clip sampled over two different windows), so a bare name is not unique either; it- // is disambiguated by how many entries of the same kind and name precede it.- //- // That makes a card stable against every move EXCEPT a swap with its own twin,- // where the two occurrence numbers trade places and React swaps the props between- // the instances instead of moving one. Rendering stays correct; the cards simply do- // not travel. Giving twins independent identity needs a per-entry uid minted on add- // and carried through normalization, which the persisted reference shape has no- // room for today.+ // Key by kind/name occurrence, not index, to preserve focus and video elements across moves. Identical twins+ // reuse instances with swapped props; independent twin identity would require persisted per-entry IDs.const referenceKeys = useMemo(() => {const seen = new Map<string, number>();return references.map((reference) => {const name = reference.kind === 'video' ? reference.clip.video_name : reference.image.image_name;- // Kind is part of the identity, matching `toGalleryItemKey`: an image and a- // video are different references even where a backend gives them one name.+ // Include kind because image and video names may collide.const identity = `${reference.kind}:${name}`;const occurrence = seen.get(identity) ?? 0;@@ -876,8 +776,7 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({</Text>) : null}<Input accept={IMAGE_UPLOAD_ACCEPT} hidden ref={imageInputRef} type="file" onChange={handleImageFileChange} />- {/* Audio files upload too: the server wraps them into waveform videos, which is- how audio-only reference clips enter the pipeline. */}+ {/* The server wraps audio uploads as waveform videos. */}<Input accept={MEDIA_UPLOAD_ACCEPT} hidden ref={videoInputRef} type="file" onChange={handleVideoFileChange} /></Stack>);diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsxindex bd643d0d94..9e796b6bd8 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx@@ -14,12 +14,6 @@ import { PlayClipSpanButton } from './PlayClipSpanButton';import { TrimBoundThumb } from './TrimBoundThumb';import { useVideoUiActions } from './VideoUiContext';-/**- * The clip to extend: the shared media slot (picker, gallery drop, upload) and- * the trim bounds — one compact row per bound, the bound's live frame at left- * and its slider at right (see TrimBoundThumb for the seek technique).- */-const DROP_ID = 'video-source-clip';const VIDEO_ONLY = ['video'] as const;@@ -98,9 +92,7 @@ export const VideoSourceClipField = memo();const previewSrc = sourceVideo ? galleryVideoUrls.full(sourceVideo.video_name) : null;- // Offered from the START bound only: both thumbs are frames of one gallery- // record, so badging each would be two controls with one destination and- // one name for a screen reader to tell apart.+ // Both bounds reference one gallery record; expose one find control.const videoName = sourceVideo?.video_name;const findClipInGallery = useCallback(() => {if (videoName !== undefined) {@@ -121,16 +113,13 @@ export const VideoSourceClipField = memo(/>{sourceVideo && previewSrc ? (<Stack gap="2">- {/* The empty-state slot shows the reason when no clip is set; with- one set, the frozen trim sliders were the only symptom. */}+ {/* Show the disabled reason even when a clip is already set. */}{disabled && disabledReason ? (<Text color="fg.muted" fontSize="2xs" textWrap="pretty">{disabledReason}</Text>) : null}<Field helpText={t('widgets.video.trimHelp')} label={t('widgets.video.trim')}>- {/* The play button leads both bound rows rather than sitting in one of- them: it plays the range they bracket, not either edge. */}<HStack align="center" gap="2" w="full"><PlayClipSpanButton clip={sourceVideo} /><Stack flex="1" gap="1" minW="0">diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsxindex 079cc1e1be..c228167062 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx@@ -4,34 +4,16 @@ import type { ReactNode } from 'react';import { createContext, use, useMemo } from 'react';-/**- * Video's UI port. The context is a dependency-direction port (the feature- * may not import workbench), not a test seam; no second adapter is expected.- */+/** Workbench supplies this UI port because features cannot import workbench. */export interface VideoUiAdapter {- /**- * Locate one of the panel's conditioning media in the Gallery grid and put it- * in front of the user: the Gallery and Preview widgets come on screen and- * the grid lands on the item's board, page, and cell. The panel's thumbnails- * are the only handle the user has on media picked long ago.- */+ /** Reveal this media's board, page, and cell in Gallery and show Preview. */findInGallery(ref: GalleryItemRef): void;- /**- * The board a file upload from the video panel should land on — the gallery's- * currently selected board. A callback rather than a value so upload handlers- * read it at upload time without subscribing to board-selection changes.- */+ /** Read the selected upload board at upload time without subscribing to board changes. */getUploadBoardId(): string;patchValues(values: Partial<VideoWidgetValues>, origin?: 'user' | 'system'): void;/**- * Show `item` in the Preview widget and loop the given window of it — how the- * panel's play buttons let a trim be judged before it is generated against.- * Selecting the item is part of the gesture: Preview shows the gallery- * selection, and the panel has no other way to put a clip in front of it.- *- * Returns the request's token, which `videoSpanPlayback` reports under once- * the player has the loop running; `null` when Preview could not be raised- * and nothing was asked of it.+ * Select item in Preview and request looping this window. Returns its playback token, or null if Preview could+ * not be raised and no request was made.*/playVideoSpanInPreview(span: { endSeconds: number; item: GalleryVideoItem; startSeconds: number }): number | null;projectId: string;@@ -44,12 +26,8 @@ export interface VideoUiAdapter {}/**- * The player's side of a span request: reported under the request's token, so a button- * can tell its own loop from a sibling card's, and gone (`null`) once nothing is armed —- * the user scrubbed out of the window, a newer request took over, or the player left the- * screen. `isPlaying` tracks the element itself, so a native pause shows in the panel- * too; `pause` stops the element and leaves the loop armed, so a native play resumes the- * selection rather than the whole clip.+ * Reports the armed request token, or null after disarming. isPlaying mirrors the element; pause preserves the+ * armed window for native resume.*/export interface VideoSpanPlaybackState {isPlaying: boolean;@@ -75,12 +53,7 @@ export type VideoUiActions = Pick<>;const VideoUiContext = createContext<VideoUiAdapter | null>(null);-/**- * Actions are published separately from the adapter because the adapter's- * identity changes on every value patch (it carries `rawValues`). Components- * that only need to *do* something — not read state — subscribe here and so are- * not re-rendered by a keystroke elsewhere in the form.- */+/** Separate actions from the value-changing adapter so action-only consumers do not rerender on form edits. */const VideoUiActionsContext = createContext<VideoUiActions | null>(null);export const VideoUiProvider = ({ adapter, children }: { adapter: VideoUiAdapter; children: ReactNode }) => {diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsxindex 3981e78476..624994086a 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx@@ -44,12 +44,7 @@ import { VideoReferenceListField } from './VideoReferenceListField';import { VideoSourceClipField } from './VideoSourceClipField';import { useVideoUi, useVideoUiActions } from './VideoUiContext';-/**- * Every prop identity in this file is stable by construction — module-scope- * constants for literals, `useCallback`/`useMemo` for anything closing over- * state, and `memo` on each section — matching the Upscale widget's contract:- * the widget re-renders on every keystroke that patches project state.- */+/** Keep section props stable: project patches rerender this widget on every keystroke. */const MAIN_MODEL_TYPES: readonly ModelTaxonomyType[] = ['main'];const SWITCH_CHECKED_PROPS = { bg: 'accent.solid' };@@ -68,12 +63,7 @@ const DURATION_FORMATTER = new Intl.NumberFormat(undefined, {minimumFractionDigits: 1,});-/**- * A media value the current model cannot consume (persisted from another- * model's session, or restored by an optimistic rollback) would otherwise- * block invoke invisibly — its section is policy-hidden. This stub is the- * visible affordance to clear it.- */+/** Expose clearing for unsupported media that would otherwise block invocation from a hidden section. */const StaleMediaStub = ({ label, onClear }: { label: string; onClear: () => void }) => {const { t } = useTranslation();@@ -105,10 +95,7 @@ const VideoModelReconciler = ({return;}- // When the store fails normalization wholesale (first open: the topbar- // Iterations field may already have patched `batchCount` into an- // otherwise-empty widget store), seeding the defaults must not wipe that- // one pre-open edit.+ // Preserve topbar batchCount edits when seeding an otherwise uninitialized widget.const batchCount = normalized ? values.batchCount : sanitizeBatchCount(rawValues.batchCount ?? values.batchCount);patchValues({ ...values, batchCount }, 'system');@@ -123,9 +110,7 @@ export const VideoWidgetView = () => {const models = useModelsSelector((snapshot) => snapshot.models);const modelsStatus = useModelsSelector((snapshot) => snapshot.status);const { patchValues, projectId, rawValues } = selection;- // Normalizing and reconciling against the model list is the widget's most- // expensive derivation; it must not run on unrelated re-renders, and a fresh- // `values` identity would re-render every section below.+ // Reconcile only when inputs change; it is expensive and fresh values rerender every section.const values = useMemo(() => {const normalized =normalizeVideoWidgetValues(rawValues) ?? createDefaultVideoWidgetValues(modelsStatus === 'loaded' ? models : []);@@ -152,31 +137,10 @@ export const VideoWidgetView = () => {const patch = useCallback((next: Partial<VideoWidgetValues>) => patchValues(next), [patchValues]);- // Always the newest normalized list. The reference field's add handlers- // `await` a gallery resolve before writing, and the Initial Video field and- // the Frames slider write references too — so an updater that resolved- // against a captured array would clobber whichever of those landed during- // the await, silently deleting the anchor or restoring a window the frame- // count had already re-derived.- // Synced in an effect rather than during render: this file's react-compiler- // rule forbids touching a ref while rendering, and a gallery resolve lands- // whole frames later, long after the commit.- // Keyed by PROJECT, and carrying a LIVENESS bit. The widget is reconciled,- // never remounted, across a project switch (the <Activity> key is the panel- // instance), while `patch` stays bound to the project its render belonged- // to — so a bare latest-list ref tracks whichever project is ACTIVE, and a- // gallery resolve landing after a switch would write the new project's- // reference list into the old project, wholesale. And a hidden <Activity>- // destroys effects while promise continuations keep running: the ref then- // freezes with the projectId still matching, so a same-project guard would- // happily replay a list the store has since rewritten (a gallery deletion- // sweep, say) — resurrecting swept references. `live` is true exactly while- // the sync effect is mounted, which is the only time the ref's contents can- // be trusted; a write finding it false or mismatched is dropped.- //- // "Fresh" here means effect-fresh, not instantaneous: two resolves landing- // in the same microtask drain still read the same pre-commit list. That- // window is inherent to reading through React state at all.+ // Async writes must use the latest committed list for this project while the sync effect is live. Hidden+ // Activity panels stop syncing, and old callbacks still target their original project; drop writes in either+ // case to avoid restoring stale references. Two resolves in one microtask drain may still see the same+ // pre-commit list.const referencesRef = useRef({ live: true, projectId, references: values.references });useEffect(() => {@@ -238,8 +202,7 @@ export const VideoWidgetView = () => {[models, patch, policy.ui.accelerator?.label, t, values]);- // One setter per field, created once per `patch` identity: inline- // `onChange={(x) => patch({ x })}` props would defeat every `memo` below.+ // Stable per-field setters preserve child memo boundaries.const set = useMemo(() => ({aspectRatio: ({ value }: { value: string[] }) => {@@ -269,13 +232,8 @@ export const VideoWidgetView = () => {[patch, values.aspectRatioId]);- // The mutual exclusion lives in the setters: a first frame and an initial- // video are different ways to claim the same conditioning slot, so setting- // one clears the other. A last frame combines with either — with a first- // frame it interpolates (FLF2V); with a source video it is the destination- // the extension should land on. On a reference-extend panel the initial- // video and the references coexist — the setter keeps the linked tail- // reference in step with the clip and its cutpoints.+ // First frame and initial video share one conditioning slot; last frame can accompany either. Reference+ // extension also keeps the linked tail reference synchronized.const referenceExtend = Boolean(policy.references?.extend);const maxVideoReferences = policy.references?.maxVideos ?? 3;const setFirstFrame = useCallback(@@ -284,13 +242,8 @@ export const VideoWidgetView = () => {[patch]);const setLastFrame = useCallback((lastFrameImage: ImageWithDims | null) => patch({ lastFrameImage }), [patch]);- // Not part of `set`: that object is memoized on `patch` alone so the field- // setters keep the children's `memo` intact, and this one has to track the- // reference list. The linked tail reference's window is budgeted against the- // generated frame count — the backend discards an ill-fitting window at its- // SEAM end — so the count and the window move together. The re-derive is- // idempotent: this fires once per keystroke of the Frames input, unclamped,- // so typing "345" arrives as 3, then 34, then 345.+ // This setter tracks references separately from patch-only field setters. Rebudget the linked tail with frame+ // count so backend truncation cannot discard its seam end; derivation must tolerate intermediate input values.const setNumFrames = useCallback((numFrames: number) =>patch(@@ -298,36 +251,21 @@ export const VideoWidgetView = () => {? { numFrames, references: applyReferenceExtendNumFrames(referencesRef.current.references, numFrames) }: { numFrames }),- // Reads the list through the ref so the Frames control keeps a stable- // prop identity: depending on `values.references` re-created this on every- // panel patch, re-rendering the slider against the file's stable-identity- // contract. Safe because the re-derive is idempotent in `numFrames`. The- // project guard is unreachable for this synchronous caller; it keeps the- // ref's contract uniform.+ // Read committed references through the guarded ref to keep the Frames callback stable; rebudgeting is+ // idempotent.[patch, projectId, referenceExtend]);const setSourceVideo = useCallback((sourceVideo: VideoSourceClip | null) => {if (referenceExtend) {- // Same guard as `setReferences`: the clip field's adopt and upload- // paths call this after an await, and a captured list would clobber a- // reference added meanwhile. Dropped when the project moved on or the- // sync effect is unmounted — the ref is effect-fresh, not live, and- // only vouches for its contents while mounted.if (!referencesRef.current.live || referencesRef.current.projectId !== projectId) {return;}const current = referencesRef.current.references;const references = applyReferenceExtendSourceVideo(current, sourceVideo, maxVideoReferences, values.numFrames);- // Unchanged identity with a clip set means the video cap is full and- // no same-clip entry could be adopted. REFUSE the whole drop: patching- // the clip anyway produced an extension with no continuity anchor at- // all, behind nothing but a toast -- and the cap gate then froze the- // clip's trim sliders. (The gate cannot pre-empt this case: it can- // only ask about the clip currently set, and this drop is a different- // one.) Clearing is never refused -- removing the linked entry cannot- // overflow anything.+ // Unchanged identity means no tail-reference slot is available: refuse the whole drop so the clip cannot+ // be set without its continuity anchor. Clearing cannot overflow.if (sourceVideo && references === current) {toaster.create({description: t('widgets.video.referenceExtendCapFullDescription'),@@ -344,26 +282,15 @@ export const VideoWidgetView = () => {},[maxVideoReferences, patch, projectId, referenceExtend, t, values.numFrames]);- // The single choke point for every list edit the reference field makes — add,- // remove, retrim, reorder — so pinning the continuity anchor here covers all- // of them. Request order is rotary order and the generation continues from- // the LAST reference, so the anchor's position is derived, not user-set.+ // Generation continues from the last reference; pin the continuity anchor after every list edit.const setReferences = useCallback((update: (current: VideoReferenceItem[]) => VideoReferenceItem[]) => {- // A pending edit is DROPPED when the ref cannot vouch for the list:- // the project moved on (this callback's `patch` still targets the one- // it rendered for), or the sync effect is unmounted (a hidden panel's- // continuations would replay a frozen list over whatever the store has- // done since). Losing one add beats overwriting a list the user can see.if (!referencesRef.current.live || referencesRef.current.projectId !== projectId) {return;}const updated = update(referencesRef.current.references);- // Identity return means the updater declined (an apply-time cap check)- // or had nothing to do: patching anyway would still fire this spread's- // firstFrameImage/lastFrameImage clearing — a refused add erasing frame- // slots it never touched — and dirty the project with a no-op write.+ // A declined/no-op updater must not reach the patch that clears frame slots and dirties the project.if (updated === referencesRef.current.references) {return;}@@ -381,13 +308,8 @@ export const VideoWidgetView = () => {const clearReferences = useCallback(() => patch({ references: [] }), [patch]);const setLoras = useCallback((loras: VideoWidgetValues['loras']) => {- // While the fast path is on it follows the list: a different complete- // accelerator set in it re-anchors the toggle onto that set at its own- // step count, and losing the last one turns the toggle off and restores- // the model's own sampling defaults (the accelerator wrote steps/CFG).- // Either way the user's list edit stands, and either way they are told —- // a silent 6-step run with no distillation LoRA behind it just looks- // like a broken model. An off accelerator is never armed from here.+ // While enabled, follow a replacement accelerator set or restore model sampling defaults if none remains.+ // Preserve the edit and notify; never enable acceleration from a list edit.if (!values.model) {patch({ loras });return;@@ -446,26 +368,15 @@ export const VideoWidgetView = () => {const supportsExtend = policy.modes.includes('extend');const supportsReferences = policy.modes.includes('reference');const supportsInitialVideo = supportsExtend || referenceExtend;- // Setting an Initial Video on a reference-extend panel has to place a linked- // tail reference, which needs a free video slot -- unless an existing entry- // can be adopted, which consumes none. Deferring to the same predicate the- // setter's refusal uses keeps the two from drifting: gating on the flag alone- // disabled the field after a recall, which restores references UNFLAGGED- // beside the source video, and `disabled` reaches the clip's trim sliders too- // -- so the cutpoint could not be moved on a clip that was legitimately set.+ // Use the setter's capacity predicate: recalled unflagged references can be adopted without consuming a slot,+ // and must not disable clip trimming.const initialVideoCapBlocked =referenceExtend &&!canPlaceReferenceExtendAnchor(values.references, values.sourceVideo?.video_name, maxVideoReferences);const hasConditioningMedia = Boolean(values.firstFrameImage || values.lastFrameImage || values.sourceVideo);const derivedSourceText = dimensions ? t(`widgets.video.dimensionSource.${dimensions.source}`) : undefined;- // Media pins the canvas to its own proportions, so the stored preset is not what the output will- // be: leaving it on the trigger of a disabled control states a ratio the render will not use. The- // preset itself is kept, not rewritten -- it is what the panel goes back to when the media is- // removed -- and the trigger names the source instead. Deliberately not the nearest standard- // preset: media rarely lands exactly on one, so that would swap one wrong ratio for another.- // Truncating, like the Generate panel's own aspect-ratio trigger: the slot clips its value text- // rather than wrapping it, so a phrase wider than the control ends mid-word in a docked panel- // instead of in an ellipsis.+ // Media determines output proportions. Show its ratio source while disabled, preserving the saved preset for+ // when media is removed.const dimensionSource = dimensions?.source;const derivedSourceValueText = useMemo(() =>@@ -495,12 +406,6 @@ export const VideoWidgetView = () => {values={values}/>- {/* Tier-1, like Generate's model card: which model you are running is the- choice every field below is conditioned on, so it sits above the- prompt rather than inside a collapsed section. */}- {/* `px` matches the inset the prompt block and every section body carry,- so the picker lines up with the fields below it — Generate's card can- skip it only because its neighbours sit flush too. */}<Stack gap="1" px="2" py="1"><Fielderror={values.model ? undefined : t('widgets.video.modelRequired')}diff --git a/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsxindex 8be40edd51..8d2117035c 100644--- a/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx@@ -16,11 +16,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { VideoReferenceListField } from './VideoReferenceListField';/**- * The starting conditioning of an added video reference is decided from the resolved gallery- * item's `mediaOrigin`. That decision is one call in one callback, and the helper behind it is- * unit-tested on its own -- so without this test, deleting the call and hardcoding- * `'video_audio'` again leaves the suite green while every wrapped audio upload silently goes- * back to conditioning the model on a picture of its own waveform.+ * Verify gallery mediaOrigin reaches conditioning defaults so wrapped audio cannot condition on its waveform+ * image.*/const galleryMocks = vi.hoisted(() => ({ resolve: vi.fn(), uploadVideo: vi.fn() }));@@ -119,8 +116,6 @@ const addUploadedVideo = async (mediaOrigin?: string): Promise<VideoReferenceIte);});- // The video picker is the file input that also accepts audio -- audio uploads are how a- // wrapped waveform clip enters the list in the first place.const inputs = [...container.querySelectorAll<HTMLInputElement>('input[type="file"]')];const videoInput = inputs.find((input) => input.accept.includes('audio/*'));diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoComparators.test.ts b/invokeai/frontend/webv2/src/features/video/ui/videoComparators.test.tsindex fa4cc43c61..d0cb9cb80a 100644--- a/invokeai/frontend/webv2/src/features/video/ui/videoComparators.test.ts+++ b/invokeai/frontend/webv2/src/features/video/ui/videoComparators.test.ts@@ -5,11 +5,7 @@ import { describe, expect, it } from 'vitest';import { areVideoValuesEqual } from './videoComparators';-/**- * The comparator is a hand-maintained field list: a field left out of it makes- * the widget judge an edit "unchanged" and skip the write. Each entry that has- * shipped a bug this way earns a case here.- */+/** Missing comparator fields suppress edits; cover each independently editable value. */describe('areVideoValuesEqual', () => {const fl2vaBase: MainModelConfig = {base: 'minimax-h3',diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoComparators.ts b/invokeai/frontend/webv2/src/features/video/ui/videoComparators.tsindex 23f9f871bf..30798e3425 100644--- a/invokeai/frontend/webv2/src/features/video/ui/videoComparators.ts+++ b/invokeai/frontend/webv2/src/features/video/ui/videoComparators.ts@@ -1,10 +1,6 @@import type { VideoWidgetValues } from '@features/video/core/types';-/**- * Content comparators for the widget's memo boundaries and the mount-time- * reconciler. The widget re-derives `values` on every patch, so equality by- * content — not identity — decides whether a write-back or re-render is due.- */+/** Patches recreate values, so memo and reconciliation boundaries compare content. */const stableStringify = (value: unknown): string => JSON.stringify(value ?? null);diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoConditioningFindInGallery.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoConditioningFindInGallery.browser.test.tsxindex 6a9cfefbbd..d0a25481d4 100644--- a/invokeai/frontend/webv2/src/features/video/ui/videoConditioningFindInGallery.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/videoConditioningFindInGallery.browser.test.tsx@@ -16,14 +16,7 @@ import { VideoFrameImageField } from './VideoFrameImageField';import { VideoSourceClipField } from './VideoSourceClipField';import { VideoUiProvider, type VideoUiAdapter } from './VideoUiContext';-/**- * The two conditioning fields the Ref2VA reference list does not cover: the- * keyframe slots, whose badge comes from the shared gallery media slot, and the- * initial video, badged on its start bound alone because both trim thumbs are- * frames of one clip. Both hand a kind+name to the port, and a video asked for- * as an image resolves against the wrong endpoint and dies in a rejected- * promise.- */+/** Conditioning slots must pass media kind with name; video names cannot resolve through the image endpoint. */const i18n = i18next.createInstance();await i18n.use(initReactI18next).init({fallbackLng: 'en',@@ -142,8 +135,7 @@ describe('video conditioning find-in-gallery badges', () => {it('reveals the initial video as a video, once, from its start bound', async () => {await render(<VideoSourceClipField sourceVideo={CLIP} onChange={vi.fn()} />);- // The end bound shows the same clip, so a second badge there would be a- // second control with one destination — and one name to tell them apart.+ // Both bounds reference one clip; expose one find control.const bounds = findButtons('source.mp4');expect(bounds).toHaveLength(1);diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoReferenceFindInGallery.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoReferenceFindInGallery.browser.test.tsxindex a4878d3dfe..c176eb94f0 100644--- a/invokeai/frontend/webv2/src/features/video/ui/videoReferenceFindInGallery.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/videoReferenceFindInGallery.browser.test.tsx@@ -13,13 +13,7 @@ import { userEvent } from 'vitest/browser';import { VideoReferenceListField } from './VideoReferenceListField';import { VideoUiProvider, type VideoUiAdapter } from './VideoUiContext';-/**- * A reference card carries ONE find badge — an image reference's poster, or the- * START bound of a video reference, whose two trim thumbs are frames of a single- * gallery record. It reveals the card's own media, so the kind has to travel- * with the name: a video asked for as an image resolves against the wrong- * endpoint and the gesture dies in a rejected promise, silently.- */+/** Each reference exposes one find action; pass kind with name so videos resolve against the video endpoint. */const i18n = i18next.createInstance();await i18n.use(initReactI18next).init({fallbackLng: 'en',@@ -104,19 +98,8 @@ const render = async (): Promise<void> => {};/**- * Park the cursor clear of the harness, BEFORE anything renders. The runner's- * pointer is stationary at the viewport origin and this list renders into the- * top-left corner, so the first card's thumbnail sits under it — and a hover- * badge whose whole contract is "hidden until this thumbnail is hovered" is- * then revealed before the test has touched anything. Mirrors- * `resetPointerAndScroll` in the rebalance-bars suite, which hit the same- * stationary cursor.- *- * Parking first, rather than after mounting, is what keeps the resting state- * readable: un-hovering something already on screen starts the reveal's- * fade-out, and the resting opacity then answers for where that animation has- * got to. A badge mounted un-hovered has no previous value to transition from,- * so it is simply at rest.+ * Park the pointer before mount: an origin hover would reveal the first badge, and moving afterward starts a fade+ * that invalidates resting-opacity assertions.*/const parkPointer = async (): Promise<void> => {const parking = document.createElement('div');@@ -162,19 +145,8 @@ describe('video reference find-in-gallery badges', () => {await parkPointer();await render();- // Each badge is scoped to its own thumbnail's `.group`, which is the whole- // mechanism that makes it a hover overlay rather than permanent chrome. A- // mouse hover cannot be synthesised, but focus-within comes from the same- // ancestor, so it proves the scoping either way.- //- // The focus sweep below reads `pointer-events` rather than `opacity`: the- // reveal sets both, under the same selector, but only opacity is- // transitioned — so opacity answers for where the animation has got to,- // while pointer-events answers for which badge the CSS considers revealed.- // That is the actual claim, and it is true the instant focus lands rather- // than a few frames later. Opacity is still worth asserting at rest, where- // nothing is animating: it is what makes the badge invisible rather than- // merely inert.+ // Focus-within exercises the same thumbnail scope as hover. Assert pointer-events during focus changes because+ // opacity transitions; assert opacity only at rest.const badges = [...findButtons('still.png'), ...findButtons('clip.mp4')];const revealed = () => badges.map((button) => getComputedStyle(button).pointerEvents);@@ -182,9 +154,6 @@ describe('video reference find-in-gallery badges', () => {expect(revealed()).toEqual(['none', 'none']);expect(badges.map((button) => getComputedStyle(button).opacity)).toEqual(['0', '0']);- // Each in turn: the one holding focus is revealed and only it. A badge whose- // thumbnail lost its `.group` would never be revealed; a `.group` hoisted to- // the card would reveal both at once.for (const [index] of badges.entries()) {await act(() => {badges[index]!.focus();@@ -197,8 +166,7 @@ describe('video reference find-in-gallery badges', () => {it('reveals a video reference as a video, once, from its start bound', async () => {await render();- // The end bound shows the same clip, so a second badge there would be a- // second control with one destination — and one name to tell them apart.+ // Both bounds reference the same clip; expose one find control.const bounds = findButtons('clip.mp4');expect(bounds).toHaveLength(1);diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoReferencePlaySpan.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoReferencePlaySpan.browser.test.tsxindex bf91ce3465..04bb4021d3 100644--- a/invokeai/frontend/webv2/src/features/video/ui/videoReferencePlaySpan.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/videoReferencePlaySpan.browser.test.tsx@@ -16,12 +16,7 @@ import { VideoReferenceListField } from './VideoReferenceListField';import { VideoSourceClipField } from './VideoSourceClipField';import { VideoUiProvider, type VideoSpanPlaybackState, type VideoUiAdapter } from './VideoUiContext';-/**- * The trim rows show two still frames, which cannot say what is between them — and for an- * audio reference, whose frames are a drawing of the sound, say nothing at all. The play- * button is the panel's answer, and what it has to get right is the arithmetic: the trim- * is inclusive frame indices, Preview wants seconds.- */+/** Playback converts inclusive frame bounds to seconds, including the full final frame. */const galleryMocks = vi.hoisted(() => ({ resolve: vi.fn() }));@@ -189,8 +184,6 @@ const RetrimmableHarness = () => {);};-// The source clip field is built on the gallery media slot, which reads the-// gallery UI port for its picker and error reporting.const galleryAdapter = {gallery: { selectBoard: vi.fn(), selectItem: vi.fn(), setView: vi.fn() },galleryValues: {},@@ -270,8 +263,7 @@ describe('video reference span playback', () => {{ kind: 'video', name: 'clip.mp4' },expect.any(AbortSignal) as AbortSignal);- // Frames 32..47 inclusive at 16 fps: the window ends at the far edge of frame 47, so- // the last selected frame is played rather than cut short.+ // Inclusive frames 32..47 end at the far edge of frame 47.expect(playVideoSpanInPreview).toHaveBeenCalledWith({endSeconds: 3,item: galleryVideoItem,@@ -280,17 +272,13 @@ describe('video reference span playback', () => {});it('offers the control only where there is something to play', async () => {- // An image reference is already fully visible as its own thumbnail; there is no window- // to audition, so the control is absent rather than dead.await render([imageReference]);expect(playButtons()).toHaveLength(0);});it("plays the Initial Video clip's window, and stays live while the field is disabled", async () => {- // Playing changes nothing, so a clip the user can see is one they can audition — the- // field is disabled whenever a first-frame image or a full reference stack blocks- // EDITING it, and its trim rows stay on screen throughout.+ // Editing gates must not prevent auditioning a visible clip.await renderTree(<InitialVideoHarness disabled />);const [button] = playButtons();@@ -309,9 +297,7 @@ describe('video reference span playback', () => {button!.focus();await press(button!);- // aria-disabled, never the DOM's `disabled`: disabling a focused button blurs it to- // <body>, which would drop a keyboard user out of the card for the length of a- // network round trip.+ // Native disabled would blur the focused button during the request; aria-disabled preserves focus.expect(button?.getAttribute('aria-disabled')).toBe('true');expect(button?.disabled).toBe(false);expect(document.activeElement).toBe(button);@@ -332,8 +318,7 @@ describe('video reference span playback', () => {await render([videoReference(), videoReference({ startFrame: 0, endFrame: 15 })]);const [first, second] = playButtons();- // The player reporting on somebody else's request — a loop the sibling card started,- // or one from before this session — is not this button's to stop.+ // Another request's playback token is not this button's to stop.await act(() => reportPlayback({ isPlaying: true, pause: pausePlayback, token: 3 }));expect(pauseButtons()).toHaveLength(0);@@ -364,8 +349,7 @@ describe('video reference span playback', () => {await press(button!);expect(pausePlayback).toHaveBeenCalledTimes(1);- // The user moved the window while it sat paused. The next press is a fresh request for- // the window the rows now show — from its start — not a resume of the old one.+ // A re-press starts the current trim, not the previously paused window.playVideoSpanInPreview.mockReturnValue(8);await act(() => retrim?.({ endFrame: 79, startFrame: 64 }));await press(button!);@@ -389,9 +373,7 @@ describe('video reference span playback', () => {await press(button!);expect(pauseButtons()).toHaveLength(0);- // Preview could not be raised for the re-press (no center view after a layout change):- // nothing was asked of the player, whose loop is still armed under the first request.- // A native play resumes that loop, and it is still this button's to stop.+ // Preview refusal leaves the first loop armed and owned by this button.playVideoSpanInPreview.mockReturnValueOnce(null);await press(button!);expect(playVideoSpanInPreview).toHaveBeenCalledTimes(2);diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoReferencePromptLabels.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoReferencePromptLabels.browser.test.tsxindex 987d9c9ea9..bd778f1215 100644--- a/invokeai/frontend/webv2/src/features/video/ui/videoReferencePromptLabels.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/videoReferencePromptLabels.browser.test.tsx@@ -12,12 +12,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { VideoReferenceListField } from './VideoReferenceListField';import { VideoUiProvider, type VideoUiAdapter } from './VideoUiContext';-/**- * Each card is badged with the labels the prompt must use for that reference. The numbers- * come from three independent per-modality counters over the WHOLE list, so they are not a- * card's own business: a move renumbers cards the user never touched, and the cards are- * memoized against exactly that kind of re-render.- */+/** Modality counters span the whole list; reordering must update labels even on otherwise unchanged memoized cards. */const i18n = i18next.createInstance();await i18n.use(initReactI18next).init({fallbackLng: 'en',@@ -120,12 +115,7 @@ const badges = (): string[] =>.map((badge) => badge.textContent!).filter((text) => /^<(?:Picture|Video|Audio) \d+>$/.test(text));-/**- * Each card's accessible name, in card order: the labels it carries followed by its media- * name. Asserting the pairing rather than a flat list of badges is what catches a card- * rendering someone else's labels — which is the failure an identity-keyed, memoized list- * of same-named references can produce.- */+/** Assert labels paired with media names so reused same-name cards cannot display another reference's labels. */const cards = (): string[] =>// `[aria-label]` narrows past the unnamed groups Chakra's own slider and select markup adds.[...host.querySelectorAll<HTMLElement>('[role="group"][aria-label]')].map((card) => card.getAttribute('aria-label')!);@@ -151,11 +141,9 @@ describe('video reference prompt labels', () => {videoReference('b-roll.mp4', 'video'),]);- // The badges carry the tokens verbatim, brackets included -- they are what the user- // copies into the prompt.+ // Badges must preserve the encoder's token syntax, including brackets.expect(badges()).toEqual(['<Audio 1>', '<Picture 1>', '<Video 1>', '<Audio 2>', '<Picture 2>', '<Video 2>']);- // An audio-only reference takes an audio number and no video number; the sounded video- // takes one from each counter, so neither number is the card's position in the list.+ // Modality counters are independent of card position.expect(cards()).toEqual(['<Audio 1> voiceover.mp4','<Picture 1> portrait.png',@@ -177,17 +165,11 @@ describe('video reference prompt labels', () => {expect(option).not.toBeNull();await act(() => option!.click());- // Dropping the FIRST reference's image track hands its video number to the second card,- // whose own reference and slot are untouched -- the card is memoized, so its labels have- // to arrive as props that change, not be derived from what it holds.+ // Removing this image track renumbers an otherwise unchanged memoized sibling.expect(cards()).toEqual(['<Audio 1> v1.mp4', '<Video 1> <Audio 2> v2.mp4']);});it('keeps the token in prompt order inside an RTL document', async () => {- // The brackets are bidi-neutral, so in an RTL paragraph they flip and the badge reads- // '>Picture 1<' -- a token the encoder will not match, shown to a user who is being- // told to type it. Arabic and Hebrew set dir on the document root (I18nController), and- // widgets.video has no translations yet, so these badges DO get rendered in an RTL- // document today.+ // In RTL text, bidi-neutral brackets can reverse the encoder token; badges must retain LTR token order.host.dir = 'rtl';await render([imageReference('portrait.png')]);@@ -198,9 +180,7 @@ describe('video reference prompt labels', () => {});it('moves the labels with the card, not with the slot', async () => {- // Twins: same media name, so the list's identity keys collide by design and React- // reuses the card instances in place rather than moving them. Only the labels arriving- // as props keeps the pairing honest through the move.+ // Same-name cards reuse their instances; label props must still follow the reordered references.await render([videoReference('twin.mp4', 'video'), videoReference('twin.mp4', 'video_audio')]);expect(cards()).toEqual(['<Video 1> twin.mp4', '<Video 2> <Audio 1> twin.mp4']);diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoReferenceReorderFocus.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoReferenceReorderFocus.browser.test.tsxindex 3c40711724..29805d79b8 100644--- a/invokeai/frontend/webv2/src/features/video/ui/videoReferenceReorderFocus.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/videoReferenceReorderFocus.browser.test.tsx@@ -12,13 +12,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { VideoReferenceListField } from './VideoReferenceListField';import { VideoUiProvider, type VideoUiAdapter } from './VideoUiContext';-/**- * Reordering the Ref2VA reference stack must not cost the user their place on- * the keyboard. Two ways it used to: the list was keyed by index, so every move- * remounted the cards it touched and the pressed arrow's DOM node was destroyed- * outright; and a move that lands on an end disables that arrow, which cannot- * then hold focus.- */+/** Reordering must preserve card identity and transfer focus when the pressed arrow becomes disabled. */const i18n = i18next.createInstance();await i18n.use(initReactI18next).init({fallbackLng: 'en',@@ -130,8 +124,6 @@ describe('video reference reorder focus', () => {expect(order()).toEqual(['a.png', 'c.png', 'b.png']);- // Same element still focused: the card survived the reorder rather than- // being remounted underneath the user.expect(document.activeElement).toBe(up);expect(buttons('Move reference up')[1]).toBe(up);});@@ -151,9 +143,7 @@ describe('video reference reorder focus', () => {});it('leaves focus alone when the arrow was pressed without holding focus', async () => {- // Pressing a button does not focus it in every browser, so the handler can- // run with the caret still in the prompt. Handing focus to an arrow then- // would haul the user out of what they were typing.+ // Some browsers dispatch clicks without focusing the button; preserve focus in the prompt.await render(['a.png', 'b.png', 'c.png']);const field = document.querySelector('[aria-label="Prompt"]') as HTMLInputElement;@@ -167,18 +157,13 @@ describe('video reference reorder focus', () => {});it('never fires a stale handoff after a dropped write', async () => {- // The reviewer's path: the write is dropped, `memo` keeps the card from- // rendering, so the arm survives. Much later an unrelated change disables- // that same arrow -- and the stale arm must not haul focus out of whatever- // the user is doing by then.+ // A dropped write must not leave an arm that steals focus when a later change disables the arrow.let drop = true;let mutate: (next: string[]) => void = () => undefined;const StaleHarness = () => {const [names, setNames] = useState(['a.png', 'b.png', 'c.png']);- // Handing the setter out is a side effect, so it happens in an effect --- // `act` has flushed it by the time the test reaches for `mutate`.useEffect(() => {mutate = setNames;}, []);@@ -235,8 +220,6 @@ describe('video reference reorder focus', () => {await act(() => field.focus());- // Now remove the first reference, which shifts this card to the top and- // disables the arrow it armed.drop = false;await act(() => mutate(['b.png', 'c.png']));@@ -246,10 +229,7 @@ describe('video reference reorder focus', () => {});it('keeps focus when a card moves PAST a duplicate of another reference', async () => {- // The same clip can legitimately appear twice, sampled over two different- // windows, so the key disambiguates by occurrence. Moving `tail` down past- // the second `dup` re-numbers nothing under that scheme; a name+index key- // would have shifted `tail` from 1 to 2 and remounted it.+ // Repeated clips use occurrence keys; moving tail past the second duplicate must preserve tail's identity.await render(['dup.png', 'tail.png', 'dup.png', 'end.png']);const down = buttons('Move reference down')[1];diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.tsindex ed19345bd8..221f3e7cfd 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts@@ -844,9 +844,7 @@ describe('integer Literal enum values in the compiled graph', () => {},};- // End-to-end companion to the template test: whatever shape the template- // takes, the value that reaches the backend has to be the number the- // `Literal[256, 512]` annotation accepts.+ // Compile template literals to backend-accepted numbers, not numeric strings.it('sends a numeric Literal enum value', () => {const parsedTemplates = parseOpenApiToTemplates(literalEnumSchema);const parsedTemplate = parsedTemplates.max_seq_len_invocation;@@ -863,9 +861,7 @@ describe('integer Literal enum values in the compiled graph', () => {});});- // The default is only half the wire path: whatever the field widget offers- // has to compile to a number too, otherwise picking an option from the- // dropdown reintroduces the rejected string.+ // Compile selected dropdown values numerically as well as defaults.it('sends a numeric value for the option the field widget offers', () => {const parsedTemplates = parseOpenApiToTemplates(literalEnumSchema);const parsedTemplate = parsedTemplates.max_seq_len_invocation;diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.tsindex 7834282d8b..99cf890d4e 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts@@ -25,10 +25,8 @@ import { isInvocationNode } from './types';import { hasAnyCycle } from './validation';/**- * Compiles the project graph document into the immutable, queue-facing- * `GraphContract`. Ported from the legacy `buildNodesGraph`, with connector- * resolution and without batch handling (batch/generator nodes are rejected by- * readiness until batching lands).+ * Compile documents to immutable queue GraphContract with connector resolution; readiness rejects unsupported+ * batch/generator nodes.*//** Client-resolved batch/generator nodes from the legacy editor; executing them server-side is meaningless. */@@ -325,14 +323,8 @@ export const compileProjectGraph = (};/**- * The inputs that carry a seed mode: the scalar integer a node declares as `seed`- * over the full seed range. Read from the template alone, so an editable label- * cannot turn an ordinary integer into a seed, and a provider's own-range `seed`- * keeps its plain control instead of wrapping at a bound it never had.- *- * Seed policy lives here rather than in `fields.ts` because it is the one place- * the workflow core depends on the platform seed arithmetic at runtime: the- * shared field/document helpers stay in the lighter utility chunk every overlay loads.+ * Seed modes require a template-declared scalar seed with the full range. Keep seed arithmetic here so shared+ * field utilities remain lightweight.*/export const isSeedInputField = (template: FieldInputTemplate): boolean =>template.name === 'seed' &&@@ -366,12 +358,8 @@ export interface WorkflowSeedPlan {}/**- * Decides every seed input's start for a submission of `batchCount` runs. Seeds- * vary per queued run, not per iteration of a loop inside a run. A random input- * draws its start here and the runs step consecutively from it, like Generate's- * random mode, while the entered seed stays in reserve; a stepping input counts- * from the authored seed and reports where the field goes afterwards. Expansion- * into per-run values happens at send time from these starts, never redrawing.+ * Choose seed starts once per submission and expand runs deterministically at send time. Random preserves the+ * entered seed; stepping reports the next authored value.*/export const planWorkflowSeeds = (document: ProjectGraphState,diff --git a/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.tsindex e20d65b512..9c5ffd68b4 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.ts@@ -640,10 +640,8 @@ describe('Call Saved Workflow dynamic fields', () => {});describe('Call Saved Workflow labels across a reload', () => {- // Consequence of the dropped `labelOverride`: on a parent whose dynamic- // templates were never persisted, the first reconcile after a reload resets- // the user's label to the child's generated one, and the library autosaver- // then writes that loss back with no user action.+ // Preserve labelOverride through reload so dynamic-template reconciliation and autosave cannot erase user+ // labels.it('keeps a user label when a template-less parent is saved and reloaded', () => {const callNode = buildInvocationNode(callSavedWorkflowTemplate, { x: 0, y: 0 });diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.tsindex 3816756296..13789177a2 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/document.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.ts@@ -29,12 +29,6 @@ import {import { getConnectorDeletionSpliceConnections } from './connectors';import { isInvocationNode, isNotesNode } from './types';-/**- * Pure operations on the project graph document. The workbench reducer- * delegates all workflow edits to `projectGraphReducer` so the document logic- * stays testable and `workbenchState.ts` only grows one action case.- */-const now = (): string => new Date().toISOString();export const createWorkflowId = (prefix: string): string =>@@ -290,10 +284,6 @@ const removeNodeFieldElements = (form: WorkflowForm, removedNodeIds: Set<string>.filter((element) => element.type === 'node-field' && removedNodeIds.has(element.data.fieldIdentifier.nodeId)).reduce((nextForm, element) => removeFormElement(nextForm, element.id), form);-// #endregion--// #region Document reducer-export type ProjectGraphAction =| { type: 'addNode'; node: WorkflowNode }| { type: 'addNodeAndEdge'; node: WorkflowNode; edge: WorkflowEdge | WorkflowEdge[] }@@ -652,8 +642,7 @@ const applyProjectGraphAction = (document: ProjectGraphState, action: ProjectGra}));}case 'setFieldSeedMode': {- // Fixed is the absent default, so choosing it leaves the instance exactly as- // pre-seed-mode documents (and legacy readers) write it.+ // Omit fixed mode to preserve legacy document shape and default behavior.return setFieldInstance(document, action.nodeId, action.fieldName, (instance) => {const { seedMode: _, ...withoutSeedMode } = instance;return action.seedMode === 'fixed' ? withoutSeedMode : { ...instance, seedMode: action.seedMode };diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.tsindex 560db5f3e7..b5198fd247 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts@@ -202,8 +202,7 @@ describe('LoRA collection values', () => {});it('preserves unreadable items verbatim so an edit cannot silently delete them', () => {- // The widget writes back the list it is given; dropping or blanking these here would make one- // click on an unrelated row destroy a hand-authored entry.+ // Keep unreadable collection entries so editing another row cannot destroy hand-authored data.const items = [LORA_ENTRY, { lora: { key: 'ghost' }, weight: 1 }, null, 'lora'];expect(toLoraFieldCollectionList(items)).toEqual(items);diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.tsindex 033e6f4295..11f30396e1 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts@@ -10,12 +10,6 @@ export const getEffectiveWorkflowFieldDescription = (? (instance.description ?? ''): instance?.description || template?.description || '';-/**- * Field-kind helpers shared by the node editor and the Linear UI panel:- * which field types render direct-input controls, and how handles/edges are- * tinted by type so connections stay readable.- */-/** Field types with a direct-input widget. Everything else is connection-only. */const STATEFUL_FIELD_TYPE_NAMES = new Set(['BoardField',@@ -25,8 +19,8 @@ const STATEFUL_FIELD_TYPE_NAMES = new Set(['FloatField','ImageField','IntegerField',- // The LoRA collection loaders take `LoRAField | list[LoRAField]`; the widget edits that list- // inline so a node can apply several LoRAs without a chain of Select LoRA / Collect nodes.+ // Collection loaders accept scalar or list LoRA fields; edit lists inline without extra selector/collector+ // nodes.'LoRAField','ModelIdentifierField','SchedulerField',@@ -141,11 +135,7 @@ export interface LoraFieldCollectionEntry {weight: number;}-/**- * Every field of the identifier is required, because that is what the backend's own- * `ModelIdentifierField` requires: a key-only entry renders as a nameless row and is rejected at- * enqueue time with a 422 that names nothing useful, so it is better treated as unreadable here.- */+/** Require complete backend model identifiers; key-only entries cannot render meaningfully or enqueue successfully. */export const isLoraFieldCollectionEntry = (value: unknown): value is LoraFieldCollectionEntry => {if (typeof value !== 'object' || value === null) {return false;@@ -161,13 +151,8 @@ export const isLoraFieldCollectionEntry = (value: unknown): value is LoraFieldCo};/**- * The collection loaders accept `LoRAField | list[LoRAField]`, so a stored value may be a single- * entry, a list, or absent. The widget always authors a list; normalizing on read keeps imported- * workflows and hand-edited JSON rendering the same way.- *- * Items are returned as-is, including ones `isLoraFieldCollectionEntry` rejects. The widget writes- * the list it is given straight back on the next edit, so discarding or blanking an unreadable item- * here would let one click on an unrelated row silently destroy a hand-authored entry.+ * Normalize absent/scalar/list values into lists without discarding unreadable entries, which subsequent edits+ * must preserve.*/export const toLoraFieldCollectionList = (value: unknown): unknown[] => {if (Array.isArray(value)) {diff --git a/invokeai/frontend/webv2/src/features/workflow/core/graphLayout.ts b/invokeai/frontend/webv2/src/features/workflow/core/graphLayout.tsindex 9dbca556a8..4915acddcb 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/graphLayout.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/graphLayout.ts@@ -1,9 +1,4 @@-/**- * Generic node/edge layout helpers shared by the graph preview flow renderer- * (`ui/graph-preview/GraphPreviewFlow.tsx`) and, eventually, Task 7's project- * graph → preview converter. Deliberately xyflow-free and contract-free —- * callers adapt their own node/edge shapes to the minimal shapes below.- */+/** Keep layout helpers independent of xyflow and UI contracts; callers adapt minimal node/edge shapes. */export interface LayoutGraphNode {id: string;diff --git a/invokeai/frontend/webv2/src/features/workflow/core/graphToDocument.ts b/invokeai/frontend/webv2/src/features/workflow/core/graphToDocument.tsindex a3d3497989..14d7119b66 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/graphToDocument.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/graphToDocument.ts@@ -3,11 +3,7 @@ import type { InvocationTemplates, ProjectGraphState, WorkflowEdge, WorkflowInvoimport { buildInvocationNode, createProjectGraph, createWorkflowId } from './document';import { getLayeredPositions } from './graphLayout';-/**- * Structural shape of the read-only preview graph (Task 1's contract graph,- * as rendered by `GraphPreviewFlow.tsx`). Kept structural rather than- * importing the ui contract so this module stays a pure `core` dependency.- */+/** Use a structural preview shape so core does not import UI contracts. */export interface PreviewGraphLike {label?: string;nodes: Array<{ id: string; type: string; inputs: Record<string, unknown> }>;@@ -33,9 +29,7 @@ export const previewGraphToDocument = (): PreviewGraphDocumentResult => {const skippedNodeTypes: string[] = [];const seenSkippedTypes = new Set<string>();- // Positions are derived from the full graph (skipped nodes still occupy a- // depth/row), matching Task 6's documented behavior rather than inventing- // a hint mechanism to exclude them.+ // Lay out the full graph, including positions reserved by skipped nodes.const positions = getLayeredPositions(graph.nodes.map((node) => ({ id: node.id })),graph.edges.map((edge) => ({ sourceNodeId: edge.sourceNodeId, targetNodeId: edge.targetNodeId }))diff --git a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.tsindex ed6d5b914e..67486738c7 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts@@ -199,11 +199,7 @@ const allocateNodeId = (graph: WorkflowBackendGraph, base: string): string => {return `${base}-${suffix}`;};-/**- * Builds a throwaway backend graph that feeds one workflow image input and- * captures one workflow image output. The editable workflow document is never- * mutated.- */+/** Compile a temporary input/output capture graph without mutating the editable document. */export const buildLayerWorkflowGraph = (options: BuildLayerWorkflowGraphOptions): BuiltLayerWorkflowGraph => {const { document, imageName, input, output, templatesSnapshot } = options;diff --git a/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.test.tsindex cfad096c18..60a016fd41 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.test.ts@@ -17,10 +17,7 @@ describe('parseWorkflowTags', () => {describe('mergeTagCountsByCase', () => {it("takes one variant's count, not their sum, because backend counts are already case-insensitive", () => {- // `counts_by_tag` counts each requested tag with `tags LIKE '%tag%'`, and- // SQLite's LIKE is case-insensitive — so the row for 'sdxl' and the row for- // 'SDXL' are both the full total over the *same* two workflows. Summing- // them showed "sdxl 4" for a library holding two.+ // Case variants already count the same workflows under SQLite LIKE; summing would double-count.expect(mergeTagCountsByCase([{ count: 2, tag: 'sdxl' },@@ -43,8 +40,7 @@ describe('mergeTagCountsByCase', () => {});it('takes the largest count if the variants ever disagree', () => {- // They should not, given the backend's LIKE semantics — but a merged chip- // that under-reports is worse than one that is merely robust.+ // Use the maximum variant count even if backend case-insensitive totals unexpectedly differ.expect(mergeTagCountsByCase([{ count: 3, tag: 'Upscaling' },diff --git a/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.ts b/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.tsindex 31a6e5f66b..12321853ad 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.ts@@ -1,10 +1,4 @@-/**- * Workflow library tag helpers. The backend stores a record's tags as one- * comma-separated string and reports per-tag counts as a plain map, so both- * shapes need the same normalization everywhere they are rendered: split and- * trim exactly like the record service does, and drop tags no workflow in the- * current category carries.- */+/** Normalize comma-separated tags like the backend and omit tags absent from the current category. */export interface WorkflowTagCount {tag: string;@@ -24,21 +18,8 @@ export const parseWorkflowTags = (tags: string | null | undefined): string[] =>};/**- * Folds rows that differ only in casing into one chip. The backend reports one- * row per *stored* casing, so a library where some workflows say `sdxl` and- * others `SDXL` gets two rows for what is, to the user, one tag.- *- * The merged count is the **maximum** of the variants, never their sum: the- * backend counts each requested tag with `tags LIKE '%tag%'`, and SQLite's LIKE- * is case-insensitive, so every variant's count is *already* the full- * case-insensitive total — the same workflows, counted once per casing. Summing- * them showed "sdxl 4" over two workflows. Given those semantics the variants- * are equal anyway; taking the max just refuses to be wrong if they ever drift.- *- * The label is the casing of the biggest contributing row, ties broken- * lexicographically — and since equal counts are the normal case, that tiebreak- * is what actually decides, which keeps the chip stable whatever order the- * backend returned.+ * Merge case variants using maximum count, not sum, because LIKE totals overlap. Choose largest-count casing,+ * breaking ties lexicographically for stable labels.*/export const mergeTagCountsByCase = (counts: readonly WorkflowTagCount[]): WorkflowTagCount[] => {const merged = new Map<string, WorkflowTagCount>();diff --git a/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.test.tsindex da8a038151..c26e96356c 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.test.ts@@ -19,11 +19,6 @@ import {type WorkflowModelRequirement,} from './modelRequirements';-/**- * Fixture helpers mirror `graphToDocument.test.ts`: minimal templates and- * documents built inline rather than mocking the module under test.- */-const fieldInput = (name: string, overrides: Partial<FieldInputTemplate> = {}): FieldInputTemplate => ({default: undefined,description: '',diff --git a/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.ts b/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.tsindex a6a76b8263..87f82ed552 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.ts@@ -4,13 +4,8 @@ import { isLoraFieldCollectionEntry, isModelFieldType, toLoraFieldCollectionListimport { isInvocationNode } from './types';/**- * "Which models does this workflow need, and are they installed?" — pure- * extraction from a project graph document plus template metadata, and pure- * resolution against injected installed/starter-catalog data. 28 of the 29- * shipped default workflows ship with *blank* model fields: the template's- * `uiModelBase` / `uiModelType` hints on an empty required input (the "slot"- * requirement) are how those workflows say what they need, so slot handling- * is not a fallback path — it's the common case.+ * Extract exact models and template-described empty required slots; blank slots are normal workflow requirements,+ * not merely a fallback.*/export interface WorkflowModelIdentifier {@@ -112,10 +107,6 @@ const buildSlotLabel = (fieldTemplate: FieldInputTemplate, base: string | null,return fieldTemplate.title || fieldTemplate.name;};-// #endregion--// #region Extraction-interface DuckTypedModelValue {key: string;hash?: unknown;@@ -192,11 +183,8 @@ const computePrimaryBase = (requirements: readonly WorkflowModelRequirement[]):};/**- * Walks invocation nodes' model-typed inputs and classifies each as an- * `exact` requirement (a concrete `{ key }` value) or a `slot` requirement- * (an empty *required* field, described by its template's `uiModelBase` /- * `uiModelType` hints). Connection-fed inputs are skipped entirely — the- * upstream node is what actually needs a model, not this pass-through.+ * Classify concrete model identifiers as exact requirements and empty required inputs as slots; skip+ * connection-fed inputs owned upstream.*/export const extractWorkflowModelRequirements = (document: ProjectGraphState,@@ -260,9 +248,8 @@ export const extractWorkflowModelRequirements = (const value = node.data.inputs[fieldTemplate.name]?.value;- // A LoRA collection holds its identifiers one level down, and holds several of them. Without- // this the LoRAs a collection loader applies are invisible to "what does this workflow need",- // even though the same LoRAs wired through Select LoRA nodes are counted.+ // Inspect nested identifiers in LoRA collections so their requirements match equivalent selector-node+ // graphs.if (isLoraCollection) {const entries = toLoraFieldCollectionList(value);@@ -304,10 +291,6 @@ export const extractWorkflowModelRequirements = (return { primaryBase: computePrimaryBase(requirements), requirements };};-// #endregion--// #region Resolution-export interface InstalledModelSummary {key: string;hash: string;@@ -443,12 +426,8 @@ const resolveFromStarter = (};/**- * Resolves each requirement against injected installed/starter-catalog data.- * `exact` requirements match installed models by key, then hash, then- * name+base+type; `slot` requirements match by base (and type, when the- * slot names one). Unmatched requirements fall through to a starter-catalog- * lookup, which reports `installing` when its (or a dependency's) source is- * already being installed.+ * Resolve exact requirements by key, hash, then name/base/type; slots by base/type. Starter fallback reports+ * installing sources, including dependencies.*/export const resolveWorkflowModelRequirements = (requirements: readonly WorkflowModelRequirement[],@@ -482,23 +461,9 @@ export const resolveWorkflowModelRequirements = ();});-// #endregion--// #region Add Models handoff-/**- * What to search for in Add Models to reach the model a requirement is missing- * — `null` when there is nothing to send anyone there for, and the row stays- * plain text.- *- * An already-installed requirement is `null` by design: Add Models searches the- * *starter catalog*, which need not carry a locally installed model's name at- * all, so the link would dead-end on an empty list.- *- * When the catalog can supply the model, its own catalog name is the surest- * query. Otherwise an exact requirement names one model, and a slot names a- * *kind* — whose display label ("FLUX checkpoint") is prose the catalog does- * not index; its raw base (or failing that, raw type) is what it does.+ * Link only missing requirements to Add Models. Prefer catalog names, then exact model names or raw slot+ * base/type; display prose is not searchable taxonomy.*/export const getAddModelsSearchTerm = (resolved: ResolvedModelRequirement): string | null => {if (resolved.status === 'installed') {diff --git a/invokeai/frontend/webv2/src/features/workflow/core/types.ts b/invokeai/frontend/webv2/src/features/workflow/core/types.tsindex 87a92c8c98..5102285a53 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/types.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/types.ts@@ -1,12 +1,6 @@/**- * Workflow domain types.- *- * The project graph is a *document*: an editable node-and-edge workflow plus a- * form describing its Linear UI. It compiles into the queue-facing- * `GraphContract` only at invocation time, so queued snapshots stay immutable- * while the document keeps evolving. The serialized shape stays compatible- * with the legacy WorkflowV3 format so workflows round-trip between the v6- * editor, the workflow library backend, and this workbench.+ * Editable legacy-compatible workflow documents compile only at invocation time so queued GraphContract snapshots+ * remain immutable.*/import type { SeedMode } from '@platform/core/seed';@@ -27,11 +21,7 @@ export interface FieldInputTemplate {description: string;type: FieldType;required: boolean;- /**- * `internal` marks a field the backend provides rather than the node author declaring it- * (`metadata`). It is a real, connectable input, but it is not part of the node's authored- * signature, so heuristics that pick "the" input for a node must skip it.- */+ /** Internal inputs are backend-provided but connectable; skip them when guessing an authored primary input. */fieldKind: 'input' | 'internal';/** How the field receives data: only via edge, only direct value, or either. */input: 'connection' | 'direct' | 'any';@@ -93,11 +83,7 @@ export interface WorkflowFieldInstance {description?: string;/** True when the description was explicitly changed by the user, including clearing it. */descriptionOverride?: boolean;- /**- * How a seed input (`isSeedInputField`) moves between queued runs. Absent means- * fixed: what every document authored before seed modes did, and what a legacy- * reader hands back after stripping the key.- */+ /** Absent seedMode means fixed, including older documents and legacy readers that strip it. */seedMode?: SeedMode;value?: unknown;}diff --git a/invokeai/frontend/webv2/src/features/workflow/core/validation.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/validation.test.tsindex 67a7edb676..be504980ab 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/validation.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/validation.test.ts@@ -238,9 +238,7 @@ describe('getCompatibleInputTemplate', () => {});it('skips internal-kind inputs when the source type is unresolved', () => {- // `metadata` has no `ui_order` and precedes the authored fields in the schema, so it- // sorts first on every WithMetadata node. With an unresolved source the type check is- // skipped entirely, so without the guard it would bury the node's real input.+ // Unresolved source types must not default to metadata merely because it sorts before authored fields.const baseInput = templates.number.inputs.value;const metadata = {...baseInput,@@ -258,9 +256,7 @@ describe('getCompatibleInputTemplate', () => {});it('still offers an internal-kind input to a source that genuinely matches it', () => {- // Dragging a real MetadataField output onto a save node must land on `metadata` -- and- // this function also decides which nodes the Add Node dialog offers for that drag, so- // excluding internal fields outright would make every WithMetadata node unreachable.+ // Resolved MetadataField outputs must still reach internal metadata inputs and their Add Node candidates.const baseInput = templates.number.inputs.value;const metadataType = { batch: false, cardinality: 'SINGLE' as const, name: 'MetadataField' };const template = {diff --git a/invokeai/frontend/webv2/src/features/workflow/core/validation.ts b/invokeai/frontend/webv2/src/features/workflow/core/validation.tsindex caf02c6161..755997c39c 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/validation.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/validation.ts@@ -21,12 +21,7 @@ import { isConnectorNode, isInvocationNode } from './types';export const LOOP_LINKAGE_FIELD = 'loop_linkage';-/**- * Connection validation, ported from the legacy editor's- * `validateConnectionTypes` / `validateConnection`. Connector nodes are- * pass-through routing nodes: their source type is resolved from the first- * upstream invocation output when one exists.- */+/** Resolve connector passthrough types from the first upstream invocation output before validating connections. */const isSingle = (type: FieldType): boolean => type.cardinality === 'SINGLE';const isCollection = (type: FieldType): boolean => type.cardinality === 'COLLECTION';@@ -184,13 +179,8 @@ export const getCompatibleInputTemplate = (inputTemplates.find((inputTemplate) =>!inputTemplate.uiHidden &&- // `metadata` sorts first on every WithMetadata node (no `ui_order`, and it precedes- // the authored fields in the schema). When the source type could not be resolved we- // skip the type check below entirely and take the first candidate, so it would win- // every time and bury the node's real input. A resolved source type still reaches it- // — dragging an actual MetadataField output onto a save node should land on- // `metadata`, and this function also gates which nodes the Add Node dialog offers- // for a pending connection.+ // Skip internal inputs for unresolved source guesses, but retain them for known matching types such as+ // MetadataField.!(sourceType === null && inputTemplate.fieldKind === 'internal') &&inputTemplate.input !== 'direct' &&(sourceType === null || validateConnectionTypes(sourceType, inputTemplate.type))diff --git a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.tsindex ab3fdb49fb..c5a448ee8f 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts@@ -536,9 +536,7 @@ describe('seed modes in workflow JSON', () => {});describe('field label overrides', () => {- // `serializeInvocationNode` writes `labelOverride` (it structuredClones the- // node data) but `parseWorkflowJson` rebuilds each instance from an explicit- // field list that omits it, so the flag is written and never read back.+ // Round-trip labelOverride through explicit parsing as well as cloned serialization.it('round-trips an explicit label override', () => {const node = buildInvocationNode(template, { x: 0, y: 0 });let doc = createProjectGraph('label-override');diff --git a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.tsindex e23262ad08..f537ea3fbd 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts@@ -14,18 +14,14 @@ import type {import { createWorkflowForm, createWorkflowId } from './document';/**- * Import/export between the project graph document and the legacy WorkflowV3- * JSON format — the format used by workflow files, image-embedded workflows,- * and the backend workflow library. Parsing is tolerant: recoverable problems- * (unknown elements and dangling edges) become warnings instead of failures.+ * Round-trip legacy WorkflowV3 files, metadata, and library records; recover unknown elements and dangling edges+ * as warnings.*/const zXYPosition = z.object({ x: z.number().catch(0), y: z.number().catch(0) }).catch({ x: 0, y: 0 });-// `seedMode` is this workbench's extension of the field instance. The legacy-// editor parses instances through a stripping schema, so a workflow it re-saves-// comes back without the key — every seed reads as fixed again, which is the-// legacy behaviour rather than a corrupted value.+// Legacy schemas strip seedMode; reimport then defaults to fixed rather than treating the missing extension as+// corruption.const zFieldInstance = z.object({description: z.string().optional().catch(undefined),descriptionOverride: z.boolean().optional().catch(undefined),@@ -476,10 +472,8 @@ export const hasMultipleWorkflowReturnNodes = (document: ProjectGraphState): boodocument.nodes.filter((node) => node.type === 'invocation' && node.data.type === 'workflow_return').length > 1;/**- * Serializes the queue/image-metadata projection of a document.- * Runtime-only dynamic templates and current-image decorations must not- * leak into the workflow embedded in a submission. Loop linkage remains- * intact so webv2 can recall the workflow from generated images.+ * Exclude runtime templates and current-image decorations from submitted workflow metadata while preserving+ * recallable loop links.*/export const serializeWorkflowJsonForSubmission = (document: ProjectGraphState): Record<string, unknown> => {const serialized = serializeWorkflowJson(document);diff --git a/invokeai/frontend/webv2/src/features/workflow/data/api.ts b/invokeai/frontend/webv2/src/features/workflow/data/api.tsindex 95e0353ebe..d74afe9543 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/api.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/api.ts@@ -1,10 +1,6 @@import { apiFetch, apiFetchJson } from '@platform/transport/http';-/**- * Client for the backend workflow library (`/api/v1/workflows`). The library- * stores legacy-format WorkflowV3 JSON, so payloads round-trip through- * `workflowJson.ts` on their way in and out of the project graph document.- */+/** Round-trip library WorkflowV3 payloads through workflowJson when crossing the document boundary. */export type WorkflowLibraryCategory = 'user' | 'default';diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.tsindex 7742a207fa..b4f7822dbe 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts@@ -23,13 +23,8 @@ import { getLibraryWorkflowCached, onWorkflowLibraryCacheInvalidated } from './limport { getInvocationTemplatesSnapshot, refreshInvocationTemplates } from './templates';/**- * Browse state for the workflow library dialog. The library is backend-owned- * and can hold thousands of records, so filtering and pagination are server- * side: every filter change is one page-0 request, infinite scroll appends the- * next page, and nothing is filtered locally. What the list endpoint cannot- * answer — node count and model requirements — is enriched in the background- * from the cached workflow payloads, per entry, so cards fill in as they load- * without blocking the grid.+ * Filter and paginate server-side; asynchronously enrich cached payloads per row so node/model details cannot+ * block the grid.*/export type { WorkflowTagCount } from '@features/workflow/core/libraryTags';@@ -93,14 +88,7 @@ const store = createExternalStore<WorkflowLibraryBrowseSnapshot>(INITIAL_SNAPSHOconst initialLoadFlight = createTrailingSingleFlight();const refreshFlight = createTrailingSingleFlight();-/**- * Bumped only when the filter (or the account) changes. A response tagged with- * an older generation was requested for a view the user has moved on from, so- * it is discarded. Two requests for the *same* filter — a cache-invalidation- * refresh racing an infinite-scroll append — are both current, and both- * publish: keying staleness to the request order instead would let the append- * silently swallow the refresh that removed a deleted row.- */+/** Fence responses by filter/account generation, not request order; same-view append and refresh must both publish. */let filterGeneration = 0;const isFilterCurrent = (generation: number, owner: AccountScope): boolean =>@@ -114,12 +102,7 @@ const toEntry = (item: WorkflowLibraryListItem): WorkflowLibraryEntry => ({tags: parseWorkflowTags(item.tags),});-/**- * Rebuilds the entry list from a server response while keeping the identity —- * and the completed enrichment — of every row the server reports unchanged.- * Selectors and memoized cards depend on those identities holding across- * refreshes.- */+/** Preserve unchanged row identity and enrichment across refreshes for selectors and memoized cards. */const mergeEntries = (previous: readonly WorkflowLibraryEntry[],items: readonly WorkflowLibraryListItem[]@@ -157,18 +140,9 @@ const publishPage = (result: WorkflowLibraryPage, mode: 'append' | 'replace'): vpumpEnrichment();};-// #endregion--// #region Enrichment-/**- * Templates are needed to know which inputs are model fields. They are a- * session-lived, shared load, so enrichment waits for one shared attempt- * instead of parsing the schema per entry. A failed attempt is remembered:- * `refreshInvocationTemplates` refetches and reparses the whole OpenAPI- * document, so retrying it per entry would turn one outage into a fetch storm.- * The memo is re-armed by an explicit refresh, a filter change, or an account- * switch.+ * Share one template-load attempt for enrichment and remember failure to prevent fetch storms; explicit+ * refresh/filter/account changes rearm it.*/let templatesFlight: Promise<void> | null = null;let hasTemplateLoadFailed = false;@@ -287,10 +261,6 @@ const pumpEnrichment = (): void => {}};-// #endregion--// #region Fetching-const fetchPage = (filter: WorkflowLibraryBrowseFilter,page: number,@@ -357,11 +327,7 @@ const loadTagCounts = async (category: WorkflowLibraryCategory, owner: AccountSc}};-/**- * One-row probe of the user category. Task 6 auto-switches to the bundled- * defaults on a fresh install, and this answers "does this account have any- * workflows?" without loading the user list.- */+/** Probe one user workflow to decide whether fresh accounts should open bundled defaults. */const probeUserTotal = async (owner: AccountScope): Promise<void> => {if (store.getSnapshot().userTotal !== null) {return;@@ -378,10 +344,6 @@ const probeUserTotal = async (owner: AccountScope): Promise<void> => {}};-// #endregion--// #region Public API-/** Applies a filter patch, resets the accumulated pages, and refetches page 0. */export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBrowseFilter>): void => {const snapshot = store.getSnapshot();@@ -497,11 +459,7 @@ export const useWorkflowLibraryBrowseSelector = store.useSelector;// #endregion-/**- * Any local mutation (save, delete, thumbnail) invalidates the library cache- * and shifts ordering, so the visible pages are refetched. A burst of- * invalidations from one action collapses into a single refresh.- */+/** Coalesce mutation invalidations into one visible-page refresh because local changes can shift ordering. */let isRefreshScheduled = false;onWorkflowLibraryCacheInvalidated(() => {diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.tsindex 12a5c433a8..d20c07f76d 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts@@ -105,9 +105,6 @@ describe('workflow library page cache keying', () => {await cache.listLibraryWorkflowsCached(first);- // A single fetch populates the cache under a tag-order-normalized key, so a- // differently-ordered request for the same tag set reads the same entry- // synchronously without triggering another fetch.expect(api.listLibraryWorkflows).toHaveBeenCalledTimes(1);expect(cache.getCachedWorkflowPage(second)).not.toBeNull();expect(cache.getCachedWorkflowPage(second)).toBe(cache.getCachedWorkflowPage(first));diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.tsindex 8035592d81..26d90fe24e 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts@@ -7,10 +7,8 @@ import {import { getLibraryWorkflow, listLibraryWorkflows, type ListWorkflowsParams, type WorkflowLibraryPage } from './api';/**- * Session-lived cache in front of the workflow library API. The library- * dialog opens instantly on cached pages and revalidates in the background;- * any local mutation (save/delete) invalidates everything since it shifts- * ordering and pagination.+ * Serve cached library pages immediately and revalidate; local mutations invalidate ordering and pagination+ * together.*/const pageCache = new Map<string, WorkflowLibraryPage>();diff --git a/invokeai/frontend/webv2/src/features/workflow/data/runCapture.ts b/invokeai/frontend/webv2/src/features/workflow/data/runCapture.tsindex 50fa1c2abf..b3c0c4421c 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/runCapture.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/runCapture.ts@@ -7,11 +7,8 @@ import { setLibraryWorkflowThumbnail, touchLibraryWorkflowLastRunAt } from './apimport { getLibraryWorkflowCached, invalidateWorkflowLibraryCache } from './libraryCache';/**- * Turns a completed workflow run into the library record's cover image and- * last-run stamp. The Queue reports the run; this module owns everything about- * the library, and every step is best-effort — a capture that fails leaves the- * record exactly as it was and never surfaces to the user, because the run it- * decorates already succeeded.+ * Best-effort capture decorates successful runs with cover/last-run metadata; failures stay silent and must not+ * affect run success.*/export interface RunCaptureDeps {@@ -24,14 +21,8 @@ export interface RunCaptureDeps {}/**- * Gallery owns image URLs, but importing its public surface statically would- * drag the gallery UI (drag-and-drop included) into every bundle that composes- * the queue runtime. The URL is needed once per completed run, so it is loaded- * on demand instead.- *- * Plain `fetch` rather than the authenticated API helper: image media routes are- * served against the path-scoped session cookie — the same credentials the- * gallery's own `<img>` tags use to render this exact URL.+ * Load gallery URL ownership lazily to avoid its UI dependencies in Queue bundles; fetch media with the existing+ * path-scoped cookie.*/const fetchThumbnailBlob = async (imageName: string, signal: AbortSignal): Promise<Blob> => {const { galleryImageUrls } = await import('@features/gallery/utility');@@ -70,9 +61,7 @@ interface PendingCapture {export const createWorkflowRunCaptureSink = (overrides?: Partial<RunCaptureDeps>): QueueWorkflowRunSink => {const deps: RunCaptureDeps = { ...PRODUCTION_DEPS, ...overrides };- // One drain chain per library record. Two runs of the SAME workflow must not- // race their thumbnail uploads (the loser would win the record), while runs of- // different workflows are independent and proceed in parallel.+ // Serialize captures per library record while allowing different workflows to upload independently.const draining = new Map<string, Promise<void>>();// At most one queued capture per record: while one is uploading, a newer run// supersedes any other run still waiting, because only the newest output@@ -121,8 +110,7 @@ export const createWorkflowRunCaptureSink = (overrides?: Partial<RunCaptureDeps>try {await capture(next);} catch {- // Capture is decoration around an already-successful run: one failed- // record must not stop the next run from trying again.+ // A failed capture must not prevent later completed runs from trying again.}}diff --git a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.test.tsindex 49a950a042..3f0ad538cb 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.test.ts@@ -146,12 +146,8 @@ describe('saved workflow detail query policy', () => {});describe('detail queries built without a fetch', () => {- // React Query builds a query during render even when the observer is- // `enabled: false`, and a cancelled fetch reverts to the same state. Picking- // a workflow that is already in the picker list therefore leaves the detail- // query pending/idle with no data and nobody fetching it; with- // `gcTime: Infinity` nothing evicts it either, so the node is pinned at- // 'loading' and Invoke stays disabled until a page reload.+ // A pending/idle detail query may have no active fetch and infinite lifetime; selecting a cached list entry must+ // start its detail request.it('fetches a query that was built but never fetched', () => {expect(shouldFetchSavedWorkflowDetail({ state: { fetchStatus: 'idle', isInvalidated: false, status: 'pending' } })diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.tsindex fac4f74ba7..17559bd970 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts@@ -220,10 +220,7 @@ describe('parseOpenApiToTemplates', () => {});it('keeps internal-kind metadata and board inputs, but drops node attributes', () => {- // `metadata` and `board` are the only two internal-kind properties in the schema, and- // both are real inputs. Without `metadata` a bundled workflow's Core Metadata edge has- // no handle to land on and is dropped on re-save; without `board` the seven bundled- // workflows that expose it get an error in place of a Linear-tab control.+ // Keep internal metadata and board inputs so saved edges and exposed Linear controls survive template parsing.const saveVideo = templates.save_video;expect(Object.keys(saveVideo?.inputs ?? {}).sort()).toEqual(['board', 'latents', 'metadata']);@@ -376,10 +373,7 @@ describe('parseFieldType', () => {});describe('integer Literal enum templates', () => {- // The backend types these fields as `Literal[256, 512]`, so the template- // default has to stay numeric: pydantic rejects the string "512" with- // `literal_error`. Both shapes below are taken from shipped schemas, and- // they reach the default through different branches.+ // Preserve numeric Literal defaults; backend validation rejects equivalent numeric strings.it('keeps a numeric Literal default numeric', () => {const parsed = parseOpenApiToTemplates({components: {@@ -413,10 +407,7 @@ describe('integer Literal enum templates', () => {expect(parsed.max_seq_len_invocation?.inputs.max_seq_len?.default).toBe(512);});- // `flux_text_encoder.t5_max_seq_len` is `Optional[Literal[256, 512]]` and- // required, so its schema default is null and the template falls back to the- // first option instead of the `String(property.default)` branch above. Legacy- // resolves the same fallback to a number.+ // Required nullable numeric literals fall back to a numeric first option, matching legacy parsing.it('keeps a nullable Literal fallback default numeric', () => {const parsed = parseOpenApiToTemplates({components: {diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.tsindex 815d7cce5d..0177509a59 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.ts@@ -17,12 +17,7 @@ import { apiFetchJson, getApiErrorMessage } from '@platform/transport/http';export type { InvocationTemplatesSnapshot } from '@features/workflow/core/types';-/**- * Invocation templates parsed from the backend OpenAPI schema. They are- * session-lived, backend-owned data shared by every workflow surface, so they- * live in an external store (the same pattern as the models library) rather- * than in project state.- */+/** Share backend invocation templates in session-lived external state rather than project documents. */const EMPTY_INVOCATION_TEMPLATES: InvocationTemplatesSnapshot = { error: null, status: 'idle', templates: {} };const store = createExternalStore<InvocationTemplatesSnapshot>(EMPTY_INVOCATION_TEMPLATES);@@ -63,11 +58,7 @@ const refToSchemaName = (ref: unknown): string | null => {const getRef = (schema: JsonObject): string | null => refToSchemaName(schema.$ref);-/**- * Derives the field type from an OpenAPI property schema. Ported from the- * legacy `parseFieldType`; returns null instead of throwing so unparseable- * fields are skipped rather than failing the whole template.- */+/** Return null for unparseable fields so one unsupported property cannot invalidate the whole template. */export const parseFieldType = (schema: unknown): FieldType | null => {if (!isJsonObject(schema)) {return null;@@ -313,23 +304,8 @@ const parseInvocationSchema = (schema: JsonObject, schemas: JsonObject): Invocatcontinue;}- // `internal` covers exactly two properties across the whole schema: `metadata` and- // `board`. Both are real inputs and both must be here.- //- // `metadata`: a workflow that wires a Core Metadata node into a save node needs that- // handle to exist, or the edge is invisible in the editor and dropped on re-save.- //- // `board`: seven bundled workflows expose it as a linear-UI field. The- // exposedFields -> form migration does not check that a field has a template, and- // NodeFieldControl renders "This field no longer exists in the project graph." when it- // does not — so excluding `board` puts a red error in those workflows' Linear tab. It is- // also in v6's templates, which reports a missing-field error for any node instance that- // lacks it. Note the value is not fully honoured yet: the queue runtime re-homes results- // onto the active gallery board after a run, and `toBoardGraphValue` reads 'auto' as "no- // board" where v6 reads it as "the auto-add board".- //- // The node-level attributes (`id`, `type`, `use_cache`, `is_intermediate`) are- // `node_attribute`, so they stay excluded here as well as by RESERVED_INPUT_FIELD_NAMES.+ // Retain internal metadata/board inputs for edges and Linear controls. Exclude node attributes; queue routing+ // still determines final result boards.const isInternal = rawProperty.field_kind === 'internal';if (rawProperty.field_kind !== 'input' && !isInternal) {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/MenuActionItem.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/MenuActionItem.tsxindex 6ee98d5d50..3bb839eba5 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/MenuActionItem.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/MenuActionItem.tsx@@ -2,17 +2,7 @@ import type { ElementType } from 'react';import { Icon, Menu, Stack, Text } from '@chakra-ui/react';-/**- * The one menu-item composition every workflow dropdown renders through: a- * leading glyph, a label, and — for menus whose choices need explaining — a- * second hint line under it. The graph preview's "Open as" menu and the- * library rail's overflow menu keep their own, distinct item *sets*; what they- * share is this layout, which was hand-rolled twice and drifted (icon- * alignment, padding, disabled opacity) between the two.- *- * A hint switches the row to two lines, so the icon top-aligns with the label- * instead of floating centered against both.- */+/** Share workflow menu row geometry; optional hint lines top-align the icon with the primary label. */const DISABLED_ITEM = { opacity: 0.4 } as const;const SINGLE_LINE_LAYOUT = { alignItems: 'center', gap: '2.5', py: '1' } as const;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsxindex 32eecd376d..ed1cf6bb82 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx@@ -16,11 +16,8 @@ import { markLibraryGraphSynced } from './library/librarySyncBridge';import { startWorkflowUiPendingLoadRuntime } from './pendingLibraryWorkflowLoadRuntime';/**- * Consumes pending workflow-load requests from surfaces that cannot reach the- * graph context themselves: the command palette names a library record, an- * image's context menu hands over the workflow it embeds. Either way the- * document is parsed and replaces the project graph — the same load path as- * WorkflowLibraryDialog, minus the dialog.+ * Apply external library or embedded-workflow requests through the same parse-and-replace path as the library+ * dialog.*/export const PendingWorkflowLoader = () => {const { t } = useTranslation();@@ -57,9 +54,7 @@ export const PendingWorkflowLoader = () => {requestWorkflowFitView(document.nodes);if (source.kind === 'library') {- // Same reasoning as the library dialog's load path: the graph just- // loaded is already in sync with the library record it came from, so- // mark it synced before the autosaver's graph-changed effect sees it.+ // Mark freshly loaded library graphs synced before autosave observes them as edits.markLibraryGraphSynced(serializeWorkflowJson(document));void touchLibraryWorkflowOpenedAt(source.workflowId, owner.signal).catch(() => {// Recency bookkeeping only; loading already succeeded.diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsxindex 423e9c86a6..fa1527ef60 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx@@ -26,9 +26,7 @@ const deferred = <T,>() => {return { promise, reject, resolve };};-// The dialogs pull in heavy leaf UI (node search, the library browser, graph-// previews) that is irrelevant to the autosave wiring under test here; stub-// them out so this stays a focused wiring-layer test.+// Stub heavy dialog leaves to isolate autosave wiring.vi.mock('./editor/AddNodeDialog', () => ({ AddNodeDialog: () => null }));vi.mock('./library/WorkflowLibraryDialog', () => ({ WorkflowLibraryDialog: () => null }));vi.mock('./PendingLibraryWorkflowLoader', () => ({ PendingWorkflowLoader: () => null }));@@ -74,17 +72,8 @@ const createGraphWithDuplicateWorkflowReturns = (): ProjectGraphState => ({});/**- * Regression coverage for the StrictMode autosaver-disposal bug: the- * autosaver used to be created once via a `useState` initializer and- * disposed in a separate effect's cleanup. React StrictMode's dev-only- * mount→cleanup→mount simulation ran that cleanup without ever re-running- * the initializer (state is preserved across the simulation, effects are- * not), permanently disposing the one live instance — autosave then- * silently no-oped for the rest of the session. The fix creates AND- * disposes the autosaver within a single mount effect (held in a ref), so- * the simulation produces a fresh, live instance instead. Mounting under a- * real `<StrictMode>` here reproduces that simulation; a test that mounted- * without it would not have caught the bug.+ * Exercise real StrictMode cleanup/remount so autosaver creation and disposal share a lifecycle and cannot leave a+ * permanently disposed instance.*/describe('WorkflowDialogHost library autosave under StrictMode', () => {let host: HTMLDivElement;@@ -151,9 +140,6 @@ describe('WorkflowDialogHost library autosave under StrictMode', () => {expect(updateLibraryWorkflowMock).not.toHaveBeenCalled();- // A graph edit on the already-bound project: a new object identity so the- // dialog host's graph-changed effect fires and schedules the debounced- // autosave.await act(() => {project.setSnapshot({...project.port.getSnapshot(),@@ -450,17 +436,7 @@ describe('WorkflowDialogHost library autosave under StrictMode', () => {expect(updateLibraryWorkflowMock).toHaveBeenCalledTimes(1);});- /**- * The host used to learn about graph edits through a selector- * (`useWorkflowProjectSelector`) feeding a change-detecting effect, which- * re-rendered this component on every graph edit just to notice the- * autosaver should be poked. Edits reach the project store through- * imperative commands, not through this component's own props or state, so- * there is nothing here that needs re-rendering to learn about them — a- * direct store subscription (held in the same mount effect that owns the- * autosaver) can notify the autosaver without forcing React back through- * this component's render.- */+ /** Notify autosave through the project store subscription without rerendering the dialog host on graph edits. */it('schedules an autosave for graph edits made outside React renders', async () => {workflowLibrarySyncStore.setSnapshot({ status: 'idle' });@@ -516,9 +492,7 @@ describe('WorkflowDialogHost library autosave under StrictMode', () => {// (StrictMode doubles it).renderCount = 0;- // Dispatch a graph edit straight through the project store — the same- // path an imperative command handler uses — rather than through a prop- // that would force this component to re-render.+ // Dispatch directly through the store to test imperative edits without prop-driven rerenders.await act(() => {project.setSnapshot({...project.port.getSnapshot(),@@ -531,18 +505,8 @@ describe('WorkflowDialogHost library autosave under StrictMode', () => {});/**- * Account rotation (`accountLifecycle.activate`/`.invalidate`) aborts the- * signal a save started under and synchronously resets- * `workflowLibrarySyncStore` to 'idle' (it is an account-owned resource,- * cleared by `clearResources()` inside `rotateScope`) — but the aborted- * write's rejection lands a tick later, after that reset. A save's own- * `assertAccountScopeCurrent` throw (which turns a late resolution into a- * rejection so a stale write never gets treated as successful) is not- * enough by itself: `runSave()`'s `.catch` still calls `onStatus('error')`- * unconditionally, and without a scope guard on that callback the late- * write would land 'error' in the *next* account's store. Modeled on the- * account-rotation tests in `useScopedAction.browser.test.tsx`, which use- * the real `accountLifecycle` singleton directly.+ * Fence status callbacks across account rotation: aborted saves reject after the new account's synchronous idle+ * reset.*/it('does not park a stale save error in the sync store after an account switch', async () => {const boundGraph = { ...createProjectGraph('workflow-1'), libraryWorkflowId: 'library-workflow-1' };@@ -596,8 +560,6 @@ describe('WorkflowDialogHost library autosave under StrictMode', () => {});});- // Past the debounce: the save has started (captured the pre-switch- // account scope) and is now awaiting the still-pending request below.await act(() =>new Promise<void>((resolve) => {@@ -608,18 +570,12 @@ describe('WorkflowDialogHost library autosave under StrictMode', () => {expect(updateLibraryWorkflowMock).toHaveBeenCalledTimes(1);try {- // Switch accounts mid-flight: aborts the pre-switch scope's signal and- // synchronously resets the sync store to 'idle' via clearResources().accountLifecycle.activate('workflow-dialog-host-test-account', ':user:workflow-dialog-host-test-account');expect(workflowLibrarySyncStore.getSnapshot().status).toBe('idle');- // The deferred request settles after the switch — the same lag as an- // in-flight fetch whose abort rejection arrives after the synchronous- // store reset. Resolving (rather than rejecting) exercises the path- // the review flagged: `assertAccountScopeCurrent` turns this into a- // rejection inside `save()`, so a stale write is never mistaken for a- // successful one.+ // Resolve after rotation to exercise scope-check rejection without leaking an error status into the new+ // account.await act(async () => {request.resolve();await request.promise.catch(() => undefined);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsxindex 4900008ed5..34503e9826 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx@@ -51,10 +51,7 @@ export interface WorkflowGraphPreviewPort {openDocumentInNewProject(document: ProjectGraphState, label: string): void; // fork a preview into a fresh project}-/**- * Workflow's UI port. The context is a dependency-direction port (the feature- * may not import workbench), not a test seam; no second adapter is expected.- */+/** This UI port preserves dependency direction: Workflow cannot import Workbench. */export interface WorkflowUiAdapter {capabilities: WorkflowReadPort<WorkflowCapabilities>;preferences: WorkflowReadPort<WorkflowPreferences>;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxindex 59c33bda95..f633ffa641 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -59,11 +59,8 @@ import {} from './workflowUiStore';/**- * The workflow widget's frame chrome. The label renders the `Workflow / [name]`- * title, where the name is the library trigger; quick actions (add node,- * library, save status) are header icon buttons; everything else contributes to the- * shared widget actions menu via the manifest's `headerMenu`. Dialogs live here- * (always mounted) and are driven through `workflowUiStore`.+ * Keep dialogs mounted here and drive them through workflowUiStore; manifest slots contribute label, quick+ * actions, and shared menu actions.*//** Icon + tooltip for each library sync status, shared by the sync control's error and non-error presentations. */@@ -88,11 +85,8 @@ export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {);}- // In the center the region's view selector already names the widget, so the- // label slot contributes only the `/ [name]` continuation. The name opens the- // library rather than editing in place: switching workflows is the thing- // reached for from a header, and renaming already lives in the details tab —- // an inline field here only invited stray keystrokes into the graph's name.+ // Center chrome already names the widget; append only the library-opening workflow name and leave renaming in+ // Details.const displayName = workflowName || t('widgets.workflow.untitled');return (@@ -200,10 +194,7 @@ export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {</IconButton></Tooltip>) : null}- {/* Center already reaches the library through the header label, which- names the current workflow; a second identical trigger beside it would- be pure duplication. Other regions render a plain `Workflow` label, so- they still need this. */}+ {/* Center labels already open the library; other regions need this separate trigger. */}{region === 'center' ? null : (<Tooltip content={t('widgets.workflow.library')}><IconButton@@ -281,31 +272,8 @@ export const WorkflowDialogHost = () => {translationRef.current = t;}, [notify, t]);- // 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)- // `workflowLibrarySyncStore` back to 'idle', but the aborted write's- // rejection lands a tick later, after that reset. Without this guard,- // `runSave()`'s `.catch` would still write 'error' into the *next*- // account's store — `save()`'s own `assertAccountScopeCurrent` throw stops- // the write from being trusted, but does not by itself stop that throw's- // `onStatus('error')` from landing. `hostScope` is captured once per mount- // — safe because this host remounts every account epoch (keyed by- // `session.accountEpoch` above it in the tree), so a mount-captured scope- // never outlives the account it was captured for.+ // Create/dispose autosave in one mount lifecycle for StrictMode. Subscribe/read directly from the project store;+ // fence status callbacks by mount account scope to reject late-account errors.useEffect(() => {const hostScope = captureAccountScope();let autosaverActive = true;@@ -321,8 +289,6 @@ export const WorkflowDialogHost = () => {return { libraryWorkflowId: graph.libraryWorkflowId, serialized: serializeWorkflowJson(graph) };},save: async (workflowId, serialized) => {- // Same scope discipline as the manual save paths: never let a- // debounced write land in the next account's library.assertAccountScopeCurrent(hostScope);const hasDuplicateWorkflowReturns = hasMultipleWorkflowReturnNodes(projectStore.getSnapshot().projectGraph);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetView.tsxindex db71535dc9..db8fcabfc3 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetView.tsx@@ -8,14 +8,6 @@ import { WorkflowEditorView } from './editor/WorkflowEditorView';import { WorkflowLinearPanel } from './linear/WorkflowLinearPanel';import { useWorkflowProjectSelector } from './WorkflowUiContext';-/**- * The workflow widget's surfaces, per its manifest: the center region is the- * node editor over the project graph; the left region is the Linear UI panel- * bound to the same document; the bottom region is a status-bar entry whose- * expanded panel is the same node editor — handy while another widget (e.g.- * the canvas and its staging area) holds the center.- */-const WorkflowStatusBarItem = () => {const workflowName = useWorkflowProjectSelector((project) => project.projectGraph.name);const isRunning = useWorkflowProjectSelector((project) => project.isWorkflowRunning);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.tsindex be07dd0d92..6a4aad4b0b 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts@@ -5,19 +5,14 @@ import type { ProjectGraphState, XYPosition } from '@features/workflow/core/typeexport type WorkflowRegion = 'left' | 'right' | 'bottom' | 'center' | 'dialog' | 'popover' | 'floating';/**- * Panel regions workflow surfaces may open/select widgets in. Structural- * mirror of workbench's `WidgetRegion` (`workbench/layoutContracts.ts`) —- * the feature may not import workbench, so drift is caught as a tsc error at- * the check site: the `widgets` wiring in `app/WorkflowUiAdapter.tsx`.+ * Mirror Workbench regions structurally; app/WorkflowUiAdapter widgets wiring catches drift without a forbidden+ * feature-to-workbench import.*/export type WorkflowWidgetPanelRegion = 'left' | 'right' | 'bottom' | 'center';/**- * Invocation sources the graph preview can route. Structural mirror of- * workbench's `InvocationSourceId` (`workbench/invocationContracts.ts`) —- * drift is caught as a tsc error at the check sites: the `graphPreview`- * wiring in `app/WorkflowUiAdapter.tsx` and the `GraphPreviewDialog` mount in- * `workbench/widget-frame/WidgetActionsMenu.tsx`.+ * Mirror invocation source IDs structurally; adapter and WidgetActionsMenu wiring provide type checks across the+ * ownership boundary.*/export type WorkflowInvocationSourceId = 'generate' | 'workflow' | 'upscale' | 'video' | 'canvas';@@ -101,12 +96,8 @@ export interface GraphPreviewProvenance {}/**- * The preview dialog's data source, built fresh per render by- * `workbench/widget-frame/graphPreviewSource.ts` from the active surface's- * `sourceId`. `isLive` drives the dialog's "Updates as you change settings."- * subtitle — true for sources that recompile from live project state- * (`generate`, `workflow`), false for sources that only replay their last- * compiled widget graph (`upscale`, `canvas`).+ * isLive distinguishes recompilation from current project state from replaying a saved compiled graph and controls+ * the dialog subtitle.*/export interface GraphPreviewSourceState {graph: WorkflowPreviewGraph | null;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsxindex bce69e9ef9..389df719a4 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsx@@ -27,11 +27,8 @@ import {import { useVirtualizer } from 'react-hook-tanstack-virtual';/**- * Command-palette-style node picker: a centered search dialog whose results- * are grouped into collapsible categories (with counts), mirroring the legacy- * editor's add-node menu. Beta nodes carry the hammer icon. The two UI-only- * nodes (Notes, Current Image) lead as a "Utility" group. No result cap —- * searching auto-expands every group; idle shows all categories collapsed.+ * Searching expands all node groups without capping results; idle groups collapse and UI-only nodes lead in+ * Utility.*/const UTILITY_CATEGORY = 'Utility';@@ -317,8 +314,6 @@ const AddNodeDialogContent = ({const [scrollElement, setScrollElement] = useState<HTMLDivElement | null>(null);useMountEffect(() => registerModalHotkeyLayer('workflow-add-node'));- // While searching, every matching group is force-expanded regardless of the- // manual expand/collapse state, so results are never hidden behind a header.const isSearching = searchTerm.trim().length > 0;const close = useCallback(diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsxindex 7aff7d08a6..e72ef076bb 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx@@ -87,12 +87,8 @@ const settle = async (ms: number) => {};/**- * A child workflow that cannot be fetched has to settle: every node naming it- * ends at `error`, so the Invoke button can say why, and the requests stop.- *- * Regression: the retry bookkeeping is keyed by workflow id while the status it- * drives is per node, so two nodes naming one failing id hand the shared flag- * back and forth, and neither the requests nor the `loading` state ever stop.+ * Shared failing child-workflow IDs must settle every node to error without ping-ponging retries or remaining+ * loading forever.*/describe('CallSavedWorkflowSyncRuntime with an unreachable child workflow', () => {let host: HTMLDivElement;@@ -205,8 +201,7 @@ describe('CallSavedWorkflowSyncRuntime with an unreachable child workflow', () =await expectSettled(readGraph, ['error']);});- // The contrast that pins the cause: the same two nodes, but distinct ids, so- // the shared retry flag is never contended.+ // Distinct workflow IDs isolate retry bookkeeping for otherwise identical nodes.it('settles two nodes naming different unreachable workflows', async () => {const { readGraph } = await mountWith([buildCallNode('call-1', 'missing-a'), buildCallNode('call-2', 'missing-b')]);@@ -352,11 +347,8 @@ describe('CallSavedWorkflowSyncRuntime with an unreachable child workflow', () =});/**- * `savedWorkflowDetailQueryOptions` sets `gcTime: Infinity` and `retry: false`,- * so an errored cache entry never expires and is never revalidated on its own.- * Selecting that workflow again is an explicit user gesture and has to attempt- * the request, otherwise a blip poisons the id for the rest of the session and- * the node blocks Invoke with no way back.+ * Explicit reselection must retry indefinitely cached failures because automatic retries and expiration are+ * disabled.*/const mockWorkflowThatRecoversAfterOneFailure = (workflowId: string) => {const attempts: string[] = [];diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsxindex d2d9ff17e0..d4c5fa5181 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx@@ -14,12 +14,6 @@ import { memo } from 'react';import type { CurrentImageFlowNode as CurrentImageFlowNodeType } from './flowAdapters';-/**- * The legacy `current_image` UI node: a live monitor inside the graph. Shows- * the in-flight denoising preview while a run executes, and the most recently- * generated image otherwise.- */-const getLatestImage = (values: Record<string, unknown>): GeneratedImageContract | null => {const recentImages = Array.isArray(values.recentImages) ? (values.recentImages as GeneratedImageContract[]) : [];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 44789c20c9..fcc7784491 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,14 +41,7 @@ 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?- */+/** Compare rasterized fills because equivalent token/color-mix colors serialize into different color spaces. */const paintedFill = (element: Element): string => {const canvas = document.createElement('canvas');const context = canvas.getContext('2d', { willReadFrequently: true })!;@@ -75,19 +68,13 @@ afterEach(async () => {describe('editor toolbar', () => {it('keeps every button on one shared square toolbar box', async () => {- // The node-opacity button is hand-rolled rather than a ToolbarButton, so it- // never picked up the primitive's size. That is not a local defect: Toolbar- // is a column Stack, and its default stretch alignment let one `sm` button- // widen every sibling while they kept their height, turning the whole- // strip into rectangles wider than the canvas one.+ // Match custom control sizing; one wider child stretches every button in the column toolbar.await render(1);expect(new Set(buttonBoxes())).toEqual(new Set(['28x28']));});it('states node opacity the way the tool buttons state themselves', async () => {- // Its "on" used to be a bespoke accent icon colour, while every other- // button in the strip fills. One control type, one vocabulary.await render(0.5);const opacity = host!.querySelector<HTMLButtonElement>('button[aria-label="Node opacity"]')!;const activeTool = host!.querySelector<HTMLButtonElement>(diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsxindex 6136284a99..8cd24f8f76 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx@@ -15,14 +15,8 @@ import {import { useCallback, useId, useMemo } from 'react';/**- * The editor's single tool strip, docked to the left edge and topped out- * directly beneath the region's floating chrome islands: interaction tools on- * top (legacy-toolbar style), viewport actions and the node-opacity slider- * below.- * - pan: dragging the pane moves the viewport (Shift-drag still box-selects)- * - box-select: dragging the pane draws a selection rectangle (middle-mouse pans)- * - lasso: dragging the pane draws a freeform selection- * - eraser: clicking nodes or edges deletes them+ * Pane drag follows the selected pan/box/lasso tool; eraser clicks delete. Shift selects while panning, and middle+ * mouse pans during box selection.*/export type EditorTool = 'pan' | 'box-select' | 'lasso' | 'eraser';@@ -89,12 +83,10 @@ export const EditorToolbar = ({<Popover.Root ids={opacityIds} positioning={POPOVER_POSITIONING}><Tooltip content="Node opacity" ids={opacityIds} positioning={TOOLTIP_POSITIONING}><Popover.Trigger asChild>- {/* Matches what `ToolbarButton` renders rather than being one:- `Popover.Trigger asChild` would clone that component's Tooltip- wrapper instead of the button. Size is load bearing — `Toolbar`- is a column Stack, so it stretches every sibling to the widest- child, and one `sm` button here once widened the whole strip- past the `xs` squares. */}+ {/*+ * Render a plain button because asChild would clone ToolbarButton's Tooltip wrapper. Match xs sizing+ * so one child cannot stretch the column.+ */}<IconButtonaria-label="Node opacity"aria-pressed={nodeOpacity < 1}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsxindex d675b82422..ff92ffda34 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx@@ -305,9 +305,8 @@ describe('InvocationFlowNode edge stacking', () => {};it('keeps a selected node clickable where its own edge crosses it, while the edge stays above other nodes', async () => {- // The target sits behind and above the source, so the edge leaves the source's right handle and- // sweeps back across the source's own body and over an unrelated node on the way. Everything stays- // inside the test viewport.+ // Route the edge back across its source and another node to test overlapping interaction paths within the+ // viewport.const target: WorkflowInvocationNode = { ...documentNode, id: 'target-node', position: { x: 0, y: 0 } };const bystander: WorkflowInvocationNode = { ...documentNode, id: 'bystander-node', position: { x: 20, y: 120 } };const graph: ProjectGraphState = {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsxindex 92437259b4..54d4a62791 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx@@ -205,8 +205,7 @@ const NodeTitle = ({ node, title }: { node: WorkflowInvocationNode; title: strinminW="0"text={title}title="Double-click to rename"- // Editing always starts from the displayed title: an unset label- // prefills with the template title rather than an empty input.+ // Start editing from the displayed title, including the template fallback for unset labels.onDoubleClick={() => setDraftLabel(title)}/>);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsxindex 4322bce40c..f5096734fb 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsx@@ -13,11 +13,6 @@ import {} from 'lucide-react';import { useCallback, useMemo } from 'react';-/**- * Right-click utilities for the flow pane and nodes, anchored at the pointer.- * The menu is fully controlled because each action needs editor-local context.- */-export interface NodeContextMenuState {kind: 'node';nodeId?: string;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsxindex 7fe3b8d728..517e917614 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx@@ -104,10 +104,8 @@ const edgeTypes: EdgeTypes = {};/**- * The workflow center view: an xyflow editor over the project graph document.- * The document is the source of truth — flow state is rebuilt from it on every- * document change (undo, import, field edits), while transient view state- * (selection, in-flight drags, the active tool) lives in local component state.+ * The graph document owns durable flow data; preserve transient selection, drags, and tool state separately when+ * rebuilding it.*/// 25px matches v6 so workflows aligned there stay on the grid here.const GRID_SIZE = 25;@@ -132,8 +130,7 @@ const toDocumentEdge = (connection: Connection): WorkflowDocumentEdge | null =>: null;const DEFAULT_EDGE_OPTIONS = { style: { strokeWidth: 2 } };-// A fresh graph starts clear of the floating toolbar in the left gutter, so-// its first column's node controls are not covered before the user pans.+// Offset fresh graphs so the floating left toolbar does not cover their first column.const DEFAULT_VIEWPORT = { x: 56, y: 0, zoom: 1 } as const;interface WorkflowFlowModel {@@ -1199,9 +1196,6 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {);};-// Graph readiness is reported on the Invoke control, which is where the user-// acts on it. A second floating copy over the canvas said the same thing twice.-export const WorkflowEditorView = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {const flowIdentity = useWorkflowProjectSelector((project) =>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.tsindex b1f3e9e13e..9b64ff302a 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.ts@@ -5,12 +5,8 @@ import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore } from '@platform/state/externalStore';/**- * Session-lived clipboard for workflow nodes. Copies hold deep clones of the- * selected nodes plus the edges that connect them to each other; pasting- * materializes fresh ids (remapping those internal edges) so a payload can be- * pasted repeatedly. Deliberately not the system clipboard: node fragments are- * not a valid workflow JSON, so a partial graph on the OS clipboard would only- * masquerade as an importable document.+ * Keep deep-cloned node fragments in a session clipboard; paste remaps internal edges to fresh IDs. Fragments are+ * not valid system-clipboard workflow documents.*/interface WorkflowClipboardSnapshot {@@ -90,11 +86,7 @@ const materializeElements = (};};-/**- * Materializes the clipboard into paste-ready elements with fresh ids.- * Positions shift by a fixed offset from the copied originals (or anchor the- * group's top-left on `at` when given) so pastes do not stack on their source.- */+/** Assign fresh IDs and offset positions, or anchor the group's top-left at the requested point. */export const buildPasteElements = (at?: XYPosition): { nodes: WorkflowNode[]; edges: WorkflowEdge[] } =>materializeElements(clipboardStore.getSnapshot(), at);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.test.tsindex c0ac0995af..57dc333cae 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.test.ts@@ -337,9 +337,8 @@ describe('flowAdapters identity preservation', () => {expect(highlighted[0]?.animated).toBe(true);expect(highlighted[0]?.className).toBe('workflow-selected-node-edge');- // xyflow already lifts these edges with `elevateEdgesOnSelect`; adding a z-index of our own- // stacked them above the selected node, where their 20px interaction path swallowed clicks- // on its controls.+ // Let xyflow elevate selected edges; extra z-index lets wide interaction paths intercept selected-node+ // controls.expect(highlighted[0]?.zIndex).toBeUndefined();expect(highlighted[0]?.style).toEqual({ strokeWidth: 2 });expect(toFlowEdges(doc, highlighted, 'default', new Set(['a']))[0]).toBe(highlighted[0]);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.tsindex 0f5a710175..da26ec1f47 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.ts@@ -30,16 +30,8 @@ import {} from '@features/workflow/utility';/**- * Adapters between the project graph document and xyflow's node/edge state.- * The document is the source of truth; xyflow state is rebuilt from it on- * every document change, carrying over transient view state (selection).- *- * Rebuilds preserve object identity for unchanged nodes/edges so memoized- * node components skip re-rendering (see React Flow's performance guidance) —- * the document reducer already keeps untouched node identities stable.- * Derived per-node facts the node components need (incoming connections,- * Linear-UI exposure) are precomputed into `data` here, so node components- * never subscribe to workbench state.+ * Rebuild from document truth while preserving unchanged identities and selection. Precompute connection/exposure+ * facts so nodes need no workbench subscriptions.*/export type InvocationFlowNode = FlowNode<diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.tsindex a8e8e8837b..950a65c257 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.ts@@ -6,12 +6,7 @@ import { createExternalStore } from '@platform/state/externalStore';import type { WorkflowFlowEdge, WorkflowFlowNode } from './flowAdapters';-/**- * Module-level handle to the mounted workflow editor's ReactFlow instance, so- * surfaces outside the ReactFlowProvider (the widget frame's header actions)- * can place inserted nodes at the current viewport center. Mirrors the legacy- * editor's nanostore-held instance.- */+/** Expose the mounted flow instance to outside-provider actions that insert nodes at viewport center. */export type WorkflowFlowInstance = ReactFlowInstance<WorkflowFlowNode, WorkflowFlowEdge>;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/selectionStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/selectionStore.tsindex 01410f42b1..0858a82e29 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/selectionStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/selectionStore.ts@@ -2,10 +2,8 @@ import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore } from '@platform/state/externalStore';/**- * Session-lived editor selection, shared with surfaces outside the flow (the- * node inspector, the form builder's zoom-to-node). The editor writes- * `selectedNodeIds` from its selection events; other surfaces ask for a- * selection via `requestNodeSelection`, which the editor applies and focuses.+ * Share session selection outside the flow; editor events publish IDs while external requests ask the editor to+ * select and focus.*/export interface WorkflowSelectionSnapshot {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/useLasso.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/useLasso.tsxindex 5edccfa144..9436912f39 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/useLasso.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/useLasso.tsx@@ -13,12 +13,8 @@ import {import type { WorkflowFlowInstance } from './flowInstanceStore';/**- * Freeform lasso selection for the flow editor. xyflow has no core lasso (its- * official one is a copy-in component), so this follows the same approach:- * capture-phase pointer handlers on the flow wrapper stop the pane's own drag,- * the path is hit-tested against node bounds in flow coordinates, and a- * pointer-events-free SVG overlay draws the path. Partial mode: a node is- * selected when any corner or its center falls inside the polygon.+ * Capture pointer events before pane dragging; hit-test flow-coordinate node corners/centers against the lasso and+ * draw a pointer-transparent overlay.*/const MIN_POLYGON_POINTS = 3;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/FieldDescriptionPopover.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/FieldDescriptionPopover.tsxindex ce56d551d3..96eb1fd550 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/FieldDescriptionPopover.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/FieldDescriptionPopover.tsx@@ -8,10 +8,6 @@ import { useCallback } from 'react';const POPOVER_POSITIONING = { placement: 'bottom-end' } as const;-/**- * Small textarea popover overriding a field's template description ("field- * notes"), shared by the editor's node field rows and the form builder.- */export const FieldDescriptionPopover = ({description,fieldName,diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsxindex 319526eed4..4423bb0319 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx@@ -28,8 +28,7 @@ vi.mock('@platform/transport/http', async (importOriginal) => ({apiFetchJson: workflowApiMock.apiFetchJson,}));-// The real picker needs the gallery data layer; the field's contract with it is-// the accepted kinds it passes and the item it gets back.+// Stub Gallery transport while asserting accepted kinds and returned items at the field boundary.vi.mock('@features/gallery/picker', () => ({GalleryPickerPopover: ({accept,@@ -66,8 +65,7 @@ const modelSelectState = vi.hoisted(() => ({},}));-// The real picker pulls in the whole model library; the widget's contract with it is the props it-// passes (scope, exclusions, base filter) and the model it gets back.+// Stub model-library UI while asserting picker filters, exclusions, and selected models.vi.mock('@features/models/react', () => ({ModelSelect: (props: NonNullable<typeof modelSelectState.props>) => {modelSelectState.props = props;@@ -255,9 +253,8 @@ const renderField = async (};/**- * Real keystrokes, not a synthetic `input` event: the weight control is a zag-js number input that- * ignores a value written straight onto the DOM node, and the defect being guarded against here is- * specifically what happens between keystrokes.+ * Use real keystrokes because the number-input state machine ignores direct DOM writes and the regression occurs+ * between inputs.*/const typeWeight = async (input: HTMLInputElement, keys: string) => {await act(async () => {@@ -834,11 +831,7 @@ describe('WorkflowFieldInput media inputs', () => {});});-/**- * A parent that actually owns the value, the way the node editor does. The static `renderField`- * harness never feeds a committed value back, which hides every defect that only shows up on the- * re-render after a keystroke — the snap-back and the clamp-on-blur are exactly those.- */+/** Feed committed values back through an owning parent to expose keystroke rerenders and blur clamping. */const StatefulLoRAField = ({ initial, onCommit }: { initial: unknown; onCommit: (value: unknown) => void }) => {const [value, setValue] = useState(initial);const onChange = useCallback(@@ -951,9 +944,7 @@ describe('WorkflowFieldInput LoRA collection', () => {const weight = host.querySelector<HTMLInputElement>('input')!;- // One keystroke at a time, because the defect lives between them: `<input type="number">`- // reports "" for a trailing ".", so the commit is dropped, the box is restored to "0", and the- // next keystroke lands as "05" = 5 — a 10x weight from a completely ordinary typing sequence.+ // Test each keystroke so trailing-decimal drafts cannot reset to zero and turn 0.5 into 5.await typeWeight(weight, '0');await pressKey('.');@@ -1059,9 +1050,7 @@ describe('WorkflowFieldInput seed inputs', () => {await renderField(SEED_TEMPLATE, 4_294_967_295, onChange, undefined, { onSeedModeChange, seedMode: 'fixed' });expect(seedInput()?.disabled).toBe(false);- // Without i18n the label is the long key, which stands in for a long translation: the- // trigger stays bounded and truncates, its accessible name stays whole, and the number- // input keeps a usable width beside it.+ // Use untranslated long keys to verify truncation preserves accessible names and number-input width.expect(modeTrigger()?.getAttribute('aria-label')).toBe('common.seedMode.label: common.seedMode.fixed');expect(modeTrigger()?.getBoundingClientRect().width).toBeLessThanOrEqual(144);expect((seedInput() as HTMLInputElement).scrollWidth).toBeLessThanOrEqual(diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex 72cb12b8ae..3902ac3144 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -115,12 +115,6 @@ const MODEL_SELECT_FALLBACK = (export const getWorkflowSelectedGalleryImage = getSelectedGalleryImageFromValues;-/**- * Direct-input controls for workflow fields, shared between the node editor- * and the Linear UI panel. Renders by template field type; connection-only- * and unsupported types fall through to a muted note.- */-export interface WorkflowFieldInputProps {id?: string;invalid?: boolean;@@ -242,11 +236,8 @@ const NumericInput = ({ id, invalid, onChange, template, value }: WorkflowFieldI};/**- * The shared seed control under a workflow row. The workflow owns the value- * and its run count, so the stepping preview is planned here from the- * workflow's own iterations; an empty field runs from the template default,- * as the plan does. `nokey` keeps xyflow's node key handling out of the row- * and the portaled menu: arrows would nudge the node and Backspace delete it.+ * Plan stepping previews from workflow iterations and template defaults; nokey prevents node shortcuts inside the+ * row and portalled menu.*/const WorkflowSeedInput = ({id,@@ -427,10 +418,7 @@ const ModelIdentifierInput = ({ id, invalid, onChange, template, value }: Workfltypeof (value as { key?: unknown } | null)?.key === 'string' ? (value as { key: string }).key : null;const modelTypes = (template.uiModelType ?? DEFAULT_MODEL_TYPES) as ModelTaxonomyType[];const allowedBases = template.uiModelBase;- // ui_model_format narrows further within a base/type — e.g. a loader's main-model field- // that accepts only diffusers-folder installs while its override fields take the- // single-file checkpoints. Offering the wrong format here would enqueue a graph that- // fails deep inside the model loader instead of at selection time.+ // Filter by model format as well as base/type so loaders cannot receive unsupported component layouts.const allowedFormats = template.uiModelFormat;const filter = useCallback((model: ModelConfig) =>@@ -585,12 +573,8 @@ const VIDEO_ONLY = ['video'] as const;const MEDIA_INPUT_FOCUS_PROPS = { outline: '2px solid {colors.accent.focusRing}', outlineOffset: '2px' } as const;/**- * Upload: file picker -> gallery upload -> adopt the uploaded items. The- * adoption is pinned to this widget instance AND the project it started in:- * `onUploaded` dispatches into the *active* project, so a completion arriving- * after a project switch (or after this node was deleted, which unmounts the- * widget) must not be applied - the upload itself still succeeded, so the- * gallery is refreshed and the user is pointed there instead.+ * Apply uploads only to their originating mounted widget/project. Late successes still refresh Gallery and direct+ * users there instead of mutating another project.*/const useMediaUpload = ({kind,@@ -801,11 +785,6 @@ const MediaDropMonitor = ({return null;};-/**- * Direct input for `ImageField` collections (Image Collection primitive, Image- * Batch): a thumbnail grid with per-item removal, a multi-select gallery- * picker, a multi-item gallery drop target, and multi-file upload.- */const ImageCollectionInput = ({ id, invalid, nodeId, onChange, template, value }: WorkflowFieldInputProps) => {const { t } = useTranslation();const { project } = useWorkflowUi();@@ -951,11 +930,6 @@ const ImageCollectionInput = ({ id, invalid, nodeId, onChange, template, value });};-/**- * Direct input for `ImageField` / `VideoField`: shows the current item with a- * thumbnail, opens the gallery picker, accepts a single-item gallery drag- * onto the row, and uploads a local file to the gallery's selected board.- */const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputProps & { kind: WorkflowMediaKind }) => {const { t } = useTranslation();const config = MEDIA_FIELD_CONFIG[kind];@@ -965,9 +939,7 @@ const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputPr: null;const invalidAriaProps = useMemo(() => (invalid ? { 'aria-invalid': true } : {}), [invalid]);- // dnd: the whole input row is a drop target for a single gallery item of the- // matching kind. The instance-unique suffix keeps ids distinct when the node- // editor and the Linear UI panel render the same field at once.+ // Use instance-unique drop IDs because editor and Linear UI can render the same field simultaneously.const instanceId = useId();const dropId = getWorkflowMediaFieldDropId(`${id ?? 'field'}:${instanceId}`);const { active } = useDndContext();@@ -985,15 +957,11 @@ const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputPr);const onClearClick = useCallback(() => onChange(undefined), [onChange]);- // A stale value (media deleted since the workflow was saved) 404s the- // thumbnail; degrade to a media icon rather than the broken-image glyph. A- // new value retries.+ // Replace failed stale thumbnails with media icons; retry when the value changes.const [failedThumbnail, setFailedThumbnail] = useState<string | null>(null);const onThumbnailError = useCallback(() => setFailedThumbnail(mediaName), [mediaName]);- // Resolve the item's details for the dimensions/duration badge (the legacy- // editor's widget shows the same). Best-effort: the preview works from the- // name alone, so a failed lookup just drops the badge.+ // Resolve badge metadata best-effort; name-based preview remains usable if lookup fails.const { data: mediaItem } = useQuery({enabled: mediaName !== null && mediaName !== '',queryFn: ({ signal }) => galleryItems.resolve({ kind, name: mediaName ?? '' }, signal),@@ -1142,15 +1110,8 @@ const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputPrconst COMPANION_VIDEO_FIELD_NAME = 'video';/**- * Integer input for `ui_component=video-frame-index` fields (`frame_index` on- * Frame from Video; `start_frame`/`end_frame` on Frame Range from Video): the- * standard number input plus a live frame preview and a scrubber slider, all- * writing the same field value. The preview is a muted `<video>` element- * seeked to `frame / fps` — browsers display the frame natively without a- * canvas roundtrip.- *- * Degrades to the plain number input (plus a hint) when the companion video- * field is unset/connection-driven or the video has no probed frame rate.+ * Share one frame value across input, scrubber, and native video preview. Fall back to plain input when the+ * companion video/rate cannot resolve.*/const VideoFrameIndexInput = (props: WorkflowFieldInputProps) => {const { nodeId, onChange, value } = props;@@ -1192,9 +1153,8 @@ const VideoFrameIndexInput = (props: WorkflowFieldInputProps) => {const videoItem: GalleryItem | undefined = data;const video = videoItem && videoItem.kind === 'video' && videoItem.name === videoName ? videoItem : null;- // Frame count is the slider's upper bound. duration*fps can be off-by-one for- // VFR containers, but the slider is for visual scrubbing — the backend- // re-resolves indices against the authoritative decoder count at invoke time.+ // Use estimated frame count only for scrubbing bounds; backend invocation resolves authoritative decoder+ // indices.const fps = video?.fps ?? null;const frameCount =video && fps && video.durationSeconds > 0 ? Math.max(1, Math.round(video.durationSeconds * fps)) : null;@@ -1256,9 +1216,7 @@ const FrameScrubber = ({}) => {const videoRef = useRef<HTMLVideoElement>(null);- // Seek whenever the resolved index changes. The half-frame nudge lands the- // seek inside the frame's display window — some codecs decode the exact- // boundary as black on first paint without it.+ // Seek inside each frame's display interval to avoid boundary decoding artifacts.useEffect(() => {const el = videoRef.current;@@ -1327,12 +1285,7 @@ const FrameScrubber = ({);};-/**- * Workflow `ColorField` values carry alpha as a `[0, 255]` integer, unlike- * every other color in the app (and unlike `RgbaColor`, whose alpha is a unit- * float). The scaling stays local to this adapter rather than pushing a second- * alpha convention into `@platform/ui`'s color helpers.- */+/** Convert workflow alpha integers 0–255 locally; platform RgbaColor uses unit alpha. */const toColorFieldValue = (color: string): Record<string, number> => {const { a, b, g, r } = parseHexColor(color);@@ -1368,14 +1321,8 @@ const ColorInput = ({ invalid, onChange, value }: WorkflowFieldInputProps) => {const LORA_MODEL_TYPES: ModelTaxonomyType[] = ['lora'];/**- * The `Apply LoRA Collection` loaders take `LoRAField | list[LoRAField]`. Rather than making the- * user wire up one `Select LoRA` node per LoRA and collect them, this edits the list in place: pick- * a LoRA from the model picker to append it, then tune each weight on its own row.- *- * Rows address entries by index, not by model key. The picker keeps the user from adding a- * duplicate, but an imported workflow can already contain one, and a key-based edit would hit every- * copy at once. Indexing also keeps entries this widget cannot read (`null` holes from- * `normalizeLoraFieldCollectionValue`) in place instead of dropping them on the next edit.+ * Edit LoRA collections by index so imported duplicate keys and unreadable entries remain independent and+ * preserved.*/const LoRACollectionInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {// The raw list, unreadable items included — see `toLoraFieldCollectionList`.@@ -1390,9 +1337,7 @@ const LoRACollectionInput = ({ id, invalid, onChange, template, value }: Workflo(model: ModelConfig) => (allowedBases ? allowedBases.includes(model.base) : true),[allowedBases]);- // An emptied list is written back as `undefined` rather than `[]`: it is the loaders' own default,- // so the node returns to "no LoRAs" instead of sitting on a value that is equal in effect but- // different from its default.+ // Write emptied collections as undefined to restore the loaders' actual default.const commit = useCallback((next: unknown[]) => onChange(next.length === 0 ? undefined : next), [onChange]);const onAdd = useCallback((model: ModelConfig | null) => {@@ -1476,10 +1421,8 @@ const LoRACollectionRow = ({onWeightChange: (index: number, weight: number) => void;}) => {const label = entry ? entry.lora.name : 'Unreadable entry';- // The committed value is a number, so re-rendering from it alone would rewrite a half-typed- // "0." to "0" mid-keystroke and turn the next digit into "05" — a 10x wrong weight from a- // plausible typing sequence. The draft holds the raw text until the field is left; blur drops- // it so the row picks up the committed (and range-clamped) value again.+ // Keep raw weight drafts through typing so trailing decimals survive numeric commits; blur returns to the+ // clamped committed value.const [draft, setDraft] = useState<string | null>(null);const onRemoveClick = useCallback(() => onRemove(index), [index, onRemove]);const onValueChange = useCallback(diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.ts b/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.tsindex 5f001589cd..2ae8cdd5d7 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/mediaFieldDnd.ts@@ -1,10 +1,5 @@import { isGalleryItemDragData } from '@features/gallery/utility';-/**- * Drop plumbing for the media (image/video) workflow field inputs: a gallery- * item dragged onto a field's input row sets that field's value.- */-export type WorkflowMediaKind = 'image' | 'video';export interface WorkflowMediaDropItem {@@ -23,12 +18,7 @@ export const getWorkflowMediaFieldDropItems = (? activeData.items.map((item) => ({ kind, name: item.name })): [];-/**- * Resolves a gallery drag payload to the single item a media field can accept,- * or null. Multi-item drags are rejected outright: a single-value field- * silently keeping only the first of several dragged items would misread the- * user's intent.- */+/** Reject multi-item drags for single-value media fields instead of silently taking the first. */export const getWorkflowMediaFieldDropItem = (activeData: unknown,kind: WorkflowMediaKinddiff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/FlowMiniMap.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/FlowMiniMap.tsxindex dbf9ffdf0c..7482d405b0 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/FlowMiniMap.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/FlowMiniMap.tsx@@ -1,11 +1,7 @@import { chakra } from '@chakra-ui/react';import { MiniMap } from '@xyflow/react';-/**- * xyflow's MiniMap wrapped in the chakra factory so its frame is styled with- * workbench tokens (the fills inside the SVG come from the `--xy-minimap-*`- * vars in `flowTheme.ts`).- */+/** Style the MiniMap frame with Chakra tokens and its SVG fills with flowTheme variables. */const StyledMiniMap = chakra(MiniMap);export const FlowMiniMap = () => (diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsxindex 1b8b3c504a..5b54e08e5b 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx@@ -16,10 +16,7 @@ import { page } from 'vitest/browser';import { GraphPreviewDialog } from './GraphPreviewDialog';-// `downloadText`, the invocation templates snapshot, and the flow's `onInit`-// instance stub all need to exist before `vi.mock` factories below run-// (they're hoisted above the imports that would otherwise define them), so-// they're built through `vi.hoisted`.+// Create mock dependencies with vi.hoisted because factories run before ordinary imports.const { downloads, fitViewMock, TEMPLATES_SNAPSHOT, templatesSnapshotRef } = vi.hoisted(() => {const fieldInput = (name: string, defaultValue: unknown) => ({default: defaultValue,@@ -77,22 +74,14 @@ const { downloads, fitViewMock, TEMPLATES_SNAPSHOT, templatesSnapshotRef } = vi.return {downloads: { downloadBlob: vi.fn(), downloadText: vi.fn() },- // `GraphPreviewFlow`'s mock (below) calls `onInit` with this so- // `handleFlowInit`'s pending-reveal consumption has a real `fitView` spy- // to assert against — asserting the dialog's own reveal logic runs to- // completion, not just that it doesn't crash.+ // Provide an initialized flow spy to verify pending reveals actually call fitView.fitViewMock: vi.fn(() => Promise.resolve(true)),TEMPLATES_SNAPSHOT: templatesSnapshot,- // Mutable so a single test can point `useInvocationTemplatesSnapshot` at- // a non-loaded status without a per-test `vi.mock` factory.templatesSnapshotRef: { current: templatesSnapshot },};});-// xyflow stays out of this shell test — the flow pane's own rendering is-// covered elsewhere (`GraphPreviewFlow`'s own tests). It still calls `onInit`-// with a stub instance so `GraphPreviewDialog`'s pending-reveal handoff-// (`selectAndReveal` → `handleFlowInit`) has something real to run against.+// Stub flow rendering but retain onInit to exercise the dialog's pending-reveal handoff.vi.mock('./GraphPreviewFlow', () => ({GraphPreviewFlow: ({ onInit }: { onInit?: (instance: { fitView: typeof fitViewMock }) => void }) => {onInit?.({ fitView: fitViewMock });@@ -105,21 +94,13 @@ vi.mock('./GraphPreviewFlow', () => ({vi.mock('@platform/browser/downloadBlob', () => downloads);-// The "Open as" menu (`GraphPreviewOpenAsMenu`) reads the invocation-// templates snapshot through the reactive hook, not the plain getter, so its-// disabled state can update live if the menu opens while templates are still-// loading — this stubs that hook (and the getter, for symmetry) with a-// pre-loaded snapshot covering the fixture graph's node types.+// Stub reactive templates so Open as disabled state follows the same loading contract as production.vi.mock('@features/workflow/react', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),getInvocationTemplatesSnapshot: () => templatesSnapshotRef.current,useInvocationTemplatesSnapshot: () => templatesSnapshotRef.current,}));-// "Save to workflow library" goes through `useSaveWorkflowToLibrary`-// (Task 8), which calls the backend through this barrel — stub the one-// function that path reaches, same mock shape as-// `useSaveWorkflowToLibrary.browser.test.tsx`.const { createLibraryWorkflowMock } = vi.hoisted(() => ({createLibraryWorkflowMock: vi.fn(),}));@@ -129,10 +110,7 @@ vi.mock('@features/workflow/queries', async (importOriginal) => ({createLibraryWorkflow: createLibraryWorkflowMock,}));-// The real client fetches en.json over HTTP (`platform/i18n/client.ts`), which-// this browser test never boots. Stub `t` with the subset of English strings-// this dialog renders, so assertions check real copy instead of raw dotted-// keys — the repo-wide convention for `react-i18next` in browser tests.+// Supply rendered English strings without starting the HTTP-backed i18n client.const TRANSLATIONS: Record<string, string> = {'common.close': 'Close','common.json': 'JSON',@@ -256,9 +234,7 @@ const INVALID_SOURCE: GraphPreviewSourceState = {summaryRows: [],};-// A single node of a type absent from `TEMPLATES_SNAPSHOT.templates` —-// `previewGraphToDocument` skips it, so the converted document has zero-// nodes and both "Open as" actions that convert to a document should bail.+// An unknown-only graph converts to an empty document; document-opening actions must stop.const UNKNOWN_NODE_GRAPH: WorkflowPreviewGraph = {id: 'unknown-node-graph',nodes: [{ id: 'mystery', type: 'unknown_type', inputs: {} }],@@ -306,12 +282,7 @@ const preferencesSnapshot = {workflowValidateConnections: true,};-// A stable object per adapter instance — `useWorkflowProjectSelector`-// (`useSaveWorkflowToLibrary`, called by `GraphPreviewOpenAsMenu`) runs this-// through `useSyncExternalStoreWithSelector`'s shallow-equality check, which-// would otherwise see a "changed" snapshot on every render (new object-// identity, same content) and force an infinite re-render loop — the same-// reason `preferencesSnapshot` above is hoisted rather than built inline.+// Keep adapter snapshots stable so external-store subscribers cannot loop on fresh equivalent objects.const createProjectSnapshot = () => ({galleryValues: {},id: 'project-1',@@ -449,9 +420,7 @@ describe('GraphPreviewDialog', () => {});};- // Opens the "Open as" menu. Chakra's `Menu.Content` is lazy-mounted and- // its open transition runs on a timer, so the click alone isn't enough —- // give the portal a beat to attach before querying for items.+ // Wait for lazy menu portal mounting before querying items.const openAsMenu = async () => {await clickButtonWithText('Open as');await act(async () => {@@ -475,10 +444,7 @@ describe('GraphPreviewDialog', () => {});};- // "Save to workflow library" fires off an async handler (`void- // saveToLibrary()`) that the click itself doesn't wait for — a macrotask- // tick drains the `await saveDocumentAsNew(document)` chain (serialize →- // `createLibraryWorkflow` → notify) before assertions run.+ // Await the detached save handler's async chain before asserting serialization, creation, and notification.const flushAsync = () =>act(async () => {await new Promise<void>((resolve) => {@@ -626,19 +592,12 @@ describe('GraphPreviewDialog', () => {expect(text).toContain('Set by');expect(text).toContain('Generate → Steps');- // The fixture's `denoise_latents` node has one incoming edge (from `seed`)- // and one outgoing edge (to `l2i`) — exercise both `getEdgesInLine` and- // the per-edge `edgesOut` lines, not just that the "Edges" heading renders.+ // Exercise both incoming and outgoing edge details, not merely their heading.expect(text).toContain('Edges');expect(text).toContain('in · 1 inputs from seed');expect(text).toContain('out · latents → l2i');- // The flow wasn't mounted when the row was clicked (mode was still- // 'list'), so the reveal had to go through the pending-reveal path:- // `selectAndReveal` stashes the id, and the flow's remount (its `onInit`- // firing again) is what actually calls `fitView`. This is the case the- // stale-ref bug broke — before the fix, `flowInstanceRef` still pointed- // at the unmounted flow's instance and this fit never happened.+ // List-mode reveal must wait for the remounted flow's onInit rather than use the destroyed previous instance.expect(fitViewMock).toHaveBeenCalledWith(expect.objectContaining({ nodes: [{ id: 'denoise_latents' }] }));});@@ -652,9 +611,7 @@ describe('GraphPreviewDialog', () => {expect(text).toContain('seed');expect(text).toContain('regenerated each run');- // Mode was already 'graph' with the flow mounted, so this reveal takes- // the immediate branch — `fitView` runs straight off `flowInstanceRef`- // instead of waiting on a remount.+ // Graph-mode reveal uses the already-mounted instance immediately.expect(fitViewMock).toHaveBeenCalledWith(expect.objectContaining({ nodes: [{ id: 'seed' }] }));});@@ -676,10 +633,7 @@ describe('GraphPreviewDialog', () => {await clickButtonWithText('denoise_latents');expect(document.body.textContent ?? '').toContain('Resolved inputs');- // The footer Close button is the path `closeAndReset` resets `selectedNodeId`- // through. Re-render with `isOpen` false then true to simulate the parent- // obeying the `onOpenChange(false)` this just triggered and reopening —- // the same controlled-`open` round trip a real host does.+ // Model the controlled close/reopen round trip to verify selection resets.await clickButtonWithText('Close');expect(onOpenChange).toHaveBeenCalledWith(false);@@ -714,8 +668,6 @@ describe('GraphPreviewDialog', () => {expect(graphPreviewPort.openDocumentInNewProject).toHaveBeenCalledTimes(1);const [document_, label] = vi.mocked(graphPreviewPort.openDocumentInNewProject).mock.calls[0] ?? [];expect(document_?.nodes).toHaveLength(3);- // The fixture graph has no `label`, so this exercises the- // `graph.label ?? sourceLabel` fallback (`sourceLabel` is "Generate").expect(document_?.name).toBe('Generate');expect(label).toBe('Opened from graph preview');// Forking must not touch the current project's workflow.@@ -731,8 +683,6 @@ describe('GraphPreviewDialog', () => {expect(downloads.downloadText).toHaveBeenCalledTimes(1);const [content, fileName, type] = vi.mocked(downloads.downloadText).mock.calls[0] ?? [];- // The fixture graph has no `backendGraph`, so this exercises the- // `graph.backendGraph ?? graph` fallback, not just the happy path.expect(content).toContain('"denoise_latents"');expect(fileName).toBe('graph.json');expect(type).toBe('application/json');@@ -774,8 +724,6 @@ describe('GraphPreviewDialog', () => {await flushAsync();expect(createLibraryWorkflowMock).toHaveBeenCalledTimes(1);- // The fixture graph has no `label`, so this exercises the- // `graph.label ?? sourceLabel` fallback (`sourceLabel` is "Generate").const [serialized] = createLibraryWorkflowMock.mock.calls[0] ?? [];expect(serialized).toMatchObject({ name: 'Generate' });expect(workflowUiAdapter.notifications.success).toHaveBeenCalledWith('Saved to workflow library');@@ -803,9 +751,7 @@ describe('GraphPreviewDialog', () => {await clickMenuItemWithText('Save to workflow library');await flushAsync();- // The fixture's only node is a type with no matching template, so- // `previewGraphToDocument` skips it and the converted document is empty —- // this must bail before ever reaching the backend save call.+ // Reject conversion with no recognized nodes before backend save.expect(createLibraryWorkflowMock).not.toHaveBeenCalled();expect(workflowUiAdapter.notifications.error).toHaveBeenCalledWith('No saveable nodes in this graph.');expect(workflowUiAdapter.notifications.success).not.toHaveBeenCalled();diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsxindex 9b17def016..7bfc28d1e7 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx@@ -25,11 +25,7 @@ interface GraphPreviewDialogProps {/** Hides the footer Invoke button only — Copy JSON and the Open-as menu stay. For sources with no invocation route (e.g. a library entry, previewed before it's ever opened into a project). */hideInvoke?: boolean;onOpenChange: (isOpen: boolean) => void;- /**- * Fires once the close transition has finished playing. Hosts that mount this- * dialog conditionally must drop the mount here rather than the moment- * `isOpen` goes false, or the exit animation never gets to run.- */+ /** Conditional hosts must unmount after close completion so exit animation can run. */onExitComplete?: () => void;}@@ -98,8 +94,7 @@ export const GraphPreviewDialog = ({const graph = source.graph;const selectedNode = graph?.nodes.find((node) => node.id === selectedNodeId) ?? null;- // Every path that can close the dialog routes through this, so the- // selection never survives into the next time it's opened.+ // Reset selection on every close path so reopening starts clean.const closeAndReset = useCallback((open: boolean) => {if (!open) {@@ -122,11 +117,7 @@ export const GraphPreviewDialog = ({});}, [graphPreview, closeAndReset, sourceId]);- // Consumed by `handleFlowInit` the next time the flow mounts. Set by- // `selectAndReveal` when it fires while the flow isn't the visible pane —- // `flowInstanceRef` still points at the *previous* mount's (destroyed)- // instance until then, so fitting it immediately would no-op on a dead- // instance instead of the one that's about to render.+ // Queue reveals for the next flow initialization; the previous mount's instance may already be destroyed.const pendingRevealNodeIdRef = useRef<string | null>(null);const handleFlowInit = useCallback((instance: ReactFlowInstance) => {@@ -146,13 +137,7 @@ export const GraphPreviewDialog = ({closeAndReset(false);}, [graphPreview, sourceId, closeAndReset]);- // Selects a node and brings it into view. List rows and the notice banner's- // "show node" link both switch to graph mode so the selection is always- // visible after they fire — but if the flow isn't the mounted pane right- // now (`mode` is still 'list'/'json' at call time), setting `mode` below- // only *starts* the remount; the fresh instance doesn't exist until- // `handleFlowInit` runs next render. Stash the id for that instead of- // fitting a stale/dead instance.+ // Switching from list/JSON starts a flow remount; defer fitView until its fresh instance initializes.const selectAndReveal = useCallback((nodeId: string) => {setSelectedNodeId(nodeId);@@ -183,10 +168,7 @@ export const GraphPreviewDialog = ({clearTimeout(copyResetTimerRef.current);}- // Deliberately not a `useEffect` cleanup (unlike `JsonPreview`'s- // equivalent timer) — the no-useEffect rule keeps this in the- // handler, and a `setHasCopied` that fires after unmount is a no-op- // in React 18+, not a leak.+ // Keep copy-feedback timing in the event handler; a post-unmount state update is ignored.copyResetTimerRef.current = setTimeout(() => setHasCopied(false), COPY_RESET_DELAY_MS);}).catch(() => toaster.create({ title: t('graphPreview.copyFailed'), type: 'error' }));@@ -204,10 +186,6 @@ export const GraphPreviewDialog = ({<Portal><Dialog.Backdrop /><Dialog.Positioner>- {/* A graph reads left-to-right, so the dialog is landscape: it takes- the width it can get and only as much height as that shape wants,- instead of the near-full-height column an 80vh-first sizing gave- it on tall displays. */}<Dialog.Content h="min(46rem, 85vh)" maxH="85vh" maxW="min(72rem, calc(100vw - 4rem))"><Dialog.Header alignItems="center" flexDirection="row" justifyContent="space-between"><Stack gap="0.5" minW="0">diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsxindex 3cad5d86f8..d8ad44ab1b 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx@@ -23,23 +23,14 @@ import { useTranslation } from 'react-i18next';import { flowThemeCss, getFlowColorMode } from './flowTheme';import { getNodeSubtitle } from './nodeSummaries';-/**- * A read-only flow rendering of a compiled `GraphContract` — the "nodes" half- * of the graph preview dialog. Contracts carry no positions, so the renderer- * uses the caller's hints (the editable document's positions, when the graph- * came from the project graph) and falls back to a layered topological layout.- */+/** Use caller position hints when available; compiled contracts otherwise receive topological layout. */type PreviewFlowNode = FlowNode<{ inputCount: number; isSelected: boolean; nodeId: string; nodeType: string; subtitle: string | null },'preview'>;-/**- * A lightweight contract view of an editable document (no templates needed),- * for previewing workflows that are not the active project graph — e.g.- * library entries before loading them.- */+/** Build a template-free contract view for documents outside the active editor, including library previews. */export const documentToPreviewGraph = (document: ProjectGraphState,fallbackLabel: string@@ -87,8 +78,6 @@ const PreviewNode = ({ data }: NodeProps<PreviewFlowNode>) => {borderWidth="1px"fontSize="xs"minW="14rem"- // Border + matching outline reads as a 2px solid accent ring — visible- // at any zoom, where the previous emphasized border was too subtle.outlineColor="accent.solid"outlineStyle={data.isSelected ? 'solid' : undefined}outlineWidth="1px"diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewList.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewList.tsxindex 166a8f04de..b17074b6fd 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewList.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewList.tsx@@ -40,13 +40,8 @@ const GraphPreviewListRow = ({ node, onSelect }: { node: PreviewListNode; onSele};/**- * The preview dialog's "List" mode: every node as a full-width row, in- * topological order, so a keyboard/screen-reader user can reach any node- * without depending on the flow canvas. Selecting a row opens the same- * inspector the flow's node click does (`GraphPreviewDialog.selectAndReveal`).- *- * Deliberately avoids `@platform/ui` — the barrel's fan-in budget is nearly- * exhausted, and this component only needs plain Chakra primitives.+ * Expose all nodes in topological rows for keyboard/screen-reader access to the shared inspector; plain Chakra+ * avoids unnecessary platform-barrel fan-in.*/export const GraphPreviewList = ({graph,@@ -55,9 +50,7 @@ export const GraphPreviewList = ({graph: WorkflowPreviewGraph;onSelect: (nodeId: string) => void;}) => {- // Live sources (e.g. Generate) recompile on every keystroke — re-sorting and- // re-mapping the node list on every one of those renders (not just when the- // graph itself changes) would make leaving List mode open needlessly costly.+ // Recompute sorted rows only when the graph changes, not on unrelated live-source renders.const orderedNodes = useMemo(() => {const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));const order = getTopologicalOrder(diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsxindex e84bc70a0b..b76bb3b17c 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx@@ -29,13 +29,8 @@ interface GraphPreviewOpenAsMenuProps {}/**- * The graph preview dialog's "Open as" menu — four ways to hand a- * read-only preview graph off to something that keeps it: convert it into an- * editable document and load it into the workflow editor, save it to the- * workflow library without touching the active project, fork it into a fresh- * project, or download the raw JSON. The trigger button lives in the dialog (it needs `@platform/ui`'s- * `Button`); this file stays out of that import so it doesn't add to that- * package's fan-in.+ * Convert previews into editor/library/project documents or download raw JSON. Keep the trigger in the dialog to+ * avoid another platform-barrel dependency.*/export const GraphPreviewOpenAsMenu = ({children,diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSidePanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSidePanel.tsxindex 7477bf580b..f8c4617c21 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSidePanel.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSidePanel.tsx@@ -9,14 +9,7 @@ import { useTranslation } from 'react-i18next';type PreviewGraphNode = WorkflowPreviewGraph['nodes'][number];-/**- * The preview dialog's right-hand rail: either a summary of the compiled- * graph (node count, result destination, source-specific settings rows), or- * — once a node is selected in the flow/list — that node's inspector (who- * set its inputs, their resolved values, and its edges). The outer- * `Scrollable` stays mounted across the switch so selecting a node doesn't- * remount the panel's scroll container.- */+/** Keep the outer scroll container mounted while switching between graph summary and node inspection. */export const GraphPreviewSidePanel = ({source,selectedNode,@@ -34,9 +27,7 @@ export const GraphPreviewSidePanel = ({const { t } = useTranslation();return (- // `minH="0"` (not `h="full"`) — an explicit height opts the panel out of- // the flex row's stretch sizing, so the root grew to its content height- // and the viewport never actually overflowed (dead scrollbar thumb).+ // Use minH=0 to retain flex stretch sizing and a genuinely overflowing scroll viewport.<Scrollable flexShrink={0} label={t('graphPreview.thisGraph')} minH="0" w="19rem">{selectedNode ? (<NodeInspector node={selectedNode} source={source} onBack={onBack} onProvenanceClick={onProvenanceClick} />@@ -117,10 +108,7 @@ const GraphSummary = ({{nodeCount !== undefined ? String(nodeCount) : '—'}</DataList.ItemValue></DataList.Item>- {/* A source with no destination has not been routed anywhere yet (a- library entry previewed before it is opened into a project). A row- reading "Destination —" states nothing; omitting it says the same- thing without the noise. */}+{source.destinationLabel === null ? null : (<DataList.Item><DataList.ItemLabel fontSize="2xs">{t('graphPreview.destination')}</DataList.ItemLabel>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/flowTheme.ts b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/flowTheme.tsindex dcf72d379e..f594c17a30 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/flowTheme.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/flowTheme.ts@@ -5,12 +5,8 @@ import { WORKFLOW_NODE_SURFACE_TOKEN } from '@features/workflow/ui/nodeChrome';import { THEMES_BY_ID } from '@theme/themes';/**- * Theme bridge for xyflow surfaces. xyflow's stylesheet only knows light/dark,- * so every flow renderer (workflow editor, graph preview) applies these- * Chakra-token-backed `--xy-*` override vars on its wrapper — they inherit- * into `.react-flow` and outrank the colorMode defaults. `--wb-flow-grid` is- * ours, consumed by `<Background color>` and preview handles; `--wb-node-surface`- * feeds the node-body token to inline-styled field handles.+ * Override xyflow light/dark defaults with inherited Chakra-backed variables; workbench variables also color grids+ * and inline handles.*/export const flowThemeCss: SystemStyleObject = {'--wb-flow-grid': '{colors.fg.grid}',diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.ts b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.tsindex 3b6a3e2c7d..652fbd58de 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.ts@@ -1,11 +1,6 @@import type { TFunction } from 'i18next';-/**- * One-line, type-specific summaries shown under a preview node's id (e.g.- * "28 steps · cfg 4" for `denoise_latents`). Callers fall back to the generic- * `id · N inputs` line when this returns `null` — most invocation types have- * no bespoke summary.- */+/** Return null when no type-specific summary exists so callers use the generic node/input summary. */export const getNodeSubtitle = (node: { id: string; type: string; inputs: Record<string, unknown> },t: TFunctiondiff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsxindex 0f6e99883d..ff2407bc39 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx@@ -8,16 +8,8 @@ import { useCallback, useState, type MouseEvent } from 'react';import { useTranslation } from 'react-i18next';/**- * One workflow in the library grid: a sample-output thumbnail over a footer- * strip of the facts that decide whether this is the workflow you want — its- * base architecture, its size, and how many models you'd have to install to- * run it.- *- * A single click selects (the right rail follows the selection); a double- * click opens; a right click selects and asks for the rail's actions at the- * pointer. Enrichment fills the footer in asynchronously per entry, so the- * strip reserves its height from the first paint and never reflows the grid- * as counts arrive.+ * Select on click, open on double-click, and select/context-menu on right-click. Reserve enrichment height so+ * async facts cannot reflow the grid.*/const CARD_HOVER = { bg: 'bg.muted', borderColor: 'border.emphasized' } as const;@@ -72,8 +64,6 @@ export const WorkflowLibraryCard = ({);const handleThumbnailError = useCallback(() => setHasThumbnailFailed(true), []);- // A broken <img> reads worse than the glyph, so a load failure falls back to- // the same placeholder a workflow that has never run gets.const showThumbnail = Boolean(item.thumbnail_url) && !hasThumbnailFailed;const primaryBase = enrichment.status === 'ready' ? enrichment.requirements.primaryBase : null;@@ -121,8 +111,7 @@ export const WorkflowLibraryCard = ({<MiddleTruncate fontSize="xs" fontWeight="600" minW="0" text={item.name || t('workflowLibrary.untitled')} /><HStack gap="1.5" h="4" minW="0">{enrichment.status === 'pending' ? (- // Enrichment in flight. An unreadable workflow ('error') gets no- // placeholder and no error styling — the facts simply stay absent.+ // Show placeholders only while enriching; unreadable workflows leave facts absent.<Skeleton data-enrichment-placeholder h="3" rounded="sm" w="14" />) : null}{primaryBase ? (@@ -136,10 +125,6 @@ export const WorkflowLibraryCard = ({</Text>) : null}{missingCount > 0 ? (- // Same amber as the detail panel's Install button and the- // requirements list's "installable" rows — the theme's warning- // tokens, not Chakra's stock orange, so it tracks every theme's- // own warning hue instead of a fixed one.<Badge bg="bg.warning" color="fg.warning" flexShrink={0} size="xs" variant="subtle">{t('workflowLibrary.installModels', { count: missingCount })}</Badge>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsxindex e386eaa297..02a98c9df1 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx@@ -14,12 +14,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { WorkflowLibraryDetailPanel } from './WorkflowLibraryDetailPanel';/**- * The panel is the only surface that turns "what does this workflow need" into- * an action, so the model stores it resolves against are replaced by mutable- * fixtures: installed models, the starter catalog, and the set of sources- * already installing. `getStarterModelInstallSources` stays real — the install- * action's contract is that it hands the *catalog's* sources to `installMany`,- * deduped across requirements.+ * Use mutable catalog fixtures but real install-source expansion to verify deduplicated catalog sources reach+ * installMany.*/const models = vi.hoisted(() => ({activeInstallSources: { current: new Set<string>() },@@ -322,10 +318,7 @@ describe('WorkflowLibraryDetailPanel', () => {const trigger = document.querySelector<HTMLElement>('[aria-label="More actions"]');expect(trigger).not.toBeNull();- // The trigger is a toggle: clicking it while the menu is already open- // (e.g. a caller re-asserts state after an in-flight action left the- // menu open, because a disabled item's click never reaches the menu- // machine) would close it instead of being the no-op callers expect.+ // Check open state before clicking the toggle; repeating an open request would otherwise close it.if (trigger?.getAttribute('data-state') === 'open') {return;}@@ -478,8 +471,6 @@ describe('WorkflowLibraryDetailPanel', () => {await renderPanel(IMAGE_TO_VIDEO);expect(requirementStatuses()).toEqual(['unresolvable', 'unresolvable', 'installed']);- // Nothing to install, so the panel keeps its Open action rather than- // offering an install that cannot run.expect(buttonWithText('Open')).not.toBeUndefined();});@@ -553,8 +544,7 @@ describe('WorkflowLibraryDetailPanel', () => {expect(RAW_WORKFLOW.meta).toStrictEqual({ category: 'default', version: '3.0.0' });expect(queries.invalidateWorkflowLibraryCache).toHaveBeenCalledTimes(1);expect(onDuplicated).toHaveBeenCalledWith('wf-copy');- // From Browse, the copy lands in a category the user is not looking at, so- // the notice is the only confirmation there is.+ // A copied default lands outside the current category, so notification confirms success.expect(NOTIFICATIONS.success).toHaveBeenCalledWith('Saved a copy under Yours');});@@ -572,10 +562,7 @@ describe('WorkflowLibraryDetailPanel', () => {await clickMenuItem('duplicate');- // Nothing has changed on screen yet — the copy is two round trips away and- // lands in a category this view is not showing — so the menu item holds- // itself closed instead of letting an impatient second click mint a second- // copy.+ // Guard duplicate creation while its two requests are pending and no visible result exists yet.await openMenu();expect(menuItem('duplicate')?.getAttribute('aria-disabled')).toBe('true');@@ -632,9 +619,6 @@ describe('WorkflowLibraryDetailPanel', () => {await renderPanel(TEXT_TO_IMAGE);await openMenu();- // The overflow menu carries the same second-line hints as the graph- // preview's "Open as" menu — this is the one place that unification is- // asserted, rather than duplicating it under every item.expect(menuItem('delete')?.textContent).toContain('Removes it from your library');await clickMenuItem('delete');@@ -690,8 +674,7 @@ describe('WorkflowLibraryDetailPanel', () => {it('links only the rows the account is missing, and takes them to Add Models', async () => {await renderPanel(IMAGE_TO_VIDEO);- // Two installable rows link; the installed VAE stays plain text — Add- // Models has nothing to offer for a model that is already here.+ // Link missing installable models only; installed requirements have no Add Models action.expect(requirementStatuses()).toEqual(['installable', 'installable', 'installed']);expect(document.querySelectorAll('[data-requirement-link]')).toHaveLength(2);expect(requirementRows()[2]?.querySelector('[data-requirement-link]')).toBeNull();@@ -713,8 +696,7 @@ describe('WorkflowLibraryDetailPanel', () => {});it('leaves a row that names nothing installable as plain text', async () => {- // Nothing installed and no catalog: the row is unresolvable, and a slot- // with neither base nor type has no query to offer either.+ // Unresolved requirements without catalog matches or searchable slot hints remain plain text.models.installedModels.current = [];models.starterModels.current = [];diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsxindex 07028a566f..64f8bbe152 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx@@ -45,17 +45,7 @@ import {WorkflowRequirementsList,} from './WorkflowRequirementsList';-/**- * The library's right rail: everything about the selected workflow that- * decides whether to open it — sample output, description, tags, and the- * models it needs — plus the one action that follows from that answer. When- * models are missing the primary button installs them instead of opening a- * workflow that would fail on its first run; everything rarer (duplicate,- * fork, download, delete) lives behind the overflow menu.- *- * The panel updates in place across selection changes: no keys, no remounts,- * so switching cards never flashes the rail.- */+/** Install missing models before offering Open; keep the detail rail mounted across selections to prevent flashing. */const DETAIL_RAIL_WIDTH = '18rem';const THUMBNAIL_ASPECT_RATIO = 3 / 2;@@ -109,10 +99,7 @@ export const WorkflowLibraryDetailPanel = ({// thumbnail without an effect resetting the flag.const [failedThumbnailUrl, setFailedThumbnailUrl] = useState<string | null>(null);const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);- // A duplicate is two round trips with nothing on screen between them, and a- // copy of a default lands in a category the user is not looking at — so the- // menu item has to hold itself closed until the copy exists, or an impatient- // second click mints a second copy.+ // Guard duplicate creation until the copy exists, including copies landing outside the visible category.const [isDuplicatePending, setIsDuplicatePending] = useState(false);const isDuplicatePendingRef = useRef(false);@@ -139,8 +126,7 @@ export const WorkflowLibraryDetailPanel = ({const handleThumbnailError = useCallback(() => setFailedThumbnailUrl(entry?.item.thumbnail_url ?? null), [entry]);- // Add Models is a different page, so the library has to get out of the way —- // the same handoff a fork into a new project makes.+ // Close the library before navigating to Add Models.const handleFindModel = useCallback((query: string) => {openAddModels(query);@@ -187,11 +173,7 @@ export const WorkflowLibraryDetailPanel = ({}, [deps, installMany, notify, resolved, t]);const handleInstall = useCallback(() => void install(), [install]);- /**- * Copies the library *record* — not the project graph, and never the- * original — so a bundled default can be adapted without the editor ever- * loading it.- */+ /** Duplicate the library record directly without loading or modifying the active project graph. */const duplicate = useCallback(async () => {if (!entry || isDuplicatePendingRef.current) {return;@@ -320,8 +302,6 @@ export const WorkflowLibraryDetailPanel = ({await deleteLibraryWorkflow(entry.item.workflow_id, owner.signal);assertAccountScopeCurrent(owner);- // The invalidation refetches the visible pages; the shell only has to- // let go of the selection this row held.invalidateWorkflowLibraryCache();onDeleted();} catch (error) {@@ -433,12 +413,10 @@ export const WorkflowLibraryDetailPanel = ({) : null}</Stack>- {/* The one place the whole name has to be readable — the rail is what- the user consults before opening a workflow, so it wraps instead- of truncating. `anywhere` so a delimiter-free name breaks too;- containment is the wrap plus the scroll area's zeroed content- min-width, not a clamp. (Grid cards still truncate: there the name- is a glance, not the answer.) */}+ {/*+ * Wrap full names, including delimiter-free strings, in the detail rail; zero content min-width permits+ * containment without truncation.+ */}<Text fontSize="sm" fontWeight="600" minW="0" overflowWrap="anywhere">{name}</Text>@@ -470,9 +448,6 @@ export const WorkflowLibraryDetailPanel = ({<Stack borderColor="border.subtle" borderTopWidth="1px" gap="2" p="2.5"><HStack gap="2" minW="0">{installableCount > 0 ? (- // The theme's warning tokens — same soft amber fill as the card's- // missing-model badge and the requirements list's "installable"- // rows, so the one signal reads the same everywhere it appears.<Buttonbg="bg.warning"color="fg.warning"diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsxindex dfbef1b56f..6c9fc9f282 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx@@ -16,19 +16,13 @@ import { act, StrictMode } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';-// A plain static import of the (mocked) module the dialog `lazy()`-loads, so-// its dynamic `import()` resolves against an already-loaded module record-// instead of paying a first-time compile cost mid-test — that cost is what-// made a cold run of the graph-preview wiring tests below flaky.+// Warm the mocked lazy module to avoid first-compile timing variability in preview wiring tests.import '@features/workflow/ui/graph-preview/GraphPreviewDialog';import { WorkflowLibraryDialog } from './WorkflowLibraryDialog';-// Task 8's graph preview wiring needs invocation templates loaded to compile-// a library entry's document (`buildLibraryGraphPreviewSource`); this suite-// never boots the real templates fetch, so it stubs the reactive snapshot-// hook with one template — matching the node type `PREVIEW_DOCUMENT` (below)-// uses — the same way `GraphPreviewDialog.browser.test.tsx` does.+// Provide the fixture node's reactive template snapshot so preview compilation can run without backend schema+// loading.const PREVIEW_NODE_TEMPLATE: InvocationTemplate = {category: 'test',classification: 'stable',@@ -55,9 +49,7 @@ vi.mock('@features/workflow/react', async (importOriginal) => ({useInvocationTemplatesSnapshot: () => TEMPLATES_SNAPSHOT,}));-// xyflow stays out of this shell test — the lazy-mounted `GraphPreviewDialog`-// (Task 8) is replaced with a stub that surfaces exactly what the wiring is-// responsible for: which graph got compiled, `hideInvoke`, and the close path.+// Stub preview rendering while exposing compiled graph, hideInvoke, and close behavior owned by dialog wiring.vi.mock('@features/workflow/ui/graph-preview/GraphPreviewDialog', () => ({GraphPreviewDialog: ({graphId,@@ -92,10 +84,7 @@ vi.mock('@features/workflow/ui/graph-preview/GraphPreviewDialog', () => ({),}));-// The browse store is Task 5's; this suite owns the *dialog*, so the store is-// replaced by a real external store the test drives directly plus spies for-// its four commands. Using a real store (not a stub hook) keeps the dialog's-// subscription, selector equality, and re-render path under test.+// Drive a real external browse store to retain subscription and selector behavior while spying on commands.const browse = vi.hoisted(() => ({ensureWorkflowLibraryBrowseLoaded: vi.fn(() => Promise.resolve()),// Assigned by the module factory below, which owns the store instance.@@ -131,9 +120,7 @@ vi.mock('@features/workflow/data/libraryBrowseStore', async () => {};});-// The load sequence (fetch → parse → replace → toasts) has its own behavior-// contract; this suite only asserts the dialog *invokes* it and reflects its-// phase in the busy overlay.+// Test loader invocation and busy-state wiring here; load sequencing has separate coverage.const loader = vi.hoisted(() => ({load: vi.fn(() => Promise.resolve()),phase: { current: 'idle' as 'applying' | 'fetching' | 'idle' },@@ -143,10 +130,7 @@ vi.mock('./useLoadLibraryWorkflow', () => ({useLoadLibraryWorkflow: () => ({ load: loader.load, loadPhase: loader.phase.current }),}));-// The detail panel resolves every entry's requirements against the model-// stores to feed the cards' missing-model badges. Those stores are the models-// feature's; here they are fixed data so the badge under test comes from the-// dialog's own wiring, not a live catalog.+// Use fixed model-store data so missing-model badges test dialog wiring rather than live catalogs.const FLUX_STARTER: StarterModel = {base: 'flux',description: 'FLUX.1 dev',@@ -167,9 +151,7 @@ vi.mock('@features/models', async (importOriginal) => ({selector({ response: { starter_models: [FLUX_STARTER] } }),}));-// The real i18n client fetches en.json over HTTP, which this browser test-// never boots. Stub `t` with the English strings this dialog renders (plus-// the `_one`/`_other` plural forms) so assertions check real copy.+// Provide English/plural strings without booting the HTTP-backed i18n client.const TRANSLATIONS: Record<string, string> = {'common.close': 'Close','workflowLibrary.allTag': 'All',@@ -216,8 +198,6 @@ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: translate }) }));const EMPTY_DOCUMENT = createProjectGraph('library-fixture');-// One `integer` node — matches `PREVIEW_NODE_TEMPLATE` above, so this is the-// document the graph-preview wiring tests compile.const PREVIEW_DOCUMENT: ProjectGraphState = projectGraphReducer(createProjectGraph('preview-fixture'), {node: buildInvocationNode(PREVIEW_NODE_TEMPLATE, { x: 0, y: 0 }),type: 'addNode',@@ -258,8 +238,7 @@ const PORTRAIT = entry('wf-portrait', 'Portrait Studio', readyEnrichment(12, 'sdtags: ['portrait'],thumbnailUrl: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==',});-// Its one requirement has no installed match but a starter that can fetch it,-// so the grid should badge it as one model to install.+// One absent requirement with a matching starter should show one model to install.const LANDSCAPE = entry('wf-landscape','Landscape Pass',@@ -275,9 +254,6 @@ const UPSCALE = entry(tags: ['upscale'],});-// The graph-preview wiring's own fixture: a `'ready'` entry whose document-// actually has a node, so the mocked preview dialog has a compiled graph to-// show instead of an empty one.const PREVIEW_FIXTURE = entry('wf-preview-fixture','Preview Fixture',@@ -308,8 +284,6 @@ const withSnapshot = (patch: Partial<WorkflowLibraryBrowseSnapshot>): WorkflowLi...patch,});-// The detail panel's ports. The dialog only has to compose them; their own-// suites cover what they do.const UI_ADAPTER = {notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },} as unknown as WorkflowUiAdapter;@@ -320,14 +294,7 @@ describe('WorkflowLibraryDialog', () => {let root: Root;let onOpenChange: (isOpen: boolean) => void;- /**- * Chakra's `SegmentGroup` tracks its indicator rect from an observer that- * commits React state a task after the commit that armed it. Under- * `StrictMode`'s mount/unmount/remount that lands in the gap *between* two- * `act` calls, where React's act queue is null — which is what raised the- * "update ... was not wrapped in act(...)" warnings. Awaiting this **inside**- * the same `act` scope as the render keeps the queue open across that gap.- */+ /** Await deferred SegmentGroup observer updates inside the render act scope, including StrictMode remounts. */const settleFrame = () =>new Promise<void>((resolve) => {setTimeout(resolve, 0);@@ -363,23 +330,14 @@ describe('WorkflowLibraryDialog', () => {});});- /**- * The lazy-loaded preview dialog (Task 8) resolves its `import()` on its- * own schedule — a fixed `wait` is either too short (flaky) or padded- * (slow), and letting it resolve outside `act` is what raises "a suspended- * resource finished loading" warnings. Polling inside `act` keeps every- * check, and the eventual resolution, in the same act scope.- */+ /** Poll lazy preview resolution inside act to avoid timing-dependent waits and suspended-resource warnings. */const waitForPreviewDialog = () =>act(async () => {await vi.waitFor(() => {expect(document.querySelector('[data-preview-dialog]')).not.toBeNull();},- // Padded past `vi.waitFor`'s default 1000ms: the static side-effect- // import above keeps the module warm, but the dynamic `import()`- // still costs a real (if now small) round trip through Vite's module- // graph before `Suspense` re-renders.+ // Allow time for Vite's dynamic-import round trip even when the module is warm.{ timeout: 2000 });});@@ -427,8 +385,7 @@ describe('WorkflowLibraryDialog', () => {await act(async () => {viewport?.dispatchEvent(new Event('scroll'));- // The ScrollArea machine reacts to the scroll a task later; see- // `settleFrame` for why that has to stay inside this `act` scope.+ // Settle deferred ScrollArea reactions within the same act scope.await settleFrame();});};@@ -585,8 +542,6 @@ describe('WorkflowLibraryDialog', () => {expect(card('wf-landscape')?.getAttribute('aria-pressed')).toBe('true');- // A filter change drops the selected row; selection falls back to the head- // of the new list rather than pointing at nothing.await act(() => browse.setSnapshot?.(withSnapshot({ entries: [SKETCH, UPSCALE] })));expect(card('wf-sketch')?.getAttribute('aria-pressed')).toBe('true');@@ -619,10 +574,7 @@ describe('WorkflowLibraryDialog', () => {});it('shows the loading copy on the very first paint, before the store leaves idle', async () => {- // The pristine store: `ensureWorkflowLibraryBrowseLoaded` only flips the- // status to 'loading' from the open-time effect, so the first paint of a- // freshly-booted session renders against 'idle'. That must never read as- // "nothing matched".+ // Initial idle state precedes loading and must not render as no matches.await openWith({entries: [],error: null,@@ -718,8 +670,6 @@ describe('WorkflowLibraryDialog', () => {it('badges the cards with the models their workflows still need', async () => {await openWith(LOADED_SNAPSHOT);- // Resolved from the same model data the rail uses: the FLUX slot has no- // installed match but a starter that can fetch it.expect(card('wf-landscape')?.textContent).toContain('Install 1 model');expect(card('wf-portrait')?.textContent).not.toContain('Install');});@@ -769,8 +719,7 @@ describe('WorkflowLibraryDialog', () => {await clickText('Close preview');- // Still mounted, now closed: unmounting here is what skipped the exit- // animation and made the preview vanish.+ // Keep the closing preview mounted until its exit animation finishes.expect(document.querySelector('[data-preview-dialog]')?.getAttribute('data-preview-open')).toBe('false');expect(document.querySelector('[data-pending-preview]')).not.toBeNull();@@ -808,16 +757,10 @@ describe('WorkflowLibraryDialog', () => {expect(document.querySelector('[data-preview-dialog]')).not.toBeNull();- // The dialog's own Close control is the only path that ever flips `isOpen`- // to `false` in the real app (`WorkflowWidgetChrome` only ever sets it- // back to `true`) — clicking it exercises the same reset the parent- // relies on. The isOpen round trip below then confirms the closed render- // drops the mount and the reopened one does not bring it back.+ // Use the dialog's real Close path, then reopen through controlled props to verify reset and mount cleanup.const closeButton = document.querySelector<HTMLButtonElement>('button[aria-label="Close"]');expect(closeButton).not.toBeNull();- // Chakra's `Dialog` commits its close transition a task after the click- // (the same class of gap `settleFrame` exists for, above) — settle inside- // this `act` scope rather than a bare click.+ // Settle deferred Dialog close transitions inside act.await act(async () => {closeButton?.click();await settleFrame();@@ -870,8 +813,7 @@ describe('WorkflowLibraryDialog', () => {expect(railViewport).not.toBeNull();expect(railViewport?.scrollWidth).toBeLessThanOrEqual((railViewport?.clientWidth ?? 0) + 1);- // The rail is where the user decides whether to open a workflow, so the- // whole name is on screen — wrapped over several lines, never clipped.+ // The detail rail must wrap the full workflow name without clipping.const heading = [...(detail?.querySelectorAll('p') ?? [])].find((element) => element.textContent === LONG_NAME);expect(heading, 'the full name should be rendered').not.toBeUndefined();expect(heading?.scrollWidth).toBeLessThanOrEqual((heading?.clientWidth ?? 0) + 1);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsxindex f55fea5467..5c2ca184f4 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx@@ -22,25 +22,13 @@ import { WorkflowLibraryGrid } from './WorkflowLibraryGrid';import { WorkflowLibraryTagChips } from './WorkflowLibraryTagChips';import { useWorkflowLibraryMissingCounts } from './WorkflowRequirementsList';-/**- * xyflow (~174 KB) stays out of this dialog's own chunk: the preview dialog- * is only ever needed once a card asks to preview it, so it is dynamic- * `import()`ed here rather than statically imported like every other panel- * in this file (mirrors `WidgetActionsMenu.tsx`'s `GraphPreviewHost`).- */+/** Load graph preview only on request to keep xyflow outside the library dialog's initial chunk. */const LazyGraphPreviewDialog = lazy(() =>import('@features/workflow/ui/graph-preview/GraphPreviewDialog').then((module) => ({default: module.GraphPreviewDialog,})));-/**- * Backend workflow library browser. Filtering and paging are server side and- * live in the browse store, so this shell owns exactly two pieces of state:- * the raw text in the search box (debounced into the store) and which card is- * selected. Everything else is read back out of the store.- */-const SEARCH_DEBOUNCE_MS = 300;const CATEGORY_ITEMS = [@@ -59,11 +47,8 @@ const selectBrowseView = (snapshot: WorkflowLibraryBrowseSnapshot) => ({});/**- * Mounted only while the dialog is open, so its mount effect *is* the "dialog- * opened" hook: it kicks the first page load and, on a fresh install with no- * saved workflows, lands the user on the bundled defaults instead of an empty- * "Yours". The switch is skipped if the user has already moved the filter- * while the probe was in flight.+ * On open, load the first page and choose defaults for empty accounts only if filters have not changed during the+ * probe.*/const WorkflowLibraryBrowseSession = () => {useMountEffect(() => {@@ -91,25 +76,16 @@ export const WorkflowLibraryDialog = ({const templatesSnapshot = useInvocationTemplatesSnapshot();const [searchInput, setSearchInput] = useState('');const [selectedWorkflowId, setSelectedWorkflowId] = useState<string | null>(null);- // The record of which workflow the rail asked to preview — mounts the lazy- // preview dialog below while set. This dialog shell is never unmounted while- // the app is up (only its `isOpen` toggles), so every path that can close- // *this* dialog has to clear it too, or a stale preview would resurrect- // itself the next time the library opens.+ // Clear pending preview entries on every library-close path because the persistent shell otherwise resurrects+ // them on reopen.const [previewEntry, setPreviewEntry] = useState<WorkflowLibraryEntry | null>(null);- // Tracked separately from `previewEntry` so closing the preview can play its- // exit transition: `isPreviewOpen` goes false first, and the entry (which is- // what keeps the lazy dialog mounted) is only released once the transition- // has finished.+ // Close before clearing previewEntry so the lazy dialog remains mounted through its exit transition.const [isPreviewOpen, setIsPreviewOpen] = useState(false);- // A right-click selects the card so the rail (which owns the actions) shows- // that workflow, then the rail opens its menu at the pointer.const [contextMenuPoint, setContextMenuPoint] = useState<{ x: number; y: number } | null>(null);const searchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const closeDialog = useCallback(() => {- // The library itself is leaving, and it takes the preview with it — there- // is nothing left to animate against, so this drops the mount outright.+ // Closing the library removes its preview immediately; the parent surface is leaving too.setPreviewEntry(null);setIsPreviewOpen(false);setContextMenuPoint(null);@@ -119,8 +95,7 @@ export const WorkflowLibraryDialog = ({const isLoadPending = loadPhase !== 'idle';const missingCounts = useWorkflowLibraryMissingCounts(entries);- // Selection is derived, not stored: a filter change or a deletion can retire- // the selected row, and the head of the list takes over without an effect.+ // Derive a fallback selection when filtering/deletion removes the selected row.const activeWorkflowId = entries.some((entry) => entry.item.workflow_id === selectedWorkflowId)? selectedWorkflowId: (entries[0]?.item.workflow_id ?? null);@@ -161,10 +136,7 @@ export const WorkflowLibraryDialog = ({}}, [isPreviewOpen]);- // Only a `'ready'` enrichment carries the compiled document; the rail's- // Preview action is disabled for anything else, so this is a defensive- // fallback (a stale `previewEntry` from before a revalidation), not a path- // the UI can normally reach.+ // Only ready enrichment has a document; guard stale preview entries after revalidation.const previewSource = useMemo(() => {if (!previewEntry || previewEntry.enrichment.status !== 'ready' || templatesSnapshot.status !== 'loaded') {return null;@@ -182,8 +154,7 @@ export const WorkflowLibraryDialog = ({clearTimeout(searchTimerRef.current);}- // Deliberately not a `useEffect` cleanup: a debounce that fires after- // unmount only patches the store the next open would reload anyway.+ // A post-unmount search debounce may update the browse store for the next opening.searchTimerRef.current = setTimeout(() => setWorkflowLibraryBrowseFilter({ search: value }), SEARCH_DEBOUNCE_MS);}, []);@@ -212,8 +183,6 @@ export const WorkflowLibraryDialog = ({const handleOpenItem = useCallback((item: WorkflowLibraryListItem) => void load(item), [load]);- // The deleted row is gone from the next refresh; dropping the selection lets- // the head of the list take over, the same way a filter change does.const handleDeleted = useCallback(() => {setSelectedWorkflowId(null);setContextMenuPoint(null);@@ -288,10 +257,7 @@ export const WorkflowLibraryDialog = ({</SegmentGroup.Item>))}</SegmentGroup.Root>- {/* In the header row rather than the dialog's absolutely- positioned corner: with a second header row of tag chips- underneath, the corner placement floated the control- across both bands instead of reading as part of either. */}+<Dialog.CloseTrigger asChild><CloseButtondisabled={isLoadPending}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsxindex d5b4e8ad19..63ecb2a854 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx@@ -9,12 +9,6 @@ import { useTranslation } from 'react-i18next';import { WorkflowLibraryCard, type WorkflowLibraryCardProps } from './WorkflowLibraryCard';-/**- * The scrolling card grid. Paging is server side and append-only: reaching the- * bottom of the accumulated pages asks the browse store for the next one,- * which no-ops once the last page has landed.- */-/** How close to the bottom (in viewports) counts as "fetch the next page". */const NEAR_BOTTOM_VIEWPORTS = 1.5;const GRID_TEMPLATE_COLUMNS = 'repeat(3, minmax(0, 1fr))';@@ -95,9 +89,7 @@ export const WorkflowLibraryGrid = ({const visibleEntries = useMemo(() => dedupeByWorkflowId(entries), [entries]);const hasEntries = visibleEntries.length > 0;- // 'idle' is the store before anything has been asked of it. The dialog's- // open-time load flips it to 'loading', but only after this first paint —- // so an idle store is a load about to start, never "nothing matched".+ // Idle precedes the first open-time load; render loading rather than an empty result.const isPending = status === 'idle' || status === 'loading';return (diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryTagChips.tsxindex 5cc8b619d6..42a738ed05 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx@@ -5,12 +5,7 @@ import { Button, Scrollable } from '@platform/ui';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';-/**- * Single-select tag filter for the library grid. The counts come from the- * backend for the whole category, not the loaded page, so a chip's number- * still means "how many workflows carry this tag" after infinite scroll has- * only fetched the first page.- */+/** Tag counts cover the whole backend category, not merely loaded infinite-scroll pages. */// A ScrollArea root defaults to `height: 100%` and grows to its content's// max-content width, so a chip strip needs both an explicit height and andiff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.browser.test.tsxindex 80846a2b08..cbb50351a7 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.browser.test.tsx@@ -9,13 +9,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { useWorkflowLibraryMissingCounts } from './WorkflowRequirementsList';-/**- * The browse store publishes a fresh `entries` array every time a *single*- * workflow finishes enriching, with four workers running — so loading a page- * of 20 re-runs this hook 20 times. Resolution is therefore cached per- * enrichment object, and this suite is the proof: the real resolver is wrapped- * in a spy, and the assertion is how many entries each publish re-resolves.- */+/** Count resolver calls across per-entry enrichment updates to verify unchanged rows reuse cached resolutions. */const resolveSpy = vi.hoisted(() => vi.fn());vi.mock('@features/workflow/core/modelRequirements', async (importOriginal) => {@@ -128,9 +122,7 @@ describe('useWorkflowLibraryMissingCounts', () => {resolveSpy.mockClear();- // What the store publishes when one more workflow finishes parsing: a new- // array, a new entry object for the row that changed, and the untouched- // entry (and its enrichment) carried over by identity.+ // Preserve unchanged entry/enrichment identities when another row completes.await render([stable, entry('wf-b', readyEnrichment())]);expect(resolveSpy).toHaveBeenCalledTimes(1);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsxindex a8682a43f7..abb46bbdb9 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsx@@ -21,12 +21,7 @@ import { CheckIcon, DownloadIcon, TriangleAlertIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-/**- * "Requires": one row per model a workflow needs, resolved against what is- * installed, what the starter catalog can fetch, and what is already- * downloading. The rows stay neutral — only the *installable* state earns the- * amber download treatment, because it is the only one the user can act on.- */+/** Highlight installable requirements only; other missing states have no actionable download. */const SKELETON_ROW_COUNT = 2;const EMPTY_STARTERS: readonly StarterModel[] = [];@@ -63,12 +58,7 @@ export interface ModelRequirementDeps {activeInstallSources: ReadonlySet<string>;}-/**- * The three inputs every requirement resolution needs, plus the one-time load- * of the two catalogs behind them. Both the detail panel and the grid's- * missing-model badges read them through here, so they always resolve against- * the same data.- */+/** Share catalog loading and resolution inputs between details and grid badges. */export const useModelRequirementDeps = (): ModelRequirementDeps => {const installedModels = useModelsSelector(selectInstalledModels);const starterModels = useStartersSelector(selectStarterModels);@@ -88,13 +78,8 @@ export const useModelRequirementDeps = (): ModelRequirementDeps => {type ReadyEnrichment = Extract<WorkflowLibraryEntryEnrichment, { status: 'ready' }>;/**- * Resolution is keyed by the enrichment object because that is exactly what- * changes when one workflow finishes parsing: the browse store publishes a new- * `entries` array per *individual* completion, with four workers running, so a- * page of 20 lands 20 arrays. Without this, every one of those would re-resolve- * every row — quadratic, synchronously, in render. The deps the entry was- * resolved under are stored alongside, so a model install or a starter-catalog- * load invalidates the entry as it should.+ * Cache by enrichment identity and catalog dependencies to avoid quadratic row resolution as individual entries+ * finish parsing.*/const resolutionCache = new WeakMap<ReadyEnrichment,@@ -119,13 +104,7 @@ export const resolveEntryRequirements = (return resolved;};-/**- * How many models each card would have to *download* to run — the count the- * grid badges and, on the selected card, exactly what the panel's Install- * button offers to fetch. Requirements nothing in the catalog can satisfy are- * deliberately excluded: an "Install 3 models" badge that installs 2 is worse- * than a quiet card.- */+/** Count only models the install action can download so card badges agree with the offered operation. */export const useWorkflowLibraryMissingCounts = (entries: readonly WorkflowLibraryEntry[]): ReadonlyMap<string, number> => {@@ -167,8 +146,6 @@ const RequirementRow = ({const presentation = STATUS_PRESENTATION[resolved.status];const statusLabel = t(presentation.labelKey);const { label } = resolved.requirement;- // `null` for rows there is nothing to install (already installed, or nothing- // the query could name) — those stay plain text.const searchTerm = getAddModelsSearchTerm(resolved);const canFindModel = Boolean(onFindModel) && searchTerm !== null;const handleFindModel = useCallback(() => {@@ -220,8 +197,6 @@ export interface WorkflowRequirementsListProps {export const WorkflowRequirementsList = ({ errorMessage, resolved, onFindModel }: WorkflowRequirementsListProps) => {const { t } = useTranslation();- // A readable workflow that needs no models says so by omission, not by an- // empty section header.if (!errorMessage && resolved?.length === 0) {return null;}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.test.tsindex 4fafd576d7..27365e80c8 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.test.ts@@ -159,13 +159,10 @@ describe('createLibraryAutosaver', () => {h.autosaver.notifyGraphChanged();h.autosaver.dispose();- // The pending debounce timer was flushed into a chained rerun queued behind- // the in-flight save, so no new timer should remain.expect(h.manual.pendingCount()).toBe(0);resolveSave!();- // The in-flight promise is never cancelled by dispose; it settles, then the- // chained runSave() picks up the newer edit and saves it too.+ // Disposal allows the in-flight write and its chained newer edit to finish.await vi.waitFor(() => expect(h.save).toHaveBeenCalledTimes(2));expect(h.save).toHaveBeenLastCalledWith('wf-1', { nodes: [2] });});@@ -206,10 +203,7 @@ describe('createLibraryAutosaver', () => {});it('does not report saved while an edit made during the save is still unwritten', async () => {- // The dangerous direction: an older save's acknowledgement lands after a- // newer edit has already marked the graph dirty. Reporting 'saved' there- // tells someone their work is safe during the window in which it is not,- // and that is exactly when they close the tab.+ // An old acknowledgement must not mark newer unsaved content saved.const h = createHarness();let resolveSave: () => void;const deferred = new Promise<void>((resolve) => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.tsindex 0beb3b196e..9252fa90ac 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.ts@@ -1,20 +1,6 @@/**- * Figma-style library sync: a project graph bound to a library workflow saves- * itself back to the library after edits settle. Content-addressed dedupe (the- * serialized JSON string) prevents echo saves; a failed save parks in 'error'- * and is retried by the next graph change or an explicit flush(). No automatic- * retry loop — persistent failures must not spin (cf. bitmapStore anti-spin).- *- * A save's acknowledgement only reports 'saved' if no edit arrived while it was- * in flight; otherwise the status stays 'dirty' and the queued write reports- * for itself. The status is a promise about the person's current work, not a- * receipt for whichever bytes happened to be in the last request.- *- * dispose() flushes rather than drops: a pending debounced edit is an unsaved- * change, so unmount collapses it into one final save (status callbacks stay- * muted). Known limitation: a hard tab close inside the debounce window can- * still lose the final write — there is no pagehide/keepalive path. Fixing- * that needs a transport-level keepalive decision and is out of scope here.+ * Deduplicate serialized content and retry failures only on edits/flush. Report saved only without newer edits.+ * Dispose flushes silently; hard tab closes can still lose debounced writes.*/export type LibrarySyncStatus = 'idle' | 'dirty' | 'saving' | 'saved' | 'error';@@ -45,14 +31,8 @@ export const createLibraryAutosaver = (deps: LibraryAutosaverDeps) => {let lastSavedJson: string | null = null;let disposed = false;/**- * Bumped by every graph change. A save captures it after serializing, so a- * captured value that no longer matches means the person edited again while- * the write was in flight and the answer we just got is about older content.- *- * Only the success path consults it, because the two ways of being wrong are- * not symmetric: claiming 'saved' over unwritten work invites someone to- * close the tab, while claiming 'error' or 'dirty' over work that did land- * costs one redundant save. Failures still report as failures.+ * Increment revision per edit; stale successes remain dirty while failures still report error rather than+ * claiming unwritten work is safe.*/let editGeneration = 0;@@ -65,9 +45,7 @@ export const createLibraryAutosaver = (deps: LibraryAutosaverDeps) => {const runSave = (): Promise<void> => {if (inFlight) {- // A save is running; chain another pass after it so content edited- // mid-save is picked up. The rerun re-reads and dedupes, so it no-ops- // when nothing newer landed — the chain always terminates.+ // Chain a rereading, deduplicating pass after active saves so mid-save edits persist without endless reruns.return inFlight.then(() => runSave());}@@ -121,9 +99,7 @@ export const createLibraryAutosaver = (deps: LibraryAutosaverDeps) => {return;}disposed = true;- // A pending debounce is an unsaved edit; losing it on unmount is data- // loss, so the timer collapses into one immediate final save. Status- // callbacks stay muted (disposed) — only the write itself survives.+ // Flush pending edits on disposal while muting status callbacks.const hasPendingEdit = timerHandle !== null;clearTimer();if (hasPendingEdit) {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.test.tsindex 2f18d9a1b2..61bdcc2bfe 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.test.ts@@ -121,9 +121,7 @@ describe('buildLibraryGraphPreviewSource', () => {it('surfaces a compile failure as an invalid reason instead of throwing', () => {const { doc } = buildDocument();- // A malformed cached document (the shape a corrupted library record could- // produce) — `nodes` is not an array, so compilation throws instead of- // silently producing an empty graph.+ // Malformed cached node collections must exercise compilation failure rather than an empty successful graph.const corrupt = { ...doc, nodes: null } as unknown as ProjectGraphState;const result = buildLibraryGraphPreviewSource(corrupt, templates);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.tsindex 266c8df183..2e5f513650 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts@@ -4,15 +4,8 @@ import { ForLoopGraphValidationError } from '@features/workflow/core/forLoops';import { compileProjectGraph } from '@features/workflow/graph';/**- * The graph preview dialog's data source for a library entry — the library- * equivalent of `workbench/widget-frame/graphPreviewSource.ts`'s workflow- * branch, minus the active project: a library entry previews its own saved- * document, not the live project graph, so the result is never live and- * carries no destination (the entry has not been opened into a project yet).- *- * `document`/`templates` come from a `'ready'` library enrichment, which only- * exists once templates have loaded — so the try/catch below is defensive- * (a malformed cached document), not an expected path.+ * Preview the entry's saved document without active-project destination or live updates; catch malformed cached+ * data despite ready enrichment.*/export const buildLibraryGraphPreviewSource = (document: ProjectGraphState,@@ -29,8 +22,6 @@ export const buildLibraryGraphPreviewSource = (isLive: false,notices: [],positionHints,- // No node-count row: the side panel's summary already opens with one, and- // adding it here rendered "Nodes" twice.summaryRows: [],};} catch (error) {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/librarySyncBridge.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/librarySyncBridge.tsindex 6bf6d9e9ef..04a3f49122 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/librarySyncBridge.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/librarySyncBridge.ts@@ -1,13 +1,6 @@/**- * Module-level bridge to the single mounted `WorkflowDialogHost`'s library- * autosaver, mirroring `editor/flowInstanceStore.ts`'s pattern for surfaces- * that need to reach a widget-scoped instance without threading it through- * props or importing the chrome component (which would cycle back through- * this directory). `WorkflowDialogHost` registers its autosaver's- * `markSynced` in a mount effect; `WorkflowLibraryDialog`'s load path and- * `useSaveWorkflowToLibrary` call `markLibraryGraphSynced` after a- * load/save so the freshly-synced content is not immediately queued for- * another autosave pass.+ * Expose the mounted autosaver's markSynced without importing chrome; load/save paths use it to prevent immediate+ * echo autosaves.*/type MarkSyncedFn = (serialized: Record<string, unknown>) => void;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/relativeTime.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/relativeTime.tsindex 539e920dce..6433fb6107 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/relativeTime.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/relativeTime.ts@@ -1,8 +1,4 @@-/**- * "2 days ago" captions for the library's `last_run_at` stamps. The clock is- * injected rather than read here, so the caption a test asserts is the caption- * the panel renders — `Date.now()` lives at the call site only.- */+/** Inject current time so relative captions remain deterministic. */const DIVISIONS: readonly { amount: number; unit: Intl.RelativeTimeFormatUnit }[] = [{ amount: 60, unit: 'second' },@@ -14,8 +10,6 @@ const DIVISIONS: readonly { amount: number; unit: Intl.RelativeTimeFormatUnit }[{ amount: Number.POSITIVE_INFINITY, unit: 'year' },];-// `numeric: 'auto'` so the single-unit steps read as "yesterday"/"last week"-// instead of "1 day ago" — matching the Launchpad's project timestamps.const formatter = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });/** Empty string for timestamps that cannot be read, so callers drop the caption entirely. */diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.tsindex 7cf9b91be0..a586fde553 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.ts@@ -16,13 +16,7 @@ import { useTranslation } from 'react-i18next';import { markLibraryGraphSynced } from './librarySyncBridge';-/**- * The library's "open this workflow into the project graph" sequence, shared- * by every surface that can start it (the library grid's double-click and its- * Open action). Two loads can never overlap — a second call while one is in- * flight is dropped rather than queued, because the winner would silently- * replace the graph the first one just applied.- */+/** Drop overlapping workflow-open requests; a queued second load would silently replace the first applied graph. */export type WorkflowLoadPhase = 'applying' | 'fetching' | 'idle';@@ -67,9 +61,7 @@ export const useLoadLibraryWorkflow = (onLoaded: () => void): LoadLibraryWorkfloassertAccountScopeCurrent(owner);replace(document, t('workflowLibrary.loadedLabel', { name: item.name }));requestWorkflowFitView(document.nodes);- // The freshly-loaded graph is already in sync with the library record- // it came from — mark it synced so the autosaver does not immediately- // queue a redundant (echo) save the moment the graph reference changes.+ // Mark loaded content synced before changed graph identity can schedule an echo save.markLibraryGraphSynced(serializeWorkflowJson(document));for (const warning of warnings) {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.browser.test.tsxindex fcd36bcaf6..58f09105cc 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.browser.test.tsx@@ -62,19 +62,7 @@ const createMutablePort = <Snapshot,>(initialSnapshot: Snapshot) => {};};-/**- * Regression coverage for the create-path echo-autosave bug (`saveToLibrary`- * on a graph with no `libraryWorkflowId` yet):- * `bindLibraryWorkflow` synchronously adds `libraryWorkflowId` to the- * stored project graph, but the hook used to mark the autosaver's baseline- * with the JSON it had serialized *before* the bind — which- * `serializeWorkflowJson` does not include `id` (added only once- * `libraryWorkflowId` is set). The library autosaver's own `read()`- * re-serializes the *current* (now-bound) graph, which does include `id`, so- * the mismatch looked like a dirty edit and queued a redundant PUT of- * otherwise-identical content on the next debounce. The fix re-serializes- * from the post-bind store snapshot before marking synced.- */+/** Baseline newly created workflows from the post-bind graph, including its ID, to prevent a redundant autosave. */describe('useSaveWorkflowToLibrary bind-then-sync', () => {let host: HTMLDivElement;let root: Root;@@ -156,10 +144,8 @@ describe('useSaveWorkflowToLibrary bind-then-sync', () => {expect(bindLibraryWorkflow).toHaveBeenCalledWith('library-workflow-99');expect(syncedCalls).toHaveLength(1);- // What the library autosaver's own read() would produce right now,- // from the bound store — the synced baseline must match this exactly- // (same content AND key order, since the autosaver dedupes on the- // stringified JSON) or the bind alone is read back as a dirty edit.+ // Synced baseline must match current serialization content and key order because deduplication compares JSON+ // strings.const expectedPostBindSerialized = serializeWorkflowJson(project.port.getSnapshot().projectGraph);expect(JSON.stringify(syncedCalls[0])).toBe(JSON.stringify(expectedPostBindSerialized));@@ -170,12 +156,7 @@ describe('useSaveWorkflowToLibrary bind-then-sync', () => {});});-/**- * `saveDocumentAsNew` saves an arbitrary document (e.g. a preview payload- * that never became the active project graph) to the library. Unlike- * `saveToLibrary`, it must not bind the result to the project or mark the- * autosaver's synced baseline — the active project graph is untouched.- */+/** Saving arbitrary preview documents must not bind or change the active project's autosave baseline. */describe('useSaveWorkflowToLibrary saveDocumentAsNew', () => {let host: HTMLDivElement;let root: Root;@@ -259,8 +240,6 @@ describe('useSaveWorkflowToLibrary saveDocumentAsNew', () => {expect(createLibraryWorkflowMock.mock.calls[0]?.[0]).toStrictEqual(serializeWorkflowJson(document));expect(bindLibraryWorkflow).not.toHaveBeenCalled();expect(invalidateWorkflowLibraryCacheMock).toHaveBeenCalledTimes(1);- // The active project graph (a different document from the one saved)- // must be untouched: no libraryWorkflowId leaked onto it.expect(project.port.getSnapshot().projectGraph.libraryWorkflowId).toBeUndefined();});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.tsindex 7bea78c00f..b986173eed 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts@@ -25,11 +25,8 @@ import { markLibraryGraphSynced } from './librarySyncBridge';import { setWorkflowLibrarySyncStatus } from './workflowLibrarySyncStore';/**- * Saves the project graph to the backend workflow library — the chrome- * header's one-click save for unbound graphs, and the graph preview's "save- * this document as a new entry". A successful save also marks the autosaver's- * baseline (`markLibraryGraphSynced`) so the freshly-saved content is not- * immediately queued for another autosave pass.+ * Save active graphs with a matching autosave baseline; arbitrary preview documents can be saved separately as new+ * records.*/export const useSaveWorkflowToLibrary = (): {saveDocumentAsNew: (document: ProjectGraphState) => Promise<string | null>;@@ -69,13 +66,8 @@ export const useSaveWorkflowToLibrary = (): {bindLibraryWorkflow(workflowId);notify.success(t('workflowLibrary.saved'), t('workflowLibrary.savedCreatedBody', { name }));- // bindLibraryWorkflow dispatches synchronously, so the store already- // reflects the bound `libraryWorkflowId`. Re-serialize from that- // post-bind graph (rather than reusing the pre-bind `serialized`,- // which has no `id`) so the autosaver's synced baseline matches- // exactly what its own read() will produce next — otherwise the id- // key `serializeWorkflowJson` adds on bind reads as a dirty edit and- // triggers a redundant echo save on the next debounce.+ // Serialize the synchronous post-bind snapshot so the baseline includes its new library ID and cannot+ // trigger an echo save.syncedSerialized = serializeWorkflowJson(projectStore.getSnapshot().projectGraph);}@@ -94,11 +86,7 @@ export const useSaveWorkflowToLibrary = (): {}}, [bindLibraryWorkflow, notify, projectGraph, projectStore, t]);- // Saves an arbitrary document — not necessarily the active project graph —- // as a new library entry. Used by "Open as → Save to workflow library" for- // a preview payload that may never have become the active project. Unlike- // `saveToLibrary`, this never binds the result to the project or marks the- // autosaver's synced baseline: the active project graph is left alone.+ // Save arbitrary documents as new entries without binding the active project or updating its autosave baseline.const saveDocumentAsNew = useCallback(async (document: ProjectGraphState): Promise<string | null> => {const owner = captureAccountScope();diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsxindex d7ad611ddc..35357b46e3 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx@@ -82,14 +82,8 @@ import {import { NodeFieldControl, useNodeFieldBinding } from './NodeFieldControl';/**- * The form builder: edit mode of the Linear UI. Every element renders as a- * card with its own title bar — type label on the left, actions on the right,- * content below — mirroring the legacy builder. Cards reorder and reparent by- * dragging their title bar (drop indicators above/below, containers accept- * drops into their body) via dnd-kit: moves happen only at `onDragEnd`, which- * fires at the `DndContext` level regardless of whether the drop reparents- * (and therefore remounts) the dragged card. All edits go through the- * project graph document reducer.+ * Commit form moves only at DndContext onDragEnd so reparenting remounts cannot lose completion; all edits use the+ * document reducer.*/interface BuilderDndContextValue {@@ -102,15 +96,7 @@ const BuilderDndContext = createContext<BuilderDndContextValue>({form: { elements: {}, rootElementId: '' },});-/**- * Split out from `BuilderDndContext`: `dropTarget` changes on every- * `onDragMove` frame while a drag is in flight, while `activeElementId`/- * `form` only change at drag start/end. Bundling them would force every- * card to re-render per pointer move (cards read `BuilderDndContext` for- * opacity/disabled state); only the drop-indicator components below read- * this one, so a move re-renders just the indicator for the affected card- * or container.- */+/** Separate per-move drop targets from start/end drag state so only indicators rerender while the pointer moves. */const BuilderDropTargetContext = createContext<FormDropTarget | null>(null);/** The dragged card's `DragOverlay` ghost: a compact title bar following the pointer. */@@ -134,11 +120,7 @@ const BuilderDragGhost = ({ element }: { element: WorkflowFormElement }) => (</HStack>);-/**- * The edge drop-indicator line above/below a card. The only piece of a card- * that needs to know `dropTarget` — isolated into its own component so it's- * also the only piece that re-renders on every drag-move frame.- */+/** Isolate edge indicators as the card's only per-move drop-target consumers. */const CardDropEdgeIndicator = ({ elementId }: { elementId: string }) => {const dropTarget = use(BuilderDropTargetContext);const edge = dropTarget?.kind === 'edge' && dropTarget.elementId === elementId ? dropTarget.edge : null;@@ -183,13 +165,8 @@ const BuilderCardBase = ({const { editGraph } = useProjectGraphCommands();const { activeElementId, form } = use(BuilderDndContext);const { attributes, listeners, setActivatorNodeRef, setNodeRef: setDragRef } = useDraggable({ id: element.id });- // The title bar is both the draggable node and its own drag handle, so it- // needs both refs: `setActivatorNodeRef` is what makes `KeyboardSensor`- // enforce `event.target === activator` (dnd-kit's `KeyboardSensor.activators`- // check) — without it, `Space`/`Enter` bubbling up from the action buttons- // this title bar contains (Remove, Zoom to node, etc.) would also lift the- // card, the keyboard equivalent of the `onPointerDown` `stopPropagation`- // guard those buttons already carry for pointer drags.+ // Set both draggable and activator refs on title bars so keyboard actions bubbling from child buttons cannot+ // lift cards.const setDragHandleRef = useCallback((node: HTMLElement | null) => {setDragRef(node);@@ -251,20 +228,10 @@ const BuilderCardBase = ({);};-/**- * Memoized so a `dropTarget` change elsewhere in the form (a context update- * that only its parent `BuilderElement` would otherwise re-render for)- * doesn't cascade into every card — `BuilderCard` itself only reads- * `BuilderDndContext`, which changes solely at drag start/end.- */+/** Memoize cards so drop-target updates do not propagate beyond the indicator consumers. */const BuilderCard = memo(BuilderCardBase);-/**- * The container drop-zone's hover styling and "drop here" vs. "empty" copy.- * The only piece of `ContainerDropZone` that needs `dropTarget` — isolated- * into its own component so it's also the only piece that re-renders on- * every drag-move frame.- */+/** Isolate container hover/copy updates from the rest of the drop zone. */const ContainerDropZoneBody = ({canDrop,containerId,@@ -522,14 +489,8 @@ const BuilderElementBase = ({};/**- * Memoized so `FormBuilderTab`'s per-drag-move `dropTarget` state update- * (a plain `useState` re-render, unrelated to any of this component's own- * props) doesn't re-invoke every card's render function on every pointer- * move — none of `element`/`hoveredNodeId`/`invalidElementIds`/- * `projectGraph`/`selectedNodeIds` change mid-drag, so this bails and the- * `dropTarget` update only reaches the drop-indicator components that- * subscribe to `BuilderDropTargetContext` directly (context updates reach- * their consumers regardless of memoized ancestors in between).+ * Memoized elements retain stable mid-drag props; only direct drop-target context consumers rerender on pointer+ * movement.*/const BuilderElement = memo(BuilderElementBase);@@ -629,12 +590,8 @@ export const FormBuilderTab = ({ projectGraph }: { projectGraph: ProjectGraphSta// indicators and container hints appear mid-drag, so re-measure continuously.const measuring = useMemo(() => ({ droppable: { strategy: MeasuringStrategy.Always } }), []);const form = projectGraph.form;- // `DragMoveEvent.delta` is scroll-adjusted (translate + the panel's scroll- // offset baked in), so `activatorEvent.clientY + delta.y` overshoots the- // real pointer once the panel auto-scrolls while `over.rect` stays in- // fresh viewport coordinates. `collisionDetection`'s `args.pointerCoordinates`- // is the one place dnd-kit hands back the true (already scroll-correct)- // pointer position, so it's captured here and read in `handleDragMove`.+ // Capture collision pointerCoordinates; drag delta includes scroll adjustment and cannot be added to clientY+ // without overshooting.const pointerYRef = useRef<number | null>(null);const collisionDetection: CollisionDetection = useCallback((args) => {@@ -675,10 +632,7 @@ export const FormBuilderTab = ({ projectGraph }: { projectGraph: ProjectGraphStareturn;}- // The true (scroll-correct) pointer position when the drag has one- // (`PointerSensor`, captured from `collisionDetection`'s- // `pointerCoordinates`); a `KeyboardSensor` drag has no pointer, so fall- // back to the dragged card's translated center.+ // Use true pointer coordinates when available; keyboard drags use the translated card center.const activeRect = active.rect.current.translated;const referenceY = pointerYRef.current ?? (activeRect ? activeRect.top + activeRect.height / 2 : over.rect.top);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/LinearFormView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/LinearFormView.tsxindex 23f19162d5..243920d9c3 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/LinearFormView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/LinearFormView.tsx@@ -8,11 +8,6 @@ import { useCallback } from 'react';import { NodeFieldControl } from './NodeFieldControl';-/**- * The Linear UI's view mode: the form rendered as clean, runnable controls —- * field values stay editable, the form structure does not.- */-const ViewElement = ({ element, projectGraph }: { element: WorkflowFormElement; projectGraph: ProjectGraphState }) => {switch (element.type) {case 'container':diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsxindex 25e7abe6bf..d969fe96bf 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx@@ -21,11 +21,6 @@ import { DicesIcon, RotateCcwIcon } from 'lucide-react';import { useCallback, useMemo, useState, type ChangeEvent } from 'react';import { useTranslation } from 'react-i18next';-/**- * One exposed node field, shared by the Linear UI's view mode and the form- * builder: label (optionally editable), optional description, and the live- * input — or a note when the field is driven by a graph connection.- *//** Resolves a form element's node, field instance, and input template against the document. */export const useNodeFieldBinding = (element: NodeFieldFormElement, projectGraph: ProjectGraphState) => {const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);@@ -59,9 +54,7 @@ export const NodeFieldControl = ({element,projectGraph);- // While the label input is focused it edits a draft seeded from the- // *displayed* label, so an unset override starts from the template title- // instead of an empty box.+ // Seed focused label drafts from displayed text, including template fallback.const [draftLabel, setDraftLabel] = useState<string | null>(null);const isConnected = getResolvedWorkflowEdges(projectGraph.nodes, projectGraph.edges).some(diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsxindex d2478d3731..a290af91c4 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx@@ -20,12 +20,6 @@ import { JsonPreview, Scrollable, Tabs } from '@platform/ui';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';-/**- * Edit-mode inspector for the editor's selected node, with the legacy tab- * set: Details (summary + notes), Outputs, Data (raw node data), Template- * (the node's backend definition). Sizing is owned by the panel's Splitter.- */-type InspectorTab = 'details' | 'outputs' | 'data' | 'template';const getInspectorTab = (values: Record<string, unknown>): InspectorTab =>@@ -82,11 +76,6 @@ const DetailsTab = ({ node, template }: { node: WorkflowInvocationNode; template);};-/**- * What the node produced the last time it ran in this session: each declared- * output's value from the latest result, the image it saved (if any), and the- * raw result for anything the summary does not show.- */const OutputsTab = ({ nodeId, template }: { nodeId: string; template: InvocationTemplate | undefined }) => {const { t } = useTranslation();const execution = useWorkflowNodeExecutionState(nodeId);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 07dfbe91c8..4263863354 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,10 +19,8 @@ import { PanelModeToggle } from './WorkflowLinearPanel';(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-// 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.+// Probe renders through a passthrough hook spy; compiler memoization can skip pure helper calls independently of+// component renders.vi.mock('@dnd-kit/core', async (importOriginal) => {const actual = await importOriginal<typeof DndKitCoreModule>();@@ -93,12 +91,7 @@ describe('Workflow Linear panel mode toggle', () => {});});-/**- * 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.- */+/** A second drag after reparenting verifies completion survives dragged-card remounts through DndContext ownership. */describe('Form builder drag and drop (dnd-kit)', () => {let host: HTMLDivElement;let root: Root;@@ -225,11 +218,7 @@ describe('Form builder drag and drop (dnd-kit)', () => {await interact(() => pointer('pointerup', handle.ownerDocument, x, y + 1));};- /**- * 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.- */+ /** Keyboard drag uses Space/arrows/Space and a net-zero settle nudge for delayed measurement. */const dragToWithKeyboard = async (sourceTitle: string, targetCenterY: number): Promise<void> => {const handle = titleBarFor(sourceTitle);const startRect = handle.getBoundingClientRect();@@ -250,8 +239,6 @@ describe('Form builder drag and drop (dnd-kit)', () => {await interact(() => key(handle, direction));await interact(() => key(handle, opposite));- // Space drops, resolving the move through the same `onDragEnd` ->- // `moveFormElementTo` path the pointer drag uses.await interact(() => key(handle, 'Space'));};@@ -269,17 +256,12 @@ describe('Form builder drag and drop (dnd-kit)', () => {await dragTo('Heading', dropZoneRect.left + dropZoneRect.width / 2, dropZoneRect.top + dropZoneRect.height / 2);- // The container's card content now holds the heading card, and the- // empty-state hint is gone.const containerContent = cardContentFor('Container (column)');expect(containerContent.textContent).toContain('Heading');expect(containerContent.textContent).not.toContain('Empty container');- // Drag 2: THE REGRESSION ASSERTION. "Divider" (still at the root) drops- // onto the now-nested "Heading" card's lower edge. Under the old native- // DnD implementation, drag 1's reparent remount lost `dragend` and left- // `draggingElementId` stuck — this second drag would never start.+ // Immediately drag again after reparenting to catch lost completion state from the remounted source.const headingCardRect = titleBarFor('Heading').parentElement!.getBoundingClientRect();await dragTo('Divider', headingCardRect.left + headingCardRect.width / 2, headingCardRect.bottom - 2);@@ -296,17 +278,7 @@ describe('Form builder drag and drop (dnd-kit)', () => {expect(opacities).not.toContain('0.4');});- /**- * Regression coverage for the "keyboard drag" finding: the drag handle- * spreads dnd-kit's `attributes` (`role="button"`, `tabIndex=0`), which- * promises "press space to lift, arrows to move" — a promise only true- * once a `KeyboardSensor` is registered alongside the `PointerSensor`.- * There's no pointer during a keyboard drag, so `KeyboardSensor` moves the- * dragged card's tracked rect by a fixed 25px step per arrow press- * (dnd-kit's `defaultKeyboardCoordinateGetter`) and collision detection- * falls through to `rectIntersection` (`pointerWithin` needs real pointer- * coordinates, which a keyboard drag never has).- */+ /** Exercise KeyboardSensor and rectangle collision fallback; keyboard drags have no pointer coordinates. */it('moves a form element into a container with the keyboard', async () => {await renderHarness();@@ -326,16 +298,7 @@ describe('Form builder drag and drop (dnd-kit)', () => {expect(containerContent.textContent).not.toContain('Empty container');});- /**- * Coverage for the keyboard *edge* path specifically: the "into a- * container" case above never reaches `getFormDropEdge`'s card-center- * fallback (`handleDragMove` returns early for `into` targets before- * `referenceY` is even computed) — a keyboard drag has no- * `pointerCoordinates`, so this is the only path that exercises the- * fallback dnd-kit needs for a real "arrows move the card" keyboard drag.- * Moves "Divider" (root sibling, after "Heading") up onto the upper- * quarter of "Heading"'s card, landing 'above' it and reordering it first.- */+ /** Test keyboard edge targeting separately from container drops to exercise the translated-card-center fallback. */it('reorders a form element above a sibling with the keyboard', async () => {await renderHarness();@@ -355,16 +318,8 @@ describe('Form builder drag and drop (dnd-kit)', () => {});/**- * Perf isolation for `BuilderDropTargetContext`: `dropTarget` (per-move- * churn) lives apart from `BuilderDndContext`'s `activeElementId`/`form`- * (drag start/end only), and `BuilderElement` is memoized on props that- * don't change mid-drag — so a move that never targets "Divider" should- * never re-invoke its `BuilderCard`. Probed via the `useDroppable`- * passthrough spy (mocked at module scope above): `BuilderCard` calls it- * exactly once per render with `formEdgeDroppableId(element.id)`, and hook- * calls (unlike plain helper calls) can't be optimized away by the React- * Compiler, so a call carrying "Divider"'s edge-droppable id is direct,- * compiler-proof evidence its `BuilderCard` re-rendered.+ * Count untouched card hook calls during pointer moves to verify drop-target context isolation despite compiler+ * memoization.*/it('does not re-render an unrelated card on a drag-move that only changes the drop target', async () => {const initialGraph = buildInitialGraph();@@ -373,10 +328,7 @@ describe('Form builder drag and drop (dnd-kit)', () => {await renderHarness(initialGraph);- // The empty-container hint's rect, captured *before* the drag starts —- // once a drag is active this card's `canDrop` flips true and its own- // text changes from "Empty container..." to "Drop here", so the text- // selector below would no longer match if read mid-drag.+ // Capture the empty hint's rect before drag changes its text to Drop here.const emptyHint = [...host.querySelectorAll<HTMLElement>('*')].find((element) => element.textContent === 'Empty container — drag elements here');@@ -392,24 +344,14 @@ describe('Form builder drag and drop (dnd-kit)', () => {const startX = startRect.left + startRect.width / 2;const startY = startRect.top + startRect.height / 2;- // Arm the `PointerSensor` (>4px activation constraint), then settle onto- // the container's drop zone the same way `dragTo` does (a same-target- // no-op nudge — `MeasuringStrategy.Always`'s remeasure lands one tick- // after the move that triggered it, so a single move can still report a- // stale `over`). This establishes a real `into` `dropTarget`; only the- // moves *after* this point, which don't change the logical target, are- // under test.+ // Activate the sensor and settle delayed measurement before testing moves within one logical target.await interact(() => pointer('pointerdown', handle, startX, startY));await interact(() => pointer('pointermove', handle.ownerDocument, startX + 8, startY));await interact(() => pointer('pointermove', handle.ownerDocument, midX, midY));await interact(() => pointer('pointermove', handle.ownerDocument, midX, midY + 1));vi.mocked(useDroppable).mockClear();- // Two more moves inside the same drop zone: `over` (and therefore the- // *logical* `dropTarget`) doesn't change, but `handleDragMove` still- // calls `setDropTarget` with a fresh object every time `onDragMove`- // fires — that per-frame churn, not touching "Divider" at all, is- // exactly what's under test.+ // Move within the same target to exercise per-frame state churn without changing the intended drop.await interact(() => pointer('pointermove', handle.ownerDocument, midX, midY + 2));await interact(() => pointer('pointermove', handle.ownerDocument, midX, midY + 3));diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.tsxindex 09198c320f..8809f4da83 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.tsx@@ -13,13 +13,6 @@ import { NodeInspector } from './NodeInspector';import { WorkflowDetailsTab } from './WorkflowDetailsTab';import { WorkflowJsonTab } from './WorkflowJsonTab';-/**- * The workflow widget's side panel — the Linear UI. View mode runs the- * project graph through its form; Edit mode opens the legacy-style tab set- * (Form builder / Details / JSON) with the node inspector pinned below.- * Panel mode, tab, and inspector height live in the widget's own state.- */-type PanelMode = 'view' | 'edit';type EditTab = 'form' | 'details' | 'json';type PanelModeItem = {@@ -65,12 +58,8 @@ export const areWorkflowPanelStatesEqual = (left: WorkflowPanelState, right: Worleft.mode === right.mode && left.editTab === right.editTab && left.inspectorSizePct === right.inspectorSizePct;/**- * View / Edit selection. These swap the whole panel body, so they are tabs- * rather than a pressed-button pair: the tablist carries roving focus and- * arrow-key selection for free, which the hand-rolled `aria-pressed` group it- * replaced could not. The visible panels remain siblings because edit mode- * drives its own splitter layout; hidden content nodes keep every generated- * `aria-controls` relationship valid and describe what selecting the tab did.+ * Use tabs for roving focus and arrow selection; hidden content nodes preserve aria-controls while edit panels+ * retain their splitter layout.*/export const PanelModeToggle = ({ mode, onChange }: { mode: PanelMode; onChange: (mode: PanelMode) => void }) => {const { t } = useTranslation();@@ -80,8 +69,6 @@ export const PanelModeToggle = ({ mode, onChange }: { mode: PanelMode; onChange:);return (- // `mb="-1"` tucks the active-tab indicator onto the header's own bottom- // rule, the same trick the edit tabs use.<Tabs.Root mb="-1" size="sm" value={mode} variant="line" onValueChange={onValueChange}><Tabs.List aria-label={t('widgets.workflow.panelMode')}>{PANEL_MODES.map(({ labelKey, icon, mode: itemMode }) => (diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.test.tsindex 9b5c0dc9f7..0146741b44 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.test.ts@@ -12,13 +12,7 @@ import {resolveFormDrop,} from './formBuilderDnd';-/**- * root -> [fieldA, container1 -> [fieldB], fieldC]- * Mirrors the shape `getFormChildren` walks: a root container element in- * `form.elements` whose `data.children` list the top-level elements, each- * carrying its own `parentId` back to its container (exactly what- * `moveFormElementTo` maintains in `core/document.ts`).- */+/** root -> [fieldA, container1 -> [fieldB], fieldC] */const buildFormFixture = (): WorkflowForm => ({elements: {container1: {@@ -94,11 +88,7 @@ describe('getFormDropEdge', () => {});});-/**- * root -> [container A -> [container B -> [fieldD], fieldC]]- * Mirrors a nested-container layout the way the builder renders it: A's own- * body holds both B (another container) and a plain field.- */+/** root -> [A -> [B -> [fieldD], fieldC]] */const buildNestedFormFixture = (): WorkflowForm => ({elements: {A: { data: { children: ['B', 'fieldC'], layout: 'column' }, id: 'A', parentId: 'root', type: 'container' },@@ -136,12 +126,8 @@ describe('pickInnermostFormCollision', () => {});/**- * A container's own `into:X` dropzone is DOM-nested inside its own- * `edge:X` box (the whole card), so hovering the dropzone always matches- * both — not just when a *different*, deeper element's edge is involved.- * `into:X` (lands inside X) must win over `edge:X` (lands inside X's- * parent): dropping onto a container's own empty-state hint has to append- * into it, not reorder it as a sibling.+ * A container's nested into target must beat its own edge target so empty-state drops append inside rather than+ * reorder outside.*/it('prefers a container over its own edge when both match the same element', () => {const collisions = [{ id: formEdgeDroppableId('A') }, { id: formIntoDroppableId('A') }];@@ -151,12 +137,8 @@ describe('pickInnermostFormCollision', () => {});/**- * root -> [C, B -> [D]]. C and B are incomparable siblings (neither is an- * ancestor of the other); D is nested under B. A greedy "compare each new- * candidate only against the current winner" pass can get stuck on C: C- * isn't D's ancestor, so a pairwise check never promotes D once C already- * won. Depth is computed independently per candidate specifically to avoid- * this, so the deepest (`D`) must win regardless of arrival order.+ * Compute depth independently so a deeper candidate wins even after incomparable siblings, regardless of+ * collision order.*/it('is order-independent for incomparable siblings plus a nested descendant', () => {const siblingForm: WorkflowForm = {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.ts b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.tsindex a42a8caa7d..1c7384d511 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formBuilderDnd.ts@@ -1,17 +1,8 @@import type { WorkflowForm } from '@features/workflow/contracts';/**- * Pure dnd-kit plumbing for the form builder: droppable id encoding/decoding- * and the drop-target -> reparent resolution the old native-DnD `onDrop`- * handlers computed inline. Kept side-effect free so it can be unit tested- * without mounting the builder; `FormBuilderTab` only wires this to- * `editGraph({ type: 'moveFormElementTo', ... })` at `onDragEnd`.- *- * `WorkflowForm` elements each carry their own `parentId` (maintained by- * `moveFormElementTo` in `core/document.ts`), so parent lookup is a direct- * read rather than a scan over every container — mirrors how `getFormChildren`- * resolves the root the same as any other container (`form.elements[id]`,- * `type === 'container'`).+ * Resolve drop IDs into pure reparent commands; use maintained parentId links rather than scanning containers and+ * commit at drag end.*/export type FormDropTarget =@@ -53,13 +44,7 @@ export const isFormDescendantOrSelf = (form: WorkflowForm, ancestorId: string, cexport const getFormDropEdge = (referenceY: number, overTop: number, overHeight: number): 'above' | 'below' =>referenceY < overTop + overHeight / 2 ? 'above' : 'below';-/**- * The container a droppable would actually land the dragged element inside:- * `into:X` lands inside `X` itself; `edge:X` lands inside `X`'s own parent- * (it resolves to a sibling reorder around `X`). Unifying both kinds onto- * this one axis is what makes the tiebreak below a single "deepest wins"- * comparison instead of two separate rules.- */+/** Compare landing containers: into:X targets X, while edge:X targets X's parent. */const formDropLandingContainerId = (form: WorkflowForm, droppableId: string): string | null => {const parsed = parseFormDroppableId(droppableId);@@ -89,15 +74,8 @@ const formContainerDepth = (form: WorkflowForm, containerId: string): number =>};/**- * 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").- *- * 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.+ * Choose deepest landing container, then prefer precise edge insertion at equal depth. Independent depth+ * calculation makes collision ordering irrelevant.*/export const pickInnermostFormCollision = (collisions: { id: string }[], form: WorkflowForm): string | null => {if (collisions.length === 0) {@@ -138,11 +116,8 @@ export const pickInnermostFormCollision = (collisions: { id: string }[], form: W};/**- * Resolves a drop target to a `moveFormElementTo` call, or null when the move- * is disallowed (dropping onto self, into own subtree, or an unresolvable- * target). The reducer re-validates and no-ops on any of these too — this is- * the same guard duplicated at the droppable level so drop zones for invalid- * targets don't render mid-drag.+ * Reject self, descendant, and unresolved drops before rendering affordances; reducer validation independently+ * enforces the same move constraints.*/export const resolveFormDrop = (form: WorkflowForm,diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/formElementMeta.ts b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formElementMeta.tsindex e66ed4b321..6341467064 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/formElementMeta.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/formElementMeta.ts@@ -3,19 +3,7 @@ import type { LucideIcon } from 'lucide-react';import { Columns2Icon, CrosshairIcon, HeadingIcon, MinusIcon, Rows2Icon, TextIcon } from 'lucide-react';-/**- * One name and one icon per form element kind.- *- * The builder shows an element's identity in three places — the card title bar,- * the drag ghost, and the Add menu — and they were each spelling it out- * separately, so the menu could offer "Container (column)" while the card it- * produced called itself something else. Naming a kind is one fact; it belongs- * in one table.- *- * Containers are keyed by layout rather than by type alone: a row and a column- * are the two things a person is actually choosing between, so they carry- * distinct names and distinct icons.- */+/** Share names/icons across cards, ghosts, and Add menus; row and column containers have distinct identities. */export type FormElementMetaKey = 'container-column' | 'container-row' | 'divider' | 'heading' | 'node-field' | 'text';export interface FormElementMeta {@@ -32,13 +20,7 @@ export const FORM_ELEMENT_META: Record<FormElementMetaKey, FormElementMeta> = {text: { icon: TextIcon, label: 'Text' },};-/**- * The kinds the Add menu offers, in the order it offers them.- *- * `node-field` is absent by construction: a field enters a form by being- * dragged off the node that owns it, so there is nothing for a menu entry to- * create.- */+/** Exclude node-field from Add because fields enter forms by dragging from their owning nodes. */export const ADDABLE_FORM_ELEMENT_KEYS = ['heading','text',diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsxindex 9e205514d4..db6d610df5 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx@@ -7,12 +7,7 @@ import { getFieldTypeColor, isModelFieldType } from '@features/workflow/utility'import { Tooltip } from '@platform/ui';import { CircleAlertIcon, CircleCheckIcon, InfoIcon } from 'lucide-react';-/**- * The single source of the workflow-node visual language. Every surface that- * draws a node — the editor's flow nodes, the node manager's static preview- * cards, the form builder — styles it from here so the renderings cannot- * drift apart.- */+/** Share node styling across editor, static previews, and form builder to prevent visual drift. */const NODE_HOVER_RING = '0 0 0 2px {colors.accent.solid/50}, {shadows.md}';const NODE_RUNNING_RING = '0 0 0 2px {colors.brand.solid/70}, 0 0 10px {colors.brand.solid/50}';@@ -89,11 +84,7 @@ export const getWorkflowNodeHeaderProps = ({ roundedBottom = false }: { roundedBpy: WORKFLOW_NODE_DENSITY.headerPaddingY,});-/**- * Field-row body. The header above supplies the divider, so the body draws no- * top border. Inferred (not `BoxProps`) so it spreads into `Stack`/`Flex`- * without tripping over the conflicting HTML `direction` prop types.- */+/** Header supplies the divider. Inferred styles avoid BoxProps direction conflicts when spread into Stack/Flex. */export const getWorkflowNodeBodyProps = ({ roundedBottom = true }: { roundedBottom?: boolean } = {}) => ({bg: WORKFLOW_NODE_SURFACE_TOKEN,borderBottomRadius: roundedBottom ? ('lg' as const) : ('none' as const),@@ -117,13 +108,7 @@ const getHandleVisual = (type: FieldType) => ({isFilled: type.cardinality === 'SINGLE',});-/**- * Inline-CSS flavor for xyflow `<Handle>`s, which live outside Chakra's style- * pipeline. xyflow's own `.react-flow__handle-left/right` CSS centers the- * handle on its `left`/`right` coordinate via `translate(∓50%, -50%)`; the- * diamond transform must restate that centering before rotating, so it needs- * the side.- */+/** Inline handle diamonds must retain side-specific xyflow centering before rotation. */export const getWorkflowNodeHandleStyle = (type: FieldType, side: 'left' | 'right'): CSSProperties => {const visual = getHandleVisual(type);@@ -138,11 +123,6 @@ export const getWorkflowNodeHandleStyle = (type: FieldType, side: 'left' | 'righ};};-/**- * Static stand-in for a connection handle in non-flow contexts (manager preview- * cards): same size, tint, and shape rules as the editor handles, centered on- * the node border.- */export const WorkflowNodeHandleDot = ({ side, type }: { side: 'left' | 'right'; type: FieldType }) => {const visual = getHandleVisual(type);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.tsindex 0c94fa1b97..f82ddfa607 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts@@ -17,12 +17,7 @@ export type AddNodeConnectionFilter =targetType: FieldType | null;};-/**- * Session-lived UI coordination for the workflow widget. Menu items live- * inside the shared widget actions menu while their dialogs and the import- * file input live in the always-mounted header actions — this store is the- * bridge between the two.- */+/** Bridge transient menu actions to always-mounted workflow dialogs and file input through session UI state. */export interface WorkflowUiSnapshot {addNodeConnection: AddNodeConnectionFilter | null;diff --git a/invokeai/frontend/webv2/src/platform/browser/auditAccessibility.browser.test.ts b/invokeai/frontend/webv2/src/platform/browser/auditAccessibility.browser.test.tsindex 4acfebd7d3..112afd8e75 100644--- a/invokeai/frontend/webv2/src/platform/browser/auditAccessibility.browser.test.ts+++ b/invokeai/frontend/webv2/src/platform/browser/auditAccessibility.browser.test.ts@@ -2,18 +2,7 @@ import { afterEach, expect, it } from 'vitest';import { auditAccessibility } from './auditAccessibility.testing';-/**- * The reason the helper exists, reproduced in miniature.- *- * A panel whose colours pass contrast comfortably at rest fails the audit while it is fading- * in, because the audit composites its text over whatever is behind it. This is what took down- * `MissingFontsDialog` whenever the suite grew a file: nothing about the palette was wrong, the- * audit simply ran a few frames early.- *- * The fade here is slow enough that the un-settled audit lands inside it with a margin of- * three orders of magnitude over the assertion that follows, so the "before" case is not itself- * a race.- */+/** Use a deliberately slow fade to reproduce a failing mid-animation contrast audit and a passing settled audit. */const FADE_MS = 800;diff --git a/invokeai/frontend/webv2/src/platform/browser/auditAccessibility.testing.ts b/invokeai/frontend/webv2/src/platform/browser/auditAccessibility.testing.tsindex ffc18da0d9..d4f6095f99 100644--- a/invokeai/frontend/webv2/src/platform/browser/auditAccessibility.testing.ts+++ b/invokeai/frontend/webv2/src/platform/browser/auditAccessibility.testing.ts@@ -3,17 +3,8 @@ import axe from 'axe-core';import { settleAnimations } from './settleAnimations.testing';/**- * Run an accessibility audit against settled UI.- *- * The settling is the point. Auditing a surface that is still animating in reports colour- * contrast against a half-composited backdrop — see {@link settleAnimations} — and the failure- * is load-dependent, so it lands on whoever next adds an unrelated test file rather than on- * whoever wrote the audit. Pairing the two here rather than leaving `settleAnimations` to be- * remembered at each call site is what keeps that from coming back; `architecture/axeAudits`- * holds callers to it.- *- * Returns the violations rather than asserting, so a caller still chooses what to expect of- * them — usually `toEqual([])`, which prints the offending nodes and colours on failure.+ * Settle animations before axe to avoid transient contrast failures; return violations so callers choose+ * assertions. Architecture checks enforce this entry point.*/export const auditAccessibility = async (target: Element): Promise<axe.Result[]> => {await settleAnimations();diff --git a/invokeai/frontend/webv2/src/platform/browser/downloadBlob.browser.test.ts b/invokeai/frontend/webv2/src/platform/browser/downloadBlob.browser.test.tsindex 6672a4abcc..6cb86e292d 100644--- a/invokeai/frontend/webv2/src/platform/browser/downloadBlob.browser.test.ts+++ b/invokeai/frontend/webv2/src/platform/browser/downloadBlob.browser.test.ts@@ -1,11 +1,7 @@import { downloadBlob, downloadText } from '@platform/browser/downloadBlob';import { afterEach, describe, expect, it, vi } from 'vitest';-/**- * Records each anchor *and whether it was in the document at the moment it was- * clicked* — the helper detaches it immediately afterwards, so reading that- * later always says no.- */+/** Record connectivity at click time; the helper immediately detaches the anchor afterward. */const capture = () => {const clicked: { download: string; href: string; wasConnected: boolean }[] = [];@@ -31,8 +27,7 @@ describe('downloadBlob', () => {expect(clicked[0]!.href.startsWith('blob:')).toBe(true);});- // A detached anchor's click has historically not worked in Firefox, which is- // how "export does nothing" bugs get reported against one browser only.+ // Attach before click for Firefox compatibility.it('attaches the anchor to the document before clicking it', () => {const { clicked } = capture();@@ -49,8 +44,7 @@ describe('downloadBlob', () => {expect(document.querySelector('a[download="notes.txt"]')).toBeNull();});- // Revoking in the same tick races the browser's own read of the URL and loses- // often enough on Safari to produce an empty download.+ // Defer revocation to avoid racing Safari's URL consumption.it('keeps the object URL alive past the click', async () => {const { clicked } = capture();const revoke = vi.spyOn(URL, 'revokeObjectURL');diff --git a/invokeai/frontend/webv2/src/platform/browser/downloadBlob.ts b/invokeai/frontend/webv2/src/platform/browser/downloadBlob.tsindex aa9454942a..f4da774436 100644--- a/invokeai/frontend/webv2/src/platform/browser/downloadBlob.ts+++ b/invokeai/frontend/webv2/src/platform/browser/downloadBlob.ts@@ -1,20 +1,6 @@/**- * Hand a blob to the browser as a download.- *- * This was written out longhand in eight places — workflows, projects, PSD- * export, the gallery, image actions, prompt templates and wildcards — each- * with its own spelling of the same five lines, and each carrying the same two- * mistakes.- *- * The anchor is appended to the document before it is clicked. A detached- * anchor works in Chromium but has historically not in Firefox, which is the- * sort of thing nobody notices until someone reports that export does nothing.- *- * The object URL is revoked on the next frame rather than immediately after the- * click. Revoking synchronously races the browser's own read of the URL, and- * loses often enough on Safari to produce an empty or failed download; a frame- * is long enough for the download to have been claimed and short enough that the- * blob is not left pinned in memory.+ * Append the download anchor for Firefox compatibility; defer URL revocation until the next frame to avoid racing+ * browser consumption.*/export const downloadBlob = (blob: Blob, fileName: string): void => {const url = URL.createObjectURL(blob);diff --git a/invokeai/frontend/webv2/src/platform/browser/randomUuid.ts b/invokeai/frontend/webv2/src/platform/browser/randomUuid.tsindex 2a0d4d2c6d..6b58b6dd32 100644--- a/invokeai/frontend/webv2/src/platform/browser/randomUuid.ts+++ b/invokeai/frontend/webv2/src/platform/browser/randomUuid.ts@@ -1,9 +1,4 @@-/**- * Generate an RFC 4122 version 4 UUID.- *- * `crypto.randomUUID` is applied in secure contexts (HTTPS or `localhost`).- * `crypto.getRandomValues` is applied in non-secure contexts.- */+/** Generate UUIDv4 with randomUUID when available, otherwise getRandomValues. *//** The subset of `Crypto` the generator relies on, so tests can swap it. */export type UuidCryptoSource = Pick<Crypto, 'getRandomValues'> & Partial<Pick<Crypto, 'randomUUID'>>;diff --git a/invokeai/frontend/webv2/src/platform/browser/settleAnimations.browser.test.ts b/invokeai/frontend/webv2/src/platform/browser/settleAnimations.browser.test.tsindex f59053c604..ea03364859 100644--- a/invokeai/frontend/webv2/src/platform/browser/settleAnimations.browser.test.ts+++ b/invokeai/frontend/webv2/src/platform/browser/settleAnimations.browser.test.ts@@ -3,14 +3,8 @@ import { afterEach, beforeEach, expect, it } from 'vitest';import { settleAnimations } from './settleAnimations.testing';/**- * The helper's whole job is to be awaited before an appearance assertion, so the two ways it- * can fail are both silent: returning early leaves the flake it was written to remove, and- * waiting on an animation that never ends hangs the run instead of failing it.- *- * The never-ending cases have no explicit timeout here on purpose — a regression surfaces as- * this file's own test timeout, which names the case. A hand-rolled deadline would only trade- * that for a wrong-reason failure whenever the machine stalls past it, which is the very class- * of bug this helper exists to remove.+ * Use the test runner's deadline for never-ending cases; extra timing thresholds introduce load-sensitive+ * failures.*/let host: HTMLDivElement | null = null;@@ -26,10 +20,7 @@ const container = (): HTMLDivElement => (host ??= document.body.appendChild(docuconst scripted = (options: KeyframeAnimationOptions): Animation =>container().appendChild(document.createElement('div')).animate(FADE, options);-/**- * A CSS-driven animation, which is what the components under test actually run and the only- * kind whose `finished` rejects when its element is removed.- */+/** Use CSS animations so element removal rejects finished, matching real components. */const cssAnimated = (): { animation: Animation; element: HTMLDivElement } => {styles ??= document.head.appendChild(document.createElement('style'));styles.textContent = `@keyframes settle-probe { from { opacity: 0 } to { opacity: 1 } }@@ -63,13 +54,10 @@ it('waits for a running animation in the subtree rather than returning on the fi});it('finds animations anywhere in the document when given no subtree, since backdrops and menus are portalled', async () => {- // Every call site relies on this default: what an audit reads is the composite, and the- // backdrop behind a dialog is a sibling of it rather than a descendant. The root element is- // included too, which is what distinguishes the document from `document.body`.+ // Cover sibling backdrops and document-root animations, not only the audited subtree or body.const outside = detached.appendChild(document.createElement('div'));const sibling = outside.animate(FADE, { duration: 120, fill: 'forwards' });- // Deliberately the longest of the three: if the helper only walked `document.body`, it would- // return when the sibling finished and leave this one running.+ // Keep the root animation longest so a body-only scan would return early.const root = document.documentElement.animate([{ opacity: 0.99 }, { opacity: 1 }], { duration: 400 });await settleAnimations();@@ -78,8 +66,6 @@ it('finds animations anywhere in the document when given no subtree, since backd});it('skips an animation that repeats forever instead of hanging on one that never finishes', async () => {- // A spinner or shimmering skeleton in the audited page. Awaiting it would never return, so a- // regression here shows up as this test timing out rather than as a bad assertion.scripted({ duration: 50, iterations: Infinity });const finite = scripted({ duration: 50, fill: 'forwards' });@@ -117,8 +103,7 @@ it('settles when an animating element is removed mid-flight, which rejects ratheelement.remove();- // Resolving well inside the animation's own duration is the assertion: the helper returned- // because the animation was cancelled, not because it waited the fade out.+ // Resolve before the fade duration to prove cancellation, not natural completion, settled the wait.await expect(settled).resolves.toBeUndefined();await rejection;});diff --git a/invokeai/frontend/webv2/src/platform/browser/settleAnimations.testing.ts b/invokeai/frontend/webv2/src/platform/browser/settleAnimations.testing.tsindex 32fb268023..2f01f32be3 100644--- a/invokeai/frontend/webv2/src/platform/browser/settleAnimations.testing.ts+++ b/invokeai/frontend/webv2/src/platform/browser/settleAnimations.testing.ts@@ -1,31 +1,11 @@/**- * Wait for animations to finish before asserting on how something looks.- *- * `toBeVisible()` is satisfied the moment an element is laid out, which for anything that- * fades or scales in is several frames before it looks like itself. An assertion that reads- * rendered appearance — a contrast audit, a screenshot, a measured box — taken in that window- * reads the animation's midpoint instead: a Chakra dialog caught at `opacity: 0.22` composites- * its text over the backdrop and audits as 1.18:1 against a 4.5:1 rule, reporting a palette- * failure that does not exist.- *- * That window is real but short, so whether an assertion lands inside it depends on how busy- * the machine is — which in a browser run means how many OTHER test files the suite happens to- * be scheduling. A suite that passes at 204 files starts failing at 205, in a file the new one- * never touches.- *- * Test-only: it needs a real browser's animation timeline, and production code has no reason- * to block on one.+ * Wait for real browser animations before visual assertions; visible elements can still be mid-transition and+ * yield false contrast failures.*//**- * Whether awaiting this animation will ever end.- *- * Four states never settle, and awaiting any of them turns a test into a timeout rather than a- * failure. Only the first is obvious, and checking `iterations` alone does not catch the rest:- * measured in this suite's Chromium, a paused animation, one with `playbackRate: 0`, and one- * with an infinite `duration` all report `iterations: 1` and leave `finished` pending forever.- * The scope below is the whole document, so one of these anywhere on the page would otherwise- * hang every caller.+ * Skip infinite iterations/duration, paused animations, and zero playback rate; each can leave finished pending+ * forever.*/const willFinish = (animation: Animation): boolean => {const timing = animation.effect?.getComputedTiming();@@ -40,20 +20,8 @@ const willFinish = (animation: Animation): boolean => {};/**- * Resolve once every animation running when it is called has finished.- *- * Defaults to the whole document rather than the subtree under assertion, because what an- * appearance assertion reads is the COMPOSITE. A Chakra dialog's backdrop is a sibling of its- * positioner, not a descendant, and fades over `slow` while the content in front of it fades- * over `moderate` — so settling only `[role="dialog"]` returns with the backdrop a third of the- * way through, and the first translucent surface anyone audits gets this flake straight back.- * Portalled content (menus, popovers) sits outside the caller's subtree for the same reason.- * Animations that never finish are filtered out, so the wider scope costs nothing.- *- * `allSettled`, not `all`: removing an element cancels its CSS animation, which rejects the- * `finished` promise captured here with an `AbortError` (measured — and CSS animations are what- * the components under test use). A subtree that stopped animating because it went away has- * settled too, and an unhandled rejection would fail the test for the wrong reason.+ * Settle the whole document by default, including sibling backdrops and portals. Ignore nonterminating animations;+ * use allSettled because removal cancels CSS animations and rejects finished.*/export const settleAnimations = async (root: Document | Element = document): Promise<void> => {await Promise.allSettled(diff --git a/invokeai/frontend/webv2/src/platform/browser/sha256.ts b/invokeai/frontend/webv2/src/platform/browser/sha256.tsindex c390d1237b..126c21ae53 100644--- a/invokeai/frontend/webv2/src/platform/browser/sha256.ts+++ b/invokeai/frontend/webv2/src/platform/browser/sha256.ts@@ -1,9 +1,4 @@-/**- * SHA-256, with a pure-JavaScript fallback for insecure contexts.- *- * `crypto.subtle` is exposed only in secure contexts, otherwise a slower fallback- * that produces identical digests is applied.- */+/** Use the JS SHA-256 fallback when insecure contexts lack crypto.subtle. */const ROUND_CONSTANTS = new Uint32Array([0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98,diff --git a/invokeai/frontend/webv2/src/platform/core/concurrency.test.ts b/invokeai/frontend/webv2/src/platform/core/concurrency.test.tsindex cc47b58839..9de5190786 100644--- a/invokeai/frontend/webv2/src/platform/core/concurrency.test.ts+++ b/invokeai/frontend/webv2/src/platform/core/concurrency.test.ts@@ -73,9 +73,7 @@ describe('mapWithConcurrency', () => {});it('starts no further work after a mapper rejects', async () => {- // `Promise.all` stops *waiting* on a rejection; it does not stop the workers. Without an- // explicit stop, an export that has already failed goes on to issue one request per asset it- // had not reached yet.+ // After rejection, stop scheduling remaining assets; Promise.all alone does not stop workers.const started: number[] = [];await expect(@@ -112,8 +110,7 @@ describe('mapWithConcurrency', () => {});it('still runs the list when told a concurrency of zero', async () => {- // Spawning `min(0, length)` workers resolved immediately with an empty array, which reads as- // "nothing to do" rather than "nothing was done".+ // Zero workers must not report successful processing of a nonempty list.const results = await mapWithConcurrency([1, 2, 3], 0, (item) => Promise.resolve(item * 2));expect(results).toEqual([2, 4, 6]);diff --git a/invokeai/frontend/webv2/src/platform/core/concurrency.ts b/invokeai/frontend/webv2/src/platform/core/concurrency.tsindex f74d852f57..cab7e82463 100644--- a/invokeai/frontend/webv2/src/platform/core/concurrency.ts+++ b/invokeai/frontend/webv2/src/platform/core/concurrency.ts@@ -1,24 +1,6 @@/**- * Run an async mapper over a list with a bounded number of tasks in flight.- *- * Every caller here is fanning out HTTP requests — importing gallery images- * onto the canvas, bundling a project's assets into an archive, restoring them- * on the way back. `Promise.all` over the whole list is the obvious spelling- * and the wrong one: a project with three hundred images opens three hundred- * sockets, the browser queues most of them anyway, and the backend sees a- * thundering herd it did nothing to deserve.- *- * Results keep the input order regardless of completion order, so callers can- * zip them back against the source list by index.- *- * A rejecting mapper rejects the whole call, exactly as `Promise.all` would;- * callers that want partial success catch inside the mapper and return a- * result union instead. The first rejection also *stops* the remaining work:- * `Promise.all` only stops waiting, so without this a failed export would go on- * to issue one request per asset it had not reached yet — hundreds of them, for- * an operation that has already failed. Results for items never started are- * left as holes, which callers see as `undefined` and never reach, because the- * rejection is what they get instead.+ * Bound concurrent mapping and preserve input order. First rejection stops scheduling new work but cannot cancel+ * running tasks; catch inside the mapper for partial results.*/export const mapWithConcurrency = async <T, R>(items: readonly T[],@@ -48,8 +30,7 @@ export const mapWithConcurrency = async <T, R>(}};- // At least one worker: a concurrency of zero would otherwise spawn none, resolve immediately and- // hand back an empty array as though the list had been processed.+ // Always start at least one worker; zero would falsely resolve without processing input.const workerCount = Math.max(1, Math.min(concurrency, items.length));await Promise.all(Array.from({ length: items.length === 0 ? 0 : workerCount }, worker));diff --git a/invokeai/frontend/webv2/src/platform/core/json.ts b/invokeai/frontend/webv2/src/platform/core/json.tsindex 3adbcd5f63..c5e7b3aabc 100644--- a/invokeai/frontend/webv2/src/platform/core/json.ts+++ b/invokeai/frontend/webv2/src/platform/core/json.ts@@ -7,13 +7,7 @@ const isJsonObject = (value: unknown): value is Record<string, unknown> => {return prototype === Object.prototype || prototype === null;};-/**- * Structural equality for JSON-safe values.- *- * Unknown inputs are accepted at integration boundaries. Distinct non-JSON- * objects are unequal; the same value or object identity still follows- * `Object.is`.- */+/** Compare JSON structurally; distinct non-JSON objects are unequal, while identical references follow Object.is. */export const areJsonValuesStructurallyEqual = (left: unknown, right: unknown): boolean => {if (Object.is(left, right)) {return true;diff --git a/invokeai/frontend/webv2/src/platform/core/seed.ts b/invokeai/frontend/webv2/src/platform/core/seed.tsindex 14811d22f5..41a4b8a908 100644--- a/invokeai/frontend/webv2/src/platform/core/seed.ts+++ b/invokeai/frontend/webv2/src/platform/core/seed.ts@@ -1,9 +1,6 @@/**- * The seed policy every seeded submission shares: the range, the four modes,- * and how a submission walks its sequence. Kept pure (no top-level calls, no- * dependencies) so a graph compiler can import it without becoming- * side-effectful; rolldown would otherwise materialise that compiler's facade- * and pull the canvas-layer chunk into the settings and palette overlays.+ * Keep seed policy free of top-level side effects so importing graph compilers cannot pull canvas chunks into+ * settings/palette bundles.*/export const SEED_MAX = 4_294_967_295;@@ -34,11 +31,7 @@ export interface SeedSequenceInput {seedMode: SeedMode;}-/**- * How many entries of the seed sequence one submission uses. A fixed seed uses- * its single entry however many images run. Otherwise every iteration takes an- * entry, and with several prompts sharing disabled every image does.- */+/** Fixed consumes one seed; otherwise consume per iteration, or per image when prompts do not share seeds. */export const getSeedSequenceLength = ({batchCount,promptCount,@@ -58,11 +51,7 @@ export interface SeedSubmissionPlan {step: SeedStep;}-/**- * The seeds a submission consumes and where the editable seed goes afterwards.- * Only the stepping modes advance it: random keeps the manual value in reserve,- * fixed reuses it.- */+/** Only stepping modes advance the editable seed; random preserves it and fixed reuses it. */export const planSeedSubmission = ({startSeed,...sequencediff --git a/invokeai/frontend/webv2/src/platform/i18n/translationKeys.test.ts b/invokeai/frontend/webv2/src/platform/i18n/translationKeys.test.tsindex 673fc1fd4f..f649b8dc3e 100644--- a/invokeai/frontend/webv2/src/platform/i18n/translationKeys.test.ts+++ b/invokeai/frontend/webv2/src/platform/i18n/translationKeys.test.ts@@ -1,11 +1,6 @@import { describe, expect, it } from 'vitest';-/**- * Guards against translation keys that render as raw dotted paths. Every static- * `t('…')` literal in production source must resolve in the English catalog —- * webv2 ships English-only today (the other locales are empty stubs behind- * `fallbackLng: 'en'`), so en.json is the whole contract.- */+/** Require every static production translation key in en.json, the fallback catalog. */const enModules = import.meta.glob('../../../public/locales/en.json', { eager: true, import: 'default' });const sourceModules = import.meta.glob('../../**/*.{ts,tsx}', {@@ -19,12 +14,7 @@ const en = Object.values(enModules)[0] as Record<string, unknown>;/** Top-level namespaces in en.json. Anchoring on these keeps the scan from matching arbitrary dotted strings. */const NAMESPACES = Object.keys(en);-/**- * Key prefixes built by interpolation and always called with a `defaultValue`,- * so a miss degrades to readable English rather than a dotted path.- * `commandPalette.commands.*`: see `entries.ts` — titles fall back to the- * command definition's own title.- */+/** Dynamic prefixes are exempt only with readable defaultValue; command titles use their definition title. */export const DYNAMIC_KEY_PREFIXES = ['commandPalette.commands.'];const isTestModule = (path: string): boolean => /\.test\.|\.type-test\.|\.testing\./.test(path);diff --git a/invokeai/frontend/webv2/src/platform/performance/semanticReady.ts b/invokeai/frontend/webv2/src/platform/performance/semanticReady.tsindex 1a9513b3ea..03df28f3d9 100644--- a/invokeai/frontend/webv2/src/platform/performance/semanticReady.ts+++ b/invokeai/frontend/webv2/src/platform/performance/semanticReady.ts@@ -3,12 +3,7 @@ export const LAUNCHPAD_READY_MARK = 'invokeai:ready:launchpad';export const getWidgetReadyMark = (region: string, typeId: string): string =>`invokeai:ready:widget:${region}:${typeId}`;-/**- * Records a product-owned readiness milestone for the browser performance- * harness. Keeping only the latest mark makes repeated layout/project- * transitions unambiguous while preserving the mark's navigation-relative- * start time.- */+/** Keep only the latest readiness mark per milestone while retaining navigation-relative timing. */export const markSemanticReady = (name: string): void => {if (typeof performance === 'undefined' || typeof performance.mark !== 'function') {return;diff --git a/invokeai/frontend/webv2/src/platform/pwa/registerServiceWorker.ts b/invokeai/frontend/webv2/src/platform/pwa/registerServiceWorker.tsindex 824402c92e..a436e3cf78 100644--- a/invokeai/frontend/webv2/src/platform/pwa/registerServiceWorker.ts+++ b/invokeai/frontend/webv2/src/platform/pwa/registerServiceWorker.ts@@ -1,14 +1,4 @@-/**- * Registers the app-shell service worker (`sw.js`, emitted by- * `scripts/service-worker-plugin.mjs`). Hashed assets become cache-first so- * repeat boots skip the network; navigations stay network-first so a plain- * reload always picks up a new deploy; the shell keeps working offline.- *- * Production only: the dev server never emits `sw.js`, and a worker caching- * unbundled dev modules would only get in the way. Registration waits for- * `load` so it cannot compete with boot-critical fetches, and- * `updateViaCache: 'none'` makes every navigation check for a new build.- */+/** Register only in production after load to avoid boot contention; bypass the HTTP cache for worker updates. */export const registerServiceWorker = (): void => {if (!import.meta.env.PROD || typeof navigator === 'undefined' || !('serviceWorker' in navigator)) {return;@@ -16,8 +6,7 @@ export const registerServiceWorker = (): void => {window.addEventListener('load', () => {navigator.serviceWorker.register('./sw.js', { updateViaCache: 'none' }).catch(() => {- // Registration failing (private mode, unsupported scheme) just means- // the app keeps loading straight from the network.+ // Registration failure leaves ordinary network loading available.});});};diff --git a/invokeai/frontend/webv2/src/platform/pwa/sw.js b/invokeai/frontend/webv2/src/platform/pwa/sw.jsindex d641313e61..c44d1cba84 100644--- a/invokeai/frontend/webv2/src/platform/pwa/sw.js+++ b/invokeai/frontend/webv2/src/platform/pwa/sw.js@@ -1,22 +1,7 @@/**- * App-shell service worker. The manifest read below is a placeholder that- * `scripts/service-worker-plugin.mjs` replaces at build time with- * `{ version, assets }` — the build's content hash and its emitted asset file- * names. The placeholder must appear exactly once; the plugin enforces this.- *- * Strategy:- * - Navigations are network-first with the cached shell as offline fallback,- * so a plain reload always picks up a new deploy — no update UI needed.- * - Hashed `assets/*` files are cache-first: their names change when their- * content does, so a cache hit is always correct and repeat boots skip the- * network entirely.- * - Locale files are stale-while-revalidate: instant from cache, refreshed in- * the background.- * - Everything else (API, sockets) is untouched.- *- * Deliberately no `skipWaiting()`: a new worker prunes assets its manifest no- * longer lists, and a still-open old tab may yet lazy-load one of them. The- * new worker activates once the old tabs are gone.+ * The plugin injects one {version, assets} manifest. Navigation is network-first, hashed assets cache-first,+ * locales stale-while-revalidate; API/socket traffic is untouched. Do not skipWaiting: old tabs may still need+ * lazy assets the new worker prunes.*/const MANIFEST = self.__SW_MANIFEST__;@@ -88,8 +73,7 @@ const respondCacheFirst = async (request) => {const response = await fetch(request);- // Only current-manifest assets are written back, which keeps the cache- // bounded; the activate handler prunes the previous build's entries.+ // Cache only current-manifest assets; activation prunes old entries.if (response.ok && ASSET_URLS.has(request.url)) {const cache = await caches.open(ASSET_CACHE);diff --git a/invokeai/frontend/webv2/src/platform/query/client.ts b/invokeai/frontend/webv2/src/platform/query/client.tsindex 49916d2189..7a593cb7e4 100644--- a/invokeai/frontend/webv2/src/platform/query/client.ts+++ b/invokeai/frontend/webv2/src/platform/query/client.ts@@ -1,9 +1,6 @@import { QueryClient } from '@tanstack/react-query';-/**- * The application query cache. Feature modules own their keys and options;- * non-React runtimes use this same client for precise realtime updates.- */+/** Features own keys/options; React and realtime runtimes share this client. */export const queryClient = new QueryClient({defaultOptions: {queries: {diff --git a/invokeai/frontend/webv2/src/platform/react/composeProviders.test.tsx b/invokeai/frontend/webv2/src/platform/react/composeProviders.test.tsxindex 5c625199f5..f734df0402 100644--- a/invokeai/frontend/webv2/src/platform/react/composeProviders.test.tsx+++ b/invokeai/frontend/webv2/src/platform/react/composeProviders.test.tsx@@ -6,8 +6,7 @@ import { describe, expect, it } from 'vitest';import { composeProviders } from './composeProviders';-// Three probe contexts. Each provider chains off the previous context's value,-// so the probe output encodes the exact nesting order.+// Chain context values so the probe detects provider order.const FirstContext = createContext('missing-first');const SecondContext = createContext('missing-second');const ThirdContext = createContext('missing-third');@@ -59,8 +58,7 @@ describe('composeProviders', () => {);expect(renderOnce()).toBe(renderOnce());- // A second call creates a distinct component: composing inside render would- // change element type each render and remount the subtree. Module scope only.+ // Render-time composition creates a new type and remounts the subtree.expect(composeProviders([FirstProvider, SecondProvider, ThirdProvider])).not.toBe(Composed);});});diff --git a/invokeai/frontend/webv2/src/platform/react/composeProviders.tsx b/invokeai/frontend/webv2/src/platform/react/composeProviders.tsxindex a350f40dc8..c2a2cce6c0 100644--- a/invokeai/frontend/webv2/src/platform/react/composeProviders.tsx+++ b/invokeai/frontend/webv2/src/platform/react/composeProviders.tsx@@ -3,13 +3,8 @@ import type { ComponentType, ReactNode } from 'react';export type ProviderComponent = ComponentType<{ children: ReactNode }>;/**- * Flattens a list of context providers into a single component. The array is- * nesting order, outermost first: `composeProviders([A, B])` renders- * `<A><B>{children}</B></A>`.- *- * MUST be called at module scope only. Each call creates a new component- * identity, so composing inside render would remount the entire subtree on- * every render.+ * Outermost provider first. Call only at module scope: each call creates a component identity and render-time+ * composition remounts children.*/export const composeProviders = (providers: ReadonlyArray<ProviderComponent>): ProviderComponent => {const Composed = ({ children }: { children: ReactNode }): ReactNode =>diff --git a/invokeai/frontend/webv2/src/platform/react/focusIfUnclaimed.ts b/invokeai/frontend/webv2/src/platform/react/focusIfUnclaimed.tsindex 87c3c24030..ca9b9596b0 100644--- a/invokeai/frontend/webv2/src/platform/react/focusIfUnclaimed.ts+++ b/invokeai/frontend/webv2/src/platform/react/focusIfUnclaimed.ts@@ -8,12 +8,7 @@ export const focusFirstOperable = (element: HTMLElement | null): void => {element?.querySelector<HTMLElement>(FOCUSABLE)?.focus();};-/**- * For content revealed after the control that held focus unmounted -- a retry button replaced by the- * thing it loaded. Moves focus into `element`, but only while nothing holds focus: it rescues a- * keyboard user whose focus fell to `<body>` without pulling focus from wherever someone has since- * moved it.- */+/** Restore focus after a control unmounts only while focus remains unclaimed; never steal a user's newer focus. */export const focusIfUnclaimed = (element: HTMLElement | null): void => {if (document.activeElement !== null && document.activeElement !== document.body) {return;diff --git a/invokeai/frontend/webv2/src/platform/react/useModifierHeld.ts b/invokeai/frontend/webv2/src/platform/react/useModifierHeld.tsindex 4ce595deab..d53714e73f 100644--- a/invokeai/frontend/webv2/src/platform/react/useModifierHeld.ts+++ b/invokeai/frontend/webv2/src/platform/react/useModifierHeld.ts@@ -1,10 +1,6 @@import { useEffect, useState } from 'react';-/**- * Tracks whether a keyboard modifier is currently held, event-driven (no- * polling). Shared across widgets: the workflow editor's Control-snap and the- * canvas settings popover's Shift-revealed Debug section both key off it.- */+/** Share event-driven modifier state across widgets. */export const useModifierHeld = (key: 'Alt' | 'Control' | 'Meta' | 'Shift'): boolean => {const [isHeld, setIsHeld] = useState(false);diff --git a/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.browser.test.tsx b/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.browser.test.tsxindex d1efddcc7d..e07b03faad 100644--- a/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.browser.test.tsx@@ -9,14 +9,8 @@ import { usePreservedScrollOffset } from './usePreservedScrollOffset';const VIEWPORT_STYLE = { height: '100px', overflow: 'auto', width: '100px' } as const;/**- * Stands in for a plain, non-virtualized list — the gallery's board list is- * the real reproduction case — whose content is sized from actual DOM layout- * rather than from a row count, so it does not survive the container being- * taken out of layout unchanged. That is what defeats the browser's own- * scroll restoration, and a container with fixed content would not reproduce- * the bug at all. A virtualized list does not have this problem: its content- * height is a pure function of row count and estimated sizes, so it survives- * unaided and needs no help from this hook.+ * Use layout-dependent content so hiding changes its size; fixed-height virtualized content would not reproduce+ * lost browser restoration.*/const Scroller = ({contentHeight,@@ -123,21 +117,13 @@ describe('preserved scroll offset', () => {await hideAndShow(true);- // The state, not the node: identity alone was never the thing at risk.- //- // Chrome restores this much on its own when the scrollable content happens- // to survive, so this pins the contract rather than reproducing the bug —- // the real reproduction is the `workbench-keep-alive-state` journey, which- // runs the gallery's actual non-virtualized board list.+ // This asserts retained state; the real gallery reproduction lives in workbench-keep-alive-state.expect(scroller()).toBe(element);expect(element.scrollTop).toBe(500);});it('keeps both axes across a keep-alive hide and show', async () => {- // `Scrollable` installs this hook unconditionally regardless of its own- // `orientation` prop, and `PreviewFilmstrip` is a horizontal `Scrollable`- // inside the keep-alive-able Preview widget — a vertical-only fix would- // leave that filmstrip snapping back to its start on every preset switch.+ // Cover horizontal offsets too: Scrollable installs the hook for filmstrips regardless of orientation.mount();await render('visible', 2000, true, 2000);await scrollToBothAxes(500, 300);diff --git a/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.ts b/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.tsindex 4aaea55096..a3dc9840ff 100644--- a/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.ts+++ b/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.ts@@ -1,29 +1,8 @@import { useLayoutEffect, useRef, type RefObject } from 'react';/**- * Keeps a scroll container's offset across the container ceasing to be rendered.- *- * The shell keeps widgets mounted across layout switches and hides them with- * `display: none`, which takes the element out of layout entirely: it has no- * scrollable overflow, its `scrollTop` reads 0, and the browser's own scroll- * restoration only survives if the scrollable content happens to be unchanged- * when it comes back. A plain, non-virtualized list — the gallery's board- * list is the real reproduction case — has its content sized from actual DOM- * layout, which is not guaranteed to come back identical, and the offset is- * simply lost. A virtualized list is not the problem: its content height is a- * pure function of row count and estimated sizes rather than of being laid- * out at all, so it survives the round trip unaided and needs no help here.- *- * The offset is tracked as the user scrolls rather than read back at teardown,- * because by the time a hidden subtree's effects are cleaned up the element is- * already out of layout and reports `scrollTop` as 0 — reading it there records- * nothing. Restoring happens in a layout effect, which runs whenever the subtree- * is shown again (a real remount and a keep-alive reveal are indistinguishable- * here, and both want the same thing) and lands before paint, so the list never- * shows a frame at the top.- *- * Scoped to one component instance by construction: a genuine unmount takes the- * remembered offset with it, exactly as before.+ * Track offsets during scrolling: hidden-subtree cleanup sees zero after display:none. Restore before paint on+ * reveal; real unmount discards the instance's offsets.*/export const usePreservedScrollOffset = (ref: RefObject<HTMLElement | null>): void => {const offsetRef = useRef({ left: 0, top: 0 });diff --git a/invokeai/frontend/webv2/src/platform/react/useScopedAction.ts b/invokeai/frontend/webv2/src/platform/react/useScopedAction.tsindex aac9b82b3e..1c9ca01740 100644--- a/invokeai/frontend/webv2/src/platform/react/useScopedAction.ts+++ b/invokeai/frontend/webv2/src/platform/react/useScopedAction.ts@@ -4,20 +4,8 @@ import { useCallback, useRef, useState } from 'react';export const getErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));/**- * Busy-tracked wrapper for account-scoped async UI actions. Owns the- * boilerplate every mutation handler otherwise repeats: capture the account- * scope, flip the busy flag, drop results that settle after an account- * switch, and route failures to the caller's error sink.- *- * `run` resolves `true` only when the action completed in the current account- * scope, so callers can gate follow-up UI (navigation, closing a pane) on- * success. While an action is in flight, further `run` calls resolve `false`- * without invoking their action — keyboard paths that bypass a button's- * `loading` state cannot double-submit.- *- * The action still calls `assertAccountScopeCurrent(owner)` itself before- * patching stores on success — the throw lands here and is swallowed when the- * scope is gone.+ * Reject overlapping runs; return true only for current-account success. Actions must assertAccountScopeCurrent+ * before store writes; the wrapper cannot fence writes inside them.*/export const useScopedAction = () => {const [isBusy, setIsBusy] = useState(false);diff --git a/invokeai/frontend/webv2/src/platform/react/useZodForm.ts b/invokeai/frontend/webv2/src/platform/react/useZodForm.tsindex d69af0de9b..6ab0f62a17 100644--- a/invokeai/frontend/webv2/src/platform/react/useZodForm.ts+++ b/invokeai/frontend/webv2/src/platform/react/useZodForm.ts@@ -2,11 +2,7 @@ import type { z } from 'zod';import { useCallback, useRef, useState } from 'react';-/**- * Minimal zod-backed form state. Validation runs on submit; editing a field- * that shows an error clears that error immediately (optimistic — the next- * submit re-validates), so users are not nagged mid-correction.- */+/** Validate on submit; editing clears that field's error without revalidating mid-entry. */export interface ZodFormField<Value> {value: Value;diff --git a/invokeai/frontend/webv2/src/platform/react/virtualizerScrollElementRemount.browser.test.tsx b/invokeai/frontend/webv2/src/platform/react/virtualizerScrollElementRemount.browser.test.tsxindex 395a16ce4d..36f61aeee1 100644--- a/invokeai/frontend/webv2/src/platform/react/virtualizerScrollElementRemount.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/react/virtualizerScrollElementRemount.browser.test.tsx@@ -4,18 +4,8 @@ import { useVirtualizer } from 'react-hook-tanstack-virtual';import { afterEach, describe, expect, it, vi } from 'vitest';/**- * Regression test for the locally patched scroll-desync in- * react-hook-tanstack-virtual / @tanstack/virtual-core.- *- * When a scroll element is swapped (a list passing through an empty loading- * state remounts its container), virtual-core restores the cached offset onto- * the new element via `scrollTo`. If the new content is too short for that- * offset, the browser clamps the scroll WITHOUT firing a scroll event, and- * nothing ever reads the element's real position back — the virtualizer keeps- * serving the range computed at the stale offset, which renders no rows at- * all. This is the gallery going blank after a semantic search or cluster- * click until a manual scroll. The patch reconciles the cached offset with- * the element's actual position whenever the scroll element changes.+ * On scroll-element replacement, browsers can clamp restored offsets without an event. Verify the local+ * virtualizer patch reconciles actual position instead of rendering a stale empty range.*/const ROW_HEIGHT = 50;@@ -98,14 +88,8 @@ afterEach(async () => {describe('useVirtualizer scroll element remount', () => {it('does not consume a programmatic scroll\u2019s pending intent while reconciling', async () => {- // virtual-core ignores an incoming scroll event when `isScrolling &&- // _intendedScrollOffset === null && offset === scrollOffset`. That guard- // exists so a PROGRAMMATIC scroll's own event still gets through, and it- // is armed by `_intendedScrollOffset` being non-null. If the- // reconciliation writes scrollOffset AND clears the intent, all three- // conditions hold, so every scrollToIndex swallows its own event and- // leaves `isScrolling` false and `scrollDirection` stale — which is what- // virtual-core steers dynamic re-measurement by.+ // Retain programmatic scroll intent during reconciliation; clearing it suppresses the matching event and+ // leaves scrolling state/direction stale.host = document.createElement('div');document.body.append(host);root = createRoot(host);@@ -117,13 +101,8 @@ describe('useVirtualizer scroll element remount', () => {scrollOffset: number | null;};- // The state a programmatic scroll leaves behind: the element has moved,- // the intent is recorded, and the cached offset is still stale because no- // scroll event has been delivered yet. Model that pre-event boundary with- // an own scrollTop value instead of the native setter: Chromium is then- // unable to race the assertion by legitimately delivering the pending- // read-back event and consuming the intent before React's concurrent- // commit settles.+ // Set an own scrollTop value to model pre-event state without Chromium racing the assertion by delivering a+ // native scroll event.await act(() => {Object.defineProperty(scroller, 'scrollTop', {configurable: true,@@ -153,8 +132,7 @@ describe('useVirtualizer scroll element remount', () => {await act(async () => {scroller!.scrollTop = 400 * ROW_HEIGHT;scroller!.dispatchEvent(new Event('scroll'));- // End the scroll like the browser would; the reconciliation deliberately- // stands down while a scroll is live.+ // End the active scroll before testing reconciliation, which intentionally waits for idle.scroller!.dispatchEvent(new Event('scrollend'));await new Promise((resolve) => {setTimeout(resolve, 0);@@ -162,16 +140,11 @@ describe('useVirtualizer scroll element remount', () => {});expect(renderedIndexes()).toContain(400);- // The container unmounts (a loading state) and remounts as a NEW element- // holding far fewer, unscrollable rows — a search-results swap. The- // core's offset restoration gets clamped to 0 by the browser with no- // scroll event; without the reconciliation patch the virtualizer keeps- // the stale deep offset and renders NO rows at all.+ // Remount with unscrollable results so the browser clamps the old offset without an event.await render(1000, false);await render(3, true);- // The reconciliation notifies from a layout effect; the corrected render- // can land a scheduler tick later.+ // Poll for the rerender scheduled by layout-effect reconciliation.await vi.waitFor(() => {expect(renderedIndexes()).toEqual([0, 1, 2]);});diff --git a/invokeai/frontend/webv2/src/platform/search/dateTokens.test.ts b/invokeai/frontend/webv2/src/platform/search/dateTokens.test.tsindex a934bda0ba..495434ccbe 100644--- a/invokeai/frontend/webv2/src/platform/search/dateTokens.test.ts+++ b/invokeai/frontend/webv2/src/platform/search/dateTokens.test.ts@@ -188,8 +188,7 @@ describe('isPossibleDatePrefix', () => {describe('formatIsoDate', () => {it('formats the calendar day itself regardless of timezone offset', () => {- // A UTC-based Date('2026-07-21') would render Jul 20 in negative offsets;- // parts-based construction must always yield the written day.+ // Parts-based construction must preserve the written day in negative UTC offsets.expect(formatIsoDate('2026-07-21', 'en-US')).toBe('Jul 21');expect(formatIsoDate('2026-07-21', 'de-DE')).toBe('21. Juli');});diff --git a/invokeai/frontend/webv2/src/platform/search/dateTokens.ts b/invokeai/frontend/webv2/src/platform/search/dateTokens.tsindex f776c00be9..482793ed37 100644--- a/invokeai/frontend/webv2/src/platform/search/dateTokens.ts+++ b/invokeai/frontend/webv2/src/platform/search/dateTokens.ts@@ -1,18 +1,6 @@/**- * Closed grammar for date-filter search tokens: `from:`, `to:`, and `date:`- * accepting ISO `YYYY-MM-DD` or the relative values `today`, `yesterday`, and- * `Nd`/`Nw`/`Nm` (that many days/weeks/calendar-months ago — a single date,- * not a span). Shared by the gallery search box and the command palette.- *- * Invalid token values are never silently dropped: they are reported in- * `invalidTokens` AND left in `text`, so plain text search still runs over- * them (this also keeps prompts that literally contain `from:something`- * findable). Only valid tokens are stripped from `text`.- *- * All dates are calendar days. Relative values resolve against the user's- * local calendar; the backend compares the resulting date-only strings- * against UTC timestamps, so day boundaries are effectively UTC — the same- * semantics as the `by_date:` virtual boards.+ * from/to/date accept ISO days, today/yesterday, or Nd/Nw/Nm ago (one day, not a span). Keep invalid tokens in+ * both text and invalidTokens. Relative dates use local calendar arithmetic; backend date boundaries are UTC.*/export type DateTokenKey = 'from' | 'to' | 'date';@@ -138,11 +126,7 @@ export const parseDateTokens = (query: string, now: Date = new Date()): DateToke};};-/**- * True when the timestamp's calendar day falls within the range (bounds- * inclusive and optional). Works for both space- and T-separated ISO- * timestamps; empty/absent timestamps fail closed.- */+/** Inclusive optional date bounds; accept space/T timestamps and reject absent timestamps. */export const isTimestampInRange = (isoTimestamp: string, range: DateRange): boolean => {const day = isoTimestamp.slice(0, 10);@@ -181,10 +165,7 @@ export const completeTrailingDateToken = (query: string, value: string): stringreturn `${query.slice(0, trailing.start)}${trailing.key}:${value} `;};-/**- * True while `partialValue` could still become a valid value with more- * typing — used to suppress invalid-token feedback during normal entry.- */+/** Suppress invalid-token feedback while the value can still become valid by typing. */export const isPossibleDatePrefix = (partialValue: string): boolean => {const lower = partialValue.toLowerCase();@@ -200,11 +181,7 @@ export const isPossibleDatePrefix = (partialValue: string): boolean => {return /^\d{1,4}(-(\d{0,2}(-\d{0,2})?)?)?$/.test(lower) && lower.length <= 10;};-/**- * The first invalid token worth surfacing as feedback. A trailing token whose- * value could still become valid with more typing (`from:`, `from:2026-`) is- * normal entry, not an error, and is exempted.- */+/** Ignore a potentially valid trailing token while reporting the first other invalid token. */export const findInvalidDateToken = (query: string, parse: DateTokenParse): InvalidDateToken | undefined => {const trailing = matchTrailingDateToken(query);@@ -219,11 +196,6 @@ export const findInvalidDateToken = (query: string, parse: DateTokenParse): Inva);};-/**- * The label shape an applied range should render as: a single day (both bounds- * equal), a closed range, or an open-ended bound. Surfaces map each kind to- * their own i18n copy.- */export type DateRangeShape =| { kind: 'day'; date: string }| { kind: 'range'; from: string; to: string }@@ -248,11 +220,7 @@ export const describeDateRange = (range: DateRange): DateRangeShape | null => {return null;};-/**- * Formats a YYYY-MM-DD string as a short local date ("Jul 14"). Builds the- * Date from parts in local time — never via `new Date(isoString)`, which- * would parse as UTC and shift the day in negative-offset timezones.- */+/** Construct local dates from parts; parsing YYYY-MM-DD as UTC would shift display in negative offsets. */export const formatIsoDate = (isoDate: string, locale?: string): string => {const parts = ISO_DATE_PATTERN.exec(isoDate);diff --git a/invokeai/frontend/webv2/src/platform/state/accountLifecycle.ts b/invokeai/frontend/webv2/src/platform/state/accountLifecycle.tsindex c12a1c9ec3..b3f5b60cb3 100644--- a/invokeai/frontend/webv2/src/platform/state/accountLifecycle.ts+++ b/invokeai/frontend/webv2/src/platform/state/accountLifecycle.ts@@ -1,9 +1,5 @@export interface AccountScope {- /**- * Stable backend identity for this authenticated lifetime. `null` represents- * the boot/login lifetime, which is still epoch-scoped so its async work can- * be invalidated before an account becomes active.- */+ /** Identity is stable for this epoch; null boot/login lifetimes are also fenced against later account activation. */readonly accountId: string | null;/** Monotonically increasing identity lifetime, including same-user logins. */readonly epoch: number;@@ -48,10 +44,8 @@ const createScope = (): AccountScope => Object.freeze({ accountId, epoch, signal, storageSuffix });/**- * Owns identity epochs and the account-resource registry behind one small- * interface. Identity decides *when* a transition happens; the App composition- * root supplies this lifecycle, and feature caches register independently so- * lazy editor modules do not enter the Launchpad's eager dependency graph.+ * Identity triggers transitions; App supplies lifecycle ownership and lazy features register cleanup without+ * entering eager bundles.*/export const createAccountLifecycle = (): AccountLifecycle => {let controller = new AbortController();@@ -64,8 +58,7 @@ export const createAccountLifecycle = (): AccountLifecycle => {try {resource.clear();} catch {- // Privacy cleanup is fail-safe: one defective resource must not leave- // every later cache live. Resource-specific tests own diagnostics.+ // Continue privacy cleanup after one resource fails so later caches cannot remain live.}}};@@ -81,8 +74,7 @@ export const createAccountLifecycle = (): AccountLifecycle => {};const invalidate = (): AccountScope => {- // Rotate first. Any completion racing a clear observes a stale epoch and- // must become a no-op even if its transport cannot be aborted.+ // Rotate the epoch before clearing resources so racing, non-abortable completions are already stale.rotateScope(null, '');clearResources();diff --git a/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.test.ts b/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.test.tsindex ef0afb61bb..3b68555fdc 100644--- a/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.test.ts+++ b/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.test.ts@@ -12,9 +12,7 @@ describe('isSlotUnclaimed', () => {});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.+ // Treat undefined as a newer write by default; opting in still cannot overwrite a claimed slot.expect(isSlotUnclaimed(undefined, 'painted')).toBe(false);expect(isSlotUnclaimed(undefined, 'painted', { treatUnknownAsUnclaimed: true })).toBe(true);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 66288ac90c..bcd58818df 100644--- a/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.ts+++ b/invokeai/frontend/webv2/src/platform/state/compareAndSwapRollback.ts@@ -1,15 +1,6 @@/**- * The one rule for undoing an optimistic write: restore a slot only if it still- * holds exactly what this mutation painted there.- *- * 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.- *- * 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.+ * Roll back only if the slot still equals this mutation's optimistic value; unconditional restore would erase+ * newer writes.*//** What a rollback needs to know about a slot: what was there, and what we put there. */@@ -21,13 +12,7 @@ export interface CompareAndSwapEntry<Value> {}export interface CompareAndSwapOptions {- /**- * Treat a slot that reads `undefined` as revertible.- *- * Correct where `undefined` means "no local copy of this exists" rather than- * "someone cleared it" — a per-item lookup that simply misses, for instance.- * Wrong where `undefined` is a value another writer could have set.- */+ /** Enable only when undefined means no local copy, never when another writer could deliberately clear the slot. */treatUnknownAsUnclaimed?: boolean;}diff --git a/invokeai/frontend/webv2/src/platform/state/projectedExternalStore.ts b/invokeai/frontend/webv2/src/platform/state/projectedExternalStore.tsindex 770ad5bf5d..f56a1a5b50 100644--- a/invokeai/frontend/webv2/src/platform/state/projectedExternalStore.ts+++ b/invokeai/frontend/webv2/src/platform/state/projectedExternalStore.ts@@ -12,11 +12,7 @@ interface ProjectedExternalStoreOptions<Source, Snapshot> {isEqual?: EqualityFn<Snapshot>;}-/**- * Projects a broad external store into a referentially stable read-only store.- * The source subscription is shared lazily and unrelated source changes remain- * silent when the projected snapshot is equal.- */+/** Share the source subscription lazily and preserve snapshot identity when the projection is equal. */export const createProjectedExternalStore = <Source, Snapshot>({isEqual = Object.is,select,diff --git a/invokeai/frontend/webv2/src/platform/state/singleFlight.ts b/invokeai/frontend/webv2/src/platform/state/singleFlight.tsindex c26922f2cd..7f0656b272 100644--- a/invokeai/frontend/webv2/src/platform/state/singleFlight.ts+++ b/invokeai/frontend/webv2/src/platform/state/singleFlight.ts@@ -17,12 +17,8 @@ export interface TrailingSingleFlight {}/**- * Single-flight dedupe for a store refresh that must not lose requests: a- * refresh asked for while one is already in flight would otherwise be- * absorbed by a request that was issued before the triggering change existed- * (e.g. two install completions ~100ms apart). The trailing rerun re-executes- * the task once after the current flight settles; its rejection is swallowed- * because no caller is attached to it.+ * Coalesce refreshes but rerun once for changes arriving mid-flight. No caller awaits the trailing run, so its+ * rejection is swallowed.*/export const createTrailingSingleFlight = (): TrailingSingleFlight => {let pending: Promise<void> | null = null;diff --git a/invokeai/frontend/webv2/src/platform/time/serverTimestamp.ts b/invokeai/frontend/webv2/src/platform/time/serverTimestamp.tsindex f5bf7a38c3..df46859ee8 100644--- a/invokeai/frontend/webv2/src/platform/time/serverTimestamp.ts+++ b/invokeai/frontend/webv2/src/platform/time/serverTimestamp.ts@@ -1,8 +1,4 @@-/**- * The backend stamps timestamps via SQLite ("2026-06-11 09:21:04.123") —- * UTC, but with no timezone marker, which `Date` would misread as local- * time. Normalize to ISO once, at the boundary that parses the value.- */+/** SQLite timestamps are UTC without a zone marker; normalize before Date can interpret them as local time. */export const normalizeServerTimestamp = (value: string): string => {if (!/^\d{4}-\d{2}-\d{2} /.test(value)) {return value;diff --git a/invokeai/frontend/webv2/src/platform/transport/connectionStore.ts b/invokeai/frontend/webv2/src/platform/transport/connectionStore.tsindex 1a8809495a..d5d700b88d 100644--- a/invokeai/frontend/webv2/src/platform/transport/connectionStore.ts+++ b/invokeai/frontend/webv2/src/platform/transport/connectionStore.ts@@ -2,13 +2,7 @@ import { createExternalStore } from '@platform/state/externalStore';import type { BackendConnectionStatus } from './types';-/**- * Provider-free connection status for the shared backend socket. The socket hub- * is the sole writer; surfaces that mount no workbench providers (the Launchpad)- * read it directly, and the editor mirrors it into workbench state via a bridge- * in `WorkbenchRuntime`. Lives outside the reducer so the connection signal is- * available everywhere the socket is, not just inside the editor.- */+/** The socket hub alone writes this provider-free store; Launchpad reads directly and Workbench mirrors it. */export interface ConnectionSnapshot {status: BackendConnectionStatus;error?: string;diff --git a/invokeai/frontend/webv2/src/platform/transport/deploymentBase.ts b/invokeai/frontend/webv2/src/platform/transport/deploymentBase.tsindex 1798b33911..529264dd1b 100644--- a/invokeai/frontend/webv2/src/platform/transport/deploymentBase.ts+++ b/invokeai/frontend/webv2/src/platform/transport/deploymentBase.ts@@ -1,9 +1,4 @@-/**- * Derives the backend deployment root (origin plus an optional reverse-proxy- * prefix) from the emitted module URL. Vite emits production chunks beneath- * `<deployment-root>/assets/`; development modules have no `/assets/` segment- * and therefore keep the existing origin-root behavior.- */+/** Production modules resolve the deployment prefix before /assets/; development falls back to the origin root. */export const deriveDeploymentBaseUrl = (moduleUrl: string,fallbackOrigin: string,diff --git a/invokeai/frontend/webv2/src/platform/transport/http.test.ts b/invokeai/frontend/webv2/src/platform/transport/http.test.tsindex d5a5d40e4d..b04b917ad2 100644--- a/invokeai/frontend/webv2/src/platform/transport/http.test.ts+++ b/invokeai/frontend/webv2/src/platform/transport/http.test.ts@@ -177,8 +177,7 @@ describe('request identity ownership', () => {describe('media cookie credentials', () => {beforeEach(() => {- // One stable identity for the whole request: a fresh object per call would read as a- // mid-request account rotation and reject before the assertion.+ // Keep the identity object stable; a fresh object would simulate rotation before the assertion.const identity = {};configureHttpAuth({ getIdentity: () => identity, getToken: () => null, onUnauthorized: vi.fn() });});diff --git a/invokeai/frontend/webv2/src/platform/transport/http.ts b/invokeai/frontend/webv2/src/platform/transport/http.tsindex 8531649f9f..422fe487a6 100644--- a/invokeai/frontend/webv2/src/platform/transport/http.ts+++ b/invokeai/frontend/webv2/src/platform/transport/http.ts@@ -1,9 +1,4 @@-/**- * Shared HTTP client for the InvokeAI backend. Every REST call goes through- * `apiFetch` so authentication matches the WebSocket connection: both read the- * an Auth-owned adapter and send it as a bearer token. The token is read per- * request, so an identity change applies without a reload.- */+/** Read the Auth-owned bearer token per request so HTTP and WebSocket identity stay aligned without reloads. */import { getDeploymentBasePath, getDeploymentBaseUrl } from './deploymentBase';@@ -28,11 +23,7 @@ export const configureHttpAuth = (adapter: HttpAuthAdapter): void => {export const getHttpAuthToken = (): string | null => authAdapter.getToken();-/**- * Called when an authenticated request comes back 401 — the stored token is no- * longer valid. The auth session store registers itself here so the HTTP layer- * stays unaware of session semantics.- */+/** Auth registers 401 handling here to keep session semantics out of transport. */export const getBackendSocketUrl = (): string => {const baseUrl = API_BASE_URL || getDeploymentBaseUrl();@@ -150,16 +141,8 @@ const fetchWithAuthToken = (path: string, init: RequestInit | undefined, token:headers.set('Authorization', `Bearer ${token}`);}- // `credentials` is stated rather than left to the fetch default because the backend now- // authenticates media routes (`/images/i/{name}/full`, `/videos/i/{name}/full`) with the- // path-scoped HttpOnly cookie that login sets — `<img>`/`<video>` cannot send a bearer- // header. Losing the login `Set-Cookie` would blank every thumbnail in multiuser mode, so- // the cookie behavior is pinned here where it can be asserted.- //- // 'same-origin' covers the normal deployment and the dev Vite proxy. A cross-origin- // VITE_INVOKEAI_API_BASE_URL would additionally need 'include' here plus- // Access-Control-Allow-Credentials on the backend; requesting 'include' unconditionally- // would instead break those setups outright, so callers opt in via `init`.+ // Use same-origin credentials so login stores the media cookie. Cross-origin API callers must opt into include+ // and configure server credential support.return fetch(buildApiUrl(path), { credentials: 'same-origin', ...init, headers });};@@ -175,8 +158,7 @@ export const apiFetchRaw = async (path: string, init?: RequestInit): Promise<Res};export const apiFetch = async (path: string, init?: RequestInit): Promise<Response> => {- // Capture one principal for the complete request. A late User A response- // must neither use User B's header nor expire User B's newer session.+ // Capture one principal so late responses cannot use or expire a newer session.const requestToken = getHttpAuthToken();const requestIdentity = authAdapter.getIdentity();const response = await fetchWithAuthToken(path, init, requestToken);@@ -196,8 +178,7 @@ export const apiFetch = async (path: string, init?: RequestInit): Promise<Responreturn asserted;} catch (error) {- // A current-session 401 intentionally rotates identity inside- // `onUnauthorized`; callers should still receive the backend ApiError.+ // Preserve the original ApiError even when current-session 401 handling rotates identity.if (!expiredCurrentIdentity) {assertHttpIdentityCurrent(requestIdentity);}@@ -206,10 +187,7 @@ export const apiFetch = async (path: string, init?: RequestInit): Promise<Respon}};-/**- * Backend errors arrive as FastAPI JSON (`{"detail": "..."}`); `ApiError`- * carries the raw body. This unwraps `detail` into a human-readable message.- */+/** Unwrap FastAPI's detail field from ApiError's raw body for display. */export const getApiErrorMessage = (error: unknown, fallback: string): string => {if (error instanceof ApiError) {try {diff --git a/invokeai/frontend/webv2/src/platform/transport/socketHub.ts b/invokeai/frontend/webv2/src/platform/transport/socketHub.tsindex 68abaa38d4..2991e5045f 100644--- a/invokeai/frontend/webv2/src/platform/transport/socketHub.ts+++ b/invokeai/frontend/webv2/src/platform/transport/socketHub.ts@@ -5,9 +5,6 @@ import type { BackendConnectionStatus } from './types';import { setConnectionStatus } from './connectionStore';import { getBackendSocketPath, getBackendSocketUrl, getHttpAuthToken } from './http';-/**- * The minimal Socket.IO surface the hub uses; tests substitute a fake.- */export interface BackendSocket {on(event: string, handler: (payload: never) => void): unknown;off(event: string, handler: (payload: never) => void): unknown;@@ -18,11 +15,7 @@ export interface BackendSocket {export type ConnectionListener = (status: BackendConnectionStatus, error?: string) => void;-/**- * Owns the single backend socket for the whole authenticated app. It is only a- * transport/status hub; feature runtimes attach their own listeners so admin- * model code and editor queue code do not leak into the base Launchpad bundle.- */+/** Own one authenticated socket; feature listeners stay outside the hub to preserve Launchpad bundle boundaries. */export interface SocketHub {/** Idempotent: connects the single socket if one is not already live. */connect(): void;@@ -38,8 +31,7 @@ export interface SocketHub {const createDefaultSocket = (): BackendSocket => {const token = getHttpAuthToken();- // Socket.IO's generic `off` overload does not structurally match our minimal- // facade; the socket satisfies the surface we actually use, so narrow it here.+ // Narrow Socket.IO's generic off overload to the facade's supported calls.return io(getBackendSocketUrl(), {auth: token ? { token } : undefined,autoConnect: false,diff --git a/invokeai/frontend/webv2/src/platform/ui/Button.tsx b/invokeai/frontend/webv2/src/platform/ui/Button.tsxindex 602c267afe..433e0496ac 100644--- a/invokeai/frontend/webv2/src/platform/ui/Button.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Button.tsx@@ -26,12 +26,7 @@ type IconButtonAccessibleName =export type IconButtonProps = Omit<ChakraIconButtonProps, 'aria-label' | 'aria-labelledby'> & IconButtonAccessibleName;-/**- * Workbench buttons. Solid buttons default to the blue `accent` palette; every- * other variant stays on the neutral, theme-aware `gray` palette. Pass- * `colorPalette` explicitly to override (e.g. `brand` for the global Invoke- * action, `red` for destructive actions).- */+/** Solid defaults to accent; other variants to gray. Explicit colorPalette overrides both. */const defaultPalette = (variant: ButtonProps['variant']): ButtonProps['colorPalette'] =>variant === undefined || variant === 'solid' ? 'accent' : 'gray';@@ -58,12 +53,7 @@ export interface ToggleIconButtonProps extends Omit<onCheckedChange: (checked: boolean) => void;}-/**- * A compact on/off control that states what it toggles. Prefer this over- * {@link ToggleDot} wherever the setting is not self-evident from its- * neighbours — the icon carries the meaning, `aria-pressed` carries the state,- * and the filled variant makes "on" readable at a glance.- */+/** Use an icon toggle when nearby context cannot explain ToggleDot; aria-pressed carries state. */export const ToggleIconButton = ({checked,icon,diff --git a/invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsx b/invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsxindex df60c9e2b5..5061b55a68 100644--- a/invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsx@@ -41,12 +41,7 @@ const MACHINE_FORMAT: Record<ColorPickerFormat, 'rgba' | 'hsla' | 'hsba'> = {rgb: 'rgba',};-/**- * The checkerboard behind transparent colors. This is a CSS *length* (it drives- * `background-size` on a conic gradient), not a size token — passing `"xs"`- * yields an invalid `background-size` and the gradient renders once, stretched,- * instead of tiling. Chakra's own default is `0.6rem`.- */+/** Checkerboard size must be a CSS length, not a Chakra size token. */const TRANSPARENCY_CHECK_SIZE = '0.5rem';const SWATCH_GROUP_CSS = {@@ -185,8 +180,6 @@ export const ColorPicker = ({const [color, setColor] = useState<Color>(() => parseColor(value));const [lastEmittedValue, setLastEmittedValue] = useState(() => toEmitted(color));- // Sync external -> internal only when the prop genuinely changed to- // something other than our own emit's round trip (see `shouldSyncExternalColor`).if (value !== previousExternalValue) {setPreviousExternalValue(value);if (shouldSyncExternalColor(value, previousExternalValue, lastEmittedValue, isAwaitingEcho)) {@@ -214,9 +207,7 @@ export const ColorPicker = ({const handleValueChange = useCallback((details: ColorPickerValueChangeDetails) => {- // A swatch pick is both a change and a commit; Zag only reports the- // change, so `CommittingSwatch` arms the commit and it lands here in the- // right order.+ // Zag emits only change for swatches; arm a commit so onChangeEnd follows onChange.const isCommit = isSwatchCommitArmed.current;isSwatchCommitArmed.current = false;emit(details.value, isCommit);@@ -322,11 +313,7 @@ export const ColorPicker = ({<Icon as={Pipette} boxSize="4" /></IconButton>) : canUseScreenEyeDropper ? (- // `EyeDropperTrigger` is a bare Ark part, not an IconButton —- // rendered directly it has no icon and drops `variant`/`size`- // onto the DOM as raw attributes, collapsing to a 0x0 button.- // `asChild` puts the machine's behavior on workbench chrome, so- // both eyedropper branches look identical.+ // Use asChild with IconButton: Ark's bare trigger has no icon or workbench styling.<ChakraColorPicker.EyeDropperTrigger asChild><IconButton aria-label={t('common.colorPicker.sampleFromScreen')} size="xs" variant="ghost"><Icon as={Pipette} boxSize="4" />diff --git a/invokeai/frontend/webv2/src/platform/ui/Combobox.tsx b/invokeai/frontend/webv2/src/platform/ui/Combobox.tsxindex f2cba27ba7..36188d8534 100644--- a/invokeai/frontend/webv2/src/platform/ui/Combobox.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Combobox.tsx@@ -185,9 +185,7 @@ export const Combobox = ({<Portal><ChakraCombobox.Positioner><ChakraCombobox.Content>- {/* The list is its own scroll container (ark scrolls it to keep the- highlighted option in view); a thin always-visible scrollbar- makes the overflow legible instead of looking cut off. */}+ {/* Keep this as Ark's scroll container so keyboard highlight remains visible. */}<ChakraCombobox.Listcss={LIST_SCROLL_CSS}maxH="16rem"diff --git a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsxindex 810cacf4f6..43d0fa54e3 100644--- a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx@@ -3,11 +3,7 @@ import { useCallback, useRef, useState, type ReactNode } from 'react';import { Button, CloseButton } from './Button';-/**- * Controlled confirmation dialog for consequential actions. The confirm- * button shows a pending state while `onConfirm` runs; errors are left to the- * caller (usually surfaced as a notification) and the dialog closes either way.- */+/** Closes after confirmation even on error; callers must report failures. */export const ConfirmDialog = ({body,confirmLabel,diff --git a/invokeai/frontend/webv2/src/platform/ui/DropTargetOverlay.tsx b/invokeai/frontend/webv2/src/platform/ui/DropTargetOverlay.tsxindex eb4932bdab..7925774fa3 100644--- a/invokeai/frontend/webv2/src/platform/ui/DropTargetOverlay.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/DropTargetOverlay.tsx@@ -2,17 +2,7 @@ import { Text } from '@chakra-ui/react';import { DropZone } from './DropZone';-/**- * The drag-in-flight affordance every image/video drop target shares: renders- * nothing until a compatible drag is active anywhere, then floats the- * `DropZone` overlay treatment (dashed border over a surface tint, flipping- * to accent while hovered) above the target's own content with a centered- * call-to-action — the "potential target" / "over" pair of states.- *- * `pointerEvents` stays off — dnd-kit hit-tests the droppable's rect, not- * this overlay — and the absolute inset needs `position: relative` (or any- * containing block) on the target element.- */+/** Requires a positioned parent. Keep pointer events off: dnd-kit hit-tests the droppable, not this overlay. */export const DropTargetOverlay = ({isActive,isOver,diff --git a/invokeai/frontend/webv2/src/platform/ui/DropZone.tsx b/invokeai/frontend/webv2/src/platform/ui/DropZone.tsxindex 9ebd081c20..e6215aa46e 100644--- a/invokeai/frontend/webv2/src/platform/ui/DropZone.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/DropZone.tsx@@ -16,27 +16,12 @@ export interface DropZoneProps extends BoxProps {isOver?: boolean;/** Forwarded to the underlying element (e.g. dnd-kit's `setNodeRef`). */ref?: Ref<HTMLDivElement>;- /**- * `inline` — a persistent, usually clickable upload box inside a form.- * `overlay` — a drag-time overlay floated above existing content; heavier- * border and a surface tint so it reads against arbitrary backdrops.- */+ /** inline is a persistent upload surface; overlay floats above content during dragging. */variant?: 'inline' | 'overlay';}-/**- * The workbench drop-target look: dashed `border.emphasized` at rest, an- * accent border on pointer hover previewing the drop treatment, and an- * `accent.solid` border over an `accent.muted` tint while a compatible drag- * hovers. Every drop zone and upload area composes this so drag affordances- * stay identical across the app; callers add their own icon/hint content,- * interaction handlers, and layout props.- */export const DropZone = ({ children, isDisabled, isOver, variant = 'inline', _hover, ...boxProps }: DropZoneProps) => {- // Merged here rather than spread: `:hover` stays live during a drag, so a- // consumer hover fill would otherwise paint over the drag-over treatment.- // The accent preview is for persistent inline zones only — overlays exist- // mid-drag, where dnd-kit's own `isOver` is the signal.+ // Merge hover styles so they cannot override drag-over fills; overlays use isOver instead of pointer hover.const hoverProps = useMemo(() => ({...(variant === 'inline' && !isDisabled ? { borderColor: 'accent.solid' } : null),diff --git a/invokeai/frontend/webv2/src/platform/ui/EmptyState.tsx b/invokeai/frontend/webv2/src/platform/ui/EmptyState.tsxindex fca6b5c7c1..fb7f5a930a 100644--- a/invokeai/frontend/webv2/src/platform/ui/EmptyState.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/EmptyState.tsx@@ -6,20 +6,7 @@ export interface EmptyStateProps extends ChakraEmptyState.RootProps {description?: string | null;icon?: React.ReactNode;danger?: boolean;- /**- * Where the block sits on its own cross axis.- *- * `center` (the default) is right inside a dialog, a panel, or anywhere the- * empty state is the only thing on screen. `start` is right on a page whose- * heading, description and toolbar are all flush left: a centered block- * under a left-aligned page has no shared edge with anything above it, and- * reads as a different screen rather than as the page's own content.- *- * `start` also drops the recipe's horizontal padding, so the text lands- * exactly on the page's text column. Left-aligning but staying inset would- * be worse than centering — a near miss reads as a mistake, where a clean- * center reads as a choice.- */+ /** center suits isolated empty states; start aligns with page content and removes horizontal recipe padding. */align?: 'center' | 'start';}@@ -28,8 +15,7 @@ export const EmptyState = React.forwardRef<HTMLDivElement, EmptyStateProps>(funcconst fgColor = danger ? 'fg.error' : undefined;const isStart = align === 'start';return (- // `px` before the spread, not after: dropping the recipe's inset is this prop's job, but a- // caller that asked for its own padding still outranks it.+ // Apply default px before caller props so explicit padding wins.<ChakraEmptyState.Root ref={ref} px={isStart ? '0' : undefined} {...rest} size={props.size ?? 'sm'}><ChakraEmptyState.Content alignItems={isStart ? 'flex-start' : undefined}>{icon && <ChakraEmptyState.Indicator color={fgColor}>{icon}</ChakraEmptyState.Indicator>}diff --git a/invokeai/frontend/webv2/src/platform/ui/Field.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Field.browser.test.tsxindex b29f0c86b6..741315e969 100644--- a/invokeai/frontend/webv2/src/platform/ui/Field.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Field.browser.test.tsx@@ -54,10 +54,8 @@ const render = async (hinted: boolean) => {describe('Field with a hint', () => {/**- * The hover-card trigger stamps its own `id` on whatever element it wraps, so- * making the `<label>` itself the trigger replaced the Field-derived id that- * controls reference through `aria-labelledby` — axe reported every hinted- * Select as having no accessible name. The trigger must sit *inside* the label.+ * Keep the hint trigger inside the label so its generated ID cannot replace the control's aria-labelledby+ * target.*/it('keeps the Field-derived label id when a hint is attached', async () => {const hosted = await render(true);diff --git a/invokeai/frontend/webv2/src/platform/ui/Field.tsx b/invokeai/frontend/webv2/src/platform/ui/Field.tsxindex e9c25ea13f..d95b607f82 100644--- a/invokeai/frontend/webv2/src/platform/ui/Field.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Field.tsx@@ -6,11 +6,6 @@ import { FeatureHint } from '@platform/ui/hints';import { fieldLabelRecipe } from '@theme/recipes';import { useMemo } from 'react';-/**- * The shared, theme-aware uppercase field label. Backed by `fieldLabelRecipe` so- * every form across the workbench renders an identical label without repeating- * the same five style props inline.- */export const FieldLabel = ({ children }: { children: ReactNode }) => {const recipe = useRecipe({ recipe: fieldLabelRecipe });@@ -68,12 +63,8 @@ export const Field = ({: undefined,[id]);- // The hint wraps the label's *text*, never the `ChakraField.Label` itself:- // the hover-card trigger stamps its own `id` on whatever element it is given,- // which would clobber the id that every control's `aria-labelledby` points at- // and leave the control with no accessible name. A conditional render, not a- // conditional hook — `FeatureHint` owns the context read and returns its child- // untouched when hints are off.+ // Wrap label text only: the hint trigger overwrites its child's ID and would break aria-labelledby on the label+ // itself.const labelContent = (<ChakraField.Label css={recipe()}>{hint ? (diff --git a/invokeai/frontend/webv2/src/platform/ui/Group.tsx b/invokeai/frontend/webv2/src/platform/ui/Group.tsxindex 097a6e933b..6ff3f84c8c 100644--- a/invokeai/frontend/webv2/src/platform/ui/Group.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Group.tsx@@ -6,19 +6,8 @@ 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.+ * Use positional selectors because composite children may drop Chakra's data-first/between/last props. Match+ * upstream declarations and priority.*/const attachedCss = {horizontal: {diff --git a/invokeai/frontend/webv2/src/platform/ui/HsvBoxPicker.tsx b/invokeai/frontend/webv2/src/platform/ui/HsvBoxPicker.tsxindex 2139825fcf..f568579224 100644--- a/invokeai/frontend/webv2/src/platform/ui/HsvBoxPicker.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/HsvBoxPicker.tsx@@ -23,13 +23,7 @@ const HUE_STRIP_CSS = {background: 'linear-gradient(to right, red, yellow, lime, cyan, blue, magenta, red)',};-/**- * The box-mode HSV picker: a saturation/value square under the hue, with a hue- * strip beneath — the layout the popover picker uses, sharing the wheel's- * `HsvColor` contract so the color pane can flip between the two. The square's- * shading is exact: white→hue across saturation, multiplied down to black by- * value, which is precisely two stacked linear gradients.- */+/** Shares HsvColor with the wheel; layered white-to-hue and transparent-to-black gradients encode saturation/value. */export const HsvBoxPicker = ({disabled = false,heightPx = 140,diff --git a/invokeai/frontend/webv2/src/platform/ui/HsvWheelPicker.tsx b/invokeai/frontend/webv2/src/platform/ui/HsvWheelPicker.tsxindex b868719600..d202e2c803 100644--- a/invokeai/frontend/webv2/src/platform/ui/HsvWheelPicker.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/HsvWheelPicker.tsx@@ -32,11 +32,8 @@ const clamp01 = (value: number): number => Math.min(1, Math.max(0, value));const THUMB_FOCUS_PROPS = { outline: '2px solid {colors.accent.solid}', outlineOffset: '2px' };/**- * The wheel-and-triangle HSV picker: a conic hue ring around a barycentric- * saturation/value triangle that points at the hue (the classic GIMP/Krita- * layout). Both thumbs are keyboard sliders; drags report live through- * `onChange` and settle through `onChangeEnd`. The triangle is painted- * per-pixel on a canvas so its shading matches the exact math the thumbs use.+ * Both HSV thumbs support keyboard input; drags emit onChange and finish with onChangeEnd. Canvas shading uses the+ * same triangle math.*/export const HsvWheelPicker = ({diameterPx = 192,@@ -61,10 +58,7 @@ export const HsvWheelPicker = ({useEffect(() => () => drag.current?.abort(), []);- // Repaint the triangle only when the hue (or geometry) changes; saturation- // and value only move the thumb. The corner geometry is hoisted out of the- // pixel loop, and the bitmap is painted at device resolution so the triangle- // stays as crisp as the CSS ring beside it.+ // Repaint at device resolution only for hue/geometry changes; saturation/value only move the thumb.useEffect(() => {const canvas = triangleCanvasRef.current;const ctx = canvas?.getContext('2d');@@ -155,8 +149,7 @@ export const HsvWheelPicker = ({if (distance > radius) {return;}- // Each drag moves one axis: a hue drag keeps the s/v it started with and- // a triangle drag keeps its hue, so the other thumb never wanders.+ // Freeze the other color axes during each drag.if (distance >= radius - ringWidth - TRIANGLE_INSET_PX / 2) {beginDrag(event, (p) => ({ ...value, h: wheelAngleToHue(pointToWheelAngle(p)) }));} else {diff --git a/invokeai/frontend/webv2/src/platform/ui/InputShell.tsx b/invokeai/frontend/webv2/src/platform/ui/InputShell.tsxindex 2048c0fcc7..2521c6514e 100644--- a/invokeai/frontend/webv2/src/platform/ui/InputShell.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/InputShell.tsx@@ -28,13 +28,7 @@ const focusInnerInput = (event: PointerEvent<HTMLDivElement>) => {}};-/**- * The themed input's chrome for composite fields whose focusable element lives- * inside the frame — a transparent input under a rendered mirror, a query- * chip. Metrics and states match `<Input size="xs">`, keyed on focus-within so- * the frame responds to the inner control; `aria-invalid` on the shell drives- * the invalid border like the input's own.- */+/** Composite input chrome follows inner focus via focus-within; put aria-invalid on the shell for its error border. */export const InputShell = ({ children, endElement, ref, startElement, ...boxProps }: InputShellProps) => (<Boxref={ref}@@ -48,8 +42,7 @@ export const InputShell = ({ children, endElement, ref, startElement, ...boxPropgap="1.5"h="7"minW="0"- // Trailing icon buttons carry their own inset; full end padding pushes- // them visibly further from the border than the leading glyph sits.+ // Trailing buttons own their inset; omit duplicate end padding.pe={endElement ? '1' : '2'}ps="2"textStyle="xs"diff --git a/invokeai/frontend/webv2/src/platform/ui/InvokeMark.tsx b/invokeai/frontend/webv2/src/platform/ui/InvokeMark.tsxindex c4c6eb09f3..a0187c0c6d 100644--- a/invokeai/frontend/webv2/src/platform/ui/InvokeMark.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/InvokeMark.tsx@@ -5,12 +5,7 @@ import { Box } from '@chakra-ui/react';/** The stylized Invoke "I" logomark path, on a 44×44 viewBox. */const INVOKE_MARK_PATH = 'M29.1951 10.6667H42V2H2V10.6667H14.8049L29.1951 33.3333H42V42H2V33.3333H14.8049';-/**- * The Invoke logomark as a bare `1em`/`currentColor` glyph, shaped like a- * Lucide icon so it drops into `<Icon as={InvokeMarkIcon} />` and inherits the- * surrounding color. Decorative by default; the button around it carries the- * accessible name.- */+/** A currentColor/1em glyph; decorative by default, so the containing control needs an accessible name. */export const InvokeMarkIcon = (props: SVGProps<SVGSVGElement>) => (<svgaria-hidden="true"diff --git a/invokeai/frontend/webv2/src/platform/ui/JsonPreview.tsx b/invokeai/frontend/webv2/src/platform/ui/JsonPreview.tsxindex 0aaf7e5890..1f4b3d4246 100644--- a/invokeai/frontend/webv2/src/platform/ui/JsonPreview.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/JsonPreview.tsx@@ -6,14 +6,7 @@ import { IconButton } from './Button';import { toaster } from './toaster';import { useScrollAreaPhantomHeal } from './useScrollAreaPhantomHeal';-/**- * The workbench's standard JSON preview: a monospace block with a copy button- * that owns its scrolling in both axes — long strings scroll horizontally- * instead of stretching the surrounding layout. Pass `value` to serialize, or- * `text` when the JSON string already exists (an export payload that must be- * copied byte-for-byte). Defaults to a bounded height; pass `maxH` (or wrap in- * a flex parent and pass `maxH="100%"`) to control it.- */+/** Pass text for byte-preserving copy, or value to serialize. Owns both scroll axes; maxH controls the bound. */export const JsonPreview = ({h,label = 'JSON preview',diff --git a/invokeai/frontend/webv2/src/platform/ui/Menu.tsx b/invokeai/frontend/webv2/src/platform/ui/Menu.tsxindex b578b8f8ab..a279ed78ce 100644--- a/invokeai/frontend/webv2/src/platform/ui/Menu.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Menu.tsx@@ -8,12 +8,7 @@ import { useRegisterWidgetOverlay } from './widgetOverlays';type MenuContentProps = ComponentProps<typeof Menu.Content>;-/**- * Menu.Content that closes with the tree that opened it. The workbench popover- * chrome (surface, stroke, radius, shadow) is applied globally by the `menu`- * slot-recipe override in `theme/recipes.ts`; this wrapper is the single- * import point for menu-wide behavior.- */+/** Menu content closes with its owning widget; the theme recipe owns chrome. */export const MenuContent = (props: MenuContentProps) => {const menu = useMenuContext();const stale = useRegisterWidgetOverlay(menu.open, menu.setOpen);@@ -86,11 +81,7 @@ export interface MenuIconItemProps {onSelect: () => void;}-/**- * An icon-only item for a menu's quick row. The tooltip wraps the icon, never- * the item: a tooltip trigger merged onto the item replaces the id zag selects- * by, so clicks and Enter would close the menu without firing `onSelect`.- */+/** Wrap the icon, not Menu.Item: tooltip IDs would replace Zag's selection ID and prevent onSelect. */export const MenuIconItem = ({ disabled, icon, iconFill, label, onSelect, tone, value }: MenuIconItemProps) => (<Menu.Itemaria-label={label}diff --git a/invokeai/frontend/webv2/src/platform/ui/MiddleTruncate.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/MiddleTruncate.browser.test.tsxindex f9b764c8f0..b0f2fd2f9c 100644--- a/invokeai/frontend/webv2/src/platform/ui/MiddleTruncate.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/MiddleTruncate.browser.test.tsx@@ -97,8 +97,7 @@ describe('MiddleTruncate', () => {expect(head.textContent).toBe('Panther and t');expect(tail.textContent).toBe('he Flask');- // `white-space: pre` keeps the leading space from collapsing; with- // `nowrap` the flex item would strip it and fuse the halves.+ // white-space: pre preserves the leading space at the flex split.expect(getComputedStyle(tail).whiteSpace).toBe('pre');});});diff --git a/invokeai/frontend/webv2/src/platform/ui/MiddleTruncate.tsx b/invokeai/frontend/webv2/src/platform/ui/MiddleTruncate.tsxindex 8c78f16e57..87d35c158b 100644--- a/invokeai/frontend/webv2/src/platform/ui/MiddleTruncate.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/MiddleTruncate.tsx@@ -5,13 +5,7 @@ const GRAPHEME_SEGMENTER = new Intl.Segmenter(undefined, { granularity: 'graphemconst DEFAULT_TAIL_GRAPHEMES = 8;-/**- * Splits text so the last `tailGraphemes` graphemes can be pinned while the- * rest ellipsizes. Splitting on graphemes rather than code units keeps- * surrogate pairs and emoji sequences intact at the boundary. Text at or- * under the tail length goes entirely into the head, which degrades to plain- * end truncation instead of an unshrinkable tail wider than its container.- */+/** Split by grapheme to preserve emoji; short strings stay entirely in the head to avoid an unshrinkable tail. */export const splitTextForMiddleTruncation = (text: string, tailGraphemes: number): { head: string; tail: string } => {if (tailGraphemes <= 0) {return { head: text, tail: '' };@@ -44,18 +38,8 @@ export interface MiddleTruncateProps extends Omit<TextProps, 'children'> {}/**- * Single-line text that truncates in the middle, macOS-style, so both the- * start and the end stay readable — for names and identifiers whose- * distinguishing part is often the suffix (file extensions, numbered copies,- * ids). Prose and static labels should keep ordinary end truncation.- *- * Pure CSS: the head is a shrinkable flex item with its own ellipsis and the- * tail never shrinks, so the split tracks container resizes without any- * measurement. When the text fits, head and tail render seamlessly. The spans- * use `white-space: pre` because each flex item is its own block: `nowrap`- * would strip a space that lands at the split point, visually fusing the two- * halves. The full text stays in the DOM, so selection, copy, and screen- * readers all see the real string.+ * For identifiers whose suffix matters. Keep white-space: pre so flex boundaries retain spaces; preserve full DOM+ * text for copy and accessibility.*/export const MiddleTruncate = ({ tailGraphemes = DEFAULT_TAIL_GRAPHEMES, text, ...textProps }: MiddleTruncateProps) => {const { head, tail } = useMemo(() => splitTextForMiddleTruncation(text, tailGraphemes), [tailGraphemes, text]);diff --git a/invokeai/frontend/webv2/src/platform/ui/ModelDefaultButton.tsx b/invokeai/frontend/webv2/src/platform/ui/ModelDefaultButton.tsxindex d6ae1ebf3b..6f6b647431 100644--- a/invokeai/frontend/webv2/src/platform/ui/ModelDefaultButton.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ModelDefaultButton.tsx@@ -4,11 +4,7 @@ import { Tooltip } from '@platform/ui/Tooltip';import { RotateCcwIcon } from 'lucide-react';import { useCallback } from 'react';-/**- * Reset-to-default affordance. Callers render it only while the value- * differs from the default, so its presence itself signals "modified". No- * fallback label: every call site knows what it's resetting and says so.- */+/** Render only for modified values and supply a specific reset label. */export const ModelDefaultButton = ({ label, onClick }: { label: string; onClick: () => void }) => {const handleClick = useCallback((event: React.MouseEvent<HTMLButtonElement>) => {diff --git a/invokeai/frontend/webv2/src/platform/ui/PageShell.tsx b/invokeai/frontend/webv2/src/platform/ui/PageShell.tsxindex 9a950b56fb..9e11875358 100644--- a/invokeai/frontend/webv2/src/platform/ui/PageShell.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/PageShell.tsx@@ -6,23 +6,8 @@ import { Flex, HStack, Heading, Stack, Text } from '@chakra-ui/react';import { Scrollable } from './Scrollable';/**- * A full-height section page: heading, optional description, an actions slot,- * and a readable measure.- *- * The Launchpad's sections each hand-rolled this — the projects and users- * pages carried duplicate `maxW="6xl"` blocks that had already drifted apart.- * It lives in Platform rather than beside the Launchpad because feature-owned- * pages need it too, and features may not import Workbench.- *- * `scroll` decides who owns the scrollbar:- * - `page` (default) scrolls the whole page, header included. Right for- * ordinary content.- * - `content` pins the header and hands `children` a flex box to fill. Right- * when the content virtualizes, since a virtualizer has to own and observe- * its own scroll element.- *- * Full-bleed views that own their layout and header (the model and node- * managers) deliberately do not use this at all.+ * Use scroll=page for whole-page scrolling; content pins the header and lets virtualized children own their scroll+ * element. Full-bleed views provide their own shell.*/const MEASURE_SX: SystemStyleObject = {@@ -38,11 +23,7 @@ const CONTENT_SCROLL_HEADER_SX: SystemStyleObject = { ...MEASURE_SX, pb: 4, pt:export interface PageShellProps {/** The section's visible heading. */title: string;- /**- * Accessible name for the scroll region when it differs from the heading —- * a greeting makes a warm heading but a poor landmark name. Ignored when- * `scroll` is `content`, where the child owns the scroll region.- */+ /** Override the scroll region's accessible name; ignored for scroll=content, where children own the region. */regionLabel?: string;/** One line under the heading; omit when the section speaks for itself. */description?: string;diff --git a/invokeai/frontend/webv2/src/platform/ui/Panel.tsx b/invokeai/frontend/webv2/src/platform/ui/Panel.tsxindex 9f92013a96..af6f259b0f 100644--- a/invokeai/frontend/webv2/src/platform/ui/Panel.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Panel.tsx@@ -4,13 +4,6 @@ import { useMemo } from 'react';export type PanelProps = BoxProps & RecipeVariantProps<typeof panelRecipe>;-/**- * Bordered surface container backed by `panelRecipe` — the one styling- * contract for panels, cards, and wells across the workbench.- *- * - `tone`: `surface` (default) | `raised` | `inset` | `control`- * - `density`: `none` (default) | `sm` | `md` — padding + gap presets- */export const Panel = ({ css, density, tone, ...rest }: PanelProps) => {const recipe = useRecipe({ recipe: panelRecipe });const panelCss = useMemo(() => [recipe({ density, tone }), css], [css, density, recipe, tone]);diff --git a/invokeai/frontend/webv2/src/platform/ui/Picker.tsx b/invokeai/frontend/webv2/src/platform/ui/Picker.tsxindex e9cf205a72..a013489168 100644--- a/invokeai/frontend/webv2/src/platform/ui/Picker.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Picker.tsx@@ -81,8 +81,7 @@ export const Picker = <T,>({[flatOptions, getIsOptionDisabled, getOptionId]);- // The active row must always exist in the current result set — a search that- // filters it away silently hands the highlight to the first remaining row.+ // If filtering removes the active row, highlight the first remaining result.const resolvedActiveId =activeId && selectableIds.includes(activeId)? activeId@@ -111,8 +110,7 @@ export const Picker = <T,>({const handleSearchKeyDown = useCallback((event: React.KeyboardEvent<HTMLInputElement>) => {- // The workbench hotkey runtime listens on the window; typing here is not- // a command sequence.+ // Stop typing events before they reach the window command runtime.event.stopPropagation();if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {@@ -194,11 +192,7 @@ export const Picker = <T,>({))}</ScrollArea.Content></ScrollArea.Viewport>- {/*- Above the sticky group headers. They paint an opaque background at- z-index 1, which would otherwise chop the scrollbar into one segment- per group.- */}+ {/* Keep the scrollbar above opaque sticky headers at z-index 1. */}<ScrollArea.Scrollbar zIndex="2"><ScrollArea.Thumb /></ScrollArea.Scrollbar>@@ -233,9 +227,7 @@ const PickerGroupSection = <T,>({const railColor = group.colorPalette ? `${group.colorPalette}.solid` : 'border.emphasized';const countLabel = group.getCountLabel?.(group.options.length);- // `w`/`minW` are load-bearing: ScrollArea's content wrapper sizes to- // max-content, so without them a long model name widens the whole list and- // every group grows a horizontal scrollbar instead of truncating.+ // Constrain width so max-content sizing cannot turn long names into horizontal overflow.return (<BoxborderInlineStartColor={showHeader ? railColor : undefined}diff --git a/invokeai/frontend/webv2/src/platform/ui/Popover.tsx b/invokeai/frontend/webv2/src/platform/ui/Popover.tsxindex 3d39f40801..261407180a 100644--- a/invokeai/frontend/webv2/src/platform/ui/Popover.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Popover.tsx@@ -9,12 +9,7 @@ type PopoverContentProps = ComponentProps<typeof Popover.Content> & {showArrow?: boolean;};-/**- * Popover.Content with the anchor arrow baked in, closing with the tree that- * opened it. Chrome (surface, stroke, shadow, arrow fill) comes from the- * `popover` slot-recipe override in `theme/recipes.ts`, so consumers stay- * consistent by construction.- */+/** Popover content closes with its owning widget; the theme recipe owns chrome. */export const PopoverContent = ({ children, showArrow = true, ...props }: PopoverContentProps) => {const popover = usePopoverContext();const stale = useRegisterWidgetOverlay(popover.open, popover.setOpen);diff --git a/invokeai/frontend/webv2/src/platform/ui/RenameDialog.tsx b/invokeai/frontend/webv2/src/platform/ui/RenameDialog.tsxindex 0aae84ba19..f36062ae6a 100644--- a/invokeai/frontend/webv2/src/platform/ui/RenameDialog.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/RenameDialog.tsx@@ -4,12 +4,7 @@ import { useCallback, useState, type FormEvent } from 'react';import { Button, CloseButton } from './Button';import { Field } from './Field';-/**- * Controlled single-field rename dialog. `onSubmit` only fires for a- * non-empty name that actually changed; it may be async, in which case the- * submit button shows a pending state and errors keep the dialog open so the- * caller's message (usually a toast) can be acted on.- */+/** Submit only changed, nonempty names; async failures keep the dialog open and callers surface the error. */export const RenameDialog = ({finalFocusEl,initialName,@@ -49,8 +44,7 @@ export const RenameDialog = ({await onSubmit(name);onClose();} catch {- // The caller surfaced the failure (toast/notification); stay open so- // the name is not lost.+ // Keep the entered name after failure; the caller reports the error.} finally {setIsPending(false);}diff --git a/invokeai/frontend/webv2/src/platform/ui/ResizableTextarea.tsx b/invokeai/frontend/webv2/src/platform/ui/ResizableTextarea.tsxindex 2f0f531800..b0a42b4342 100644--- a/invokeai/frontend/webv2/src/platform/ui/ResizableTextarea.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ResizableTextarea.tsx@@ -146,8 +146,7 @@ export const ResizableTextarea = ({<ScrollArea.Viewport asChild role="textbox"><Textarea ref={textareaRef} resize="none" {...textareaProps} /></ScrollArea.Viewport>- {/* zag skips scrollbar re-measurement entirely without a content element;- the textarea is the viewport, so park an empty one for its observer. */}+ {/* Zag needs a content element to remeasure; the textarea itself is the viewport. */}<ScrollArea.Content h="0" minW="0" overflow="hidden" position="absolute" /><ScrollArea.Scrollbar><ScrollArea.Thumb />diff --git a/invokeai/frontend/webv2/src/platform/ui/Row.tsx b/invokeai/frontend/webv2/src/platform/ui/Row.tsxindex a1a3031e71..07653fe19e 100644--- a/invokeai/frontend/webv2/src/platform/ui/Row.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Row.tsx@@ -4,16 +4,7 @@ import { useMemo } from 'react';export type RowProps = BoxProps & RecipeVariantProps<typeof rowRecipe>;-/**- * Interactive list / table row backed by `rowRecipe`: hover and focus fills- * come from the recipe, and the previously ad-hoc `isSelected ? … : …`- * ternaries collapse into the `active` variant.- *- * - `active`: `none` (default) | `muted` (context) | `selected` (co-selected) |- * `emphasized` (the active item) | `brand` (identity) | `accent` (highlight)- *- * Render as a real `<button>` (`as="button"`) when the row is clickable.- */+/** Use as=button for clickable rows; active selects the themed emphasis level. */export const Row = ({ active, css, ...rest }: RowProps) => {const recipe = useRecipe({ recipe: rowRecipe });const rowCss = useMemo(() => [recipe({ active }), css], [active, css, recipe]);diff --git a/invokeai/frontend/webv2/src/platform/ui/Scrollable.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Scrollable.browser.test.tsxindex 4b1ac3051a..2bff1ad9d0 100644--- a/invokeai/frontend/webv2/src/platform/ui/Scrollable.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Scrollable.browser.test.tsx@@ -7,14 +7,7 @@ import { afterEach, describe, expect, it } from 'vitest';import { PopoverContent } from './Popover';import { Scrollable } from './Scrollable';-/**- * zag pins `min-width: fit-content` inline on the scroll-area content box. A- * horizontal strip needs that; a vertical area must not inherit it, because it- * renders no horizontal scrollbar — anything pushed sideways there is simply- * unreachable. The popover test covers the other zag trap: an initial measure- * that lands while the popover mounts at zero size leaves the machine's- * "has overflow" default standing, stranding a phantom thumb.- */+/** Cover Zag's inline-width overflow and phantom thumbs from zero-size popover mounts. */let host: HTMLDivElement | null = null;let root: Root | null = null;@@ -81,8 +74,6 @@ describe('Scrollable', () => {expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth);- // The orientation guard must not over-hide: a bar whose own axis- // overflows stays visible.const scrollbar = document.querySelector<HTMLElement>('[data-scope="scroll-area"][data-part="scrollbar"][data-orientation="horizontal"]')!;@@ -92,10 +83,7 @@ describe('Scrollable', () => {});it('hides the vertical scrollbar when only sideways spill exists', async () => {- // Chakra's stock guard hides a scrollbar only when NEITHER axis- // overflows, so nowrap rows spilling sideways pinned a min-size thumb on- // the vertical bar (dynamic prompts, JSON previews). The theme's- // orientation-scoped guard is what this pins.+ // Stock Chakra checks both axes together; horizontal overflow must not show a vertical thumb.const viewport = await renderScrollable(<div style={{ whiteSpace: 'nowrap' }}>{UNBREAKABLE}@@ -114,8 +102,6 @@ describe('Scrollable', () => {await waitFor(() => getComputedStyle(scrollbar).display === 'none');expect(scrollbar).not.toBeNull();- // The spill is real and zag records it; only the orientation guard keeps- // the vertical bar out of it.expect(scrollbar.hasAttribute('data-overflow-x')).toBe(true);expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth);expect(getComputedStyle(scrollbar).display).toBe('none');diff --git a/invokeai/frontend/webv2/src/platform/ui/Scrollable.tsx b/invokeai/frontend/webv2/src/platform/ui/Scrollable.tsxindex 3d184180d2..6f0fff2f5e 100644--- a/invokeai/frontend/webv2/src/platform/ui/Scrollable.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Scrollable.tsx@@ -11,22 +11,12 @@ type ScrollAreaContentProps = ComponentProps<typeof ScrollArea.Content>;type ScrollAreaViewportProps = ComponentProps<typeof ScrollArea.Viewport>;/**- * zag pins `min-width: fit-content` *inline* on every scroll-area content box,- * so the box grows to its content's min-content width. A horizontal strip wants- * exactly that. In a vertical area it is a trap: one unbreakable string (a long- * name, an unwrapped identifier) widens the content box past the viewport, the- * area scrolls sideways — and since a vertical area renders no horizontal- * scrollbar, the overflow is simply unreachable. Vertical areas override it back- * to zero, so their content stretches to the viewport and truncation inside is- * what gives. Only an inline style can beat an inline style.+ * Override Zag's inline min-width in vertical areas; long unbroken content would otherwise create unreachable+ * horizontal overflow.*/const VERTICAL_CONTENT_STYLE = { minWidth: 0 } as const;-/**- * The workbench's standard scroll container: ScrollArea with hover-revealed- * scrollbars and the content wrapper zag needs for correct thumb sizing.- * Layout props (h, maxH, flex, ...) go to the root.- */+/** Layout props target the root; the content wrapper is required for Zag's thumb sizing. */export const Scrollable = ({children,contentProps,@@ -45,27 +35,19 @@ export const Scrollable = ({orientation?: 'horizontal' | 'vertical';/** Extra props for the scrolling viewport itself, e.g. scroll/focus handlers. */viewportProps?: ScrollAreaViewportProps;- /**- * The scrolling element itself — what a virtualizer needs to observe. A- * callback ref is attached alongside the internal one, for mount-time work- * such as restoring a remembered offset.- */+ /** Ref to the scrolling viewport; callback refs support mount-time offset restoration. */viewportRef?: Ref<HTMLDivElement | null>;}) => {const fallbackViewportRef = useRef<HTMLDivElement | null>(null);- // One object ref, shared with the caller when it hands one in, so nothing- // has to merge or reassign refs during render.const resolvedViewportRef = viewportRef && typeof viewportRef !== 'function' ? viewportRef : fallbackViewportRef;const viewportCallback = typeof viewportRef === 'function' ? viewportRef : undefined;- // A callback ref is composed with the object ref the hooks observe; the- // composition only runs when React attaches the element, never in render.+ // Compose callback refs at attachment time, not during render.const attachViewport = useCallback((element: HTMLDivElement | null) => mergeRefs(fallbackViewportRef, viewportCallback)(element),[viewportCallback]);- // The shell keeps widgets mounted across layout switches, and a scroll- // container that stops being rendered loses its offset outright.+ // Hidden mounted widgets can lose scroll offsets; restore them when shown.usePreservedScrollOffset(resolvedViewportRef);useScrollAreaPhantomHeal(resolvedViewportRef);diff --git a/invokeai/frontend/webv2/src/platform/ui/ScrubberField.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/ScrubberField.browser.test.tsxindex 27af0f45f8..5a3a4431ff 100644--- a/invokeai/frontend/webv2/src/platform/ui/ScrubberField.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ScrubberField.browser.test.tsx@@ -158,8 +158,7 @@ describe('ScrubberField', () => {});it('ignores stops beyond the track while Alt is held', async () => {- // A default past the track (FLUX Fill's guidance of 30 on a 0..10 track) is not a stop: an Alt- // gesture would otherwise snap straight off the track's end.+ // Exclude out-of-range defaults from stops so Alt-drag cannot jump off-track.const { frame, onChange } = await mount({ defaultValue: 30, marks: [50], max: 10, value: 5 });await pointer(frame, 'pointerdown', { altKey: true, clientX: trackX(frame, 0.5) });diff --git a/invokeai/frontend/webv2/src/platform/ui/ScrubberField.tsx b/invokeai/frontend/webv2/src/platform/ui/ScrubberField.tsxindex 36284d41a9..42b2a04d36 100644--- a/invokeai/frontend/webv2/src/platform/ui/ScrubberField.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ScrubberField.tsx@@ -190,14 +190,8 @@ const isSameExtents = (a: TextExtents | null, b: TextExtents): boolean =>a !== null && a.labelEnd === b.labelEnd && a.valueStart === b.valueStart && a.width === b.width;/**- * One-row numeric parameter: label left, value right, the whole frame is the- * track. Dragging anywhere but the value scrubs relative to the current value- * — a press alone never moves it (Shift: fine, Alt: stops only); the value is- * a button that swaps in a text editor; arrows step- * (Shift/PageUp/PageDown: ×10, Home/End: bounds); double-click or- * Backspace/Delete restores `defaultValue`. Owns its label, hint, and help or- * error line, so it replaces a `Field` + slider pairing outright. Debouncing- * stays with the caller.+ * Relative drag; Shift fine, Alt stops. Click the value to edit; arrows step, Shift/Page keys ×10, Home/End+ * bounds. Double-click or Backspace/Delete resets. Caller owns debouncing.*/export const ScrubberField = ({defaultValue,@@ -231,8 +225,7 @@ export const ScrubberField = ({useMountEffect(() => () => pointerSessionRef.current?.abort());- // Stops hide under the text, so the label's and value's extents are tracked- // as they resize (value digits, localized labels, the editor swapping in).+ // Track label/value bounds so stops stay hidden beneath changing text.const measureText = useCallback((root: HTMLElement) => {const next = readTextExtents(root);@@ -315,8 +308,7 @@ export const ScrubberField = ({setEdit({ draft, selectAll });}, []);- // Enter and Escape hand focus back to the slider; a blur means focus already- // went where the user sent it, and pulling it back would break Tab and clicks.+ // Restore slider focus on Enter/Escape, never blur: Tab and clicks already chose a destination.const finishEditing = useCallback((commit: boolean, restoreFocus: boolean) => {const session = editSessionRef.current;@@ -362,17 +354,13 @@ export const ScrubberField = ({const session = new AbortController();let latest = value;let isPendingTouch = event.pointerType === 'touch';- // A gesture is relative to the value it started from, wherever the press- // lands (like a native iOS slider): re-anchoring on each ratio change means- // neither pressing nor releasing Shift mid-drag jumps.+ // Re-anchor on sensitivity changes so toggling Shift mid-drag does not jump.let anchor = { clientX: event.clientX, ratio: event.shiftKey ? FINE_DRAG_RATIO : 1, value };pointerSessionRef.current = session;setIsDragging(true);- // Keeps hover states elsewhere quiet and the resize cursor stable while- // the pointer roams. Throws for an already-released pointer; the window- // listeners still carry the gesture.+ // Pointer capture preserves drag cursor/hover isolation; window listeners cover capture failure.try {root.setPointerCapture(event.pointerId);} catch {@@ -391,8 +379,7 @@ export const ScrubberField = ({return pointer.altKey && markValues?.length ? nearestMark(raw, markValues) : snapToStep(raw);};- // The gesture belongs to the pointer that started it; a second finger or- // pen contact neither moves the value nor ends the drag.+ // Only the initiating pointer may move or end this gesture.const apply = (pointer: PointerSample) => {if (pointer.pointerId !== event.pointerId) {return;@@ -439,9 +426,7 @@ export const ScrubberField = ({[defaultValue, disabled, emit]);- // Every key the slider acts on is consumed outright: the window-level hotkey- // runtime only exempts editable elements, so a digit that opens the editor- // must not also fire the shortcut bound to that digit.+ // Consume handled keys so the window hotkey runtime cannot also treat editor-opening digits as commands.const handleSliderKeyDown = useCallback((event: KeyboardEvent<HTMLDivElement>) => {if (disabled || event.ctrlKey || event.metaKey) {@@ -533,8 +518,7 @@ export const ScrubberField = ({},[observeText, selectAll]);- // No `relatedTarget` means nothing else took focus (the window deactivated,- // or a click landed on nothing focusable), so the slider keeps the tab stop.+ // With no relatedTarget, retain the slider tab stop.const handleInputBlur = useCallback((event: FocusEvent<HTMLInputElement>) => finishEditing(true, event.relatedTarget === null),[finishEditing]diff --git a/invokeai/frontend/webv2/src/platform/ui/SeedInput.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/SeedInput.browser.test.tsxindex d02dc0dbf7..d64db034b2 100644--- a/invokeai/frontend/webv2/src/platform/ui/SeedInput.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/SeedInput.browser.test.tsx@@ -114,8 +114,7 @@ describe('SeedInput', () => {});it('shows the rolled seed under a host-supplied id too', async () => {- // A host id must reach the element through zag's id map; overriding the attribute- // would leave the DOM value stale after an external change.+ // Host IDs must use Zag's ID map or external changes leave the DOM value stale.const onCommit = await renderHost('fixed', 42, 'node-1-seed');expect(seedInput()?.id).toBe('node-1-seed');@@ -146,8 +145,7 @@ describe('SeedInput', () => {const onCommit = await renderHost('fixed', 42);const input = seedInput() as HTMLInputElement;- // A pasted fraction arrives whole; a typed one is rounded at every keystroke, so the- // decimal point never survives either way.+ // Paste fractions as a whole; per-keystroke rounding removes a typed decimal point.await act(async () => {await userEvent.fill(input, '1.5');await new Promise<void>((resolve) => {diff --git a/invokeai/frontend/webv2/src/platform/ui/SeedInput.tsx b/invokeai/frontend/webv2/src/platform/ui/SeedInput.tsxindex 41cd7bcaed..26881bd345 100644--- a/invokeai/frontend/webv2/src/platform/ui/SeedInput.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/SeedInput.tsx@@ -32,15 +32,9 @@ export interface SeedModeMenuProps {contentClassName?: string;}-/**- * How the seed moves from one submission to the next. A menu rather than a- * toggle because the choice has four answers, and each needs a line of- * explanation the first time it is read.- */export const SeedModeMenu = ({ contentClassName, description, onChange, value }: SeedModeMenuProps) => {const { t } = useTranslation();- // Shared ids let the tooltip ride the menu trigger without wrapping it- // (wrapping `Menu.Trigger` swallows the anchor ref — see RoutingControl).+ // Share trigger IDs; wrapping Menu.Trigger loses its anchor ref.const triggerId = useId();const triggerIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);const label = t('common.seedMode.label');@@ -139,12 +133,7 @@ export interface SeedInputProps {onCommit: (patch: SeedInputPatch) => void;}-/**- * The seed control every seeded host shares: the number input with the- * one-shot new-seed action inside it, the mode menu beside it, and the- * stepping preview underneath. Random quiets the input and the dice but keeps- * the value on show, so it is there again the moment the mode changes back.- */+/** Random mode disables editing without discarding the displayed seed. */export const SeedInput = ({ariaLabel,className,@@ -160,16 +149,13 @@ export const SeedInput = ({const { t } = useTranslation();const previewId = useId();const isRandom = seedMode === 'random';- // Inside a Field the input stays described by the field's helper and error text, and the preview- // joins that list. Ark 5.39 moved the error id from `ariaDescribedby` to its input props' error message.+ // Preserve Field helper/error descriptions alongside the seed preview; error IDs come from Ark input props.const field = useFieldContext();const describedBy =[field?.ariaDescribedby, field?.getInputProps()['aria-errormessage'], plan ? previewId : undefined].filter(Boolean).join(' ') || undefined;- // The host's id goes through zag's id map, never onto the element: zag syncs the DOM value- // by looking the input up under its own id, so an overriding `id` leaves an external change- // (the dice, a recall, an advance) invisible until the next keystroke.+ // Pass host IDs through Zag's ID map; overriding the DOM ID breaks external value synchronization.const inputIds = useMemo(() => (id ? { input: id } : undefined), [id]);const stepperTranslations = useMemo(() => ({ decrementLabel: t('common.decreaseValue'), incrementLabel: t('common.increaseValue') }),@@ -205,8 +191,7 @@ export const SeedInput = ({onDoubleClick={selectInputText}/></NumberInput.Root>- {/* The tooltip is the visible hint; the accessible name stays on the button because a- tooltip only describes its trigger while open. */}+ {/* Keep the button's accessible name independent of the tooltip's open state. */}<Tooltip content={t('common.newSeed')}><IconButtonaria-label={t('common.newSeed')}diff --git a/invokeai/frontend/webv2/src/platform/ui/SegmentTabs.tsx b/invokeai/frontend/webv2/src/platform/ui/SegmentTabs.tsxindex c8bfd999aa..a3de652959 100644--- a/invokeai/frontend/webv2/src/platform/ui/SegmentTabs.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/SegmentTabs.tsx@@ -3,9 +3,6 @@ import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react';import { Box, chakra, HStack, Text } from '@chakra-ui/react';import { Fragment, useCallback } from 'react';-// Accent-tinted translucent fills, so the strip reads the same on the layer-// panels and on popover/dialog surfaces that share the solid fills' color,-// and sits in the menus' cool-tinted interaction family.const TAB_HOVER_PROPS = { bg: 'gray.hoverTint/8', color: 'fg' };const TAB_SHOWN_BG = 'gray.hoverTint/15';@@ -39,15 +36,8 @@ const focusSibling = (event: ReactKeyboardEvent<HTMLElement>) => {};/**- * The workbench's segment-style tab strip: a row of pill tabs over a panel the- * caller owns. Ids follow one convention — tab `${idBase}-tab-${id}`, panel- * `${idBase}-panel` — so the caller's `role="tabpanel"` region wires itself- * with `id={segmentTabsPanelId(idBase)}` and- * `aria-labelledby={segmentTabsTabId(idBase, activeId)}`. Clicking the active- * tab calls `onSelect` again, which lets a collapsible block treat it as a- * toggle; `showActivePanel={false}` keeps the active tab selected and focusable- * while dropping the shown look (a collapsed block). `trailing` renders after- * the tablist, outside it, for chevrons and action buttons.+ * Wire caller-owned panels with segmentTabsPanelId/segmentTabsTabId. Active-tab clicks call onSelect again;+ * showActivePanel=false retains selection. trailing sits outside the tablist.*/export const SegmentTabs = <T extends string>({activeId,diff --git a/invokeai/frontend/webv2/src/platform/ui/SegmentedControl.tsx b/invokeai/frontend/webv2/src/platform/ui/SegmentedControl.tsxindex 5815a05978..69decfda0c 100644--- a/invokeai/frontend/webv2/src/platform/ui/SegmentedControl.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/SegmentedControl.tsx@@ -3,8 +3,7 @@ import type { ReactNode } from 'react';import { SegmentGroup } from '@chakra-ui/react';import { useCallback } from 'react';-// Axe measures the checked label against the item's own background, not the-// moving indicator sibling painted behind it, so the item carries the fill too.+// Paint the checked item's background too; axe cannot infer the indicator sibling behind it.const CHECKED_ITEM_STYLES = { bg: 'accent.solid', color: 'accent.contrast' } as const;export interface SegmentedControlOption {diff --git a/invokeai/frontend/webv2/src/platform/ui/Select.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Select.browser.test.tsxindex dd345f6054..4ba67da02f 100644--- a/invokeai/frontend/webv2/src/platform/ui/Select.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Select.browser.test.tsx@@ -39,10 +39,7 @@ describe('Select', () => {});it('shows the selected label by default and lets a caller name the value instead', async () => {- // Callers that override the trigger text rely on omitting the prop falling back to the- // selection rather than rendering an empty trigger -- a Select whose value is still meaningful- // but whose display is not (a disabled control whose size comes from elsewhere, a preset list- // with no exact match) states something the selection alone cannot.+ // An omitted trigger-text override must fall back to the selection, not an empty display.await act(() => {root.render(<ChakraProvider value={system}>diff --git a/invokeai/frontend/webv2/src/platform/ui/Select.tsx b/invokeai/frontend/webv2/src/platform/ui/Select.tsxindex 7fbea6016c..4e77fc6261 100644--- a/invokeai/frontend/webv2/src/platform/ui/Select.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Select.tsx@@ -50,16 +50,11 @@ const DEFAULT_ITEMS_MAX_H = 'min(20rem, calc(var(--available-height) - 0.5rem))'export interface SelectProps<T extends CollectionItem> extends Omit<SelectRootProps<T>, 'children'> {contentProps?: SelectContentProps;/**- * Caps the open menu's height; the items scroll inside a Scrollable. The- * machine's own content-element scrolling is replaced by a `scrollToIndexFn`- * targeting the Scrollable viewport, so keyboard highlight, typeahead, and- * the open-reveal keep working. `null` restores the machine's plain overflow.+ * Caps menu height and routes keyboard scrolling through Scrollable; null restores the machine's native+ * overflow.*/itemsMaxH?: string | null;- /**- * Renders labelled item groups: consecutive items with the same group key- * share one header. Items must already be ordered by group.- */+ /** Only consecutive equal keys form a group; callers must order items by group. */groupBy?: (item: T) => string;/** The visible header for a group key; defaults to the key itself. */renderGroupLabel?: (group: string) => ReactNode;@@ -93,9 +88,7 @@ export const Select = <T extends CollectionItem>({valueTextProps,...rootProps}: SelectProps<T>) => {- // Inside a Field the machine adopts the field's label id, so rendering our- // own Label part there would duplicate that id; the field's visible label- // already names the trigger.+ // Inside Field, reuse its label ID; rendering another Label would duplicate it.const field = useFieldContext();const itemsRef = useRef<HTMLDivElement>(null);const scrollToIndexFn = useCallback(({ index }: { index: number }) => {@@ -103,9 +96,7 @@ export const Select = <T extends CollectionItem>({options?.[index]?.scrollIntoView({ block: 'nearest' });}, []);return (- // The items (and their Scrollable's scroll-area machine) mount only while- // open: a widget carries many selects at rest, and the machine's observers- // are per instance.+ // Mount items only while open to avoid per-select scroll observers at rest.<ChakraSelect.Rootcollection={collection}lazyMount@@ -115,9 +106,7 @@ export const Select = <T extends CollectionItem>({// An empty list is nothing to choose from: the trigger disables instead of opening a blank menu.disabled={rootProps.disabled || collection.items.length === 0}>- {/* A real (visually hidden) Label part: the machine's trigger always points- its aria-labelledby at this id, so a bare aria-label must materialize it —- left on the Root it lands on a div, which ARIA prohibits. */}+ {/* Materialize the trigger's aria-labelledby target; aria-label on Root would name a generic div instead. */}{ariaLabel && !field ? <ChakraSelect.Label srOnly>{ariaLabel}</ChakraSelect.Label> : null}<ChakraSelect.HiddenSelect /><ChakraSelect.Control>diff --git a/invokeai/frontend/webv2/src/platform/ui/Slider.tsx b/invokeai/frontend/webv2/src/platform/ui/Slider.tsxindex 97de382b88..b7636f7456 100644--- a/invokeai/frontend/webv2/src/platform/ui/Slider.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Slider.tsx@@ -14,9 +14,7 @@ export interface SliderProps extends Omit<ChakraSlider.RootProps, 'children'> {withThumbTooltip?: boolean;}-// Marks stay mounted so the slider keeps a stable height, but only fade in-// while the slider is hovered or dragged. This is driven by the primitives' own-// DOM state: the root carries `data-dragging` for the whole gesture.+// Keep marks mounted to preserve height; show them on hover or data-dragging.const INTERACTION_REVEAL_CSS = {'& [data-part="marker-group"]': {opacity: 0,@@ -59,14 +57,7 @@ const SliderThumb = ({ index, isTooltipOpen, label }: { index: number; isTooltip</ChakraTooltip.Root>);-/**- * Workbench slider. Wraps the Chakra slider primitives with the conveniences- * the legacy (Chakra v2) slider had: a formatted value tooltip on each thumb- * that shows while the slider is hovered and stays up through drags, and track- * marks that reveal on hover so dense forms stay quiet until the slider is- * being used. Renders one thumb per entry in `value`/`defaultValue`, so it- * covers single and range sliders.- */+/** One thumb per value, with hover/drag tooltips and hover-revealed marks; supports single and range values. */export const Slider = ({formatValue = formatValueDefault,marks,diff --git a/invokeai/frontend/webv2/src/platform/ui/SliderNumberField.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/SliderNumberField.browser.test.tsxindex 46b3dcf0d3..47e0276fea 100644--- a/invokeai/frontend/webv2/src/platform/ui/SliderNumberField.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/SliderNumberField.browser.test.tsx@@ -60,9 +60,7 @@ describe('SliderNumberField', () => {);const input = hosted.querySelector<HTMLInputElement>('input[aria-label="Steps"]');- // The thumb is also the tooltip trigger (`asChild`), so the tooltip's own- // `data-part`/`data-scope` win on the shared node — `role="slider"` is the- // stable selector, not `[data-part="thumb"]`.+ // Select by role=slider; the shared tooltip trigger overwrites thumb data attributes.const thumb = hosted.querySelector('[role="slider"]');expect(input?.value).toBe('150');@@ -70,10 +68,7 @@ describe('SliderNumberField', () => {});it('drops a mark the track cannot place instead of painting it past the end', async () => {- // Marks come from callers that also set a looser `numberInputMax` (a model default of 30 on a- // guidance track that stops at 10). The thumb clamps, but the marker was forwarded unclamped and- // painted off the track. Dropped rather than clamped: a marker sitting on the bound would label- // 10 as the default it is not. The number input still carries the real value.+ // Drop out-of-range default marks without changing the input value or falsely marking a bound as default.const hosted = await mount(<SliderNumberFieldariaLabel="Guidance"diff --git a/invokeai/frontend/webv2/src/platform/ui/SliderNumberField.tsx b/invokeai/frontend/webv2/src/platform/ui/SliderNumberField.tsxindex 18d4242ae6..23da6d2209 100644--- a/invokeai/frontend/webv2/src/platform/ui/SliderNumberField.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/SliderNumberField.tsx@@ -10,13 +10,7 @@ type SliderNumberFieldProps = {min: number;max: number;step: number;- /**- * Reference points on the track. A mark outside `[min, max]` is dropped, not clamped: with- * `numberInputMin`/`Max` looser than the track, callers legitimately mark a value that has no- * position on it (a model default of 30 on a track that stops at 10), and a marker pinned to the- * bound would claim a default at a value that is not the default. `Slider` itself still paints- * whatever it is given.- */+ /** Drop off-track marks instead of clamping: clamping would falsely label a bound as the default. */marks?: SliderMark[];/** Looser clamps for typed values (slider bounds apply otherwise). */numberInputMin?: number;@@ -28,12 +22,8 @@ type SliderNumberFieldProps = {};/**- * Slider + number input combo for numeric parameters. The slider covers the- * practical range; the input accepts values beyond it when the numberInput- * bounds are looser. Debouncing stays with the caller. Label, hint, and- * validation messaging are the caller's job (compose with `Field`) — this- * component only owns the slider/input pairing. Parameter rows in the- * Generate/Upscale widgets use `ScrubberField` instead.+ * Input bounds may exceed slider bounds. Callers own Field messaging and debouncing; parameter rows use+ * ScrubberField.*/export const SliderNumberField = memo(function SliderNumberField({ariaLabel,@@ -50,9 +40,7 @@ export const SliderNumberField = memo(function SliderNumberField({value,}: SliderNumberFieldProps) {const sliderAriaLabel = useMemo(() => [ariaLabel], [ariaLabel]);- // Typed values may exceed the slider's own range (the number input has its own,- // looser bounds via numberInputMin/Max); the thumb clamps to stay on the track- // instead of rendering off it, while the input keeps showing the typed value.+ // Clamp only the thumb; preserve typed values within the input's wider bounds.const sliderValue = useMemo(() => [Math.min(max, Math.max(min, value))], [max, min, value]);const placeableMarks = marks?.filter((mark) => {const markValue = typeof mark === 'number' ? mark : mark.value;diff --git a/invokeai/frontend/webv2/src/platform/ui/StatusWidgetChip.tsx b/invokeai/frontend/webv2/src/platform/ui/StatusWidgetChip.tsxindex c53e01edaa..529736f6e4 100644--- a/invokeai/frontend/webv2/src/platform/ui/StatusWidgetChip.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/StatusWidgetChip.tsx@@ -23,11 +23,7 @@ const PROGRESS_FILL_SX: SystemStyleObject = {transition: 'width var(--wb-motion-duration-fast) linear',};-/**- * Indeterminate: a band sweeping the track, so "working, no percent yet"- * (model load, graph prep) reads as activity instead of a stuck bar. Under- * reduce-motion the band does not run at all; the quiet fill carries the state.- */+/** Use a static fill under reduced motion; otherwise sweep the indeterminate band. */const PROGRESS_SWEEP_SX: SystemStyleObject = {':root[data-reduce-motion="true"] &': { animationName: 'none' },animationDuration: '1.4s',diff --git a/invokeai/frontend/webv2/src/platform/ui/Tooltip.tsx b/invokeai/frontend/webv2/src/platform/ui/Tooltip.tsxindex 7e34cc816c..58e58c0d1a 100644--- a/invokeai/frontend/webv2/src/platform/ui/Tooltip.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Tooltip.tsx@@ -78,28 +78,13 @@ export interface TooltipProps extends ChakraTooltip.RootProps {content: ReactNode;contentRef?: Ref<HTMLDivElement>;contentProps?: ChakraTooltip.ContentProps;- /**- * Which trigger edge the tooltip sits on, centered against it — `top`/- * `bottom` center horizontally, `left`/`right` center vertically; `-start`/- * `-end` suffixes align to an edge instead. Shorthand for- * `positioning.placement` (an explicit `positioning.placement` wins).- */+ /** Shorthand for positioning.placement; an explicit positioning.placement wins. */placement?: TooltipPlacement;ref?: Ref<HTMLButtonElement>;triggerProps?: TooltipTriggerProps;}-/**- * Workbench tooltip. Chrome comes from the `tooltip` slot-recipe override in- * `theme/recipes.ts`, so this wrapper only provides the trigger/portal- * structure and the `content` convenience API.- */-/**- * One trigger id for a menu or popover whose trigger a `Tooltip` wraps. Both- * machines render onto the same element and each wants to own its id; without- * sharing, the menu has no anchor and opens at the viewport origin. Pass the- * result as `ids` to the Menu/Popover root and to the Tooltip.- */+/** Pass the same ids to Menu/Popover and Tooltip; competing trigger IDs leave the popup without an anchor. */export const useTooltipTriggerIds = (): { trigger: string } => {const trigger = useId();diff --git a/invokeai/frontend/webv2/src/platform/ui/VendoredIcon.tsx b/invokeai/frontend/webv2/src/platform/ui/VendoredIcon.tsxindex 3586cf2bfc..bfd7c10303 100644--- a/invokeai/frontend/webv2/src/platform/ui/VendoredIcon.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/VendoredIcon.tsx@@ -1,18 +1,8 @@import type { SVGProps } from 'react';/**- * Vendored icons: marks from Simple Icons (https://simpleicons.org, CC0-1.0)- * and the odd glyph from another set, each recorded with its `origin`.- *- * Everything else is a Lucide icon; these are the exceptions, and there are a- * handful of them. Both `react-icons` and the `simple-icons` package expose- * their icons through a single ~5 MB barrel module with no per-icon entry- * point, which the dev server transforms in full to hand back a few paths —- * so the paths live here instead, as the data they are.- *- * To add or refresh one: copy the path data and viewBox from the source,- * keeping the slug and title as the upstream name so a later refresh is a- * straight lookup.+ * Vendored paths avoid large icon barrels. Simple Icons paths are CC0-1.0 (https://simpleicons.org); other glyph+ * sources are recorded in origin. Preserve upstream slug/title and viewBox for updates.*/interface VendoredIconSource {@@ -31,9 +21,7 @@ interface VendoredIconSource {const createVendoredIcon = ({ paths, title, viewBox = '0 0 24 24' }: VendoredIconSource) => {const VendoredIcon = ({ titleAccess, ...props }: SVGProps<SVGSVGElement> & { titleAccess?: boolean }) => (<svg- // Decorative by default: every current consumer pairs the mark with- // visible text, and a titled icon there is announced twice. Pass- // `titleAccess` when the icon stands alone.+ // Decorative by default to avoid duplicate announcements; pass titleAccess for standalone icons.aria-hidden={titleAccess ? undefined : true}fill="currentColor"height="1em"diff --git a/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts b/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.tsindex 810fceb4fb..0921720475 100644--- a/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts+++ b/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts@@ -12,15 +12,7 @@ const FORMAT_STORAGE_KEY = 'invokeai:v7:webv2:color-format';const MODE_STORAGE_KEY = 'invokeai:v7:webv2:color-picker-mode';const MAX_RECENTS = 12;-/**- * The workbench palette: neutrals plus the regional-guidance mask hues, so a- * brush color and a mask fill picked from defaults read as one system.- *- * These values intentionally duplicate `REGIONAL_GUIDANCE_FILL_COLORS` in the- * canvas engine. `platform/` may not import `workbench/` (`platform-independence`)- * and the engine may not import back out (`canvas-engine-independence`), so a- * shared constant would have to live in a third module owned by neither.- */+/** Keep defaults aligned with REGIONAL_GUIDANCE_FILL_COLORS; owner boundaries forbid importing the canvas constant. */export const DEFAULT_COLOR_SWATCHES: readonly string[] = ['#000000','#ffffff',@@ -39,11 +31,7 @@ const isColorPickerFormat = (value: unknown): value is ColorPickerFormat =>const isColorPickerMode = (value: unknown): value is ColorPickerMode => value === 'wheel' || value === 'box';-/**- * Reads a persisted string. Touching `localStorage` at all can throw- * (SecurityError when storage is disabled), not just `getItem` — both stay- * inside the guard.- */+/** Guard access to localStorage itself; the property getter can throw before getItem. */const readStored = (key: string): string | null => {if (typeof window === 'undefined') {return null;diff --git a/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.ts b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.tsindex efe392d85e..da7de274e4 100644--- a/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.ts+++ b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.ts@@ -9,22 +9,16 @@ describe('shouldSyncExternalColor', () => {});it('does not sync when the external value changed to exactly what we last emitted (our own round trip)', () => {- // This is the grey-hue-loss scenario: the user drags the hue slider at- // S=0, we emit "#808080", the consumer stores it and passes it back as- // the new `value` prop -- that must not force a re-parse that would- // collapse the hue we're holding onto internally.+ // Echoing grey hex must not discard the picker's hidden hue.expect(shouldSyncExternalColor('#808080', '#7f7f7f', '#808080', true)).toBe(false);});it('syncs an external change back to the last-emitted value once its echo was consumed', () => {- // An X swap and swap back lands on the color we last emitted long after- // the echo settled; with no emit outstanding this is a genuine change.+ // After the echo settles, returning to the last emitted value is an independent change.expect(shouldSyncExternalColor('#808080', '#7f7f7f', '#808080', false)).toBe(true);});it('syncs when the external value changed to something other than what we last emitted', () => {- // A genuine external change (e.g. a programmatic reset, or a different- // control writing to the same underlying value) should still win.expect(shouldSyncExternalColor('#ff0000', '#808080', '#808080', true)).toBe(true);});@@ -49,8 +43,6 @@ describe('shouldSyncExternalColor', () => {});it('syncs when only the alpha differs', () => {- // Under `withAlpha`, a consumer changing just the opacity is a real- // external change even though the RGB triplet is untouched.expect(shouldSyncExternalColor('#ff000080', '#ff0000ff', '#ff0000ff', true)).toBe(true);});@@ -59,8 +51,7 @@ describe('shouldSyncExternalColor', () => {});it('passes non-hex values through without treating them as equal', () => {- // Fallback-verbatim normalization means unparseable values still compare- // as themselves rather than collapsing to a shared sentinel.+ // Unparseable colors compare verbatim, not through a shared sentinel.expect(shouldSyncExternalColor('transparent', 'currentColor', 'currentColor', true)).toBe(true);expect(shouldSyncExternalColor('transparent', 'currentColor', 'transparent', true)).toBe(false);});diff --git a/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.ts b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.tsindex c3932e9457..934c7786a7 100644--- a/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.ts+++ b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.ts@@ -1,28 +1,8 @@import { normalizeHex } from './color';/**- * True when `externalValue` (the latest `value` prop given to `ColorPicker`)- * should be re-parsed into the picker's internal `Color`, versus kept as-is.- *- * We only want to re-sync from the external string when it reflects a change- * the consumer made independently of the picker (e.g. a programmatic reset) —- * not the round trip of the value the picker *just emitted itself* via- * `onValueChange`. That round trip loses hue information for any grey/black/- * white color (saturation or value = 0, where hex/RGB is hue-agnostic), so- * re-parsing it on every render would snap the hue thumb back to whatever- * `parseColor` yields for an indeterminate hue — the picker would only ever- * be able to *emit* a new hue at S=0, never actually keep it.- *- * The round trip is only swallowed while one is actually outstanding- * (`isAwaitingEcho`: armed by an emit, consumed by the next external change).- * Without that, an independent change that lands back on the last-emitted- * value — an X foreground/background swap and back is the everyday case —- * would be misread as our own echo and leave the swatch stale.- *- * Values are compared after normalization, so a consumer that stores or echoes- * back a differently-cased or shorthand form of the same color (`#FF0000` for- * `#ff0000`, `#f00` for `#ff0000`, `#ff0000ff` for `#ff0000`) does not count as- * an independent change and does not clobber the internal hue.+ * Ignore only an outstanding normalized echo, preserving hue lost in hex for greys. Independent changes—including+ * a later return to the last emitted color—must resync.*/export const shouldSyncExternalColor = (externalValue: string,diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsxindex 3cd6d715ff..fbe37a2638 100644--- a/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsx@@ -36,17 +36,7 @@ let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-/**- * Returns the pointer to the viewport origin — where the harness below states- * it starts.- *- * That only holds for the first test. Once one has hovered the trigger the- * cursor stays on it, so the next render mounts a fresh trigger underneath the- * pointer and the card opens before the test asks for it. That surfaced as a- * strict-mode violation, with `CLIP skip` matching both the trigger and the- * already-open card's own heading and paragraph. The trigger is inset by- * 120px, so the origin is reliably clear of it.- */+/** Reset the pointer before each test so a newly mounted trigger cannot open under the previous test's cursor. */const parkPointer = async (): Promise<void> => {const parking = document.createElement('div');@@ -85,11 +75,7 @@ const render = async (adapter: FeatureHintsAdapter) => {<ChakraProvider value={system}><I18nextProvider i18n={i18n}><FeatureHintsProvider adapter={adapter}>- {/*- Inset and shrink-wrapped on purpose: the mouse starts at the- viewport origin, so a full-width trigger at (0,0) would already- contain the pointer and `pointerenter` would never fire.- */}+ {/* Inset the trigger from the initial pointer position so entering it emits pointerenter. */}<FeatureHint hint="clipSkip"><Text display="inline-block" m="120px">CLIP skip@@ -108,16 +94,6 @@ const render = async (adapter: FeatureHintsAdapter) => {const cardText = (): string =>document.querySelector('[data-scope="hover-card"][data-part="content"]')?.textContent ?? '';-/**- * Waits for the hover card to actually open, rather than sleeping past its- * open delay and hoping.- *- * The fixed 900ms wait this replaces was comfortably longer than the delay on- * an idle machine and not always long enough on a loaded CI runner, where the- * card had not opened yet and every assertion below read an empty string.- * Polling takes as long as the machine needs and fails loudly if the card- * never appears.- */const waitForCard = async (timeoutMs = 5000): Promise<void> => {const deadline = Date.now() + timeoutMs;diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.tsx b/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.tsxindex 108b1fa773..53f659a7cf 100644--- a/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.tsx@@ -87,12 +87,8 @@ const ExclusionProvider = ({ children }: { children: ReactNode }) => {};/**- * A region inside a hint's trigger that the pointer can rest on without- * summoning the hint — controls that carry their own tooltips. Entering the- * region counts as leaving the trigger and leaving it as re-entering, so the- * card closes over the region and reopens over the rest of the trigger. React- * dispatches enter events outermost first, so a pointer landing straight on the- * region never opens the card. Keyboard focus on the trigger is unaffected.+ * Suppress pointer hints over nested tooltip controls by treating entry/exit as trigger leave/enter; keyboard+ * focus is unaffected.*/export const FeatureHintExclusion = ({ children }: { children: ReactElement<HTMLAttributes<HTMLElement>> }) => {const handlers = useContext(ExclusionContext);@@ -106,16 +102,8 @@ export interface FeatureHintProps {}/**- * Attaches an informational hint card to a control, opened by hovering the- * child. Copy lives in the `hints.*` i18n namespace; {@link getFeatureHint}- * supplies the optional support link.- *- * The child is the trigger via `asChild`, and zag builds trigger props with- * `normalize.element` rather than `normalize.button` — so wrapping a field- * label adds pointer/focus handlers and `data-*` attributes but no `tabindex`- * and no role. Labels stay out of the tab order and keep click-to-focus.- *- * When hints are turned off the child renders untouched, with no popper mounted.+ * Attach to the child without button roles/tabindex so labels retain semantics; disabled hints return the child+ * untouched.*/export const FeatureHint = ({ children, hint }: FeatureHintProps) => {const { enabled, onDisable } = useFeatureHints();diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.test.ts b/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.test.tsindex 78b06ecfc9..c78c2b79ea 100644--- a/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.test.ts+++ b/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.test.ts@@ -2,16 +2,7 @@ import { describe, expect, it } from 'vitest';import { FEATURE_HINTS } from './hintRegistry';-/**- * Keeps the registry and the `hints.*` catalog in step in BOTH directions. The- * component builds its keys by template literal, so the generic- * `translationKeys.test.ts` scanner cannot see them — a heading that never got- * written would otherwise surface to users as the literal string- * `hints.tileOverlap.heading`.- *- * The legacy frontend drifted exactly this way: 85 feature ids, 84 catalog- * entries, and a `hrf` key that resolved to nothing.- */+/** Check registry/catalog parity both ways; generic static-key scanning misses interpolated hint keys. */const enModules = import.meta.glob('../../../../public/locales/en.json', { eager: true, import: 'default' });const en = Object.values(enModules)[0] as Record<string, unknown>;diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts b/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.tsindex d2a2d42e0d..b63a211ff2 100644--- a/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts+++ b/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts@@ -5,11 +5,7 @@ type HintPlacement = NonNullable<NonNullable<HoverCard.RootProps['positioning']>interface HintDefinition {/** Support article opened by the card's "Learn more" link. */href?: string;- /**- * Overrides {@link DEFAULT_HINT_PLACEMENT}. Nothing needs it today — the- * popper flips on its own when a panel is docked against the far edge — but- * a control whose card would cover its own value can pin itself here.- */+ /** Override DEFAULT_HINT_PLACEMENT when the card would cover its own control. */placement?: HintPlacement;}@@ -19,11 +15,7 @@ export const DEFAULT_HINT_PLACEMENT: HintPlacement = 'right';const SUPPORT_ADVANCED_SETTINGS = 'https://support.invoke.ai/support/solutions/articles/151000178161-advanced-settings';const SUPPORT_CONCEPTS = 'https://support.invoke.ai/support/solutions/articles/151000159072';-/**- * Every hint the workbench can attach to a control. Prose lives in the `hints.*`- * i18n namespace — this table carries only what a translator should not own.- * `hintRegistry.test.ts` proves the two stay in step in both directions.- */+/** Keep prose in hints.* and non-translatable metadata here; tests enforce registry/catalog parity. */export const FEATURE_HINTS = {aspectRatio: {},cfgRescale: { href: SUPPORT_ADVANCED_SETTINGS },diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/hintsContext.tsx b/invokeai/frontend/webv2/src/platform/ui/hints/hintsContext.tsxindex fed7eada59..a37805b94a 100644--- a/invokeai/frontend/webv2/src/platform/ui/hints/hintsContext.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/hints/hintsContext.tsx@@ -2,22 +2,14 @@ import type { ReactNode } from 'react';import { createContext, use } from 'react';-/**- * Feature hints' host port. Platform may not import Workbench, so the enabled- * preference and the "turn these off" command are pushed in from App — the same- * direction `I18nController` and `ThemeController` feed their platform- * singletons. Not a test seam; no second adapter is expected.- */+/** App supplies hint preferences/actions because Platform cannot import Workbench. */export interface FeatureHintsAdapter {enabled: boolean;/** Turns hints off from inside a card; null when the host cannot persist preferences. */onDisable: (() => void) | null;}-/**- * Inert by default: a tree with no provider renders exactly as it did before- * hints existed, so unit tests and isolated browser tests need no setup.- */+/** Default to disabled without a provider so isolated trees remain unchanged. */const DEFAULT_FEATURE_HINTS_ADAPTER: FeatureHintsAdapter = {enabled: false,onDisable: null,diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/index.ts b/invokeai/frontend/webv2/src/platform/ui/hints/index.tsindex b5c396b7ec..91227fb5bb 100644--- a/invokeai/frontend/webv2/src/platform/ui/hints/index.ts+++ b/invokeai/frontend/webv2/src/platform/ui/hints/index.ts@@ -1,6 +1,4 @@-// Published as the deep specifier `@platform/ui/hints`, deliberately absent from-// the `@platform/ui` barrel: that barrel sits near its `maxDirectImporters`-// budget, and every hint call site would otherwise count against it.+// Keep the hints entry outside the UI barrel to preserve its direct-importer budget.export * from './FeatureHint';export * from './hintRegistry';export * from './hintsContext';diff --git a/invokeai/frontend/webv2/src/platform/ui/hsv.ts b/invokeai/frontend/webv2/src/platform/ui/hsv.tsindex ad657e2812..06b0a9ab6d 100644--- a/invokeai/frontend/webv2/src/platform/ui/hsv.ts+++ b/invokeai/frontend/webv2/src/platform/ui/hsv.ts@@ -1,12 +1,4 @@-/**- * HSV math for the wheel-and-triangle color picker: RGB↔HSV conversion with- * sticky hue/saturation for the hue-agnostic greys, and the hue-ring/triangle- * geometry mapping. Pure functions, no React, no Chakra.- *- * The triangle follows the classic GIMP/Krita layout: it points at the hue on- * the ring, with the pure hue, white, and black at its corners; a color's- * position is the barycentric blend `hue·(s·v) + white·(v·(1−s)) + black·(1−v)`.- */+/** Preserve hue/saturation for achromatic colors. Triangle weights: hue=s·v, white=v·(1−s), black=1−v. */import type { RgbaColor } from './color';@@ -89,12 +81,7 @@ export const hslToRgb = ({ h, l, s }: HslColor): RgbaColor => {return hsvToRgb({ h, s: v === 0 ? 0 : 2 * (1 - clamp01(l) / v), v });};-/**- * Parses a hex color into HSV, keeping the hue (and, at black, the saturation)- * from `previous` when the parsed color cannot express them: hex is- * hue-agnostic for greys, and without stickiness every grey would snap the- * wheel's hue thumb back to red.- */+/** Preserve previous hue for greys and saturation at black; hex cannot encode them. */export const hexToHsv = (hex: string, previous?: HsvColor): HsvColor => {const parsed = rgbToHsv(parseHexColor(hex));if (!previous) {@@ -142,11 +129,7 @@ export const hsvToTrianglePoint = (hsv: HsvColor, radius: number): Point => {};};-/**- * The `{s, v}` for a center-relative point, clamped into the hue's triangle:- * barycentric weights are floored at zero and renormalized, so dragging- * outside any edge slides along it instead of escaping.- */+/** Clamp outside points by flooring and renormalizing barycentric weights, keeping drags inside the triangle. */export const trianglePointToHsv = (point: Point, hue: number, radius: number): HsvColor => {const [hueCorner, whiteCorner, blackCorner] = triangleCorners(hue, radius);// Solve the barycentric weights for `point` against the three corners.diff --git a/invokeai/frontend/webv2/src/platform/ui/settings/SettingsSelect.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/settings/SettingsSelect.browser.test.tsxindex 6fce3b499e..49e04fb7f5 100644--- a/invokeai/frontend/webv2/src/platform/ui/settings/SettingsSelect.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/settings/SettingsSelect.browser.test.tsx@@ -103,8 +103,7 @@ describe('settings language select', () => {await expect.element(page.getByRole('dialog', { name: 'Settings', exact: true })).toBeVisible();await expect.poll(() => dialogContent()?.querySelector('output')?.textContent).toBe('zh-Hant');await expect.element(language()).toHaveFocus();- // Tab only once the list has finished closing: a Tab during its exit- // animation races the select's own focus restore.+ // Wait for exit focus restoration before pressing Tab.await expect.poll(() => listbox()?.checkVisibility() ?? false).toBe(false);await act(() => userEvent.keyboard('{Tab}'));await expect.poll(() => dialogContent()?.contains(document.activeElement) ?? false).toBe(true);diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/DataListDividers.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/theme/DataListDividers.browser.test.tsxindex e369fab476..11260ad6ed 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/DataListDividers.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/theme/DataListDividers.browser.test.tsx@@ -55,8 +55,7 @@ describe('dataList slot recipe', () => {it('uses the subtle border token, not the inherited text color', async () => {const { reference, rows } = await renderDataList();- // A failed token lookup would fall back to `currentColor`; comparing- // against a border.subtle reference catches that regression.+ // Compare the resolved border token to catch accidental currentColor fallback.expect(getComputedStyle(rows[1]).borderTopColor).toBe(getComputedStyle(reference).borderTopColor);expect(getComputedStyle(rows[1]).borderTopColor).not.toBe(getComputedStyle(rows[1]).color);});diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/HighContrast.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/theme/HighContrast.browser.test.tsxindex 72ed0c3d8f..7eb48fddd1 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/HighContrast.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/theme/HighContrast.browser.test.tsx@@ -8,10 +8,8 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it } from 'vitest';/**- * The high-contrast preference flips `<html data-high-contrast>`; every theme's- * muted text and borders must then clear the WCAG AA thresholds (4.5:1 for- * text, 3:1 for a non-text boundary) on the panel surfaces chrome paints on,- * while muted text stays a visible rank below the foreground.+ * Require high-contrast muted text ≥4.5:1 and boundaries ≥3:1 across themes, while keeping muted text below fg+ * emphasis.*/let host: HTMLDivElement | null = null;diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/SegmentGroupContrast.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/theme/SegmentGroupContrast.browser.test.tsxindex 154b55e58f..7bbac14370 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/SegmentGroupContrast.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/theme/SegmentGroupContrast.browser.test.tsx@@ -51,8 +51,7 @@ const renderSegments = async (): Promise<{ checked: HTMLElement; count: HTMLElem};describe('segmentGroup checked contrast', () => {- // The indicator is a solid accent fill, so anything inside the checked item- // has to be readable against accent — not against the panel behind it.+ // Measure checked text against the accent indicator, not the panel.it('renders the checked label against the accent fill at AA contrast', async () => {const { checked, indicator } = await renderSegments();@@ -65,8 +64,7 @@ describe('segmentGroup checked contrast', () => {const { count, indicator } = await renderSegments();const style = getComputedStyle(count);- // Secondary text inside a segment must dim from `currentColor`; pinning it- // to a fixed `fg.muted` grey drops to ~1.5:1 on the accent fill.+ // Derive secondary text from currentColor; fixed muted gray loses contrast on selected accent fills.const ratio = getContrastRatio(style.color, getComputedStyle(indicator).backgroundColor, Number(style.opacity));expect(ratio).toBeGreaterThanOrEqual(4.5);diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/SegmentGroupSizing.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/theme/SegmentGroupSizing.browser.test.tsxindex c551b8d92b..512d0a711d 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/SegmentGroupSizing.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/theme/SegmentGroupSizing.browser.test.tsx@@ -47,8 +47,7 @@ const renderPair = async (size: '2xs' | 'xs' | 'sm'): Promise<{ button: HTMLElem};describe('segmentGroup slot recipe sizing', () => {- // Segment groups sit beside buttons in toolbars; a size name must mean the- // same outer height on both (Chakra's defaults run one size-name small).+ // Same-size segment groups and buttons must have equal outer heights.(['2xs', 'xs', 'sm'] as const).forEach((size) => {it(`matches the ${size} button height`, async () => {const { button, segmentRoot } = await renderPair(size);diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/SpinnerReducedMotion.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/theme/SpinnerReducedMotion.browser.test.tsxindex e0b2e3c928..bed451d78c 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/SpinnerReducedMotion.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/theme/SpinnerReducedMotion.browser.test.tsx@@ -4,11 +4,7 @@ import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it } from 'vitest';-/**- * Reduce-motion kills every animation token, which froze spinners into a- * static arc that reads as a broken icon. A loading spinner is essential- * status (WCAG 2.3.3 exempts essential motion), so it slows instead.- */+/** Reduced motion slows status spinners instead of freezing them. */let host: HTMLDivElement | null = null;let root: Root | null = null;diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/__tokenResolve.ts b/invokeai/frontend/webv2/src/platform/ui/theme/__tokenResolve.tsindex 4a9649767d..84641c94d4 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/__tokenResolve.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/__tokenResolve.ts@@ -1,12 +1,4 @@-/**- * Test-only helper: resolve every semantic color token to its FINAL literal value- * (following `var(--chakra-colors-…)` references) for each workbench theme, straight- * from `system.getTokenCss()`. This mirrors what the browser computes for a given- * `<html data-theme=… class="dark|light">`, so it is the ground truth used by the- * legacy-value gate in `system.test.ts`.- *- * Not imported by any app entry — excluded from the production bundle.- */+/** Resolve semantic CSS-variable chains per theme for token tests; keep this helper out of production imports. */type Block = Record<string, string>;type Layer = Record<string, Block>;diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/applyTheme.ts b/invokeai/frontend/webv2/src/platform/ui/theme/applyTheme.tsindex 08bdaf9074..fbb2cb2872 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/applyTheme.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/applyTheme.ts@@ -1,20 +1,13 @@import { DEFAULT_THEME, THEMES_BY_ID } from './themes';-/**- * Applies a theme to the document root. Semantic tokens key off- * `:root[data-theme]`, so these attribute writes restyle the whole shell with- * no React re-render. Deliberately does NOT touch the pre-paint localStorage- * hint — callers that persist (ThemeController) own that; transient callers- * (palette live-preview) must not.- */+/** Apply root theme attributes without persisting hints; transient previews must not overwrite saved appearance. */export const applyThemeToRoot = (themeId: string): void => {const root = document.documentElement;const theme = THEMES_BY_ID[themeId as keyof typeof THEMES_BY_ID] ?? DEFAULT_THEME;root.dataset.theme = theme.id;root.style.colorScheme = theme.colorScheme;- // Keep the native color-mode class in sync for unthemed browser chrome- // (scrollbars, native pickers) and any Chakra defaults we don't override.+ // Keep native color-mode classes aligned for browser chrome and unoverridden Chakra defaults.root.classList.toggle('dark', theme.colorScheme === 'dark');root.classList.toggle('light', theme.colorScheme === 'light');};diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/contrastRatio.testing.ts b/invokeai/frontend/webv2/src/platform/ui/theme/contrastRatio.testing.tsindex 7a76261813..2342b98da9 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/contrastRatio.testing.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/contrastRatio.testing.ts@@ -1,14 +1,4 @@-/**- * WCAG contrast measurement for accessibility assertions in browser tests.- *- * Lives here rather than in each test because it is a fixed formula, not a- * per-surface judgement: two copies of it can silently disagree about what a- * ratio *is*, and a contrast test that measures wrong is worse than no test —- * it reports the palette as accessible when it is not.- *- * Test-only. It resolves colours by painting them to a canvas, so it needs a- * real browser and has no place in the app bundle.- */+/** Browser-only contrast helpers; resolve colors through canvas and keep out of production bundles. *//** Resolve any CSS colour — named, `oklch()`, `color-mix()` — to sRGB channels. */export const toRgb = (color: string): [number, number, number] => {@@ -32,12 +22,7 @@ const getRelativeLuminance = ([red, green, blue]: [number, number, number]): numreturn 0.2126 * linearize(red) + 0.7152 * linearize(green) + 0.0722 * linearize(blue);};-/**- * Contrast of `foreground` at `alpha` composited over `background`.- *- * Opacity is applied by compositing rather than by scaling the ratio, because- * a translucent foreground is read against the pixel it actually produces.- */+/** Composite alpha before measuring contrast; never scale the ratio itself. */export const getContrastRatio = (foreground: string, background: string, alpha: number): number => {const backgroundRgb = toRgb(background);const composited = toRgb(foreground).map((channel, index) =>@@ -50,11 +35,7 @@ export const getContrastRatio = (foreground: string, background: string, alpha:return (lighter! + 0.05) / (darker! + 0.05);};-/**- * The colour a translucent fill actually produces over an opaque surface.- * Painted rather than parsed: `toRgb` reads raw channels and would report a- * semi-transparent background as if it were opaque.- */+/** Paint translucent fills over the surface; raw channel parsing would ignore compositing. */export const compositeColors = (top: string, bottom: string): string => {const context = document.createElement('canvas').getContext('2d')!;diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.tsindex b4944bc8a9..560d8b521f 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts@@ -1,12 +1,7 @@import { defineRecipe, defineSlotRecipe } from '@chakra-ui/react';import { recipes as chakraRecipes, slotRecipes as chakraSlotRecipes } from '@chakra-ui/react/theme';-/**- * Tooltip chrome: raised surface with a hairline stroke instead of inverted- * fill. Extends Chakra's default recipe — replacing it wholesale would drop- * the `arrow` slot's `--arrow-size`/`--arrow-background` vars, which renders- * arrows at zero size (invisible).- */+/** Extend the tooltip recipe; replacing it drops arrow size/background variables. */export const tooltipSlotRecipe = defineSlotRecipe({...chakraSlotRecipes.tooltip,base: {@@ -30,16 +25,7 @@ export const tooltipSlotRecipe = defineSlotRecipe({},});-/**- * Feature hint cards. Same raised surface as the tooltip so the two read as one- * family, one step wider for prose. Extends Chakra's default recipe: the arrow- * slots derive `--arrow-background` from `--hovercard-bg`, so replacing the base- * wholesale would render the arrow unfilled.- *- * The content owns its padding — cards must not add their own, or the two stack.- * Chakra's `md` default (20px) reads as a dialog rather than an annotation, so- * these default to `xs`.- */+/** Extend the hover-card recipe to preserve arrow variables. Content owns padding; callers must not duplicate it. */export const hoverCardSlotRecipe = defineSlotRecipe({...chakraSlotRecipes.hoverCard,base: {@@ -61,13 +47,7 @@ export const hoverCardSlotRecipe = defineSlotRecipe({defaultVariants: { size: 'xs' },});-/**- * Popover chrome: same raised surface as the tooltip/hover-card family, with- * an arrow pointing at the anchor. Extends Chakra's default recipe so the- * `arrow` slot keeps its `--arrow-size`/`--arrow-background` vars (which- * derive from `--popover-bg`); replacing the base wholesale would render- * arrows at zero size.- */+/** Extend the popover recipe to preserve arrow size/background variables. */export const popoverSlotRecipe = defineSlotRecipe({...chakraSlotRecipes.popover,base: {@@ -79,8 +59,6 @@ export const popoverSlotRecipe = defineSlotRecipe({borderWidth: '1px',boxShadow: 'lg',color: 'fg',- // The same drop-in motion as menus: Chakra's scale-fade reads as a- // dialog, and its `fast` open lags behind the click on a busy workbench._open: { animationStyle: 'slide-fade-in', animationDuration: 'faster' },_closed: { animationStyle: 'slide-fade-out', animationDuration: 'faster' },},@@ -127,8 +105,6 @@ export const tabsSlotRecipe = defineSlotRecipe({...chakraSlotRecipes.tabs.variants?.variant?.line,trigger: {...chakraSlotRecipes.tabs.variants?.variant?.line?.trigger,- // Rounded only at the top: the trigger's hover fill should read as- // rising from the underline, not as a floating pill.roundedTop: 'sm',_hover: {'&:not([data-selected])': { bg: 'bg.muted/60', color: 'fg' },@@ -139,9 +115,7 @@ export const tabsSlotRecipe = defineSlotRecipe({...chakraSlotRecipes.tabs.variants?.variant?.subtle,trigger: {...chakraSlotRecipes.tabs.variants?.variant?.subtle?.trigger,- // The buttons' corner and translucent accent-leaning hover (see- // `SegmentTabs`): solid subtle fills vanish against muted chrome.- // Selected stays the stock accent fill — nav sidebars rely on it.+ // Translucent hover stays visible on muted chrome; preserve selected accent fills for navigation.borderRadius: 'control',_hover: {'&:not([data-selected])': { bg: 'gray.hoverTint/10', color: 'fg' },@@ -192,8 +166,7 @@ export const buttonRecipe = defineRecipe({},variants: {...chakraRecipes.button.variants,- // One notch denser than Chakra's scale: `xs` lands on the segment-tab- // pill height, so the controls that share a row share a silhouette.+ // Align xs button height with segment tabs.size: {...chakraRecipes.button.variants?.size,xs: { ...chakraRecipes.button.variants?.size?.xs, h: '7', minW: '7' },@@ -202,10 +175,7 @@ export const buttonRecipe = defineRecipe({},variant: {...chakraRecipes.button.variants?.variant,- // Chakra's ghost/outline hover is the solid `subtle` fill, whose- // lightness collides with muted/control surfaces (invisible hover); a- // translucent `hoverTint` fill reads on every surface, leans toward the- // accent on the default palette, and keeps the tint of the others.+ // Use translucent hover tint because solid subtle fills disappear on matching surfaces.ghost: {...chakraRecipes.button.variants?.variant?.ghost,_hover: { bg: 'colorPalette.hoverTint/10' },@@ -216,15 +186,12 @@ export const buttonRecipe = defineRecipe({_hover: { bg: 'colorPalette.hoverTint/10' },_expanded: { bg: 'colorPalette.hoverTint/10' },},- // Stock Chakra gives plain buttons no hover state at all; they take the- // same surface-proof fill as ghost.+ // Give plain buttons the same visible hover fill as ghost buttons.plain: {...chakraRecipes.button.variants?.variant?.plain,_hover: { bg: 'colorPalette.hoverTint/10' },},- // Chakra's subtle fill (`colorPalette.subtle`) is a step off the panel- // surface, so a tinted button read as flat; the translucent tint keeps- // the palette's hue legible on every surface.+ // Use translucent tint so subtle buttons retain their palette hue across surfaces.subtle: {...chakraRecipes.button.variants?.variant?.subtle,bg: 'colorPalette.hoverTint/22',@@ -242,14 +209,12 @@ export const segmentGroupSlotRecipe = defineSlotRecipe({root: {...chakraSlotRecipes.segmentGroup.base?.root,'--segment-radius': 'radii.sm',- // A neutral fill disappears against the lighter section surfaces these- // controls sit on, so the selection reads through the accent palette.+ // Use accent selection because neutral fills disappear on lighter section surfaces.'--segment-indicator-bg': 'colors.accent.solid','--segment-indicator-shadow': 'none',bg: 'transparent',borderColor: 'border.subtle',- // The buttons' shared corner outside, minus the 1px border inside — the- // sm segment radius already sits at that inner value.+ // Inner radius subtracts the 1px border from the shared outer radius.borderRadius: 'control',borderWidth: '1px',boxShadow: 'none',@@ -257,10 +222,8 @@ export const segmentGroupSlotRecipe = defineSlotRecipe({item: {...chakraSlotRecipes.segmentGroup.base?.item,color: 'fg.muted',- // Items above the indicator by positive z-order rather than the base- // recipe's negative indicator: browsers paint both the same, but axe sorts- // a negative z-index beneath the page and measures the checked label's- // contrast against the panel instead of the indicator.+ // Use positive z-order; axe can treat negative indicators as beneath the page and measure the wrong+ // contrast.zIndex: 1,fontWeight: '500',transitionDuration: 'faster',@@ -277,8 +240,7 @@ export const segmentGroupSlotRecipe = defineSlotRecipe({},indicator: {...chakraSlotRecipes.segmentGroup.base?.indicator,- // Zag slides the indicator via inline `var(--transition-duration, 150ms)`;- // pointing the var at the motion-aware `fast` token collapses it under reduce motion.+ // Bind Zag's inline transition variable to the motion-aware duration token.'--transition-duration': '{durations.fast}',shadow: 'none',zIndex: 0,@@ -286,15 +248,10 @@ export const segmentGroupSlotRecipe = defineSlotRecipe({},variants: {...chakraSlotRecipes.segmentGroup.variants,- // Item heights are the button height of the same size name minus the- // root's 1px border, so a segment group's outer box lands exactly on the- // buttons it sits beside — Chakra's defaults run one size-name small- // (their `xs` item is button-`2xs` height). Text styles mirror the- // button recipe's `xs` cap.+ // Subtract root borders from same-size button heights so segment controls align with neighboring buttons.size: {...chakraSlotRecipes.segmentGroup.variants?.size,- // Repo extension (like the button's own `2xs`): Chakra ships no- // segment-group `2xs`, so this borrows the `xs` item styles as its base.+ // Chakra has no 2xs segment group; derive it from xs styles.'2xs': {item: {...chakraSlotRecipes.segmentGroup.variants?.size?.xs?.item,@@ -358,22 +315,14 @@ export const formControlInteraction = {const formControlOpen = { borderColor: 'accent.solid' };-/**- * `formControlInteraction` keyed on focus-within, for composite fields whose- * focusable element lives inside the frame (see `platform/ui/InputShell`).- */+/** Use focus-within for composite fields such as InputShell. */export const inputShellInteraction = {...formControlInteraction,_focusWithin: formControlFocused,_hover: { ...formControlInteraction._hover, _focusWithin: formControlFocused },};-/**- * `formControlInteraction` for `platform/ui/ScrubberField`: the frame is the- * pointer target and clicks focus an inner layer programmatically, so the- * accent border keys on keyboard focus (`:focus-visible`) or the inline editor,- * never on a plain click, which shows the dragging state instead.- */+/** Scrubber borders follow keyboard/editor focus; pointer clicks use drag state instead. */export const scrubberInteraction = {...formControlInteraction,'&:has(:focus-visible), &[data-editing]': formControlFocused,@@ -387,8 +336,7 @@ export const inputRecipe = defineRecipe({...chakraRecipes.input,variants: {...chakraRecipes.input.variants,- // The same one-notch drop as the button scale, so same-named sizes share a- // row height (select/combobox/numberInput repeat it for their vars).+ // Keep same-named input, select, combobox, and button sizes aligned.size: {...chakraRecipes.input.variants?.size,xs: { ...chakraRecipes.input.variants?.size?.xs, '--input-height': 'sizes.7' },@@ -480,8 +428,7 @@ export const dropdownContent = {export const dropdownItem = {borderRadius: 'l2',- // One `data-danger` attribute is the whole destructive treatment; every- // delete/uninstall/clear item opts in instead of restyling locally.+ // Use data-danger for destructive menu items.'&[data-danger]': {color: 'fg.error',_highlighted: { bg: 'bg.error' },@@ -535,10 +482,8 @@ export const menuSlotRecipe = defineSlotRecipe({export const selectSlotRecipe = defineSlotRecipe({...chakraSlotRecipes.select,- // The outline variant carries its own `_expanded` (border.emphasized) which- // would override a base-level open style, so the accent open state lives on- // the variant too. The cast keeps defineSlotRecipe's variant inference- // anchored to Chakra's own map, which the spread-with-override loses.+ // Override outline _expanded at variant level; base styles lose to it. Preserve Chakra's variant-map inference+ // in the cast.variants: {...chakraSlotRecipes.select.variants,size: {@@ -656,12 +601,6 @@ export const comboboxSlotRecipe = defineSlotRecipe({},});-/**- * The one dialog look: compact tool windows on a single surface. Density and- * chrome live here — a dialog file should carry structure, not styling.- * Chakra's stock 24px gutters, `lg` title, and top placement all read as a- * marketing modal rather than a desktop app's dialog.- */export const dialogSlotRecipe = defineSlotRecipe({...chakraSlotRecipes.dialog,base: {@@ -714,12 +653,7 @@ export const dialogSlotRecipe = defineSlotRecipe({},});-/**- * Chakra hides a scrollbar only when NEITHER axis overflows- * (`&:not([data-overflow-x], [data-overflow-y])`), so a vertical-only bar- * sticks around — thumb clamped to its minimum size — whenever content merely- * spills sideways (nowrap rows, wide JSON). Each bar answers for its own axis.- */+/** Check each scrollbar's own overflow axis; Chakra's combined guard leaves phantom thumbs on the other axis. */export const scrollAreaSlotRecipe = defineSlotRecipe({...chakraSlotRecipes.scrollArea,base: {@@ -746,13 +680,8 @@ export const sliderSlotRecipe = defineSlotRecipe({variants: {...chakraSlotRecipes.slider.variants,size: {- // Chakra's thumb sizes are touch targets. With a mouse the track itself- // is the drag target, so fine-pointer devices get a much smaller thumb.- // `--slider-marker-center` must shrink with it: it is the marker group's- // top offset, (thumb - marker) / 2, keeping marks centered on the track.- // `--slider-marker-inset` is zeroed at every size: zag already offsets- // marks by half the thumb within the group, so any extra inset shifts- // the end marks off the thumb positions they label.+ // Fine pointers use smaller thumbs. Update marker center with thumb size and zero marker inset because Zag+ // already applies half-thumb offsets.lg: {root: {...chakraSlotRecipes.slider.variants?.size?.lg?.root,@@ -878,12 +807,8 @@ export const colorPickerSlotRecipe = defineSlotRecipe({});/**- * Skeletons sweep a subtle highlight instead of pulsing. The gradient rests on- * the same `bg.emphasized` surface the stock pulse used; the band is a small- * fg lift so it stays quiet on every theme. The sweep runs linear: the stock- * ease-in-out lingers at each end and rushes the middle, which reads as a- * stutter. Reduce-motion is handled by the global `.chakra-skeleton`- * animation kill in `system.ts`.+ * Use a linear sweep to avoid endpoint pauses; system.ts disables skeleton motion and gradients under reduced+ * motion.*/export const skeletonRecipe = defineRecipe({...chakraRecipes.skeleton,@@ -942,8 +867,7 @@ export const rowRecipe = defineRecipe({textAlign: 'start',transition: 'background var(--wb-motion-duration-fast) ease, color var(--wb-motion-duration-fast) ease',w: 'full',- // A pointer hint, not a state: it stays under the `muted` (selected)- // variant's own `bg.muted` so hovering never reads as selecting.+ // Keep hover below selected emphasis so pointing does not resemble selection._hover: { bg: 'bg.muted/60' },_focusVisible: {outline: '2px solid',@@ -1072,13 +996,7 @@ export const themeCardRecipe = defineSlotRecipe({defaultVariants: { selected: false },});-/**- * Hairline dividers between rows. Metadata lists carry values of very- * different heights — a seed next to a wrapped prompt — and a bare row gap- * stops reading as separation once values grow tall; the rule keeps each- * label/value pair visually bound. `paddingTop` mirrors the 1.5-unit row gap- * the metadata lists use, so the line sits centered between rows.- */+/** Separate variable-height metadata rows with centered dividers; keep padding aligned with the row gap. */export const dataListSlotRecipe = defineSlotRecipe({...chakraSlotRecipes.dataList,base: {@@ -1086,8 +1004,7 @@ export const dataListSlotRecipe = defineSlotRecipe({item: {...chakraSlotRecipes.dataList.base?.item,'&:not(:first-child)': {- // `borderColor` + top-only width, like the chrome islands: the- // side-specific color property does not resolve the semantic token.+ // Use borderColor plus top width; side-specific color does not resolve the semantic token.borderColor: 'border.subtle',borderTopWidth: '1px',paddingTop: '1.5',diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/system.test.ts b/invokeai/frontend/webv2/src/platform/ui/theme/system.test.tsindex cf44f43a9a..4ec45df27e 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/system.test.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/system.test.ts@@ -18,9 +18,7 @@ const lightnessOf = (oklch: string): number => {};describe('color token contract — legacy-value gate', () => {- // Primary gate: every consumer token must resolve to the EXACT value it had- // before the ramp refactor. The baseline was captured from the previous system- // on the working tree before any change (see __fixtures__/legacyTokenBaseline.json).+ // Pin semantic-token values against __fixtures__/legacyTokenBaseline.json.for (const theme of THEMES) {for (const token of CONSUMER_TOKENS) {it(`${theme}: ${token} is unchanged`, () => {@@ -68,10 +66,8 @@ describe('ramp + mapping structure', () => {});it('emits surface/text/border tokens via per-theme conditions only — never the leaky mode selectors', () => {- // Chakra's `_light` selector (`:root &, .light &`) matches under EVERY theme via its- // `:root &` arm. A surface token placed there leaks its light value into the dark- // themes (the classic-renders-light regression). These tokens must live ONLY in the- // base + `[data-theme=…]` selectors.+ // Avoid Chakra _light for surfaces: its :root arm matches dark themes too. Use base and explicit data-theme+ // selectors.const layer = sys.getTokenCss()['@layer tokens'];const LEAKY = [':root &, .light &', '.dark &, .dark .chakra-theme:not(.light) &'];const surfaceTokens = [@@ -143,8 +139,7 @@ describe('native Chakra integration', () => {});it('leaves stock Chakra hue palettes untouched in Phase 1', () => {- // Phase 2 will theme these; for now they must remain Chakra defaults so model- // badges / destructive actions keep their stock colors.+ // Stock Chakra palette values.expect(sys.tokens.getByName('colors.red.500')).toBeTruthy();expect(sys.tokens.getByName('colors.blue.500')).toBeTruthy();expect(sys.tokens.getByName('colors.purple.500')).toBeTruthy();@@ -156,8 +151,7 @@ describe('brand palette derives from its two seeds (like accent)', () => {for (const theme of THEMES) {const solid = resolveToken(sys, theme, 'brand.solid');const surface = resolveToken(sys, theme, 'bg.subtle');- // `brand.fg` is the exception: it darkens on the light theme, where the- // seed measures 1.20:1 against the panel it would sit on.+ // Darken brand.fg on light backgrounds to preserve contrast.expect(resolveToken(sys, theme, 'brand.fg')).toBe(theme === 'light' ? `color-mix(in oklab, ${solid} 50%, oklch(22.5% 0.013 264))` : solid);diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/system.ts b/invokeai/frontend/webv2/src/platform/ui/theme/system.tsindex 2c20cc7d98..a25283d4b2 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/system.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/system.ts@@ -24,22 +24,8 @@ import {import { DEFAULT_THEME, DEFAULT_THEME_ID, type NeutralStep, THEMES, type ThemeDefinition } from './themes';/**- * Workbench design system.- *- * Each theme is one neutral ramp (`neutral.50…950`) plus seeds and four- * off-ramp neutrals, turned into two token layers:- *- * 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` 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.+ * Emit theme-varying ramps as semantic tokens; map component tokens and Chakra gray onto them. Root data-theme+ * switches appearance; light elevations are not a reversed dark ramp.*/const NON_DEFAULT_THEMES = THEMES.filter((theme) => theme.id !== DEFAULT_THEME_ID);@@ -66,12 +52,8 @@ const mix = (top: Compute, pct: number, bottom: Compute): TokenValue =>const LIGHT_FALLBACK_THEME = THEMES.find((theme) => theme.colorScheme === 'light') ?? DEFAULT_THEME;/**- * Like `colorToken`, but additionally shadows Chakra's `_light`/`_dark`- * class-conditional values. Nested palette tokens (`gray.*`) deep-merge with- * `defaultConfig` instead of replacing it, so without these keys the default- * gray values would survive the merge and outrank our zero-specificity `base`- * value whenever `ThemeController` sets the `.dark`/`.light` class. The explicit- * `:root[data-theme=…]` conditions still win over both.+ * Shadow default gray _light/_dark keys because nested palettes deep-merge; explicit root theme selectors must+ * still win.*/const grayToken = (compute: Compute): TokenValue => {const token = colorToken(compute);@@ -80,24 +62,12 @@ const grayToken = (compute: Compute): TokenValue => {return token;};-/**- * A token that reads a ramp step, chosen per theme by `colorScheme`. Emitted as- * per-`[data-theme]` conditions, NOT Chakra's `_light`/`_dark`: the built-in- * `_light` selector is `:root &, .light &`, and its `:root &` arm matches under- * EVERY theme — so a mode-flip token leaks its light value into the dark themes.- * Per-theme conditions sidestep the cascade entirely (this is how the pre-refactor- * system worked, and why dark themes rendered correctly).- */+/** Use explicit data-theme conditions: Chakra _light includes :root and can leak light values into dark themes. */const ref = (step: NeutralStep): string => `{colors.neutral.${step}}`;const stepRef = (darkStep: NeutralStep, lightStep: NeutralStep): TokenValue =>colorToken((theme) => ref(theme.colorScheme === 'light' ? lightStep : darkStep));-/**- * The high-contrast boost only differs by color scheme, so two conditions- * cover every theme: ramp-step references resolve per theme on their own.- * Unrelated to Chakra's built-in `_highContrast` (`forced-colors`); these key- * off the app preference.- */+/** App high-contrast conditions follow color scheme; they are separate from forced-colors. */const withHighContrast = (token: TokenValue, darkStep: NeutralStep, lightStep: NeutralStep): TokenValue => {token.value._highContrastDark = ref(darkStep);token.value._highContrastLight = ref(lightStep);@@ -124,19 +94,7 @@ const success: Compute = (theme) => theme.colors.success;const warning: Compute = (theme) => theme.colors.warning;const brandSolid: Compute = (theme) => theme.colors.brand.solid;-/**- * Brand as a *foreground* colour rather than a fill.- *- * The seed is a bright lime picked to carry on the dark themes' near-black- * surfaces, where it measures 14.5:1. On the light theme the same value sits at- * L≈92% against a 99% white panel and measures 1.20:1 — invisible, which is why- * the Invoke mark all but disappeared there. Darkening it halfway into the text- * ramp brings it to 4.2:1 on the panel and 4.1:1 on `brand.subtle`: still- * unmistakably the brand hue, now actually a colour you can put something in.- *- * `brand.solid` is untouched — fills keep the bright seed and pair it with- * `brand.contrast`.- */+/** Darken brand.fg on light themes for contrast; keep bright brand.solid paired with brand.contrast. */const brandFg: Compute = (theme) =>theme.colorScheme === 'light'? `color-mix(in oklab, ${theme.colors.brand.solid} 50%, ${theme.colors.neutral[950]})`@@ -146,8 +104,7 @@ const accentSolid: Compute = (theme) => theme.colors.accent.solid;/** The neutral ramp, emitted as `neutral.50…neutral.950`, one value per theme. */const neutralRamp = Object.fromEntries(STEPS.map((step) => [step, colorToken((theme) => theme.colors.neutral[step])]));-// Additional categorical hues. Seeds are dark-theme foregrounds; light themes-// darken them for text, and every fill derives from the same hue and surface.+// Darken categorical text seeds for light themes; derive fills from the same hue.const categoricalPalettes = Object.fromEntries(Object.entries({coral: '#ff8e80',@@ -179,17 +136,14 @@ const categoricalPalettes = Object.fromEntries();/**- * The semantic-token contract. Backgrounds/foregrounds/borders reference ramp- * steps (`stepRef`); the four off-ramp neutrals and the status/identity hues read- * their per-theme seed directly. Where a Chakra built-in name exists we use it- * verbatim so built-ins inherit the theme for free.+ * Reuse Chakra token names so built-ins inherit themes; ramp references and explicit seeds form the semantic+ * contract.*/const semanticColors = {...categoricalPalettes,neutral: neutralRamp,- // Surface ladder. Light panels are whiter than the app bg, so the light steps- // are not a mirror of the dark ones.+ // Light panels are brighter than the app background, not a reversed dark ladder.bg: stepRef(950, 200),'bg.subtle': stepRef(900, 50),'bg.muted': stepRef(800, 100),@@ -201,8 +155,7 @@ const semanticColors = {'bg.success': mix(success, 14, surface),'bg.warning': mix(warning, 14, surface),- // Foreground. Muted/subtle text carries the contrast burden: under high- // contrast they climb toward `fg` while staying a visible rank below it.+ // High contrast raises muted text toward fg while preserving its lower emphasis.fg: stepRef(50, 950),'fg.muted': contrastStepRef(300, 700, 200, 800),'fg.subtle': contrastStepRef(400, 500, 300, 700),@@ -220,14 +173,8 @@ const semanticColors = {'border.image': colorToken((theme) => (theme.colorScheme === 'light' ? 'oklch(0 0 0 / 0.1)' : 'oklch(1 0 0 / 0.1)')),/**- * Chakra's default `colorPalette` is `gray`; re-pointing its virtual-palette- * keys at the ramp makes every un-palettized component (ghost buttons, menu- * items, badges, …) theme-aware with zero props.- *- * Palette tokens must stay NESTED — the `colorPalette` virtual-token map is- * built from the nested structure and ignores flat dotted keys. Because nesting- * deep-merges with the defaults, every gray key shadows the default- * `_light`/`_dark` values via `grayToken`.+ * Keep palette tokens nested for Chakra's virtual-token map; shadow deep-merged gray _light/_dark defaults via+ * grayToken.*/gray: {contrast: grayToken((theme) =>@@ -248,11 +195,7 @@ const semanticColors = {300,600),- /**- * Interaction-fill base for the default palette: fg pulled toward the- * accent, so translucent hovers read in the menus' cool-tinted family- * instead of a flat gray. Used at low alpha (`gray.hoverTint/10`).- */+ /** Mix foreground toward accent for low-alpha interaction fills. */hoverTint: grayToken((theme) =>`color-mix(in oklab, ${theme.colors.accent.solid} 40%, ${@@ -265,13 +208,7 @@ const semanticColors = {orange: { hoverTint: { value: '{colors.orange.fg}' } },green: { hoverTint: { value: '{colors.green.fg}' } },blue: { hoverTint: { value: '{colors.blue.fg}' } },- /**- * Invoke identity palette (lime). Authored from two seeds (`solid` + `contrast`),- * like `accent`; the rest derive. `brand.fg` is the seed on the dark themes and a- * darkened mix on the light one (see {@link brandFg}), so it is safe to put text- * and icons in on any theme; `brand.solid` stays the bright fill and wants- * `brand.contrast` on top of it.- */+ /** Use brand.fg for text/icons and brand.solid with brand.contrast for fills. */brand: {solid: colorToken(brandSolid),contrast: colorToken((theme) => theme.colors.brand.contrast),@@ -297,13 +234,11 @@ const semanticColors = {},};-// `:root` raises specificity above the `.dark`/`.light` colorScheme classes so-// an explicit theme always beats the class-conditional fallback values.+// :root specificity makes explicit themes override .dark/.light fallbacks.const themeConditions = Object.fromEntries(NON_DEFAULT_THEMES.map((theme) => [conditionName(theme.id), `:root[data-theme=${theme.id}]`]));-// The attribute pair outranks the plain `[data-theme]` conditions; light-// themes are enumerated so a future light theme cannot fall into the dark arm.+// Paired attributes outrank data-theme; enumerate light themes to avoid dark fallbacks.const lightThemeSelectors = THEMES.filter((theme) => theme.colorScheme === 'light').map((theme) => `[data-theme=${theme.id}]`).join(', ');@@ -328,20 +263,13 @@ const config = defineConfig({margin: 0,overflow: 'hidden',},- // Interactive elements keep the default arrow even over their text —- // without this, non-button rows (picker options, menu items) compute- // `auto` and show the I-beam. Recipes still override (e.g. not-allowed).- // Attribute values stay unquoted: serialized markup assertions (SamOptions)- // grep for the quoted forms. No `[role=combobox]` — zag puts that role on- // type-able inputs, which must keep the I-beam.+ // Exclude editable comboboxes from arrow cursors. Keep role values unquoted while SamOptions assertions match+ // quoted markup.'button, [role=button], [role=menuitem], [role=menuitemcheckbox], [role=menuitemradio], [role=option], [role=tab], [role=radio], [role=checkbox], [role=switch]':{cursor: 'default',},- // While a gallery-item drag is in flight (body flag set by- // GalleryDragCursor) the closed-hand cursor applies everywhere: without- // the descendant rule, every element that sets its own cursor (buttons,- // textareas, grab handles) would flicker it back mid-drag.+ // Apply the drag cursor to descendants too, overriding controls' own cursors during gallery drags.'body[data-gallery-drag], body[data-gallery-drag] *': {cursor: 'grabbing !important',},@@ -351,8 +279,7 @@ const config = defineConfig({'--wb-motion-duration-slow': '0.2s','--wb-motion-animation-iteration-count': 'infinite',},- // Keep durations non-zero: Ark presence waits for animation lifecycle events.- // Chakra recipe motion is covered by conditional duration/animation tokens below.+ // Keep reduced-motion durations nonzero because Ark presence awaits animation events.':root[data-reduce-motion="true"]': {'--wb-motion-duration-fast': '1ms','--wb-motion-duration-medium': '1ms',@@ -360,17 +287,12 @@ const config = defineConfig({'--wb-motion-animation-iteration-count': '1',scrollBehavior: 'auto !important',},- // `backgroundImage` too: the shine gradient frozen mid-sweep reads as a- // smudge, so reduce-motion falls back to the flat fill.+ // Remove the shine gradient as well as motion so a frozen band does not remain visible.':root[data-reduce-motion="true"] .chakra-skeleton': {animation: 'none !important',backgroundImage: 'none !important',},- // A loading spinner is essential status, not decoration — frozen, its arc- // reads as a broken icon. It slows to a crawl instead of stopping; WCAG- // 2.3.3 targets non-essential motion only. (Chakra's indeterminate- // progress circle already behaves this way: its raw `spin 2s` shorthand- // bypasses the animation tokens the reduce-motion condition nulls out.)+ // Slow loading spinners under reduced motion so they continue conveying activity.':root[data-reduce-motion="true"] .chakra-spinner': {animation: 'spin 2s linear infinite !important',},@@ -384,15 +306,12 @@ const config = defineConfig({},},tokens: {- // Pro-app convention: controls keep the default arrow cursor; pointer is- // reserved for links. Overrides Chakra's `button`/`switch` pointer tokens.+ // Use arrow cursors for controls and pointer for links.cursor: {button: { value: 'default' },switch: { value: 'default' },},radii: {- // The shared corner for interactive controls — buttons and the- // segment-tab pills meet between Chakra's l2 (4px) and md (6px).control: { value: '0.3125rem' },},fonts: {@@ -422,8 +341,6 @@ const config = defineConfig({slowest: motionDurationToken('500ms'),},},- // Chrome-level overrides for Chakra's built-in components, so popover and- // dialog surfaces are consistent everywhere without per-instance props.recipes: {button: buttonRecipe,input: inputRecipe,diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/themes.ts b/invokeai/frontend/webv2/src/platform/ui/theme/themes.tsindex 8167dc0c3a..c6fd9f2bd6 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/themes.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/themes.ts@@ -1,29 +1,11 @@export type WorkbenchThemeId = 'classic' | 'light' | 'osakaJade' | 'mono' | 'ultradark' | 'catppuccinMocha';-/**- * Steps of the neutral ramp. `50` is the lightest, `950` the darkest — the same- * absolute orientation Chakra/Tailwind use, so the ramp can be aliased onto the- * built-in `gray` palette without surprises.- */+/** Keep the ramp absolute: 50 lightest, 950 darkest, matching Chakra gray. */export type NeutralStep = 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 950;/**- * One workbench theme, expressed as a small set of concrete OKLch values.- *- * The bulk of a theme is the `base` ramp — a single neutral scale from which the- * semantic-token layer in `system.ts` derives every background, foreground, and- * border (`bg → neutral.950` in dark mode, `fg → neutral.50`, …). Everything else is a- * handful of seeds:- *- * - `brand` / `accent` — the two identity hues (lime action, blue selection);- * - `danger` / `success` / `warning` — status intents;- * - `inset` / `fill` / `grid` / `control` — four neutrals whose *elevation rank*- * differs from theme to theme, so they cannot sit on a single shared ramp step- * (e.g. `inset` recesses below the app background in the light theme but lifts- * above it in the dark themes). They are kept as explicit per-theme values and- * consumed by name through `bg.inset`, `fg.grid`, `gray.subtle`, `bg.emphasized`.- *- * Adding a theme is therefore: author one ramp + the seeds. No component changes.+ * Themes supply a neutral ramp and hue seeds; inset/fill/grid/control stay explicit because their elevation order+ * varies by theme.*/export interface ThemeColors {/** Neutral ramp, lightest (`50`) → darkest (`950`). Source of all bg/fg/border. */@@ -57,9 +39,6 @@ export interface ThemeDefinition {colors: ThemeColors;}-// The slate tint is deliberately even: chroma tracks the ramp smoothly-// (0.014 → 0.026 → 0.014) instead of the old spike-at-400 curve, and the dark-// end sits ~2.5% L lower so the chrome reads as slate, not washed graphite.const classic: ThemeColors = {neutral: {50: 'oklch(96% 0.006 264.5)',@@ -80,16 +59,12 @@ const classic: ThemeColors = {success: 'oklch(79.8% 0.1132 141.63)',warning: 'oklch(76.62% 0.0612 62.9)',inset: 'oklch(18.8% 0.014 264.4)',- // Sits ~7% L above the neutral.800 surface like every other dark theme's- // fill; matching neutral.800 exactly made ghost hovers invisible on muted- // surfaces.+ // Keep fill visibly above control surfaces so ghost hovers do not disappear.fill: 'oklch(36% 0.021 264.3)',grid: 'oklch(38.5% 0.022 264.3)',control: 'oklch(34% 0.02 264.3)',};-// Cool blue-gray neutrals (hue 264, harmonizing with the blue accent): near-white-// chrome floating on a soft-gray work floor, near-black cool text. Airy and clean.const light: ThemeColors = {neutral: {50: 'oklch(99.4% 0.002 264)',@@ -115,8 +90,6 @@ const light: ThemeColors = {control: 'oklch(93.5% 0.005 264)',};-// Jade rather than leaf: the ramp lives on the blue-green side (hue ~180)-// like stone, with the leafier greens reserved for brand and success.const osakaJade: ThemeColors = {neutral: {50: 'oklch(92% 0.028 178)',@@ -167,9 +140,6 @@ const mono: ThemeColors = {control: 'oklch(27.274% 0 0)',};-// True-black floor with faintly cool text: the old light steps carried a-// green-lime cast that clashed with everything but the brand mark; the ramp-// now cools toward slate and lets brand lime and sky accent be the color.const ultradark: ThemeColors = {neutral: {50: 'oklch(89% 0.008 250)',@@ -195,11 +165,7 @@ const ultradark: ThemeColors = {control: 'oklch(19% 0.004 250)',};-// Catppuccin Mocha (https://catppuccin.com), converted from the published sRGB-// hex values. The ramp is the palette's own neutral ladder — Crust/Mantle/Base as-// the app, subtle and panel surfaces, Surface0–2 for controls and borders,-// Overlay/Subtext/Text for foregrounds — so every step is a palette color.-// Mauve carries the brand, Blue the accent.+// Catppuccin Mocha palette (https://catppuccin.com), converted from published sRGB; Mauve brand, Blue accent.const catppuccinMocha: ThemeColors = {neutral: {50: 'oklch(87.87% 0.0426 272.28)', // Text@@ -220,18 +186,13 @@ const catppuccinMocha: ThemeColors = {success: 'oklch(85.77% 0.1092 142.72)', // Greenwarning: 'oklch(82.37% 0.1015 52.63)', // Peachinset: 'oklch(18.28% 0.0204 284.2)', // Crust- // The palette has no step between Surface0 and Surface1; the fill sits at- // their midpoint so ghost hovers and subtle badges stay visible on controls.+ // Interpolate fill between Surface0 and Surface1 so hover and badges remain visible on controls.fill: 'oklch(36.4% 0.0319 281.06)',grid: 'oklch(40.37% 0.032 280.15)', // Surface1control: 'oklch(32.4% 0.0319 281.98)', // Surface0};-/**- * Theme registry. Order here is the display order in the Settings picker.- * `THEMES` is the single source of truth consumed by both the token builder- * and the settings UI.- */+/** Registry order is Settings display order. */export const THEMES: ThemeDefinition[] = [{id: 'classic',@@ -317,10 +278,6 @@ export const resolveWorkbenchThemeId = (value: unknown): WorkbenchThemeId | nullconst surfaceOf = (theme: ThemeDefinition): string =>theme.colorScheme === 'light' ? theme.colors.neutral[50] : theme.colors.neutral[900];-/**- * The four representative chips shown in the Settings appearance picker:- * surface, control fill, brand, accent — a compact read of the theme's identity.- */export const previewSwatches = (theme: ThemeDefinition): [string, string, string, string] => [surfaceOf(theme),theme.colors.control,diff --git a/invokeai/frontend/webv2/src/platform/ui/useScrollAreaPhantomHeal.ts b/invokeai/frontend/webv2/src/platform/ui/useScrollAreaPhantomHeal.tsindex e40ee45bb8..91f10fcd17 100644--- a/invokeai/frontend/webv2/src/platform/ui/useScrollAreaPhantomHeal.ts+++ b/invokeai/frontend/webv2/src/platform/ui/useScrollAreaPhantomHeal.ts@@ -3,27 +3,15 @@ import type { RefObject } from 'react';import { useMountEffect } from '@platform/react/useMountEffect';/**- * Zag's initial scroll-area measure can race a popover's or dialog's- * zero-size mount (its resize observers can even end up watching pre-remount- * nodes), and its "has overflow" default then strands a phantom thumb on- * content that never overflowed. Whenever a check finds that contradiction on- * the live nodes, one synthetic scroll routes a re-measure through zag's own- * event path — and clears the contradiction, so the checks cannot loop.- * Scroll listeners on these viewports must tolerate a no-op scroll event.- *- * Mount this next to any `ScrollArea.Viewport` (see `Scrollable`); the ref- * must point at the viewport element.+ * Zag can retain phantom overflow after zero-size/remounted content. Check live viewport nodes and dispatch one+ * no-op scroll to remeasure; listeners must tolerate it.*/export const useScrollAreaPhantomHeal = (viewportRef: RefObject<HTMLElement | null>): void => {useMountEffect(() => {- // Always through the ref: a presence pass can remount the subtree, and a- // node captured at effect time goes dead (which is also how zag's own- // observers end up blind here).+ // Read the ref each time; presence remounts can invalidate captured nodes.const hasPhantomScrollbar = () => {const viewport = viewportRef.current;- // `:scope >`: a nested scroll area's scrollbar must not answer for- // ours. Every scrollbar carries both overflow attributes, so the first- // sibling bar is authoritative.+ // Use direct children so nested scrollbars cannot report our overflow state.const scrollbar = viewport?.parentElement?.querySelector(':scope > [data-part="scrollbar"]');if (!viewport || !scrollbar) {@@ -61,9 +49,7 @@ export const useScrollAreaPhantomHeal = (viewportRef: RefObject<HTMLElement | nu}};- // The timed checks catch a presence remount the observer can no longer- // see; each re-syncs observation to the ref's current node, and the- // re-synced observer covers real resizes from then on.+ // Timed checks recover missed remounts and rebind the observer to the current node.for (const delay of [64, 250, 600]) {timers.push(setTimeout(check, delay));}diff --git a/invokeai/frontend/webv2/src/platform/ui/wheelScrollsHorizontally.ts b/invokeai/frontend/webv2/src/platform/ui/wheelScrollsHorizontally.tsindex 2a3f685423..bd3406a650 100644--- a/invokeai/frontend/webv2/src/platform/ui/wheelScrollsHorizontally.ts+++ b/invokeai/frontend/webv2/src/platform/ui/wheelScrollsHorizontally.ts@@ -15,12 +15,7 @@ const handleWheel = (event: WheelEvent): void => {element.scrollLeft += event.deltaMode === WheelEvent.DOM_DELTA_LINE ? event.deltaY * LINE_HEIGHT_PX : event.deltaY;};-/**- * Ref for a strip that only scrolls sideways: a vertical wheel, the one most- * mice have, moves it along its axis instead of doing nothing. Trackpad- * gestures that already carry a horizontal delta pass through untouched, as- * does a strip whose content fits.- */+/** Map vertical wheels to horizontal scrolling; preserve horizontal gestures and non-overflowing strips. */export const wheelScrollsHorizontally: RefCallback<HTMLElement> = (element) => {if (!element) {return;diff --git a/invokeai/frontend/webv2/src/platform/ui/widgetOverlayRegistry.ts b/invokeai/frontend/webv2/src/platform/ui/widgetOverlayRegistry.tsindex f6d8288aab..2f39c3114d 100644--- a/invokeai/frontend/webv2/src/platform/ui/widgetOverlayRegistry.ts+++ b/invokeai/frontend/webv2/src/platform/ui/widgetOverlayRegistry.ts@@ -1,8 +1,4 @@-/**- * The React-free half of widget overlay dismissal: an epoch every registered- * overlay watches, plus the closes to resend. `widgetOverlays.ts` binds it to- * React; the workbench store bumps it before a switch hides widgets.- */+/** React-free dismissal epochs and pending closes; Workbench bumps them before hiding widgets. */let epoch = 0;const subscribers = new Set<() => void>();@@ -25,12 +21,8 @@ export const registerWidgetOverlayCloser = (close: () => void): (() => void) =>};/**- * Closes every overlay that originates inside a widget; shell overlays stay.- * Call it before the switch that hides the widget: the overlay library defers- * its own close to a microtask and drops it once the widget's tree is hidden,- * so the epoch bump removes the content synchronously, in the same commit as- * the switch, and the deferred close catches up wherever it can. Every widget's- * overlays close, including ones the switch leaves visible.+ * Call before hiding widgets: deferred library closes may be dropped. Epochs hide content synchronously; all+ * widget overlays close, while shell overlays remain.*/export const closeWidgetOverlays = (): void => {epoch += 1;diff --git a/invokeai/frontend/webv2/src/platform/ui/widgetOverlays.ts b/invokeai/frontend/webv2/src/platform/ui/widgetOverlays.tsindex be241d8779..08b4e48feb 100644--- a/invokeai/frontend/webv2/src/platform/ui/widgetOverlays.ts+++ b/invokeai/frontend/webv2/src/platform/ui/widgetOverlays.ts@@ -9,19 +9,14 @@ import {export { closeWidgetOverlays } from './widgetOverlayRegistry';-/**- * Marks a subtree as one widget's own: overlays opened inside it answer to- * `closeWidgetOverlays`. Provided by the widget host.- */+/** Associates overlays with the widget host for closeWidgetOverlays. */export const WidgetOverlayOwnerContext = createContext(false);const subscribeToNothing = (): (() => void) => () => undefined;/**- * Registers an overlay's content with the widget it lives in, for as long as- * the content is mounted. Returns true while the overlay was told to close but- * its library still reports it open — the content then renders nothing. A- * widget shown again re-runs its effects, which is when the close is resent.+ * Register while mounted; hide content synchronously after dismissal and resend the library close when a hidden+ * widget returns.*/export const useRegisterWidgetOverlay = (open: boolean, setOpen: (open: boolean) => void): boolean => {const ownedByWidget = useContext(WidgetOverlayOwnerContext);@@ -36,8 +31,7 @@ export const useRegisterWidgetOverlay = (open: boolean, setOpen: (open: boolean)setOpening({ epoch: current, open });}const stale = ownedByWidget && open && opening.epoch !== current;- // Runs on mount and again when a hidden widget is shown; the registry is read- // live so a bump that happened while hidden counts too.+ // Read the current dismissal epoch on remount so closes issued while hidden still apply.useMountEffect(() => {if (!ownedByWidget) {return;diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsxindex ab59162466..c091aaf07f 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx@@ -29,11 +29,7 @@ import { createWorkbenchStore, type WorkbenchSnapshot, type WorkbenchInternalStointerface WorkbenchContextValue {activeProject: Project;- /**- * True once the persisted snapshot has been loaded (or found absent). Side- * effects that read or mutate the queue must wait for this, or they race the- * async hydration and act on state that is about to be replaced.- */+ /** Queue side effects must wait for hydration to avoid acting on state about to be replaced. */hasHydrated: boolean;}@@ -107,14 +103,10 @@ export const WorkbenchProvider = ({persistence,signal: owner.signal,});- // Published for the whole life of the mount, so a library surface rendered beside the editor- // mutates an open project through the sync engine rather than beside it.+ // Publish throughout the mount so sibling library surfaces mutate open projects through the sync engine.const openProjectBroker = createOpenProjectBroker({closeProject: (projectId) => {- // The last tab is not this handle's business. `close` refuses it *and* raises "at least one- // project must remain open" — correct for someone closing a tab, wrong for a deletion,- // which is not asking to keep working here. Leaving the editor is the caller's job- // (`leaveEditorIfLast`), and it is already doing it.+ // Skip close's last-tab refusal during deletion; leaveEditorIfLast owns leaving the editor.if (store.getSnapshot().projects.length > 1) {store.commands.projects.close(projectId);}@@ -123,8 +115,7 @@ export const WorkbenchProvider = ({flushProject: (projectId) => {const project = store.getSnapshot().projects.find((candidate) => candidate.id === projectId);- // A project the editor no longer holds has nothing to push, and the id is by definition- // whatever the server last acknowledged for it.+ // Unopened projects have no local edits; their ids reflect server acknowledgements.return project? persistence.flushProjectToServer(project): Promise.resolve<ProjectPushOutcome>({ documentJson: '', kind: 'acknowledged' });diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsxindex b12e4f0d95..cfdf5e542a 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsx@@ -24,13 +24,10 @@ const HydratedSessionController = ({ search }: { search: WorkbenchSearch }) => {useMountEffect(() => {if (search.new === true) {- // Arrange the fresh draft before the search is stripped, so the intent- // applies exactly once and never survives into a later navigation.+ // Apply the draft intent before stripping it from search so it runs exactly once.const intent = resolveLaunchpadIntent(search.intent);- // A named preset wins: the user picked the arrangement itself, so it- // outranks whatever arrangement an intent merely implies. The intent- // still gets to name the invocation source, which a preset cannot.+ // A named preset chooses the arrangement; intent may still choose the invocation source.if (search.preset) {commands.layout.applyPreset(search.preset);} else if (intent) {@@ -88,10 +85,7 @@ const HydratedSessionController = ({ search }: { search: WorkbenchSearch }) => {return null;};-/**- * Search changes remount the lifecycle adapter, eliminating effect-based prop- * synchronization while preserving cancellation for asynchronous hydration.- */+/** Key search-dependent hydration lifecycles to cancel stale asynchronous loads. */export const WorkbenchSessionController = ({ search }: { search: WorkbenchSearch }) => {const hasHydrated = useWorkbenchHasHydrated();diff --git a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.tsindex 91297354a4..3da395c54f 100644--- a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts+++ b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts@@ -11,8 +11,7 @@ import { submitActiveInvocation, type ActiveInvocationSubmissionRuntime } from 'import { isCanvasInvocationPreparing } from './canvasInvocationPreparation';import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';-// Generation policy now fails closed without the capability table, and a submission cannot-// happen before app boot has fetched it. Seeding it here is what the running app does.+// Seed capabilities to match app boot; submission fails closed without them.seedArchitectureCapabilities();const owner = { signal: new AbortController().signal } as AccountScope;diff --git a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.ts b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.tsindex c51f2568ea..abadcf1443 100644--- a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.ts+++ b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.ts@@ -81,9 +81,7 @@ describe('widget edit classification', () => {expect(isHighConfidenceUpscaleEdit(['futureSetting'])).toBe(true);});- // The two live in one object and read alike, but only one of them changes- // what generates. Looking at the merged prompt is not an edit; applying the- // template that produced it is.+ // Previewing merged text does not change generation intent; applying its template does.it('separates looking at a template from applying one', () => {expect(isHighConfidenceGenerateEdit(['promptTemplateViewMode'])).toBe(false);expect(isHighConfidenceGenerateEdit(['promptTemplate'])).toBe(true);diff --git a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.tsindex ee80fce708..ae8f66428e 100644--- a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts+++ b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts@@ -24,10 +24,8 @@ export const autoSwitchDestinations: Record<InvocationSourceId, ResultDestinatio};/**- * Route after a high-confidence edit on `sourceId`; identity-preserving when- * nothing changes. The destination remaps only on an actual source transition,- * so repeated edits on the same surface never re-force a manually chosen- * destination, and locks always win.+ * Only source transitions remap the destination; repeated edits preserve manual destinations, locks, and no-op+ * identity.*/export const getRouteAfterHighConfidenceEdit = (invocation: InvocationRoute,@@ -45,16 +43,10 @@ export const getRouteAfterHighConfidenceEdit = (export const getChangedValueKeys = (previous: Record<string, unknown>, patch: Record<string, unknown>): string[] =>Object.keys(patch).filter((key) => !Object.is(previous[key], patch[key]));-// Named beside the interface they belong to rather than restated here, so a-// field that is renamed or removed cannot leave a dead string behind. Which-// fields are arrangement and which are intent is a fact about `GenerateSettings`-// and reads as one there; this only asks the question.+// Derive intent fields from GenerateSettings so renamed fields cannot leave stale policy keys.const GENERATE_UI_NOISE_KEYS: ReadonlySet<string> = new Set(Object.keys(GENERATE_UI_STATE_KEYS));-// Its own list, and not a subset of the above: Upscale's values are a different-// shape that happens to share a prompt box and a batch count. It has no aspect-// lock and no templates, so naming those here would describe a widget that does-// not exist.+// Upscale owns a separate intent-field list because its settings contract differs from Generate's.const UPSCALE_UI_NOISE_KEYS: ReadonlySet<string> = new Set(['batchCount','negativePromptHeightPx',diff --git a/invokeai/frontend/webv2/src/workbench/bootWidgetPreload.ts b/invokeai/frontend/webv2/src/workbench/bootWidgetPreload.tsindex b591f0f436..5f0394a903 100644--- a/invokeai/frontend/webv2/src/workbench/bootWidgetPreload.ts+++ b/invokeai/frontend/webv2/src/workbench/bootWidgetPreload.ts@@ -5,17 +5,8 @@ import { getLayoutWidgetTypeIds } from './layoutWidgetSet';import { getWidgetHosts, warmWidgets } from './widgetRegistry';/**- * The widget implementations a boot will render are only knowable for certain- * after the project has hydrated from the backend — but that hydration fetch- * is exactly the window the network sits idle. This hint records the active- * layout's widget set so the next boot can start those chunk downloads in- * parallel with hydration instead of after it.- *- * Dedicated hint key rather than the workbench snapshot for the same reason as- * the theme hint: the snapshot is per-user on multi-user backends, and a- * preload is harmless when the signed-in user turns out to differ — unknown or- * disabled type ids are ignored, and a stale set merely warms chunks the boot- * would have fetched moments later.+ * Remember widget types in a separate boot hint so chunk downloads overlap hydration. Unknown or disabled types+ * are ignored; stale or cross-account hints only preload unused chunks.*/const BOOT_WIDGET_HINT_STORAGE_KEY = 'invokeai:v7:webv2:boot-widgets';@@ -53,12 +44,8 @@ export const writeBootWidgetHint = (typeIds: readonly WidgetTypeId[]): void => {};/**- * Starts the widget chunk downloads a boot will need, called when the editor- * route mounts — while project hydration is still in flight. Host widgets are- * known statically from the registry; panel widgets come from the last boot's- * hint, falling back to the default layout for a first run. Loads are cached- * by the implementation resource, so a wrong guess costs one idle download and- * a right one lets the shell mount without ever suspending.+ * Preload registry hosts and the hinted panel types during hydration, falling back to the default layout. The+ * implementation resource caches loads.*/export const preloadBootWidgets = (): void => {for (const widget of getWidgetHosts()) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex a890240673..7cea16741d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -55,12 +55,8 @@ export interface LayerExportGuard {}/**- * Why a guarded layer mutation declined to touch the document: the transaction- * outcomes a permit-guarded commit can hit (`busy` — another edit owns the- * document or a gesture started mid-flight; `stale` — the guarded pixels no- * longer match the live layer; `aborted` — the caller's signal fired) plus the- * command refusals its target can raise. Structural commits use the- * transaction-only {@link StructuralCommitResult}.+ * Guarded mutations can decline as busy (another edit or gesture), stale (pixels changed), aborted (caller+ * signal), or command-specific refusals. Structural commits use {@link StructuralCommitResult}.*/export type GuardedMutationRefusal =| SubsetOf<CanvasTransactionOutcome, 'aborted' | 'busy' | 'stale'>@@ -173,10 +169,9 @@ export interface CanvasDocumentCapability {captureSnapshot(): CanvasDocumentSnapshot | null;getDocument(): CanvasDocumentContractV3 | null;/**- * Counts every reducer document identity change, whatever its origin (user edits, previews,- * selection, system syncs). Unlike `documentGeneration` (raster invalidation) and the persisted- * `documentRevision` (wholesale swaps), it moves on each edit, so an edit prepared against a- * captured value can be refused as stale once anything else lands.+ * Counts every reducer document identity change, including previews, selection and syncs, to reject stale+ * prepared edits. Unlike raster `documentGeneration` or wholesale-swap `documentRevision`, it advances on each+ * edit.*/getEditRevision(): number;/** Where a new `stack` layer lands: above `aboveId` when it belongs to the stack, else the stack top. */@@ -209,11 +204,7 @@ export interface CanvasPsdExportCapability {export interface CanvasViewportCapability {getViewport(): Viewport;fitToView(): void;- /**- * Fits the document into view only the first time this engine is shown.- * Surfaces attach on every re-show of a kept-alive widget; an unconditional- * fit there would discard the user's zoom and pan.- */+ /** Fit only on first show; reattaching a kept-alive widget must preserve zoom and pan. */fitToViewOnFirstShow(): void;setBboxGrid(size: number): void;}@@ -262,11 +253,6 @@ export interface CanvasExportCapability {export type { RasterCompositeExportRequest, RasterCompositeExportResult } from './exportRasterComposite';-/**- * The canvas mutation vocabulary. Declared under `canvas-engine` (see- * `mutationContracts.ts`) and surfaced here so workbench callers reach it- * through the public API instead of the engine importing upward for it.- */export type {CanvasEditIntent,CanvasLayerBasePatch,@@ -304,12 +290,7 @@ export interface CanvasSelectionCapability {getSelectionBounds(): Rect | null;getSelectionMaskRect(): Rect | null;invertSelection(): void;- /**- * Encodes the selection's pixels on the active layer as a PNG, or `null` when- * there is nothing to copy. The engine deliberately stops at the blob: writing- * to the system clipboard is a widget-layer concern (`canvas-engine` may not- * reach `workbench/widgets`).- */+ /** Returns the active layer's selected pixels as PNG, or null if empty. The widget owns system clipboard writes. */exportSelectionBlob(): Promise<Blob | null>;/** Inserts decoded pixels as a new raster layer above the active one. */pasteImage(pixels: ImageData, center?: Vec2): NewRasterLayerResult;@@ -428,9 +409,8 @@ export interface CanvasLifecycleCapability {export type CanvasEditCapability = CanvasEditGate;/**- * The input to {@link CanvasEnginePreviewCapability.setGuardedFilterPreview}: a- * persisted filter result (decoded via the engine's `imageResolver`) and the- * document-space rect it occupies, tagged with the filter that produced it.+ * Persisted filter result for {@link CanvasEnginePreviewCapability.setGuardedFilterPreview}, decoded by+ * `imageResolver`, with its document-space rect and producing filter.*/export interface FilterPreviewInput {imageName: string;@@ -439,11 +419,8 @@ export interface FilterPreviewInput {}/**- * Result of {@link CanvasEngineLayerCapability.mergeVisibleRasterLayers}: `'merged'` when a new- * composite layer was inserted, `'not-ready'` when a contributor could not be- * rasterized consistently, `'over-budget'` when safe raster allocation was- * refused, `'busy'` when another edit owns the document, and `'nothing'` when- * fewer than two eligible rasters have content.+ * Merge result: inserted composite, inconsistent contributor raster, allocation refusal, edit contention, or fewer+ * than two eligible nonempty rasters.*/export type MergeVisibleResult =| 'merged'@@ -510,18 +487,13 @@ export interface CanvasEngineToolCapability extends CanvasToolCapability {handleEscapePriority(options: { gestureWasActive: boolean }): void;onStrokeCommitted(listener: (event: StrokeCommittedEvent) => void): () => void;/**- * Arms the eyedropper for a single sample of the composited document,- * resolving with the picked `#rrggbb` or `null` if the user cancels (Escape,- * another tool, or the engine going away). Restores the previously active- * tool either way. Backs the color picker's eyedropper button.+ * Samples the composite once as `#rrggbb`, or null on Escape, tool change or disposal. Restores the previous+ * tool on either outcome.*/requestColorSample(): Promise<string | null>;/**- * Installs the sink for eyedropper samples no one-shot request claims: the- * workbench routes them to the active foreground/background target. Without- * a router (or when it declines with false) the sample lands in the brush- * color option — the engine-standalone behavior. Returns a dispose that- * uninstalls only this router, so a stale cleanup cannot evict a newer one.+ * Routes unclaimed eyedropper samples to the active color target, falling back to brush color if absent or+ * declined. Disposal removes only this router, preserving newer registrations.*/setColorSampleRouter(router: (hex: string) => boolean): () => void;setInteractionLocked(locked: boolean): void;@@ -568,9 +540,8 @@ export interface CanvasEngineExportCapability extends CanvasExportCapability {export interface CanvasEnginePreviewCapability extends CanvasPreviewCapability {/**- * Draws a fit-to-`maxSizePx` composite of the whole document into `target`- * (sizing its backing store), for the Overview pane. Returns the drawn- * document rect, or null when no document is attached.+ * Sizes `target` and draws the whole document fitted to `maxSizePx`. Returns its drawn rect, or null without a+ * document.*/drawDocumentOverview(target: HTMLCanvasElement, maxSizePx: number): Rect | null;preloadStagedPreview(imageName: string): void;@@ -601,8 +572,6 @@ export interface CanvasEngine {readonly fonts: CanvasFontCapability;}-// Public Canvas-owned value contracts. These remain serializable and contain-// no engine implementation, mutable store, controller, or construction type.export type * from './contracts';export { CANVAS_COLOR_LABELS, CANVAS_MAX_NODE_COUNT, CANVAS_MAX_NODE_DEPTH } from './contracts';export type BooleanRasterOperation = 'intersect' | 'cutout' | 'cutaway' | 'exclude';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/color.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/color.tsindex 8ddef1befc..9bf310a45f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/color.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/color.ts@@ -1,18 +1,10 @@-/**- * Small pure color helpers shared by the engine. Zero React, zero import-time- * side effects.- */-/** Clamps a color channel to the `[0, 255]` byte range, rounding to the nearest integer. */const clampChannel = (value: number): number => Math.max(0, Math.min(255, Math.round(value)));const toHexByte = (value: number): string => clampChannel(value).toString(16).padStart(2, '0');/**- * Formats an opaque color as a lowercase `#rrggbb` CSS hex string. Channels are- * `[0, 255]`; alpha is intentionally not part of the output — brush/eraser- * options store an opaque fill color, and the color picker's own transparency- * check (`sampleDocumentColor` returning `null`) already decides whether a- * sample is pickable at all.+ * Formats [0, 255] channels as lowercase `#rrggbb`. Brush colors are opaque; `sampleDocumentColor` handles+ * unpickable transparent samples.*/export const rgbaToHex = (r: number, g: number, b: number): string => `#${toHexByte(r)}${toHexByte(g)}${toHexByte(b)}`;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.tsindex 9f1e43be9c..05928c203e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts@@ -63,16 +63,8 @@ export interface CanvasStagingAreaContract {areThumbnailsVisible: boolean;}-// ----------------------------------------------------------------------------// Canvas v3 document contracts-//-// A document holds four stack forests (raster, control, regional guidance and-// inpaint mask). Each forest is a top-first tree of leaves and pass-through-// groups. Leaves are positioned by `transform` and reference bitmaps by-// `imageName` (via `CanvasImageRef`) rather than by resolved URLs, since URLs-// are ephemeral. Groups organise leaves and gate their effective enabled,-// locked and hidden state; they carry no opacity, blend mode or transform.-// ---------------------------------------------------------------------------+// Four top-first stack forests hold raster, control, regional guidance and inpaint nodes. Leaves use transforms+// and stable image names, never ephemeral URLs. Groups gate descendant enabled, locked and hidden state.export type CanvasBlendMode =| 'normal'@@ -93,12 +85,8 @@ export type CanvasBlendMode =| 'luminosity';/**- * Stable identity for an indexed custom font face.- *- * The family and label are deliberately copied into the document alongside- * the opaque id and hash. They keep an unresolved document understandable and- * let the missing-font recovery UI offer a useful replacement without ever- * persisting the browser-only family alias used by the font runtime.+ * Stable custom-font identity. Persist family and label for unresolved-font recovery; browser-only family aliases+ * are never persisted.*/export interface CanvasTextFontRef {id: string;@@ -129,12 +117,8 @@ export type CanvasLayerSourceContract =type: 'paint';bitmap: CanvasImageRef | null;/**- * The layer-local origin of `bitmap`'s top-left pixel. Paint layers are- * content-sized: the persisted bitmap covers only the painted region, and- * this offset records where that region sits in the layer's local space- * (it can be negative). Absent (or `{ x: 0, y: 0 }`) for legacy documents- * whose paint bitmaps were document-sized at the origin — they load- * identically.+ * Bitmap origin in layer-local pixels, possibly negative. Paint bitmaps cover only content; absent or zero+ * preserves legacy document-sized bitmaps at the origin.*/offset?: { x: number; y: number };}@@ -172,11 +156,8 @@ export type CanvasLayerSourceContract =angle: number;stops: { offset: number; color: string }[];/**- * The gradient's explicit content extent (layer-local pixels). Gradient- * layers are content-sized like every other layer: the extent is set at- * creation (bbox-sized) and preserved across angle edits. Absent for legacy- * documents whose gradients were document-sized by construction — they- * default to the document dimensions on load (see `getSourceContentRect`).+ * Layer-local gradient extent, initialized from the bbox and preserved across angle edits. Legacy absence+ * defaults to document dimensions via `getSourceContentRect`.*/width?: number;height?: number;@@ -185,10 +166,7 @@ export type CanvasLayerSourceContract =* a linear ramp, or the radial center. Absent = the extent center.*/center?: { x: number; y: number };- /**- * Linear: the distance between the 0 and 1 stops; radial: the radius.- * Absent = a ramp fitted to the extent (the legacy, fixed-center look).- */+ /** Linear stop distance or radial radius; absence fits the ramp to the extent. */span?: number;};@@ -222,9 +200,8 @@ interface CanvasAdjustmentEntryBase {}/**- * One non-destructive adjustment in a raster layer's ordered stack. List order- * is application order; disabling keeps the tuned values out of every render- * without losing them. The Layers tree projects each entry as a child row.+ * Non-destructive raster adjustment, applied in list order. Disabling preserves settings while excluding it from+ * renders.*/export type CanvasAdjustmentEntry =| (CanvasAdjustmentEntryBase & { type: 'brightness-contrast'; brightness: number; contrast: number })@@ -273,23 +250,15 @@ export interface CanvasMaskContract {bitmap: CanvasImageRef | null;fill: CanvasMaskFillContract;/**- * The layer-local origin of `bitmap`'s top-left pixel. Mask layers are- * content-sized exactly like paint layers: the persisted mask bitmap covers- * only the painted region, and this offset records where that region sits in- * the layer's local space (it can be negative). Absent (or `{ x: 0, y: 0 }`)- * for legacy documents whose mask bitmaps were document-sized at the origin —- * they load identically. Mirrors {@link CanvasLayerSourceContract} `paint`.+ * Content-sized mask bitmap origin in layer-local pixels, possibly negative. Absent or zero preserves legacy+ * document-sized masks; matches {@link CanvasLayerSourceContract} paint offsets.*/offset?: { x: number; y: number };}/**- * A raster layer's attached regenerate region: the layer's OWN content alpha- * presented as a live inpaint mask ("copy to inpaint mask", non-destructively).- * Every stroke, erase, and transform of the layer updates the coverage, which- * unions into generation's inpaint mask while the layer contributes. Singleton,- * like a mask's noise modifier; absent ⇒ never added. Carries no pixels of its- * own — only the overlay fill.+ * Singleton regenerate region using the raster layer's live alpha as inpaint coverage. It follows strokes, erasure+ * and transforms, contributes while the layer does, and stores only overlay fill. Absence means never added.*/export interface CanvasLayerRegionContract {isEnabled: boolean;@@ -313,15 +282,8 @@ export interface CanvasControlLayerContract extends CanvasLayerBaseContract {withTransparencyEffect: boolean;filter?: { type: string; settings: Record<string, unknown> };/**- * Whether this layer's on-canvas preview is suppressed. DISPLAY ONLY — a- * hidden layer still affects generation exactly as it would if visible, which- * is the whole point: you can get a control map or mask overlay out of the way- * without changing the image it produces. Absent ⇒ not hidden.- *- * Only these three types carry it. For a raster layer, visibility and- * participation are the SAME fact — the raster stack IS the generation- * input — so `isEnabled` alone says everything, and a hidden-but-contributing- * raster layer is deliberately not representable.+ * Display-only visibility for overlay layers; generation is unchanged. Absence means visible. Raster layers+ * instead use `isEnabled` for both visibility and participation.*/isHidden?: boolean;}@@ -334,15 +296,8 @@ export interface CanvasRegionalGuidanceLayerContract extends CanvasLayerBaseContautoNegative: boolean;referenceImages: RegionalGuidanceReferenceImage[];/**- * Whether this layer's on-canvas preview is suppressed. DISPLAY ONLY — a- * hidden layer still affects generation exactly as it would if visible, which- * is the whole point: you can get a control map or mask overlay out of the way- * without changing the image it produces. Absent ⇒ not hidden.- *- * Only these three types carry it. For a raster layer, visibility and- * participation are the SAME fact — the raster stack IS the generation- * input — so `isEnabled` alone says everything, and a hidden-but-contributing- * raster layer is deliberately not representable.+ * Display-only visibility for overlay layers; generation is unchanged. Absence means visible. Raster layers+ * instead use `isEnabled` for both visibility and participation.*/isHidden?: boolean;}@@ -366,15 +321,8 @@ export interface CanvasInpaintMaskLayerContract extends CanvasLayerBaseContractnoise?: CanvasMaskNoiseContract;denoise?: CanvasMaskDenoiseContract;/**- * Whether this layer's on-canvas preview is suppressed. DISPLAY ONLY — a- * hidden layer still affects generation exactly as it would if visible, which- * is the whole point: you can get a control map or mask overlay out of the way- * without changing the image it produces. Absent ⇒ not hidden.- *- * Only these three types carry it. For a raster layer, visibility and- * participation are the SAME fact — the raster stack IS the generation- * input — so `isEnabled` alone says everything, and a hidden-but-contributing- * raster layer is deliberately not representable.+ * Display-only visibility for overlay layers; generation is unchanged. Absence means visible. Raster layers+ * instead use `isEnabled` for both visibility and participation.*/isHidden?: boolean;}@@ -388,13 +336,8 @@ export type CanvasLayerContract =export type CanvasLayerStackKind = CanvasLayerContract['type'];/**- * A group. It belongs to exactly one stack forest and may contain only that- * stack's leaves and groups. `isHidden` is display-only and valid only in overlay stacks, with the- * meaning the overlay leaves already give it; a raster group has no display-only hidden state.- *- * A group composites pass-through unless it carries a non-identity `adjustments` stack, which is- * valid only on RASTER-stack groups (overlay groups composite coverage, not color) and applies to- * the group's composited children before the result reaches its parent.+ * Groups contain only their own stack's nodes. `isHidden` is display-only and valid only for overlay stacks.+ * Raster-only adjustments apply to composited children before the parent; identity adjustments pass through.*/export interface CanvasGroupContract {id: string;@@ -464,12 +407,8 @@ export interface CanvasStateContractV3 {version: 3 | 4;document: CanvasDocumentContractV3;/**- * Monotonic counter bumped whenever the document is swapped wholesale- * (snapshot restore, `replaceCanvasDocument`) rather than incrementally- * edited. The document mirror treats any change to this value as a full- * document replacement (clearing engine pixel history), even when the new- * document keeps the same dimensions and reuses layer ids — the case a- * reference/dimension diff alone cannot distinguish from an ordinary edit.+ * Monotonic wholesale-replacement counter. The mirror clears pixel history whenever it changes, including+ * replacements reusing dimensions and layer ids that ordinary diffs cannot detect.*/documentRevision: number;snapshots: CanvasSnapshotContract[];diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.tsindex 143df22211..88cbc10199 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts@@ -258,8 +258,7 @@ export class PixelEditController {try {o.notifyPainted(layerId);} catch {- // The live cache already owns the accepted pixels and is dirty. A- // later render invalidation reconciles ancillary UI observers.+ // Accepted pixels are already dirty in the live cache; later invalidation reconciles UI observers.}} finally {releasePersistence();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.tsindex c5d60bcbd7..c3bd6eca90 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts@@ -108,8 +108,7 @@ describe('EditingController', () => {transform: createTransformOptions(),});- // The exposed selection records history over the created state; the- // float and a document swap reach the state itself.+ // The exposed selection records history; floats and document swaps access the underlying state.controller.selection.clear();expect(selection.clear).toHaveBeenCalledTimes(1);controller.discardSelection();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.tsindex ba99c76473..8df2095650 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts@@ -182,8 +182,7 @@ describe('FloatingSelectionController: display effects', () => {});it('bakes a display copy for a control layer with the transparency effect', () => {- // Without it the float would show the control map's raw, opaque black- // background — the effect the layer itself renders away.+ // Apply the layer effect so the float hides the control map's opaque black background.const h = createHarness({ layer: controlLayer(true) });h.controller.lift('a');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.tsindex 8037c31537..6997053ff2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts@@ -47,21 +47,9 @@ const isIdentity = (transform: LayerTransform): boolean =>transform.rotation === 0;/**- * Owns the floating-selection lifecycle: cutting selected pixels off a layer,- * holding them in flight, and either baking them back as ONE undo entry or- * putting them back untouched.- *- * **The lift is deliberately not a history entry.** Only `commit` pushes, with- * `before` = the pre-lift pixels and `after` = the post-bake pixels over the- * union of the hole and the landing region. So one undo restores the layer- * exactly, no matter how many drags happened in between — and a cancelled float- * leaves the history untouched rather than adding a pair of entries that undo- * each other.- *- * The cache is mutated on lift (the hole) but deliberately NOT marked dirty:- * persisting a holed bitmap mid-drag would upload a state the user never asked- * for, and a slow network could land it after the commit. Only `commit` marks- * dirty.+ * Lifts pixels without history or dirtying, preventing persistence of the temporary hole. Commit records pre-lift+ * and post-bake pixels across the hole/landing union as one undo entry and marks dirty. Cancellation restores+ * pixels without history.*/export class FloatingSelectionController {private float: FloatingSelection | null = null;@@ -83,11 +71,7 @@ export class FloatingSelectionController {return getDocumentLayer(document, float.layerId) ?? null;}- /**- * Cuts the selection's pixels out of `layerId` into a new float. Returns false- * when there is nothing to lift (no selection, an ineligible layer, or no- * overlap between the two).- */+ /** Lifts selected pixels; returns false for absent selection, ineligible layers or no overlap. */lift(layerId: string): boolean {if (this.disposed || this.float || !this.deps.canEdit()) {return false;@@ -136,9 +120,7 @@ export class FloatingSelectionController {this.float = {before: { data: before, rect: region },- // Baked now, not per frame: floating a control map must show the same- // darkness-dropped-out pixels the layer itself shows, never its raw- // opaque background.+ // Bake darkness dropout once so the float matches the rendered control map.display: renderLayerDisplayEffect(this.deps.backend, layer, lifted.pixels.surface),layerId,mask: { rect: mask.rect, surface: mask.surface },@@ -162,10 +144,8 @@ export class FloatingSelectionController {}/**- * Bakes the float back into its layer as one undoable entry, and carries the- * selection outline along with it. A float whose transform never moved is- * still put back (it was cut out), but without a history entry — nothing- * changed.+ * Bakes pixels and moves the selection in one undo entry. An unmoved float restores its cut pixels without+ * adding history.*/commit(): void {const float = this.float;@@ -258,10 +238,6 @@ export class FloatingSelectionController {}}- /**- * Re-places the document-space selection mask by the float's motion, so the- * marching ants end up around the pixels' new home rather than their old one.- */private moveSelectionWithFloat(layer: CanvasLayerContract,floatMatrix: ReturnType<typeof bakeMatrix>,@@ -302,8 +278,7 @@ export class FloatingSelectionController {if (this.disposed) {return;}- // A live float holds pixels that exist nowhere else; put them back rather- // than dropping them on the floor.+ // Restore the float's uniquely held pixels before disposal.this.cancel();this.disposed = true;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.tsindex e793b22134..b696632e63 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts@@ -171,12 +171,8 @@ export class LayerMutationController {if (!o.history.canRetain(historyBytes)) {return { status: 'over-budget' };}- // Durable layer sources are immutable, so their one prepared cache is used- // only for the initial insertion and can be reconstructed from the source- // on redo. Live paint/mask pixels that have not reached a durable source- // retain a separate immutable history capture and therefore need a second- // live cache. This makes the common path one full-size copy while keeping- // dirty pixels exact and every allocation inside the raster reservation.+ // Immutable durable sources rebuild caches on redo, needing one insertion copy. Unpersisted paint/mask pixels+ // need separate history and live copies; both remain within the raster reservation.const reservation = o.reserve(reserveBytes);if (reservation.status === 'over-budget') {return { status: 'over-budget' };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.tsindex c0c6742246..a337ec3df4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts@@ -228,8 +228,7 @@ export class MergeLayerController {const context = pixels.ctx;context.setTransform(1, 0, 0, 1, 0, 0);context.clearRect(0, 0, rect.width, rect.height);- // Merged pixels must reproduce the screen; a per-leaf bake cannot under- // member opacity/blending.+ // Composite the group to preserve member opacity and blending in merged pixels.const drawMerged = (target: RasterSurface['ctx'],from: number,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.tsindex 61176c6942..94a2892d8f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts@@ -17,10 +17,8 @@ import { EMPTY_STACKS } from '@workbench/canvas-engine/document/documentTree';import { captureInsertionAnchor, captureRestoreAnchor } from '@workbench/canvas-engine/document/insertionAnchors';/**- * The shared mutation substrate handed to canvas controllers: the guarded- * document-mutation protocol (the edit-concurrency surface, prepared-cache- * dispatch with reducer/mirror postconditions, layer-cache replacement install),- * plus the small set of engine services every mutating controller needs.+ * Shared guarded mutation protocol: edit permits, prepared-cache dispatch with reducer/mirror postconditions,+ * cache replacement, and required engine services.*/export interface CanvasMutationContext extends CanvasEditConcurrency {readonly history: History;@@ -65,10 +63,8 @@ export interface CanvasMutationContextDeps {}/**- * Creates the shared mutation substrate. Owns the document-edit permit epoch- * machine (subscribed to the editing-lock store until {@link dispose}) and the- * prepared-mutation dispatch postcondition protocol; everything else delegates- * to the engine through `deps`.+ * Owns edit-permit epochs and prepared-dispatch postconditions. The editing-lock subscription lasts until {@link+ * dispose}; other services delegate to `deps`.*/export const createCanvasMutationContext = (deps: CanvasMutationContextDeps@@ -117,11 +113,8 @@ export const createCanvasMutationContext = (throw new Error('Canvas document mutation was rejected');}} catch (error) {- // Store subscribers run after the reducer has accepted an action. A- // faulty observer must not strand an applied document mutation before- // its matching engine state and history are published. Preserve real- // reducer/dispatch failures by swallowing only when the exact intended- // postcondition is visible in the authoritative reducer state.+ // Ignore observer throws only when authoritative reducer state proves the exact mutation landed, so matching+ // engine state/history can publish. Preserve actual dispatch failures.if (!isApplied()) {throw error;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.tsindex 987269ca3d..c63639ef7c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts@@ -98,8 +98,7 @@ const createHarness = (options: HarnessOptions = {}) => {createLayerId: () => `new-${(nextId += 1)}`,dispatchPrepared: (action) => {dispatched.push(action);- // Mirror the reducer: apply the stack mutation to the local document so- // the controller's postconditions and later reads see the new layer.+ // Apply the local stack mutation so controller postconditions see the inserted layer.if (action.type === 'applyCanvasLayerStackMutation' && document) {let next = document.stacks;for (const insertion of action.add ?? []) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.tsindex c0c1a7d2a1..7d82c64e92 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts@@ -44,18 +44,9 @@ export interface NewRasterLayerControllerOptions {}/**- * Creates raster layers out of loose pixels, undoably.- *- * Two callers want the same thing — Paste (pixels from the system clipboard)- * and Layer via Copy (the selection's pixels lifted off the active layer) — so- * they share one guarded insert rather than growing two near-identical- * controllers. The transactional shape follows `ExtractMaskedAreaController`:- * capture a permit, build the layer, `dispatchPrepared` with reducer AND mirror- * postconditions, install the prepared cache, then push a failure-atomic history- * entry whose redo re-runs the exact same apply.- *- * The new layer is inserted directly above the active one, which is where the- * user is looking, and becomes the selection.+ * Shared undoable insertion for Paste and Layer via Copy. Acquire a permit, verify reducer/mirror postconditions,+ * install the prepared cache, then record failure-atomic history with the same redo path. Insert above and select+ * the active layer's new sibling.*/export class NewRasterLayerController {private disposed = false;@@ -81,10 +72,8 @@ export class NewRasterLayerController {this.deps.endBurst();const layerId = this.deps.createLayerId();- // Pixels are placed by the layer SOURCE offset, not the transform, so the- // layer's own transform stays identity — the same shape a paint layer takes- // after a stroke, which keeps every later edit (move, transform, float) on- // the ordinary path.+ // Place pixels with the source offset, leaving the transform at identity for ordinary move, transform and+ // float handling.const layer: CanvasLayerContract = {blendMode: 'normal',id: layerId,@@ -147,10 +136,7 @@ export class NewRasterLayerController {return { layerId, status: 'created' };}- /**- * Copies the selection's pixels off the active layer into a new layer above- * it, leaving the source untouched (Photoshop's "Layer via Copy").- */+ /** Copies selected pixels into a new layer above the active layer without changing the source. */liftSelectionToLayer(name: string, label: string): NewRasterLayerResult {const document = this.deps.getDocument();const layer = getDocumentLayer(document, document?.selectedLayerId);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.tsindex 8a643ad4ca..156caaac1b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts@@ -102,8 +102,7 @@ export class PsdExportController {if (!this.deps.isDocumentSnapshotCurrent(documentSnapshot)) {return 'stale';}- // The raster tree as it stands, minus leaves with nothing captured; the planner derives- // effective visibility from the own flags, the same way Photoshop will.+ // Omit uncaptured leaves; derive effective visibility from own flags as Photoshop does.let missing: string | null = null;// PSD cannot represent a group stack: bake enclosing stacks into each// leaf (own first, then innermost outward). Approximate under memberdiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.tsindex 1030ff4efb..433406f7d0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts@@ -249,8 +249,8 @@ export class RasterController {}releaseBitmapIfUnreferenced(imageName: string): void {- // Decoded bitmaps are lease-owned and close automatically after the final- // rasterizer releases them. Retained for callers that also update tracking.+ // Leases close decoded bitmaps after the final rasterizer releases them; this hook also supports tracking+ // callers.void imageName;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.tsindex 72d9c8b1b8..a220750f9e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts@@ -20,12 +20,8 @@ const wrapCanvasSurface = (canvas: HTMLCanvasElement): RasterSurface => {canvas.width = width;canvas.height = height;},- // This wraps the canvas ELEMENT that is mounted in the document, so it- // cannot use the swap-the-backing-store trick the offscreen surfaces use —- // the element has to stay the one the page is displaying. It copies through- // a temporary instead. Nothing calls this on the display surface (only layer- // caches grow), so the slower shape costs nothing; it is here to honour the- // contract rather than to be used.+ // The mounted canvas element must retain identity, so growth copies through a temporary surface instead of+ // swapping backing stores. Only layer caches currently grow.resizePreserving(width: number, height: number, dx: number, dy: number) {const previous = document.createElement('canvas');previous.width = canvas.width;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.tsindex 6835fd4c3b..c4a2f3e1fe 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts@@ -157,10 +157,8 @@ export class StructuralLayerController {}/**- * Live gesture previews coalesce to one dispatch per frame: sliders, color- * pickers and curve drags fire per pointer move, and every dispatch fans out- * to the whole project-state subscriber tree. `true` means accepted, not- * delivered — a lock, gesture, or dispose landing before the flush drops it.+ * Coalesce gesture previews to one dispatch per frame to limit project subscriptions. True means queued; a lock,+ * gesture or disposal before flush discards it.*/preview(action: CanvasProjectMutation): boolean {if (!this.canCommit()) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentFixtures.testStub.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentFixtures.testStub.tsindex 1a615fbfb9..8403848115 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentFixtures.testStub.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentFixtures.testStub.ts@@ -123,8 +123,8 @@ export const createLargeFlatDocument = ();/**- * `count` nodes cycling through every stack: every `fanout` leaves are wrapped in a group, and every- * `fanout` groups in another, so the tree exercises depth and ancestor-effective state.+ * Cycles `count` nodes through all stacks, grouping every `fanout` leaves and groups to exercise depth and+ * inherited state.*/export const createLargeTreeDocument = (count: number,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.tsindex 9c4398e532..67a801f297 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts@@ -803,8 +803,7 @@ describe('createDocumentModel', () => {status: 'wrong-type',});- // The reducer holds the invariant on its own: an unvalidated dispatch- // (a preview, a replay) cannot stamp a stack onto an overlay group.+ // Even unvalidated preview/replay dispatches must reject adjustment stacks on overlay groups.const rawDispatch = applyCanvasProjectMutation(project, {config: { adjustments: stack, layerType: 'group' },id: 'OG',diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.tsindex 81de16c12d..bf76fc497e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts@@ -65,10 +65,8 @@ export interface DocumentModelContext {}/**- * The pure document seam over a v3 canvas document: lookup, tree facts, semantic leaves and- * prepared edits, with no knowledge of the engine, the screen or the panel. The index is built once- * per forest identity; a leaf keeps its identity while its layer object and ancestor-effective- * state are unchanged. Ordering belongs to the returned sequences.+ * Pure document lookup, tree facts, semantic leaves and prepared edits. Indexes cache by forest identity; leaves+ * retain identity while layer and ancestor-effective state match. Returned sequences define ordering.*/export interface CanvasDocumentModel {readonly document: CanvasDocumentContractV3;@@ -1122,9 +1120,7 @@ export const createDocumentModel = (status: 'wrong-type',};}- // Opacity/blend apply to a group's isolated composite; overlay groups- // composite coverage, so the fields are meaningless there (the same rule- // as group adjustments).+ // Opacity/blend describe isolated color composites, so they are invalid for coverage-only overlay groups.if ((command.patch.opacity !== undefined || command.patch.blendMode !== undefined) && entry.stack !== 'raster') {return { operation: 'blend an overlay-stack group', status: 'unsupported' };}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticNode.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticNode.tsindex 3d8dd07a35..3b928db98f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticNode.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticNode.ts@@ -6,9 +6,8 @@ import { collectSubtreeLeaves, isGroupNode, subtreeDepth } from '@workbench/canvimport { isNodeHidden } from '@workbench/canvas-engine/document/layerEligibility';/**- * Document facts about one node, leaf or group, with its ancestors already applied: what a row,- * a toolbar or a planner may show or refuse without recomputing any rule. Nothing about the- * screen, the panel or the session.+ * Node facts with ancestor state applied, shared by rows, tools and planners without screen or session+ * dependencies.*/export interface SemanticNode {readonly id: string;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.tsindex e08a788783..f6a35f1986 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts@@ -14,10 +14,8 @@ import { createBitmapStore, DEFAULT_FAILURE_BACKOFF_MS } from './bitmapStore';const LAYER = 'layer-1';/**- * A manual, fully-controlled timer stub for the ambient-failure tests: jobs- * queue up (recording their requested delay) and only run when explicitly- * fired via `fireNext`, so a test can assert the exact reschedule delay at- * each step without depending on fake-timer advancement matching it.+ * Timers record delays and run only through `fireNext`, allowing exact ambient retry assertions without fake-clock+ * advancement.*/interface ManualTimers extends BitmapStoreTimers {/** Every delay ever passed to `setTimeout`, in call order. */@@ -229,8 +227,6 @@ describe('createBitmapStore', () => {it('dispatches a same-hash re-flush when the offset changed (pure-translation persistence)', async () => {const h = createHarness({ offset: { x: 0, y: 0 } });- // First flush: paint pixels at the origin → uploads img-0, document now- // points at { imageName: 'img-0', offset: { x: 0, y: 0 } }.h.store.markLayerDirty(LAYER);await vi.advanceTimersByTimeAsync(1500);await h.store.flushPendingUploads();@@ -268,8 +264,6 @@ describe('createBitmapStore', () => {source: { bitmap: { imageName: 'img-0' }, offset: { x: 40, y: 25 }, type: 'paint' },type: 'updateCanvasLayerSource',});- // The encoded blob covers only the content-sized surface (10×10 stub), so a- // reload rasterizes those pixels at the persisted offset.expect(h.encodeSurface).toHaveBeenCalledWith(expect.objectContaining({ height: 10, width: 10 }));h.store.dispose();});@@ -297,8 +291,7 @@ describe('createBitmapStore', () => {await vi.advanceTimersByTimeAsync(1500);await store.flushPendingUploads();- // The engine-provided seam receives the ref + offset; the default paint-source- // dispatch is NOT used (the engine picks updateCanvasLayerConfig for masks).+ // The engine receives ref and offset and chooses mask actions; default paint dispatch must remain unused.expect(dispatchBitmap).toHaveBeenCalledTimes(1);expect(dispatchBitmap).toHaveBeenCalledWith('mask1', expect.objectContaining({ imageName: 'mask-img' }), {x: 7,@@ -487,8 +480,6 @@ describe('createBitmapStore', () => {await h.store.flushPendingUploads();expect(h.uploadImage).toHaveBeenCalledTimes(2);- // Undo restores state A's pixels in the cache; the engine re-marks the layer- // dirty. The re-flush re-hashes to img-0's content and reuses it — NO upload.h.setEncoded('pixels-A');h.store.markLayerDirty(LAYER);await vi.advanceTimersByTimeAsync(1500);@@ -585,8 +576,7 @@ describe('createBitmapStore', () => {settled = true;});- // Encode/hash have run and the upload is in flight, but it hasn't resolved.- // Drain the encode→hash microtask chain (several awaits) without resolving.+ // Drain encode/hash awaits while leaving the upload unresolved.for (let i = 0; i < 5; i += 1) {await Promise.resolve();}@@ -752,14 +742,10 @@ describe('createBitmapStore', () => {expect(uploadImage).toHaveBeenCalledTimes(1);expect(settled).toBe(false);- // A fresh stroke lands mid-flight: new pixels re-dirty the layer while the- // stale upload is still pending.h.setEncoded('pixels-B');h.store.markLayerDirty(LAYER);- // The stale upload resolves. The barrier must NOT settle yet: the layer- // was re-dirtied by a newer stroke during the await, so it owes a follow-up- // flush of the newer pixels before the "latest painted pixels" guarantee holds.+ // The barrier must flush the newer stroke before settling, despite completion of the stale upload.deferreds[0].resolve({ height: 10, imageName: 'img-old', width: 10 });await drainUntil(() => uploadImage.mock.calls.length >= 2);expect(uploadImage).toHaveBeenCalledTimes(2);@@ -787,9 +773,7 @@ describe('createBitmapStore', () => {debounceMs: 1500,dispatch,encodeSurface: () => Promise.resolve(new Blob(['pixels'], { type: 'image/png' })),- // A fixed 1500ms ambient retry delay, unrelated to this test's subject- // (the barrier's own anti-spin): the growing-backoff schedule is covered- // by the dedicated 'ambient failure handling' tests below.+ // Fix ambient retries at 1500ms to isolate barrier anti-spin; dedicated tests cover backoff.failureBackoffMs: [1500],getLayerSource: () => PAINT_SOURCE,getLayerSurface: () => ({ offset: { x: 0, y: 0 }, surface }),@@ -804,16 +788,11 @@ describe('createBitmapStore', () => {store.markLayerDirty(LAYER);await expect(store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');- // The internal retry cap (maxUploadAttempts) bounds a single flush's own- // attempts. The barrier must not loop back and re-attempt a layer whose- // flush already FAILED this call, so the total stays at that cap instead- // of growing with extra barrier iterations (no spin).+ // A barrier must not retry a flush already failed in this call beyond `maxUploadAttempts`.expect(uploadImage).toHaveBeenCalledTimes(2);expect(dispatch).not.toHaveBeenCalled();expect(onError).toHaveBeenCalledTimes(1);- // The layer is still dirty (deferred, not dropped): a later ambient retry- // (at the fixed backoff configured above) fires it again.await vi.advanceTimersByTimeAsync(1500);expect(uploadImage.mock.calls.length).toBeGreaterThan(2);@@ -859,14 +838,11 @@ describe('createBitmapStore', () => {const applied = h.dispatch.mock.calls[0][0] as Extract<CanvasProjectMutation, { type: 'updateCanvasLayerSource' }>;expect(h.store.isSelfEcho(LAYER, applied.source)).toBe(true);- // A wholesale document replacement drops the outgoing document's self-echo- // bookkeeping (a reused layer id must not inherit it).+ // Wholesale replacement must discard self-echo state before layer ids are reused.h.store.reset();expect(h.store.isSelfEcho(LAYER, applied.source)).toBe(false);- // Re-persisting identical pixels now dispatches again: the content-hash- // dedupe reuses the already-uploaded image (no new upload), but the stale- // self-echo no longer suppresses the dispatch, so the contract converges.+ // Hash dedupe reuses the upload, but cleared self-echo state permits the dispatch needed to converge.h.store.markLayerDirty(LAYER);await vi.advanceTimersByTimeAsync(1500);await h.store.flushPendingUploads();@@ -1128,10 +1104,8 @@ describe('createBitmapStore', () => {const h = createHarness();h.store.markLayerDirty(LAYER);- // The layer converted back to a parametric source (e.g. rasterize → undo)- // before the debounce window elapsed — the cache surface still resolves- // (a source swap doesn't clear it), so only this guard prevents a stale- // paint dispatch.+ // Source swaps preserve cache surfaces; the guard must stop delayed paint persistence from overwriting a+ // restored parametric source.h.setSource({fill: '#ff0000',height: 40,@@ -1185,8 +1159,6 @@ describe('createBitmapStore', () => {h.store.markLayerDirty(LAYER);const barrier = h.store.flushPendingUploads();- // Encode/hash/upload have started (passing the entry-time guard while the- // source was still `paint`); the upload is now in flight.await drainUntil(() => uploadImage.mock.calls.length >= 1);expect(uploadImage).toHaveBeenCalledTimes(1);@@ -1318,10 +1290,8 @@ describe('createBitmapStore', () => {expect(uploadImage).toHaveBeenCalledTimes(3);expect(onError).toHaveBeenCalledTimes(2);- // flushPendingUploads() runs before every Generate/export and on- // blur/pagehide/visibilitychange; it still attempts a circuit-open layer- // (the breaker only gates the AMBIENT reschedule), so a persistently- // failing layer must not re-report on every one of those barrier retries.+ // Explicit persistence barriers bypass the ambient breaker, but repeated failure must not repeatedly report+ // the same streak.await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');@@ -1392,9 +1362,7 @@ describe('createBitmapStore', () => {await expect(store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');expect(onError).not.toHaveBeenCalled();- // A real upload failure lands mid-streak (position 3 of a 5-max streak):- // under the old `failures === 1 || failures === max` check this matched- // neither condition and would have gone unreported.+ // A real failure midway through a decline streak must still be reported.content = 'pixels-B';uploadShouldFail = true;await expect(store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');@@ -1456,9 +1424,7 @@ describe('createBitmapStore', () => {expect(timers.pendingCount()).toBe(0);- // A fresh stroke closes the circuit: it schedules again at the base- // debounce (not a backoff delay), and the now-succeeding upload clears- // everything.+ // A fresh stroke resets to base debounce; successful upload clears the failure streak.shouldFail = false;h.store.markLayerDirty(LAYER);expect(timers.scheduledDelays.at(-1)).toBe(1500);@@ -1494,8 +1460,6 @@ describe('createBitmapStore', () => {timers.fireNext(); // succeeds → clears the failure count.await drainUntil(() => h.dispatch.mock.calls.length === 1);- // A later failure, on fresh pixels, is a new streak (consecutiveFailures:- // 1), not a continuation of the earlier one.shouldFail = true;h.setEncoded('pixels-B');h.store.markLayerDirty(LAYER);@@ -1768,8 +1732,7 @@ describe('truthful extent: trimming and clearing', () => {await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');expect(h.trimLayerPixels).toHaveBeenCalledTimes(2);- // Both attempts advance the shared breaker; only the streak's first failure- // is reported (the second is a silent continuation, not a fresh problem).+ // Both failures advance the shared breaker; report only the streak's first failure.expect(onError).toHaveBeenCalledTimes(1);expect(onError).toHaveBeenNthCalledWith(1, error, LAYER, { consecutiveFailures: 1, willRetry: true });expect(h.encodeSurface).not.toHaveBeenCalled();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.tsindex bf35661b3b..2764ec0ed8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts@@ -1,36 +1,10 @@/**- * Paint persistence via content-hashed server images.+ * Content-hashed paint persistence: debounce dirty layers, encode PNG, dedupe uploads, and swap the bitmap ref+ * only on success. Failures leave pixels dirty. Self-echo detection avoids rerasterizing accepted pixels.*- * 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.- *- * 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.- * - **Truthful extent**: the persisted bitmap's dimensions become the layer's- * content rect, which draws the move outline, frames the transform tool and- * drives fit-to-content. The cache only ever grows, so each flush first trims- * it to its visible pixels ({@link BitmapStoreDeps.trimLayerPixels}); a layer- * left with none is cleared to `{ bitmap: null }` rather than uploading a- * transparent PNG whose dimensions would keep reporting a phantom rect.- *- * Every side effect is injectable, so this runs in node tests. Zero React.+ * Recheck source type before trim and after awaits because cache surfaces survive source changes. Compare dispatch+ * dedupe against the current document, not remembered refs. Trim to visible pixels before encoding; clear empty+ * bitmaps so content bounds remain truthful.*/import type { CanvasImageRef, CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';@@ -75,21 +49,13 @@ export interface BitmapStoreTimers {/** Dependencies for {@link createBitmapStore}. */export interface BitmapStoreDeps {/**- * Returns a layer's live cache surface (its painted pixels) plus the layer-local- * `offset` its top-left pixel sits at (its content rect origin), or `null` when- * the cache is gone/empty. The surface is CONTENT-SIZED, so the encoded PNG- * covers only the painted region and the dispatched paint source carries the- * offset (loading rasterizes at it). Read atomically here so the encoded pixels- * and the offset always agree.+ * Atomically reads the content-sized cache surface and layer-local offset, or null when absent. Encoding and+ * persisted placement must describe the same pixels.*/getLayerSurface(layerId: string): { surface: RasterSurface; offset: { x: number; y: number } } | null;/**- * Returns a layer's CURRENT document source, or `null` if the layer no- * longer exists. Used to guard a flush against a source-type change that- * happened AFTER the dirty mark was recorded — e.g. rasterize (paint) →- * undo (back to shape/gradient) — where the layer's cache surface still- * resolves (it isn't cleared by the source swap) but persisting it would- * dispatch stale paint pixels over a now-parametric layer.+ * Reads the current source to prevent an old dirty mark from persisting surviving cache pixels over a layer+ * converted away from paint.*/getLayerSource(layerId: string): CanvasLayerSourceContract | null;/**@@ -105,27 +71,18 @@ export interface BitmapStoreDeps {/** Dispatches to the reducer (the single swap-on-success `updateCanvasLayerSource`). */dispatch(action: CanvasProjectMutation): boolean;/**- * Applies the persisted bitmap ref + offset to the layer's document contract,- * as the single swap-on-success dispatch. Lets the engine pick the right- * action per layer type — `updateCanvasLayerSource` (paint source) for raster/- * control layers, `updateCanvasLayerConfig` (mask) for inpaint/regional masks —- * while the store stays type-agnostic. Absent ⇒ the default paint-source- * dispatch (used by the store's own tests, which only exercise paint layers).+ * Swap-on-success bitmap/offset dispatch. The engine chooses paint-source versus mask-config actions; absence+ * uses the paint-source default.*/dispatchBitmap?(layerId: string, bitmap: CanvasImageRef, offset: { x: number; y: number }): boolean;/**- * Trims a layer's cache to its visible pixels (see **Truthful extent** above).- * Called after the source-type guard and BEFORE `getLayerSurface`, so this flush- * reads the trimmed surface and offset. A `'deferred'` result leaves the layer- * dirty without encoding; a barrier waits and retries until ownership is released.- * Absent ⇒ `'kept'` ⇒ no trimming.+ * Trim visible bounds before reading the surface. Deferred trims stay dirty; barriers retry until ownership+ * releases. Absence behaves as kept.*/trimLayerPixels?(layerId: string): PaintCacheTrim;/**- * Clears a layer's bitmap ref, for a layer the trim found empty. Returns whether- * the layer accepted it, like {@link dispatchBitmap}. Kept separate from that- * rather than widening it to a nullable ref: there is no offset to carry, and a- * mask must clear `mask.bitmap` while preserving its `fill`.+ * Clears empty bitmap refs and reports acceptance like {@link dispatchBitmap}. Separate dispatch preserves mask+ * fill and needs no offset.*/clearBitmap?(layerId: string): boolean;/** Content-hashes a blob (defaults to SHA-256 hex via `@platform/browser/sha256`). */@@ -147,10 +104,8 @@ export interface BitmapStoreDeps {/** Injectable delay used for retry backoff (default: `timers.setTimeout`). */sleep?(ms: number): Promise<void>;/**- * Reports a persistent flush/upload failure. Called on the FIRST failure of a- * streak and again when the circuit opens; intermediate retries are silent, so- * a persistently failing layer surfaces one report, not one every retry cycle.- * Omitted callbacks leave the failure unreported.+ * Reports the first failure and circuit opening in a streak; intermediate retries stay silent. Optional+ * callback.*/onError?(error: unknown, layerId: string, info: { consecutiveFailures: number; willRetry: boolean }): void;}@@ -173,24 +128,13 @@ export interface BitmapStore {/** Flushes every dirty layer immediately and resolves once all in-flight uploads settle. */flushPendingUploads(): Promise<void>;/**- * True when `source` is exactly the paint bitmap ref this store most recently- * applied to `layerId` — i.e. the engine is seeing its own dispatch round-trip- * and must NOT re-rasterize/invalidate the cache (the pixels already match).- * A different bitmap (undo/import) returns `false` and re-rasterizes as usual.- *- * A clear (`bitmap: null`) is deliberately never an echo: re-rasterizing a- * bitmap-less paint source collapses the cache to a zero rect, which is exactly- * the reconciliation a cleared layer needs.+ * Detects the most recently applied paint ref so the engine skips self-echo rasterization. Different refs+ * rerasterize. Null is never an echo: clearing must collapse cache bounds.*/isSelfEcho(layerId: string, source: CanvasLayerSourceContract | null): boolean;/**- * Drops the persistence bookkeeping that describes the OUTGOING document, for- * use on a wholesale document replacement. Clears the `lastApplied` self-echo- * map (a reused layer id in the new document could otherwise have a legit- * persistence dispatch suppressed forever) and any pending dirty/debounced- * work for the old document. The content-hash dedupe cache is intentionally- * kept — it is a pure content-addressed mapping (identical PNG bytes → the- * same immutable uploaded image) and so is never stale across documents.+ * Drops outgoing-document dirty work and self-echo state so reused ids cannot suppress dispatches. Retains+ * content-hash dedupe because identical bytes name immutable images across documents.*/reset(): void;/** Cancels all timers; in-flight uploads are left to settle (no dispatch after dispose). */@@ -230,12 +174,8 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {/** Layers awaiting a flush (either debounced or re-dirtied during a flush). */const dirty = new Set<string>();/**- * Why a layer is currently in `dirty`: `'stroke'` means a new paint stroke- * (re)marked it — worth retrying inside a barrier call; `'failure'` means- * its last flush attempt failed, and `'deferred'` means another operation still- * owns the pixels. Failures are not retried again within the same- * {@link flushPendingUploads} call (anti-spin); deferrals are polled until the- * owner releases the pixels. A new stroke flips either back to `'stroke'`.+ * Dirty reasons: new strokes may retry within a barrier; failures may not, preventing spin; deferred pixel+ * ownership is polled until released. A new stroke resets either reason.*/const dirtyReason = new Map<string, 'deferred' | 'failure' | 'stroke'>();/** Active debounce timers, keyed by layer id. */@@ -244,12 +184,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {const inFlight = new Map<string, Promise<void>>();/** Consecutive ambient flush failures per layer; cleared on success or a fresh stroke. */const failureCounts = new Map<string, number>();- /**- * Layer ids whose CURRENT failure streak has already produced one report.- * Cleared everywhere `failureCounts` is cleared, so a fresh streak (a new- * stroke, or a streak that closed via a successful flush) reports its own- * first failure again.- */+ /** Tracks reported failure streaks; clearing with `failureCounts` lets the next streak report again. */const reportedStreaks = new Set<string>();/** Content-hash → uploaded image, an LRU-ish dedupe cache (bounded). */const hashToImage = new Map<string, CanvasImageUploadResult>();@@ -355,20 +290,9 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {};/**- * 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.- *- * 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 commits BEFORE `reportError`, because an observer may call back- * into this store and its outcome must be the final word.+ * Throws and declined dispatches share backoff and circuit accounting. Report the first non-silent failure and+ * always report circuit opening, including silent declines. Commit bookkeeping before notifying observers, whose+ * reentrant changes must win.*/const recordFlushFailure = (layerId: string, error: unknown, options: { silent: boolean }): void => {const failures = (failureCounts.get(layerId) ?? 0) + 1;@@ -388,10 +312,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {}};- /**- * Clears a layer's bitmap ref, for a layer the trim found empty. Synchronous- * throughout, so no generation re-check is needed before the dispatch.- */+ /** Clears empty bitmap refs synchronously, requiring no generation recheck. */const clearLayerBitmap = (layerId: string, requeueFailure: (error: unknown) => void): void => {// Drop the self-echo entry on every path: the trim established that the live// cache no longer matches the last bitmap this store dispatched, including@@ -432,10 +353,8 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {return;}if (accepted !== true && deps.getLayerSource(layerId) !== null) {- // As with a declined bitmap dispatch: not a network error worth a toast of- // its own, but it still advances (and can open) the shared breaker. The- // clear stays pending, so the next flush re-attempts it even though the- // trim has already collapsed the cache.+ // Declined clears advance the shared breaker without a network-error toast. Keep the clear pending even+ // after trim collapses the cache.recordFlushFailure(layerId, new Error('Bitmap clear was not accepted.'), { silent: true });return;}@@ -456,16 +375,8 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {}recordFlushFailure(layerId, error, { silent: false });};- // Source-type guard (see `getLayerSource` doc): the dirty mark may predate- // a conversion away from `paint` (rasterize → undo is the motivating case,- // but any convert-back qualifies). The cache surface survives a source swap,- // so without this check we'd encode and dispatch a `paint` source over a layer- // that is no longer paint at all. Drop the pending flush entirely: nothing- // about this dirty mark is still valid, and a future genuine paint stroke will- // re-mark it if the layer ever becomes a paint layer again.- //- // Also before the TRIM: shrinking a cache that now backs a parametric render- // would break the compositor's cache-rect-equals-content-rect invariant.+ // Reject obsolete dirty work before trim if the source is no longer paint. Cache surfaces survive conversion;+ // trimming or persisting them would corrupt parametric content bounds or source state.const sourceAtEntry = deps.getLayerSource(layerId);if (!sourceAtEntry || sourceAtEntry.type !== 'paint') {pendingClears.delete(layerId);@@ -473,8 +384,6 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {clearTimer(layerId);return;}- // Truthful extent (see the header). `getLayerSurface` below re-reads the cache,- // so it picks up the trimmed surface and origin with no further work.let trimResult: PaintCacheTrim = 'kept';try {trimResult = deps.trimLayerPixels?.(layerId) ?? 'kept';@@ -510,10 +419,8 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {clearTimer(layerId);return;}- // Capture the surface AND its offset together at encode time so they agree:- // encode reads these pixels, and the dispatch below carries this offset. A- // growth during the async encode window re-marks the layer (its stroke marks- // it dirty), so a follow-up flush re-converges with the current rect + offset.+ // Capture surface and offset atomically for encoding. Growth during awaits marks dirty again, so a follow-up+ // flush converges placement.const { offset, surface } = placed;// Consume the dirty flag up front; a failure re-adds it below. A stroke that// lands mid-flush re-marks the layer, so the finally handler re-schedules.@@ -548,8 +455,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {}result = uploaded;} catch (error) {- // Swap-on-success: never dispatch on failure. The old ref stays valid- // and the layer stays dirty for a later retry.+ // Dispatch only on success; failed uploads retain the old ref and dirty state.requeueFailure(error);return;}@@ -559,26 +465,14 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {if (!isCurrentGeneration()) {return;}- // Re-check the source right before dispatching: `encodeSurface`/`hashBlob`/- // `uploadImage` above all awaited, so a source-type change (rasterize →- // undo) landing DURING that window would slip past the entry-time- // `sourceAtEntry` check otherwise. This is the final gate before the- // side-effecting dispatch.+ // Recheck source type after encode/hash/upload awaits before dispatching, preventing overwrite of a newly+ // restored parametric source.const sourceNow = deps.getLayerSource(layerId);if (!sourceNow || sourceNow.type !== 'paint') {return;}- // The document already points at this image, so skip the dispatch and its- // self-echo round-trip.- //- // 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 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.+ // Skip only when the current document matches both bitmap and offset. Remembered refs survive source round+ // trips, and byte-identical translations still need their new offset persisted.const currentOffset = sourceNow.bitmap ? (sourceNow.offset ?? { x: 0, y: 0 }) : null;if (sourceNow.bitmap?.imageName === result.imageName &&@@ -622,9 +516,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {authoritativeOffset?.x === offset.x &&authoritativeOffset.y === offset.y;if (didLand) {- // The dispatch's THROW was ancillary (e.g. a subscriber failing after- // commit): the bitmap itself landed, so this attempt succeeded — close- // the ambient breaker the same as a clean accept.+ // The bitmap landed despite an observer throw; treat it as accepted and close the breaker.failureCounts.delete(layerId);reportedStreaks.delete(layerId);return;@@ -644,10 +536,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {}return;}- // The upload+dispatch that may have been failing repeatedly just- // succeeded: close the ambient breaker so a later failure is reported- // (and backed off) as a fresh streak, not a silent continuation of one- // already surfaced.+ // Successful persistence closes the breaker so later failures start a new reported streak.failureCounts.delete(layerId);reportedStreaks.delete(layerId);};@@ -663,12 +552,9 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {}const op = flushLayer(layerId).finally(() => {inFlight.delete(layerId);- // Re-dirtied during the flush (new stroke), deferred by an operation that- // still owns the pixels, or a failure re-queued it.if (dirty.has(layerId) && !disposed && !isSuspended(layerId)) {if (dirtyReason.get(layerId) !== 'failure') {- // `'stroke'` and `'deferred'` both re-poll on the ordinary debounce;- // a deferral is transient and costs only the trim's busy check.+ // Strokes and deferred ownership retry at ordinary debounce; a deferral only checks trim ownership.scheduleFlush(layerId);} else {const failures = failureCounts.get(layerId) ?? 0;@@ -693,8 +579,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {if (disposed) {return;}- // A fresh stroke closes the circuit: whatever was failing about the old- // pixels no longer applies to the ones about to be persisted.+ // A fresh stroke closes the circuit and retries the new pixels.failureCounts.delete(layerId);reportedStreaks.delete(layerId);pendingClears.delete(layerId);@@ -769,14 +654,8 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {const MAX_BARRIER_ITERATIONS = 10_000;const flushPendingUploads = async (): Promise<void> => {- // Immediately flush every currently-dirty layer (cancelling its debounce),- // then await the in-flight ops — looping so a layer re-dirtied by a NEW- // stroke that lands while its upload is in flight gets a follow-up flush- // before the barrier resolves (the "document points at the latest painted- // pixels" guarantee). A layer whose flush FAILED within this barrier call is- // not retried again this call. A transient DEFERRED layer is different: the- // barrier polls until the operation owning its pixels releases them, matching- // suspension semantics instead of surfacing a false persistence failure.+ // Flush dirty layers and await in-flight work until newer strokes also persist. Do not retry failures within+ // this barrier; poll deferred ownership until pixels are released.const blockedThisBarrier = new Set<string>();for (let iteration = 0; iteration < MAX_BARRIER_ITERATIONS; iteration += 1) {const toFlush = Array.from(dirty).filter((layerId) => !blockedThisBarrier.has(layerId) && !isSuspended(layerId));@@ -841,8 +720,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {pendingClears.clear();suspensions.clear();notifySuspensionWaiters();- // The self-echo map is per-(old)document; a reused layer id in the new- // document must not inherit it. `hashToImage` is content-addressed and kept.+ // Clear per-document self-echo state before ids are reused; retain content-addressed `hashToImage`.lastApplied.clear();// Same reasoning as `lastApplied`: a reused layer id in the new document// must start with a closed circuit, not inherit the old document's streak.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.tsindex fce65b8b97..df036326b7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts@@ -27,10 +27,7 @@ export interface CanvasNodeEntry {readonly ancestorsHidden: boolean;}-/**- * The per-forest index shared by the reducer, the mirror and the document model. It is keyed on- * the `stacks` object, which the reducer preserves across selection, bbox and geometry-only edits.- */+/** Shared forest index keyed by `stacks`, whose identity survives selection, bbox and geometry-only edits. */export interface CanvasDocumentIndex {readonly stacks: CanvasStackForests;readonly byId: ReadonlyMap<string, CanvasNodeEntry>;@@ -123,9 +120,8 @@ class LayeredEntryMap implements ReadonlyMap<string, CanvasNodeEntry> {}/**- * An index that extends a source index by the entries a value edit replaced; the rest reads through.- * Chains read through their predecessors; every ninth derivation flattens onto the plain root so- * lookups stay bounded and nothing older than the root is retained.+ * Value-edit overlay index with predecessor read-through. Every ninth derivation flattens onto the plain root to+ * bound lookup depth and retention.*/class DerivedIndex implements CanvasDocumentIndex {readonly byId: ReadonlyMap<string, CanvasNodeEntry>;@@ -195,10 +191,7 @@ const derivationDepth = (index: CanvasDocumentIndex): number => {return depth;};-/**- * Folds a chain onto its plain root: one override layer holding the newest entry of every id the- * chain touched. Once overrides cover too much of the root, a plain index is cheaper than the layer.- */+/** Flatten newest overrides onto the plain root; rebuild a plain index when override coverage becomes too large. */const flatten = (index: DerivedIndex): CanvasDocumentIndex => {const overrides = new Map<string, CanvasNodeEntry>();let leafChanged = false;@@ -282,12 +275,9 @@ const flagsChanged = (previous: CanvasNodeContract, next: CanvasNodeContract): b(previous.isHidden === true) !== (next.isHidden === true));/**- * Registers the index of `nextStacks` as a derivation of `previousStacks`' index after a value edit- * that rewrote exactly the nodes in `changed` (and, through structural sharing, their ancestors).- * Structure is untouched, so every entry keeps its place; only the replaced nodes, their ancestors,- * and the subtree under a group whose flags changed get new entries. Everything else reads through- * to the previous index, so the cost is the changed paths, never the document. Returns `null` when- * no previous index exists or the edit was not a value edit, leaving the next lookup to build.+ * Derives an index after value-only edits, replacing changed nodes, ancestors and descendants affected by group+ * flags. Unchanged entries read through. Returns null without a prior index or when structure changed, deferring a+ * full build.*/export const deriveIndexForValueEdit = (previousStacks: CanvasStackForests,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.tsindex 95645149ff..8cb4cfe493 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts@@ -105,8 +105,7 @@ describe('createDocumentMirror: selection changes', () => {});it('reports a selection-only change without reporting a layer change', () => {- // A selection-only edit produces a new `document` object that reuses the- // `layers` array reference — none of the other callbacks can see it.+ // Selection-only edits replace the document but reuse layers; other callbacks cannot detect them.const a = rasterLayer('a');const b = rasterLayer('b');const doc = makeDoc([a, b], { selectedLayerId: 'a' });@@ -202,9 +201,7 @@ describe('createDocumentMirror', () => {const callbacks = spyCallbacks();createDocumentMirror(store, 'p1', callbacks);- // Replace only layer `a` (new object), keep `b` identity. A prop-only edit- // (like the reducer's `updateCanvasLayer`) keeps the `source` reference, so- // the id is reported as changed but NOT source-changed.+ // Only `a` changes identity; preserved source references mean changed but not source-changed.const nextDoc: CanvasDocumentContractV3 = { ...doc, stacks: stacksFrom([{ ...a, opacity: 0.5 }, b]) };store.setState({ projects: [{ canvas: { ...canvas, document: nextDoc }, id: 'p1' }] });@@ -222,9 +219,7 @@ describe('createDocumentMirror', () => {const callbacks = spyCallbacks();createDocumentMirror(store, 'p1', callbacks);- // Prop-only edit (opacity): spreading the prior layer preserves its `source`- // reference exactly as the reducer does, so the engine must NOT re-rasterize- // (which would clear an unflushed paint layer).+ // Opacity changes preserve source identity; rerasterization would erase unflushed paint.const opacityEdit: CanvasDocumentContractV3 = { ...doc, stacks: stacksFrom([{ ...a, opacity: 0.5 }]) };store.setState({ projects: [{ canvas: { ...canvas, document: opacityEdit }, id: 'p1' }] });expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], []);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.tsindex 4551414ced..663404d954 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts@@ -18,12 +18,9 @@ export interface DocumentMirrorStore {/** Callbacks fired when the mirrored document changes. */export interface DocumentMirrorCallbacks {/**- * One or more leaves were added, removed, replaced, or had their effective state changed by an- * ancestor (the `changed` ids). `sourceChanged` is the subset whose rasterization source- * (`source` for raster/control layers, `mask.bitmap` for guidance/mask layers) changed, plus any- * newly added leaf: the leaves whose cached pixels are now stale. A property, transform, or- * ancestor-flag change reports the id in `changed` but not in `sourceChanged`, so the engine- * keeps its raster cache.+ * Reports leaf or ancestor-effective changes. `sourceChanged` contains added leaves and changed raster/control+ * sources or mask bitmaps whose caches are stale. Property, transform and ancestor-flag changes retain cached+ * pixels.*/onLayersChanged(changed: string[], sourceChanged: string[]): void;/**@@ -41,10 +38,8 @@ export interface DocumentMirrorCallbacks {/** The staging area changed. */onStagingChanged(): void;/**- * The document's `selectedLayerId` changed. A selection-only edit produces a new `document`- * object with the same `stacks` reference and an equal `bbox`, so none of the other callbacks- * fire for it. The engine uses it to repaint selection-derived chrome and to close per-layer- * transient sessions, since the layer panel is the sole authority on which node is active.+ * Selection-only changes reuse stacks and bbox, requiring a separate callback for selection chrome and per-layer+ * session cleanup.*/onSelectionChanged?(selectedLayerId: string | null): void;}@@ -65,12 +60,8 @@ const bboxEqual = (a: Bbox, b: Bbox): boolean =>a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;/**- * The reference whose change requires re-rasterizing a leaf's cache: the `source` for- * raster/control layers, the mask's `bitmap` for guidance/mask layers. The reducer preserves this- * reference across a property-only edit, so comparing it distinguishes a genuine source swap from- * an opacity/blend/lock/visibility/rename/nudge tweak. For masks the reference is the bitmap, not- * the whole `mask`: the cache holds only the alpha stencil, so a fill-only change must not clear- * unflushed strokes that live only in the cache.+ * Raster invalidation identity is raster/control `source` or mask `bitmap`. Property edits preserve it; mask fill+ * changes must preserve unflushed alpha-cache strokes.*/const rasterSourceRef = (layer: CanvasLayerContract): unknown =>layer.type === 'raster' || layer.type === 'control' ? layer.source : layer.mask.bitmap;@@ -87,9 +78,8 @@ interface ForestDiff {}/**- * Diffs two forests by leaf identity and ancestor-effective state. A leaf whose object is unchanged- * but whose ancestors now enable, lock or hide it differently is reported as changed, because its- * rendered contribution changed even though nothing about it did.+ * Diffs leaf identity and ancestor-effective enabled, locked and hidden state, including unchanged leaves affected+ * by ancestors.*/const diffForests = (prev: CanvasDocumentIndex, next: CanvasDocumentIndex): ForestDiff => {const changed = new Set<string>();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.tsindex bdea6b27c1..31163afe36 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts@@ -116,9 +116,8 @@ export const replaceChildren = (};/**- * Rewrites every node named by `updates` in place, sharing every untouched node. Groups are- * rebuilt only along the paths to a changed node; the same forests come back when nothing changed.- * `changed` holds the nodes an update actually replaced, keyed by id.+ * Rewrites named nodes with structural sharing along changed paths. Returns the same forests if unchanged;+ * `changed` records replaced nodes by id.*/export const updateNodesTracked = (stacks: CanvasStackForests,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.test.tsindex c81cbf790e..2c23dba66a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.test.ts@@ -49,9 +49,7 @@ describe('a layer that is gone', () => {['transform', { hasTransformSession: true }, 'cancelTransformSession'],['text-edit', { hasTextEditSession: true }, 'cancelTextEditSession'],])('tears down an open %s session belonging to it', (_label, session, field) => {- // A session outlives individual gestures, so it can outlive its own layer —- // deleted from the layers panel, or undone — and must not be left pointing- // at an id that no longer exists.+ // Sessions outlive gestures; removing their layer must clear the retained id.expect(decide({ layer: undefined, ...session })).toMatchObject({ [field]: true });});@@ -69,9 +67,7 @@ describe('a layer that is gone', () => {describe('a change that left the source alone', () => {it('never invalidates the cache', () => {- // Invalidating here is wasteful for an image layer and destructive for an- // unflushed paint layer, whose `bitmap: null` source rasterizes to a cleared- // surface and would wipe strokes still only in the cache.+ // Rerasterizing a null-bitmap paint source erases unflushed cache-only strokes.expect(decide().kind).toBe('appearance-only');});@@ -122,8 +118,7 @@ describe('a genuine source swap', () => {});it('does not invalidate the bitmap store’s own echo', () => {- // The cache already holds exactly those pixels; re-rasterizing would refetch- // them and risk a flicker.+ // Self-echo pixels already match the cache; rerasterization risks flicker.expect(decide({ isSelfEcho: () => true, sourceChanged: true })).toMatchObject({ invalidateCache: false });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.tsindex 1d8e55e9b2..33c02b7247 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.ts@@ -20,10 +20,7 @@ export interface LayerChangeInput {readonly hasTransformSession: boolean;/** Whether an open text-edit session belongs to this layer. */readonly hasTextEditSession: boolean;- /**- * Whether this source swap is the bitmap store's own echo. Lazy because it is- * only ever asked on the source-changed path, and answering costs a lookup.- */+ /** Lazily checks bitmap self-echo only when the source changed. */readonly isSelfEcho: () => boolean;}@@ -48,22 +45,9 @@ export type LayerChangeDecision =};/**- * What has to happen to one layer's engine-side state after the document- * changed it. Pure: the caller performs the effects in loop order.- *- * The three outcomes are genuinely different, and conflating them has real- * costs. A prop or transform change — opacity, blend, lock, visibility, rename,- * nudge — replaces the layer object while leaving its SOURCE reference intact,- * so the rasterized pixels remain valid. Invalidating there would be wasteful- * for an image layer and *destructive* for an unflushed paint layer, whose- * `bitmap: null` source rasterizes to a cleared surface and would wipe strokes- * that live only in the cache until their debounced upload lands. The- * compositor applies transform, opacity and blend at draw time, so a recomposite- * is all such a change needs.- *- * A genuine source swap does invalidate — unless it is the echo of a write the- * bitmap store just made, where the cache already holds exactly those pixels and- * re-rasterizing would re-fetch them and risk a flicker.+ * Pure layer-change decisions, applied by the caller in order. Properties and transforms need only recomposition;+ * rerasterizing them could erase unflushed paint. Source swaps invalidate except bitmap-store self-echoes, whose+ * pixels already match.*/export const decideLayerChange = (input: LayerChangeInput): LayerChangeDecision => {const { layer, previousImageName } = input;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.tsindex 5320920f6d..3e4cd40083 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts@@ -43,10 +43,7 @@ export const getSiblingOrder = (const sameIds = (a: readonly string[], b: readonly string[]): boolean =>a.length === b.length && a.every((id, index) => id === b[index]);-/**- * Writes the command's order back into its parent's child list, leaving every other node untouched.- * Returns `null` when the ids are not exactly the parent's children.- */+/** Reorders only the parent's children; rejects ids that do not exactly match them. */export const reorderSiblings = (stacks: CanvasStackForests,command: ReorderSiblingsCommanddiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeDown.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeDown.tsindex 4856565501..31ebb01252 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeDown.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeDown.ts@@ -1,18 +1,6 @@/**- * Pure transform math for merging one layer down into the layer below it.- *- * "Merge down" bakes the upper layer's pixels into the lower layer while the- * reducer keeps the lower layer's transform verbatim (see- * `mergeCanvasLayersDown` — it never touches pixels). So the engine must draw- * the upper layer's cache into the lower layer's *local* space: upper-local →- * document (via the upper transform) → lower-local (via the inverse of the- * lower transform). Composing those gives the matrix returned here, which the- * engine feeds to `ctx.setTransform` when blitting the upper cache onto the- * merged surface. When the merged (lower) layer is later composited with its- * unchanged transform, the upper content lands back at its original document- * position: `lowerTransform · (lowerTransform⁻¹ · upperTransform) = upperTransform`.- *- * Zero React, zero DOM, zero import-time side effects.+ * Merge down preserves the lower transform, so map upper pixels through `inverse(lowerTransform) * upperTransform`+ * into lower-local space. Later lower-layer compositing restores the original document placement.*/import type { CanvasLayerBaseContract } from '@workbench/canvas-engine/contracts';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.tsindex 950f598b59..5d30edb0d8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.ts@@ -195,8 +195,7 @@ describe('hide vs disable', () => {});it('leaves a hidden layer renderable — hiding is display-only, not disabling', () => {- // `isRenderableLayer` gates rasterization and generation eligibility; only- // `isEnabled` may switch it off.+ // Rasterization and generation eligibility depend on `isEnabled`, not display hiding.expect(isRenderableLayer(control(true))).toBe(true);expect(isRenderableLayer({ ...control(true), isEnabled: false })).toBe(false);});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.tsindex 6384ff1afa..46cd7c66d5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts@@ -1,15 +1,6 @@/**- * Small pure helpers over canvas layers and their sources, shared by the engine- * (cache sizing, culling, fit-to-content) and the rasterizers.- *- * `getSourceBounds` returns a layer's axis-aligned bounds in **document space**- * (used for culling / fit-to-content), while `getSourcePixelSize` returns the- * **native** (unscaled) pixel dimensions of the layer's raster cache surface —- * the compositor applies the layer transform when drawing, so caches hold- * unscaled pixels. `isRenderableLayer` reports whether a layer can be- * rasterized today (enabled, with an image/paint source).- *- * Zero React, zero import-time side effects.+ * Shared layer/source geometry. `getSourceBounds` returns document-space bounds; `getSourcePixelSize` returns+ * unscaled cache dimensions because compositing applies transforms.*/import type {@@ -41,12 +32,8 @@ export const isMaskLayer = (layer: CanvasLayerContract): layer is MaskLayer =>layer.type === 'inpaint_mask' || layer.type === 'regional_guidance';/**- * A mask layer's alpha bitmap viewed as a `paint` source, so the whole paint- * pipeline (rasterize, content-sized cache, growth, stroke, persistence) can- * operate on masks unchanged: the mask stores an alpha stencil exactly like a- * paint bitmap; only the compositor differs (it colorizes the alpha with the- * layer's `fill` instead of blitting the RGBA directly). Returns `null` for a- * non-mask layer.+ * Views mask alpha as paint for shared rasterization, growth, stroke and persistence paths. Compositing alone+ * colorizes with mask fill. Returns null for non-mask layers.*/export const maskAsPaintSource = (layer: CanvasLayerContract@@ -54,10 +41,8 @@ export const maskAsPaintSource = (isMaskLayer(layer) ? { bitmap: layer.mask.bitmap, offset: layer.mask.offset, type: 'paint' } : null;/**- * A layer's rasterizable source: its own `source` for raster/control layers, or- * a synthetic `paint` view of a mask layer's alpha bitmap. `null` for layers- * with neither (there are none today). This is the single "what pixels does this- * layer hold" accessor the engine's rasterize / cache / persistence paths share.+ * Shared rasterizable-source accessor: raster/control source or a synthetic paint view of mask alpha; otherwise+ * null.*/export const renderableSourceOf = (layer: CanvasLayerContract): CanvasLayerSourceContract | null => {if (hasSource(layer)) {@@ -70,16 +55,12 @@ export const renderableSourceOf = (layer: CanvasLayerContract): CanvasLayerSourcexport const isEmptyPolygonShape = (source: { kind: ParametricShapeKind | 'polygon'; points?: unknown[] }): boolean =>source.kind === 'polygon' && (source.points?.length ?? 0) < 3;-/**- * True when a layer's source is one the engine can rasterize: image, paint,- * gradient, text, or a shape — a polygon only once it has three points.- */+/** Rasterizable sources are image, paint, gradient, text and shapes; polygons require three points. */export const isRenderableLayer = (layer: CanvasLayerContract): boolean => {if (!isLayerContributing(layer)) {return false;}- // Mask layers are renderable whenever enabled: an empty (bitmap-less) mask- // rasterizes to a zero-rect surface (skipped downstream, like empty paint).+ // Enabled empty masks rasterize to zero-rect surfaces, skipped downstream like empty paint.if (isMaskLayer(layer)) {return true;}@@ -101,18 +82,9 @@ export const isRenderableLayer = (layer: CanvasLayerContract): boolean => {};/**- * A layer's content rectangle in its LOCAL (untransformed) coordinate space —- * the extent its raster cache surface covers, before the layer transform is- * applied. Every layer type is content-sized:- *- * - `image`: `[0, 0, w, h]` at the image's native pixels.- * - `shape` / `text`: `[0, 0, w, h]` at the source's own / estimated extent.- * - `gradient`: `[0, 0, width, height]` from the explicit extent, defaulting to- * the document dims for legacy gradients that predate the extent field.- * - `paint`: the persisted bitmap's dims at its `offset` (legacy default `0, 0`),- * or an EMPTY rect when the layer has no bitmap yet (a brand-new paint layer).- *- * Throws for layers without a rasterizable source, so callers fail loudly.+ * Untransformed local cache extent: native image size, shape/text extent, explicit gradient extent (legacy+ * document dimensions), or paint bitmap size at its offset (legacy zero). Empty paint has an empty rect;+ * unsupported sources throw.*/export const getSourceContentRect = (layer: CanvasLayerContract, doc: CanvasDocumentContractV3): Rect => {const source = renderableSourceOf(layer);@@ -152,9 +124,8 @@ export const getSourceContentRect = (layer: CanvasLayerContract, doc: CanvasDocu};/**- * A layer's axis-aligned bounds in DOCUMENT space: its {@link getSourceContentRect}- * projected through the layer transform (rotation-aware). Used for culling and- * fit-to-content. Throws for layers without a rasterizable source.+ * Rotation-aware document bounds from transformed {@link getSourceContentRect}, for culling and fitting.+ * Unsupported sources throw.*/export const getSourceBounds = (layer: CanvasLayerContract, doc: CanvasDocumentContractV3): Rect => {const contentRect = getSourceContentRect(layer, doc);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.tsindex 68835db0c0..b6a52a2c9a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.ts@@ -1,37 +1,14 @@/**- * The canvas edit-concurrency model. Controllers that capture permits receive- * {@link CanvasEditConcurrency} as their mutation context; synchronous guards- * read `canEdit` and `isGestureActive` from the same context. The engine keeps- * four mechanisms behind it.+ * Canvas edit guards share {@link CanvasEditConcurrency}. Exclusive operation leases abort on document/project+ * replacement or owned-layer changes. Permits capture the editing-lock epoch and recheck before publishing; lock+ * owners bypass the lock.*- * Leases (`editGate.ts`, exposed as the engine's edit capability): at most one- * exclusive canvas operation per engine (today `filter` and `select-object`).- * A lease is acquired for an identity, carries an abort signal, and is- * invalidated when the document is replaced, when the project changes, and on- * any contract or pixel change to its own layer. The editing controller owns- * the gate and hands it to canvas operations.+ * Structural/pixel commits and history replay refuse active gestures; tools own stroke commits, and floats guard+ * lift rather than bake. Project ids and edit revisions fence insertion/structural commits; exports also guard+ * layer reference, cache version and document generation.*- * Permits ({@link DocumentEditPermit}): a claim on the editing-lock epoch. A- * commit captures one before async work and re-checks it before publishing;- * every lock transition bumps the epoch, and the lock owner bypasses the lock.- *- * Gesture guard: structural commits, pixel commits and history replay refuse- * while a pointer gesture owns the surface. Tools commit through their own- * stroke path; the floating selection is guarded when it is lifted, not when- * it is baked back.- *- * Project identity and edit revision: insertion anchors carry the engine's- * project id and the edit revision they were captured at; export guards carry- * the project id, the layer reference, its cache version and the document- * generation they observed; structural commit options carry an expected- * revision. The reducer refuses another project's anchor; a structural commit- * refuses a mismatched revision as `stale`.- *- * {@link CanvasTransactionOutcome} is what the runtime reports when a- * transaction could not run. The document model reports command refusals with- * its own vocabulary (`canvas-engine/document/commandRefusal.ts`), which never- * depends on runtime concepts; a runtime result type may list both, naming- * each member through {@link SubsetOf} so a near-miss variant cannot compile.+ * {@link CanvasTransactionOutcome} describes runtime refusals. Document command refusals remain+ * runtime-independent; combined results use {@link SubsetOf} to verify their vocabulary.*/export interface CanvasEditConcurrency {readonly projectId: string;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.tsindex 8de8f9140f..6ec88f7204 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts@@ -1,10 +1,6 @@/**- * Inpaint mask engine behaviour: painting into a mask's alpha cache, persisting- * the mask bitmap through the bitmap store, and the in-place mask invert.- *- * Isolated in its own file so it can `vi.mock` the canvas-image upload seam- * (the engine's INTERNAL bitmap store uses it) without touching the rest of the- * engine test suite.+ * Mask painting, persistence and inversion tests. Isolated to mock the engine's internal image-upload seam without+ * affecting other engine tests.*/import type {@@ -246,10 +242,6 @@ const pointerAt = (x: number, y: number, buttons = 1): Partial<PointerEvent> =>timeStamp: 0,}) as Partial<PointerEvent>;-/**- * `readbackAlpha` overrides the stub's opaque readback when a test needs to model- * transparent pixels explicitly. See `StubRasterBackendOptions`.- */const setupEngine = (doc: CanvasDocumentContractV3, options: { readbackAlpha?: number } = {}) => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);@@ -391,12 +383,8 @@ describe('mask invert', () => {engine.lifecycle.dispose();});- // Regression: the invert domain used to come ONLY from `getSourceContentRect`,- // which reads the persisted `mask.bitmap` — stale/null until the debounced- // bitmap-store flush runs. A stroke painted moments earlier (already reflected- // in the live `layerCache`, not yet flushed to the contract) that extends past- // the document bbox was silently excluded from the invert, so its pixels never- // got flipped. The domain must union in the live cache rect too.+ // Invert must include live cache bounds: unflushed strokes outside the bbox are absent from persisted+ // `mask.bitmap` bounds.it('unions the live (unflushed) cache rect into the invert domain, covering an out-of-bbox stroke', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);@@ -434,34 +422,23 @@ describe('mask invert', () => {raf.flush();engine.tools.setTool('brush');- // Paint well outside the document bbox (0,0,100,100 per `maskDoc`). The live- // cache grows to cover the stroke immediately; deliberately never call- // `flushPendingUploads()`, so the contract's `mask.bitmap` stays null and- // `getSourceContentRect` alone would report an empty content rect.+ // Paint beyond the 100x100 bbox without flushing, leaving a grown live cache but null persisted bitmap.overlay.fire('pointerdown', pointerAt(150, 150));overlay.fire('pointermove', pointerAt(180, 180));overlay.fire('pointerup', pointerAt(180, 180, 0));expect(engine.layers.invertMask('mask1')).toBe(true);- // Growing the cache (both while painting and inside `invertMask` itself)- // reallocates a fresh backing surface each time its extent changes, so- // `surfaces` holds one entry per intermediate size, not one per layer. The- // invert's own read/write always lands on the LAST surface that gets a- // `putImageData` — the final, invert-sized surface — so pick that one- // rather than the first surface that happens to have a `getImageData`- // (which would be a stale, already-abandoned paint-time surface).+ // Growth replaces backing surfaces. Inspect the last surface receiving `putImageData`, which owns the final+ // invert extent.const putSurfaces = surfaces.filter((surface) => surface.callLog.some((entry) => entry.op === 'putImageData'));const maskCache = putSurfaces[putSurfaces.length - 1];expect(maskCache).toBeDefined();const getCalls = maskCache!.callLog.filter((entry) => entry.op === 'getImageData');expect(getCalls.length).toBeGreaterThan(0);const [sx, sy, sw, sh] = getCalls[getCalls.length - 1]!.args as [number, number, number, number];- // A domain of just the document bbox (0,0,100,100) — what `getSourceContentRect`- // alone would report, since `mask.bitmap` is still null pre-flush — would read- // a region that ends at x/y 100. Unioning in the live cache rect must grow the- // domain to also cover the stroke out at document (150,150)-(180,180), well- // past that 100 bound on both axes.+ // The invert domain must cover the unflushed stroke at (150,150)-(180,180), beyond persisted/bbox bounds+ // ending at 100.expect(sx + sw).toBeGreaterThan(110);expect(sy + sh).toBeGreaterThan(110);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 91599ecf33..df365306e8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -141,8 +141,7 @@ const createCanvasEngine = ({reportError: reportError ?? (() => undefined),});-// Records adjusted-surface cache access without exposing it on the engine. The-// factory wraps the real implementation, preserving all behaviour.+// Wraps the real adjusted cache to record access without exposing engine internals.const adjustedSurfaceCacheDeletes = vi.hoisted(() => [] as string[]);const adjustedSurfaceCacheGets = vi.hoisted(() => [] as string[]);const adjustedSurfaceCacheDeleteFaults = vi.hoisted(() => new Set<string>());@@ -271,14 +270,8 @@ const createEngine = () => {return { doc, engine, unsubscribe };};-// ---- Reactive store + render-loop harness ------------------------------//-// The tests above never `attach()`, so the render loop (and thus-// `ensureLayerCaches`) never runs. The tests below exercise the document-// mirror wired into a live engine, so they need: a store that actually-// notifies subscribers on change, a controllable `requestAnimationFrame`-// pair to drive the (otherwise real) scheduler deterministically, and fake-// canvases whose `getContext('2d')` returns a recording stub context.+// Attached-engine tests use notifying stores, controlled animation frames and recording canvas contexts to+// exercise the live document mirror and cache scheduler./** A reactive fake store: `setDocument` notifies subscribers, unlike `createFakeStore` above. */const createReactiveStore = (@@ -425,11 +418,8 @@ type RecordingRasterBackend = StubRasterBackend & {};/**- * Stateful raster backend for publication-race tests. Every scratch/cache- * surface gets a stable id, as do the fake bitmaps supplied by each test. This- * lets a test distinguish a decode drawn into an isolated scratch surface from- * a scratch surface published into the live cache without exposing cache- * internals from the production engine.+ * Stable scratch/cache and bitmap ids distinguish isolated rasterization from publication without exposing engine+ * cache internals.*/const createRecordingRasterBackend = (): RecordingRasterBackend => {const base = createTestStubRasterBackend();@@ -792,9 +782,7 @@ describe('createCanvasEngine', () => {void engine.tools.requestColorSample().then((hex) => {settled = hex;});- // A press stashes a color; the cancel discards that stash (so a dead- // gesture's color can never ride a later release — see the tool tests)- // without settling the claim, leaving the eyedropper armed for a retry.+ // Cancel drops the pressed color but keeps the one-shot claim armed for retry.overlay.fire('pointerdown', pointerAt(5, 5));overlay.fire('pointercancel', pointerAt(5, 5, { buttons: 0 }));await flushMicrotasks();@@ -1180,10 +1168,8 @@ describe('createCanvasEngine', () => {});it('uploads per-generation composites through the intermediate seam, not the durable one', async () => {- // Both consumers once shared a single un-parameterised `uploadImage`, so- // every invocation's base/mask composite was stored as a permanent image.- // Nothing in the document ever points at a composite, so it must be- // reclaimable; only pixels a layer references may be durable.+ // Generation composites have no document references and must be reclaimable; only layer-owned pixels require+ // durable uploads.const doc = makeDoc();const { store } = createFakeStore(doc);const uploadImage = vi.fn(() => Promise.resolve({ height: 1, imageName: 'durable', width: 1 }));@@ -2574,8 +2560,6 @@ describe('document mirror wiring: layer reorder', () => {const overlay = createFakeCanvas();engine.surface.attach(screen.element, overlay.element);- // Initial frame: dispatches (and, after a microtask flush, completes) the- // rasterize for both layers.raf.flush();await flushMicrotasks();raf.flush(); // the follow-up frame each rasterize's resolve scheduled@@ -2591,8 +2575,7 @@ describe('document mirror wiring: layer reorder', () => {// No layer content changed, so nothing should be re-rasterized.expect(resolver).toHaveBeenCalledTimes(2);- // The compositor draws bottom-to-top; `a` (alpha 0.25) is now the bottom- // layer and `b` (alpha 0.75) the top, so alpha is applied in that order.+ // Bottom-to-top compositing applies `a` at 0.25 before `b` at 0.75.const alphaOrder = screen.surface.callLog.filter((entry) => entry.op === 'set' && entry.args[0] === 'globalAlpha').map((entry) => entry.args[1]);@@ -2663,23 +2646,17 @@ describe('resize: synchronous composite (no flash/strobe on panel drag)', () =>const overlay = createFakeCanvas();engine.surface.attach(screen.element, overlay.element);- // Run the initial attach frame so the surface holds a composited frame, then- // isolate what the resize alone draws.raf.flush();screen.surface.callLog.length = 0;- // A single resize event (as a ResizeObserver fires mid panel-drag). Sizing a- // `<canvas>` backing store CLEARS it; the fix recomposites synchronously so the- // cleared surface is repainted before the browser paints (no blank frame).- // No `raf.flush()` follows — so any draw seen here happened IN-TASK.+ // Resize clears the backing store; recomposition must happen in-task before paint. No animation-frame flush+ // follows.engine.surface.resize(800, 600, 1);// Backing store was resized in the same call...expect(screen.element.width).toBe(800);expect(screen.element.height).toBe(600);- // ...and the composite ran SYNCHRONOUSLY (drew into the surface without a rAF- // flush). `compositeDocument` always clears the target, so a `clearRect` here- // proves the recomposite happened in-task rather than being deferred to rAF.+ // A `clearRect` without an animation-frame flush proves synchronous recomposition.const composited = screen.surface.callLog.some((entry) => entry.op === 'clearRect');expect(composited).toBe(true);@@ -2709,8 +2686,6 @@ describe('resize: synchronous composite (no flash/strobe on panel drag)', () =>// The synchronous composite ran...expect(screen.surface.callLog.some((entry) => entry.op === 'clearRect')).toBe(true);- // ...and setViewportSize's viewport-subscription `{ view: true }` invalidate was- // suppressed, so NO rAF frame is queued to recomposite the identical content.expect(raf.pendingCount()).toBe(0);// Draining any frame anyway must not produce a second composite.@@ -2722,9 +2697,7 @@ describe('resize: synchronous composite (no flash/strobe on panel drag)', () =>});it('marks the composite dirty flag so the synchronous path is not gated out (T22)', () => {- // A resize must force a full recomposite even though no layer pixels changed:- // if it only marked `overlay`, the T22 `needsComposite` gate would skip the- // composite and the just-cleared screen surface would stay blank.+ // Resize must force full recomposition even with unchanged pixels, or the cleared screen stays blank.const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);@@ -2777,19 +2750,14 @@ describe('ensureLayerCaches: edit-during-rasterize race', () => {const overlay = createFakeCanvas();engine.surface.attach(screen.element, overlay.element);- // Subscribe to thumbnail-version notifications for layer 'a' *before* either- // rasterize settles. A bare `.get()` check at the end can't distinguish- // "notified once, at the wrong time, with stale pixels on the surface" from- // "notified once, at the right time, with fresh pixels on the surface" --- // both leave the same final version number. Tracking call count/timing does.+ // Subscribe before decodes settle: final version alone cannot distinguish notification with stale pixels from+ // correctly timed publication.const thumbnailListener = vi.fn();const unsubscribe = engine.stores.thumbnailVersion.subscribeKey('a', thumbnailListener);const contentListener = vi.fn();const unsubscribeContent = engine.interaction.subscribe('rasterContentEpoch', contentListener);expect(engine.interaction.get('rasterContentEpoch')).toBe(0);- // Frame 1: dispatches the first rasterize for imageName 'a'; it stays in flight- // (the deferred is never auto-resolved).raf.flush();expect(resolver).toHaveBeenCalledTimes(1);expect(resolver).toHaveBeenNthCalledWith(1, 'a', expect.any(AbortSignal));@@ -2797,8 +2765,6 @@ describe('ensureLayerCaches: edit-during-rasterize race', () => {// An edit lands mid-flight: same layer id, new object reference, new source.setDocument({ ...doc, stacks: stacksFrom([rasterLayer('a', { imageName: 'a-v2' })]) });- // A frame runs while the first rasterize is still in flight. The source no- // longer matches that job, so a fresh isolated job starts immediately.raf.flush();expect(resolver).toHaveBeenCalledTimes(2);expect(resolver).toHaveBeenNthCalledWith(2, 'a-v2', expect.any(AbortSignal));@@ -2812,8 +2778,7 @@ describe('ensureLayerCaches: edit-during-rasterize race', () => {expect(contentListener).toHaveBeenCalledTimes(1);expect(engine.interaction.get('rasterContentEpoch')).toBe(1);- // The older decode resolves afterwards. It may finish its isolated scratch- // draw, but it must neither publish nor notify subscribers.+ // The older decode may draw scratch pixels but must neither publish nor notify.deferreds.get('a')!.resolve(new Blob());await flushMicrotasks();raf.flush();@@ -2827,14 +2792,6 @@ describe('ensureLayerCaches: edit-during-rasterize race', () => {});});-// ---- Engine-owned history (P2.3) ---------------------------------------//-// Drives a real brush stroke end-to-end through the engine (attach → dispatch-// pointer events → commit) and asserts the history wiring: strokeCommitted pushes-// an image patch, undo/redo write the before/after pixels back into the layer's-// cache surface AND re-mark the layer dirty for persistence, and the canUndo /-// canRedo stores track the stacks.-const paintDoc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },@@ -3892,10 +3849,8 @@ describe('engine-owned history: stroke → undo → redo', () => {const dirtyAfterStroke = bitmapStore.markLayerDirty.mock.calls.length;expect(dirtyAfterStroke).toBeGreaterThanOrEqual(1);- // Undo: the layer's cache surface receives putImageData(before), and the layer- // is re-marked dirty (convergence path). Content-sized: the paint layer started- // empty and grew to exactly the stroke's dirty rect, so the cache-local origin- // equals the dirty-rect origin and the patch lands at surface (0, 0).+ // Undo restores pre-stroke pixels and marks dirty. The content-sized cache starts at the dirty-rect origin, so+ // restoration lands at (0,0).engine.history.undo();const undoPut = putImageDataCalls(surfaces).find((call) => call.image === event.beforeImageData);expect(undoPut).toBeDefined();@@ -3917,10 +3872,8 @@ describe('engine-owned history: stroke → undo → redo', () => {});it('round-trips pixels exactly across a cache-growing stroke → undo → redo', () => {- // Integrated case: a multi-move stroke that GROWS the (initially empty) paint- // cache across several pointer batches, then undo/redo restore the exact- // before/after ImageData over the FULL grown extent. The piecewise pieces- // (growth, patch application) are covered elsewhere; this pins them together.+ // Multiple pointer batches grow the cache; integrated undo/redo must restore exact pixels over the full grown+ // extent.const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);@@ -3961,8 +3914,6 @@ describe('engine-owned history: stroke → undo → redo', () => {engine.surface.attach(screen.element, overlay.element);engine.tools.setTool('brush');- // Drag rightward across the document in several batches so the content-sized- // cache grows (and reallocates) as the stroke extends.overlay.fire('pointerdown', pointerAt(10, 50));overlay.fire('pointermove', pointerAt(30, 50));overlay.fire('pointermove', pointerAt(50, 50));@@ -3972,17 +3923,13 @@ describe('engine-owned history: stroke → undo → redo', () => {expect(strokes).toHaveLength(1);const event = strokes[0]!;- // The stroke grew the cache well beyond a single dab: the dirty rect spans most- // of the drag width, and the captured before/after cover that full extent.expect(event.dirtyRect.width).toBeGreaterThan(60);expect(event.beforeImageData.width).toBe(event.dirtyRect.width);expect(event.beforeImageData.height).toBe(event.dirtyRect.height);expect(event.afterImageData.width).toBe(event.dirtyRect.width);expect(event.afterImageData.height).toBe(event.dirtyRect.height);- // Undo writes the EXACT pre-stroke ImageData back into the cache. The cache- // grew to exactly the (chunk-padded) dirty rect, so its local origin equals the- // dirty-rect origin and the patch lands at surface (0, 0).+ // Undo restores exact pre-stroke pixels at (0,0), since cache and padded dirty rect share an origin.engine.history.undo();const undoPut = putImageDataCalls(surfaces).find((call) => call.image === event.beforeImageData);expect(undoPut).toBeDefined();@@ -4078,10 +4025,8 @@ describe('engine-owned history: stroke → undo → redo', () => {overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));expect(engine.stores.canUndo.get()).toBe(true);- // A snapshot restore reuses the same dims AND layer ids (structuredClone), so- // only the bumped documentRevision distinguishes it from an ordinary edit. It- // must still clear history: a subsequent undo would otherwise put pre-restore- // pixels over the restored content.+ // Only the revision bump distinguishes a restore reusing dimensions and ids; clear history to prevent undo+ // overwriting restored pixels.setDocument(paintDoc(), 1);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(false);@@ -4125,15 +4070,9 @@ describe('engine-owned history: stroke → undo → redo', () => {expect(resolver).toHaveBeenCalledTimes(1);expect(resolver).toHaveBeenNthCalledWith(1, 'src-v1', expect.any(AbortSignal));- // A revision bump that REUSES layer id 'a' with a DIFFERENT source: the- // mirror routes this through onDocumentReplaced (a full swap), which a- // reference diff alone could not tell from an ordinary edit. The engine must- // invalidate the surviving cache entry so it re-rasterizes the new source- // (a stale cache entry would keep rendering the v1 pixels).+ // Whole-document replacement must invalidate reused-id caches when the source changes.setDocument({ ...docV1, stacks: stacksFrom([rasterLayer('a', { imageName: 'src-v2' })]) }, 1);- // Persistence bookkeeping for the outgoing document was dropped so a reused- // layer id can't have its next legit persistence dispatch suppressed.expect(bitmapStore.reset).toHaveBeenCalledTimes(1);// The invalidated cache re-rasterizes, this time from the v2 source.@@ -4195,16 +4134,12 @@ describe('engine-owned history: undo/redo guarded during an active gesture', ()overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));expect(engine.stores.canUndo.get()).toBe(true);- // Start a SECOND stroke and leave it open (pointer down + move, no up).- // (The live session itself may draw, so snapshot the put count after it opens.)+ // Leave the second stroke open; snapshot writes after its initial live drawing.overlay.fire('pointerdown', pointerAt(50, 50));overlay.fire('pointermove', pointerAt(60, 60));const putsMidGesture = putImageDataCalls(surfaces);- // Mid-gesture undo/redo must be no-ops: no history pop, and not a single- // additional putImageData. Comparing the whole log — rather than just its- // length, or scanning it for the first stroke's snapshot — keeps this honest- // whether or not the live session reuses one "before" snapshot across frames.+ // Mid-gesture undo/redo must leave history and the entire pixel-write log unchanged.engine.history.undo();engine.history.redo();expect(engine.stores.canUndo.get()).toBe(true);@@ -5218,9 +5153,7 @@ const twoPaintDoc = (): CanvasDocumentContractV3 => ({isLocked: false,name: 'upper',opacity: 0.5,- // Content-sized: a persisted bitmap gives the cache a non-empty content rect.- // The upper (40×40) sits fully within the below (60×60) in below-local space,- // so the merge union stays 60×60 and the warped upper transform is non-trivial.+ // The transformed 40x40 upper layer lies inside the 60x60 lower layer, preserving the union extent.source: { bitmap: { height: 40, imageName: 'upper-bmp', width: 40 }, offset: { x: 0, y: 0 }, type: 'paint' },transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 30, y: 40 },type: 'raster',@@ -5283,8 +5216,7 @@ describe('mergeLayerDown', () => {const screen = createFakeCanvas();const overlay = createFakeCanvas();engine.surface.attach(screen.element, overlay.element);- // One frame builds both layer caches; await the async bitmap decode so both- // caches are READY (merge refuses stale/in-flight caches — finding 20).+ // Await both decodes; merge requires ready caches.raf.flush();await flushMicrotasks();raf.flush();@@ -5302,10 +5234,7 @@ describe('mergeLayerDown', () => {upperLayerId: 'upper',});- // A fresh union-sized surface was allocated for the merged pixels. Content-- // sized: below's rect {0,0,60,60} unioned with upper's rect warped into- // below-local space {20,20,40,40} is {0,0,60,60}, so the merged surface stays- // 60×60 with origin (0,0).+ // Below-local union of {0,0,60,60} and {20,20,40,40} remains 60x60 at the origin.const merged = surfaces[surfacesBeforeMerge];expect(merged).toBeDefined();expect(merged!.width).toBe(60);@@ -5415,10 +5344,8 @@ describe('mergeLayerDown', () => {});- // A two-paint doc where exactly ONE layer is content-empty (bitmap: null → a 0×0- // cache surface). Merging must NOT `drawImage` the zero-dimension operand (which- // throws in browsers) but must still dispatch the collapse and composite the- // non-empty operand.+ // Collapse the layers and composite the nonempty operand without drawing a zero-sized canvas, which browsers+ // reject.const oneEmptyPaintDoc = (emptyId: 'upper' | 'below'): CanvasDocumentContractV3 => {const doc = twoPaintDoc();return {@@ -5464,8 +5391,6 @@ describe('mergeLayerDown', () => {const screen = createFakeCanvas();const overlay = createFakeCanvas();engine.surface.attach(screen.element, overlay.element);- // Await the kept layer's bitmap decode so its cache is READY before merge- // (the empty operand needs no decode; merge refuses stale/in-flight caches).raf.flush();await flushMicrotasks();raf.flush();@@ -5478,8 +5403,6 @@ describe('mergeLayerDown', () => {true);- // The merged surface only composites the NON-empty operand: exactly one- // drawImage, and it never draws a zero-dimension source canvas.const merged = surfaces[surfacesBeforeMerge];expect(merged).toBeDefined();const draws = merged!.callLog.filter((entry) => entry.op === 'drawImage');@@ -5494,8 +5417,7 @@ describe('mergeLayerDown', () => {});- // A both-empty pair must fold trivially (delete the upper, below stays empty)- // rather than silently no-op — otherwise merge-visible stalls on such a run (F4).+ // Two empty layers must still collapse, allowing merge-visible to make progress.it('folds a both-empty pair trivially: dispatches the collapse and allocates no merged surface (F4)', async () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);@@ -5543,20 +5465,14 @@ describe('mergeLayerDown', () => {expect(dispatch.mock.calls.some((call) => (call[0] as EngineTestAction).type === 'mergeCanvasLayersDown')).toBe(true);- // No merged surface was allocated: a 0×0 union surface would throw, and there- // are no pixels to composite.+ // No pixels require allocation; zero-sized union canvases would throw.expect(surfaces.length).toBe(surfacesBeforeMerge);engine.lifecycle.dispose();});- // Regression: `mergeLayerDown` used to gate on `isRenderableLayer`, which masks- // satisfy (a mask rasterizes to a stencil whenever enabled). That let a mask- // reach the merge path, whose reducer unconditionally produces a `type: 'raster'`- // result — merging a mask blitted its stencil into the layer below and/or- // clobbered a mask below into a raster layer, destroying its config, with no- // undo. The guard must reject a mask on EITHER side, mirroring the layers- // panel's `isMergeableRasterLayer`/`canMergeLayerDown` enablement exactly.+ // Reject masks on either merge side, matching panel eligibility. The raster merge reducer would otherwise+ // destroy mask configuration or blend stencils into color pixels.it.each([{ label: 'mask above a raster layer', maskId: 'upper' as const },{ label: 'a raster layer above a mask', maskId: 'below' as const },@@ -5587,8 +5503,6 @@ describe('mergeLayerDown', () => {expect(dispatch.mock.calls.some((call) => (call[0] as EngineTestAction).type === 'mergeCanvasLayersDown')).toBe(false);- // Document unchanged: still two layers, each with its original type — no- // mask was blitted into, and no mask was clobbered into a raster layer.expect(getDocumentLeaves(engine.document.getDocument()!).map((l) => l.type)).toEqual(getDocumentLeaves(doc).map((l) => l.type));@@ -6119,9 +6033,8 @@ describe('extract masked canvas area', () => {// ---- mergeVisibleRasterLayers: guarded non-destructive composite ----/**- * An EngineStore backed by the REAL workbench reducer, so the operation's- * prepared stack mutation advances the document and mirror atomically — the- * no-op mock store cannot exercise that transaction.+ * Uses the real reducer so prepared mutations advance document and mirror atomically; a no-op store cannot+ * exercise publication.*/const createReducerBackedStore = (document: CanvasDocumentContractV3,@@ -7538,11 +7451,8 @@ describe('mergeVisibleRasterLayers', () => {raf.flush();await flushMicrotasks();raf.flush();- // A reference-only copy would allocate both a visible cache and a- // rasterization scratch surface here, after the transaction reservation was- // gone. Prepared caches make this frame allocation-free.- // The frame may lazily create its single checkerboard tile, but it must not- // rebuild any of the already-prepared duplicate layer caches.+ // Prepared duplicate caches must avoid frame-time cache/scratch allocation after the reservation expires. The+ // checkerboard tile may still initialize lazily.expect(surfaces).toHaveLength(afterDuplicate + 1);expect(engine.stores.canUndo.get()).toBe(true);engine.lifecycle.dispose();@@ -7944,15 +7854,12 @@ describe('rasterizeLayer (parametric → paint)', () => {if (convert?.type === 'convertCanvasLayer') {expect(convert.layer.type).toBe('raster');if (convert.layer.type === 'raster') {- // Content-sized: the shape (60×40) at transform (10,20) bakes to a paint- // layer whose bitmap sits at offset (10,20); the transform resets to identity.+ // The 60x40 shape translated by (10,20) bakes with that source offset and an identity transform.expect(convert.layer.source).toEqual({ bitmap: null, offset: { x: 10, y: 20 }, type: 'paint' });expect(convert.layer.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });}}- // A fresh CONTENT-sized surface (the transformed shape bounds, 60×40) was- // allocated and the parametric cache baked into it.const baked = surfaces[before];expect(baked).toBeDefined();expect(baked?.width).toBe(60);@@ -7997,9 +7904,8 @@ describe('rasterizeLayer (parametric → paint)', () => {});it('redo re-bakes from params rather than pinning the doc-sized surface (byte-budget honesty)', () => {- // Regression: the history entry declared bytes:256 but captured the doc-sized- // `baked` surface in its redo closure, so repeated rasterizes could retain- // gigabytes invisible to HISTORY_BYTE_BUDGET. Redo must re-bake instead.+ // Redo must rebake; capturing the full baked surface under a 256-byte history entry bypasses the history+ // memory budget.const { engine, surfaces } = setup(shapeLayerDoc());expect(engine.layers.rasterizeLayer('shape1')).toBe(true);@@ -8010,9 +7916,6 @@ describe('rasterizeLayer (parametric → paint)', () => {expect(surfaces.length).toBe(afterApply);engine.history.redo();- // Redo allocates FRESH surfaces: it re-baked from params (content-sized to the- // transformed shape bounds, 60×40) rather than reusing a surface pinned by the- // entry.expect(surfaces.length).toBeGreaterThan(afterApply);const rebaked = surfaces.at(-1);expect(rebaked?.width).toBe(60);@@ -8051,23 +7954,9 @@ describe('rasterizeLayer (parametric → paint)', () => {paint.engine.lifecycle.dispose();});- // ---- rasterize → undo → bitmap-store flush: source-type guard --------- //- // Reviewer-flagged bug: rasterize bakes the shape to a paint layer and marks- // it dirty in the bitmap store; undo re-converts it back to the parametric- // shape. Nothing previously cleared the pending dirty mark, so the eventual- // debounced (or barrier) flush would encode the paint-cache surface — still- // populated, since a source swap doesn't clear it — and dispatch- // `updateCanvasLayerSource({ type: 'paint', ... })`, silently flipping the- // parametric layer back to paint with stale, wrong-extent pixels.- //- // These tests wire a REAL `createBitmapStore` (exercising the actual guard- // in `flushLayer`) through `opts.bitmapStore`, with test-controlled- // encode/upload stubs (no real network) and a `getLayerSurface` that always- // resolves — mirroring the bug precondition that a source swap does NOT- // clear the cache. `getLayerSource` reads the engine's own mirrored- // document, so it reflects the exact reducer round trip the test drives via- // `setDocument`.+ // Rasterize then undo leaves a dirty mark and surviving cache, but persistence must not overwrite the restored+ // parametric source. A real bitmap store reads the mirrored source with controlled encode/upload and an+ // always-resolving cache surface.describe('rasterize → undo → bitmap-store flush (source-type guard)', () => {afterEach(() => {vi.useRealTimers();@@ -8086,9 +7975,7 @@ describe('rasterizeLayer (parametric → paint)', () => {// real cache, whose surface a source swap does NOT clear (only marks stale).const fakeSurface = createTestStubRasterBackend().createSurface(10, 10);- // Forward-declared: `getLayerSource` closes over it, but is only ever- // CALLED once `engine` is assigned below (bitmap-store flushes never- // happen synchronously during construction).+ // Flushes run after construction, so the source reader sees the assigned engine.let engine: ReturnType<typeof createCanvasEngine>;const bitmapStore = createBitmapStore({dispatch: createTestMutationPort(store, 'p1').dispatch,@@ -8119,11 +8006,7 @@ describe('rasterizeLayer (parametric → paint)', () => {return { dispatch, encodeSurface, engine, raf, setDocument, uploadImage };};- /**- * Applies the most recently dispatched `convertCanvasLayer` action onto- * `doc`, simulating what the real reducer would do — `createReactiveStore`'s- * `dispatch` is a bare spy and does not mutate state on its own.- */+ /** Applies the latest conversion to `doc`; the reactive store's dispatch spy does not update state itself. */const applyLastConvert = (doc: CanvasDocumentContractV3, dispatch: Mock): CanvasDocumentContractV3 => {const converts = convertCalls(dispatch);const last = converts.at(-1);@@ -8137,11 +8020,8 @@ describe('rasterizeLayer (parametric → paint)', () => {};/**- * Rasterizes `shape1` (paint bake, dirty-marks the bitmap store), applies- * that conversion to the mirrored document, then undoes it and applies- * THAT conversion too — the full reducer round trip a live document would- * go through. Leaves the document back at its original parametric shape- * source, with the paint-bake dirty mark for `shape1` still pending.+ * Drives rasterize and undo through mirrored conversions, restoring the parametric source while leaving the+ * paint dirty mark pending.*/const rasterizeThenUndo = () => {vi.useFakeTimers();@@ -8199,15 +8079,8 @@ describe('rasterizeLayer (parametric → paint)', () => {});it('redo after rasterize → flush → undo re-dispatches the paint image ref (fix round 2: no permanent bitmap:null)', async () => {- // Reviewer round 2, data-loss finding: rasterize → flush (contract lands- // on img-x, and the store's `lastApplied` remembers img-x) → undo (back- // to shape) → redo (convertCanvasLayer resets to `paint {bitmap: null}`)- // → a further flush re-bakes IDENTICAL pixels, so the content-hash dedupe- // resolves back to img-x — but the old `lastApplied`-based redundant-- // dispatch skip treated that as "already applied" and swallowed the- // dispatch, permanently stranding the document on `bitmap: null`. This- // drives the FULL sequence (including the first flush landing for real)- // and asserts the second flush actually re-dispatches the ref.+ // Rasterize/flush/undo/redo/flush reuses identical uploaded pixels, but must redispatch the ref into the+ // reset null-bitmap source. Remembered `lastApplied` alone cannot determine current document state.vi.useFakeTimers();let doc = shapeLayerDoc();const { dispatch, engine, raf, setDocument, uploadImage } = setupWithRealBitmapStore(doc);@@ -8225,8 +8098,6 @@ describe('rasterizeLayer (parametric → paint)', () => {const firstPersist = paintSourceDispatches(dispatch).at(-1);expect(firstPersist).toBeDefined();expect(firstPersist?.source).toMatchObject({ bitmap: { imageName: 'img-x' }, type: 'paint' });- // Apply the persisted ref onto the mirrored document, as the real reducer- // would — the document now genuinely points at img-x, not `bitmap: null`.doc = {...doc,stacks: stacksFrom(@@ -8244,8 +8115,7 @@ describe('rasterizeLayer (parametric → paint)', () => {setDocument(doc);raf.flush();- // Redo → paint bake again; the fresh conversion lands on `bitmap: null`- // (only the debounced flush fills in the persisted ref).+ // Redo resets to paint with null bitmap until the next persistence flush.engine.history.redo();doc = applyLastConvert(doc, dispatch);setDocument(doc);@@ -8253,10 +8123,7 @@ describe('rasterizeLayer (parametric → paint)', () => {const layerAfterRedo = getDocumentLeaves(engine.document.getDocument()!)[0] as CanvasRasterLayerContractV2;expect(layerAfterRedo.source).toEqual({ bitmap: null, offset: { x: 10, y: 20 }, type: 'paint' });- // Flush again: the re-baked pixels are identical, so the content hash- // dedupes back to img-x with NO new upload — but the ref must still be- // re-dispatched into the contract, since the document currently reads- // `bitmap: null`, not img-x.+ // Identical pixels skip upload but must redispatch the ref because the document bitmap is null.await vi.advanceTimersByTimeAsync(1500);await engine.lifecycle.flushPendingUploads();@@ -8512,8 +8379,6 @@ const imageSelectedDoc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- // Selected layer is an image (not paintable) → a brush stroke auto-creates a- // fresh paint layer for the gesture.stacks: stacksFrom([rasterLayer('img')]),selectedLayerId: 'img',version: 3,@@ -8582,8 +8447,6 @@ describe('engine-owned history: composed auto-create + stroke entry', () => {const putBefore = () => putImageDataCalls(surfaces).some((call) => call.image === strokes[0]!.beforeImageData);const beforeUndoPutBefore = putBefore();- // Undo: removes the auto-created layer, and does NOT restore pre-stroke pixels- // (the layer's cache is gone).engine.history.undo();const removeAfterUndo = dispatch.mock.calls.map((call) => call[0] as EngineTestAction)@@ -8666,9 +8529,7 @@ describe('setStagedPreview', () => {// Two rapid selections; the second supersedes the first.engine.previews.setStagedPreview({ dataUrl: dataUrl('AAAA'), height: 10, width: 10 }); // decode #0- engine.previews.setStagedPreview({ dataUrl: dataUrl('BBBB'), height: 20, width: 20 }); // decode #1-- // The newer decode resolves first and is drawn; a frame must have been scheduled.+ engine.previews.setStagedPreview({ dataUrl: dataUrl('BBBB'), height: 20, width: 20 });bitmaps.resolveBitmap(1);await flushMicrotasks();expect(raf.pendingCount()).toBeGreaterThan(0);@@ -8681,8 +8542,7 @@ describe('setStagedPreview', () => {const draws = stagedDraws(screen.surface);expect(draws.length).toBeGreaterThan(0);- // Every staged draw is the 20x20 candidate at the bbox origin; the 10x10- // stale decode never reaches the screen.+ // Only the 20x20 candidate may reach the screen; the stale 10x10 decode must not publish.for (const args of draws) {expect(args.slice(1)).toEqual([0, 0, 20, 20]);}@@ -9590,8 +9450,7 @@ describe('commitRasterFilterResult', () => {const uploaded = createDeferred<{ height: number; imageName: string; width: number }>();const uploadImage = vi.fn(() => uploaded.promise);const harness = await createRealBitmapStoreHarness(uploadImage);- // The harness creates live source paint to establish a guarded export;- // this test targets only persistence owned by the subsequently-created copy.+ // Source paint establishes the guard; assertions isolate the new copy's persistence.harness.bitmapStore.discardLayer(harness.source.id);const copied = await harness.engine.layers.commitRasterFilterResult({guard: harness.exported.guard,@@ -12242,11 +12101,8 @@ describe('guarded filter previews', () => {});/**- * A layer that can be added/removed from the document to drive the mirror's- * `onLayersChanged`/`onDocumentReplaced` callbacks, without itself consuming a- * `createImageBitmap` call — a `bitmap: null` paint source rasterizes- * synchronously (a clear), unlike an image source, so it can't shift the call- * ordering the pruning tests rely on to target a SPECIFIC filter-preview decode.+ * Null-bitmap paint changes the mirror without asynchronous image decoding, preserving the preview-decode+ * ordering under test.*/const previewableLayer = (id: string): CanvasLayerContract => ({blendMode: 'normal',@@ -13606,14 +13462,8 @@ describe('guarded filter previews', () => {});});-// ---- C1: prop/transform edits must not wipe an unflushed paint layer ------//-// A `bitmap: null` paint layer's strokes live ONLY in its raster cache until a-// debounced upload persists them. The paint rasterizer clears the surface for a-// null bitmap, so re-rasterizing such a layer WIPES the strokes. The engine must-// therefore invalidate a layer's cache only when its SOURCE reference changed —-// never for a prop/transform-only edit (opacity/blend/lock/rename/nudge), which-// the compositor already applies at draw time.+// Property and transform changes must preserve unflushed paint caches. Rerasterizing their null-bitmap source+// would erase strokes; only source changes justify invalidation./** Full-surface clears (`clearRect(0,0,w,h)`) recorded on a stub surface — the wipe signature. */const fullClearCount = (surface: StubRasterSurface): number =>@@ -13621,11 +13471,8 @@ const fullClearCount = (surface: StubRasterSurface): number =>describe('document mirror wiring: prop vs source change (paint-pixel survival)', () => {/**- * Rasterizes the pre-existing `paint1` layer to completion (as real frames- * would before the user paints — the existing-layer paint path does NOT mark- * the cache non-stale itself), then draws one stroke into that non-stale cache.- * This reproduces the C1 state: real strokes living only in a cache that a- * spurious re-rasterize (of the `bitmap: null` source) would clear to blank.+ * Complete initial rasterization before painting so the stroke resides in a valid cache that spurious+ * null-source rasterization would erase.*/const paintOneStroke = async () => {const raf = createControllableRaf();@@ -13666,8 +13513,6 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',engine.surface.attach(screen.element, overlay.element);engine.tools.setTool('brush');- // Initial rasterize of the (bitmap: null) paint layer → one full clear, then- // the cache settles non-stale (the `.then` fires on a microtask).raf.flush();await flushMicrotasks();raf.flush();@@ -13894,13 +13739,10 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',it('keeps an unflushed paint layer’s pixels on a transform/opacity-only change (no re-rasterize)', async () => {const { engine, paintCache, raf, resolver, setDocument } = await paintOneStroke();- // Baseline: the stroke composited into the cache (a drawImage). Exactly one- // full clear so far — the initial rasterize; the stroke never clears.expect(paintCache.callLog.some((entry) => entry.op === 'drawImage')).toBe(true);const clearsBefore = fullClearCount(paintCache);- // A prop-only edit that PRESERVES the source reference (exactly as the reducer- // does — it spreads `...layer`): opacity + a transform nudge.+ // Opacity and nudge edits preserve source identity, matching reducer structural sharing.const doc = engine.document.getDocument()!;const layer = getDocumentLeaves(doc)[0]!;setDocument({@@ -13911,8 +13753,6 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',await flushMicrotasks();raf.flush();- // The cache was NOT re-rasterized: no new full clear, so the painted pixels- // survive. (A `bitmap: null` re-rasterize would clear the surface to blank.)expect(fullClearCount(paintCache)).toBe(clearsBefore);// No resolve/rasterize was even attempted for the paint layer.expect(resolver).not.toHaveBeenCalled();@@ -14050,9 +13890,7 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',await engine.lifecycle.flushPendingUploads();- // The flush barrier ran, and it operated on a cache that was never wiped: the- // surface still carries the stroke (drawImage) with no re-rasterize clear, so- // the bitmap store (which encodes this exact surface) persists real pixels.+ // The barrier must encode the preserved stroke surface without an intervening rasterization clear.expect(bitmapStore.flushPendingUploads).toHaveBeenCalled();expect(fullClearCount(paintCache)).toBe(clearsBefore);expect(paintCache.callLog.some((entry) => entry.op === 'drawImage')).toBe(true);@@ -14064,9 +13902,7 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',const { engine, raf, resolver, setDocument } = await paintOneStroke();expect(resolver).not.toHaveBeenCalled();- // A genuine source swap (undo/import → a NEW paint source object with a- // persisted bitmap). isSelfEcho is false in the spy store, so this must- // invalidate and re-rasterize — which decodes the persisted image.+ // A new persisted paint source is not a self-echo and must invalidate and decode.const doc = engine.document.getDocument()!;const layer = getDocumentLeaves(doc)[0] as CanvasRasterLayerContractV2;setDocument({@@ -14192,8 +14028,7 @@ describe('hasExportableLayerContent', () => {const overlay = createInputCanvas();engine.surface.attach(createInputCanvas().element, overlay.element);- // Settle the initial empty paint/mask rasterization before drawing. A stroke- // then grows that current cache without updating the persisted contract.+ // Settle initial rasterization before a stroke grows the cache beyond persisted bounds.raf.flush();await flushMicrotasks();raf.flush();@@ -14467,8 +14302,7 @@ describe('gesture guard: nudge / commitStructural mid-stroke', () => {const overlay = createInputCanvas();const screen = createInputCanvas();engine.surface.attach(screen.element, overlay.element);- // Build both layer caches so a merge could otherwise succeed; await the async- // decode so both are READY (merge refuses stale/in-flight caches — finding 20).+ // Await both cache decodes so readiness would otherwise permit merging.raf.flush();await flushMicrotasks();raf.flush();@@ -14530,8 +14364,7 @@ describe('brush cursor ring: live size updates', () => {raf.flush();expect(raf.pendingCount()).toBe(0);- // The `[`/`]` path: a size step with NO pointer event must schedule a frame- // (the ring redraws at its last position with the new radius).+ // Keyboard brush resizing must schedule a frame at the last pointer position.engine.tools.stepBrushSize(1);expect(raf.pendingCount()).toBeGreaterThan(0);raf.flush();@@ -14662,14 +14495,8 @@ describe('doc-replace mid-gesture: cancels the active tool gesture', () => {});});-// ---- Zoom-cost regressions: what must NOT scale with zoom -----------------//-// The reported lag ("laggier the closer you zoom in") traced to the render loop-// recompositing the whole document on EVERY invalidation — including overlay-only-// hover frames, whose cost is otherwise constant. A full composite up-scales each-// doc-sized layer surface to fill the screen, so its fill-rate grows with zoom.-// These lock the two fixes: overlay-only frames skip the composite, and composites-// disable image smoothing when zoomed in (crisp + no bilinear up-scale per frame).+// Overlay-only frames must skip document compositing, whose fill cost grows with zoom. Zoomed composites disable+// smoothing for crisp pixels without bilinear upscaling.describe('zoom-cost: overlay-only frames skip the document composite', () => {/** A fake canvas that can BOTH fire pointer events and expose its recording surface. */@@ -14743,8 +14570,6 @@ describe('zoom-cost: overlay-only frames skip the document composite', () => {overlay.fire('pointermove', pointerAt(40, 40, { buttons: 0 }));raf.flush();- // The screen composite did NOT run: zero clears/fills/blits landed on it. This- // is the win — hover cost is now independent of zoom and document size.expect(compositeOps(screen.surface)).toHaveLength(0);// The overlay WAS redrawn: cleared, and the cursor ring arc drawn.expect(overlay.surface.callLog.some((e) => e.op === 'clearRect')).toBe(true);@@ -14879,8 +14704,6 @@ describe('checker colors: fed-token tile rebuild', () => {expect(tiles).toHaveLength(1);expect(fillStyleSets(tiles[0]!)).toEqual([DEFAULT_CHECKER_COLORS.a, DEFAULT_CHECKER_COLORS.b]);- // Feed new (resolved-token) checker colors: the cached tile is dropped and- // rebuilt with the new colors on the next composite, which is forced to run.engine.stores.checkerColors.set({ a: '#010101', b: '#020202' });raf.flush();await flushMicrotasks();@@ -14924,8 +14747,6 @@ describe('checker colors: fed-token tile rebuild', () => {await flushMicrotasks();expect(tiles).toHaveLength(1);- // Re-feeding the SAME colors is a no-op (the store's equality check drops it),- // so no invalidation and no tile rebuild.engine.stores.checkerColors.set({ ...DEFAULT_CHECKER_COLORS });raf.flush();await flushMicrotasks();@@ -14962,15 +14783,13 @@ describe('fitToView: content ∪ bbox', () => {engine.viewport.fitToView();- // avail = 400 - 48*2 = 304; fitting the 100px bbox → 3.04. Fitting the 1000px- // doc rect would have been ~0.304 — the doc rect is no longer the fit target.+ // The padded 304px viewport fits the 100px bbox at 3.04, not the 1000px document at 0.304.expect(engine.viewport.getViewport().getZoom()).toBeCloseTo(3.04, 2);engine.lifecycle.dispose();});it('unions a renderable layer that lies beyond the bbox into the fit', () => {- // A raster layer 100x100 translated to (900,900): content extends to 1000, far- // past the 100px bbox. Fitting content ∪ bbox spans 0..1000 → zoom ~0.304.+ // Content at (900,900) extends the bbox union to 1000px, fitting at about 0.304.const layer: CanvasLayerContract = {blendMode: 'normal',id: 'a',@@ -15079,9 +14898,6 @@ describe('transform session', () => {});it('parametric (text) layer Apply commits ONE param transform, stays type text, no bake; undo restores', () => {- // Regression: parametric layers (shape/gradient/text) could not be transformed- // — `applyTransform` only handled image sources. Phase 5 "param for parametric":- // the transform commits as a param edit and the source stays editable-forever.const textLayerDoc: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },@@ -15224,10 +15040,8 @@ describe('transform session', () => {vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- // A paint layer that already carries a non-identity transform, so undo restores- // a transform distinct from the post-bake identity. Content-sized: it needs a- // persisted bitmap so its cache is non-empty (an empty paint layer is not- // transformable).+ // Persisted content makes the paint layer transformable; a nonidentity transform distinguishes undo from the+ // baked identity.const movedPaint = paintDoc();const movedLayer = getDocumentLeaves(movedPaint)[0] as CanvasRasterLayerContractV2;movedLayer.source = {@@ -15269,17 +15083,13 @@ describe('transform session', () => {dispatch.mockClear();engine.layers.applyTransform();- // A fresh CONTENT-sized surface (the transformed content bounds, 100×100 here)- // was allocated and drawn through the bake matrix. The 50×50 cache at scale 2 +- // offset (10,20) bakes to bounds {10,20,100,100}, so the surface is 100×100 and- // the bake transform's translation is shifted by the baked origin to (0,0).+ // A 50x50 cache scaled by two at (10,20) bakes into a 100x100 surface; subtracting the baked origin leaves+ // zero translation.const baked = surfaces[surfacesBeforeApply];expect(baked).toBeDefined();expect(baked!.width).toBe(100);expect(baked!.height).toBe(100);const setTransforms = baked!.callLog.filter((entry) => entry.op === 'setTransform');- // The non-identity setTransform carries the bake matrix scale (a=2, d=2), with- // its translation shifted into baked-local space (e=0, f=0).expect(setTransforms.some((entry) => entry.args[0] === 2 && entry.args[3] === 2 && entry.args[4] === 0 && entry.args[5] === 0@@ -15388,15 +15198,8 @@ describe('transform session', () => {engine.lifecycle.dispose();});- // ---- temp-tool switch (space/alt hold) must not discard the session ----- //- // The pointer pipeline flags a modifier-hold switch (and its matching- // restore) with `{ temporary: true }` on `setTool` (see- // `pointerPipeline.test.ts`, "temporary modifier tools"). These tests drive- // that same seam directly against the engine: the public `CanvasEngine`- // type narrows `setTool` to one argument, but the runtime function accepts- // the pipeline's second (`opts`) argument, so the cast below exercises the- // exact call the pipeline makes on a real space/alt hold and release.+ // Drive the pipeline's `{ temporary: true }` tool-switch seam directly to verify modifier holds preserve+ // sessions. The cast exposes its runtime second argument beyond the public one-argument type.describe('temp-tool switch (space/alt hold)', () => {it('preserves the session and its numeric edits, resuming after the hold ends', () => {const raf = createControllableRaf();@@ -15431,8 +15234,6 @@ describe('transform session', () => {setTool('transform', { temporary: true }); // space up: resumeexpect(engine.stores.activeTool.get()).toBe('transform');- // Resuming does not reopen the session from the layer's committed- // transform, discarding the edit.expect(engine.stores.transformSession.get()?.transform).toEqual(edited);engine.lifecycle.dispose();@@ -15489,17 +15290,11 @@ describe('transform session', () => {expect(engine.stores.transformSession.get()).not.toBeNull();const setTool = engine.tools.setTool as (id: ToolId, opts?: { temporary?: boolean }) => void;- setTool('view', { temporary: true }); // space down-- // The session's layer is deleted while temp-switched away (e.g. via the- // layers panel) — the layer-change teardown cancels the session- // immediately, regardless of which tool is active.+ setTool('view', { temporary: true }); // Deleting the session layer while temporarily switched away must cancel immediately.setDocument({ ...doc, stacks: stacksFrom([]) });expect(engine.stores.transformSession.get()).toBeNull();- setTool('transform', { temporary: true }); // space up: resume- // Resuming must not resurrect a session against the now layer-less- // document.+ setTool('transform', { temporary: true });expect(engine.stores.transformSession.get()).toBeNull();engine.lifecycle.dispose();@@ -16088,9 +15883,7 @@ describe('engine selection: fill / erase', () => {it('eraseSelection records one undoable edit (on existing content)', () => {const { engine } = makeEngine(paintDoc());engine.selection.selectAll();- // Content-sized: erase only affects EXISTING pixels, so give the layer content- // first (a fill grows the empty paint cache to the selection). Then erase records- // its own edit within that extent.+ // Fill first to establish content; erasure may edit only existing cache extent.engine.selection.fillSelection();engine.selection.eraseSelection();expect(engine.stores.canUndo.get()).toBe(true);@@ -16145,8 +15938,7 @@ describe('engine selection: fill / erase', () => {it('clearCaches flushes pending bitmap uploads before invalidating (unflushed strokes survive)', async () => {const { bitmapStore, engine } = makeEngine(paintDoc());- // The debug "Clear caches" action must persist any in-flight (debounced) paint- // upload before it drops the layer caches — otherwise an unflushed stroke is lost.+ // Cache clearing must flush pending paint first to avoid losing unpersisted strokes.await engine.diagnostics.clearCaches();expect(bitmapStore.flushPendingUploads).toHaveBeenCalledTimes(1);engine.lifecycle.dispose();@@ -16641,14 +16433,8 @@ describe('text edit session', () => {expect(engine.stores.textEditSession.get()).toBeNull();});- // ---- click-elsewhere-to-commit (pointerdown / Escape) ----- //- // Regression: `commitTextEdit` only fired on the portal's blur, but the pointer- // pipeline `preventDefault`s a canvas pointerdown (suppressing that blur), and- // the mid-gesture guard swallowed any blur that did land. The commit now runs- // engine-side on pointerdown (before a gesture starts), reading the live portal- // content via a registered reader; Escape cancels a defocused session via the- // engine's escape ladder. These drive that engine-side logic directly.+ // Canvas pointerdown suppresses portal blur, so text commits read live portal content before starting the+ // gesture. Escape cancels defocused sessions through the engine ladder.it('commitOpenTextSession reads the registered content reader and commits the create', () => {const { engine, layerActions } = makeEngine(paintDoc());@@ -16719,8 +16505,7 @@ describe('text edit session', () => {});describe('canTargetLayerFromContextMenu (canvas right-click target)', () => {- // The menu acts on the document's SELECTED layer — the canvas never hit-tests- // to pick one, so this only reports whether an in-progress edit suppresses it.+ // Menus target the selected layer; this checks edit-session suppression, not hit testing.const doc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex a08cd3c863..8e9493d410 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -187,15 +187,8 @@ import { createStrokeCommit } from './strokeCommit';import { createViewTool } from './tools/viewTool';/**- * Result of {@link CanvasEngineExportCapability.exportRasterLayersToPsd}: `'exported'` on- * success, `'nothing'` when there are no raster layers with content, `'too-large'`- * when the union bounds exceed the PSD dimension cap, and `'not-ready'` when a- * participant's cache is still decoding (nothing exported — surface feedback).- */-/**- * Re-exported from the controller that produces it, so the many callers that- * name it off `canvas-engine/engine` keep resolving while there is only one- * definition to keep in step.+ * PSD export returns exported, nothing (no raster content), too-large (union exceeds PSD limits), or not-ready (a+ * contributor is decoding; surface feedback).*/export type { ExportLayerPixelsResult };@@ -245,15 +238,13 @@ export interface CanvasEngineOptions {projectId: string;mutationPort: CanvasProjectMutationPort;/**- * Persists encoded engine-owned bitmaps DURABLY. A layer's document points at- * the resulting image name, so the upload must not be garbage-collectable.- * Application networking stays outside the core.+ * Uploads engine bitmaps durably because document layer refs must survive garbage collection. Networking remains+ * outside the core.*/uploadImage(blob: Blob): Promise<{ height: number; imageName: string; width: number }>;/**- * Uploads a TRANSIENT image — one no layer will reference, such as a- * per-generation composite. Marked intermediate so it is reclaimable instead- * of accumulating one durable image per invocation forever.+ * Uploads unreferenced composites as transient intermediates so each invocation does not leave a permanent+ * image.*/uploadIntermediateImage(blob: Blob): Promise<{ height: number; imageName: string; width: number }>;/** Supplies the currently selected model base for core-created control layer contracts. */@@ -270,16 +261,10 @@ export interface CanvasEngineOptions {backend?: RasterBackend;/** Resolves persisted image assets to blobs for decoding. */imageResolver: ImageResolver;- /**- * Overrides the paint-persistence store. Defaults to a real {@link createBitmapStore}- * wired to the layer cache and the upload backend. Tests inject a fake to- * observe dirty-marking / avoid network uploads.- */bitmapStore?: BitmapStore;/**- * Overrides the web-font readiness api used to re-rasterize text layers once a- * pending font loads. Defaults to the browser's `document.fonts` (or a no-op- * in node). Tests inject a fake to drive the load without a real FontFaceSet.+ * Font readiness seam for rerasterizing loaded text. Defaults to `document.fonts`, or a no-op without the DOM;+ * injectable for tests.*/fonts?: FontLoadApi | CanvasFontRuntime | null;/** Enables deterministic raster/render counters. Disabled by default. */@@ -289,14 +274,8 @@ export interface CanvasEngineOptions {export interface CanvasEngineSelectionCapability extends CanvasSelectionCapability {}/**- * The export surface the engine actually builds. It widens the public- * {@link CanvasEngineExportCapability} with members that stay inside the Canvas- * module — raster snapshots, layer-pixel exports, and the composite executor- * deps are consumed by `canvas-operations`, never by `api.ts` callers.- *- * Declared as an `extends` rather than a parallel copy so the two can never- * silently diverge: anything added to the public capability must be implemented- * here, and anything added here is visibly internal.+ * Extends {@link CanvasEngineExportCapability} with Canvas-internal raster snapshots, pixel exports and executor+ * dependencies. Inheritance keeps public requirements synchronized while internal additions stay out of `api.ts`.*/export interface CanvasEngineInternalExportCapability extends CanvasEngineExportCapability {captureRasterSnapshot(@@ -419,9 +398,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCsubscribeLayerThumbnailStatus: (layerId, listener) => stores.thumbnailStatus.subscribeKey(layerId, listener),subscribeLayerThumbnailVersion: (layerId, listener) => stores.thumbnailVersion.subscribeKey(layerId, listener),};- // Web-font readiness for text layers: re-rasterizes a text layer once its font- // resolves (a no-op in node / when `document.fonts` is absent). `undefined`- // opts.fonts falls back to the DOM api; an explicit `null` forces the no-op.+ // Undefined uses browser font readiness; explicit null disables it. Loaded fonts trigger text rerasterization.const fontLoader = createFontLoader(opts.fonts === undefined ? domFontLoadApi() : opts.fonts);let syncActiveFontSources: () => void = () => undefined;const tools = new Map<ToolId, Tool>([@@ -441,9 +418,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC]);let interactionLocked = false;- // Transient per-layer transform overrides driving the move/transform drag- // preview (compositor + overlay read at render time; the mirror stays untouched).- // The move tool sets only x/y; the transform tool sets the full transform.+ // Render-time transform previews leave the mirror untouched; move overrides position, transform overrides the+ // full matrix.const transformOverrides = new Map<string,{ x: number; y: number; scaleX?: number; scaleY?: number; rotation?: number }@@ -495,19 +471,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// The brush/eraser cursor ring, drawn on the overlay (set by the active tool).let overlayCursor: OverlayCursor | null = null;- // The transparency checkerboard pattern tile, built once (lazily) through the- // raster backend and reused each frame (see `createCheckerboardTile`). It is- // rebuilt only when the fed checker colors change (theme/color-mode switch),- // signalled by nulling it in the `checkerColors` subscription below.+ // Lazy checker tile reused until checker colors change, when the subscription clears it.let checkerboardTile: RasterSurface | null = null;const getCheckerboardTile = (): RasterSurface => {checkerboardTile ??= createCheckerboardTile(backend, stores.checkerColors.get());return checkerboardTile;};- // Cached mask fill pattern tiles, keyed by `style:color` (a solid style has no- // tile → cached as `null`). Built lazily through the backend seam like the- // checkerboard and reused each frame by the compositor's mask colorize path.+ // Lazy mask tiles keyed by style/color; solid fills cache null.const maskPatternTiles = new Map<string, RasterSurface | null>();const getMaskPatternTile = (style: string, color: string): RasterSurface | null => {const key = `${style}:${color}`;@@ -520,9 +491,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCreturn maskPatternTiles.get(key) ?? null;};- // Memoized adjusted surfaces for raster layers carrying brightness/contrast/- // saturation/curves — rebuilt only when a layer's cache version or its- // adjustments change (never per frame). Reused each frame by the compositor.+ // Adjusted raster surfaces rebuild on cache-version or adjustment changes, not each frame.const derivedSurfaceCache = rasterController.derived;const deleteDerivedSurfaces = (layerId: string): void => rasterController.deleteDerivedSurfaces(layerId);const getAdjustedSurface = (layer: CanvasLayerContract, entry: LayerCacheEntry): RasterSurface | null => {@@ -536,8 +505,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCreturn rasterController.getAdjustedSurface(layer, entry);};- // Members draw through the guarded `getAdjustedSurface`, so the pixel-edit- // double-apply guard holds inside groups too.+ // Use guarded adjusted surfaces inside groups too, preventing double application during pixel edits.const groupSurfaces = createGroupSurfaceCache({createSurface: (width, height) => backend.createSurface(width, height),getAdjustedSurface: (layer, entry) => getAdjustedSurface(layer, entry),@@ -547,10 +515,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgroupSurfaces.get(scope, members, matrices, excludeIds);/**- * Re-reads the live cache sizes into the memory budget. Both caches change- * outside the budget's knowledge (a rasterize grows one, an eviction shrinks- * the other), so every allocation decision has to re-sync first or it reserves- * against a stale total.+ * Resync actual cache sizes before every allocation: rasterization and eviction change memory outside the+ * budget's accounting.*/const syncMemoryBaselines = (): void => {rasterController.memory.setBaseBytes(layerCache.byteSize());@@ -564,19 +530,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreClet applicationEscapeHandler: ((gestureWasActive: boolean) => boolean) | null = null;/**- * A layer's CURRENT document source (raster/control layers only), or `null`- * if the layer doesn't exist / isn't a source-bearing layer. Shared by the- * bitmap store's source-type flush guard and `onLayersChanged`'s self-echo- * check below — both need the same "what does this id currently point at"- * lookup. Reads `mirror` by closure; safe because neither caller invokes it- * before `mirror` is assigned further down.+ * Current layer source shared by persistence guards and self-echo checks. The closure is called only after+ * `mirror` initialization.*/const getLayerSourceById = (layerId: string): CanvasLayerSourceContract | null => {const doc = mirror.getDocument();const layer = getDocumentLayer(doc, layerId);- // Masks expose their alpha bitmap as a synthetic `paint` source so the bitmap- // store's source-type/redundant-dispatch guards and the mirror's self-echo- // check work uniformly across paint layers and masks.+ // Synthetic paint sources let masks share persistence source guards and self-echo detection.return layer ? renderableSourceOf(layer) : null;};@@ -586,12 +546,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};/**- * Applies a persisted bitmap ref + offset to a layer's document contract — the- * bitmap store's single swap-on-success dispatch. Raster/control layers take a- * `paint` source (`updateCanvasLayerSource`); mask layers take their `mask`- * bitmap + offset (`updateCanvasLayerConfig`, preserving the fill). The self-echo- * `lastApplied` name the store records covers both, so a mask flush round-tripping- * back through the mirror is skipped for re-rasterization exactly like a paint one.+ * Swap persisted refs/offsets via paint-source actions for raster/control or mask-config actions preserving+ * fill. Self-echo tracking covers both, avoiding redundant rasterization.*/const dispatchLayerBitmap = (layerId: string, bitmap: CanvasImageRef, offset: { x: number; y: number }): boolean => {const doc = mirror.getDocument();@@ -622,10 +578,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};/**- * Clears a layer's persisted bitmap, for a layer the paint-cache trim found empty.- * The counterpart to {@link dispatchLayerBitmap}, routed the same way per layer- * type. The resulting source is byte-identical to a brand-new layer's, so an- * emptied layer is indistinguishable from a fresh one downstream.+ * Clear empty paint/mask bitmaps through type-specific actions, restoring the same source state as a fresh empty+ * layer.*/const clearLayerBitmap = (layerId: string): boolean => {const doc = mirror.getDocument();@@ -653,10 +607,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};/**- * True while something other than persistence owns or frames a layer's pixels, so- * the paint-cache trim defers rather than moving the extent underneath it. ANY new- * session kind that reads a layer's cache rect belongs here — notably the transform- * session, whose frame and bake are both expressed relative to that rect.+ * Defer trim while another operation owns or frames the pixels. Include every session that depends on cache+ * bounds, especially transform frame/bake.*/const isLayerBusyForTrim = (layerId: string): boolean => {if (pipeline.isGestureActive()) {@@ -678,9 +630,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCreturn !!layer && isCurrentRasterizationJob(layer);};- // Paint persistence: debounced PNG encode → SHA-256 dedupe → upload → a single- // swap-on-success `updateCanvasLayerSource` (paint) / `updateCanvasLayerConfig`- // (mask). Wired to committed strokes below.const bitmapStore: BitmapStore =opts.bitmapStore ??createBitmapStore({@@ -702,8 +651,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetLayerSource: getLayerSourceById,getLayerSurface: (layerId) => {const entry = layerCache.get(layerId);- // Content-sized: skip empty (zero-rect) caches — nothing to persist — and- // carry the cache's content-rect origin as the paint source offset.if (!entry || entry.rect.width <= 0 || entry.rect.height <= 0) {return null;}@@ -713,19 +660,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCreportError(info.willRetry ? 'Bitmap persistence failed' : 'Bitmap persistence suspended',layerId,- // `willRetry === false` means the circuit just opened: strokes stop- // persisting from here until a fresh one closes it. That is more- // urgent than whatever error tripped it, so the toast leads with it- // instead of the (already-surfaced, on the streak's first report)- // underlying error text.+ // Lead circuit-opening feedback with persistence stopping until a fresh stroke, rather than repeating+ // the underlying error.info.willRetry ? error : new Error('Canvas changes are no longer uploading. A new stroke will retry.')),uploadImage: (blob) => opts.uploadImage(blob),});const persistenceController = new PersistenceController(bitmapStore);- // Engine-owned canvas history (paint pixel patches + structural patches).- // Project-level undo deliberately no longer covers the canvas (Phase 0).const historyController = new HistoryController({canEdit: () => canEditDocument(),canRedoStore: stores.canRedo,@@ -761,29 +703,16 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst endNudgeBurst = (): void => structuralController.endBurst();/**- * 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 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.+ * Undo/redo restores cache pixels and marks dirty. An in-flight newer upload self-echoes without replacing+ * restored pixels; the serialized follow-up flush persists the restored state.*/const applyImagePatch: ImagePatchApply = (layerId, rect, pixels) => {if (!layerCache.get(layerId)) {// The layer's cache is gone (removed/evicted); nothing to restore into.return;}- // The patch `rect` is in LAYER-LOCAL coordinates (stable across cache growth).- // Grow the cache to cover it before writing — an undo/redo whose region falls- // outside the current (possibly shrunk-since) extent must re-expand the cache- // rather than write out of bounds. `growToRect` preserves existing pixels.+ // Grow to the layer-local patch rect before writing; undo/redo may reach beyond a cache trimmed since capture.const entry = layerCache.growToRect(layerId, rect);- // Match the paint hot path: write pixels straight into the live cache surface- // (no re-rasterize from source), translated to the surface's local origin,- // then bump version/thumbnail and recomposite.entry.surface.ctx.putImageData(pixels, rect.x - entry.rect.x, rect.y - entry.rect.y);notifyLayerPainted(layerId);// Re-persist the restored pixels (converges the contract ref; see above).@@ -791,13 +720,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};/**- * REPLACES a layer's whole cache with a fresh content-sized surface holding- * `pixels` placed at `rect` (layer-local). Unlike {@link applyImagePatch} (which- * grows + overlays a dirty region into a persistent cache), this swaps the entire- * cache extent — used by the transform bake's undo/redo, where the pre- and- * post-bake states occupy DIFFERENT rects (an overlay would leave stale pixels- * outside the smaller rect). Shields the pixels from the async rasterize pass and- * re-persists through the normal dirty path.+ * Replaces the whole cache with pixels at a layer-local rect. Transform undo/redo needs exact extent replacement+ * to remove stale pixels outside smaller bounds; shield from rasterization and mark dirty.*/const restoreLayerCache = (layerId: string, rect: Rect, pixels: ImageData): void => {layerCache.delete(layerId);@@ -838,10 +762,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};/**- * A composed history entry for a stroke that auto-created its paint layer.- * Undo removes the created layer (its cache is dropped by the mirror, so no- * pixel restore is needed); redo re-adds the layer, recreates a blank cache,- * and re-applies the stroke's `after` pixels.+ * Auto-created stroke history removes the layer on undo; redo recreates its blank cache and reapplies+ * after-pixels.*/const { commitOrdinaryStroke } = createStrokeCommit({applyImagePatch,@@ -855,13 +777,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCstrokeListeners,});- // ---- Selection (transient interaction state) + marching ants ------------- //- // The selection lives on the engine, never the reducer, and is not undoable- // (legacy parity). The lasso tool commits paths through `commitSelection`; the- // mask clips paint strokes and drives fill/erase. Marching ants animate on the- // overlay only (never recomposite — Task-22 gate) while a selection exists and- // the engine is attached.+ // Engine-owned selection masks clip strokes and drive fill/erase. Marching ants redraw only the overlay while+ // selection exists and the engine is attached.let antsPhase = 0;@@ -1002,11 +919,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst selection = editingController.selection;const floatingSelection = editingController.floatingSelection;- /**- * The float's render inputs for the current frame: the compositor's- * layer-local placement, and the document-space matrix the ants ride through- * so the outline tracks the pixels in flight.- */+ /** Resolve layer-local float placement and the matching document-space ants transform for the frame. */const nowMs = (): number =>typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now();@@ -1058,10 +971,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC}/**- * A one-shot sample claim from a picker's eyedropper button. Press/drag- * stash `sampledHex`; the RELEASE settles (the gesture is over, so the- * caller may commit structurally). Escape, tool switch, and teardown settle- * `null`, so the awaited promise never dangles.+ * One-shot color claims stash samples during press/drag and settle on release, after structural edits are+ * allowed. Escape, tool change and teardown resolve null.*/let pendingColorSample: {previousToolId: ToolId;@@ -1107,8 +1018,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC},getSelectionMask: () => selection.mask(),getStrokeClipRect: () => {- // Legacy "clip strokes to bbox". Read at gesture start, so moving the frame- // mid-stroke cannot change where the stroke already landed.+ // Capture bbox clipping at gesture start so moving the frame cannot alter the active stroke.const doc = mirror.getDocument();return stores.clipToBbox.get() && doc ? { ...doc.bbox } : null;},@@ -1176,13 +1086,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCapplyCursorToInput(cursor);};- /**- * Resizes the brush/eraser cursor ring in place when the active tool's size- * changes without a pointer event (`[`/`]` hotkeys, ctrl+wheel, or the- * options-bar slider). The ring's radius otherwise stays stale until the next- * pointermove; here we keep its last-known center and just refresh the radius,- * then invalidate the overlay so it redraws immediately.- */+ /** Size changes without pointer events update the cursor radius at its last center and invalidate the overlay. */const refreshBrushCursorRadius = (): void => {if (!overlayCursor) {return;@@ -1383,13 +1287,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst copyLayerToRaster = (layerId: string): Promise<string | null> => layerController.copy.copyToRaster(layerId);/**- * Rasterizes a single layer on demand and returns its cache surface plus the- * content rect (layer-local origin/size) those pixels occupy, for the- * composite-for-generation executor. Rasterize-or-throw: a missing layer, a- * non-raster/control layer, or an unsupported source throws a descriptive error- * rather than returning a blank surface, so an invoke can never silently drop a- * contributing layer. Only invoked for layers the pure planner already selected- * (enabled image/paint rasters).+ * Returns rasterized layer pixels with local content bounds for generation. Missing, ineligible or unsupported+ * layers throw so exports cannot silently omit selected contributors.*/type LayerSurfaceForExportResult =| { status: 'ok'; surface: RasterSurface; rect: Rect }@@ -1455,25 +1354,16 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCreturn;}- // The composited document only needs redrawing when pixels, layer order, or- // the viewport transform changed. An overlay-ONLY invalidation (the common- // hover case: a cursor-ring move dispatches `{ overlay: true }`) must NOT- // recomposite: the screen canvas retains its last frame, and the overlay is- // redrawn on top. Skipping the composite here is the single biggest zoom-lag- // win — a full composite up-scales every doc-sized layer surface to fill the- // screen, and that fill-rate grows with zoom, so recompositing on every hover- // move at high zoom is exactly the reported "laggier the closer you zoom in".+ // Only pixel, ordering and viewport changes need recomposition. Overlay-only hover retains the screen frame,+ // avoiding layer upscaling whose fill cost grows with zoom.const samPreview = renderController.previews.getSam();- // Resolved once: the composite draws the float's pixels, the overlay rides- // the ants through the matching document-space transform.+ // Resolve float placement once so composite pixels and selection ants agree.const floatRender = floatingSelectionFrame(floatingSelection.get(), doc);if (flags.all || flags.view || flags.layers.size > 0) {compositeFrame.draw(screen, doc, view, floatRender, samPreview, flags.damage);}- // The overlay is cheap (a handful of screen-space strokes, independent of- // zoom and document size) and shares the `view` transform with the composite,- // so redraw it whenever any frame runs — including overlay-only frames.+ // Redraw the screen-space overlay on every frame to match the composite's view transform.renderOverlay(overlay, overlayFrame.describe(doc, view, floatRender, samPreview));};@@ -1549,10 +1439,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// ---- Document mirror ----------------------------------------------------const mirror: DocumentMirror = createDocumentMirror(mutationPort, {- // The bbox rectangle/handles are overlay chrome, so a bbox move is normally- // overlay-only (no recomposite). The one exception: a legacy/progress staged- // preview is drawn in the COMPOSITE at the current bbox origin, so it must- // recomposite to follow the bbox. Explicitly placed candidates do not.+ // Bbox changes need only overlay redraw unless a bbox-relative staged preview must move in the composite.+ // Explicitly placed candidates stay fixed.onBboxChanged: () => {const staged = renderController.previews.getStaged();scheduler.invalidate(staged && !staged.placement ? { all: true } : { overlay: true });@@ -1566,36 +1454,22 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst previousImageNames = rasterController.mirroredImageNames();cleanup.run(() => rasterController.invalidateDocument());cleanup.run(() => stores.thumbnailStatus.clear());- // A wholesale document swap — project switch, dims/background change, or a- // snapshot restore that changes dims — invalidates the pixel history: its- // entries reference layers/pixels that no longer describe the live document.- //- // Cancel any in-flight tool gesture FIRST: a swap mid-drag leaves stale tool- // state (a bbox `startBbox`, a move drag anchor) whose pointer-up would- // otherwise commit against the replaced document. Routing through the- // pipeline clears `gestureActive` and runs the tool's `onPointerCancel`, so- // the tool drops its own transient state.- // Defensive: a non-bbox active tool won't have cleared a lingering preview.+ // Whole-document swaps invalidate pixel history. Cancel the pointer gesture first to discard stale tool+ // anchors and clear active-gesture state; also clear any lingering bbox preview.cleanup.run(() => stores.bboxPreview.set(null));cleanup.run(() => history.clear());cleanup.run(endNudgeBurst);- // A transform session (which outlives individual gestures) belongs to the- // outgoing document; tear it down alongside its preview override.cleanup.run(() => stores.transformSession.set(null));cleanup.run(() => transformOverrides.clear());// A text-edit session likewise belongs to the outgoing document; drop it.cleanup.run(() => stores.textEditSession.set(null));- // A staged preview belongs to the outgoing document's bbox/candidates; a- // wholesale swap (project switch, snapshot restore) invalidates it.cleanup.run(clearStagedPreview);// Per-layer control-filter previews likewise belong to the outgoing// document — a swap can reuse a layer id with different content, so// pruning only "missing" ids isn't enough; drop them all.cleanup.run(clearAllFilterPreviews);- // The selection is document-scoped interaction state: a swap drops it (and- // any in-progress lasso preview), stopping the ants loop via onChange.- // A float belongs to the outgoing document's layer. Cancel (not commit):- // the layer it would bake into is about to be replaced.+ // Drop document-scoped selection/lasso state and cancel outgoing floats; committing would target a replaced+ // layer.cleanup.run(() => floatingSelection.cancel());cleanup.run(() => editingController.discardSelection());cleanup.run(() => stores.lassoPreview.set(null));@@ -1619,21 +1493,15 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(() => rasterController.untrackLayerImage(layerId));}}- // A wholesale replacement can reuse a layer id with a DIFFERENT source, so- // a surviving cache entry may hold pixels from the outgoing document.- // Invalidate EVERY id in the incoming document — not just ids whose- // reference happened to change — to force a re-rasterize from the new- // source; a diff can't be trusted across a full swap.+ // Invalidate every incoming cache on wholesale replacement: reused ids may still hold outgoing pixels,+ // regardless of reference diffs.for (const layerId of present) {cleanup.run(() => invalidateLayerCache(layerId));}for (const imageName of previousImageNames) {cleanup.run(() => releaseBitmapIfUnreferenced(imageName));}- // Persistence bookkeeping (the self-echo `lastApplied` map and pending- // debounced flushes) described the OLD document. Drop it so a reused layer- // id can't have its next legit persistence dispatch suppressed as a stale- // self-echo.+ // Discard old-document self-echo and pending persistence state before ids are reused.cleanup.run(() => bitmapStore.reset());cleanup.run(() => scheduler.invalidate({ all: true }));cleanup.throwIfFailed();@@ -1682,13 +1550,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCrasterController.deleteMirroredImage(id);}}- // A transform session outlives individual gestures (and any tool switch,- // including a temp modifier-hold), so it can easily outlive its own layer- // being deleted out from under it — e.g. deleted via the layers panel- // while the pointer is elsewhere, or while temp-switched to view/colorPicker.- // Tear it down (session + preview override) the same way a document- // replace does, rather than leaving a ghost session/override pointing at- // a layer id that no longer exists.+ // Remove transform sessions and preview overrides when their layer disappears, even during temporary tool+ // switches.const session = stores.transformSession.get();const textSession = stores.textEditSession.get();for (const id of ids) {@@ -1709,12 +1572,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCif (releaseImageName) {cleanup.run(() => releaseBitmapIfUnreferenced(releaseImageName));}- // A control-filter preview (session + decoded surface) belongs to a- // specific layer; a layer removed out from under an in-flight or- // already-decoded preview (delete via the layers panel, or an undo- // that removes it) must have its preview dropped and its decode- // token bumped, or a late-resolving decode — or a later undo that- // restores this same id — would repopulate a stale preview.+ // Removed preview layers must drop decoded pixels and advance decode tokens so late results or restored+ // ids cannot revive stale previews.cleanup.run(() => clearFilterPreview(id));if (decision.cancelTransformSession) {cleanup.run(cancelTransform);@@ -1749,14 +1608,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.throwIfFailed();},/**- * The layers panel is the sole authority on which layer is active, so a- * panel selection has to retarget the engine's per-layer transient state.- * Nothing here dispatches — this only reconciles engine-side state.- *- * A selection-only document change reuses the `layers` array reference and- * leaves the bbox equal, so none of the other callbacks fire for it: without- * this the move-tool outline and the transform frame would keep framing the- * previously selected layer until some unrelated edit invalidated the overlay.+ * Panel selection is authoritative. Reconcile transient sessions and selection chrome without dispatch;+ * selection-only edits reuse stacks/bbox and trigger no other callback.*/onSelectionChanged: (selectedLayerId) => {const cleanup = createCleanupAccumulator();@@ -1765,8 +1618,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(() => floatingSelection.commit());const session = stores.transformSession.get();if (session && session.layerId !== selectedLayerId) {- // The open session belongs to the layer that was just deselected; drop- // its preview rather than leaving a frame on an inactive layer.cleanup.run(() => cancelTransform());if (selectedLayerId !== null && interactionController.getActiveToolId() === 'transform') {cleanup.run(() => beginTransformSession(selectedLayerId));@@ -1787,8 +1638,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst document = mutationPort.getCanvasState()?.document;const stacks = document?.stacks ?? null;const draft = document ? stores.textEditSession.get()?.source : undefined;- // The text defaults are active too: the pane previews them, and the next- // created text rasterizes with them.+ // Text defaults also affect pane previews and the next created layer.const options = document ? stores.textOptions.get() : undefined;if (stacks === fontSourceStacks && draft === draftFontSource && options === defaultsFontOptions) {return;@@ -1849,13 +1699,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCprojectWasPresent = projectIsPresent;});- // ---- Viewport → stores/scheduler ----------------------------------------- // Set while `resize` drives `setViewportSize` synchronously: the resize path- // composites in the same task (the anti-strobe fix), so the viewport- // subscription must NOT also schedule a `{ view: true }` frame — that pending- // flag would recomposite identical content on the next rAF (a second full- // composite per ResizeObserver event during a panel-drag resize).+ // During synchronous resize repaint, suppress viewport frame scheduling to avoid a second identical composite+ // next animation frame.let suppressViewportInvalidate = false;const unsubscribeViewport = viewport.subscribe(() => {@@ -1865,41 +1710,24 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC}});- // ---- Tool-option / setting stores → overlay + recomposite ---------------- //- // A brush/eraser size change must resize the cursor ring even with no pointer- // event; toggling the checkerboard must recomposite the document.const unsubscribeBrushOptions = stores.brushOptions.subscribe(refreshBrushCursorRadius);const unsubscribeEraserOptions = stores.eraserOptions.subscribe(refreshBrushCursorRadius);const unsubscribeCheckerboard = stores.checkerboard.subscribe(() => scheduler.invalidate({ all: true }));- // New checker colors (theme/color-mode switch): drop the cached tile so it- // rebuilds with the fed colors on the next composite, then force a recomposite.const unsubscribeCheckerColors = stores.checkerColors.subscribe(() => {checkerboardTile = null;scheduler.invalidate({ all: true });});- // The grid lives on the (cheap) overlay; toggling it or changing its snap size- // only needs an overlay redraw, never a recomposite.const unsubscribeShowGrid = stores.showGrid.subscribe(() => scheduler.invalidate({ overlay: true }));const unsubscribeBboxGrid = stores.bboxGrid.subscribe(() => {if (stores.showGrid.get()) {scheduler.invalidate({ overlay: true });}});- // The bbox frame, bbox overlay shade, and rule-of-thirds guides live on the- // (cheap) overlay; toggling any only needs an overlay redraw, never a- // recomposite. (`snapToGrid` is a pure interaction preference the bbox tool- // reads on gesture — no render effect.)+ // Bbox frame, shade and guides need only overlay redraw. Snap preference has no render effect.const unsubscribeShowBbox = stores.showBbox.subscribe(() => scheduler.invalidate({ overlay: true }));const unsubscribeBboxOverlay = stores.bboxOverlay.subscribe(() => scheduler.invalidate({ overlay: true }));const unsubscribeRuleOfThirds = stores.ruleOfThirds.subscribe(() => scheduler.invalidate({ overlay: true }));- // ---- Pointer / wheel / key input ---------------------------------------- //- // Normalization, capture, coalescing, temp-tool holds, and gesture cancel live- // in the pointer pipeline; wheel routing (zoom vs brush-size step) lives in the- // wheel handler. The engine just supplies seams and wires the DOM listeners.-/** Steps the active brush/eraser diameter by one notch (ctrl+wheel or the `[`/`]` hotkeys). */const stepActiveBrushSize = (direction: 1 | -1): void => {if (interactionController.getActiveToolId() === 'brush') {@@ -1933,10 +1761,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCupdateCursor,});/**- * Settles a pending one-shot color sample. `restoreTool` puts the user back- * on whatever they were holding before reaching for the eyedropper; callers- * that are themselves switching tools skip it, so the switch they asked for- * wins rather than being immediately undone.+ * Settle a pending sample, optionally restoring the previous tool. Tool-switch callers skip restoration so their+ * requested switch wins.*/const settleColorSample = (hex: string | null, restoreTool: boolean): void => {const pending = pendingColorSample;@@ -1958,11 +1784,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCinteractionController.setTool(toolId, options);};- /**- * Arms the eyedropper for one sample; resolves `#rrggbb` on pointer release- * (after the gesture, so the caller may commit structurally) or `null` on- * cancel. Reads the composited document, not the screen.- */+ /** Samples the document composite and resolves hex on release, after the gesture, or null on cancellation. */const requestColorSample = (): Promise<string | null> => {// A second request supersedes the first; the earlier caller gets a cancel.settleColorSample(null, false);@@ -1974,15 +1796,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};/**- * The engine's Escape priority ladder, run by the pointer pipeline AFTER it- * cancels any in-flight gesture, matching the planned chain "gesture → text- * session → transform → deselect": cancel an open text-edit session, else an- * open transform session, else deselect. A focused text portal consumes Escape- * itself (stopPropagation), so this window-level handler only reaches a- * defocused-but-open text session. Deselect is suppressed when a drag just- * consumed the Escape (`gestureWasActive`), so a mid-lasso Escape drops only the- * in-progress path, never the committed selection. Exposed for the pipeline- * wiring and node tests (the real DOM keydown listener can't run in node-env).+ * After gesture cancellation, Escape cancels defocused text editing, then transform, then selection. Focused+ * portals handle Escape themselves. If a gesture consumed Escape, preserve committed selection. Shared with+ * pipeline wiring and node tests.*/const handleEscapePriority = ({ gestureWasActive }: { gestureWasActive: boolean }): void => {// An armed eyedropper is the most recent thing the user opted into, so it@@ -2000,9 +1816,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCreturn;}if (floatingSelection.has()) {- // Escape ABANDONS a float: the lifted pixels go back where they came from- // and the selection stays, so the move can simply be redrawn. Committing- // instead is what Enter / deselect / a tool switch do.+ // Escape restores lifted pixels while retaining selection; Enter, deselect and tool switches commit the+ // float.floatingSelection.cancel();return;}@@ -2039,13 +1854,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCviewport,});- // ---- Lifecycle: shrink the paint-loss window ---------------------------- //- // Unload cannot be reliably blocked, so these are fire-and-forget kicks that- // narrow the gap between the last paint and its upload; the real barrier is- // `flushPendingUploads()`, which invoke/export await. `blur` additionally- // resets the pointer pipeline so a held space/alt temp tool doesn't strand- // when the window loses focus mid-hold.+ // Lifecycle flushes reduce paint-loss exposure but cannot reliably block unload; invoke/export await the actual+ // barrier. Blur also resets held temporary tools.const kickPendingFlush = (): void => {// Lifecycle events cannot await this best-effort flush. Real persistence// failures are already reported through BitmapStore.onError; consume the@@ -2157,10 +1967,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};const resize = (cssWidth: number, cssHeight: number, dpr: number): void => {- // Suppress the viewport subscription's `{ view: true }` invalidate: the- // synchronous `render` below already repaints this size change, so letting the- // subscription schedule a frame would composite the identical result again on- // the next rAF (two full composites per resize event).+ // Suppress viewport invalidation because the same-task render already repaints this resize.suppressViewportInvalidate = true;viewport.setViewportSize(cssWidth, cssHeight, dpr);suppressViewportInvalidate = false;@@ -2168,13 +1975,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst backingWidth = Math.round(cssWidth * backingDpr);const backingHeight = Math.round(cssHeight * backingDpr);renderController.resize(backingWidth, backingHeight);- // Composite SYNCHRONOUSLY, in this same task, right after the backing-store- // resize. Sizing a `<canvas>` backing store clears it, so deferring the- // recomposite to the next rAF (the normal dirty-path) leaves a blank frame- // on screen until then — during a continuous panel-drag resize that reads as- // a flash/strobe. A same-task repaint lands before the browser paints, so the- // canvas never shows empty. `all: true` forces the composite through the T22- // dirty gate; `render` no-ops when detached (no surfaces).+ // Resize clears canvas pixels; force full recomposition in the same task to prevent a blank browser frame.+ // Detached rendering is a no-op.render({ all: true, damage: null, layers: new Set<string>(), overlay: true, view: true });};@@ -2185,9 +1987,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCif (!doc) {return;}- // The document rect is no longer a spatial boundary — fit content ∪ bbox. The- // bbox (generation frame) is the primary anchor, so an empty canvas fits it;- // any renderable layer beyond the bbox is unioned in so it lands in view.+ // Fit content union bbox, using the bbox as the empty-canvas anchor and including content beyond it.let bounds: Rect = { ...doc.bbox };for (const leaf of compileDocumentLeaves(doc)) {if (leaf.contributionEnabled && isRenderableLayer(leaf.layer)) {@@ -2199,15 +1999,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};/**- * Fits the document into view only if this engine has never fitted it.- *- * A surface attaches every time the canvas widget is put on screen, and the- * shell keeps widgets mounted across layout switches — so returning to a- * layout re-attaches the surface and an unconditional fit would throw away- * whatever zoom and pan the user had set. The engine outlives the hide (it is- * leased per project and released with a grace period), so it is the thing- * that knows whether this is genuinely the canvas's first showing. A fresh- * engine has no viewport worth preserving and fits as before.+ * Fit only once per engine. Kept-alive widgets reattach after layout switches, and the project engine preserves+ * their existing zoom/pan.*/const fitToViewOnFirstShow = (): void => {if (hasEverFitToView) {@@ -2235,12 +2028,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst { layerId } = prepared;const target = layerCache.installReplacement(prepared);- // Allocation and raster drawing happen in prepareGeneratedPaintCache().- // Once a document mutation has been dispatched and this detached cache has- // been installed, observer/scheduling/persistence hooks are notifications:- // none may veto the already-applied document+cache transaction. In normal- // production code these hooks do not throw; containment protects the- // transaction from a faulty subscriber or host scheduling implementation.+ // After prepared cache installation and document dispatch, observer, scheduler and persistence hooks only+ // notify; their failures cannot veto the completed transaction.const notifyBestEffort = (notify: () => void): void => {try {notify();@@ -2540,14 +2329,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst rasterizeLayer = (layerId: string): boolean => layerController.rasterize.rasterize(layerId);- // ---- Transform session --------------------------------------------------- //- // The transform tool opens a session on one layer (start/live transform in- // `stores.transformSession`, preview via `transformOverrides`) that outlives- // individual pointer gestures. Apply commits — a param edit for image layers,- // a pixel bake for paint layers — as ONE undoable entry; Cancel drops the- // preview. The transform tool drives begin/update/cancel through the tool- // context; React (numeric bar + Apply/Cancel buttons) drives the public API.+ // Transform sessions span gestures. Apply records one undoable parameter edit for image layers or pixel bake for+ // paint; Cancel drops previews. Tools and public UI share the session API.const beginTransformSession = (layerId: string): void => editingController.transform.begin(layerId);const updateTransformSession = (transform: LayerTransform): void => editingController.transform.update(transform);@@ -2568,15 +2351,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCeditingController.transform.apply();};- // ---- Text editing session ------------------------------------------------ //- // The text tool opens a session (create or edit) exposed through- // `stores.textEditSession`; React renders a contenteditable portal over it and- // drives the commit (blur / mod+enter) — the engine never sees per-keystroke- // content, so commit takes the final content from React. ONE commit per close:- // create → `addCanvasLayer` (inverse removes), edit → `updateCanvasLayerSource`- // (exact inverse). A no-change / empty-create commit dispatches nothing (cancel- // semantics). The options bar restyles the live session via `updateTextEditStyle`.+ // Text sessions expose a portal with DOM-owned typing until commit. Creation/add or source update records one+ // undo entry; unchanged edits and empty creation cancel. Live style changes remain in session state.const setTextEditContentReader = (reader: (() => string) | null): void =>editingController.text.setContentReader(reader);@@ -2598,14 +2374,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// ---- Selection public API -----------------------------------------------/**- * The bounded domain selectAll/invert operate over now that the document rect is- * retired: `content ∪ bbox` — the same union `fitToView` fits. The bbox anchors- * an empty canvas; any renderable layer beyond it is unioned in. The closest- * coherent analogue of legacy's bounded canvas for the complement in `invert`.+ * Select-all and invert use content union bbox as their bounded domain, matching fit-to-view and anchoring empty+ * canvases.*/- // Every selection-level operation banks a live float first: the pixels are- // already cut, and the op that follows must see the document the user does.- // (Escape is the one path that abandons instead — see `handleEscapePriority`.)+ // Commit live floats before selection operations so they see displayed pixels; Escape instead abandons the+ // float.const selectAll = (): void => {floatingSelection.commit();editingController.selectAll();@@ -2628,11 +2401,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCeditingController.selectionPixels.run('erase');};- /**- * The selection's pixels on the active layer, encoded as a PNG. Reuses the- * float's own masked-copy step (it never mutates the source — the cut is a- * separate call), so Copy and a lift always take exactly the same pixels.- */+ /** Copy reuses the float's nonmutating masked-copy path so clipboard and lift select identical pixels. */const exportSelectionBlob = (): Promise<Blob | null> => {floatingSelection.commit();const doc = mirror.getDocument();@@ -2693,11 +2462,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(() => rasterExportController.dispose());cleanup.run(cancelAllLayerRasterizations);cleanup.run(detach);- // Drop any open text-edit session (its layer belongs to a document this- // engine no longer serves).cleanup.run(() => stores.textEditSession.set(null));- // Drop any guarded filter previews outright — the engine is going away, so- // there's no render loop left to invalidate for them.cleanup.run(() => antsAnimator.stop());// No render loop left to sample with; release any awaited eyedropper.cleanup.run(() => settleColorSample(null, false));@@ -2741,14 +2506,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};const clearCaches = async (): Promise<void> => {- // Flush pending paint-bitmap uploads FIRST: an unflushed stroke lives only in- // the live `layerCache` until the debounced (1500ms) flush persists it. If we- // invalidated the cache before flushing, that in-flight stroke would be- // destroyed — the next composite re-rasterizes from the (older) source.+ // Flush paint before invalidating caches; otherwise rerasterizing the older persisted source would erase+ // unuploaded strokes.await persistenceController.flush();const doc = mirror.getDocument();- // Invalidate (mark stale → re-rasterize) every live layer cache and drop its- // memoized adjusted surface; the next composite rebuilds them from source.for (const layer of getDocumentLeaves(doc)) {invalidateLayerCache(layer.id);deleteDerivedSurfaces(layer.id);@@ -2778,12 +2539,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};/**- * Whether the canvas context menu may target a layer at all. It never picks a- * layer by hit-testing — the menu acts on the document's selected layer, since- * the layers panel is the sole authority on which layer is active. This only- * suppresses the menu during an in-progress edit: a live paint/drag gesture, or- * an open transform / text-edit session. Right-click during those belongs to- * the interaction. Mirrors the mid-gesture guards on merge/nudge/undo above.+ * Menus target the selected layer without hit testing. Suppress them during gestures, transforms and text+ * editing, when right-click belongs to the interaction.*/const canTargetLayerFromContextMenu = (): boolean =>!pipeline.isGestureActive() &&@@ -2811,8 +2568,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCsyncMemoryBaselines();return rasterController.memory.reserveOperation(bytes, { purpose: 'invocation-composite' });},- // Generation inputs, not layer pixels: nothing in the document will point at- // these, so they upload as intermediates rather than durable images.+ // Unreferenced generation inputs upload as reclaimable intermediates.uploadImage: (blob) => opts.uploadIntermediateImage(blob),});const exportRasterComposite = (request: RasterCompositeExportRequest) =>@@ -3142,9 +2898,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCupdateTextEditStyle,updateTransformSession,};- // The Overview pane's document composite: fit the whole document into the- // target at thumbnail scale through the canonical compositor, so ordering,- // blend modes, transforms, adjustments and mask fills match the main surface.let overviewRequestedDoc: CanvasDocumentContractV3 | null = null;const overviewRequestedLayerIds = new Set<string>();const drawDocumentOverview = (target: HTMLCanvasElement, maxSizePx: number): Rect | null => {@@ -3153,12 +2906,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCif (!doc || !ctx || doc.width <= 0 || doc.height <= 0) {return null;}- // The frame path rasterizes only what its viewport demands and the budget- // may evict what it culled; the overview wants everything, so ask for the- // missing caches and heal on the next content-epoch repaint (a publish- // bumps it). One request per layer per document: a source that cannot- // rasterize must not be retried (and re-toast) on every repaint. It never- // pins: under real memory pressure the budget still wins over the navigator.+ // Overview requests missing offscreen caches and repaints after publication. Attempt each layer once per+ // document to avoid repeated failures; never pin against memory-budget eviction.if (overviewRequestedDoc !== doc) {overviewRequestedDoc = doc;overviewRequestedLayerIds.clear();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.tsindex 608654b406..08eea6bc3b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts@@ -1,14 +1,6 @@/**- * Per-engine transient external stores.- *- * These are the narrow, imperative channels React subscribes to (in the widget- * task) to observe engine-owned interaction state — active tool, zoom,- * readiness, cursor, and per-layer thumbnail versions — without the engine ever- * importing React. They follow Platform's React-free external-store core (a- * listener channel plus a snapshot getter, `useSyncExternalStore`-compatible).- * The React hooks live with the widget shell.- *- * Zero React, zero import-time side effects.+ * Per-engine React-free external stores expose narrow interaction snapshots and subscriptions. Widget hooks adapt+ * them to React without coupling the engine to UI.*/import type {@@ -42,10 +34,8 @@ export interface BrushOptions {/** Whether pen pressure modulates the stroke width. */pressureAffectsWidth: boolean;/**- * Whether pen pressure modulates the stroke's alpha along its length.- *- * Off by default: unlike width, it costs a full-region scratch refill per frame (see- * `strokeSession`), and it changes how a stroke reads rather than just its shape.+ * Pressure-alpha is off by default: unlike width modulation it refills the full scratch region each frame and+ * changes stroke appearance.*/pressureAffectsOpacity: boolean;}@@ -74,11 +64,6 @@ export const DEFAULT_LASSO_OPTIONS: LassoToolOptions = {shape: 'freehand',};-/**- * Marquee (selection) tool options: the shape the next drag traces, and the- * boolean op it applies when no modifier overrides it. One tool covers both- * shapes — see `tools/marqueeTool.ts`.- */export interface MarqueeToolOptions {kind: 'rect' | 'ellipse';/** The op a committed marquee applies to the selection, when no modifier overrides it. */@@ -98,10 +83,8 @@ export interface GradientStop {}/**- * Shape tool options: the kind drawn on the next drag, plus whether the new- * shape gets a fill and a stroke. The colors themselves come from the active- * foreground/background pair at gesture start — there is no second global- * shape color; a selected shape's explicit fill/stroke is document state.+ * Next-shape kind and fill/stroke toggles. Colors come from foreground/background at gesture start; selected-shape+ * colors belong to the document.*/export type ShapeToolKind = ParametricShapeKind | 'polygon' | 'freehand';@@ -131,11 +114,8 @@ export const DEFAULT_SHAPE_OPTIONS: ShapeToolOptions = {export const MAX_SHAPE_STROKE_WIDTH = 2000;/**- * Gradient tool options: the kind, the linear angle (degrees), the preset, and- * the explicit custom stops. The `pair` preset resolves the foreground →- * background pair at gesture start; `custom` uses `stops` verbatim. The- * minimal two-stop editor edits `stops[0]` (start) and the last stop (end);- * a full multi-stop editor is a follow-up.+ * Gradient kind, angle, preset and custom stops. Pair resolves foreground/background at gesture start; custom uses+ * stops verbatim. The editor changes first and last stops.*/export interface GradientToolOptions {kind: 'linear' | 'radial';@@ -176,9 +156,8 @@ export const DEFAULT_GRADIENT_OPTIONS: GradientToolOptions = {};/**- * The text style the text tool applies to a newly created layer (and edits- * live). A new session's color comes from the active foreground at open; the- * session's and a selected layer's color are document/session state.+ * New-text defaults and live style. Initial color comes from foreground; active session and selected-layer colors+ * are independently stored.*/export interface TextToolOptions {fontFamily: string;@@ -196,11 +175,6 @@ export interface TextToolOptions {align: 'left' | 'center' | 'right';}-/**- * A small curated font list offered by the text options bar. Values are CSS- * `font-family` stacks so each falls back gracefully; keep it short this phase- * (a full system-font enumeration is a follow-up).- */export const TEXT_FONT_FAMILIES: readonly { label: string; value: string }[] = [{ label: 'Inter', value: "'Inter Variable', Inter, sans-serif" },{ label: 'Sans-serif', value: 'system-ui, sans-serif' },@@ -277,11 +251,8 @@ export const DEFAULT_ERASER_OPTIONS: EraserOptions = {};/**- * An active transform-tool session on one layer. Outlives individual pointer- * gestures (drag handles, adjust numerics) until Apply or Cancel. `startTransform`- * is the committed transform captured at session start (restored on Cancel /- * used as the undo inverse); `transform` is the live, edited transform the- * compositor previews and the options bar renders as numerics.+ * Transform sessions span gestures until Apply/Cancel. `startTransform` is the committed undo/cancel baseline;+ * `transform` drives preview and numeric controls.*/export interface TransformSession {layerId: string;@@ -290,23 +261,11 @@ export interface TransformSession {}/**- * An active text-editing session. Set by the text tool; while it is active the- * contenteditable portal (in `widgets/canvas`) shows the live text and the- * compositor SKIPS the session's layer (edit mode) so the two don't double-draw.- *- * Two modes:- * - **create**: no layer exists yet (`layerId === null`, `startSource === null`).- * Commit dispatches ONE `addCanvasLayer` with the final content; cancel adds- * nothing. This keeps a new text layer to a single, cleanly-undoable commit.- * - **edit**: an existing text layer is being re-edited. `startSource` is its- * committed source (the exact undo inverse / no-change baseline); `source` is- * the live, style-edited source. Commit dispatches ONE `updateCanvasLayerSource`.+ * Text sessions suppress the edited layer while its portal renders. Create has no layer/start source until one add+ * commit; edit keeps `startSource` as undo and no-change baseline for one source-update commit.*- * `source` carries the live style (font/size/weight/lineHeight/align/color) the- * portal renders WYSIWYG and the options bar edits; `content` on it is only the- * seed — the live typed content lives in the contenteditable DOM until commit.- * `transform` positions/scales the portal (document→screen via the view matrix).- * `id` increments per session so React can key (remount) the editable per open.+ * `source` holds live styles but only seeded content; typing stays in the DOM until commit. `transform` places the+ * portal, and incrementing `id` remounts it per session.*/export interface TextEditSession {id: number;@@ -348,11 +307,7 @@ const createScalarStore = <T>(initial: T, isEqual: (a: T, b: T) => boolean = Obj};};-/**- * A keyed numeric store with per-key subscription granularity, so a React- * component watching one layer's thumbnail version only re-renders when that- * layer changes. A global `subscribe` is also exposed for coarse observers.- */+/** Per-key subscriptions rerender only the affected thumbnail; global subscription supports coarse observers. */export interface KeyedVersionStore {get(key: string): number | undefined;set(key: string, value: number): void;@@ -478,11 +433,7 @@ export interface EngineStores {rasterContentEpoch: ScalarStore<number>;/** Brush tool options (size / color / opacity / pressure). */brushOptions: ScalarStore<BrushOptions>;- /**- * The workbench's foreground/background pair, mirrored in for gesture-start- * reads (new shapes, text sessions, the gradient pair preset). One-way: the- * engine never writes it.- */+ /** One-way foreground/background mirror for gesture-start reads; the engine never writes it. */colorPair: ScalarStore<ActiveColorPairState>;/** Eraser tool options (size / opacity). */eraserOptions: ScalarStore<EraserOptions>;@@ -505,125 +456,53 @@ export interface EngineStores {/** Text tool options (font family / size / weight / line-height / align). */textOptions: ScalarStore<TextToolOptions>;/**- * The active text-editing session, or `null`. React reads it to render the- * contenteditable portal and enable the text options bar's live-restyle path;- * the engine reads it to skip the session layer in the composite. Cleared on- * commit, cancel, real tool switch, layer delete, or document replace.+ * Text session drives the portal, live style controls and composite suppression. Commit, cancel, real tool+ * switch, deletion or replacement clears it.*/textEditSession: ScalarStore<TextEditSession | null>;- /**- * The live shape-tool drag preview (document-space rect + kind), or `null`- * when idle. The overlay renders the shape outline in place of a committed- * layer so the drag tracks without dispatching; cleared on commit/cancel.- */+ /** Document-space shape preview replaces dispatch during drag; null when idle, cleared on commit/cancel. */shapePreview: ScalarStore<{ rect: Rect; kind: ParametricShapeKind } | null>;- /**- * The live gradient-tool drag preview: the drag vector's start/end points in- * document space. The overlay draws a linear ramp as the vector and a radial- * one as the circle it will fill. `null` when idle; cleared on commit/cancel.- */+ /** Document-space gradient drag vector; overlay shows a linear ramp or radial circle. Cleared on commit/cancel. */gradientPreview: ScalarStore<GradientPreview | null>;- /**- * Whether a pixel selection currently exists. React reads it to enable the- * fill/erase/invert/deselect controls and the engine gates selection hotkeys- * and marching-ants animation off it. The engine writes it as the selection- * mask gains/loses content.- */hasSelection: ScalarStore<boolean>;- /**- * Whether pixels are currently in flight as a floating selection. React reads- * it to enable the transform bar's Apply/Cancel while a float is framed (there- * is no `transformSession` in that case — the float is the session).- */+ /** Floating pixels enable Apply/Cancel without a separate transform session. */hasFloatingSelection: ScalarStore<boolean>;/** Core-only visual SAM interaction state; application session status remains outside the engine. */samInteraction: ScalarStore<SamInteractionState | null>;/**- * The in-progress lasso outline (document space), or `null` when idle. The- * overlay draws a freehand drag as a dashed outline; a polygon session also- * shows its placed vertices, the rubber band to the cursor, and whether the- * cursor sits on the first vertex (a click there closes). Cleared on- * commit/cancel. Like `bboxPreview`, a transient channel — no dispatch.+ * Transient lasso overlay: freehand outline or polygon vertices, cursor band and close target. Cleared on+ * commit/cancel without dispatch.*/lassoPreview: ScalarStore<LassoPreview | null>;- /**- * The live marquee-tool drag outline (document-space rect + shape), or `null`- * when idle. Like `lassoPreview`, a transient overlay-only channel: the mask- * is untouched until the drag commits.- */+ /** Transient marquee outline; the selection mask changes only on commit. */marqueePreview: ScalarStore<{ rect: Rect; kind: 'rect' | 'ellipse' } | null>;- /**- * Whether brush/eraser strokes are clipped to the generation frame (legacy- * "clip strokes to bbox"). Resolved once per gesture by the paint tool.- */+ /** Legacy bbox stroke clipping, captured once per paint gesture. */clipToBbox: ScalarStore<boolean>;/** Model-dependent grid size (document px) the bbox snaps to. React feeds this from generate settings. */bboxGrid: ScalarStore<number>;/**- * The live bbox preview rect during a bbox-tool gesture (document space), or- * `null` when idle. The overlay renders this in place of the committed bbox so- * the frame tracks the drag without dispatching; cleared on commit/cancel.+ * Document-space bbox preview replaces the committed overlay frame during drag without dispatch. Cleared on+ * commit/cancel.*/bboxPreview: ScalarStore<Rect | null>;- /**- * The active transform-tool session (layer id + start/live transform), or- * `null` when no session is open. React reads it to render the numeric options- * and enable Apply/Cancel; the engine drives the live preview from it. Cleared- * on Apply, Cancel, tool switch, or document replace.- */+ /** Transform session supplies numeric controls, Apply/Cancel and live preview; null when closed. */transformSession: ScalarStore<TransformSession | null>;- /**- * Whether the transparency checkerboard is drawn behind transparent documents- * (default ON). Off shows the widget surface through the document instead. The- * compositor reads this each frame; the canvas settings menu toggles it.- */+ /** Checkerboard defaults on; disabling reveals the widget surface through transparent document pixels. */checkerboard: ScalarStore<boolean>;/**- * The two square colors of the transparency checkerboard, resolved from Chakra- * semantic tokens in React and fed down (see `widgets/canvas/checkerColors.ts`).- * The engine rebuilds its cached checker tile and recomposites when these- * change (e.g. a theme/color-mode switch); {@link DEFAULT_CHECKER_COLORS} is the- * React-free fallback until the first feed.+ * React supplies semantic checker colors; changes rebuild the tile and recompose. {@link DEFAULT_CHECKER_COLORS}+ * supplies the React-free initial fallback.*/checkerColors: ScalarStore<CheckerColors>;- /**- * Whether the document-space grid (at the bbox snap size) is drawn on the- * overlay (default OFF). The overlay reads this each frame; the canvas settings- * menu toggles it.- */showGrid: ScalarStore<boolean>;- /**- * Whether ctrl+wheel brush/eraser sizing is inverted (default OFF): normally- * wheel-up grows the size. The wheel handler reads this; the canvas settings- * menu toggles it. Purely an input preference — no render effect.- */+ /** Inverts ctrl+wheel sizing; default wheel-up grows. Input-only preference. */invertBrushSizeScroll: ScalarStore<boolean>;- /**- * Whether the generation bbox (dashed frame) is drawn as passive overlay chrome- * (default ON). The overlay reads this each frame; the canvas settings popover- * toggles it. The bbox is still drawn (with its handles) while the bbox TOOL is- * active regardless, so it stays editable — this only hides the passive frame.- */+ /** Passive bbox frame defaults on. The active bbox tool always draws its editable frame and handles. */showBbox: ScalarStore<boolean>;- /**- * Whether the bbox overlay shade is drawn (default OFF): a translucent dark- * fill over everything OUTSIDE the bbox, focusing attention on the generation- * region (legacy `CanvasBboxToolModule` overlayRect parity). Overlay-only —- * toggling never recomposites the document.- */+ /** Optional shade outside the generation bbox. Overlay-only toggling never recomposites document pixels. */bboxOverlay: ScalarStore<boolean>;- /**- * Whether the rule-of-thirds composition guide (two vertical + two horizontal- * lines dividing the bbox into thirds) is drawn inside the bbox (default OFF).- * The overlay reads this each frame; the canvas settings popover toggles it.- */ruleOfThirds: ScalarStore<boolean>;- /**- * Whether bbox-tool moves/resizes snap to the model grid (default ON). The bbox- * tool reads this; the canvas settings popover toggles it, and the fit-bbox- * header actions honor it too. Holding Alt bypasses snapping independently.- * Purely an interaction preference — no render effect.- */+ /** Bbox moves, resizes and fit actions use grid snapping by default; Alt bypasses it. Input-only preference. */snapToGrid: ScalarStore<boolean>;/** Whether an engine-owned operation currently excludes ordinary document edits. */documentEditingLocked: ScalarStore<boolean>;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.tsindex 4a5ebe0f52..83ef76ca8d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts@@ -1,43 +1,11 @@/**- * Export raster layers to a Photoshop (.psd) document.+ * PSD export separates pure geometry planning from raster baking, lazy `ag-psd` serialization and download.+ * Reverse every top-first tree level for ag-psd's bottom-first children; omit empty leaves/folders and size the+ * document to exported world bounds.*- * Split into a PURE planner and an IMPURE executor, mirroring the- * planner/executor split of `compositeForGeneration.ts`:- *- * - {@link planPsdExport} is pure geometry (no DOM, no `ag-psd`, no engine): it- * turns each raster layer's transform + content rect into a PSD layer entry- * (position, opacity, blend, hidden, order) and the document bounds. Unit- * tested in node.- * - {@link executePsdExport} is the side-effecting half: it bakes each layer's- * pixels through the {@link RasterBackend} seam, lazily imports `ag-psd`- * (`writePsd`) at call time so the library never enters the main bundle, and- * triggers a browser download. Verified by types + manual QA (opening the PSD).- *- * ### Conventions- * - **Order.** The canvas document stores nodes top-first (index 0 = top-most) at- * every level of the raster tree. ag-psd's `children` array is BOTTOM-to-top- * (`children[0]` is the bottom-most layer, written first to the PSD layer- * records, which the format stores bottom-up). So the plan reverses every- * level of the top-first input into bottom-to-top.- * - **Folders.** Groups become pass-through PSD folders with their own name and- * visibility; a folder whose subtree exports nothing is dropped with it. The- * flat leaf order is the depth-first order of the tree, which is also the- * visual order because groups do not composite in isolation.- * - **Bounds.** The PSD canvas is the union of every EXPORTED layer's- * world-space (document-space) content AABB — document/bbox-independent. An- * empty union means nothing to export.- * - **Opacity.** ag-psd's `Layer.opacity` is 0..1 (the writer multiplies by 255- * internally), NOT 0..255. Our `layer.opacity` is already 0..1, so it passes- * through unchanged (clamped).- * - **Hidden.** Every raster layer with content is exported; a layer disabled in- * its own right is written with `hidden: true` rather than dropped, and a- * disabled group becomes a hidden folder. The merged preview flattens only the- * leaves that contribute (enabled with every ancestor enabled), which is what- * Photoshop shows for the same flags.- * - **Adjustments.** Non-destructive raster adjustments are BAKED into the- * layer's pixels (PSD has no matching non-destructive representation we emit),- * exactly as `compositeForGeneration` bakes them, so the PSD matches what the- * user sees. Opacity/blend stay as PSD layer properties (not baked).+ * Export disabled content as hidden layers/folders; flatten only effectively enabled content for the merged+ * preview. Opacity stays in [0,1]. Bake raster adjustments into pixels, but retain opacity/blend as PSD+ * properties.*/import type { CanvasAdjustmentsContract, CanvasBlendMode, CanvasColorLabel } from '@workbench/canvas-engine/contracts';@@ -51,11 +19,7 @@ import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engimport { applyAdjustments } from '@workbench/canvas-engine/render/adjustments';import { blendToComposite } from '@workbench/canvas-engine/render/compositor';-/**- * Maximum PSD side length. ag-psd/Photoshop tolerate up to 300000px, but a- * multi-gigabyte export from an unbounded-canvas union helps nobody — refuse- * past a sane cap and tell the user. Legacy Photoshop's own PSD limit is 30000.- */+/** Cap exports at the legacy PSD 30000px side limit to bound unbounded-canvas allocations. */export const PSD_MAX_DIMENSION = 30000;/** A canvas layer transform (TRS), duplicated to keep this module contract-light. */@@ -68,10 +32,8 @@ export interface PsdLayerTransform {}/**- * Maps a document blend mode to ag-psd's blend key. Every blend mode the canvas- * supports has a direct PSD equivalent (Photoshop is the origin of these modes),- * so this is total; an unknown value falls back to 'normal' and is reported via- * {@link PsdExportOk.unmappedBlends}.+ * Maps supported blends to PSD keys; unknown values fall back to normal and populate {@link+ * PsdExportOk.unmappedBlends}.*/const BLEND_MODE_TO_PSD: Record<CanvasBlendMode, BlendMode> = {color: 'color',@@ -210,13 +172,8 @@ const layerMatrix = (t: PsdLayerTransform): Mat2d => fromTRS({ x: t.x, y: t.y },const clamp01 = (value: number): number => (value < 0 ? 0 : value > 1 ? 1 : value);/**- * Plans a PSD export from the raster tree (top-first at every level). Computes- * each layer's world-space AABB, unions them for the PSD canvas, and produces- * per-layer PSD entries in bottom-to-top order plus the folder tree they sit in.- * Layers with no content (empty rect, or a degenerate zero-area transform)- * contribute nothing and are omitted, and so is any folder left without a leaf.- * Returns `empty` when nothing has content and `too-large` when the union- * exceeds the dimension cap.+ * Plans world-AABB union bounds and a bottom-first PSD tree. Omit empty/degenerate leaves and empty folders;+ * return empty or too-large when applicable.*/export const planPsdExport = (inputs: readonly PsdExportNodeInput[],@@ -224,8 +181,8 @@ export const planPsdExport = (): PsdExportPlan => {const maxDimension = options.maxDimension ?? PSD_MAX_DIMENSION;- // Leaves in depth-first (visual, top-first) order with their effective enablement, and the- // world-space AABB of each (null = no content: empty local rect or a zero-area transform).+ // Top-first depth-first leaves with effective enablement and world bounds; null bounds indicate empty or+ // degenerate content.const withBounds: { input: PsdExportLayerInput; contributes: boolean; worldRect: Rect | null }[] = [];const walk = (nodes: readonly PsdExportNodeInput[], enabled: boolean): void => {for (const node of nodes) {@@ -361,11 +318,7 @@ const defaultReadImageData = (surface: RasterSurface, rect: Rect): ImageData =>const defaultWriteImageData = (surface: RasterSurface, imageData: ImageData, x: number, y: number): void =>surface.ctx.putImageData(imageData, x, y);-/**- * Serializes a {@link Psd} to bytes via a LAZILY-imported `ag-psd`, so the- * library is never pulled into the main bundle (Vite code-splits the dynamic- * import into its own chunk, loaded only when an export runs).- */+/** Lazy-loads `ag-psd` only for serialization, keeping it out of the main bundle. */const defaultWritePsd = async (psd: Psd): Promise<ArrayBuffer> => {const { writePsd } = await import('ag-psd');return writePsd(psd);@@ -383,11 +336,7 @@ export interface ExecutePsdExportDeps {backend: { createSurface(width: number, height: number): RasterSurface };/** Cancels before the next background allocation or side effect. */signal?: AbortSignal;- /**- * Ensures a layer's cache is rasterized and returns its surface plus the- * content `rect` (layer-local origin/size) those pixels occupy. The engine- * wires this to its rasterize path (reading live paint caches when present).- */+ /** Returns rasterized pixels and local content bounds, using live paint caches when available. */getLayerSurface(layerId: string): Promise<{ surface: RasterSurface; rect: Rect }>;/** Reads a surface region's pixels (default `getImageData`). */readImageData?(surface: RasterSurface, rect: Rect): ImageData;@@ -411,10 +360,8 @@ const throwIfAborted = (signal?: AbortSignal): void => {};/**- * Bakes one planned layer's pixels into a world-AABB-sized surface: draws the- * layer's cache through its transform (offset into the AABB), then bakes any- * non-destructive adjustments in place. Opacity/blend are NOT baked — they ride- * on the PSD layer. Returns the surface + its straight-alpha `ImageData`.+ * Bakes transformed pixels and adjustments into world-AABB bounds, returning surface and straight-alpha ImageData.+ * Opacity/blend remain PSD properties.*/const bakeLayer = async (planLayer: PsdPlanLayer,@@ -453,10 +400,8 @@ const bakeLayer = async (};/**- * Executes a PSD export plan: bakes each layer, flattens the enabled layers into- * a merged composite (so Photoshop/Bridge show a correct preview — ag-psd does- * NOT regenerate the composite), assembles the {@link Psd}, serializes via the- * lazily-imported `ag-psd`, and triggers a download. No-op for a non-`ok` plan.+ * Bakes layers, builds the enabled merged preview (ag-psd does not generate it), serializes and downloads. Non-ok+ * plans do nothing.*/export const executePsdExport = async (plan: PsdExportPlan,@@ -507,11 +452,8 @@ export const executePsdExport = async ();const children = toChildren(plan.tree);- // Flatten the contributing tree (bottom-to-top at every level) into the merged- // composite the PSD carries as its full-document preview. A folder with- // non-default opacity/blend is isolated into a buffer first — readers apply- // those properties to the folder's composite, and the preview must match the- // file's own layers.+ // Flatten bottom-first. Isolate folders with opacity/blend so the merged preview matches readers' folder+ // compositing.throwIfAborted(deps.signal);const surfaceById = new Map(baked.map(({ planLayer, surface }) => [planLayer.id, surface]));const drawPreview = (ctx: Ctx, nodes: readonly PsdPlanNode[]): void => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/fontReferences.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/fontReferences.tsindex 1dac3fbd35..108c379be7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/fontReferences.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/fontReferences.ts@@ -189,9 +189,8 @@ const replaceNodes = (};/**- * Replaces every exact reference in a document while sharing untouched trees.- * `targetAxes` is empty for a static face, so all source variation coordinates- * are intentionally reset and included in the summary.+ * Replaces exact font refs with structural sharing. Static targets have no axes, so reset and report all source+ * variations.*/export const replaceCanvasFontReferences = (document: CanvasDocumentContractV3,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.tsindex 08248cdaa9..a8eb98ae06 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.ts@@ -38,11 +38,7 @@ const noise = (seed: number): (() => number) => {};};-/**- * A slow, near-straight drag advancing `speed` document units per sample. Below- * ~0.5 units/sample the jitter dominates the direction vector — the regime that- * used to fill the outline with spurious full-radius corner caps.- */+/** Near-straight samples below roughly 0.5 units per step expose jitter-driven false corner caps. */const slowDrag = (speed: number, jitter: number): StrokeSamplePoint[] => {const rand = noise(7);return Array.from({ length: 400 }, (_, i) => ({@@ -63,11 +59,8 @@ const arc = (radius: number, sweep: number): StrokeSamplePoint[] => {};/**- * The edge lengths along the body of a stroke outline — how coarsely it- * approximates the offset curve, which under any serialization is the visible- * faceting. Edges within `size` of either end are excluded: the caps are drawn- * with a fixed segment count rather than by the vertex cull, so they say nothing- * about body density.+ * Measure body-edge lengths as visible faceting; exclude end caps within `size`, whose fixed segmentation is+ * independent of vertex culling.*/const bodyEdgeLengths = (polygon: readonly Vec2[], points: readonly StrokeSamplePoint[], size: number): number[] => {const ends = [points[0]!, points[points.length - 1]!];@@ -206,8 +199,7 @@ describe('outlineSmoothing', () => {describe('stroke quality at large brush sizes', () => {it('does not let pointer jitter inflate the outline (spurious corner caps)', () => {- // Each >90° direction reversal splices a cap of the CURRENT radius into the- // outline, so jitter used to add hundreds of full-size lumps to a big brush.+ // Sharp jitter reversals insert current-radius caps, producing large brush lumps.const jittery = slowDrag(0.2, 1);const clean = slowDrag(0.2, 0);for (const size of [20, 100, 400, 1000, 2000]) {@@ -218,9 +210,7 @@ describe('stroke quality at large brush sizes', () => {});it('keeps outline vertex spacing bounded independently of brush size', () => {- // The library culls outline vertices closer than (size × smoothing), so a- // constant smoothing lets spacing — and with it the faceting — grow with the- // brush. On this arc a 400px brush used to reach 200-unit edges.+ // Constant smoothing scales vertex spacing with brush size; a 400px brush previously produced 200-unit edges.const curve = arc(1000, Math.PI / 2);for (const size of [50, 200, 400]) {const polygon = strokeOutlinePolygon(curve, { size, thinning: 0 });@@ -231,10 +221,8 @@ describe('stroke quality at large brush sizes', () => {});it('tracks pressure from the start of a large-brush stroke', () => {- // The library's start-of-stroke noise gate drops every intermediate point —- // and so every pressure reading — until the running length reaches `size`.- // Sized in document units instead of brush diameters, it no longer flattens- // the pressure ramp across the first 1000 units of a 1000px brush.+ // Gate stroke starts in document units so large brushes preserve early pressure samples instead of flattening+ // a diameter-long ramp.const size = 1000;const rampLength = 300;const stroke: StrokeSamplePoint[] = [];@@ -269,10 +257,6 @@ describe('polygonToSvgPath', () => {});});-/**- * A node-safe `Path2D` double that records the commands traced onto it, so the- * curve can be asserted without a DOM.- */const recordingPath = () => {const commands: string[] = [];const points: Vec2[] = [];diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.tsindex d2c9396558..9219c23d68 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts@@ -1,47 +1,9 @@/**- * A thin wrapper over `perfect-freehand`, turning a pressure-sampled point path- * into the filled outline polygon of a variable-width stroke.- *- * The polygon math ({@link strokeOutlinePolygon}) is pure and DOM-free, so it is- * fully unit-testable in node. `Path2D` does not exist in node, so building the- * fillable path is split out into {@link strokeToPath}, which takes an injected- * `createPath2D` factory (the engine passes `() => new Path2D()`; tests pass a- * recording stub). This keeps the interesting geometry testable without a DOM.- *- * ## Why this isn't a bare `getStroke` call- *- * `perfect-freehand` is tuned for pen-sized strokes; driven naively it degrades- * badly as the brush diameter grows, in three independent ways. Each is- * corrected here, and each correction is a no-op at small sizes:- *- * 1. **Input decimation** ({@link decimateSamples}). The library flags any turn- * sharper than 90° between consecutive point vectors as a corner and splices- * a cap of the CURRENT RADIUS into the outline. Nothing upstream decimates- * pointer input, so once the pointer advances less than ~0.5 document units- * per sample — a slow drag, a high-rate pen, or any zoom above ~2×, since- * document units per screen pixel shrink with zoom — sub-pixel jitter- * dominates the direction vector and fires those reversals constantly. At a- * 10px brush the spurious caps are invisible; at a 1000px brush each one is a- * 500px-radius lump. Distance-gating the samples removes them outright.- *- * 2. **Size-relative smoothing** ({@link outlineSmoothing}). `smoothing` feeds- * exactly one thing in the library: the `(size * smoothing)²` outline-vertex- * cull. Left at a constant, vertex spacing scales with the brush, so a large- * brush traces a smooth arc with edges hundreds of units long. Pinning the- * PRODUCT instead holds spacing near {@link TARGET_VERTEX_SPACING}.- *- * 3. **A decoupled start gate** ({@link START_GATE_SIZE}). `getStrokePoints`- * drops every intermediate point until the running length reaches `size`, to- * suppress start-of-stroke noise. Since `size` is the brush diameter, a 400px- * brush renders the first 400 document units as one straight capsule. Running- * the two library stages separately lets that gate keep its small absolute- * value while the outline stage gets the real diameter.- *- * Finally, the outline is traced as quadratic curves- * ({@link traceSmoothPolygon}) rather than the straight segments the lasso- * wants, so whatever facets remain read as curves.- *- * Zero React, zero import-time side effects.+ * Pressure-sampled strokes use pure outline geometry and an injected Path2D factory. Large brushes need three+ * corrections to perfect-freehand: decimate subpixel direction jitter that creates radius-sized corner caps; keep+ * size*smoothing near {@link TARGET_VERTEX_SPACING}; and use {@link START_GATE_SIZE} independently of brush+ * diameter to retain early pressure samples. {@link traceSmoothPolygon} uses quadratic curves for remaining+ * outline facets.*/import type { Rect, Vec2 } from '@workbench/canvas-engine/types';@@ -81,14 +43,8 @@ const DEFAULT_STREAMLINE = 0.5;const DEFAULT_THINNING = 0.5;/**- * Target spacing (document units) between adjacent outline vertices, held- * roughly constant across brush sizes by {@link outlineSmoothing}.- *- * Chosen against the QUADRATIC curve, not straight segments: at this spacing the- * rendered curve strays from the true offset curve by under 0.2 document pixels- * even where the stroke turns on a 60px radius. Going finer only multiplies- * vertices — the outline is re-tessellated and re-filled on every pointer batch,- * so vertex count is squarely on the hot path.+ * Size-independent outline spacing via {@link outlineSmoothing}, chosen for quadratic tracing. Finer spacing+ * increases per-pointer-batch tessellation and fill work.*/export const TARGET_VERTEX_SPACING = 24;@@ -122,26 +78,13 @@ const dist2 = (a: StrokeSamplePoint, b: StrokeSamplePoint): number => {export const sampleSpacing = (size: number): number =>Math.min(MAX_SAMPLE_SPACING, Math.max(MIN_SAMPLE_SPACING, size * SAMPLE_SPACING_RATIO));-/**- * The `smoothing` value that holds outline vertex spacing near- * {@link TARGET_VERTEX_SPACING} for a stroke of diameter `size`. Falls back to- * the library's own {@link DEFAULT_SMOOTHING} for brushes small enough that it- * already yields tight enough spacing.- */+/** Holds vertex spacing near {@link TARGET_VERTEX_SPACING}; small brushes retain {@link DEFAULT_SMOOTHING}. */export const outlineSmoothing = (size: number): number =>Math.min(DEFAULT_SMOOTHING, TARGET_VERTEX_SPACING / Math.max(size, 1));/**- * Drops input samples closer together than `spacing` (document units) so- * sub-pixel pointer jitter can't masquerade as a direction reversal — see the- * module docs.- *- * The scan is greedy left-to-right, so the samples retained for a prefix of- * `points` are themselves a prefix of those retained for the whole array: as new- * samples arrive mid-gesture, already-drawn geometry never shifts. The one- * exception is the final sample, which is retained only once `last` is set, so- * the completed stroke ends exactly under the pointer. Mid-gesture the head- * therefore trails by at most `spacing` (≤ {@link MAX_SAMPLE_SPACING}).+ * Distance-gates jitter with a greedy, prefix-stable scan so existing geometry stays fixed. Retain the exact final+ * sample only when `last`; live heads trail by at most spacing, bounded by {@link MAX_SAMPLE_SPACING}.*/export const decimateSamples = (points: readonly StrokeSamplePoint[],@@ -171,13 +114,8 @@ export const decimateSamples = (};/**- * Computes the filled outline polygon (a closed ring of document-space points)- * of a variable-width stroke through `points`. Pure and DOM-free.- *- * The two `perfect-freehand` stages are driven separately so the start-of-stroke- * noise gate (which `getStrokePoints` derives from `size`) can keep a small- * absolute value while the outline is built at the real brush diameter. Passing- * the same `size` to both is exactly equivalent to calling `getStroke`.+ * Pure document-space stroke outline. Separate perfect-freehand stages keep the start gate small while using the+ * real diameter for outline width.*/export const strokeOutlinePolygon = (points: readonly StrokeSamplePoint[], opts: FreehandOptions): Vec2[] => {if (points.length === 0) {@@ -223,24 +161,9 @@ export const polygonToSvgPath = (polygon: readonly Vec2[]): string => {};/**- * Traces an outline polygon onto `path` as a smooth closed curve, treating each- * vertex as the control point of a quadratic segment running between the- * midpoints of its two edges.- *- * The curve stays inside the convex hull of the polygon, so- * {@link polygonBounds} of the polygon bounds the rendered shape — which is what- * the dirty-rect accounting in the stroke session relies on. Collinear runs are- * reproduced exactly, so this only differs from {@link polygonToSvgPath} where- * the outline actually turns.- *- * Drawn with direct path calls rather than by building an SVG string for the- * browser to re-parse. A stroke's outline is re-traced on every pointer batch- * and runs to thousands of vertices, and at that size the round trip through a- * string costs an order of magnitude more than the drawing does — 3.31ms versus- * 0.18ms at 6000 samples — while describing exactly the same curve.- *- * Polygons with fewer than three vertices have no meaningful curvature and fall- * back to straight segments.+ * Trace quadratic segments between edge midpoints using vertices as controls. The curve stays inside the polygon+ * hull, preserving dirty bounds and collinear runs. Direct path calls avoid SVG parsing on each batch; fewer than+ * three vertices use lines.*/export const traceSmoothPolygon = (path: Path2D, polygon: readonly Vec2[]): void => {const n = polygon.length;@@ -295,15 +218,8 @@ export const polygonBounds = (polygon: readonly Vec2[]): Rect => {};/**- * Builds a fillable `Path2D` for the stroke through `points`, using the injected- * `createPath2D` factory (so callers in node can stub it). Returns the built- * path and the polygon's document-space {@link Rect} bounds so the caller can- * derive the dirty region without recomputing the outline.- *- * The path is the smooth ({@link traceSmoothPolygon}) form — the outline is a- * coarse sampling of a curve, so joining its vertices with straight lines would- * show as facets at large brush sizes. The returned bounds still come from the- * polygon, which encloses the curve.+ * Builds the smooth stroke path through an injected Path2D factory and returns enclosing polygon bounds, avoiding+ * duplicate outline computation.*/export const strokeToPath = (points: readonly StrokeSamplePoint[],diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.tsindex 2f2879a480..61ee2367a7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.ts@@ -1,8 +1,5 @@/**- * A structural history entry: a pair of reducer actions (forward + inverse)- * dispatched to undo/redo a document-shape change. Unlike a pixel- * {@link createImagePatchEntry | image patch}, it carries no bitmaps, so- * structural edits share the engine-owned undo stack with paint edits at a+ * Structural history stores forward/inverse reducer actions without bitmaps, sharing the pixel undo stack at* nominal byte cost.*/diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.tsindex 5c7a960a87..e31c26ba33 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts@@ -69,8 +69,6 @@ describe('createHistory: entry-count eviction', () => {for (let i = 0; i < HISTORY_MAX_ENTRIES + 1; i += 1) {history.push(makeEntry(`e${i}`, log));}- // Undo every retained entry: there should be exactly the cap, and the very- // first entry (e0) should have been evicted (never undone).let undos = 0;while (history.canUndo()) {history.undo();@@ -173,9 +171,7 @@ describe('createHistory: amendLast', () => {const log: string[] = [];const history = createHistory({ byteBudget: 25 });history.push(makeEntry('a', log, 10));- history.push(makeEntry('b', log, 10)); // burst start-- // Coalesce: replace 'b' with 'b2' (still one burst entry).+ history.push(makeEntry('b', log, 10));history.amendLast(makeEntry('b2', log, 10));let undos = 0;@@ -255,14 +251,10 @@ describe('createHistory: re-entrancy guard', () => {history.undo();expect(observed).toEqual([true]);expect(history.isApplying()).toBe(false);- // The sneaky push during undo was dropped: redo stack still holds only the- // reentrant entry, and no 'sneaky' entry is reachable.expect(history.canRedo()).toBe(true);history.redo();expect(observed).toEqual([true, true]);- // Still exactly one undoable entry (the reentrant one); the sneaky pushes- // never landed.let undos = 0;while (history.canUndo()) {history.undo();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.tsindex 54c23533ca..06d5926524 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts@@ -1,24 +1,7 @@/**- * Engine-owned canvas history: a bounded undo/redo stack of opaque entries.- *- * Project-level undo (`pushUndo` in the reducer) deliberately no longer covers- * the canvas (Phase 0) — pixels never cross the reducer boundary, so the reducer- * can't cheaply snapshot them. Instead the canvas keeps its OWN history here,- * living entirely inside the engine. Each {@link HistoryEntry} is a self-contained- * undo/redo pair (a paint {@link createImagePatchEntry | pixel patch} or a- * structural {@link createDocumentPatchEntry | document patch}) plus a byte cost- * used to bound memory.- *- * Budgets (evict oldest beyond EITHER dimension):- * - at most {@link HISTORY_MAX_ENTRIES} undo entries, and- * - at most {@link HISTORY_BYTE_BUDGET} bytes across both stacks.- *- * Re-entrancy: while an entry's `undo`/`redo` runs, {@link History.isApplying}- * is `true`. The engine's paint/apply paths check it and skip recording, and- * `push` is a hard no-op during apply — so replaying an entry can never spawn a- * new entry (which would corrupt the stacks).- *- * Zero React, zero DOM, zero import-time side effects.+ * Engine-owned opaque undo/redo entries account for pixel and structural edits. Evict oldest entries beyond {@link+ * HISTORY_MAX_ENTRIES} or {@link HISTORY_BYTE_BUDGET} across both stacks. During replay `isApplying` prevents+ * recording and `push` is a no-op, avoiding recursive history.*//** Max number of undo entries retained before the oldest is evicted. */@@ -64,10 +47,8 @@ export interface History {/** Records a new entry (clearing the redo stack) and enforces the budgets. No-op while applying. */push(entry: HistoryEntry): void;/**- * Replaces the most recent undo entry in place (adjusting the byte total),- * used to coalesce a rapid burst of same-target edits — e.g. arrow-key nudges —- * into a single reversible step. Falls back to {@link push} when the undo stack- * is empty. Clears the redo stack like `push`. No-op while applying.+ * Replaces the latest undo entry for coalescing, adjusts bytes and clears redo. Falls back to {@link push} if+ * empty; no-op during replay.*/amendLast(entry: HistoryEntry): void;/** Reverts the most recent entry (moving it onto the redo stack). No-op when empty or already applying. */@@ -174,8 +155,6 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {undoStack.push(entry);undoBytes += entry.bytes;enforceBudgets();- // A push always clears redo and grows undo, so both booleans may have moved- // (canUndo→true on the first push, canRedo→false when redo was non-empty).notify();};@@ -209,9 +188,8 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {return;}if (!entry.replayFailureAtomic) {- // Legacy callbacks may mutate their domain before an observer throws.- // Move first so a retry cannot apply that mutation twice. If replay- // clears history, `clear()` owns the notification and the reset wins.+ // Legacy replay may mutate before observer failure: move first to prevent duplicate retries. A replay-time+ // clear owns reset and notification.undoStack.pop();undoBytes -= entry.bytes;redoStack.push(entry);@@ -249,9 +227,7 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {if (undoStack.at(-1) !== entry) {return;}- // Move the entry only after replay succeeds. A fallible callback (for- // example detached raster-cache preparation) may throw before applying- // anything; keeping the stacks and byte totals untouched makes retry exact.+ // Fallible replay moves entries only after success, preserving stacks and byte totals for an exact retry.undoStack.pop();undoBytes -= entry.bytes;redoStack.push(entry);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/imagePatch.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/imagePatch.tsindex a7825d9411..2ff0000eb1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/imagePatch.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/imagePatch.ts@@ -1,21 +1,7 @@/**- * A paint-edit history entry: a before/after pair of `ImageData` over a- * LAYER-LOCAL rect, reversed by putting the pixels back into the layer's cache- * surface. Layer-local coordinates are stable across cache growth/reallocation- * (the cache's content rect origin can shift as strokes grow it), so an old- * entry replays correctly no matter how the cache has been resized since.- *- * Painting (P2.1) commits a stroke as a {@link StrokeCommittedEvent} carrying the- * `dirtyRect` plus `beforeImageData`/`afterImageData` (both sized to that rect).- * This wraps that pair into a {@link HistoryEntry}: undo puts `before`, redo puts- * `after`. The actual pixel write is delegated to an engine-provided- * {@link ImagePatchApply} so this module stays free of the cache/backend/bitmap- * store — it just owns the before/after bookkeeping and the byte accounting.- *- * Byte cost = both buffers' `byteLength`, which is what the history budget bounds.- *- * Zero React, zero DOM (ImageData is a plain data carrier here), zero import-time- * side effects.+ * Before/after pixel history uses layer-local rects, stable across cache growth and shifted origins. The+ * engine-provided {@link ImagePatchApply} owns writes and persistence; this entry accounts for both buffers' byte+ * lengths.*/import type { Rect } from '@workbench/canvas-engine/types';@@ -23,9 +9,8 @@ import type { Rect } from '@workbench/canvas-engine/types';import type { HistoryEntry } from './history';/**- * Writes `pixels` into `layerId`'s cache at `rect`'s origin and propagates the- * edit (invalidate/version bump + mark the layer dirty for persistence). Provided- * by the engine; the entry never touches the cache or backend directly.+ * Engine-owned pixel write at the layer-local rect, including invalidation/versioning and dirty persistence+ * marking.*/export type ImagePatchApply = (layerId: string, rect: Rect, pixels: ImageData) => void;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.tsindex fef214ce9f..4d9c8f009f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts@@ -390,8 +390,7 @@ describe('pointer pipeline: temporary modifier tools', () => {const h = createHarness();h.pipeline.onPointerEnter();h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space' }));- // Flagged `temporary` so a session-bearing tool (transform) can tell this- // apart from a real switch and keep its session alive across the hold.+ // Temporary switches preserve sessions across modifier holds.expect(h.setTool).toHaveBeenLastCalledWith('view', { temporary: true });h.pipeline.onKeyUp(makeKeyEvent({ code: 'Space' }));expect(h.setTool).toHaveBeenLastCalledWith('brush', { temporary: true });@@ -505,8 +504,6 @@ describe('pointer pipeline: temporary modifier tools', () => {const h = createHarness({ tools: ['view', 'brush', 'colorPicker'] });h.pipeline.onPointerEnter();- // Typing space/alt in an input, textarea, or contenteditable belongs to that- // field, not the canvas — the temp-tool hold must not fire.h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', target: { tagName: 'INPUT' } }));h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', target: { tagName: 'textarea' } }));h.pipeline.onKeyDown(makeKeyEvent({ code: 'AltLeft', target: { isContentEditable: true } }));diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.tsindex a2b8996241..90589e8438 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts@@ -1,24 +1,8 @@/**- * The pointer pipeline: normalizes raw DOM pointer/key events into the engine's- * {@link PointerInput} vocabulary and routes them to the active tool.- *- * Responsibilities lifted out of the engine so `engine.ts` stays lean:- * - Pointer capture on down; `getCoalescedEvents()` batching on move (so fast- * strokes keep every intermediate sample); mouse pressure defaulted to 0.5.- * - Middle-mouse pan (engine-level, tool-independent).- * - Modifier/key-hold temporary tools: space → view, alt → colorPicker, hold C- * → bbox (quick-tap C still sticky-selects bbox). The prior tool is restored- * on release. Temp switches are suppressed mid-gesture, and are- * flagged `{ temporary: true }` on `setTool` so a session-bearing tool- * (transform) can tell them apart from a real switch and keep its session- * alive across the hold.- * - Gesture cancellation: pointercancel and Esc route to the tool's- * `onPointerCancel`; secondary/extra buttons are ignored during a gesture.- *- * The pipeline reaches the DOM only through the injected `getInputElement`- * (for pointer capture / element rect) and the events passed to its handlers, so- * it is fully driveable by a fake harness in node tests. Zero React, zero- * import-time side effects.+ * Normalizes DOM events into tool input with capture, coalesced samples and default mouse pressure 0.5. Middle+ * mouse pans independently. Space, Alt and held C temporarily select view, picker and bbox; release restores the+ * tool, while quick C selects bbox persistently. Temporary switches preserve sessions and are blocked mid-gesture.+ * Escape/pointercancel cancel; extra buttons are ignored mid-gesture. DOM access is injected.*/import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';@@ -43,31 +27,20 @@ export interface PointerPipelineDeps {getActiveToolId(): ToolId;getToolContext(): ToolContext;/**- * Switches the active tool. `opts.temporary` marks a modifier-hold switch- * (and its matching restore) so a session-bearing tool's `onActivate`/- * `onDeactivate` can preserve its session instead of tearing it down — see- * {@link beginTempTool} / {@link endTempTool}.+ * Temporary modifier switches and restores preserve tool sessions; see {@link beginTempTool} and {@link+ * endTempTool}.*/setTool(id: ToolId, opts?: { temporary?: boolean }): void;hasTool(id: ToolId): boolean;updateCursor(): void;/**- * The engine's Escape priority, run AFTER the in-flight gesture is cancelled- * (and skipped in editable fields): cancel a transform session, else deselect.- * `gestureWasActive` tells it a drag just consumed this Escape, so it should- * cancel a session (session teardown is wanted mid-drag, matching the prior- * behavior) but NOT also deselect. Optional so minimal harnesses can omit it.- * See `engine.ts` `handleEscape`.+ * Optional Escape handler after gesture cancellation, skipped in editable fields. `gestureWasActive` allows+ * session teardown while preserving committed selection.*/handleEscape?(opts: { gestureWasActive: boolean }): void;/**- * Called on a primary-button pointerdown BEFORE any gesture starts. Returns- * `true` if the engine consumed the press to commit an open modal session (a- * text-edit session), in which case the pipeline swallows the press entirely —- * no capture, no gesture, no tool routing — because the click's sole job was to- * close the session (the next press then starts a fresh interaction). Running- * before `gestureActive` is set is what lets the commit through the engine's- * mid-gesture guard. Optional so minimal harnesses can omit it.+ * Optional primary-press hook before gesture activation. True consumes the press to commit a modal text session+ * without capture or tool routing, avoiding mid-gesture commit guards.*/maybeCommitModalSession?(): boolean;}@@ -82,18 +55,11 @@ export interface PointerPipeline {onPointerLeave(): void;onKeyDown(event: KeyboardEvent): void;onKeyUp(event: KeyboardEvent): void;- /**- * True while a primary-button paint/drag gesture is mid-stroke (pointer down,- * not yet up/cancel). The engine consults this to no-op undo/redo during a- * live stroke, so a mid-gesture mod+z can't inject pixels under the session.- */+ /** Primary gesture state blocks undo/redo from injecting pixels during live strokes. */isGestureActive(): boolean;/**- * Cancels an in-flight primary-button gesture the same way Esc/pointercancel- * do: releases pointer capture, runs the active tool's `onPointerCancel` (so it- * drops its own transient state), and refreshes the cursor. A no-op when no- * gesture is active. The engine calls this on a wholesale document replacement- * so a mid-drag swap can't commit against the outgoing document on pointer-up.+ * Cancels capture/tool state and refreshes the cursor. Used on document replacement so a later release cannot+ * commit stale drag state; idle calls do nothing.*/cancelActiveGesture(): void;/** Replaces a matching tool id that a currently-held temporary tool would restore on release. */@@ -110,11 +76,8 @@ const isBboxKey = (event: KeyboardEvent): boolean =>event.code === 'KeyC' && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey;/**- * True when the key event targets an editable element (text input, textarea, or- * a contenteditable node). The space/alt temp-tool holds are window-level, so- * without this guard typing a space in a rename field would hijack the canvas- * view tool. Duck-typed on `tagName`/`isContentEditable` so it stays node-safe- * (no `instanceof HTMLElement`, which throws where those globals are absent).+ * Editable targets retain their keys instead of activating temporary tools. Duck typing keeps this safe without+ * HTMLElement globals.*/const isEditableTarget = (target: EventTarget | null): boolean => {const el = target as { tagName?: unknown; isContentEditable?: unknown } | null;@@ -296,13 +259,8 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin},onKeyDown: (event) => {if (event.key === 'Escape') {- // Cancel any active drag first, then run the engine's Escape priority- // (cancel a transform session, else deselect). The editable guard keeps- // Escape in a text field from tearing down a canvas session/selection the- // field isn't part of. A mid-drag Escape cancels the gesture here; the- // subsequent `handleEscape` still sees (and cancels) a transform session- // the reverted drag kept open, matching the prior gesture+session teardown,- // but skips deselect so a mid-lasso Escape drops only the in-progress path.+ // Cancel the gesture before the engine Escape ladder. Editable fields keep Escape; gesture-consuming+ // Escape may cancel a session but must preserve committed selection.const gestureWasActive = gestureActive;cancelGesture();if (!isEditableTarget(event.target)) {@@ -310,9 +268,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin}return;}- // Never let space/alt temp-tool holds (or Enter apply) fire while the user is- // typing in an editable field (e.g. a layer rename input) — that key belongs- // to the field, not the canvas.+ // Editable fields own temporary-tool and Enter keys.if (isEditableTarget(event.target)) {return;}@@ -380,11 +336,8 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinif (event.button !== 0) {return;}- // A primary press while a text-edit session is open commits it (engine-side,- // reading the live portal content) and is swallowed — no gesture, no tool- // routing. This must precede `gestureActive = true` so the engine's- // mid-gesture commit guard cannot drop it. `preventDefault` avoids a stray- // focus/selection default now that the session has already been closed.+ // Commit and consume modal text presses before gesture activation; prevent default focus/selection after+ // closing the session.if (deps.maybeCommitModalSession?.()) {event.preventDefault();return;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheel.tsindex 96ec4770f2..f3b48345db 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheel.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheel.ts@@ -1,15 +1,6 @@/**- * Wheel routing for the canvas.- *- * - Plain wheel → the active tool's `onWheel` if it defines one, else viewport- * zoom about the cursor (the default navigation behavior).- * - Ctrl+wheel → when the active tool is brush/eraser, step its size; otherwise- * it is swallowed (reserved for the browser pinch-zoom gesture).- *- * The handler is a pure function of injected deps (viewport, the active tool, and- * a `stepActiveBrushSize` callback the engine wires to the tool-options stores),- * so it is driven directly in node tests. DOM is touched only through the passed- * `WheelEvent`. Zero React, zero import-time side effects.+ * Plain wheel routes to the tool or cursor-centered zoom. Ctrl+wheel sizes brush/eraser and is otherwise+ * swallowed. Injected dependencies keep routing testable without DOM setup.*/import type { InvalidatePayload } from '@workbench/canvas-engine/render/scheduler';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.tsindex 05fc06044d..15cc87ccdf 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts@@ -48,15 +48,9 @@ export interface LayerExportGuards {}/**- * The engine's answer to "are this layer's cached pixels trustworthy right now?"- *- * Every async commit in the engine — filter, generation, SAM, merge, export —- * captures a guard before it starts and re-checks it before it publishes. The- * guard is deliberately identity-based: it holds the layer *object* the caller- * saw, so any mutation that replaces the contract invalidates it even when the- * id and the pixels are unchanged. Cache version, document generation and- * project id cover the rest, and disposal or a torn-down canvas state- * invalidates everything at once.+ * Async pixel guards capture layer object identity, cache version, document generation and project id, then+ * recheck before publication. Any replacement, disposal or teardown invalidates the guard, even if pixels look+ * unchanged.*/export const createLayerExportGuards = (deps: CreateLayerExportGuardsDeps): LayerExportGuards => {const { layerCache } = deps;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.tsindex d6ccab2597..e4c21aef19 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts@@ -65,9 +65,8 @@ export interface CreateLayerRasterizerDeps {export interface LayerRasterizer {/**- * Starts — or joins — the rasterization of one layer, resolving with how it- * ended. Safe to call every frame: a job that already describes the same- * source, cache version and document generation is shared, not restarted.+ * Starts or joins rasterization for the same source, cache version and document generation; repeated frame+ * requests do not restart it.*/getOrStartLayerRasterization(layer: CanvasLayerContract,@@ -77,26 +76,10 @@ export interface LayerRasterizer {}/**- * Rasterizes a layer's source into its cache.- *- * Rasterizing is slow and the document is live, so a job never draws straight- * into the cache: pixels land in a scratch surface, and are copied across only- * if the job still describes the world it started in — same source (compared by- * value, since a reducer pass replaces objects wholesale), same cache version,- * same document generation, same job still installed, engine not disposed. Any- * of those moving means the result describes a layer that no longer exists in- * that form, and it is dropped as `'stale'` rather than published over whatever- * replaced it.- *- * The same check appears three times and is deliberately not shared. The- * post-success one holds the cache entry it is about to write to, so it can- * distinguish a deleted cache from a fresh one at version 0 — the two are- * indistinguishable through `version()` alone. The font-load one runs before- * any job is installed, so it has no job identity to compare.- *- * Text is the one source that can rasterize correctly and still be wrong: the- * font may not have loaded yet. Rather than block, it rasterizes with whatever- * is available and re-invalidates once the real font arrives.+ * Rasterize into scratch, publishing only if source value, cache version, document generation, installed job and+ * lifecycle still match. Post-success also checks cache-entry identity to distinguish recreation at version zero;+ * font callbacks run before job installation. Text renders available fonts immediately and invalidates when the+ * real face loads.*/export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRasterizer => {const { jobs, layerCache } = deps;@@ -233,8 +216,7 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRaslayerCache.version(layer.id) !== version ||!areJsonValuesStructurallyEqual(renderableSourceOf(currentLayer), source)) {- // The failure describes a layer that has already moved on; reporting it- // would surface an error about work nobody is waiting for.+ // Discard failures from obsolete work rather than reporting errors for replaced layers.return 'stale';}deps.thumbnails.setStatus(layer.id, 'error');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/mat2d.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/mat2d.tsindex cd6b641cc2..d320154699 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/mat2d.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/mat2d.ts@@ -1,27 +1,11 @@-/**- * Pure functions on `Mat2d`, the engine's 2D affine matrix type.- *- * Convention (matches `CanvasRenderingContext2D.setTransform`):- * ```- * x' = a*x + c*y + e- * y' = b*x + d*y + f- * ```- *- * No classes, no mutation — every function returns a new `Mat2d`.- */+/** Immutable 2D affine math matching canvas transforms: x' = a*x + c*y + e; y' = b*x + d*y + f. */import type { Mat2d, Vec2 } from '@workbench/canvas-engine/types';/** Returns the identity matrix. */export const identity = (): Mat2d => ({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });-/**- * Composes two matrices such that applying the result to a point is- * equivalent to applying `b` first, then `a` (i.e. `result = a * b`, using- * the same composition order as `DOMMatrix.multiply` / `ctx.transform`- * chaining: `a.multiply(b)` applies `b`'s transform in `a`'s coordinate- * space).- */+/** Returns a*b: apply b first, then a, matching DOMMatrix multiplication. */export const multiply = (a: Mat2d, b: Mat2d): Mat2d => ({a: a.a * b.a + a.c * b.b,b: a.b * b.a + a.d * b.b,@@ -67,12 +51,7 @@ export const applyToPoint = (m: Mat2d, p: Vec2): Vec2 => ({y: m.b * p.x + m.d * p.y + m.f,});-/**- * Composes a matrix from translation, rotation, and scale, in the order- * translate · rotate · scale — i.e. scale is applied first (in local- * space), then rotation, then translation. This is the standard TRS- * composition used for layer transforms.- */+/** Composes translate*rotate*scale, applying local scale first, then rotation and translation. */export const fromTRS = (translation: Vec2, rotationRad: number, scaleX: number, scaleY: number = scaleX): Mat2d => {let m = identity();m = translate(m, translation);@@ -82,11 +61,8 @@ export const fromTRS = (translation: Vec2, rotationRad: number, scaleX: number,};/**- * Extracts an approximate uniform scale magnitude from a matrix — the- * geometric mean of the transformed lengths of the unit x/y axis vectors.- * Useful for stroke-width and zoom math where an exact per-axis scale isn't- * needed. For a matrix with no shear/non-uniform scale this equals the- * true scale factor.+ * Approximate uniform scale from the geometric mean of transformed unit-axis lengths; exact for uniform scale+ * without shear.*/export const getScale = (m: Mat2d): number => {const scaleX = Math.hypot(m.a, m.b);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/rect.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/rect.tsindex 141aa54831..4d1fb13576 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/rect.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/rect.ts@@ -1,10 +1,3 @@-/**- * Pure functions on `Rect`, the engine's axis-aligned rectangle type.- *- * No classes, no mutation — every function returns a new `Rect` (or a- * primitive / array of `Rect`).- */-import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';import { applyToPoint } from './mat2d';@@ -61,11 +54,7 @@ export const expand = (r: Rect, margin: number): Rect => ({height: r.height + margin * 2,});-/**- * Rounds a rect outward to integer bounds (floor the min edges, ceil the- * max edges). Used to align dirty rects to pixel boundaries so patches- * fully cover the region that changed.- */+/** Round outward to integer pixels so dirty patches fully cover changed bounds. */export const roundOut = (r: Rect): Rect => {const x = Math.floor(r.x);const y = Math.floor(r.y);@@ -106,18 +95,8 @@ const isNearby = (a: Rect, b: Rect, slack: number): boolean => {};/**- * Coalesces a list of dirty rects into at most `maxRegions` rects.- *- * Algorithm: greedily merges any two rects that overlap or are within a- * small proximity slack (derived from the average rect size) whenever the- * merge doesn't waste too much area — specifically, whenever the merged- * rect's area is no more than 2x the sum of the two input areas, or the- * rects already overlap/touch. This repeats to a fixed point. If more than- * `maxRegions` rects remain, it falls back to merging everything into a- * single bounding rect (merge-all fallback) — simpler than picking which- * regions to keep, and cheap dirty-rect accounting favors correctness- * (never under-repaint) over minimizing painted area in the pathological- * case.+ * Greedily merge overlapping/touching or nearby rects when combined area stays within twice their sum. Repeat to+ * stability; if still over `maxRegions`, union all to guarantee repaint coverage.*/export const mergeDirtyRects = (rects: Rect[], maxRegions = 4): Rect[] => {const nonEmpty = rects.filter((r) => !isEmpty(r));diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.test.tsindex 87006be129..592b0f5bb2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.test.ts@@ -100,8 +100,7 @@ describe('constrainAspect', () => {it('keeps the sw corner fixed', () => {const result = constrainAspect(square, 0.5, 'sw');- // bottom edge (30) stays fixed; height = width / aspect... width kept? currentAspect(1) < aspect? no aspect=0.5 <1- // currentAspect(1) > aspect(0.5) -> keep width(20), height = width/aspect = 40+ // Keep width 20 and bottom edge 30; aspect 0.5 requires height 40.expect(result).toEqual({ x: 10, y: -10, width: 20, height: 40 });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.tsindex 97bcbab04f..5c972cc54f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.ts@@ -1,17 +1,6 @@-/**- * Pure snapping/clamping helpers for zoom, grid, and aspect-ratio math.- *- * No classes, no mutation — every function returns a new value.- */-import type { Rect, Vec2 } from '@workbench/canvas-engine/types';-/**- * The zoom levels the HUD dropdown offers. Presets only — wheel zoom is- * continuous and deliberately does NOT snap to these: a ~3% capture band around- * every level meant a slow scroll stalled at each one and had to be pushed out,- * which reads as the zoom sticking rather than as a helpful detent.- */+/** HUD presets only. Wheel zoom stays continuous because capture bands make slow scrolling stick at preset levels. */export const ZOOM_PRESETS: readonly number[] = [0.25, 0.33, 0.5, 0.67, 0.75, 1, 1.25, 1.5, 2, 3, 4, 5];/** Minimum allowed zoom, used by `clampZoom`. */@@ -32,14 +21,8 @@ export const snapToGrid = (value: number, grid: number): number => {};/**- * The snapped absolute position for a drag of `delta` away from `origin`.- *- * Snaps the RESULT, not the delta, so something that starts off-grid seats onto- * the grid instead of carrying its misalignment along forever.- *- * Per axis, and only for axes the drag actually moved: an axis with a zero delta- * (shift locked it, or the pointer simply never moved along it) is passed through- * untouched rather than being pulled onto a grid line the user never crossed.+ * Snap the resulting absolute position so off-grid origins align. Preserve axes with zero delta, avoiding+ * unintended movement on locked axes.*/export const snapMovedPoint = (origin: Vec2, delta: Vec2, grid: number): Vec2 => ({x: delta.x === 0 ? origin.x : snapToGrid(origin.x + delta.x, grid),@@ -58,13 +41,7 @@ export const snapRectToGrid = (rect: Rect, grid: number): Rect => {/** The corner or center kept fixed when `constrainAspect` resizes a rect. */export type AspectAnchor = 'nw' | 'ne' | 'sw' | 'se' | 'center';-/**- * Resizes `rect` to match `aspect` (width / height), keeping the named- * anchor point fixed. The rect's area is preserved as closely as possible- * by scaling both dimensions from the current size to fit the target- * aspect ratio (the dimension that would grow beyond the current bounding- * box is chosen based on which axis needs less change).- */+/** Resizes to width/height aspect while keeping the named anchor fixed. */export const constrainAspect = (rect: Rect, aspect: number, anchor: AspectAnchor): Rect => {if (aspect <= 0 || rect.width <= 0 || rect.height <= 0) {return rect;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.tsindex 50b2634b9b..0469b6458a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts@@ -1,9 +1,3 @@-/**- * The canvas document mutation vocabulary. Declared inside `canvas-engine` because the engine and- * its controllers are its heaviest consumers; the reducer that interprets it lives in- * `workbench/canvasProjectMutations.ts` and re-exports these types.- */-import type { ProjectEvent } from '@workbench/projectEventContracts';import type {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/pressureBands.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/pressureBands.tsindex af20c44994..7e7937f7fc 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/pressureBands.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/pressureBands.ts@@ -1,31 +1,7 @@/**- * Splits a pressure-sampled stroke into contiguous constant-alpha bands.- *- * ## Why bands, and why they must not overlap-blend- *- * `strokeSession` fills the whole stroke into a scratch surface at full alpha and composites- * it into the layer exactly once at the stroke opacity. That single composite is what stops- * overlapping segments *within one stroke* from darkening each other — a slow drag revisits- * the same pixels dozens of times, and `source-over` at partial alpha would compound every- * one of them into a dark blob.- *- * Pressure-dependent opacity breaks that model, because alpha now varies along the stroke and- * cannot be one `globalAlpha` on one composite. The fix is to fill the stroke as a sequence of- * bands, each a contiguous run of samples at one quantized alpha, and to paint each band into- * the scratch as *replace* (`destination-out` the band's own path, then `source-over` it at the- * band's alpha) rather than as a blend. Replace keeps the no-compounding guarantee: where two- * bands overlap, the later one wins outright, which is also the behaviour a stroke wants — the- * newer sample's pressure is the current one.- *- * Bands are quantized rather than per-sample because each band is a separate outline- * computation and two extra canvas fills. Quantizing to {@link PRESSURE_ALPHA_STEPS} levels- * keeps a normal drag to a handful of bands while staying below the ~2% alpha difference an- * eye can pick out of a soft edge.- *- * Consecutive bands share a sample ({@link BAND_OVERLAP_SAMPLES}) so their outlines abut- * instead of leaving a hairline gap where the pressure level changes.- *- * Zero React, zero import-time side effects.+ * Pressure-opacity bands replace overlapping scratch pixels (destination-out then source-over), so newer pressure+ * wins without alpha compounding. Quantization to {@link PRESSURE_ALPHA_STEPS} limits outline/fill work; shared+ * {@link BAND_OVERLAP_SAMPLES} avoid seams. The completed scratch composites once at stroke opacity.*/import type { StrokeSamplePoint } from '@workbench/canvas-engine/freehand';@@ -55,11 +31,8 @@ export interface PressureBand {}/**- * Quantizes pressure to a band alpha in (0, 1].- *- * Non-finite pressure floors to {@link MIN_PRESSURE_ALPHA} rather than propagating: clamping- * alone would let NaN through to `globalAlpha`, where a non-finite value is ignored and the- * band would silently paint at full alpha — the opposite of the lightest possible touch.+ * Quantizes pressure to (0,1]; nonfinite values use {@link MIN_PRESSURE_ALPHA}, avoiding canvas ignoring NaN and+ * painting fully opaque.*/export const toPressureAlpha = (pressure: number): number => {if (!Number.isFinite(pressure)) {@@ -72,12 +45,7 @@ export const toPressureAlpha = (pressure: number): number => {return Math.max(MIN_PRESSURE_ALPHA, quantized);};-/**- * Groups samples into constant-alpha bands, in stroke order.- *- * A single sample yields a single band — `perfect-freehand` renders a lone point as a dot, and- * dropping it would make a tap invisible. An empty input yields no bands.- */+/** Groups samples by alpha in stroke order. Preserve a lone sample as a dot; empty input has no bands. */export const getPressureBands = (points: readonly StrokeSamplePoint[]): PressureBand[] => {if (points.length === 0) {return [];@@ -95,8 +63,7 @@ export const getPressureBands = (points: readonly StrokeSamplePoint[]): Pressurecontinue;}- // The level changed. Close the current band, then open the next one seeded with the- // shared sample so the two outlines abut rather than leaving a seam.+ // Share the boundary sample when opening a band to avoid an outline seam.bands.push(current);const overlap = current.points.slice(-BAND_OVERLAP_SAMPLES);current = { alpha, points: [...overlap, point] };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.tsindex ed2a0c8d0a..8cb40f2306 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.ts@@ -60,12 +60,7 @@ export interface PreviewPublisher {): Promise<FilterPreviewOutcome>;}-/**- * Decodes a `data:` URL to a `Blob` without a DOM (`atob`/`Blob`/`Uint8Array`- * are all node-safe), so the staged-progress decode path runs in vitest through- * the injected raster backend just like the imageName path runs through the- * injected resolver.- */+/** DOM-free data-URL decoding lets injected-backend progress previews run in node tests. */const dataUrlToBlob = (dataUrl: string): Blob => {const commaIndex = dataUrl.indexOf(',');const header = commaIndex >= 0 ? dataUrl.slice(0, commaIndex) : '';@@ -83,16 +78,9 @@ const dataUrlToBlob = (dataUrl: string): Blob => {};/**- * Publishes the two kinds of transient preview the engine draws over a layer:- * the staged generation result and a filter's output.- *- * Both decode asynchronously, so both are token-guarded — a decode that- * resolves after a newer set/clear must not paint. Filter previews carry the- * extra requirement that the layer still exist and its export guard still be- * current, re-checked *after* the decode as well as before, because the user- * can edit the layer while the image is in flight. A dimension mismatch on a- * typed filter is a hard error rather than a silent stale, since it means the- * backend returned something that does not describe the region asked for.+ * Staged and filter previews token-guard async decodes against newer sets/clears. Filters also recheck layer+ * existence and export guards after decode. Typed-filter dimension mismatches are contract errors, not silent+ * stale results.*/export const createPreviewPublisher = (deps: CreatePreviewPublisherDeps): PreviewPublisher => {const { previews } = deps;@@ -160,12 +148,8 @@ export const createPreviewPublisher = (deps: CreatePreviewPublisherDeps): Previe};/**- * Drops a layer's filter-preview state and bumps its token so an in-flight- * decode for it is discarded — even if the id is later reused (e.g. an undo- * that restores a deleted layer must not resurrect a stale decode result- * that resolves afterward). The token is bumped, never reset/deleted, so a- * later guarded preview for the same id can never collide with a- * still-in-flight decode's captured token.+ * Drop preview state and increment, never delete/reset, its token so late decodes cannot revive previews after+ * layer-id reuse.*/const clearFilterPreview = (layerId: string): void => {if (previews.clearFilter(layerId)) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.tsindex 4ba6fa39b0..d8c23fdcf2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts@@ -16,11 +16,7 @@ import { isSupportedExportSource } from '@workbench/canvas-engine/layerExportGuaconst BYTES_PER_PIXEL = 4;-/**- * What a layer is expected to cost once rasterized, from its source rather than- * from a raster pass. Reserved up front so a capture that cannot fit is refused- * before any work is done; the real cost is topped up per layer afterwards.- */+/** Reserve source-estimated raster bytes before capture; top up with actual layer costs after rasterization. */const estimatedLayerBytes = (layer: CanvasLayerContract, document: CanvasDocumentContractV3): number => {const source = renderableSourceOf(layer);if (source?.type === 'image') {@@ -68,25 +64,11 @@ export interface RasterSnapshotCapture {}/**- * Takes point-in-time copies of the canvas for long-running background work —- * PSD export, invocation composites — that must not see the document change- * underneath it.- *- * A document snapshot is a structural clone plus a private record of the engine- * state it was cloned from: the canvas object identity, the raster content- * epoch, the lifecycle generation, and the document generation. Currency is- * that whole tuple, so an edit that produces an identical-looking document- * still invalidates the snapshot. The record lives in a `WeakMap` keyed by the- * snapshot, which is also how a foreign object is rejected as `'not-ready'`- * rather than mistaken for a stale one.+ * Document snapshots clone structure and privately record canvas identity, raster epoch and lifecycle/document+ * generations. WeakMap membership distinguishes foreign from stale snapshots.*- * A raster snapshot then detaches real pixels. Because rasterizing is async and- * one capture covers many layers, currency is re-checked before and after every- * layer, and every guard captured along the way is re-checked once more before- * the snapshot is published — a capture that raced an edit is discarded whole- * rather than returning a mix of old and new pixels. Bytes are reserved up- * front from a source-based estimate and topped up per layer when a rasterized- * surface turns out larger, so a capture cannot overrun the budget mid-flight.+ * Raster capture checks currency before/after every layer and all guards before publication, rejecting mixed+ * revisions. Reserve estimated bytes upfront and top up larger actual surfaces before exceeding budget.*/export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDeps): RasterSnapshotCapture => {const { isGuardCurrent, memory, syncMemoryBaselines } = deps;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.tsindex ced7c323f6..3cdb5f51c9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.ts@@ -36,12 +36,7 @@ export interface AdjustedSurfaceCache {export const createAdjustedSurfaceCache = (backend: RasterBackend,cache: DerivedSurfaceCache = createDerivedSurfaceCache(),- /**- * Reports the surface-local region a layer's cache was written in since a- * given version — {@link LayerCacheStore.damageSince}. Omit it and every- * rebuild is wholesale, which is what callers without a layer cache (tests,- * one-off derivations) want.- */+ /** Optional surface-local {@link LayerCacheStore.damageSince} lookup; callers without it rebuild whole surfaces. */layerDamageSince?: (layerId: string, version: number) => Rect | null): AdjustedSurfaceCache => {/** The damaged region clamped to the surface, or `null` to rebuild in full. */@@ -60,8 +55,6 @@ export const createAdjustedSurfaceCache = (adjustments: CanvasAdjustmentsContract | undefined): RasterSurface | null => {if (isIdentityAdjustments(adjustments)) {- // Identity: nothing to cache — drop any stale slot and let the caller draw- // the original surface.cache.delete(layerId, 'adjustments');return null;}@@ -77,13 +70,8 @@ export const createAdjustedSurfaceCache = (if (resized) {surface.resize(width, height);}- // Rebuilding this costs a full-surface readback plus a per-pixel JS pass- // — 35ms on a 2600x2100 layer, which is where a live stroke on an- // adjusted layer spends its entire frame. A stroke bumps the source- // version every tick, so the memo misses every frame; refreshing only- // the region the stroke actually wrote turns that into a fraction of the- // work. A resize invalidates the retained pixels, so it forces the full- // path regardless of what the trail says.+ // Source versions change every stroke tick. Refresh only reported damage to avoid full-surface readback+ // and adjustment work; resized surfaces always rebuild.const refresh =resized || reusableFromVersion === null ? null : damageSince(layerId, reusableFromVersion, width, height);const region = refresh ?? { height, width, x: 0, y: 0 };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceDamage.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceDamage.browser.test.tsindex 9a79eb0d29..0428e17587 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceDamage.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceDamage.browser.test.ts@@ -1,15 +1,4 @@-/**- * The correctness guard for partially-refreshed adjusted surfaces.- *- * A live stroke bumps its layer's cache version every tick, which defeats the- * adjusted-surface memo — so on an adjusted raster layer the surface was being- * rebuilt from the whole layer every frame: a full readback plus a per-pixel JS- * pass, 35 ms on a 2600×2100 layer. It now refreshes only the band the stroke- * reported writing.- *- * That is only safe if a partial refresh is indistinguishable from a rebuild, so- * these tests drive real canvases and compare the two pixel for pixel.- */+/** Real-canvas tests require damage-only adjusted-surface refreshes to match full rebuilds pixel for pixel. */import type { CanvasAdjustmentsContract } from '@workbench/canvas-engine/contracts';import type { Rect } from '@workbench/canvas-engine/types';@@ -73,10 +62,6 @@ const worstDifference = (a: Uint8ClampedArray, b: Uint8ClampedArray): number =>return worst;};-/**- * Runs `steps` against two independent caches — one refreshing partially, one- * always rebuilding — and returns both results.- */const compare = (steps: { rect: Rect; color: string }[], reportDamage = true) => {const partial = setup(true);const wholesale = setup(false);@@ -126,13 +111,8 @@ describe('partially-refreshed adjusted surfaces match a full rebuild', () => {});it('rebuilds in full when a later write does not report its damage', () => {- // The case that matters is MIXED: a reported write followed by an unreported- // one. Treating the unreported write as "nothing changed there" would refresh- // only the first band and leave the second one's pixels unadjusted, so this- // is what pins `damageSince` bailing out rather than skipping the step.- // Two writes have to follow the build for this to bite: one reported, one- // not. With only the unreported one there is nothing to refresh either way,- // so the bail-out and a "skip the unknown step" bug look identical.+ // Reported then unreported writes must force a full refresh; skipping the unknown step leaves its pixels+ // unadjusted. Both writes are needed to distinguish partial-refresh bugs.const partial = setup(true);const wholesale = setup(false);const built = { height: 60, width: 80, x: 40, y: 30 };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustments.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustments.tsindex 015c69c24b..a5a9c9bb93 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustments.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustments.ts@@ -26,11 +26,8 @@ const isIdentityCurve = (points: CurvePoints | undefined): boolean => {};/**- * Builds a 256-entry LUT that maps input → output through the channel's curve- * control points using monotone-cubic (Fritsch–Carlson) interpolation, so the- * result never overshoots between points. Fewer than two points → identity.- * Values before the first / after the last point are clamped to that point's- * output (flat extension).+ * Builds a 256-entry monotone-cubic Fritsch–Carlson LUT without overshoot. Fewer than two points gives identity;+ * outside endpoints uses flat extension.*/export const buildCurveLut = (points: CurvePoints | undefined): Uint8ClampedArray => {const lut = new Uint8ClampedArray(LUT_SIZE);@@ -271,9 +268,8 @@ const entryLuts = (};/**- * Compiles the stack into the fewest segments that reproduce it in order:- * enabled non-identity entries only, adjacent per-channel entries folded into- * one LUT trio. The empty result means identity.+ * Compiles enabled nonidentity entries in order, folding adjacent per-channel operations into LUT trios. Empty+ * means identity.*/export const compileAdjustments = (adjustments: CanvasAdjustmentsContract | undefined): CompiledAdjustmentSegment[] => {const segments: CompiledAdjustmentSegment[] = [];@@ -336,11 +332,7 @@ export const adjustmentsKey = (adjustments: CanvasAdjustmentsContract | undefine.join('||');};-/**- * Applies the stack to `imageData` IN PLACE in one pixel pass: the compiled- * segments run in order per pixel — LUT remaps, saturation luma lerps. Alpha- * is never modified. A no-op for an identity stack.- */+/** Applies compiled LUT/saturation segments in one in-place pixel pass, preserving alpha. Identity is a no-op. */export const applyAdjustments = (imageData: ImageData, adjustments: CanvasAdjustmentsContract | undefined): void => {const segments = compileAdjustments(adjustments);if (segments.length === 0) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.test.tsindex b18580e672..e94274931b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.test.ts@@ -69,8 +69,7 @@ describe('alphaBounds', () => {});it('finds the rightmost pixel even when a later row is narrower', () => {- // Exercises the inward-from-the-right scan: row 0 sets the running maxX, and- // row 1 must not be able to lower it, while row 2 must be able to raise it.+ // Later rows may increase maxX but never decrease it.const pixels = buffer(10, 3);setAlpha(pixels, 1, 0, 255);setAlpha(pixels, 6, 0, 255);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.tsindex f76cba09df..bb10b70844 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.ts@@ -1,20 +1,11 @@/**- * Alpha-derived content bounds for an RGBA pixel buffer — where a layer's visible- * pixels actually are, as opposed to the geometric extent its cache grew to.- *- * ANY non-zero alpha counts as content (matching `selection/selectionState.ts`, not- * the mask outline's solidity threshold): a higher threshold would silently discard- * faint pixels the user painted.- *- * Zero React, zero import-time side effects.+ * Bounds include every nonzero-alpha pixel, preserving faint content rather than applying the mask-outline+ * solidity threshold.*/import type { Rect } from '@workbench/canvas-engine/types';-/**- * An RGBA pixel buffer; only the alpha channel is read. `ImageData` satisfies this- * structurally, so tests can pass a plain literal — no canvas required.- */+/** Structural RGBA buffer compatible with ImageData; only alpha is read. */export interface AlphaPixels {readonly data: Uint8ClampedArray;readonly height: number;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.tsindex d3c0c3d47f..415ea17443 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.ts@@ -23,11 +23,7 @@ interface FixedPixelBackend extends RasterBackend {__surfaces: FakeSurface[];}-/**- * A minimal `RasterBackend` whose scratch surfaces report a single fixed pixel- * for every `getImageData` call — enough to test `sampleDocumentColor`'s- * bounds/alpha/traversal logic without modeling real canvas compositing.- */+/** Fixed-pixel scratch surfaces isolate sampling bounds, alpha and traversal without simulating compositing. */const createFixedPixelBackend = (pixel: readonly [number, number, number, number]): FixedPixelBackend => {const createdSurfaces: FakeSurface[] = [];@@ -175,9 +171,8 @@ describe('sampleDocumentColor', () => {sampleDocumentColor(doc, layers, backend, { x: 12.7, y: 34.2 });const scratch = backend.__surfaces.at(-1)!;- // Identity layer transform composed with the sample-point translation: e/f- // carry the floored, negated point (no per-layer offset/scale/rotation).- // The last `setTransform` is the per-layer draw (the first is the initial reset).+ // Identity-layer sampling translates by the negated floored point; inspect the final per-layer transform after+ // reset.expect(scratch.transforms.at(-1)).toEqual([1, 0, 0, 1, -12, -34]);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.tsindex a247971c8c..a5523a3eef 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts@@ -1,16 +1,6 @@/**- * Samples the composited document color at a document-space point, for the- * color-picker tool. Composites just the renderable layers (bottom → top,- * respecting opacity/blend/transform, matching {@link compositeDocument}'s- * paint order) into a 1×1 scratch surface translated so the sampled pixel- * lands at its origin — cheap regardless of document size, since only one- * destination pixel is ever rasterized.- *- * The document background (solid fill or checkerboard) and the staged- * preview are intentionally excluded: a point with no layer coverage samples- * as fully transparent (`null`), not the page chrome.- *- * Zero React, zero import-time side effects.+ * Samples composited layer pixels into a translated 1x1 scratch using normal ordering and display effects.+ * Excludes background/checkerboard and staged previews so uncovered points return null.*/import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';@@ -30,11 +20,8 @@ export interface RgbaSample {}/**- * Samples the composited document color at `docPoint` (document space;- * fractional coordinates are floored to the covering pixel). The canvas plane- * is unbounded, so transformed layer content outside the document dimensions- * remains pickable. Returns `null` when no renderable layer covers the point- * with non-zero alpha.+ * Floors document coordinates to a pixel; transformed content remains pickable outside document dimensions.+ * Returns null for zero-alpha coverage.*/export const sampleDocumentColor = (doc: CanvasDocumentContractV3,@@ -51,9 +38,8 @@ export const sampleDocumentColor = (const scratch = backend.createSurface(1, 1);const view: Mat2d = { a: 1, b: 0, c: 0, d: 1, e: -px, f: -py };- // Reuse the canonical compositor so sampling shares its layer ordering,- // cache-origin placement, transforms, blend modes, and display effects.- // Omitting a checkerboard tile and staged preview keeps empty space transparent.+ // Use canonical compositing for placement and display effects, omitting checkerboard/staged previews to retain+ // transparent empty space.compositeDocument(scratch, doc, layers, view, { backend, ...providers });const { data } = scratch.ctx.getImageData(0, 0, 1, 1);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.tsindex cb81efbbbf..307e25b7ed 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts@@ -55,48 +55,27 @@ export interface CompositeFrame {floatFrame: FloatingSelectionFrame | null,samPreview: SamPreviewState | null,/**- * The regions this frame must repaint, in their layers' local spaces, or- * `null` to repaint everything. Supplied by the render scheduler, which only- * produces a non-null value when every invalidation in the frame named the- * region it changed.+ * Layer-local repaint regions; null means full repaint. Partial damage is valid only when every invalidation+ * named its region.*/damage?: LayerDamage[] | null): void;}/**- * Draws the document onto the screen surface.- *- * This is the expensive half of a frame and runs only when pixels, layer order- * or the viewport actually changed — an overlay-only invalidation reuses the- * last composite. Before drawing it works out which layers the frame really- * demands (visible, in view, not isolated away) and kicks off rasterization for- * any of those whose cache is stale; after drawing it enforces the surface- * budget against exactly that set, so a layer the user is looking at is never- * the one evicted.- *- * SAM isolation makes this frame describe one layer instead of the document:- * the composite is narrowed to the isolated layer through `isolationLayerId`- * and clipped to the preview rect, and every other in-flight embellishment — filter previews, the- * staged candidate, the floating selection, transform overrides — is suppressed,- * because none of them describe what the user is being asked to judge.+ * Composite only for pixel/order/view changes. Rasterize demanded visible layers and protect them during post-draw+ * eviction. SAM isolation restricts drawing and clipping to its layer/rect, suppressing unrelated previews, floats+ * and transform overrides.*/export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFrame => {const { derivedSurfaceCache, diagnostics, layerCache, memory, previews, stores, transformOverrides, viewport } = deps;/**- * Ensures every layer this frame demands has a cache entry, and starts a- * rasterization for any that is stale.- *- * Creation must never resize an existing entry: a paint layer's live cache can- * have grown past its persisted content rect (fresh unflushed strokes), and- * shrinking it back to the contract size here would destroy those pixels. The- * rasterizer owns sizing the surface and placing its content rect.+ * Create missing caches and rasterize stale ones, but never resize existing entries here: unflushed paint may+ * exceed persisted bounds. Rasterization owns bounds changes.*/const ensureLayerCaches = (doc: CanvasDocumentContractV3, activeFrameLayerIds: ReadonlySet<string>): void => {for (const layer of getDocumentLeaves(doc)) {- // The layer's rasterizable source: a raster/control `source`, or a mask- // layer's alpha bitmap viewed as a paint source (colorized at composite).if (!isLayerContributing(layer) || !renderableSourceOf(layer) || !activeFrameLayerIds.has(layer.id)) {continue;}@@ -126,11 +105,7 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF};};- /**- * Trims cached surfaces back inside the budget, protecting the layers this- * frame drew and anything pinned by in-flight background work. Runs after the- * composite so the frame the user is looking at is never the eviction victim.- */+ /** Evict after drawing, protecting displayed layers and background-work pins. */const enforceBudget = (activeFrameLayerIds: ReadonlySet<string>): void => {deps.syncMemoryBaselines();const snapshot = memory.snapshot();@@ -146,10 +121,7 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFdiagnostics);deps.syncMemoryBaselines();- // Prune version-keyed dependents for every evicted id (mirrors dropLayer):- // the evicted surface is gone, so its adjusted-surface memo and thumbnail- // state must not linger keyed to a version the re-rasterized entry will- // exceed (the cache floor keeps versions monotonic across the recreate).+ // Eviction must prune adjusted-surface and thumbnail dependents; recreated cache versions remain monotonic.for (const id of evictedBaseLayerIds) {deps.deleteDerivedSurfaces(id);stores.thumbnailVersion.delete(id);@@ -181,36 +153,19 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFensureLayerCaches(doc, activeFrameLayerIds);compositeDocument(screen, doc, layerCache, view, {- // Confines the clear, the checkerboard and every layer blit to the pixels- // that actually changed; `null` repaints the whole viewport.damage: isolatedGuard ? null : damage,- // Memoized adjusted surfaces for raster layers with brightness/contrast/- // saturation/curves. Memoized on the layer's cache version, so an idle- // frame costs nothing — but a live stroke bumps that version every tick,- // and the memo misses. What keeps that affordable is that the miss then- // refreshes only the band the stroke reported writing, rather than- // re-deriving from the whole layer (see adjustedSurfaceCache).adjustedSurface: deps.getAdjustedSurface,groupSurface: deps.getGroupSurface,- // The raster backend + mask fill tile resolver drive the mask colorize- // path (alpha stencil → source-in fill colour/pattern, above all layers).backend: deps.backend,- // Feed the cached checkerboard tile only while the toggle is ON; passing- // `null` renders transparent documents without a checkerboard.checkerboardTile: stores.checkerboard.get() ? deps.getCheckerboardTile() : null,clipRect: isolatedGuard && samPreview ? samPreview.rect : null,derivedSurfaces: derivedSurfaceCache,diagnostics,// Pixels in flight, drawn directly above the layer they were cut from.floatingSelection: isolatedGuard ? null : (floatFrame?.composite ?? null),- // Crisp + cheap when zoomed in (nearest-neighbor up-scale), smooth when- // shrinking (bilinear down-scale). See `shouldSmoothAtZoom`.imageSmoothing: shouldSmoothAtZoom(viewport.getZoom()),isolationLayerId: isolatedGuard?.layerId ?? null,- // Non-destructive control-filter previews, drawn in place of the layer's- // committed pixels. Snapshotted only when one is actually active — this- // runs every composite frame, so an unconditional copy would allocate a- // map per frame for the overwhelmingly common case of none.+ // Snapshot filter previews only when active, avoiding an empty map allocation every frame.layerPreviews: !isolatedGuard && previews.filterCount() > 0 ? previews.filterSnapshot() : null,maskPatternTile: deps.getMaskPatternTile,// Screen frames are display-time: the region tint may draw.@@ -232,8 +187,7 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFsurface: stagedPreview.surface,}: null,- // While a text-edit session is open on a layer, skip it in the composite —- // the contenteditable portal shows its live text instead (avoids double-draw).+ // Skip the edited text layer because its portal renders live content.skipLayerId: stores.textEditSession.get()?.layerId ?? null,transformOverrides: !isolatedGuard && transformOverrides.size > 0 ? transformOverrides : null,});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.tsindex 992ed5de20..b0785b9607 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts@@ -265,8 +265,7 @@ describe('compositeDocument', () => {expect(patternCalls[0]!.args[0]).toBe(tile.canvas);expect(patternCalls[0]!.args[1]).toBe('repeat');- // The whole 200x200 target is filled with the pattern — NOT clipped to the- // 100x100 doc rect (the document is no longer a visual boundary).+ // Checkerboard fills the 200x200 viewport beyond the 100x100 document.const fills = target.callLog.filter((e) => e.op === 'fillRect');expect(fills).toHaveLength(1);expect(fills[0]!.args).toEqual([0, 0, 200, 200]);@@ -311,8 +310,7 @@ describe('compositeDocument', () => {const caches = createLayerCacheStore(backend);const solidTarget = backend.createSurface(200, 200);- // The `background` field no longer renders: a color-background doc with the- // checkerboard on still fills the whole viewport with the pattern, not a flat color.+ // Document background no longer renders; checkerboard still fills the viewport.compositeDocument(solidTarget, makeDoc([], { background: { color: '#123456' } }), caches, VIEW, {checkerboardTile: createCheckerboardTile(backend),});@@ -363,8 +361,7 @@ describe('compositeDocument', () => {compositeDocument(target, makeDoc([maskLayer('rg')]), caches, VIEW, { backend });- // The colorize happens on a NEW intermediate surface (not the target, not the- // mask cache): it blits the stencil then fills source-in with the fill colour.+ // Colorize the stencil on a separate intermediate surface using source-in.const colorized = created.find((s) =>s !== target &&@@ -535,13 +532,9 @@ describe('compositeDocument', () => {const doc = makeDoc([rasterLayer('raster'), maskLayer('mask')]);compositeDocument(target, doc, caches, VIEW, { backend });- // The mask's source-in colorize marks its draw pass; it must come AFTER the- // last raster blit. Find the first source-in op (mask pass) and assert every- // non-mask blit already ran — i.e. the mask pass draws last.+ // Every raster blit must precede the first mask source-in pass.const firstDrawImage = target.callLog.findIndex((e) => e.op === 'drawImage');expect(firstDrawImage).toBeGreaterThanOrEqual(0);- // Two draws land on the target: the raster blit, then the colorized mask blit;- // the mask blit is the LAST drawImage.const drawIdxs = target.callLog.map((e, i) => (e.op === 'drawImage' ? i : -1)).filter((i) => i >= 0);expect(drawIdxs.length).toBeGreaterThanOrEqual(2);});@@ -586,8 +579,6 @@ describe('compositeDocument', () => {const target = backend.createSurface(200, 200);compositeDocument(target, makeDoc([rasterLayer('a')]), caches, VIEW, { imageSmoothing: false });- // The smoothing flag is set exactly once, to false, so every layer/staged- // blit up-scales nearest-neighbor (crisp + cheap) rather than bilinear.expect(findSet(target.callLog, 'imageSmoothingEnabled')).toEqual([false]);});@@ -684,8 +675,7 @@ describe('shouldSmoothAtZoom', () => {expect(shouldSmoothAtZoom(0.1)).toBe(true);expect(shouldSmoothAtZoom(0.5)).toBe(true);expect(shouldSmoothAtZoom(0.99)).toBe(true);- // At or above 1× the document is magnified: keep pixels crisp and skip the- // per-frame bilinear up-scale whose cost grows with zoom.+ // At zoom >=1, disable smoothing for crisp magnification without bilinear upscaling.expect(shouldSmoothAtZoom(1)).toBe(false);expect(shouldSmoothAtZoom(4)).toBe(false);expect(shouldSmoothAtZoom(20)).toBe(false);@@ -761,9 +751,7 @@ describe('compositeDocument — floating selection', () => {});describe('compositeDocument — hidden layers', () => {- // Typed to the guidance member: `isHidden` exists only on the three overlay- // contracts, so a bare spread of the union does not accept it — which is the- // invariant this design is built on.+ // Only overlay contracts carry display-only `isHidden`; narrow to guidance before setting it.const hiddenMask = (id: string): CanvasLayerContract => ({...(maskLayer(id) as CanvasRegionalGuidanceLayerContract),isHidden: true,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.tsindex aee8f2d1d3..701b387576 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts@@ -1,16 +1,7 @@/**- * Composites a canvas document onto a target surface.- *- * Draws (in order): a clear + a viewport-filling checkerboard (the unbounded- * plane's surround; omitted when the checkerboard is off), then each layer's- * cached surface from bottom to top applying opacity / blend mode / transform,- * and finally an optional staged-generation preview. Layers without a cache entry are- * skipped — rasterization is the caller's job (see `rasterizers/` +- * `layerCache.ts`); this module only draws what's already cached.- *- * Every pixel operation flows through the {@link RasterSurface} `ctx`, which- * in tests is the recording stub, so composite order is assertable in node.- * Zero React, zero import-time side effects.+ * Draws cached content: clear/checkerboard across the viewport, bottom-first transformed layers with+ * opacity/blend, then staged preview. Missing caches are skipped; callers own rasterization. RasterSurface+ * contexts make ordering testable.*/import type {@@ -43,22 +34,11 @@ import { colorizeMask } from './maskFill';/** Screen-space size (px) of each checkerboard square for transparent backgrounds. */export const CHECKERBOARD_SQUARE_PX = 8;-/**- * CSS-zoom threshold at/above which image smoothing is disabled while- * compositing. See {@link shouldSmoothAtZoom}.- */export const SMOOTHING_MAX_ZOOM = 1;/**- * Image-smoothing policy for compositing at a given CSS zoom.- *- * Smoothing is enabled only when the document is DOWN-scaled (`zoom < 1`) —- * bilinear interpolation keeps a shrunk image clean. When zoomed IN- * (`zoom >= 1`) the document is up-scaled to fill the screen; smoothing is- * disabled so (a) pixels stay crisp when magnified — the behavior legacy pixel- * editors adopt above ~1× — and (b) the browser skips the per-frame bilinear- * interpolation of an ever-larger upscale, whose fill-rate cost is precisely- * what grows with zoom. Nearest-neighbor upscaling is dramatically cheaper.+ * Smooth only below 1x for clean downscaling. Magnification uses nearest-neighbor for crisp pixels without+ * per-frame bilinear upscaling.*/export const shouldSmoothAtZoom = (zoom: number): boolean => zoom < SMOOTHING_MAX_ZOOM;@@ -70,21 +50,12 @@ export interface CheckerColors {b: string;}-/**- * Fallback checkerboard colors when no theme tokens have been fed to the engine- * (node tests, first frame before React resolves the tokens). Deliberately DARK,- * theme-appropriate greys (in the spirit of the legacy dark transparency pattern)- * so the indicator reads as "empty" against the dark workbench surface. In the- * app these are replaced by resolved Chakra semantic tokens (see- * `widgets/canvas/checkerColors.ts`).- */+/** Dark checker fallback before React supplies semantic theme colors, and for DOM-free callers. */export const DEFAULT_CHECKER_COLORS: CheckerColors = { a: '#2a2a2a', b: '#363636' };/**- * Fallback tint alpha for a mask-bearing layer drawn WITHOUT a backend (a bare- * {@link compositeDocument} call in a minimal test): the mask coverage is blitted- * and a translucent flat fill laid over it. The real path (with a backend)- * colorizes the mask alpha via `source-in` at the layer opacity, matching legacy.+ * Without a backend, approximate masks with coverage plus flat tint. Production uses source-in colorization at+ * layer opacity.*/export const MASK_TINT_ALPHA = 0.5;@@ -100,102 +71,59 @@ export interface CompositeOptions {/** A staged generation candidate to draw at its placement (document space). */stagedPreview?: { surface: RasterSurface; rect: Rect; opacity?: number } | null;/**- * The cached checkerboard pattern tile (see {@link createCheckerboardTile}) to- * fill the ENTIRE viewport with (the canvas is an unbounded plane — the checker- * is the world, not a document backdrop). Omit or pass `null` to draw NO- * checkerboard (the "checkerboard off" state) — the cleared surface then shows- * the widget's themed `bg.inset` through it.+ * Checker tile fills the unbounded viewport. Null/absence disables it, revealing themed widget background+ * through the cleared surface.*/checkerboardTile?: RasterSurface | null;/**- * Whether `imageSmoothingEnabled` is on for this composite's `drawImage`- * blits (layer caches + staged preview). Defaults to `true` (the browser- * default) so non-viewport callers are unaffected; the engine feeds- * {@link shouldSmoothAtZoom} so zoomed-in frames composite crisp and cheap.+ * Smoothing defaults true for non-viewport callers; engine frames use {@link shouldSmoothAtZoom} for crisp+ * magnification.*/imageSmoothing?: boolean;/**- * The regions this composite must repaint, each in its layer's local space.- * When present, the clear, the checkerboard and every layer blit are clipped- * to their union on screen and the rest of the target keeps the previous- * frame — which is the difference between resampling a whole doc-sized layer- * to screen scale and resampling a few hundred pixels of it.- *- * `undefined` or `null` repaints the whole target, which is what every caller- * that cannot name its damage gets.+ * Layer-local damage clips clear, checkerboard and layer draws to its screen union, retaining other pixels.+ * Null/absence repaints the whole target.*/damage?: LayerDamage[] | null;/**- * Transient per-layer transform overrides (a live move/transform preview): a- * layer with an entry here is drawn through the overridden transform instead of- * its committed one. `scaleX`/`scaleY`/`rotation` fall back to the committed- * transform when absent (the move tool overrides only `x`/`y`). The mirror stays- * untouched.+ * Transient transforms override committed values without changing the mirror. Missing scale/rotation retain+ * committed values, supporting position-only move previews.*/transformOverrides?: ReadonlyMap<string,{ x: number; y: number; scaleX?: number; scaleY?: number; rotation?: number }> | null;- /**- * A layer id to SKIP entirely (draw nothing for it). Used while a text-edit- * session is open: the contenteditable portal shows the layer's live text- * instead, so drawing its committed pixels underneath would double up. `null`- * (or absent) skips nothing.- */+ /** Skip an edited text layer to avoid drawing beneath its live portal; null/absence skips nothing. */skipLayerId?: string | null;/**- * The raster backend, needed to colorize mask layers (an intermediate surface- * holds the alpha stencil while the fill is composited `source-in`). When- * absent, mask layers fall back to the flat-tint approximation- * ({@link MASK_TINT_ALPHA}); the engine always supplies it.+ * Backend supplies mask source-in intermediates. Absence uses {@link MASK_TINT_ALPHA} approximation; production+ * always supplies it.*/backend?: RasterBackend | null;- /**- * Returns a cached repeat tile for a mask fill (style, colour), or `null` for a- * solid fill (drawn directly). The engine caches tiles by `style:color` (like- * the checkerboard). Absent ⇒ solid fills only.- */+ /** Cached mask pattern by style/color; null means direct solid fill. Without a provider, only solid fills render. */maskPatternTile?: ((style: string, color: string) => RasterSurface | null) | null;/**- * Opt-in for the regenerate-region overlays (a raster layer's own alpha- * colorized above it while its region is enabled). STRICTLY display-time:- * only screen frames and the Overview pass it — a composite whose pixels are- * consumed (generation, extraction, color sampling, exports) must not, or the- * tint becomes real content.+ * Display-only regenerate overlays for screen/Overview. Pixel-consuming composites must omit them or their tint+ * becomes generated, sampled or exported content.*/regionOverlays?: boolean;/**- * Transient per-layer content previews (a non-destructive control-filter- * preview): a layer with an entry here draws the preview surface at its returned- * layer-local output rect, through the layer transform, INSTEAD of- * its committed cache, so the document is untouched until the filter is applied.- * `null`/absent ⇒ no previews.+ * Filter previews replace committed pixels at layer-local output bounds through the layer transform without+ * document mutation. Null/absence means none.*/layerPreviews?: ReadonlyMap<string, { surface: RasterSurface; rect: Rect }> | null;- /**- * Draws only this leaf and suppresses staged content and filter previews. A leaf the document- * would not draw (disabled or hidden) stays undrawn even while isolated.- */+ /** Isolate one leaf and suppress staged/filter previews; disabled or hidden leaves remain undrawn. */isolationLayerId?: string | null;/**- * Returns a raster layer's ADJUSTED cache surface (brightness/contrast/- * saturation/curves applied), or `null` when the layer has identity (or no)- * adjustments — in which case the committed cache surface is drawn directly.- * The engine wires this to a memoizing {@link- * import('./adjustedSurfaceCache').AdjustedSurfaceCache} so the adjusted pixels- * are NOT recomputed each frame (see that module). Only consulted for raster- * layers; absent ⇒ adjustments are ignored (a bare test call draws raw pixels).+ * Memoized adjusted raster surface, or null for raw pixels. Optional provider; without it adjustments are+ * ignored. Cache versions prevent per-frame recomputation.*/adjustedSurface?: ((layer: CanvasLayerContract, entry: LayerCacheEntry) => RasterSurface | null) | null;/** Shared memoized surfaces for mask and control display effects. */derivedSurfaces?: DerivedSurfaceCache | null;/**- * A live floating selection: pixels cut out of `layerId` and held in flight.- * They are drawn immediately ABOVE their own layer (the hole they left is- * already in that layer's cache), inheriting its opacity and blend mode, so- * the z-order is right by construction. `surface`/`rect` are LAYER-LOCAL, and- * `matrix` is the float's layer-local transform — both are composed with the- * layer's own matrix at draw time. `null`/absent ⇒ nothing in flight.+ * Draw floating pixels immediately above their cut source layer with its opacity/blend. Surface, rect and float+ * matrix are layer-local and compose with the layer transform.*/floatingSelection?: { layerId: string; surface: RasterSurface; rect: Rect; matrix: Mat2d } | null;/** Optional deterministic render counters; omitted in the normal zero-overhead path. */@@ -260,12 +188,7 @@ const isDefinitelyOffscreen = (return intersect(bounds, { height: target.height, width: target.width, x: 0, y: 0 }) === null;};-/**- * Builds a small, reusable two-tone checkerboard tile (a 2×2 grid of `squarePx`- * cells) through the {@link RasterBackend} seam. The engine creates this ONCE and- * feeds it back via {@link CompositeOptions.checkerboardTile}; each frame then- * only `createPattern`s over it, so no per-cell fill loop runs per frame.- */+/** Build a reusable 2x2 checker tile through {@link RasterBackend}; frames use patterns instead of per-cell fills. */export const createCheckerboardTile = (backend: RasterBackend,colors: CheckerColors = DEFAULT_CHECKER_COLORS,@@ -286,16 +209,8 @@ export const createCheckerboardTile = (};/**- * Fills the ENTIRE viewport with the checkerboard pattern. The canvas is a- * virtually infinite plane (like legacy): the checker IS the world surround, not- * a document backdrop — the document rect is no longer a visual boundary, so the- * contract's `background` field no longer renders. When no tile is provided the- * checkerboard is off and the cleared surface shows the widget's `bg.inset`.- *- * The pattern is laid with the identity transform in place, anchoring its cells- * to the screen (canvas) origin at a fixed pixel size — like legacy, which pins- * the pattern to the stage — so it stays visually stable and never swims or- * scales while panning/zooming.+ * Fill the unbounded viewport, ignoring document background. Identity-transform placement fixes checker cell+ * size/origin during pan and zoom. Without a tile, the cleared target reveals widget background.*/const drawBackground = (ctx: Ctx, tile: RasterSurface | null, bounds: Rect): void => {if (!tile) {@@ -311,18 +226,8 @@ const drawBackground = (ctx: Ctx, tile: RasterSurface | null, bounds: Rect): voi};/**- * Resolves {@link CompositeOptions.damage} to the screen-space rect a frame may- * confine itself to, or `null` for "repaint everything".- *- * Each region arrives in its layer's local space, so it is carried to the screen- * through the same `view × layerMatrix` the layer itself is drawn with — which- * keeps this correct for moved, scaled and rotated layers without the reporter- * needing to know any of that. A region naming a layer that is no longer in the- * document cannot be placed, so the frame falls back to a full repaint.- *- * The result is rounded outward and grown by a pixel: the layer blit is- * antialiased at the seam, and a clip that lands mid-pixel would leave a hairline- * of the previous frame behind.+ * Transform local damage by view*layerMatrix into screen bounds. Missing layers force full repaint. Round outward+ * and pad one pixel to cover antialiased seams.*/const resolveDamage = (doc: CanvasDocumentContractV3,@@ -372,13 +277,8 @@ const isMaskLayer = (layer.type === 'regional_guidance' || layer.type === 'inpaint_mask';/**- * Draws a mask-bearing layer as a TINTED, TRANSLUCENT overlay. With a backend- * available (the engine path) it colorizes the mask's alpha stencil with the- * layer's fill colour/pattern (`source-in`) on an intermediate surface, then- * blits that through the current (already transformed, `globalAlpha =- * layer.opacity`) context — legacy's `source-in` compositing-rect technique.- * Without a backend it falls back to blitting the coverage plus a flat- * translucent fill.+ * Colorize mask alpha with fill/pattern on a source-in intermediate, then draw with the current layer+ * transform/opacity. Without a backend, approximate with coverage and flat tint.*/const drawMaskLayer = (ctx: Ctx,@@ -401,8 +301,7 @@ const drawMaskLayer = (sourceVersion,}): colorizeMask(opts.backend, surface, surface.width, surface.height, fill, tile);- // The outer loop already set globalAlpha = layer.opacity; blit the colorized- // overlay at the mask's local content origin.+ // Draw at local content origin; the outer context already applies layer opacity.ctx.drawImage(colorized.canvas, origin.x, origin.y);return;}@@ -413,11 +312,6 @@ const drawMaskLayer = (ctx.fillRect(origin.x, origin.y, surface.width, surface.height);};-/**- * Draws one cached layer through its transform, applying opacity/blend and any- * transient transform override. Mask-bearing layers are colorized; everything- * else is a straight blit of its content-sized cache surface.- */const drawCachedLayer = (ctx: Ctx,leaf: SemanticLeaf,@@ -438,9 +332,8 @@ const drawCachedLayer = (const origin = { x: entry.rect.x, y: entry.rect.y };const preview = isIsolated(opts) ? null : (opts.layerPreviews?.get(layer.id) ?? null);if (preview) {- // Non-destructive filter preview: draw the full backend output at its- // layer-local rect (through the already-applied layer transform), including- // the same display-only control transparency effect used after commit.+ // Draw the full filter output at its local rect with the same control-transparency display effect as committed+ // pixels.const displayPreview =layer.type === 'control' && layer.withTransparencyEffect && opts.backend? opts.derivedSurfaces@@ -465,8 +358,6 @@ const drawCachedLayer = (} else if (isMaskLayer(layer)) {drawMaskLayer(ctx, layer, entry.surface, entry.version, origin, opts);} else if (layer.type === 'control' && layer.withTransparencyEffect && opts.backend) {- // Display-only lightness→alpha effect (legacy `LightnessToAlphaFilter`): dark- // areas of the control map drop out so underlying content shows through.const effect = opts.derivedSurfaces? opts.derivedSurfaces.get({create: (target) =>@@ -480,12 +371,8 @@ const drawCachedLayer = (: renderControlTransparency(opts.backend, entry.surface, entry.surface.width, entry.surface.height);ctx.drawImage(effect.canvas, origin.x, origin.y);} else {- // Raster layers may carry non-destructive adjustments; the engine supplies a- // memoized adjusted surface. The memo is keyed on the layer's cache version,- // so it holds across idle frames but is deliberately missed on every tick of- // a live stroke — that is what makes the stroke visible through the- // adjustments. The miss refreshes only the written band. Fall back to the raw- // cache when there are no adjustments or no provider.+ // Version-keyed adjusted surfaces refresh stroke damage on each cache write and reuse idle frames. Without+ // adjustments/provider, draw raw cache pixels.const adjusted = layer.type === 'raster' && opts.adjustedSurface ? opts.adjustedSurface(layer, entry) : null;ctx.drawImage((adjusted ?? entry.surface).canvas, origin.x, origin.y);}@@ -498,10 +385,8 @@ const drawCachedLayer = (};/**- * Draws a raster layer's regenerate region: the layer's OWN content alpha,- * colorized like an inpaint mask and laid directly above the layer through the- * same (already applied) transform. The mask IS the layer — every stroke,- * erase, and transform updates it live, with nothing separate to persist.+ * Colorize the raster layer's own alpha above it as a regenerate overlay; strokes, erasure and transforms update+ * coverage without separate pixel persistence.*/const drawRegionCoverage = (ctx: Ctx,@@ -562,10 +447,6 @@ const drawFloatingSelection = (ctx.restore();};-/**- * Composites `doc` onto `target`, using `caches` for each layer's pixels and- * `view` as the document→screen transform.- */export const compositeDocument = (target: RasterSurface,doc: CanvasDocumentContractV3,@@ -578,20 +459,11 @@ export const compositeDocument = (ctx.save();- // Smoothing policy for all layer/staged `drawImage` blits below. Set once- // under the outer save (inner per-layer save/restore preserves it). Off when- // zoomed in keeps magnified pixels crisp and skips the costly bilinear upscale.+ // Set smoothing once under the outer save; nested layer restores preserve it.ctx.imageSmoothingEnabled = opts.imageSmoothing ?? true;- // Clear the target in screen space, then lay the checkerboard across it — the- // canvas is an unbounded plane, so the checker is the world, not a document- // backdrop. With the checkerboard off the cleared surface shows the widget's- // themed `bg.inset` through it.- //- // When the frame declared its damage, both are confined to it and a clip keeps- // every layer blit below inside it too, so the untouched majority of the target- // simply keeps the previous frame's pixels. Damage that resolves to an empty- // rect means nothing visible changed: leave the target entirely alone.+ // Clear and checker-fill the viewport, clipping all draws to declared damage. Unchanged pixels retain the+ // previous frame; empty visible damage leaves the target untouched.identityTransform(ctx);const damageScreen = resolveDamage(doc, view, target, opts);if (damageScreen && isEmpty(damageScreen)) {@@ -719,8 +591,7 @@ export const compositeDocument = (ctx.restore();}- // Staged generation preview over its bbox (document space), with a subtle- // dashed outline so the pending result reads distinctly from committed pixels.+ // Draw staged preview in document space with a dashed outline distinguishing pending pixels.const staged = isIsolated(opts) ? null : opts.stagedPreview;if (staged) {ctx.save();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.tsindex cd17f9119b..445e81412f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts@@ -1,12 +1,6 @@/**- * The correctness guard for damage-clipped compositing.- *- * A damage-clipped frame leaves everything outside the damage rect showing the- * PREVIOUS frame. That is the whole point, and also the whole risk: if the- * damage under-reports by even a pixel, the target keeps stale content, and no- * assertion about draw-call order would notice. So these tests run every case- * twice against real canvases — once repainting in full, once damage-clipped- * on top of the previous frame — and demand the two are pixel-identical.+ * Compare full and damage-clipped repaints over previous frames on real canvases. Pixel equality catches+ * underreported damage that draw-call assertions cannot.*/import type {@@ -88,10 +82,6 @@ const countDifferences = (a: Uint8ClampedArray, b: Uint8ClampedArray): { differi};describe('damage-clipped compositing matches a full repaint', () => {- /**- * Composites `steps` twice: once always in full, once with each step's damage- * clipped on top of the previous frame. Returns both screens' pixels.- */const run = (doc: CanvasDocumentContractV3,caches: ReturnType<typeof createLayerCacheStore>,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/controlTransparency.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/controlTransparency.test.tsindex 886ef4c79b..b7386080be 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/controlTransparency.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/controlTransparency.test.ts@@ -72,11 +72,7 @@ interface FakeSurface extends RasterSurface {readonly putImageDataCalls: ImageData[];}-/**- * A minimal but faithful `RasterBackend` for `renderControlTransparency`: every- * surface's `getImageData` returns a fresh copy of `sourcePixels`, and its- * `putImageData` is recorded so the transform's output can be inspected.- */+/** Backend readbacks copy source pixels; recorded writes expose the transparency transform's output. */const createFakeBackend = (sourcePixels: Uint8ClampedArray): RasterBackend & { readonly created: FakeSurface[] } => {const created: FakeSurface[] = [];diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/controlTransparency.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/controlTransparency.tsindex 20f99b3a6e..3a2d7c1897 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/controlTransparency.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/controlTransparency.ts@@ -1,28 +1,12 @@/**- * The control-layer transparency effect (legacy `LightnessToAlphaFilter`).- *- * A control layer with `withTransparencyEffect` renders its source so DARK areas- * become transparent — for an edge/depth/pose map, the black background drops out- * and the underlying content shows through. This mirrors legacy- * `features/controlLayers/konva/filters.ts`: per pixel, HSL lightness- * `(min(r,g,b) + max(r,g,b)) / 2` becomes the new alpha, clamped to never EXCEED- * the pixel's existing alpha.- *- * It is DISPLAY-ONLY: at generation time the control image is composited at full- * opacity with NO transparency effect (see `generation/canvas/compositePlan.ts`- * `toControlLayerRef`), exactly like legacy (which rasterizes control with- * `filters: []`, `bg: 'black'`).- *- * Zero React, zero import-time side effects.+ * Display-only control transparency matches legacy LightnessToAlphaFilter: alpha becomes min(existing alpha, (min+ * RGB + max RGB)/2), dropping dark backgrounds. Generation omits this effect and composites the control image at+ * full opacity.*/import type { RasterBackend, RasterSurface } from './raster';-/**- * Applies the lightness→alpha transform to an RGBA pixel buffer in place: each- * pixel's alpha becomes `min(alpha, lightness)` where `lightness` is the HSL- * lightness of its RGB. Pure — the unit-testable core of the effect.- */+/** In-place RGBA alpha = min(existing alpha, HSL lightness); RGB is unchanged. */export const applyLightnessToAlpha = (data: Uint8ClampedArray): void => {for (let i = 0; i + 3 < data.length; i += 4) {const r = data[i] ?? 0;@@ -34,12 +18,6 @@ export const applyLightnessToAlpha = (data: Uint8ClampedArray): void => {}};-/**- * Produces a transparency-effect copy of a control layer's cache surface (same- * dimensions): the cache is drawn, its pixels transformed by- * {@link applyLightnessToAlpha}, and the result returned. The caller blits it- * through the layer transform in place of the raw cache.- */export const renderControlTransparency = (backend: RasterBackend,cache: RasterSurface,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/derivedSurfaceCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/derivedSurfaceCache.tsindex 277edeb910..2462bef0ad 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/derivedSurfaceCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/derivedSurfaceCache.ts@@ -11,13 +11,8 @@ export interface DerivedSurfaceRequest {paramsKey: string;source: RasterSurface;/**- * Builds the derived surface.- *- * `target` is the previous surface when it can be reused (same source), else- * `null`. `reusableFromVersion` is the source version `target` was built at,- * or `null` when there is nothing to refresh from — which is the signal that- * the build must be wholesale. Given both, an implementation may ask the- * layer cache what changed since that version and refresh only that region.+ * Reuse `target` only for the same source. `reusableFromVersion` permits damage-based refresh; null requires a+ * wholesale build.*/create(target: RasterSurface | null, reusableFromVersion: number | null): RasterSurface;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.tsindex 924b0a4ecd..b5b9c2dbb9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.ts@@ -16,14 +16,8 @@ export interface FloatingSelectionFrame {}/**- * How a floating selection appears this frame, or `null` when there is nothing- * floating (or its layer has gone).- *- * The composite and the overlay must agree exactly — the ants outline the same- * pixels the compositor drew — so both are resolved from one call rather than- * each deriving the transform for itself. `display` is preferred over `pixels`- * for drawing because a layer with a display-only effect shows its adjusted- * copy; only the bake ever touches the raw pixels.+ * Resolve float drawing and ants together so transforms agree. Prefer display-effect pixels for drawing, raw+ * pixels for baking; return null when no float/layer exists.*/export const floatingSelectionFrame = (float: FloatingSelection | null,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.tsindex 3e75e321b7..c0262830a7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/fontLoader.ts@@ -1,13 +1,6 @@/**- * The Canvas-owned font boundary.- *- * Built-in CSS families continue to use the small `FontFaceSet` slice below.- * The application can inject its account-scoped custom-font runtime without- * making the Canvas engine import feature code. Custom sources are translated- * into the runtime's stable reference plus their exact style, weight, and axis- * coordinates; the runtime owns the browser-only family alias.- *- * Zero React, zero import-time side effects.+ * Canvas font boundary: built-ins use FontFaceSet; injected account-scoped runtimes resolve custom refs with exact+ * style, weight and axes while owning browser-only aliases.*/import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';@@ -30,18 +23,13 @@ export interface CanvasFontReference {axes?: Readonly<Record<string, number>>;}-/**- * Application-owned custom-font runtime. It is intentionally structural so- * Canvas stays below feature composition and remains usable in node tests.- */+/** Structural custom-font runtime keeps Canvas independent of feature composition and usable in node tests. */export interface CanvasFontRuntime {/** Ensures the exact static face/instance is loaded and returns its browser family alias. */ensure(reference: CanvasFontReference, signal?: AbortSignal): Promise<string>;/**- * Revalidates the exact face against the current account/catalog state before- * an exported or generated output is allowed to use it. Preview ensures may- * serve the browser registry cache; output checks must be able to reject a- * deleted or changed resource even when that cache still has an alias.+ * Revalidate exact faces against current account/catalog state for outputs; cached preview aliases must not+ * allow deleted or changed resources.*/ensureForOutput(reference: CanvasFontReference, signal?: AbortSignal): Promise<string>;/** Keeps the loaded face registered while this engine has a live text consumer. */@@ -216,10 +204,8 @@ export const createFontLoader = (api: FontLoadApi | CanvasFontRuntime | null): Fconst nextGeneration = api.getSnapshot?.().generation;const generationChanged = nextGeneration === undefined || nextGeneration !== runtimeSnapshotGeneration;runtimeSnapshotGeneration = nextGeneration ?? runtimeSnapshotGeneration;- // The runtime owns account lifecycle and may remove every registered- // face at once. A runtime without a generation API is treated as a- // coarse lifecycle boundary for compatibility; runtimes with a- // generation leave ordinary loading/ready notifications alone.+ // Runtime generations distinguish account resets from ordinary font notifications. Without generation+ // support, treat every notification as a coarse lifecycle boundary.if (generationChanged) {generation += 1;cancelPendingPreviews();@@ -452,9 +438,7 @@ export const createFontLoader = (api: FontLoadApi | CanvasFontRuntime | null): F}},() => {- // A failed load leaves fallback pixels in place. An asynchronous- // raster job must not become an unhandled rejection solely because a- // face is missing; the UI can retry explicitly.+ // Keep fallback pixels on load failure without unhandled raster-job rejection; the UI may retry.});},diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/goldenHarness.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/goldenHarness.tsindex f8798aa465..ec8ec03fb3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/goldenHarness.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/goldenHarness.ts@@ -3,15 +3,9 @@ import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import { commands } from 'vitest/browser';/**- * Deterministic image goldens for the Chromium raster suite. A golden is a- * reviewed PNG under `__golden__/` next to a JSON record of the browser and- * raster configuration that produced it. Frames are normalised before- * comparison: flattened over an opaque background so premultiplied alpha- * cannot introduce rounding, then compared channel by channel.- *- * `pnpm run test:browser:update-goldens` rewrites baselines; a normal run only- * compares and, on failure, writes expected/actual/diff PNGs under the- * gitignored `__screenshots__/golden/` directory.+ * Reviewed Chromium PNG goldens include raster/browser metadata. Flatten onto opaque backgrounds before channel+ * comparison to avoid premultiplied-alpha rounding. Update only via the golden command; normal failures write+ * ignored expected/actual/diff artifacts.*/export interface GoldenTolerance {/** Largest per-channel difference a pixel may show before it counts as differing. */diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentComposite.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentComposite.browser.test.tsindex 89265e7103..b54cece0aa 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentComposite.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentComposite.browser.test.ts@@ -94,11 +94,8 @@ describe('group adjustment composite', () => {});it('applies nested stacks inner-first', async () => {- // Inner group inverts mid-gray 25% red-over-white... keep it simple:- // inner invert turns white → black; outer gamma-2 keeps black at 0.- // Reversed order (gamma then invert) would give 255 − 255·sqrt(1) = 0 too,- // so use a mid value: member is 25% gray (64). invert → 191; gamma-2 on- // 191 → 255·sqrt(191/255) ≈ 221. Reversed: gamma-2(64) ≈ 128, invert → 127.+ // Use gray 64 to distinguish nested order: invert then gamma-2 yields about 221; reversed order yields about+ // 127.const document = docWith([groupContract('outer', [groupContract('inner', [raster('gray')], { adjustments: invertStack('ia') })], {adjustments: gammaStack('oa'),@@ -146,9 +143,7 @@ describe('group adjustment composite', () => {});it('resolves sibling scopes nested inside a parent scope with correct member indexing', async () => {- // outer gamma-2 group holding: invert-group [a], plain b, invert-group [d].- // a=#404040 → invert 191 → outer gamma ≈221. b=#404040 → outer gamma ≈128.- // d covers nothing at centre (checked via left pixel below).+ // Outer gamma-2 maps inverted `a` from 64 to about 221 and plain `b` to about 128; `d` does not cover center.const document = docWith([groupContract('outer',@@ -228,9 +223,7 @@ describe('group adjustment composite', () => {});it('applies group blend mode when the isolated composite lands, on screen and in export', async () => {- // Mid-gray group multiplied over a white base: 0x80 × 0xff = 0x80. A- // per-leaf multiply would be identical here, so also nest: outer normal- // group holding a multiply group proves the landing applies INSIDE parents.+ // Nesting the multiply group proves its composite lands inside the parent, not only at the root.const document = docWith([groupContract('g', [raster('gray')], { blendMode: 'multiply' }), raster('under')]);const scene = sceneFor({ gray: '#808080', under: '#ffffff' });const exported = await renderRasterComposite(planBaseRasterComposite(document, BBOX), scene);@@ -294,9 +287,7 @@ describe('group adjustment composite', () => {});it('holds two keys per group so alternating consumers (frame vs overview) stop rebuilding', () => {- // A transform session makes the frame composite session matrices while the- // overview composites the settled contract: two keys for one group, forever- // alternating. Two slots must absorb that; a third key still evicts.+ // Frame/session and settled Overview matrices alternate two keys; two slots retain them, while a third evicts.const scene = sceneFor({ red: '#ff0000' });let builds = 0;const groupSurfaces = createGroupSurfaceCache({diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.tsindex 87b31e2864..c196342d72 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.ts@@ -1,9 +1,6 @@/**- * Nested contiguous [start, end) scopes over a flat drawn list, one per- * composited group — a group whose output must be built in isolation because it- * carries a contributing adjustment stack, an opacity below 1, or a non-normal- * blend mode. Both renderers consume the same shape. Relies on preorder (or its- * reversal) keeping every subtree contiguous.+ * Contiguous [start,end) scopes identify isolated groups with adjustments, opacity or blend. Both renderers rely+ * on preorder/reversed-preorder keeping subtrees contiguous.*/import type {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.tsindex e5f52e0bb8..18324cdedb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts@@ -1,11 +1,7 @@/**- * Per-group memoized document-space composites of composited groups (adjustment- * stack, opacity, or blend mode). Keyed on the scope shape plus every drawn- * member's cache version, appearance, and effective matrix (so a transform- * session inside a composited group rebuilds per tick); the scope's own- * opacity/blend land at draw time and stay out of the key. Accepted tradeoff:- * document resolution, so transformed members resample twice and zoom > 100%- * upscales the group surface.+ * Document-space group composites cache scope shape and member versions, appearance and effective matrices. Own+ * opacity/blend apply at draw time. Document-resolution buffers resample transformed members twice and upscale+ * above 100% zoom.*/import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';@@ -167,8 +163,7 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCacctx.clearRect(0, 0, rect.width, rect.height);const view: Mat2d = { a: 1, b: 0, c: 0, d: 1, e: -rect.x, f: -rect.y };drawRange(ctx, view, members, memberMatrices, excludeIds, baseIndex, scope.start, scope.end, scope.children);- // A group scoped only for opacity/blend has an identity stack: skip the- // full-surface pixel round trip.+ // Opacity/blend-only groups have identity adjustments; skip pixel readback.if (!isIdentityAdjustments(scope.adjustments)) {const pixels = ctx.getImageData(0, 0, rect.width, rect.height);applyAdjustments(pixels, scope.adjustments);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.tsindex df7e7957d4..0e4627b7c4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts@@ -128,9 +128,7 @@ describe('createLayerCacheStore', () => {store.invalidate('a');expect(first.version).toBe(2);- // Delete + recreate (undo→redo / transform bake / merge / evict→re-show): the- // fresh entry must start above 2 so version-keyed caches (adjusted surface,- // thumbnails) can't mistake its new pixels for a version they already hold.+ // Recreated ids must exceed prior versions so adjusted surfaces and thumbnails cannot reuse stale pixels.store.delete('a');const recreated = store.getOrCreate('a', 10, 10);expect(recreated.version).toBeGreaterThan(2);@@ -263,11 +261,7 @@ describe('growToRect (paint caches grow with strokes)', () => {expect(grown.surface.width).toBe(40);expect(grown.surface.height).toBe(40);- // The growth preserves the old pixels at their layer-local position within- // the grown surface: old origin (10,10) minus new origin (-10,-10) =- // surface (20,20). It must NOT go through a CPU round trip to do it — the- // whole point of `resizePreserving` is that the copy stays on the GPU, and- // a `getImageData` here would mean that regressed.+ // Preserve local placement at new surface offset (20,20) using GPU blits, without getImageData readback.const log = (grown.surface as StubRasterSurface).callLog;expect(log.filter((e) => e.op === 'resizePreserving').map((e) => e.args)).toEqual([[40, 40, 20, 20]]);expect(log.map((e) => e.op)).not.toContain('getImageData');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.tsindex 3e5ce11ab1..192a412c59 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts@@ -1,15 +1,6 @@/**- * Per-layer raster cache store.- *- * Each layer's rendered pixels are cached on their own {@link RasterSurface}- * so the compositor can redraw the document without re-rasterizing every- * layer each frame. Caches are always re-rasterizable, so eviction is safe:- * a hidden layer's cache can be dropped to stay under a memory budget and- * rebuilt on demand when it becomes visible again.- *- * All surface allocation flows through the injected {@link RasterBackend}- * seam, so the store runs unchanged in node tests. Zero React, zero- * import-time side effects.+ * Per-layer raster surfaces avoid repeated rasterization during compositing. Allocation uses injected {@link+ * RasterBackend}; callers protect pixels that cannot yet be reconstructed before eviction.*/import type { Rect } from '@workbench/canvas-engine/types';@@ -23,14 +14,7 @@ export const DEFAULT_CACHE_BUDGET_BYTES = 512 * 1024 * 1024;const BYTES_PER_PIXEL = 4;-/**- * How many recent writes a layer's damage trail retains.- *- * A derived surface asks what changed since the version it was built at, so the- * trail only has to span the gap between two composites — normally one write.- * The cap keeps a long stroke from growing the trail without bound; overrunning- * it just means derived surfaces rebuild wholesale, which is the old behaviour.- */+/** Bound damage history between derived-surface refreshes. Overrunning the window safely forces a full rebuild. */const DAMAGE_TRAIL_LIMIT = 16;/** One recorded write: the version it produced, and where it landed (`null` = everywhere). */@@ -48,12 +32,8 @@ export interface LayerCacheEntry {/** True only after real pixels have been published into this allocation. */hasPublishedPixels: boolean;/**- * The surface's content bounds in the layer's LOCAL coordinate space. The- * surface holds `rect.width`×`rect.height` pixels; surface pixel `(sx, sy)`- * maps to layer-local `(rect.x + sx, rect.y + sy)`. The origin can be negative- * (a paint layer grown up/left of its start). The compositor draws the surface- * at `transform × rect.origin`. An empty rect (0 width/height) marks an empty- * layer (a brand-new or cleared paint layer) — safe to skip everywhere.+ * Local content bounds map surface (sx,sy) to (rect.x+sx,rect.y+sy), allowing negative origins. Composite at+ * transform*origin; zero-sized rects represent empty layers.*/rect: Rect;/** Bumped every time the cache is invalidated; thumbnails/subscribers watch this. */@@ -94,43 +74,23 @@ export interface LayerCacheStore {/** Returns the existing cache entry for a layer, or `undefined`. Touches LRU order. */get(layerId: string): LayerCacheEntry | undefined;/**- * Returns the cache entry for a layer, creating (or resizing) its surface to- * `width`x`height` at the LOCAL origin `(0, 0)`. The returned entry identity is- * stable across calls that don't change the size, so callers can hold onto it- * between frames. Use this for origin-anchored layers (image / shape / text /- * gradient); paint caches, which can grow off-origin, use {@link getOrCreateRect}- * / {@link growToRect}.+ * Create/resize origin-anchored caches with stable entry identity while size matches. Off-origin paint uses+ * {@link getOrCreateRect} or {@link growToRect}.*/getOrCreate(layerId: string, width: number, height: number): LayerCacheEntry;/**- * Like {@link getOrCreate} but places the surface at an arbitrary layer-local- * `rect` origin (which may be negative). Creates the entry when absent; when it- * already exists the surface is left untouched (the caller — a rasterizer or a- * growth op — owns resizing), only ensuring existence. Used for paint layers- * whose content rect is not origin-anchored.+ * Ensure a cache at an arbitrary local rect, including negative origins. Existing surfaces remain untouched;+ * rasterization/growth owns resizing.*/getOrCreateRect(layerId: string, rect: Rect): LayerCacheEntry;/**- * Grows (never shrinks) a layer's cache to cover `rect` in layer-local space,- * preserving the existing pixels at their new offset. A no-op when `rect` is- * already within the current extent. Creates the entry (surface sized to `rect`)- * when absent. Returns the entry.+ * Grow to include a local rect while preserving pixels and offset; never shrink. Creates missing entries and+ * reuses already-covering ones.*/growToRect(layerId: string, rect: Rect): LayerCacheEntry;/**- * Shrinks a layer's cache to `rect` (layer-local) — the mirror of- * {@link growToRect}. `rect` is INTERSECTED with the current extent, so this can- * never grow a cache; retained pixels move to the new offset and the rest is- * dropped. An empty `rect` collapses the cache to a zero-rect surface.- *- * Bumps the version UNCONDITIONALLY, unlike `growToRect`: a shrink destroys pixels,- * so an in-flight rasterization job must invalidate itself rather than resize the- * trimmed surface back up and redraw over it.- *- * MUTATES the entry, never deletes it — `applyImagePatch` gates undo on the entry- * existing, so a collapsed cache must still accept restored pixels via `growToRect`.- *- * No-op when `rect` already equals the extent; `undefined` when there is no cache.+ * Intersect-crop local bounds, retaining the entry even when empty so undo can grow it again. Changed bounds+ * always bump version to fence stale raster jobs. Equal bounds are a no-op; missing caches return undefined.*/shrinkToRect(layerId: string, rect: Rect): LayerCacheEntry | undefined;/** Clones `pixels` into a detached replacement without mutating the live cache. */@@ -138,20 +98,13 @@ export interface LayerCacheStore {/** Publishes a detached replacement without allocating, resizing, or drawing. */installReplacement(prepared: PreparedLayerCacheReplacement): LayerCacheEntry;/**- * Marks directly-written pixels current, bumps the version, and notifies- * observers.- *- * `damage` is the surface-local rect the write touched. Supplying it lets- * surfaces DERIVED from this cache (adjusted, mask-fill) refresh just that- * rect instead of rebuilding wholesale — see {@link damageSince}. Omitting it- * declares the whole surface changed, which is always safe.+ * Publish direct writes as current, bump version and notify. Optional surface-local damage enables partial+ * derived refresh; omission means the whole surface changed.*/publishPixels(layerId: string, damage?: Rect | null): LayerCacheEntry | undefined;/**- * The union of the regions written to `layerId` since `version`, or `null` if- * that cannot be established — because some write did not name its damage,- * because the trail is older than the retained window, or because the surface- * was reallocated. `null` means "assume everything changed".+ * Union damage since version, or null for unknown writes, expired history or reallocation. Null requires full+ * refresh.*/damageSince(layerId: string, version: number): Rect | null;/** Marks a layer's cache stale and bumps its `version`. */@@ -162,11 +115,7 @@ export interface LayerCacheStore {version(layerId: string): number;/** Total bytes held across all cache surfaces (w*h*4 each). */byteSize(): number;- /**- * Evicts hidden-layer caches (those whose id is not in `visibleIds`) in- * least-recently-used order until the total {@link byteSize} is within- * `budgetBytes`. Visible layers are never evicted. Returns the evicted ids.- */+ /** Evict unprotected ids in LRU order until within `budgetBytes`; never evict `visibleIds`. Returns evicted ids. */evictHidden(visibleIds: Iterable<string>, budgetBytes?: number): string[];/** Releases every cache entry. Cache surfaces are GC'd with the store. */dispose(): void;@@ -196,12 +145,8 @@ export const createLayerCacheStore = (}damageTrails.set(entry.layerId, trail);};- // Per-id version FLOOR: the highest version each layer id has ever reached,- // retained across delete/recreate (delete, LRU eviction). A recreated entry- // (undo→redo, transform bake, merge, evict→re-show) starts ABOVE this floor- // rather than resetting to 0 — so version-keyed dependents (the adjusted-surface- // cache, thumbnail state) never mistake fresh pixels for a stale version they- // already have cached. Only ever grows; a plain number per id (negligible).+ // Retain per-id version floors across deletion/eviction. Recreated entries start above prior versions so derived+ // caches cannot mistake new pixels for old ones.const versionFloors = new Map<string, number>();let tick = 0;@@ -345,12 +290,8 @@ export const createLayerCacheStore = (// recorded so far is void. Dropping the trail makes derived surfaces rebuild// wholesale for one frame rather than refresh the wrong pixels.damageTrails.delete(layerId);- // Grow onto a fresh backing store with the old pixels blitted across, at- // their new offset within it. `resize` cannot do this — it clears — so the- // pixels would otherwise have to make a CPU round trip, which measured as- // roughly the whole cost of the growth again on top of the allocation. This- // is the hot path for a stroke: painting outward grows the cache once per- // chunk boundary crossed, and each growth stalls the gesture.+ // Grow by adopting a fresh backing store and blitting old pixels at the new offset. Ordinary resize clears,+ // and CPU readback/upload would add work on the stroke hot path.const surface = existing.surface;if (!curEmpty && cur.width > 0 && cur.height > 0) {surface.resizePreserving(newRect.width, newRect.height, cur.x - newRect.x, cur.y - newRect.y);@@ -429,8 +370,7 @@ export const createLayerCacheStore = (rect: prepared.rect,stale: false,surface: prepared.surface,- // Directly-published pixels receive the same extra version bump that the- // old create-then-notify path applied, while remaining monotonic on swap.+ // Direct publication preserves the extra create-then-notify version bump and monotonic swaps.version: initialVersion(prepared.layerId) + 1,};touch(entry);@@ -522,9 +462,7 @@ export const createLayerCacheStore = (if (total <= budgetBytes) {break;}- // Retain the version floor so a re-shown (re-rasterized) layer resumes ABOVE- // its pre-eviction version, not from 0 — otherwise the adjusted-surface /- // thumbnail caches would serve stale pixels keyed to the recycled version.+ // Retain version floors across eviction to prevent stale adjusted surfaces and thumbnails after recreation.rememberFloor(entry);entries.delete(entry.layerId);damageTrails.delete(entry.layerId);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheGrowth.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheGrowth.browser.test.tsindex a54d9b9038..7f1817a979 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheGrowth.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheGrowth.browser.test.ts@@ -5,16 +5,8 @@ import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';import { describe, expect, it } from 'vitest';/**- * Growing a layer cache is the one place the engine moves a whole surface's- * pixels, and it happens repeatedly mid-stroke. It preserves them by adopting a- * fresh backing store and blitting the old canvas into it (`resizePreserving`)- * rather than round-tripping through `getImageData`/`putImageData`. That is- * measurably faster, but it also means the copy is real GPU work with a real- * offset — a wrong `dx`/`dy`, or a blit that silently does nothing, would- * corrupt layer content on any stroke that paints outward.- *- * The node tests can only assert the ARGUMENTS, because the stub surface holds- * no pixels. These assert the pixels.+ * Real-canvas growth tests verify resizePreserving pixels and offsets; recorded node calls cannot detect failed+ * blits or content corruption.*//** Distinctly-coloured marks, addressed in layer-local space. */@@ -94,19 +86,13 @@ describe('growToRect preserves pixels', () => {});it('keeps the pixels across a run of successive growths', () => {- // A single stroke crosses many chunk boundaries, so the pixels are copied- // again and again. Any per-growth drift (a rounding slip in the offset, or a- // blit that resamples) compounds; one growth is not enough to catch it.+ // Repeated growth catches cumulative offset or resampling drift that a single copy cannot expose.const store = createLayerCacheStore(createDomRasterBackend());store.growToRect('L', START);const entry = store.get('L')!;entry.surface.ctx.fillStyle = 'rgb(220,30,90)';- entry.surface.ctx.fillRect(100, 100, 10, 10); // layer-local (200,200)- // A semi-transparent mark too: this is the one that could drift, since a- // copy that un-premultiplies and re-premultiplies loses a step. It must- // settle rather than lose a step per growth — a stroke's "before" snapshot- // is read off this surface, so drift here would slowly lift the pixels the- // gesture is supposed to leave pristine.+ entry.surface.ctx.fillRect(100, 100, 10, 10); // A semitransparent mark at local (200,200) must stabilize across copies; repeated premultiplication rounding+ // would corrupt untouched pixels and history snapshots.entry.surface.ctx.fillStyle = 'rgba(40,180,220,0.5)';entry.surface.ctx.fillRect(20, 20, 10, 10); // layer-local (120,120)const settled = entry.surface.ctx.getImageData(25, 25, 1, 1).data;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheShrink.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheShrink.browser.test.tsindex 306180268b..f5be8a95ce 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheShrink.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheShrink.browser.test.ts@@ -5,10 +5,8 @@ import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';import { describe, expect, it } from 'vitest';/**- * `shrinkToRect` crops by blitting the surviving window with a NEGATIVE- * `resizePreserving` offset, letting `drawImage` clip the rest. A sign slip would- * keep the wrong pixels; a no-op blit would lose the layer entirely. The node tests- * assert the arguments — these assert the pixels.+ * Real pixels verify shrink's negative copy offset and clipping; wrong signs retain the wrong region and failed+ * blits lose content.*/const START: Rect = { height: 200, width: 200, x: 100, y: 100 };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerDisplayEffect.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerDisplayEffect.tsindex 130815e070..df22342a7a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerDisplayEffect.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerDisplayEffect.ts@@ -1,23 +1,7 @@/**- * The display-only effects a layer's pixels pass through on the way to screen:- * the raster **adjustment stack** and the- * control-layer **transparency effect** (lightness→alpha, so a dark control map- * drops its background out).- *- * The compositor applies these to a layer's cache every frame through memoizing- * caches. This module exists for the one case that has pixels of its own outside- * that cache: a floating selection. Its pixels were cut from the layer, so they- * must render exactly as the layer's own pixels do — otherwise floating a region- * of a control map shows the raw, opaque black background the effect normally- * removes.- *- * Both effects are strictly PER-PIXEL, so applying one to a cut-out region gives- * exactly the same result as applying it to the whole layer and then cutting.- * That is what lets the float bake its display copy ONCE at lift time rather- * than re-deriving it every frame: nothing about its transform can change the- * outcome, and a change to the layer's display properties cancels the float.- *- * Zero React, zero import-time side effects.+ * Floating selections need the same raster adjustments/control transparency as their layer. These per-pixel+ * effects commute with cutting, so bake a display copy once at lift. Transform changes do not affect it;+ * appearance changes cancel the float.*/import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';@@ -35,11 +19,7 @@ export const hasLayerDisplayEffect = (layer: CanvasLayerContract): boolean => {return layer.type === 'raster' && !isIdentityAdjustments(layer.adjustments);};-/**- * A copy of `source` with `layer`'s display effects baked in, or `null` when the- * layer has none — the caller then draws `source` directly, which is the common- * case and allocates nothing.- */+/** Returns an effect-baked copy, or null when drawing the source directly needs no allocation. */export const renderLayerDisplayEffect = (backend: RasterBackend,layer: CanvasLayerContract,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.tsindex 6c59da9e94..2cdac60fd6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.ts@@ -43,11 +43,7 @@ const drawDiagonalLines = (}};-/**- * Builds a colour-specific repeat tile for a non-solid fill `style`, or returns- * `null` for `'solid'` (no pattern — the colour is filled directly). The tile is- * drawn in `color` through the backend seam.- */+/** Builds a color-specific repeating tile; solid fills return null for direct color drawing. */export const createMaskPatternTile = (backend: RasterBackend,style: CanvasMaskFillContract['style'],@@ -75,8 +71,7 @@ export const createMaskPatternTile = (case 'grid':case 'horizontal':case 'vertical': {- // Pixel-centred lines (0.5 offset) so 1px strokes stay crisp, matching- // the legacy SVG tiles (lines at 0.5 / 3.5 / 6.5, etc.).+ // Half-pixel alignment keeps 1px strokes crisp, matching legacy SVG tiles.for (let p = 0.5; p < spec.size; p += spec.spacing) {if (style !== 'horizontal') {ctx.beginPath();@@ -97,12 +92,7 @@ export const createMaskPatternTile = (return tile;};-/**- * Produces a colorized RGBA surface the size of the mask cache: the mask's alpha- * is the stencil, the `fill` supplies the colour (solid) or a repeat `tile`- * (pattern), composited `source-in`. The caller blits the result through the- * layer transform.- */+/** Colorizes cache alpha with solid fill or repeat tile via source-in; the caller applies the layer transform. */export const colorizeMask = (backend: RasterBackend,mask: RasterSurface,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.tsindex feb4e99849..991e2a794e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts@@ -60,14 +60,8 @@ export interface OverlayFrame {}/**- * Projects engine state into the overlay renderer's descriptor.- *- * The overlay is chrome — bbox, grid, cursor ring, marching ants, tool- * previews — and every part of it is derived, never owned. Keeping the- * projection pure means the overlay's rules can be tested without a canvas:- * which tool shows which affordance, that a live drag preview stands in for- * committed state so the overlay tracks the gesture, and that a frame is- * suppressed rather than drawn against stale geometry.+ * Pure projection of engine state into overlay descriptors. Live previews replace committed geometry; stale frames+ * are suppressed. The overlay owns no interaction state.*/export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame => {const { getActiveToolId, selection, stores, transformOverrides } = deps;@@ -117,8 +111,7 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =return null;}const layer = lookupDocumentLayer(doc, session.layerId);- // The layer's LOCAL content rect (off-origin aware): the frame must wrap the- // pixels where the compositor draws them, not an assumed origin-anchored box.+ // Frame actual local content bounds, including off-origin pixels.const rect = layer ? hittableLayerRect(layer, doc) : null;if (!rect) {return null;@@ -129,8 +122,6 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =return {describe: (doc, view, floatFrame, samPreview) => {const activeTool = getActiveToolId();- // While the bbox tool drags, the transient preview stands in for the- // committed frame so the rect and its handles track the gesture.const bboxPreview = stores.bboxPreview.get();const samSession = stores.samInteraction.get();return {@@ -141,13 +132,11 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =bboxOverlayColor: stores.checkerColors.get().a,cursor: deps.getOverlayCursor(),gradientPreview: stores.gradientPreview.get(),- // The grid spans the whole viewport at the bbox snap size when the- // setting is on; the document rect no longer bounds it.+ // Grid spans the viewport at bbox snap size, independent of document bounds.gridSize: stores.bboxGrid.get(),lassoPreview: stores.lassoPreview.get(),layerOutline: moveOutlineCorners(doc),- // Ants advance via the animator's overlay-only ticks, and ride the- // float's matrix so they track lifted pixels rather than the layer.+ // Overlay-only ants ticks use the float matrix to follow lifted pixels.marchingAnts: selection.hasSelection()? { matrix: floatFrame?.ants ?? null, paths: selection.antsPaths(), phase: deps.getAntsPhase() }: null,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.tsindex f77ce218e3..cc9fd720ec 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts@@ -99,8 +99,7 @@ describe('renderOverlay', () => {const target = backend.createSurface(200, 200);renderOverlay(target, baseState());const strokeStyles = findSet(target.callLog, 'strokeStyle');- // With the document outline gone, the bbox is the only stroked chrome here:- // exactly one stroke color is applied.+ // Only bbox chrome is stroked; there is no document outline.expect(strokeStyles).toEqual(['#3b82f6']);});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.tsindex 4dc7fbad94..39b5925f4c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts@@ -1,15 +1,6 @@/**- * Renders the interaction overlay — the second stacked canvas above the- * composited document: bbox rectangle, an optional viewport-wide grid, and- * the brush cursor ring. Everything is drawn in screen space (document points- * projected through `view`) so strokes stay a constant pixel width regardless- * of zoom. The canvas is an unbounded plane, so no document-bounds outline is- * drawn.- *- * Marching ants and transform handles come later; the functions here are kept- * small and composable so those can slot in. Every pixel operation flows- * through the {@link RasterSurface} `ctx` seam. Zero React, zero import-time- * side effects.+ * Interaction overlays render in screen space through `view`, keeping strokes and handles constant-sized at any+ * zoom. The unbounded plane has no document outline; all drawing uses {@link RasterSurface} contexts.*/import type { ParametricShapeKind } from '@workbench/canvas-engine/contracts';@@ -85,23 +76,14 @@ export interface OverlayState {gridSize?: number;/** Brush cursor ring, or `null`/absent to hide it. */cursor?: OverlayCursor | null;- /**- * A layer's rendered-bounds outline (the move tool's selection marquee): the- * four document-space corners, projected through `view` and stroked as a closed- * polygon. Absent/`null` to hide it.- */+ /** Move outline uses four document-space content corners projected through view; null/absence hides it. */layerOutline?: readonly Vec2[] | null;/**- * The active transform-tool frame: the layer's rotated bounds, its eight scale- * handles, and the center/top-edge points for the rotation nub — all in- * document space, projected through `view`. Absent/`null` when no transform- * session is active.+ * Document-space rotated transform bounds, eight handles and rotation-nub anchors; null/absence means no+ * session.*/transformFrame?: TransformFrameOverlay | null;- /**- * The in-progress lasso outline (document space): a freehand drag, or a- * polygon session with its placed vertices and close cue. Absent/`null` when idle.- */+ /** Document-space freehand/polygon lasso preview with vertices and close cue; null/absence means idle. */lassoPreview?:| { kind: 'freehand'; points: readonly Vec2[] }| {@@ -112,26 +94,13 @@ export interface OverlayState {closeArmed: boolean;}| null;- /**- * The committed selection's marching ants: the outline paths (document space)- * plus the animated dash phase. Absent/`null` when there is no selection.- */+ /** Committed document-space selection paths and animated dash phase; absent without selection. */marchingAnts?: MarchingAntsRender | null;- /**- * The in-progress shape-tool drag (document-space rect + kind), drawn as a- * live outline while a shape is being created. Absent/`null` when idle.- */+ /** Document-space shape creation preview; null/absence means idle. */shapePreview?: RectShapePreview | null;- /**- * The in-progress marquee-tool drag (document-space rect + kind), drawn as a- * live outline while a pixel selection is being dragged out. Absent/`null`- * when idle; the committed selection shows as marching ants instead.- */+ /** Document-space marquee drag preview; committed selections instead use ants. */marqueePreview?: RectShapePreview | null;- /**- * The in-progress gradient-tool drag (document-space start/end): a linear- * ramp's vector, or a radial one's center and radius. Absent/`null` when idle.- */+ /** Gradient drag start/end defines the linear vector or radial center/radius; absent when idle. */gradientPreview?: { kind: 'linear' | 'radial'; start: Vec2; end: Vec2 } | null;/** Dedicated Select Object mask preview, already colorized by the engine. */samPreview?: {@@ -165,11 +134,8 @@ const strokeRectScreen = (ctx: Ctx, screenRect: Rect): void => {};/**- * Draws grid lines across the entire viewport, in screen space, skipping when- * too dense. The canvas is an unbounded plane, so the grid is not clipped to any- * document rect: the visible screen rect is projected back into document space- * (via the inverse view) and snapped out to whole grid cells so the lines tile- * seamlessly while panning/zooming.+ * Project viewport bounds into document space and snap outward to grid cells for seamless pan/zoom. Skip overly+ * dense grids; never clip to document bounds.*/const drawGrid = (ctx: Ctx, state: OverlayState, target: RasterSurface): void => {const gridSize = state.gridSize ?? 0;@@ -270,10 +236,8 @@ const drawLayerOutline = (ctx: Ctx, state: OverlayState): void => {};/**- * Draws the transform frame (rotated bounds polygon, eight scale handles, and a- * rotation nub past the top edge) in screen space. Handles/nub stay a constant- * pixel size; the nub direction follows the rotated frame (top-edge → away from- * center), so it reads correctly at any layer rotation.+ * Screen-space transform bounds and fixed-size handles. Rotation nub extends from the top edge away from center,+ * following layer rotation.*/const drawTransformFrame = (ctx: Ctx, state: OverlayState): void => {const frame = state.transformFrame;@@ -299,8 +263,6 @@ const drawTransformFrame = (ctx: Ctx, state: OverlayState): void => {ctx.closePath();ctx.stroke();- // Rotation nub: from the top-edge midpoint, outward (away from center), a- // constant screen length; a small knob at the tip.const anchor = applyToPoint(view, frame.rotationAnchor);const center = applyToPoint(view, frame.center);const dx = anchor.x - center.x;@@ -335,11 +297,7 @@ const LASSO_PREVIEW_DASH: readonly number[] = [4, 4];/** Screen-space half-size of a placed polygon vertex knob. */const LASSO_VERTEX_HALF_PX = 2;-/**- * Draws the in-progress lasso as a dashed screen-space outline. A polygon also- * shows its placed vertices and, once it can close, a ring on the first one at- * the close hit radius, filled while the cursor is inside it.- */+/** Dashed lasso preview; polygons add vertices and a first-vertex close-radius cue filled on hover. */const drawLassoPreview = (ctx: Ctx, state: OverlayState): void => {const preview = state.lassoPreview;if (!preview) {@@ -390,11 +348,6 @@ const drawLassoPreview = (ctx: Ctx, state: OverlayState): void => {ctx.restore();};-/**- * Draws a rect-or-ellipse drag outline in screen space. Shared by the shape tool- * (previewing the layer it will create) and the marquee tool (previewing the- * region it will select) — the same dashed outline in both cases.- */const drawRectShapePreview = (ctx: Ctx, state: OverlayState, preview: RectShapePreview | null | undefined): void => {if (!preview || preview.rect.width <= 0 || preview.rect.height <= 0) {return;@@ -411,10 +364,6 @@ const drawRectShapePreview = (ctx: Ctx, state: OverlayState, preview: RectShapePctx.restore();};-/**- * Draws the gradient-tool drag in screen space: the vector with endpoint dots,- * plus the circle a radial gradient will fill.- */const drawGradientPreview = (ctx: Ctx, state: OverlayState): void => {const preview = state.gradientPreview;if (!preview) {@@ -508,10 +457,8 @@ const drawSamGeometry = (ctx: Ctx, state: OverlayState): void => {};/**- * Draws the bbox overlay shade: a translucent fill over the ENTIRE viewport- * with the bbox region punched out (even-odd fill rule — the two nested rect paths- * cancel inside the bbox), dimming everything outside the generation frame. The- * opacity rides `globalAlpha` so the theme color needs no string surgery.+ * Even-odd viewport/bbox fill shades outside the generation frame; globalAlpha controls opacity independently of+ * theme color.*/const drawBboxOverlayShade = (ctx: Ctx, state: OverlayState, target: RasterSurface): void => {if (!state.bboxOverlay) {@@ -528,11 +475,6 @@ const drawBboxOverlayShade = (ctx: Ctx, state: OverlayState, target: RasterSurfactx.restore();};-/**- * Draws the rule-of-thirds guides: two vertical and two horizontal lines dividing- * the bbox into thirds (screen space, solid, in the grid color). A composition aid- * over the generation frame.- */const drawRuleOfThirds = (ctx: Ctx, state: OverlayState): void => {if (!state.ruleOfThirds) {return;@@ -583,11 +525,7 @@ export const renderOverlay = (target: RasterSurface, state: OverlayState): voidctx.setTransform(1, 0, 0, 1, 0, 0);ctx.clearRect(0, 0, target.width, target.height);- // The document rect is retired as a visual boundary (unbounded plane), so no- // document outline is drawn. The bbox (generation frame) is the primary anchor.-- // The bbox overlay shade first: it dims the composited document outside the- // bbox, and every piece of overlay chrome (grid, guides, frame) draws over it.+ // Shade outside bbox first, then draw overlay chrome above it. The unbounded plane has no document outline.drawBboxOverlayShade(ctx, state, target);// Grid next (behind the bbox), spanning the whole viewport.@@ -598,9 +536,7 @@ export const renderOverlay = (target: RasterSurface, state: OverlayState): void// Rule-of-thirds guides sit inside the bbox, behind its frame.drawRuleOfThirds(ctx, state);- // Bbox (dashed, distinct color). Drawn as passive chrome unless the setting hides- // it (`showBbox === false`); the handles below still render for the bbox tool so- // the frame stays editable even when hidden.+ // Passive bbox visibility is optional; active-tool handles remain editable even when hidden.if (state.showBbox ?? true) {ctx.strokeStyle = BBOX_COLOR;ctx.setLineDash([...BBOX_DASH]);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.browser.test.tsindex a123376c74..6b62d90294 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.browser.test.ts@@ -7,9 +7,8 @@ import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';import { describe, expect, it } from 'vitest';/**- * The trim's verdict and its crop blit are both real pixel work, which the node stub- * (uniform invented readback, recorded-only blits) cannot exercise. These assert the- * pixels — including the `destination-out` erase that produced the reported bug.+ * Real pixels verify trim decisions and crop blits, including destination-out erasure that recording stubs cannot+ * model.*//** A published cache at a non-zero origin — the shape a chunk-padded stroke leaves. */diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.test.tsindex d3c0ef52f0..51d41cb001 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.test.ts@@ -5,11 +5,7 @@ import { trimPaintCacheToAlpha } from '@workbench/canvas-engine/render/paintCachimport { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';-/**- * A real cache store on the stub backend, whose readback is zeroed — so every- * published surface reads as transparent, making this the home for the `emptied`- * case and the guard matrix. Real cropping is asserted in the browser suite.- */+/** Zero-alpha stub readbacks exercise empty-cache verdicts and guards; browser tests verify actual cropping. */const harness = (options: { busy?: boolean } = {}) => {const store = createLayerCacheStore(createTestStubRasterBackend({ readbackAlpha: 0 }));const isLayerBusy = vi.fn(() => options.busy ?? false);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.tsindex 16d7a1a0ff..a42bb9ebf2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts@@ -1,16 +1,7 @@/**- * Trims a paint layer's raster cache back to the pixels it can actually show.- *- * The cache only ever grows (strokes chunk-pad their extent; the eraser grows it- * too), and persistence bakes that extent into the layer's bitmap dimensions — which- * is what the move outline, the transform frame and fit-to-content read. So a fully- * erased layer kept a draggable rectangle around nothing.- *- * Runs from the debounced persistence flush, so its synchronous full-surface alpha- * readback never touches the paint hot path. The readback is distinct from the- * asynchronous PNG encode and its cost scales with the cache extent.- *- * Zero React, zero import-time side effects.+ * Trim grown paint caches to visible alpha before persistence so erased padding does not become phantom layer+ * bounds. Full-surface synchronous readback runs in debounced flush, outside the stroke hot path, and scales with+ * cache extent.*/import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';@@ -31,10 +22,6 @@ export interface TrimPaintCacheDeps {readonly isLayerBusy: (layerId: string) => boolean;}-/**- * Shrinks `layerId`'s cache to its non-transparent bounds, or collapses it to a zero- * rect when it has none.- */export const trimPaintCacheToAlpha = (deps: TrimPaintCacheDeps, layerId: string): PaintCacheTrim => {// `peek`, not `get`: a persistence-side probe must not reorder the LRU.const entry = deps.layers.peek(layerId);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.test.tsindex ff5bbab857..dda76842b2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.test.ts@@ -50,8 +50,7 @@ describe('createTestStubRasterBackend', () => {});it('readbackAlpha fills the alpha channel only, leaving RGB zeroed', () => {- // The contract anything inferring content FROM pixels depends on: a stub- // surface reports pixels only when the test declares that it has them.+ // Pixel-derived decisions must reflect the content explicitly declared by the stub test.const backend = createTestStubRasterBackend({ readbackAlpha: 255 });const imageData = backend.createSurface(2, 2).ctx.getImageData(0, 0, 2, 2);const alphas = [...imageData.data].filter((_, index) => index % 4 === 3);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.tsindex c143316cb0..5ddbfcf5c3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts@@ -1,23 +1,7 @@/**- * A node-safe `RasterBackend` stub for vitest. Surfaces are backed by a- * fake 2D context that records every call it receives instead of touching- * a real canvas, so engine tests can assert on what was drawn without a- * DOM or `OffscreenCanvas`.- *- * The subset of `CanvasRenderingContext2D` the engine currently uses is- * implemented as recorded methods (save/restore/clearRect/fillRect/- * strokeRect/drawImage/path building/fill/stroke/clip/createPattern/- * createLinearGradient/createRadialGradient/setTransform/- * getImageData/putImageData/setLineDash). Gradients returned by the- * `create*Gradient` factories record their `addColorStop` calls on the same- * surface call log. Property assignments (fillStyle,- * globalAlpha, globalCompositeOperation, ...) are recorded too, via a- * `{ op: 'set', args: [prop, value] }` entry, so tests can assert that- * opacity/blend/style state was applied in order. Extend the method table in- * `createStubCtx` below as later tasks need more of the API surface.- *- * Readbacks are INVENTED, since the stub holds no pixels: `getImageData` returns a- * correctly-sized buffer whose alpha is {@link StubRasterBackendOptions.readbackAlpha}.+ * Node-safe RasterBackend records drawing calls, context properties and gradient stops without real pixels.+ * Synthetic getImageData buffers use {@link StubRasterBackendOptions.readbackAlpha}; browser tests verify actual+ * raster results.*/import type { RasterBackend, RasterSurface } from './raster';@@ -41,12 +25,8 @@ export interface StubRasterBackend extends RasterBackend {/** Options for {@link createTestStubRasterBackend}. */export interface StubRasterBackendOptions {/**- * The alpha every pixel of a synthetic readback reports (default `255`).- *- * A transparent readback MEANS something: the paint-cache trim reads alpha to- * decide whether a layer still has content, and clears one that has none. A test- * driving an explicitly empty-cache path must therefore declare- * `readbackAlpha: 0`; ordinary engine-integration tests default to visible pixels.+ * Synthetic readback alpha defaults to visible 255. Set zero explicitly for empty-cache tests because trimming+ * interprets transparent pixels as no content.*/readbackAlpha?: number;}@@ -62,10 +42,8 @@ const createStubImageData = (width: number, height: number, alpha = 0): ImageDat};/**- * Deterministic per-character advance the stub's {@link measureText} multiplies- * by the current font's pixel size — the same `0.6` factor the text rasterizer's- * pure `estimateTextExtent` uses (`TEXT_CHAR_WIDTH_FACTOR`), so a text layer's- * measured surface size in node tests exactly matches its estimated extent.+ * Stub text advance matches estimateTextExtent's 0.6*font-size factor, keeping node cache estimates and measured+ * extents consistent.*/const STUB_CHAR_WIDTH_FACTOR = 0.6;@@ -83,9 +61,6 @@ const createStubCtx = (callLog.push({ args, op });};- // Stored non-method property values (fillStyle, globalAlpha, font, etc.).- // Declared before the method table so `measureText` can read the current- // `font` to produce font-size-dependent metrics.const props: Record<string, unknown> = {};const methods: Record<string, (...args: unknown[]) => unknown> = {@@ -95,8 +70,6 @@ const createStubCtx = (clip: (...args: unknown[]) => log('clip', args),closePath: (...args: unknown[]) => log('closePath', args),fillText: (...args: unknown[]) => log('fillText', args),- // Deterministic, font-size-aware metrics: width = chars × fontSizePx × 0.6.- // No DOM/real canvas needed, so text measurement is reproducible in node.measureText: (...args: unknown[]) => {log('measureText', args);const text = String(args[0] ?? '');@@ -105,17 +78,13 @@ const createStubCtx = (},createLinearGradient: (...args: unknown[]) => {log('createLinearGradient', args);- // A recording CanvasGradient stand-in: every addColorStop is logged on- // the surface's own call log (as `addColorStop`), so tests can assert the- // stop offsets/colors that were applied to the gradient.return {addColorStop: (...stopArgs: unknown[]) => log('addColorStop', stopArgs),} as unknown as CanvasGradient;},createPattern: (...args: unknown[]) => {log('createPattern', args);- // A non-null marker standing in for a CanvasPattern, so callers that- // guard on a null return (e.g. the checkerboard fill) proceed.+ // Non-null pattern marker lets guarded fill paths execute.return { __stubPattern: true } as unknown as CanvasPattern;},createRadialGradient: (...args: unknown[]) => {@@ -150,8 +119,6 @@ const createStubCtx = (strokeRect: (...args: unknown[]) => log('strokeRect', args),};- // The proxy records every property assignment (into `props`, declared above)- // so tests can assert on applied state.const proxy = new Proxy(methods, {get(target, prop: string) {if (prop in target) {@@ -190,10 +157,8 @@ class StubRasterSurfaceImpl implements StubRasterSurface {}/**- * The stub holds no pixels, so this only records the resize and the offset the- * real surface would have blitted the old canvas to. Unlike the real surface- * the `ctx` is NOT replaced — keeping one call log per surface is what lets- * tests assert on a surface's whole history across a growth.+ * Records resize/offset without real pixels. Preserve the context log across growth so tests can inspect the+ * surface's full history.*/resizePreserving(w: number, h: number, dx: number, dy: number): void {this.callLog.push({ args: [w, h, dx, dy], op: 'resizePreserving' });@@ -202,10 +167,6 @@ class StubRasterSurfaceImpl implements StubRasterSurface {}}-/**- * Creates a `RasterBackend` whose surfaces are backed by a fake, node-safe- * 2D context that records draw calls instead of executing them.- */export const createTestStubRasterBackend = (options: StubRasterBackendOptions = {}): StubRasterBackend => ({createImageBitmap: (source: ImageBitmapSource): Promise<ImageBitmap> => {void source;@@ -213,8 +174,7 @@ export const createTestStubRasterBackend = (options: StubRasterBackendOptions =},createSurface: (width: number, height: number): StubRasterSurface =>new StubRasterSurfaceImpl(width, height, options.readbackAlpha ?? 255),- // Deterministic fake blob keyed on the surface size, so encode calls are- // reproducible in node without touching a real canvas.+ // Size-keyed fake blobs keep node encoding deterministic.encodeSurface: (surface: RasterSurface, type = 'image/png'): Promise<Blob> =>Promise.resolve(new Blob([`stub-surface-${surface.width}x${surface.height}`], { type })),});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.tsindex ade9a2df50..d3db5fe446 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.ts@@ -1,9 +1,6 @@/**- * The RasterBackend seam: every place the engine needs a 2D canvas surface- * or an ImageBitmap, it goes through an injected `RasterBackend` instead of- * calling `document.createElement('canvas')` / `new OffscreenCanvas(...)`- * directly. This keeps the engine testable in node — tests inject- * `render/raster.testStub.ts`'s stub backend instead of `createDomRasterBackend()`.+ * Injected RasterBackend owns all canvas/ImageBitmap creation, allowing node tests to use recording surfaces+ * instead of browser globals.*//** A single drawable/resizable 2D surface, backed by either an OffscreenCanvas or an HTMLCanvasElement. */@@ -14,26 +11,9 @@ export interface RasterSurface {readonly height: number;resize(w: number, h: number): void;/**- * Resizes to `w`×`h` while keeping the current pixels, placed at `(dx, dy)`- * in the new surface.- *- * This exists because {@link resize} cannot preserve anything: assigning- * `canvas.width` resets the backing store, so a caller that wants its pixels- * back has to read them out to the CPU first and upload them again. That- * round trip is the dominant cost of growing a layer cache during a stroke —- * measured at 33.8 ms for a 3520×3200 → 3840×3712 growth, against a 14.9 ms- * floor for reallocating and preserving nothing.- *- * Adopting a fresh canvas and blitting the old one into it does the copy on- * the GPU instead, for 17.9 ms on the same growth. It costs no extra- * allocation — the copy's target IS the new surface, and the old canvas is- * dropped — which is what separates it from a temp-buffer scheme, where the- * second allocation gives back everything the faster copy wins.- *- * `canvas` and `ctx` are therefore REPLACED, not mutated. The surface object- * itself keeps its identity (caches key derived surfaces on it), but anything- * holding a reference to the old `canvas`/`ctx` across this call is holding a- * detached one. As with `resize`, all context state resets to defaults.+ * Resize preserves pixels at (dx,dy) by adopting a fresh canvas and blitting the old backing store, avoiding CPU+ * readback and a second temporary allocation. Surface identity remains stable, but canvas/context references are+ * replaced and all context state resets.*/resizePreserving(w: number, h: number, dx: number, dy: number): void;}@@ -47,10 +27,6 @@ export interface RasterSurfaceOptions {export interface RasterBackend {createSurface(width: number, height: number, options?: RasterSurfaceOptions): RasterSurface;createImageBitmap(source: ImageBitmapSource): Promise<ImageBitmap>;- /**- * Encodes a surface's pixels to an image `Blob` (PNG by default). Used by the- * bitmap store to persist painted layers as content-hashed server images.- */encodeSurface(surface: RasterSurface, type?: string): Promise<Blob>;}@@ -158,11 +134,7 @@ class DomCanvasRasterSurface implements RasterSurface {}}-/**- * Creates a `RasterBackend` backed by the DOM/browser: `OffscreenCanvas`- * when available, falling back to `HTMLCanvasElement` otherwise (notably- * Safari < 16.4, which lacks `OffscreenCanvas` support).- */+/** Uses OffscreenCanvas when available, otherwise HTMLCanvasElement. */export const createDomRasterBackend = (): RasterBackend => {const useOffscreen = isOffscreenCanvasSupported();return {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.tsindex e86ce2fdb4..90355fafdc 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts@@ -232,9 +232,7 @@ export const renderRasterComposite = async (const drawRef = async (ctx: Ctx, ref: CompositeLayerRef): Promise<void> => {const layerSurface = await deps.getLayerSurface(ref.id);if (ref.adjustments) {- // Bake non-destructive adjustments so the generated image matches what the- // user sees: render this layer alone into a bbox temp, apply the LUTs, then- // composite the adjusted temp with the layer's opacity/blend.+ // Bake adjustments into an isolated bbox surface before applying layer opacity/blend to generation output.const temp = deps.backend.createSurface(width, height);const tempCtx = temp.ctx;setTransform(tempCtx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.tsindex 7fa0b52c2b..b0a25e72d9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.ts@@ -1,17 +1,7 @@/**- * Rasterizes a `gradient` layer source (linear / radial). Gradient layers are- * PARAMETRIC and CONTENT-SIZED: the source carries an explicit `width`/`height`- * extent (set bbox-sized at creation, preserved across angle edits) and the- * gradient spans that extent. Legacy gradients that predate the extent field- * default to the document dims (see {@link RasterizeDeps.documentSize}), so they- * render identically. The compositor positions the extent via the layer transform.- *- * Linear: the gradient line runs through `center` along `angle` (degrees;- * 0° = left→right) for `span` px. Radial: `span` is the radius around `center`.- * Without an anchor the ramp is centered on the extent and fitted to its- * corners (how gradients looked before the drag placed them).- *- * Zero React, zero import-time side effects.+ * Content-sized parametric gradients use explicit extent, falling back to document dimensions for legacy sources.+ * Linear angle 0 runs left-to-right over span; radial span is radius. Without anchors, center and fit the ramp to+ * extent corners.*/import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';@@ -49,10 +39,8 @@ const buildGradient = (ctx: Ctx, source: GradientSource, width: number, height:};/**- * Draws a gradient source into a surface sized to its explicit extent (or the- * document dims for legacy gradients), reusing `target` if provided. Synchronous- * work wrapped in a resolved promise so it shares the `rasterizeSource` dispatch- * signature.+ * Rasterizes explicit or legacy document extent, reusing target. Synchronous drawing returns a resolved promise to+ * match source dispatch.*/export const rasterizeGradientSource = (source: GradientSource,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/imageRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/imageRasterizer.tsindex f70ec5b8f4..8b0dbe0d46 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/imageRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/imageRasterizer.ts@@ -1,13 +1,3 @@-/**- * Rasterizes an `image` layer source: decodes the referenced asset to an- * `ImageBitmap` (cached per image name in the store) and blits it onto a- * surface sized to the bitmap.- *- * Decoding is async and goes entirely through injected seams (the resolver- * for bytes, the backend for `createImageBitmap`), so it runs in node tests- * with fakes. Zero React, zero import-time side effects.- */-import type { CanvasImageRef } from '@workbench/canvas-engine/contracts';import type { DecodedBitmapLease } from '@workbench/canvas-engine/render/decodedBitmapPool';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.tsindex 8821b108f3..fe0c772520 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts@@ -1,14 +1,3 @@-/**- * Source rasterizer dispatch.- *- * Given a layer `source`, produces a {@link RasterSurface} holding its- * rasterized pixels. `image`, `paint`, `shape`, `gradient`, and `text` are- * implemented. A `polygon` shape (no points-editing UX yet) throws — the- * dispatch only routes parametric (non-polygon).- *- * Zero React, zero import-time side effects.- */-import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';@@ -29,10 +18,6 @@ export { rasterizePaintSource } from './paintRasterizer';export { rasterizeShapeSource } from './shapeRasterizer';export { rasterizeTextSource, textFontString, textFontVariationSettings } from './textRasterizer';-/**- * Rasterizes any supported layer source into a surface. Throws only for the- * deferred `polygon` shape kind (no rasterizer yet).- */export const rasterizeSource = (source: CanvasLayerSourceContract,deps: RasterizeDeps,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/paintRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/paintRasterizer.tsindex 9ef8f158ef..b880f90841 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/paintRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/paintRasterizer.ts@@ -1,12 +1,6 @@/**- * Rasterizes a `paint` layer source. Paint layers are CONTENT-SIZED: the- * persisted bitmap covers only the painted region, positioned in the layer's- * local space by the source `offset` (default `{ x: 0, y: 0 }` for legacy- * document-sized bitmaps). When the source has a bitmap it is decoded and- * blitted onto a surface sized to the bitmap; when it is `null` the layer is- * empty and the result is a zero-rect surface (a brand-new / cleared layer).- *- * Zero React, zero import-time side effects.+ * Paint surfaces match persisted bitmap dimensions at the source's local offset (legacy zero). Null bitmaps yield+ * empty zero-rect surfaces.*/import type { CanvasImageRef } from '@workbench/canvas-engine/contracts';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.tsindex 0c93fd5850..cc12c0278b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts@@ -1,20 +1,6 @@/**- * Rasterizes a `shape` layer source (rect / ellipse / triangle / star /- * polygon). Shape layers are PARAMETRIC: their pixels are derived from the source params (`width`,- * `height`, `fill`, `stroke`, `strokeWidth`, `kind`) rather than a persisted- * bitmap, so they re-render for free whenever a param changes.- *- * Extent semantics: a shape's surface is sized to the source's own- * `width`×`height` (its layer-local extent), NOT the document — the compositor- * applies the layer transform (position/scale/rotation) when drawing, exactly- * like an `image` layer. The stroke is drawn INSET by `strokeWidth / 2` so a- * thick outline stays entirely within the extent rather than clipping at the- * surface edge.- *- * `polygon` sources carry their vertices across the extent; a polygon with- * fewer than three points has nothing to draw and is refused by the dispatch.- *- * Zero React, zero import-time side effects.+ * Parametric shapes rasterize at source width/height; compositing applies transforms. Inset strokes by half-width+ * to contain outlines. Polygons with fewer than three vertices are refused.*/import type { CanvasLayerSourceContract, ParametricShapeKind } from '@workbench/canvas-engine/contracts';@@ -30,14 +16,8 @@ const STAR_INNER_RATIO = 0.382;const STAR_SPIKES = 5;/**- * Builds the parametric path for `kind` into an `x/y + width×height` box inset- * by `inset` on every side. Shared by the rasterizer and the drag-preview- * outline so a committed shape lands exactly where its preview drew. Sharp- * kinds (triangle, star) are stroked with round joins, so a half-stroke-width- * inset genuinely contains the outline. The inset path is a box RESCALE, not a- * uniform offset: on slanted edges a thick stroke drifts slightly outside the- * fill silhouette — accepted (the ellipse's radius-shrink has the same class- * of error), revisit only if design objects.+ * Shared raster/preview path inside an inset box, with round joins for sharp corners. Inset rescales the box+ * rather than uniformly offsetting edges, so slanted thick outlines may drift slightly beyond the fill silhouette.*/export const buildParametricShapePath = (ctx: Ctx,@@ -102,11 +82,7 @@ export const buildParametricShapePath = (ctx.rect(x + inset, y + inset, w, h);};-/**- * Draws a shape source's fill then stroke into an `x/y + width×height` box on- * the current transform. Shared by the layer rasterizer and the shape tool's- * pixel placement so both stroke a shape the same way.- */+/** Shared fill-then-stroke drawing keeps shape rasterization and pixel placement consistent. */export const drawShapeSource = (ctx: Ctx,source: ShapeSource,@@ -133,12 +109,6 @@ export const drawShapeSource = (}};-/**- * Draws a shape source onto a surface sized to the source extent. Reuses- * `target` if provided (resizing it to the extent), matching the paint/image- * rasterizer contract. Synchronous work wrapped in a resolved promise so it- * shares the `rasterizeSource` dispatch signature.- */export const rasterizeShapeSource = (source: ShapeSource,deps: RasterizeDeps,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.tsindex 7b92ddd754..354476c683 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/textRasterizer.ts@@ -1,30 +1,7 @@/**- * Rasterizes a `text` layer source. Text layers are PARAMETRIC and- * EDITABLE-FOREVER: their pixels are derived from the source params (`content`,- * `fontFamily`, `fontSize`, `fontWeight`, `fontStyle`, `fontVariations`,- * `lineHeight`, `align`, `color`) rather- * than a persisted bitmap, so a style/content edit re-renders for free — the- * headline upgrade over legacy's rasterized (frozen) text.- *- * Layout is deliberately SIMPLE (Risk 8): manual line breaks on `\n`, a- * `lineHeight` multiplier over `fontSize`, and per-line horizontal alignment- * within the measured block width. There is NO shaping engine — no BiDi, no- * complex-script clustering, no automatic word wrap, no kerning beyond what the- * platform `fillText` applies. Metrics come through the {@link RasterSurface}- * `ctx` seam (`measureText`), so node tests run on the stub's deterministic- * `width = chars × fontSizePx × 0.6` (see `raster.testStub.ts`).- *- * Extent semantics: like a shape, the surface is sized to the text BLOCK's own- * measured `width`×`height` (its layer-local extent, top-left origin); the- * compositor applies the layer transform (position/scale) when drawing. A layer- * with an empty `content` still produces a minimal 1×lineHeight surface so its- * transform/anchor stays meaningful.- *- * Font loading (late web-font availability) is handled by the ENGINE, not here:- * this rasterizer draws with whatever metrics `ctx` currently reports, and the- * engine re-rasterizes when a pending font resolves (see `render/fontLoader.ts`).- *- * Zero React, zero import-time side effects.+ * Editable parametric text uses manual newlines, font-size line-height and per-line alignment within measured+ * bounds. Browser measureText/fillText supply metrics and shaping; there is no custom layout or automatic+ * wrapping. Empty text retains a minimal 1xlineHeight extent. The engine owns late-font rerasterization.*/import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';@@ -37,12 +14,8 @@ export type TextSource = Extract<CanvasLayerSourceContract, { type: 'text' }>;type Ctx = RasterSurface['ctx'];/**- * Per-character horizontal advance as a fraction of the font's pixel size, used- * by the pure {@link estimateTextExtent}. It matches the test stub's- * `measureText` factor so a text layer's estimated extent and its- * stub-measured surface size agree exactly in node tests. In the browser the- * true `measureText` governs the rendered surface; the estimate is only a- * pre-measure cache-size / bounds approximation.+ * Pure estimated character advance matches node stub metrics. Browser measureText determines final surfaces;+ * estimates only seed bounds/cache sizing.*/export const TEXT_CHAR_WIDTH_FACTOR = 0.6;@@ -66,11 +39,8 @@ export const textLines = (content: string): string[] => content.split('\n');const lineHeightPx = (source: TextSource): number => source.fontSize * source.lineHeight;/**- * A pure, DOM-free estimate of a text block's unscaled pixel extent, matching- * the stub's deterministic metrics (`TEXT_CHAR_WIDTH_FACTOR`). Used by the pure- * geometry helpers (`sources.ts`) to size caches / bounds before a real- * `measureText` runs; the rasterizer resizes the surface to the precise- * measured size, so a browser mismatch only affects the initial cache size.+ * DOM-free text extent estimate for pre-measure geometry. Rasterization resizes to actual measured bounds; node+ * stubs use matching metrics.*/export const estimateTextExtent = (source: TextSource): { width: number; height: number } => {const lines = textLines(source.content);@@ -94,10 +64,8 @@ const measureBlock = (ctx: Ctx, source: TextSource, lines: string[]): { width: n};/**- * Draws a text source into a surface sized to the measured text block, reusing- * `target` if provided (resizing it to the measured extent), matching the- * paint/image/shape rasterizer contract. Synchronous work wrapped in a resolved- * promise so it shares the `rasterizeSource` dispatch signature.+ * Draws into measured text bounds, resizing an optional target. Returns a resolved promise to match source+ * dispatch.*/export const rasterizeTextSource = (source: TextSource,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/types.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/types.tsindex 0173b6b0c1..8bddb1647e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/types.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/types.ts@@ -1,33 +1,18 @@-/**- * Shared vocabulary for the source rasterizers.- *- * Type-only module (no runtime), so it can be imported by both the dispatch- * (`rasterizeSource`) and the per-source rasterizers without any import- * cycle. Zero React, zero side effects.- */-import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { DecodedBitmapPool } from '@workbench/canvas-engine/render/decodedBitmapPool';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-/**- * Resolves a persisted image asset (referenced by name in the document) to a- * `Blob` for decoding. The DOM implementation (deriving a URL and fetching)- * ships with the React shell task; the engine only depends on this seam so it- * stays node-testable.- */+/** Resolves persisted image names to decode blobs; application networking stays behind this injectable seam. */export type ImageResolver = (imageName: string, signal?: AbortSignal) => Promise<Blob>;/** A text source whose family may be replaced by an injected custom-font alias. */export type RasterizeTextSource = Extract<CanvasLayerSourceContract, { type: 'text' }>;/**- * The result of rasterizing a source: the surface holding its pixels plus the- * content `rect` those pixels occupy in the layer's LOCAL coordinate space. For- * origin-anchored sources (image / shape / text / gradient) the rect origin is- * `(0, 0)`; a `paint` source places its bitmap at the persisted `offset`.+ * Pixels and their layer-local content rect. Image/shape/text/gradient start at zero; paint uses its persisted+ * offset.*/export interface RasterizeResult {surface: RasterSurface;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.tsindex 22417531e6..b54f883111 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.ts@@ -1,14 +1,6 @@/**- * A single-rAF render scheduler.- *- * Consumers call `invalidate(...)` many times per frame; the scheduler- * coalesces those into one pending `RenderFlags` set and runs the injected- * `render` callback at most once per animation frame. The rAF driver is- * injectable so the scheduler can be driven deterministically in node tests.- *- * Zero React, zero import-time side effects; the only DOM touch point is the- * default `requestFrame`/`cancelFrame`, which are resolved lazily at call- * time (never at import) and are always overridden in tests.+ * Coalesces invalidations into one flag set and render per animation frame. Injected drivers support deterministic+ * tests; default browser functions resolve lazily.*/import type { LayerDamage, RenderFlags } from '@workbench/canvas-engine/types';@@ -24,12 +16,8 @@ export interface InvalidatePayload {/** Force a full repaint next frame. */all?: true;/**- * The layer-local region this invalidation changed — purely an optimisation,- * letting the frame repaint only those pixels.- *- * It is honoured ONLY when it names the single layer in `layers`; anything- * else (a bare `layers`, a `view`, an `all`) widens the frame back to a full- * repaint. Callers therefore opt in, and omitting it is always safe.+ * Optional local damage is honored only for the sole named layer. View/all or unqualified layer invalidations+ * force full repaint; omission is safe.*/damage?: LayerDamage;}@@ -74,10 +62,6 @@ const defaultCancelFrame = (handle: number): void => {globalThis.cancelAnimationFrame(handle);};-/**- * Creates a coalescing, single-frame render scheduler. See module docs for- * the coalescing and pause/resume semantics.- */export const createRenderScheduler = (deps: RenderSchedulerDeps): RenderScheduler => {const requestFrame = deps.requestFrame ?? defaultRequestFrame;const cancelFrame = deps.cancelFrame ?? defaultCancelFrame;@@ -121,11 +105,8 @@ export const createRenderScheduler = (deps: RenderSchedulerDeps): RenderScheduleif (disposed) {return;}- // Damage merging is deliberately pessimistic: a frame may repaint only part- // of the viewport just when EVERY invalidation in it named the region it- // changed. A repaint-everything flag, or a layer invalidation without a- // region, drops the frame back to full — so a caller that forgets to report- // damage costs performance, never correctness.+ // Partial repaint requires every invalidation to declare damage. Any unknown region widens to full, trading+ // performance for correctness.if (payload.all) {pending.all = true;pending.damage = null;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.tsindex 71b4a0fca2..3c8fe94a9a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/thumbnail.ts@@ -13,10 +13,8 @@ export interface ThumbnailSize {export type LayerThumbnailFallbackStage = 'thumbnail' | 'full' | 'failed';/**- * Scales a `srcW`x`srcH` surface to fit inside a `maxSize`x`maxSize` box,- * preserving aspect ratio and never upscaling (scale is clamped to ≤ 1). Both- * returned dimensions are at least 1px. Returns a zero size for a degenerate- * (non-positive) source.+ * Aspect-preserving fit without upscaling; positive sources return at least 1px dimensions, degenerate sources+ * return zero size.*/export const fitThumbnailSize = (srcW: number, srcH: number, maxSize: number): ThumbnailSize => {if (srcW <= 0 || srcH <= 0 || maxSize <= 0) {@@ -29,12 +27,7 @@ export const fitThumbnailSize = (srcW: number, srcH: number, maxSize: number): T};};-/**- * Resolves the persisted image that can stand in for a layer while its engine- * cache is unavailable. Image and paint sources are handled uniformly through- * `renderableSourceOf`, including the synthetic paint source exposed by masks.- * Empty paint/mask and parametric sources have no persisted image fallback.- */+/** Persisted image fallback for image/paint and synthetic mask sources. Empty or parametric sources have none. */export const resolveLayerThumbnailImageRef = (layer: CanvasLayerContract): CanvasImageRef | null => {try {const source = renderableSourceOf(layer);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.tsindex 2bf607abd2..46b0e15d79 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.ts@@ -31,15 +31,8 @@ export interface SelectObjectBridge {}/**- * The engine's half of the Select Object (SAM) flow.- *- * Both halves are policy rather than wiring. The decode validates that what- * came back actually matches the mask it was asked for — a SAM output whose- * dimensions disagree with the preview rect would silently paint the wrong- * region, so it fails loudly with a tagged error the application layer can- * report. The start gate mirrors the refusal reasons the UI shows, and computes- * the layer's document-space bounds so the caller does not have to re-derive- * them from the transform.+ * SAM bridge validates decoded dimensions against requested mask bounds and reports tagged errors. Start+ * eligibility mirrors UI refusals and provides transformed document bounds.*/export const createSelectObjectBridge = (deps: CreateSelectObjectBridgeDeps): SelectObjectBridge => ({decodeSelectObjectPreview: async (result, signal) => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.test.tsindex 181c00ede5..cb763b9ed1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.test.ts@@ -129,10 +129,8 @@ describe('liftSelectedPixels', () => {layerMatrix: matrixOf({ rotation: Math.PI / 2 }),mask: placed({ height: 20, width: 10, x: 30, y: 40 }),});- // A quarter turn swaps the axes: document x becomes local -y and vice versa,- // so document [30,40]×[40,60] lands on local [40,60]×[-40,-30]. The region is- // rounded OUTWARD, so trig landing a hair off an integer may widen it by a- // pixel — harmless, since the stencil's alpha is zero out there.+ // Quarter-turn mapping swaps axes into local [40,60]x[-40,-30]. Outward rounding may add a harmless+ // transparent pixel at floating-point edges.const rect = lifted!.pixels.rect;expect(rect.x).toBe(40);expect(rect.width).toBe(20);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.tsindex 6f72d62a52..bdea4307a9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.ts@@ -1,32 +1,8 @@/**- * The floating selection: pixels lifted out of a layer and held in flight.- *- * Dragging inside the marching ants cuts the selected pixels off the layer into- * a transient float that follows the pointer, leaving a hole behind. The float- * stays live — re-draggable, transformable — until it is committed (baked back- * into the same layer as ONE undo entry) or cancelled (the hole refilled). This- * module owns the geometry and the pixel extraction; `FloatingSelectionController`- * owns the lifecycle, history, and persistence around it.- *- * ## Coordinate spaces- *- * The distinction that makes this work: **the selection mask is in DOCUMENT- * space, the layer cache is in LAYER-LOCAL space.** They coincide only when the- * layer's transform is the identity — which the existing `selectionOps` fill and- * erase happen to assume. A float cannot assume it: it lands back in the layer- * cache, so it must be exact under rotation and scale.- *- * So the float keeps its pixels and its live transform in **layer-local** space:- *- * - The lift maps the mask into layer-local through the inverse layer matrix,- * which resamples the MASK (cheap, and only its coverage matters) rather than- * the content.- * - The lifted content is never resampled — a plain blit out and, for a pure- * translate at whole pixels, a plain blit back.- * - The move tool converts its document-space pointer delta into layer-local- * before applying it (see {@link documentDeltaToLocal}).- *- * Zero React, zero import-time side effects.+ * Owns float geometry and extraction; the controller owns lifecycle/history/persistence. Document-space masks map+ * through the inverse layer transform into local space, resampling coverage rather than content. Pixels and live+ * transforms stay layer-local; whole-pixel translations preserve exact blits, and pointer deltas convert via+ * {@link documentDeltaToLocal}.*/import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';@@ -43,12 +19,8 @@ export interface FloatingSelection {/** The lifted pixels, placed at their lift-time rect in LAYER-LOCAL space. */readonly pixels: PlacedSurface;/**- * `pixels` with the layer's display-only effects baked in (control- * transparency / raster adjustments), or `null` when the layer has none. The- * compositor draws THIS; the bake writes back the untouched `pixels`, so the- * effect is never burned into the document. Computed once at lift: the effects- * are per-pixel, so the float's transform cannot change them, and a change to- * the layer's display properties cancels the float outright.+ * Effect-baked display copy; raw `pixels` alone are written back. Per-pixel effects are computed at lift and+ * unaffected by transforms; appearance changes cancel the float.*/readonly display: RasterSurface | null;/** The layer cache's pre-lift pixels over the cut region, for cancel and the undo entry. */@@ -108,10 +80,7 @@ export const floatDocumentMatrix = (layerMatrix: Mat2d, floatMatrix: Mat2d): Matreturn inverse ? multiply(multiply(layerMatrix, floatMatrix), inverse) : null;};-/**- * Draws a document-space placed surface into a fresh surface covering `region`- * in LAYER-LOCAL space, projecting through `inverseLayerMatrix`.- */+/** Projects a placed document surface through the inverse layer matrix into a fresh local-region surface. */const projectIntoLocal = (backend: RasterBackend,source: PlacedSurface,@@ -133,13 +102,8 @@ const projectIntoLocal = (};/**- * Copies the layer's content within the selection into a detached surface, and- * returns the layer-local stencil that produced it. Returns `null` when the- * selection does not overlap the layer's content — there would be nothing to- * float.- *- * This does NOT modify the cache: punching the hole is the caller's step, done- * with the returned `localMask` so the two agree exactly.+ * Copies selected layer content and returns its exact local stencil, or null without overlap. Does not mutate+ * cache; callers cut with the same stencil.*/export const liftSelectedPixels = ({backend,@@ -174,10 +138,7 @@ export const liftSelectedPixels = ({return { localMask, pixels: { rect: region, surface } };};-/**- * Re-places a document-space mask through `matrix`, returning a fresh placed- * surface — how the selection outline follows a committed float.- */+/** Repositions the document mask through a matrix so committed selection outlines follow the float. */export const transformPlacedMask = (backend: RasterBackend,mask: PlacedSurface,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/marchingAnts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/marchingAnts.tsindex cbcd4c3c95..9bc8ec55c7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/marchingAnts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/marchingAnts.ts@@ -1,27 +1,7 @@/**- * Marching ants: the animated dashed outline of a pixel selection.- *- * Two concerns live here:- *- * 1. {@link drawMarchingAnts} strokes the selection's committed path list onto- * the overlay surface as a two-tone (black/white) dashed outline. It draws in- * document space (paths are document-space `Path2D`s) via the shared `view`- * transform, scaling line width and dash by `1/scale` so the ants stay a- * constant pixel size at any zoom — the same screen-constant convention the- * rest of the overlay uses. The animated `lineDashOffset` (`phase`) makes the- * white dashes crawl.- *- * 2. {@link createAntsAnimator} drives the `phase` advance. It self-reschedules- * through an injected `requestFrame`/`cancelFrame` pair (the engine passes the- * global rAF, so it rides the same frame clock as the scheduler) and, throttled- * by an injected `now()` to ~a few fps (the legacy look, not 60fps), calls- * `onStep` — the engine advances the phase and requests an OVERLAY-ONLY- * invalidation there, so an ants tick never recomposites layers (Task-22 gate).- * It runs only while started (a selection exists AND the engine is attached)- * and cancels its pending frame on `stop`, so there are no timer leaks on- * detach/deselect/dispose.- *- * Zero React, zero import-time side effects.+ * Draws black/white selection paths with zoom-compensated widths and dashes. A throttled injected frame loop+ * advances phase through overlay-only invalidation; run only while selected and attached, and cancel pending+ * frames on stop.*/import type { RasterSurface } from '@workbench/canvas-engine/render/raster';@@ -46,18 +26,12 @@ export interface MarchingAntsRender {/** Animated dash offset in screen pixels. */phase: number;/**- * An extra DOCUMENT-space transform to draw the outlines through, or absent- * for none. A live floating selection sets it so the ants track the pixels in- * flight without rebuilding the paths every frame; on commit the selection is- * re-placed for real and this goes back to absent.+ * Optional document transform moves ants with live float pixels without rebuilding paths. Commit replaces+ * selection geometry and removes the override.*/matrix?: Mat2d | null;}-/**- * Strokes the selection outline(s) as animated two-tone marching ants, in- * document space projected through `view`. A no-op with no paths.- */export const drawMarchingAnts = (ctx: RasterSurface['ctx'], view: Mat2d, render: MarchingAntsRender): void => {if (render.paths.length === 0) {return;@@ -116,11 +90,7 @@ export interface AntsAnimatorDeps {intervalMs?: number;}-/**- * Creates a self-rescheduling animation loop that fires `onStep` at most every- * `intervalMs`. It reschedules on every frame while running (to keep polling the- * clock) but only steps on the throttle boundary.- */+/** Polls the injected frame clock while running, firing `onStep` only at `intervalMs` boundaries. */export const createAntsAnimator = (deps: AntsAnimatorDeps): AntsAnimator => {const intervalMs = deps.intervalMs ?? ANTS_INTERVAL_MS;let running = false;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/maskOutline.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/maskOutline.tsindex 0bc0338db2..b2e799abfe 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/maskOutline.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/maskOutline.ts@@ -1,11 +1,6 @@/**- * Rectilinear boundary tracing for alpha masks.- *- * Converts a mask's alpha channel into closed pixel-edge contours so the- * marching ants can stroke the mask's true outline instead of its bounding- * rect. Outer boundaries wind clockwise (screen coordinates) and holes wind- * counter-clockwise, so the emitted path also nonzero-fills to the same shape- * it outlines.+ * Traces alpha masks as pixel-edge contours: clockwise outer boundaries and counterclockwise holes in screen+ * coordinates, preserving nonzero-fill shape.*/interface MaskAlphaSource {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.tsindex c73a081b9f..8e7dc04a2e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.ts@@ -1,13 +1,6 @@/**- * Makes a {@link SelectionState} undoable: every selection-changing call is- * bracketed by snapshots and recorded on the engine history as one step, so a- * marquee, lasso, select-all, invert, deselect, or Select Object result reverts- * on its own instead of taking the previous pixel edit with it.- *- * Replay restores snapshots directly and never re-enters this wrapper's- * recording path; a call that leaves the selection unchanged records nothing.- *- * Zero React, zero import-time side effects.+ * Snapshots selection-changing calls into individual engine-history steps. Unchanged selections record nothing;+ * replay restores snapshots directly without recording again.*/import type { History } from '@workbench/canvas-engine/history/history';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOpMode.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOpMode.tsindex 7353ce45a9..207e65885e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOpMode.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOpMode.ts@@ -1,12 +1,6 @@/**- * How a selection gesture's boolean op is resolved.- *- * Every selection tool (lasso, marquee) offers the same choice: a persistent op- * mode from its options bar, transiently overridden by modifiers held at commit- * time. Keeping the resolution here means the tools agree by construction rather- * than by convention, and neither has to import the other.- *- * Zero React, zero import-time side effects.+ * Shared selection-op resolution: commit-time modifiers override persistent mode consistently across lasso and+ * marquee.*/import type { PointerModifiers, SelectionOp } from '@workbench/canvas-engine/types';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOps.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOps.test.tsindex 59314ea8be..0ee50a3c31 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOps.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOps.test.ts@@ -70,8 +70,7 @@ describe('fillMaskedRegion', () => {targetOrigin: { x: 0, y: 0 },});- // Transparency lock: the final blit is source-atop, so colour lands ONLY where- // the target is already opaque (never fills transparent space).+ // Source-atop fill preserves transparency by coloring only existing target coverage.expect(compositeOps(target)).toContain('source-atop');expect(compositeOps(target)).not.toContain('source-over');});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOps.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOps.tsindex 73387d0768..42bac9a4d5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOps.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOps.ts@@ -1,22 +1,7 @@/**- * Selection-constrained raster primitives: fill and erase a layer's pixels- * within the selection mask.- *- * These are the pure pixel ops behind the engine's `fillSelection` /- * `eraseSelection` (the engine owns the layer-eligibility guards, dirty-rect- * before/after capture, undo history, and persistence around them). Each op- * composites through a scratch surface so the write lands ONLY where the mask is- * opaque — pixels outside the selection are never touched — and flows entirely- * through the {@link RasterBackend} `ctx` seam, so it runs on the node stub.- *- * Coordinate spaces: both the layer cache and the selection mask are content-- * sized (placed) surfaces with their own origins. `rect` is the edit region in- * document (= layer-local) space; `targetOrigin` / `maskOrigin` are the target- * cache surface's and the mask surface's document-space origins, so a document- * coordinate `d` maps to target-surface `d - targetOrigin` and mask-surface- * `d - maskOrigin`.- *- * Zero React, zero import-time side effects.+ * Masked fill/erase primitives; engine callers own guards, history and persistence. Scratch compositing confines+ * edits to selection coverage. Rect coordinates are document=layer-local here; subtract target/mask origins to+ * address each content-sized surface.*/import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';@@ -38,14 +23,8 @@ export interface MaskedEditParams {}/**- * Fills `color` into `target` wherever `mask` is opaque, within `rect`. Builds a- * `color`-filled scratch (region-local), intersects it with the mask- * (`destination-in`), then draws the masked color over the target.- *- * `composite` is the final blit's op: `source-over` (default) fills every masked- * pixel; `source-atop` honours a transparency lock — colour lands ONLY where the- * target is already opaque, never into transparent space (mirrors the- * transparency-locked brush in `paintTool.ts`).+ * Fill a region-local scratch, intersect the mask, then composite onto target. Default source-over fills coverage;+ * source-atop preserves transparency lock.*/export const fillMaskedRegion = ({backend,@@ -67,8 +46,6 @@ export const fillMaskedRegion = ({sctx.globalAlpha = 1;sctx.fillStyle = color;sctx.fillRect(0, 0, rect.width, rect.height);- // Keep the color only where the mask is opaque (mask drawn at its offset within- // the region-local scratch).sctx.globalCompositeOperation = 'destination-in';sctx.drawImage(mask.canvas, maskOrigin.x - rect.x, maskOrigin.y - rect.y);@@ -81,11 +58,6 @@ export const fillMaskedRegion = ({ctx.restore();};-/**- * Erases (`destination-out`) `target`'s pixels wherever `mask` is opaque, within- * `rect`. The mask shape is copied into a region-local scratch and composited out- * of the target.- */export const eraseMaskedRegion = ({backend,mask,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionPaths.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionPaths.tsindex 3f41efc0b0..01b07231da 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionPaths.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionPaths.ts@@ -1,17 +1,4 @@-/**- * SVG path data for the primitive selection shapes.- *- * Selection geometry reaches the engine as a closed `Path2D` (see- * {@link SelectionCommit}), built through the injected {@link CreatePath2D} seam- * so it stays node-safe. These builders produce the path DATA — the string — so- * they are pure, trivially testable, and usable on the node raster stub where- * `Path2D` is a fake.- *- * All coordinates are DOCUMENT space, matching the space the selection mask is- * placed in.- *- * Zero React, zero import-time side effects.- */+/** Pure document-space SVG path builders feed injected Path2D creation for selection commits and node tests. */import type { Rect } from '@workbench/canvas-engine/types';@@ -19,13 +6,7 @@ import type { Rect } from '@workbench/canvas-engine/types';export const rectPathData = (r: Rect): string =>`M ${r.x} ${r.y} L ${r.x + r.width} ${r.y} L ${r.x + r.width} ${r.y + r.height} L ${r.x} ${r.y + r.height} Z`;-/**- * SVG path data for a closed ellipse inscribed in `r`, as two half-arcs from the- * left extreme to the right and back. `A` (elliptical arc) is used rather than a- * Bézier approximation so the curve is exact; a full ellipse cannot be a single- * arc segment (start and end would coincide and the arc would be dropped), hence- * the pair.- */+/** Exact ellipse from two half-arcs; a single closed arc would have coincident endpoints and be dropped. */export const ellipsePathData = (r: Rect): string => {const rx = r.width / 2;const ry = r.height / 2;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.tsindex 5191726741..3819ea4dec 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.ts@@ -71,8 +71,7 @@ describe('selectionState: mask building from a path', () => {it('no longer clamps bounds to the document rect (infinite plane); the mask is bounded to the path', () => {const { selection } = createHarness();selection.commit({ bounds: rectBounds(-10, -10, 200, 200), op: 'replace', path: fakePath('p') });- // Content-sized: the selection bounds are the path's own bounds, not clamped- // to the document. The mask surface is placed at that (negative) origin.+ // Selection masks use path bounds, including negative origins, without document clamping.expect(selection.bounds()).toEqual(rectBounds(-10, -10, 200, 200));expect(selection.mask()?.rect).toEqual(rectBounds(-10, -10, 200, 200));});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.tsindex b08fa05c49..04dcccd58c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts@@ -1,36 +1,10 @@/**- * Engine-transient pixel selection.+ * Engine-owned, unpersisted selection state uses snapshots for undo. The bounded document-space alpha mask is+ * authoritative for clipping and boolean operations; paths serve only ants rendering.*- * Per the plan's state-tier table, a selection is *interaction* state: it lives- * on the engine, never in the reducer contract. It is undoable only through the- * engine's own history, which {@link SelectionState.snapshot} / `restore` serve- * (see `selectionHistory.ts`); persistence never sees it. The source- * of truth is the set of closed `Path2D` polygons the lasso tool commits; the- * derived artifact is a bounded **mask surface** (alpha 255 inside the- * selection), sized to the selection extent and placed in document space (a- * {@link PlacedSurface}), built through the {@link RasterBackend} seam. Boolean ops- * (`replace`/`add`/`subtract`/`intersect`) are applied to the MASK — that is the- * single source of truth for painting/fill clipping. The committed path list is- * kept only for {@link marchingAnts} rendering (stroking the outlines), not for- * re-deriving the mask.- *- * ## Marching ants- *- * A `replace` strokes its own path. Every boolean op (`add` / `subtract` /- * `intersect`) re-traces the mask's true edge via {@link traceMaskOutlinePath},- * the same way {@link SelectionState.replaceMask} does, so the ants show the- * boolean result rather than the union of the source outlines. `selectAll` /- * `invert` keep their document-border path. When a trace yields nothing after- * an `add` (a raster stub with no readable pixels), the source paths are- * stroked instead; after `subtract` / `intersect` an empty trace means the mask- * is empty, and the selection is dropped.- *- * ## Emptiness- *- * `hasSelection` is structural for `replace` / `add` (they cannot empty the- * mask) and pixel-derived for `subtract` / `intersect` through the same trace.- *- * Zero React, zero import-time side effects.+ * Replace uses its path; boolean operations retrace actual mask edges. Add may fall back to source paths when stub+ * pixels cannot be read; empty subtract/intersect results clear selection. Replace/add emptiness is structural,+ * while subtract/intersect inspect alpha.*/import type { CreatePath2D } from '@workbench/canvas-engine/freehand';@@ -68,11 +42,7 @@ export interface SelectionState {hasSelection(): boolean;/** The selection's document-space bounds, or `null` when empty. */bounds(): Rect | null;- /**- * The selection mask as a placed surface (alpha 255 inside) in document space,- * bounded to the selection extent (the `rect` records its origin/size), or- * `null` when empty.- */+ /** Document-space mask surface and extent, or null when empty. */mask(): PlacedSurface | null;/** The committed path outlines, for marching-ants rendering. */antsPaths(): readonly Path2D[];@@ -84,12 +54,7 @@ export interface SelectionState {replaceMask(mask: PlacedSurface): void;/** Selects the whole `domain` rectangle (the engine passes `content ∪ bbox`). */selectAll(domain: Rect): void;- /**- * Inverts the selection within `domain` (empty → select `domain`). The domain- * is the bounded region the complement is taken over — the engine passes- * `content ∪ bbox`, the coherent analogue of legacy's bounded canvas now that- * the document rect is retired.- */+ /** Complements within a bounded domain; empty selection selects it. Engine domain is content union bbox. */invert(domain: Rect): void;/** Clears the selection (deselect). */clear(): void;@@ -173,10 +138,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =onChange();};- /**- * Ensures the mask surface exists and covers `rect` (integer bounds),- * preserving any existing mask pixels at their new offset when it must grow.- */+ /** Ensure integer mask bounds, preserving old pixels at their shifted offset when growing. */const ensureMask = (rect: Rect): RasterSurface => {const want: Rect = roundOut(rect);if (!mask || !maskRect) {@@ -219,11 +181,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =return mask;};- /**- * Fills a path into the mask under `op`'s composite mode. The mask surface is- * offset by `maskRect.origin`, so the (document-space) path is drawn through a- * translate that maps document → surface coordinates.- */+ /** Draw document paths with document-to-mask translation under the boolean operation's composite mode. */const fillPath = (surface: RasterSurface, origin: Vec2, path: Path2D, op: GlobalCompositeOperation): void => {const ctx = surface.ctx;ctx.save();@@ -257,10 +215,8 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =const replaceMask = (next: PlacedSurface): void => {const rect = roundOut(next.rect);const publishEmptyReplacement = (): void => {- // Replacing from a valid empty alpha result should not clear the old- // surface in place: clearSurface() is fallible and would run after the- // logical selection flags had already changed. Detach the old surface and- // atomically publish an empty selection instead; it is reclaimed by GC.+ // Publish empty selection by detaching the old surface; a fallible in-place clear after changing logical+ // flags would break atomicity.mask = null;maskRect = null;commits = [];@@ -350,8 +306,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =selected = selected || bounds !== null;break;case 'subtract':- // Bounds only shrink; they stay the prior over-approximation, and the- // trace below decides whether anything is left.+ // Retain conservative prior bounds; tracing determines whether coverage remains.break;case 'intersect':selectionBounds = selectionBounds && bounds ? intersect(selectionBounds, bounds) : null;@@ -377,8 +332,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =return null;}const pixels = mask.ctx.getImageData(0, 0, maskRect.width, maskRect.height);- // A subtract that emptied the mask is the common way to get here: one alpha- // scan settles it without paying for two full traces.+ // One alpha scan detects emptied subtraction without two full traces.let hasAlpha = false;for (let index = 3; index < pixels.data.length; index += 4) {if (pixels.data[index] !== 0) {@@ -417,8 +371,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =return;}const rect = roundOut(domain);- // The current mask, captured over the domain: draw the (offset) mask onto a- // domain-sized temp so the complement is taken in domain-local coordinates.+ // Copy the placed mask into a domain-local temporary before complementing.const temp = backend.createSurface(Math.max(0, rect.width), Math.max(0, rect.height));const tctx = temp.ctx;tctx.setTransform(1, 0, 0, 1, 0, 0);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/stagedPreviewBlobCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/stagedPreviewBlobCache.tsindex 14fd40a773..e83759308f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/stagedPreviewBlobCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/stagedPreviewBlobCache.ts@@ -31,9 +31,8 @@ export interface StagedPreviewBlobCacheOptions {}/**- * Keeps compressed staged-result bytes warm without retaining decoded full-size- * surfaces for every candidate. Background requests are bounded, while the- * latest explicit `get()` preempts stale demand and promotes queued work.+ * Caches compressed candidate bytes with bounded background demand. Latest explicit get preempts stale requests+ * and promotes queued work without retaining all decoded surfaces.*/export const createStagedPreviewBlobCache = (resolveImage: ImageResolver,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.tsindex 2b98665a67..25b5b4c9a9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts@@ -31,12 +31,8 @@ export interface StrokeCommit {}/**- * Turns a committed stroke into its durable consequences.- *- * A stroke that auto-created its own layer cannot be undone as a plain pixel- * patch — undo has to remove the layer too — so those get a composed history- * entry that pairs the layer mutation with the pixel write. Ordinary strokes- * take the pixel-patch path.+ * Ordinary strokes record pixel patches; auto-created layers need composed history that also removes/recreates the+ * layer.*/export const createStrokeCommit = (deps: CreateStrokeCommitDeps): StrokeCommit => {const { applyImagePatch, dispatchCanvasMutation, history, layerCache } = deps;@@ -54,9 +50,7 @@ export const createStrokeCommit = (deps: CreateStrokeCommitDeps): StrokeCommit =label,redo: () => {dispatchCanvasMutation({ anchor: created.anchor, layer: created.layer, type: 'addCanvasLayer' });- // Re-create an EMPTY cache marked fresh so the async rasterize pass can't- // clobber the restored stroke; `applyImagePatch` grows it to the stroke's- // content bounds and writes the `after` pixels.+ // Create a fresh empty cache to fence async rasterization before restoring stroke pixels and bounds.const entry = layerCache.getOrCreateRect(layerId, { height: 0, width: 0, x: 0, y: 0 });entry.stale = false;applyImagePatch(layerId, rect, afterImageData);@@ -75,9 +69,7 @@ export const createStrokeCommit = (deps: CreateStrokeCommitDeps): StrokeCommit =// Persistence first: mark the layer dirty so a debounced upload fires even// when no external subscriber is attached.deps.markLayerDirty(event.layerId);- // Record the edit on the engine-owned history. Guarded against re-entrancy:- // an undo/redo replay routes pixels through `applyImagePatch`, not a fresh- // stroke, so this never fires during apply — the guard is belt-and-braces.+ // Guard history recording during replay, which restores via image patches rather than fresh strokes.if (!history.isApplying()) {deps.commitPaintEdit();const label = strokeCommitLabel(event.tool);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.tsindex 1cbe5d3434..5d039c2dc3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.ts@@ -1,16 +1,6 @@/**- * Pure geometry for the bbox (generation-frame) tool: handle layout, screen-space- * hit-testing, and resize/move math.- *- * The bbox is an axis-aligned document-space rectangle. Its eight resize handles- * (four corners + four edge midpoints) are hit-tested in SCREEN space so their- * grab areas stay a constant pixel size regardless of zoom — callers project the- * bbox to screen coordinates first. Resize math runs in DOCUMENT space: the edge- * opposite the grabbed handle stays fixed (or the center, under `symmetric`),- * the moved edge(s) follow a pointer delta, then snapping, min-size clamping,- * and (optionally) an aspect constraint are applied.- *- * Zero React, zero import-time side effects.+ * Bbox handles hit-test in screen space for fixed grab sizes; move/resize math uses document space. Keep opposite+ * edges, or symmetric center, anchored while applying snapping, minimum sizes and aspect constraints.*/import type { Rect, Vec2 } from '@workbench/canvas-engine/types';@@ -78,11 +68,7 @@ export const bboxHandleAt = (return null;};-/**- * What a screen-space `point` targets on the bbox: a resize handle (grab area- * first), the interior (`'move'`), or `null` (outside — the bbox is never- * deselected).- */+/** Hit-test handles before interior move; outside returns null without deselecting bbox. */export const bboxTargetAt = (screenRect: Rect,point: Vec2,@@ -122,11 +108,7 @@ export interface ResizeBboxParams {constrain: boolean;/** Target width / height ratio, used when `constrain`. */ratio: number;- /**- * Mirror the drag across the frame's center (ctrl/⌘): the opposite edge moves- * by the same amount in the opposite direction and the center stays put,- * instead of the opposite edge staying fixed.- */+ /** Ctrl/Command mirrors edge movement across a fixed center. */symmetric: boolean;}@@ -367,16 +349,8 @@ const pixelAlignResize = (rect: Rect, p: ResizeBboxParams): Rect => {};/**- * Resizes `start` for a handle drag. Applies (in order) the delta to the moved- * edge(s), grid snapping (unless bypassed), min-size clamping, and — when- * `constrain` — an aspect-ratio constraint anchored at the opposite corner- * (corners) or the center (edges).- *- * Under `symmetric` the frame mirrors across its center instead: both sides move- * by the drag, so the frame grows/shrinks twice as fast and the center stays- * put. That is exactly the anchored resize of a doubled delta re-centered on the- * start center — the grabbed edge still lands under the pointer, and snapping,- * min-size clamping and the aspect constraint all keep applying unchanged.+ * Apply drag delta, grid snap, minimum size and optional aspect constraint. Symmetric resize doubles the anchored+ * delta then recenters, preserving pointer alignment and the same constraints.*/export const resizeBbox = (p: ResizeBboxParams): Rect => {const resized = p.symmetricdiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.tsindex e99cc5348a..35dc25fc92 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts@@ -338,9 +338,7 @@ describe('bbox tool: hover cursors', () => {expect(cursorAt(64, 16)).toBe('ns-resize'); // N edge midpointexpect(cursorAt(112, 64)).toBe('ew-resize'); // E edge midpointexpect(cursorAt(64, 64)).toBe('move'); // interior- expect(cursorAt(400, 400)).toBe('default'); // off the frame-- // The tool asked the engine to re-apply the cursor as the hover target changed.+ expect(cursorAt(400, 400)).toBe('default');expect(h.ctx.updateCursor).toHaveBeenCalled();});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.tsindex 3292af3f56..cb721f80a4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.ts@@ -1,30 +1,7 @@/**- * The bbox tool: interactive editing of the generation bounding box- * (`document.bbox`).- *- * Interaction contract (CANVAS_PLAN Phase 4.1):- * - **Pointer-down** hit-tests the bbox: on a resize handle → a resize gesture;- * inside the frame → a move gesture; outside → nothing (the bbox is never- * "deselected").- * - **Pointer-move** updates an engine-transient preview rect (via- * `stores.bboxPreview`) that the overlay renders — it never dispatches. Sizes- * and positions snap to the model grid (`stores.bboxGrid`); hold **alt** to- * bypass model-grid snapping. Bypassed movement and resize still stay aligned- * to whole document pixels. While moving, **shift** constrains the frame to the- * dominant horizontal or vertical axis. Corner/edge resize preserves the- * aspect ratio when the lock is active (`stores.bboxOptions`); **shift**- * toggles the constraint on for an unlocked frame (a locked ratio stays- * locked). **Ctrl** (⌘ on macOS) mirrors- * the resize across the frame's center, so the opposite edge moves too and the- * center holds; it composes with both snapping and the aspect constraint.- * Modifiers are sampled per pointer sample, so a mid-drag press takes effect on- * the next pointer move.- * - **Commit** (pointer-up after a real change): exactly one `commitStructural`- * with the new/old bbox (`setCanvasBbox`, undoable). A zero-delta gesture- * commits nothing.- * - **Cancel** (Esc / pointercancel): drops the preview, no dispatch.- *- * Zero React, zero import-time side effects.+ * Bbox drags preview without dispatch. Handles resize, interior moves and outside is inert. Alt bypasses grid+ * while retaining integer pixels; Shift constrains movement/aspect, Ctrl/Command resizes symmetrically. Read+ * modifiers per sample. Release commits one changed bbox with undo; cancellation and zero change commit nothing.*/import type { Rect, Vec2 } from '@workbench/canvas-engine/types';@@ -38,10 +15,6 @@ import { type BboxTarget, bboxEquals, bboxTargetAt, moveBbox, resizeBbox, roundB/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */const PRIMARY_BUTTON = 1;-/**- * The CSS cursor for each bbox target: axis-aware resize arrows on the handles- * (opposite corners/edges share a cursor) and `move` inside the frame.- */const CURSOR_FOR_TARGET: Record<BboxTarget, string> = {e: 'ew-resize',move: 'move',@@ -126,8 +99,6 @@ const nextBboxFor = (/** Creates a fresh bbox tool with its own gesture state. */export const createBboxTool = (): Tool => {let state: GestureState | null = null;- // The bbox target under the pointer while idle (no gesture), driving the hover- // resize/move cursor. `null` = the pointer is off the frame.let hoverTarget: BboxTarget | null = null;const clearPreview = (ctx: ToolContext): void => {@@ -136,8 +107,7 @@ export const createBboxTool = (): Tool => {};return {- // During a drag the grabbed target's cursor holds; while idle the hovered- // handle/interior wins; off the frame it falls back to the default arrow.+ // Hold the grabbed cursor during drag; otherwise use hovered handle/interior or default arrow.cursor: () => {const target = state?.target ?? hoverTarget;return target ? CURSOR_FOR_TARGET[target] : 'default';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/brushTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/brushTool.tsindex 37fb7cfb3a..79a179f21d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/brushTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/brushTool.ts@@ -1,14 +1,3 @@-/**- * The brush tool: paints variable-width, pressure-sensitive strokes in the brush- * color into the target paint layer's cache surface. It is a thin binding over- * {@link createPaintTool} that sources its size/color/opacity/pressure from the- * engine's `brushOptions` store; all gesture and pixel logic lives in the shared- * paint tool and {@link createStrokeSession}.- *- * Each engine builds its own instance so gesture state is per-engine. Zero React,- * zero import-time side effects.- */-import { PRESSURE_THINNING } from '@workbench/canvas-engine/tools/paintConstants';import { createPaintTool } from '@workbench/canvas-engine/tools/paintTool';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.tsindex 016588a503..ec48fe3505 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts@@ -1,15 +1,6 @@/**- * The color-picker tool: while held down (usually via the alt-hold temp-tool- * switch the pointer pipeline already drives — see `input/pointerPipeline.ts`),- * it samples the composited document color under the cursor and hands it to- * `resolveColorSample` — in the app that lands in the active- * foreground/background target, so releasing alt drops the user right back- * into painting with the picked color. Sampling reads the layer cache directly- * through {@link sampleDocumentColor} — this tool never dispatches and never- * touches pixels.- *- * Each engine builds its own instance so cursor-ring state is per-engine.- * Zero React, zero import-time side effects.+ * Samples composited cached color while pressed and routes it to the active color target. Alt-hold restoration+ * returns to the prior tool; the picker neither dispatches nor edits pixels. State is per engine.*/import type { PointerInput } from '@workbench/canvas-engine/types';@@ -31,11 +22,7 @@ const updateCursorRing = (ctx: ToolContext, input: PointerInput): void => {ctx.invalidate({ overlay: true });};-/**- * Samples the composited color under `input` and offers it through- * `resolveColorSample` (one-shot claim, then the workbench router). The brush- * color option is only the engine-standalone fallback.- */+/** Offers sampled color to the one-shot claim then workbench router; standalone fallback updates brush color. */const pickColorAt = (ctx: ToolContext, input: PointerInput): void => {const doc = ctx.getDocument();if (!doc) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/eraserTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/eraserTool.tsindex 50078c6bbb..ab23840356 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/eraserTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/eraserTool.ts@@ -1,12 +1,6 @@/**- * The eraser tool: clears pixels along a stroke by compositing the same freehand- * shape as the brush with `destination-out` into the target paint layer's cache.- * A thin binding over {@link createPaintTool} sourcing size/opacity from the- * engine's `eraserOptions` store; the eraser is pressure-insensitive (thinning 0)- * and has no color (the shape alone drives the erase).- *- * Each engine builds its own instance so gesture state is per-engine. Zero React,- * zero import-time side effects.+ * Eraser binds shared paint gestures to destination-out with eraser size/opacity, no color and pressure thinning+ * zero. Gesture state is per engine.*/import { createPaintTool } from '@workbench/canvas-engine/tools/paintTool';@@ -21,8 +15,6 @@ export const createEraserTool = (): Tool =>id: 'eraser',hardness: (ctx) => ctx.stores.eraserOptions.get().hardness,opacity: (ctx) => ctx.stores.eraserOptions.get().opacity,- // Upstream keeps eraser pressure width-only too; a pressure-faded erase reads as a- // failed erase rather than a soft one.pressureOpacity: () => false,size: (ctx) => ctx.stores.eraserOptions.get().size,thinning: () => 0,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.tsindex 615d2379fe..1a41541267 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts@@ -1,27 +1,8 @@/**- * The gradient tool: drag to place a gradient. A linear ramp runs from the- * press point (stop 0) to the release point (stop 1); a radial one is centered- * on the press point with the drag length as its radius.- *- * Interaction contract (CANVAS_PLAN Phase 6.1):- * - **Pointer-down** (primary button) starts a gesture at the press point.- * - **Pointer-move** (past a small threshold) updates a transient overlay- * preview (`stores.gradientPreview`, the drag vector) — it never dispatches.- * - **Commit** (pointer-up after a real drag): exactly ONE commit.- * - A gradient layer is selected (unlocked + visible) → one `commitStructural`- * with `updateCanvasLayerSource` (new angle/center/span; kind + stops and- * the extent preserved). The drag is read in the layer's local space, so a- * moved/rotated/scaled gradient still lands where the pointer went.- * - Otherwise → create a new bbox-sized gradient layer (placement from the- * drag, kind + stops from the tool options, extent = the generation frame)- * via `addCanvasLayer`.- * - A selected gradient layer that is locked/hidden is a no-op (don't silently- * spawn a new layer over it), mirroring the paint tool's locked-target rule.- * - **Cancel** (Esc / pointercancel): drops the preview, no dispatch.- *- * The selection mask does NOT constrain gradient layers (parametric, not pixels).- *- * Zero React, zero import-time side effects.+ * Gradient drag defines linear start/end or radial center/radius. Editable selected gradients update placement in+ * layer-local space while preserving kind/stops/extent; locked or hidden gradients refuse. Otherwise create a+ * bbox-sized gradient from options. Preview/cancel never dispatch; one real drag makes one commit. Selection masks+ * do not clip parametric gradients.*/import type {@@ -181,9 +162,7 @@ export const createGradientTool = (): Tool => {return;}- // Create a new bbox-sized gradient layer: the extent is the bbox size,- // positioned at the bbox origin via the layer transform, so the drag maps- // to layer space by that offset alone.+ // New gradients use bbox size and origin; subtract that origin to map drag coordinates locally.const options = ctx.stores.gradientOptions.get();// The built-in FG→BG preset resolves the pair now; custom stops are// explicit and independent of later pair edits.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gridSnap.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gridSnap.tsindex 1cc144a511..09566a5ebe 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gridSnap.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gridSnap.ts@@ -1,29 +1,13 @@/**- * The grid-snapping gate for the tools that position LAYERS (move, transform).- *- * The canvas has exactly one grid: `stores.bboxGrid`, the model grid that the bbox- * tool snaps to and that `overlayRenderer` actually paints. Layer positions snap to- * that same grid, so a layer lands on the lines the user can see — there is no- * second, invisible positional grid (legacy's 64/8 pair does not apply here; its- * drawn grid was decoupled from the bbox grid).- *- * The math itself lives in `math/snapping` (`snapToGrid`, `snapMovedPoint`), which- * stays pure and store-free; this module only answers "which grid, right now".- *- * Zero React, zero import-time side effects.+ * Layer positioning uses the same model grid the bbox tool and overlay show. Pure snapping math remains in+ * math/snapping; this module resolves current settings.*/import type { ToolContext } from './tool';/**- * The grid layer positions should snap to right now, or `0` for no snap —- * `snapToGrid` treats `grid <= 0` as "leave the value alone", so callers never- * need a second boolean.- *- * `bypass` is the per-gesture escape hatch (alt, matching the bbox tool). Alt- * reaches the tool rather than switching to the color picker because- * `pointerPipeline.beginTempTool` refuses to start a temp-tool hold while a- * gesture is active — the same mechanism the bbox tool's alt bypass relies on.+ * Returns active grid or zero to disable snapping. Alt bypass reaches active gestures because temporary picker+ * switching is suppressed mid-gesture.*/export const positionGrid = (ctx: ToolContext, bypass: boolean): number =>!bypass && ctx.stores.snapToGrid.get() ? ctx.stores.bboxGrid.get() : 0;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.tsindex f2f44b4721..247af3b32b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts@@ -32,8 +32,7 @@ const createHarness = () => {invalidate: vi.fn(),stores,updateCursor: vi.fn(),- // Identity viewport: document and screen coordinates coincide, so the- // polygon's close-on-first-vertex hit test is expressed in the same numbers.+ // Identity viewport makes document coordinates valid for the screen-space polygon close test.viewport: { documentToScreen: (p: { x: number; y: number }) => p },} as unknown as ToolContext;return { commits, ctx, dispatched, stores };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.tsindex 525632962a..05bbc8429f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts@@ -1,30 +1,8 @@/**- * The lasso tool: freehand and polygonal pixel-selection.- *- * Both shapes commit the same thing — a closed polygon through- * {@link ToolContext.commitSelection}, with the boolean op resolved by- * {@link selectionOpFor} (shift = add, alt = subtract, shift+alt = intersect;- * with none held, the persistent op mode from `lassoOptions`). Only the way the- * points are gathered differs, so they share one tool rather than two:- *- * - **freehand** (`shape: 'freehand'`) — a primary-button DRAG accumulates- * document-space points, coalesced by the pipeline then distance-decimated- * here like the brush thins its input. Pointer-up closes and commits.- * - **polygon** (`shape: 'polygon'`) — a click-to-place-vertex SESSION spanning- * many clicks. Each press appends a vertex; a rubber-band segment tracks the- * cursor. The session closes and commits on a double-click, on Enter, or on a- * click landing within the shared polyline close radius of the first- * vertex. Escape drops it.- *- * A live dashed preview of the in-progress path is published to the engine's- * `lassoPreview` store (a transient channel — no dispatch, no reducer traffic).- * The polygon session survives a temporary modifier-hold tool switch (space →- * view, so the user can pan mid-polygon), the same way the transform session- * does; a REAL tool switch drops it.- *- * Selection edits are transient interaction state: they are NOT dispatches and- * NOT recorded on the engine's undo history (legacy parity — selection changes- * aren't undoable). Zero React, zero import-time side effects.+ * Freehand lasso gathers decimated drag points; polygon lasso spans clicks and closes on double-click, Enter or+ * first-vertex proximity. Both commit through `commitSelection` with shared modifier/persistent-op resolution.+ * Previews never dispatch. Temporary tool switches preserve polygon sessions; real switches cancel them. Selection+ * history is owned by the engine wrapper.*/import type { Vec2 } from '@workbench/canvas-engine/types';@@ -130,9 +108,8 @@ export const createLassoTool = (): Tool => {usesAltKey: true,onDeactivate: (ctx, opts) => {if (opts?.temporary) {- // A modifier-hold switch (space → view to pan mid-polygon) must not- // discard the session; the pipeline suppresses temp switches mid-drag,- // so a freehand gesture cannot be interrupted here either.+ // Temporary switches preserve polygon sessions for panning; mid-drag switches are already blocked by the+ // pipeline.return;}reset();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.tsindex a827d43952..d06f8be2ac 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.ts@@ -1,30 +1,7 @@/**- * The marquee tool: rectangular and elliptical pixel-selection by drag.- *- * One tool covers both shapes, switched by `marqueeOptions.kind` — they share- * every part of the gesture, and splitting them would double the entry in the- * `ToolId` union, the tool strip, and the options bar for one differing line.- * This mirrors `ShapeToolOptions.kind`.- *- * Interaction contract:- * - **Pointer-down** (primary button) anchors the drag.- * - **Pointer-move** (past a small threshold) publishes a live outline to- * `stores.marqueePreview` — it never dispatches and never touches the mask.- * **shift** constrains to a square/circle; **alt** draws from the press point- * as the CENTRE rather than a corner. Both compose.- * - **Commit** (pointer-up after a real drag): one `ctx.commitSelection` with- * the shape's closed path and the boolean op resolved from the modifiers, or- * the persistent op mode when none are held — the same resolution the lasso- * uses (`selectionOpFor`), so the whole mask/boolean pipeline is reused- * unchanged. A degenerate (sub-pixel) drag commits nothing.- * - **Cancel** (Esc / pointercancel): drops the preview, no commit.- *- * Note the modifier overlap: shift/alt pick the boolean op AND shape the rect.- * That is deliberate and matches Photoshop — alt-dragging a marquee subtracts a- * region drawn from its centre.- *- * Selection edits are transient interaction state: not dispatches, not undoable.- * Zero React, zero import-time side effects.+ * Rect/ellipse marquee previews do not change the mask. Shift constrains aspect; Alt draws from center. On release+ * those same modifiers choose the shared boolean op, intentionally composing shape and operation.+ * Degenerate/cancelled drags do not commit; engine selection history records accepted changes.*/import type { Rect, Vec2 } from '@workbench/canvas-engine/types';@@ -72,11 +49,7 @@ const constrainedDelta = (start: Vec2, end: Vec2, square: boolean): Vec2 => {return { x: (dx < 0 ? -1 : 1) * side, y: (dy < 0 ? -1 : 1) * side };};-/**- * The integer, normalized document rect for a marquee drag from `start` to- * `end`. With `fromCenter` the press point is the centre, so the constrained- * delta is mirrored through it — giving a rect twice the drag extent.- */+/** Normalized integer marquee bounds; centered mode mirrors the constrained delta around the press point. */export const marqueeRect = (start: Vec2, end: Vec2, constraints: MarqueeConstraints): Rect => {const delta = constrainedDelta(start, end, constraints.square);const a = constraints.fromCenter ? { x: start.x - delta.x, y: start.y - delta.y } : start;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.tsindex f2b27b6fe8..99abee60a5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts@@ -251,8 +251,7 @@ describe('live cache rect (freshly-painted, not-yet-flushed content)', () => {it('unions the live rect with persisted content (both contribute to the hit area)', () => {const layer = paintLayer('p', { width: 10, height: 10 }); // persisted content [0,0,10,10]- const liveRect = { height: 10, width: 10, x: 40, y: 40 }; // grown region off to the side- // A point only inside the grown live region is now hit-testable.+ const liveRect = { height: 10, width: 10, x: 40, y: 40 };expect(hitTestLayer(layer, doc([layer]), { x: 45, y: 45 }, liveRect)).toBe(true);// The original persisted region is still hit-testable.expect(hitTestLayer(layer, doc([layer]), { x: 5, y: 5 }, liveRect)).toBe(true);@@ -261,11 +260,8 @@ describe('live cache rect (freshly-painted, not-yet-flushed content)', () => {describe('a layer erased to nothing behaves exactly like a brand-new one', () => {/**- * The reported bug: an erased layer kept a full-size transparent bitmap, so it still- * drew a movable, transformable outline around nothing. The paint-cache trim now- * clears it to `{ bitmap: null }` — a freshly-added layer's source — so every- * affordance derived from `hittableLayerRect` disappears. Pinning that equivalence- * is why the fix needs no change to the overlay or the tools.+ * Trimmed empty layers become null-bitmap sources, so bounds-derived move/transform affordances disappear like+ * those of fresh layers.*/it('reports no hittable extent once its bitmap has been cleared', () => {const erased = paintLayer('erased');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.tsindex 39f0610f82..3f1a780844 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts@@ -1,27 +1,7 @@/**- * Pure geometry for the move tool: layer hit-testing and outline corners.- *- * A layer's raster cache holds unscaled pixels in the layer's LOCAL space; the- * compositor draws it through the layer transform (translate·rotate·scale). To- * hit-test a document-space point we invert that transform and check the point- * against the layer's native `[0,w]×[0,h]` rect — so rotation and scale are- * handled exactly, not via an axis-aligned approximation.- *- * Every renderable layer is hit-testable — image by its native size, paint by- * its content rect (bitmap dims at the persisted offset), the parametric sources- * (shape/gradient/text) by the same content rect the compositor/cache use- * (CANVAS_PLAN Phase 5: "param for parametric"), and MASK layers (inpaint /- * regional) by their alpha bitmap's content rect (legacy allows moving masks).- * An EMPTY layer (a brand-new / cleared paint or mask layer with no pixels)- * returns `null`/`false` rather than throwing, so callers can probe a mixed- * stack safely.- *- * There is deliberately no "top-most layer under the point" query here: the- * layers panel is the sole authority on which layer is active, so no tool picks- * a target by hit-testing the stack. These helpers answer "where is THIS layer",- * which is what the move outline and the transform frame need.- *- * Zero React, zero import-time side effects.+ * Transform document points into layer-local content bounds for exact rotation/scale hit tests. All renderable+ * source types and mask alpha use the same bounds; empty content returns null/false. Helpers locate a specified+ * layer, never choose a stack target instead of panel selection.*/import type {@@ -38,13 +18,8 @@ import { isEmpty, union } from '@workbench/canvas-engine/math/rect';type LayerTransform = CanvasLayerBaseContract['transform'];/**- * A hit-testable layer's content rectangle in its LOCAL (untransformed) space —- * including its (possibly off-zero) origin for content-sized paint/mask layers —- * or `null` for a layer with no rasterizable content or an EMPTY layer (no- * pixels). Mask layers hit-test by their alpha bitmap's content rect, so the move- * tool can grab a painted mask (matching legacy). Every source (image/paint/- * shape/gradient/text) and mask reuses {@link getSourceContentRect} — the exact- * rect the cache/compositor render.+ * Local content bounds include off-origin paint/mask pixels and share {@link getSourceContentRect}. Empty or+ * unsupported layers return null.*/export const hittableLayerRect = (layer: CanvasLayerContract,@@ -55,11 +30,7 @@ export const hittableLayerRect = (return null;}const content = getSourceContentRect(layer, doc);- // Union the live cache rect (when present): a stroke painted moments ago lives- // in the cache but not yet in the persisted contract (the bitmap flush is- // debounced), so content alone would leave freshly-painted pixels ungrabbable —- // and content is EMPTY for a brand-new paint layer whose first stroke hasn't- // flushed. Mirrors `invertMask`'s live-cache union.+ // Union live cache bounds so unflushed first strokes and newly extended content remain grabbable.const rect = liveRect && !isEmpty(liveRect) ? (isEmpty(content) ? liveRect : union(content, liveRect)) : content;if (rect.width <= 0 || rect.height <= 0) {return null;@@ -67,11 +38,6 @@ export const hittableLayerRect = (return rect;};-/**- * The native (unscaled) local pixel size of a hit-testable layer, or `null` when- * not hit-testable. A thin wrapper over {@link hittableLayerRect} for callers- * that only need eligibility / dimensions (not the origin).- */export const hittableLayerSize = (layer: CanvasLayerContract,doc: CanvasDocumentContractV3@@ -85,8 +51,8 @@ export const layerMatrix = (transform: LayerTransform) =>fromTRS({ x: transform.x, y: transform.y }, transform.rotation, transform.scaleX, transform.scaleY);/**- * True when `point` (document space) falls inside `layer`'s rendered bounds.- * @internal No production caller today; kept for a future stack hit-test consumer.+ * Tests a document-space point against rendered layer bounds.+ * @internal No production caller.*/export const hitTestLayer = (layer: CanvasLayerContract,@@ -107,11 +73,8 @@ export const hitTestLayer = (};/**- * The four document-space corners of a layer's rendered rectangle (for the move- * overlay outline), or `null` when the layer has no hit-testable bounds.- * `override` shifts/scales/rotates the rect for a live drag preview without- * mutating the layer (fields absent from the override fall back to the committed- * transform; the move tool passes only `x`/`y`).+ * Returns transformed content corners or null. Partial overrides preview move/scale/rotation without mutation;+ * omitted fields retain committed values.*/export const layerOutlineCorners = (layer: CanvasLayerContract,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.tsindex 1930ae92bf..c365ce586c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts@@ -103,11 +103,7 @@ interface HarnessOptions {canLift?: boolean;/** A float that is already in flight before the gesture starts. */existingFloat?: boolean;- /**- * Grid-snapping state. Defaults to OFF so the drag/commit-contract tests below- * assert raw pointer deltas; the snapping tests opt in explicitly. (The product- * default is on — see `createEngineStores`.)- */+ /** Tests default snapping off to isolate raw deltas; snapping cases opt in. Product default is on. */snapToGrid?: boolean;/** The grid snapping uses when enabled; defaults to the engine's own default. */bboxGrid?: number;@@ -151,8 +147,6 @@ const createHarness = (doc: CanvasDocumentContractV3, options: HarnessOptions =getFloatingSelection: () => float.current,invalidate: vi.fn(),isPointInSelection: () => options.selectionContainsPoint === true,- // A real (empty) layer cache so the tool's cache seam resolves; no test here- // relies on cached content, so entries stay absent.layers: createLayerCacheStore(createTestStubRasterBackend()),liftFloatingSelection: (layerId) => {if (options.canLift === false) {@@ -221,8 +215,7 @@ describe('move tool: the layers panel owns selection', () => {});it('does not steal the selection when pressing another layer above the selected one', () => {- // The exact complaint this contract exists to fix: 'bottom' is selected in- // the panel and 'top' covers the press point.+ // The panel selects bottom while top covers the press point.const doc = makeDoc([imageLayer('top', { width: 50, height: 50 }), imageLayer('bottom', { width: 50, height: 50 })],'bottom'@@ -320,8 +313,6 @@ describe('move tool: drag', () => {});it('drags a parametric shape layer, committing one structural transform', () => {- // Regression: shape/gradient/text layers were not hit-testable, so the move- // tool skipped them (Phase 5 "param for parametric" hit-testing).const doc = makeDoc([shapeLayer('s', { x: 0, y: 0, width: 50, height: 50 })], 's');const h = createHarness(doc);const tool = createMoveTool();@@ -339,8 +330,7 @@ describe('move tool: drag', () => {});it('moves the SELECTED layer even when another layer covers the press point', () => {- // 'top' is composited over the press point, but 'bottom' is what the panel- // selected — the panel wins, and no selection dispatch is emitted.+ // Panel selection wins over visible top pixels, without a selection dispatch.const doc = makeDoc([imageLayer('top', { width: 50, height: 50 }), imageLayer('bottom', { width: 50, height: 50 })],'bottom'diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.tsindex 3e36d99edb..80504deddc 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts@@ -1,38 +1,11 @@/**- * The move tool: drag to move the SELECTED layer group, or the selected PIXELS.+ * Move targets panel selection, never stack hit tests. Dragging inside selection, or an existing float, moves+ * pixels across multiple drags until commit/cancel; otherwise move eligible selected layers with a primary-layer+ * fallback.*- * Interaction contract:- * - **The layers panel is the sole authority on which layer is active.** The move- * tool never hit-tests the stack to pick a target and never dispatches- * `setCanvasSelectedLayer`. Clicking canvas pixels that belong to some other- * layer does not steal the selection, and clicking empty space does not clear- * it — an editor where the pointer silently re-targets is the behaviour this- * contract exists to prevent.- * - **Click** (press+release under the drag threshold): a no-op.- * - **Drag inside a live selection** — or with a float already in flight —- * moves the selected PIXELS: the first such drag cuts them out of the selected- * layer into a floating selection that follows the pointer, leaving a hole.- * The float stays live across further drags until it is committed (Enter,- * deselect, tool switch — one undo entry for the whole move) or cancelled- * (Escape). This is the Photoshop feel: ants present and the press inside them- * moves pixels; otherwise the press moves the layer.- * - **Drag anywhere else**: moves every panel-selected layer together, when all- * are enabled and unlocked. The document's `selectedLayerId` remains the- * primary target and a stale selection falls back to that layer alone.- * Pointer-move only sets transient transform overrides (live preview) — it- * never dispatches.- * - **`shift`** constrains motion to the dominant axis, for both modes.- * - **Snap**: with the snap-to-grid setting on, a LAYER drag lands its origin on- * the model grid (the one the overlay draws); hold **alt** to bypass. Moving- * PIXELS never snaps — a float's transform is layer-local, so document-space- * grid math would skew it on a rotated or scaled layer.- * - **Commit** (pointer-up after a real layer move): one `commitStructural` with- * the new/old transform x/y. A zero-delta drag commits nothing. Moving a float- * commits nothing here — the float's own commit does that later.- * - **Cancel** (Esc / pointercancel): drops the layer override or reverts the- * float to where this drag started. Neither dispatches.- *- * Zero React, zero import-time side effects.+ * Shift locks the dominant axis. Layer movement uses the visible model grid unless Alt bypasses; local-space+ * floats never snap. Preview only during drag; changed layer moves commit once, float history waits for its later+ * bake. Cancel restores the drag start; clicks/zero movement do nothing.*/import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';@@ -94,10 +67,7 @@ export const createMoveTool = (): Tool => {state = null;};- /**- * The drag target is the document's selected layer, and nothing else — the- * press point plays no part in choosing it.- */+ /** Target comes solely from document selection, regardless of press location. */const selectedDraggableLayers = (ctx: ToolContext): { layers: readonly CanvasLayerContract[]; primaryId: string | null } => {@@ -161,11 +131,7 @@ export const createMoveTool = (): Tool => {input.modifiers.shift);- /**- * Where a layer drag puts the layer's origin, snapped to the grid unless the- * setting is off or alt bypasses it. Shared by the live preview and the commit- * so the layer lands exactly where the drag showed it.- */+ /** Share snapped layer-origin calculation between preview and commit; Alt or settings may bypass. */const nextLayerPosition = (ctx: ToolContext,origin: { x: number; y: number },@@ -208,8 +174,7 @@ export const createMoveTool = (): Tool => {endGesture();},onKeyCommand: (ctx, command) => {- // Enter banks a float in place. Escape's abandon runs on the engine's own- // ladder (it must work whichever tool is active), so it is not handled here.+ // Enter commits the float; engine Escape abandons it regardless of active tool.if (command === 'apply' && !state) {ctx.commitFloatingSelection?.();}@@ -265,8 +230,7 @@ export const createMoveTool = (): Tool => {return;}if (current.mode.kind === 'float') {- // The float keeps the drag; it bakes later, as one entry for the whole- // move however many drags it took. Floats never snap — see the header.+ // Retain float movement for one eventual history entry across drags; floats never snap.applyDelta(ctx, current, input);return;}@@ -276,8 +240,7 @@ export const createMoveTool = (): Tool => {const effectiveDelta = { x: primaryNext.x - primary.origin.x, y: primaryNext.y - primary.origin.y };if (effectiveDelta.x === 0 && effectiveDelta.y === 0) {- // Nothing moved — either a zero-delta drag, or a drag whose snapped- // result landed back on the origin. Drop the preview, commit nothing.+ // Drop zero-result previews, including movement snapped back to origin, without committing.for (const target of current.mode.targets) {ctx.setLayerTransformOverride(target.id, null);}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintConstants.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintConstants.tsindex 61e34c55a2..38377dded9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintConstants.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintConstants.ts@@ -1,9 +1,3 @@-/**- * Shared brush/eraser painting constants and the size-step math both the- * ctrl+wheel path (`input/wheel.ts`) and the `[`/`]` hotkeys drive through the- * same helper. Zero React, zero import-time side effects.- */-import { MAX_BRUSH_SIZE, MIN_BRUSH_SIZE } from '@workbench/canvas-engine/engineStores';/** Freehand `thinning` applied when brush pressure sensitivity is on. */@@ -16,9 +10,5 @@ export const SIZE_STEP_FACTOR = 0.1;export const clampBrushSize = (value: number): number =>Math.max(MIN_BRUSH_SIZE, Math.min(MAX_BRUSH_SIZE, Math.round(value * 100) / 100));-/**- * Steps a brush/eraser diameter by one notch: `+1` grows by `SIZE_STEP_FACTOR`,- * `-1` shrinks by it, clamped to the valid size range.- */export const stepBrushSize = (size: number, direction: 1 | -1): number =>clampBrushSize(size * (1 + direction * SIZE_STEP_FACTOR));diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.tsindex b5a5a5ed47..bd40ebb19b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts@@ -212,9 +212,7 @@ describe('brush tool: stroke into an existing paint layer', () => {expect(event.tool).toBe('brush');expect(event.layerId).toBe('paint1');- // Dirty rect is integer and non-empty. Content-sized: it is the stroke's TRUE- // bounds (no document clamp), so it can extend past the document edges — a- // paint layer grows with its strokes.+ // Dirty bounds remain integer and nonempty beyond document edges as paint content grows.const { dirtyRect } = event;expect(Number.isInteger(dirtyRect.x)).toBe(true);expect(Number.isInteger(dirtyRect.width)).toBe(true);@@ -547,8 +545,7 @@ describe('mask strokes are forced opaque', () => {it('composites a mask stroke at globalAlpha 1 even when the brush opacity is 0.5', () => {const doc = makeDoc([inpaintMaskLayer('mask1')], 'mask1');const h = createHarness(doc);- // A half-opacity brush: on a raster layer this would land alpha ~128, but a- // mask is an all-or-nothing alpha stencil and must be forced fully opaque.+ // Masks force full-alpha stencils even when brush opacity is one half.h.ctx.stores.brushOptions.set({ ...h.ctx.stores.brushOptions.get(), opacity: 0.5 });const brush = createBrushTool();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.tsindex 6d329bb983..6ed93b808e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts@@ -1,17 +1,7 @@/**- * The shared machinery behind the brush and eraser tools. Both are the same- * gesture — resolve a paintable target layer on pointer-down (auto-creating a- * fresh paint layer when the selection can't be painted into), drive a- * {@link StrokeSession} across the move batches, and commit or cancel on release —- * differing only in their blend (`source-over` fill vs `destination-out`) and in- * which options store they read. `createBrushTool` / `createEraserTool`- * (in `brushTool.ts` / `eraserTool.ts`) are thin wrappers over- * {@link createPaintTool}.- *- * This is the ONE place a painting tool is allowed to dispatch, and only ever- * the single gesture-start `addCanvasLayer`. Pointer-move never dispatches.- *- * Zero React, zero import-time side effects.+ * Shared brush/eraser gesture resolves or creates a target, drives a StrokeSession and commits/cancels. Only+ * gesture-start layer creation dispatches here; moves never dispatch. Fill/erase differ by blend and option+ * source.*/import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';@@ -59,11 +49,7 @@ interface PaintTarget {cancel(): void;/** When the gesture auto-created its layer, the created contract + its anchor (for history). */createdLayer?: { layer: CanvasLayerContract; anchor: CanvasNodeInsertionAnchor };- /**- * Overrides the brush colour for this gesture (mask targets paint an opaque- * stencil — the stored RGB is irrelevant, the compositor colorizes by alpha).- * Absent ⇒ the tool's own colour.- */+ /** Optional gesture color override; mask RGB is irrelevant because compositing colorizes alpha. */color?: string;/*** True when the target is a transparency-LOCKED raster paint layer. The brush@@ -72,18 +58,11 @@ interface PaintTarget {*/transparencyLocked?: boolean;/**- * True for mask targets (inpaint / regional guidance). A mask is an opaque- * alpha stencil, so the stroke is forced to opacity 1 regardless of the brush's- * opacity slider — a 50%-opacity brush would otherwise land alpha ~128 and- * silently attenuate the mask (a ~50% denoise, invisible in the tinted overlay).+ * Masks force opacity one; partial brush alpha would silently attenuate generation coverage despite the tinted+ * preview.*/forceOpaque?: boolean;- /**- * The target layer's committed transform. The session paints layer-local- * pixels through its inverse so the stroke lands under the cursor even on a- * moved, scaled or rotated layer. Absent ⇒ identity (a freshly auto-created- * layer).- */+ /** Invert the committed layer transform to paint under the cursor; absence is identity for new layers. */transform?: CanvasLayerContract['transform'];}@@ -97,8 +76,7 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetconst selected = leaf?.layer;if (leaf && selected && selected.type === 'raster' && selected.source.type === 'paint') {- // The selection is a paint layer: paint into it, unless it's locked/disabled- // (a no-op — don't silently spawn a new layer over the user's locked target).+ // Locked/disabled paint targets refuse rather than silently creating another layer.if (!isLeafPaintable(leaf)) {return null;}@@ -124,9 +102,8 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget}if (leaf && selected?.type === 'raster' && selected.source.type === 'image' && tool === 'eraser') {- // Erasing is a destructive pixel edit, so materialize the image into an- // undoable paint layer in place. A locked/disabled/unready image refuses the- // transaction; never spawn a new layer over the selected image.+ // Erase materializes image pixels as an undoable paint layer in place; locked, disabled or unready images+ // refuse without spawning.if (!isLeafPaintable(leaf) || isLayerTransparencyLocked(selected)) {return null;}@@ -145,10 +122,8 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget}if (leaf && selected && isMaskLayer(selected)) {- // The selection is a mask: paint the stroke into its alpha stencil cache- // (brush adds coverage, eraser removes — the shared stroke session handles- // both via its composite op). Never auto-create a paint layer here. A- // locked/disabled mask refuses the stroke (a no-op, not a spawn).+ // Paint mask alpha directly, adding/removing coverage. Locked/disabled masks refuse and never auto-create+ // paint layers.if (!isLeafPaintable(leaf)) {return null;}@@ -182,9 +157,7 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget};}- // Selection is an image/other raster, another layer type, or nothing: create a- // fresh paint layer (inserted on top and selected by the reducer) and paint- // into it. This is the single allowed gesture-start dispatch.+ // Other eligible selections create a selected paint layer at the top via the sole gesture-start dispatch.const layerId = ctx.createLayerId();const previousSelectedLayerId = doc.selectedLayerId;const layer: CanvasRasterLayerContractV2 = {@@ -201,17 +174,12 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetconst anchor = ctx.captureInsertionAnchor('raster', doc.selectedLayerId);ctx.dispatch({ anchor, layer, type: 'addCanvasLayer' });- // A brand-new empty paint layer: create a zero-rect cache marked fresh so the- // async rasterize pass doesn't clobber the stroke mid-gesture. The first stroke- // grows it from empty to the stroke's content bounds.+ // Mark the new zero-rect cache fresh to fence async rasterization; the stroke grows its bounds.const entry = ctx.layers.getOrCreateRect(layerId, { height: 0, width: 0, x: 0, y: 0 });entry.stale = false;return {- // The dispatch above happens at pointer-DOWN, before any pixel exists, and sits- // outside history (the stroke's composed entry owns the create+paint pair), so it- // needs a real rollback like the control branch's. Reached whenever- // `strokeSession.commit()` returns null — every point clipped away by the- // generation frame or the selection — plus pointercancel and a mid-drag switch.+ // Gesture-start creation is outside history until a stroke commits. Roll it back for fully clipped strokes,+ // cancellation or mid-drag switching.cancel: () => {ctx.layers.delete(layerId);ctx.dispatch({ ids: [layerId], type: 'removeCanvasLayers' });@@ -283,8 +251,6 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {if (!resolvedTarget) {return;}- // Transparency lock: the eraser is refused (it would alter the locked alpha);- // the brush switches to `source-atop` so colour lands only on existing pixels.if (resolvedTarget.transparencyLocked && spec.id === 'eraser') {return;}@@ -304,9 +270,7 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {target = resolvedTarget;try {session = createStrokeSession({- // Resolve the selection clip ONCE per gesture: when a selection exists the- // stroke is masked to it; with none the field is null and the hot path is- // untouched (no per-point mask lookup).+ // Capture selection clipping once per gesture; no selection avoids per-point mask work.clipMask: ctx.getSelectionMask?.() ?? null,clipRect: ctx.getStrokeClipRect?.() ?? null,color: target.color ?? spec.color(ctx),@@ -318,8 +282,6 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {ctx,layerId: target.layerId,layerTransform,- // Mask strokes are forced opaque (an alpha stencil is all-or-nothing); a- // brush-opacity mask stroke would silently attenuate the denoise strength.opacity: target.forceOpaque ? 1 : spec.opacity(ctx),// A mask stroke is an all-or-nothing alpha stencil, so pressure must not thin it —// a partially-transparent mask would silently attenuate the denoise strength.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.tsindex 8e6d40dcea..94e3412f0b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.ts@@ -1,11 +1,6 @@/**- * A click-to-place polyline shared by the lasso's polygon mode and the shape- * tool's polygon kind: vertices accumulate across presses, a rubber band- * follows the cursor, and the shape closes on a double-click, on Enter, or on- * a press within a screen radius of the first vertex — which the overlay- * previews as an armed ring while the cursor hovers there.- *- * Zero React, zero import-time side effects.+ * Shared click-to-place polyline with cursor band. Close on double-click, Enter or first-vertex screen-radius hit;+ * preview that hit with a ring.*/import type { LassoPreview } from '@workbench/canvas-engine/engineStores';@@ -58,10 +53,6 @@ export const isOnFirstVertex = (ctx: ToolContext, session: PolylineSession, screreturn distance(ctx.viewport.documentToScreen(first), screenPoint) <= POLYLINE_CLOSE_HIT_PX;};-/**- * Handles a press after the first: closes when it double-clicks or lands on- * the first vertex, else places a vertex. Returns what happened.- */export const pressPolyline = (ctx: ToolContext, session: PolylineSession, input: PointerInput): 'close' | 'place' => {const isDoubleClick =input.timeStamp - session.lastPressAt <= POLYLINE_DOUBLE_CLICK_MS &&diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.tsindex 06f07d785e..7743833175 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts@@ -1,22 +1,8 @@/**- * The shape tool. The box kinds (rect / ellipse / triangle / star) drag out a- * rect; `polygon` places vertices click by click through the shared polyline- * session; `freehand` traces a drag and closes it. A finished shape lands- * either as pixels on the selected paint layer (one undoable stroke, clipped- * to the selection and the bbox like a brush stroke) or, when the target is- * `new` or the selection is not a paint layer, as its own parametric shape- * layer. A locked, disabled or not-yet-rasterized paint layer refuses the- * shape (a no-op, like the brush) rather than spawning a layer over it.- *- * Interaction contract:- * - **Pointer-move** updates a transient overlay preview (the drag rect, or the- * polyline through `stores.lassoPreview`) — it never dispatches. Hold- * **shift** to constrain a drag to a square/circle.- * - **Commit**: exactly one `commitStructural` (`addCanvasLayer`, undone by- * `removeCanvasLayers`) or one stroke event. A zero-area shape commits nothing.- * - **Cancel** (Esc / pointercancel): drops the preview, no dispatch.- *- * Zero React, zero import-time side effects.+ * Shapes use box drags, polygon clicks or closed freehand. Commit pixels to eligible selected paint with+ * selection/bbox clipping, otherwise create a parametric layer. Locked/disabled/unready paint refuses. Shift+ * constrains box aspect; previews/cancellation do not dispatch, and nonzero shapes produce one structural or+ * stroke commit.*/import type { CanvasLayerSourceContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';@@ -148,11 +134,8 @@ export const createShapeTool = (): Tool => {};/**- * Draws the shape as pixels onto the selected paint layer, as one stroke- * event: the layer cache grows to the shape's layer-local bounds (clamped to- * the selection and bbox clips, so growth never escapes them), the shape is- * drawn through the layer's inverse transform, then clipped to the selection- * mask and the bbox exactly as a brush stroke is.+ * One pixel-shape stroke grows local bounds within selection/bbox clips, draws through the layer inverse and+ * applies the same masks as brush painting.*/const commitPixels = (ctx: ToolContext, leaf: SemanticLeaf, placed: PlacedShape): PixelPlacement => {const layer = leaf.layer;@@ -193,10 +176,8 @@ export const createShapeTool = (): Tool => {const sy = dirtyRect.y - entry.rect.y;const beforeImageData = surfaceCtx.getImageData(sx, sy, dirtyRect.width, dirtyRect.height);- // Draw into a scratch the size of the dirty rect (scratch origin = dirtyRect- // origin in layer space) so the clips and the transparency lock apply in- // one composite. Document → layer-local → scratch: the layer's inverse,- // then the scratch offset.+ // Draw into dirty-rect-local scratch so clipping and transparency lock apply in one composite; map through+ // layer inverse then scratch offset.const scratch = ctx.backend.createSurface(dirtyRect.width, dirtyRect.height);const draw = scratch.ctx;const { rect, source } = placed;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.tsindex 40dd62e563..f386d35534 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts@@ -16,10 +16,6 @@ const pointer = (x: number, y: number, pressure = 0.5): PointerInput => ({timeStamp: 0,});-/**- * Paints `path` through a session, delivering it in batches of `batchSize`, and- * returns the committed pixels plus the rect they cover.- */const paint = (path: PointerInput[],batchSize: number,@@ -64,11 +60,7 @@ const paint = (return { pixels: event.afterImageData.data, rect: event.dirtyRect };};-/**- * The largest per-channel difference attributable to premultiplied-alpha- * rounding. Structural errors (a gap, a seam, a double-composite) are one to two- * orders of magnitude above this.- */+/** Tolerance covers premultiplied-alpha rounding; gaps, seams and double composites exceed it substantially. */const ROUNDING_TOLERANCE = 6;const tapCoverage = (@@ -191,21 +183,9 @@ const sweep = (): PointerInput[] => {};describe('incremental compositing produces the same coverage as recompositing everything', () => {- // The session restores and composites only the band where the outline moved,- // and grows its "before" snapshot from the strips the region gains. If either- // bound were too tight the stroke would come out with gaps, seams or doubled- // opacity.- //- // The assertion is about COVERAGE, not bit-equality. Whether a given edge- // pixel's antialiasing was laid down on this frame or three frames ago can- // shift it by a subpixel, so a handful of boundary pixels legitimately differ- // from a single-batch paint. What must not differ is the interior: any gap,- // seam or double-composite shows up as an opaque pixel disagreeing by far more- // than a rounding step, which is what these bounds catch.- //- // Calibrated by deliberately shrinking the band: 10px still passes (the vertex- // diff carries that much natural slack at these sample rates), 30px fails all- // four cases.+ // Band updates and incremental before-snapshots must preserve interior coverage. Boundary antialiasing may+ // differ by subpixels across batches; interior gaps or compounded opacity may not. Deliberately shrinking the+ // band by 30px fails all four cases.const cases: { batchSize: number; label: string; opacity: number; size: number; thinning: number }[] = [{ batchSize: 1, label: 'one sample per batch, opaque', opacity: 1, size: 220, thinning: 0 },{ batchSize: 1, label: 'one sample per batch, semi-transparent', opacity: 0.4, size: 220, thinning: 0 },@@ -221,8 +201,7 @@ describe('incremental compositing produces the same coverage as recompositing evexpect(incremental.rect).toEqual(wholesale.rect);expect(incremental.pixels.length).toBe(wholesale.pixels.length);- // Interior = a pixel both paints agree is essentially opaque. A gap or a- // double-composite lands here; antialiasing never does.+ // Compare essentially opaque interior pixels to exclude antialiasing differences.let interiorDiffering = 0;let interiorWorst = 0;let edgeDiffering = 0;@@ -244,11 +223,7 @@ describe('incremental compositing produces the same coverage as recompositing ev}}const total = incremental.pixels.length / 4;- // Interior pixels may drift by a rounding step — compositing at an opacity- // rounds premultiplied channels, and which frame did it changes nothing- // else. What this rules out is structural error, which is nowhere near this- // scale: an unpainted gap reads as a 255 difference and a double-composite- // at opacity 0.4 as ~100.+ // Allow rounding-scale interior drift, not gaps or double-composite errors hundreds of channel steps larger.expect(interiorWorst).toBeLessThanOrEqual(ROUNDING_TOLERANCE);expect(interiorDiffering / total).toBeLessThan(0.001);// The antialiased boundary may land a subpixel differently, but only there.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.tsindex 2337d67582..f237edbea2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts@@ -101,11 +101,8 @@ describe('strokeSession: selection-constrained painting', () => {it('applies the selection clip on the scratch, not by changing the cache composite ops', () => {const withMask = runStroke({ withMask: true });const noMask = runStroke({ withMask: false });- // The clip is a `destination-in` on the SCRATCH; the layer-cache composite op- // sequence (source-over blit of the clipped stroke) is unchanged — the clip- // never adds a mask op to the cache itself. (The cache's content EXTENT can- // differ: without a selection the cache grows to the stroke's true bounds,- // while a selection bounds the growth to the mask — content-sized behavior.)+ // Apply destination-in only to scratch; cache compositing remains unchanged. Selection bounds may limit cache+ // growth.expect(compositeOps(withMask.cache)).toEqual(compositeOps(noMask.cache));expect(compositeOps(withMask.cache)).not.toContain('destination-in');});@@ -187,10 +184,7 @@ describe('strokeSession: bbox-clipped painting', () => {});it('still covers the whole stroke when the clip rect contains it', () => {- // The stroke spans (10,10)→(40,40) with a 20px brush, so its true content- // reaches [0,50] on both axes. A generous clip may trim the region's chunk- // PADDING back to the clip boundary — an internal cache extent — but must- // never trim painted content.+ // Clip may remove chunk padding but must retain actual 20px stroke coverage across [0,50] on both axes.const { event } = runClipped({ height: 200, width: 200, x: -50, y: -50 });const dirty = event!.dirtyRect;@@ -241,10 +235,7 @@ describe('strokeSession: content-sized cache growth', () => {session.addPoints([pointer(50, 60)]);const event = session.commit();- // The cache adopted the stroke's content bounds, snapped OUTWARD to the 64px- // growth-chunk grid — still content-sized (a couple of chunks), NOT an- // origin-anchored document-sized surface. A size-20 dab at (50,60) sits roughly- // at [40,60]×[50,70], which chunk-pads to a small chunk-aligned rect.+ // A dab near (50,60) grows to a small outward chunk-aligned rect, not a document-sized surface.expect(entry.rect.width).toBeGreaterThan(0);expect(entry.rect.height).toBeGreaterThan(0);// Chunk-aligned extent (origin and size are multiples of the 64px chunk).@@ -306,12 +297,7 @@ describe('strokeSession: content-sized cache growth', () => {const surface = entry.surface as StubRasterSurface;const resizeCount = (): number => surface.callLog.filter((e) => e.op === 'resize').length;- // Ten 10px batches extending the stroke 100px rightward within a single chunk- // row. Without chunk-padding, growToRect grows to the EXACT union every batch,- // so each batch reallocates + full-copies the cache (≈10 resizes). With the- // 64px chunk grid, successive small extensions land inside the padded extent,- // so the surface reallocates only when the stroke crosses a chunk boundary- // (~100 / 64 ≈ 2 times).+ // Ten small batches should allocate only at 64px chunk crossings, not on every exact-bound extension.const batches = 10;for (let i = 0; i < batches; i++) {session.addPoints([pointer(100 + i * 10, 100)]);@@ -320,8 +306,6 @@ describe('strokeSession: content-sized cache growth', () => {const resizes = resizeCount();expect(resizes).toBeLessThanOrEqual(2);- // Sanity: far fewer reallocations than batches — the unpadded behavior this- // regression guards would resize on nearly every batch.expect(resizes).toBeLessThan(batches);});});@@ -366,8 +350,7 @@ describe('strokeSession: cache version bump (live adjusted-surface invalidation)const v1 = entry.version;session.addPoints([pointer(40, 40)]);const v2 = entry.version;- // Each painted frame advances the version — a version-keyed adjusted surface- // would otherwise serve stale (pre-stroke) adjusted pixels mid-stroke.+ // Every painted frame must advance version so adjusted caches show live strokes.expect(v1).toBeGreaterThan(v0);expect(v2).toBeGreaterThan(v1);});@@ -426,9 +409,7 @@ describe('incremental "before" snapshot', () => {const { layers, session } = makeSession(100);drag(session, 3000, 50);const region = layers.get('L')!.rect;- // `growToRect` re-reads the surface when it reallocates (args are its own- // full extent from the origin); the session's own snapshot reads are the- // strips, and none of them may span the accumulated width.+ // Session readbacks must cover only newly added strips, never accumulated width.const stripReads = surfaceOf(layers).callLog.filter((entry) => entry.op === 'getImageData').filter((entry) => Number(entry.args[0]) !== 0 || Number(entry.args[1]) !== 0);@@ -441,8 +422,7 @@ describe('incremental "before" snapshot', () => {it('re-snapshots only when the region actually grows, not on every batch', () => {const { layers, session } = makeSession(100);- // Many batches inside one chunk: the region never changes, so the retained- // snapshot is reused and nothing is read back at all.+ // Batches within unchanged bounds reuse the before-snapshot without readback.session.addPoints([pointer(0, 0)]);const baseline = surfaceOf(layers).callLog.filter((e) => e.op === 'getImageData').length;for (let i = 0; i < 20; i++) {@@ -453,8 +433,7 @@ describe('incremental "before" snapshot', () => {});it('reallocates less often for a wide brush than a fixed 64px grid would', () => {- // The growth grid scales with the brush, so a 1200px brush crossing 4000px- // of travel reallocates on a ~300px pitch rather than every 64px.+ // Large brushes scale growth pitch: 1200px diameter uses roughly 300px chunks instead of 64px.const { layers, session } = makeSession(1200);drag(session, 4000, 100);const resizes = surfaceOf(layers).callLog.filter((entry) => entry.op === 'resize').length;@@ -515,8 +494,7 @@ describe('strokeSession: pressure-dependent opacity', () => {it('fills the stroke once at full alpha when pressure opacity is off', () => {const scratch = runPressureStroke(false, [0.25, 0.5, 1]);- // One fill for the whole outline: overlapping parts of the stroke union instead of- // compounding, which is the guarantee the single-composite design provides.+ // Fill the whole outline once so overlaps union without compounding opacity.expect(scratch.callLog.filter((e) => e.op === 'fill')).toHaveLength(1);expect(alphaValues(scratch).every((alpha) => alpha === 1)).toBe(true);});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.tsindex 1930e630b3..2aabccb9ab 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts@@ -1,40 +1,11 @@/**- * The per-gesture paint session shared by the brush and eraser tools.+ * Per-gesture brush/eraser sessions accumulate samples and draw one scratch silhouette, compositing at stroke+ * opacity without overlap darkening. Brush uses source-over or transparency-locked source-atop; erase uses+ * destination-out and is refused under transparency lock.*- * A session is created on pointer-down against a resolved target layer's cache- * surface and lives until commit (pointer-up) or cancel (Esc / pointercancel).- * It owns the hot path the plan pins as invariant: coalesced points accumulate,- * and on each batch the full freehand outline is filled into a scratch surface- * at **full alpha** and composited into the layer cache at the stroke's opacity —- * so overlapping segments within one stroke never darken (the "stroke buffer"- * approach). Brush composites `source-over` in the fill color; eraser composites- * `destination-out`. When the target raster layer's transparency is LOCKED, the- * brush composites `source-atop` instead, so colour only lands on already-opaque- * pixels and the layer's alpha channel is never grown (legacy "lock transparent- * pixels"). The eraser is refused entirely on a transparency-locked layer (it- * would alter alpha), handled by the tool before a session is created.- *- * ## Per-frame restore/recomposite- *- * The cache is the live preview, so it must show `before ∪ stroke@opacity` each- * frame. To recomposite without compounding opacity, every frame first restores- * the painted region from the captured "before" pixels, then composites the- * whole accumulated stroke once. This keeps `beforeImageData` exactly equal to- * the pre-stroke pixels over the final dirty rect — which is what commit hands- * to history — and makes cancel a single `putImageData`.- *- * The "before" snapshot is EXTENDED rather than recaptured (see- * {@link extendBefore}). Re-reading the whole region every frame was by far the- * most expensive thing this module did — a full-region `getImageData` costs- * roughly ten times the rest of the frame put together, and it grows with the- * area painted so far, which is exactly why covering a large area with a big- * brush degraded the longer you painted. Since the stroke is never composited- * outside the accumulated rect, the pixels the region gains are still pristine- * and can simply be read as strips and stitched onto the snapshot we already- * hold, leaving per-frame readback proportional to new area rather than total.- *- * Everything flows through the {@link RasterSurface} `ctx` seam, so this runs- * unchanged on the node test stub. Zero React, zero dispatch on the move path.+ * Each preview restores affected pristine pixels before compositing the accumulated stroke. Extend+ * before-snapshots only with newly covered strips, keeping readback proportional to added area. Commit records+ * exact before/after pixels; cancel restores before. Move processing never dispatches.*/import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';@@ -71,43 +42,26 @@ export interface StrokeSessionConfig {/** Edge hardness in [0, 1]: 1 keeps the crisp hot path; lower feathers the silhouette. */hardness: number;/**- * Cache composite operation: `source-over` (brush), `destination-out` (eraser),- * or `source-atop` (transparency-locked brush — colour only where the layer is- * already opaque, alpha never grows).+ * Composite mode: brush source-over, eraser destination-out, or transparency-locked brush source-atop preserving+ * alpha.*/composite: 'source-over' | 'destination-out' | 'source-atop';tool: 'brush' | 'eraser' | 'shape';/** Set only when this gesture auto-created its paint layer (for the composed history entry). */createdLayer?: { layer: CanvasLayerContract; anchor: CanvasNodeInsertionAnchor } | null;/**- * The bounded selection mask to clip the stroke to (resolved once by the tool- * on pointer-down when a selection exists), as a placed surface in DOCUMENT- * space. When set, the paint region is intersected with the mask bounds- * (mapped through the layer inverse) and the scratch stroke is masked- * (`destination-in`) before compositing, so pixels outside the selection are- * never written and the cache only grows within the selection. Absent ⇒ the- * no-selection hot path.+ * Optional document-space selection mask captured at pointerdown. Map bounds locally to limit growth, then+ * destination-in clip scratch so unselected pixels remain untouched.*/clipMask?: PlacedSurface | null;/**- * A document-space rectangle the stroke may not paint outside — the legacy- * "clip strokes to bbox" setting, resolved ONCE per gesture like `clipMask`.- *- * Unlike the selection mask this needs no compositing pass: the scratch is- * region-local and the region is clamped to this rect, so path geometry beyond- * it falls outside the scratch surface and is never drawn. A mask needs the- * extra `destination-in` only because it is an arbitrary SHAPE within its rect.- *- * Absent/`null` ⇒ unclipped (the default, and the hot path).+ * Optional document-space bbox clip captured once per gesture. Region bounds limit scratch coverage; arbitrary+ * selection masks additionally need shape clipping.*/clipRect?: Rect | null;/**- * The target layer's local→document transform. Inputs and clips arrive in- * DOCUMENT space while the session runs in LAYER-LOCAL space (the cache, the- * damage it reports and the history patches all are), so every input crosses- * this boundary through the inverse — the compositor then carries the painted- * pixels back to the screen through the layer's own matrix. Absent ⇒- * identity, the untransformed-layer hot path.+ * Local-to-document layer transform; inverse-map document input/clips because cache, damage and history are+ * local. Absence uses identity.*/layerTransform?: Mat2d | null;}@@ -123,33 +77,17 @@ export interface StrokeSession {}/**- * Cache/scratch growth is snapped OUTWARD to this pixel grid. Without it, an- * outward brush drag extends the paint region by a few pixels on every batch, so- * the cache (and the scratch) would reallocate + full-copy on every pointer-move.- * Snapping to a coarse chunk grid means successive small extensions land inside- * the current padded extent, so growth happens at most once per chunk crossed —- * O(stroke / CHUNK) reallocations instead of O(batches).+ * Outward chunk alignment limits cache/scratch reallocations to crossed chunks rather than every small pointer+ * extension.*/const GROWTH_CHUNK = 64;-/**- * Upper bound on the growth chunk. Reallocating the cache surface costs roughly- * the same as a full-region readback — it is dominated by re-allocating the- * backing canvas, not by preserving the pixels — so a wide brush wants a coarse- * grid to cross fewer boundaries.- */+/** Cap growth chunks; wider brushes need coarser grids to reduce expensive backing-store reallocations. */const MAX_GROWTH_CHUNK = 512;/**- * Fraction of the brush diameter used as the growth chunk, above the- * {@link GROWTH_CHUNK} floor.- *- * Scaling with the brush keeps the padding a constant FRACTION of the stroke- * rather than a constant number of pixels. A fixed 64px grid means a 1200px- * brush reallocates every 64px of travel, and each reallocation costs about as- * much as a whole frame; scaled, it reallocates ~5× less often for the same- * relative overhead. Small brushes keep the fine grid, so their history patches- * (sized from this padded rect) stay small.+ * Scale growth chunks with brush diameter above {@link GROWTH_CHUNK}; wide brushes cross fewer boundaries while+ * small brushes retain compact history patches.*/const GROWTH_CHUNK_RATIO = 0.25;@@ -180,24 +118,9 @@ type SurfaceContext = RasterSurface['ctx'];const CHANGE_MARGIN = 2;/**- * Bounds of the vertices where two outline rings disagree, or `null` when they- * are identical.- *- * This decides how little of the cache a frame has to rewrite, and it is- * answered from the geometry itself rather than inferred from the input.- * Bounding it by "a brush radius around the newest samples" is the intuitive- * approach and it is wrong: the ring is- * `left ++ endCap ++ reverse(right) ++ startCap`, so extending the stroke- * appends to `left`, rewrites `endCap`, and — because the right side is- * REVERSED — shifts the index of every vertex after it. Comparing the rings- * directly costs one linear scan and assumes nothing about how far a new sample- * can reach.- *- * The scan takes the longest common prefix and the longest common suffix; what- * lies between is everything that moved, appeared or vanished. One vertex of- * slack is added on each side, because a vertex is the control point of the- * quadratic spanning its two neighbouring edge midpoints, so its influence on- * the rendered curve reaches one vertex either way.+ * Find changed outline bounds via common prefix/suffix, accounting for appended sides, rewritten caps and reversed+ * right-side indices. Add one neighboring vertex each side because quadratic controls influence adjacent midpoint+ * segments; input-radius guesses can miss changes.*/const changedVertexBounds = (previous: readonly Vec2[], current: readonly Vec2[]): Rect | null => {const shortest = Math.min(previous.length, current.length);@@ -240,14 +163,8 @@ const sameRect = (a: Rect, b: Rect): boolean =>a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;/**- * Grows the pristine "before" snapshot from `previous` to cover `region`,- * reading ONLY the newly-added area from the surface.- *- * The stroke has never been composited outside `previous` — every frame- * composites within the accumulated rect — so the surface still holds pristine- * pixels there and they can be read directly. Carrying the existing snapshot- * forward by copy, instead of re-reading the whole region, is what keeps the- * per-frame cost proportional to new area rather than total painted area.+ * Extend pristine snapshots by copying retained data and reading only new strips, where no stroke has yet+ * composited.*/const extendBefore = (surfaceCtx: SurfaceContext,@@ -275,8 +192,6 @@ const extendBefore = (// Carry the pixels we already hold forward untouched...blit(existing, previous);- // ...and read only the frame the growth exposed. The stroke has never been- // composited out here, so the surface still holds pristine pixels.for (const strip of surroundingStrips(previous, region)) {blit(surfaceCtx.getImageData(strip.x - originX, strip.y - originY, strip.width, strip.height), strip);}@@ -330,8 +245,8 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession// the inverse (exact under rotation and uniform scale, the geometric mean// under non-uniform — the stroke then stretches with the layer's own pixels).const localSize = size * getScale(toLocal);- // Blurring the one filled silhouette keeps soft edges uniform and non-compounding.- // Sub-quarter-pixel sigma is invisible; treating it as crisp keeps the banded hot path.+ // Blur the whole silhouette for uniform, noncompounding softness; sub-quarter-pixel sigma uses the crisp banded+ // path.const rawSigma = ((1 - Math.min(1, Math.max(0, config.hardness))) * localSize) / 4;const featherSigma = rawSigma < 0.25 ? 0 : rawSigma;const featherBleed = Math.ceil(featherSigma * 3);@@ -351,13 +266,9 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionlet soft: RasterSurface | null = null;const points: StrokeSamplePoint[] = [];- // A click that drifts a few pixels must read as a round dot, not a capsule- // stretched by the flick. Below this much total travel the aim point (the- // first sample) IS the stroke.+ // Below the travel threshold, preserve the first aim point as a round dab rather than a short capsule.const tapCollapseLength = Math.max(2, localSize * 0.25);- // `beforeImageData` holds the pristine (pre-stroke) pixels of `accumRect`, in- // LAYER-LOCAL coordinates — so it stays valid across a cache growth-realloc- // (which only shifts the surface origin, not the layer-local geometry).+ // Before pixels cover `accumRect` in stable layer-local coordinates, unaffected by backing-store origin shifts.let beforeImageData: ImageData | null = null;let accumRect: Rect | null = null;let previousPolygon: Vec2[] | null = null;@@ -398,8 +309,7 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession}const { bounds, path, polygon } = strokeToPath(effective, { last, size: localSize, thinning }, ctx.createPath2D);let dirty: Rect | null = roundOut(featherBleed > 0 ? expand(bounds, featherBleed) : bounds);- // Selection clip: only the region inside the selection can ever change, so- // bound the dirty/growth region to the mask extent (and skip empty results).+ // Limit dirty/growth bounds to selection coverage and skip empty intersections.if (clipMaskLocalRect) {dirty = intersect(dirty, clipMaskLocalRect);}@@ -409,15 +319,8 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionif (!dirty || isEmpty(dirty)) {return;}- // Accumulate the dirty union, then round it OUTWARD to a coarse chunk grid.- // Chunk-padding is the allocation-light seam the plan pins as invariant: an- // extending drag now grows the cache/scratch at most once per chunk it crosses- // instead of on every pointer batch. The padded extent may exceed the true- // content bounds — fine: it is an internal cache extent, so the flush just- // encodes a slightly larger (mostly-transparent) PNG at a consistent offset,- // and the reported dirty/before/after all use this same padded region so every- // consumer stays coherent. When a selection clips the stroke, clamp the padded- // region back to the mask so growth still never escapes the selection.+ // Outward chunk-padding amortizes growth; dirty regions and history use the same padded extent. Clamp padding+ // to selection bounds, and trim visible content during persistence.let region = padToChunk(accumRect ? roundOut(union(accumRect, dirty)) : dirty, chunk);if (clipMaskLocalRect) {const clamped = intersect(region, clipMaskLocalRect);@@ -426,9 +329,7 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession}}if (clipRectLocal) {- // Clamping the region IS the bbox clip: the scratch is sized to the region- // and the path is drawn translated into it, so anything beyond the rect- // lands outside the surface and never reaches the cache.+ // Region-local scratch clips axis-aligned bbox overflow at its surface boundary.const clamped = intersect(region, clipRectLocal);if (clamped) {region = clamped;@@ -438,11 +339,7 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionreturn;}- // Grow the cache to cover the (chunk-padded, layer-local) region, preserving- // existing pixels. Because `region` is chunk-aligned and monotonically growing,- // `entry.surface` is reallocated at most once per chunk boundary the stroke- // crosses — not once per batch — keeping the hot path allocation-light. The- // surface is resized in place (identity preserved).+ // Grow preserving pixels at chunk crossings while retaining surface-object identity.const entry = layers.growToRect(layerId, region);const target = entry.surface;const targetCtx = target.ctx;@@ -450,20 +347,13 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionconst ox = entry.rect.x;const oy = entry.rect.y;- // 1. Extend the pristine "before" snapshot over whatever the region just- // gained, reading only the newly-exposed frame rather than re-reading- // everything painted so far.const previousRect = accumRect;if (!beforeImageData || !previousRect || !sameRect(previousRect, region)) {beforeImageData = extendBefore(targetCtx, beforeImageData, previousRect, region, ox, oy);}accumRect = region;- // 2. Work out where the silhouette actually moved since the last frame, and- // confine the rest of the frame to it. Outside this band the cache already- // holds the correct composite and the shape has not changed, so redoing it- // would only cost time — and rewriting the whole accumulated region every- // frame is what made a long stroke get slower the longer it got.+ // Rewrite only changed silhouette bounds; unchanged pixels already hold the correct composite.const moved = previousPolygon ? changedVertexBounds(previousPolygon, polygon) : null;const touched =previousRect && moved ? intersect(roundOut(expand(moved, CHANGE_MARGIN + featherBleed)), region) : region;@@ -472,10 +362,8 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionconst changed = touched && !isEmpty(touched) ? touched : region;previousPolygon = polygon;- // 3. Restore that band to pristine "before" pixels, so recompositing the- // stroke over it doesn't compound its opacity. `putImageData`'s dirty-rect- // arguments write only this window out of the full-region snapshot. On the- // opening frame nothing has been composited yet, so there is nothing to undo.+ // Restore the changed band from pristine pixels before compositing to avoid compounded opacity. The first+ // frame has nothing to restore.if (previousRect) {targetCtx.putImageData(beforeImageData,@@ -488,23 +376,9 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession);}- // 4. Render the accumulated stroke into the scratch surface at full alpha.- // The path is filled in ONE pass, so overlapping parts of a stroke union- // rather than compounding — filling it in pieces across frames would let- // the antialiased edges of successive batches blend into each other and- // leave seams. The scratch is region-local: translate the (layer-local)- // path by -region.origin.- //- // Only the changed band is refreshed. The scratch persists between- // frames, and outside that band the silhouette is by definition the same- // one already sitting there — so re-clearing and re-filling the whole- // region was redrawing pixels to their existing values. A region change- // resizes the scratch, which clears it, so that case still refills whole.- //- // Pressure-opacity forces the whole region to refresh instead. Bands are painted as- // replace, so a band straddling the changed strip would be half-punched by a partial- // refill and lose its earlier half. Refilling whole keeps the band sequence intact,- // at the cost of the per-frame saving above — which is why it stays opt-in.+ // Fill the accumulated outline once in region-local scratch, refreshing only changed bounds to avoid overlap+ // seams. Resizing clears scratch and requires a full fill. Pressure-alpha also refreshes fully because partial+ // replacement could split a band and lose earlier coverage.const scratchCleared = !previousRect || !sameRect(previousRect, region);// The blur reads the whole silhouette; a band-only refill would seam.const refresh = scratchCleared || pressureOpacity || featherSigma > 0 ? region : changed;@@ -523,21 +397,15 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessiontapPoint !== undefined && bounds.width > 0 && bounds.width < 1 && bounds.height > 0 && bounds.height < 1;if (isSubpixelTap) {- // Skia can quantize a filled path smaller than one pixel to zero coverage,- // making a valid minimum-size click disappear completely. Represent the- // dab as coverage in the containing pixel instead: the alpha is the area- // of the requested elliptical outline, so this remains a genuinely- // sub-pixel mark rather than silently inflating it to a 1px brush.+ // Subpixel paths may quantize to zero in Skia. Represent a tiny dab in its containing pixel with+ // ellipse-area alpha, preserving subpixel coverage rather than inflating brush size.strokeCtx.globalCompositeOperation = 'source-over';const pressureAlpha = pressureOpacity ? (getPressureBands([tapPoint])[0]?.alpha ?? 1) : 1;strokeCtx.globalAlpha = Math.min(1, ((Math.PI * bounds.width * bounds.height) / 4) * pressureAlpha);strokeCtx.fillRect(Math.floor(tapPoint.x), Math.floor(tapPoint.y), 1, 1);} else if (pressureOpacity) {- // Each band replaces its own footprint rather than blending into it: punch the band's- // outline out of whatever is already there, then fill it at the band's alpha. Blending- // would compound alpha wherever bands overlap — the exact darkening the single- // full-alpha fill below exists to prevent. Replacing means the later (newer) band wins- // in the overlap, which is the pressure the user is applying now.+ // Pressure bands erase then replace their footprint at current alpha; newer bands win overlaps without+ // compounding.for (const band of getPressureBands(effective)) {const bandPath = strokeToPath(band.points, { last, size: localSize, thinning }, ctx.createPath2D).path;@@ -571,10 +439,8 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession}const paintCtx = paintSurface.ctx;- // 4b. Selection clip: keep only the stroke pixels inside the selection mask.- // The mask is a placed surface; draw it at (maskOrigin - regionOrigin) in- // the scratch's region-local space. Confined to the same band — masking- // already-masked pixels a second time would multiply their alpha again.+ // Mask only the changed scratch band at maskOrigin-regionOrigin; masking retained pixels again would multiply+ // alpha twice.if (clipMask) {paintCtx.setTransform(1, 0, 0, 1, 0, 0);paintCtx.save();@@ -591,9 +457,7 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionpaintCtx.restore();}- // 4c. Bbox clip on a rotated/sheared layer: the region clamp above only- // bounds the AABB, so keep exactly the pixels inside the document-space- // rect, drawn through the same inverse the mask uses.+ // Rotated/sheared bbox AABBs need exact inverse-mapped rectangular clipping beyond the coarse region clamp.if (clipRect && clipRectNeedsMask) {paintCtx.setTransform(1, 0, 0, 1, 0, 0);paintCtx.save();@@ -610,10 +474,8 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionpaintCtx.restore();}- // 5. Composite the scratch stroke into the cache at the stroke opacity, using- // the tool's blend (brush over / eraser out), clipped to the band this- // batch changed. The clip also confines the whole-canvas `drawImage` to- // the region, which the scratch may exceed after a resize.+ // Composite scratch at stroke opacity with tool blend, clipping to changed bounds even if scratch exceeds the+ // region.targetCtx.save();targetCtx.setTransform(1, 0, 0, 1, 0, 0);targetCtx.beginPath();@@ -624,28 +486,16 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessiontargetCtx.drawImage(paintSurface.canvas, region.x - ox, region.y - oy);targetCtx.restore();- // The cache pixels changed THIS frame — bump the version, WITH the band they- // changed in, so a version-keyed dependent (the memoized adjusted-surface- // cache) recomputes over the live stroke without rebuilding from the whole- // layer. Without the bump the compositor would keep serving the pre-stroke- // adjusted surface, and the live stroke would be invisible on an adjusted- // raster layer until pointer-up (and jump on rect growth). The band is in- // SURFACE-local coordinates, the space a derived surface is built in. Note- // it is the derived surfaces that need this — the stroke's own scratch and- // cache writes are already bounded above. This does NOT- // touch `thumbnailVersion` (only `notifyLayerPainted`/rasterize do), so- // thumbnails don't churn mid-stroke.+ // Bump cache version with surface-local changed bounds so adjusted surfaces refresh live strokes partially.+ // Keep thumbnail versions unchanged until committed paint/rasterization notifications.layers.publishPixels(layerId, {height: changed.height,width: changed.width,x: changed.x - ox,y: changed.y - oy,});- // Report the region as damage so the frame repaints only these pixels- // instead of re-resampling every doc-sized layer to screen scale — the cost- // that grows with zoom. `region` is layer-local, which is exactly what the- // compositor wants: it carries it to the screen through the layer's own- // matrix, so this stays correct on a moved or scaled layer.+ // Report layer-local damage; compositor transforms it to screen space, avoiding full-layer resampling as zoom+ // increases.ctx.invalidate({ damage: { layerId, rect: changed }, layers: [layerId] });};@@ -660,11 +510,8 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionconst entry = layers.get(layerId);if (entry && accumRect && beforeImageData) {entry.surface.ctx.putImageData(beforeImageData, accumRect.x - entry.rect.x, accumRect.y - entry.rect.y);- // Bump the version so the adjusted-surface memo (which recomputed over the- // live stroke) re-derives from the RESTORED pixels — otherwise an adjusted- // raster layer would keep showing the cancelled stroke's adjusted preview.- // The restore spans everything the gesture touched, so this reports the- // whole accumulated rect rather than any one frame's band.+ // Cancellation reports the whole restored accumulated rect so adjusted caches discard the live stroke+ // preview.layers.publishPixels(layerId, {height: accumRect.height,width: accumRect.width,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.tsindex 1b959c31d7..11ec21276d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.ts@@ -60,8 +60,7 @@ const createHarness = (doc: CanvasDocumentContractV3) => {const ctx = {cancelTextEdit,getDocument: () => doc,- // No layer cache in these tests, so hit-testing falls back to the pure- // estimateTextExtent (a `get` that always misses).+ // Missing caches force hit tests to use estimated text extent.layers: { get: () => undefined },openTextCreate,openTextEdit,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.tsindex 5cc63761c2..1786e23f9e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.ts@@ -1,35 +1,10 @@/**- * The text tool: click to CREATE editable-forever text, or click an existing- * text layer to re-edit it.+ * Text clicks edit the topmost eligible hit layer or open creation at the point. Measured cache bounds fall back+ * to estimates, with inverse-transform hit testing.*- * Interaction contract (CANVAS_PLAN Phase 6.2):- * - **Click on empty area** → open a CREATE-mode text-editing session at that- * document point (style seeded from the text options bar). Nothing is added to- * the document until the session commits (a single `addCanvasLayer`).- * - **Click on an existing text layer** (top-most, enabled, unlocked) → open an- * EDIT-mode session on it. Hit-testing inverts the layer transform and checks- * the point against the layer's rendered text-block rect (cache size, or the- * pure estimate before a cache exists). Locked/hidden text layers are skipped.- * - **Click while a session is open** → the pointer pipeline commits the open- * session engine-side (`maybeCommitModalSession` → `commitOpenTextSession`,- * reading the live portal content) and swallows the press BEFORE it reaches- * this tool, so `onPointerDown` below is never invoked for that press. A- * subsequent click then places/edits. The `textEditSession` guard here is a- * defensive backstop for a harness that routes the press through anyway.- * - **Commit** is engine-side on a canvas pointerdown (above); the portal's blur- * (focus lost to non-canvas UI) and `mod+enter` also commit. The live typed- * text is read from the portal only at commit time (no per-keystroke traffic).- * - **Escape** is handled by the focused contenteditable (cancels the session);- * a defocused-but-open session is cancelled by the engine's Escape chain- * (`handleEscape`: text → transform → deselect), not routed to this tool.- * - A **real** tool switch cancels the session (`onDeactivate`); a **temporary**- * modifier-hold switch (space→view / alt→colorPicker) preserves it, mirroring- * the transform tool.- *- * Text layers are not hit-testable by the move/transform tools (like shapes and- * gradients), so this tool owns its own text hit-test.- *- * Zero React, zero import-time side effects.+ * An open session consumes the next canvas press after committing live portal content; blur and Mod+Enter also+ * commit. Escape cancels through the portal or engine ladder. Temporary switches preserve sessions; real switches+ * cancel. Creation adds no layer until its single commit.*/import type {@@ -58,11 +33,7 @@ type TextLayer = Extract<CanvasLayerContract, { type: 'raster' }> & { source: Teconst isTextLayer = (layer: CanvasLayerContract): layer is TextLayer =>layer.type === 'raster' && layer.source.type === 'text';-/**- * The rendered text-block size for hit-testing: the live cache surface size when- * one exists (the precise, measured extent), else the pure estimate (before the- * layer has been rasterized once).- */+/** Hit-test measured cache bounds when available, otherwise estimate before first rasterization. */const textLayerSize = (layer: TextLayer, ctx: ToolContext): { width: number; height: number } => {const cache = ctx.layers.get(layer.id);if (cache) {@@ -97,19 +68,15 @@ export const createTextTool = (): Tool => ({id: 'text',onDeactivate: (ctx, opts) => {if (opts?.temporary) {- // A modifier-hold switch (space/alt) preserves the open session for- // `onActivate` to resume when the hold ends — like the transform tool.+ // Preserve text sessions across modifier holds for later reactivation.return;}- // A real tool switch cancels the session (in practice the contenteditable's- // blur has already committed by now; this is the safety teardown).+ // Real switches cancel remaining sessions after any portal-blur commit.ctx.cancelTextEdit?.();},onKeyCommand: (ctx, command) => {- // Defensive backstop: the pipeline does not route 'cancel' to tools (the- // engine's `handleEscape` chain owns text/transform/deselect), so this only- // fires if a harness routes it directly. Cancel drops a defocused session;- // apply is a no-op here (only the portal holds the live content to commit).+ // Direct harness cancellation is a backstop; production Escape uses the engine ladder. Apply needs portal+ // content and does nothing here.if (command === 'cancel') {ctx.cancelTextEdit?.();}@@ -118,9 +85,7 @@ export const createTextTool = (): Tool => ({if ((input.buttons & PRIMARY_BUTTON) === 0) {return;}- // Backstop: when a session is open the pipeline commits+swallows the press- // before it reaches this tool, so this branch is normally unreached. Guard- // anyway so a harness that routes the press through never opens a 2nd session.+ // Defensively reject a second session if a harness bypasses the pipeline's commit-and-consume hook.if (ctx.stores.textEditSession.get()) {return;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex 47dcd9bcd5..5fc16e804c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -1,16 +1,7 @@/**- * The `Tool` seam: the engine routes normalized pointer/wheel input to whichever- * tool is active. Tools are pure interaction handlers — they read the viewport- * and mirrored document through the engine-provided {@link ToolContext} and- * request re-renders via `invalidate`.- *- * Navigation tools (view) never dispatch and never touch pixels. Painting tools- * (brush/eraser) reach the layer-cache surfaces and raster backend through the- * same context, dispatch at most once per gesture (auto-creating a paint layer- * on pointer-down when needed), and emit exactly one {@link StrokeCommittedEvent}- * on commit — persistence/history are wired to that event downstream, not here.- *- * Zero React, zero import-time side effects.+ * Tools handle normalized input through engine context and request rendering. Navigation changes only viewport.+ * Painting may create a layer at gesture start, edits caches without move dispatch, and emits one {@link+ * StrokeCommittedEvent} for downstream history/persistence.*/import type { StructuralCommitResult } from '@workbench/canvas-engine/capabilities';@@ -32,12 +23,7 @@ import type { LayerTransform } from '@workbench/canvas-engine/transform/transforimport type { PlacedSurface, PointerInput, PointerModifiers, Rect, ToolId, Vec2 } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';-/**- * Emitted once per completed brush/eraser gesture. Persistence (Task P2.2) and- * history (Task P2.3) subscribe via `engine.tools.onStrokeCommitted`. `beforeImageData`- * and `afterImageData` are both sized to `dirtyRect`, so an undo can restore the- * pre-stroke pixels and a redo can re-apply the post-stroke pixels cheaply.- */+/** One completed-stroke event carries before/after images sized to dirtyRect for exact undo/redo and persistence. */export interface StrokeCommittedEvent {/** The layer that received the stroke. */layerId: string;@@ -49,13 +35,7 @@ export interface StrokeCommittedEvent {afterImageData: ImageData;/** Which tool produced the stroke; a `shape` is one drawn as pixels onto a paint layer. */tool: 'brush' | 'eraser' | 'shape';- /**- * When the gesture auto-created its paint layer on pointer-down, the created- * layer contract (and where it was inserted). The engine composes this into- * the stroke's history entry so an undo removes BOTH the stroke and the- * now-empty auto-created layer (and a redo re-adds the layer + stroke).- * Absent for strokes painted into a pre-existing layer.- */+ /** Optional auto-created layer and insertion placement let stroke history remove/recreate both layer and pixels. */createdLayer?: { layer: CanvasLayerContract; anchor: CanvasNodeInsertionAnchor };}@@ -73,10 +53,8 @@ export interface PixelEditTransaction {}/**- * A transient per-layer transform override the compositor/overlay read at render- * time (a live drag preview that never touches the mirror). The move tool sets- * only `x`/`y` (rotation/scale fall back to the committed transform); the- * transform tool sets the full transform so a scale/rotate preview renders.+ * Transient render-time transforms leave the mirror unchanged. Move sets position only; transform supplies full+ * values.*/export interface LayerTransformOverride {x: number;@@ -100,27 +78,14 @@ export interface ToolContext {dispatch(action: CanvasProjectMutation): void;/** Where a layer the tool creates lands: above `aboveId` when it belongs to `stack`, else the stack top. */captureInsertionAnchor(stack: LayerStackKind, aboveId: string | null): CanvasNodeInsertionAnchor;- /**- * Records a structural document edit on the engine-owned canvas history:- * dispatches `forward` now, and an undo dispatches `inverse` / a redo- * re-dispatches `forward`. The move tool commits a layer nudge through this.- */+ /** Applies forward structural action now and records inverse/forward replay in canvas history. */commitStructural(label: string,forward: CanvasProjectMutation,inverse: CanvasProjectMutation): StructuralCommitResult;- /**- * Sets (or clears with `null`) a transient per-layer transform override the- * compositor and overlay read at render time — a live drag preview that never- * touches the mirror/document. Cleared on commit or cancel.- */+ /** Set or clear transient compositor/overlay transforms without document mutation; clear on commit/cancel. */setLayerTransformOverride(layerId: string, override: LayerTransformOverride | null): void;- /**- * Begins a transform session on `layerId` (captures its committed transform,- * shows the live preview). Provided by the engine; the transform tool calls it- * on activate / when a layer is clicked. Absent in minimal test harnesses.- */beginTransformSession?(layerId: string): void;/** Prepares direct or materializing pixel editing for a selected control or raster-image layer. */beginPixelEdit?(layerId: string): PixelEditTransaction | null;@@ -128,25 +93,13 @@ export interface ToolContext {requestLayerRasterization?(layerId: string): void;/** Updates the active transform session's live transform (drag or numeric edit). */updateTransformSession?(transform: LayerTransform): void;- /**- * Commits the active transform session: a param commit (image layers) or a- * pixel bake (paint layers), as ONE undoable entry. Then clears the session.- */+ /** Commits image parameters or paint bake as one undo entry, then clears the session. */applyTransform?(): void;/** Cancels the active transform session (drops the preview, no dispatch). */cancelTransform?(): void;- /**- * Opens a CREATE-mode text-editing session at `docPoint` (no layer yet; the- * commit later dispatches one `addCanvasLayer`). Seeds style from the text- * options store. The text tool calls it on an empty-area click. Absent in- * minimal test harnesses.- */+ /** Optional creation session at document point with tool defaults; no layer exists until one add commit. */openTextCreate?(docPoint: Vec2): void;- /**- * Opens an EDIT-mode text-editing session on an existing text layer (captures- * its committed source for the undo inverse). The text tool calls it when a- * click hits a text layer. Absent in minimal test harnesses.- */+ /** Optional edit session captures the existing text source as exact undo baseline. */openTextEdit?(layerId: string): void;/** Cancels the active text-editing session (drops it, no dispatch). */cancelTextEdit?(): void;@@ -165,12 +118,8 @@ export interface ToolContext {/** Sets (or clears) the brush cursor ring drawn on the overlay. */setOverlayCursor(cursor: OverlayCursor | null): void;/**- * Hands a sampled color to whoever claims it: a one-shot request made from- * outside the canvas (a color picker's eyedropper button) wins first, then- * the workbench's persistent router (which writes the active- * foreground/background target). Returns whether anyone took it; only then- * does the color-picker tool fall back to writing the brush color — the- * engine-standalone behavior. Absent in minimal test harnesses.+ * Route samples to one-shot claim, then persistent workbench target. Return whether consumed; otherwise picker+ * falls back to brush color. Optional in test harnesses.*/resolveColorSample?(hex: string): boolean;/** Compositor providers that make sampling WYSIWYG; absent ⇒ raw cached pixels. */@@ -184,43 +133,25 @@ export interface ToolContext {/** Drops the stashed sample (gesture cancel, fresh press) without settling the request. */discardColorSample?(): void;/**- * Re-evaluates the active tool's CSS cursor and applies it to the input- * element. A tool calls this when its `cursor(ctx)` result changes off a plain- * pointer-move (e.g. the bbox tool switching to a resize cursor while hovering a- * handle) — pointer-move does not otherwise refresh the cursor.+ * Refresh the input element cursor when tool state changes; ordinary pointermove does not automatically+ * reevaluate it.*/updateCursor(): void;/** Emits a completed-stroke event to `engine.tools.onStrokeCommitted` subscribers. */emitStrokeCommitted(event: StrokeCommittedEvent): void;/** Bumps a layer's cache version (without marking it stale) after a direct paint, and recomposites. */notifyLayerPainted(layerId: string): void;- /**- * Commits a lasso path to the engine's transient selection (boolean op applied- * to the mask). Provided by the engine; the lasso tool calls it on pointer-up.- * Absent in minimal test harnesses.- */commitSelection?(commit: SelectionCommit): void;/**- * The current selection mask as a placed surface (alpha 255 inside) in document- * space — the mask is bounded to the selection extent, so its `rect` records- * where it sits. `null` when there is no selection. Painting tools read it ONCE- * on pointer-down to clip the stroke; a `null` result keeps the zero-overhead- * hot path. Absent in minimal test harnesses.+ * Optional placed document-space selection mask; paint tools capture it once at pointerdown. Null avoids masking+ * work.*/getSelectionMask?(): PlacedSurface | null;- /**- * The document-space rectangle strokes may not paint outside, or `null` when- * unclipped. Painting tools read it ONCE on pointer-down, alongside the- * selection mask. Absent in minimal test harnesses.- */+ /** Optional document-space stroke clip captured once at pointerdown; null means unclipped. */getStrokeClipRect?(): Rect | null;/** Updates visual SAM input for the active engine-owned Select Object session. */updateSamInput?(input: SamVisualInput): void;- /**- * Cuts the current selection's pixels out of `layerId` into a floating- * selection, returning whether anything was lifted. Absent in minimal test- * harnesses.- */+ /** Optional lift of selected layer pixels into a float; returns whether any were lifted. */liftFloatingSelection?(layerId: string): boolean;/** The live floating selection, or `null`. */getFloatingSelection?(): FloatingSelection | null;@@ -239,13 +170,7 @@ export interface ToolContext {isPointInSelection?(point: Vec2): boolean;}-/**- * Why a tool is being (de)activated, passed by the engine's `setTool` so a- * session-bearing tool (transform) can tell a temporary modifier-hold switch- * (space→view, alt→colorPicker; the pointer pipeline restores the prior tool- * on release) apart from a REAL tool switch. A temp switch must not tear down- * an in-progress session — only a real switch (or dispose) does.- */+/** Temporary modifier switches/restores preserve sessions; real switches or disposal tear them down. */export interface ToolActivationOptions {/** True for a pipeline modifier-hold switch (and its matching restore); absent/false for a real switch. */temporary?: boolean;@@ -269,10 +194,8 @@ export interface Tool {/** The active gesture was cancelled (Esc, pointercancel, focus loss). */onPointerCancel?(ctx: ToolContext): void;/**- * A session-level key command routed from the pointer pipeline: Enter →- * `'apply'`, Escape → `'cancel'`. Tools with a multi-gesture session (transform)- * use it to commit/abort; other tools ignore it. Escape also runs the normal- * gesture cancel independently.+ * Optional session commands from the pipeline; tools may apply/cancel while gesture cancellation remains+ * separate.*/onKeyCommand?(ctx: ToolContext, command: 'apply' | 'cancel'): void;/** Wheel over the canvas; `screenAnchor` is the CSS-pixel cursor position. */diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.tsindex 84067fad59..5095d5517a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts@@ -105,12 +105,8 @@ interface Harness {}/**- * A ToolContext whose transform-session seams mutate a real `transformSession`- * store (mirroring the engine), so the tool's reads reflect its own writes across- * a down→move→up drag. The viewport projects document→screen 1:1.- *- * Grid snapping starts OFF so the gesture-math tests assert raw pointer deltas;- * the snapping tests re-enable it on `h.ctx.stores`. (The product default is on.)+ * Real session stores reflect tool writes during 1:1 gesture tests. Snap defaults off here to isolate deltas;+ * dedicated cases enable the product-default behavior.*/const createHarness = (doc: CanvasDocumentContractV3, zoom = 1, float?: FloatingSelection | null): Harness => {const stores = createEngineStores();@@ -434,14 +430,10 @@ describe('transform tool: rotation nub (regression — a nub press must rotate,const tip = nubTipScreen(transformed, layerSize, zoom);down(tool, h.ctx, pointerAtScreen(tip, zoom));- // (a) Gesture start must NOT touch the session/override values. The bug read- // the nub press as off-frame and re-opened the session, resetting its live- // transform back to the committed one.+ // Pressing the nub must preserve live session values rather than reopening from committed transforms.expect(h.session()?.transform).toEqual(startTransform);expect(h.overrides.length).toBe(overridesBefore);- // (b) A subsequent move begins a ROTATION: rotation changes by the swept- // angle, scale is untouched (not a move/scale/reset).const geo = transformOverlayGeometry(transformed, layerSize);const centerScreen: Vec2 = { x: zoom * geo.center.x, y: zoom * geo.center.y };const moved = rotateAbout(tip, centerScreen, 0.5);@@ -518,8 +510,7 @@ describe('transform tool: apply / cancel', () => {const tool = createTransformTool();activate(tool, h.ctx);- // se corner drag, past the threshold — a gesture is now in progress and- // holds (conceptually) pointer capture.+ // Southeast drag crosses the threshold and owns pointer capture.down(tool, h.ctx, pointer(100, 100));move(tool, h.ctx, pointer(120, 120));const midDrag = h.session()?.transform.scaleX;@@ -527,8 +518,6 @@ describe('transform tool: apply / cancel', () => {tool.onKeyCommand?.(h.ctx, 'apply');- // No-op: the engine apply seam was NOT invoked (unlike the "Enter applies- // the session" test above, which has no live gesture).expect(h.applyCount()).toBe(0);// The gesture is still alive — it did not silently freeze mid-drag.@@ -554,9 +543,7 @@ describe('transform tool: temp-tool switch (space/alt hold)', () => {tool.onDeactivate?.(h.ctx, { temporary: true });expect(h.session()?.transform).toEqual(edited);- // Space up: a temporary activate must not re-open the session from the- // current selection (which would stomp the preserved edit with the- // layer's committed transform).+ // Temporary reactivation must preserve live edits instead of reopening from committed values.tool.onActivate?.(h.ctx, { temporary: true });expect(h.session()?.transform).toEqual(edited);});@@ -569,8 +556,7 @@ describe('transform tool: temp-tool switch (space/alt hold)', () => {expect(h.session()).not.toBeNull();tool.onDeactivate?.(h.ctx, { temporary: true });- // Simulates the engine's layer-change teardown (Task 26 finding #3)- // cancelling the session out-of-band while temp-switched away.+ // Simulate engine cancellation while temporarily switched away after the layer disappears.h.ctx.cancelTransform?.();expect(h.session()).toBeNull();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.tsindex 135194e4b3..5b2c2bdf3c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts@@ -1,38 +1,12 @@/**- * The transform tool: an interactive scale/rotate/move SESSION on a single layer.+ * Transform sessions frame the selected eligible layer without retargeting and span multiple gestures/numeric+ * edits. Handles scale about opposite anchors (Alt center, Shift uniform); rotate zones use Shift 15-degree snap;+ * interior moves with axis lock.*- * Interaction contract (CANVAS_PLAN Phase 5):- * - **Session**: selecting the tool with an eligible layer selected (or pressing- * the canvas with no session open) captures the SELECTED layer's committed- * transform and opens a session on it. A press never re-targets which layer is- * active — that is the layers panel's job. The live preview- * flows through the engine's transform-override channel; a `transformSession`- * store exposes the layer id + live transform so the numeric options bar can- * render and edit it. The session survives multiple gestures — drag handles,- * drag to rotate/move, adjust numerics — until **Apply** or **Cancel**.- * - **Gestures** (each a fresh pointer drag on the session's frame): a scale- * handle scales about the opposite handle (alt = center, shift = uniform on- * corners); a corner rotate zone rotates about the center (shift = 15° snap);- * the interior moves (shift = axis constrain). Pointer-move only updates the- * session preview — it never dispatches.- * - **Snap**: with the snap-to-grid setting on, a LAYER gesture lands its origin- * (move) or the dragged handle (scale) on the model grid. Alt bypasses the snap- * on a move; on a scale handle it does not, because alt already means- * scale-about-center there. Float gestures never snap — their transform is- * layer-local, so a document-space grid would skew rotated/scaled layers.- * - **Apply** (`enter` / options button): the engine commits — a param edit for- * image layers, a pixel bake for paint layers — as ONE undoable entry.- * - **Cancel** (`esc` / options button / a REAL tool switch): drops the- * preview, no dispatch. A mid-gesture pointercancel reverts just that drag,- * keeping the session; Escape aborts the whole session. A TEMPORARY tool- * switch (space/alt modifier-hold) is not a cancel — the session and its- * preview survive the hold and resume when it ends (see `onActivate`/- * `onDeactivate`'s `opts.temporary`). If the session's layer is deleted- * while held, the engine's layer-change teardown cancels it regardless of- * which tool is active.- *- * Locked/hidden layers get no session (same guard as the move tool). Zero React,- * zero import-time side effects.+ * Layer origins/handles snap to the model grid; Alt bypasses move snapping but retains center-scale meaning.+ * Local-space floats never snap. Apply makes one parameter edit or paint bake. Pointercancel reverts only its+ * drag; Escape/real switches cancel the session. Temporary switches preserve edits, and deletion always tears them+ * down.*/import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';@@ -89,12 +63,8 @@ const cursorForTarget = (transform: LayerTransform, target: TransformTarget): st};/**- * What a transform gesture acts on. A layer works in DOCUMENT space; a floating- * selection works in its layer's LOCAL space (that is where its pixels and its- * transform live). The gesture math is space-agnostic as long as `rect`,- * `transform`, and the pointer are all expressed in the same space — `toDocument`- * / `fromDocument` bridge that space to the viewport, so both cases run through- * exactly the same handle hit-testing and scale/rotate/move code.+ * Layer gestures use document space; floats use layer-local space. Convert pointers through to/fromDocument so+ * bounds, transforms and gesture math share one coordinate system.*/interface TransformSubject {readonly kind: 'layer' | 'float';@@ -118,19 +88,13 @@ export const createTransformTool = (): Tool => {let hoverCursor: string | null = null;const isEligible = (layer: CanvasLayerContract, doc: NonNullable<ReturnType<ToolContext['getDocument']>>): boolean =>- // Masks are MOVE-able (legacy parity) but not transform-able in this phase:- // `applyTransform` has no mask bake path, so a transform session on a mask- // would preview then no-op on Apply. Exclude them until that lands (Phase 7+).+ // Masks lack an applyTransform bake path, so reject sessions that would preview but fail to apply.isLeafEditable(lookupDocumentLeaf(doc, layer.id)) &&layer.type !== 'inpaint_mask' &&layer.type !== 'regional_guidance' &&hittableLayerRect(layer, doc) !== null;- /**- * What the tool currently acts on: a live floating selection takes precedence- * over the layer session — the pixels are already detached, so the frame must- * wrap them, not the layer they came from.- */+ /** Live floats take precedence over layer sessions so the frame follows detached pixels. */const subjectOf = (ctx: ToolContext): TransformSubject | null => {const doc = ctx.getDocument();if (!doc) {@@ -195,8 +159,6 @@ export const createTransformTool = (): Tool => {});const nextTransform = (ctx: ToolContext, state: GestureState, input: PointerInput): LayerTransform => {- // The pointer arrives in document space; the gesture math runs in the- // subject's space, so convert before doing anything with it.const pointer = state.fromDocument(input.documentPoint);const delta: Vec2 = {x: pointer.x - state.startPointerDoc.x,@@ -245,17 +207,11 @@ export const createTransformTool = (): Tool => {id: 'transform',onActivate: (ctx, opts) => {if (opts?.temporary) {- // Resuming from a modifier-hold switch (space→view, alt→colorPicker):- // `onDeactivate` preserved the session (and its preview override)- // across the hold, so there is nothing to (re)open here. Re-opening- // from the current selection would stomp the live preview with the- // layer's committed transform, discarding accumulated drags/numeric- // edits. If the session's layer vanished mid-hold, the engine's- // layer-change teardown already cancelled it — leave that alone too.+ // Temporary reactivation preserves existing edits and does not reopen from committed transforms. If+ // deletion cancelled the session mid-hold, leave it closed.return;}- // A live float IS the session — entering the tool frames the pixels in- // flight, so no layer session is opened over the top of them.+ // A live float already owns the session; do not open a layer session over it.if (ctx.getFloatingSelection?.()) {return;}@@ -270,12 +226,8 @@ export const createTransformTool = (): Tool => {onDeactivate: (ctx, opts) => {hoverCursor = null;if (opts?.temporary) {- // A modifier-hold switch (space/alt) must not discard an in-progress- // session: the pipeline already suppresses temp switches mid-gesture,- // so `gesture` is guaranteed null here — this only clears the idle- // hover cursor. The session + preview override are left for- // `onActivate` to resume when the hold ends. A REAL tool switch (below)- // still cancels.+ // Temporary switches occur only between gestures and clear hover state while preserving session/preview.+ // Real switches cancel.endGesture();return;}@@ -287,15 +239,9 @@ export const createTransformTool = (): Tool => {},onKeyCommand: (ctx, command) => {if (gesture) {- // A live drag holds pointer capture (its own pointerup/pointercancel- // will end it); applying or cancelling now would tear the gesture down- // out from under the still-open pointer session, freezing the preview- // mid-drag. No-op instead — mirrors `applyTransform`'s own mid-gesture- // guard (`pipeline.isGestureActive()`) for the same reason.+ // Ignore apply/cancel during captured drags to avoid tearing down the still-active pointer session.return;}- // A float owns Apply/Cancel while it is in flight: baking it is what- // "apply" means, and abandoning it is what "cancel" means.if (ctx.getFloatingSelection?.()) {if (command === 'apply') {ctx.commitFloatingSelection?.();@@ -333,8 +279,6 @@ export const createTransformTool = (): Tool => {if (!doc) {return;}- // 1) A framed subject (a float, or an open layer session): a press on its- // frame starts a scale/rotate/move gesture.const subject = subjectOf(ctx);if (subject) {const target = targetAt(ctx, subject, input.screenPoint);@@ -356,9 +300,7 @@ export const createTransformTool = (): Tool => {return;}- // 2) Nothing framed yet: open a session on the SELECTED layer (the layers- // panel is the sole authority on which layer is active — a press never- // re-targets it) and start a move gesture.+ // Open an unframed session on panel selection and begin movement without retargeting.const selectedId = doc.selectedLayerId;const selected = selectedId ? getDocumentLayer(doc, selectedId) : undefined;if (!selected || !isEligible(selected, doc)) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/viewTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/viewTool.tsindex 515e39a272..a47f031bda 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/viewTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/viewTool.ts@@ -1,12 +1,6 @@/**- * The view tool: pan the canvas by dragging, zoom with the wheel. It is the- * default tool and the one the engine temporarily swaps in while space is held.- * All navigation flows through the viewport, so it never mutates the document- * and never dispatches.- *- * Each engine builds its own instance via {@link createViewTool} so the private- * drag state is per-engine (never module-global). Zero React, zero import-time- * side effects.+ * Per-engine view tool pans and zooms through viewport state without document dispatch; also used for temporary+ * Space navigation.*/import type { PointerInput, PointerModifiers, Vec2 } from '@workbench/canvas-engine/types';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.test.tsindex ab9a0d85ec..5b51333dbc 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.test.ts@@ -53,8 +53,7 @@ describe('localHandlePoint', () => {});it('honors an off-origin content rect (content-sized paint layers)', () => {- // A paint layer whose bitmap sits at offset (10, 20): every handle shifts- // by the origin — the frame must wrap the pixels, not [0,w]×[0,h].+ // Off-origin paint at (10,20) shifts every handle to frame actual pixels.const offOrigin: TransformRect = { height: 40, width: 60, x: 10, y: 20 };expect(localHandlePoint(offOrigin, 'nw')).toEqual({ x: 10, y: 20 });expect(localHandlePoint(offOrigin, 'se')).toEqual({ x: 70, y: 60 });@@ -91,9 +90,7 @@ describe('off-origin content rect (content-sized layers)', () => {transform: identity,});expect(corner).toEqual({ handle: 'se', kind: 'scale' });- // A point far from the shifted frame (outside its interior, handles, and- // rotate zones) is NOT a target, even though an (incorrect) origin-anchored- // frame would sit in that direction.+ // Far points must not hit an incorrect origin-anchored frame.const stale = transformTargetAt({point: { x: -40, y: -40 },rect: offOrigin,@@ -165,9 +162,7 @@ describe('transformTargetAt', () => {});it('hits the rotation nub above the top edge (drawn but previously not hit-testable)', () => {- // The nub tip sits `TRANSFORM_ROTATE_NUB_PX` above the top-edge midpoint —- // outside the frame polygon and away from every corner, so before the fix it- // fell through to `null` (misread by the tool as an off-frame press → reset).+ // The visible rotation nub lies outside frame/corners and must not be misread as an off-frame reset.const target = transformTargetAt({point: nubTip(identity, rect, 1),rect,@@ -481,8 +476,6 @@ describe('bakeMatrix', () => {const transform: LayerTransform = { rotation: Math.PI / 6, scaleX: 1.5, scaleY: 0.8, x: 12, y: 34 };const bake = bakeMatrix(transform);const direct = layerTransformMatrix(transform);- // For any local point, drawing the baked surface at identity reproduces the- // transformed point exactly.for (const q of [{ x: 0, y: 0 },{ x: 100, y: 0 },diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.tsindex e2fc0ceffb..80ea399960 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.ts@@ -1,20 +1,7 @@/**- * Pure transform math for the transform tool: handle geometry, screen-space- * hit-testing over a rotated/scaled layer, per-handle rotation-aware cursors, and- * the scale-about-anchor / rotate / move transform derivations.- *- * A layer's raster cache holds unscaled pixels in the layer's LOCAL space; the- * compositor draws it through `fromTRS(transform)` (translate·rotate·scale). The- * transform tool edits that {@link LayerTransform}. All handle positions are- * computed in LOCAL space, mapped to document space via the layer matrix, then- * projected to SCREEN space by the caller-supplied `toScreen` so grab areas stay- * a constant pixel size regardless of zoom (mirrors `bboxHitTest.ts`, generalized- * to a rotated frame). Every derivation returns a fresh transform from a captured- * `start` transform plus a pointer delta — negative scale (a flip past the anchor)- * is allowed and kept correct; `|scale|` is clamped to {@link MIN_ABS_SCALE} so a- * collapsed axis never produces a singular/NaN matrix.- *- * Zero React, zero DOM, zero import-time side effects.+ * Pure transform geometry maps local content through TRS then screen projection for fixed-size hit regions. Derive+ * fresh transforms from gesture-start values; allow negative-scale flips while clamping absolute scale to {@link+ * MIN_ABS_SCALE} to avoid singular matrices.*/import type { CanvasLayerBaseContract } from '@workbench/canvas-engine/contracts';@@ -27,11 +14,8 @@ import { snapMovedPoint } from '@workbench/canvas-engine/math/snapping';export type LayerTransform = CanvasLayerBaseContract['transform'];/**- * The layer's content rectangle in its LOCAL (untransformed) space — the extent- * being transformed. Content-sized layers can sit off-origin (a paint layer's- * persisted offset, negative for strokes up/left of the origin), so the frame,- * handles, and scale/rotate anchors are all derived from this rect, never from- * an assumed `[0,w]×[0,h]`.+ * All frames and anchors derive from local content rects, including negative paint offsets, never assumed+ * origin-zero bounds.*/export interface TransformRect {x: number;@@ -43,10 +27,6 @@ export interface TransformRect {/** The eight scale handles: four corners + four edge midpoints. */export type TransformHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';-/**- * What a pointer landed on over the transform frame: a scale handle, a corner- * rotate zone (just outside a corner), or the interior (`'move'`).- */export type TransformTarget =| { kind: 'scale'; handle: TransformHandle }| { kind: 'rotate'; handle: TransformHandle }@@ -64,11 +44,7 @@ export const TRANSFORM_HANDLE_HIT_PX = 14;/** Radius (screen px) of a corner's rotate zone, measured from the corner outward. */export const TRANSFORM_ROTATE_ZONE_PX = 22;-/**- * Screen-px length of the rotation-indicator nub the overlay draws past the top- * edge midpoint (the `'n'` handle), outward away from the center. Shared with the- * overlay renderer so the drawn nub and its hit region stay in lock-step.- */+/** Screen-pixel rotation-nub length shared by drawing and hit testing. */export const TRANSFORM_ROTATE_NUB_PX = 18;/** Screen-px grab radius around the rotation nub/knob (the capsule half-width). */@@ -207,11 +183,7 @@ export interface TransformHitTestParams {rotateNubHitPx?: number;}-/**- * What a screen-space `point` targets on the transform frame: a scale handle- * (grab area first, corners before edges), a corner rotate zone (outside the- * frame, near a corner), the interior (`'move'`), or `null`.- */+/** Hit priority: scale handles (corners before edges), rotation targets, interior move, then null. */export const transformTargetAt = (params: TransformHitTestParams): TransformTarget | null => {const { point, rect, toScreen, transform } = params;const half = (params.handleHitPx ?? TRANSFORM_HANDLE_HIT_PX) / 2;@@ -230,13 +202,8 @@ export const transformTargetAt = (params: TransformHitTestParams): TransformTargreturn { kind: 'move' };}- // Rotation nub: a capsule from the top-edge (`'n'`) midpoint outward (away- // from center) by `TRANSFORM_ROTATE_NUB_PX`, matching the drawn nub. Tested- // after the interior polygon (so an interior click stays a move) and before- // the corner rotate zones (disjoint regions — a top-middle nub vs corners).- // Without this, a click on the visible nub falls through to `null`, which the- // tool misreads as an off-frame press — re-opening the session (resetting its- // live transform) instead of starting a rotation.+ // Test the outward top-edge nub after interior and before corner rotate zones. Missing this hit would+ // reopen/reset the session instead of rotating.const anchorScreen = screenOf('n');const centerScreen = toScreen(applyToPoint(m, { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }));const outX = anchorScreen.x - centerScreen.x;@@ -264,11 +231,8 @@ export const transformTargetAt = (params: TransformHitTestParams): TransformTargconst RESIZE_CURSORS = ['ew-resize', 'nesw-resize', 'ns-resize', 'nwse-resize'] as const;/**- * The resize cursor for a scale handle, accounting for the layer's rotation:- * the handle's outward normal is rotated/scaled by the layer matrix, then the- * resulting screen-space angle is quantized to one of the four resize- * orientations. (The view adds only a uniform scale — no rotation/flip — so the- * document-space angle equals the screen-space angle.)+ * Rotate/scale the handle normal and quantize its angle to four resize cursors. Uniform nonrotating viewport scale+ * preserves the document angle.*/export const resizeCursorForHandle = (transform: LayerTransform, handle: TransformHandle): string => {const m = layerTransformMatrix(transform);@@ -299,12 +263,8 @@ export const constrainMoveDelta = (delta: Vec2, shift: boolean): Vec2 => {};/**- * Translates `start` by a document-space pointer delta (shift = axis constrain).- *- * A positive `grid` snaps the RESULTING origin to that grid, per axis and only- * for axes the drag moved — an axis that shift has locked carries a zero delta,- * so it passes through exactly rather than being pulled onto a grid line.- * `grid = 0` (the default) leaves the position untouched.+ * Translate by document delta with optional axis lock. Snap only moved axes' resulting origins; grid zero disables+ * snapping.*/export const applyMove = (start: LayerTransform, deltaDoc: Vec2, shift: boolean, grid = 0): LayerTransform => ({...start,@@ -329,15 +289,8 @@ export interface ScaleParams {}/**- * Scales `start` by dragging `handle`, anchored at the opposite handle (or the- * center under `alt`). The grabbed handle tracks the pointer; edge handles scale- * one axis, corners scale both (`shift` forces a uniform, aspect-preserving- * factor). Dragging past the anchor flips the axis (negative scale), which is- * kept correct; each axis is clamped to {@link MIN_ABS_SCALE}.- *- * `grid` snaps where the HANDLE lands in document space (the equivalent of the- * legacy Konva `anchorDragBoundFunc`); the scale factors stay derived from that- * snapped target rather than being rounded themselves, so the anchor never drifts.+ * Scale about opposite handle or Alt center; edges affect one axis, Shift corners preserve aspect. Allow flips+ * with minimum absolute scale. Snap the handle's document target, not scale factors, to preserve the anchor.*/export const applyScale = (p: ScaleParams): LayerTransform => {const { alt, handle, rect, shift, start } = p;@@ -403,11 +356,7 @@ export interface RotateParams {shift: boolean;}-/**- * Rotates `start` about the layer center by the angle the pointer sweeps around- * that center since gesture start. `shift` snaps the resulting absolute rotation- * to 15° increments. Scale is unchanged.- */+/** Rotate around center by pointer angle delta; Shift snaps absolute rotation to 15 degrees without changing scale. */export const applyRotate = (p: RotateParams): LayerTransform => {const { rect, start } = p;const m = layerTransformMatrix(start);@@ -434,12 +383,8 @@ export const applyRotate = (p: RotateParams): LayerTransform => {};/**- * The matrix that renders a layer's local (cache) pixels into a NEW document-space- * surface so that the result, drawn at identity, reproduces the layer as if drawn- * through `transform` — i.e. `fromTRS(transform)`. Used by the paint-layer bake:- * old pixels are drawn through this matrix, the layer transform is then reset to- * identity, and the composite is unchanged. Kept as a named helper so the bake- * site reads intentionally and composes with `math/mat2d`.+ * Bake matrix maps local pixels through TRS into document space, preserving appearance when the layer transform+ * resets to identity.*/export const bakeMatrix = (transform: LayerTransform): Mat2d => layerTransformMatrix(transform);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/types.tsindex 45a39de93b..282d52e4c1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts@@ -1,12 +1,3 @@-/**- * Core types for the canvas engine.- *- * This module is the shared vocabulary for the imperative canvas engine- * (`src/workbench/canvas-engine/`). It has zero React imports and zero- * side effects at import time — it is pure type/interface declarations (the- * single type-only import below is erased at compile time).- */-import type { RasterSurface } from './render/raster';/** A 2D point or vector. */@@ -34,17 +25,7 @@ export interface PlacedSurface {rect: Rect;}-/**- * A 2D affine transform matrix, using the canvas transform convention:- *- * ```- * x' = a*x + c*y + e- * y' = b*x + d*y + f- * ```- *- * This matches `CanvasRenderingContext2D.setTransform(a, b, c, d, e, f)` and- * the DOMMatrix 2D constructor argument order.- */+/** Canvas/DOMMatrix affine order: x' = a*x + c*y + e; y' = b*x + d*y + f. */export interface Mat2d {a: number;b: number;@@ -70,12 +51,7 @@ export type ToolId =| 'text'| 'sam';-/**- * A pixel-selection boolean operation applied when a new lasso path commits- * against the existing selection mask (see `selection/selectionState.ts`):- * `replace` swaps it, `add` unions, `subtract` cuts out, `intersect` keeps the- * overlap.- */+/** Selection operations replace, union, subtract or intersect the existing alpha mask. */export type SelectionOp = 'replace' | 'add' | 'subtract' | 'intersect';/** Modifier key state accompanying a pointer sample. */@@ -102,11 +78,7 @@ export interface PointerInput {timeStamp: number;}-/**- * Describes what needs to be re-rendered on the next frame. Consumers- * (scheduler/compositor, added in later tasks) union flags together rather- * than always doing a full repaint.- */+/** Next-frame render requirements coalesce in the scheduler to avoid unnecessary full repaint. */export interface RenderFlags {/** The viewport transform (pan/zoom) changed. */view: boolean;@@ -117,20 +89,13 @@ export interface RenderFlags {/** Force a full repaint, ignoring the other flags. */all: boolean;/**- * The regions that changed, when every contributing invalidation could name- * one — letting the composite repaint just those pixels instead of the whole- * viewport. `null` means "repaint everything", and is the default: an- * invalidation that does not carry damage widens the frame back to full.+ * Partial damage requires every contributing invalidation to name a region; null/default or any unknown damage+ * forces full repaint.*/damage: LayerDamage[] | null;}-/**- * A changed region, in the LAYER-LOCAL space of `layerId` — the same space a- * layer's cache rect lives in, so a caller that already knows its dirty rect- * (the stroke session does) can report it without knowing the layer's transform.- * The compositor maps it to the screen through that layer's effective matrix.- */+/** Changed region in layer-local coordinates; compositor applies the effective layer matrix to reach screen space. */export interface LayerDamage {layerId: string;rect: Rect;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.test.tsindex 6780a14d2a..0d862e44e8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.test.ts@@ -43,8 +43,7 @@ describe('createViewport', () => {});it('wheelZoom is continuous and does not snap to a preset', () => {- // Zoom used to be captured by a ~3% band around every preset, so a slow- // scroll stalled at each one; a small step must now actually move.+ // Small zoom steps must move instead of sticking inside preset capture bands.const vp = createViewport({ pan: { x: 0, y: 0 }, zoom: 1 });const anchor: Vec2 = { x: 0, y: 0 };@@ -54,8 +53,7 @@ describe('createViewport', () => {});it('wheelZoom crosses a preset instead of parking on it', () => {- // 0.99 sits inside the old ~3% capture band around 1, so a notch used to- // land exactly on the preset. It must now pass straight through.+ // A step from 0.99 must pass through 1x without preset snapping.const vp = createViewport({ pan: { x: 0, y: 0 }, zoom: 0.99 });vp.wheelZoom(-100, { x: 0, y: 0 });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.tsindex 49ed368045..acdec5c162 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.ts@@ -1,30 +1,6 @@/**- * The pan/zoom viewport: the single source of truth for how document space- * maps to the on-screen canvas. It owns `{ pan, zoom }`, the CSS viewport- * size, and the device-pixel ratio, and derives the document→screen- * transform used by both the renderer (device pixels) and pointer routing- * (CSS pixels).- *- * ## Coordinate convention- *- * - **Document space**: the canvas document's own pixel grid, unaffected by- * pan/zoom (a layer at document `(0,0)` is the top-left of the document).- * - **Screen/CSS space**: CSS pixels relative to the canvas element's- * top-left. This is what `PointerEvent.clientX/Y` (minus the element rect)- * gives you. `pan` is stored in CSS pixels.- * - **Device space**: the canvas backing store, `CSS × dpr`. The renderer- * draws here.- *- * The mappings are:- * ```- * screen = zoom * doc + pan (CSS pixels)- * device = dpr * screen = (zoom*dpr) * doc + dpr*pan- * ```- * so `viewMatrix(dpr)` is `scale(zoom*dpr)` followed by a `dpr*pan`- * translation — i.e. `a = d = zoom*dpr`, `e = dpr*pan.x`, `f = dpr*pan.y`.- *- * Zero React, zero import-time side effects; DOM-free (operates on plain- * numbers), so it runs unchanged in node tests.+ * Viewport owns pan, zoom, CSS size and device-pixel ratio. CSS mapping is screen=zoom*document+pan; device+ * mapping multiplies by DPR. Shared transforms keep renderer device pixels and pointer CSS coordinates aligned.*/import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';@@ -104,12 +80,8 @@ export const createViewport = (initial?: Partial<ViewState>): Viewport => {const documentToScreen = (p: Vec2): Vec2 => ({ x: zoom * p.x + pan.x, y: zoom * p.y + pan.y });/**- * Inverts the CSS view transform (`scale(zoom)` then `translate(pan)`)- * directly rather than through a general matrix inverse: the view is only ever- * a uniform scale plus a translation, so the inverse is one subtraction and- * one division. This runs once per coalesced- * pointer sample — a brush batch can carry dozens — which is enough for the- * matrix allocation to be worth skipping.+ * Invert uniform CSS zoom/pan directly with subtraction/division, avoiding matrix allocation for every coalesced+ * pointer sample.*/const screenToDocument = (p: Vec2): Vec2 =>zoom === 0 ? { x: 0, y: 0 } : { x: (p.x - pan.x) / zoom, y: (p.y - pan.y) / zoom };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.tsindex 7be55be79f..132e194746 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts@@ -1,21 +1,7 @@/**- * Uploads canvas paint bitmaps to the backend as persistent, non-gallery- * images. Paint layers reference their pixels by `imageName` (never by URL or- * inline data), so the persisted workbench document — which autosaves to- * localStorage (~5 MB) — stays ref-only and the pixels live server-side.- *- * `image_category='other'` is the canvas's private category: the backend lists- * it in neither `IMAGE_CATEGORIES` nor `ASSETS_CATEGORIES`- * (`image_records_common.py`), so it surfaces in neither gallery view nor in a- * board's counts. That is what hides it — NOT `is_intermediate`, which is a- * separate axis. `is_intermediate=false` is what keeps it durable, and every- * image a layer points at must be durable or garbage collection would strand- * the layer. Transient images no layer will reference (per-generation- * composites) pass `isIntermediate: true` instead.- *- * The `fetch` seam is injectable so this runs in node tests without a DOM.- * Auth + base-URL resolution mirror the shared HTTP client so uploads carry the- * same bearer token as every other authenticated request. Zero React.+ * Persist paint as imageName references. Category other hides pixels from gallery views; is_intermediate=false+ * makes referenced pixels durable. Only unreferenced generation composites are intermediate. Uploads use the+ * shared authentication and base-URL policy.*/import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';@@ -63,11 +49,6 @@ export class CanvasImageUploadError extends Error {}}-/**- * POSTs `blob` as a PNG to `/api/v1/images/upload` (multipart `file` field) and- * returns the server-assigned image name and dimensions. Throws- * {@link CanvasImageUploadError} on any non-success response.- */export const uploadCanvasImage = async (blob: Blob,options: UploadCanvasImageOptions = {}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/canvasImportNotice.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/canvasImportNotice.test.tsindex a127daa00e..adaa8e9b77 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/canvasImportNotice.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/canvasImportNotice.test.ts@@ -51,8 +51,7 @@ describe('getCanvasImportNotice', () => {});it('tells a blocked import apart from one waiting on model capabilities', () => {- // Both are informational and both stop the import, but only one is something the user can- // act on. Sharing a message sent people looking for a canvas operation they never started.+ // Distinguish capability unavailability from an operation the user can finish.expect(getCanvasImportNotice({ status: 'blocked' }).titleKey).toBe('widgets.canvas.import.blocked');expect(getCanvasImportNotice({ status: 'capabilities-unavailable' }).titleKey).toBe('widgets.canvas.import.capabilitiesUnavailable'diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.tsindex ce6d98ae67..1b4a166797 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.ts@@ -430,8 +430,6 @@ describe('executeCompositePlan — raster adjustments baked into generation pixeawait executeCompositePlan(planComposites(plainDoc, BBOX), harness.deps);expect(writeImageData).not.toHaveBeenCalled();- // Adjusted layer: brightness bake → the executor reads the temp, applies the- // LUT, and writes the adjusted pixels back before compositing.const adjustedDoc = makeDoc([rasterLayer('b', {adjustments: [diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.tsindex 1d18f47a02..dc98e27079 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts@@ -1,28 +1,8 @@/**- * The composite-plan executor: turns a {@link CompositePlan} into an uploaded,- * bbox-sized base image plus the geometry the mode detector needs.- *- * This is the impure half of the canvas → generation pipeline (the planner in- * `generation/canvas/compositePlan.ts` is pure). It lives under `canvas-engine`- * and has zero React: every side-effecting dependency (surface allocation,- * layer rasterization, encode, hash, upload) is injected, so it runs in node- * tests against `render/raster.testStub.ts` + a mock uploader — no fetch, no DOM.- *- * For each `base-raster` entry it:- * 1. Composites the entry's enabled raster layers, in z-order, through each- * layer's transform / opacity / blend mode, cropped to the bbox onto a- * bbox-sized surface (following `render/compositor.ts`'s draw model, where- * the "view" is a bbox translate). Layers are rasterized on demand via the- * injected {@link ExecuteCompositePlanDeps.getLayerSurface}.- * 2. Computes `contentBounds` (union of the entry's layer bounds in document- * space) and `bboxFullyCovered` (an alpha scan of the composited surface).- * 3. Encodes → PNG blob → SHA-256, then dedupes: an unchanged plan key reuses- * the previous upload with zero new work, and a changed plan whose pixels- * hash identically reuses the previous upload via the content hash.- *- * Dedupe state lives in a caller-owned {@link CompositeDedupeCache} passed- * through `deps`, so it persists across invokes while the function stays a plain- * `(plan, deps) → result`.+ * Execute a {@link CompositePlan} with injected raster, encoding, hashing, and upload dependencies. Composite+ * enabled layers in z-order through their transforms, opacity, and blend modes into the bbox, then compute+ * document-space bounds and alpha coverage. The caller-owned {@link CompositeDedupeCache} skips unchanged plans+ * and reuses uploads with identical pixel hashes.*/import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';@@ -108,15 +88,13 @@ export interface ExecuteCompositePlanDeps {encodeSurface(surface: RasterSurface, type?: string): Promise<Blob>;};/**- * Ensures a layer's cache is rasterized and returns its surface plus the- * content `rect` (layer-local origin/size) those pixels occupy. The executor- * draws the surface at `rect.origin` (then through the layer transform). The- * engine wires this to its rasterize path; tests return a stub.+ * Return the rasterized surface and its layer-local content rect; drawing applies rect.origin before the layer+ * transform.*/getLayerSurface(layerId: string): Promise<{ surface: RasterSurface; rect: Rect }>;/**- * Uploads a composited blob and resolves to its server image name + dims. The- * engine wires this to `uploadCanvasImage(blob, { isIntermediate: true })`.+ * Upload the composite and return its server name and dimensions; the engine marks generation composites+ * intermediate.*/uploadImage(blob: Blob): Promise<CanvasImageUploadResult>;/** Persistent dedupe state (see {@link CompositeDedupeCache}). */@@ -191,13 +169,8 @@ const setTransform = (ctx: Ctx, m: Mat2d): void => {};/**- * Union of a plan's base-raster content bounds in document space, or `null`- * when the plan has no enabled raster content. Pure geometry (no pixels, no- * upload), so the invoke orchestrator can run it as a bounds-only pre-pass to- * decide txt2img (no bbox overlap) before paying for a composite/encode/upload.- * When `actualLayerRects` is supplied, those detached cache rects replace the- * planner's estimates for sources whose browser metrics can differ from their- * DOM-free extent.+ * Union base-raster bounds in document space, or null without enabled content. This geometry-only pre-pass avoids+ * uploads for txt2img; actualLayerRects replaces estimates with captured browser measurements.*/export const computeCompositeContentBounds = (plan: CompositePlan,@@ -238,12 +211,8 @@ const isFullyOpaque = (imageData: ImageData): boolean => {};/**- * Flattens an RGBA control composite over black. Control adapters consume RGB- * rather than alpha; leaving transparent pixels in the uploaded PNG lets the- * backend's shared channel normalizer matte them over white, which turns an- * erased area into strong control signal. Legacy generation rasterized control- * layers with `bg: 'black'`, so preserve that model-facing contract here while- * editable layer surfaces remain transparent.+ * Flatten control composites over black: backend RGB normalization would otherwise matte erased pixels over white,+ * creating control signal. Editable surfaces retain alpha.*/const flattenControlSurfaceOverBlack = (surface: RasterSurface): void => {const { ctx } = surface;@@ -257,10 +226,8 @@ const flattenControlSurfaceOverBlack = (surface: RasterSurface): void => {};/**- * Composites, scans coverage, encodes, hashes, dedupes, and (when needed)- * uploads a single raster-style entry (`base-raster` or `control-layer`).- * Shared by {@link executeCompositePlan} and {@link executeControlComposite} so- * both go through the identical plan-key + content-hash dedupe path.+ * Share raster composition, coverage scanning, encoding, and plan-key/content-hash upload deduplication between+ * {@link executeCompositePlan} and {@link executeControlComposite}.*/const executeRasterEntry = async (entry: CompositeEntry,@@ -269,8 +236,6 @@ const executeRasterEntry = async (const hashBlob = deps.hashBlob ?? defaultHashBlob;const readImageData = deps.readImageData ?? defaultReadImageData;- // Plan-key hit: nothing that affects these pixels changed — reuse everything,- // no composite, no encode, no upload.const cached = deps.dedupe.byKey.get(entry.key);if (cached) {return {@@ -305,8 +270,6 @@ const executeRasterEntry = async (const blob = await deps.backend.encodeSurface(surface);const pixelHash = await hashBlob(blob);- // Content-hash dedupe: identical pixels (even under a different key) reuse the- // already-uploaded image — no second upload.let upload = deps.dedupe.byHash.get(pixelHash);let reusedUpload = true;if (!upload) {@@ -337,11 +300,6 @@ const executeRasterEntry = async (}};-/**- * Executes `plan`'s base-raster composite: composites, scans coverage, encodes,- * dedupes, and (when needed) uploads. Returns the base image identity plus the- * `contentBounds` / `bboxFullyCovered` facts the mode detector consumes.- */export const executeCompositePlan = async (plan: CompositePlan,deps: ExecuteCompositePlanDeps@@ -357,11 +315,7 @@ export const executeCompositePlan = async (return { base, bboxFullyCovered, contentBounds };};-/**- * Executes a single `control-layer` composite entry (one enabled control layer,- * composited alone over the bbox). Reuses the same dedupe cache as the base- * composite, so an unchanged control layer skips re-upload across invokes.- */+/** Composite one control layer over the bbox; the shared cache avoids re-uploading unchanged controls. */export const executeControlComposite = async (entry: CompositeEntry,deps: ExecuteCompositePlanDeps@@ -370,13 +324,7 @@ export const executeControlComposite = async (return result;};-/**- * Executes a single `regional-mask` composite entry (one enabled regional-guidance- * layer's mask, composited alone over the bbox with its alpha preserved). The- * uploaded image's alpha channel is the region coverage, consumed by- * `alpha_mask_to_tensor`. Reuses the same dedupe cache + raster path as the base- * / control composites, so an unchanged region mask skips re-upload.- */+/** Composite one regional mask with alpha preserved for alpha_mask_to_tensor; share the base/control dedupe cache. */export const executeRegionalMaskComposite = async (entry: CompositeEntry,deps: ExecuteCompositePlanDeps@@ -388,11 +336,8 @@ export const executeRegionalMaskComposite = async (// ---- Grayscale mask composite (inpaint/outpaint) ---------------------------/**- * Converts a mask layer's alpha into legacy grayscale, in place: a masked pixel- * (alpha > 127) becomes `255 - round(255 * attributeValue)` (black at full- * strength), an unmasked pixel becomes white (255); alpha is forced opaque. This- * mirrors `getGrayscaleMaskCompositeImageDTO`'s per-pixel step so multiple masks- * can be darken-composited over a white background (dark = inpaint, white = keep).+ * Convert alpha > 127 to 255 - round(255 * attributeValue), otherwise white, with opaque alpha. Darken-compositing+ * these masks preserves legacy semantics: dark inpaints, white keeps.*/export const toGrayscaleMaskPixels = (imageData: ImageData, attributeValue: number): void => {const { data } = imageData;@@ -490,11 +435,8 @@ const compositeMaskEntry = async (};/**- * Executes a grayscale mask composite entry (`inpaint-mask` / `noise-mask`):- * composites the mask layers into a white-backed grayscale image, scans whether- * any masked region exists, then encodes / dedupes / uploads exactly like the- * base composite. Content-hash + plan-key dedupe reuse the same caller-owned- * cache so an unchanged mask skips re-upload.+ * Composite inpaint/noise masks over white, scan mask coverage, and reuse the caller-owned plan-key/content-hash+ * upload cache.*/export const executeMaskComposite = async (entry: CompositeEntry,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.test.tsindex baaa6e05ac..2f408a6fc7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.test.ts@@ -57,8 +57,7 @@ describe('createCanvasFromImages', () => {expect(result.status).toBe('imported');expect(result.projectId).not.toBe(before);expect(store.getState().activeProjectId).toBe(result.projectId);- // The sizing mutations route the fresh project to the canvas, which is what- // keeps the generate dimensions following the frame.+ // Routing to Canvas makes Generate dimensions follow the new frame.expect(store.getProject(result.projectId!)!.invocation.sourceId).toBe('canvas');const { document } = store.getProject(result.projectId!)!.canvas;expect({ height: document.height, width: document.width }).toEqual({ height: 900, width: 640 });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.tsindex 23b9cf0f57..3b58e11e4f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.ts@@ -1,9 +1,6 @@/**- * "New Canvas from Image": a fresh project whose canvas is sized to the- * images, with each image imported as a raster layer at the origin.- *- * Runs before any canvas widget mounts for the new project, so the import- * always lands through the reducer path of {@link importGalleryImagesToCanvas}.+ * Create an image-sized canvas with raster layers at the origin. Before widgets mount, {@link+ * importGalleryImagesToCanvas} uses its reducer path.*/import type { GalleryImage } from '@features/gallery';@@ -26,8 +23,6 @@ export const createCanvasFromImages = async (options: {return { projectId: null, status: 'empty' };}const created = createProject();- // The document and generation frame both cover the largest image; the- // bbox/generate-size sync then picks the matching generate dimensions.const width = Math.max(...images.map((image) => image.width));const height = Math.max(...images.map((image) => image.height));applyCanvasMutation(created.id, { height, type: 'resizeCanvasDocument', width });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.tsindex 639e13f699..498dac2526 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts@@ -37,12 +37,8 @@ type CreateFromBboxEngine = CanvasCompositeExportEngine & {};/**- * Composites the visible raster layers within the generation bbox, uploads- * the PNG as a canvas-owned image, and either hands the upload back for the- * global-reference flow or creates the destination layer at the bbox origin- * via the shared gallery-import pipeline (which re-checks the document- * captured in `project` against the latest state, covering the export/upload- * window).+ * Upload visible raster content inside the bbox for a global reference or layer at the bbox origin. The shared+ * import pipeline rechecks document identity after export/upload.*/export const createFromBbox = async (options: {applyCanvasMutation: (projectId: string, mutation: CanvasProjectMutation) => boolean | void;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.tsindex d0dfd5524e..83853169d6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts@@ -1,17 +1,6 @@/**- * The engine registry: one {@link CanvasEngine} per project, shared by the- * canvas and layers widgets (and any other surface that needs the same live- * document/pixels).- *- * Acquisition is reference-counted: `getOrCreateEngine` hands out (or creates)- * the instance and bumps the count; `releaseEngine` drops it. When the count- * reaches zero the engine is not disposed immediately — a grace-period timer- * runs first, so a quick unmount/remount (route change, widget re-layout)- * re-acquires the same warm instance instead of paying to rebuild it. A- * re-acquire cancels the pending disposal. The timer is injectable so tests can- * drive it deterministically.- *- * Zero React, zero import-time side effects.+ * Share one engine per project through reference-counted leases. Delay disposal after the last release;+ * reacquisition cancels it so quick remounts reuse the warm engine.*/import type { CanvasEngine as PublicCanvasEngine } from '@workbench/canvas-engine/api';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.tsindex b9f35e96a4..d9dfa0187c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.ts@@ -53,12 +53,7 @@ export const buildFilterDefaults = (definition: FilterDefinition): Record<stringreturn settings;};-/**- * The supported filters, in the legacy display order of the required set- * (`features/controlLayers/store/filters.ts`), plus named presets that improve- * discoverability. Params carry legacy defaults + ranges; a preset may project- * its UI id to a different backend node type.- */+/** Preserve legacy filter order, defaults, and ranges; named presets may map to different backend node types. */export const CONTROL_FILTERS: readonly FilterDefinition[] = [{params: [@@ -324,14 +319,8 @@ export interface FilterGraphResult {}/**- * Builds the single-node filter graph for `filterType` over `imageName`. Throws- * for an unknown filter type. Unknown / out-of-range settings fall back to the- * filter's legacy defaults, so a malformed persisted `filter.settings` still- * produces a valid graph. The output image is INTERMEDIATE (`is_intermediate:- * true`): every preview click runs this graph, and an intermediate output stays- * out of the gallery and is garbage-collected. Only on "Apply" does the caller- * promote the chosen image to durable (`makeImageDurable`), so it survives as- * the layer's new source without every preview littering the gallery.+ * Reject unknown filter types; invalid settings use legacy defaults. Preview outputs are intermediate and+ * collectible; Apply promotes the selected image to durable layer content.*/export const buildFilterGraph = (filterType: string,@@ -453,10 +442,8 @@ export const buildFilterGraph = (filterType !== 'img_blur' &&filterType !== 'spandrel_filter';if (canRestoreSourceAlpha) {- // Most control preprocessors convert RGBA to RGB. Transparent erased pixels- // then become black, producing an opaque black region (and false boundary- // edges). Composite over white before processing, then restore the source- // alpha so the processed control retains the user's erased holes.+ // Process over white to avoid black erased areas and false edges from RGB conversion, then restore the source+ // alpha.delete graph.nodes[FILTER_NODE_ID]!.image;graph.nodes.control_filter_background = {color: { a: 255, b: 255, g: 255, r: 255 },diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterPreferences.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterPreferences.tsindex d93ec3a2b8..6f6a6f9e57 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterPreferences.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterPreferences.ts@@ -2,11 +2,7 @@ import { isSupportedFilterType } from './filterGraphs';const STORAGE_KEY = 'invokeai:v7:webv2:last-filter-type';-/**- * The user's last-chosen filter type, remembered per user. A fresh filter- * operation on a layer without its own filter starts here instead of the- * hard-coded default; unknown or unreadable values fall back silently.- */+/** Remember the last filter per user for layers without one; unknown or unreadable preferences use the default. */export const readLastUsedFilterType = (): string | null => {if (typeof window === 'undefined') {return null;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.tsindex fdbb43753d..11d074dac3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts@@ -155,10 +155,8 @@ interface HostOptions {}/**- * Assembles a fake {@link GenerationCompositeHost} mirroring the widget invoke- * harness: the raster test stub for surfaces, a counting uploader, a spy-able- * release, and a per-call-unique hash so every distinct composite entry uploads- * (plan-key dedupe still reuses across calls).+ * Use raster stubs and unique per-call hashes so distinct entries upload while plan-key dedupe still reuses+ * unchanged plans.*/const makeHost = (document: CanvasDocumentContractV3, options: HostOptions = {}): HostHarness => {const stub = createTestStubRasterBackend();@@ -310,8 +308,7 @@ describe('composeForGeneration', () => {});it('resolves txt2img from the bounds pre-pass: no base upload, detectMode never consulted, controls and regionals still composited', async () => {- // No raster layers → no content bounds → txt2img without executing the base- // plan; control + regional composites are mode-independent and still run.+ // No raster bounds means txt2img without a base composite; control and regional composites still run.const harness = makeHost(makeDoc([controlLayer('control-a'), regionalLayer('region-a')]));const detectMode = vi.fn(() => 'img2img' as const);@@ -418,8 +415,7 @@ describe('composeForGeneration', () => {const result = await compose(harness.host, { detectMode });- // Base upload, then the inpaint-mask upload, then (and only then) the mode- // strategy — the mask's coverage is one of its inputs.+ // Upload the inpaint mask before mode detection because coverage determines the mode.expect(harness.events).toEqual(['upload:composite-1.png', 'upload:composite-2.png', 'detectMode']);expect(detectMode).toHaveBeenCalledWith(expect.objectContaining({ hasActiveInpaintMask: true }));expect(result.status).toBe('ok');@@ -447,8 +443,7 @@ describe('composeForGeneration', () => {if (result.status !== 'ok') {return;}- // Base upload + the region-driven inpaint-mask upload; the mask composite- // read the raster layer's own surface — the mask IS the layer content.+ // The region-driven inpaint mask uses the raster layer's own content alpha.expect(result.composites.mode).toBe('inpaint');expect(result.composites.maskImageName).toBe('composite-2.png');expect(harness.surfaceIds).toContain('base');@@ -467,8 +462,7 @@ describe('composeForGeneration', () => {])('composites the noise mask only for inpaint/outpaint ($mode)',async ({ expectedMask, expectedNoise, expectedUploads, mode }) => {- // The inpaint mask defines a noiseLevel, so the plan carries a noise-mask- // entry — it must execute only when the resolved mode consumes it.+ // Only modes consuming noise may execute the planned noise mask.const harness = makeHost(makeDoc([rasterLayer('base'), inpaintMaskLayer('mask', 0.5)]));const result = await compose(harness.host, { detectMode: () => mode });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.tsindex da571ff4b2..b0487750eb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts@@ -1,32 +1,8 @@/**- * The composite-generation operation: one deep call that turns the live canvas- * into every uploaded image a canvas invoke needs.- *- * `composeForGeneration` owns the whole snapshot → plan → capture → composite- * protocol that callers previously drove step by step through- * `CanvasCompositeTransaction`: it captures the document snapshot, plans the- * base / mask / control / regional composites, detaches the required layer- * surfaces, runs a bounds-only pre-pass (content that does not overlap the bbox- * is txt2img — no base composite, no upload, and the mode strategy is never- * consulted), executes the base composite + grayscale masks + per-layer control- * and regional-mask composites, and releases the raster snapshot in a `finally`- * on both success and failure. Pixels, surfaces, dedupe caches, and memory- * reservations never cross the seam.- *- * Caller-owned policy enters as three strategies on the options:- * - `detectMode` maps composite facts to a generation mode. It is called at- * most once, and only when raster content overlaps the bbox.- * - `shouldCompositeControlLayer` vets each planned control layer in z-order:- * `false` skips the layer (no upload); a **throw aborts the whole operation**- * (the snapshot is released, no dedupe entry is committed, and the error is- * rethrown to the caller).- * - `shouldCompositeRegionalMask` vets each planned regional-guidance layer in- * z-order: `false` silently skips the region (no upload).- *- * Successful composition returns one opaque, idempotent dedupe commit. The- * caller publishes it only after graph compilation and synchronous queue- * dispatch both succeed; every earlier failure discards the operation-local- * cache while the uploaded intermediates remain safe to retry.+ * Own snapshot, planning, capture, and all generation composites; always release captured rasters. No bbox overlap+ * means txt2img without base upload or mode detection. detectMode runs at most once; control/regional predicates+ * skip rejected layers, while thrown errors abort without committing dedupe. Return an idempotent dedupe commit+ * for publication only after graph compilation and synchronous queue dispatch succeed.*/import type {@@ -58,10 +34,8 @@ import {} from '@workbench/canvas-operations/generationCompositePlan';/**- * The generation mode a composite resolves to. Structural mirror of- * generation's `CanvasGenerationMode` — canvas-operations must not import the- * feature, and tsc guards drift in both directions at the caller's `detectMode`- * wiring.+ * Mirror CanvasGenerationMode without importing the feature; caller wiring checks compatibility in both+ * directions.*/export type GenerationCompositeMode = 'txt2img' | 'img2img' | 'inpaint' | 'outpaint';@@ -102,11 +76,6 @@ export interface ComposeForGenerationOptions {/** The engine-side executor dependencies the host supplies (dedupe + surfaces are operation-owned). */export type GenerationCompositeExecutorDeps = Omit<ExecuteCompositePlanDeps, 'dedupe' | 'getLayerSurface'>;-/**- * The engine seam {@link composeForGeneration} runs against. Production wiring- * lives in `createCanvasEngine`; tests assemble a fake host over- * `render/raster.testStub` + a mock uploader.- */export interface GenerationCompositeHost {/** Captures the current document snapshot, or `null` without an active document. */captureDocumentSnapshot(): CanvasDocumentSnapshot | null;@@ -199,9 +168,7 @@ export const composeForGeneration = async (}const rasterSnapshot = capture.snapshot;- // A test/fallback host may resolve capture despite an already-aborted signal;- // preserve the no-pixel-output guarantee and release that caller-owned- // snapshot before returning.+ // Release captures returned after abort, preserving the no-pixel-output guarantee.if (options.signal.aborted) {rasterSnapshot.release();return { status: 'aborted' };@@ -235,13 +202,8 @@ export const composeForGeneration = async (};try {- // Bounds-only pre-pass (pure geometry, no upload): content that does not- // overlap the bbox is txt2img no matter the coverage. Also naturally skips a- // zero-area bbox (`intersect` is null for empty rects). `intersect`'s strict- // overlap matches generation's `rectsIntersect` (flush edges don't count).- // The planner uses a DOM-free text extent estimate. Once capture has run,- // the detached surfaces provide actual measured rects, so a wide loaded- // font cannot be omitted from generation because its estimate was narrow.+ // Use captured rects, including measured text, for the bounds-only overlap check. Empty boxes and touching+ // edges do not overlap and need no base upload.const actualLayerRects = new Map<string, Rect>();for (const [layerId, detached] of rasterSnapshot.layerSurfaces) {actualLayerRects.set(layerId, detached.rect);@@ -257,10 +219,8 @@ export const composeForGeneration = async (const result = await executeCompositePlan(plan, deps);baseImageName = result.base.imageName;- // The grayscale denoise-limit mask (when enabled inpaint masks exist) both- // decides inpaint-vs-img2img (its coverage) and feeds the graph — it must- // execute BEFORE the mode strategy runs. Legacy parity: raster opaque +- // mask has content → inpaint; else img2img.+ // Composite the denoise-limit mask before mode detection: even opaque raster content becomes inpaint when+ // the mask has coverage.const maskEntry = plan.entries.find((entry) => entry.kind === 'inpaint-mask');const maskResult = maskEntry ? await executeMaskComposite(maskEntry, deps) : null;@@ -282,9 +242,7 @@ export const composeForGeneration = async (}}- // Control layers apply in every mode, independent of the base composite —- // composite each accepted layer regardless of whether raster content- // overlaps. Each layer is composited SEPARATELY (never blended).+ // Composite each accepted control separately in every mode, regardless of base-raster overlap.const controlImages: { layerId: string; imageName: string }[] = [];for (const { entry, layerId } of controlPlan) {const layer = lookupDocumentLayer(document, layerId);@@ -298,8 +256,7 @@ export const composeForGeneration = async (controlImages.push({ imageName: result.imageName, layerId });}- // Regional guidance also applies in every mode — each accepted region's- // mask is composited separately (its alpha feeds its own tensor).+ // Composite each accepted regional alpha mask separately in every mode.const regionalMaskImages: { layerId: string; imageName: string }[] = [];for (const { entry, layerId } of regionalPlan) {const layer = lookupDocumentLayer(document, layerId);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.tsindex 0892f75ced..517753bf4e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.ts@@ -207,9 +207,7 @@ describe('planComposites — plan shape', () => {});it('excludes an empty (bitmap: null) paint layer so it cannot force outpaint', () => {- // An auto-created paint layer left blank (e.g. its stroke was undone) carries- // no pixels; including it would inject a doc-sized transparent rect that reads- // as outpaint. It must not appear among the base-raster contributors.+ // Exclude blank paint layers: their transparent document-sized bounds would falsely imply outpaint.const doc = makeDoc([rasterLayer('img', { source: { image: imageRef('pic'), type: 'image' } }),rasterLayer('blank', { source: { bitmap: null, type: 'paint' } }),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.tsindex be1dd38e08..21d2d0362c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.ts@@ -79,11 +79,8 @@ const isInpaintMaskWithContent = (layer: CanvasLayerContract): layer is CanvasInlayer.type === 'inpaint_mask' && layer.mask.bitmap !== null;/**- * A raster layer whose regenerate region is enabled and whose source can both- * hold pixels and rasterize: the layer's OWN content alpha joins the inpaint- * mask. Invoke flushes paint uploads before planning, so a stroked layer always- * carries its bitmap; a pointless polygon shape has no raster and would fail- * the snapshot capture, so it never enters the plan.+ * Regenerate regions use their raster layer's own alpha. Include only pixel-bearing, rasterizable sources; paint+ * uploads flush before planning.*/const isRegionRasterWithContent = (layer: CanvasLayerContract): layer is CanvasRasterLayerContractV2 =>layer.type === 'raster' &&@@ -99,12 +96,7 @@ const stableSourceKey = (value: unknown): string =>: entry);-/**- * A region ref's pixel-identity fragment. Unlike the base plan — where- * parametric sources never reach a dedupe key — a region can sit on a text,- * shape, or gradient layer, so their pixel-determining fields must be part of- * the key or an edited layer would reuse the previous mask upload.- */+/** Include text, shape, and gradient pixel parameters in region keys so edits invalidate mask uploads. */const regionSourceRef = (source: CanvasLayerSourceContract): string => {switch (source.type) {case 'image':@@ -202,16 +194,9 @@ const deriveMaskKey = (kind: string, bbox: Rect, layers: CompositeMaskLayerRef[]`${kind}|${rectKey(bbox)}|${layers.map(maskLayerKey).join('|')}`;/**- * Plans the composites required to invoke `document` over `bbox`:- * - one `base-raster` entry (the initial image);- * - one `inpaint-mask` entry (grayscale denoise-limit mask) when enabled inpaint- * masks with content exist — an absent OR DISABLED `denoise` modifier resolves- * to the legacy default (1.0, full denoise) — or when a contributing raster- * layer carries an enabled regenerate region (its own content alpha joins the- * mask at full denoise);- * - one `noise-mask` entry when at least one such mask carries an ENABLED- * `noise` modifier (absent and disabled are equivalent, mirroring legacy —- * they must NOT be treated as noise 0). Regions never add noise.+ * Plan a base raster plus inpaint masks with content. Missing/disabled denoise means full denoise; enabled+ * regenerate regions add their own alpha at full denoise. Add a noise mask only for enabled noise modifiers;+ * absent/disabled noise is not zero, and regions add none.*/export const planComposites = (document: CanvasDocumentContractV3, bbox: Rect): CompositePlan => {const entries: CompositeEntry[] = [planBaseRasterComposite(document, bbox)];@@ -271,11 +256,8 @@ const controlContentRect = (};/**- * Projects a control layer into a standalone composite contribution. Opacity is- * forced to 1 and blend mode to `normal` (the layer's DISPLAY opacity/blend and- * transparency effect never alter the control image sent to the backend — legacy- * rasterizes control at opacity 1, no filters), so display tweaks don't churn the- * entry key.+ * Force control contributions to opacity 1 and normal blend; display opacity, blend, and transparency effects must+ * not affect backend pixels or dedupe keys.*/const toControlLayerRef = (layer: CanvasControlLayerContract, doc: CanvasDocumentContractV3): CompositeLayerRef => {const rect = controlContentRect(layer, doc);@@ -303,12 +285,8 @@ export interface ControlCompositeEntry {}/**- * Plans one composite per enabled control layer WITH content — each composited- * separately over `bbox` (legacy parity: control images are never blended- * together). Empty control layers (no source / blank paint) are excluded (they- * carry no control content and are rejected upstream with a "no control" reason).- * Control layers never contribute to the `base-raster` composite, so they never- * paint into the img2img/inpaint source.+ * Plan separate bbox composites for enabled controls with content. Never blend controls together or include them+ * in base-raster content.*/export const planControlComposites = (document: CanvasDocumentContractV3, bbox: Rect): ControlCompositeEntry[] =>contributingLayers(document, isControlLayerWithContent).map((layer) => {@@ -338,11 +316,8 @@ const regionalMaskContentRect = (};/**- * Projects a regional-guidance layer into a standalone ALPHA composite- * contribution (opacity 1, normal blend) — the executor composites the mask's- * alpha coverage over the bbox and uploads it, so `alpha_mask_to_tensor` can read- * the region's alpha. Display opacity/blend never alter the mask sent to the- * backend (mirrors control layers).+ * Use opacity 1 and normal blend for regional alpha masks; display settings must not affect alpha_mask_to_tensor+ * input.*/const toRegionalMaskRef = (layer: CanvasRegionalGuidanceLayerContract): CompositeLayerRef => {const rect = regionalMaskContentRect(layer);@@ -370,11 +345,8 @@ export interface RegionalMaskCompositeEntry {}/**- * Plans one alpha-mask composite per enabled regional-guidance layer WITH mask- * content — each composited separately over `bbox` (a region's mask feeds its own- * `alpha_mask_to_tensor`; regions are never combined). Regions without mask- * content carry no region and are skipped (they'd be rejected upstream with a- * "no region" reason). Regional layers never contribute to `base-raster`.+ * Plan separate alpha masks for enabled regions with content; omit empty regions and exclude all regions from+ * base-raster.*/export const planRegionalMaskComposites = (document: CanvasDocumentContractV3,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.tsindex b8c7f985a3..f7562b68cd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts@@ -627,9 +627,8 @@ describe('importGalleryImagesToCanvas', () => {it('does not upload an old account image after local preprocessing crosses an account switch', async () => {accountLifecycle.activate('user-a');- // Activating an account drops the capability table with the rest of the previous account's- // state; the app reloads it for the incoming one. Resized imports are refused without it, and- // this test is about the account fence, not that gate.+ // Reseed capabilities after the account reset so this test reaches the account fence rather than the resize+ // gate.setArchitectureCapabilities(architectureCapabilitiesFixture);const { project, state } = withProject();let resolveFetch: ((response: Response) => void) | undefined;@@ -739,9 +738,7 @@ describe('importGalleryImagesToCanvas', () => {describe('importGalleryImagesToCanvas with a table that does not describe the architecture', () => {it('refuses a resized import rather than uploading at fallback dimensions for that model', async () => {- // A backend build that has no row for the project's architecture answers with the same fallback- // 1024 / grid 8 for that one model as a missing table does for all of them, and the upload is- // just as irreversible.+ // A missing architecture row produces the same unsafe resize defaults as a missing table.const { project, state } = withProject((value) => setModel(value, 'sd-1'));const fetchImage = vi.fn<typeof fetch>();const uploadImage = vi.fn<typeof uploadCanvasImage>();@@ -766,10 +763,8 @@ describe('importGalleryImagesToCanvas with a table that does not describe the ardescribe('importGalleryImagesToCanvas before the capability table arrives', () => {it('refuses a resized import rather than uploading at fallback dimensions', async () => {- // The resize target is the model's native size and grid, and this is the one import path whose- // mistake cannot be taken back: the asset is uploaded and becomes a layer. With no table every- // architecture reads as 1024 / grid 8, so an SD-1 project would upload four times the area it- // asked for. Nothing re-derives it afterwards.+ // Require native size/grid policy before the irreversible resize upload; fallback dimensions would persist the+ // wrong asset.const { project, state } = withProject((value) => setModel(value, 'sd-1'));const fetchImage = vi.fn<typeof fetch>();const uploadImage = vi.fn<typeof uploadCanvasImage>();@@ -786,8 +781,7 @@ describe('importGalleryImagesToCanvas before the capability table arrives', () =uploadImage,});- // Its own status, not 'blocked' -- that one tells the user to finish an operation they- // did not start, and gives them nothing to act on.+ // Use a distinct status: blocked incorrectly asks the user to finish an operation.expect(result).toEqual({ status: 'capabilities-unavailable' });expect(fetchImage).not.toHaveBeenCalled();expect(uploadImage).not.toHaveBeenCalled();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.tsindex 9be6abcad6..6416ea9a34 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts@@ -279,13 +279,8 @@ export const importGalleryImagesToCanvas = async (options: {let layerImages: readonly LayerImage[] = images;let failedImageNames: string[] = [];if (destination === 'control-resized') {- // The resize target is the model's native size and grid, and this is the one import path- // whose mistake is irreversible: the resized asset is uploaded to the server and becomes a- // layer. Without the table `getGenerationDimensions` answers 1024 / grid 8 for every- // architecture, so an SD-1 project would upload four times the area it asked for and a- // CogView 4 project an off-grid layer. Refuse instead, the way the Invoke gate does -- also- // when the table is there but has no row for the selected architecture, which is the same- // fallback answer for that one model.+ // Refuse resize uploads without policy for the selected architecture: fallback size/grid would persist an+ // incorrectly sized asset that cannot be re-derived later.const targetModel = normalizeGenerateWidgetValues(getProjectWidgetValues(project, 'generate'))?.model;if (getArchitectureCapabilitiesSnapshot().revision === 0 ||@@ -344,8 +339,7 @@ export const importGalleryImagesToCanvas = async (options: {return { status: 'blocked' };}} else {- // No live editing session — a background project, or the active project- // with its canvas closed — so the import lands as ingestion.+ // Without a live canvas session, import through ingestion.applyCanvasMutation(project.id, forward);}return { failedImageNames, layerIds: layers.map((layer) => layer.id), status: 'imported' };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.tsindex 87d90c080a..c189c829c6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts@@ -34,9 +34,7 @@ const buildCanvasSaveMetadata = (project: Project, rect: Rect): Record<string, ureturn dimensions;}- // The merged prompts, matching what a generated image's `core_metadata` records.- // A saved canvas is recalled through the same path, so the two must agree or- // recalling from a saved image would restore different text.+ // Save merged prompts to match generated core_metadata and restore identical text on recall.const effectivePrompts = getEffectivePrompts(generateValues);return {diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.tsindex 207f4689cb..c9758606fe 100644--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts@@ -74,9 +74,7 @@ describe('reconcileCanvasDims (pure)', () => {prev: snapshot(1024, 1024, 1024, 1024),});- // 4:3 as an id, but the numeric ratio must agree so downstream constraint- // math (GenerateDimensionFields' getActiveRatio) uses the fresh ratio- // instead of a stale 1.0 left over from the previous (square) dims.+ // Update the numeric ratio too; getActiveRatio prefers it over the aspect id.expect(result).toMatchObject({ aspectRatioId: '4:3', aspectRatioValue: 1024 / 768, kind: 'patch-dims' });});@@ -285,10 +283,7 @@ describe('createCanvasDimsSync (wiring)', () => {expect(values.width).toBe(512);expect(values.height).toBe(768);expect(values.aspectRatioId).toBe('2:3');- // The numeric ratio must be re-derived alongside the id, or downstream- // constraint math (GenerateDimensionFields' getActiveRatio, which prefers- // aspectRatioValue whenever it is > 0) keeps constraining edits to the- // stale ratio from before the bbox drag.+ // Re-derive numeric aspectRatioValue because downstream constraints prefer it over the id.expect(values.aspectRatioValue).toBeCloseTo(512 / 768);// Exactly one sync dispatch (the echo is a no-op, so no unbounded loop).expect(getSyncDispatches()).toBe(1);@@ -340,8 +335,6 @@ describe('createCanvasDimsSync (wiring)', () => {const nextWidth = 800;const constrainedHeight = nextWidth / activeRatio;- // Before the fix this would divide by the stale ratio (1.0, from the- // original 1024x1024 dims) and yield the wrong height (800 instead of 600).expect(constrainedHeight).toBeCloseTo(600);sync.dispose();});@@ -368,9 +361,7 @@ describe('createCanvasDimsSync (wiring)', () => {dispatchCanvas(store, { bbox: { height: 1024, width: 1024, x: 32, y: 48 }, type: 'setCanvasBbox' });const before = getSyncDispatches();- // 501 is not a multiple of the sdxl grid (8): dims -> bbox must snap it,- // then write the valid value back to the dimensions. The re-entrancy guard- // must keep those two bounded system writes from echoing indefinitely.+ // Off-grid input requires a bbox snap and dimension echo; re-entry must keep those writes bounded.store.commands.generation.patchSettings({ width: 501 });const { bbox: nextBbox, values } = getActiveGenerate(store.getState());@@ -488,8 +479,7 @@ describe('createCanvasDimsSync before the capability table arrives', () => {};it('reconciles an external generator at once, which will never get a row to wait for', () => {- // Holding off on `null` is right for an architecture the backend will describe. An external- // provider has no row coming, so waiting would leave its canvas sync off for the whole session.+ // External providers never receive a capability row, so waiting would disable sync permanently.const externalModel = {base: 'external',capabilities: { modes: ['txt2img'], supports_seed: true },@@ -517,9 +507,7 @@ describe('createCanvasDimsSync before the capability table arrives', () => {});it('writes nothing into the project while the architecture has no answer', () => {- // Reopening a saved canvas project: `prev` is null, so the bbox wins and the dims are patched- // and persisted. With no table the grid reads as 8, which is a real answer for SDXL and a guess- // for Wan -- and Wan's denoise node rejects anything but multiples of 16.+ // First-run bbox reconciliation persists dimensions; guessing grid 8 is invalid for Wan's grid 16.const { getSyncDispatches, store, sync } = setupWanProject();expect(getSyncDispatches()).toBe(0);@@ -528,9 +516,7 @@ describe('createCanvasDimsSync before the capability table arrives', () => {});it('reconciles as soon as the table lands, with no other change to the project', () => {- // The gap this closes: nothing else moves when the table arrives -- the widget's own resolver- // produces no patch for an already-consistent project -- so this listener has to hear about the- // table itself or the wrong dimensions stay persisted.+ // Capability arrival alone must retrigger sync; an otherwise consistent project emits no workbench change.const { getSyncDispatches, store, sync } = setupWanProject();setArchitectureCapabilities(architectureCapabilitiesFixture);diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.tsindex 0942ea667f..eadac1740d 100644--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts@@ -1,37 +1,8 @@/**- * Two-way sync between a project's canvas generation frame (`canvas.document.bbox`)- * and its model-valid generate-widget processing dimensions (`width` / `height` /- * `aspectRatioId`).- *- * Legacy-compatible geometry: the generation frame remains the exact final- * canvas footprint, including off-grid sizes. Resizing the bbox (tool gesture,- * the frame form, undo/redo) drives width/height snapped to the selected model's- * hard processing grid; the canvas graph resizes inputs to that processing size- * and the result back to the bbox. The optional "Scale before processing"- * policy (`resolveCanvasProcessingSize`) applies only at submit and never- * touches the dimensions synced here. Editing the generate dimensions (or picking an aspect preset)- * still resizes the bbox in place (top-left anchored). Position-only bbox moves- * never touch the dimensions.- *- * The module is two parts:- * - {@link reconcileCanvasDims}: a pure, unit-tested reconcile that decides which- * side (if any) to write, given the current bbox, the current committed- * generate dims, the snapping grid, and the last-synced snapshot.- * - {@link createCanvasDimsSync}: a thin `store.subscribe` wiring that feeds the- * reconcile from workbench state and dispatches the resulting action. It also- * subscribes to the architecture capability table, because the grid is- * generation policy that arrives over the network rather than workbench state,- * and both directions of this sync are persisted.- *- * Loop safety: the reconcile short-circuits to `none` whenever the bbox and dims- * already agree, so applying either direction is a fixed point. The wiring also- * updates its last-synced snapshot *before* dispatching and hard-guards against- * re-entrant notifications, keeping the dispatch count per external change- * bounded (at most one echo, which is itself a no-op).- *- * Only active while `project.invocation.sourceId === 'canvas'`; for every other- * source the sync is inert and generate-dimension editing behaves exactly as it- * does today. Zero React.+ * Sync only for Canvas sources. Bbox edits retain the exact footprint and derive model-grid processing dimensions;+ * Generate edits resize the bbox at its top-left. Position-only changes and submit-only scaling do not+ * participate. Capability changes retrigger reconciliation; update the expected snapshot before dispatch and guard+ * re-entry.*/import type { AspectRatioId } from '@features/generation/contracts';@@ -71,11 +42,8 @@ export interface CanvasDimsReconcileInput {export type CanvasDimsReconcileResult =| { kind: 'none' }/**- * Write a model-grid processing size onto the generate dims (bbox wins),- * retaining the exact bbox ratio in the aspect controls. Both aspect values- * are re-derived from the bbox unconditionally (even when the form's ratio is- * locked to a preset) so a locked preset does not veto the bbox, which remains- * authoritative.+ * Bbox authority overrides locked aspect presets; derive both aspect values from the exact bbox while snapping+ * processing dimensions.*/| { kind: 'patch-dims'; width: number; height: number; aspectRatioId: AspectRatioId; aspectRatioValue: number }/** Resize the bbox to the (grid-snapped) generate dims, keeping its top-left position. */@@ -101,15 +69,8 @@ const createSnapshot = (});/**- * Decide which direction of the bbox <-> dims sync to apply.- *- * - No bbox (not in canvas mode) -> `none`.- * - A grid-valid bbox and dims that already agree -> `none` (the primary loop guard).- * - Otherwise the side that changed since `prev` wins; the bbox is authoritative- * when both (or neither, on first run) changed. Bbox -> dims writes the nearest- * model-grid processing size while preserving the exact bbox footprint and- * aspect. Dims -> bbox snaps to the grid and only emits when the snapped size- * actually differs from the live bbox.+ * The changed side wins; bbox wins on first run or simultaneous changes. Write model-grid dimensions without+ * changing its exact footprint, and skip already-consistent state.*/export const reconcileCanvasDims = ({bbox,@@ -179,8 +140,7 @@ const readModelBase = (values: Record<string, unknown>): string | null => {: null;};-// The grid is variant-dependent -- Wan TI2V-5B enforces 32 where A14B enforces 16 -- and this-// path persists what it reconciles, so it has to ask with the variant.+// Use the model variant because its grid can differ and reconciled dimensions are persisted.const readModelVariant = (values: Record<string, unknown>): string | null => {const model = values.model;return model && typeof model === 'object' && typeof (model as { variant?: unknown }).variant === 'string'@@ -188,20 +148,13 @@ const readModelVariant = (values: Record<string, unknown>): string | null => {: null;};-/**- * Wire the bbox <-> generate-dims reconcile onto a workbench store. Subscribes- * immediately; dispatches `patchGenerateSettings` / `setCanvasBbox` as the- * reconcile directs. Returns a handle whose `dispose` removes the subscription.- */export const createCanvasDimsSync = (store: CanvasDimsSyncStore): CanvasDimsSync => {let prev: CanvasDimsSnapshot | null = null;let lastProjectId: string | null = null;let isSyncing = false;const handleChange = (): void => {- // A dispatch below re-enters this listener synchronously; the snapshot is- // already updated to the post-dispatch expectation, so the nested pass would- // be a no-op — skip it to keep the dispatch count strictly bounded.+ // Dispatch synchronously re-enters this listener; skip the nested pass to bound writes.if (isSyncing) {return;}@@ -220,8 +173,6 @@ export const createCanvasDimsSync = (store: CanvasDimsSyncStore): CanvasDimsSyncprev = null;}- // Inert unless the project is invoking into the canvas: for every other- // source the generate dimensions behave exactly as they do today.if (project.invocation.sourceId !== 'canvas') {prev = null;return;@@ -239,10 +190,8 @@ export const createCanvasDimsSync = (store: CanvasDimsSyncStore): CanvasDimsSyncconst bbox = project.canvas.document.bbox;const grid = resolveModelGrid(readModelBase(generateValues), readModelVariant(generateValues));- // Nothing is written until the backend has answered for this architecture. Both writes below- // are `patchSettings` / `setCanvasBbox` on the project, so reconciling against a fallback grid- // would *persist* an off-grid width/height for a base whose denoise node rejects it -- and the- // capability subscription below is what brings this listener back once the answer lands.+ // Wait for backend capabilities before persisting dimensions; a fallback grid may be invalid for this+ // architecture.if (grid === null) {prev = null;return;@@ -285,9 +234,7 @@ export const createCanvasDimsSync = (store: CanvasDimsSyncStore): CanvasDimsSync};const unsubscribeStore = store.subscribe(handleChange);- // The grid is generation policy, not workbench state, and it arrives over the network after this- // runtime is constructed. A project that is already consistent produces no workbench-store change- // when the table lands, so without this the gate above would never be re-entered.+ // Capability arrival may not change workbench state, so subscribe directly to retry the gated reconciliation.const unsubscribeCapabilities = subscribeArchitectureCapabilities(handleChange);// Seed from the current state so an already-canvas project reconciles on mount.diff --git a/invokeai/frontend/webv2/src/workbench/canvasInvocationPreparation.ts b/invokeai/frontend/webv2/src/workbench/canvasInvocationPreparation.tsindex 72c9ca0224..e4681e23f4 100644--- a/invokeai/frontend/webv2/src/workbench/canvasInvocationPreparation.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasInvocationPreparation.ts@@ -16,10 +16,8 @@ const store = createExternalStoreCore<CanvasInvocationPreparationSnapshot>({ lealet nextLeaseToken = 1;/**- * Acquires the user-facing canvas preparation slot before any asynchronous- * module loading, prompt expansion, persistence, compositing, or upload begins.- * The deeper canvas orchestrator keeps its own guard for non-active entry- * points; this one owns the Ctrl+Enter/topbar acknowledgement window.+ * Acquire the active-submit acknowledgement before any async work; the Canvas orchestrator separately guards other+ * entry points.*/export const beginCanvasInvocationPreparation = (projectId: string): CanvasInvocationPreparationLease | null => {const { leases } = store.getSnapshot();@@ -37,9 +35,7 @@ export const beginCanvasInvocationPreparation = (projectId: string): CanvasInvocexport const endCanvasInvocationPreparation = (lease: CanvasInvocationPreparationLease): void => {const { leases } = store.getSnapshot();- // Account invalidation clears every lease synchronously. If an old async- // submission settles after a new account/project acquired the same id, its- // stale token must not release the new owner's acknowledgement.+ // After account invalidation, an old submission token must not release a new owner's lease for the same id.if (leases.get(lease.projectId) !== lease.token) {return;}diff --git a/invokeai/frontend/webv2/src/workbench/canvasLayerContent.ts b/invokeai/frontend/webv2/src/workbench/canvasLayerContent.tsindex b3c057634e..a6e7e2bede 100644--- a/invokeai/frontend/webv2/src/workbench/canvasLayerContent.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasLayerContent.ts@@ -5,17 +5,8 @@ import type {} from '@workbench/canvas-engine/api';/**- * The single source of truth for "does this layer carry pixels the generation- * pipeline will actually use".- *- * Both the composite planner (which decides what reaches the backend) and the- * invoke readiness checks (which decide what the user is told) gate on these- * predicates. They used to be two hand-maintained copies; a desync there means- * readiness silently disagrees with what the graph does — a layer reported ready- * but dropped from the composite, or vice versa.- *- * Depends only on layer contracts, so the pure planner can import it without- * pulling in models, graph, or React.+ * Shared pixel-content predicates for composite planning and invocation readiness; depends only on layer+ * contracts.*//** True when a control layer holds an image source or committed paint pixels. */diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.tsindex eda20d9360..fbd32d1fce 100644--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts@@ -234,8 +234,7 @@ const zCanvasLayer = z.discriminatedUnion('type', [zLayerBase.extend({adapter: zControlAdapter,filter: zFilter.optional(),- // Display-only visibility; absent ⇒ not hidden, so older documents load- // unchanged. Only the three overlay types carry it — see `contracts.ts`.+ // Missing display-only visibility means visible for older documents; only overlay types carry it.isHidden: z.boolean().optional(),source: zLayerSource,type: z.literal('control'),@@ -317,11 +316,7 @@ export const createEmptyCanvasDocument = (version: 3,});-/**- * A brand-new project's default inpaint mask: one empty mask with the default diagonal-hatch fill- * in the first cycled mask colour. Mirrors `createInpaintMaskLayer` in `widgets/layers/layerOps`,- * duplicated so this pure module does not pull in the panel module graph.- */+/** Mirror the default inpaint mask without importing the Layers panel into this pure module. */const createInitialInpaintMaskLayer = (): CanvasInpaintMaskLayerContract => ({blendMode: 'normal',id: createMigrationId('layer'),@@ -373,10 +368,6 @@ export const canvasDocumentRequiresFontSchemaV4 = (document: Pick<CanvasDocumentconst writableDocumentVersion = (declaredVersion: unknown, stacks: CanvasStackForests): 3 | 4 =>declaredVersion === 4 || canvasDocumentRequiresFontSchemaV4({ stacks }) ? 4 : 3;-/**- * Converts a `{x,y,width,height}` placement rect, plus the native size of the image it places,- * into a layer `transform`. Used by the "accept staged image into a raster layer" reducer path.- */export const placementToTransform = (placement: { x: number; y: number; width: number; height: number },imageWidth: number,@@ -568,11 +559,8 @@ const parseNode = (value: unknown, path: string, depth: number, context: ParseCoif (context.stack === 'raster' || shell.data.isHidden === false) {delete shell.data.isHidden;}- // Adjustments, opacity and blend are the raster-stack mirror of the isHidden- // rule: overlay groups composite coverage, not color, so all three are- // meaningless there. Stripped SILENTLY, unlike isHidden: diagnostics are- // fatal to the whole parse, and rejecting a document over a meaningless- // property is worse than dropping it.+ // Overlay groups carry coverage, not color. Drop raster-only properties silently because diagnostics reject the+ // whole document.if (context.stack !== 'raster') {delete shell.data.adjustments;delete shell.data.blendMode;@@ -748,9 +736,8 @@ const loadCanvasStateStep = (canvas: unknown): LoadStep<CanvasStateContractV3> =};/**- * Version-checks persisted canvas state before anything is defaulted or parsed: an absent state is- * a fresh empty canvas, the current version is validated strictly, every other declared version is- * refused so its raw payload stays available for recovery.+ * Check versions before defaulting: absent state is fresh, current state is validated, and other versions retain+ * raw payloads for recovery.*/export const loadCanvasState = (canvas: unknown): CanvasLoadResult<CanvasStateContractV3> => {const step = loadCanvasStateStep(canvas);diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.tsindex 5a8686ff1c..2ab6f834e4 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts@@ -309,11 +309,8 @@ const siblingKey = (stack: CanvasNodeInsertionAnchor['stack'], parentId: string`${stack}\0${parentId ?? ''}`;/**- * Applies every move with one removal pass, one index, and one rebuild. Anchors resolve on the- * same ladder as {@link insertNodesAtAnchor}, against sibling lists that already hold the earlier- * moves, so the result matches applying the moves one after another. Moves whose anchors name a- * moving node, or whose blocks nest, take the sequential path, since only it can see the forest- * between moves.+ * Batch rebuilds must match sequential moves. Use the sequential path when anchors name moving nodes or blocks+ * nest, because intermediate forests affect resolution.*/const applyMoves = (stacks: CanvasStackForests, moves: readonly CanvasNodeMove[], projectId: string) => {if (moves.length === 0) {@@ -882,9 +879,7 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasPro);case 'updateCanvasLayerConfigs':return updateCanvasDocument(project, (document) => {- // All-or-nothing, like setCanvasLayerPositions: a batch with any- // unresolvable target applies nothing (history replay must never- // half-apply an entry).+ // Reject the whole batch if any target cannot resolve; history replay must be atomic.const applicable = mutation.updates.every((update) => isConfigTargetValid(document, update.id, update.config));if (!applicable) {return document;diff --git a/invokeai/frontend/webv2/src/workbench/controlLayerChecks.ts b/invokeai/frontend/webv2/src/workbench/controlLayerChecks.tsindex c5a294b7ff..1dd1026285 100644--- a/invokeai/frontend/webv2/src/workbench/controlLayerChecks.ts+++ b/invokeai/frontend/webv2/src/workbench/controlLayerChecks.ts@@ -27,10 +27,8 @@ const resolveAdapterModel = (};/**- * The control-layer problems that would make the invoke pipeline reject the- * document, in document order. Mirrors `createControlLayerCollector`: only- * enabled, content-bearing control layers are validated, and the per-kind- * limit counters advance only past valid layers.+ * Validate the same enabled, content-bearing layers as createControlLayerCollector; invalid layers do not consume+ * per-kind limits.*/export const getBlockingControlLayerIssues = (params: {layers: readonly CanvasLayerContract[];@@ -87,11 +85,7 @@ export const getBlockingControlLayerIssues = (params: {return issues;};-/**- * Relaxed per-layer check for ambient warning UI: content is not required- * (a fresh model-less layer should already warn) and the per-kind limit- * counters are pinned to zero (limit problems stay in the invoke tooltip).- */+/** Ambient warnings include empty layers but omit per-kind limits, which belong in the Invoke tooltip. */export const getControlLayerAttentionReason = (layer: CanvasControlLayerContract,mainBase: string,diff --git a/invokeai/frontend/webv2/src/workbench/deferredResource.ts b/invokeai/frontend/webv2/src/workbench/deferredResource.tsindex 208569792f..c40d8664af 100644--- a/invokeai/frontend/webv2/src/workbench/deferredResource.ts+++ b/invokeai/frontend/webv2/src/workbench/deferredResource.ts@@ -1,14 +1,7 @@/**- * The shape React's `use()` inspects before deciding to suspend. A bare promise- * — even an already-resolved one — always costs a suspension on first read,- * because `use()` cannot read a native promise synchronously; it has to attach a- * callback, throw, and retry on the ping. Settling these fields as soon as the- * load completes lets `use()` return the value on the very first render instead.- *- * That distinction is worth real time. Suspending shows a fallback, and once a- * fallback has been shown React withholds the resolved tree for- * `FALLBACK_THROTTLE_MS` (300ms) to avoid a flash — which measured as the whole- * cost of switching layout, long after the chunk had finished downloading.+ * Set React use() settlement fields when loading completes so the first read can return synchronously. Native+ * promises otherwise suspend on first read, potentially triggering fallback throttling after the chunk is already+ * available.*/interface TrackedThenable<T> extends Promise<T> {reason?: unknown;diff --git a/invokeai/frontend/webv2/src/workbench/diagnostics/contracts.ts b/invokeai/frontend/webv2/src/workbench/diagnostics/contracts.tsindex 83aed49486..2cfd8b3976 100644--- a/invokeai/frontend/webv2/src/workbench/diagnostics/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/diagnostics/contracts.ts@@ -1,8 +1,4 @@-/**- * Identifier for a workbench color theme. The matching palette lives in- * `theme/themes.ts`; the active id is applied to `<html data-theme>` so the- * semantic-token conditions in `theme/system.ts` resolve to the right colors.- */+/** Theme ids select palettes through html data-theme and the semantic-token conditions. */export type DeveloperLogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';export type DeveloperLogNamespace =diff --git a/invokeai/frontend/webv2/src/workbench/extensions/extensionRegistry.ts b/invokeai/frontend/webv2/src/workbench/extensions/extensionRegistry.tsindex 5dcc321291..f15e2d402e 100644--- a/invokeai/frontend/webv2/src/workbench/extensions/extensionRegistry.ts+++ b/invokeai/frontend/webv2/src/workbench/extensions/extensionRegistry.ts@@ -38,11 +38,7 @@ export interface ExtensionRegistry {toolbars: WidgetToolbarApi;}-/**- * One extension registry is constructed per Workbench mount (see- * WorkbenchProvider) so contribution state lives and dies with the mount —- * never in process-wide singletons.- */+/** Construct one registry per Workbench mount so contribution state shares its lifetime. */export const createExtensionRegistry = (): ExtensionRegistry => {const stores: ExtensionContributionStores = {commands: createCollectionStore<WidgetCommandContribution>(),diff --git a/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts b/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.tsindex 2bf59e2f98..f07a7a9a1e 100644--- a/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts@@ -78,10 +78,7 @@ describe('floatWidget', () => {state = workbenchReducer(state, { instanceId: lastCenterInstanceId, type: 'floatWidget' });const center = getActiveProject(state).widgetRegions.center;- // The surface may go empty — the fallback view carries it — and the- // window remembers the center as its dock-back target. The active pointer- // holds the floated instance so docking restores it as the active view,- // and the center takes no collapsed state.+ // An empty center retains the floated active instance as its dock-back target and uses its fallback view.expect(center.instanceIds).toEqual([]);expect(center.activeInstanceId).toBe(lastCenterInstanceId);expect(center.isCollapsed).toBe(false);@@ -91,10 +88,8 @@ describe('floatWidget', () => {});it('docks back into the region the float was asked from, not the first member region', () => {- // The Edit preset places the preview in the center AND the right rail, and- // `right` precedes `center` in the region map — without the origin hint,- // floating it from the center chrome would detach the rail's membership- // and dock it back there.+ // Preview belongs to center and right; right precedes center, so this catches loss of the explicit float+ // origin.let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'edit', type: 'applyPreset' });state = workbenchReducer(state, { instanceId: 'preview', region: 'center', type: 'floatWidget' });const project = getActiveProject(state);@@ -115,9 +110,7 @@ describe('floatWidget', () => {const project = getActiveProject(state);const floating = project.floatingWidgets?.preview;- // The hint is what makes dock-back deterministic; without it some member- // region still hosts the float — which one is region map order, not a- // contract.+ // Without an origin hint, the chosen member region is unspecified map order.expect(floating).toBeDefined();expect(['center', 'right']).toContain(floating!.returnRegion);});@@ -182,9 +175,6 @@ describe('dockFloatingWidget', () => {});it('restores the tab to the position it floated from', () => {- // Docking appended, so float-then-dock — a gesture that reads as undoing- // the float — permanently reordered the rail and left the project drifted- // from its preset.const initial = createInitialWorkbenchState();const before = [...getActiveProject(initial).widgetRegions.right.instanceIds];@@ -307,9 +297,7 @@ describe('interaction with region placement', () => {});it('selectRegionWidget docks a floating instance instead of double-rendering it', () => {- // The preview is still a member of the right rail while it floats in a- // window docked back to the center; selecting its rail slot would- // otherwise make the rail show it alongside the window.+ // Selecting Preview's remaining rail slot must dock it rather than show it alongside the floating copy.let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'edit', type: 'applyPreset' });state = workbenchReducer(state, { instanceId: 'preview', region: 'center', type: 'floatWidget' });state = workbenchReducer(state, { region: 'right', type: 'selectRegionWidget', widgetId: 'preview' });@@ -395,8 +383,6 @@ describe('normalization of persisted floating windows', () => {} as unknown as Project['floatingWidgets'],});- // Dropping the entry must leave the instance docked where it already was,- // rather than floating by a malformed description or vanishing entirely.expect(normalized.floatingWidgets).toBeUndefined();for (const instanceId of ['queue', 'preview', 'notifications']) {expect(getRegionsHolding(normalized, instanceId)).not.toEqual([]);@@ -417,12 +403,8 @@ describe('normalization of persisted floating windows', () => {});it('lets a sole center view keep floating across a reload', () => {- // Floating the last center view empties the work surface into its fallback- // view, and the window's dock control is one click from restoring it. The- // persisted shape is an EMPTY center whose active pointer names the floated- // instance — normalization must honour it, not read it as missing center- // data and refill the default arrangement (which would inject views the- // project never placed).+ // An explicitly empty center with a floated active pointer must survive normalization without default views+ // being added.let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'video', type: 'applyPreset' });state = workbenchReducer(state, { instanceId: 'preview', region: 'center', type: 'floatWidget' });const project = getActiveProject(state);@@ -475,9 +457,7 @@ describe('interaction with presets and undo', () => {});it('a preset saved with the sole center view floating restores the emptied surface, not a phantom view', () => {- // Normalizing before the snapshot must not refill the emptied center with- // the default arrangement — the saved preset would otherwise carry center- // views the project never placed.+ // Snapshot normalization must preserve an intentionally empty center.let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'video', type: 'applyPreset' });state = workbenchReducer(state, { instanceId: 'preview', region: 'center', type: 'floatWidget' });state = workbenchReducer(state, { presetId: 'video', type: 'saveLayoutPreset' });@@ -491,8 +471,6 @@ describe('interaction with presets and undo', () => {});it('carries a saved preset’s floating window through account rehydration', () => {- // Account presets are rebuilt by `cloneLayoutPresetSnapshot` on every load;- // a field it forgets is a field the preset loses on the next reload.let state = workbenchReducer(createInitialWorkbenchState(), { instanceId: 'gallery', type: 'floatWidget' });state = workbenchReducer(state, { presetId: 'compose', type: 'saveLayoutPreset' });@@ -560,8 +538,6 @@ describe('interaction with presets and undo', () => {expect(project.floatingWidgets ?? {}).toEqual({});expect(project.widgetRegions.right.instanceIds).toContain('gallery');- // Mirror case: float, take a snapshot, dock, undo -> floating state returns- // WITH the matching regions; the widget is exactly one of docked/floating.state = workbenchReducer(state, { instanceId: 'gallery', type: 'floatWidget' });state = workbenchReducer(state, { presetId: 'compose', type: 'applyPreset' });state = workbenchReducer(state, { type: 'undoProjectChange' });diff --git a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.tsindex 014e1f1cc5..174839adc6 100644--- a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts@@ -14,8 +14,7 @@ import { describe, expect, it, vi } from 'vitest';import { resolveAndSubmitGraphPreviewInvocation } from './graphPreviewInvocation';-// Generation policy now fails closed without the capability table, and a submission cannot-// happen before app boot has fetched it. Seeding it here is what the running app does.+// Seed capabilities to match app boot; submission fails closed without them.seedArchitectureCapabilities();const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };@@ -47,10 +46,7 @@ const getActiveProject = (values: GenerateWidgetValues) => {return project!;};-// Mounts the canvas widget into the center region so `resolveInvocationRoute`-// treats a `canvas` source as available (mirrors invocation.test.ts's-// `canvasInputFor` mountedWidgetIds override, but here as an actual project-// mutation since `resolveAndSubmitGraphPreviewInvocation` takes a real Project).+// Mount Canvas in the project so resolveInvocationRoute considers that source available.const withCanvasWidgetMounted = (project: ReturnType<typeof getActiveProject>): ReturnType<typeof getActiveProject> => ({diff --git a/invokeai/frontend/webv2/src/workbench/graphWidgets.test.ts b/invokeai/frontend/webv2/src/workbench/graphWidgets.test.tsindex 9a629529ff..e568fc35cc 100644--- a/invokeai/frontend/webv2/src/workbench/graphWidgets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/graphWidgets.test.ts@@ -31,9 +31,7 @@ describe('graph widget sources', () => {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.+ // Keep unplaced sources selectable so switching sources does not require manual layout changes.it('offers every graph widget as a source', () => {expect(graphWidgetSources.map((source) => source.sourceId)).toEqual(['generate',@@ -51,15 +49,11 @@ describe('graph widget sources', () => {expect([...getVisibleWidgetTypeIds(project)]).toEqual(expect.arrayContaining(['generate', 'canvas']));expect(getVisibleWidgetTypeIds(project).has('workflow')).toBe(false);- // ...while Upscale is still placed second in the left rail, so routing to- // it needs no new placement, only revealing. Workflow belongs to Automate.expect([...getPlacedWidgetTypeIds(project)]).toEqual(expect.arrayContaining(['generate', 'canvas', 'upscale']));expect(getPlacedWidgetTypeIds(project).has('workflow')).toBe(false);});it('counts a floated widget as both visible and placed', () => {- // A widget in a window is on screen; reading only the rails would drop the- // first graph-bearing widget that floats out of the invoke-source list.let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'edit', type: 'applyPreset' });state = workbenchReducer(state, { instanceId: 'upscale', type: 'floatWidget' });const project = state.projects.find((candidate) => candidate.id === state.activeProjectId)!;diff --git a/invokeai/frontend/webv2/src/workbench/graphWidgets.ts b/invokeai/frontend/webv2/src/workbench/graphWidgets.tsindex 1ddc04395d..dac3a35ff2 100644--- a/invokeai/frontend/webv2/src/workbench/graphWidgets.ts+++ b/invokeai/frontend/webv2/src/workbench/graphWidgets.ts@@ -51,12 +51,7 @@ export const graphWidgetSources: GraphWidgetSource[] = graphWidgetTypeIds})).filter((source) => isInvocationSourceAvailable(source.sourceId));-/**- * Floated instances belong in both sets below: a widget in a window is on- * screen and placed, just not in a rail. Reading only `widgetRegions` would- * drop the first graph-bearing widget that opts into floating out of the- * invoke-source list while it sits in plain view.- */+/** Floating graph widgets are both visible and placed, so include them in invocation-source discovery. */const addFloatingWidgetTypeIds = (project: Project, typeIds: Set<WidgetTypeId>): void => {for (const instanceId of Object.keys(project.floatingWidgets ?? {})) {const typeId = project.widgetInstances[instanceId]?.typeId;diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.test.tsindex 27887cfe17..6ab8a550ec 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.test.ts@@ -41,9 +41,7 @@ describe('shouldPreventHotkeyDefault', () => {});it('prevents the browser default for a matched binding with no explicit preventDefault', () => {- // Regression: widget hotkeys (e.g. canvas `mod+d`) are registered without a- // `preventDefault` flag; a claimed binding must still swallow the browser- // default (mod+d used to open the bookmark dialog).+ // Claimed widget bindings must prevent browser defaults even without an explicit preventDefault flag.expect(shouldPreventHotkeyDefault(createHotkey({}))).toBe(true);});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsxindex 0128e07854..95b53a5a9d 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx@@ -23,14 +23,8 @@ export const getHotkeyExecutionSource = (): WidgetContributionSource | null => (hotkey.scope.kind === 'global' ? (hotkey.source ?? null) : activeSource);/**- * Whether the browser default should be suppressed for a resolved hotkey.- *- * `resolveHotkey` only returns a hotkey once it has *claimed* the event — the- * scope is active and it is not skipped by the editable-target/modal-layer- * rules — so a matched-and-run binding must swallow the browser default (e.g.- * `mod+d` opening the bookmark dialog). Prevention is therefore on by default;- * a binding opts out only by explicitly setting `preventDefault: false`. A- * `null` hotkey (no binding claimed the event) never prevents the default.+ * Claimed bindings suppress browser defaults unless preventDefault is explicitly false. Unclaimed events retain+ * browser behavior.*/export const shouldPreventHotkeyDefault = (hotkey: RegisteredHotkey | null): boolean =>hotkey !== null && hotkey.preventDefault !== false;diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.tsindex 6273f3ce29..5110e725a8 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts@@ -4,13 +4,6 @@ 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)- // + the seven top-bar redesign commands (alt+mod+enter, mod+p, an unbound- // save, and alt+1..4) + `app.openSettings` (mod+,) + `gallery.toggleStarredOnly`- // (webv2 starred-only listing filter, unbound) + the two unbound canvas- // gallery saves (`canvas.saveToGallery`, `canvas.saveBboxToGallery`).- // `app.togglePreview` (z) replaces the legacy `viewer.toggleViewer`.expect(firstPartyHotkeyCatalog).toHaveLength(104);expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.togglePreview');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.invoke');diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.tsindex 1e537bdeef..f310987870 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts@@ -1,36 +1,10 @@import type { HotkeyCategory, HotkeyDefinition } from './types';/**- * Intentional browser-default interception- *- * Every registered hotkey prevents default, but only entries with handlers- * actually shadow a browser chord. Handlers come from two registries sharing- * the same scope resolution: this catalog's `implemented` set, and the- * extension-hotkey path (`CanvasWidgetView` registers the canvas's runtime- * chords there with `allowInEditable: false`; several ids — X/D color pair,- * undo/redo, delete, entity nav, mergeDown, transformSelected — exist in BOTH,- * resolving at equal widget-scope priority). A catalog entry with no handler- * anywhere (the mod+0…4 zoom chords) intercepts nothing.- *- * Chords that deliberately override a browser default, outside editable- * fields (hotkeys skip editables unless listed in `editableAppHotkeys`):- *- * - mod+p (`app.openProjectSwitcher`) — print dialog;- * - mod+k (`app.openCommandPalette`) — address-bar search;- * - mod+, (`app.openSettings`) — browser settings, where the browser- * delivers the event to the page at all;- * - mod+z / mod+shift+z / mod+y (canvas and workflow undo/redo) — native- * text undo;- * - mod+a / mod+c / mod+v (canvas, workflow, gallery select/copy/paste) —- * the app's own selection/clipboard semantics replace the page's;- * - canvas mod+e (merge down) — macOS "use selection for find" / address-bar- * search; mod+d (deselect) — bookmark; mod+shift+i (invert selection) —- * devtools where delivered; mod+t (transform) — browser-reserved in most- * builds, fires only where forwarded.- *- * Scoping bounds the blast radius: `app.*` chords are global, everything- * else fires only while its widget owns focus (`categoryScopes`). Bare keys- * ([ ] tool width, X/D, tool mnemonics) conflict with no browser default.+ * Only registered handlers intercept chords; handlerless catalog entries do not. App chords are global, other+ * chords require widget focus, and editable fields are excluded unless explicitly allowed. Overrides include+ * print/search/settings, undo/redo, selection/clipboard, and Canvas merge/deselect/invert/transform;+ * browser-reserved chords work only when delivered to the page.*/const categoryScopes = {@@ -116,12 +90,8 @@ const implemented = new Set([]);/**- * Hotkeys that must fire with the caret inside a text field or numeric input.- *- * The topbar's Invoke button is the only one that is always on screen (the- * floating preview window carries a second one, but only while it floats), so- * `app.invoke` and its variants are load-bearing: a prompt textarea that- * swallows ⌘↵ leaves the user with no way to submit at all.+ * Keep invocation shortcuts available inside text and numeric fields so prompt editing does not swallow+ * submission.*/const editableAppHotkeys = new Set(['app.focusPrompt',@@ -181,14 +151,11 @@ 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.+ // Override the destination for one submission without changing the saved route.hotkey('app', 'invokeToOtherDestination', ['alt+mod+enter']),hotkey('app', 'invokeFront', ['mod+shift+enter']),hotkey('app', 'openProjectSwitcher', ['mod+p']),- // `mod` rather than a literal ctrl: this is ⌘, on macOS and ctrl+, elsewhere,- // which is the platform-standard settings shortcut on both.+ // Use mod for the platform settings chord: Command on macOS, Control elsewhere.hotkey('app', 'openSettings', ['mod+,']),hotkey('app', 'saveLayoutPreset', []),hotkey('app', 'selectComposePreset', ['alt+1']),diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/keyGlyphs.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/keyGlyphs.tsxindex 1901d47202..b8c05e51de 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/keyGlyphs.tsx+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/keyGlyphs.tsx@@ -18,12 +18,7 @@ import {import { IS_MAC_OS } from './keys';-/**- * Keys whose keycap symbol is universal get an icon on every platform; the- * platform-branded modifier symbols (⌘ ⌥ ⇧ ⌃) are macOS-only — printing them- * in a Windows/Linux hint would name keys those keyboards do not have, so- * there the modifiers keep their word labels ("Ctrl", "Alt", "Win").- */+/** Use universal key icons everywhere; macOS modifier glyphs become word labels on Windows/Linux. */const UNIVERSAL_KEY_ICONS: Record<string, LucideIcon> = {arrowdown: ArrowDownIcon,arrowleft: ArrowLeftIcon,@@ -64,12 +59,7 @@ export const SHORTCUT_KEY_ARIA_LABELS: Record<string, string> = {tab: 'Tab',};-/**- * One key of a shortcut hint: the key's icon where it has one, otherwise the- * caller's text fallback (each render site keeps its own text casing). Icon- * renders carry a screen-reader-only spoken name, so an icon-only `Kbd` still- * announces the key.- */+/** Render an icon or the caller's text casing; icon-only hints include a spoken key name. */export const ShortcutKeyGlyph = ({ fallback, part }: { fallback?: ReactNode; part: string }) => {const GlyphIcon = getShortcutKeyIcon(part);diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsxindex bd31dff956..edd838da51 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx@@ -110,9 +110,7 @@ const pickQuickItem = async (label: string): Promise<void> => {);}});- // zag applies `data-highlighted` asynchronously and ignores a click on an unhighlighted item, so- // a fixed wait here silently dropped the click whenever the machine needed longer than it --- // the action mock simply recorded no call, and only under CI load.+ // Wait for Zag's asynchronous highlight before clicking; unhighlighted items ignore clicks.await settleUntil(() => target!.hasAttribute('data-highlighted'), `"${label}" to be highlighted`);await interact(() => target!.click());};@@ -248,8 +246,7 @@ describe('ImageContextMenu starred state', () => {getComputedStyle(document.querySelector<HTMLElement>(`[aria-label="${label}"] svg`)!).fill;it('fills the star for a starred item and leaves it outlined otherwise', async () => {- // Lucide is stroke-only, so an unfilled star was the *only* thing shown for- // both states — the text label was carrying all of the meaning.+ // Fill distinguishes starred state because Lucide outlines alone look identical.const unstarred = item('image', 'plain.png');await renderItemMenu(createActions(vi.fn()), {itemRefs: [{ kind: 'image', name: unstarred.name }],diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsxindex 14253c2805..8f382bf269 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx@@ -151,11 +151,7 @@ export const getImageContextMenuRecallRequestKey = (image: GalleryImage | null,return `${image.imageName}:${image.width}:${image.height}`;};-/**- * Shared right-click menu for backend images, usable from any widget (gallery- * grid, preview, ...). Anchored to the cursor through a virtual rect, so it- * needs no trigger element — set `target` to open it.- */+/** Shared image context menu anchored to a cursor rect; setting target opens it without a trigger element. */export const ImageContextMenu = ({actions,boards,@@ -319,8 +315,6 @@ const SingleItemMenuItems = ({const handleDelete = useCallback(() => onRequestDeletion([itemRef]), [itemRef, onRequestDeletion]);const { generation, widgets } = useWorkbenchCommands();const openWidget = useOpenWorkbenchWidget();- // Video recall availability, fetched from the item's recorded core_metadata- // when the menu opens on a video — the video twin of the image menu's flow.const [videoRecallCapabilities, setVideoRecallCapabilities] = useState<VideoRecallCapabilities>(EMPTY_VIDEO_RECALL_CAPABILITIES);@@ -820,8 +814,7 @@ const SingleImageMenuItems = ({onClick={handleUseAsReferenceImage}/><ContextMenuItem- // Same signal "Use Prompt" reads, rather than staying enabled and- // raising a toast to say the image had no prompt after all.+ // Use the same availability signal as Use Prompt to disable empty recall upfront.disabled={isLoadingRecallCapabilities || !recallCapabilities.prompts}icon={TypeIcon}label="Use as Prompt Template"diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsxindex 65ec4db70b..fd95f30b54 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsx@@ -11,11 +11,8 @@ import {import type { ImageRecallCapabilities, ImageRecallKind } from './imageRecall';/**- * The shared recall-verbs row: one look and one vocabulary for every surface- * that recalls generation settings (preview metadata panel, queue item- * details). Verbs mirror the image context menu — same labels, same icons —- * and disable (rather than hide) when a capability is unavailable, with the- * host's `disabledReason` explaining why.+ * Share recall labels/icons across metadata and queue details. Unavailable actions stay visible but disabled with+ * the host's reason.*/const RECALL_ACTION_ITEMS: {@@ -35,11 +32,7 @@ const RECALL_ACTION_ITEMS: {/** The recall verbs in their canonical order, for hosts that lay them out themselves. */export const IMAGE_RECALL_KINDS: readonly ImageRecallKind[] = RECALL_ACTION_ITEMS.map((item) => item.kind);-/**- * The verb's icon and label for hosts that surface a recall affordance- * outside this row (per-row buttons in the metadata panel), so every recall- * control keeps the same vocabulary.- */+/** Reuse recall icons and labels in controls outside the shared row. */export const getImageRecallVerb = (kind: ImageRecallKind): { icon: LucideIcon; label: string } => {const item = RECALL_ACTION_ITEMS.find((candidate) => candidate.kind === kind) ?? RECALL_ACTION_ITEMS[0]!;diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.tsindex d4211add90..cc966a5ae6 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts@@ -17,11 +17,6 @@ export type AppendReferenceImageResult =| { status: 'appended'; referenceImages: GenerateWidgetValues['referenceImages'] }| { status: 'full' | 'unsupported' };-/**- * Builds the generate widget's next `referenceImages` array with `image`- * appended as a new reference image for the current model. Pure: the caller- * patches the widget values on 'appended'.- */export const appendReferenceImage = ({generateValues,image,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.tsindex 1bafd46cf4..4c4c3ffe9b 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts@@ -36,9 +36,8 @@ import {} from './imageRecall';/**- * Replaces the project graph with the workflow embedded in `image`. The editor's- * always-mounted chrome consumes the request, so `openWorkflowEditor` runs first to- * mount it in layouts that had it hidden; a `false` result means nowhere to load.+ * Open the workflow editor before requesting replacement with the image's embedded graph; false means no editor+ * can consume it.*/export const executeLoadImageWorkflow = async ({image,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.tsindex 427a9eca3f..7699675512 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.ts@@ -63,12 +63,7 @@ const verifyRecalledReferenceImages = async ();};-/**- * Applies one `recall_parameters_updated` payload to a project's Generate- * values. `getGenerateValues` returns null once the project is gone, which- * ends the attempt quietly. Resolves to true when at least one field was- * committed.- */+/** Apply one recall payload; stop quietly if the project disappears. Return true when at least one field commits. */export const executeRecallParameters = async ({commands,getGenerateValues,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.tsindex 2f226776d1..201f7994bf 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts@@ -148,9 +148,8 @@ describe('executeVideoRecall', () => {it('writes only the prompt keys for a prompts-only recall', async () => {galleryApi.galleryVideos.metadata.mockResolvedValue(metadata);const { commands, patchValues } = createCommands();- // A panel whose recorded main is NOT installed: `getCurrentVideoValues`- // re-snaps it onto another family, so a whole-values write here would push- // that transition into the store behind a "prompts" toast.+ // A prompts-only recall must not persist the model-family transition produced by resnapshotting an uninstalled+ // main.const videoValues = { ...createDefaultVideoWidgetValues([wanModel]), numFrames: 41, steps: 4 };const didRecall = await executeVideoRecall({@@ -201,10 +200,7 @@ describe('ref2va reference conditioning on recall', () => {galleryApi.galleryItems.resolve.mockReset();});- // Recall must reproduce the run. The panel offers all three conditionings, so a recorded- // 'video_audio' on a wrapped audio clip is a deliberate user choice -- and it is the one- // value an enumerate-the-literals check is most likely to omit, because it used to be the- // fall-through default and so cost nothing to forget.+ // Preserve all recorded conditioning modes, including video_audio on wrapped audio clips.it('keeps a recorded video_audio, even on a clip marked as a wrapped audio upload', async () => {expect(await recallReferences('video_audio')).toMatchObject([{ conditioning: 'video_audio' }]);});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.tsindex 5f722da322..4c8a28b6a2 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts@@ -118,9 +118,7 @@ export const executeVideoRecall = async ({return false;}- // Conditioning media re-hydrates against the gallery: the metadata records- // only names, and the panel needs dimensions/probe data — plus deleted- // media must drop rather than resurrect as broken references.+ // Resolve media names against the gallery for dimensions/probe data and drop deleted references.if (result.fields.includes('media')) {let recalledMedia = false;const { firstFrameName, lastFrameName, sourceVideoName } = result.mediaNames;@@ -162,9 +160,7 @@ export const executeVideoRecall = async ({name: sourceItem.name,width: sourceItem.width,});- // Restore the recorded trim, clamped to the fresh estimate (which- // can differ from the run's own) — the default trim would extend- // from a completely different frame than the run did.+ // Restore recorded trim against the fresh estimate; default trim would select different frames.const trim = rebuiltClip.numFrames >= 2 ? result.mediaNames.sourceVideoTrim : null;const startFrame = trim? Math.min(Math.max(trim.startFrame, 0), rebuiltClip.numFrames - 2)@@ -187,9 +183,7 @@ export const executeVideoRecall = async ({}if (result.mediaNames.references.length > 0) {- // Ordered re-hydration: resolve every recorded reference against the gallery,- // dropping deleted media while PRESERVING the survivors' order (order is part of- // the request contract).+ // Hydrate references in recorded order, dropping deleted media without reordering survivors.const imageNames = result.mediaNames.references.filter((reference): reference is typeof reference & { kind: 'image' } => reference.kind === 'image').map((reference) => reference.name);@@ -232,10 +226,8 @@ export const executeVideoRecall = async ({const endFrame = recorded.trim? Math.min(Math.max(recorded.trim.endFrame, startFrame), clip.numFrames - 1): clip.numFrames - 1;- // A recorded conditioning is what the run actually used, so it wins -- ALL THREE- // values of it, tested as a set. Only when the metadata recorded nothing usable- // does this fall back to the default the add path would pick, which for a- // wrapped audio upload is its soundtrack rather than a picture of its waveform.+ // Any valid recorded conditioning wins; otherwise use add-path defaults, including soundtrack+ // conditioning for wrapped audio.const conditioning = isVideoReferenceConditioning(recorded.conditioning)? recorded.conditioning: getDefaultReferenceConditioning(item.mediaOrigin);@@ -265,12 +257,8 @@ export const executeVideoRecall = async ({result.fields = result.fields.filter((field) => field !== 'media');}- // What survived hydration can imply a mode the effective model rejects- // — a deleted first frame leaves an interpolate recall holding only its- // last frame (no Wan mode), and an uninstalled recorded model leaves- // i2v media on whatever main the panel kept. Reconcile with the same- // rules the model-selection transition applies, so the recall never- // assembles an un-generatable panel behind a success toast.+ // Reconcile hydrated media with the effective model's modes; deleted frames or unavailable models must not+ // leave an ungeneratable panel.const effectiveModel = result.values.model;if (effectiveModel) {@@ -329,14 +317,8 @@ export const executeVideoRecall = async ({return false;}- // Prompts are Video's own widget values now, not the draft Generate and- // Upscale share — but a prompts-only recall must still write ONLY the prompt- // keys. `result.values` is the panel re-snapshotted through- // `syncVideoWidgetValuesWithModels`, so writing it wholesale would push an- // unrelated model-family transition into the store behind a toast that says- // "prompts" (uninstall the recorded main, recall prompts, and the panel's- // frames/fps/resolution/LoRAs all reset). It would also widen the- // lost-update window against a concurrent recall still awaiting its media.+ // Commit only prompt keys: resnapshotted values may contain an unrelated model-family transition and would+ // widen the lost-update window for concurrent media recall.if (result.fields.every((field) => field === 'prompts')) {commands.widgets.patchValues('video',diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.test.tsindex 71b746de6c..11da64a9de 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.test.ts@@ -13,12 +13,8 @@ import {} from './galleryOptimisticRollback';/**- * Reducer-level coverage for the delete-rollback widget-store restore- * mechanism (Task 7 review finding #6): exercises the real `workbenchState`- * reducer end to end, rather than a mocked store, so the capture/diff/select- * functions are proven against the actual `removeGalleryItems` and- * `patchWidgetValues` contracts instead of a hand-rolled stand-in that could- * silently drift from them.+ * Exercise deletion rollback against the real reducer so capture/diff/restore follows actual removal and+ * widget-patch contracts.*/const galleryItem: GalleryItem = {@@ -56,9 +52,7 @@ const getProject = (state: WorkbenchState, projectId: string): Project => {return project as Project;};-/** Seeds a fresh project with `a.png` selected, compared, in the recent-image- * overlay, and locked as the upscale widget's input — everything- * `removeGalleryItemsFromAllProjects` can touch. */+/** Seed a.png in selection, comparison, recent images, and locked upscale input to cover every deletion target. */const seedProjectWithItem = (): { projectId: string; state: WorkbenchState } => {let state = createInitialWorkbenchState();const projectId = state.activeProjectId;@@ -209,8 +203,6 @@ describe('gallery optimistic rollback against the real reducer', () => {const restored = applyRestorePatches(claimed, patches);const videoValues = getProjectWidgetValues(getProject(restored, projectId), 'video');- // Restoring the first frame would recreate the forbidden- // first-frame+initial-video pair; the restore loses.expect(videoValues.firstFrameImage).toBeNull();expect(videoValues.sourceVideo).toEqual(sourceClip);// Unrelated fields still restore normally.@@ -218,9 +210,7 @@ describe('gallery optimistic rollback against the real reducer', () => {});it('restores swept references even when an initial video occupies the panel (reference-extend pair)', () => {- // sourceVideo <-> references is a LEGAL pair on a Ref2VA reference-extend- // panel; treating them as rivals made a failed deletion permanently drop- // the reference the sweep removed.+ // Ref2VA sourceVideo and references may coexist; rollback must restore both after failed deletion.const seeded = seedProjectWithItem();const projectId = seeded.projectId;const sourceClip = {diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.ts b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.tsindex c80abc882c..fab12e2d6e 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.ts@@ -18,11 +18,8 @@ import { isSlotUnclaimed, selectUnclaimedEntries } from '@platform/state/compareimport { getProjectWidgetValues } from '@workbench/widgetState';/**- * Fields `removeGalleryItemsFromAllProjects` (workbenchState.ts) can mutate,- * across every project: it strips a removed item from any project's- * recent-generation overlay and selection, and clears the upscale widget's- * locked input if it pointed at a removed image. None of that is visible to- * `patchGalleryItemCaches`, which only ever touches the query cache.+ * Track project selections, recent generations, and locked upscale inputs cleared by removal; query-cache rollback+ * cannot restore widget state.*/const TRACKED_GALLERY_REMOVAL_FIELDS: ReadonlyArray<{ key: string; widgetId: WidgetTypeId }> = [{ key: 'compareImage', widgetId: 'gallery' },@@ -38,13 +35,8 @@ const TRACKED_GALLERY_REMOVAL_FIELDS: ReadonlyArray<{ key: string; widgetId: Wid];/**- * Widget slots that are mutually exclusive by design (the video widget's- * first-frame XOR initial-video rule, enforced by its setters). A rollback- * restore is the one write path that bypasses those setters: after our- * optimistic clear, the user may have claimed the RIVAL slot, and restoring- * this one would recreate a pair no setter can produce — normalization then- * masks one of the two, which reads as a silently wrong generation mode.- * When the rival slot is occupied, the restore loses.+ * Skip restoration when a mutually exclusive rival slot was filled after optimistic removal; bypassing setters+ * must not recreate an invalid pair.*/const EXCLUSIVE_RIVAL_FIELDS: ReadonlyArray<{ key: string; rivalKey: string; widgetId: WidgetTypeId }> = [{ key: 'firstFrameImage', rivalKey: 'sourceVideo', widgetId: 'video' },@@ -53,10 +45,8 @@ const EXCLUSIVE_RIVAL_FIELDS: ReadonlyArray<{ key: string; rivalKey: string; wid{ key: 'sourceVideo', rivalKey: 'firstFrameImage', widgetId: 'video' },{ key: 'references', rivalKey: 'firstFrameImage', widgetId: 'video' },{ key: 'references', rivalKey: 'lastFrameImage', widgetId: 'video' },- // sourceVideo <-> references is deliberately NOT a rival pair: the two- // coexist on a Ref2VA reference-extend panel, and normalization keeps both- // (validation owns rejecting the pair per model). Treating them as rivals- // made a FAILED gallery deletion permanently drop the other slot's value.+ // sourceVideo and references coexist for Ref2VA reference-extend; treating them as rivals would lose valid data+ // on rollback.];const trackedFieldKey = (projectId: string, widgetId: WidgetTypeId, key: string): string =>@@ -90,13 +80,8 @@ export interface GalleryWidgetKeySnapshotEntry {}/**- * Diffs the tracked fields' current value against a `before` snapshot and- * returns only the entries the optimistic mutation actually changed, each- * carrying both the pre-mutation and post-mutation ("after") value — the same- * shape `patchGalleryItemCaches`'s rollback closure captures- * (`queryCache.ts` `ItemCacheRollbackEntry`), so the restore can apply the- * same conflict rule: only put a key back if nothing else wrote to it since.- * Call immediately after the optimistic mutation.+ * Immediately after optimistic mutation, capture only changed fields with before/after values so rollback can+ * detect subsequent writes.*/export const diffGalleryWidgetKeyValues = (before: GalleryWidgetKeyValueMap,@@ -139,16 +124,8 @@ export interface GalleryWidgetRestorePatch {}/**- * Selects which snapshot entries are still safe to restore, under the shared- * compare-and-swap rule (`@platform/state/compareAndSwapRollback`): a key- * restores only if its current value is still what our own mutation left it- * at. A key something else wrote to since (a generation completing, a user- * re-selecting) is left alone rather than clobbered. Entries for the same- * project+widget are merged into a single patch.- *- * A project that has since disappeared has no slot to restore, so its entries- * drop out before the compare rather than resolving to a bare `undefined` that- * the check could mistake for a match.+ * Restore only values still equal to the optimistic mutation's output, merging patches per project/widget. Drop+ * disappeared projects before comparison so undefined cannot falsely match.*/export const selectRestorableGalleryWidgetPatches = (entries: readonly GalleryWidgetKeySnapshotEntry[],@@ -196,11 +173,8 @@ export interface GalleryStoreKnownItemFields {}/**- * Reads the board and starred state of each requested item from whichever- * project widget state holds it locally: the recent-generation overlay, the- * current selection, or the compare slot. `getGalleryItemBoardIdsFromCaches`- * /`getGalleryItemStarredFromCaches` only see items a list query has already- * fetched; a just-generated image can be known *only* here.+ * Read board/star state from project selection, comparison, or recent generations; newly generated items may not+ * exist in list caches yet.*/export const collectGalleryStoreKnownItemFields = (projects: readonly Project[],diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.tsindex 2af58acd3c..b5e95c0300 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@ -519,8 +519,7 @@ describe('image recall', () => {});it('recalls the size for an external generator, which has no architecture row to wait for', () => {- // The fail-closed rule below is for architectures the backend describes. An external provider- // never gets a row, so treating it the same way lost its dimension recall for good.+ // External providers have no capability row and must remain eligible for dimension recall.const externalModel = {base: 'external',capabilities: { modes: ['txt2img'], supports_seed: true },@@ -552,9 +551,7 @@ describe('image recall', () => {});describe('before the capability table arrives', () => {- // Recalled dimensions are snapped to the architecture's grid and then persisted into the- // project. With no table every base reads as grid 8, so a 16- or 32-grid project would- // store a size its own denoise node rejects -- and nothing re-derives it afterwards.+ // Require the model's grid before persisting recalled dimensions; fallback grid 8 can produce invalid sizes.beforeEach(() => {resetArchitectureCapabilities();});@@ -591,8 +588,7 @@ describe('image recall', () => {vaeModels: [],});- // Recall All used to apply the model's fallback defaults and skip the size, and the project kept- // that result after the table arrived.+ // Recall All must not persist fallback defaults while capabilities are unavailable.expect(recall('all')).toBeNull();expect(recall('remix')).toBeNull();expect(recall('prompts')?.fields).toEqual(['prompts']);diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.tsindex 3188d4197a..6204d53bab 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts@@ -227,10 +227,8 @@ const getImageSize = (image: GalleryImage,model: GenerateModelConfig): Pick<GenerateWidgetValues, 'height' | 'width'> | null => {- // Fail closed: recalled dimensions are snapped to the architecture's grid and then persisted- // into the project. Without the served table every base reads as grid 8, so a krea-2 or- // CogView 4 project would store a size its denoise node rejects. Recalling nothing is- // recoverable; storing the wrong size silently is not.+ // Decline dimension recall without architecture policy; persisting fallback grid 8 can leave sizes the model+ // rejects.const grid = getDimensionGrid(model.base, model.variant);if (grid === null) {@@ -247,8 +245,7 @@ export const getMetadataSize = (metadata: unknown,model: GenerateModelConfig): Partial<Pick<GenerateWidgetValues, 'height' | 'width'>> => {- // Same reason as getImageSize: an empty result means 'no size recalled', which the caller- // already handles, and the field list then does not claim a size was restored.+ // Return no size and omit its field label when architecture policy is unavailable.const grid = getDimensionGrid(model.base, model.variant);if (grid === null) {@@ -361,11 +358,7 @@ const getPromptPatch = (const hasPrompt = (metadata: unknown): boolean => Object.keys(getPromptPatch(metadata)).length > 0;-/**- * The prompts an image was generated with, for seeding a new prompt template.- * These are the merged prompts — metadata records what the model was given — so- * the template starts from the text that produced the image.- */+/** Seed templates from merged metadata prompts: these are the words the model received. */export const getMetadataPrompts = (metadata: unknown): { negativePrompt: string; positivePrompt: string } => ({negativePrompt: getNullableString(metadata, 'negative_prompt') ?? '',positivePrompt: getString(metadata, 'positive_prompt') ?? '',@@ -382,13 +375,7 @@ const hasGenerationSettings = (metadata: unknown): boolean =>getBoolean(metadata, 'seamless_x') !== null ||getBoolean(metadata, 'seamless_y') !== null;-/**- * Krea-2's conditioning rebalance, as written by `buildKrea2Graph`.- *- * Gated on the recalled model's base because the settings keys are family-specific, and- * validated because `krea2RebalanceWeights` is forwarded to the node verbatim — a- * metadata blob is not a trusted source for a string the backend will parse.- */+/** Gate Krea-2 rebalance on model base and validate metadata before forwarding weights verbatim to the node parser. */const getMetadataKrea2Rebalance = (metadata: unknown,model: GenerateModelConfig | undefined@@ -469,10 +456,8 @@ export const getSupportedClipSkip = (metadata: unknown, model: GenerateModelConf};/**- * Recall All, Remix and CLIP skip read architecture policy -- model defaults, VAE and CLIP skip rules- * -- and their result is persisted into the project, where it outlives the outage. Without the served- * table they would be computed on fallbacks and stored. Prompts and seed are the image's own, and- * a dimensions recall already declines per model when it has no grid to snap to.+ * Require served policy for Recall All, Remix, and CLIP skip before persisting model defaults or compatibility+ * choices. Prompts/seed are intrinsic; dimension recall gates its own grid.*/export const isImageRecallKindAvailable = (kind: ImageRecallKind): boolean =>kind === 'prompts' || kind === 'seed' || kind === 'dimensions' || hasArchitectureCapabilities();diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.tsindex cc0cc2b6f6..c0a315cce6 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts@@ -163,14 +163,8 @@ const toReferenceImage = (config: GenerateReferenceImageConfig): GenerateReferenconst clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));/**- * Translates one recall payload into the next Generate values. Pure: the caller- * verifies reference-image availability and commits the result.- *- * Present keys are applied; a `null` value (strict mode) resets that field to- * the effective model's default. Keys the Generate panel has no home for- * (refiner, denoise strength, canvas control layers) and entries that cannot- * be resolved against the installed models are reported in `skipped` rather- * than silently dropped.+ * Apply present payload keys; strict nulls reset to effective-model defaults. Report unsupported fields and+ * unresolved models in skipped. The caller verifies reference availability and commits.*/export const buildRecallParametersSettings = ({currentValues,@@ -210,9 +204,7 @@ export const buildRecallParametersSettings = ({if (!model) {skip('model', 'unresolved', parameters.model);} else if (model.key !== values.model.key) {- // Model defaults first (as image recall does), then the same compatibility- // transition the model selector runs: retarget reference images, clear an- // incompatible VAE and component selections.+ // Apply model defaults before the selector's compatibility transition for references, VAE, and components.const { settings } = getGenerateModelSelectionResult({currentValues: getSettingsWithModelDefaults(values, model),model,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.tsindex ba73dbe492..d5052698e8 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.ts@@ -13,11 +13,8 @@ interface RecallParametersRuntimeModule {}/**- * Keeps the recall runtime, and the gallery and model lookups it needs, out of- * the editor's boot graph: the runtime module loads on the first recall event,- * and events that arrive while it loads are handed over in order, each with the- * project that was active when it arrived. A failed load is reported and the- * next event retries it.+ * Lazy-load recall on its first event; buffer events in arrival order with their original project. Report load+ * failures and retry on the next event.*/export const attachRecallParametersRuntime = ({commands,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.tsindex 220b48dffa..5a9fe4f0db 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.ts@@ -22,13 +22,8 @@ export interface PendingRecallEvent {const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));/**- * Applies `POST /api/v1/recall` updates, delivered as `recall_parameters_updated`- * socket events, to the project that was active when each event arrived.- *- * Events are applied strictly in arrival order: applying one awaits model and- * image lookups, and an `append` that overlapped an in-flight replace must see- * the replaced list rather than race it. `replay` events (buffered before this- * runtime existed) go first.+ * Apply socket recall events to their arrival-time project, strictly in order so append observes preceding+ * replace. Buffered replay events run first.*/export const createRecallParametersRuntime = ({commands,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/revealGalleryItem.ts b/invokeai/frontend/webv2/src/workbench/image-actions/revealGalleryItem.tsindex f96db6382d..a4c6306ed0 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/revealGalleryItem.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/revealGalleryItem.ts@@ -15,12 +15,7 @@ import {} from '@features/gallery/queries';import { getProjectWidgetValues } from '@workbench/widgetState';-/**- * What a reveal needs from the workbench. Passed in rather than read from hooks- * so this module can be loaded on the press that needs it — the panels' find- * badges are on the editor's initial route, and eagerly importing the gallery- * item/transfer barrel from there cost two more initial script requests.- */+/** Inject workbench dependencies so reveal loads on demand without adding gallery transfer code to editor boot. */export interface GalleryRevealContext {commands: WorkbenchCommands;queries: WorkbenchQueries;@@ -67,39 +62,17 @@ const ensureGalleryPagesLoaded = async (};/**- * Lands the gallery on one item: its board and view, any search or similarity- * filter cleared (the item may not match it), and its position in the board's- * ordering looked up so the grid can reach it — the page is selected in- * paginated mode, and in infinite mode the pages down to it are loaded. The- * grid scrolls to the newly selected item on its own once it is in the loaded- * window. Preview follows the gallery selection by itself.- *- * The caller knows an item's kind and name; the selection contract wants a full- * gallery item, so each is hydrated through the by-ref resolver — always fresh,- * since a cached DTO's star/board state can drift, and kind-aware, since the- * item can be a video. A slow fetch can never overwrite a newer selection.- *- * This is navigation only: no widget is raised, because the caller that sits- * beside the grid (the image map) must not rearrange the workspace to scroll it.- * `useFindGalleryItem` is the panels' gesture, which does both.- *- * The `ticket` is minted by the CALLER, at the moment of the gesture, so a- * caller that loads this module on demand is still ordered — and fenced to its- * project — by when it was pressed rather than by when its chunk landed. The- * returned promise rejects if the item cannot be hydrated — a click on a- * just-deleted item, or a blip mid-backend-restart — leaving the selection- * unchanged; what to say about that is the caller's, since only it knows whether- * it has already rearranged the workspace on the user's behalf.+ * Reveal a freshly resolved item in its board/view with filters cleared and its page loaded; selection drives grid+ * scrolling and Preview. Do not raise widgets. Caller-minted gesture tickets fence project changes and later+ * selections even across lazy loading. Hydration failures reject without changing selection; position failures+ * only lose scrolling.*/export const revealGalleryItem = ({ commands, queries, queryClient }: GalleryRevealContext,ref: GalleryItemRef,{ projectId, sequence }: GalleryRevealTicket): Promise<void> => {- // The press belongs to the project it was made in. This resolves over the- // network, and a switch in that window would otherwise clear the INCOMING- // project's search and move its selection — the same fence the video panel's- // play button carries.+ // Fence the network result to the gesture's project before clearing filters or selecting.const isCurrent = () => isGalleryNavigationCurrent(sequence) && queries.isActiveProject(projectId);return galleryItems.resolve(ref).then(async (image) => {@@ -110,11 +83,7 @@ export const revealGalleryItem = (const getGalleryValues = () => getProjectWidgetValues(queries.getSnapshot().activeProject, 'gallery');const settings = getGallerySettings(getGalleryValues());const targetView: GalleryView = image.category === 'general' ? 'images' : 'assets';- // The board listing the gallery will show once the reveal below has- // cleared any search: identical filter shape, so the name list (and- // the prefetched pages) land in the cache the gallery reads.- // The grid partitions on the flag: a starred image is revealed in- // the starred-only listing, an unstarred one in the plain listing.+ // Match the post-reveal listing filters and starred partition so prefetched pages enter the gallery's cache.const wantsStarredOnly = image.starred === true;const listingFilter = {boardId: image.boardId,@@ -123,13 +92,8 @@ export const revealGalleryItem = (searchTerm: '',starred: wantsStarredOnly,};- // The image's position within its board's ordering, which is what- // lets the gallery land on the right page rather than page 0. A- // failure here only costs the scroll, not the selection. The boards- // list rides along because the gallery falls back to Uncategorized- // when the target board is not listable (archived with "show- // archived" off) — landing on the hidden board's page number there- // would jump to an unrelated page of the wrong board.+ // Resolve position for paging, but preserve selection on failure. Check board visibility to avoid using a+ // hidden board's page in Uncategorized.let boardIndex: number | null = null;try {@@ -178,9 +142,7 @@ export const revealGalleryItem = ((typeof values.searchTerm === 'string' && values.searchTerm !== '') ||typeof values.semanticSearchText === 'string';- // Filters would hide the listing the index was computed against- // (the image may not match them), so the reveal clears them and sets- // the starred filter to the image's own side of the partition.+ // Clear filters to match the indexed listing and select the item's starred partition.if (hasSearch ||(values.starredOnly === true) !== wantsStarredOnly ||@@ -198,11 +160,8 @@ export const revealGalleryItem = (commands.gallery.setView(targetView);}- // Select the image's board before the image. A reveal spans every- // accessible board, but `selectGalleryItem` stamps the navigation- // query from whatever list the gallery is CURRENTLY showing — a- // cross-board reveal without this left Preview's next/prev with no- // cursor. Mirrors the command palette's reveal-in-gallery.+ // Select the board before the item so its navigation query captures the destination listing for Preview+ // next/previous.commands.gallery.selectBoard(image.boardId);const page = boardIndex !== null ? Math.floor(boardIndex / GALLERY_PAGE_SIZE) : null;@@ -213,10 +172,8 @@ export const revealGalleryItem = (if (boardIndex !== null && page !== null && settingsNow.paginationMode === 'infinite') {if (boardIndex < GALLERY_MAX_ROWS) {- // Within the base window's reach: load every page down to the- // image so the grid can scroll to it. Fire and forget — the- // selection must not wait on page hydration, and the grid's- // pending reveal settles whenever the item appears.+ // Load pages through the item without delaying selection; the grid completes its reveal when the item+ // arrives.void ensureGalleryPagesLoaded(queryClient, listingFilter, page + 1).catch(() => {});} else {// Deeper than the base window can ever load: anchor thediff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useFindGalleryItem.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useFindGalleryItem.tsindex 1fd3de0cc2..a637cd21a2 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useFindGalleryItem.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useFindGalleryItem.ts@@ -10,15 +10,8 @@ import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchCimport { useCallback } from 'react';/**- * Where to raise the grid, when it is already somewhere. `openWorkbenchWidget`- * picks a region from the MANIFEST rather than from the layout, and the reducer- * then adopts the existing instance into that region WITHOUT vacating the one- * it came from — so an unqualified open lists one grid in two regions at once- * and leaves it permanently in the centre tab strip. Naming the region it- * already occupies keeps the open a raise.- *- * Centre is the last resort: it is Preview's home, and the two would contest- * one slot. A project with no grid at all falls through to default placement.+ * Raise the gallery in its existing region to avoid duplicate placement. Prefer rails over center, where Preview+ * competes; absent grids use default placement.*/const SIDE_REGIONS: readonly WidgetRegion[] = ['right', 'left', 'bottom', 'center'];@@ -30,24 +23,8 @@ const getGalleryRegions = (project: Project): WidgetRegion[] =>);/**- * "Find in gallery", as the Generate and Video panels offer it on the media- * they are conditioning on: bring the Gallery and Preview widgets on screen,- * then reveal the item in the grid. Unlike the image map's reveal this DOES- * rearrange the workspace — the panels are the far side of the app from the- * grid, and a selection the user cannot see is not a find.- *- * Preview is raised first so that the grid wins if the two share a region:- * the gesture is named for the grid, and Preview follows the selection anyway- * once it is on screen. Both are raised on the press itself, ahead of the- * reveal, so the gesture reads as immediate; a widget no region can host is- * simply skipped, and the reveal still runs.- *- * The reveal is fetched on the press. Loading it eagerly pulled the gallery- * item/transfer barrel into the editor's initial graph, costing two more- * initial script requests (measured against the request-count budgets), for a- * control most sessions never touch. Its own sequence number is claimed HERE,- * before the import, so a press still takes its place in the global ordering- * at the moment it happened rather than whenever the chunk lands.+ * Raise Preview then Gallery immediately so Gallery wins shared regions, then lazy-load reveal. Claim the gesture+ * ticket before import to preserve press order and project fencing.*/export const useFindGalleryItem = (): ((ref: GalleryItemRef) => void) => {const commands = useWorkbenchCommands();@@ -73,16 +50,8 @@ export const useFindGalleryItem = (): ((ref: GalleryItemRef) => void) => {void import('@workbench/image-actions/revealGalleryItem').then(({ revealGalleryItem }) => revealGalleryItem({ commands, queries, queryClient }, ref, ticket)).catch((error: unknown) => {- // Either the chunk 404'd (a tab left open across a redeploy) or the- // media is gone from the gallery — an ordinary state, since a- // reference outlives the image it was taken from. The widgets are- // already raised, so failing silently would leave the user with a- // rearranged workspace and no explanation for the grid not moving.- //- // Only for the gesture still in force: a press the user has since- // superseded, or left behind in another project, has no claim on- // their attention. The claim itself is not given back — a later press- // was a later intent, and it stands even though it could not be met.+ // Report chunk or media failures only for the still-current gesture, since widgets already moved. Keep+ // the failed gesture's claim so older intents cannot reclaim selection.if (!isGalleryNavigationCurrent(ticket.sequence) || !queries.isActiveProject(ticket.projectId)) {return;}diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsxindex e9dd353f0f..678624f7f2 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx@@ -277,8 +277,7 @@ beforeEach(() => {currentItemActionContext = null;});-// After the account switch, which drops the table, and before the mount, so the Probe renders-// with it present and is unmounted before it is dropped again; the order keeps both inside `act`.+// Seed capabilities after account activation and before mounting so reset and teardown stay inside act.seedArchitectureCapabilities();beforeEach(async () => {@@ -545,9 +544,6 @@ describe('partial image mutation outcomes', () => {boardId: 'board-1',});- // Partial failure: the optimistic patch is rolled back wholesale, the- // confirmed subset re-applied, and the rejected ref returns to the board- // it was captured on.expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();expect(mocks.patchGalleryItemCaches).toHaveBeenNthCalledWith(2, expect.anything(), {boardId: 'board-1',@@ -591,8 +587,6 @@ describe('partial image mutation outcomes', () => {starred: true,});- // The rejected ref must reappear where it was: the cache snapshot comes- // back and only the confirmed ref is re-applied; the store flips it back.expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();expect(mocks.patchGalleryItemCaches).toHaveBeenNthCalledWith(2, expect.anything(), {kind: 'star',@@ -760,8 +754,6 @@ describe('mixed item mutation outcomes', () => {);expect(mocks.galleryRemoveItems).toHaveBeenNthCalledWith(1, ['video:gone.mp4', 'image:locked.png']);- // The failed ref is resurrected by the rollback, then only the confirmed- // ref is removed again.expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();expect(mocks.patchGalleryItemCaches).toHaveBeenNthCalledWith(2, expect.anything(), { kind: 'delete', result });expect(mocks.galleryRemoveItems).toHaveBeenNthCalledWith(2, ['video:gone.mp4']);@@ -810,16 +802,11 @@ describe('total transport failure rollback', () => {// The optimistic removal happened up front, before the transport was asked.expect(mocks.galleryRemoveItems).toHaveBeenNthCalledWith(1, ['image:gone.png']);- // The transport threw outright: the cache rollback captured before the- // mutate call must run on the throw path rather than waiting on the- // (also-failing) trailing invalidation.+ // Transport failures must roll back immediately; trailing invalidation may fail too.expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();- // `gallery.removeItems` is a no-op stub here, so the pre/post-removal- // widget snapshot never actually diverges — nothing to restore, and the- // CAS-guarded restore correctly does nothing. Real restore correctness- // (recentImages, selection, upscale.inputImage, and the concurrent-change- // guard) is covered against the real reducer in galleryOptimisticRollback.test.ts.+ // The removal stub leaves widget state unchanged, so CAS restoration does nothing. Real reducer rollback is+ // covered in galleryOptimisticRollback.test.ts.expect(mocks.galleryWidgetsPatchValues).not.toHaveBeenCalled();expect(mocks.reportError).toHaveBeenCalledOnce();@@ -910,9 +897,7 @@ describe('total transport failure rollback', () => {const beforePaint = makeMockProject('project-1', {recentImages: [{ ...recentImageFixture, boardId: 'board-overlay', imageName: 'overlay-only.png' }],});- // `gallery.patchItems` is a no-op stub here, so simulate its real effect- // by having the snapshot reflect the optimistic paint from the second- // call onward (the first call is the pre-paint `previousBoardIds` capture).+ // Simulate optimistic board state after the initial pre-paint snapshot because patchItems is stubbed.const afterPaint = makeMockProject('project-1', {recentImages: [{ ...recentImageFixture, boardId: 'board-1', imageName: 'overlay-only.png' }],});@@ -933,8 +918,6 @@ describe('total transport failure rollback', () => {expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();- // The cache-known item and the overlay-only item both return to their- // captured prior board.expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:moved.png'], { boardId: 'board-0' });expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:overlay-only.png'], { boardId: 'board-overlay' });@@ -964,9 +947,6 @@ describe('total transport failure rollback', () => {await getItemActions().moveItemsToBoard(refs, 'board-B');});- // The rollback must not force the item back to 'board-A': it's no- // longer on 'board-B' (this move's target), so something else already- // moved it on and that later write must win.expect(mocks.galleryPatchItems).not.toHaveBeenCalledWith(['image:overlay-only.png'], { boardId: 'board-A' });// Only the initial optimistic paint touched the store.expect(mocks.galleryPatchItems).toHaveBeenCalledOnce();@@ -977,12 +957,8 @@ describe('total transport failure rollback', () => {{ kind: 'image' as const, name: 'was-starred.png' },{ kind: 'image' as const, name: 'was-unstarred.png' },];- // One of the two requested items was already starred before this batch;- // a blanket invert-everything rollback would wrongly unstar it too. The- // cache reflects each item's real prior flag pre-paint, then (since- // `patchGalleryItemCaches` is a no-op stub here) the painted flag- // (`true`, this action's target) from the rollback's read onward,- // simulating the optimistic paint having actually landed.+ // Capture each prior flag: one item was already starred, so blanket inversion would corrupt rollback. Later+ // reads simulate the stubbed optimistic paint.mocks.getItemStarred.mockReturnValueOnce(new Map([@@ -1007,8 +983,6 @@ describe('total transport failure rollback', () => {starred: true,});- // Each store item reverts to its own prior flag, not a single blanket- // value; the cache restores the snapshot the optimistic patch returned.expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:was-starred.png'], { starred: true });expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:was-unstarred.png'], { starred: false });expect(mocks.patchGalleryItemCaches).toHaveBeenCalledOnce();@@ -1020,10 +994,7 @@ describe('total transport failure rollback', () => {it('does not clobber a star toggle a concurrent mutation already applied, in either the cache or the store', async () => {const refs = [{ kind: 'image' as const, name: 'shared.png' }];- // Prior: unstarred. This action stars it (painted = true). By the time- // the rollback reads current state, a concurrent toggle already left it- // somewhere other than what this action painted, in both the cache and- // the store overlay.+ // Simulate a concurrent toggle replacing this action's painted flag in both cache and store.mocks.getItemStarred.mockReturnValueOnce(new Map([['image:shared.png', false]])).mockReturnValue(new Map([['image:shared.png', false]]));@@ -1043,10 +1014,6 @@ describe('total transport failure rollback', () => {await getItemActions().setItemsStarred(refs, true);});- // The store restore never ran: the rollback's read of current state- // never matched what this batch painted (`true`), so it correctly assumed- // something else had already written a newer value and left it alone. The- // cache side hands the same decision to the snapshot's own CAS rollback.expect(mocks.galleryPatchItems).toHaveBeenCalledOnce();expect(mocks.patchGalleryItemCaches).toHaveBeenCalledOnce();expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();@@ -1072,8 +1039,7 @@ const galleryItem = (kind: GalleryItem['kind'], name: string): GalleryItem => {describe('primary successor after confirmed deletion', () => {it('selects the next surviving item in display order — the one that takes the deleted slot', async () => {- // Also what keeps deletion out of the leading starred block. Pinned at the- // unit level in core/selection.test.ts.+ // Selection also keeps deletion out of the leading starred block; core/selection.test.ts covers that rule.const before = galleryItem('video', 'before.mp4');const primary = galleryItem('image', 'primary.png');const after = galleryItem('image', 'after.png');@@ -1201,9 +1167,7 @@ describe('primary successor after confirmed deletion', () => {});it('stamps the successor with the page the host navigates from, when the host provides one', async () => {- // The successor comes from the host's own list. Preview anchored deep in a- // board the grid shows from the top would otherwise have it stamped with- // the grid's page, outside the window it came from.+ // Preserve the successor's host page rather than stamping the grid's unrelated navigation window.const before = galleryItem('video', 'before.mp4');const primary = galleryItem('image', 'primary.png');const after = galleryItem('image', 'after.png');diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex 199737d479..221ee8379b 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -81,9 +81,8 @@ import {} from './videoRecall';/**- * Image operations shared by every surface that shows backend images (gallery- * grid, preview, image context menus). Mutations patch the shared Gallery cache- * when possible and explicitly invalidate the affected server state.+ * Share backend image mutations across surfaces; patch Gallery caches optimistically and invalidate affected+ * server state.*/export interface ImageActions extends GalleryItemActions {/** Whether the generate widget's current model can accept another reference image. */@@ -210,11 +209,8 @@ export const useImageActions = ({return project ? getProjectWidgetValues(project, 'video') : {};};- // 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.+ // Snapshot deletion-sensitive widget values across all projects; cache rollback cannot restore them. Diff+ // before/after values for conflict-safe restoration.const applyGalleryItemRemoval = (itemKeys: GalleryItemKey[]): GalleryWidgetKeySnapshotEntry[] => {const before = captureGalleryWidgetKeyValues(queries.getSnapshot().projects);@@ -226,11 +222,8 @@ export const useImageActions = ({const patches = selectRestorableGalleryWidgetPatches(entries, queries.getSnapshot().projects);for (const patch of patches) {- // `patchWidgetValues` is documented "not undoable" (workbenchState.ts);- // this restore works around that by re-applying the exact prior values- // as a forward patch, guarded by the CAS check above. `origin: 'system'`- // keeps it from tripping the auto-route side effects a user-driven- // widget patch would trigger.+ // Restore exact prior values as a CAS-guarded system patch; widget patches are not undoable, and+ // user-origin patches would auto-route.commands.widgets.patchValues(patch.widgetId, patch.values, patch.projectId, 'system');}};@@ -289,9 +282,7 @@ export const useImageActions = ({await applyConfirmed(result, owner.signal);} catch (caught: unknown) {error = caught;- // The whole mutation failed — nothing was confirmed, so the optimistic- // apply must not stand. The trailing invalidation cannot be relied on- // here: whatever killed the mutation (offline) usually kills it too.+ // Roll back total failures immediately; an offline mutation often means invalidation also fails.if (isAccountScopeCurrent(owner)) {rollback?.();}@@ -319,11 +310,8 @@ export const useImageActions = ({reportMutationOutcome(action, requested.length, result, boardId);};const deleteItemsConfirmed = (items: GalleryItemRef[]): Promise<void> => {- // 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.+ // Capture successor context before optimistic removal. Partial failures reconcile via invalidation; total+ // failures restore widget snapshots directly.const deletionContext = getItemActionContext?.() ?? null;let orderedRefs: GalleryItemRef[] | null = null;const isDeletionContextCurrent = (): boolean => {@@ -343,10 +331,8 @@ export const useImageActions = ({kind: 'delete',result: { failed: [], succeeded: items },});- // `rollbackCaches` is invoked from two independent places below (the- // partial-failure branch inside `applyConfirmed`, and the total-failure- // `rollback`): guard so an `applyConfirmed` that throws after already- // rolling back a partial failure can't undo the cache patch twice.+ // Guard cache rollback shared by partial/total failures so an exception after partial restoration cannot+ // roll it back twice.let cachesRolledBack = false;const rollbackCachesOnce = () => {if (cachesRolledBack) {@@ -356,11 +342,7 @@ export const useImageActions = ({cachesRolledBack = true;rollbackCaches();};- // Once `applyConfirmed` starts applying a backend-confirmed result (some- // items really were deleted), nothing after that point may trigger a- // full rollback even if it throws — `onImagesDeleted` is a caller-- // supplied callback invoked after confirmation and can throw for- // reasons that have nothing to do with the mutation itself.+ // Once backend-confirmed deletion starts applying, later callback failures must not restore deleted items.let confirmedApplied = false;const galleryWidgetSnapshot = applyGalleryItemRemoval(items.map(toGalleryItemKey));@@ -464,11 +446,8 @@ export const useImageActions = ({? requestDeletionConfirmation(items, () => deleteItemsConfirmed(items)): deleteItemsConfirmed(items);const moveItemsToBoard = (items: GalleryItemRef[], boardId: string): Promise<void> => {- // 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.+ // On partial move failure, restore then reapply confirmed items. Capture prior boards from cache and store,+ // preferring cache; invalidation reconciles conflicts.const previousBoardIds = new Map<GalleryItemKey, string>([...collectGalleryStoreKnownItemFields(queries.getSnapshot().projects, items)].map(([key, fields]) => [key,@@ -485,9 +464,7 @@ export const useImageActions = ({kind: 'move',result: { failed: [], succeeded: items },});- // See the delete path's `cachesRolledBack` note: `rollbackCaches` is- // reachable both from the partial-failure branch below and from the- // total-failure `rollback`, so guard against undoing it twice.+ // Partial and total failure paths share rollback; guard against applying it twice.let cachesRolledBack = false;const rollbackCachesOnce = () => {if (cachesRolledBack) {@@ -497,11 +474,8 @@ export const useImageActions = ({cachesRolledBack = true;rollbackCaches();};- // 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.+ // Restore store boards only while they still match this move's optimistic board; group by prior board to+ // preserve concurrent moves.const restorePreviousBoardIds = () => {const currentStoreBoardIds = collectGalleryStoreKnownItemFields(queries.getSnapshot().projects, items);const safeKeys = new Set(@@ -567,13 +541,8 @@ export const useImageActions = ({gallery.patchItems(keys, { starred });};const setItemsStarred = (items: GalleryItemRef[], starred: boolean): Promise<void> => {- // Optimistic: paint the whole selection and put back only what the- // backend refuses. The listing and the starred strip partition on the- // flag, so a star moves items between cache windows; the cache side is- // therefore a snapshot/restore pair with its own CAS, like delete and- // move. The store overlay is a value flip, so it captures each item's- // actual prior flag up front — a blanket invert would wrongly flip- // items that already matched.+ // Cache star changes move items between listing partitions and need snapshot/CAS rollback. Store restoration+ // uses each actual prior flag, never blanket inversion.const previousStarred = new Map<GalleryItemKey, boolean>([...collectGalleryStoreKnownItemFields(queries.getSnapshot().projects, items)].map(([key, fields]) => [key,@@ -616,9 +585,8 @@ export const useImageActions = ({},mutate: (signal) => galleryItemOrganization.setStarred(items, starred, signal),requested: items,- // Total failure: the cache restores its snapshot; the store restores- // each item's actual prior flag, leaving items with no known prior as- // painted, and only where the painted value is still what is there.+ // Restore known prior flags only where this action's painted value remains; cache rollback restores its+ // own snapshot.rollback: () => {rollbackCachesOnce();@@ -891,8 +859,7 @@ export const useImageActions = ({projectId,});- // The value patch auto-routes the invoke source (media/settings are- // intent-bearing keys); surfacing the widget is the caller-side touch.+ // The value patch auto-routes invocation; the caller reveals the widget.if (isAccountScopeCurrent(owner) && didRecall && (!projectId || queries.isActiveProject(projectId))) {openWorkbenchWidget('video', { preferredRegions: ['left'] });}@@ -912,8 +879,6 @@ export const useImageActions = ({return;}- // The widget hosts the editor, so it has to be on screen for the- // handoff to be visible.openWorkbenchWidget('generate', { preferredRegions: ['left'] });setPendingPromptTemplateDraft({ negativePrompt, positivePrompt });} catch (error: unknown) {diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.tsindex 01b7a1292f..5e12e75da4 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts@@ -494,9 +494,7 @@ describe('model-position recall shapes', () => {const currentValues = { ...createDefaultVideoWidgetValues([install]) };it('promotes a legacy transformer-override recording onto the model slot before deriving the accelerator', () => {- // Pre model-positions metadata: the Diffusers install as `model`, the- // checkpoint as an override extra. The 4-step Ref2V Turbo derivation only- // succeeds if the promote lands first — it needs the ref2va variant.+ // Promote the legacy transformer override before deriving Ref2V Turbo's four-step accelerator set.const result = buildVideoRecallSettings({currentValues,kind: 'all',@@ -551,9 +549,7 @@ describe('model-position recall shapes', () => {expect(gone?.values.h3HybridBaseModel).toBeNull();expect(gone?.values.h3HybridStartBlock).toBe(currentValues.h3HybridStartBlock);- // A base the panel already holds does not stand in for the uninstalled recorded one: the- // recall reproduces the run, which cannot run that hybrid any more. Base Y's block 30 must- // not land on base X either.+ // An uninstalled recorded hybrid base must not reuse the panel's base or receive its recorded blocks.const otherBase: MainModelConfig = { ...fl2vaBase, key: 'h3-fl2va-other', name: 'Another FL2VA' };const holding = { ...currentValues, h3HybridBaseModel: otherBase, h3HybridStartBlock: 12 };const onto = buildVideoRecallSettings({@@ -606,8 +602,7 @@ describe('model-position recall shapes', () => {expect(bare?.values.h3HybridBaseModel).toBeNull();expect(bare?.fields).not.toContain('components');- // A recall that moves the panel to a main without the hybrid slot drops the base in the- // model transition; that is still this recall clearing it, so the toast says so.+ // Report a hybrid base cleared by the model transition as cleared by recall.const toFl2va = buildVideoRecallSettings({currentValues: holding,kind,@@ -656,9 +651,7 @@ describe('model-position recall shapes', () => {expect(result?.values.componentSourceModel?.key).toBe(install.key);});it('promotes the recorded transformer even when the recorded install itself is gone', () => {- // The transformer defines the run; the panel's current model (a- // checkpoint) stands in for the missing install and must not suppress the- // promote — pre-fix the references were dropped as unsupported.+ // Promote the recorded transformer even when the missing install falls back to the panel's checkpoint.const panelCheckpoint: MainModelConfig = {base: 'minimax-h3',format: 'checkpoint',diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.tsindex a5bee6421e..db7947d43a 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts@@ -23,14 +23,8 @@ import {import { SEED_MAX } from '@platform/core/seed';/**- * Pure mapping from a video's recorded `core_metadata` to a Video-panel- * patch — the sibling of `imageRecall.ts`. Models resolve against the- * installed catalog by key, then hash, then name+base+type (see- * `resolveRecordedModel`); an unresolvable model skips the model field and- * everything downstream validates against the current model instead. The- * conditioning mode is never recalled directly: the panel derives it from- * which media fields are filled, so recall restores the media and lets the- * mode fall out.+ * Map video metadata to panel values using installed model key, hash, then name/base/type. Unresolved models+ * retain the current model for validation. Restore media to derive mode rather than recalling mode directly.*//**@@ -188,12 +182,8 @@ const getMetadataModelRef = (metadata: unknown, key: string): RecordedModelRef |toRecordedModelRef(getRecord(metadata, key));/**- * The installed catalog entry a recorded model refers to. Keys are minted per- * install, so a record that travelled with a downloaded file names keys this- * catalog has never seen; the hash is the content identity and resolves the- * same weights wherever they are installed. Name+base+type is the last- * resort for records without a hash (or a re-quantized copy), and the only- * step that can pick a different file of the same model.+ * Resolve install-local keys, then portable content hashes, then name/base/type. Only the final fallback may+ * select different weights.*/const resolveRecordedModel = <T extends ModelConfig>(ref: RecordedModelRef | null, models: readonly T[]): T | null => {if (!ref) {@@ -251,11 +241,8 @@ const getSourceVideoName = (metadata: unknown): string | null => {};/**- * The keyframe names the recall should restore, per the recorded mode. In- * extend mode `first_frame_image` is the frame the graph EXTRACTED from the- * source clip — derived conditioning, not user input — so restoring it would- * both misrepresent the session and collide with the panel's first-frame ⊻- * initial-video exclusion.+ * In extend mode, first_frame_image was extracted from the source clip; do not restore it as user input or+ * conflict with initial video.*/export const getRecallableMediaNames = (metadata: unknown@@ -300,10 +287,8 @@ const VIDEO_COMPONENT_METADATA_KEYS = [] as const;/**- * The recorded W×H inverted back into the panel's aspect-ratio preset +- * target-resolution pair — exact matches only. A near-miss would silently- * recall a preset the run never used: a non-matching size means the dims came- * from conditioning media, and recalling that media locks the size anyway.+ * Recall aspect/resolution presets only on exact dimension matches; other dimensions came from conditioning media+ * and remain media-controlled.*/export const getVideoSizeRecall = (model: MainModelConfig,@@ -334,12 +319,8 @@ export const getVideoSizeRecall = (};/**- * Whether the recalled LoRA list is itself a complete accelerator set for this- * model, run at the step count that set was distilled for — if so the flag- * (and its recorded keys) come back on, so the panel shows the same fast-path- * state that produced the video. Two Turbo LoRAs are both valid fast paths at- * different step counts, so the set is read off the recalled list rather than- * off whatever the catalog would pick today.+ * Restore acceleration only when recalled LoRAs form a complete set at its distilled step count; derive from+ * recorded keys, not today's catalog preference.*/export const deriveAcceleratorRecallState = (model: MainModelConfig,@@ -347,10 +328,8 @@ export const deriveAcceleratorRecallState = (steps: number,settings: VideoWidgetValues): Pick<VideoWidgetValues, 'acceleratorEnabled' | 'acceleratorLoraKeys'> => {- // The H3 task variant lives on the model itself (a single-file transformer- // checkpoint carries its own variant), and the two tasks have DIFFERENT- // accelerators (fl2va Turbo at 6 or 8 steps, ref2v Turbo at 4 or 8). Callers must- // promote a legacy transformer override onto `model` before deriving this.+ // Promote legacy H3 transformer overrides before deriving task-specific accelerators: fl2va and ref2v use+ // different sets and steps.const accelerator = getVideoModelPolicy(model, settings).ui.accelerator;const recalled = accelerator? findAcceleratorLorasIn(@@ -401,11 +380,7 @@ export interface VideoRecallMediaNames {firstFrameName: string | null;lastFrameName: string | null;sourceVideoName: string | null;- /**- * The recorded trim bounds (metadata extras), so the executor can restore- * the clip's actual trim instead of `createVideoSourceClip`'s default —- * without them a recalled extension would start from the wrong frame.- */+ /** Restore recorded clip trim so extension starts from the original frame rather than the default. */sourceVideoTrim: { endFrame: number; startFrame: number } | null;/*** The recorded Ref2VA references, in conditioning order. Names and options only — the@@ -471,9 +446,7 @@ export const buildVideoRecallSettings = ({const fields: VideoRecalledField[] = [];let values: VideoWidgetValues = { ...currentValues };- // Held aside rather than folded into `values` where it is read: the model- // transition below rebuilds `values` from the recalled family's defaults, and- // recalled prompts must survive that. Merged in at each return instead.+ // Hold prompts outside values until return so model-default transitions cannot overwrite them.let promptPatch: Partial<VideoWidgetValues> | null = null;const mediaNames: VideoRecallMediaNames = {firstFrameName: null,@@ -487,9 +460,7 @@ export const buildVideoRecallSettings = ({const { negativePrompt, positivePrompt } = getMetadataPrompts(metadata);if (positivePrompt !== null || negativePrompt !== undefined) {- // A disabled negative submits as '' — an empty recorded negative is- // indistinguishable from disabled, so it must not flip the toggle on- // (or erase a saved-but-disabled draft's enabled state).+ // An empty recorded negative cannot distinguish disabled from empty; preserve the panel's toggle.promptPatch = {...(positivePrompt !== null ? { positivePrompt } : {}),...(typeof negativePrompt === 'string' && negativePrompt.length > 0@@ -578,9 +549,7 @@ export const buildVideoRecallSettings = ({const fps = getInteger(metadata, 'fps');- // Wan records the delivered frame rate (H3 records its fixed 24, which its- // policy never lets the panel edit). Recalling it into an extend-mode panel is harmless: the fps field- // is display-only there and the compiled graph re-inherits the clip's rate.+ // Wan records delivered fps; extend compilation still inherits clip fps, and H3 fixes it at 24.if (policy.fps.editable && fps !== null && fps >= 1 && fps <= 120) {if (fps !== values.fps) {values = { ...values, fps };@@ -595,8 +564,7 @@ export const buildVideoRecallSettings = ({fields.push('size');}- // Components recall FIRST: the accelerator derivation below resolves the H3 task off the- // recalled transformer override, so `values` must already hold it.+ // Recall components before deriving acceleration so H3 task detection sees the recorded transformer.let componentsRecalled = false;let hybridBaseRecalled = false;@@ -610,14 +578,8 @@ export const buildVideoRecallSettings = ({}}- // The hybrid base reproduces the recorded run exactly: it comes back when- // the run recorded a still-installed one, and is CLEARED otherwise — a run- // without the hybrid (or one whose base is gone) must not keep the panel's- // base, which would misrepresent the run. The required components (source- // install, text encoder) keep the panel's pick on absence instead: they are- // what makes the main runnable, not a record of the run. Reported against- // the ORIGINAL panel state, like media: a base the model transition above- // already dropped was still cleared by this recall.+ // Restore only an installed recorded hybrid base; otherwise clear it and report against the original panel.+ // Required source/text components retain current picks when absent.if (!hybridBaseRecalled) {if (values.h3HybridBaseModel) {values = { ...values, h3HybridBaseModel: null };@@ -642,15 +604,8 @@ export const buildVideoRecallSettings = ({fields.push('components');}- // Legacy metadata shape (pre model-positions): the run recorded the H3- // Diffusers install as `model` with the single-file transformer as an- // override extra. The transformer is the model identity now — promote it,- // so the accelerator derivation below judges the right task. It promotes- // whenever the components loop resolved an installed H3 checkpoint into the- // override slot, even when the recorded install itself is gone (the panel's- // current model then stands in for `model`): the transformer is what- // defines the run. Anything else that landed in the slot (corrupt metadata- // naming a non-main) is dropped rather than left as dangling state.+ // Promote an installed H3 checkpoint from legacy transformer metadata to model identity, even if the recorded+ // Diffusers install is gone. Drop invalid non-main overrides.if (values.h3TransformerModel) {const transformer = values.h3TransformerModel;@@ -685,9 +640,8 @@ export const buildVideoRecallSettings = ({: [];});- // The recall reproduces the recorded LoRA set: empty when the video ran- // without LoRAs, and also when the recorded ones are no longer installed —- // keeping the panel's current LoRAs would misrepresent the run either way.+ // Reproduce the recorded LoRA set, including empty or entirely uninstalled sets; never retain unrelated panel+ // LoRAs.if (resolvedLoras.length > 0 || values.loras.length > 0) {values = {...values,@@ -709,9 +663,7 @@ export const buildVideoRecallSettings = ({currentValues.references.length > 0);- // Media selects the graph family (t2v vs i2v vs extend vs reference), so an all/remix- // recall must reproduce the recorded media EXACTLY: whatever the panel held- // is cleared, and the executor re-hydrates the recorded names on top.+ // All/remix recall clears current media before restoring recorded names because media determines graph family.if (hadMedia) {values = { ...values, firstFrameImage: null, lastFrameImage: null, references: [], sourceVideo: null };}diff --git a/invokeai/frontend/webv2/src/workbench/image-map/api.ts b/invokeai/frontend/webv2/src/workbench/image-map/api.tsindex cfa79d68dc..057789a84b 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/api.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/api.ts@@ -13,12 +13,7 @@ export interface ImageMapPoint {y: number;/** The gallery item this point stands for; videos plot beside images. */item: GalleryItemRef;- /**- * `item`'s gallery key, derived once here. Every comparison the map makes —- * hit-testing a click, masking the selection, keying a hover — is against a- * key, and a 100k-point map re-scans on each wheel-zoom event, so deriving- * it per comparison would allocate a string per point per frame.- */+ /** Cache gallery keys once to avoid per-point string allocation during large-map zoom and selection scans. */key: GalleryItemKey;/** DBSCAN cluster label; -1 means unclustered noise. */cluster: number;@@ -60,11 +55,7 @@ interface BackendImageMapPointsResponse {updated_at: string | null;}-/**- * Opts this client into video items. The backend indexes videos either way and- * serves them only to clients that resolve each item through the endpoint its- * `kind` names — which this one does, so every map request asks for them.- */+/** Opt into videos because item-kind routing resolves both backend namespaces. */const INCLUDE_VIDEOS_PARAM = { include_videos: 'true' } as const;const mapPoints = (body: BackendImageMapPointsResponse): ImageMapPoints => ({@@ -72,9 +63,7 @@ const mapPoints = (body: BackendImageMapPointsResponse): ImageMapPoints => ({modelName: body.model_name ?? null,pointCount: body.point_count,points: body.points.map((point) => {- // Only `video` names the other namespace; anything else is an image, so an- // unexpected value degrades to the kind that has always been on the map- // rather than producing an item no endpoint can resolve.+ // Only explicit video uses its namespace; unknown kinds fall back to image resolution.const item: GalleryItemRef = { kind: point.kind === 'video' ? 'video' : 'image', name: point.image_name };return { cluster: point.cluster, item, key: toGalleryItemKey(item), x: point.x, y: point.y };@@ -116,16 +105,9 @@ interface BackendImageMapStatusResponse {index?: { total: number; embedded: number; failed?: number } | null;}-/**- * Current index/projection status. Only the index counts are read here: the- * projection half of the response duplicates what /points already carries, and- * the counts are the one thing no other call returns.- */+/** Read index counts from status; projection details already come from points. */export const fetchImageMapStatus = async (): Promise<ImageMapStatus> => {- // Sent for consistency with the map's other calls: this reader keeps only- // `index` (which counts both kinds), but the response's projection half is- // kind-filtered by this flag, and a future reader of it should not have to- // discover that the call it inherited asked for a different map.+ // Request the same video-inclusive map as other endpoints, including the unused projection portion.const body = await apiFetchJson<BackendImageMapStatusResponse>(`/api/v1/image_map/status?${new URLSearchParams(INCLUDE_VIDEOS_PARAM).toString()}`);diff --git a/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.browser.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.browser.test.tsindex 8ca7d35397..79193babf2 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.browser.test.ts@@ -4,11 +4,7 @@ import type { AxisRanges } from './imageMapViewport';import { attachWheelZoom } from './attachWheelZoom';-/**- * The gesture bookkeeping needs real pointer and touch events, so this runs in- * the browser suite; the range arithmetic it drives is unit-tested against- * `imageMapViewport` directly.- */+/** Browser events verify gesture bookkeeping; unit tests cover viewport arithmetic. */let detach: (() => void) | null = null;let host: HTMLElement | null = null;diff --git a/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.ts b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.tsindex 4f8e040fde..39c326e37e 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.ts@@ -3,10 +3,8 @@ import type { AxisRanges } from './imageMapViewport';import { zoomFactorFromWheel, zoomRangesAroundFraction } from './imageMapViewport';/**- * Custom wheel + two-finger-pinch zoom for the plotly map. Plotly's built-in- * scrollZoom is deliberately off (long-standing Safari/trackpad issues —- * PhotoMapAI replaced it the same way); single-finger drag still uses- * plotly's native pan.+ * Custom wheel/pinch zoom replaces Plotly scrollZoom for Safari/trackpad behavior, following PhotoMapAI.+ * Single-touch pan remains native.*/interface ZoomHost {@@ -53,10 +51,8 @@ export const attachWheelZoom = (element: HTMLElement, host: ZoomHost): (() => volet pinchDistance: number | null = null;- // Re-baselined on any transition INTO two touches, in either direction. A- // third finger landing mid-pinch suspends the gesture without clearing the- // baseline, so measuring against it after that finger lifts — with the other- // two moved meanwhile — would snap the viewport by an arbitrary factor.+ // Rebaseline every transition into two touches; movement during a third-finger pause must not cause a zoom jump+ // on resume.const handleTouchStart = (event: TouchEvent) => {if (event.touches.length === 2) {pinchDistance = touchDistance(event.touches);diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterPalette.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterPalette.tsindex 89c9b41200..fa226f4926 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/clusterPalette.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterPalette.ts@@ -1,8 +1,4 @@-/**- * Categorical colors for map clusters, cycled by cluster id. Modeled on- * PhotoMapAI's cluster palette: saturated, well-separated hues that read on- * both light and dark plot backgrounds.- */+/** Cluster-id palette modeled on PhotoMapAI, with distinct saturated colors for light/dark backgrounds. */export const CLUSTER_PALETTE = ['#4E79A7','#F28E2B',@@ -32,11 +28,7 @@ export const getClusterColor = (cluster: number): string => {return CLUSTER_PALETTE[cluster % CLUSTER_PALETTE.length];};-/**- * Whether text on this background needs to be dark to stay readable.- * Perceived-brightness formula and threshold from PhotoMapAI, so hover cards- * flip dark/light at the same point its popups do.- */+/** PhotoMapAI's perceived-brightness threshold selects readable dark/light hover text. */export const isClusterColorLight = (hexColor: string): boolean => {const hex = hexColor.replace('#', '');const r = parseInt(hex.slice(0, 2), 16);diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.tsindex fc7af4281e..ecf39e79ec 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts@@ -88,10 +88,7 @@ describe('buildHighlightedPointsTrace', () => {describe('toHighlightRestyle', () => {it('carries every per-point array the highlight trace holds', () => {- // plotly keeps whatever a restyle omits, so an array left behind is then- // indexed at the new point count — which crashes inside scattergl's own- // marker lookup, nowhere near the omission. Selecting a cluster is what- // resizes this trace, so the failure lands on an ordinary click.+ // Plotly retains omitted restyle arrays; stale lengths crash scattergl when cluster clicks resize the trace.const trace = buildHighlightedPointsTrace(POINTS, new Set(['image:a.png' as const, 'video:clip.mp4' as const]));const payload = toHighlightRestyle(trace);@@ -103,8 +100,7 @@ describe('toHighlightRestyle', () => {for (const key of [...perPointKeys, 'customdata', 'x', 'y']) {expect(Object.keys(payload)).toContain(key);}- // Every entry is wrapped for the one trace it restyles, and describes the- // same points.+ // Wrap every property for one trace and keep point arrays aligned.for (const value of Object.values(payload)) {expect(value).toHaveLength(1);expect(value[0]).toHaveLength(trace.x.length);@@ -119,8 +115,7 @@ describe('buildClusterAnnotations', () => {expect(annotations).toHaveLength(1);const landscapes = annotations[0];- // Centered on the cluster's x centroid, anchored above its topmost point- // with a pixel lift so the label never covers the points it names.+ // Anchor at cluster x-centroid above its top point with fixed-pixel clearance.expect(landscapes?.x).toBeCloseTo(4 / 3);expect(landscapes?.y).toBeCloseTo(5);expect(landscapes?.yanchor).toBe('bottom');@@ -151,9 +146,7 @@ describe('buildClusterAnnotations', () => {});describe('declutterAnnotations', () => {- // Cluster 0: three points near the origin; cluster 1: one point at (10, 0).- // The small cluster's point deliberately comes first, so these tests fail- // if the size-priority ordering in buildClusterAnnotations regresses.+ // Place the smaller cluster first to prove size priority overrides input order.const clusters = [point('far.png', 10, 0, 1),point('a.png', 0, 0, 0),@@ -190,10 +183,8 @@ describe('declutterAnnotations', () => {});it('drops labels covering the current-image marker, which draws beneath them', () => {- // Zoomed in, both labels normally survive (see the first case). Putting the- // marker on the 'portraits' anchor at (10, 0) evicts that label instead:- // the gold target is on the WebGL canvas under plotly's annotation layer,- // so it cannot be stacked over a pill it overlaps.+ // Hide the label overlapping the gold target: SVG annotations sit above WebGL markers and cannot be reordered+ // below them.const ranges = { x: [-0.5, 10.5] as [number, number], y: [-4, 4] as [number, number] };const kept = declutterAnnotations(annotations, ranges, view.widthPx, view.heightPx, { x: 10, y: 0 });expect(kept.map((annotation) => annotation.text)).toEqual(['landscapes']);@@ -203,19 +194,14 @@ describe('declutterAnnotations', () => {const ranges = { x: [-0.5, 10.5] as [number, number], y: [-4, 4] as [number, number] };const kept = declutterAnnotations(annotations, ranges, view.widthPx, view.heightPx, { x: 5, y: -3.5 });expect(kept.map((annotation) => annotation.text)).toEqual(['landscapes', 'portraits']);- // A null marker (nothing selected, or the selection is off the map) is the- // same as passing none at all.expect(declutterAnnotations(annotations, ranges, view.widthPx, view.heightPx, null)).toEqual(declutterAnnotations(annotations, ranges, view.widthPx, view.heightPx));});it('does not hand the space it clears to a lower-priority label', () => {- // 'portraits' (1 point) anchors ~55px from 'landscapes' (3 points): inside- // the bigger label's footprint, outside the marker's clearance. Without the- // marker, 'landscapes' wins the spot and 'portraits' is dropped. Parking- // the marker on 'landscapes' must not promote 'portraits' into the very- // patch of map the marker was supposed to clear.+ // A marker hiding the larger winning label must not promote a smaller overlapping label into the cleared+ // region.const crowded = [point('a.png', 0, 0, 0),point('b.png', 1, 0, 0),@@ -236,12 +222,7 @@ describe('declutterAnnotations', () => {});it('leaves labels the marker does not cover exactly as they were', () => {- // Three labels 50px apart: 'bbb' loses its spot to 'aaa' and is invisible- // with or without a marker, while 'ccc' clears 'aaa' and survives. Parking- // the marker on 'bbb' — whose 11px rect reaches neither neighbour — must- // change nothing: a label that never won a spot cannot reserve one, or- // selecting an image under an already-suppressed label would silently take- // out the cluster next door.+ // An already-suppressed label reserves no space; placing a marker there must not evict neighboring labels.const row = [point('a1.png', 0, 0, 0),point('a2.png', 0, 0, 0),diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.tsindex d15f90532f..1e678c30bf 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts@@ -2,14 +2,7 @@ import type { GalleryItemKey } from '@features/gallery/contracts';import type { ImageMapPoint } from './api';-/**- * Cluster-click selection: everything in the clicked point's cluster,- * ordered by distance from the clicked point (PhotoMapAI's proximity- * ordering) so gallery multi-selection walks outward from the click.- *- * Members are item keys: a cluster groups by what the encoder saw, so a video- * sits in the same cluster as the images that look like it.- */+/** Cluster clicks select image/video keys ordered outward by distance, following PhotoMapAI proximity ordering. *//** Selection size guard; DBSCAN can put most of a huge gallery in one cluster. */export const MAX_CLUSTER_SELECTION = 5000;diff --git a/invokeai/frontend/webv2/src/workbench/image-map/events.ts b/invokeai/frontend/webv2/src/workbench/image-map/events.tsindex bf4a59137f..9881504bb5 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/events.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/events.ts@@ -1,10 +1,4 @@-/**- * Typed contracts for the backend Socket.IO events the image map consumes.- * Payload shapes mirror the pydantic models in- * `invokeai/app/services/events/events_common.py` (serialized as snake_case).- * These events belong to the image-map domain, so they live here rather than- * in a feature's event map.- */+/** Image-map Socket.IO contracts mirror snake_case models in events_common.py and remain owned by this domain. *//** Embedding-index progress counts. Routed to admins only by the backend. */export interface ImageIndexStatusEvent {@@ -12,19 +6,13 @@ export interface ImageIndexStatusEvent {embedded: number;pending: number;/**- * Images given up on after repeated embedding failures. Excluded from- * `pending`, so it is the only thing that explains a settled index where- * `embedded` never reaches `total`. Optional: the backend defaults it to 0,- * and an older server omits it entirely.+ * Failed embeddings are excluded from pending, explaining settled totals above embedded counts. Optional for+ * older servers; default zero.*/failed?: number;}-/**- * Counts-free poke to one user whose images were just (re)embedded, routed- * to that user's room only. This is what lets a non-admin's map refresh- * after their own generations: the status event above never reaches them.- */+/** User-room refresh signal after embedding; nonadmins need it because admin index status never reaches them. */export interface ImageIndexUpdatedEvent {user_id: string;}diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.tsindex da20311f6b..98e9fef23f 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts@@ -19,8 +19,7 @@ import { clearImageLabels, getImageLabels } from './imageLabelCache';describe('image map image-label cache', () => {beforeEach(() => {mocks.apiFetchJson.mockReset();- // Each activation owns a fresh cache: the previous test's entries (and- // any 409 latch) are account state and go with the account.+ // Each activation gets account-owned cache/cooldown state, cleared on account transition.accountLifecycle.invalidate();accountLifecycle.activate('user-a');});@@ -86,8 +85,7 @@ describe('image map image-label cache', () => {vi.useFakeTimers();try {- // A backend or proxy restart mid-sweep must not permanently blank the- // tags of every image the pointer crossed during the outage...+ // Temporary outages must not cache empty tags permanently for hovered items.mocks.apiFetchJson.mockRejectedValue(new ApiError('bad gateway', 502));await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toBeNull();await expect(getImageLabels({ kind: 'image', name: 'b.png' })).resolves.toBeNull();@@ -141,9 +139,7 @@ describe('image map image-label cache', () => {});it('drops cached labels when a vocabulary rebuild lands', async () => {- // The phrases these are scored against are admin-editable, so a rebuild- // makes every cached answer stale — including a cooldown that was only- // ever waiting for that rebuild.+ // Vocabulary rebuild invalidates all answers and the cooldown waiting for that rebuild.mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });await getImageLabels({ kind: 'image', name: 'a.png' });expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.tsindex 1bff4fdcbc..c57303edf9 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts@@ -13,30 +13,21 @@ import type { ImageMapImageLabels } from './api';import { fetchImageMapImageLabels } from './api';/**- * Item-key → vocabulary-labels cache for map hover cards. Labels derive from- * the item's stored embedding, which never changes, and the labeling- * vocabulary, which does: an admin can edit the supplementary term list. So- * results (including "no labels for this item") are cached until a- * vocabulary rebuild lands, at which point `clearImageLabels` drops them.+ * Caches per-item vocabulary labels, including empty results, until vocabulary rebuild. Embeddings are stable;+ * editable vocabulary determines invalidation.*/const labels = new Map<string, ImageMapImageLabels | null>();const inflight = new Map<string, Promise<ImageMapImageLabels | null>>();/**- * How long a server-wide failure suppresses further requests. Such a failure- * is not about this image, so hovering across the map would otherwise fire one- * doomed request per point — but it is not necessarily permanent either: the- * vocabulary is built lazily by the index worker, and every call until that- * build lands answers "still being prepared". A cooldown backs off without- * giving up.+ * Server-wide cooldown prevents one failing request per hovered point while allowing recovery after lazy+ * vocabulary build or outage.*/const UNAVAILABLE_COOLDOWN_MS = 60_000;let unavailableUntil = 0;-// Labels are account-owned gallery data: drop them on login/logout so one-// account's hovers can never serve another account's labels. The cooldown is-// account state too — a different login may have a different backend.+// Clear labels and cooldown on login/logout to prevent cross-account results or backend failure state.registerAccountOwnedResource({clear: () => {labels.clear();@@ -47,12 +38,8 @@ registerAccountOwnedResource({});/**- * Drop every cached label. Called when a supplementary-vocabulary rebuild- * lands: the same phrases the cluster labels are re-fetched for also decide- * these, and a card pairing freshly-fetched cluster tags with tags scored- * against the previous vocabulary would be quietly inconsistent. Also clears- * the cooldown, since a completed rebuild is exactly what a 409 was waiting- * for.+ * Vocabulary rebuild clears hover labels and cooldown so item tags agree with refreshed cluster labels and+ * pending-build retries resume.*/export const clearImageLabels = (): void => {labels.clear();@@ -96,20 +83,15 @@ export const getImageLabels = (item: GalleryItemRef): Promise<ImageMapImageLabel}if (error instanceof ApiError && (error.status === 409 || error.status >= 500)) {- // Server-wide and possibly temporary: a 409 means the vocabulary may- // still be building, a 5xx that the backend is unwell. Back off rather- // than cache anything per item — but back off, because this is driven- // by pointer movement, and a deterministic failure would otherwise- // refire several times a second for the rest of the session.+ // Treat 409/build and 5xx outages as temporary server-wide failures: back off without caching per-item+ // results.unavailableUntil = Date.now() + UNAVAILABLE_COOLDOWN_MS;} else if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {- // The only definitive per-item answers: not indexed, or not visible- // to this account. Nothing about this session can change either.+ // Cache definitive item misses: not indexed or not visible to this account.labels.set(key, null);}- // Everything else (5xx, 429, a dropped connection) is transient and is- // deliberately not cached: the next hover of this item retries.+ // Other transient failures remain uncached so later hover retries.return null;}).finally(() => {diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.tsindex 3e238c80ad..f62d9360dc 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts@@ -52,11 +52,8 @@ const BACKEND_RESPONSE = {visible_hash: 'hash-1',};-// A labels response stamped for some other projection, which the store must-// discard. Tests that exercise the points/status flows answer labels requests-// with this: a body without a `labels` key throws a TypeError in the api-// mapping, which the store classifies as a network failure and retries —-// arming a real-timer chain that outlives the test.+// Return valid labels stamped for another projection to exercise discard. Malformed fixtures throw TypeError and+// arm network retries beyond the test.const FOREIGN_LABELS_RESPONSE = { labels: {}, updated_at: 'another projection', visible_hash: 'another set' };const mockPointsWithForeignLabels = (): void => {@@ -188,8 +185,7 @@ describe('image map store', () => {'0': { alternates: ['kittens', 'pets'], label: 'cats' },});});- // Stamped with the set they were clustered over, so a consumer can tell- // they still describe the drawn points.+ // Fingerprint labels with their clustered visible set.expect(imageMapStore.getSnapshot().clusterLabelsHash).toBe(BACKEND_RESPONSE.visible_hash);});@@ -211,10 +207,8 @@ describe('image map store', () => {expect(imageMapStore.getSnapshot().clusterLabelsHash).toBe(BACKEND_RESPONSE.visible_hash);});- // L2: a refresh over a drifted set, whose labels have not come back yet.- // DBSCAN may have renumbered every cluster, so the labels still in the- // store describe a clustering that is no longer drawn — the hash must say- // so for the whole window rather than only once new labels arrive.+ // While new labels lag refreshed points, retain the old fingerprint so consumers reject potentially renumbered+ // cluster labels.const drifted = { ...BACKEND_RESPONSE, visible_hash: 'hash-2' };mocks.apiFetchJson.mockImplementation((url: string) =>url.startsWith('/api/v1/image_map/cluster_labels') ? new Promise(() => {}) : Promise.resolve(drifted)@@ -248,8 +242,7 @@ describe('image map store', () => {'/api/v1/image_map/cluster_labels?include_videos=true&eps=0.42');});- // Flush the response handler: cluster ids from a different visible set- // must not be applied to the rendered map.+ // Settle the handler and reject cluster ids from a different visible set.await new Promise((resolve) => {setTimeout(resolve, 0);});@@ -450,10 +443,8 @@ describe('image map store', () => {});it('clears labels when the newest request fails outright', async () => {- // L1 lands labels; L2's request then fails with its sequence still- // current — the failure must wipe them rather than leave L1's clustering- // annotated over the newer point set. (L2's failure is a plain Error:- // non-retryable, so no timer is armed either.)+ // Current-request failure clears older labels instead of annotating new points with stale clusters; plain+ // Error avoids retry timers.mocks.apiFetchJson.mockImplementation((url: string) => {if (url.startsWith('/api/v1/image_map/cluster_labels')) {return Promise.resolve({@@ -526,11 +517,8 @@ describe('image map store', () => {});it('collapses mid-flight refresh requests into one rerun', async () => {- // The socket runtime can call refresh while the first load is still in- // flight (projection-ready is admitted during 'loading'), and several- // events may land inside one fetch's window. Every caller must join the- // in-flight request, and exactly one rerun may follow — not one per- // caller, and never a parallel fetch.+ // Concurrent refreshes join one in-flight fetch and coalesce into exactly one follow-up, including socket+ // events during initial load.const pointsResolvers: Array<(value: typeof BACKEND_RESPONSE) => void> = [];mocks.apiFetchJson.mockImplementation((url: string) => {if (url.startsWith('/api/v1/image_map/points')) {@@ -586,9 +574,6 @@ describe('image map store', () => {refreshImageMapPoints();await first;- // The rerun ran (a second points fetch) despite the first one failing,- // and it recovered the map. Without the queued rerun, pointsCall would- // sit at 1 and loadState at 'error'.await vi.waitFor(() => expect(pointsCall).toBe(2));await new Promise((resolve) => {setTimeout(resolve, 0);@@ -622,8 +607,7 @@ describe('trace builders', () => {expect(trace.y).toEqual([2, 4]);// Keys, not bare names: a click has to know which namespace to resolve in.expect(trace.customdata).toEqual(['image:a.png', 'video:clip.mp4']);- // Kind gets the one channel colour and size do not already carry, so a- // clip is findable on the map without hovering every point.+ // Marker shape exposes video kind independently of cluster color and size.expect(trace.marker.symbol).toEqual(['circle', 'diamond']);expect((trace.marker.color as string[])[0]).toBe(getClusterColor(0));// Noise points are dimmed relative to clustered points.@@ -657,10 +641,7 @@ describe('trace builders', () => {describe('map layout stability', () => {it('pins uirevision to a constant so pan/zoom survives a data refresh', () => {- // The whole point of uirevision is that plotly keeps the user's viewport- // when the traces change. A value derived from the data (a point count, a- // hash, a timestamp) would compare unequal on every refresh and silently- // reset the view — which looks identical to "it works" in a static test.+ // Stable uirevision preserves viewport across data refreshes; data-derived revisions would silently reset it.const first = buildMapLayout();const second = buildMapLayout();@@ -704,8 +685,7 @@ describe('snapshot transitions', () => {});it('clears a render failure on a successful refresh so the plot can retry', () => {- // Without this the WebGL error is permanent for the session: the view stops- // mounting the plot, and nothing else ever resets renderError.+ // Retry must clear renderError so a transient WebGL failure can remount the plot.imageMapStore.setSnapshot({clusterLabels: null,clusterLabelsHash: null,@@ -836,9 +816,7 @@ describe('image index progress', () => {});it('re-reads the counts on every mount, not just the first load of the map', async () => {- // The widget is routinely reopened long after the first load — mid-- // backfill, with the worker parked and no event due — which is exactly- // when the panel has nothing else to show.+ // Reopening mid-backfill must fetch counts even if the worker is paused and no event is due.mocks.apiFetchJson.mockImplementation((url: string) =>url.startsWith('/api/v1/image_map/status')? Promise.resolve({ enabled: true, index: { embedded: 70, failed: 0, total: 100 } })@@ -879,8 +857,7 @@ describe('image index progress', () => {});it('runs one status request at a time so an older response cannot land last', async () => {- // Concurrent requests resolve in no fixed order, and every mount, retry- // and reconnect asks for one.+ // Mount, retry and reconnect requests must coalesce despite unordered completions.const resolvers: Array<(value: unknown) => void> = [];mocks.apiFetchJson.mockImplementation(() =>@@ -895,8 +872,6 @@ describe('image index progress', () => {expect(resolvers).toHaveLength(1);- // ...and the claim is released once it settles, so the next caller is not- // locked out for the rest of the session.resolvers[0]?.({ enabled: true, index: { embedded: 40, failed: 0, total: 100 } });await vi.waitFor(() => expect(imageMapStore.getSnapshot().indexCounts).not.toBeNull());diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.tsindex 1516572f3b..ab6b1f8311 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts@@ -1,8 +1,3 @@-/**- * Accessors for the Image Map widget's persisted view settings, so the header- * toggle and the view read the same shape from one place.- */-export const getImageMapClickSelectsCluster = (values: Record<string, unknown>): boolean =>values.clickSelectsCluster === true;diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.tsindex ee2508711a..fc12af49d2 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts@@ -12,11 +12,7 @@ import type { ImageIndexCounts } from './indexProgress';import { fetchImageMapClusterLabels, fetchImageMapPoints, fetchImageMapStatus } from './api';import { hasProgressed } from './indexProgress';-/**- * Read model for the semantic image map, shared by the widget body and any- * future header/footer chrome. One store, one in-flight fetch; refreshes are- * driven by user action now and by socket events in a later runtime.- */+/** Shared image-map read model with one in-flight fetch and refreshes from user actions and socket events. */export interface ImageMapSnapshot {data: ImageMapPoints | null;@@ -24,34 +20,18 @@ export interface ImageMapSnapshot {error: string | null;/** Embedding-index progress; only ever pushed to admins by the backend. */indexCounts: ImageIndexCounts | null;- /**- * When the index last actually moved, so the UI can say how long it has- * stood still. Not when the counts were last written: `total` shifts- * whenever anyone saves or deletes an image, and a generation running while- * the indexer waits for it must not read as the index progressing. Null- * whenever there are no counts.- */+ /** Time of actual indexing progress, not count writes or gallery-total changes. Null without counts. */indexUpdatedAt: number | null;/** Cluster id -> automatic label info; null when unavailable (e.g. no text encoder). */clusterLabels: Record<string, ImageMapClusterLabelInfo> | null;/**- * The visible-set fingerprint `clusterLabels` were computed over, so a- * consumer can tell whether they still describe the drawn clustering.- *- * Labels lag their points by a request: a refresh replaces `data` while the- * previous clustering's labels are still in the store, and DBSCAN can- * renumber every cluster between the two. Annotations have always accepted- * that lag (clearing them on each refresh would blink every label off and- * back on), but a consumer making a stronger promise — the hover card names- * one specific cluster — compares this against `data.visibleHash` and shows- * nothing rather than another cluster's tags.+ * Fingerprint of the visible set used for cluster labels. Labels may lag refreshed points whose cluster ids+ * changed; precise consumers such as hover cards require equality with `data.visibleHash`.*/clusterLabelsHash: string | null;/**- * The plot canvas itself failed (WebGL unavailable). Distinct from `error`,- * which means a fetch failed: with `error` the cached points are still worth- * showing, whereas here there is nothing that can draw them, so the view must- * stop mounting the plot and say so.+ * Plot/WebGL failure differs from fetch failure: cached points remain useful after fetch errors, but render+ * errors require unmounting the plot and reporting inability to draw.*/renderError: string | null;}@@ -82,8 +62,7 @@ registerAccountOwnedResource({clear: () => {inflight = null;rerunRequested = false;- // Orphan any in-flight labels request so its completion (or failure)- // cannot touch the next account's labels.+ // Retire label requests so old-account completion/failure cannot update the new account.labelsSequence += 1;statusInflight = null;indexEventSequence += 1;@@ -94,9 +73,8 @@ registerAccountOwnedResource({export const refreshImageMapPoints = (): Promise<void> => {if (inflight) {- // A refresh requested mid-flight (e.g. projection_ready arriving while- // the fetch that triggered the recompute is still running) must not be- // swallowed by the dedup: run once more when the current fetch settles.+ // Coalesce mid-flight refresh requests into one rerun after settling instead of swallowing them through+ // dedupe.rerunRequested = true;return inflight;@@ -111,9 +89,7 @@ export const refreshImageMapPoints = (): Promise<void> => {return;}- // renderError is cleared too: a retry is the user's way out of a- // transient WebGL failure, so a fresh point set must get a fresh attempt- // at drawing rather than staying stuck on the previous canvas failure.+ // Clear renderError on retry so fresh points receive a new WebGL draw attempt.imageMapStore.patchSnapshot({ data, error: null, loadState: 'loaded', renderError: null });refreshClusterLabels(data);})@@ -173,19 +149,8 @@ const areLabelMapsEqual = ();};-/**- * Labels are decoration: fetched best-effort after the points land. Cluster- * ids are only meaningful against the projection the points came from, so a- * label response for a different projection — or one overtaken by a newer- * request — is discarded rather than mislabeling clusters.- */-/**- * Whether the map is currently showing labels. Pushed down from the widget's- * toggle so the request can be skipped outright: labelling costs the server a- * DBSCAN pass over the visible set, an embedding gather and a 1675-way matmul- * per cluster, and it is precisely the people with galleries large enough to- * feel that who turn the labels off.- */+/** Best-effort labels must match point projection and current request sequence before publication. */+/** Skip labels entirely when hidden, avoiding server clustering, embedding gathers and vocabulary scoring. */let clusterLabelsEnabled = true;export const setClusterLabelsEnabled = (enabled: boolean): void => {@@ -211,22 +176,14 @@ export const setClusterLabelsEnabled = (enabled: boolean): void => {};/**- * Backoff for a labels request the server could not answer yet. The 409 the- * vocabulary build window answers with literally says "try again shortly":- * the build is already queued server-side the moment that response is sent,- * and the index worker lands it within seconds (a 1s poll, plus a disk-cached- * phrase matrix). The schedule's tail covers a cold build — minutes on a- * fresh install — while staying bounded; after it exhausts, the state is the- * old one: no labels until the next points refresh or the label toggle.+ * Bounded label backoff covers pending vocabulary builds, including cold starts. After exhaustion, the next points+ * refresh or label toggle retries.*/const LABELS_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000, 30_000, 60_000, 60_000, 60_000];/**- * Failures worth retrying: the 409s (`TextSearchUnavailableError` — the- * vocabulary still building, or the text tower absent), 5xx, and the network- * refusal of a restarting backend (`fetch` rejects with TypeError). Auth and- * contract failures (401, 403, 422) are permanent from this client's side and- * settle on the first response.+ * Retry 409 vocabulary/text-tower unavailability, 5xx and fetch TypeErrors. Auth/contract failures 401, 403 and+ * 422 settle immediately.*/const isRetryableLabelsFailure = (error: unknown): boolean => {if (error instanceof ApiError) {@@ -236,17 +193,10 @@ const isRetryableLabelsFailure = (error: unknown): boolean => {return error instanceof TypeError;};-/**- * One attempt of the labels fetch, retrying retryable failures on the- * schedule above. The `sequence` is the guard every deferred step re-checks:- * a newer labels request, the label toggle, or an account switch bumps it and- * retires this attempt's callbacks outright.- */+/** Every deferred retry checks sequence; newer requests, toggles and account switches retire prior callbacks. */const attemptClusterLabels = (sequence: number, data: ImageMapPoints, attempt: number): void => {- // Pass the points' effective eps so both requests cluster with the same- // value — the adaptive default is derived from the visible set, which can- // drift between the two requests. Same eps alone does not pin cluster ids- // under drift; the visibleHash comparison below discards those responses.+ // Reuse the points' effective eps, but still require visibleHash equality because cluster ids can drift with the+ // visible set.void fetchImageMapClusterLabels(data.clusterEps !== null ? { eps: data.clusterEps } : undefined).then((response) => {const current = imageMapStore.getSnapshot();@@ -277,11 +227,8 @@ const attemptClusterLabels = (sequence: number, data: ImageMapPoints, attempt: nreturn;}- // Nothing else re-requests labels on its own: a plain widget activation- // fetches no points (the store is already loaded), and the next socket- // event can be minutes away. Without this retry, one 409 in the- // vocabulary-build window after a backend restart leaves the map- // label-less until the user toggles labels off and back on.+ // Retry pending vocabulary responses because loaded-widget activation may fetch nothing and the next socket+ // event may be far away.const delay = LABELS_RETRY_DELAYS_MS[attempt];setTimeout(() => {if (sequence === labelsSequence) {@@ -311,13 +258,7 @@ const refreshClusterLabels = (data: ImageMapPoints): void => {attemptClusterLabels(sequence, data, 0);};-/**- * Re-fetch labels for the currently loaded points. For callers outside the- * points-refresh flow whose action changes what the labels *say* without- * moving a single point — today that is a supplementary-vocabulary edit, once- * the server reports its embedding rebuild finished. A no-op while labels are- * toggled off or no points are loaded.- */+/** Refresh labels without moving points after vocabulary rebuild; no-op when labels are hidden or points absent. */export const refetchClusterLabels = (): void => {const { data } = imageMapStore.getSnapshot();@@ -327,11 +268,8 @@ export const refetchClusterLabels = (): void => {};/**- * Fold one status report into the snapshot.- *- * `measure` marks a socket-delivered report. Only those bump the sequence a- * status fetch checks itself against, so a fetch cannot rewind counts an event- * delivered while it was in flight.+ * Socket reports alone bump the fetch-fencing sequence, preventing older status fetches from rewinding event+ * counts.*/export const recordImageIndexStatus = (counts: ImageIndexCounts,@@ -343,32 +281,19 @@ export const recordImageIndexStatus = (}const { indexCounts: previous, indexUpdatedAt: previousAt } = imageMapStore.getSnapshot();- // Only real progress restarts the clock. A re-read that returns the same- // work done — which is every re-read while the indexer waits out a- // generation, since `total` moves as that generation saves images — would- // otherwise hide exactly the stall the note exists to report.+ // Restart the stall clock only for actual completed work, not repeated counts or generation-driven total+ // changes.const updatedAt = hasProgressed(previous, counts) ? at : (previousAt ?? at);imageMapStore.patchSnapshot({ indexCounts: counts, indexUpdatedAt: updatedAt });};/**- * Pull the counts from the status endpoint.- *- * Status events only fire as batches complete, so without this a panel opened- * while the worker is parked (it waits out every generation) shows no progress- * at all until the queue moves again — and a client that was disconnected when- * the run's final `pending === 0` event went out would otherwise show a- * finished backfill as still running until the page is reloaded. Called on the- * first load, on every socket reconnect, and from the panel's own retry.- *- * Best-effort: a failure just leaves the socket to fill the counts in.+ * Best-effort status fetch recovers paused-worker counts and missed completion events on load/reconnect/retry.+ * Failure leaves socket reports authoritative.*/export const refreshImageIndexStatus = (): void => {- // One at a time, like the point set above. Every widget mount, every retry- // click and every reconnect calls this, and concurrent requests resolve in- // no particular order: without the dedup the *oldest* response can land last- // and rewind the counts to what the server said before the newer one asked.+ // Deduplicate status requests so an older response cannot land last and rewind counts.if (statusInflight) {return;}@@ -389,8 +314,7 @@ export const refreshImageIndexStatus = (): void => {recordImageIndexStatus(status.index, Date.now(), { measure: false });}).catch(() => {- // Progress detail is optional chrome; the map itself reports its own- // load failures.+ // Progress failure is optional detail; point loading reports its own errors.}).finally(() => {// Release only this request's claim: an account switch already cleared@@ -408,9 +332,7 @@ export const ensureImageMapLoaded = (): void => {void refreshImageMapPoints();}- // Unguarded, unlike the point set: the counts are one cheap request, and the- // widget may well be reopened long after the first load — mid-backfill, with- // the worker parked and no event due — which is exactly the case the panel- // exists for. The store's own guards stop it rewinding anything newer.+ // Always refresh cheap status counts on reopen; a paused worker may emit no event. Store guards prevent stale+ // rewinds.refreshImageIndexStatus();};diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.tsindex fcfa43ba57..a802181533 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts@@ -7,10 +7,8 @@ import type { AxisRanges } from './imageMapViewport';import { getClusterColor } from './clusterPalette';/**- * Pure trace/layout builders for the map, kept apart from the plotly host so- * the math is testable without WebGL. Trace identity follows PhotoMapAI:- * named traces in a fixed z-order, with "Current Image" always last so the- * gold marker renders on top.+ * Pure WebGL-independent trace builders follow PhotoMapAI's fixed named order, placing Current Image last so gold+ * markers render above other traces.*/export const ALL_POINTS_TRACE = 'All Points';@@ -53,9 +51,7 @@ export const buildAllPointsTrace = (points: ImageMapPoint[]): ScatterTrace => ({color: points.map((point) => getClusterColor(point.cluster)),opacity: points.map((point) => (point.cluster < 0 ? NOISE_OPACITY : POINT_OPACITY)),size: 5,- // Videos are diamonds. Color already carries the cluster, so kind needs- // the one remaining channel: without it a clip is pixel-identical to an- // image and can only be found by hovering points one at a time.+ // Diamonds identify videos independently of cluster color without requiring hover.symbol: points.map((point) => (point.item.kind === 'video' ? VIDEO_SYMBOL : IMAGE_SYMBOL)),},mode: 'markers',@@ -65,11 +61,7 @@ export const buildAllPointsTrace = (points: ImageMapPoint[]): ScatterTrace => ({y: points.map((point) => point.y),});-/**- * The gallery's multi-selection (e.g. a cluster click), drawn larger with a- * white outline over the base points. Empty when fewer than two items are- * selected — a single selection is already marked by the gold target.- */+/** White-outlined enlarged multi-selection trace; fewer than two items need only the gold current target. */export const buildHighlightedPointsTrace = (points: ImageMapPoint[],selectedKeys: ReadonlySet<GalleryItemKey>@@ -98,10 +90,7 @@ export const buildHighlightedPointsTrace = (};};-/**- * The gold target marking the current gallery image. Built empty here; a later- * PR restyles it live as the selection changes.- */+/** Gold current-item target, populated by live selection restyles. */export const buildCurrentImageTrace = (): ScatterTrace => ({customdata: [],// 'skip' (not 'none') excludes the marker from hit-testing entirely, so@@ -121,19 +110,13 @@ export const buildCurrentImageTrace = (): ScatterTrace => ({y: [],});-// Theme-independent grid: visible but recessive on both light and dark-// map backgrounds; the axis origin is slightly stronger for orientation.+// Theme-independent grid with a stronger origin for orientation.const GRID_LINE_COLOR = 'rgba(128, 128, 128, 0.16)';const GRID_ZERO_COLOR = 'rgba(128, 128, 128, 0.32)';/**- * The restyle payload for the highlight overlay: every per-point array the- * trace carries, so the overlay can be updated in place.- *- * Derived from the trace rather than listed at the call site, because plotly- * keeps whatever a restyle omits — so leaving one array behind means it is- * indexed at the NEW point count, and scattergl dies inside its own marker- * lookup rather than anywhere near the omission.+ * Restyle every per-point array derived from the trace. Plotly retains omitted arrays, causing scattergl length+ * mismatches after selection changes.*/export const toHighlightRestyle = (trace: ScatterTrace): Record<string, unknown[]> => ({customdata: [trace.customdata],@@ -156,9 +139,6 @@ export const buildMapLayout = (// Preserves the user's pan/zoom across Plotly.react data updates.uirevision: 'image-map',xaxis: {- // Unlabeled gridlines give the eye a frame of reference when the map is- // sparse. Mid-gray at low alpha reads on every theme background, like- // the rest of the map's fixed styling.gridcolor: GRID_LINE_COLOR,gridwidth: 1,range: initialRanges?.x,@@ -196,15 +176,8 @@ export interface ClusterAnnotation {}/**- * One text annotation per labeled cluster: centered horizontally on the- * cluster but anchored just above its topmost point (a fixed pixel lift, so- * zoom never lands the label on the points it names). White-on-dark pill- * styling is theme-independent — it reads on every map background.- * Pure so placement math is testable; plotly consumes the array via layout.- *- * Ordered by cluster size (largest first, cluster id as the tiebreak): array- * order is the keep-priority for declutterAnnotations, so when two labels- * collide the one naming more items survives.+ * Place theme-independent cluster pills above topmost points with fixed-pixel clearance. Sort largest clusters+ * first, then id, defining declutter priority.*/export const buildClusterAnnotations = (points: ImageMapPoint[],@@ -245,18 +218,12 @@ export const buildClusterAnnotations = (}));};-// Label extent estimates for collision testing. Annotations render in an SVG-// layer we cannot measure before drawing, so the pill's footprint is-// approximated from its text length at the fixed 10px font.+// Estimate SVG label collision width from fixed-10px text length because labels cannot be measured before drawing.const LABEL_CHAR_WIDTH_PX = 6;const LABEL_HEIGHT_PX = 18;/** Two labels closer than this (edge to edge) count as colliding. */const LABEL_GAP_PX = 4;-/**- * Half-extent of the gold current-image target: marker size 18 plus its 2px- * outline, so the pixel it occupies reaches ~10px from the anchor. Rounded up- * by one so a label never kisses the outline.- */+/** Marker half-extent includes its 18px size, 2px outline and one extra pixel of label clearance. */const MARKER_RADIUS_PX = 11;interface LabelRect {@@ -273,11 +240,8 @@ const rectsCollide = (a: LabelRect, b: LabelRect): boolean =>a.bottom > b.top - LABEL_GAP_PX;/**- * The gold target's footprint in screen pixels, or null when it is not on- * screen. An off-view marker cannot be covered by anything, and reserving- * space for it would evict labels that are off-view in the same direction —- * invisible either way, but it would churn the applied annotation set on every- * pan. The bounds test also rejects NaN coordinates by construction.+ * Return onscreen marker footprint only; offscreen reservations churn invisible labels during panning. Bounds+ * checks reject NaN too.*/const markerRectFor = (markerPoint: { x: number; y: number },@@ -306,18 +270,8 @@ const markerRectFor = (};/**- * Zoomed far out, every cluster label converges on the same few pixels and- * the map disappears under a pile of pills. Greedily keep labels in array- * order (buildClusterAnnotations puts larger clusters first), dropping any- * whose estimated pixel footprint collides with one already kept — fully- * deterministic for a given annotation set and view. Zooming back in spreads- * the anchors apart and the dropped labels reappear.- *- * `markerPoint` — the current gallery image, when it is on the map — outranks- * every label. Plotly draws annotations in an SVG layer above the WebGL canvas- * holding the scatter traces, so the gold target can never be stacked over a- * pill it overlaps; dropping the pill instead is the only way to keep the- * target visible where labels are dense.+ * Greedily retain noncolliding labels in priority order. Current-image markers outrank labels because Plotly SVG+ * annotations render above WebGL and cannot be stacked underneath the gold target.*/export const declutterAnnotations = (annotations: ClusterAnnotation[],@@ -356,14 +310,8 @@ export const declutterAnnotations = (continue;}- // This label owns the spot from here on, whether or not it gets drawn —- // deciding that BEFORE consulting the marker is what keeps the marker's- // effect local. Reserving first and testing second means a label the- // marker hides still holds its ground, so the next label in priority- // order cannot put a smaller cluster's name on the patch of map the- // marker was supposed to clear; and a label that lost its spot to a- // higher-priority label never reserves anything, so it cannot evict a- // third label the marker is nowhere near.+ // Reserve a winning label's space before testing marker overlap, preventing lower-priority replacements in the+ // cleared region. Labels already losing to another label reserve nothing.blockingRects.push(rect);if (markerRect !== null && rectsCollide(rect, markerRect)) {diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.tsindex 96a7099340..3be6a0be5f 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.ts@@ -84,8 +84,7 @@ describe('zoomFactorFromWheel', () => {});it('normalizes line and page deltas, so a Firefox wheel is not inert', () => {- // Firefox reports a classic mouse wheel as ±3 LINES. Read as pixels that- // is a 0.3% zoom — ~230 notches to double the view.+ // Firefox mouse deltas use three lines; interpreting them as pixels makes zoom nearly inert.const firefoxNotch = zoomFactorFromWheel(3, LINE, false);expect(firefoxNotch).toBeGreaterThan(1.02);expect(firefoxNotch).toBeCloseTo(zoomFactorFromWheel(48, PIXEL, false), 10);@@ -153,8 +152,7 @@ describe('fitRangesToAspect', () => {});it('keeps at least 90% of points in view for any container shape', () => {- // The user-facing contract for the first render: the fitted view must- // show (nearly) the whole map, however skewed the container.+ // Initial fitting must show nearly the whole map at any container aspect ratio.const points: ImageMapPoint[] = Array.from({ length: 100 }, (_, index) => ({cluster: 0,item: { kind: 'image', name: `p${index}.png` },diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.tsindex 03fa80fa59..caf6361c17 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.ts@@ -1,11 +1,5 @@import type { ImageMapPoint } from './api';-/**- * Pure viewport math for the image map: initial axis ranges, focal-point- * zoom, and keep-the-marker-in-view recentering. Kept free of plotly/DOM so- * every invariant is unit-testable.- */-export interface AxisRanges {x: [number, number];y: [number, number];@@ -26,10 +20,7 @@ const quantile = (sorted: number[], q: number): number => {return sorted[lower] * (1 - weight) + sorted[upper] * weight;};-/**- * Initial view: the 1st..99th percentile of each axis (PhotoMapAI's choice —- * a handful of outlier points must not dwarf the whole map), padded slightly.- */+/** Fit padded 1st–99th percentiles per axis, following PhotoMapAI to limit outlier influence. */export const computePercentileRanges = (points: ImageMapPoint[],lowerQ: number = 0.01,@@ -54,10 +45,8 @@ export const computePercentileRanges = (};/**- * Grow ranges minimally so `point` sits at least `padFraction` of the span- * inside every edge. Used before the initial fit so the current-image marker- * starts comfortably in view and the auto-recenter has no reason to shift- * the freshly fitted map.+ * Minimally expand ranges to keep the current marker inside padded edges before fitting, avoiding immediate+ * recentering.*/export const expandRangesToInclude = (ranges: AxisRanges,@@ -74,12 +63,8 @@ export const expandRangesToInclude = (};/**- * Expand ranges so the whole box stays visible in a plot whose axes are- * constrained to equal unit scale (xaxis.scaleanchor = 'y'). Handing plotly- * an over-constrained range pair makes it re-solve against the container's- * aspect ratio, which can CROP one axis — silently zooming the first render- * into a sliver of the map. Pre-expanding the narrower constraint instead- * guarantees everything inside the box remains in view. Only ever expands.+ * Expand ranges for equal-scale axes before handing them to Plotly; otherwise its aspect correction may crop one+ * axis. Never shrink the requested box.*/export const fitRangesToAspect = (ranges: AxisRanges, aspectRatio: number): AxisRanges => {if (!Number.isFinite(aspectRatio) || aspectRatio <= 0) {@@ -112,9 +97,8 @@ const WHEEL_LINE_HEIGHT_PX = 16;const WHEEL_PAGE_HEIGHT_PX = 400;/**- * Above this many pixels a ctrl+wheel came from a real wheel, not a trackpad- * pinch: browsers report a pinch as ctrl+wheel too, but in small synthetic- * steps, while one mouse notch is 100px (Chrome) or 3 lines (Firefox).+ * Distinguish larger mouse-wheel deltas from small synthetic ctrl+wheel pinch steps; normalize Firefox line units+ * first.*/const PINCH_DELTA_LIMIT_PX = 40;@@ -122,10 +106,8 @@ const PINCH_DELTA_LIMIT_PX = 40;const MAX_WHEEL_ZOOM_STEP = 1.25;/**- * Wheel deltas do not arrive in the same unit everywhere. Firefox reports a- * classic mouse wheel in LINES (deltaY ±3), so treating deltaY as pixels made- * one notch a 0.3% zoom — and since the handler preventDefaults, the user got- * neither zoom nor scroll.+ * Normalize delta units: Firefox mouse wheels report lines, whose raw values would otherwise produce imperceptible+ * zoom while native scrolling is prevented.*/export const normalizeWheelDeltaY = (deltaY: number, deltaMode: number): number => {if (deltaMode === 1) {@@ -145,8 +127,7 @@ export const zoomFactorFromWheel = (deltaY: number, deltaMode: number, isCtrlHelconst isPinch = isCtrlHeld && Math.abs(pixels) < PINCH_DELTA_LIMIT_PX;const factor = Math.exp(pixels * (isPinch ? 0.01 : 0.001));- // The pinch gain applied to a mouse-sized delta would zoom 2.7x in one- // notch; clamping keeps every input device to a usable step.+ // Clamp mouse-sized deltas so pinch gain cannot cause oversized zoom steps.return Math.min(Math.max(factor, 1 / MAX_WHEEL_ZOOM_STEP), MAX_WHEEL_ZOOM_STEP);};diff --git a/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.test.tsindex 3356adc3ca..46e781da01 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.test.ts@@ -29,15 +29,13 @@ describe('index progress arithmetic', () => {});it('counts images given up on as finished so the bar reaches full', () => {- // They never drain. Leaving them out parks the bar short of full for a run- // that has in fact finished.+ // Failed items are finished work; excluding them would keep a drained queue below 100%.expect(getIndexPercent(counts({ embedded: 94, failed: 5, pending: 1, total: 100 }))).toBe(99);expect(getIndexPercent(counts({ embedded: 95, failed: 5, pending: 0, total: 100 }))).toBe(100);});it('agrees with the counts line it is shown beside', () => {- // "300 of 1,000 images" next to "90%" is not something a user can- // reconcile; both are read off `pending`, so they cannot diverge.+ // Derive completed counts and percent from pending so labels and progress agree.const description = describeIndexProgress(counts({ embedded: 300, failed: 600, pending: 100, total: 1000 }));expect(description.counts).toBe('900 of 1,000 images');@@ -67,9 +65,7 @@ describe('hasProgressed', () => {});it('is not progress when only the gallery moved', () => {- // `total` shifts whenever anyone saves or deletes an image — including the- // very generation the indexer is waiting out. Counting that as progress- // would reset the "no progress" clock every time someone generates.+ // Gallery total changes are not indexing progress and must not reset the stall clock.expect(hasProgressed(counts({ pending: 75, total: 100 }), counts({ pending: 76, total: 101 }))).toBe(false);expect(hasProgressed(counts(), counts())).toBe(false);});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.ts b/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.tsindex af0002ea87..3a50e32129 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.ts@@ -1,17 +1,6 @@/**- * Progress arithmetic for the embedding index, kept apart from both the store- * that holds the counts and the components that draw them, so the wording and- * the numbers behind it can be tested without a socket or a DOM.- *- * Deliberately no time estimate. The indexer stands down for the whole of- * every generation (`_wait_for_idle_generation`) and reports nothing while it- * waits, so the gaps between reports are mostly other people's work, not the- * index's. Measuring across them makes the estimate pessimistic by ~200x;- * excluding them makes it optimistic by ~10x, because the pauses still to come- * are left out; and no threshold separates the two, since embedding a batch on- * a slow CPU takes exactly as long as a fast generation. What the panel can- * say honestly is how far the run has got and when it last moved, which is all- * that was needed to tell progress from a stall.+ * Pure progress arithmetic reports completed work and time since progress. Generation pauses make remaining-time+ * estimates unreliable.*//** Embedding-index counts as the backend reports them. */@@ -23,26 +12,15 @@ export interface ImageIndexCounts {failed: number;}-/**- * How long the counts may stand still before the panel says so.- *- * Above any single batch — the worker emits one report per batch of- * `image_index_batch_size`, seconds apart on a GPU and up to a minute on a- * slow CPU — so ordinary embedding never trips it, and short enough that a run- * that has actually stopped does not keep looking busy.- */+/** Stall threshold should exceed ordinary batch intervals while revealing prolonged inactivity. */export const STALE_AFTER_MS = 2 * 60_000;/** Images the index is finished with, whether they embedded or were given up on. */const getProcessed = (counts: ImageIndexCounts): number => Math.max(0, counts.total - counts.pending);/**- * Share of the gallery the index is finished with, 0-100.- *- * Counted off `pending` so the bar is full exactly when the queue drains.- * Images given up on are finished with too: leaving them out parks the bar- * short of full forever, and taking them out of the denominator instead- * shrinks the total under the user as they retire one by one.+ * Completion percent derives from pending so drained queues reach 100%, including abandoned items without+ * shrinking the denominator.*/export const getIndexPercent = (counts: ImageIndexCounts): number => {if (counts.total <= 0) {@@ -52,12 +30,7 @@ export const getIndexPercent = (counts: ImageIndexCounts): number => {return Math.min(100, Math.max(0, (getProcessed(counts) / counts.total) * 100));};-/**- * What to paint, print and announce — one value for all three, so the bar- * cannot sit visually full beside a number that says otherwise. Held below- * full while anything is outstanding: 99.7% rounded up tells a screen reader- * the run is done with 300 images still queued.- */+/** Use one percent for visuals, text and announcements; cap below 100 while pending work remains. */export const getDisplayPercent = (counts: ImageIndexCounts): number => {const percent = Math.round(getIndexPercent(counts));@@ -68,12 +41,7 @@ export const getDisplayPercent = (counts: ImageIndexCounts): number => {export const isIndexing = (counts: ImageIndexCounts | null): counts is ImageIndexCounts =>counts !== null && counts.pending > 0;-/**- * Whether one report represents progress over another, rather than the same- * work re-reported. `total` moves whenever anyone saves or deletes an image,- * so it cannot be part of this: a generation running while the indexer waits- * for it would otherwise look like the index moving.- */+/** Detect completed index work, ignoring total changes from gallery saves/deletions. */export const hasProgressed = (previous: ImageIndexCounts | null, next: ImageIndexCounts): boolean =>previous === null || previous.embedded !== next.embedded || previous.failed !== next.failed;@@ -115,14 +83,8 @@ export interface IndexProgressDescription {}/**- * The strings the progress UI shows. Assembled here rather than in the- * components so both the panel and the footer say the same thing, and so the- * wording is covered by the same tests as the numbers behind it.- *- * `sinceMs` is how long the counts have been standing. The note it produces- * states the fact and stops there: nothing the client can see distinguishes an- * indexer waiting out a generation from one that has died, so it must not- * claim to know which.+ * Shared panel/footer progress wording. `sinceMs` reports inactivity without claiming whether the worker is paused+ * for generation or has failed.*/export const describeIndexProgress = (counts: ImageIndexCounts, sinceMs = 0): IndexProgressDescription => ({compact: `${formatCount(getProcessed(counts))}/${formatCount(counts.total)}`,diff --git a/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.test.tsindex 458790360d..25dfd08a16 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.test.ts@@ -40,8 +40,7 @@ describe('image map thumbnail cache', () => {Promise.resolve({ durationSeconds: 2.5, kind: ref.kind, thumbnailUrl: `/thumbs/${ref.kind}/${ref.name}` }));- // The duration rides along for videos only: the hover card shows the same- // play badge the gallery tile does, and an image has none to show.+ // Video duration drives the same play badge as gallery tiles; images omit it.await expect(getThumbnailUrl({ kind: 'video', name: 'clip' })).resolves.toEqual({durationSeconds: 2.5,url: '/thumbs/video/clip',@@ -54,10 +53,7 @@ describe('image map thumbnail cache', () => {});it('remembers a definitive miss but retries a transient failure', async () => {- // Hovering is driven by pointer movement, so a deleted or hidden item has- // to be remembered — the by-names resolver this cache used to call- // returned an empty array for a miss, which was cached; the by-ref one- // throws, and the miss would otherwise be re-fetched on every dwell.+ // Cache missing/deleted items despite resolver throws so pointer dwell does not repeatedly fetch them.mocks.resolve.mockRejectedValue(new ApiError('gone', 404));await expect(getThumbnailUrl({ kind: 'image', name: 'gone.png' })).resolves.toBeNull();diff --git a/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.ts b/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.tsindex c33a34103b..32cd2b67c5 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.ts@@ -10,9 +10,8 @@ import {import { ApiError } from '@platform/transport/http';/**- * What a hover card shows for one item: the thumbnail, plus the duration that- * makes a clip's card read like its gallery tile. Both derive from the- * immutable item name, so unlike full DTOs they never go stale.+ * Hover thumbnail and optional video duration derive from immutable item names and can be cached independently of+ * mutable DTOs.*/export interface HoverThumbnail {url: string;@@ -67,11 +66,7 @@ export const getThumbnailUrl = (item: GalleryItemRef): Promise<HoverThumbnail |return thumbnail;}).catch((error: unknown): null => {- // A deleted or no-longer-visible item answers definitively, and hovering- // is driven by pointer movement — so remember the miss, or every dwell- // over that point re-fetches the same 404 for the rest of the session.- // (The by-names resolver this replaced returned an empty array for a- // miss, which the `then` above cached; the by-ref one throws.)+ // Remember definitive missing/invisible-item responses so each hover does not repeat the same 404.if (error instanceof ApiError && (error.status === 403 || error.status === 404) && isAccountScopeCurrent(owner)) {urls.set(key, null);}diff --git a/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.test.tsindex 41d49d10a4..3184370c08 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.test.ts@@ -96,8 +96,7 @@ describe('updateImageMapVocab rebuild watcher', () => {await updateImageMapVocab(['zebra', 'okapi']);await advancePolls(2);- // Two PUTs, one poll: the second save reused the live watcher, which acts- // on the final state rather than on which save produced it.+ // Two saves share one watcher observing final rebuild state, not individual save identity.expect(mocks.apiFetchJson).toHaveBeenCalledTimes(3);expect(mocks.refetchClusterLabels).toHaveBeenCalledTimes(1);});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.ts b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.tsindex b29656770a..f18eb9830e 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.ts@@ -1,11 +1,6 @@/**- * The supplementary cluster-labeling vocabulary: a server-wide term list that- * admins maintain and the backend merges with its bundled vocabulary when it- * builds the label embeddings.- *- * Reads are open to every user; the PUT is admin-only (the router's- * `AdminUserOrDefault`). The list is replaced whole on save — the editor- * always holds the full list, and replace semantics keep the API idempotent.+ * Admin-maintained server-wide supplementary terms augment bundled label vocabulary. All users can read;+ * admin-only saves replace the full list idempotently.*/import {@@ -73,15 +68,8 @@ export const imageMapVocabQueryOptions = () =>})();/**- * Replace the whole term list. The server normalizes (lowercase, collapsed- * whitespace), dedupes, and rejects over-limit input with a 422 whose detail- * names the offending term; the response carries the stored list.- *- * When the response reports a background embedding rebuild, a module-level- * watcher is started so any open map's labels are re-fetched when it lands —- * a vocabulary edit changes what the labels say without moving a single- * point, so nothing in the map's own flow would notice, and the watcher must- * outlive the settings dialog the save was made from.+ * Replace all terms; server normalizes/dedupes and returns stored values or term-specific 422 limits. Background+ * rebuild watching outlives the settings dialog and refreshes map labels even when points do not move.*/export const updateImageMapVocab = async (terms: string[]): Promise<ImageMapVocab> => {const body = await apiFetchJson<BackendImageMapVocabResponse>('/api/v1/image_map/vocab', {@@ -97,9 +85,7 @@ export const updateImageMapVocab = async (terms: string[]): Promise<ImageMapVocareturn vocab;};-// The rebuild usually lands in seconds, but the index worker parks during-// generations, so it can also take a long while: back the poll off rather-// than holding a 2s cadence indefinitely.+// Back off rebuild polling because generation pauses can delay completion substantially.const REBUILD_POLL_MIN_MS = 2_000;const REBUILD_POLL_MAX_MS = 30_000;@@ -143,20 +129,16 @@ const watchRebuild = (): void => {}if (body.state === 'ready') {- // The hover card's per-image tags are scored against this same- // vocabulary, so they go stale on exactly this event — and unlike- // the cluster labels, nothing else in the map's flow refetches them.+ // Vocabulary rebuild also invalidates cached per-item hover tags.clearImageLabels();refetchClusterLabels();}- // 'error', 'unavailable', and 'idle' all mean no new labels are- // coming from this rebuild; the settings UI reports those itself.+ // Error, unavailable and idle end this rebuild's label wait; settings owns their feedback.return;}} catch {- // Label refresh is best-effort decoration; the next points refresh- // fetches labels anyway.+ // Label refresh is best-effort; the next point refresh fetches labels again.} finally {rebuildWatchActive = false;}diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.tsindex 87f55d6196..44f9d36aea 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts@@ -500,8 +500,7 @@ describe('submitResolvedInvocation', () => {expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({ positivePrompts: undefined });});- // Submitting the authored text on a failed expansion would put the literal- // `{a|b}` or `__name__` in front of the model, so neither failure generates.+ // Expansion failures must not submit literal dynamic syntax.describe('when a prompt cannot be expanded', () => {const submitDynamicPrompt = () => {const project = getActiveProject(createGenerateValues(animaModel, { positivePrompt: 'a {red|green} cat' }));@@ -578,8 +577,7 @@ describe('resolveInvocationRoute — video destination compatibility', () => {sourceLocked: false,};- // A canvas-routed video run would complete with the output appearing- // nowhere (staging is image-based; only gallery-destined videos board).+ // Canvas cannot stage video, and only Gallery-destined videos are boarded.const blocked = resolveInvocationRouteInput(input, 'global', canvasRoute);expect(blocked.destinationValid).toBe(false);diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.tsindex 3770efd7ad..1e5d363908 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts@@ -28,14 +28,6 @@ import { compileContributingLayers } from '@workbench/canvas-engine/api';import { getBlockingControlLayerIssues } from './controlLayerChecks';import { getProjectWidgetValues } from './widgetState';-/**- * Static metadata for the Invocation Controller surfaces.- *- * MVP destinations are limited to Canvas and Gallery per the spec. Sources are- * the first-party graph-bearing surfaces; only `generate` is wired in Phase 1,- * the rest are declared so the source menu reads as a real (if partly inert)- * placeholder for later phases.- */export interface InvocationSourceMeta {id: InvocationSourceId;label: string;@@ -201,9 +193,7 @@ export const resolveInvocationRouteInput = (const sourceId = route.sourceId;const destination = route.destination;const sourceWidgetId = sourceWidgetIds[sourceId];- // The project graph validates against its compiled readiness; templates are- // read imperatively, and surfaces that render the route subscribe to the- // templates store so the result stays live.+ // Route-rendering surfaces subscribe to templates because readiness reads them imperatively.const projectGraphReadiness =sourceId === 'workflow' ? getProjectGraphReadiness(input.projectGraph, getInvocationTemplatesSnapshot()) : null;const validationReasons: Array<string | ForLoopValidationReason> = [];@@ -235,18 +225,14 @@ export const resolveInvocationRouteInput = (}if (sourceId === 'canvas') {- // Canvas shares the generate model/prompt/steps, so reuse those reasons, then- // require a non-degenerate generation frame (a zero-area bbox has nothing to- // generate into and the graph compiler would reject it anyway).+ // Canvas shares Generate readiness and additionally requires a nonzero generation frame.validationReasons.push(...getGenerateSnapshotValidationReasons(input.generateValues, models));if (input.canvasBbox.width <= 0 || input.canvasBbox.height <= 0) {validationReasons.push('Canvas generation frame must have a positive area.');}- // Control layers that would make the invoke pipeline reject the document.- // Gated on a loaded models list so a not-yet-loaded snapshot can't produce- // false "missing model" blocks.+ // Wait for models before validating control layers to avoid false missing-model errors.if (models) {const values = normalizeGenerateWidgetValues(input.generateValues);if (values && isSupportedGenerateModel(values.model)) {@@ -266,10 +252,7 @@ export const resolveInvocationRouteInput = (}const sourceValid = validationReasons.length === 0;- // A video result is structurally undeliverable to the Canvas: staging is- // image-based and the queue runtime only boards gallery-destined videos, so- // a canvas-routed video run would complete with the output appearing- // nowhere. Block it instead of letting the result vanish.+ // Canvas staging accepts images only; video routes must target Gallery or their outputs would be unreachable.const destinationCompatible = !(sourceId === 'video' && destination === 'canvas');const destinationAvailable = isResultDestinationAvailable(destination);const destinationValid = destinationAvailable && destinationCompatible;diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.tsindex 19a41d58dc..5283e3e09c 100644--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts@@ -1,16 +1,6 @@/**- * The single canvas-vs-generate submit decision, shared by the three Invoke- * surfaces: the topbar Invoke button (`shell/topbar/InvokeControl`), the Invoke- * hotkey command (`hotkeys/firstPartyCommands`), and the graph-preview dialog's- * submit (`graph-preview/GraphPreviewDialog`).- *- * Both surfaces flush drafts, resolve the route, and gate on route validity +- * backend connection themselves; this helper owns only what happens *after* that- * gate — routing a `canvas` source through the async canvas pipeline- * (`prepareCanvasInvocation`, honoring the resolved destination) versus- * dispatching the reducer's `submitResolvedInvocationSnapshot` for every other- * source. `prepareCanvasInvocation` is injected so the decision stays pure and- * node-testable with a fake dispatch + a stubbed canvas pipeline.+ * After callers flush drafts and validate route/connection, send Canvas through async preparation and other+ * sources through reducer submission. Inject Canvas preparation to keep this decision independent of the engine.*/import type { GenerateSettings } from '@features/generation/contracts';@@ -46,10 +36,8 @@ export interface SubmitResolvedInvocationDeps {owner: AccountScope;commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;/**- * The async canvas-invoke entry point, injected for testability. The real- * implementation resolves after preparation has either queued the graph or- * reported a failure; a canvas source never dispatches- * `submitResolvedInvocationSnapshot`.+ * Resolves after Canvas preparation queues or reports failure; Canvas never dispatches+ * submitResolvedInvocationSnapshot.*/prepareCanvasInvocation: (args: PrepareCanvasInvocationArgs) => Promise<void> | void;/** Localizes a control-layer rejection notice; defaults to the English validation sentence. */@@ -57,14 +45,8 @@ export interface SubmitResolvedInvocationDeps {}/**- * The GenerateSettings behind a route that expands `{a|b}`, or `null` when the- * route submits its prompt literally (Upscale, Workflow) or has no such syntax.- *- * The returned settings carry the *merged* prompts, so both the gate and the- * expansion below see what will actually generate. That matters in both- * directions: an active template can introduce `{a|b}` a plain authored prompt- * never had, and it always consumes its own `{prompt}` placeholder before the- * expander could mistake it for a one-option group.+ * Return merged Generate prompts only for dynamic routes; templates may introduce syntax and must consume their+ * own placeholders before expansion.*/const getExpandableSettings = (project: Project, route: ResolvedInvocationRoute): GenerateSettings | null => {if (route.sourceId === 'upscale' || route.sourceId === 'video' || route.sourceId === 'workflow') {@@ -83,14 +65,8 @@ const getExpandableSettings = (project: Project, route: ResolvedInvocationRoute)};/**- * Resolving the expansion here rather than inside Queue keeps Queue free of a- * Generation import, which would close a `gallery -> queue -> generation`- * dependency cycle. Reading the shared cache means invoking mid-edit still- * submits the prompts the backend actually produces.- *- * `null` means the request itself failed. A response may still carry an `error`- * alongside a usable-looking `prompts` — the route is deliberately soft so the- * preview can show the message, but the submit path must not act on it.+ * Expand here to avoid a gallery → queue → generation cycle. Treat null or response.error as failure even if+ * prompts are present.*/const resolveExpandedPrompts = async (settings: GenerateSettings): Promise<ParseDynamicPromptsResponse | null> => {try {@@ -120,18 +96,15 @@ export const submitResolvedInvocation = async ({const expandableSettings = getExpandableSettings(project, route);- // Only a prompt with dynamic syntax pays for a round trip; every other Invoke- // stays on the synchronous path it has always taken.+ // Only dynamic prompts require a round trip.if (expandableSettings) {const expansion = await resolveExpandedPrompts(expandableSettings);if (!isAccountScopeCurrent(owner)) {return;}- // Submitting the authored text would put the literal `{a|b}` or `__name__`- // in front of the model, so a prompt that could not be expanded does not- // generate at all. The Invoke button gates on the same state; this covers- // the hotkey and graph-preview paths, which never see it.+ // Reject failed expansions for hotkey and preview callers too, so literal dynamic syntax never reaches+ // generation.if (expansion === null || expansion.error) {commands.notifications.add({kind: 'error',@@ -167,12 +140,8 @@ const dispatchResolvedInvocation = async (positivePrompts: string[] | undefined): Promise<void> => {if (route.sourceId === 'canvas') {- // The canvas graph is composited + compiled asynchronously outside the- // reducer. Awaiting it lets the active submission coordinator hold its- // immediate acknowledgement/duplicate guard through the whole preparation.- // The orchestrator records any failure notice and keeps its own guard for- // direct/preview callers. The resolved destination is threaded through so a- // Canvas source can still land its output in the Gallery.+ // Await Canvas preparation to retain the submission guard until completion; pass the resolved destination so+ // Canvas can output to Gallery.await prepareCanvasInvocation({compositing: readCanvasCompositingSettings(getProjectWidgetValues(project, 'canvas')),destination: route.destination,diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/HelpMenu.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/HelpMenu.tsxindex 858407eb65..f488087993 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/HelpMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/HelpMenu.tsx@@ -8,13 +8,6 @@ import { DiscordIcon, GithubIcon } from '@platform/ui/VendoredIcon';import { BookOpenTextIcon, ChevronRightIcon, ClapperboardIcon, CircleQuestionMarkIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';-/**- * Docs and community, pinned to the bottom of the Launchpad rail. This used to- * be two outlined cards — the only card-styled objects on the surface, and- * visually heavier than the section nav above them. One menu button says the- * same thing without competing with the navigation for attention.- */-const MENU_POSITIONING = { placement: 'right-end' } as const;const GROUP_LABEL_PROPS = { color: 'fg.subtle', fontSize: '2xs', textTransform: 'uppercase' } as const;const TRIGGER_JUSTIFY = { justifyContent: 'space-between' } as const;diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsxindex de3ea6ca92..eee30909a4 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx@@ -17,16 +17,8 @@ import { ProjectsPage } from './pages/ProjectsPage';import { ProjectActionsMenuProvider } from './projects/ProjectActionsMenuHost';/**- * The landing surface at `/`: a full-height shell with a slim section rail and- * a full-width page area — the editor equivalent of Photoshop's home screen.- * Sections live as switchable pages (Projects, the model manager, and admin- * user management) so the surface has room to grow without crowding any one of- * them. It deliberately mounts none of the workbench providers or runtimes, so- * it stays on the light side of the route-level code split; the heaviest page,- * the model manager, lazy-loads its own chunk the first time it is opened.- *- * Sections carry a `group`, because where you work and what you administer are- * not peers: a flat list gave "Users" the same standing as "Projects".+ * Launchpad owns grouped home/admin pages without mounting workbench runtimes. Model management loads on demand+ * across the route split.*/type LaunchpadSectionId = 'home' | 'projects' | 'models' | 'nodes' | 'users' | 'fonts';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadNav.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadNav.tsxindex c756ccbe6d..5d16b7e0fa 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadNav.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadNav.tsx@@ -11,25 +11,13 @@ import { HelpMenu } from './HelpMenu';const NAV_BORDER_END_WIDTH = { md: '1px' } as const;const NAV_BORDER_BOTTOM_WIDTH = { base: '1px', md: '0' } as const;const NAV_WIDTH = { base: 'full', md: '56' } as const;-/**- * Below `md` the shell stacks the rail above the page, and `h="full"` there- * made the rail claim the entire viewport — collapsing the page area to zero- * height inside the fixed, overflow-hidden shell. The rail takes only what its- * content needs until it is a sidebar again.- */+/** Below md, size the stacked rail to content; full height would consume the fixed shell and leave no page area. */const NAV_HEIGHT = { base: 'auto', md: 'full' } as const;const FOOTER_MARGIN_TOP = { md: 'auto' } as const;/**- * The Launchpad's persistent left rail. Sections are split into where you work- * and what you administer: they are not peers, and stacking them in one flat- * list gave "Users" the same weight as "Projects".- *- * The group headings are `role="presentation"` children of a single- * `Tabs.List`, not separate lists — roving focus walks `[role=tab]`- * descendants, so one tablist keeps arrow-key navigation running across the- * whole rail while the headings stay decorative. Two sibling lists would split- * that navigation in half.+ * Keep decorative group headings inside one Tabs.List so arrow navigation crosses groups while separating work+ * from administration.*/export type LaunchpadNavGroupId = 'workspace' | 'manage';@@ -48,11 +36,7 @@ const GROUP_LABEL_KEY: Record<LaunchpadNavGroupId, string> = {workspace: 'launchpad.groups.workspace',};-/**- * Deliberately not the shared `dropdownGroupLabel` fragment: that one is tuned- * for menu surfaces, and its `fg.subtle` only reaches 4.11:1 against the rail's- * background at this size. `fg.muted` clears 4.5:1.- */+/** Use fg.muted for rail-heading contrast; the menu label's fg.subtle falls below 4.5:1 here. */const GROUP_LABEL_SX: SystemStyleObject = {color: 'fg.muted',fontSize: '2xs',@@ -70,8 +54,7 @@ export const LaunchpadNav = ({ items }: { items: LaunchpadNavItem[] }) => {),[items]);- // Headings only earn their space once there is more than one group to tell- // apart; a capability-limited account often has just the one.+ // Show headings only when multiple groups need distinguishing.const showGroupLabels = groups.length > 1;return (diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsxindex 14baafc995..e664ecf817 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx@@ -15,12 +15,7 @@ const CONNECTION_LABEL_KEY: Record<Exclude<BackendConnectionStatus, 'connected'>disconnected: 'launchpad.connection.disconnected',};-/**- * Subtle backend-connection indicator; hidden while the socket is healthy.- *- * The status changes on its own, with no interaction to attribute it to, so- * the region is announced politely rather than only being visible.- */+/** Hide healthy connection status; announce spontaneous status changes politely. */const ConnectionChip = () => {const { t } = useTranslation();const status = useConnectionStatusSelector((snapshot) => snapshot.status);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/OpenProjectsControl.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/OpenProjectsControl.tsxindex f7c4ab9c23..5236dd6b3f 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/OpenProjectsControl.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/OpenProjectsControl.tsx@@ -11,18 +11,8 @@ import { useMemo } from 'react';import { useTranslation } from 'react-i18next';/**- * The way back into the editor, driven by the saved session rather than the- * URL.- *- * The button used to be unconditional, which meant a brand-new account was- * offered "Back to project" with no project to go back to — and `/app` bounces- * a definitely-empty session straight back here. So an empty open set hides- * the control entirely.- *- * An *unknown* session (first run, a pre-split blob, an unreachable backend)- * is not the same as an empty one: the store reports it as `null` and the- * `/app` guard deliberately does not redirect on it. This mirrors that —- * unknown still offers the plain way in and lets the editor sort it out.+ * Hide editor re-entry only for a known-empty saved session. Unknown sessions retain entry so the editor can+ * resolve them.*/const MENU_POSITIONING = { placement: 'bottom-start' } as const;diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/home/IntentTiles.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/home/IntentTiles.tsxindex 1afde3f405..c4f4aad8e2 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/home/IntentTiles.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/home/IntentTiles.tsx@@ -8,17 +8,8 @@ import { BlocksIcon, BrushIcon, ClapperboardIcon, ScalingIcon, TypeIcon } from 'import { useMemo } from 'react';import { useTranslation } from 'react-i18next';-/**- * "What do you want to make?", asked before "which file do you want to open?".- *- * Each tile opens a fresh draft already arranged for that kind of work. The- * old frontend put this inside the editor as a per-tab panel; at the home- * level it is the first move rather than a thing you find after arriving.- */-const TILE_COLUMNS = { base: 1, lg: 5, sm: 2 } as const;-// Pro-app convention (see the theme's cursor tokens): tiles act like-// controls, so they keep the arrow instead of the anchor's pointer.+// Tiles follow the theme's control cursor convention.const TILE_LINK_STYLE = { cursor: 'default' } as const;const TILE_HOVER = { bg: 'bg.muted', borderColor: 'border.emphasized' } as const;const TILE_TRANSITION =diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/home/LivePanel.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/home/LivePanel.tsxindex 3ff021d02a..fab267d3d2 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/home/LivePanel.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/home/LivePanel.tsx@@ -1,14 +1,8 @@import { lazy, Suspense } from 'react';/**- * Places one live panel on Home.- *- * All three resolve from the same `import('./livePanels')` promise, so the- * bundler emits a single dynamic chunk for the lot rather than one per panel —- * but each still mounts wherever the page wants it. Every panel renders- * nothing until it has something to report, so the fallback is `null`: a- * skeleton for a band that will usually turn out to be empty is worse than- * nothing appearing at all.+ * Load all live panels from one shared chunk while mounting independently. Use a null fallback because empty+ * panels render nothing.*/const loadLivePanels = () => import('./livePanels');diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/home/RecentProjectsRow.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/home/RecentProjectsRow.tsxindex ce93d08cf5..b6fa7f3a70 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/home/RecentProjectsRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/home/RecentProjectsRow.tsx@@ -7,12 +7,6 @@ import { ProjectCard } from '@workbench/launchpad/projects/ProjectCard';import { ArrowRightIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';-/**- * A short strip of recent projects under the resume card — enough to recognise- * what else is in flight without turning Home into a second library. The full- * one is a click away.- */-const GRID_COLUMNS = { base: 1, lg: 4, sm: 2 } as const;export const RecentProjectsRow = ({diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/home/ResumeCard.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/home/ResumeCard.tsxindex e211140562..23f967bb57 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/home/ResumeCard.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/home/ResumeCard.tsx@@ -17,15 +17,6 @@ import { ArrowRightIcon, EllipsisVerticalIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-/**- * The single most recently edited project, given more room than the rest.- *- * Returning users almost always want the thing they were last working on, and- * making them find it in a grid of equals is the small tax the old home screen- * charged on every visit. It is still a library project, so it carries the- * same actions menu as the grid cards — on right-click and on the corner dots.- */-const CARD_HOVER = { bg: 'bg.muted', borderColor: 'border.emphasized' } as const;const LINK_STYLE = { cursor: 'default', inset: 0, position: 'absolute' } as const;const CARD_TRANSITION =diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/home/livePanels.ts b/invokeai/frontend/webv2/src/workbench/launchpad/home/livePanels.tsindex 0e3bb98ee6..742de7da45 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/home/livePanels.ts+++ b/invokeai/frontend/webv2/src/workbench/launchpad/home/livePanels.ts@@ -1,12 +1,6 @@/**- * Every Launchpad panel that reads live backend state, behind one import.- *- * These are the only Home surfaces that need Gallery, Models, or Queue code,- * none of which belongs in the Launchpad's initial graph. Giving each its own- * `lazy()` boundary cost ten extra requests at first paint, because each- * dynamic entry split its own copy of the shared feature graph out with it.- * Collapsing them into this single module means one dynamic chunk for all- * three, while `LivePanel` still lets the page place them independently.+ * One dynamic entry keeps Gallery, Models, and Queue out of Home's initial graph without duplicating shared chunks+ * per panel.*/export { RecentOutputs } from '@features/gallery/launchpad';export { ModelsNotice } from '@features/models/launchpad';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/intents.ts b/invokeai/frontend/webv2/src/workbench/launchpad/intents.tsindex 96a5511fa2..e8fee4cd2d 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/intents.ts+++ b/invokeai/frontend/webv2/src/workbench/launchpad/intents.ts@@ -2,22 +2,8 @@ import type { InvocationSourceId } from '@workbench/invocationContracts';import type { BuiltInLayoutPresetId } from '@workbench/layoutContracts';/**- * What the user said they wanted to make, translated into how the editor- * should open.- *- * A layout preset supplies the account's default route, while an intent names- * its source explicitly because it can be more specific. For example, Generate- * and Upscale share Compose but need different invocation sources.- *- * This is the whole contract behind `/app?new=true&intent=…`: the Launchpad- * writes the id into the URL, and the editor's session controller applies it- * once, on the fresh draft.- *- * `?preset=` is the same contract one level lower: it names an arrangement- * directly, for when the user picked a layout rather than a kind of work. The- * id list lives here rather than being derived from `layoutPresets` so that- * validating the URL costs the editor route nothing — this module is already- * shared between both routes, the preset table is not.+ * Apply URL intent once to the fresh draft: presets choose arrangement, intents choose the more specific+ * invocation source. Keep built-in ids here so both routes validate without loading full preset snapshots.*/export type LaunchpadIntentId = 'generate' | 'canvas' | 'upscale' | 'video' | 'workflow';@@ -47,20 +33,10 @@ const INTENTS: Record<LaunchpadIntentId, LaunchpadIntent> = {export const isLaunchpadIntentId = (value: unknown): value is LaunchpadIntentId =>typeof value === 'string' && LAUNCHPAD_INTENT_IDS.includes(value as LaunchpadIntentId);-/**- * The arrangements the Launchpad can start a draft in. Built-ins only: custom- * presets live in the account state that only the mounted workbench holds, and- * the Launchpad renders outside that provider.- */+/** Launchpad can select built-ins only; custom presets require the mounted account workbench. */export const LAUNCHPAD_LAYOUT_IDS: readonly BuiltInLayoutPresetId[] = ['compose', 'edit', 'video', 'automate'];-/**- * Display names for the built-in arrangements, kept here rather than read off- * `layoutPresets` so the Launchpad can name them without pulling that table —- * which carries a full widget-region snapshot per preset — onto its route chunk.- * `layoutPresets` builds its own labels from this map, so there is still one- * definition.- */+/** Share built-in labels without loading widget-region snapshots; layoutPresets derives its labels from this map. */export const BUILT_IN_LAYOUT_PRESET_LABELS: Record<BuiltInLayoutPresetId, string> = {automate: 'Automate',compose: 'Compose',diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/pages/HomePage.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/pages/HomePage.tsxindex 737962ab25..8f9c4259ba 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/pages/HomePage.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/pages/HomePage.tsx@@ -24,15 +24,6 @@ import { FileUpIcon } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';-/**- * The Launchpad's landing section: resume what you were doing, or start- * something new.- *- * Home deliberately shows only a handful of recent projects — the full library- * is its own section. What it adds over a file list is the first move: intent- * tiles that open a draft already arranged for the kind of work you named.- */-const RECENT_PROJECT_COUNT = 4;const BROWSER_ISSUES_BANNER = <KnownBrowserIssuesAlert />;@@ -90,15 +81,10 @@ export const HomePage = () => {regionLabel={t('launchpad.sections.home')}title={greeting}>- {/* Ordered by how much it should interrupt: a missing model blocks- everything, a running job is worth knowing about, the rest is- browsing. Each renders nothing when it has nothing to say.-- The models panel is capability-gated rather than merely hidden: every- endpoint it touches — catalog, starters, install — is admin-only, so- mounting it for a non-admin would mean a burst of unauthorized- requests on every visit to Home, and a call to action they could not- complete. */}+ {/*+ * Order panels by urgency. Gate model-panel mounting by capability because its catalog/install endpoints are+ * admin-only; empty panels render nothing.+ */}{canManageModels ? <LivePanel panel="models" /> : null}<LivePanel panel="queue" />diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsxindex 873ee74af9..1dd16f4e95 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx@@ -22,13 +22,7 @@ import { FileUpIcon } from 'lucide-react';import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';-/**- * The Launchpad's project library.- *- * Sort, layout, and pins persist through workbench preferences, so they follow- * the account rather than the browser. The search term deliberately does not —- * a filter you did not set is a filter you cannot find your way out of.- */+/** Persist sort, layout, and pins in account preferences; keep search transient to avoid restoring hidden filters. */export const ProjectsPage = () => {const navigate = useNavigate();diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/NewProjectButton.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/NewProjectButton.tsxindex 7079678e68..36f3aa21f7 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/NewProjectButton.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/NewProjectButton.tsx@@ -2,8 +2,6 @@ import type { BuiltInLayoutPresetId } from '@workbench/layoutContracts';import type { LucideIcon } from 'lucide-react';import { Icon, Menu, Portal } from '@chakra-ui/react';-// Concrete modules, not the barrel: `@platform/ui` sits at its direct-importer-// budget, and this component needs four of its exports.import { Button, IconButton } from '@platform/ui/Button';import { Group } from '@platform/ui/Group';import { MenuContent } from '@platform/ui/Menu';@@ -13,20 +11,8 @@ import { ChevronDownIcon, ClapperboardIcon, LayersIcon, PlusIcon, TypeIcon, Workimport { useTranslation } from 'react-i18next';/**- * New project, plus the arrangement to open it in.- *- * The plain click keeps the old behaviour — a draft in whatever preset the- * account last used — because most of the time the arrangement is not the- * decision being made. The caret is for when it is: it names the shipped- * layouts so starting from "Edit" does not mean opening a draft and then- * rearranging it.- *- * Labels come from the shared id/label map that `layoutPresets` also builds- * from, so the menu and the editor's preset strip cannot disagree about what a- * layout is called — without the Launchpad having to load the preset table's- * full widget-region snapshots. Icons are mapped locally for the same- * reason: `resolveLayoutPresetIcon` exists for the custom-preset picker and- * carries its whole curated catalogue.+ * Plain clicks use the last preset; the caret chooses a built-in arrangement. Shared labels avoid drift without+ * importing preset snapshots or the custom icon catalog.*/const NEW_PROJECT_SEARCH = { new: true } as const;diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsxindex 1c16619ecc..45bf51ccbd 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx@@ -5,9 +5,8 @@ import { ArrowRightIcon, CopyIcon, FileDownIcon, PencilIcon, PinIcon, PinOffIconimport { useTranslation } from 'react-i18next';/**- * The per-project action menu's content. Right-click and the overflow button- * offer the same things in the same order everywhere; the single mounted- * instance and its dialogs live in `ProjectActionsMenuHost`.+ * Share action order between right-click and overflow menus; ProjectActionsMenuHost owns the single menu and+ * dialogs.*/export const ProjectActionsMenuBody = ({isCompatible,diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.browser.test.tsxindex b6e6157596..899be5f0e2 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.browser.test.tsx@@ -143,9 +143,8 @@ describe('ProjectActionsMenuHost', () => {});it('moves the one menu across cards instead of racing sibling layers', async () => {- // Per-card menus died here: zag's dismissable stack treats a layer mounted- // above another as nested, so the second card's menu was dismissed along- // with the first card's still-closing one.+ // A single host prevents Zag from treating the next card's menu as nested under the still-closing previous+ // menu.host = document.createElement('div');document.body.append(host);root = createRoot(host);@@ -181,8 +180,7 @@ describe('ProjectActionsMenuHost', () => {expect(openMenus()).toHaveLength(1);expect(dotsButton('two').getAttribute('aria-expanded')).toBe('true');- // A dots click opens; a second dots click toggles closed (the pointerdown- // already dismissed the menu — the click must not reopen it).+ // A second dots click closes; pointerdown dismissal must not cause click to reopen.await leftClick(dotsButton('one'));expect(openMenus()).toHaveLength(1);expect(dotsButton('one').getAttribute('aria-expanded')).toBe('true');diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsxindex 96befdeeb8..40d7abb15b 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx@@ -14,16 +14,8 @@ import { ProjectActionsMenuBody } from './ProjectActionsMenu';import { useProjectCardActions } from './useProjectCardActions';/**- * One menu instance for every project card on the page.- *- * Per-card menus raced: zag's dismissable stack treats any layer mounted- * above another as nested, so right-clicking card B while card A's menu was- * still tearing down dismissed B's menu along with A's. A single host never- * has two layers — switching targets remounts the one menu, and React runs- * the old instance's cleanup before the new one's effects in the same commit.- *- * The rename/delete dialogs live beside the menu, not inside it, because- * choosing a menu item closes the menu (and with it anything it rendered).+ * Use one menu host so switching cards cannot race Zag's nested-layer teardown. Keep dialogs beside the menu so+ * selecting an action does not unmount them.*/interface ProjectMenuTarget {@@ -131,9 +123,6 @@ export const ProjectActionsMenuProvider = ({ children }: { children: ReactNode }/><ConfirmDialog- // No "it is open, so it may come back" caveat: an open project is deleted through the- // editor's own sync handle, so the deletion is final either way. What is worth saying- // instead is what else goes — the project's board — and what does not.body={`${t('projects.deleteProjectCardBody', { name: dialogRequest?.name ?? '' })} ${t('projects.deleteProjectBoardNote')}`}confirmLabel={t('projects.deleteProject')}isOpen={dialogRequest?.kind === 'delete'}@@ -147,13 +136,7 @@ export const ProjectActionsMenuProvider = ({ children }: { children: ReactNode }const NOOP_SUBMIT = () => Promise.resolve();-/**- * Handlers for a card's dots button. The button is not a registered zag- * trigger, so a pointerdown on it while its own menu is open dismisses the- * menu as an outside interaction — and the click that follows would reopen- * it. The pointerdown handler runs while the pre-dismiss state is still- * rendered, so it can mark the click as a toggle-close instead.- */+/** Remember open state on pointerdown so outside dismissal followed by click toggles closed instead of reopening. */export const useProjectActionsMenuTrigger = (target: ProjectMenuTarget) => {const menu = useProjectActionsMenu();const suppressNextOpenRef = useRef(false);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCard.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCard.tsxindex a74e464604..9ab747c556 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCard.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCard.tsx@@ -16,10 +16,8 @@ import { ProjectCompatibilityBadge } from './ProjectCompatibilityBadge';import { ProjectCover } from './ProjectCover';/**- * One saved project in the library grid. The whole card is a deep link into- * the editor (`/app?project=…` — hovering preloads the editor chunk); the- * corner menu and right-click carry the library actions, served by the page's- * shared `ProjectActionsMenuHost`.+ * Cards deep-link to the editor and preload on hover; the shared menu host handles overflow and right-click+ * actions.*/const CARD_HOVER = { bg: 'bg.muted', borderColor: 'border.emphasized' } as const;diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.browser.test.tsxindex 7ee1b82216..420e34fcb5 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.browser.test.tsx@@ -6,13 +6,7 @@ import { afterEach, describe, expect, it } from 'vitest';import { ProjectCover } from './ProjectCover';-/**- * The three states a cover has: an image, no image, and an image the browser- * could not load. The last is the one worth pinning — a cover names a server- * image that may since have been deleted, and a broken `<img>` reads worse than- * the glyph. All three reserve the same box, so a grid does not reflow as- * covers resolve.- */+/** Image, absent-cover, and failed-load states reserve identical geometry; deleted images fall back to the glyph. */// A 1x1 transparent GIF, so the success path needs no network.const PIXEL = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.tsxindex ff602bbcb5..3a98c4e737 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.tsx@@ -3,19 +3,8 @@ import { FolderIcon } from 'lucide-react';import { useCallback, useState } from 'react';/**- * A project's thumbnail.- *- * `coverUrl` comes from the per-user cover index (`projects/covers.ts`), which- * records each project's newest result as it saves. The box is reserved- * unconditionally, so a card does not reflow when its cover resolves.- *- * The glyph is not a placeholder awaiting an image. It is the permanent state- * for a project that has produced nothing, and for a cover whose image has- * since been deleted — a broken `<img>` reads worse than the glyph, so a load- * failure falls back to it.- *- * The image is decorative (`alt=""`): every caller renders the project's name- * beside it, and announcing it twice helps nobody.+ * Reserve cover geometry to prevent reflow. Missing or deleted covers use the permanent glyph; images are+ * decorative beside the project name.*/export const PROJECT_COVER_ASPECT_RATIO = 16 / 10;diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectRow.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectRow.tsxindex 8d69ccccb0..74198cd1b1 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectRow.tsx@@ -16,13 +16,6 @@ import { useProjectActionsMenu, useProjectActionsMenuTrigger } from './ProjectAcimport { ProjectCompatibilityBadge } from './ProjectCompatibilityBadge';import { ProjectCover } from './ProjectCover';-/**- * One saved project in the list view — the density a large library wants.- * Carries the same link target and the same action menu as the grid card- * (served by the page's shared `ProjectActionsMenuHost`); only the shape- * differs.- */-const LINK_STYLE = { cursor: 'default', inset: 0, position: 'absolute' } as const;const REVEAL_ON_HOVER = { opacity: 1 } as const;const THUMBNAIL_WIDTH = '14';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsBrowser.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsBrowser.tsxindex b58a80475b..5549378c12 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsBrowser.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsBrowser.tsx@@ -27,14 +27,8 @@ import {} from './projectsMetrics';/**- * The library itself: grouped, virtualized, and in whichever layout was chosen- * last.- *- * Rows are the virtualization unit in both layouts — a grid row holds- * `columnCount` cards, a list row holds one — so headings and items share a- * single flat index space and grouping costs nothing extra. Row heights are- * derived rather than measured, which is what lets the virtualizer place- * everything without a layout pass.+ * Virtualize derived-height rows in both layouts: grid rows hold multiple cards, list rows one. Headings share the+ * same flat index space.*/const MEASURE_SX: SystemStyleObject = {@@ -179,10 +173,6 @@ export const ProjectsBrowser = ({) : rows.length === 0 ? (<ProjectsEmptyState isSearching={isSearching} searchTerm={searchTerm} onClearSearch={onClearSearch} />) : (- // No "new project" cell here: the page header already carries that- // action, and a lone dashed tile in a four-column row reads as a- // broken grid. The empty state, where it is the only thing to do,- // still offers it.<Box height={`${virtualizer.totalSize}px`} position="relative" w="full">{virtualizer.virtualItems.map((virtualRow) => {const row = rows[virtualRow.index];@@ -259,9 +249,7 @@ const VirtualProjectsRow = ({</SimpleGrid>) : (row.projects.map((project) => (- // The wrapper owns the virtualizer's full row pitch. No divider: the- // row's own rounded hover fill separates the items, and a hairline- // running under a rounded fill only cuts across its corners.+ // Let the wrapper own full row pitch; rounded hover fills separate items without intersecting dividers.<Box h={`${PROJECT_ROW_HEIGHT_PX}px`} key={project.id}><ProjectRow isPinned={pinnedIds.includes(project.id)} summary={project} onTogglePin={onTogglePin} /></Box>@@ -271,16 +259,6 @@ const VirtualProjectsRow = ({);};-/**- * Both empty states align to `start`, on the same axis as the page heading,- * the description and the search field. A centered block under a left-aligned- * page shares an edge with nothing above it.- *- * The action is a button, not the dashed tile this used to render. That tile- * was a grid cell with no grid around it — floating at an arbitrary width, and- * shown even in list view — and it repeated a call to action the header- * already carries. A button matches what the no-matches state beside it does.- */const ProjectsEmptyState = ({isSearching,onClearSearch,@@ -314,10 +292,6 @@ const ProjectsEmptyState = ({icon={NO_PROJECTS_ICON}title={t('projects.noSavedProjects')}>- {/* Outline, not solid: the header already carries this action as the- page's one accent, and repeating that weight a few hundred pixels- away doubles the loudest thing on an otherwise quiet screen without- adding a choice. */}<NewProjectButton variant="outline" /></EmptyState>);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsToolbar.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsToolbar.browser.test.tsxindex b11a4d05c7..9d87fd0e95 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsToolbar.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsToolbar.browser.test.tsx@@ -7,14 +7,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { ProjectsToolbar } from './ProjectsToolbar';/**- * The layout control, which is a segmented radio group wearing two icons.- *- * Both assertions here exist because of a shape that looks right and is not.- * `Tooltip.Trigger` is `asChild` and merges its own `data-state` onto whatever- * it clones, so wrapping the *item* silently overwrites `data-state="checked"`- * — the selected segment styles as unselected and the indicator measures 0×0.- * Moving the tooltip onto the icon fixes that but puts it on an `<svg>`, which- * cannot take focus, so the label goes hover-only. Both need to hold at once.+ * Verify both selected styling and keyboard tooltips: asChild on the item overwrites checked data-state, while an+ * icon-only trigger cannot receive focus.*/let host: HTMLDivElement | null = null;@@ -73,11 +67,7 @@ const waitUntil = async (predicate: () => boolean, description: string) => {throw new Error(`never became true: ${description}`);};-/**- * By position, not by label: these tests run without an i18next instance, so- * `t()` returns its key. What matters here is the wiring, and the two segments- * render in `PROJECTS_VIEW_IDS` order — grid, then list.- */+/** Select by PROJECTS_VIEW_IDS order because tests render untranslated keys. */const viewRadios = (container: HTMLElement): HTMLInputElement[] => {const radios = [...container.querySelectorAll<HTMLInputElement>('input[type="radio"]')];diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsToolbar.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsToolbar.tsxindex 4161c0267e..c83dabf257 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsToolbar.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsToolbar.tsx@@ -11,21 +11,6 @@ import type { ProjectSortId, ProjectsViewId } from './projectLibraryView';import { isProjectsViewId, PROJECT_SORT_IDS, PROJECTS_VIEW_IDS } from './projectLibraryView';-/**- * Search, ordering, and layout for the project library.- *- * The row spans the page's measure rather than packing to the left: search- * holds the left edge under the heading, and the controls sit on the right- * edge under the header's buttons. That gives the top of the page two vertical- * lines instead of one line and a drifting cluster.- *- * The layout choice is a `SegmentGroup`, not two adjacent icon buttons. Two- * buttons where one happens to be highlighted read as two actions, one of- * which is somehow active; a segmented control reads as one control with two- * positions, which is what it is. It also inherits the design system's- * concentric radii — `radii.sm` items inside a `radii.md` track.- */-const MENU_POSITIONING = { placement: 'bottom-end' } as const;const SEARCH_ICON = <Icon as={SearchIcon} boxSize="3.5" color="fg.subtle" />;@@ -46,18 +31,8 @@ const VIEW_ICON: Record<ProjectsViewId, typeof LayoutGridIcon> = {};/**- * One position of the layout control.- *- * The tooltip wraps the icon rather than the item, because `Tooltip.Trigger` is- * `asChild` and merges its own `data-state` onto whatever it clones — on the- * item that overwrites `data-state="checked"`, so the selected segment styles- * as unselected and the indicator measures 0×0.- *- * An icon is not focusable, though, so hover alone would leave the label- * unreachable by keyboard — the tooltip used to sit on an `IconButton`, which- * was. The hidden radio *is* the focusable control here, so it drives the- * tooltip open alongside pointer hover. Screen readers were never affected:- * the radio carries the accessible name either way.+ * Attach the tooltip to the icon to preserve the item's checked data-state; drive it from hidden-radio focus for+ * keyboard access.*/const ViewSegment = ({ id }: { id: ProjectsViewId }) => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/projectLibraryView.ts b/invokeai/frontend/webv2/src/workbench/launchpad/projects/projectLibraryView.tsindex c731535ab5..da4da5fda9 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/projectLibraryView.ts+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/projectLibraryView.ts@@ -1,12 +1,6 @@import type { ProjectSummary } from '@workbench/projects/library';-/**- * How the project library is presented: what matches the search, what order it- * is in, and which bucket each project falls into.- *- * All of it is pure and takes `now` as an argument rather than reading the- * clock, so the date bucketing is testable without freezing time.- */+/** Keep filtering, sorting, and grouping pure; inject now for deterministic date buckets. */export type ProjectSortId = 'edited' | 'created' | 'name';@@ -93,11 +87,7 @@ export const matchesProjectSearch = (summary: ProjectSummary, searchTerm: stringconst DATE_GROUP_ORDER: readonly ProjectGroupId[] = ['today', 'week', 'month', 'older'];-/**- * Group order is fixed: pinned, then what is already open, then recency. A- * search or an alphabetical sort collapses the date buckets into one `all`- * group — ranking twelve results under four date headings hides them.- */+/** Group pinned, open, then recent projects; search and alphabetical sort collapse date buckets. */export const buildProjectGroups = ({now,openProjectIds,@@ -149,14 +139,7 @@ export type ProjectRowModel =| { kind: 'header'; group: ProjectGroupId; count: number }| { kind: 'projects'; group: ProjectGroupId; projects: ProjectSummary[] };-/**- * Flatten groups into virtualizer rows. `columnCount` is how many cards share- * a row, so the grid virtualizes by row and the list is just the same shape- * with one column.- *- * A single unnamed group (the search/alphabetical `all` case) renders without- * a heading — there is nothing to distinguish it from.- */+/** Flatten headings and card rows into one virtualizer index; omit the heading for a single unnamed group. */export const flattenProjectGroupsToRows = (groups: readonly ProjectGroup[], columnCount: number): ProjectRowModel[] => {const perRow = Math.max(1, columnCount);const showHeadings = groups.length > 1 || groups[0]?.id !== 'all';diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/projectPins.ts b/invokeai/frontend/webv2/src/workbench/launchpad/projects/projectPins.tsindex 4867bc9a51..2f5cb1cb19 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/projectPins.ts+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/projectPins.ts@@ -4,17 +4,7 @@ import { getWorkbenchPreferences, patchWorkbenchPreferences } from '@workbench/simport { prunePinnedProjectIds, toggleProjectPin } from './projectLibraryView';-/**- * Pin writes, in one place.- *- * Pins live in account preferences, so they follow the user across devices —- * which also means a stale id persists forever unless something removes it.- * Home and the library both pin, and both now go through here rather than- * each reimplementing the read-modify-write.- *- * Every write reads the live snapshot rather than a captured render value, so- * two quick toggles cannot drop the first one.- */+/** Centralize account pin writes and read the live snapshot so rapid toggles do not overwrite each other. */export const toggleProjectPinPreference = (projectId: string): void => {const current = getWorkbenchPreferences().launchpadPinnedProjectIds;diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/projectsMetrics.ts b/invokeai/frontend/webv2/src/workbench/launchpad/projects/projectsMetrics.tsindex 46ea8d6812..feca6a3b1a 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/projectsMetrics.ts+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/projectsMetrics.ts@@ -2,13 +2,7 @@ import { useCallback, useRef, useState } from 'react';import type { ProjectsViewId } from './projectLibraryView';-/**- * The grid's measurements, as numbers rather than CSS breakpoints.- *- * The virtualizer needs both before anything is laid out: how many cards share- * a row, and how tall a row is. Measuring the container rather than the window- * keeps both honest when the panel is resized instead of the browser.- */+/** Derive row height and column count from container width so virtualization also responds to panel resizing. */const MIN_CARD_WIDTH_PX = 240;const MAX_COLUMNS = 4;diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts b/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.tsindex 35d2f27b59..0a01be4dfb 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts@@ -6,11 +6,7 @@ import { useTranslation } from 'react-i18next';import { dropProjectPin } from './projectPins';-/**- * The library actions a single project offers, shared by the grid card and the- * list row so the two cannot drift. Every one runs against the server without- * mounting the editor.- */+/** Share server-backed library actions between grid and list without mounting the editor. */export interface ProjectCardActions {rename: (name: string) => Promise<void>;/** Reports its own progress and result, so there is nothing to await here. */@@ -42,9 +38,7 @@ export const useProjectCardActions = (summary: ProjectSummary): ProjectCardActio[summary.id, t]);- // Progress, partial success and error translation all come from the shared reporter — the same- // one import and export use. Duplication runs the same restore engine over the same board, so a- // hand-rolled toast here only meant it reported that work differently from its twins.+ // Use the import/export reporter because duplication shares their restore engine and progress/error semantics.const duplicate = useCallback(() => {startDuplicate(summary.id);}, [startDuplicate, summary.id]);@@ -68,9 +62,7 @@ export const useProjectCardActions = (summary: ProjectSummary): ProjectCardActio}}, [summary.id, t]);- // Memoized because `ProjectActionsMenu` derives callbacks from this object, and the browser- // renders one of these per row in a virtualized list: a fresh literal each render invalidates- // every one of them on every render.+ // Stabilize the actions object so virtualized row renders do not invalidate derived menu callbacks.return useMemo(() => ({ delete: deleteProject, duplicate, export: exportProject, rename }),[deleteProject, duplicate, exportProject, rename]diff --git a/invokeai/frontend/webv2/src/workbench/layerPanelState.ts b/invokeai/frontend/webv2/src/workbench/layerPanelState.tsindex 2042aeef00..01e71e23b0 100644--- a/invokeai/frontend/webv2/src/workbench/layerPanelState.ts+++ b/invokeai/frontend/webv2/src/workbench/layerPanelState.ts@@ -5,9 +5,8 @@ import { createExternalStore } from '@platform/state/externalStore';import { getDocumentIndex } from '@workbench/canvas-engine/api';/**- * Transient Layers-panel state, kept per project and outside the document, its snapshots and- * history. The primary selection stays `document.selectedLayerId`; `primaryId` mirrors the value- * this state was built against so an external primary change collapses stale secondaries.+ * Per-project transient selection stays outside persistence/history; primaryId detects external primary changes+ * and clears stale secondaries.*/export interface LayerPanelState {@@ -198,11 +197,7 @@ export const setLayerPanelFilter = (projectId: string, primaryId: string | null,}};-/**- * Keeps a state valid after an external primary change, a project switch, or a node removal. A- * primary that arrived from outside the panel (a hotkey, an undo, a new layer) is revealed: every- * group above it expands so the row it names is on screen.- */+/** Reconcile external changes and removals; reveal an externally selected primary by expanding its ancestors. */export const reconcileLayerPanelState = (state: LayerPanelState,projectId: string,diff --git a/invokeai/frontend/webv2/src/workbench/layoutContracts.ts b/invokeai/frontend/webv2/src/workbench/layoutContracts.tsindex b8d237ae5c..5e582fb45b 100644--- a/invokeai/frontend/webv2/src/workbench/layoutContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutContracts.ts@@ -1,12 +1,7 @@import type { InvocationSourceId, ResultDestination } from './invocationContracts';import type { WidgetInstanceId, WidgetTypeId } from './widgetContracts';-/**- * The 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`).- */+/** Presets name arrangements, not invocation sources; graphWidgets owns source resolution. */export type BuiltInLayoutPresetId = 'compose' | 'edit' | 'automate' | 'video';export type LayoutPresetId = BuiltInLayoutPresetId | (string & {});@@ -37,11 +32,7 @@ export interface FloatingWidgetState {mode: FloatingWidgetMode;/** The dockable region this window returns to when docked. */returnRegion: WidgetRegion;- /**- * Where it sat in that region's tab strip when it floated, so docking puts it- * back rather than appending. Optional: entries written before this existed,- * and any whose index cannot be trusted, dock to the end.- */+ /** Original rail index for docking; absent or invalid indices append. */returnIndex?: number;/** Z-order within the floating layer; higher renders on top. */stackOrder: number;@@ -73,11 +64,7 @@ export interface LayoutPresetSnapshot {layout: ProjectLayoutState;widgetInstances: Record<WidgetInstanceId, LayoutPresetWidgetInstanceSnapshot>;widgetRegions: Record<WidgetRegion, WidgetRegionState>;- /**- * Captured with widgetRegions: a floated instance is in no region, so a- * preset that recorded only the regions would drop it on the floor. Absent- * on presets saved before floating existed, which have no floating windows.- */+ /** Capture windows with widgetRegions so floated instances survive presets; absent means none. */floatingWidgets?: Record<WidgetInstanceId, FloatingWidgetState>;}@@ -96,20 +83,12 @@ export interface LayoutPreset {isBuiltIn?: boolean;/** Missing only on legacy or source-less custom presets. */defaultRoute?: LayoutPresetRoute;- /**- * 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.- */+ /** Persist an icon id, resolved through the picker registry with an unknown-id fallback. */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.- */+/** Account overrides store edits to code-owned built-ins and drive both drift checks and revert. */export type LayoutPresetOverrides = Partial<Record<BuiltInLayoutPresetId, LayoutPresetSnapshot>>;/** Per-account edits to the default routes shipped with built-in presets. */diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.tsindex b8047ae35a..916c0900fc 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.ts@@ -36,8 +36,7 @@ describe('layout preset activation', () => {expect(appliedPresetIds).toEqual(['edit']);});- // Callers paint the selection before the store has it; a dropped activation- // that resolved silently would strand the control on a preset nothing applied.+ // Dropped activations must reject so optimistic preset selection can recover.it('reports the dropped activation when the active project changed under it', async () => {const appliedPresetIds: string[] = [];let activeProjectId = 'project-a';@@ -142,11 +141,7 @@ describe('layout preset activation', () => {expect(appliedPresetIds).toEqual([layoutPresets[0].id]);});- // Condition 2 of the fast-path contract: the fast path must bump- // latestRequestId itself, not rely on apply's downstream dispatch to do it.- // If it didn't, an earlier slow activation — still racing its deadline —- // would see requestId === latestRequestId when its timer fires and would- // overwrite the fast-path's result.+ // The warm fast path must advance latestRequestId itself so an older cold deadline cannot overwrite it.it('bumps the request id so an earlier pending slow activation cannot overwrite a later fast-path apply', async () => {const appliedPresetIds: string[] = [];let loaded = false;@@ -159,18 +154,12 @@ describe('layout preset activation', () => {load: () => new Promise(() => {}),});- // Start a slow activation for a cold preset; it will sit waiting for its- // deadline timer.const slowActivation = activator.activate(layoutPresets[0]);- // A later, fully-warm activation for a different preset takes the fast- // path and applies synchronously.loaded = true;void activator.activate(layoutPresets[1]);expect(appliedPresetIds).toEqual(['edit']);- // When the slow activation's deadline fires, it must see it has been- // superseded and must not clobber the fast-path result.await expect(slowActivation).resolves.toBeNull();expect(appliedPresetIds).toEqual(['edit']);});diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.tsindex d5b6a31073..2cdd00ee63 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.ts@@ -4,14 +4,8 @@ import { getLayoutWidgetTypeIds } from './layoutWidgetSet';import { loadWidgets, warmWidgets } from './widgetRegistry';/**- * How long a *cold* activation waits for widget implementations before- * applying the preset anyway. A fully warm switch (every widget already in- * memory) never consults this — it applies synchronously in the caller's own- * task. This deadline only bounds how long the tab waits before revealing a- * cold switch progressively; the tab has already acknowledged the press- * either way. A cold or failing chunk stops gating the entire layout at this- * deadline: the switch commits and the stragglers reveal progressively behind- * their own per-widget fallbacks.+ * Bound cold widget loading before applying the preset with per-widget fallbacks. Fully warm switches apply+ * synchronously and never consult the deadline.*/const APPLY_DEADLINE_MS = 250;@@ -66,11 +60,8 @@ export const createLayoutPresetActivator = ({const projectId = getActiveProjectId();const requestId = ++latestRequestId;- // The common case — hover-preloaded, or a preset visited before. Awaiting- // here costs a microtask, which is enough to push the commit out of the- // click's own task and lose the frame on which the press was acknowledged.- // `requestId` is already bumped above, so a still-pending slow activation- // that lands after this one cannot overwrite it.+ // Apply warm presets synchronously in the click task; the already-advanced request id fences older cold+ // activations.if (isLoaded(preset)) {apply(preset.id);diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetCollection.test.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetCollection.test.tsindex 119e7b2f7f..6022e2f7d8 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresetCollection.test.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetCollection.test.ts@@ -30,8 +30,7 @@ describe('layout preset collection', () => {});it('slots a newly shipped built-in beside its neighbour instead of appending it', () => {- // The order every account persisted before Video shipped. Appending would- // pin Video to the end of the strip for all of them.+ // Use pre-Video saved order to catch unconditional append behavior.expect(normalizeLayoutPresetOrder(['compose', 'edit', 'automate'], layoutPresets)).toEqual(['compose','edit',diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetCollection.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetCollection.tsindex 129ad9f86e..9397bff4f0 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresetCollection.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetCollection.ts@@ -5,17 +5,8 @@ import { layoutPresets } from './layoutPresets';import { resolveSavedLayoutPreset } from './layoutPresetSnapshots';/**- * The account's saved order, with anything it has never seen slotted in.- *- * A preset the order has never recorded is placed next to its canonical- * neighbour rather than appended. Appending looks the same on a fresh account —- * nothing is stored, so every preset is "new" and they land in `presets` order- * — but it is wrong the moment a *shipped* preset is added later: every- * existing account would pin it to the end of the strip no matter where the- * built-in list puts it, and there is no schema version to hang a migration on.- *- * The saved order still wins for everything it does name: ids already stored- * keep their relative positions, so a dragged tab stays dragged.+ * Preserve saved relative order, inserting unseen presets beside canonical neighbors so newly shipped presets do+ * not always append.*/export const normalizeLayoutPresetOrder = (value: unknown, presets: readonly LayoutPreset[]): LayoutPresetId[] => {const knownIds = new Set(presets.map(({ id }) => id));@@ -36,8 +27,6 @@ export const normalizeLayoutPresetOrder = (value: unknown, presets: readonly Layreturn;}- // The nearest preset that canonically precedes this one and is already- // placed. Nothing before it means it belongs at the front.let insertAt = 0;for (let index = presetIndex - 1; index >= 0; index -= 1) {diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.tsindex 0f8f4bdd1e..8bc58ac0ac 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts@@ -32,13 +32,7 @@ export const getLayoutPresetCommandTitleOverrides = (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.- */+/** Apply, revert, and drift checks all resolve account overrides here so Save changes has consistent meaning. */export const resolveSavedLayoutPreset = (account: AccountState, presetId: LayoutPresetId): LayoutPreset => {const resolvedPresetId = resolveLayoutPresetId(presetId);const customPreset = isBuiltInLayoutPresetId(resolvedPresetId)@@ -137,13 +131,7 @@ const areWidgetInstanceSnapshotsEqual = ();};-/**- * Window geometry counts as drift for the same reason panel `sizePx` does: it- * is part of what `Save changes` would store, so the strip's dot has to offer- * to store it. `stackOrder` is excluded — it is a monotonically rising counter- * bumped by every click on a window, so comparing it would leave the dot lit- * for good the first time someone focuses one.- */+/** Geometry counts as saved-layout drift; focus-driven stack ordering does not. */const areFloatingWidgetsEqual = (left: LayoutPresetSnapshot['floatingWidgets'],right: LayoutPresetSnapshot['floatingWidgets']diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.test.tsindex a94447e59d..4a90d02535 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts@@ -102,10 +102,6 @@ describe('built-in layout preset descriptors', () => {right: 'gallery',},bottom: ['server-status', 'queue-status', 'gallery:bottom', 'notifications', 'autosave-status'],- // Compose keeps Gallery as a center view: the retired `gallery` preset- // migrates here (see legacyLayoutPresetIds) precisely because it was- // "Compose with the center view swapped", so the swap has to remain- // available.center: ['preview', 'gallery:center'],left: ['generate', 'upscale'],panels: { isBottomOpen: false, isLeftOpen: true, isRightOpen: true },@@ -122,8 +118,6 @@ describe('built-in layout preset descriptors', () => {center: ['canvas', 'preview'],left: ['generate', 'upscale'],panels: { isBottomOpen: false, isLeftOpen: true, isRightOpen: true },- // The editors are panes inside the Layers panel; the preview docks- // behind Layers so its float/dock surface stays reachable by default.right: ['layers', 'preview'],},video: {diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.tsindex 738e79598c..968e9ecec6 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts@@ -148,11 +148,7 @@ const createPresetDescriptor = ({},});-/**- * The shipped presets. Each combines an arrangement with an editable default- * route. The route is explicit preset data rather than something inferred from- * whichever graph widgets happen to be placed in the layout.- */+/** Presets define arrangement and default route explicitly; placed graph widgets do not determine the route. */export const builtInLayoutPresetDescriptors: BuiltInLayoutPresetDescriptor[] = [createPresetDescriptor({centerViewId: 'preview',@@ -171,12 +167,8 @@ export const builtInLayoutPresetDescriptors: BuiltInLayoutPresetDescriptor[] = [isCollapsed: true,sizePx: 180,}),- // Gallery stays a center view here: the retired `gallery` preset resolves- // to Compose because it was "Compose with the center view swapped" (see- // legacyLayoutPresetIds), so the swap has to stay reachable. Curating it- // out also made Gallery an *addable* widget instead of a placed one,- // which routed the switch through a menu that warms the Canvas chunk on- // intent — a chunk a gallery-only session must never download.+ // Keep Gallery placed in Compose so migrated gallery presets remain reachable without the add-widget path+ // warming Canvas.center: createRegion({activeInstanceId: 'preview',instanceIds: ['preview', 'gallery:center'],@@ -223,9 +215,7 @@ export const builtInLayoutPresetDescriptors: BuiltInLayoutPresetDescriptor[] = [}),right: createRegion({activeInstanceId: 'layers',- // Preview docks behind Layers: the editors are Layers panes, but the- // preview is a floatable widget, and its float/dock pair and floated- // Invoke control are only reachable where it is actually placed.+ // Place Preview behind Layers so its float/dock and floated Invoke controls remain reachable.instanceIds: ['layers', 'preview'],sizePx: 450,}),@@ -306,11 +296,7 @@ export const layoutPresets: BuiltInLayoutPreset[] = builtInLayoutPresetDescriptoexport 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.- */+/** The historical gallery preset was a Compose center-view variant, so it maps to Compose. */const legacyLayoutPresetIds: Record<string, BuiltInLayoutPresetId> = {canvas: 'edit','canvas-default': 'compose',@@ -318,11 +304,7 @@ const legacyLayoutPresetIds: Record<string, BuiltInLayoutPresetId> = {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.- */+/** Remap historical built-in ids; account-defined custom ids pass through unchanged. */export const resolveLayoutPresetId = (presetId: string): string => legacyLayoutPresetIds[presetId] ?? presetId;export const getLayoutPreset = (presetId: string): BuiltInLayoutPreset =>diff --git a/invokeai/frontend/webv2/src/workbench/layoutWidgetSet.ts b/invokeai/frontend/webv2/src/workbench/layoutWidgetSet.tsindex 3787ed13cf..4ca42488d3 100644--- a/invokeai/frontend/webv2/src/workbench/layoutWidgetSet.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutWidgetSet.ts@@ -10,21 +10,12 @@ export interface LayoutWidgetSource {widgetRegions: Record<string, { activeInstanceId: string; instanceIds: string[] }>;}-/**- * Regions in the order a boot reveals them, so callers that care about- * priority get it for free and callers that do not are unaffected.- */+/** Order regions by boot reveal priority. */const REGION_ORDER = ['center', 'left', 'right', 'bottom'];/**- * Every widget type a layout renders: each region's active instance, plus every- * placed bottom instance — the status bar mounts all of its items as compact- * widgets, not just the active one.- *- * Single definition on purpose. The boot preloader and the preset activation- * gate previously disagreed: activation only awaited region actives, so a- * switch never gated on four of the five bottom instances every built-in preset- * places, and the atomic reveal the deadline buys was incomplete.+ * Include every active region widget and all bottom widgets, since the status bar renders them all. Share this set+ * between preload and activation gating.*/export const getLayoutWidgetTypeIds = (layout: LayoutWidgetSource): WidgetTypeId[] => {const typeIds = new Set<WidgetTypeId>();diff --git a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsxindex 546a2814cd..ebad474ad7 100644--- a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx@@ -248,12 +248,8 @@ describe('CommandPaletteDialog interaction', () => {const { input } = await renderPalette({ entries: [], providers: [provider] });await act(() => userEvent.fill(input, 'zz'));- // Let the root search reject first, so the scope is entered from the settled- // state rather than from the window before the debounce fires. Tab only- // enters a scope when a scope row is highlighted, and the rejected root- // search puts its own navigable "Retry entities search" row ahead of the- // trailing scope rows — so reach the scope row explicitly, as ArrowUp wraps- // to it either way.+ // Wait for root rejection, then explicitly highlight the scope row; the retry row precedes scopes and Tab+ // enters only the highlighted scope.await waitForDebounce();await act(() => userEvent.keyboard('{ArrowUp}'));await act(() => userEvent.keyboard('{Tab}'));diff --git a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsxindex ba6912c9b9..8fdd20b29a 100644--- a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx@@ -69,8 +69,6 @@ export const CommandPaletteDialog = ({finalFocusEl={getCommandPaletteReturnFocusElement}lazyMountopen={isOpen}- // Not the recipe's centered tool-window placement: a palette hangs from- // the top band (its positioner pins the exact offset).placement="top"restoreFocusscrollBehavior="inside"diff --git a/invokeai/frontend/webv2/src/workbench/palette/contributionKey.ts b/invokeai/frontend/webv2/src/workbench/palette/contributionKey.tsindex afe7748f36..c2fcef82f6 100644--- a/invokeai/frontend/webv2/src/workbench/palette/contributionKey.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/contributionKey.ts@@ -1,11 +1,8 @@import type { WidgetContributionSource } from '@workbench/widgetContracts';/**- * Stable identity for every palette contribution. Widget source identity is- * part of the key so two instances may safely contribute the same local id.- * The source tuple intentionally mirrors getWidgetContributionSourceKey;- * keeping the palette helper self-contained prevents its lazy chunk from- * pulling extension registry internals into either route's initial graph.+ * Include widget source identity so instances can reuse local ids. Mirror the source tuple locally to preserve the+ * palette's lazy boundary.*/export const getPaletteContributionKey = (kind: 'command' | 'provider' | 'provider-error' | 'provider-result' | 'provider-row' | 'scope' | 'scope-command',diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.test.tsindex bc29fc7176..aad3d8dad9 100644--- a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts@@ -23,13 +23,6 @@ import {resolveActivePaletteRow,} from './entries';-/**- * The palette's source aggregation and ranking contract: unimplemented and- * hotkey-only commands never surface, widget commands follow layout presence,- * settings rows read/write preferences, and the row list keeps its fixed- * section order with fuzzy ranking inside each section.- */-const noop = () => undefined;const translations: Record<string, string> = {'commandPalette.actions.openInSettings': 'Open in Settings',diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.tsindex e338bbb2af..5e81147e4e 100644--- a/invokeai/frontend/webv2/src/workbench/palette/entries.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.ts@@ -11,11 +11,8 @@ import fuzzysort from 'fuzzysort';import { getPaletteContributionKey } from './contributionKey';/**- * Palette content model: every source (catalog commands, extension palette- * contributions, settings, navigation) normalizes into `PaletteEntry`, and- * `searchPaletteRows` turns the aggregate into the rendered row list. Ranking- * is fuzzy (fuzzysort) *within* a section; section order itself is fixed so- * the list reads spatially — commands above settings, always.+ * Normalize sources to PaletteEntry; rank fuzzily within fixed sections so command/settings placement remains+ * stable.*/export interface PaletteStageOption {@@ -148,14 +145,7 @@ const groupRank = (group: string): number => {return index === -1 ? PALETTE_GROUP_ORDER.length : index;};-// ----------------------------------------------------------------------------// Commands source (hotkey catalog)-// -----------------------------------------------------------------------------/**- * Hotkey-only interactions that would be pure noise as palette rows: arrow- * navigation, caret-relative nudges, and the palette's own toggle.- */+/** Omit navigation, caret nudges, and the palette toggle from searchable rows. */const PALETTE_HIDDEN_COMMANDS = new Set(['app.openCommandPalette',// Both palettes already ship `buildOpenSettingsEntry` under this id, and it@@ -281,10 +271,6 @@ export const buildCatalogCommandEntries = ({};});-// ----------------------------------------------------------------------------// Settings source-// ----------------------------------------------------------------------------export interface SettingsEntryDeps {openSettingsSection: (destination: SettingsSectionId | SettingsDestination) => void;patchPreferences: (patch: Partial<WorkbenchPreferences>) => unknown;@@ -296,11 +282,7 @@ export interface SettingsEntryDeps {themes: ReadonlyArray<{ id: WorkbenchPreferences['themeId']; label: string }>;}-/**- * The "Open Settings" entry shared verbatim by both palette hosts. `keys` is- * the resolved `app.openSettings` shortcut, which only the editor binds — the- * Launchpad has no hotkey catalog, so it omits the hint.- */+/** Share Open Settings across hosts; only the editor supplies its resolved hotkey hint. */export const buildOpenSettingsEntry = (t: TFunction, openSettings: () => void, keys?: string[]): PaletteEntry => ({group: 'App',groupLabel: t('commandPalette.groups.app'),@@ -433,10 +415,6 @@ export const buildSettingsEntries = (return [...preferenceEntries, themeEntry, ...sections, ...fields];};-// ----------------------------------------------------------------------------// Search / row assembly-// ----------------------------------------------------------------------------interface RankedEntry {entry: PaletteEntry;matchIndexes?: readonly number[];@@ -502,11 +480,8 @@ const buildEmptyStateRows = (};/**- * The full query pipeline: empty query renders the launcher state (recents +- * navigation); otherwise fuzzysort ranks every entry over title/keywords/- * subtitle (subtitle down-weighted so value text like "On" cannot dominate),- * grouped into the fixed section order, ranked within each section by score,- * then recency, then title.+ * Empty queries show recents/navigation. Otherwise rank title/keywords/down-weighted subtitle within fixed+ * sections, breaking ties by recency then title.*/export const searchPaletteRows = (entries: readonly PaletteEntry[],@@ -574,10 +549,6 @@ export const searchPaletteRows = (return toGroupedRows(groups);};-// ----------------------------------------------------------------------------// Stage / provider row assembly-// ----------------------------------------------------------------------------/** Row-id prefix for stage options; the dialog strips it to recover the option id. */export const STAGE_ENTRY_ID_PREFIX = 'stage:';@@ -664,11 +635,7 @@ export const buildProviderSectionRows = (return rows;};-/**- * Trailing escape hatches into scoped mode, one per provider, under a shared- * "Search in" header. An empty query means a pure date filter is active — the- * scope searches "by date".- */+/** Offer one scoped-search escape per provider; an empty query represents date-only filtering. */export const buildScopeRows = (providers: ReadonlyArray<Pick<PaletteSearchProvider, 'providerKey' | 'label'>>,query: string,diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.tsindex 2b0c78731a..679a7925e7 100644--- a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts@@ -23,12 +23,7 @@ import type { PaletteEntry, PaletteSearchProvider } from './entries';import { getPaletteContributionKey } from './contributionKey';import { getObjectIdentity } from './objectIdentity';-/**- * First-party entity providers behind the palette's scoped search. Each is a- * plain factory taking the workbench callbacks it needs — the host component- * owns the hooks. Extension `search` contributions adapt into the same- * PaletteSearchProvider shape, so all sections aggregate identically.- */+/** Factories receive host-owned workbench callbacks; extension searches adapt to the same provider contract. */const PROVIDER_PAGE_SIZE = 8;@@ -322,8 +317,7 @@ export const createImagesProvider = ({const boardNames = new Map(boards.map((board: GalleryBoard) => [board.id, getGalleryBoardLabel(board, t)] as const));- // Images carry no prompt, so the creation date+time is the title; the time- // keeps same-day results (the common case for 20 recents) distinguishable.+ // Use date and time to distinguish promptless images generated on the same day.return page.images.map<PaletteEntry>((image) => {const createdAt = new Date(normalizeServerTimestamp(image.createdAt ?? image.queuedAt));diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteStore.tsindex 5d7f73f9c4..53649c88fb 100644--- a/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts@@ -3,11 +3,8 @@ import { createExternalStoreCore } from '@platform/state/externalStoreCore';import { useSyncExternalStore } from 'react';/**- * Open/close state for the command palette, addressable from anywhere: the- * top-bar buttons, the `app.openCommandPalette` command, and the Launchpad's- * own mod+K binding all funnel through here. The dialog is hosted per surface- * (WorkbenchCommandPalette in the editor, LaunchpadCommandPalette on the- * launchpad) and subscribes to this store.+ * Share palette visibility across topbar, editor command, and Launchpad shortcut; each surface hosts its own+ * subscribed dialog.*/export const commandPaletteStore = createExternalStoreCore<{ isOpen: boolean }>({ isOpen: false });diff --git a/invokeai/frontend/webv2/src/workbench/palette/recents.ts b/invokeai/frontend/webv2/src/workbench/palette/recents.tsindex 9737f820bc..6a7eba3789 100644--- a/invokeai/frontend/webv2/src/workbench/palette/recents.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/recents.ts@@ -1,9 +1,6 @@/**- * Frecency record of executed palette entries, persisted per browser (not per- * project — muscle memory should not reset when switching projects). Reads- * return ids ranked by use count decayed by recency; stored ids can go stale- * (commands renamed, widgets closed), so readers filter them against the live- * entry list at render time.+ * Persist decayed-use rankings per browser across projects; filter stale ids against current entries when+ * rendering.*/import type { PaletteEntry } from './entries';diff --git a/invokeai/frontend/webv2/src/workbench/panZoom.test.ts b/invokeai/frontend/webv2/src/workbench/panZoom.test.tsindex a58d12244f..dbc7b16783 100644--- a/invokeai/frontend/webv2/src/workbench/panZoom.test.ts+++ b/invokeai/frontend/webv2/src/workbench/panZoom.test.ts@@ -60,8 +60,6 @@ describe('panZoom', () => {);expect(next.zoom).toBe(2);- // The content point under the starting midpoint — (100, 50) at zoom 1 —- // ends up under the midpoint's new position.expect(next.zoom * 100 + next.pan.x).toBeCloseTo(140, 6);expect(next.zoom * 50 + next.pan.y).toBeCloseTo(60, 6);});@@ -75,8 +73,7 @@ describe('panZoom', () => {expect(atLimit.zoom).toBe(8);expect(pastLimit.zoom).toBe(8);- // Spreading further cannot zoom past the limit, but the gesture is still a- // move: both agree on where the anchored content point was dragged to.+ // Clamping zoom must still allow midpoint translation.expect(pastLimit.pan).toEqual(atLimit.pan);expect(pastLimit.zoom * 50 + pastLimit.pan.x).toBeCloseTo(180, 6);});diff --git a/invokeai/frontend/webv2/src/workbench/panZoom.ts b/invokeai/frontend/webv2/src/workbench/panZoom.tsindex a2a8d660e5..3aa9b6bb72 100644--- a/invokeai/frontend/webv2/src/workbench/panZoom.ts+++ b/invokeai/frontend/webv2/src/workbench/panZoom.ts@@ -1,11 +1,6 @@/**- * DOM-free pan/zoom state transitions shared by every workbench viewport.- *- * Coordinate convention: `screen = zoom * content + pan`. Callers provide- * their own zoom constraint because canvas, preview, and comparison viewports- * have different limits. Constraints are applied before anchor translation is- * calculated, so reaching a zoom limit is an exact no-op instead of becoming- * an accidental pan.+ * Shared DOM-free transitions use screen = zoom * content + pan. Clamp zoom before anchor translation so hitting a+ * limit does not pan.*//** Wheel exponential zoom sensitivity: `zoom *= exp(-deltaY * step)`. */@@ -78,15 +73,8 @@ export const panBy = (transform: PanZoomTransform, screenDelta: PanZoomPoint): P});/**- * Applies a two-pointer pinch: zoom scales by how far the pointers have spread- * since the gesture began, and the content point under the gesture's starting- * midpoint is carried to the midpoint's current position — so the image tracks- * the fingers rather than just growing around a fixed anchor.- *- * Every argument is measured against the transform the gesture *started* from,- * so each move is one transition from that origin instead of a step on top of- * the last one: clamping at a zoom limit never accumulates into drift, and- * spreading past the limit still pans with the fingers.+ * Measure every pinch move from the starting transform. Carry its anchored content point to the current midpoint,+ * allowing pan at zoom limits without accumulated drift.*/export const pinchZoomAtPoints = (start: PanZoomTransform,diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.tsindex c8f09c499f..d649d2ac64 100644--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts@@ -296,10 +296,8 @@ describe('Workbench persistence runtime', () => {});it('applies server outcomes from a save that went stale', async () => {- // A stale save is one whose *snapshot* moved on, which says nothing about what the server- // answered. The board id in a create response exists nowhere else, and the first save of a new- // draft is exactly the one an edit is most likely to overtake — so dropping it there leaves the- // project pointing at no board until the next reload.+ // A stale snapshot can still receive the draft's only authoritative board id; preserve that create response+ // despite intervening edits.const aggregate = createAggregate();const { persistence } = createPersistence(() => Promise.resolve(null));const first = deferred<WorkbenchSaveResult>();diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.tsindex d803b9702a..66b2b89704 100644--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts@@ -126,8 +126,7 @@ export const createWorkbenchPersistenceRuntime = ({return;}- // Staleness is read before anything is applied, because applying is itself an edit: assigning- // a board dispatches through the reducer and bumps the generation this check compares against.+ // Check staleness before applying board assignment, which itself advances the compared generation.const isStale = isStaleSave(revision, saveGeneration, requireCurrentRevision);// Board identity is a server fact and remains safe to apply when this save is stale.diff --git a/invokeai/frontend/webv2/src/workbench/projectContracts.ts b/invokeai/frontend/webv2/src/workbench/projectContracts.tsindex 78fe45e599..a4dfba0617 100644--- a/invokeai/frontend/webv2/src/workbench/projectContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/projectContracts.ts@@ -33,12 +33,7 @@ export interface Project {projectGraph: ProjectGraphState;widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;widgetRegions: Record<WidgetRegion, WidgetRegionState>;- /**- * Widget instances detached into floating windows. Optional and additive:- * projects persisted before this field existed hydrate with no floating- * windows. A floated instance is removed from its region's instanceIds- * while it floats.- */+ /** Floating instances leave their region's instanceIds; absent in older projects means no floating windows. */floatingWidgets?: Record<WidgetInstanceId, FloatingWidgetState>;widgetGraphs: Partial<Record<WidgetTypeId, GraphContract>>;canvas: CanvasStateContractV3;@@ -128,11 +123,7 @@ export interface UndoRedoEntry {mergedAt?: string;}-/**- * Project-level undo snapshot. Deliberately excludes `canvas`: the canvas- * rendering engine owns its own pixel-patch history, so project undo/redo- * passes the live `project.canvas` through untouched (see `restoreUndoSnapshot`).- */+/** Project undo preserves the live canvas; the engine owns pixel history. */export interface ProjectUndoSnapshot {layout: ProjectLayoutState;invocation: InvocationControllerState;diff --git a/invokeai/frontend/webv2/src/workbench/projectEventContracts.ts b/invokeai/frontend/webv2/src/workbench/projectEventContracts.tsindex 883c3711f8..e0821b74a2 100644--- a/invokeai/frontend/webv2/src/workbench/projectEventContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/projectEventContracts.ts@@ -1,11 +1,6 @@/**- * Project event vocabulary, split out of `projectContracts.ts` as a leaf.- *- * `CanvasProjectMutation` (owned by `canvas-engine/mutationContracts.ts`) carries- * a `ProjectEvent` on its staging commits. Keeping these two types in- * `projectContracts.ts` would force the engine to import a module that imports- * `canvas-engine/api` right back — the edge that closed the 16-module import- * cycle. This module imports nothing, so both sides can depend on it freely.+ * Keep ProjectEvent dependency-free: CanvasProjectMutation consumes it, while projectContracts imports+ * canvas-engine/api.*/export type ProjectEventType =diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts b/invokeai/frontend/webv2/src/workbench/projects/api.test.tsindex 4332013f88..d0a10df4ff 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts@@ -31,12 +31,7 @@ beforeEach(() => {accountLifecycle.activate('project-api-test-user');});-/**- * The caller has already uploaded a board's worth of media by the time this runs, and it deletes- * that media if — and only if — this proves the project does not exist. Getting it wrong one way- * leaves clutter; the other way guts a project that does exist. So absence has to be *proved*, never- * assumed from silence.- */+/** Cleanup requires proven project absence after an ambiguous create. */describe('createProjectSettled', () => {const request = { data: {}, name: 'Imported', project_id: 'project-1' };const post = () => ({@@ -54,11 +49,7 @@ describe('createProjectSettled', () => {expect(transport.apiFetchJson).toHaveBeenCalledTimes(1);});- /**- * The case a `GET` cannot answer. The create may be mid-transaction, so a read of the id returns- * 404 about a project that is moments from existing — and the caller deletes its media. A second- * `POST` cannot commit before the first, so its answer is about a settled database.- */+ /** Settle with a retry write: GET 404 can race the initial create transaction. */it('adopts the project when a retried create finds the first one committed', async () => {transport.apiFetchJson.mockRejectedValueOnce(new TypeError('network error'))diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.ts b/invokeai/frontend/webv2/src/workbench/projects/api.tsindex 6be0f13c3a..b005c6dfa9 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.ts@@ -7,12 +7,7 @@ import {MAX_SUPPORTED_CANVAS_SCHEMA_VERSION,} from '@workbench/canvasSchemaVersion';-/**- * REST surface for server-side project persistence (`/api/v1/projects`) and- * the per-user client-state KV (`/api/v1/client_state`) that holds the small- * account-scoped workbench blob. Both work in single-user mode too — the- * backend scopes them to the system user.- */+/** Project records and client state are scoped to the authenticated account. */const PROJECTS_BASE = '/api/v1/projects';const PROJECT_WRITE_MAX_ATTEMPTS = 9;@@ -22,10 +17,7 @@ const CLIENT_STATE_BASE = '/api/v1/client_state/default';export interface ProjectSummaryDTO {project_id: string;- /**- * The project's private board. Authoritative: the `projectBoardId` in the project document is a- * cache the client overwrites from this on hydration, never the other way round.- */+ /** The server's board ID is authoritative; the document stores only a cache. */board_id: string;name: string;revision: number;@@ -40,10 +32,7 @@ export interface ProjectRecordDTO extends ProjectSummaryDTO {export interface ProjectCreateRequest {project_id?: string;- /**- * An existing unclaimed private board for the new project to adopt, renamed to match. Omit to- * have the server create one. This is what makes the create an import's single commit point.- */+ /** Adopt and rename an unclaimed private board, or omit to create one atomically with the project. */board_id?: string;name: string;data: Record<string, unknown>;@@ -209,12 +198,7 @@ export const deleteProject = async (projectId: string, signal?: AbortSignal): Prawait apiFetch(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}`, { method: 'DELETE', signal });};-/**- * Everything on the project's board that the gallery would show — including results the document- * never references, which is exactly what a project file has to carry to be the whole workspace- * rather than only the canvas. Intermediates and the canvas's private `other` category are- * excluded by the backend.- */+/** Includes unreferenced visible board media; excludes intermediate/other categories. */export const getProjectBoardSnapshot = (projectId: string, signal?: AbortSignal): Promise<ProjectBoardSnapshotDTO> =>apiFetchJson<ProjectBoardSnapshotDTO>(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}/board-snapshot`, {signal,@@ -308,12 +292,7 @@ export const getProjectWriteSizeRefusal = (error: unknown): ProjectWriteSizeRefu}};-/**- * A create that never reached the server, and is therefore safe to compensate for.- *- * Raised by {@link createProjectSettled} in place of the original rejection when it can prove the- * project does not exist. Callers roll back on this and on nothing else.- */+/** Only confirmed project absence permits compensation. */export class ProjectCreateAbsentError extends Error {readonly cause: unknown;@@ -325,20 +304,9 @@ export class ProjectCreateAbsentError extends Error {}/**- * Create a project, resolving the one outcome a bare `POST` cannot report: a create that reached- * the server but whose response did not reach us. Getting that wrong orphans a board's worth of- * already-uploaded media, or *deletes* it out from under a project that does exist.- *- * A read cannot decide it — `GET` returns 404 while the create transaction is still committing,- * exactly the window a dropped connection leaves open. A write can: SQLite has a single writer, so- * a second `POST` cannot commit before the first finishes and its answer is about a settled- * database.- *- * - `201` — the first attempt never landed and this one did.- * - `409` — the retry ran to completion, so the follow-up `GET` races nothing: a record means the- * first create committed and is adopted; a 404 means something else holds the staging board.- * - any other deterministic rejection — the server answered, and answered no.- * - another transport failure — still unknown, and unknown must not authorize deletion.+ * Settle ambiguous creates with a second POST: SQLite serializes writers, while GET 404 can race the initial+ * commit. A 201 succeeds; after 409, GET distinguishes an existing project from a board conflict. Other+ * deterministic rejections prove absence. Transport failure remains unknown and must never authorize deletion.*/export const createProjectSettled = async (request: ProjectCreateRequest,@@ -348,11 +316,7 @@ export const createProjectSettled = async (const body = serializeCreateProjectRequest(request);const writeBudget = createProjectWriteRetryBudget();- /**- * A 409 says the id or the board is spoken for, without saying by whom. Because the server has- * answered, nothing is mid-commit any more and reading the id is decisive: our own committed- * create, or somebody else's board.- */+ /** The settled 409 makes this lookup decisive: an existing project committed; 404 means a board conflict. */const settleConflict = async (conflict: unknown): Promise<ProjectRecordDTO> => {if (projectId === undefined) {throw conflict;@@ -386,8 +350,7 @@ export const createProjectSettled = async (} catch (error) {assertAccountScopeCurrent(owner);- // Without an id of our choosing there is nothing to retry idempotently: a second POST would- // mint a second project rather than collide with the first.+ // The caller must choose the ID so retries are idempotent.if (projectId === undefined || !isIndeterminate(error)) {return classify(error);}@@ -397,8 +360,7 @@ export const createProjectSettled = async (} catch (retryError) {assertAccountScopeCurrent(owner);- // Still no answer. Unknown must not authorize deletion, so the original failure stands and- // the uploads are left where they are: clutter is recoverable, a gutted project is not.+ // An ambiguous retry must retain uploads; unknown never authorizes cleanup.if (isIndeterminate(retryError) || isProjectWriteBusyError(retryError)) {throw error;}diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsxindex 064e3a2a12..b253e0634a 100644--- a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx@@ -43,11 +43,7 @@ const ProjectLibraryRefresh = () => {return null;};-/**- * "Open project…" from the tab bar: the saved projects that are not already- * open as tabs, plus import. Selecting one hydrates its document from the- * library and opens it in place — no navigation, the editor stays mounted.- */+/** Exclude open tabs; hydrate in place to avoid remounting the editor. */export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) => {const projectIds = useWorkbenchSelector((snapshot) => snapshot.projects.map((project) => project.id), areArraysEqual);const { projects } = useWorkbenchCommands();diff --git a/invokeai/frontend/webv2/src/workbench/projects/covers.test.ts b/invokeai/frontend/webv2/src/workbench/projects/covers.test.tsindex 39997173c4..3c3de2f4c9 100644--- a/invokeai/frontend/webv2/src/workbench/projects/covers.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/covers.test.ts@@ -4,11 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type * as coversModule from './covers';-/**- * The cover index: a per-user blob that lets the library grid show thumbnails- * without fetching every project's document. It is an index, not a truth, so- * every failure here has to degrade to "no cover" rather than to an error.- */+/** Cover-index failure degrades to missing thumbnails. */const api = vi.hoisted(() => {const clientState = new Map<string, string>();@@ -102,13 +98,7 @@ describe('loadProjectCovers', () => {});});-/**- * The index is one blob and every write replaces it, so a record made before- * the first read must not reach the KV — it would delete every project's cover- * but its own. Autosave reaches `recordProjectCover` from the editor, which- * loads the index only when the project switcher opens, so this ordering is the- * ordinary one for anyone who reloads straight into a project.- */+/** Do not replace the KV blob before the initial read succeeds. */describe('recordProjectCover before the index has loaded', () => {it('shows the cover immediately without writing over an index it has not read', async () => {api.__clientState.set('webv2:project-covers', '{"other":"b.png"}');@@ -118,8 +108,7 @@ describe('recordProjectCover before the index has loaded', () => {expect(covers.getProjectCoverImageName('p1')).toBe('a.png');expect(api.setClientStateValue).not.toHaveBeenCalled();- // Recording kicks off the read it was waiting for; drain it so the write- // lands inside this test rather than after it.+ // Drain triggered reads and writes before the test ends.await covers.loadProjectCovers();expect(api.setClientStateValue).toHaveBeenCalledTimes(1);diff --git a/invokeai/frontend/webv2/src/workbench/projects/covers.ts b/invokeai/frontend/webv2/src/workbench/projects/covers.tsindex a3239626fa..99c993d04e 100644--- a/invokeai/frontend/webv2/src/workbench/projects/covers.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/covers.ts@@ -11,20 +11,8 @@ import { absolutizeApiUrl } from '@platform/transport/http';import { getClientStateValue, setClientStateValue } from './api';/**- * Which image stands for each project, as an index in the per-user client-state KV.- *- * The document is the source of truth, but the library grid lists projects from `GET /projects`,- * which returns summaries with no document. So the answer is written down once, on save or import.- * Being an index, it is allowed to be stale: a project with no entry shows the folder glyph.- *- * ### The whole index is one value, so a write must not precede a read- *- * The KV holds one blob and `setClientStateValue` replaces it outright, so writing from a store- * that has not loaded would delete every entry but the one being written. Not hypothetical:- * autosave reaches {@link recordProjectCover} from the editor, which loads the index only when the- * switcher or Open dialog opens. Records made before the load wait in {@link pendingCoverNames}.- *- * A read that *fails* is not a read — merging onto a blank answer is the same destructive write.+ * The cover index is nonauthoritative. Load it before replacing the whole blob; failed reads must not unlock+ * writes.*/export const PROJECT_COVERS_KEY = 'webv2:project-covers';@@ -100,8 +88,7 @@ const enqueuePersist = (coverImageNames: Record<string, string>, owner: AccountStry {await setClientStateValue(PROJECT_COVERS_KEY, value, owner.signal);} catch {- // Losing the write costs a glyph until the next save. Keeping the snapshot dirty is what- // lets that save retry the complete blob.+ // Retain dirty cover state after a failed write for retry.return;}@@ -113,10 +100,7 @@ const enqueuePersist = (coverImageNames: Record<string, string>, owner: AccountS});};-/**- * Trim to the cap, oldest first. Insertion order is recency order because- * {@link recordProjectCover} re-inserts what it touches, so the entry being written is never evicted.- */+/** Insertion order records recency because updates reinsert entries. */const boundCovers = (coverImageNames: Record<string, string>): Record<string, string> => {const entries = Object.entries(coverImageNames);@@ -139,8 +123,7 @@ export const loadProjectCovers = (): Promise<void> => {try {raw = await getClientStateValue(PROJECT_COVERS_KEY, owner.signal);} catch {- // Not "no covers yet": a failed read leaves the store unloaded so nothing writes over an- // index we could not see. Pending records wait for the next refresh.+ // Failed reads leave the index unloaded so pending covers cannot overwrite unseen entries.return;}@@ -199,8 +182,7 @@ export const recordProjectCover = (const next = { ...coverImageNames };- // Deleted before it is set, so the project moves to the end and survives the insertion-order- // eviction below.+ // Reinsert updated covers at the newest eviction position.delete next[projectId];if (coverImageName !== null) {@@ -212,8 +194,7 @@ export const recordProjectCover = (store.setSnapshot({ coverImageNames: bounded, isDirty: true, isLoaded });if (!isLoaded) {- // The grid can show this immediately, but the KV cannot receive it until we- // know what else is in there. See the module docblock.+ // Display local covers immediately; durable writes must await index loading.pendingCoverNames.set(projectId, coverImageName);void loadProjectCovers();diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.tsindex 5c43625935..976b6cfc64 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts@@ -66,13 +66,7 @@ describe('writeArchive / readArchive', () => {});});- /**- * `unzip` reports the damage this version happens to produce through its callback, which is- * wrapped. It is not contractually bound to: a throw out of its own walk would bypass that wrap- * and reach the caller as an fflate message, so the two ways a file can be unreadable would stop- * looking the same from outside. Forced rather than provoked, because provoking it means relying- * on which corruptions a given fflate release chooses to raise rather than report.- */+ /** Force the synchronous unzip failure to cover both error channels deterministically. */it('reports damage fflate raises synchronously as not a project too', async () => {vi.resetModules();vi.doMock('fflate', () => ({@@ -85,8 +79,7 @@ describe('writeArchive / readArchive', () => {try {const { readArchive: readWithThrowingUnzip } = await import('./archive');- // Matched by shape, not by class: resetting the registry gives this import its own copy of- // `./format`, so `InvkFormatError` here is a different constructor than the one above.+ // Match errors structurally: reset module instances have different constructors.await expect(readWithThrowingUnzip(new Uint8Array([1, 2, 3]))).rejects.toMatchObject({name: 'InvkFormatError',reason: 'not-a-project',@@ -124,13 +117,7 @@ describe('writeArchive / readArchive', () => {});});-/**- * The point of this guard is *when* it fires. `unzip` is fully buffered, so a- * total measured over its result describes a bomb that has already landed; the- * budget is what fflate consults per entry before inflating it. Testing it- * directly is how the sizes involved stay expressible — proving the same thing- * through `readArchive` would mean actually building a multi-gigabyte archive.- */+/** Exercise the pre-inflation budget without allocating multi-gigabyte fixtures. */describe('createExpansionBudget', () => {const entry = (name: string, originalSize: number, size = originalSize, compression = 8) => ({compression,diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.tsindex bf1790a472..bd92a5e98c 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts@@ -1,30 +1,11 @@import { INVK_MIME_TYPE, InvkFormatError } from './format';/**- * The ZIP seam. The only module that knows `.invk` is a ZIP, and the only one that imports fflate —- * lazily, so a route that never opens a project file never pays for it.- *- * JSON entries are deflated, image entries stored: bitmaps are already PNG or WEBP, while the- * document is repetitive JSON that compresses tenfold.- *- * ### Why the read guard lives in fflate's filter- *- * `unzip` is fully buffered — by the time it returns, every entry is already inflated in memory, so- * a total measured there is a postmortem rather than a guard. The filter is consulted per entry- * *before* inflation, using the central directory's declared size, which is the only place a- * ceiling can actually stop a zip bomb.- *- * fflate allocates deflated entries from `originalSize` but stored entries from `size`. Stored- * entries must declare those identically, so the filter rejects a mismatch before the copy.+ * Lazy ZIP boundary: deflate JSON and store compressed media. Enforce declared-size budgets in the filter before+ * buffered inflation. Stored entries require size === originalSize because fflate allocates them from size.*/-/**- * Ceiling for a single archive, in either direction.- *- * Deliberately well under 4 GiB, where ZIP32's 32-bit sizes stop describing the file: fflate reads- * zip64 records but `zip()` never emits them, so an archive at that boundary would be written- * structurally invalid rather than rejected.- */+/** Stay below ZIP32 overflow; the writer does not emit zip64. */export const INVK_MAX_ARCHIVE_BYTES = 2 * 1024 * 1024 * 1024;/** Ceiling on entry count, which bounds the cost of building the entry map. */@@ -100,9 +81,8 @@ export interface InvkExpansionBudget {}/**- * The read-side ceiling, consulted during the walk. The refusal is *returned* rather than thrown- * from `accept`: a throw inside fflate's walk unwinds through its decoder and arrives as a decode- * failure, so the caller would be told the file was not a project when it was merely too big.+ * Return size refusals instead of throwing inside the filter, which would misclassify oversized archives as+ * corrupt.*/export const createExpansionBudget = (): InvkExpansionBudget => {let entryCount = 0;@@ -111,8 +91,7 @@ export const createExpansionBudget = (): InvkExpansionBudget => {return {accept: (file) => {- // Directory records carry nothing and only inflate the count toward the- // guard.+ // Empty directory records do not consume the entry budget.if (file.name.endsWith('/')) {return false;}@@ -137,12 +116,7 @@ export const createExpansionBudget = (): InvkExpansionBudget => {};};-/**- * Expand a ZIP into its entries. Anything that is not a readable ZIP surfaces as- * `not-a-project` rather than an fflate error, because from the caller's side- * "you picked the wrong file" and "this ZIP has a bad central directory" are the- * same event.- */+/** Corrupt and non-ZIP inputs share the same typed refusal. */export const readArchive = async (bytes: Uint8Array): Promise<Map<string, Uint8Array>> => {if (bytes.byteLength > INVK_MAX_ARCHIVE_BYTES) {throw new InvkFormatError('too-large', `Project archive is ${bytes.byteLength} bytes.`);@@ -151,10 +125,7 @@ export const readArchive = async (bytes: Uint8Array): Promise<Map<string, Uint8Aconst { unzip } = await import('fflate');const budget = createExpansionBudget();const expanded = await new Promise<Record<string, Uint8Array>>((resolve, reject) => {- // `unzip` reports most damage through the callback, but raises some of it — a central directory- // it cannot walk at all — synchronously. That throw rejects this promise with fflate's own error- // rather than the one this function promises to raise, so it is caught here too. Otherwise the- // guarantee holds for a truncated file and quietly fails for a corrupt one.+ // Normalize both synchronous throws and asynchronous unzip errors.try {unzip(bytes, { filter: budget.accept }, (error, data) => {if (error) {diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.tsindex bdb806b6e6..a845c9272c 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts@@ -68,8 +68,7 @@ describe('import rollback transport', () => {});it('sends authoritative image and video identities to their batch-delete routes', async () => {- // Imported at the top rather than probed for: a `toBeTypeOf` guard with an early return passes- // silently if the export ever disappears, which is the one thing this test exists to catch.+ // Import and assert unconditionally so a missing export cannot skip coverage.const signal = new AbortController().signal;mocks.apiFetchJson.mockResolvedValue({});@@ -134,10 +133,7 @@ describe('board media transport', () => {expect(Object.fromEntries(uploadQuery())).toEqual(query);});- /**- * A document reference is not gallery content: it goes up unboarded, under the canvas's private- * category. The two upload paths must not drift into each other.- */+ /** Document-reference uploads remain private and unboarded. */it('keeps document-reference uploads unboarded and private', async () => {mocks.apiFetch.mockResolvedValue(new Response(JSON.stringify({ height: 1, image_name: 'fresh.png', width: 1 }), { status: 201 })diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.tsindex bc9c37f1e7..18956411f9 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts@@ -12,18 +12,7 @@ import type { InvkMediaCategory } from './board';import { INVK_MAX_ARCHIVE_BYTES } from './archive';import { InvkFormatError } from './format';-/**- * The asset half of a project file: pulling referenced bytes off the server on the way out, and- * putting the missing ones back on the way in.- *- * Not reached through `canvas-operations/backend/canvasImages.ts`, which does the same upload:- * importing is a Launchpad action on a route that never loads the editor, and it must not pull the- * canvas graph behind it.- *- * Document references upload under category `'other'` — the canvas's private category, in neither- * `IMAGE_CATEGORIES` nor `ASSETS_CATEGORIES` — because pixels a document points at are the- * document, not gallery content. Board items upload under the category the archive recorded.- */+/** Launchpad-safe transport. Document references upload privately; board items retain their archived categories. *//** One budget for the whole transfer: a per-phase limit would multiply what it exists to bound. */export const INVK_TRANSFER_CONCURRENCY = 5;@@ -35,13 +24,7 @@ const VIDEOS_BASE = '/api/v1/videos';/** The backend truncates board names at 300 characters; doing it here keeps the name we chose. */const MAX_BOARD_NAME_LENGTH = 300;-/**- * Whether a failure means "this work is over" rather than "this one asset could not be served".- *- * An aborted signal makes *every* asset unservable, and a skip-everything export writes an empty- * archive and hands it over as a success. Distinguishable only where the request fails — by the- * time the archive is packed the two look identical.- */+/** Cancellation aborts the operation rather than reporting remaining assets as missing. */export const isRequestCancellation = (error: unknown): boolean =>error instanceof HttpRequestIdentityExpiredError || (error instanceof Error && error.name === 'AbortError');@@ -120,10 +103,7 @@ const getDeclaredContentLength = (response: Response): number | null => {return Number.isSafeInteger(byteLength) ? byteLength : Number.POSITIVE_INFINITY;};-/**- * A single export-scoped reader: every response streams through one fixed byte budget, so neither a- * hostile response nor many small ones can materialize an oversized project in memory.- */+/** Share one streaming byte budget across all export responses. */export const createAssetResponseReader = (): AssetResponseReader => {type AssetStreamReader = ReadableStreamDefaultReader<Uint8Array>;@@ -276,8 +256,7 @@ export const findExistingImageNames = async (imageNames: readonly string[],signal?: AbortSignal): Promise<Set<string>> => {- // Through the same pool as everything else. Splitting the names was meant to stop one slow- // lookup stalling the check, which a sequential loop gives straight back.+ // Use the shared bounded pool for existence checks; do not serialize chunks.const found = await mapWithConcurrency(toBatches(imageNames, EXISTENCE_BATCH_SIZE),INVK_TRANSFER_CONCURRENCY,@@ -293,10 +272,7 @@ export const findExistingImageNames = async (return new Set(found.flat().map((dto) => dto.image_name));};-/**- * Which of `videoNames` the server already has. No bulk equivalent of `images_by_names` exists for- * videos, so this asks per name; a 404 is the answer, not an error.- */+/** Videos need individual existence requests because no bulk endpoint exists; 404 means absent. */export const findExistingVideoNames = async (videoNames: readonly string[],signal?: AbortSignal@@ -308,8 +284,7 @@ export const findExistingVideoNames = async (const response = await apiFetchRaw(`${VIDEOS_BASE}/i/${encodeURIComponent(videoName)}`, { signal });if (response.ok) {- // The DTO is not wanted, only its existence — but an unread body holds its connection open- // until it is collected, and this runs once per referenced video.+ // Discard unused response bodies to release connections.await discardBody(response);return videoName;}@@ -328,10 +303,7 @@ export const findExistingVideoNames = async (return new Set(found.filter((videoName): videoName is string => videoName !== null));};-/**- * Bytes for one asset, or `null` when the server will not serve it. A missing asset is not an export- * failure: a project that exports every layer but one is far more use than one that refuses.- */+/** Null means unavailable; exports may complete with missing assets. */const fetchAsset = async (url: string,signal: AbortSignal | undefined,@@ -403,13 +375,7 @@ export const createAssetExportTransport = () => {};};-/**- * Put bytes on the server. The returned name is authoritative and frequently differs from the one- * asked for — the server names media itself — which is why every import ends with a remapping pass.- *- * A board upload's name is a genuinely new identity, always — see the `board_images` rule in- * `transfer.ts`.- */+/** Use server-returned names. Board uploads must always receive fresh identities. */const uploadMedia = async <T>(base: string,query: Record<string, string>,@@ -583,10 +549,7 @@ const copyMediaToBoard = async <Entry>({return result;};-/**- * Copy media onto a board without the bytes leaving the server. Carries category, origin and- * embedded metadata; starring is not part of a copy, so callers star afterwards.- */+/** Server-side copies preserve metadata, category, and origin; starring is separate. */export const copyImagesToBoard = (imageNames: readonly string[],boardId: string,@@ -621,10 +584,7 @@ export interface BulkStarResult {failed: string[];}-/**- * Failures are derived from the success list, not read from `failed_*`: only the video endpoint- * reports failures, and a name it silently skipped appears in neither list.- */+/** Derive failures from missing successes because endpoint failure lists are incomplete. */const toBulkStarResult = (requested: readonly string[], starred: readonly string[]): BulkStarResult => {const succeeded = new Set(starred);@@ -674,12 +634,7 @@ export const starVideos = async (videoNames: readonly string[], signal?: AbortSireturn { failed };};-/**- * An unclaimed private board for a restore to upload into, which project creation then claims.- *- * This is what makes the create the commit point: the media is in place before the project exists,- * so the create either claims the board and its contents or leaves nothing a person can see.- */+/** Atomically claiming the staging board is the project-create commit point. */export const createStagingBoard = async (boardName: string, signal?: AbortSignal): Promise<string> => {const query = new URLSearchParams({ board_name: boardName.slice(0, MAX_BOARD_NAME_LENGTH) });const dto = await apiFetchJson<{ board_id: string }>(`${BOARDS_BASE}/?${query.toString()}`, {@@ -771,10 +726,7 @@ const VIDEO_MIME_BY_EXTENSION: Readonly<Record<string, string>> = {webm: 'video/webm',};-/**- * Best guess at a bundled entry's MIME type. The fallback is per kind because the endpoint checks- * it: an unknown video extension falling back to `image/png` would be refused by `/videos/upload`.- */+/** Use a kind-specific MIME fallback so unknown video extensions remain video uploads. */export const mimeForEntryName = (entryName: string, kind: 'image' | 'video' = 'image'): string => {const extension = entryName.split('.').pop()?.toLowerCase() ?? '';diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/board.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/board.test.tsindex c7789711ab..7d53ecc0b4 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/board.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/board.test.ts@@ -3,11 +3,7 @@ import { describe, expect, it } from 'vitest';import { buildInvkBoardSnapshot, parseInvkBoardSnapshot } from './board';import { InvkFormatError } from './format';-/**- * `board.json` is the only part of an archive that tells the reader what the project *had*, as- * opposed to what it draws with. A reader that half-trusted it would restore the wrong thing- * quietly, so everything here is a structural refusal rather than a warning.- */+/** Malformed board enumeration must fail before restore creates resources. */const item = (overrides: Partial<Parameters<typeof buildInvkBoardSnapshot>[0][number]> = {}) => ({category: 'general' as const,diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/board.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/board.tsindex 2be6664d65..b7945995e1 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/board.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/board.ts@@ -4,19 +4,8 @@ import { INVK_MAX_ENTRIES } from './archive';import { InvkFormatError } from './format';/**- * `board.json`: what was on the project's board when the archive was written. A document names only- * the media it draws with, so everything else the project produced appears nowhere in it — this- * entry is the difference between carrying a project's canvas and carrying its workspace.- *- * ```json- * { "version": 1, "items": [{ "category": "general", "kind": "image", "name": "…", "starred": false }] }- * ```- *- * The version is the *file's*, not the API's: an archive format pinned to the wire format would- * have to move whenever it did, and vice versa.- *- * Validation is strict and structural — a duplicate `(kind, name)` or a non-basename name means the- * file is malformed and must be refused before anything is uploaded, not reported alongside it.+ * The independently versioned board entry includes unreferenced media. Validate it strictly before uploading+ * anything.*/export type InvkMediaKind = 'image' | 'video';@@ -34,11 +23,7 @@ export interface InvkBoardSnapshot {items: InvkBoardItem[];}-/**- * A media name must be exactly what the server would name a file: no separators, no traversal, no- * NUL. The archive stores these under `images/` and `videos/`, so anything else would either- * escape that prefix or fail to round-trip through the ZIP.- */+/** Names must be basenames without separators, traversal, or NUL to round-trip safely as archive paths. */const zMediaName = z.string().min(1)@@ -56,25 +41,18 @@ const zBoardItem = z.object({const zBoardSnapshot = z.object({- // Bounded by the same ceiling as archive entries: every item is at most one entry, so a list- // that could not be packed cannot be honest either.+ // Board item count cannot exceed the archive entry capacity.items: z.array(zBoardItem).max(INVK_MAX_ENTRIES),version: z.literal(1),})- // Unknown keys are refused rather than ignored: this file is small, entirely generated, and a- // reader silently dropping a field a later version added would restore the wrong thing quietly.+ // Reject unknown fields rather than silently discard future semantics..strict();/** Sort by kind then name. Images and videos are separate namespaces, so one name can be both. */const compareItems = (left: InvkBoardItem, right: InvkBoardItem): number =>left.kind.localeCompare(right.kind) || left.name.localeCompare(right.name);-/**- * Parse and canonicalize `board.json`.- *- * Input order is free — the server's ordering is its own business — but the result is sorted, so- * every consumer sees one order and tests can compare whole structures.- */+/** Accept arbitrary input order; emit deterministic order. */export const parseInvkBoardSnapshot = (data: unknown): InvkBoardSnapshot => {const parsed = zBoardSnapshot.safeParse(data);diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.tsindex 944fe56c22..c2a833a2b8 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts@@ -11,15 +11,11 @@ import type * as assetTransportModule from './assetTransport';import type * as duplicateProjectModule from './duplicateProject';/**- * Duplication end to end, with the copy endpoints and the project API replaced.- *- * The rules it has to keep are import's rules, because it is import's engine: board media takes new- * identities, the document follows them, a failed copy cannot leave a reference pointing at the- * original's image, and a failure before the create undoes exactly what it made.+ * Verify fresh board identities, remapped references, isolated copy failures, and exact rollback through mocked+ * transport.*/-// `createProjectSettled` is the seam, not `createProject`: it is what decides whether a create that-// went unanswered actually landed, and therefore whether the copies below may be deleted.+// Mock settled creation because its verdict determines whether rollback is safe.const api = vi.hoisted(() => ({createProjectSettled: vi.fn(),getProject: vi.fn(),@@ -47,9 +43,7 @@ vi.mock('@workbench/projects/api', async (importOriginal) => ({...(await importOriginal<typeof apiModule>()),...api,}));-// Partial, so the module's constants and pure predicates stay real — a stub of-// `isRequestCancellation` would let the tests agree with a duplication that mistook a-// cancellation for a board's worth of individually failed copies.+// Preserve real cancellation predicates in partial mocks.vi.mock('./assetTransport', async (importOriginal) => ({...(await importOriginal<typeof assetTransportModule>()),...transport,@@ -119,8 +113,6 @@ const restoredLayerName = (): string =>beforeEach(async () => {vi.resetModules();- // Restores the hoisted `vi.fn(impl)` defaults; only `createProjectSettled`, which has none, is- // re-established below.vi.resetAllMocks();const account = await import('@platform/state/accountLifecycle');@@ -128,8 +120,6 @@ beforeEach(async () => {account.accountLifecycle.activate('duplicate-user');owner = account.captureAccountScope();- // These two are hoisted as bare `vi.fn()` with no implementation, so unlike the rest they are- // not restored by the reset above.transport.copyImagesToBoard.mockImplementation((names: readonly string[]) => Promise.resolve(copiesOf(names)));transport.copyVideosToBoard.mockImplementation((names: readonly string[]) => Promise.resolve(copiesOf(names)));api.createProjectSettled.mockImplementation(@@ -224,10 +214,7 @@ describe('duplicateProjectRecord', () => {expect(transport.copyImagesToBoard).toHaveBeenCalledWith([], 'staging-board', owner.signal);});- /**- * A reference to media outside the project's own board is a pointer, and both projects live on- * this one server, so the copy simply keeps pointing at it.- */+ /** Same-server duplicates share external references. */it('reuses a document reference the board does not own, copying nothing', async () => {const record = sourceRecord({ futureImageInput: { image_name: 'external.png' } });@@ -237,10 +224,7 @@ describe('duplicateProjectRecord', () => {expect((createdData().futureImageInput as { image_name: string }).image_name).toBe('external.png');});- /**- * The failure that must not bind to a stranger: on this server the original's `shared.png` is- * right there, and falling back to it would leave the copy quietly sharing the original's image.- */+ /** A failed copy must never fall back to source-owned media. */it('forces a reference dangling when its board copy fails', async () => {transport.copyImagesToBoard.mockResolvedValue({ copied: [], failed: ['shared.png'] });@@ -302,12 +286,7 @@ describe('duplicateProjectRecord', () => {expect(transport.deleteStagingBoard).toHaveBeenCalledWith('staging-board', owner.signal);});- /**- * The outcome that used to be decided by a `GET`, and decided wrongly: the read returns 404 while- * the create transaction is still committing, so the copies were deleted out from under a project- * that then appeared — with every reference in its document dangling. An unproven absence must- * leave the media alone.- */+ /** Retain media for unproven create outcomes; GET 404 can race commit. */it('leaves the copies alone when a rejected create may already have landed', async () => {const failure = new Error('connection ended after create');diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.tsindex 1968d0dccd..ae15e0a67f 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts@@ -30,16 +30,7 @@ import {} from './restoreProjectMedia';import { toMediaRefs } from './transfer';-/**- * Duplicating a project: the same restore as import, with the bytes taking a shortcut.- *- * A copy must own its media outright (see `transfer.ts`), which makes this import's problem. Only- * materialization differs, and it differs because both projects live on this one server: the copy- * endpoints work in place, so a 2 GiB board costs no traffic instead of 4 GiB and 2N requests.- *- * Document-only references already exist here and are not the project's own board content, so the- * shared engine's existence check finds them all and nothing is uploaded.- */+/** Copy board media server-side and reuse external reference identities. */export interface DuplicateProjectInput {/** The board's visible contents, enumerated for the source project. */@@ -64,12 +55,8 @@ export interface DuplicateProjectResult extends ProjectTransferIssues {}/**- * The duplication half of the materialization seam: one bounded request sequence per kind, pixels- * staying put. Progress moves per item once the sequence answers — there is no finer event.- *- * A batch that does not answer at all is every name in it failing, not the duplication failing:- * the route reports per-item failures so one bad source cannot cost the batch, and letting a- * transport error do what the route refuses would give that away at the last step.+ * Report each batch item's outcome and progress; cancellation aborts the operation rather than becoming a batch+ * failure.*/export const createCopyMediaMaterializer = (deps: { copyImages?: typeof copyImagesToBoard; copyVideos?: typeof copyVideosToBoard; signal?: AbortSignal } = {}@@ -111,13 +98,7 @@ export const createCopyMediaMaterializer = (};};-/**- * Copy a project and everything its board holds, under identities the copy owns.- *- * The commit point is the same as an import's: the media is materialized onto an unclaimed staging- * board, and creating the project claims it. A failure before that deletes exactly what this- * duplication made and leaves the original untouched.- */+/** Project creation commits the staging board; precommit rollback deletes only ledger-owned resources. */export const duplicateProjectRecord = async (input: DuplicateProjectInput,deps: DuplicateProjectDeps = {}@@ -128,8 +109,7 @@ export const duplicateProjectRecord = async (assertAccountScopeCurrent(owner);- // Canonicalized through the reducer with the new identity, exactly as an import is: the copy is a- // new project, not a second pointer at the original's board and gallery selection.+ // Canonicalize with a fresh project identity and reset source board/selection state.const { deserializeProjectDocument } = await import('@workbench/projects/syncedPersistence');assertAccountScopeCurrent(owner);@@ -161,8 +141,7 @@ export const duplicateProjectRecord = async ({boardId: stagingBoardId,boardItems,- // Nothing is bundled: every byte this project needs is already on this server, so a- // reference the copy cannot resolve is one the original could not resolve either.+ // Same-server duplication needs no bundled bytes and inherits unresolved external references.coverBytes: null,coverSourceImageName: selectCoverImageName(canonicalDocument),documentRefs: toMediaRefs(collectLiveAssetRefs(canonicalDocument)),@@ -170,9 +149,7 @@ export const duplicateProjectRecord = async (projectId: id,},{- // Both projects live on this server, so every document-only reference resolves here by- // definition — the check would ask the server whether it has media it just told us about.- // For videos that is one request per referenced video, against a certain answer.+ // Reuse document-only names without existence probes; references may already be dangling.findExistingImageNames: (names) => Promise.resolve(new Set(names)),findExistingVideoNames: (names) => Promise.resolve(new Set(names)),materializeBoardMedia: createCopyMediaMaterializer({diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.tsindex 43e49ec5b9..1265542204 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts@@ -64,11 +64,7 @@ describe('planInvkExport', () => {expect(planInvkExport(planInput).coverImageName).toBe('live-a.png');});- /**- * The selection was already excluded from bundling; this is the other half —- * it must not reach the archive at all, or the imported project opens- * pointing at images the receiving server has never had.- */+ /** Strip selection references as well as excluding their bytes. */it('writes a document carrying no gallery selection', () => {const plan = planInvkExport({...planInput,@@ -190,8 +186,7 @@ describe('executeInvkExport', () => {const [blob] = download.mock.calls[0]! as [Blob];const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));- // `board.json` is written even for a project with no board contents: its absence would be- // indistinguishable from a v2 archive that never knew about boards.+ // An explicit empty board entry differs from a legacy archive with no board entry.expect([...entries.keys()].sort()).toEqual(['board.json', 'manifest.json', 'project.json']);expect(JSON.parse(readEntryText(entries.get(INVK_MANIFEST_ENTRY)!)).cover).toBeUndefined();});@@ -259,15 +254,7 @@ describe('executeInvkExport', () => {});});- /**- * A cancelled export must not look like a successful one. Every fetch fails- * when the signal aborts, so treating those as "the server would not serve- * it" would pack an archive holding nothing and download it.- */- /**- * Cancellation is the one failure that is not a skip, wherever it lands: skipping every asset- * would pack an archive of nothing and hand it over as a finished download.- */+ /** Aborted fetches must fail export rather than produce an empty successful archive. */it.each([['the fetches themselves abort',@@ -359,8 +346,7 @@ describe('executeInvkExport', () => {};const secondBodyCancel = vi.fn(() => Promise.resolve());const secondGetReader = vi.fn(() => {- // With one budget per request, let the first response finish so the- // broken export resolves instead of hanging in this regression test.+ // Complete the first response so a per-request budget bug fails instead of hanging.settleFirstRead({ done: true, value: undefined });return secondReader;@@ -412,10 +398,7 @@ describe('executeInvkExport', () => {});});-/**- * Version 3's whole point: a project's board is part of the project. A result generated but never- * placed on canvas is named nowhere in the document, so without `board.json` it simply vanishes.- */+/** board.json carries generated media absent from document references in the v2 archive. */describe('board membership', () => {const bytesFor = (name: string) => new Uint8Array([...name].map((character) => character.codePointAt(0)!));const boardItem = (name: string, overrides: Record<string, unknown> = {}) => ({diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.tsindex 048122e6d3..27e29b80fb 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts@@ -32,16 +32,7 @@ import {import { buildInvkManifest, toInvkFileName } from './manifest';import { createTransferIssueLog, planMediaTransfer, toMediaRefs } from './transfer';-/**- * Writing an `.invk`, split into a pure planner and an impure executor, as- * `canvas-engine/export/psdExport.ts` splits PSD export. {@link planInvkExport} decides what the- * archive contains from the document alone, so that decision is a node test.- *- * An unservable image is logged and skipped, never fatal. Cancellation is the one failure that is- * *not* a skip: it makes every asset unservable at once, and skipping all of them would pack an- * archive of nothing and hand it over as a finished download. The signal is checked once more- * before the archive is written.- */+/** Skip unavailable assets, but abort on cancellation before packing. */export interface InvkExportPlan {/** The board's contents exactly as they will be written to `board.json`. */@@ -65,10 +56,7 @@ export interface InvkExportPlan {transferItems: InvkTransferItem[];}-/**- * Fixed entries every archive carries: manifest, document, board. The cover is counted separately- * because it is optional.- */+/** Budget fixed entries separately from the optional cover. */const FIXED_ENTRY_COUNT = 3;export const planInvkExport = (input: {@@ -82,16 +70,13 @@ export const planInvkExport = (input: {}): InvkExportPlan => {const sourceProjectId = typeof input.projectDocument.id === 'string' ? input.projectDocument.id : undefined;- // Installation state is dropped here rather than left to the collector's skip list: not bundling- // a reference does not stop it travelling, it only stops it arriving with pixels. The planner is- // where "what belongs in a project file" is decided, so it is where the answer is applied.+ // Strip installation state during planning; excluding its bytes alone leaves dangling references.const projectDocument = stripInstallationState(input.projectDocument);const boardSnapshot = buildInvkBoardSnapshot(input.boardItems);const transferItems = planMediaTransfer(boardSnapshot.items, toMediaRefs(collectLiveAssetRefs(projectDocument)));const fonts = collectFontDependencies(projectDocument);- // Refused before a single byte is fetched. An archive that cannot be packed is not worth the- // hundreds of round trips it would take to discover that at the end.+ // Check the archive budget before downloading assets.const worstCaseEntries = FIXED_ENTRY_COUNT + transferItems.length + (input.includeFonts ? fonts.length : 0) + 1;if (worstCaseEntries > INVK_MAX_ENTRIES) {@@ -101,8 +86,7 @@ export const planInvkExport = (input: {return {boardSnapshot,coverImageName: selectCoverImageName(projectDocument),- // Compact rather than indented: the document is machine-read, and the two- // bytes per line would be the largest entry in the archive before deflate.+ // Serialize compactly to limit the uncompressed document size.documentJson: JSON.stringify(projectDocument),fileName: toInvkFileName(input.name),fonts,@@ -192,9 +176,7 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDeplan.coverImageName === null ? null : await skipUnservable(() => readThumbnail(plan.coverImageName!, deps.signal));const coverEntryName = cover === null ? undefined : `cover.${coverExtensionForMime(cover.contentType)}`;- // One queue over both kinds and both roles: an item that is on the board *and* referenced by the- // document is one fetch, not two. The concurrency limit exists to be kind to the backend, and it- // would not be if images and videos each got their own.+ // Share one deduplicated queue and concurrency budget across media kinds and roles.const assets = plan.transferItems;await mapWithConcurrency(assets, INVK_TRANSFER_CONCURRENCY, async (item) => {@@ -207,8 +189,7 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDedeps.onProgress?.({ completed, phase: 'bundling', total });if (bytes === null) {- // Reported against every role it filled: the same failure costs a board result and a canvas- // layer, and the person holding the file needs to know which.+ // Report loss for each affected board/document role.if (item.isBoardItem) {issues.addBoardItemIssue(item, 'fetch-failed');}@@ -231,9 +212,7 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDeentries.set(`${INVK_VIDEOS_PREFIX}${name}`, binaryEntry(bytes));});- // The last fetch may have completed just as the export stopped being wanted;- // no fetch would have rejected in that window, and packing is the expensive- // step that precedes handing a file to the browser.+ // Check cancellation again before expensive packing.deps.signal?.throwIfAborted();deps.onProgress?.({ completed, phase: 'packing', total });@@ -247,10 +226,7 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDe// The manifest is the one entry a person may open by hand, so it is indented.entries.set(INVK_MANIFEST_ENTRY, textEntry(JSON.stringify(manifest, null, 2)));entries.set(INVK_DOCUMENT_ENTRY, textEntry(plan.documentJson));- // Written even when empty. "This project's board held nothing" is a fact the reader needs; its- // absence would be indistinguishable from a v2 archive that never knew about boards. The- // descriptor is kept for an item whose bytes could not be fetched, so the loss is reported on- // import rather than silently forgotten here.+ // Write an explicit empty board entry and retain missing-byte descriptors for import reporting.entries.set(INVK_BOARD_ENTRY, textEntry(JSON.stringify(plan.boardSnapshot)));if (cover !== null && coverEntryName !== undefined) {diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/format.tsindex 709d1f0e0e..851c9a38e3 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts@@ -2,22 +2,12 @@ import type { RefusedWorkbenchProject } from '@workbench/projectContracts';import { MIN_SUPPORTED_CANVAS_SCHEMA_VERSION } from '@workbench/canvasSchemaVersion';-/**- * What an `.invk` is called and how reading one can fail.- *- * Split from `manifest.ts`, which owns the zod schemas, because these are needed *eagerly* — the- * picker names the extension and every call site translates the error's reason. That is what keeps- * zod and the ZIP codec behind the lazy import.- */+/** Keep format/error constants eager and zod/ZIP dependencies lazy. */export const INVK_EXTENSION = '.invk';export const INVK_MIME_TYPE = 'application/zip';-/**- * Workbench projects are version 2; version 1 is the previous frontend's canvas project, refused by- * name. Board membership did not bump this — webv2 has not shipped, so no v2 archive predating- * `board.json` exists outside dev builds, and an archive without the entry names no board.- */+/** Version 2 is supported. Version 1 receives a named refusal; board.json is optional in v2. */export const INVK_VERSION = 2;/** Fixed entry paths. `cover` varies by image format and is named in the manifest. */@@ -27,12 +17,7 @@ export const INVK_DOCUMENT_ENTRY = 'project.json';/** The project board's contents; see `board.ts` for why a reader cannot infer them. */export const INVK_BOARD_ENTRY = 'board.json';-/**- * Filed by kind, not pooled: import must know which namespace an entry belongs to, and a folder- * states it where a shared one would leave it to a file extension. `images/` is byte-identical to- * the legacy v1 container. `videos/` needed no version bump — `readInvkArchive` ignores entries it- * does not recognize, so an older reader just leaves those references dangling.- */+/** Media uses kind-specific folders; readers tolerate unknown archive entries. */export const INVK_IMAGES_PREFIX = 'images/';export const INVK_VIDEOS_PREFIX = 'videos/';@@ -55,10 +40,7 @@ export type InvkFormatReason =/** The file is larger than the archive budget, or expands past it. */| 'too-large';-/**- * Every way reading an `.invk` can fail, as a value rather than a message. Call- * sites map `reason` to a translated string; nothing user-facing is built here.- */+/** Callers localize typed failure reasons. */export class InvkFormatError extends Error {readonly reason: InvkFormatReason;diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.tsindex 77bf991357..f660fd092a 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts@@ -83,11 +83,7 @@ describe('readInvkArchive', () => {expect(contents.cover).toBeNull();});- /**- * "This file names no board" and "this project's board was empty" are different answers, and the- * restore treats them differently — only the first may have an empty board invented for it. An- * archive with no `board.json` is one a build from before project boards wrote, not a broken one.- */+ /** Missing board entries retain legacy semantics; explicit empty entries describe an empty board. */it('reads an archive with no board enumeration as naming no board', async () => {const contents = await readInvkArchive(await validArchive());@@ -264,10 +260,7 @@ describe('restoreArchiveMedia', () => {...overrides,});- /**- * The overlap case: `a.png` is both on the board and drawn by the canvas. It travels once, as- * board media, and the layer follows it to the copy.- */+ /** Transfer media shared by board and document once, remapping the document to the copy. */it('restores an overlapping item once and points the document at the copy', async () => {const archive = await readInvkArchive(await boardArchive());const ledger = createRestoredMediaLedger('staging');@@ -357,8 +350,7 @@ describe('restoreArchiveMedia', () => {restoreDeps({ uploadBoardVideo }));- // `image/png` here would be announced to the video endpoint as an image and refused before the- // bytes were read.+ // Video MIME fallbacks must pass upload type validation.expect(uploadBoardVideo).toHaveBeenCalledWith(new Uint8Array([7]), 'clip.unknown', {boardId: 'staging',category: 'general',diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.tsindex f3a038100b..43948220b3 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts@@ -32,14 +32,7 @@ import { type InvkManifest, parseInvkManifest } from './manifest';import { restoreProjectMedia } from './restoreProjectMedia';import { toMediaRefs } from './transfer';-/**- * Reading an `.invk` back, in two steps a caller can put a decision between.- *- * {@link readInvkArchive} is pure inspection — no network, no mutation — so everything structural- * fails before a board or a single uploaded image exists. {@link restoreArchiveMedia} is the part- * with consequences. Neither touches the document: the caller applies the returned mapping,- * because the caller is also the one assigning the new project id.- */+/** Inspect before creating resources; callers own document remapping and fresh project identity. */export interface InvkArchiveContents {/**@@ -74,10 +67,7 @@ const parseDocumentEntry = (bytes: Uint8Array): Record<string, unknown> => {return parsed as Record<string, unknown>;};-/**- * The board enumeration, or `null` when the archive carries none. Absent is valid; *malformed* is- * not, and must fail before anything is created — half an enumeration is not a board.- */+/** An absent board entry is valid; a malformed one must fail before mutations. */const parseBoardEntry = (entries: ReadonlyMap<string, Uint8Array>): InvkBoardSnapshot | null => {const entry = entries.get(INVK_BOARD_ENTRY);@@ -96,11 +86,7 @@ const parseBoardEntry = (entries: ReadonlyMap<string, Uint8Array>): InvkBoardSna}};-/**- * The part of `images/<name>` that is a name, or `null` otherwise. A ZIP path is attacker-controlled:- * `images/../../x.png` would let an entry masquerade as media the board enumeration asks for by- * name. Server media names never contain a separator, so the check costs nothing legitimate.- */+/** Reject path separators so malicious ZIP paths cannot impersonate board media. */const toSafeBasename = (path: string, prefix: string): string | null => {const name = path.slice(prefix.length);@@ -135,8 +121,7 @@ export const readInvkArchive = async (file: File): Promise<InvkArchiveContents>throw new InvkFormatError('damaged', `Archive has no ${INVK_DOCUMENT_ENTRY}.`);}- // Before the bytes are indexed: an archive whose enumeration is malformed must create nothing,- // and the enumeration is what decides which of those bytes are board media at all.+ // Validate enumeration before indexing bytes or creating resources.const boardSnapshot = parseBoardEntry(entries);const images = new Map<string, Uint8Array>();const videos = new Map<string, Uint8Array>();@@ -179,14 +164,7 @@ export interface ArchiveBoardUploadDeps {uploadBoardVideo?: typeof uploadBoardVideo;}-/**- * The import half of the materialization seam: board media comes out of the archive. Uploaded with- * no existence check — see `transfer.ts`. A descriptor the archive carries no bytes for is reported- * rather than skipped: the exporting server said it was there.- *- * Entries are dropped as they land. An `.invk` may be two gigabytes, and holding every one until- * the import finishes means holding the archive *and* everything unpacked from it.- */+/** Upload fresh identities, report missing bytes, and release materialized entries to bound memory. */export const createArchiveMediaMaterializer = (archive: Pick<InvkArchiveContents, 'images' | 'videos'>,deps: ArchiveBoardUploadDeps = {}@@ -223,8 +201,7 @@ export const createArchiveMediaMaterializer = (result.materialized.push({ kind: item.kind, name, sourceName: item.name });entries.delete(item.name);} catch (error) {- // A cancelled signal or an expired account is not this item failing — it is every- // remaining item failing at once, which is an ended operation rather than a lossy one.+ // Cancellation or account expiry aborts the operation rather than counting as per-item loss.if (isRequestCancellation(error)) {throw error;}diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.test.tsindex 0524562288..75c4314e1c 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.test.ts@@ -58,11 +58,7 @@ describe('parseInvkManifest', () => {expectReason({ ...v2, version: 4 }, 'unsupported-version');});- /**- * A version this app writes is a version it can read, so one that still fails to parse is a- * broken file — not a newer Invoke. Telling someone to upgrade over a truncated manifest sends- * them somewhere that cannot help.- */+ /** Malformed supported versions are damaged, not newer-version incompatible. */it('reports a malformed manifest at a version it knows as damaged', () => {expectReason({ appVersion: '7.0', createdAt: '', name: 'x', version: 2 }, 'damaged');expectReason({ version: 1 }, 'damaged');diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.tsindex 5d058ac5bd..eed506910e 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts@@ -4,26 +4,8 @@ import { zInvkFontDependency } from './fonts';import { INVK_EXTENSION, INVK_VERSION, InvkFormatError } from './format';/**- * The `.invk` manifest. The previous frontend's canvas project files are ZIPs with this same root- * `manifest.json` and `images/` folder; that container is kept verbatim, and version 2 changes only- * the payload.- *- * ```- * <name>.invk- * ├── manifest.json this file's shape- * ├── project.json the project document- * ├── board.json the project board's visible contents- * ├── cover.<ext> optional preview; the entry name is recorded here- * ├── images/<image_name> bytes, named exactly as the server names them- * └── videos/<video_name> the same, for the other namespace- * ```- *- * Parsed as a discriminated union rather than `z.literal(2)` so a refusal can name the version- * precisely: "this is a canvas project from an earlier version" is actionable, a zod issue list is- * not.- *- * Adding `board.json` did not bump the version — a version tells a reader what it may assume about- * a file *someone else wrote*, and webv2 has not shipped. Readers treat the entry as optional.+ * The v2 ZIP contains manifest.json, project.json, optional board.json and cover, and images/<name> or+ * videos/<name>. Recognize v1 only to return a specific unsupported-version refusal.*/const zManifestV1 = z.object({@@ -57,10 +39,7 @@ const KNOWN_VERSIONS: ReadonlySet<number> = new Set([1, 2]);/** A manifest this app can read: the workbench project container. */export type InvkManifest = z.infer<typeof zManifestV2>;-/**- * Accepts a v2 manifest; throws {@link InvkFormatError} for anything else.- * Never returns a v1 manifest — recognizing v1 exists only to name the refusal.- */+/** Accept v2; recognize v1 only for a named refusal. */export const parseInvkManifest = (data: unknown): InvkManifest => {const parsed = zManifest.safeParse(data);@@ -71,9 +50,7 @@ export const parseInvkManifest = (data: unknown): InvkManifest => {throw new InvkFormatError('not-a-project');}- // A version this app has written is a version it can read, so a manifest that still fails to- // parse at one of them is damaged — a truncated name, a missing timestamp. Calling that- // "written by a newer version of Invoke" tells someone to go and upgrade over a broken file.+ // Report malformed known versions as corrupt, not newer-version incompatible.throw new InvkFormatError(KNOWN_VERSIONS.has(version) ? 'damaged' : 'unsupported-version');}@@ -106,11 +83,7 @@ export const buildInvkManifest = (input: {...(input.sourceProjectId === undefined ? {} : { sourceProjectId: input.sourceProjectId }),});-/**- * File name for the download. Replaces what filesystems reject and drops- * control/format characters, but leaves the rest of unicode alone — a project- * named in a non-Latin script should not export as `project.invk`.- */+/** Remove forbidden/control characters while preserving other Unicode filename characters. */export const toInvkFileName = (projectName: string): string => {const trimmed = projectName.replaceAll(/["*/:<>?\\|]/gu, '_')diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.tsindex c864c968ae..0c62f3d875 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts@@ -6,14 +6,7 @@ import type { InvkMediaRef } from './transfer';import { createRestoredMediaLedger, restoreProjectMedia, rollbackRestoredMedia } from './restoreProjectMedia';-/**- * The restore engine, with the byte source and the transport replaced.- *- * These are the rules that make a restored project *its own* project rather than a second view of- * somebody else's: board media always gets a new identity, a board item that fails takes its- * document references down with it rather than letting them resolve to a stranger, and everything- * that could not be carried is reported against the role it failed in.- */+/** Verify fresh ownership, failed-reference isolation, and role-aware loss reporting. */const BOARD_ID = 'staging-board';const PROJECT_ID = 'project-new';@@ -83,11 +76,7 @@ const restore = (};describe('board media', () => {- /**- * `board_images` has `PRIMARY KEY (image_name)`, so reusing a name would move the destination's- * image onto this project's board rather than copy it — and deleting either board would then take- * it from both. The existence check that document references get is deliberately not run here.- */+ /** Board media needs fresh copies: adopting an existing image-name primary key would move another board's media. */it('takes a fresh identity even when the destination already has that name', async () => {const findExisting = vi.fn(() => Promise.resolve(new Set(['board.png'])));const result = await restore(@@ -143,10 +132,7 @@ describe('board media', () => {expect(result.mappings.images.get('board.png')).toBe('staging-board-board.png');});- /**- * A rejected star call reaches the caller's rollback, which deletes every asset the restore just- * uploaded. Trading a whole project's media for a flag is the one thing this must not do.- */+ /** Star rejection must not roll back restored media. */it('does not lose the restore when the star request itself fails', async () => {const result = await restore({ boardItems: [boardItem({ starred: true })], documentRefs: [imageRef('board.png')] },@@ -166,10 +152,7 @@ describe('board media', () => {).rejects.toBe(cancelled);});- /**- * The invariant this module exists for. The old name is not neutral: on the same server it is- * already taken, by the source project's own image.- */+ /** After a failed copy, the existing source name remains unsafe to reuse. */it('forces an overlapping reference dangling when its board item fails', async () => {const result = await restore({ boardItems: [boardItem({ name: 'both.png' })], documentRefs: [imageRef('both.png')] },@@ -188,21 +171,14 @@ describe('board media', () => {{ materializeBoardMedia: freshNameMaterializer({ fail: new Set(['a.png', 'b.png']) }) });- // Derived from the descriptor's position, not from the order the failures arrived in, so two- // failed items can never collapse onto one placeholder.+ // Derive stable placeholders from descriptors, independently of completion order.expect([...result.mappings.images]).toEqual([['a.png', `${PROJECT_ID}-missing-image-0`],['b.png', `${PROJECT_ID}-missing-image-1`],]);});- /**- * The live reference set skips history — `collectLiveAssetRefs` walks past `recentImages`, canvas- * snapshots and the queue — but `remapAssetRefs` rewrites the whole document. Gating the *mapping*- * on that set therefore left the newest generated result, which is on the board and in the gallery- * recents but not yet on canvas, pointing at the source project's image: the copy renders the- * original's picture, and deleting the original breaks it with no explanation.- */+ /** Remap the entire document, including history excluded from collection. */it('remaps a failed board item the document names only from history', async () => {const result = await restore(// No document ref: this name lives in `recentImages`, which the live-ref walker skips.@@ -212,14 +188,12 @@ describe('board media', () => {expect(result.mappings.images.get('newest.png')).toBe(`${PROJECT_ID}-missing-image-0`);expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'newest.png', reason: 'upload-failed' }]);- // Still not *reported*: a gallery recent that stops resolving is not something the person lost- // from this project, and counting it would inflate every report.+ // Missing history references do not count as live losses.expect(result.documentReferenceIssues).toEqual([]);});it('keeps two failures the board never described apart', async () => {- // No descriptor position to derive from. Collapsing both onto index 0 would merge two unrelated- // missing items into one dangling reference.+ // Allocate distinct fallback indices for references without descriptor positions.const result = await restore({ boardItems: [boardItem({ name: 'described.png' })] },{@@ -241,10 +215,7 @@ describe('board media', () => {});/** A materializer that answers neither way has still not delivered the media. */- /**- * Three ways a descriptor can fail to arrive, all of which must produce exactly one issue and one- * placeholder: reported missing, reported twice, and not reported at all.- */+ /** Missing, duplicate, or unreported settlements must produce exactly one issue and placeholder per descriptor. */it.each([['the source could not materialize it',@@ -293,10 +264,7 @@ describe('board media', () => {});describe('document-only references', () => {- /**- * The existence check is an optimization — it only decides whether an upload can be skipped. A- * failed probe should cost bandwidth, never the import.- */+ /** Failed existence probes may cause extra uploads, but must not fail the import. */it('uploads everything when the existence check fails', async () => {const uploadImage = vi.fn((_bytes: Uint8Array, fileName: string) =>Promise.resolve({ height: 1, imageName: `uploaded-${fileName}`, width: 1 })@@ -485,8 +453,7 @@ describe('rollbackRestoredMedia', () => {expect(deleteImages).toHaveBeenCalledWith(['board-image', 'cover-image', 'document-image'], undefined);expect(deleteVideos).toHaveBeenCalledWith(['board-video', 'document-video'], undefined);- // The board goes last, and without `include_images`, so anything that wandered onto it while- // the import ran survives as Uncategorized.+ // Delete the board last with include_images=false to preserve unrelated media.expect(order.at(-1)).toBe(`board:${BOARD_ID}`);});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.tsindex ed0df91194..cbd6c5cf2b 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts@@ -26,27 +26,11 @@ import {import { buildMissingMediaName, createTransferIssueLog, toMediaKey } from './transfer';/**- * Putting a project's media on this server, for whichever direction needs it. Import and- * duplication differ in exactly one step — where the bytes come from, {@link MediaMaterializer} —- * and share everything around it.- *- * ### A failed board item must not resolve to a stranger- *- * An item both on the board and named by the document, whose materialization fails, must not keep- * its old name: on the same server that name is already taken, by the *source* project's image, so- * the project would open showing the right picture from the wrong owner. Failed items are forced- * onto {@link buildMissingMediaName}, which resolves to nothing and renders as a missing layer.- *- * The placeholder is written for every failed item, because `remapAssetRefs` walks the whole- * document. The live reference set — which skips history — decides only what is worth *reporting*:- * a gallery recent that stops resolving is not something the person lost from this project.+ * Shared materialization always remaps failed names away from existing media; loss reporting includes only live+ * references.*/-/**- * Degrade to `fallback`, except for cancellation. Starring is a flag and an existence probe only- * spares an upload — neither is worth reaching the caller's rollback. Cancellation is the- * exception because it makes *every* remaining call fail, which is not a half-restored project.- */+/** Ancillary/probe failures are best-effort; operation cancellation propagates. */const degradeUnlessCancelled =<T>(fallback: T) =>(error: unknown): T => {@@ -78,10 +62,7 @@ export interface MaterializeResult {materialized: MaterializedMedia[];}-/**- * Make board media exist on `boardId`, however this direction gets its bytes. `onItemSettled` fires- * once per descriptor, so progress moves through the part people actually wait for.- */+/** onItemSettled fires exactly once per descriptor. */export type MediaMaterializer = (items: readonly InvkBoardItem[],boardId: string,@@ -174,12 +155,7 @@ interface RestoreKindAdapter {upload: (bytes: Uint8Array, name: string, signal?: AbortSignal) => Promise<string>;}-/**- * The cover, preferring an image the restore already put here — the same picture without a second- * copy. Uploading the bundled entry unconditionally left one orphan per import, in the private- * `'other'` category where nobody could find or delete it. The bytes are the fallback, for a cover- * whose source image is dangling.- */+/** Reuse the restored cover source before uploading fallback bytes. */const resolveCoverImageName = async (input: {coverBytes: { bytes: Uint8Array; entryName: string } | null;coverSourceImageName: string | null;@@ -211,17 +187,12 @@ const resolveCoverImageName = async (input: {return uploaded.imageName;} catch {- // A project with no cover shows the folder glyph, which is a state the library already- // renders. Not worth failing an import over.+ // Cover failure is nonfatal; fall back to a missing cover.return null;}};-/**- * Restore a project's media and report what could not be carried. Nothing throws for a media- * failure; the only rejections are the ones that end the operation — cancellation, an expired- * account.- */+/** Per-media failures belong in the result; rejections end the whole operation. */export const restoreProjectMedia = async (input: RestoreProjectMediaInput,deps: RestoreProjectMediaDeps@@ -239,11 +210,7 @@ export const restoreProjectMedia = async (const boardKeys = new Set(input.boardItems.map(toMediaKey));/** Descriptor position, so a placeholder name does not depend on the order failures happened in. */const descriptorIndexes = new Map(input.boardItems.map((item, index) => [toMediaKey(item), index]));- /**- * Descriptor position where it exists; counting past the descriptors otherwise. Collapsing- * position-less failures onto one index would merge two unrelated missing items into a single- * dangling reference.- */+ /** Allocate unique placeholders even without descriptor positions. */let nextUnknownIndex = input.boardItems.length;const missingNameIndex = (key: string): number => {const index = descriptorIndexes.get(key);@@ -258,19 +225,15 @@ export const restoreProjectMedia = async (};const starredKeys = new Set(input.boardItems.filter((item) => item.starred).map(toMediaKey));- // Document-only references are the ones the board does not own; those the board owns are- // restored as board media and their references follow the copy.const documentOnlyRefs = input.documentRefs.filter((ref) => !boardKeys.has(toMediaKey(ref)));const documentOnlyImages = documentOnlyRefs.filter((ref) => ref.kind === 'image').map((ref) => ref.name);const documentOnlyVideos = documentOnlyRefs.filter((ref) => ref.kind === 'video').map((ref) => ref.name);- // A board with no staging board to put it on cannot be materialized; every descriptor then falls- // through to the unsettled pass below, which is the honest reading of "the media did not arrive".+ // Descriptors without a staging board still require explicit failure reporting.const stagingBoardId = input.boardItems.length === 0 ? null : input.boardId;let completed = 0;- // The document-only total is only known once the existence checks answer, so progress is reported- // against the worst case: every reference needing an upload. It can only finish early.+ // Use the worst-case progress total until existence probes resolve.let total =(stagingBoardId === null ? 0 : input.boardItems.length) +documentOnlyRefs.length +@@ -301,13 +264,8 @@ export const restoreProjectMedia = async (},};- // Started before the board upload, awaited after it: the probes need only the document's own- // references, and the board upload is the minutes-long part. An empty answer degrades safely —- // the check only skips redundant uploads, so failing it costs bandwidth, never correctness.- //- // `allSettled` is constructed here, not at the await: a promise started now and awaited after the- // upload would surface as an unhandled rejection if the upload threw first. Cancellation still- // ends the restore, re-thrown at the await below in its proper order.+ // Run probes alongside uploads and attach allSettled immediately to prevent unhandled rejection. Propagate+ // cancellation at the ordered await.const settledProbes = Promise.allSettled([documentOnlyImages.length === 0? Promise.resolve(new Set<string>())@@ -356,16 +314,13 @@ export const restoreProjectMedia = async (settledBoardKeys.add(key);issues.addBoardItemIssue(failure, failure.reason);- // Mapped unconditionally: `remapAssetRefs` rewrites the whole document while `documentKeys`- // covers only live references, so a name left unmapped survives in history — pointing, on this- // server, at the source project's own image.+ // Remap all references, including history; reporting scans only live references.kindAdapters[failure.kind].mapping.set(failure.name,buildMissingMediaName(input.projectId, failure.kind, missingNameIndex(key)));- // Only the live references are *reported*. A gallery recent that no longer resolves is not- // something the person lost from this project, and counting it would inflate every report.+ // Exclude recents/history from live loss counts.if (documentKeys.has(key)) {issues.addDocumentReferenceIssue(failure, failure.reason);}@@ -375,16 +330,14 @@ export const restoreProjectMedia = async (failBoardItem(failure);}- // A descriptor reported neither way is a failure too: dropping it silently would leave its- // document reference on the old name.+ // Treat unreported descriptors as failures with missing placeholders.for (const item of input.boardItems) {if (!settledBoardKeys.has(toMediaKey(item))) {failBoardItem({ kind: item.kind, name: item.name, reason: 'upload-failed' });}}- // A failed star costs a flag, not the media, so it must not reject: a rejection here reaches the- // caller's rollback and deletes every image just uploaded, over a flag.+ // Star failure must not trigger rollback of successfully restored media.const [imageStars, videoStars] = await Promise.all([starRestoredImages(starTargets.image, deps.signal).catch(degradeUnlessCancelled({ failed: starTargets.image })),starRestoredVideos(starTargets.video, deps.signal).catch(degradeUnlessCancelled({ failed: starTargets.video })),@@ -437,8 +390,7 @@ export const restoreProjectMedia = async (}}- // Deduplication and missing bytes both shrink the work; say so, or a restore that ends with- // nothing left to upload reports its last count against a total it will never reach.+ // Reduce progress totals for deduplication and absent bytes.if (total !== plannedTotal) {deps.onProgress?.({ completed, total });}@@ -447,8 +399,7 @@ export const restoreProjectMedia = async (const { kind, name } = item;const bytes = item.bytes;- // Dropped before the request, not after: the upload body holds its own reference, and this- // queue was why a large restore held every asset it had not sent yet.+ // Release queued bytes before upload; the request body retains them.item.bytes = null;if (bytes === null) {@@ -466,14 +417,12 @@ export const restoreProjectMedia = async (adapter.mapping.set(name, restoredName);}} catch (error) {- // Not a failure of this asset: cancellation makes every remaining upload fail too, and- // reporting them one by one would name hundreds of dangling references.+ // Cancellation is one operation failure, not a missing-asset result for every queued item.if (isRequestCancellation(error)) {throw error;}- // A failed upload leaves the reference pointing at a name this server does not have — the- // same outcome as an asset the source never carried, and honest for the same reason.+ // Failed uploads must remain unresolved rather than bind to unrelated existing media.issues.addDocumentReferenceIssue({ kind, name }, 'upload-failed');}@@ -498,11 +447,8 @@ export const restoreProjectMedia = async (};/**- * Run a restore's rollback, but only when the project it was staging certainly does not exist.- * Three things must hold: the create did not already succeed; the failure *proves* absence, which- * is what {@link ProjectCreateAbsentError} means and why the create goes through- * `createProjectSettled`; and the account has not changed. An unknown outcome must never authorize- * a deletion — uploads are recoverable clutter, a project stripped of its media is not.+ * Rollback requires all three: creation did not succeed, ProjectCreateAbsentError proves absence through+ * createProjectSettled, and the original account is still current. Unknown outcomes never authorize deletion.*/export const rollbackUnlessProjectExists = async (error: unknown,@@ -528,11 +474,7 @@ export interface RollbackRestoredMediaDeps {signal?: AbortSignal;}-/**- * Undo a restore whose project was never created — exactly the identities it made, then the board.- * Best-effort throughout, so a failing cleanup cannot replace the actionable error. The board goes- * last and without `include_images`; see {@link deleteStagingBoard}.- */+/** Best-effort cleanup deletes only ledger-owned resources, then the board without include_images. */export const rollbackRestoredMedia = async (ledger: RestoredMediaLedger,deps: RollbackRestoredMediaDeps = {}diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.test.tsindex 2699c8bb53..ad7159d633 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.test.ts@@ -75,10 +75,7 @@ describe('planMediaTransfer', () => {});describe('createTransferIssueLog', () => {- /**- * The same failure can cost a board result and a canvas layer at once. Reporting it against both- * roles is not double-counting — it genuinely failed as both.- */+ /** One failed asset can legitimately count in both roles. */it('records an overlapping failure against both roles and sorts the result', () => {const log = createTransferIssueLog();@@ -101,11 +98,7 @@ describe('createTransferIssueLog', () => {});describe('buildMissingMediaName', () => {- /**- * A failed board copy must not leave the document pointing at the old name: the destination may- * well have its own media under it — on the same server, during a duplication, it certainly does- * — and the project would open showing a stranger's picture with nothing to indicate it is wrong.- */+ /** Remap failed board references away from existing source names. */it('is stable within one project and distinct across projects, kinds and items', () => {expect(buildMissingMediaName('p1', 'image', 0)).toBe(buildMissingMediaName('p1', 'image', 0));expect(buildMissingMediaName('p1', 'image', 0)).not.toBe(buildMissingMediaName('p2', 'image', 0));diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.tsindex cd4a86bab3..16de69d9c3 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.ts@@ -3,18 +3,8 @@ import type { ProjectAssetRefs } from '@workbench/projects/projectAssets';import type { InvkBoardItem, InvkMediaKind } from './board';/**- * The vocabulary shared by export, import and duplication — and the one rule they all turn on.- *- * A project's media comes from two overlapping places, and what must happen differs by which:- *- * - **Board membership** must be *copied*. `board_images` has `PRIMARY KEY (image_name)`, so one- * image sits on exactly one board; reusing an existing name would *share* another project's- * media, and deleting either board would take it from both.- * - **Document references** may be *reused*. They are pointers, not membership, so an image the- * destination already has satisfies them without a second copy.- *- * So an item that is *both* is restored as board media and its references rewritten to the copy.- * When that copy fails the reference must not keep the old name — see {@link buildMissingMediaName}.+ * Board media needs fresh ownership; document-only references may be reused. Shared references remap to the copy,+ * and failed copies receive missing placeholders.*//** One item, in whichever namespace it belongs to. */@@ -44,11 +34,7 @@ export interface InvkMediaIssue extends InvkMediaRef {reason: InvkMediaIssueReason;}-/**- * What a transfer could not carry, counted apart: a missing board item costs a result still- * findable elsewhere, a missing document reference costs a layer in the canvas. An item that was- * both appears in both arrays — it genuinely failed in both roles.- */+/** Report losses separately by role; an item may fail in both. */export interface ProjectTransferIssues {boardItemIssues: InvkMediaIssue[];documentReferenceIssues: InvkMediaIssue[];@@ -93,11 +79,7 @@ export interface InvkTransferItem extends InvkMediaRef {boardItem: InvkBoardItem | null;}-/**- * Merge board membership and document references into one list, each item once. An item that is- * both must be fetched or uploaded once, and the union is what lets one failure be reported- * against both roles.- */+/** Materialize once while retaining both roles for loss reporting. */export const planMediaTransfer = (boardItems: readonly InvkBoardItem[],documentRefs: readonly InvkMediaRef[]@@ -135,13 +117,6 @@ export const planMediaTransfer = (return [...byKey.values()].sort(compareMediaRefs);};-/**- * A name guaranteed not to resolve, for a document reference whose board media could not be- * restored. Keeping the original would be worse: the destination may hold its own image under that- * exact name — during a duplication it certainly does — so the project would open pointing at a- * stranger's picture, plausibly and silently.- *- * Derived from the new project id, so it is stable within one import and unique across them.- */+/** Missing names are stable within an import and cannot resolve to existing source media. */export const buildMissingMediaName = (projectId: string, kind: InvkMediaKind, index: number): string =>`${projectId}-missing-${kind}-${index}`;diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.tsindex 2dcd53a70f..d10c8d4165 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts@@ -7,12 +7,6 @@ import type * as libraryModule from './library';import type { ProjectPushOutcome } from './projectFlush';import type * as syncStoreModule from './syncStore';-/**- * The project library store: summaries normalized at the boundary, sorted by- * recency, and the explicit mutations (delete, rename, duplicate) that are- * the only paths off the server.- */-const api = vi.hoisted(() => ({createProject: vi.fn(),deleteProject: vi.fn(),@@ -241,11 +235,7 @@ describe('library mutations', () => {expect(library.getProjectLibrary().summaries[0]?.name).toBe('New name');});- /**- * The invariant: a project the workbench holds is mutated through the sync engine, everything- * else over HTTP. A library PUT beside an open project's revision chain used to fork it into a- * conflict copy, and would now rename its board from outside the transaction that owns both.- */+ /** Route open-project mutations through sync ownership; use HTTP for closed projects. */it('renames an open project through the editor rather than over HTTP', async () => {api.listProjects.mockResolvedValue([summaryDto('open', 'Old name', '2026-06-10 10:00:00.000')]);await library.refreshProjectLibrary();@@ -260,12 +250,7 @@ describe('library mutations', () => {expect(library.getProjectLibrary().summaries[0]?.name).toBe('New name');});- /**- * The DELETE goes through the sync engine's own queue, not beside it. Marking the project stops a- * save that has not begun, but a PUT already on the wire is past every check the engine has — it- * returns 404 once the DELETE commits, and the engine answers a 404 by forking the local document- * into a *new* server project. Queueing is what makes that unreachable rather than unlikely.- */+ /** Serialize deletion after in-flight saves; marking cannot stop an already-sent PUT. */it('deletes an open project through the sync engine, then closes the tab', async () => {const { calls } = openProject('open');@@ -308,10 +293,7 @@ describe('library mutations', () => {expect(release).toHaveBeenCalledOnce();});- /**- * A project left marked deleted never autosaves again for the rest of the session, and nothing- * says so. Unmarking belongs with the mark, inside the handle, rather than in each caller's catch.- */+ /** Unmark failed deletes only with mark ownership so autosave resumes safely. */it('surfaces a failed deletion of an open project to its caller', async () => {const { calls, handle } = openProject('open');@@ -373,11 +355,7 @@ describe('library mutations', () => {expect(calls).toEqual(['flush', 'get']);});- /**- * The GET below returns the last *acknowledged* document, which is exactly what the flush exists- * to move past. A flush that resolved without landing therefore reads as success and copies stale- * bytes, under a clean toast — so an unacknowledged push has to end the operation instead.- */+ /** An unacknowledged flush must abort duplication rather than copy stale server bytes. */it('refuses to duplicate a project whose flush never reached the server', async () => {const { calls, handle } = openProject('source');@@ -423,8 +401,7 @@ describe('library mutations', () => {const duplicated = await library.duplicateLibraryProject('source');- // The board is enumerated before anything is created: a copy whose board came back silently- // empty would look like a faithful duplication of a project that had produced nothing.+ // Enumerate the board successfully before creating copy resources.expect(api.getProjectBoardSnapshot).toHaveBeenCalledWith('source', expect.any(AbortSignal));expect(duplication.duplicateProjectRecord.mock.calls[0]?.[0]).toMatchObject({boardItems: [{ name: 'on-board.png' }],diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.tsindex ebe7c499ce..a979fcaf99 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts@@ -34,17 +34,7 @@ import { assertProjectFlushed } from './projectFlush';import { pruneSessionProject } from './session';import { getOpenProject } from './syncStore';-/**- * The project library: every project saved on the server for the current- * user, as lightweight summaries (no documents). The Home screen, the Open- * Project dialog, and the editor's save pass all read and patch this one- * store, so "what projects exist" has a single answer everywhere.- *- * The library is intentionally separate from the workbench session: open tabs- * hold hydrated documents in workbench state, while the library only knows- * metadata. Deleting through the library is the only way a project leaves the- * server — closing a tab never does.- */+/** User-scoped library summaries are separate from hydrated tabs; closing a tab must not delete its server record. */export interface ProjectSummary {id: string;@@ -53,12 +43,7 @@ export interface ProjectSummary {minimumCanvasSchemaVersion: number;createdAt: string;updatedAt: string;- /**- * Thumbnail for the library grid, resolved from the per-user cover index- * (`covers.ts`) rather than from the project document, which listings do not- * carry. Absent for a project that has produced no images, and for one last- * saved by a build that did not record covers.- */+ /** The cover index is independent of document-free listings; absent entries yield no cover. */coverUrl?: string;}@@ -96,12 +81,7 @@ const toSummary = (dto: ProjectSummaryDTO): ProjectSummary =>updatedAt: normalizeServerTimestamp(dto.updated_at),});-/**- * The cover index loads and updates independently of the listing, so summaries- * are re-derived whenever it changes. Without this a cover recorded after the- * library rendered — the first generation in a new project — would not appear- * until the next refresh.- */+/** Recompute summaries when the independent cover index changes. */subscribeProjectCovers(() => {const { status, summaries } = store.getSnapshot();@@ -148,9 +128,7 @@ export const refreshProjectLibrary = (): Promise<void> =>const owner = captureAccountScope();return refreshFlight.run(`project-library:${owner.epoch}`, () =>- // Covers resolve alongside the listing rather than after it: they come- // from a different store, and seeding without them would show a grid of- // glyphs that fills in a moment later.+ // Fetch covers and listings concurrently to avoid a temporary glyph-only grid.Promise.all([listProjects(owner.signal), loadProjectCovers()]).then(([dtos]) => {seedProjectLibrary(dtos, owner);@@ -168,11 +146,7 @@ export const refreshProjectLibrary = (): Promise<void> =>);})();-/**- * Reflect a save the editor just pushed, so the library stays current without- * a refetch. `updatedAt` is stamped locally; the next refresh replaces it- * with the server's value.- */+/** Refresh replaces optimistic local updatedAt with server time. */export const upsertProjectSummary = (entry: { id: string; minimumCanvasSchemaVersion?: number; name: string; revision: number | null },owner: AccountScope@@ -246,8 +220,7 @@ export const deleteLibraryProject = async (projectId: string): Promise<void> =>forgetProjectCover(projectId, owner);store.patchSnapshot({ summaries: store.getSnapshot().summaries.filter((summary) => summary.id !== projectId) });- // The saved session outlives the editor, so a deleted project has to leave it here or the next- // boot tries to open something the server no longer has.+ // Remove deleted projects from durable session state so missing records do not reopen.await pruneSessionProject(projectId, owner.signal);await refreshOpenProjects();} finally {@@ -290,12 +263,7 @@ export const renameLibraryProject = async (projectId: string, name: string): ProupsertProjectSummary({ id: updated.project_id, name: updated.name, revision: updated.revision }, owner);};-/**- * The server record for a project about to be copied or exported, flushed first when the editor- * holds it, and fatal if that flush does not land. The GET returns the last *acknowledged*- * document, so without this an unacknowledged push is indistinguishable from a successful one and- * the copy silently omits the last ten minutes of work under a success toast.- */+/** Export/copy requires an acknowledged flush before reading server bytes. */export const readAcknowledgedProject = async (projectId: string, owner: AccountScope): Promise<ProjectRecordDTO> => {const openProject = getOpenProject(projectId);@@ -330,9 +298,8 @@ export interface DuplicatedProject extends ProjectTransferIssues {}/**- * Copy a project, its board and everything on it, under a fresh id. Enumerating the board is fatal:- * a board that came back silently empty would look like a successful copy of a project that had- * produced nothing. The copying shares import's restore engine behind the lazy `invk/` boundary.+ * Duplicate with a fresh identity and whole-board copy. Enumeration failure is fatal; restoration stays lazy and+ * shared.*/export const duplicateLibraryProject = async (projectId: string,diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.tsindex 6e07645c62..ba8c509508 100644--- a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts@@ -5,11 +5,7 @@ import type { ProjectPushOutcome } from './projectFlush';import { createOpenProjectBroker } from './openProjectBroker';import { getOpenProject } from './syncStore';-/**- * The registry has to say exactly which projects the editor holds: it is what decides whether a- * library mutation goes through the sync engine or over HTTP, and a stale entry would put a write- * on the wrong side of that.- */+/** The exact open-project registry decides between sync and HTTP writes. */const createHarness = () => {const listeners = new Set<() => void>();@@ -58,8 +54,7 @@ describe('createOpenProjectBroker', () => {account.accountLifecycle.activate('broker-user');});- // The registry is module state. A test that leaves a handle in it is a test the next one- // inherits, and these only pass in isolation by using different ids.+ // Clear the module registry between tests to avoid leaked handles.afterEach(() => {for (const broker of brokers.splice(0)) {broker.dispose();@@ -143,11 +138,7 @@ describe('createOpenProjectBroker', () => {expect(harness.deps.closeProject).toHaveBeenCalledWith('a');});- /**- * A rename is already in the reducer and the local snapshot by the time the flush runs, and the- * next save retries the push. Failing the rename because the network blipped would undo nothing- * and explain less — so the outcome is read by the surfaces that read the project back, not here.- */+ /** Local rename may succeed with a retryable flush; server-reading operations require acknowledgement. */it('does not fail a rename whose flush did not reach the server', async () => {const harness = createHarness();@@ -159,11 +150,7 @@ describe('createOpenProjectBroker', () => {expect(harness.deps.renameProject).toHaveBeenCalledWith('a', 'New name');});- /**- * The registry is cleared when the account changes. A broker that trusted its own record of what- * it had published would never register those projects again, and every library mutation would- * silently take the HTTP path for the rest of the mount — the exact thing this exists to stop.- */+ /** Republish after account clears even if the broker's previous set is unchanged. */it('republishes its handles after the registry is cleared underneath it', async () => {const harness = createHarness();const account = await import('@platform/state/accountLifecycle');diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.tsindex 261ab2a385..a3b13dc9d7 100644--- a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts@@ -2,13 +2,7 @@ import type { ProjectPushOutcome } from './projectFlush';import { type OpenProjectHandle, registerOpenProject, unregisterOpenProject } from './syncStore';-/**- * Publishes one {@link OpenProjectHandle} per open tab, for the life of the mounted editor.- *- * Derived from workbench state on every change rather than maintained by open and close call sites:- * the registry decides whether the library mutates through the sync engine or over HTTP, so one- * that disagreed with the tabs would put a write on the wrong side of that invariant.- */+/** Derive the broker from actual tabs so mutation routing cannot drift. */export interface OpenProjectBrokerDeps {/** Drop the tab. Called after the project is already gone from the server. */closeProject: (projectId: string) => void;@@ -37,13 +31,7 @@ export const createOpenProjectBroker = (deps: OpenProjectBrokerDeps): OpenProjecdeleteOnServer: () => deps.deleteProject(projectId),flush: () => deps.flushProject(projectId),markDeleted: () => deps.markProjectDeleted(projectId),- // Renaming through the reducer first is what keeps the open document and the server's copy- // telling the same story: the flush that follows carries the new name on the project's own- // revision chain, where a library PUT would have landed beside it and forced a conflict fork.- //- // The flush outcome is deliberately ignored. The rename is already in the reducer and on the- // local snapshot; a push that did not land is retried by the next save, and failing the rename- // because the network blipped would undo nothing and explain less.+ // Rename through the reducer's revision chain; an unacknowledged flush remains recoverable.rename: async (name: string) => {deps.renameProject(projectId, name);await deps.flushProject(projectId);@@ -51,13 +39,7 @@ export const createOpenProjectBroker = (deps: OpenProjectBrokerDeps): OpenProjecunmarkDeleted: () => deps.unmarkProjectDeleted(projectId),});- /**- * Publish the current open set, unregistering whatever is no longer in it.- *- * Registration is unconditional: the registry is cleared when the account changes, and a- * `published` set that believed otherwise would never re-register, silently sending every library- * mutation over HTTP for the rest of the mount. `published` records only what to *retract*.- */+ /** Register unconditionally after account clears; published tracks only retraction. */const sync = (): void => {const openIds = new Set(deps.getOpenProjectIds());diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjects.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjects.tsindex 5c5dfebe16..e897fad055 100644--- a/invokeai/frontend/webv2/src/workbench/projects/openProjects.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/openProjects.ts@@ -8,18 +8,7 @@ import { createSingleFlight } from '@platform/state/singleFlight';import { fetchSessionBlob } from './session';-/**- * Which projects the editor currently has open, read from the saved session.- *- * The Launchpad asks this from two places — the top bar's way back in, and the- * library's "open" grouping — so it lives in one store with one request rather- * than a fetch per component.- *- * `ids: null` means *unknown*, not empty: a first run, a session blob written- * before the open set existed, or an unreachable backend all land there. The- * `/app` guard makes the same distinction and declines to redirect on it, so- * callers must not treat unknown as "nothing is open".- */+/** Share the route guard's request and null-as-unknown contract. */export interface OpenProjectsSnapshot {status: 'idle' | 'loading' | 'ready';diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.tsindex f7c04abe58..d556abf493 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts@@ -2,12 +2,6 @@ import { describe, expect, it } from 'vitest';import { collectLiveAssetRefs, remapAssetRefs, selectCoverImageName, stripInstallationState } from './projectAssets';-/**- * The walker's contract, stated as documents rather than as paths: what an- * archive must bundle, what it must leave behind, which kind each name is, and- * what has to be rewritten when the server hands back a different name.- */-const imageRef = (imageName: string) => ({ height: 512, imageName, width: 512 });const imageLayer = (id: string, imageName: string) => ({@@ -119,10 +113,7 @@ describe('collectLiveAssetRefs', () => {expect(refs.videos).toEqual(new Set());});- /**- * `VideoField { video_name }` reaches `projectGraph` through an imported- * workflow. It is a separate namespace from images and must not be conflated.- */+ /** Video and image references have separate namespaces, even with identical names. */it('collects a graph node video as a video, never as an image', () => {const refs = collectLiveAssetRefs(projectDocument({@@ -149,18 +140,8 @@ describe('collectLiveAssetRefs', () => {expect(refs.videos).toEqual(new Set(['clip.mp4']));});- /**- * The gallery selection is a pointer into per-install gallery content, not- * something the document renders, so neither kind is bundled. The second- * assertion is the regression guard: the exclusion is by key, so it survives- * `GalleryItem` spelling its name field the same way the canvas does.- */- /**- * `compareImage` is a `GeneratedImageContract`, so it carries `imageName` and would otherwise be- * collected. A comparison left open is not project content. The last row guards the exclusion- * against `selectedImage` starting to spell its name `imageName`, which no collector key matches- * today only by accident.- */+ /** Exclude selection by parent key regardless of media-name spelling. */+ /** Exclude compare/selection references independently of recognized imageName keys. */it.each([['the selection, of either kind',@@ -187,12 +168,7 @@ describe('collectLiveAssetRefs', () => {});});-/**- * Not bundling the selection is only half of leaving it behind. A reference- * that is skipped by the collector but left in the document still travels —- * broken, and invisible to the restore pass that would otherwise report it as- * dangling.- */+/** Strip skipped selection references so unbundled names cannot travel broken and unreported. */describe('stripInstallationState', () => {it('drops every selection key at any depth', () => {const stripped = stripInstallationState({@@ -233,10 +209,7 @@ describe('stripInstallationState', () => {});});- /**- * A board id means nothing on the machine a project arrives at, and the one- * naming the project's own board is a cache the server overwrites anyway.- */+ /** Gallery board IDs are installation-specific; hydration replaces them with server-authoritative IDs. */it('drops the gallery board ids from both the current and legacy widget shapes', () => {const stripped = stripInstallationState({widgetInstances: {@@ -254,11 +227,7 @@ describe('stripInstallationState', () => {expect(JSON.stringify(stripped)).toContain('galleryView');});- /**- * A URL is built around a media name and a server. The name is remapped by a transfer; the URL is- * not — so a cached one keeps resolving, to the *source* project's picture, on a document that no- * longer references that media at all.- */+ /** Invalidate cached URLs when transfer changes names or server roots. */it('blanks the cached media URLs rather than dropping them', () => {const stripped = stripInstallationState({widgetInstances: {@@ -289,18 +258,13 @@ describe('stripInstallationState', () => {] as { state: { values: { recentImages: Record<string, unknown>[] } } }).state.values.recentImages;- // Blanked, not removed: `getBoundedRecentImages` requires both to be strings and silently drops- // any entry missing one, so deleting the keys would discard the whole recents overlay.+ // Preserve URL keys as blank strings so recents entries survive.expect(recent).toMatchObject({ imageName: 'recent.png', imageUrl: '', thumbnailUrl: '' });expect(Object.keys(recent!)).toContain('thumbnailUrl');expect(JSON.stringify(stripped)).not.toContain('source-install');});- /**- * Subtrees with nothing to change keep their identity. The last row matters most: only the- * gallery widget's own two keys are installation state, so a board named by a workflow node is an- * authored input that has to survive the round trip.- */+ /** Preserve unchanged identity and authored workflow board inputs. */it.each([['no selection', { canvas: { document: { stacks: { raster: [imageLayer('l1', 'a.png')] } } }, id: 'p1' }],[diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.tsindex f9cb297c2c..5332eaef8f 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts@@ -1,24 +1,6 @@/**- * Which assets a project document points at, and how to rewrite those pointers.- *- * ### Collection is by key, not by path- *- * Three keys hold an asset name: `imageName`, `image_name` and `video_name`. Collecting every- * string found at those keys is complete by construction — a new adapter kind or node field is- * picked up without touching this file. The legacy frontend walks a hand-written list of paths- * instead, which is why it enumerates `ip_adapter` and `flux_redux` by name and drops the pixels of- * anything added since. A false positive costs nothing: it fails to resolve and is skipped.- *- * Images and videos get a set and a mapping each, because they are separate backend namespaces and- * could share a name — one flat map would let one rewrite the other.- *- * ### Collection skips history, remapping does not- *- * Legacy queue entries embedded whole canvas snapshots and the gallery keeps sixty recents, so- * bundling everything could turn a working project into a multi-gigabyte archive;- * {@link collectLiveAssetRefs} walks only what the project needs to open. {@link remapAssetRefs}- * walks everything, because imported legacy documents may still contain history while their asset- * references are being rewritten before canonical serialization removes it.+ * Discover references by name key with separate image/video namespaces. Collection excludes history; remapping+ * includes it.*//** Keys whose string values name an image. */@@ -33,14 +15,7 @@ export const PROJECT_HISTORY_ROOT_KEYS: ReadonlySet<string> = new Set(['events',/** Keys that introduce history at any depth (`canvas.snapshots`, the gallery's recents). */export const PROJECT_HISTORY_KEYS: ReadonlySet<string> = new Set(['recentImages', 'snapshot', 'snapshots']);-/**- * The gallery widget's selection: per-install content, so a project arriving elsewhere opens with- * nothing selected rather than dragging a stranger's gallery behind it.- *- * Skipping them during collection is only half of it — an unbundled, unstripped reference still- * travels, just broken, and the same skip hides it from the restore pass so import cannot even- * report it as dangling. {@link stripGallerySelection} is the other half.- */+/** Skip and strip installation-specific selection references so unbundled names cannot travel silently. */export const GALLERY_SELECTION_KEYS: ReadonlySet<string> = new Set(['compareImage','selectedImage',@@ -48,22 +23,10 @@ export const GALLERY_SELECTION_KEYS: ReadonlySet<string> = new Set(['selectedImageNames',]);-/**- * Board ids the gallery widget holds. Installation state, not project state: `projectBoardId` is a- * cache the server owns and hydration overwrites.- *- * Board ids elsewhere in the document — a workflow node's board input — are meaningful and- * deliberately NOT stripped, which is why this names only the gallery widget's two keys.- */+/** Strip gallery board IDs while preserving authored workflow board inputs. */export const GALLERY_INSTALLATION_KEYS: ReadonlySet<string> = new Set(['projectBoardId', 'selectedBoardId']);-/**- * Where the gallery was scrolled to. Meaningless in another install: the board- * ids above are stripped, so an imported project lands on a different (usually- * near-empty) board, where a page number — or, in infinite mode, the mid-board- * window anchor it doubles as — describes a position that does not exist and- * renders as an empty board.- */+/** Clear pagination/window anchors when transferred board IDs change. */export const GALLERY_POSITION_KEYS: ReadonlySet<string> = new Set(['galleryPage']);const INSTALLATION_STATE_KEYS: ReadonlySet<string> = new Set([@@ -72,15 +35,7 @@ const INSTALLATION_STATE_KEYS: ReadonlySet<string> = new Set([...GALLERY_POSITION_KEYS,]);-/**- * URLs the document caches beside a media name, naming *this* install's copy.- *- * Blanked, not removed: `getBoundedRecentImages` requires both to be strings and drops any entry- * missing one, so deleting them would discard the whole gallery-recents overlay on import. Every- * consumer already falls back to deriving the URL from the name, which is the only correct answer- * once a transfer has renamed the media — the name is remapped, a URL built around the old one is- * not, and would keep resolving to the source project's picture.- */+/** Blank cached URLs instead of deleting keys, preserving entries while forcing URL derivation from remapped names. */const DERIVED_URL_KEYS: ReadonlySet<string> = new Set(['imageUrl', 'thumbnailUrl', 'videoUrl']);export interface ProjectAssetRefs {@@ -125,11 +80,6 @@ const collectFrom = (node: unknown, refs: ProjectAssetRefs): void => {}};-/**- * Every asset name the project needs in order to open: canvas layers and masks,- * reference images, widget values, and graph node inputs. History and gallery- * selections are excluded — see the module docblock.- */export const collectLiveAssetRefs = (projectDocument: Record<string, unknown>): ProjectAssetRefs => {const refs: ProjectAssetRefs = { images: new Set<string>(), videos: new Set<string>() };@@ -147,12 +97,7 @@ export const collectLiveAssetRefs = (projectDocument: Record<string, unknown>):/** `{ drop: true }` removes the key, `{ value }` replaces it, `null` recurses into it. */type NodeVisit = { drop: true } | { value: unknown } | null;-/**- * Walk every entry of a project document at every depth, applying `visit`.- *- * Subtrees with nothing to change keep their identity, so a document that matches nothing comes- * back as the very same object rather than a structurally-equal copy.- */+/** Preserve structural sharing; unchanged documents return the same object. */const mapDocument = (node: unknown, visit: (key: string, value: unknown) => NodeVisit): unknown => {if (Array.isArray(node)) {let hasChanged = false;@@ -197,13 +142,7 @@ const mapDocument = (node: unknown, visit: (key: string, value: unknown) => Nodereturn hasChanged ? next : node;};-/**- * Drop everything describing *this install* rather than the project, at every depth.- *- * Removing a key is the same as clearing it here: every reader already tolerates absence. By key at- * any depth rather than by walking `widgetInstances`, which covers the legacy `widgetStates.gallery`- * shape for free and is safe because these keys occur nowhere else in a document.- */+/** Strip reserved keys at every depth, covering both persisted widget shapes. */export const stripInstallationState = (projectDocument: Record<string, unknown>): Record<string, unknown> =>mapDocument(projectDocument, (key, value) => {if (INSTALLATION_STATE_KEYS.has(key)) {@@ -218,12 +157,7 @@ export interface ProjectAssetMappings {videos: ReadonlyMap<string, string>;}-/**- * Rewrite every asset reference in the document through the mapping for its- * kind. Names absent from their mapping are left alone, and subtrees with- * nothing to rewrite keep their identity, so empty mappings return the document- * unchanged.- */+/** Use kind-specific mappings; preserve unmapped names and unchanged subtree identity. */export const remapAssetRefs = (projectDocument: Record<string, unknown>,mappings: ProjectAssetMappings@@ -258,8 +192,7 @@ const readGalleryRecentImageName = (projectDocument: Record<string, unknown>): scontinue;}- // `recentImages` is persisted newest-first and bounded (see- // `getBoundedRecentImages`), so index 0 is the project's latest result.+ // recentImages must be newest-first for index zero to identify the latest result.for (const image of values.recentImages) {if (isRecord(image) && typeof image.imageName === 'string' && image.imageName !== '') {return image.imageName;@@ -300,11 +233,6 @@ const readTopmostCanvasImageName = (projectDocument: Record<string, unknown>): sreturn null;};-/**- * The image that best stands for this project: its newest generated result,- * falling back to the top-most canvas layer with pixels. `null` for a project- * that has neither, which is the permanent state for one that has produced- * nothing — `ProjectCover` renders a glyph for exactly that case.- */+/** Prefer the newest result, then the topmost raster, otherwise null. */export const selectCoverImageName = (projectDocument: Record<string, unknown>): string | null =>readGalleryRecentImageName(projectDocument) ?? readTopmostCanvasImageName(projectDocument);diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts b/invokeai/frontend/webv2/src/workbench/projects/projectDocument.tsindex b47ae33a1e..759a410f9b 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts@@ -2,18 +2,7 @@ import type { Project } from '@workbench/projectContracts';import { stripInfiniteWindowAnchor, stripSessionScopedGallerySearch } from '@features/gallery/contracts';-/**- * The project *document* codec: the wire and file shape of a project, and the- * migrations that heal older ones. It deliberately knows nothing about the- * Workbench reducer.- *- * Rehydrating a document into a live `Project` needs `loadWorkbenchProject`- * from the aggregate state module, which transitively owns generation graphs,- * widget state, and every policy the editor runs on. Keeping that step out of- * this module is what lets the Launchpad read, write, and shape-check project- * files without paying for the editor — see `deserializeProjectDocument` in- * `./syncedPersistence` for the rehydrating half.- */+/** Keep document codecs reducer-free; load rehydration lazily. */export const PROJECT_DOCUMENT_SCHEMA_VERSION = 2;export const PROJECT_DOCUMENT_MAX_BYTES = 32 * 1024 * 1024;@@ -145,20 +134,8 @@ const patchGalleryValues = (});/**- * Write the server's board id into a project document's gallery state.- *- * The server owns the project-to-board relationship; `projectBoardId` in the document is only a- * cache of it. Every path that learns the authoritative id — hydrating a record, creating a- * project, importing one, duplicating one, forking a conflicted one — comes through here, so there- * is one place that decides what "the project's board" means in a document.- *- * `selectBoard` distinguishes the two cases. A project the user is meeting for the first time- * should also be *pointed* at its board; one being re-hydrated should keep whatever destination- * the user last chose, which `getGallerySelectedBoardId` resolves separately.- *- * Both widget shapes are patched — the current `widgetInstances` map and the `widgetStates.gallery`- * one older builds wrote — and a document with neither is returned untouched rather than having a- * shape invented for it.+ * Cache the server-authoritative board ID in either persisted widget shape. selectBoard selects it on first open;+ * rehydration preserves the user's destination. Leave documents without gallery state untouched.*/export const applyAuthoritativeProjectBoard = (projectDocument: Record<string, unknown>,@@ -207,12 +184,7 @@ export const applyAuthoritativeProjectBoard = (return hasChanged ? next : projectDocument;};-/**- * The minimum a document must carry to be a project at all. A document that- * fails this can never rehydrate, so callers that only need to reject junk- * (an import picker, a file preview) can stop here instead of loading the- * reducer to find out.- */+/** Reject invalid document formats without eagerly loading the reducer. */export const isProjectDocumentShape = (data: Record<string, unknown>): boolean =>typeof data.id === 'string' &&typeof data.name === 'string' &&diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.tsindex 10a7684aad..60c57ea8da 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts@@ -12,12 +12,7 @@ import type * as persistenceModule from './syncedPersistence';import { ProjectCreateAbsentError } from './api';-/**- * The `.invk` workflow end to end: export writes an archive that import reads- * back, an imported project always lands under a fresh id so a file can never- * overwrite an existing project, and a file that is not ours is refused before- * anything reaches the server.- */+/** Verify fresh IDs, no overwrites, and format rejection before server mutation. */const api = vi.hoisted(() => ({createProjectSettled: vi.fn(),@@ -53,9 +48,6 @@ const transport = vi.hoisted(() => ({deleteArchiveImages: vi.fn(() => Promise.resolve()),deleteArchiveVideos: vi.fn(() => Promise.resolve()),deleteStagingBoard: vi.fn(() => Promise.resolve()),- // `Uint8Array | null` up front: a fetcher that returns `null` is how the- // "server would not serve it" path is exercised, and inferring the narrower- // type here would make that untypeable at the call site.fetchImageBytes: vi.fn((imageName: string): Promise<Uint8Array | null> =>Promise.resolve(new TextEncoder().encode(`bytes:${imageName}`))),@@ -91,9 +83,7 @@ vi.mock('./covers', async (importOriginal) => ({recordProjectCover: covers.recordProjectCover,}));vi.mock('@platform/browser/downloadBlob', () => downloads);-// Partial, so the module's pure predicates stay real. `isRequestCancellation` decides whether a-// failure is this asset's or the whole operation's — a stub of it would let the tests agree with a-// restore that mistook a cancelled import for three hundred dangling references.+// Preserve real cancellation predicates so cancellation cannot masquerade as missing assets.vi.mock('./invk/assetTransport', async (importOriginal) => ({...(await importOriginal<typeof assetTransportModule>()),...transport,@@ -170,8 +160,6 @@ const acceptCreate = (): void => {beforeEach(async () => {vi.resetModules();- // `resetAllMocks` restores the implementations the hoisted `vi.fn(impl)` factories declare, so- // the defaults do not need re-establishing here.vi.resetAllMocks();projectFile = await import('./projectFile');@@ -186,12 +174,7 @@ describe('exportOpenProject', () => {expect(downloads.downloadBlob.mock.calls[0]![1]).toBe('My project.invk');});- /**- * The transport is mocked by module path, and every assertion below about what- * did *not* reach the server is vacuous if that path stops resolving. This one- * fails loudly instead: a document with a known image reference must reach the- * mock on the way out.- */+ /** Include a positive transport probe so negative server-call assertions cannot pass vacuously. */it('reaches the server through the mocked transport', async () => {api.getProject.mockResolvedValue({data: {@@ -285,12 +268,7 @@ describe('exportLibraryProject', () => {expect(manifest.minimumCanvasSchemaVersion).toBe(4);});- /**- * This is reachable from a project card and from the gallery board menu, both of which can be on- * screen while the editor holds that project — and the board most likely to be right-clicked is- * the open project's own. Reading the server record without flushing first hands someone a file- * missing everything since the last autosave.- */+ /** Flush open projects before export to include unacknowledged edits. */it('flushes an open project before reading its record', async () => {const { registerOpenProject, unregisterOpenProject } = await import('./syncStore');const order: string[] = [];@@ -328,12 +306,7 @@ describe('exportLibraryProject', () => {expect(order).toEqual(['flush', 'get']);});- /**- * The record read below is the last one the server *acknowledged*, which is precisely what the- * flush exists to move past. A flush that resolved without landing is therefore indistinguishable- * from one that worked: the archive gets built from stale bytes and downloaded under a success- * toast, silently missing everything since the last successful autosave.- */+ /** Require an acknowledged flush before reading/exporting server bytes. */it('refuses to export a project whose flush never reached the server', async () => {const { registerOpenProject, unregisterOpenProject } = await import('./syncStore');@@ -371,11 +344,7 @@ describe('exportLibraryProject', () => {});});-/**- * Both directions can half-succeed, and both used to compute exactly what was- * lost and then discard it — so a project that shed forty layers looked like a- * clean round trip. These pin the reporting all the way out to the caller.- */+/** Partial-loss outcomes must reach callers. */describe('what a transfer reports', () => {const projectWithImages = () => {const project = createDraftProject([]);@@ -456,12 +425,7 @@ describe('what a transfer reports', () => {});});-/**- * The board half: an archive carries the project's board, and importing it gives that board's media- * new identities on a staging board the create then claims. Nothing here may reuse a name the- * destination already holds — `board_images` keys on the image name, so a reused name would move a- * stranger's picture onto this project's board instead of copying it.- */+/** Copy imported board media to fresh identities; adopting existing names would move another board's media. */describe('importing a project board', () => {const boardProject = () => {const project = createDraftProject([]);@@ -542,14 +506,9 @@ describe('importing a project board', () => {expect(uploadedBoardNames().sort()).toEqual(['shared.png', 'unreferenced.png']);});- /**- * The failure that must never bind to a stranger: on this server `shared.png` is taken, by the- * project this archive came from.- */it('forces an overlapping reference dangling when its board upload fails', async () => {acceptCreate();- // The destination has an image called `shared.png` — it is the source project's own. Falling- // back to that name would open the copy pointing at somebody else's picture.+ // Failed copies must not reuse existing source-owned names.transport.findExistingImageNames.mockImplementation((names: readonly string[]) => Promise.resolve(new Set(names)));transport.uploadBoardImage.mockImplementation((_bytes: Uint8Array, fileName: string) =>fileName === 'shared.png'@@ -672,12 +631,7 @@ describe('importProjectFile', () => {expect(createRequest.data.id).toBe(createRequest.project_id);});- /**- * Export strips installation state, so its own archives never carry it — but import must not- * rely on that. A legacy `.invokeproject.json`, a dev-build archive or a hand-edited one can all- * arrive with a stranger's gallery selection, and the collector skips those keys, so a restore- * can neither fetch what they point at nor report it as dangling.- */+ /** Strip installation state on import too; skipped references cannot be remapped or reported. */it('strips a stranger’s gallery selection from a document it did not write', async () => {acceptCreate();const envelope = {diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.tsindex 3ee592bb39..316e2d9dc3 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts@@ -55,25 +55,9 @@ export const parseProjectFile = (text: string): Record<string, unknown> | null =}};-/**- * Export and import a project as an `.invk` archive. This module is the workflow; `./invk` is the- * format.- *- * An imported document gets a fresh id, never the one in the file: two people exchanging a project- * would otherwise collide the moment both saved.- *- * The ZIP codec and the workbench reducer are both `await import()`ed. The Launchpad offers Import- * and Export on a route that never mounts the editor, and should not pay for either until someone- * picks a file.- */--/**- * How far along a project file is.- *- * `bundling` and `restoring` count assets; `packing` is the single ZIP write at- * the end, which has no unit worth counting and is reported so the caller can- * stop showing a number that has stopped moving.- */+/** Imports receive fresh IDs; ZIP and reducer dependencies remain lazy. */++/** Asset-count phases exclude ZIP packing. */export interface ProjectFileProgress {completed: number;phase: 'bundling' | 'packing' | 'restoring' | 'restoring-fonts';@@ -130,8 +114,7 @@ const exportProjectDocument = async (assertAccountScopeCurrent(owner);- // Enumerated before anything is planned, and fatal if it fails. An archive whose `board.json`- // silently said "empty" would be a lie the reader has no way to detect — worse than no archive.+ // Board enumeration failure must abort export rather than describe a falsely empty board.const snapshot = await getProjectBoardSnapshot(projectId, owner.signal);assertAccountScopeCurrent(owner);@@ -195,8 +178,7 @@ export const exportOpenProject = async (assertAccountScopeCurrent(owner);- // Preserve any higher compatibility floor already acknowledged by the server. Direct/offline- // exports fall back to what their live canvas demonstrably requires.+ // Use the acknowledged server compatibility floor; offline fallback uses live canvas requirements.const record = getOpenProject(project.id) ? await readAcknowledgedProject(project.id, owner) : null;const minimumCanvasSchemaVersion = Math.max(getProjectCanvasSchemaRequirement(document),@@ -206,14 +188,7 @@ export const exportOpenProject = async (return exportProjectDocument(project.name, project.id, document, minimumCanvasSchemaVersion, { ...options, owner });};-/**- * Import an `.invk` as a new server project: restore its media, rewrite every reference the server- * renamed, then create the project — claiming its staging board in the same request. Throws- * {@link InvkFormatError} so callers can translate the reason.- *- * Creating the project is the commit point; see {@link createStagingBoard}. A v2 archive or a- * legacy JSON document stages no board, and the server gives the new project an empty one.- */+/** Project creation commits remapped/staged media. Archives without board entries receive a new empty server board. */export const importProjectFile = async (file: File,options: ProjectFileOptions = {}@@ -239,14 +214,9 @@ export const importProjectFile = async (typeof projectDocument.name === 'string' && projectDocument.name.trim()? projectDocument.name.trim(): 'Imported project';- // Stripped on the way in as well as on the way out, so the rule holds for documents this app did- // not write: a legacy `.invokeproject.json`, an archive from a dev build, a hand-edited one. A- // stranger's `selectedImage`/`compareImage` would otherwise arrive intact and unfixable — the- // collector skips those keys, so the restore can neither fetch them nor report them as dangling.+ // Strip selection on import because skipped references cannot be restored or reported.const candidate = { ...stripInstallationState(projectDocument), id, name };- // Full validation rehydrates the document through the Workbench reducer, so- // it is loaded here rather than imported: the Launchpad should not carry the- // editor's aggregate state just to offer an Import button.+ // Validate through the reducer lazily to keep editor aggregates out of Launchpad imports.const { deserializeProjectDocument } = await import('./syncedPersistence');assertAccountScopeCurrent(owner);@@ -278,8 +248,7 @@ export const importProjectFile = async (assertAccountScopeCurrent(owner);- // Only an archive that actually carries board media needs somewhere to put it. An empty board is- // the server's to create, and staging one would be an unclaimed board to leak for no gain.+ // Create staging boards only when media needs one.const stagingBoardId =archive?.boardSnapshot && archive.boardSnapshot.items.length > 0? await (async () => {@@ -367,8 +336,7 @@ export const importProjectFile = async (return {boardItemIssues: restored?.boardItemIssues ?? [],documentReferenceIssues: restored?.documentReferenceIssues ?? [],- // The board the server says it claimed, not the one we asked it to: a project meeting its- // owner for the first time is also pointed at its board, which is what `selectBoard` means.+ // Bind the initial selection to the authoritative returned board ID, not the requested ID.record: {...record,data: applyAuthoritativeProjectBoard(record.data, record.board_id, { selectBoard: true }),@@ -383,8 +351,7 @@ export const importProjectFile = async (await restoreMedia.rollbackUnlessProjectExists(error, didCreateProject, owner, rollback);}}- // Reached through the lazily-loaded module, so a legacy JSON import still never pulls the- // restore engine into the graph — it has no media to undo.+ // Media-free legacy JSON imports do not load restore rollback.if (ledger !== null && restoreMedia !== null) {const rollback = () => restoreMedia.rollbackRestoredMedia(ledger, { signal: owner.signal });if (!didAttemptProjectCreate && isAccountScopeCurrent(owner)) {diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.tsindex 2e2eb14287..3abbfb1020 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts@@ -1,17 +1,7 @@import { InvkFormatError } from './invk/format';import { ProjectFlushError } from './projectFlush';-/**- * Turn a failed project-file read or write into something worth showing. `InvkFormatError` carries- * a `reason` rather than a message so the wording lives in the catalog and differs per failure: the- * fix for a legacy canvas project is not the fix for a corrupt archive.- *- * `direction` matters for the two reasons both halves raise. Telling someone their project "is too- * large to open" while they were exporting it names the wrong operation and the wrong file.- *- * `ProjectFlushError` is not a bad file but a project whose newest content never reached the- * server. Anything else already carries a message meant for people and passes through.- */+/** Localize failure reason and direction; flush errors are distinct from archive corruption. */export type ProjectFileDirection = 'read' | 'write';export const describeProjectFileError = (diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.tsindex 82726dc5a6..98678c1f59 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts@@ -2,13 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type * as toastsModule from './projectFileToasts';-/**- * What a project file says while it runs and when it stops.- *- * The two properties worth pinning are that it is *one* toast for the whole- * operation — a slow export must not stack a line per asset — and that a run- * which lost assets does not finish looking like a clean one.- */+/** Update one toast throughout the transfer; partial loss finishes as a warning. */interface ToastOptions {description?: string;@@ -60,10 +54,7 @@ describe('startProjectFileReport', () => {expect(toaster.update.mock.calls.every(([id]) => id === 'toast-1')).toBe(true);});- /**- * Progress arrives once per asset and a project can hold hundreds of them, during the phase- * already saturating the network. The first count shows at once; the rest coalesce.- */+ /** Show the first progress update immediately and coalesce subsequent per-asset updates. */it('redraws at most once per interval while assets settle', () => {vi.useFakeTimers();@@ -109,11 +100,7 @@ describe('startProjectFileReport', () => {}});- /**- * `succeed` runs before a caller's own follow-up work — the navigation after an import. A- * failure there is not a failure of the transfer, and saying so after it demonstrably worked is- * the worse lie.- */+ /** Navigation failure after transfer cannot change its successful verdict. */it('does not take back a verdict it has already given', () => {const report = toasts.startProjectFileReport(t, 'projects.importing');@@ -136,11 +123,7 @@ describe('startProjectFileReport', () => {);});- /**- * Losing a board result and losing a canvas layer are different sizes of problem, so one count- * cannot stand for both — and a project that lost forty layers must not read the same as one- * that lost none.- */+ /** Count missing board media separately from missing document references. */it.each([['nothing', [], [], { title: 'projects.exported', type: 'success' }],[diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.tsindex b067792d0a..4871ea0d29 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts@@ -5,38 +5,23 @@ import type { ProjectFileProgress } from './projectFile';import { describeProjectFileError, type ProjectFileDirection } from './projectFileErrors';-/**- * One live toast per transfer, updated in place. No progress bar: the countable unit is assets and- * the expensive one is bytes, so a bar drawn from the first would sit at 99% through the second.- *- * A lossy run settles as a warning naming the count, not a success — the person holding the file- * needs to know before they hand it to someone else.- */+/** Update one toast with asset counts, not byte progress; partial loss completes as a warning. *//** i18next's `t`, narrowed to what this module needs. */type Translate = (key: string, options?: Record<string, unknown>) => string;export interface ProjectFileReporter {- /**- * Take the toast down without a verdict, for the one case that has none: the- * account went away, so the operation belongs to a session that is over.- */+ /** Account loss dismisses the toast without a verdict. */dismiss: () => void;/** Update the live toast from a transfer's progress. */report: (progress: ProjectFileProgress) => void;- /**- * Board items and document references are counted apart: a missing board item is a result still- * findable elsewhere, a missing document reference is a hole in the canvas.- */+ /** Count missing board media separately from missing document references. */succeed: (title: string, issues: ProjectTransferIssues) => void;/** Finish as a failure, translating an `InvkFormatError` reason where there is one. */fail: (title: string, error: unknown) => void;}-/**- * The reasons that mean the media is *not here*. `star-failed` is excluded: the item arrived, it- * just did not get its star back, and counting it would report lost media when nothing was lost.- */+/** Exclude star-failed from missing-media counts because the bytes arrived. */const MISSING_REASONS: ReadonlySet<InvkMediaIssueReason> = new Set(['fetch-failed', 'missing-entry', 'upload-failed']);const countIssues = (issues: ProjectTransferIssues) => ({@@ -62,9 +47,8 @@ const describeProgress = (t: Translate, progress: ProjectFileProgress): string =const PROGRESS_REDRAW_INTERVAL_MS = 200;/**- * Open the live toast. The reporter owns it for the rest of the operation — every path through a- * caller's `try`/`catch` must end in `succeed` or `fail`, or the toast stays up. `direction` words- * the failure: the same `too-large` reason arises from opening a file and from exporting one.+ * Every reporter path must finalize the toast. Direction determines failure wording; account cancellation+ * dismisses without a verdict.*/export const startProjectFileReport = (t: Translate,@@ -72,8 +56,7 @@ export const startProjectFileReport = (direction: ProjectFileDirection = 'read'): ProjectFileReporter => {const id = toaster.create({- // No duration: a transfer ends when it ends, and a toast that expired- // mid-export would leave the operation invisible again.+ // Keep the toast alive until the operation completes.duration: Number.POSITIVE_INFINITY,title,type: 'loading',@@ -104,9 +87,7 @@ export const startProjectFileReport = (toaster.dismiss(id);},fail: (failureTitle, error) => {- // A verdict is not taken back. `succeed` runs before the caller's own follow-up work — the- // navigation after an import, say — and a failure there is not a failure of the transfer:- // telling someone their import failed after it demonstrably worked is the worse lie.+ // Success is final even if follow-up navigation fails.if (isSettled) {return;}@@ -126,8 +107,7 @@ export const startProjectFileReport = (return;}- // Leading edge, then trailing: the first count appears at once, and whatever the latest is- // when the interval expires replaces it.+ // Publish the leading update immediately and retain the latest trailing count.toaster.update(id, { description: pendingDescription });pendingDescription = null;redrawTimer = setTimeout(() => {@@ -148,8 +128,7 @@ export const startProjectFileReport = (return;}- // Counts, never names: a project can lose hundreds of assets at once, and a toast listing- // them would be unreadable. The typed detail stays on the outcome for anything that needs it.+ // Keep toasts bounded to counts; detailed losses remain on the outcome.const parts = [...(boardItems === 0 ? [] : [t('projects.file.missingBoardItems', { count: boardItems })]),...(documentReferences === 0 ? [] : [t('projects.file.missingReferences', { count: documentReferences })]),diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFlush.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFlush.tsindex 8ddc23e534..7346b782a3 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFlush.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFlush.ts@@ -1,12 +1,6 @@/**- * What a push to the server actually achieved, as distinct from whether the call threw.- *- * Its own module rather than part of the sync engine: the caller that needs it, `library.ts`, is a- * module the sync engine itself imports, so reaching back would be a cycle.- *- * A push swallows every failure because they are all recoverable — the document is cached and the- * next save retries. But "recoverable" is not "done", and reading a project back after an- * unacknowledged push is how an export ships someone's work minus the last ten minutes of it.+ * Nonthrowing completion does not imply acknowledgement. This standalone outcome type avoids a library/sync+ * dependency cycle.*//** The document the push was carrying, so a caller can compare it with what the engine recorded. */@@ -30,10 +24,7 @@ export type ProjectSchemaRefusal =export type ProjectPushOutcome =/** The server holds exactly this document. */| ({ kind: 'acknowledged' } & ProjectPushOutcomeBase)- /**- * This project id no longer holds our document: it was deleted or overwritten elsewhere, and the- * local edits continue under a different id. Reading the id back would read a stranger's version.- */+ /** After identity supersession, a server reread could return another document. */| ({ kind: 'superseded' } & ProjectPushOutcomeBase)/** A newer client raised the project's compatibility floor. Local bytes remain cached. */| ({ kind: 'schema-refused'; refusal: ProjectSchemaRefusal } & ProjectPushOutcomeBase)diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.tsindex 03feefba30..a3b271a25a 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts@@ -251,11 +251,7 @@ describe('renameProject', () => {});});-/**- * SQLite owns which board belongs to which project; the document only caches it. This is the one- * place that writes that cache, so every path — hydration, create, import, duplicate, fork —- * agrees on what "the project's board" means.- */+/** Synchronize the document's board cache from server-authoritative IDs. */describe('applyAuthoritativeProjectBoard', () => {const galleryDocument = (values: Record<string, unknown>): Record<string, unknown> => ({widgetInstances: {diff --git a/invokeai/frontend/webv2/src/workbench/projects/session.ts b/invokeai/frontend/webv2/src/workbench/projects/session.tsindex dcdf07d483..a7bbb22e29 100644--- a/invokeai/frontend/webv2/src/workbench/projects/session.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/session.ts@@ -8,23 +8,13 @@ import type { ProjectDraftStore } from './draftStore';import { getClientStateValue, setClientStateValue } from './api';-/**- * The per-user session blob in the client-state KV: which projects are open as tabs and which is- * active, plus a legacy account snapshot. Settings live in `settings.ts` so Home can load them- * without mounting the workbench provider.- *- * An `undefined` `openProjectIds` means "unknown — open every project", which is what the versions- * predating the library/session split did, so old sessions migrate without visible change.- */+/** Session tabs are separate from settings; legacy undefined openProjectIds means unknown/open-all. */export const SESSION_STATE_KEY = 'webv2:workbench-account';/**- * Search params understood by the /app route: `project` deep-links a library- * project into the session; `new` opens the editor with a fresh draft, and- * `intent` or `preset` says how that draft should be arranged (see- * `launchpad/intents`). `preset` names the arrangement outright and wins over- * the one an intent implies.+ * project opens a library project; new creates a draft. An explicit preset overrides the arrangement implied by+ * intent.*/export interface WorkbenchSearch {new?: true;@@ -163,11 +153,7 @@ const listDurableRecoveryProjectIds = async (): Promise<DurableRecoveryProjectId}};-/**- * Take a deleted project out of the saved session, which the `/app` guard and the Launchpad's- * "open" grouping read. Best-effort and silent: the deletion has already happened, and failing to- * tidy up after it is not a reason to say the project was not deleted.- */+/** Session cleanup is best-effort after committed deletion and cannot change its verdict. */export const pruneSessionProject = async (projectId: string, signal?: AbortSignal): Promise<void> => {try {const blob = await fetchSessionBlob(signal);diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts b/invokeai/frontend/webv2/src/workbench/projects/syncStore.tsindex 34ba4d655b..fb05444a4d 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts@@ -3,19 +3,7 @@ import { createExternalStore } from '@platform/state/externalStore';import type { ProjectPushOutcome, ProjectSchemaRefusal } from './projectFlush';-/**- * The bridge between the project sync layer and everything outside the editor.- * {@link ProjectSyncSnapshot} is a read-only window for shell surfaces; {@link OpenProjectHandle}- * is the other direction.- *- * ### One invariant, replacing three races- *- * A project the workbench holds is mutated only through the sync engine; every other project over- * HTTP. Unconditional GET-and-PUT meant renaming an open project forked it into a conflict copy,- * duplicating one copied what the server last acknowledged rather than what was on screen, and- * deleting one raced the autosave about to recreate it. Now that a board commits with its project's- * name, a stray write renames the board too.- */+/** Only the sync engine mutates open projects; closed projects use HTTP. */export interface ProjectSyncInfo {/** Server revision the next save is based on; null = never reached the server. */@@ -57,34 +45,17 @@ registerAccountOwnedResource({name: 'project-sync',});-/**- * What a mounted editor can do to a project it holds, for callers that are not the editor.- *- * Every method routes through the workbench reducer or the sync engine, so the project's document,- * its revision chain and its board stay in step. The handle exists only while the project is open;- * `getOpenProject` returning `null` is the signal to go over HTTP instead.- */+/** Registered handles own open-project revisions and board state for their lifetime; null permits HTTP fallback. */export interface OpenProjectHandle {/** Close the tab, after the project has been deleted on the server. */close: () => void;/** Delete through the sync engine's mutation queue so in-flight saves finish first. */deleteOnServer: () => Promise<void>;- /**- * Push the live document, and report whether the server actually took it.- *- * Deliberately an outcome rather than a rejection. A push that did not land is recoverable — the- * document is cached and the next save retries — so a rename or a closing tab is right to ignore- * it. A caller about to read the project back from the server is not: see `assertProjectFlushed`.- */+ /** Flush returns an acknowledgement outcome; callers reading server bytes must assert success. */flush: () => Promise<ProjectPushOutcome>;/** Stop the autosave from recreating this project while it is being deleted. */markDeleted: () => void;- /**- * Undo {@link markDeleted} after a deletion that did not happen.- *- * Paired with it here rather than left to call sites, because a project left marked never- * autosaves again for the rest of the session — a silent, unrecoverable failure to notice.- */+ /** Unmark failed deletes so autosave can resume. */unmarkDeleted: () => void;/** Rename through the reducer, then flush — so the project and its board rename together. */rename: (name: string) => Promise<void>;diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.tsindex 26deb66ab7..109524b45a 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts@@ -25,18 +25,8 @@ import { describeRefusedProject } from './projectLoadRefusal';const CLOSE_FLUSH_ATTEMPTS = 3;/**- * 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- * Home — an editor with no documents is the Home screen.- * - Delete removes the project from the server (the only path that does, for- * open projects) and then closes its tab.+ * Open reuses or hydrates a project. Close flushes while preserving the server record; closing the last tab+ * returns Home. Delete removes the server project.*/export const useProjectActions = (): {closeProject: (project: Project) => void;diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.tsindex 27701e7811..6b2047ead7 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts@@ -20,14 +20,7 @@ import { duplicateLibraryProject } from './library';import { exportLibraryProject, exportOpenProject, importProjectFile, pickProjectFile } from './projectFile';import { startProjectFileReport } from './projectFileToasts';-/**- * Picking, importing and exporting a project file, with the reporting attached.- *- * Five surfaces offer these, and each had its own copy of the scope capture, picker, try/catch and- * toast — which had already drifted. One sequence is what makes progress and partial-success- * reporting land on all five at once. Only what happens with the imported record differs, and that- * is the callback.- */+/** Share the scoped transfer and reporting lifecycle across callers. *//** Runs the sequence, keeping the toast and the account scope in step. */const runReported = async <T>(@@ -41,9 +34,7 @@ const runReported = async <T>(try {await run(report, owner);} catch (error) {- // An operation cancelled by the account going away failed on purpose, and- // its error is written for a developer. There is no verdict to show,- // because there is no longer anyone the verdict is about.+ // Account-cancellation errors stay silent because the operation no longer belongs to the active session.if (!isAccountScopeCurrent(owner)) {report.dismiss();@@ -54,10 +45,7 @@ const runReported = async <T>(}};-/**- * Import from the file picker. Resolves without doing anything if the picker is- * dismissed — no toast is opened for a decision not to import.- */+/** Picker dismissal resolves without work or a toast. */export const useImportProjectFile = (onImported: (record: ProjectRecordDTO) => Promise<void> | void): (() => void) => {const { t } = useTranslation();const { requestReferencesOnlyImport } = useProjectFileOptions();@@ -127,13 +115,7 @@ export const useExportLibraryProject = (): ((projectId: string, name: string) =>);};-/**- * Duplicate a project, reported like the transfers it shares its engine with.- *- * Duplication is a project file operation in everything but the file: same restore, same partial- * success, same durations. It reported none of that — no progress for the whole server-side copy,- * and `InvkFormatError`'s developer message straight into a toast on failure.- */+/** Duplication shares transfer progress and partial-success reporting. */export const useDuplicateProject = (onDuplicated?: (duplicated: DuplicatedProject) => Promise<void> | void): ((projectId: string) => void) => {@@ -146,8 +128,7 @@ export const useDuplicateProject = ({ direction: 'write', failed: t('projects.duplicateFailed'), running: t('projects.duplicating') },async (report, owner) => {const duplicated = await duplicateLibraryProject(projectId, {- // Everything a duplication moves is restored onto the copy's board, so the phase is- // fixed. Naming it here keeps the reporting vocabulary in the reporting layer.+ // Duplication uses the restore phase; this owner defines its reporting vocabulary.onProgress: ({ completed, total }) => report.report({ completed, phase: 'restoring', total }),owner,});diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsxindex ba7077031f..a4d1f3ca8c 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx@@ -8,11 +8,6 @@ import { FileTextIcon, WandSparklesIcon } from 'lucide-react';import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';-/**- * Per-item actions for the RECENT details panel. Recall lives in the image- * context menu and the Details rows, not in a button row here. "View JSON"- * opens the raw queue item in a dialog.- */export const QueueItemActions = ({ item }: { item: QueueItemReadModel }) => {const { t } = useTranslation();const notify = useNotify();diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueProgressRail.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueProgressRail.browser.test.tsxindex 56059e9a63..27c2286769 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueProgressRail.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueProgressRail.browser.test.tsx@@ -6,10 +6,8 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';/**- * The rail is shared between the top bar and the floating preview window, so- * its show/hide rules are pinned here once: hidden with nothing in flight or- * the backend away, a sweep while the running item has reported no step yet,- * a determinate fill once it has.+ * Share rail visibility/progress coverage across topbar and floating Preview: offline/idle hides, unstepped runs+ * sweep, stepped runs fill.*/const state = vi.hoisted(() => ({diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueProgressRail.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueProgressRail.tsxindex 4e8c14eea1..56f8c82628 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueProgressRail.tsx+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueProgressRail.tsx@@ -14,18 +14,8 @@ import { useActiveProjectSelector, useWorkbenchSelector } from '@workbench/Workbimport { useMemo } from 'react';/**- * The generation progress rail: one accent-colored segment per running- * session, sweeping while indeterminate, hidden while nothing is in flight or- * the backend is away. The top bar pins it along its bottom edge- * (`TopbarProgressRail`); the floating preview window pins it under its title- * bar. Placement is the caller's — this component owns only the model and the- * fills, so the two surfaces cannot drift on when they show or what they show.- *- * Sessions divide the width instead of stacking — a hairline cannot stack to- * four GPUs without growing into the content or dropping below visibility.- *- * Not exposed to assistive tech: the queue cluster already owns a throttled- * live region, and a second announcer would double the chatter.+ * Share progress fills across hosts; callers own placement. Divide width among sessions, hide offline/idle, and+ * leave announcements to the queue's throttled live region.*/export const QueueProgressRail = ({ css }: { css: SystemStyleObject }) => {const queueItems = useActiveProjectSelector((project) => project.queue.items);@@ -72,8 +62,6 @@ const DETERMINATE_SX: SystemStyleObject = {transition: 'width var(--wb-motion-duration-fast) linear',};-// Reuses Chakra's built-in `position` keyframe, the same one its own-// indeterminate Progress range animates on.const INDETERMINATE_SX: SystemStyleObject = {'--animate-from-x': '-45%','--animate-to-x': '100%',@@ -82,10 +70,7 @@ const INDETERMINATE_SX: SystemStyleObject = {insetBlock: 0,minWidth: '45%',position: 'absolute',- // With motion off there is no sweep to fall back on, so the segment becomes a- // quiet static fill: still "something is running", minus the movement. Spelled- // as a raw selector because the `_reduceMotion` condition this repo defines is- // only typed inside token values, not in style objects.+ // Reduced motion uses a static fill; use the raw selector because _reduceMotion is typed only in token values.':root[data-reduce-motion=true] &': {animation: 'none',backgroundImage: 'none',diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.tsindex 384e383ae1..084e5b16aa 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts@@ -112,9 +112,7 @@ describe('buildQueueRecallValues', () => {).toBeNull();});- // A snapshot is the other story: it stores the prompt as *authored*, so the- // template that shaped it has to come back too. Recalling `a cat` and dropping- // `Cinematic` silently generated something other than the item recalled from.+ // Snapshots store authored prompts, so recall must restore their template too.it('recalls the snapshot`s own template alongside its authored prompt', () => {const promptTemplate = { id: 't1', name: 'Cinematic', negativePrompt: '', positivePrompt: '{prompt}, cinematic' };const snapshot = makeValues({ positivePrompt: 'a cat', promptTemplate });diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.tsindex 384e0b42bb..3f445c45f4 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts@@ -6,11 +6,8 @@ import type { ImageRecallCapabilities, ImageRecallKind } from '@workbench/image-import { cloneVideoWidgetValues } from '@features/video';/**- * Snapshot/session-based recall for queue items, mirroring the image-metadata- * recall semantics: partial kinds merge the recalled fields into the CURRENT- * generate form values; `all`/`remix` replace them with the submission- * snapshot. Items this client submitted carry the full snapshot; foreign items- * still expose prompts + the actual executed seed via the session meta.+ * Partial recall merges current values; all/remix restores the submission snapshot. Foreign items expose only+ * session prompts and executed seed.*/export const getQueueRecallCapabilities = (@@ -75,15 +72,8 @@ export const buildQueueRecallValues = (return {...current,positivePrompt,- // The two sources disagree about what they hold, so the template has to- // follow whichever one the prompt came from. A snapshot stores the text as- // authored, alongside the template that shaped it — recalling the text and- // dropping the template would quietly generate something else. The session- // metadata has no snapshot and carries the merged prompt outright, so- // there the current template has to go or it would wrap it a second time.- //- // Older recall snapshots may predate prompt templates and must not recall- // `undefined` into the current settings.+ // Restore templates with authored snapshot prompts; clear templates for already-merged session prompts to+ // avoid double wrapping. Older snapshots must not write undefined templates.promptTemplate: snapshot ? (snapshot.promptTemplate ?? null) : null,...(negativePrompt !== undefined? { negativePrompt, negativePromptEnabled: snapshot?.negativePromptEnabled ?? negativePrompt.length > 0 }@@ -141,14 +131,8 @@ export const buildVideoQueueRecallPatch = (return {positivePrompt: meta.positivePrompt,- // Session meta cannot distinguish "no negative recorded" from "negative- // disabled, submitted as ''", so an absent or empty negative leaves the- // toggle exactly as the user has it rather than flipping it off. This- // matches the gallery-side video recall for Wan. MiniMax H3 differs:- // it never wires a negative into its metadata, so gallery recall sees- // nothing, while the batch still records the field and we recall it —- // harmless, since H3's panel hides the negative and the value restored- // is the one the panel already held.+ // Absent/empty session negatives cannot identify disabled state, so preserve the toggle. H3 batch negatives+ // may recall harmless hidden values absent from gallery metadata....(meta.negativePrompt !== undefined && meta.negativePrompt.length > 0? { negativePrompt: meta.negativePrompt, negativePromptEnabled: true }: {}),@@ -164,11 +148,8 @@ export const buildVideoQueueRecallPatch = (};/**- * Which panel a queue-item recall targets, and what to write there. A- * discriminated union rather than a caller-side `if`: the two panels take- * different payloads (Video a partial patch, Generate a whole values object),- * so a caller that forgets a branch fails to compile instead of silently- * recalling into the wrong panel — which is exactly the bug this replaced.+ * Discriminate Video patches from complete Generate values so callers must handle the correct destination+ * contract.*/export type QueueRecallPlan =| { target: 'generate'; values: GenerateWidgetValues }diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useActiveQueueProgress.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/useActiveQueueProgress.tsindex 7fb7e6fca6..d7f3a50d48 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/useActiveQueueProgress.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useActiveQueueProgress.ts@@ -2,12 +2,7 @@ import { getQueueSummary } from '@features/queue/contracts';import { useQueueItemProgress } from '@features/queue/react';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';-/**- * The one pairing every aggregate progress surface needs: the active project's- * queue summary plus the running item's live progress. Extracted because four- * chrome surfaces (Invoke button, tab title, queue cluster, queue-status chip)- * had copies that could — and did — drift on edge-case handling.- */+/** Pair active-project queue summaries with live item progress for consistent chrome surfaces. */export const useActiveQueueProgress = () => {const queueItems = useActiveProjectSelector((project) => project.queue.items);const baseSummary = getQueueSummary(queueItems);diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.tsindex 89195fe2a0..29940a4688 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts@@ -22,12 +22,8 @@ import { useLocalRecallSnapshot } from './useLocalRecallSnapshot';const selectGenerateRecallValues = createGenerateFormValuesSelector();/**- * Recall for a queue item by origin, shared by every surface that offers it- * (the Recent details panel, staged canvas results). Items this client- * submitted recall from the exact submission snapshot; foreign items still- * offer prompts + the executed seed from `meta`. Recalls write to the ACTIVE- * project — "recall" means "load this into the panel I am looking at" — and- * reveal the panel they wrote to.+ * Recall local submission snapshots or foreign session prompts/seed into the active project, then reveal the+ * destination panel.*/export const useQueueItemRecall = (origin: string | null | undefined,@@ -68,9 +64,7 @@ export const useQueueItemRecall = (const plan = planQueueRecall(kind, { current, isVideoItem, meta, snapshot: localGenerateValues, videoSnapshot });if (!plan) {- // The Generate copy names a missing Generate model, which is not why a video recall- // would come back empty -- nor why a fresh project cannot be initialised without the- // capability table.+ // Use a generic unavailable reason: Video and missing capabilities are not missing Generate models.const reason = isVideoItem? 'widgets.queue.recallUnavailableForItem': !current && !hasArchitectureCapabilities()diff --git a/invokeai/frontend/webv2/src/workbench/settings/AboutSettings.tsx b/invokeai/frontend/webv2/src/workbench/settings/AboutSettings.tsxindex bd86f1a3ad..9d43dfc4d6 100644--- a/invokeai/frontend/webv2/src/workbench/settings/AboutSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/AboutSettings.tsx@@ -11,12 +11,6 @@ import { refreshAboutInfo, useAboutInfo } from './aboutInfoStore';const GITHUB_URL = 'https://github.com/invoke-ai/InvokeAI';const DISCORD_URL = 'https://discord.gg/ZmtBAhwWhy';-/**- * The legacy About modal's content as a settings section: the server's- * version, the community links, and the full system-information blob- * (installed dependency versions plus, for admins, the redacted runtime- * config) as copyable JSON.- */export const AboutSettings = () => {const { t } = useTranslation();const { canManageAppConfig } = useCapabilities();diff --git a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsxindex dfb7e1fd70..6303410270 100644--- a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx@@ -240,8 +240,7 @@ const CustomSettingField = ({ field }: SettingFieldProps) => {editor = <GenerationDevicesSettings />;break;case 'hotkeys':- // The hotkey editor owns its heading; its virtual list takes the height- // the dialog hands a `fill` entry (see `isFillSettingsEntry`).+ // The hotkey editor owns its heading and fills the dialog's allocated height.return (<Box display="flex" flex="1" flexDirection="column" minH="0"><HotkeysSettingsSection />diff --git a/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.browser.test.tsxindex b4d2f31b5d..ee3fb3bbed 100644--- a/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.browser.test.tsx@@ -89,8 +89,7 @@ describe('GenerationDevicesSettings', () => {it('explains that parallel generation needs more than one accelerator on a single-device box', async () => {await render({ options: [{ device: 'cuda:0', name: 'RTX 5090' }] });- // This machine's real configuration: one GPU, `auto`. No switches should appear,- // because there is nothing to choose between.+ // One GPU in auto mode has no device choice to expose.expect(host?.textContent).toContain('RTX 5090');expect(host?.textContent).toContain('needs more than one accelerator');expect(host?.querySelectorAll('input[type="checkbox"]')).toHaveLength(0);@@ -150,9 +149,7 @@ describe('GenerationDevicesSettings', () => {it('refuses to deselect the last GPU rather than letting the server 422', async () => {await render({ options: TWO_GPUS, setting: ['cuda:1'] });- // Index 0 is the auto switch; the per-device switches follow in device order, so- // index 2 is cuda:1 — the only selected device. Turning it off would write an- // empty list, which the backend rejects and which would fail the next startup.+ // Disabling the last selected device would persist an empty list rejected by the backend and startup.await act(() => userEvent.click(switchControls()[2]!));expect(mocks.updateGenerationDevices).not.toHaveBeenCalled();diff --git a/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.tsx b/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.tsxindex e7ad0bee5f..8e8e80273c 100644--- a/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.tsx@@ -12,13 +12,7 @@ import { useMountEffect } from '@platform/react/useMountEffect';import { ModifiedSettingIndicator } from '@platform/ui/settings/ModifiedSettingIndicator';import { useCallback, useMemo, useState } from 'react';-/**- * Which accelerators the server uses for generation (`generation_devices`).- *- * Server-wide app config rather than a user preference, so it is admin-only and only- * takes effect after a restart — both of which the copy states plainly instead of- * pretending the change is live.- */+/** Generation devices are admin-only server configuration and take effect after restart. */export const GenerationDevicesSettings = () => {const { canManageAppConfig } = useCapabilities();const { error, loadState, options, setting } = useGenerationDevices();@@ -154,10 +148,6 @@ export const GenerationDevicesSettings = () => {);};-/**- * One device's switch. Binds the device to the shared handler in its own scope so the- * list does not create a fresh callback per row on every render.- */const DeviceToggle = ({checked,device,diff --git a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.browser.test.tsxindex 4130975708..ca7b7fc86d 100644--- a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.browser.test.tsx@@ -190,9 +190,7 @@ describe('ImageMapVocabularySettings', () => {});it('explains that the rebuild is queued behind image indexing', async () => {- // The rebuild runs on the index worker only once it has no images left to- // embed, so during a backfill the spinner can stand for as long as the- // backfill does. Without the counts it reads as a hang.+ // Show indexing counts because vocabulary rebuild waits behind the entire image backfill.mocks.indexCounts = { embedded: 1204, failed: 0, pending: 16846, total: 18050 };await render({ state: 'building', terms: ['zebra'] });diff --git a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsxindex 5439de0622..364801838d 100644--- a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx@@ -16,19 +16,10 @@ import { PlusIcon } from 'lucide-react';import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';-/**- * How often the index counts are re-read while a rebuild is queued behind one.- * Coarse on purpose: it only feeds a "waiting for indexing" line, and the- * backend pushes `image_index_status` per batch anyway — this exists so the- * line is right when the panel is opened mid-run with no event due.- */+/** Coarse polling fills gaps when opening mid-indexing before the next pushed status batch. */const INDEX_STATUS_POLL_MS = 5_000;-/**- * Normalize one draft entry the way the server will, so the chips a save adds- * are exactly the chips that come back. Splitting on commas and newlines makes- * a pasted list import in one keystroke.- */+/** Match server normalization; split pasted comma/newline lists into entries. */const parseDraft = (draft: string): string[] => {const seen = new Set<string>();const terms: string[] = [];@@ -48,12 +39,8 @@ const parseDraft = (draft: string): string[] => {};/**- * Editor for the supplementary cluster-label vocabulary. Each add/remove- * persists immediately (the whole list is replaced server-side); after a save- * the server rebuilds the label embeddings in the background, so the query- * polls while that runs to keep the status line honest. Re-fetching an open- * map's labels when the rebuild lands is NOT this component's job — the data- * module's watcher does it, because the dialog may well be closed by then.+ * Persist whole vocabulary lists immediately and poll rebuild status. The data watcher refreshes map labels even+ * after this dialog closes.*/export const ImageMapVocabularySettings = () => {const { t } = useTranslation();@@ -67,9 +54,7 @@ export const ImageMapVocabularySettings = () => {const [inputError, setInputError] = useState<string | null>(null);const [saveError, setSaveError] = useState<string | null>(null);const { isBusy: isSaving, run } = useScopedAction();- // The rebuild runs on the index worker, which services it only once it has- // no images left to embed — so during a backfill the spinner can stand for- // as long as the backfill does. The counts turn that into a stated wait.+ // Show indexing counts while vocabulary rebuild waits behind image embedding.const indexCounts = imageMapStore.useSelector((snapshot) => snapshot.indexCounts);const isBuilding = query.data?.state === 'building';@@ -92,11 +77,8 @@ export const ImageMapVocabularySettings = () => {const updated = await updateImageMapVocab(nextTerms);assertAccountScopeCurrent(owner);- // Cancel first: a poll that was issued before the PUT can resolve- // after it, and TanStack Query would write that older list over the- // response — resurrecting a removed chip and, worse, overwriting- // 'building' with a stale 'ready' so the status line goes quiet while- // the server is still rebuilding.+ // Cancel pre-save polls so stale responses cannot resurrect removed entries or replace building with+ // ready.await queryClient.cancelQueries({ queryKey: imageMapVocabKeys.all });assertAccountScopeCurrent(owner);queryClient.setQueryData(imageMapVocabKeys.all, updated);@@ -283,14 +265,8 @@ const VocabularyStatusLine = ({vocab: ImageMapVocab;}) => {const { t } = useTranslation();- // Embedding a handful of terms takes seconds; a wait longer than that means- // the rebuild is queued behind image indexing, not running slowly. Saying- // which is the difference between "working" and "hung".- //- // No age is passed, so no "no progress reported for N" note: that needs a- // clock ticking in render, which the compiler rightly refuses, and the whole- // stall treatment already exists on the map widget where the counts live. A- // stalled index shows up here as a number that stops moving.+ // Explain that rebuild waits behind indexing. Omit age-based stall text here; the map owns the ticking stall+ // display.const progress = isIndexing(indexCounts) ? describeIndexProgress(indexCounts) : null;return (diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsButton.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsButton.tsxindex 1a378455c9..209544ed5b 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsButton.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsButton.tsx@@ -8,9 +8,8 @@ import { openWorkbenchSettings } from './settingsDialogStore';const handleOpen = () => openWorkbenchSettings();/**- * 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.+ * Launchpad settings entry; the workbench opens settings from its app menu and hosts {@link SettingsDialogHost}+ * separately.*/export const SettingsButton = () => {return (diff --git a/invokeai/frontend/webv2/src/workbench/settings/aboutInfoStore.ts b/invokeai/frontend/webv2/src/workbench/settings/aboutInfoStore.tsindex 08b0165c1e..c6fc57c0ff 100644--- a/invokeai/frontend/webv2/src/workbench/settings/aboutInfoStore.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/aboutInfoStore.ts@@ -6,12 +6,7 @@ import {import { createExternalStore } from '@platform/state/externalStore';import { apiFetchJson, getApiErrorMessage } from '@platform/transport/http';-/**- * System information for the settings About section: the server's version and- * its installed dependency versions (with the synthesized `CUDA` entry), plus- * — for admins — the redacted runtime config, mirroring the legacy About- * modal's blob. Pull-based: nothing here changes without a server restart.- */+/** Pull server/dependency versions and admin-only redacted runtime config; these change only after restart. */export interface AboutInfoSnapshot {/** The server's app version, or null while unknown. */diff --git a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts b/invokeai/frontend/webv2/src/workbench/settings/contracts.tsindex cfa01d2a75..6496144fc5 100644--- a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts@@ -9,30 +9,19 @@ export type { ProjectSortId, ProjectsViewId } from '@workbench/launchpad/projectexport type { WorkbenchLanguage } from '@platform/i18n/languages';/**- * Settings that belong to the *project* and therefore travel inside its `.invk`- * export. Anything describing how a person likes to work — as opposed to how- * this document generates — belongs in {@link WorkbenchPreferences} instead, so- * that opening someone else's project cannot rewrite your editor.+ * Export document generation settings with the project; personal editor choices belong in {@link+ * WorkbenchPreferences} so imports cannot overwrite them.*/export interface ProjectSettings {useCpuNoise: boolean;antialiasProgressImages: boolean;- /**- * Not surfaced in the Settings dialog: the Preview widget's header owns this- * as a live toggle, and following a generation flips it implicitly. It is- * persisted per project because that is the lifetime the toggle expects.- */+ /** Preview owns this live toggle; persist it per project rather than exposing it in Settings. */showProgressImagesInViewer: boolean;}/**- * A saved conditioning-rebalance curve as it is persisted.- *- * Structurally the feature's `RebalancePreset`, declared here rather than imported:- * these preferences load on the launchpad route, and a value import from- * `@features/generation` would pull that feature's whole core into the initial bundle.- * Settings stores the record; the generation feature owns what `weights` means and- * re-validates it on read.+ * Store the RebalancePreset shape locally to keep generation out of Launchpad's bundle. Generation owns and+ * revalidates weights on read.*/export interface StoredRebalancePreset {id: string;diff --git a/invokeai/frontend/webv2/src/workbench/settings/index.ts b/invokeai/frontend/webv2/src/workbench/settings/index.tsindex 589612d6e7..04286b5f18 100644--- a/invokeai/frontend/webv2/src/workbench/settings/index.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/index.ts@@ -1,6 +1,4 @@-// The dialog body is deliberately absent: it is reached only through-// `SettingsButton`'s lazy import, and re-exporting it here would make every-// barrel consumer load it eagerly.+// Keep the dialog body out of this barrel to preserve lazy loading.export * from './SettingsButton';export * from './settingsDialogStore';export * from './store';diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.tsindex 502918b9ea..2a34b4c719 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts@@ -6,9 +6,8 @@ import type { ProjectSettings } from './contracts';import type * as storeModule from './store';/**- * The settings store's load/patch contract: backend-first with legacy- * migration, resolved once per account scope, and offline edits replay- * instead of being reverted by a stale server copy.+ * Verify backend-first loading, legacy migration, per-account resolution, and offline-edit replay over stale+ * server state.*/const api = vi.hoisted(() => {@@ -348,10 +347,8 @@ describe('normalizeProjectSettings', () => {});/**- * Prompt highlighting and attention style used to be project settings. They- * are per-user preferences now, and a document written by an older build- * still carries them — normalizing must not let them back in, or importing- * someone else's project would rewrite the reader's editor.+ * Discard legacy project highlighting/attention settings so imports cannot overwrite personal editor+ * preferences.*/it('drops prompt preferences that older documents still carry in project settings', () => {const normalized = store.normalizeProjectSettings({diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex cbc9307879..54c90dcc36 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -147,12 +147,7 @@ const normalizeDeveloperLogNamespaces = (values: unknown): DeveloperLogNamespacereturn DEVELOPER_LOG_NAMESPACES.filter((namespace) => enabled.has(namespace));};-/**- * Guards for the Launchpad library's view state. Deliberately local rather- * than imported from the Launchpad: these settings load on every route, and a- * value import would put launchpad view code in the editor's bundle too. The- * types come from `contracts`, which is type-only and therefore free.- */+/** Keep view guards local so shared settings do not pull Launchpad code into the editor bundle. */const isProjectsViewId = (value: unknown): value is ProjectsViewId => value === 'grid' || value === 'list';const isProjectSortId = (value: unknown): value is ProjectSortId =>@@ -191,10 +186,8 @@ const normalizeGenerateSectionsOpen = (values: unknown): Record<string, boolean>};/**- * Shape-only: settings keeps the saved records intact and readable, and the generation- * feature re-validates `weights` against the backend's grammar when it reads them- * (`normalizeRebalancePresets`). Parsing here would mean importing that feature into the- * launchpad bundle for no gain.+ * Validate record shape here; generation validates weight grammar when reading, preserving Launchpad's bundle+ * boundary.*/const normalizeRebalancePresets = (values: unknown): StoredRebalancePreset[] => {if (!Array.isArray(values)) {@@ -533,8 +526,6 @@ const resolveSettings = async (return backendPreferences;}- // First contact for this account: adopt whatever the legacy locations- // hold and write the new backend key once.const preferences =(await loadLegacySessionPreferences(owner)) ??local?.preferences ??diff --git a/invokeai/frontend/webv2/src/workbench/shell/AlphaNoticeDialog.tsx b/invokeai/frontend/webv2/src/workbench/shell/AlphaNoticeDialog.tsxindex 1674f9d9a4..c8f5009fe9 100644--- a/invokeai/frontend/webv2/src/workbench/shell/AlphaNoticeDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/AlphaNoticeDialog.tsx@@ -17,11 +17,7 @@ const AlphaNoticeModalLayer = () => {return null;};-/**- * One-time alpha disclaimer, shown once the account's preferences have loaded- * so a fresh session does not flash it at someone who already dismissed it.- * Dismissal is a preference, so it follows the account rather than the browser.- */+/** Wait for account preferences before showing the notice; dismissal follows the account. */export const AlphaNoticeDialog = () => {const { t } = useTranslation();const isOpen = useWorkbenchSettingsSelector(diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsxindex b2ba45ac98..5eb0895123 100644--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx@@ -9,9 +9,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';const centerAreaMocks = vi.hoisted(() => {const icon = () => null;- // A settled deferred resource, the shape `use()` can read without- // suspending — the center view's icon resolves the implementation to decide- // whether to show a spinner, and this fixture is always "already loaded".+ // Use a settled resource so the center icon reads synchronously without suspending.const loadedImplementation = () => {const promise: Promise<object> & { status?: string; value?: object } = Promise.resolve({});diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsxindex bd7b221e8d..5f240b7efc 100644--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx@@ -45,9 +45,7 @@ const CENTER_MENU_POSITIONING = { placement: 'bottom-start' } as const;const CENTER_PREFERRED_REGIONS = ['center'] as const;const CENTER_CHROME_INSET_STYLE = { '--wb-center-chrome-inset': '3rem' } as React.CSSProperties;-// The work surface's floor. Side panels shrink to honour it (see-// `WidgetPanelFrame`), so on a portrait tablet the center stays usable instead-// of collapsing to nothing between two fixed-width panels.+// Reserve a usable center width; side panels shrink to honor this floor.const CENTER_MIN_WIDTH = '20rem';export const CenterArea = () => {@@ -347,15 +345,8 @@ const CenterViewMenu = ({};/**- * The active center view's icon, showing a spinner while its implementation- * chunk is still downloading.- *- * Panel widgets get this from their frame header; the center has no header —- * `CenterArea` owns its chrome — so the identity slot in this trigger was the- * one place a cold widget looked fully loaded while it was not. Suspense is- * the mechanism because `DeferredResource` exposes a status but nothing to- * subscribe to; the same `use()`/fallback pair already drives the chrome slots- * in `WidgetRenderer`.+ * Use Suspense for the center icon's loading state because DeferredResource has no subscription and center widgets+ * lack frame headers.*/const CenterViewIcon = ({ widget }: { widget: RegisteredWidget }) => {const fallback = useMemo(@@ -409,13 +400,7 @@ const CenterViewMenuRow = ({);};-/**- * One kept center view. It resolves its own instance and widget rather than- * taking a region view-model item: a kept instance is by definition no longer- * in the region's item list, because applying a preset replaces `instanceIds`- * wholesale. `applyLayoutPresetToProject` merges `widgetInstances`, so the- * instance itself survives and can still be resolved here.- */+/** Resolve kept instances from widgetInstances: presets replace region membership but merge and preserve instances. */const KeptCenterViewSlot = ({ instanceId }: { instanceId: string }) => {const instance = useActiveProjectSelector((project) => project.widgetInstances[instanceId],diff --git a/invokeai/frontend/webv2/src/workbench/shell/DocumentTitleProgress.tsx b/invokeai/frontend/webv2/src/workbench/shell/DocumentTitleProgress.tsxindex fcd30ceeb5..42ba4818a9 100644--- a/invokeai/frontend/webv2/src/workbench/shell/DocumentTitleProgress.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/DocumentTitleProgress.tsx@@ -6,13 +6,7 @@ import { useTranslation } from 'react-i18next';import { DOCUMENT_TITLE_BASE, formatDocumentTitle } from './documentTitle';-/**- * Writes generation progress into the browser tab. Renders nothing — it is the- * effect adapter for a piece of chrome React does not own.- *- * Percent is rounded before it reaches the title so a batch writes `document.title`- * about a hundred times instead of once per progress frame.- */+/** Write rounded progress to document.title to avoid updating on every progress frame. */export const DocumentTitleProgress = () => {const { t } = useTranslation();const { progress, summary } = useActiveQueueProgress();diff --git a/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx b/invokeai/frontend/webv2/src/workbench/shell/Panels.tsxindex 9b60c9e3bf..ff6a4ecf8c 100644--- a/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx@@ -29,10 +29,8 @@ export const RightPanel = ({ instanceId }: { instanceId: WidgetInstanceId }) =>);/**- * Keeps the panel widgets this session has already shown mounted behind the- * active one, so switching a layout preset hides them rather than destroying- * their scroll position, selection and virtualizer state. The remembered set is- * independent of the region's `instanceIds`, which a preset replaces wholesale.+ * Keep previously shown panels mounted to preserve scroll, selection, and virtualization across presets that+ * replace region membership.*/export const WidgetPanelSlot = ({ instanceId, region }: { instanceId: WidgetInstanceId; region: PanelRegion }) => {const projectId = useActiveProjectId();diff --git a/invokeai/frontend/webv2/src/workbench/shell/PasteMediaDialog.tsx b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaDialog.tsxindex d211692218..f602fa94e7 100644--- a/invokeai/frontend/webv2/src/workbench/shell/PasteMediaDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaDialog.tsx@@ -93,9 +93,8 @@ const CanvasDestinationButton = ({};/**- * Destination picker for a media paste. Every choice uploads the files to the- * gallery's current board first (the asset stays findable), then hands the- * uploaded images on to the existing canvas-import or reference-image actions.+ * Upload pasted media to the current board before forwarding it to canvas/reference actions so assets remain+ * findable.*/export const PasteMediaDialog = ({ request }: { request: PasteMediaRequest }) => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.tsx b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.tsxindex 2bfce1ad77..61320e1765 100644--- a/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.tsx@@ -21,11 +21,8 @@ const PasteMediaDialog = lazy(() =>);/**- * Turns a media paste anywhere in the workbench into a destination choice.- * The canvas keeps its own `mod+v` (a layer from the clipboard pixels): its- * hotkey cancels the keydown, so no paste event reaches here while the canvas- * owns focus. Text pasted into a field and pastes inside open dialogs are never- * intercepted.+ * Offer destinations for workbench media paste. Canvas handles its own chord; text fields and open dialogs retain+ * normal paste behavior.*/export const PasteMediaRuntime = () => {const [request, setRequest] = useState<PasteMediaRequest | null>(null);diff --git a/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsxindex e018e78333..b67f307a75 100644--- a/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx@@ -7,16 +7,12 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';/**- * A store whose center region is replaced the way `applyLayoutPresetToProject`- * replaces it: `instanceIds` is rewritten wholesale, so the outgoing widget is- * no longer in the region at all. The widget instances are merged and survive,- * which is what the keep-alive set resolves against.+ * Model preset application by replacing region ids while preserving merged widget instances for keep-alive+ * resolution.*/const keepAliveMocks = vi.hoisted(() => {const icon = () => null;- // A settled deferred resource, the shape `use()` can read without- // suspending — the center view's icon resolves the implementation to decide- // whether to show a spinner, and these fixtures are always "already loaded".+ // Use settled resources so center icons read synchronously without suspending.const loadedImplementation = () => {const promise: Promise<object> & { status?: string; value?: object } = Promise.resolve({});@@ -253,8 +249,7 @@ describe('preset switch keep-alive', () => {const hiddenCanvas = centerWidget('canvas');expect(hiddenCanvas).not.toBeNull();- // `display: none` takes the subtree out of the accessibility tree, so it is- // unreachable by pointer hit-testing and by sequential focus navigation.+ // display:none removes hidden views from accessibility, hit testing, and sequential focus.expect(hiddenCanvas?.getClientRects().length).toBe(0);});@@ -269,8 +264,7 @@ describe('preset switch keep-alive', () => {await setRightInstanceId('preview');- // The right rail is now rendering this instance for real; a hidden centre- // copy would be the same instance mounted twice, one of them a ghost.+ // A live rail placement must evict the hidden center copy to avoid mounting one instance twice.expect(centerWidget('preview')).toBeNull();});diff --git a/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsx b/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsxindex a4b9e90f2d..8580d8ae2c 100644--- a/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsx@@ -46,19 +46,10 @@ interface BottomWidgetItem extends PlacedWidgetRegionItem<WidgetPlacementInstancconst BOTTOM_MENU_POSITIONING = { placement: 'top-end' } as const;const WIDGET_POPOVER_POSITIONING = { placement: 'top-end' } as const;const BOTTOM_MENU_TRIGGER = { kind: 'bottom' } as const;-/**- * Same ladder as the side rails (see `WidgetBar`): hover and active share one- * fill, and the brand hue marks the open widget through its content colour,- * because a brand tint of this bar is indistinguishable from it on the light- * theme.- */+/** Use content color for active brand accents; background tint is indistinguishable on the light theme. */const COMPACT_ROW_HOVER_PROPS = { bg: 'bg.emphasized', color: 'fg' };-/**- * The per-cluster drop chrome: the rail overlay itself, sized to its- * cluster. Two of these replace the strip-wide curtain, which hid the- * right-side target behind itself.- */+/** Size drop overlays per cluster so one strip-wide curtain cannot cover the other target. */const ClusterDropRing = ({ dropState, isOver }: { dropState: WidgetRegionDropState; isOver: boolean }) => (<WidgetRegionDropOverlay dropState={dropState} isOver={isOver} left="-4px" right="-4px" zIndex={3} />);@@ -122,10 +113,8 @@ export const StatusBar = ({ dropState }: { dropState: WidgetRegionDropState }) =return [{ ...item, isExpandable: isExpandableBottomItem(item), isPopover: isPopoverBottomItem(item) }];});- // The trailing cluster: placement stays in `instanceIds` order within each- // side, so drag-reorders keep working; only the render splits. Cluster- // membership moves via the context menu, by dropping onto the spacer, or by- // landing beside a widget of the other cluster (see `resolveWidgetDragEnd`).+ // Preserve instance order within clusters; only rendering splits them. Context menus, spacer drops, or+ // neighboring widgets move membership.const alignEndIds = useMemo(() => new Set(bottomRegion.alignEndInstanceIds ?? []),[bottomRegion.alignEndInstanceIds]@@ -174,14 +163,10 @@ export const StatusBar = ({ dropState }: { dropState: WidgetRegionDropState }) =[widgets]);const isItemAlignedEnd = useCallback((item: WidgetEnableMenuItem) => alignEndIds.has(item.id), [alignEndIds]);- // The two-cluster drop chrome only lights for widget drags the region- // accepts; the shell's dropState already encodes allowedRegions.const dnd = useDndContext();const showDropChrome =dropState.isActive && dropState.isAllowed && isWidgetInstanceDragData(dnd.active?.data.current);- // Highlight rules mirror the rails exactly: the accent treatment fires- // only when the pointer is over the zone's own background, never over- // chips — a chip hover previews a reorder, not a zone drop.+ // Accent only zone-background hover; chip hover previews reordering.const isOverStart = showDropChrome && String(dnd.over?.id ?? '') === getWidgetRegionDropId('bottom');const handleContextClose = useCallback(() => setEnableMenuTarget(null), []);const handleInstanceClose = useCallback(() => setInstanceMenuTarget(null), []);@@ -353,8 +338,6 @@ const CompactBottomWidget = ({);if (item.isPopover) {- // VSCode-style notification center: the chip anchors a large dismissable- // popover instead of claiming the shared bottom panel.return (<Popover.RootlazyMountdiff --git a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsxindex 513dfb1c86..2626c3e0b7 100644--- a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx@@ -62,14 +62,8 @@ import { TopBar } from './topbar';const DND_MODIFIERS = [restrictToWindowEdges];/**- * Default 20% edge zones, at half the default scroll speed. The zones must- * stay full-size: in the side layout the board list is under 250px tall, so- * a narrower band excludes the first and last visible rows — the places an- * image is actually held to scroll the list. Speed is halved because at- * dnd-kit's default a list this small dumps its full range in under half a- * second, far too fast to pick a row. Phantom off-screen targets triggering- * scrolls from afar are prevented by the visibility check inside- * widgetCollisionDetection, not by shrinking zones.+ * Keep 20% edge zones for short board lists but halve scrolling speed. Collision visibility checks exclude+ * offscreen targets rather than narrowing usable zones.*/const DND_AUTO_SCROLL = { acceleration: 5 };const EMPTY_FLOATING: NonNullable<Project['floatingWidgets']> = {};@@ -84,8 +78,6 @@ export const WorkbenchShell = () => {const floatingWidgets = useActiveProjectSelector((project) => project.floatingWidgets ?? EMPTY_FLOATING);const placementProject = useActiveProjectSelector(getWidgetPlacementProject, areWidgetPlacementProjectsEqual);const sensors = useSensors(- // `PrimaryMouseSensor`/`HoldToDragSensor` replace the stock `PointerSensor`:- // see holdToDragSensor.ts for why touch gestures need the hold gate.useSensor(PrimaryMouseSensor, { activationConstraint: { distance: 6 } }),useSensor(HoldToDragSensor, {activationConstraint: { delay: TOUCH_DRAG_HOLD_DELAY_MS, tolerance: TOUCH_DRAG_MOVE_TOLERANCE_PX },@@ -200,8 +192,7 @@ export const WorkbenchShell = () => {[placementProject, widgets]);const handleDragCancel = useCallback(() => setActiveDrag(null), []);- // A floating slot's click is the rail-side dock control, the mirror of the- // window's own; the drafts flush for the same reason that control's does.+ // Flush drafts before rail-side docking, as the window's dock control does.const handleSelect = useCallback((region: WidgetBarGroup['region'], instanceId: string) => {if (floatingWidgets[instanceId]) {@@ -309,9 +300,7 @@ 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. */}+ {/* Use a named content region: the project switcher is no longer a tablist. */}<Flexaria-labelledby="workbench-project-heading"flex="1"@@ -350,11 +339,10 @@ export const WorkbenchShell = () => {<FloatingWidgetLayer /><GalleryDragCursor /><PasteMediaRuntime />- {/* The overlay renders whenever anything is being dragged, even with no- preview to show — and it is a fixed, full-size div over the dragged- element. Without this it swallows every pointer event aimed at what- is underneath, which is how a second finger meant for the preview's- pinch never reaches the preview. */}+ {/*+ * Allow pointer events through the full-size drag overlay so another finger can reach Preview pinch+ * handlers.+ */}<DragOverlay style={DRAG_OVERLAY_STYLE}>{activeDrag ? <WidgetDragPreview activeDrag={activeDrag} /> : null}</DragOverlay>diff --git a/invokeai/frontend/webv2/src/workbench/shell/documentTitle.test.ts b/invokeai/frontend/webv2/src/workbench/shell/documentTitle.test.tsindex ed253ef5db..abbbf76a7b 100644--- a/invokeai/frontend/webv2/src/workbench/shell/documentTitle.test.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/documentTitle.test.ts@@ -38,8 +38,6 @@ describe('formatDocumentTitle', () => {});it('trails a running title with the short label, not the idle one', () => {- // The whole point of the split: the idle title names the product in full,- // and a running title spends that width on the numbers instead.const running = formatDocumentTitle({ current: 2, labels, percent: 42, total: 8 });expect(DOCUMENT_TITLE_PRODUCT.length).toBeLessThan(DOCUMENT_TITLE_BASE.length);diff --git a/invokeai/frontend/webv2/src/workbench/shell/documentTitle.ts b/invokeai/frontend/webv2/src/workbench/shell/documentTitle.tsindex 24bbbaaf27..66176f229c 100644--- a/invokeai/frontend/webv2/src/workbench/shell/documentTitle.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/documentTitle.ts@@ -1,22 +1,9 @@-/**- * Generation progress in the browser tab, for the batch you walked away from.- *- * Batches run for minutes and people switch tabs while they do; every other- * progress surface in the app is invisible the moment this document is not the- * foreground one. Tab titles truncate hard and from the right, so the numbers- * lead and the product name trails.- */+/** Lead tab titles with progress because background tabs hide other indicators and truncate labels from the right. *//** Mirrors the static `<title>` in index.html, which is what we restore to. */export const DOCUMENT_TITLE_BASE = 'Invoke V7 Workbench';-/**- * The trailing label while a batch runs, deliberately shorter than the idle- * title. The idle title can afford to name the product precisely; a running one- * is competing for the same few characters as the numbers, and those are the- * part worth reading. Spending the width on "V7 Workbench" is what pushes the- * percent out of a pinned or crowded tab.- */+/** Shorten the running title's product label to leave room for progress in crowded tabs. */export const DOCUMENT_TITLE_PRODUCT = 'Invoke';export interface DocumentTitleLabels {diff --git a/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.browser.test.tsxindex 5ab748b982..53f388dce3 100644--- a/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.browser.test.tsx@@ -6,9 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { HoldToDragSensor, PrimaryMouseSensor } from './holdToDragSensor';-// Small enough to exercise the gate with real timers; production uses 400ms/10px.-// Gesture moves are 20px: comfortably past both the tolerance and the 6px-// immediate-activation distance.+// Use short real-timer gates; 20px moves exceed both tolerance and immediate activation distance.const HOLD_DELAY_MS = 120;const HOLD_TOLERANCE_PX = 10;@@ -54,11 +52,7 @@ const mouse = (type: string, target: EventTarget, clientX: number, clientY: numbtarget.dispatchEvent(new MouseEvent(type, { bubbles: true, button, cancelable: true, clientX, clientY }));};-/**- * The draggable must live in a component INSIDE `DndContext`: React context- * flows downward, so a `useDraggable` in the same component that renders the- * provider would read dnd-kit's default internal context instead.- */+/** Mount useDraggable below DndContext so it receives the provider rather than default context. */const DraggableTile = ({ onClick, pannable }: { onClick: () => void; pannable: boolean }) => {const { listeners, setNodeRef } = useDraggable({ id: 'tile' });@@ -165,12 +159,8 @@ describe('HoldToDragSensor touch gate', () => {});it('holds the browser pan off from arming onward, but not during the hold', async () => {- // The browser's own pan threshold can be tighter than the move tolerance- // (Android Chrome starts scrolling around 8px), so from arming onward the- // sensor must keep the pan from starting at all; during the hold the pan- // must stay available for the native scroll. The handler only reads- // `cancelable` and calls `preventDefault()`, so a plain cancelable event- // exercises the same path a real TouchEvent takes.+ // After arming, prevent native pan before its threshold wins; during the hold preserve scrolling. A cancelable+ // event covers the handler's preventDefault path.const { events, tile } = await renderHarness();const touchMove = () => {@@ -201,8 +191,7 @@ describe('HoldToDragSensor touch gate', () => {});it('treats a motionless armed hold that lifts as an ordinary tap', async () => {- // The stock TouchSensor delay constraint activates on the timer alone, so a- // deliberate slow tap selected nothing and the trailing click was swallowed.+ // A motionless hold must remain a tap; timer-only activation would swallow selection.const { events, tile } = await renderHarness();await interact(() => pointer('pointerdown', tile(), 150, 150));@@ -239,9 +228,7 @@ describe('HoldToDragSensor touch gate', () => {});it('releases the gesture on pointercancel and accepts a new one', async () => {- // The browser claims the gesture (a native pan). A sensor that stops without- // ending the gesture leaves dnd-kit's activation guard set, which blocks- // every later drag on the context until reload.+ // Native pan cancellation must end the gesture and clear dnd-kit's activation guard for later drags.const { events, tile } = await renderHarness();await interact(() => pointer('pointerdown', tile(), 150, 150));@@ -288,8 +275,7 @@ describe('HoldToDragSensor touch gate', () => {await wait(HOLD_ELAPSED_MS);expect(tile().getAttribute('data-drag-armed')).toBe('true');- // Android's long-press menu (~500ms) outlasts the hold: menu intent, so the- // menu is allowed and the gate disarms instead of dragging over it.+ // Allow long-press menus and disarm dragging when menu intent wins.const menuWhileArmed = new MouseEvent('contextmenu', { bubbles: true, cancelable: true });await interact(() => window.dispatchEvent(menuWhileArmed));@@ -317,8 +303,7 @@ describe('HoldToDragSensor touch gate', () => {it('activates immediately by distance on a surface that cannot pan', async () => {const { events, tile } = await renderHarness({ pannable: false });- // No hold: `touch-action: none` means the browser can never pan, so there- // is nothing to arbitrate and a small movement starts the drag at once.+ // touch-action:none needs no hold because native pan cannot compete.await interact(() => pointer('pointerdown', tile(), 150, 150));await interact(() => pointer('pointermove', document, 170, 150));@@ -347,8 +332,7 @@ describe('PrimaryMouseSensor button guard', () => {it('starts drags for the primary button only', async () => {const { events, tile } = await renderHarness();- // Middle-click (and other aux buttons) must not pick the tile up: the stock- // MouseSensor only rejects the right button.+ // Reject all auxiliary buttons; stock MouseSensor rejects only the right button.await interact(() => mouse('mousedown', tile(), 150, 150, 1));await interact(() => mouse('mousemove', document, 170, 150));diff --git a/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.ts b/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.tsindex 3420658d54..9881af7211 100644--- a/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/holdToDragSensor.ts@@ -1,49 +1,10 @@import { MouseSensor, type Activator, type SensorOptions, type SensorProps } from '@dnd-kit/core';/**- * Sensors for the shell's drag-and-drop that make touch scrolling possible.- *- * A distance-only activation constraint (the stock `PointerSensor` setup)- * claims a touch-drag as soon as the pointer moves a few pixels — before the- * browser can start panning — so any scrollable surface of draggable items- * (the gallery grid, the preview filmstrip) is unscrollable by touch: the- * image is picked up and dragged instead.- *- * `HoldToDragSensor` arbitrates the gesture for touch pointers with a timing- * gate, and keeps pens and the pre-gate behavior for surfaces that cannot pan:- *- * - A touch `pointerdown` starts a hold. While the hold is pending the sensor- * leaves the gesture strictly alone, so the browser is free to pan: an early- * move past the tolerance cancels the gate and the native scroll keeps the- * gesture. When the hold elapses the gate *arms* — the draggable node gets- * `data-drag-armed` so the tile can show its cue — and only movement past- * the tolerance after that starts the drag. A motionless hold that lifts is- * therefore an ordinary tap: the sensor never activates, no click is- * suppressed, and selection works exactly as before.- * - If the touched element sits under a `touch-action: none` (itself, or any- * ancestor below the first scroll container) the browser can never pan, so- * there is nothing to arbitrate: touch drags activate on a small distance,- * the pre-gate behavior. This keeps non-scrolling drag surfaces (the preview- * frame, floating widget windows) feeling immediate.- * - Pen pointers activate on a small distance, like the mouse: pen panning- * cannot be `preventDefault`ed after the fact (no touch events fire for a- * pen), so a hold gate would hand the armed gesture to the browser's pan- * claim unpredictably.- *- * From the moment the hold arms the gate, the sensor holds the browser's pan- * off with a document-level non-passive `touchmove` listener — pointer events- * cannot `preventDefault` a pan, and the browser's own pan threshold can be- * tighter than the move tolerance (Android Chrome starts scrolling around- * 8px) — so an armed drag cannot be stolen by the native scroll before it- * activates, nor mid-drag afterwards.- *- * Every path through the state machine ends the gesture explicitly- * (`onEnd`/`onCancel`), which is what clears dnd-kit's activation guard; a- * sensor that stops mid-gesture without doing so blocks every later drag on- * the context until reload. In particular, `pointercancel` — the browser- * claiming the gesture for a pan — is handled for every pointer type, which- * is why pens route through this sensor instead of reaching `MouseSensor`- * (whose mouse-event set has no cancel event).+ * For touch on pannable surfaces, hold first, then require movement: early movement yields to scrolling and+ * motionless holds remain taps. Pen and touch-action:none surfaces activate by distance. Once armed, a non-passive+ * touchmove listener prevents native pan from stealing the gesture. Every exit, including pointercancel, calls+ * onEnd/onCancel to clear dnd-kit's activation guard.*/export const TOUCH_DRAG_HOLD_DELAY_MS = 400;@@ -227,8 +188,6 @@ export class HoldToDragSensor {return;}- // Waiting: movement past the tolerance is scrolling intent. The native- // scroll keeps the gesture; stop tracking it.if (distance > this.tolerance) {this.endGesture(false);}@@ -239,8 +198,7 @@ export class HoldToDragSensor {return;}- // A lift: an ordinary tap (never activated) or the end of a drag. Both end- // the gesture; only an activated drag suppresses the trailing click.+ // End taps and drags on lift; only activated drags suppress the trailing click.this.endGesture(true);};@@ -267,11 +225,8 @@ export class HoldToDragSensor {};private readonly handleTouchMove = (event: TouchEvent) => {- // From arming onward, hold the browser's pan off: pointer events cannot- // preventDefault a pan, and the browser's own pan threshold can be tighter- // than the move tolerance (Android Chrome starts scrolling around 8px), so- // an armed drag would otherwise be lost to the native scroll the instant- // the finger moves.+ // Prevent native touch pan after arming; pointer-event prevention cannot stop it and its threshold may precede+ // drag tolerance.if ((this.gate === 'armed' || this.gate === 'active') && event.cancelable) {event.preventDefault();}@@ -323,11 +278,7 @@ export class HoldToDragSensor {this.document.getSelection()?.removeAllRanges();};- /**- * Ends the in-flight gesture. Mirrors the stock sensors' end semantics:- * `onAbort` when nothing ever activated, then `onEnd`/`onCancel` — the call- * that clears dnd-kit's activation guard.- */+ /** Abort unactivated gestures, then always call onEnd/onCancel to clear dnd-kit's activation guard. */private endGesture(ended: boolean) {const activated = this.gate === 'active';@@ -373,11 +324,7 @@ export class HoldToDragSensor {}}-/**- * The stock `MouseSensor` activates for any non-right button, where the- * `PointerSensor` it replaces only ever accepted the primary button. Restore- * that guard so middle-click and back/forward buttons cannot start drags.- */+/** Restrict MouseSensor to the primary button, matching the replaced PointerSensor. */export class PrimaryMouseSensor extends MouseSensor {}PrimaryMouseSensor.activators = [diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsxindex 1d4651bc54..67f8841bdb 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsx@@ -156,8 +156,6 @@ const AppMenuGlyph = () => (const SearchMenuAction = () => {const { t } = useTranslation();- // Same formatter as every other shortcut hint in the top bar, so the two- // hinted actions in this row read alike (and macOS gets ⌘K, not "cmd+k").const shortcut = useTopbarShortcut(OPEN_COMMAND_PALETTE_HOTKEY.commandId);const label = shortcut ? t('commandPalette.buttonTooltip', { hotkey: shortcut }) : t('commandPalette.buttonLabel');@@ -174,8 +172,6 @@ const SettingsMenuAction = ({ onClick }: { onClick: () => void }) => {return <AppMenuAction icon={SettingsIcon} label={label} value="settings" onClick={onClick} />;};-// Sized like the 2xs icon buttons in widget headers; menu items default to a-// much roomier padding than an icon-only action needs.const FOOTER_ITEM_PROPS = {alignItems: 'center',flex: '0 0 auto',diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvocationCluster.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvocationCluster.tsxindex 2932492d3d..89608bd9b4 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvocationCluster.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvocationCluster.tsx@@ -7,15 +7,6 @@ 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();diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsxindex a4ecefe54b..86f83e3cb7 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsx@@ -10,13 +10,8 @@ import { userEvent } from 'vitest/browser';import type { InvocationState } from './useInvocationState';import type * as UseTopbarShortcutModule from './useTopbarShortcut';-// Isolates the regression this file exists to catch: the icon slot must swap-// back to progress once the pointer leaves AND the button does not hold-// `:focus-visible` — a plain mouse click leaves it focused (browsers focus a-// button on mousedown) but must not count, or every mouse-invoked batch would-// show a play glyph it cannot act on. Mocking the shared hook keeps the test-// about that gating, not about queue-summary plumbing (which-// `useActiveQueueProgress` and its call sites already cover elsewhere).+// Verify progress returns after hover ends unless focus-visible remains; mouse click-focus must not pin the play+// icon. Mock queue plumbing to isolate that gate.const harness = vi.hoisted(() => ({progress: { activeItemIndex: 1, completedItemCount: 0, message: '', percentage: 0.42 },summary: { current: 1, remaining: 1, runningQueueItemId: 'item-1', total: 1 },diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsxindex fefb8eb120..fc1110fd04 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx@@ -22,9 +22,7 @@ const TOOLTIP_CONTENT_PROPS = { p: '0' };const SHORTCUT_BORDER = 'color-mix(in oklab, currentColor 40%, transparent)';type ProgressCircleRootProps = ComponentProps<typeof ProgressCircle.Root>;-// The `3xs` size (14px/2px, defined in platform/ui/theme/recipes.ts) is a repo-// extension the generated Chakra types don't know about yet; QueueProgressIndicator-// casts through the same seam for its `2xs` extension.+// Cast the repository's 3xs theme extension, which generated Chakra types do not yet include.const ICON_RING_SIZE = '3xs' as ProgressCircleRootProps['size'];const compactBlockingReason = (reason: string, noNodesLabel: string): string => {@@ -38,18 +36,8 @@ const compactBlockingReason = (reason: string, noNodesLabel: string): string =>const plural = (count: number, noun: string): string => `${count} ${noun}${count === 1 ? '' : 's'}`;/**- * The single Invoke action for the whole application.- *- * Its geometry, 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. Only the icon slot's content may change: it- * shows the queue's progress while a batch runs and the pointer is elsewhere- * and the button does not hold keyboard focus, and reverts to the play glyph- * on hover or on `:focus-visible` (not a plain click-focus, which would leave- * a mouse-invoked batch stuck on the play glyph) so "queue more on top"- * always reads as available. Aggregate progress otherwise belongs to the- * queue group. (§5.1, contract §9.4.)+ * Keep Invoke geometry and availability stable while work runs. Only the icon changes to progress; hover or+ * keyboard focus-visible restores play to signal that more work can queue.*/export const InvokeButton = ({ state }: { state: InvocationState }) => {const { t } = useTranslation();@@ -68,9 +56,7 @@ export const InvokeButton = ({ state }: { state: InvocationState }) => {const handlePointerEnter = useCallback(() => setIsHovered(true), []);const handlePointerLeave = useCallback(() => setIsHovered(false), []);const [isFocused, setIsFocused] = useState(false);- // `focus`, unlike `:focus-visible`, fires on every mousedown too — gating on- // the pseudo-class keeps this keyboard-only so a mouse click mid-batch does- // not strand the icon on the play glyph until something else steals focus.+ // Check focus-visible so mouse click-focus cannot pin the play icon throughout a batch.const handleFocus = useCallback((event: FocusEvent<HTMLButtonElement>) => {if (event.currentTarget.matches(':focus-visible')) {setIsFocused(true);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsxindex b480ddb476..66533dc3ef 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsx@@ -8,13 +8,6 @@ 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(diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsxindex 6df2fc76a5..a87a0a9644 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx@@ -15,11 +15,7 @@ import { closeLayoutPresetAdmin, layoutPresetManagerStore } from './layoutPresetconst EMPTY_LAYOUT_PRESETS: LayoutPreset[] = [];-/**- * 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.- */+/** Host shared preset dialogs once; triggers only select the preset id. */export const LayoutPresetAdminDialogs = () => {const { t } = useTranslation();const { layout } = useWorkbenchCommands();diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.tsxindex c51fb4f9a1..c9e0c9bab5 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.tsx@@ -61,13 +61,7 @@ const getNextIconId = (currentIconId: string, key: string): string | null => {return layoutPresetIconIds[nextIndex] ?? null;};-/**- * Identity and default routing for a layout preset.- *- * Presets collapse to icon-only below 1280px, so the icon is not decoration.- * The curated picker keeps the task focused on telling layouts apart at a- * glance instead of turning it into an icon-library search.- */+/** Presets become icon-only below 1280px; a curated picker keeps them distinguishable without a full icon search. */export const LayoutPresetDialog = ({defaultRoute: initialDefaultRoute,iconId: initialIconId,@@ -108,9 +102,7 @@ export const LayoutPresetDialog = ({const sourceValue = useMemo(() => (defaultRoute ? [defaultRoute.sourceId] : []), [defaultRoute]);const canSubmit = name.trim().length > 0 && (sourceOptions.length === 0 || defaultRoute !== undefined);- // 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.+ // Use trap-managed initialFocusEl so typing reaches the name after the dialog is ready.const initialFocusEl = useCallback(() => nameRef.current, []);const handleOpenChange = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialog.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialog.tsxindex 2a749fbfad..fa032f0bbe 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialog.tsx@@ -2,11 +2,7 @@ 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.- */+/** Lazy-load the infrequently used preset manager outside the editor's initial payload. */const LazyLayoutPresetManagerDialogBody = lazy(() =>import('./LayoutPresetManagerDialogBody').then((module) => ({ default: module.LayoutPresetManagerDialogBody })));diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.browser.test.tsxindex 6f0265bb44..180c21b92a 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.browser.test.tsx@@ -152,9 +152,7 @@ describe('LayoutPresetStrip', () => {expect(store.getSnapshot().activeProject.layout.presetId).toBe('edit');});- // Desktop tab strips — Chrome, Firefox, VS Code — select a tab the moment it- // is pressed and reorder it from that same gesture. Reordering therefore- // activates the dragged tab, and does so on the press rather than the drop.+ // Desktop tabs activate on press, including the press that begins reordering.it('selects a dragged tab on the press and reorders it in the same gesture', async () => {await renderStrip();await act(() => userEvent.click(presetTab('edit')!));diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsxindex b8c438ce9d..2dbfcf97ac 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx@@ -112,21 +112,14 @@ export const LayoutPresetStrip = () => {() => ({ destination: invocation.destination, sourceId: invocation.sourceId }),[invocation.destination, invocation.sourceId]);- /**- * Desktop semantics: the control acknowledges the press on its own frame,- * then the workspace rearranges. Activating inside the handler put a- * ~100ms blocking React commit between the click and any pixel changing,- * and the tab itself did not repaint for ~330ms.- */+ /** Acknowledge the tab press before rearranging the workspace so a blocking layout commit cannot delay feedback. */const requestPreset = useCallback((presetId: LayoutPresetId) => {setPendingPresetId(presetId);requestAnimationFrame(() => {void layout.activatePreset(presetId).then((appliedPresetId) => {- // An activation can be dropped — superseded, overtaken by a project- // switch, or aimed at a preset the account has since replaced. Give- // the tab back to the store rather than leave it painting a preset- // nothing ever applied. Guarded so a newer request keeps its own.+ // Return dropped activations to store selection without overwriting a newer request's optimistic+ // selection.if (appliedPresetId !== presetId) {setPendingPresetId((pending) => (pending === presetId ? null : pending));}@@ -209,10 +202,7 @@ export const LayoutPresetStrip = () => {))}</Tabs.List></SortableContext>- {/* 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. */}+ {/* Provide aria-controls targets describing the shared dock outside this component. */}{presets.map((preset) => (<Tabs.Content key={preset.id} value={preset.id} asChild><VisuallyHidden>{`${preset.label} layout`}</VisuallyHidden>@@ -284,9 +274,8 @@ const PresetTab = ({opacity: isDragging ? 0.5 : undefined,position: 'relative' as const,transform: CSS.Translate.toString(transform),- // dnd-kit's inline transform transition replaces the recipe's CSS- // transition outright, which froze hover/selected fills; compose the- // buttons' fill fade back in (motion-aware duration token).+ // Compose fill transitions with dnd-kit's inline transform transition so hover/selection fades remain+ // active.transition: [transition, TAB_FILL_TRANSITION].filter(Boolean).join(', '),zIndex: isDragging ? 1 : undefined,}),@@ -295,10 +284,7 @@ const PresetTab = ({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.+ // Use a span chevron recognized by the tab handler; nested buttons are invalid.const handleClick = useCallback((event: MouseEvent<HTMLButtonElement>) => {const trigger = event.target instanceof Element ? event.target.closest(`[${PRESET_MENU_ATTRIBUTE}]`) : null;@@ -312,18 +298,11 @@ const PresetTab = ({[onOpenMenu, preset]);- // The press, not the click, is what the user is waiting on: the tabs machine- // lands the selection correctly either way, but only once the button is- // released. Primary button only — `pointerdown` fires for the secondary- // button too, ahead of `contextmenu`, and right-clicking an inactive preset- // to reach its menu must not switch to it first and strip the menu of the- // very item it was opened for. dnd-kit's own `MouseSensor` bails the same way.+ // Activate on primary press for immediate feedback; right-click must preserve the inactive preset's menu+ // actions.const handlePointerDown = useCallback((event: PointerEvent<HTMLButtonElement>) => {- // dnd-kit owns the drag gesture; chain rather than replace. Inert today —- // the strip's sensors activate on `onMouseDown`/`onTouchStart`/`onKeyDown`- // and only the unused `PointerSensor` would put a listener here — kept so- // a future sensor swap does not silently lose its activator.+ // Chain dnd-kit's activator so a sensor change cannot silently lose drag initiation.(listeners as { onPointerDown?: (value: unknown) => void } | undefined)?.onPointerDown?.(event);if (event.button === 0 && event.pointerType !== 'touch' && !isActive) {diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStripAck.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStripAck.browser.test.tsxindex 5f02b79741..4d9cc6503a 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStripAck.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStripAck.browser.test.tsx@@ -12,9 +12,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';type ActivatePreset = (presetId: LayoutPresetId) => Promise<LayoutPresetId | null>;-// The store is read for real but never written: `activatePreset` is a stub the-// test can freeze outright, which is the point of the suite. If the tab only-// acknowledges the press once the store has caught up, nothing here passes.+// Freeze activation writes while reading the real store to verify acknowledgement precedes store completion.let store: WorkbenchInternalStore;// Rebuilt per render rather than read from a module slot at call time. The@@ -115,11 +113,8 @@ afterEach(async () => {});describe('LayoutPresetStrip acknowledgment', () => {- // The selected paint, `aria-selected` for assistive technology, and the mark- // the performance gate observes are all the same attribute pair, written by- // the tabs machine from the controlled `value`. Pinning it here means a- // future release that defers those writes fails a test rather than silently- // regressing the budget.+ // Assert the controlled selected/ARIA attributes also observed by performance checks so deferred writes cannot+ // silently regress feedback.it('selects the pressed tab on pointerdown, before any store update', async () => {// activatePreset never resolves: the store is deliberately frozen.const activate = vi.fn<ActivatePreset>(() => new Promise<LayoutPresetId | null>(() => {}));@@ -168,11 +163,7 @@ describe('LayoutPresetStrip acknowledgment', () => {expect(activate).not.toHaveBeenCalled();});- // The strip is horizontally scrollable and its tabs carry `touchAction:- // 'pan-x'`, so a finger landing on an inactive tab to begin a pan is a- // supported gesture, not a click. Activating on touch `pointerdown` would- // switch the layout before the pan even starts. Touch keeps activating on- // `click`, same as before this component acknowledged presses at all.+ // Touch activates on click, preserving horizontal pan gestures that begin on inactive tabs.it('ignores a touch-pointer press', async () => {const activate = vi.fn<ActivatePreset>(() => Promise.resolve('edit'));@@ -186,9 +177,7 @@ describe('LayoutPresetStrip acknowledgment', () => {expect(presetTab('compose').getAttribute('aria-selected')).toBe('true');});- // `pointerdown` fires for the secondary button too, ahead of `contextmenu`.- // Switching on right-click would strip the menu of the "switch to this- // preset" item that is the whole reason to open it on an inactive tab.+ // Right-click must not activate an inactive preset before its context menu opens.it('ignores a secondary-button press', async () => {const activate = vi.fn<ActivatePreset>(() => Promise.resolve('edit'));@@ -202,10 +191,8 @@ describe('LayoutPresetStrip acknowledgment', () => {expect(presetTab('compose').getAttribute('aria-selected')).toBe('true');});- // Three activations are silently dropped by the store — superseded, overtaken- // by a project switch, or aimed at a replaced preset definition. Painting the- // selection ahead of the store means the tab has to be handed back when that- // happens, or it shows a preset nothing ever applied, permanently.+ // Restore store selection when supersession, project switch, or replaced definitions drop an optimistic+ // activation.it('gives the selection back to the store when the activation is dropped', async () => {// Settled by hand inside `act` rather than pre-resolved: it pins the// handoff to the moment the outcome is known, instead of to whicheverdiff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsxindex 7b48b2fe3c..6763cbda44 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx@@ -140,9 +140,7 @@ export const ProjectSwitcher = () => {return;}- // Export bundles every image the project points at, so it runs for as long- // as the project is large and can fail on a dropped connection or a project- // past the archive ceiling. The reporter owns saying both.+ // Use the reporter for export progress and failures, including connection loss and archive limits.startExport(project);}, [activeProjectId, getProject, startExport]);const closeActiveProject = useCallback(() => {@@ -172,9 +170,7 @@ export const ProjectSwitcher = () => {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. */}+ {/* This labeled trigger supplies its own name; wrapping it with Tooltip would lose the menu anchor ref. */}<Menu.Trigger asChild><Buttonref={triggerRef}@@ -279,9 +275,10 @@ export const ProjectSwitcher = () => {onClose={closeDeleteDialog}onConfirm={confirmDeleteProject}/>- {/* Rendered unconditionally and driven by `open`: the dialog already declares `lazyMount`- and `unmountOnExit`, so it costs nothing while closed — and unmounting it here instead- skipped its exit transition, closing by cutting rather than fading. */}+ {/*+ * Keep the dialog mounted by open state; its lazyMount/unmountOnExit handle closed cost and preserve exit+ * animation.+ */}<OpenProjectDialog isOpen={isOpenDialogVisible} onClose={hideOpenDialog} /></>);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.tsxindex 1151b94591..fffcd3ed31 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.tsx@@ -113,10 +113,6 @@ export const QueueCluster = () => {variant={tone === 'idle' ? 'outline' : 'subtle'}onClick={handleOpenQueue}>- {/* No background fill here any more: the top bar's progress rail is- twenty pixels below this button and says the same thing at- viewport width, where a 35%-opacity wash behind a number never- really did. The count and the tooltip are this control's job. */}<Icon as={isPaused ? PauseIcon : ListOrderedIcon} position="relative" zIndex="1" /><chakra.span fontVariantNumeric="tabular-nums" position="relative" textAlign="center" zIndex="1">{remaining}diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsxindex 5d369bf82c..6dfdb91731 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx@@ -10,16 +10,8 @@ import { ProjectSwitcher } from './ProjectSwitcher';import { TopbarProgressRail } from './TopbarProgressRail';/**- * The workbench top bar.- *- * 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.- *- * 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).+ * Use minmax(0,1fr) side columns to center presets independently of project-name width. Collapse left labels+ * first; preserve route and queue indicators.*/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 7c9459b301..0b751f7fb3 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopbarProgressRail.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopbarProgressRail.tsx@@ -2,19 +2,7 @@ import type { SystemStyleObject } from '@chakra-ui/react';import { QueueProgressRail } from '@workbench/queue-integration/QueueProgressRail';-/**- * The primary generation indicator: a hairline lighting up along the top bar's- * bottom edge while work is in flight.- *- * 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 1px divider rather than below it, so appearing costs no- * reflow and reads as the existing line lighting up. The rail itself is- * shared with the floating preview window (`QueueProgressRail`); only this- * placement is the top bar's.- */+/** Overlay the shared progress rail on the divider for visibility in every layout without reflow. */const RAIL_SX: SystemStyleObject = {bottom: '-1px',diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopbarShortcutKeys.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopbarShortcutKeys.tsxindex 701bac0fff..33f939002d 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopbarShortcutKeys.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopbarShortcutKeys.tsx@@ -5,11 +5,7 @@ import { Fragment } from 'react';import { formatTopbarShortcutPart } from './useTopbarShortcut';-/**- * The per-key body of a topbar shortcut hint, rendered inside a `Kbd`: icons- * where a key has a universal glyph, the platform's text label otherwise.- * macOS runs keys together like its menu hints; elsewhere keys join with `+`.- */+/** Use universal key glyphs or platform text; join macOS hints directly and other platforms with +. */export const TopbarShortcutKeys = ({ parts }: { parts: string[] }) => (<chakra.span alignItems="center" display="inline-flex" gap="0.5">{parts.map((part, index) => (diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeButtonModel.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeButtonModel.tsindex a6ab3d2dbd..715ec6a7a8 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeButtonModel.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeButtonModel.ts@@ -1,13 +1,8 @@export type InvokeIconMode = { mode: 'play' } | { mode: 'progress'; value: number | null };/**- * The Invoke button's icon slot. Progress replaces the play glyph only while a- * batch runs AND `isHovered` is false; hovering always restores the play glyph- * so "queue more on top" stays legible. The caller folds `:focus-visible`- * keyboard focus into this same flag for parity — a plain click-focus does- * not count, or every mouse-invoked batch would be stuck on the play glyph.- * (Contract §9.4: geometry, width, and enabled state never change — only the- * icon slot's content may.)+ * Replace play with progress only when running without hover or keyboard focus-visible. Preserve geometry and+ * availability; click-focus does not count.*/export const getInvokeIconMode = ({hasOpenWork,diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetIcons.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetIcons.tsindex 7c7fed334f..0a28a57235 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetIcons.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetIcons.ts@@ -40,15 +40,8 @@ import {} 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.+ * Persist stable icon ids; never rename them. The curated set supports quick selection, and removed/unknown ids+ * fall back safely.*/export interface LayoutPresetIconOption {id: string;diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetManagerStore.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetManagerStore.tsindex a0162d01cb..819e42ca51 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetManagerStore.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetManagerStore.ts@@ -1,11 +1,7 @@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.- */+/** Share preset-manager visibility across triggers; the topbar hosts one dialog independently of menu mounting. */interface LayoutPresetManagerSnapshot {deletePresetId: string | null;editPresetId: string | null;diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsxindex 2831c6d101..5e33e871cf 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx@@ -134,8 +134,7 @@ describe('useInvocationState and the architecture capability table', () => {'Model capabilities are not available. Generation is blocked until they load; if this persists, retry from the Generate panel.');- // The retry button in the Generate widget, succeeding. Nothing else about the project changes,- // so the route resolution has to be driven by the table's arrival alone.+ // Capability arrival alone must recompute the route after retry succeeds.await act(() => {setArchitectureCapabilities(architectureCapabilitiesFixture);});@@ -146,8 +145,7 @@ describe('useInvocationState and the architecture capability table', () => {describe('useInvocationState and the workflow node templates', () => {it('re-resolves a workflow route when the templates finish loading after the capability table', async () => {- // The capability table is already there, so its snapshot never changes again. A route cached on- // that snapshot alone kept "still loading" after the templates arrived.+ // Template arrival must recompute the route even when the capability snapshot is unchanged.setArchitectureCapabilities(architectureCapabilitiesFixture);await renderProbe(activeProject(diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.tsindex 997d289301..5686bec29f 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts@@ -36,11 +36,8 @@ import { useTranslation } from 'react-i18next';const selectInvocationRouteInput = createInvocationRouteInputSelector();/**- * Route resolution reads two stores imperatively: the capability table (Generate validation fails- * closed without it) and the invocation templates (workflow readiness). The selector that resolves- * the route is only re-run when its snapshot changes, so the snapshot has to change with either --- * a templates load that lands after the table would otherwise leave "Node definitions are still- * loading." on Invoke until an unrelated edit.+ * Include capability and template snapshots in route selection so either load independently clears its readiness+ * gate.*/const subscribeRouteSources = (listener: () => void): (() => void) => {const unsubscribeCapabilities = subscribeArchitectureCapabilities(listener);@@ -120,11 +117,8 @@ export const useInvocationState = (): InvocationState => {void ensureModelsLoaded();});- // `getGenerationValidationReasons` fails closed while the capability table is absent, and workflow- // readiness while the node templates are, so either load -- including one that only succeeds on- // retry -- has to reach Invoke on its own. The route is resolved inside the stores' selector, like- // `useModelGridSize`: both are module state, so to React Compiler a bare call is a pure function of- // these arguments and stays memoised until an unrelated edit changes one of them.+ // Resolve inside subscribed selectors: bare imperative reads can remain compiler-memoized after capabilities or+ // templates arrive.const resolvedRoute = useExternalStoreSelector(subscribeRouteSources,getRouteSourcesSnapshot,@@ -149,9 +143,8 @@ export const useInvocationState = (): InvocationState => {? 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.+ // Block unexpandable prompts rather than submitting literal dynamic syntax; hotkey submission enforces the same+ // rule.const expansionReason = promptExpansion.isError? 'The prompt could not be expanded.': (promptExpansion.error ?? null);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useLayoutDrift.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useLayoutDrift.tsindex 831bcb1036..0a12f30f55 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useLayoutDrift.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useLayoutDrift.ts@@ -15,10 +15,7 @@ export interface LayoutDriftState {hasDrifted: boolean;}-// Module scope, not inline closures: a selector whose identity changed every-// render would defeat `useSyncExternalStoreWithSelector`'s memoization and-// re-run it on each one — and the drift comparison serialises the whole-// arrangement.+// Keep selector identities stable because drift comparison serializes the entire arrangement.const selectActiveLayoutPresetId = (snapshot: WorkbenchSnapshot): LayoutPresetId =>snapshot.activeProject.layout.presetId;@@ -28,24 +25,11 @@ const selectHasDrifted = (snapshot: WorkbenchSnapshot): boolean => {return !areLayoutPresetSnapshotsEqual(createLayoutPresetSnapshot(snapshot.activeProject), activePreset.snapshot);};-/**- * Which preset the active project is on, read live.- *- * Deliberately not routed through the drift debounce below: the strip renders- * the selected tab from this, and a debounced read meant the control the user- * pressed was the last thing on screen to acknowledge the press.- */+/** Read active preset immediately so the pressed tab acknowledges before debounced drift settles. */export const useActiveLayoutPresetId = (): LayoutPresetId =>useWorkbenchSelector(selectActiveLayoutPresetId, Object.is);-/**- * 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.- */+/** Debounce drift across multi-dispatch gestures so only the settled arrangement changes the indicator. */export const useLayoutDrift = (): LayoutDriftState => ({hasDrifted: useDebouncedWorkbenchSelector(selectHasDrifted, DRIFT_SETTLE_MS),});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.test.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.test.tsindex be25585754..570fbc6196 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.test.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.test.ts@@ -3,11 +3,6 @@ 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');diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.tsindex 6f76dc6d83..042e47dd6f 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useTopbarShortcut.ts@@ -5,13 +5,7 @@ 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.- */+/** Use adjacent modifier glyphs on macOS and word labels joined by + elsewhere. */const MAC_GLYPHS: Record<string, string> = {alt: '⌥',cmd: '⌘',@@ -57,11 +51,7 @@ export const formatTopbarShortcutForAria = (hotkey: string): string =>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.- */+/** Display effective bindings, including remaps; return null for unbound commands. */export const useTopbarShortcut = (commandId: string): string | null => {const binding = useTopbarShortcutBinding(commandId);diff --git a/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.browser.test.tsxindex 4074112c07..979ec51ac3 100644--- a/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.browser.test.tsx@@ -8,17 +8,12 @@ import {withoutInstancesShownElsewhere,} from './useMountedInstanceIds';-// `@testing-library/react` is not a dependency of this package, so the hook is-// driven through a probe component the way the other browser suites here do.(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;let host: HTMLDivElement | null = null;let root: Root | null = null;-/**- * The value the probe last produced. Module scope keeps the probe prop-free, and- * it is published from an effect so the probe stays render-pure.- */+/** Publish probe output from an effect to keep rendering pure and the probe prop-free. */const latest: { ids: string[] } = { ids: [] };const Probe = ({ activeId, limit, resetKey }: { activeId: string | undefined; limit?: number; resetKey: string }) => {@@ -154,10 +149,7 @@ describe('instances shown elsewhere', () => {right: { activeInstanceId: 'layers', instanceIds: ['layers'] },};- // `floatWidget` hands the region off to a fallback, so `image-map` no- // longer appears as any region's active — only the floating map catches- // it, which is what keeps the region's kept copy from shadowing the- // floating window.+ // Floating removes the regional active id; floating ids must also evict kept regional copies.expect(getActiveInstanceIdsOutside(widgetRegions, 'right', { 'image-map': {} })).toEqual(['canvas', 'image-map']);});});diff --git a/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.ts b/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.tsindex 4f22feaf5f..b0f4cf3b92 100644--- a/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.ts@@ -1,38 +1,12 @@import { useState } from 'react';-/**- * How many instances a region keeps mounted behind it. A kept gallery holds its- * virtualizer, its measurement cache and the decoded images in its window, and- * every kept widget holds its DOM, so this is bounded rather than unlimited;- * three covers every realistic back-and-forth.- */+/** Bound kept mounts because each retains DOM and widgets may retain decoded images and measurement caches. */export const MOUNTED_INSTANCE_LIMIT = 3;/**- * The instance ids a region keeps mounted, most-recently-shown last.- *- * Deliberately independent of the region's own `instanceIds`: applying a preset- * replaces those wholesale, so a widget the user is switching away from is no- * longer in the region at all. Remembering it here is what lets `<Activity>`- * hold it — and with it the canvas viewport, gallery scroll and selection that- * a full unmount would take.- *- * `resetKey` is the active project id. Widget instance ids are deterministic and- * identical in every project, so a remembered id does not go stale on a project- * switch — it silently resolves to a real instance of the *new* project, and the- * previous project's scroll offsets and in-widget selection would surface under- * it. Dropping the set when the key changes is what keeps a session's memory- * scoped to the project it belongs to.- *- * Ephemeral by design. A remembered mount is a session affordance, not state- * worth persisting.- *- * Known and accepted: closing a widget reads as hiding it. `closeWidgetPlacement`- * takes the instance out of its region but leaves it in `widgetInstances`, so a- * closed widget is kept like any other and reopens with its state intact — the- * way a desktop editor reopens a panel you closed. Telling a close apart from a- * layout switch needs an explicit dismissal signal that does not exist yet; until- * it does, `limit` is what bounds the consequence.+ * Remember recently shown instances independently of replaced region membership. Reset on project id because+ * instance ids repeat across projects. State is ephemeral; closing hides rather than destroys retained instances,+ * bounded by limit.*/export const useMountedInstanceIds = (activeId: string | undefined,@@ -57,23 +31,8 @@ export const useMountedInstanceIds = (};/**- * Kept ids, minus any instance another region is actively rendering.- *- * One instance can be placed in more than one region — `preview` is Compose's- * centre view and also sits in Edit's and Automate's right rails — so a kept- * hidden copy can end up shadowing a live one: the same instance mounted twice,- * one of them a ghost the user can neither see nor dismiss. A floated instance- * is the same hazard: `floatWidget` hands its region off to a fallback but- * does not touch this hook's remembered set, so the region's kept copy would- * otherwise stay mounted hidden while `FloatingWidgetWindow` mounts the same- * instance visible — and re-docking would make the stale hidden copy visible- * again, silently discarding whatever happened in the floating window.- *- * Only the regions' `activeInstanceId` values and the floating instance ids- * are consulted. Region membership (`instanceIds`) is the thing a preset- * replaces wholesale, and deriving anything here from it would reintroduce- * the very filtering bug this mechanism exists to avoid. Actives and floating- * ids are a small, stable signal that cannot.+ * Exclude instances active in another region or floating window to prevent hidden duplicate mounts. Consult+ * active/floating ids, not preset-replaced membership lists.*/export const withoutInstancesShownElsewhere = (mountedIds: string[],diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.tsxindex 118226ecb3..c3d030d2ac 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.tsx@@ -13,11 +13,8 @@ const FloatingWidgetWindow = lazy(() =>const EMPTY_FLOATING: Record<WidgetInstanceId, FloatingWidgetState> = {};/**- * Renders every floated widget instance of the active project as a fixed- * window. Mounted once in the shell; nothing renders while no widget floats.- * z-order derives from the RANK of each window's stackOrder, not its raw- * value — stackOrder grows monotonically forever (it is persisted), and raw- * values would eventually climb past the UI library's layer tokens.+ * Render floating windows with z-order derived from stackOrder rank, keeping persisted ordering within UI layer+ * bounds.*/export const FloatingWidgetLayer = () => {const floatingWidgets = useActiveProjectSelector(diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsxindex 58d5f8099b..6e8161c782 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsx@@ -18,10 +18,8 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';/**- * A floated widget renders bare inside this window, so its header controls- * only exist here — the map's label and selection toggles used to disappear on- * float. The window mounts widget actions and the shared settings gear, with- * its own shade/maximize/dock controls replacing the frame's layout controls.+ * Floating windows must retain widget actions and settings while substituting their own shade/maximize/dock+ * controls.*/const windowMocks = vi.hoisted(() => ({@@ -69,8 +67,7 @@ vi.mock('./createWidgetRuntime', () => ({ useWidgetRuntime: () => ({}) }));import { FloatingWidgetWindow } from './FloatingWidgetWindow';-// The floating slot includes settings, while the overflow menu belongs to the-// full docked header cluster.+// Floating chrome includes settings; overflow belongs to the docked header cluster.const manifest = {allowFloating: true,allowedRegions: ['center', 'left', 'right'],@@ -161,8 +158,7 @@ const renderWindow = async (floatingState: FloatingWidgetState = state) => {);await implementationPromise;});- // The chrome slot suspends on the implementation chunk; one more flush lets- // the resolved actions paint before the assertions run.+ // Flush the suspended chrome slot once more before asserting resolved actions.await act(async () => {await Promise.resolve();});@@ -212,8 +208,6 @@ describe('FloatingWidgetWindow chrome', () => {const shade = host!.querySelector<HTMLButtonElement>('button[aria-label="Shade"]')!;const [actionRect, gearRect, shadeRect] = [action, gear, shade].map((button) => button.getBoundingClientRect());- // A block-level wrapper around the slot laid the gear out under the- // actions group — visibly a second row of chrome in the title bar.expect(gearRect.top).toBeLessThan(actionRect.bottom);expect(gearRect.bottom).toBeGreaterThan(actionRect.top);// Strip order: widget actions, then the gear, then the window's controls.@@ -241,10 +235,7 @@ describe('FloatingWidgetWindow chrome', () => {await renderWindow();- // The chrome slot's `use()` rethrows the rejected load on every render.- // Nothing between this bar and the app root catches it, so the window has- // to contain it — dropping the widget's actions, keeping the dock control- // that is the only way back to the rail.+ // Contain repeated rejected-resource throws in the title bar so the window's dock control survives.expect(host?.querySelector('button[aria-label="Toggle cluster labels"]')).toBeNull();expect(host?.querySelector<HTMLButtonElement>('button[aria-label="Dock to panel"]')).not.toBeNull();});diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsxindex 700e365e87..58060501ec 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx@@ -46,29 +46,15 @@ const FLOATING_BASE_Z_INDEX = 800;const FLOATING_STEP_PX = 16;/**- * The title bar is a drag handle first and a control strip second: a- * `pointerdown` anywhere on it that is not inside a `<button>` starts a window- * drag, and a double-click shades it. Widget-supplied chrome is arbitrary —- * a switch, a slider, a menu trigger rendered as a div — so it is isolated- * from both gestures rather than trusted to be a button.+ * Isolate arbitrary widget controls from title-bar drag and double-click shade gestures; not every control is a+ * button.*/const stopChromeEvent = (event: ReactPointerEvent<HTMLDivElement> | ReactMouseEvent<HTMLDivElement>): void =>event.stopPropagation();/**- * Drops the widget's title-bar chrome if it throws, keeping the window itself- * alive. The chunk carrying a widget's implementation can fail to load — a- * deploy replaced the hashed file, or the tab is offline — and the deferred- * resource then hands `use()` the same rejected thenable on every render.- * Inside the body that throw lands in `WidgetFailureBoundary`, which offers a- * retry; up here there is no boundary between this bar and the app root, so an- * unguarded throw would take the whole workbench down — and with it the dock- * control that is a floated widget's only way back to the rail.- *- * Recovery is deliberately one-way: a retry from the body's failure card- * reloads the implementation but does not reset this boundary, so the chrome- * returns on the window's next mount. Chrome that stays missing is a far- * cheaper failure than chrome that cannot be reached at all.+ * Contain failed widget chrome so the window and dock control survive. Body retry does not reset this boundary;+ * chrome returns on the next window mount.*/class FloatingChromeBoundary extends Component<{ children: ReactNode }, { hasFailed: boolean }> {state = { hasFailed: false };@@ -82,13 +68,6 @@ class FloatingChromeBoundary extends Component<{ children: ReactNode }, { hasFai}}-/**- * One detached widget window: fixed-position chrome with a draggable title- * bar, a corner resize handle, shade/maximize/dock controls, and the standard- * widget renderer as its body. Drag and resize use the same raw-pointer- * pattern as the panel resize handles — transient local px state, one commit- * to the reducer on release.- */export const FloatingWidgetWindow = ({instanceId,stackRank,@@ -120,9 +99,7 @@ export const FloatingWidgetWindow = ({const pointerSessionRef = useRef<AbortController | null>(null);- // A drag can outlive the window — docking from a command, an applied preset,- // or a project switch all unmount mid-gesture — and window-level listeners- // would then stay bound for the rest of the session.+ // Dispose window listeners on unmount because docking, presets, or project switches can interrupt drags.useEffect(() => () => pointerSessionRef.current?.abort(), []);const beginPointerOperation = useCallback(@@ -152,9 +129,7 @@ export const FloatingWidgetWindow = ({};const handlePointerMove = (moveEvent: PointerEvent) => {- // Releasing the button over another application swallows `pointerup`,- // and the window would then follow the cursor with nothing held. The- // first move that arrives with no button down ends the drag instead.+ // End dragging on a move with no pressed button in case another application swallowed pointerup.if (moveEvent.buttons === 0) {handlePointerUp();@@ -198,9 +173,7 @@ export const FloatingWidgetWindow = ({[beginPointerOperation]);- // Pointer gestures are not the only way to place a window: without these the- // keyboard can shade, maximize and dock a floated widget but never move or- // resize it. Stepping mirrors the panel resize handles in `WidgetFrames`.+ // Provide keyboard move/resize alongside shade/maximize/dock, matching panel resize steps.const handleTitleKeyDown = useCallback((event: ReactKeyboardEvent<HTMLDivElement>) => {const step = event.shiftKey ? FLOATING_STEP_PX * 2 : FLOATING_STEP_PX;@@ -212,11 +185,7 @@ export const FloatingWidgetWindow = ({};const offset = offsets[event.key];- // Only the bar itself moves the window. It hosts real controls — its own- // shade/maximize/dock buttons and the widget's header actions — and- // React sees their keystrokes bubble up here: without this, an arrow key- // pressed on a focused toggle moved the window 16px and wrote the new- // geometry to the reducer.+ // Handle movement keys only on the bar itself; controls' bubbling arrows must not alter geometry.if (!offset || state.mode === 'maximized' || event.target !== event.currentTarget) {return;}@@ -254,9 +223,7 @@ export const FloatingWidgetWindow = ({);const handleFocus = useCallback(() => widgets.focusFloating(instanceId), [instanceId, widgets]);- // Docking remounts the widget in its rail. The draft registry's cleanup only- // deregisters the flusher, so an uncommitted edit needs committing first —- // the same reason `closeWidgetPlacement` flushes before it unmounts.+ // Flush drafts before docking remounts the widget; registry cleanup only removes flushers.const handleDock = useCallback(() => {flushWorkbenchDrafts();widgets.dockFloating(instanceId);@@ -284,14 +251,7 @@ export const FloatingWidgetWindow = ({return null;}- // A floated widget that fails registration — or whose type has gone from the- // registry entirely in a later build — keeps its chrome. Rendering nothing- // would strand the instance: it is in no region, so the dock control in this- // title bar is the only way back to the rail, and to the docked failure card- // that owns the retry. This is why a `hidden` widget still shows a window- // here while `getWidgetsForRegion` keeps it out of the rails: a rail the- // widget is missing from is merely tidy, a window it is missing from is a- // widget the person cannot reach.+ // Retain window chrome for missing or failed widgets so users can dock them back to the retry surface.const isEnabled = widget?.status === 'enabled';const label = widget ? resolveWidgetInstanceLabel(instance, widget.manifest, t) : (instance.title ?? instance.id);const geometry = dragGeometry ?? state;@@ -320,15 +280,7 @@ export const FloatingWidgetWindow = ({rounded={isMaximized ? 'none' : 'md'}shadow="xl"zIndex={FLOATING_BASE_Z_INDEX + stackRank}- // The docked frames carry these and the hotkey runtime reads them to tell- // which widget a keystroke is for. Floating content renders bare — this- // window is its chrome — so without them `getHotkeyTargetWidget` found- // nothing and the runtime fell back to the last focused REGION's active- // widget: Delete pressed over a floating window ran the docked Gallery's- // delete-selection on whatever that had selected. `floating` is a legal- // contribution-source region and is what the runtime registers this- // widget's own contributions under, so its hotkeys now resolve as well —- // previously they could not fire at all.+ // Mark floating widget identity and region so hotkeys target it rather than the last focused docked widget.data-hotkey-widget-instance-id={instanceId}data-hotkey-widget-region="floating"data-hotkey-widget-type-id={instance.typeId}@@ -361,12 +313,10 @@ export const FloatingWidgetWindow = ({</Text></HStack><HStack flexShrink={0} gap="1">- {/* The widget's own header toggles: floated content renders bare, so- without this the docked header's controls would simply vanish on- float. Frame-level actions stay out — this bar carries its own.- The slot yields siblings (the widget's actions group and the- settings gear), so the wrapper is a row: as a block it stacked the- gear under the actions instead of continuing the strip. */}+ {/*+ * Render widget actions and settings in a row because floating content has no frame header; window+ * controls already own layout actions.+ */}{isEnabled && widget ? (<FloatingChromeBoundary><Suspense fallback={null}>diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/GraphPreviewHost.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/GraphPreviewHost.tsxindex 5c594d6e90..881a6c61fe 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/GraphPreviewHost.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/GraphPreviewHost.tsx@@ -10,10 +10,7 @@ import { useTranslation } from 'react-i18next';import { buildGraphPreviewSource } from './graphPreviewSource';-/**- * Mounted only while the preview dialog is open (it subscribes to the whole- * active project so the compiled graph tracks every settings edit live).- */+/** Subscribe to the whole project only while the preview is open so graph compilation follows settings edits. */export const GraphPreviewHost = ({isOpen,surface,diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsxindex f502b99a08..225dfa65c1 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsx@@ -12,11 +12,7 @@ import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-/**- * The drag-to-collapse gesture against the *real* store, reducer and shell- * gating — the unit tests either side of this one mock the command layer, so- * between them they cannot catch a break in the wiring itself.- */+/** Exercise real store/reducer/shell wiring absent from command-mocked unit tests. */const storeRef = vi.hoisted(() => ({ current: null as WorkbenchInternalStore | null }));@@ -102,9 +98,7 @@ beforeEach(() => {root = createRoot(host);storeRef.current = createWorkbenchStore();- // Presets ship the bottom strip closed *and* collapsed, and `setRegionCollapsed`- // deliberately does not touch `panels.isBottomOpen`. Open it the way the app- // does — by selecting its active widget from the status rail.+ // Open the bottom strip through its active status widget; setRegionCollapsed does not set isBottomOpen.const bottom = storeRef.current.getSnapshot().activeProject.widgetRegions.bottom;storeRef.current.commands.widgets.select({diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/RailActiveContrast.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/RailActiveContrast.browser.test.tsxindex 09c32137b0..0036ce3b77 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/RailActiveContrast.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/RailActiveContrast.browser.test.tsx@@ -11,11 +11,8 @@ import { afterEach, describe, expect, it } from 'vitest';import { WIDGET_ITEM_SX } from './WidgetBar';/**- * The rail's active state is a neutral fill with the widget icon in- * `brand.fg`. Two things can silently break it, so both are pinned here:- * `brand.fg` reverting to the raw seed (1.20:1 on the light theme's panel —- * invisible), and the active fill being swapped for a brand tint, which on the- * light theme lands within 1.06:1 of the rail behind it.+ * Verify brand icon contrast and neutral active fill; raw brand seed/tinted fills are nearly invisible on light+ * rails.*/const RAIL_ITEM_SX = WIDGET_ITEM_SX;diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsxindex af44d95aea..0f6a054420 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx@@ -20,25 +20,13 @@ import { Component, lazy, Suspense, useCallback, useMemo, useState, type ReactNoimport { useTranslation } from 'react-i18next';/**- * The widget frame's shared header actions menu. It hosts the universal- * graph-bearing actions (`Set Source`, `View Graph`) and any extra entries the- * widget's manifest contributes via `headerMenu` — one menu per widget, so- * widgets extend the frame instead of stacking their own menus and toolbars.- *- * Floating is not among them: it is a mode toggle, so it renders as its own- * header icon ({@link WidgetFloatButton}) opposite the floating window's dock- * control rather than as a menu item.+ * Combine graph actions and manifest headerMenu contributions in one menu. Floating has its own {@link+ * WidgetFloatButton} mode toggle.*/const GraphPreviewHost = lazy(() => import('./GraphPreviewHost'));-/**- * The preview is a dialog over the widget, not part of it: a throw inside it- * (a failed chunk load, a compile edge case that escaped the source) surfaces- * as a toast and drops the dialog, instead of climbing to the widget's- * failure boundary and replacing the whole widget with a failure card. An- * error unmounts the host, so the next open starts a fresh boundary.- */+/** Contain preview errors as a toast and closed dialog, preserving the widget. Reopening creates a fresh boundary. */class GraphPreviewBoundary extends Component<{ children: ReactNode; onError: (error: Error) => void },{ hasFailed: boolean }@@ -116,9 +104,7 @@ export const WidgetActionsMenu = ({}) => {const { t } = useTranslation();const [isPreviewOpen, setIsPreviewOpen] = useState(false);- // Mount outlives `isPreviewOpen`: dropping the host the moment the dialog- // closes cancels its exit transition, so the preview blinked out of- // existence. The host reports when the transition is done instead.+ // Keep the host until exit transition completion to avoid abrupt dialog removal.const [isPreviewMounted, setIsPreviewMounted] = useState(false);const label = resolveWidgetLabel(manifest, t);const surface = useMemo(diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsxindex 6690ec9b9a..b53ad1371e 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx@@ -173,17 +173,8 @@ const RailGroup = ({};/**- * Rail states: idle icon dimmed, hover and active share the same fill, and- * only the active icon takes the brand hue.- *- * The brand lives in the icon rather than the fill because it cannot live in- * the fill: the seed is a 92%-lightness lime, so every brand tint of the light- * theme's near-white rail lands within 1.06:1 of it — a state you cannot see.- * As an icon on a neutral fill it clears 3:1 on all five themes, which- * `RailActiveContrast.browser.test.tsx` pins.- *- * The attribute selectors outrank `rowRecipe`'s own `_hover`, so hovering the- * active item leaves it alone instead of flickering to the hover fill.+ * Use brand color on active icons over neutral fill for cross-theme contrast. Attribute selectors preserve active+ * styling on hover.*/export const WIDGET_ITEM_SX: SystemStyleObject = {display: 'flex',diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetEnableMenu.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetEnableMenu.tsxindex 6ea371aaaa..c2d091f8a0 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetEnableMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetEnableMenu.tsx@@ -58,8 +58,7 @@ const getWidgetEnableMenuTriggerButton = (label: string, trigger: WidgetEnableMereturn (<Flexalign="center"- // The rail's strips stretch to stay full-width drop targets; the trigger- // is a lone fixed-size child and must center itself to line up with them.+ // Center the fixed-size trigger within full-width rail drop targets.alignSelf={isBottom ? undefined : 'center'}aria-label={label}as="button"diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsxindex 1c64d8218b..9ed69391c1 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsx@@ -19,11 +19,7 @@ import { WidgetPanelFrame, WidgetTooltipFrame } from './WidgetFrames';interface WidgetFailureBoundaryProps {children: ReactNode;- /**- * Presentation context, mirroring what `WidgetLoadingFallback` receives. When- * supplied, the fallback keeps the widget's own frame — panel width, overflow- * clamp and resize handle survive the crash. Headless hosts omit it.- */+ /** Retain region framing, size, and resize handles on failure; headless hosts omit presentation context. */instance?: WidgetInstanceRuntimeMeta;presentation?: WidgetViewProps['presentation'];region?: WidgetViewProps['region'];@@ -140,12 +136,7 @@ const WidgetFailureHeader = ({ label, region }: { label: string; region: WidgetV</Box>);-/**- * Presentation- and region-aware failure UI, the twin of `WidgetLoadingFallback`.- * Rendering the bare card everywhere used to blow a crashed widget out of its- * region: in the status bar it overflowed a 24px strip, and in a side panel it- * destroyed the frame that carries the panel width and the resize handle.- */+/** Match loading-frame geometry on failure so status cards do not overflow and panels retain resizing. */const WidgetFailureFallback = ({details,instance,@@ -191,8 +182,6 @@ const WidgetFailureFallback = ({</>);- // Keeping the widget's own frame is the whole point: the panel frame carries- // the region width, the overflow clamp and the resize handle.return isPanel ? (<WidgetPanelFrame instanceId={instance?.id} region={region} typeId={instance?.typeId}>{framed}diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFloatButton.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFloatButton.browser.test.tsxindex bfd0ebf87e..3fe547b628 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFloatButton.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFloatButton.browser.test.tsx@@ -12,12 +12,8 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';/**- * The float control replaced a menu item, so the conditions that used to hide- * that item now decide whether a button renders at all: only a widget whose- * manifest forbids floating, and the floating region itself. Even the last- * center view may float — the emptied surface falls back to the center's- * fallback view until the window docks back. Docking is covered by the- * floating window's own chrome.+ * Offer floating only from dockable panel regions when the manifest allows it; center and already-floating chrome+ * expose no float button.*/const floatMocks = vi.hoisted(() => ({diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsxindex a331c81cfd..db045a308f 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx@@ -81,14 +81,11 @@ export const WidgetPanelFrame = ({// Clamped at render, not just on commit, so a persisted size from before a// bounds change heals on screen immediately instead of on the next resize.const displaySizePx = clampPanelSize(region, drag?.sizePx ?? regionState.sizePx);- // Mid-drag past the threshold the panel snaps shut on screen, dockview-style;- // the store's collapse is only committed on release.+ // Preview collapse mid-drag; commit store collapse only on release.const isSnappedShut = drag?.isSnappedShut ?? false;const renderSizePx = isSnappedShut ? 0 : displaySizePx;- // Side panels yield to a viewport that cannot hold them (see- // `panelSizeProps`), so the width on screen can sit below the stored one.- // The gesture, the keyboard floor and the separator's announced value all- // work from what is on screen; the store keeps the preferred size.+ // Use rendered width for dragging, keyboard floors, and ARIA values when viewport constraints shrink stored+ // preferences.const frameRef = useRef<HTMLDivElement | null>(null);const [measuredSizePx, setMeasuredSizePx] = useState<number | null>(null);@@ -137,9 +134,7 @@ export const WidgetPanelFrame = ({let nextDrag: PanelResizeDrag = { isSnappedShut: false, sizePx: clampPanelSize(region, startSizePx) };- // Keeps the gesture alive when the pointer leaves the window, which is- // where it goes when dragging the bottom strip shut. Throws if the- // pointer is already gone; the window listeners still carry the drag.+ // Capture keeps dragging across window edges; window listeners cover capture failures after pointer loss.try {event.currentTarget.setPointerCapture(event.pointerId);} catch {@@ -210,9 +205,7 @@ export const WidgetPanelFrame = ({event.preventDefault();- // Keyboard parity with the drag: a further collapse-ward step at the- // floor collapses, instead of silently clamping forever. A squeezed- // panel is already below the floor on screen, so it collapses too.+ // A collapse-ward keyboard step at or below the visible floor collapses the panel.if (sizeChange < 0 && visibleSizePx <= minPanelSizePx) {layout.setRegionCollapsed(region, true);@@ -223,11 +216,8 @@ export const WidgetPanelFrame = ({},[commitSize, displaySizePx, isBottom, isLeft, layout, maxPanelSizePx, minPanelSizePx, region, visibleSizePx]);- // The stored size is a preference, not a guarantee: side panels yield- // (`flexShrink`) when the viewport cannot hold both of them plus the- // center's minimum — a portrait tablet — so the center never collapses and- // the opposite rail never gets pushed offscreen. The bottom panel keeps a- // hard height because the column has no minimum-width peer to protect.+ // Treat side widths as preferences that shrink to protect center space and opposite rails; bottom height remains+ // fixed.const panelSizeProps = useMemo(() =>isBottom@@ -235,9 +225,7 @@ export const WidgetPanelFrame = ({: { flexShrink: 1, h: 'full', w: `${renderSizePx}px` },[renderSizePx, isBottom]);- // Inside the panel's box, never straddling its edge: the frame clips its- // overflow, so a handle hung outside loses that half and leaves a ~4px- // target sitting behind the border people actually aim at.+ // Keep resize handles inside clipped panel bounds so their full hit target remains reachable.const resizeOrientationProps = useMemo(() => (isBottom ? { h: '2', left: '0', right: '0', top: '0' } : { bottom: '0', top: '0', w: '2' }),[isBottom]@@ -293,13 +281,6 @@ export const WidgetPanelFrame = ({);};-/**- * The docked half of the float/dock pair: one icon in the widget's header- * actions that detaches it into a floating window. Its opposite — the dock- * control — sits in the same corner of `FloatingWidgetWindow`'s title bar, so- * the mode is one click away either way instead of a menu item in one mode and- * a button in the other.- */export const WidgetFloatButton = ({instanceId,manifest,@@ -311,15 +292,9 @@ export const WidgetFloatButton = ({}) => {const { t } = useTranslation();const { widgets } = useWorkbenchCommands();- // A dialog or popover's chrome never floats, and neither does the center:- // its views are the work surface, and a window over an emptied surface is a- // view the rails cannot reach. Panels are the dock-back target.const dockableRegion = isWidgetRegion(region) && region !== 'center' ? region : undefined;- // Floating unmounts the docked subtree; the draft registry's cleanup only- // deregisters the flusher, so an uncommitted edit is lost without this. The- // region rides along: one instance may be placed in several regions (the- // preview lives in the center and a rail), and the window docks back into- // the one whose button was clicked.+ // Flush drafts before floating unmounts the docked view; preserve the clicked region as the multi-region+ // instance's dock origin.const handleFloat = useCallback(() => {if (!dockableRegion) {return;@@ -328,8 +303,6 @@ export const WidgetFloatButton = ({flushWorkbenchDrafts();widgets.float(instanceId, dockableRegion);}, [dockableRegion, instanceId, widgets]);- // Floating is offered only from dockable regions; the floating window's own- // chrome carries the dock control.const canFloat = Boolean(manifest.allowFloating) && dockableRegion !== undefined;if (!canFloat) {@@ -351,13 +324,7 @@ export const WidgetFloatButton = ({);};-/**- * The trailing action cluster of a widget's chrome: the manifest's own- * `headerActions`, the settings gear, the float control, and the shared- * overflow menu. Panels render it inside {@link WidgetHeader}; the center- * region renders it on its own, floating over the work surface, so it lives- * apart from the header row.- */+/** Share widget actions, settings, float, and overflow between panel headers and hoisted center chrome. */export const WidgetHeaderActionsGroup = ({actions,HeaderMenu,@@ -419,8 +386,6 @@ export const WidgetHeader = ({runtime: WidgetRuntimeApi;}) => {const { t } = useTranslation();- // Manifests may provide a component label (e.g. Workflow's editable- // `Workflow / [name]`); plain strings render as the standard title.const label = resolveWidgetInstanceLabel(instance, manifest, t);return (diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsxindex c94f9b3084..f317dec74c 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx@@ -38,12 +38,8 @@ export const projectNeedsWorkflowHost = (project: WidgetHostProject): boolean =>const WidgetHost = ({ widget }: { widget: ReturnType<typeof getWidgetHosts>[number] }) => {const Host = use(widget.host!.load());- // react-compiler flags any JSX tag that is directly the value returned by- // `use()` as though it were freshly created each render. `Host` is the- // module's cached export, resolved once by the deferred resource and- // stable across renders; the false positive disappears the moment the- // value is read through a property access instead of being the call's- // direct result, which is what the sibling `WidgetRenderer` slots do.+ // Host is the deferred resource's stable cached export; React Compiler misidentifies a direct use() result as a+ // new component.// eslint-disable-next-line react/static-componentsreturn <Host />;};diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.browser.test.tsxindex 2bf729c1ce..802281d9f1 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.browser.test.tsx@@ -120,9 +120,8 @@ afterEach(async () => {});describe('WidgetLoadingFallback', () => {- // `CenterArea` owns the center region's chrome and keeps it mounted across- // the load, so the fallback paints no header of its own — a header here would- // appear and then collapse the moment the implementation resolved.+ // CenterArea keeps chrome mounted during loading; fallback headers would disappear and shift layout on+ // resolution.it('fills the center region with announced, chrome-free surface while the implementation loads', async () => {const { widget } = createTestWidget();await render(<WidgetLoadingFallback instance={instance} region="center" widget={widget} />);diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.tsxindex ab44007f36..312668c08e 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.tsx@@ -142,9 +142,7 @@ export const WidgetLoadingFallback = ({ instance, presentation, region, widget });}- // The center region's chrome floats above the work surface and is owned by- // `CenterArea`, so a loading center view is just the recessed surface — no- // header row to paint and then collapse when the implementation resolves.+ // CenterArea owns persistent chrome; the loading view only paints the recessed surface.if (region === 'center') {return (<Flexdiff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsxindex b76f9ca422..7d3eec4ebf 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsx@@ -16,9 +16,7 @@ const frameMocks = vi.hoisted(() => ({sizePx: 450,}));-// The frame reads the region's persisted size and writes back through the-// layout commands; both are stubbed so the drag arithmetic is what is under-// test, not the reducer.+// Stub persisted size and commands to isolate frame drag arithmetic from reducer behavior.vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({...(await importOriginal<typeof workbenchContext>()),shallowEqual: Object.is,@@ -129,8 +127,6 @@ describe('WidgetPanelFrame resize', () => {await dragTo(separator, { widthPx: 260 });expect(frameMocks.setRegionCollapsed).toHaveBeenCalledExactlyOnceWith('left', true);- // The width the user chose survives the collapse, so the rail button- // reopens the panel where they left it rather than at the floor.expect(frameMocks.setRegionSize).not.toHaveBeenCalled();});@@ -159,9 +155,7 @@ describe('WidgetPanelFrame resize', () => {expect(separator.getAttribute('aria-valuemax')).toBe('720');});- // The frame clips its overflow, so a handle hung outside the panel edge- // loses that half — leaving a sliver behind the border people aim at, and a- // gesture that silently does nothing.+ // Keep handles inside clipped bounds so the whole target receives pointer gestures.it.each(['left', 'right', 'bottom'] as const)('keeps the whole %s handle inside the clip', async (region) => {const separator = await renderFrame(region);const handle = separator.getBoundingClientRect();@@ -258,9 +252,7 @@ describe('WidgetPanelFrame resize', () => {});});-// A viewport too narrow for the stored size (a portrait tablet) squeezes the-// side panel below its floor on screen. The gesture, the keyboard floor and-// the announced value then work from the width that is actually there.+// Use actual squeezed width for gestures, keyboard floors, and announced values.describe('WidgetPanelFrame squeezed by the viewport', () => {const renderSqueezed = async () => {host!.style.cssText = 'display:flex;height:600px;width:400px;';diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRegionDropOverlay.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRegionDropOverlay.tsxindex 03fe1cceee..02ff414ee7 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRegionDropOverlay.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRegionDropOverlay.tsx@@ -4,12 +4,7 @@ import { DropZone, type DropZoneProps } from '@platform/ui/DropZone';const DISALLOWED_STYLES: DropZoneProps = { bg: 'bg.muted', borderColor: 'border.subtle' };-/**- * The one drag-time chrome for widget drop targets: rails render it across- * their whole strip, the status bar renders one per cluster with inset- * overrides. Styling lives in `DropZone`; keep consumers prop-thin so the- * look cannot fork.- */+/** Share DropZone styling across full rails and inset status clusters; consumers supply placement only. */export const WidgetRegionDropOverlay = ({dropState,isOver,diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.browser.test.tsxindex 27c0cc8779..9ce4c088d6 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.browser.test.tsx@@ -212,9 +212,7 @@ afterEach(async () => {});describe('WidgetRenderer loading identity transitions', () => {- // The center region and the right-rail docks have no header row of their own- // (`CenterArea` and the dock tab strips carry it), so the identity slot lives- // in the left and bottom panel frames.+ // Center and right docks own separate chrome; identity slots belong in left/bottom panel frames.it('swaps spinner for icon without moving a renamed standard header', async () => {const { resolve, widget } = createDeferredWidget();await render(<WidgetRenderer instance={createInstance('Renamed widget')} region="left" widget={widget} />);diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsxindex 25f9878f19..707a0c23dc 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx@@ -47,11 +47,8 @@ type WidgetChromeSlotName = 'actions' | 'label' | 'viewActions';interface WidgetChromeSlotByIdProps {instanceId: string;/**- * The region the hoisted chrome acts for; the center region, which hoists- * its chrome for every widget it shows, is the default. It becomes the- * runtime's region, which is what `closeWidgetInstance` and- * `revealWidgetInstance` act on — a caller hoisting chrome for some other- * region must say so, or those act on the center's placement instead.+ * Specify the runtime region for hoisted chrome outside center so close/reveal commands target the correct+ * placement.*/region?: WorkbenchRegion;slot: WidgetChromeSlotName;@@ -68,14 +65,8 @@ export const WidgetRendererById = ({ instanceId, widget, ...props }: WidgetRende};/**- * Renders one chrome slot of a widget outside its own frame. The center region- * floats its chrome over the work surface and a floating window owns its title- * bar, so their label and action slots are mounted by `CenterArea` and- * `FloatingWidgetWindow` rather than by the widget's frame — this resolves the- * same implementation and runtime the view would get.- *- * Suspends on first load of the implementation chunk; callers wrap it in their- * own `Suspense` so the rest of the chrome paints immediately.+ * Resolve widget chrome with the view's implementation/runtime for center and floating hosts. Callers supply+ * Suspense so other chrome paints during chunk loading.*/export const WidgetChromeSlotById = ({ instanceId, region = 'center', slot, widget }: WidgetChromeSlotByIdProps) => {const selection = useActiveProjectSelector(@@ -132,15 +123,12 @@ const WidgetChromeSlot = ({return null;}- // A widget-supplied label only replaces the standard title, which the center- // view selector already shows — a renamed instance keeps the selector's text.+ // Custom labels replace only standard titles; renamed instances retain selector text.if (slot === 'label') {return HeaderLabel && !instanceMeta.title ? <HeaderLabel region={region} /> : null;}- // The window chrome around a floating widget already carries the frame's own- // controls (shade, maximize, dock). Preferences remain available beside the- // widget's own actions without duplicating those layout controls.+ // Keep preferences beside floating widget actions without duplicating the window's layout controls.if (slot === 'viewActions') {return (<>@@ -302,8 +290,6 @@ const WidgetShellFrame = ({);}- // The center region floats its chrome over the work surface, so the widget's- // header slots are mounted by `CenterArea` and the body runs full-bleed here.return (<Flexbg="bg.inset"@@ -408,13 +394,8 @@ const HeaderSlot = memo(function HeaderSlot({);}, areSlotPropsEqual);-// Grid content with minH="full" stretches fill-height widget views (gallery,-// layers, preview) to the viewport while letting flowing views grow and scroll.-// The explicit minmax(0, 1fr) column is load-bearing: an implicit auto track-// sizes to its item's max-content, so any long unbreakable text or wide row-// inside a widget (prompt strings, UUIDs, button groups) silently stretches-// the widget past its panel and clips. Panels only ever scroll vertically.-// Covered by PanelBodySlot.browser.test.tsx.+// Stretch fill-height views while allowing flowing content to scroll vertically. minmax(0,1fr) prevents long+// content from widening and clipping panels.const panelBodyContentProps = {display: 'grid',gridTemplateColumns: 'minmax(0, 1fr)',diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetSourceLockBadge.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetSourceLockBadge.tsxindex 4c418d00b5..88203bdc24 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetSourceLockBadge.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetSourceLockBadge.tsx@@ -6,14 +6,7 @@ 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.- */+/** Mark the pinned source widget only; presets describe arrangement rather than invocation ownership. */export const WidgetSourceLockBadge = ({ typeId }: { typeId?: WidgetTypeId }) => {const sourceId = typeId ? getSourceIdForWidgetTypeId(typeId) : null;const isLockedSource = useActiveProjectSelector(diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.tsindex 306f8e1178..22c936f900 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts@@ -18,11 +18,8 @@ import { getDestinationLabel } from '@workbench/invocation';import { getProjectWidgetValues } from '@workbench/widgetState';/**- * Pure translation from the active project + surface into the preview- * dialog's data. Kept side-effect free so it can run on every keystroke- * (`GraphPreviewHost` recomputes it in a `useMemo`) without triggering any- * loads itself — callers are responsible for ensuring models/templates are- * fetched (`ensureModelsLoaded`, `ensureInvocationTemplatesLoaded`).+ * Translate project/surface to preview data without effects; callers load models/templates before per-edit+ * compilation.*/export interface GraphPreviewSourceDeps {models: readonly ModelConfig[] | undefined;@@ -97,9 +94,7 @@ const buildGenerateSource = (): GraphPreviewSourceWithoutDestination => {let result: ReturnType<typeof compileGeneratePreviewGraph>;- // A compile that throws (a model policy the stored values violate, a graph- // builder edge case) is a reason the preview shows, not a render error that- // takes the widget's chrome down with it.+ // Return compile failures as preview reasons instead of throwing through widget chrome.try {result = compileGeneratePreviewGraph({destination: project.invocation.destination,diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/useWidgetSortable.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/useWidgetSortable.tsindex 43a475a532..cac7eab427 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/useWidgetSortable.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/useWidgetSortable.ts@@ -63,10 +63,7 @@ export const useWidgetSortable = ({return {dragHandleProps: { ...attributes, ...listeners },isDragging,- // Tabs and other semantic controls already own their role, state, and- // roving tab index. Keep dnd-kit's pointer/keyboard listeners and- // description without letting its generic "button" contract overwrite- // the host control's accessibility semantics.+ // Preserve host roles, state, and roving tab indices while adding dnd listeners/descriptions.semanticDragHandleProps: {...semanticAttributes,...semanticListeners,@@ -75,9 +72,7 @@ export const useWidgetSortable = ({setNodeRef: setSortableNodeRef,style: {transform: CSS.Transform.toString(transform),- // dnd-kit's inline transform transition replaces the CSS transition- // outright, which froze the chips' hover fills; compose the fill fade- // back in (motion-aware duration token).+ // Compose fill fading with dnd-kit's inline transform transition.transition: [transition, WIDGET_FILL_TRANSITION].filter(Boolean).join(', '),},};diff --git a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts b/invokeai/frontend/webv2/src/workbench/widgetContracts.tsindex 4478aba409..9268070a0f 100644--- a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts@@ -300,15 +300,7 @@ export interface WidgetManifest {* failure state, and retry; callers never invoke this directly.*/load: () => Promise<WidgetImplementation>;- /**- * A singleton runtime the editor mounts once at boot, in its own chunk.- *- * Deliberately separate from `load`: hosts are data runtimes and dialog- * shells that must run whether or not the widget is on screen, so sharing a- * module with the view meant every boot paid for the view. Splitting the- * loader makes it impossible to declare an always-on part without giving it- * its own chunk.- */+ /** Load always-on runtimes and dialog shells separately so boot does not download their widget views. */loadHost?: () => Promise<WidgetHost>;/** Shared definitions for the shell's quick controls and full settings dialog. */settings?: SettingsContribution;diff --git a/invokeai/frontend/webv2/src/workbench/widgetDnd.browser.test.ts b/invokeai/frontend/webv2/src/workbench/widgetDnd.browser.test.tsindex 54b55dfa14..1828967245 100644--- a/invokeai/frontend/webv2/src/workbench/widgetDnd.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetDnd.browser.test.ts@@ -28,8 +28,6 @@ describe('measureDroppableVisibleRect', () => {});it('collapses a droppable scrolled out of its container to zero height', () => {- // Mirrors a gallery board row below the fold: its client rect would- // otherwise extend past the list over whatever is rendered below.const root = mount(`<div id="scroller" style="height:100px;overflow-y:auto;width:200px;"><div style="height:120px;"></div>@@ -65,8 +63,6 @@ describe('measureDroppableVisibleRect', () => {});it('clips against every overflow ancestor, not just the nearest', () => {- // The stacked gallery wraps the board panel in an overflow:hidden box- // that is itself shorter than the scroll area it contains.const root = mount(`<div style="height:60px;overflow:hidden;width:200px;"><div id="scroller" style="height:100px;overflow-y:auto;">@@ -98,9 +94,8 @@ describe('measureDroppableVisibleRect', () => {});describe('widgetCollisionDetection pointer visibility', () => {- // dnd-kit measures droppable rects once at drag start and only shifts them- // by ancestor scroll deltas afterwards, so these tests hand the detection- // the stale drag-start rect while the live DOM says otherwise.+ // dnd-kit shifts cached drag-start edges on scroll without remeasuring dimensions; test against the stale rect+ // and live DOM.const createCollisionArgs = (options: {droppables: Array<{ id: string; node: HTMLElement; rect: ClientRect }>;pointerCoordinates: { x: number; y: number };diff --git a/invokeai/frontend/webv2/src/workbench/widgetDnd.test.ts b/invokeai/frontend/webv2/src/workbench/widgetDnd.test.tsindex a0df7ee007..0f19575e8b 100644--- a/invokeai/frontend/webv2/src/workbench/widgetDnd.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetDnd.test.ts@@ -158,9 +158,7 @@ describe('bottom cluster drops', () => {describe('bottom cluster collisions', () => {it('a pointer over the spacer wins the end zone, not the nearest chip', () => {- // The spacer sits inside the strip's own region droppable, which used to- // shadow it into the nearest-chip fallback — the drop then landed beside- // a start chip and the gesture silently did nothing.+ // The containing strip must not shadow the spacer into the nearest-chip fallback.const collisions = widgetCollisionDetection(createCollisionArgs({activeData: getWidgetInstanceDragData('bottom', 'server-status', 'server-status'),diff --git a/invokeai/frontend/webv2/src/workbench/widgetDnd.ts b/invokeai/frontend/webv2/src/workbench/widgetDnd.tsindex 8a7b098d82..d812c591bb 100644--- a/invokeai/frontend/webv2/src/workbench/widgetDnd.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetDnd.ts@@ -15,15 +15,8 @@ import { isWidgetRegion as isKnownWidgetRegion } from '@workbench/layoutContractconst clipsOverflow = (value: string): boolean => value !== 'visible';/**- * Measures a droppable's rect clipped by its overflow ancestors — the part- * of it a user can actually see. A fully hidden droppable collapses to a- * zero-size rect no pointer can be within.- *- * This must NOT be used as `measuring.droppable.measure`: dnd-kit measures- * droppables once at drag start and only shifts the cached rect by ancestor- * scroll deltas (width/height stay frozen), so a row hidden at drag start- * would keep a zero-size rect even after auto-scroll reveals it. It is- * evaluated live at collision time instead (see widgetCollisionDetection).+ * Clip against live overflow ancestors at collision time, never in dnd-kit's cached droppable measurement: hidden+ * rows must become hittable when scrolling reveals them.*/export const measureDroppableVisibleRect = (element: HTMLElement): ClientRect => {const rect = { ...getClientRect(element) };@@ -300,8 +293,7 @@ export const resolveWidgetDragEnd = (overData.kind === 'widget-instance'? Math.max(0, overRegionState.instanceIds.indexOf(overData.instanceId)): overRegionState.instanceIds.length;- // Entering a region adopts the drop target's cluster; a remembered end- // alignment from an earlier placement is cleared when landing at the start.+ // Adopt the target cluster; discard remembered end alignment when dropping at the start.const targetIsEnd =overData.kind === 'widget-region-end' ||(overData.kind === 'widget-instance' && (overRegionState.alignEndInstanceIds ?? []).includes(overData.instanceId));@@ -319,15 +311,8 @@ export const resolveWidgetDragEnd = (};/**- * Drops pointer collisions with droppables the pointer is not visibly over.- *- * The rects `pointerWithin` tested against are cached at drag start and never- * re-clipped, so a droppable scrolled out of its container extends invisibly- * across whatever is rendered below — a gallery board row below the fold- * overlays the entire image grid, catching drags and racing the auto-scroller.- * Re-checking the pointer against the live visible rect removes those phantom- * hits while still letting a row that auto-scroll reveals mid-drag be hit the- * moment it appears.+ * Recheck cached pointer hits against live clipped rects so scrolled-out rows cannot intercept drops over+ * neighboring content.*/const dropOccludedPointerCollisions = (collisions: Collision[],@@ -372,9 +357,7 @@ export const widgetCollisionDetection: CollisionDetection = (args) => {}if (isWidgetInstanceDragData(activeData)) {- // The trailing-cluster spacer sits inside its strip's own region- // droppable, which would otherwise shadow it into the nearest-chip- // fallback below; a direct pointer hit on it wins like a chip hit.+ // Prefer a direct spacer hit over its containing region to preserve trailing-cluster drops.const endZoneCollisions = pointerCollisions.filter((collision) =>isWidgetRegionEndDropData(getCollisionData(args, collision.id)));diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.ts b/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.tsindex 7309a310c3..b19f7298b6 100644--- a/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.ts@@ -58,10 +58,8 @@ export interface WidgetRegionViewModel<Instance extends WidgetPlacementInstanceM}/**- * A floated widget leaves its region's `instanceIds`, but the rail still shows- * its slot — at the index it docks back to — so the window stays one click- * from the strip it came from. Ascending by index keeps later insertions from- * displacing earlier ones.+ * Keep floated widgets reachable from their original rail slots; insert by ascending dock index to preserve+ * ordering.*/const withFloatingSlots = (instanceIds: WidgetInstanceId[],diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts b/invokeai/frontend/webv2/src/workbench/widgetRegistry.tsindex 1e7a67e7b9..f187323067 100644--- a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts@@ -95,10 +95,8 @@ export const registerFirstPartyWidgets = (): RegisteredWidget[] => registerWidgeexport const registeredWidgets = registerFirstPartyWidgets();/**- * Admin-only widgets are offered only while an admin is signed in to a- * multi-user backend. The imperative session read is safe here: the route- * guard resolves the session before the workbench mounts, and a user change- * remounts the workbench route.+ * Admin widgets require a multi-user admin session; the route resolves session before mounting and remounts on+ * user changes.*/const isWidgetAvailable = (widget: RegisteredWidget): boolean => {if (!widget.manifest.requiresAdmin) {@@ -136,13 +134,8 @@ export const warmWidgets = (typeIds: readonly WidgetTypeId[]): void => {};/**- * Like {@link warmWidgets}, but resolves when the implementations are in hand.- *- * Callers that are about to make widgets appear use this to get the modules- * BEFORE committing the state change, so the render never suspends. Suspending- * is not free even when the chunk is already downloaded: showing a fallback- * makes React withhold the resolved content for `FALLBACK_THROTTLE_MS` (300ms)- * to avoid a flash, which measured as the entire cost of a layout switch.+ * Await implementations before making widgets visible to avoid Suspense fallback throttling even for downloaded+ * chunks.*/export const loadWidgets = (typeIds: readonly WidgetTypeId[]): Promise<unknown> =>Promise.allSettled(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasBottomOverlay.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasBottomOverlay.tsxindex c1d828e5e2..c89b9d960c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasBottomOverlay.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasBottomOverlay.tsx@@ -23,11 +23,7 @@ export const BOTTOM_OVERLAY_STACK_LAYOUT = {overflow: 'hidden',} satisfies StackProps;-/**- * The staging slot spans the canvas rather than hugging its content, so the- * staged-thumbnail strip gets the whole widget width to scroll within while the- * bars it contains stay centered.- */+/** Stretch staging to canvas width so thumbnails scroll while contained bars remain centered. */export const BOTTOM_STAGING_SLOT_LAYOUT = {flexShrink: '0',minW: '0',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFloatingBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFloatingBar.tsxindex 5bdc95dd65..5e8751d98d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFloatingBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFloatingBar.tsx@@ -4,15 +4,8 @@ import { Box } from '@chakra-ui/react';import { Panel } from '@platform/ui';/**- * Shared floating-panel chrome for the canvas: the raised, rounded, shadowed- * surface that the tool options bar, the staging bar, and (later) the text-tool- * / layer-selection quick bars all sit on. It supplies only the *look* and- * re-enables pointer events (its parent group is click-through); positioning- * over the surface is the parent's job.- *- * Composition-friendly: consumers lay out their own sections inside — an- * `HStack` of controls, `{@link CanvasFloatingBarDivider}` between groups — so- * no per-consumer boolean props accrete here.+ * Share floating canvas chrome and re-enable pointer events; parents own positioning and consumers compose their+ * own sections with {@link CanvasFloatingBarDivider}.*/export const CanvasFloatingBar = ({ children, ...rest }: PanelProps) => (<Panel density="sm" pointerEvents="auto" rounded="lg" shadow="lg" p="1" tone="surface" {...rest}>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsxindex b3adf13080..08da4fb67d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx@@ -73,16 +73,6 @@ const selectModelVariant = (project: Project): string | null => {return typeof values?.model?.variant === 'string' ? values.model.variant : null;};-/**- * Canvas widget header actions, in legacy toolbar order: the zoom-percent menu, a- * reset-view (fit content to view) button, fit-bbox-to-layers / fit-bbox-to-masks,- * undo / redo, save-to-gallery (canvas, with the bbox region in its menu), and a- * new-session menu. Rendered in the widget frame's header slot; resolves the- * shared engine like the layers header does, and renders nothing until it is- * available.- *- * Excluded per product decision: the project (save/load) menu and the snapshot menu.- */export const CanvasHeaderActions = ({ runtime }: WidgetViewProps) => {const engine = useCanvasEngine();return engine ? <CanvasHeaderActionsInner engine={engine} runtime={runtime} /> : null;@@ -142,11 +132,8 @@ const CanvasHeaderActionsInner = ({[document, editingLocked, engine]);- // Commands (hotkey-assignable; catalog ids `canvas.fitBboxToLayers` /- // `canvas.fitBboxToMasks` / `canvas.saveToGallery` / `canvas.saveBboxToGallery` /- // `canvas.newSession`). `useEffectEvent` reads the latest fit rects / dialog- // opener without re-registering per document change. The new-session command- // routes through the SAME confirm dialog as the button.+ // Register catalog commands once while useEffectEvent reads current fit rects/dialog openers; new-session uses+ // the button's confirmation flow.const executeHeaderCommand = useEffectEvent((commandId: string) =>executeCanvasHeaderCommand(commandId, commandContext()));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsxindex e69c55064d..9f80a2dcc1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx@@ -13,27 +13,8 @@ export type CanvasSurfaceEngine = Pick<>;/**- * Give the canvas widget hotkey focus on a pointerdown on the surface, so tool- * hotkeys (`b`/`e`/`r`/…) work immediately after clicking the canvas.- *- * The two `<canvas>` targets aren't focusable, so a plain click never moves DOM- * focus — it stays on whatever was last focused (e.g. a layers-panel button in a- * *different* widget), and the hotkey runtime's `getHotkeyTargetWidget` keeps- * resolving to that widget, so canvas hotkeys don't fire. Focusing this- * `tabIndex={-1}` container (a descendant of the canvas widget's- * `data-hotkey-widget-instance-id` element) moves focus into the canvas subtree- * so hotkeys resolve to the canvas. Focus-from-pointer doesn't match- * `:focus-visible`, so there's no focus ring.- *- * When focus is ALREADY inside the surface — critically, the text tool's- * contenteditable — this must NOT refocus: doing so in the capture phase would- * blur-commit the open text session before the engine's own (bubble-phase)- * pointerdown could run its commit-and-swallow, regressing "click away to- * commit" into "commit + open a stray new session at the click point". The full- * decision lives in the node-tested {@link shouldFocusCanvasSurface}.- *- * Runs in the capture phase so it fires before the engine's overlay pointerdown- * listener (which may `stopPropagation`).+ * Focus the canvas container in capture before engine handlers so hotkeys resolve here. Preserve focus already+ * inside, especially text editing, to avoid blur-commit before the engine's commit-and-swallow path.*/const focusCanvasSurface = (event: ReactPointerEvent<HTMLDivElement>) => {if (shouldFocusCanvasSurface(event.currentTarget, event.target, document.activeElement)) {@@ -42,17 +23,8 @@ const focusCanvasSurface = (event: ReactPointerEvent<HTMLDivElement>) => {};/**- * The engine-rendered canvas surface: two stacked `<canvas>` targets (the- * composited document below, the interaction overlay on top) bound to the- * shared {@link CanvasEngine}.- *- * Binding is done through the container's **ref callback** (React 19: the- * returned function is the cleanup), never a `useEffect` — the callback wires- * `attach` + a `ResizeObserver` and tears both down on unmount or engine swap.- * Because the callback closes over `engine`, a project switch (new engine- * instance) re-runs it: detach the old, attach the new. Pointer/wheel/key input- * is owned entirely by the engine via the overlay, so this component never- * re-renders on interaction.+ * Bind document/overlay canvases and ResizeObserver through an engine-keyed ref callback with cleanup. The engine+ * owns input without React interaction renders.*/export const CanvasSurface = ({ engine }: { engine: CanvasSurfaceEngine }) => {const screenRef = useRef<HTMLCanvasElement>(null);@@ -101,12 +73,7 @@ export const CanvasSurface = ({ engine }: { engine: CanvasSurfaceEngine }) => {><canvas ref={screenRef} style={CANVAS_STYLE} /><canvas ref={overlayRef} style={OVERLAY_STYLE} />- {/*- * The text-editing portal: a positioned contenteditable that overlays the- * canvas whenever a text-edit session is active. It lives inside this- * relatively-positioned container so its `documentToScreen`-derived- * absolute offsets share the same origin as the canvas targets.- */}+ {/* Position text editing inside the canvas container so documentToScreen offsets share the canvas origin. */}<TextEditPortal engine={engine} /></Box>);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex e768fdda06..07dea3a8b7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -67,12 +67,8 @@ const MissingFontsDialog = lazy(() =>);/**- * The canvas widget shell. The engine owns pixels and interaction and renders- * into {@link CanvasSurface}; this component only wires the reducer-backed- * chrome around it — command/hotkey registration, the settings-store feed and- * the floating staging bar. Tool and operation settings live in the- * Properties widget; zoom / fit / settings in the widget header- * ({@link CanvasHeaderActions}).+ * Wire reducer chrome, commands, settings, and staging around the pixel/input engine. Properties owns tool+ * settings; {@link CanvasHeaderActions} owns view controls.*/export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {const { t } = useTranslation();@@ -98,9 +94,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {const { isSaving, save: saveToGallery } = useCanvasGallerySave(engine);const { createFromBbox, isCreating } = useCreateFromBbox(engine);- // Canvas invocation stays code-split from the rest of the workbench, but the- // canvas being mounted is a strong intent signal. Warm it while the user edits- // instead of making the first Ctrl+Enter pay the chunk download/evaluation.+ // Warm the split invocation chunk when Canvas mounts so the first submission need not download it.useMountEffect(preloadCanvasInvocation);// Right-click on the canvas surface targets the selected layer (the panel is@@ -108,9 +102,8 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {// shared per-layer menu or the global menu at the pointer.const [contextMenuTarget, setContextMenuTarget] = useState<CanvasContextMenuTarget | null>(null);const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);- // The bbox tool snaps to a model-dependent grid; the engine is model-agnostic, so read the- // active generate model and feed the grid size in. Two primitive selectors rather than one- // object, so the subscription compares by value.+ // Feed model grid policy into the model-agnostic engine using primitive selectors for value-stable+ // subscriptions.const modelBase = useActiveProjectSelector((project) => {const values = getProjectWidgetValues(project, 'generate') as { model?: { base?: unknown } } | undefined;return typeof values?.model?.base === 'string' ? values.model.base : null;@@ -124,10 +117,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {engine?.viewport.setBboxGrid(bboxGrid);}, [bboxGrid, engine]);- // Canvas view settings (checkerboard / grid / invert-scroll) persist in the- // canvas widget's per-project values; the engine only reads its stores, so- // push the resolved values down whenever they change — same one-directional- // feed as the bbox grid above. The header settings menu writes the values.+ // Feed persisted per-project view settings into engine stores; header controls write the widget values.const settings = useActiveProjectSelector((project) => resolveCanvasSettings(getProjectWidgetValues(project, 'canvas')),canvasSettingsEqual@@ -149,12 +139,8 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {// edits never re-render this shell; the commands feed the X/D hotkeys below.const colorCommands = useActiveColorCommands();- // The checkerboard fills the whole (unbounded) canvas, so its two square colors- // come from theme tokens rather than hardcoded greys. Resolve them from the live- // Chakra theme and feed them into the engine's checker-colors store; re-resolve- // whenever the theme (and thus color mode) changes. `themeId` flips- // `<html data-theme>` in ThemeController's layout effect, which runs before this- // passive effect in the same commit, so getComputedStyle reads the new theme.+ // Resolve checker colors from live theme tokens after ThemeController updates data-theme, then feed the engine+ // store.const themeId = useWorkbenchSettingsSelector((snapshot) => snapshot.preferences.themeId);useEffect(() => {engine?.interaction.set('checkerColors', resolveCheckerColors());@@ -170,10 +156,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {(item) =>item.snapshot.destination === 'canvas' &&(item.status === 'pending' || item.status === 'running') &&- // Only this canvas SESSION's in-flight items: an item submitted before a- // wholesale swap (new canvas / snapshot restore) belongs to a document- // that no longer exists, so its denoise frames must not leak onto the- // fresh canvas (F2). `documentRevision` bumps only on those swaps.+ // Show progress only for this documentRevision; wholesale session swaps invalidate earlier denoise frames.item.snapshot.canvas.documentRevision === canvas.documentRevision);const interactionCapabilities = getCanvasInteractionCapabilities({@@ -186,12 +169,8 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {const isInteractionLocked = interactionCapabilities.isSurfaceInteractionLocked;const handleSurfaceContextMenu = useCallback((event: ReactMouseEvent<HTMLDivElement>) => {- // Keep the native menu inside inline editors (the text tool's contenteditable- // overlay), consistent with the surface-focus INLINE_EDIT_SELECTOR.- //- // The menu targets the SELECTED layer, not the layer under the pointer, and- // never dispatches a selection — the layers panel is the sole authority on- // which layer is active.+ // Preserve native menus in inline editors. Canvas context actions target the selected layer without changing+ // selection.const resolution = resolveCanvasContextMenu({clientX: event.clientX,clientY: event.clientY,@@ -247,11 +226,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {[canvasCommands, engine, notifications, queries, t]);- /**- * Copies the selection's pixels to the system clipboard, optionally cutting- * them. The engine produces the blob; the clipboard write is a widget concern- * (`canvas-engine` may not reach `workbench/widgets`).- */+ /** The engine produces selected pixels; widget code owns system clipboard writes and optional cutting. */const copySelection = useEffectEvent((cut: boolean) => {const mountedEngine = engine;if (!mountedEngine) {@@ -362,9 +337,6 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {);const progressImage = settings[CANVAS_SHOW_PROGRESS_KEY] ? selectedPlaceholderProgressImage : null;- // What the engine should draw as the staged preview: the live denoise-progress- // frame while generating, else the selected candidate, else nothing. The pure- // helper is unit-tested; the effect below drives the engine imperatively.const previewSource = selectStagedPreviewSource({bboxHeight: document.bbox.height,bboxWidth: document.bbox.width,@@ -376,11 +348,8 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {});const previewKey = stagedPreviewKey(previewSource);- // Syncing an external imperative system (the engine's staged preview) with- // derived reducer/progress state is a genuine effect. `useEffectEvent` reads- // the latest source without making it a dependency, so the decoding- // `setStagedPreview` re-runs only when `previewKey` actually changes (which- // includes every new progress frame) — never on unrelated re-renders.+ // Decode staged previews only when previewKey changes, including progress frames; read current source without+ // retriggering on unrelated renders.const applyStagedPreview = useEffectEvent(() => {engine?.previews.setStagedPreview(previewSource);});@@ -425,9 +394,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {['canvas.resetSelected', t('widgets.canvas.commands.resetSelected'), ['shift+c']],['canvas.undo', t('widgets.canvas.commands.undo'), ['mod+z']],['canvas.redo', t('widgets.canvas.commands.redo'), ['mod+shift+z', 'mod+y']],- // Tool selection and brush/eraser size step. `allowInEditable: false` below- // keeps these single-letter/bracket keys from firing while the user is- // typing in a prompt/text field elsewhere in the workbench.+ // Exclude editable targets so tool letters and size brackets do not intercept typing.['canvas.tool.view', t('widgets.canvas.commands.selectViewTool'), ['h']],['canvas.tool.move', t('widgets.canvas.commands.selectMoveTool'), ['v']],['canvas.transformSelected', t('widgets.canvas.commands.selectTransformTool'), ['mod+t']],diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsxindex 3284037cde..84c5c6507d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsx@@ -1,14 +1,6 @@/**- * Canvas compositing settings for the generate widget.- *- * One of the Generate form's canvas-only sections (`GenerateCanvasSections`),- * alongside the denoising strength. This section- * holds the legacy canvas compositing controls — infill method,- * coherence pass mode / edge size / min denoise, and mask blur — persisted- * per-project in the canvas widget's own `state.values` (same store as- * `denoisingStrength`), read back by `prepareCanvasInvocation` and threaded into- * the pure graph compiler. Rendered only when the active invocation source is- * the canvas (the generate widget is shared with the Generate tab).+ * Expose canvas-only infill/coherence/mask controls in Generate. Persist them in canvas values for+ * prepareCanvasInvocation and graph compilation.*/import type { NumberInput as ChakraNumberInput, SelectValueChangeDetails } from '@chakra-ui/react';@@ -32,8 +24,7 @@ import { useTranslation } from 'react-i18next';const INFILL_METHODS: readonly CanvasInfillMethod[] = ['patchmatch', 'lama', 'cv2', 'color', 'tile'];const COHERENCE_MODES: readonly CanvasCoherenceMode[] = ['Gaussian Blur', 'Box Blur', 'Staged'];-// Full-width form fields: the menu hangs from the trigger's start edge at the-// trigger's width — `bottom-end`/fit-content is for narrow inline selects.+// Match full-width menus to the trigger width and start edge.const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: true } as const;const selectCanvasValues = (project: Parameters<typeof getProjectWidgetValues>[0]): Record<string, unknown> =>@@ -125,8 +116,6 @@ export const GenerateCanvasCompositingSection = () => {[patch]);- // `infillColorValue` is already `{ r, g, b }` 0-255 plus a unit alpha, which- // is exactly the shape the platform color helpers speak.const infillColor = formatHexColor(settings.infillColorValue, { alpha: true });const handleInfillColorChange = useCallback(@@ -145,8 +134,6 @@ export const GenerateCanvasCompositingSection = () => {const opt = (key: string) => t(`widgets.generate.compositingOptions.${key}`);- // The collapsed header carries the effective recipe — infill method and mask- // blur — so canvas fill reads as a one-line contextual summary until opened.const badges = (<><Badge size="xs">{t(`widgets.generate.compositingOptions.infillMethods.${settings.infillMethod}`)}</Badge>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.browser.test.tsxindex 25bce55914..aa7e5a4e23 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.browser.test.tsx@@ -89,9 +89,8 @@ describe('GenerateCanvasScalingSection', () => {await render();expect(shownSize()).toEqual([1280, 720]);- // TI2V-5B takes multiples of 32; its base row says 16, on which 720 would still sit. The section- // used to drop the variant and to latch its first answer, and either kept showing 1280x720 while- // `compileCanvasGraph` generated at a different height.+ // TI2V-5B requires grid 32 rather than its base's 16; preserve variant and capability updates so shown and+ // compiled sizes agree.await act(() => {setArchitectureCapabilities(architectureCapabilitiesFixture);});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.tsxindex 44276d76e5..1879493fd6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.tsx@@ -1,9 +1,6 @@/**- * Canvas "Scale before processing" for the generate widget: whether the bbox- * is denoised at its own size, grown to the model's optimal area, or at a- * manual size, with the result always resized back to the bbox. Persisted in- * the canvas widget's values next to the denoising strength; read back by- * `prepareCanvasInvocation` and threaded into the pure graph compiler.+ * Choose bbox, optimal, or manual processing size, then resize results back to bbox. Persist in canvas values for+ * invocation compilation.*/import type { NumberInput as ChakraNumberInput, SelectValueChangeDetails } from '@chakra-ui/react';@@ -32,9 +29,8 @@ const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: true } as conconst selectCanvasValues = (project: Project): Record<string, unknown> => getProjectWidgetValues(project, 'canvas');/**- * The generate model's base, type and variant, and the PiD mode, decide the grid and optimal area the- * policy works in -- the same model `compileCanvasGraph` compiles with, variant included, or the size- * shown here is not the size that is generated.+ * Use model base/type/variant and PiD mode matching compileCanvasGraph so displayed size follows identical+ * grid/area policy.*/const selectProcessingContext = (project: Project) => {const generate = getProjectWidgetValues(project, 'generate') as {@@ -72,9 +68,8 @@ export const GenerateCanvasScalingSection = () => {const values = useActiveProjectSelector(selectCanvasValues);const scaling = useMemo(() => readCanvasScaling(values), [values]);const context = useActiveProjectSelector(selectProcessingContext, processingContextEqual);- // Both answer from the capability table, so they are read inside the store's selector: to React- // Compiler a bare call is a pure function of `context` and `scaling`, and would keep the fallback- // grid 8 / optimal 1024 it answered before the table arrived.+ // Read policy inside the capability selector so arrival replaces fallback grid/area despite compiler+ // memoization.const { dimensions, processingSize } = useExternalStoreSelector(subscribeArchitectureCapabilities,getArchitectureCapabilitiesSnapshot,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateDenoisingStrength.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateDenoisingStrength.tsxindex 34a9c7ed50..5d12518c09 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateDenoisingStrength.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateDenoisingStrength.tsx@@ -23,11 +23,7 @@ const formatStrengthPercent = (value: number): string => `${Math.round(value * 1const selectCanvasStrength = (project: Parameters<typeof getProjectWidgetValues>[0]): number =>readCanvasDenoisingStrength(getProjectWidgetValues(project, 'canvas'));-/**- * The canvas denoising strength as its own Generate-form section: the one- * img2img knob, persisted in the canvas widget's values and flushed with the- * form's other drafts before an invocation.- */+/** Persist canvas denoising strength in widget values and flush its draft with the Generate form before invocation. */export const GenerateDenoisingStrength = () => {const { t } = useTranslation();const { widgets } = useWorkbenchCommands();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.browser.test.tsxindex fe2042e8bf..3d24c34e41 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.browser.test.tsx@@ -155,9 +155,7 @@ describe('StagingBar thumbnail strip', () => {const bounds = viewport.getBoundingClientRect();expect(thumbnails).toHaveLength(24);- // The strip gets the full canvas widget to scroll within — not the width of- // the options bar beneath it, and never wider than the canvas itself (the- // overlay would silently clip the centered overflow at both edges).+ // Constrain staging scroll width to the canvas, independent of the narrower options bar.expect(bounds.width).toBe(overlay.getBoundingClientRect().width);expect(bounds.width).toBeLessThanOrEqual(CANVAS_WIDTH);expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsxindex 45000651a8..f4f46ded90 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx@@ -74,13 +74,8 @@ interface StagingBarProps {}/**- * The floating staging bar over the canvas: appears while a canvas generation- * is in flight or staged candidates await a decision. It drives the reducer's- * staging actions (cycle / accept / discard / auto-switch); the candidate and- * live progress pixels themselves are drawn on the engine canvas via- * `engine.previews.setStagedPreview` (wired in {@link CanvasWidgetView}). Rendered inside- * the canvas's bottom-center floating group, stacked directly above the tool- * options bar; positioning is the parent's job.+ * Show staging controls for running or pending canvas results. {@link CanvasWidgetView} feeds pixels to+ * engine.previews; the parent positions this bar above tool options.*/export const StagingBar = ({antialiasProgressImages,@@ -139,8 +134,6 @@ export const StagingBar = ({};return (- // The bar mounts when staging begins; a short slide-fade lands it instead- // of popping it in. Duration collapses under reduce-motion with the theme.<Stack align="center" animationDuration="moderate" animationName="slide-from-bottom, fade-in" gap="2" w="full">{contextMenuTarget ? (<StagingItemContextMenu@@ -153,11 +146,8 @@ export const StagingBar = ({/>) : null}{hasSlots ? (- // The strip spans the whole canvas widget and scrolls within it: the- // overlay's staging slot stretches, so this width is definite and a long- // run of staged candidates can only ever scroll — never widen the- // floating bar group past the canvas, where the overlay would silently- // clip the centered overflow at both edges.+ // Constrain thumbnail scrolling to canvas width so centered overflow cannot be clipped outside the+ // surface.<ScrollArea.Rooth={areThumbnailsVisible ? THUMBNAIL_STRIP_HEIGHT : '0'}opacity={areThumbnailsVisible ? 1 : 0}@@ -421,8 +411,7 @@ const StagingThumbnail = ({onSelect: () => void;}) => {const { t } = useTranslation();- // Ref callbacks re-run when `isSelected` changes, so cycling with the arrows- // (or an auto-switch) drags the strip along without an effect.+ // Selection-sensitive ref callbacks scroll the active thumbnail into view without an effect.const scrollIntoView = useCallback((node: HTMLElement | null) => {if (node && isSelected) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.tsxindex 309e3538e9..b6edca6ac5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.tsx@@ -27,12 +27,7 @@ export interface StagingItemContextMenuTarget {/** A staged result carries no executed field values; the local submission snapshot is the source. */const NO_META: QueueGenerationMeta = {};-/**- * The executed prompts and seed of the backend item that produced a staged- * result, from the project's queue read model (normally warm from the queue- * widget). A randomized run's seed lives only there, so without it "Use Seed"- * would stay disabled for the most common case.- */+/** Read executed prompts and seed from queue metadata; randomized seeds are unavailable from authored settings. */const useStagedCandidateMeta = (projectId: string, backendItemId: number | undefined): QueueGenerationMeta => {const scope = useMemo(() => ({ originPrefix: buildProjectQueueItemOriginPrefix(projectId) }), [projectId]);const select = useCallback(@@ -45,11 +40,6 @@ const useStagedCandidateMeta = (projectId: string, backendItemId: number | undefreturn useQuery({ ...getQueueReadModelOptions(scope), enabled: backendItemId !== undefined, select }).data ?? NO_META;};-/**- * Right-click menu for a staged canvas result: recall its submission settings- * into the Generate panel (the same verbs as gallery images and the queue's- * Recent panel), or act on the candidate without hunting for the bar's buttons.- */export const StagingItemContextMenu = ({canAccept,onAccept,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.browser.test.tsxindex b62b7ee8af..7d1bf386f9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.browser.test.tsx@@ -39,10 +39,6 @@ const session = (overrides: Partial<TextEditSession> = {}): TextEditSession =>...overrides,}) as unknown as TextEditSession;-/**- * A minimal engine double: the portal only needs the interaction store to read- * the session, the layers commands it drives, and a viewport for positioning.- */const createEngine = (initialSession: TextEditSession | null,fonts?: {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsxindex 555c564689..7290a58390 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx@@ -19,27 +19,9 @@ type TextEditEngine = Pick<CanvasEngineHandle, 'interaction' | 'layers' | 'viewpPartial<Pick<CanvasEngineHandle, 'fonts'>>;/**- * The text-editing portal: a positioned `contenteditable` div, rendered over the- * canvas whenever a text-edit session is active, that IS the text while editing- * (the compositor skips the session's layer so the two never double-draw).- *- * ## WYSIWYG- *- * The editable's intrinsic styles are set in DOCUMENT units (font size in px,- * unitless line-height, family/weight/align/color from the live session source)- * — exactly what the rasterizer will bake. A single CSS transform then maps the- * layer's document anchor to the screen and magnifies by the view zoom, so the- * on-screen editable matches the rasterized output at any pan/zoom. `white-space:- * pre` mirrors the rasterizer's manual-line-break, no-auto-wrap layout.- *- * ## Keystrokes stay local- *- * Typing only mutates the editable's DOM — never the engine/store (no per-key- * traffic). Every keydown is `stopPropagation`'d so canvas hotkeys can't fire- * from the field (belt-and-braces with the pipeline's editable guard and the- * widget hotkeys' `allowInEditable: false`). Commit is on blur / `mod+enter`;- * `esc` cancels — the editable owns Escape (stopPropagation) so the engine's- * Escape priority never also runs.+ * Render session text as document-unit contenteditable transformed by pan/zoom; the compositor skips that layer.+ * Preserve manual line breaks without wrapping. Keystrokes stay in DOM and stop hotkey propagation; blur/mod+enter+ * commits and Escape cancels.*//** Re-renders on any viewport (pan/zoom) change via a value-stable snapshot string. */@@ -94,11 +76,7 @@ interface TextEditableProps {session: TextEditSession;}-/**- * The single editable element for one session. Keyed by `session.id` in the- * parent so a fresh session remounts it — the ref callback then seeds content +- * focus exactly once, while position/style recompute on each render.- */+/** Key by session.id so content/focus seed once while position and style remain reactive. */const TextEditable = ({ engine, session }: TextEditableProps) => {// Re-render on pan/zoom so the transform below tracks the viewport.useViewportTick(engine);@@ -107,10 +85,8 @@ const TextEditable = ({ engine, session }: TextEditableProps) => {const resolvedFontFamily = useResolvedTextFontFamily(engine.fonts, source);const ignoreNextBlur = useRef(false);- // Seeds content + focus once when the element mounts, and registers a live-- // content reader with the engine so it can commit on a canvas pointerdown- // (click-elsewhere-to-commit) without per-keystroke traffic. Cleared on unmount.- // A stable callback, so React never re-runs it on a position/style re-render.+ // Use a stable ref to seed/focus once and register a live DOM reader for click-away commit without per-key store+ // writes; clear it on unmount.const setRef = useCallback((el: HTMLDivElement | null) => {if (!el) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsxindex b7ec4ec087..37bae7a909 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx@@ -168,12 +168,7 @@ const SelectFamilyButton = ({*/const TOOL_STRIP_TOP = 'var(--wb-center-chrome-inset, var(--chakra-spacing-2))';-/**- * The canvas's left-docked, vertical tool strip, topped out directly beneath- * the region's floating chrome islands. Color-picker is intentionally absent —- * it's alt-hold-only for now (see `canvas-engine/input/pointerPipeline.ts`),- * not a sticky tool a user selects directly.- */+/** Keep color picking alt-hold-only rather than exposing it as a sticky tool. */const ToolStripRoot = ({engine,isInteractionLocked = false,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStripFlyout.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStripFlyout.tsxindex 81a3ac35a2..69b863e5b8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStripFlyout.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStripFlyout.tsx@@ -17,11 +17,8 @@ export interface ToolFlyoutItem {}/**- * A tool-strip slot that owns subtools, Photoshop-style: plain click selects- * the slot's current subtool; press-and-hold (or right-click, or ArrowRight /- * the context-menu key) opens a flyout beside the button. Releasing the held- * pointer over an entry selects it; a quick release leaves the flyout open for- * a click. The corner tick marks the slot as holding more tools.+ * Click selects the current subtool; hold, right-click, or keyboard opens the flyout. Release over an entry+ * selects; quick release leaves it open.*/export const ToolFamilyButton = ({currentId,@@ -180,9 +177,8 @@ export const ToolFamilyButton = ({);const onPointerMove = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {- // Dragging off the button mid-hold cancels the pending open but keeps an- // already-open flyout (the pointer is heading for it). Capture suppresses- // pointerleave, so the bounds check runs on the retargeted moves instead.+ // Cancel pending hold when the pointer leaves, but preserve open flyouts; capture requires bounds checks+ // instead of pointerleave.if (holdTimer.current === null) {return;}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.browser.test.tsxindex c70f0f907e..b8fb0042ba 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.browser.test.tsx@@ -38,9 +38,8 @@ afterEach(async () => {describe('useModelGridSize', () => {it('re-reads the grid when the capability table lands after mount', async () => {- // The real sequence for a saved project: the base is restored from disk and never changes, so- // an effect keyed on it alone never re-runs. Wan's denoise node enforces multiples of 16; the- // canvas used to keep snapping at 8 for the rest of the session.+ // Capability arrival must update a restored unchanged base's snapping grid rather than retaining boot fallback+ // 8.await render('wan');expect(grid()).toBe('8');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.tsindex e9d7b22ca8..1dddb0ec5d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts@@ -27,17 +27,13 @@ describe('gridSizeForModelBase', () => {});it('reads the 32px grid Wan TI2V-5B declares, from the table the backend really serves', () => {- // Against the committed fixture rather than a hand-built row: this is the one architecture- // whose grid is not a property of the base, and 1280x720 is the size that slips through a- // base-only lookup -- both multiples of 16, and 720 % 32 === 16.+ // Use the committed variant fixture: 1280x720 passes base grid 16 but fails TI2V-5B grid 32.expect(gridSizeForModelBase('wan', 'ti2v_5b')).toBe(32);expect(gridSizeForModelBase('wan')).toBe(16);expect(720 % gridSizeForModelBase('wan', 'ti2v_5b')).not.toBe(0);});it('no longer offers 8px steps for architectures that reject them', () => {- // The drift this replaces: these three fell through to the default 8 here while their denoise- // nodes carry multiple_of=16, so the canvas offered sizes that failed at enqueue time.for (const base of ['krea-2', 'wan', 'ideogram-4']) {expect(gridSizeForModelBase(base)).toBe(16);}@@ -52,9 +48,7 @@ describe('gridSizeForModelBase', () => {});describe('resolveModelGrid before the capability table arrives', () => {- // Deliberately unseeded. Every case above runs with the table present, which is the state the- // app reaches a round trip *after* boot -- and a project reopened before then is exactly where- // the grid used to latch at 8 for the session.+ // Leave capabilities absent to reproduce reopening before the table arrives.it('reports the grid as unknown rather than as 8', () => {// The distinction a writer needs: 8 is a real answer for SDXL and a guess for Wan, and only@@ -81,14 +75,8 @@ describe('resolveModelGrid before the capability table arrives', () => {});describe('the grid a variant declares', () => {- // Wan is the architecture whose grid is not a property of the base: A14B enforces multiples of- // 16 on its denoise node, TI2V-5B multiples of 32 in the reference-image encoder. The backend- // publishes that as a variant row; the canvas has to join on `(base, variant)` or it offers a- // size the run rejects after the model is already loaded -- 1280x720 is the obvious one, both- // multiples of 16, and 720 % 32 === 16.- //- // Seeded with a hand-built override rather than the committed fixture, so this states the rule- // rather than whatever number that fixture happens to carry.+ // Override variant policy independently of fixtures: Wan grid depends on base plus variant, and 720 fails grid+ // 32 despite passing 16.beforeEach(() => {setArchitectureCapabilities(architectureCapabilitiesFixture.map((row) =>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.tsindex 53d093752b..8db0196981 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts@@ -1,19 +1,7 @@/**- * Maps a model base to the bbox snapping grid size (document px). React reads the active generate- * model's base and feeds the result into `engine.viewport.setBboxGrid`; the engine itself stays- * model-agnostic.- *- * The rule comes from the backend now, which is where it is enforced: each denoise node carries a- * `multiple_of` on its width/height fields, and the architecture declares the same number. This- * used to be a second, hand-maintained copy of that column -- and it had drifted, offering 8px- * steps for krea-2, wan and ideogram-4, all of which reject anything but multiples of 16 at- * enqueue time.- *- * Because the rule now arrives over the network, "the grid for this base" has a third answer- * besides a number and "no model": *not yet*. {@link resolveModelGrid} keeps that answer distinct- * so a writer (the bbox <-> dims sync, which persists) can wait while a reader (the tool's snap- * step) can pick a harmless default -- and {@link useModelGridSize} makes the reader re-read when- * the table lands instead of latching whatever it answered on the first render.+ * Feed backend model grid policy into the model-agnostic engine. {@link resolveModelGrid} distinguishes+ * unavailable policy so persistent writers wait while readers may use defaults; {@link useModelGridSize} updates+ * readers when policy arrives.*/import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities } from '@features/generation/runtime';@@ -35,17 +23,8 @@ export const gridSizeForModelBase = (base: string | null | undefined, variant?:resolveModelGrid(base, variant) ?? DEFAULT_MODEL_GRID;/**- * The grid for `base`, re-read whenever the capability table changes.- *- * `base` comes from the persisted project and is therefore already final on the first render, so an- * effect keyed on it alone never re-runs: without this subscription a project reopened before the- * table arrives snaps at 8px for the whole session, on an architecture whose denoise node enforces- * 16 or 32.- *- * The read happens *inside* the selector rather than after a bare subscription call. The grid lives- * in the core registry, not in this snapshot, so to React Compiler a plain `gridSizeForModelBase(base)`- * in a component body is a pure function of `base` and is memoised for the component's lifetime --- * subscribing alongside it would re-render and hand back the cached 8 anyway.+ * Resolve grid inside the capability selector so table updates recompute it even when the persisted base stays+ * unchanged and compiler memoization would retain a fallback.*/export const useModelGridSize = (base: string | null | undefined, variant?: string | null): number =>useExternalStoreSelector(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.tsindex b26c84c463..c39ecd11a4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.ts@@ -1,14 +1,6 @@/**- * System-clipboard access for canvas pixel selections.- *- * The engine deliberately stops at `Blob` / `ImageData` — `canvas-engine` may- * not reach `workbench/widgets`, and clipboard permissions are a DOM concern- * either way. This module is the widget-side bridge: it reads an image off the- * clipboard and decodes it to `ImageData` the engine can paste, and re-exports- * the existing write helper so a canvas caller has one place to import from.- *- * Every dependency is injectable so the whole path is testable without a real- * clipboard or canvas.+ * Bridge clipboard images and engine Blob/ImageData on the widget side; inject dependencies for tests without real+ * clipboard/canvas access.*/export { copyBlobToClipboard } from '@workbench/widgets/layers/layerExportActions';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.tsindex 8937eb3db3..0650dd6295 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts@@ -34,8 +34,6 @@ describe('resolveCanvasContextMenu', () => {});it('targets the selected layer regardless of where the pointer is', () => {- // The canvas never hit-tests for the menu: the layers panel is the sole- // authority on which layer is active, so the pointer position is irrelevant.const overOneCorner = resolveCanvasContextMenu({ ...baseOptions, selectedLayerId: 'layer-7' });const overAnother = resolveCanvasContextMenu({...baseOptions,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.tsindex 25f15e7c86..316f9c0661 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts@@ -7,12 +7,7 @@ export interface CanvasContextMenuTarget {interface ResolveCanvasContextMenuOptions {clientX: number;clientY: number;- /**- * The document's selected layer — the menu's target. The canvas deliberately- * does NOT hit-test the pixel under the pointer: the layers panel is the sole- * authority on which layer is active, so right-clicking a layer's pixels must- * not silently re-target the menu (or the selection) to it.- */+ /** Target the selected layer without hit-testing right-click pixels; the layers panel owns selection. */selectedLayerId?: string | null;isInlineEditor: boolean;isInteractionLocked: boolean;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.tsindex 86317db599..db82842977 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts@@ -8,10 +8,7 @@ import type { CanvasGallerySaveRegion } from '@workbench/canvas-operations/api';import { createNewCanvasState } from '@workbench/canvasMigration';-/**- * The slice of the engine the header's actions drive. Structural rather than the- * full handle, so this module stays React-free and testable with a plain double.- */+/** Use the header's structural engine subset to keep command tests React-free. */export interface CanvasHeaderCommandEngine {readonly document: Pick<CanvasDocumentCapability, 'replaceDocument'>;readonly layers: {@@ -54,12 +51,7 @@ export const zoomAtViewportCentre = (engine: CanvasHeaderCommandEngine, value: nviewport.zoomAtPoint(value, { x: size.width / 2, y: size.height / 2 });};-/**- * Commits a fit-bbox as one undoable `setCanvasBbox` whose inverse restores the- * current bbox — exactly how a manual bbox-tool edit commits. `refit` re-centres- * the view afterward (legacy re-fits the stage after fit-to-layers, but not after- * fit-to-masks). A null rect means nothing to fit to, and is a no-op.- */+/** Commit one undoable bbox change; optionally refit afterward. Null bounds are a no-op. */export const applyFitBbox = (ctx: CanvasHeaderCommandContext, rect: Rect | null, refit: boolean): void => {if (ctx.editingLocked || !rect) {return;@@ -88,11 +80,7 @@ export const confirmNewCanvas = (ctx: NewCanvasContext): void => {ctx.engine.document.replaceDocument(createNewCanvasState(ctx.document.width, ctx.document.height).document);};-/**- * Routes a header command id. `canvas.newSession` deliberately opens the confirm- * dialog rather than replacing directly, so the command and the button share one- * destructive path.- */+/** Route new-session commands through the button's confirmation dialog. */export const executeCanvasHeaderCommand = (commandId: string, ctx: CanvasHeaderCommandContext): void => {if (commandId === 'canvas.fitBboxToLayers') {applyFitBbox(ctx, ctx.fitLayersRect, true);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.tsindex 422e4f9229..4bedd85785 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts@@ -38,11 +38,7 @@ const documentOf = (layers: readonly CanvasLayerContract[], selectedLayerId: strwidth: 64,}) as CanvasDocumentContractV3;-/**- * A recording engine double. Interaction state is a plain bag so tests can put- * the engine into "has a pixel selection" or "already on the lasso tool" without- * standing up the real store.- */+/** Use a recording engine with mutable interaction state for selection/tool scenarios without real stores. */const createEngine = (interaction: Partial<CanvasInteractionState> = {}) => {const state: Record<string, unknown> = {activeTool: 'brush',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.tsindex a958df8e2e..1ea314f97d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts@@ -43,11 +43,7 @@ const REORDER_KINDS: Record<string, LayerStackMoveKind> = {'canvas.layerToFront': 'front',};-/**- * Everything the canvas hotkey dispatcher reads or drives. The widget supplies- * these from its render scope; keeping them as an explicit parameter is what- * makes the ~35-command dispatch table testable without mounting React.- */+/** Pass hotkey dependencies explicitly so dispatch can be tested without mounting React. */export interface CanvasHotkeyContext {readonly document: CanvasDocumentContractV3;readonly engine: CanvasEngine | null;@@ -146,8 +142,7 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC}if (commandId === 'canvas.deleteSelected') {- // With a live pixel selection, Delete clears the selected PIXELS — the- // Photoshop meaning. Only with no selection does it delete the layer.+ // Delete clears selected pixels before falling back to layer deletion.if (engine?.interaction.get('hasSelection')) {engine.selection.eraseSelection();} else if (engine && selected && !selectedFrozen) {@@ -162,9 +157,7 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC} else if (commandId === 'canvas.pasteImage') {ctx.pasteFromClipboard();} else if (commandId === 'canvas.toggleNonRasterLayers') {- // Hide, never disable: this is the "get the overlays out of my way" shortcut, and it must- // leave the generated image untouched. Hiding turns off the overlay roots; showing turns on- // every node hidden in its own right, so nothing stays gated behind a hidden group.+ // Hide overlays without disabling generation content; showing restores individually hidden nodes too.const overlays = index.nodes.filter((entry) => isOverlayStack(entry.stack));const leaves = compileDocumentLeaves(document).filter((leaf) => isOverlayStack(leaf.stack));if (engine && leaves.length > 0) {@@ -186,11 +179,7 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyCengine.layers.clearMask(selectedLayer.id);}} else if (commandId === 'canvas.undo') {- // Canvas undo/redo is engine-scoped: it drives the engine-owned pixel/- // structural history, NOT project-level (reducer) undo. When the canvas- // history is empty this is a no-op — it deliberately does not fall back to- // `undoProjectChange` (project undo keeps its own commands/hotkeys, e.g.- // the workflow editor's `workflows.undo`).+ // Use engine pixel/structural history only; empty canvas history never falls back to project undo.engine?.history.undo();} else if (commandId === 'canvas.redo') {engine?.history.redo();@@ -210,8 +199,7 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyCengine?.tools.setTool('eraser');} else if (commandId === 'canvas.tool.lasso') {if (engine) {- // Pressing the shortcut while already on the tool cycles its shape- // (Photoshop-style) rather than re-selecting the tool it is already on.+ // Repeating the active tool shortcut cycles its shape.if (engine.interaction.get('activeTool') === 'lasso') {const lasso = engine.interaction.get('lassoOptions');engine.interaction.set('lassoOptions', {@@ -299,12 +287,7 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyCctx.reportPreparedCommit(ungroupLayers(engine, ctx.selectedLayerIds, t('widgets.canvas.commands.ungroupLayers')));}} else if (commandId === 'canvas.mergeDown') {- // Gate on the SAME predicate the layers panel's context menu uses to- // enable/disable its "Merge Down" item (`canMergeLayerDown`), so the hotkey- // can never fire where the menu would refuse — e.g. a mask layer selected,- // or a mask directly below the selection. `engine.layers.mergeLayerDown` also- // guards this itself (defense in depth for callers other than this hotkey),- // but checking here keeps the two surfaces visibly in lockstep.+ // Share canMergeLayerDown with the layer menu so shortcuts respect identical eligibility.if (engine && selectedLayer && canMergeLayerDown(document, selectedLayer.id, true)) {engine.layers.mergeLayerDown(selectedLayer.id);}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.tsindex de364cd960..5570bc2a33 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts@@ -1,25 +1,7 @@/**- * Canvas view settings — the sectioned, legacy-style popover of per-project- * canvas preferences (Behavior / Display / Grid), plus the Shift-revealed Debug- * actions rendered separately in the header.- *- * Each setting is a boolean persisted in the canvas widget's own state values- * (`widgetInstances['canvas'].state.values[key]`) — the same plumbing as the- * denoising strength (`invoke/canvasStrength.ts`), so it survives reloads and is- * read when a queue submission is compiled. Persistence is per-user (per-project), NEVER in- * the canvas undo history.- *- * A setting either drives an engine boolean store (`store` set — React resolves- * the persisted value and feeds it down; see the settings-feed effect in- * `CanvasWidgetView`, the engine reads only its stores and never React) OR is- * consumed elsewhere in the frontend (`store` absent — e.g. `showProgressOnCanvas`- * in the widget shell or `outputOnlyMaskedRegions` during invocation submission).- * The feed is strictly- * one-directional: settings → engine, never the reverse.- *- * The list is data-driven: adding a boolean setting is one entry here plus its- * i18n label and (when engine-backed) the store it drives. Pure data + readers;- * no React, no engine imports — unit-testable in node.+ * Persist canvas preferences in per-project widget values outside undo history. Feed engine-backed settings+ * one-way into stores; other consumers read values directly. Popover and engine bindings derive from this data+ * list.*/import { CANVAS_COMPOSITING_KEYS, DEFAULT_CANVAS_COMPOSITING } from './invoke/canvasCompositing';@@ -51,8 +33,7 @@ export const CANVAS_SHOW_PROGRESS_KEY = 'showProgressOnCanvas';export const CANVAS_OUTPUT_ONLY_MASKED_REGIONS_KEY = CANVAS_COMPOSITING_KEYS.outputOnlyMaskedRegions;const OUTPUT_ONLY_MASKED_REGIONS_SETTING: CanvasBooleanSetting = {- // Legacy parity: generation results keep alpha outside the expanded mask- // unless the user explicitly asks to composite them over the source image.+ // Keep output alpha outside the expanded mask unless source compositing is explicitly enabled.defaultValue: DEFAULT_CANVAS_COMPOSITING.outputOnlyMaskedRegions,key: CANVAS_OUTPUT_ONLY_MASKED_REGIONS_KEY,labelKey: 'widgets.canvas.settings.outputOnlyMaskedRegions',@@ -73,11 +54,7 @@ export interface CanvasBooleanSetting {section: CanvasSettingSection;}-/**- * The canvas settings, in popover order (grouped by section). Extend by adding an- * entry (plus its label and, when engine-backed, a store); the popover,- * persistence, and engine feed all derive from this list.- */+/** Derive popover order, persistence, and engine feeds from these sectioned entries. */export const CANVAS_SETTINGS: readonly CanvasBooleanSetting[] = [// ── Behavior ──────────────────────────────────────────────────────────────{diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/checkerColors.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/checkerColors.tsindex e579b54f91..e1ce7ca7f6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/checkerColors.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/checkerColors.ts@@ -1,25 +1,11 @@/**- * Resolves the transparency checkerboard's two square colors from the live Chakra- * theme so the infinite-canvas surround uses theme tokens (not hardcoded greys),- * and re-resolves on theme / color-mode switches. The resolved colors are fed- * one-directionally into the engine's `checkerColors` store (the same- * settings→engine-store pattern as the boolean canvas settings); the engine stays- * React-free and rebuilds its cached checker tile when the colors change.- *- * Resolution reads the *computed* backgroundColor of a hidden probe element set to- * each semantic token's CSS custom property — the browser's ground truth for the- * active `<html data-theme>`. Falls back to {@link DEFAULT_CHECKER_COLORS} when the- * DOM is unavailable (node tests) or a token yields nothing usable.+ * Resolve checker semantic tokens through computed probe colors and feed the engine one-way. Use {@link+ * DEFAULT_CHECKER_COLORS} without DOM or usable tokens; changed colors rebuild its cached tile.*/import { system } from '@theme/system';import { type CheckerColors, DEFAULT_CHECKER_COLORS } from '@workbench/canvas-engine/api';-/**- * The two Chakra semantic tokens used for the checker squares. `bg.subtle` and- * `bg.emphasized` are two adjacent neutral surfaces, giving a low-contrast checker- * that reads as "empty" in every theme (light and dark) without a bespoke pair.- */export const CHECKER_TOKEN_A = 'bg.inset';export const CHECKER_TOKEN_B = 'bg.subtle';@@ -40,11 +26,7 @@ export const isUsableColor = (value: string | null | undefined): value is stringexport const pickCheckerColor = (resolved: string | null | undefined, fallback: string): string =>isUsableColor(resolved) ? resolved : fallback;-/**- * Resolves both checker colors from the current theme. Safe to call anytime; in a- * non-DOM environment (or before the theme is applied) it returns the fallback- * pair so callers always get concrete colors.- */+/** Return concrete theme checker colors, falling back when DOM/theme values are unavailable. */export const resolveCheckerColors = (): CheckerColors => {if (typeof document === 'undefined' || typeof getComputedStyle !== 'function' || !document.body) {return { ...DEFAULT_CHECKER_COLORS };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsxindex ea3ed5edf3..002eb0bb27 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx@@ -5,16 +5,8 @@ import { useEffect } from 'react';import { useActiveColorCommands, useActiveColorPair } from './useActiveColors';/**- * The bridge between the active color pair and one engine, kept out of the- * canvas widget shell so per-pointermove pair edits (chip drags, eyedropper- * scrubs) re-render only this null component:- *- * - the pair owns painting color, and the engine's brush color is its mirror- * (the legacy field kept as a compatibility adapter), fed one-directionally- * like the view settings — strokes capture the color at gesture start, so a- * mid-stroke pair change cannot recolor half an edit;- * - unclaimed eyedropper samples route to the active foreground/background- * target instead of the brush option.+ * Isolate frequent color-pair updates in this null adapter. Mirror the pair into brush color, captured at stroke+ * start, and route unclaimed samples to the active pair target.*/export const CanvasColorFeed = ({ engine }: { engine: CanvasEngineHandle | null }) => {const colorPair = useActiveColorPair();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/colorPair.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/colorPair.tsindex 2fcafb7684..eabd8c9206 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/colorPair.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/colorPair.ts@@ -1,9 +1,6 @@/**- * The project's active color pair — the desktop-editor foreground/background- * colors that seed painting and creation defaults. The pair is a preference:- * it persists in the canvas widget's per-project values, never in the document- * or its history, and changing it never rewrites selected content. Pure data +- * readers; no React, no engine imports — unit-testable in node.+ * Persist foreground/background preferences in canvas widget values, outside document history; pair changes never+ * rewrite existing content.*/import { formatHexColor, normalizeHex, parseHexColor } from '@platform/ui/color';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/maskTintTarget.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/maskTintTarget.tsindex e355c20491..38d1b739f0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/maskTintTarget.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/maskTintTarget.ts@@ -2,11 +2,8 @@ import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore } from '@platform/state/externalStore';/**- * The Color pane's one non-pair target: a mask layer's tint, armed explicitly- * from a compatible Layer property or the pane's own chip. Transient by- * design — the tint itself is document state; this only names which layer the- * pane is currently editing. Cleared whenever the armed layer stops being the- * selected mask, so the pane falls back to the foreground/background target.+ * Track the transient mask-tint editing target; clear it when it is no longer the selected mask. Tint itself+ * remains document state.*/export const maskTintTargetStore = createExternalStore<{ layerId: string | null }>({ layerId: null });diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useActiveColors.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useActiveColors.tsindex 174c89c2eb..506d9dd258 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useActiveColors.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useActiveColors.ts@@ -1,9 +1,4 @@-/**- * React bindings for the active color pair. Every surface that shows or edits- * the pair (the Color pane, the Properties chip mirror, the canvas hotkeys and- * eyedropper routing) reads and writes the one persisted copy in the canvas- * widget's project values through these hooks — no surface holds its own.- */+/** Share one persisted color pair across pane, properties, hotkeys, and eyedropper through these hooks. */import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useMaskTintEditor.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useMaskTintEditor.tsindex e78ad6c1f1..85ca0328b0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useMaskTintEditor.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useMaskTintEditor.ts@@ -27,10 +27,8 @@ export interface MaskTintEditor {}/**- * A gesture in flight: the layer and fill captured before the first preview- * (the entry's undo target), the latest applied hex, and the settle timer.- * Holding these in one ref keeps the eventual commit closure-safe — the- * gesture can outlive re-renders, a disarm, and even the pane unmounting.+ * Capture layer, original fill, latest color, and timer together so commits survive rerenders, disarming, and+ * unmount.*/interface TintGesture {layer: MaskLayer;@@ -45,12 +43,8 @@ const configFor = (layer: MaskLayer, fill: CanvasMaskFillContract) =>: ({ layerType: 'regional_guidance', mask: { fill } } as const);/**- * The armed mask-tint target as an editor, or `null` when no target is armed.- * Watches the document: if the armed layer disappears, stops being a mask, or- * stops being the selected layer, the target clears itself and the Color pane- * returns to the foreground/background pair. A pending gesture always settles- * into exactly one history entry — on the idle timer, on disarm, or on- * unmount — so a preview can never outlive its commit.+ * Clear invalid/unselected mask targets and return to pair editing. Settle each pending preview into exactly one+ * history entry on idle, disarm, or unmount.*/export const useMaskTintEditor = (engine: MaskTintEngine | null): MaskTintEditor | null => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.tsindex 82e18d7053..14e2aff6bb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts@@ -1,12 +1,4 @@-/**- * React bindings for the engine's transient stores.- *- * `canvas-engine/engineStores.ts` deliberately ships React-free- * (`useSyncExternalStore`-compatible) channels so the engine stays node-safe.- * These hooks are the widget-side adapter — the one place React subscribes to- * that engine-owned interaction state. Keeping the React import here (under- * `widgets/`) preserves the engine's zero-React boundary.- */+/** Adapt engine-owned external stores to React here, preserving the engine's React-free boundary. */import type {BboxToolOptions,@@ -44,11 +36,8 @@ const useCanvasInteractionState = <K extends keyof CanvasInteractionState>(};/**- * Subscribes to a single layer's thumbnail version on `engine`, re-rendering- * only when that layer's cached pixels change (the engine bumps the version on- * every repaint / rasterize). Tolerates a `null` engine — before the engine- * mounts the hook simply reports `undefined` and never subscribes — so the- * layers panel can render fallback thumbnails without an attached engine.+ * Subscribe only to one layer's thumbnail version; null engines return undefined without subscribing for fallback+ * rendering.*/export const useLayerThumbnailVersion = (engine: CanvasCoreStoreCapability | null,@@ -155,12 +144,7 @@ export const useCanvasRasterContentEpoch = (engine: CanvasCoreStoreCapability |return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);};-/**- * The brush tool's current options (size / color / opacity / pressure). Write- * through `engine.interaction.set('brushOptions', ...)` directly — there is no reducer- * mirror to dispatch through, so the options bar reads and writes this one- * store.- */+/** Read/write brush options directly through engine.interaction; no reducer mirror exists. */export const useBrushOptions = (engine: CanvasCoreStoreCapability): BrushOptions =>useCanvasInteractionState(engine, 'brushOptions');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.tsindex 62aa92aeda..e1bbaa9578 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts@@ -1,23 +1,7 @@/**- * Pure geometry for the "fit bbox to layers / masks" header actions, mirroring- * legacy `CanvasBboxToolModule.fitToLayers` / `useAutoFitBBoxToMasks`:- *- * 1. Union the DOCUMENT-space bounds of the qualifying ENABLED, renderable,- * non-empty layers (all layers for fit-to-layers; INPAINT masks only for- * fit-to-masks — legacy fits `getVisibleRectOfType('inpaint_mask')`, so- * regional-guidance masks are deliberately excluded).- * 2. For masks, expand the union outward by a fixed padding (legacy adds- * `maskBlur + 8`; webv2 does not plumb the mask-blur param through the widget- * yet, so a constant {@link MASK_FIT_PADDING} is used — see the report).- * 3. Snap the rect INWARD to the model bbox grid via {@link fitRectToGrid} so the- * result lands on the same multiples a manual bbox edit snaps to.- *- * Returns `null` when there is nothing to fit (no qualifying content, or the- * snapped rect collapses to empty) so the caller can disable the button and never- * dispatch a degenerate bbox. React feeds the grid size from generate settings- * (`gridSizeForModelBase`), exactly like the bbox tool.- *- * Zero React, zero engine/DOM state — unit-tested in node.+ * Union enabled, renderable, nonempty layer bounds in document space. Mask fitting includes only inpaint masks and+ * adds {@link MASK_FIT_PADDING}; snap inward with {@link fitRectToGrid}. Return null for no content or a collapsed+ * result.*/import {@@ -35,10 +19,8 @@ import {const MASK_FIT_PADDING = 8;/**- * Snaps a rect INWARD to `gridSize`: the top-left edges round up (toward the- * interior) and the width/height round down, so the result aligns to the grid and- * never exceeds the input rect. `gridSize <= 1` degrades to a plain integer round- * (no snapping — used when snap-to-grid is off). Mirrors legacy `fitRectToGrid`.+ * Snap inward: round origins up and sizes down. gridSize <= 1 uses integer rounding, matching legacy+ * fitRectToGrid.*/export const fitRectToGrid = (rect: Rect, gridSize: number): Rect => {const g = gridSize > 1 ? gridSize : 1;@@ -49,13 +31,7 @@ export const fitRectToGrid = (rect: Rect, gridSize: number): Rect => {return { height, width, x, y };};-/**- * The union of the document-space bounds of every ENABLED, renderable layer whose- * content is non-empty and that satisfies `predicate`, or `null` when none- * qualify. Empty layers (a brand-new bitmap-less mask, an empty paint layer)- * contribute a zero-size rect and are skipped, matching legacy's `hasObjects()`- * gate.- */+/** Union document bounds of enabled, renderable, nonempty layers matching predicate; return null when none qualify. */export const unionRenderableBounds = (doc: CanvasDocumentContractV3,predicate: (layer: CanvasLayerContract) => booleandiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.tsindex ea599196b4..823bd3ad2e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.ts@@ -1,18 +1,7 @@/**- * Canvas compositing settings — the infill / coherence / mask-blur knobs and- * output-compositing policy used by canvas inpaint and outpaint invocations.- *- * Like {@link import('./canvasStrength').readCanvasDenoisingStrength}, these- * values are persisted per-project inside the canvas widget's own state values- * (`widgetInstances['canvas'].state.values`), so they survive reloads and are- * consumed when the queue submission is compiled. The generate widget's compositing section owns the- * numeric controls; the canvas settings menu owns the masked-only output flag.- * `prepareCanvasInvocation` reads them together — defaulted + clamped — and- * threads one generation-facing contract into the pure graph compiler.- *- * Defaults mirror the legacy params/canvas-settings slices: infill `lama`, mask- * blur 16, coherence Gaussian Blur / edge 16 / min-denoise 0, and masked-only- * output enabled. Pure data + a reader; no React, no engine.+ * Persist canvas compositing policy per project. Generate owns numeric controls, Canvas settings owns masked-only+ * output, and prepareCanvasInvocation supplies defaulted/clamped values to compilation. Defaults mirror legacy+ * infill/coherence/mask behavior.*//** The infill methods the outpaint graph can request (legacy `zInfillMethod`). */@@ -102,11 +91,7 @@ const readInfillColor = (value: unknown): CanvasInfillColor => {return { ...DEFAULT_CANVAS_COMPOSITING.infillColorValue };};-/**- * Reads the persisted canvas compositing settings from a widget's `state.values`,- * applying legacy defaults for any missing/invalid field and clamping to valid- * ranges. Always returns a fully-populated settings object.- */+/** Return complete compositing settings with legacy defaults for invalid/missing fields and valid-range clamping. */export const readCanvasCompositingSettings = (values: Record<string, unknown> | undefined): CanvasCompositingSettings => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasScaling.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasScaling.tsindex 96bfd850fc..961f9f1b43 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasScaling.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasScaling.ts@@ -1,9 +1,4 @@-/**- * Canvas "Scale before processing": persisted in the canvas widget's own- * `state.values` like the denoising strength, read back with defaults by the- * invoke orchestrator and threaded into the pure graph compiler. `none` keeps- * today's behaviour (the bbox snapped to the model grid).- */+/** Persist processing scale in canvas values for compilation; none preserves bbox size snapped to model grid. */import type { CanvasScaleMethod, CanvasScalingSettings } from '@features/generation/contracts';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasStrength.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasStrength.tsindex 01bec0d793..4875ca043f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasStrength.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasStrength.ts@@ -1,14 +1,6 @@/**- * Canvas denoising-strength: the single knob a canvas img2img invoke exposes.- *- * The value is persisted in the canvas widget's own state values- * (`widgetInstances['canvas'].state.values.denoisingStrength`) so it survives- * reloads, and is read — with the default applied — by the invoke orchestrator- * when compiling a submission. Only consulted for img2img- * (txt2img ignores it), matching the graph compiler.- *- * Pure data + a reader; no React, no engine. Shared by the tool-options UI and- * `prepareCanvasInvocation` so the storage key and clamp stay in one place.+ * Share the persisted canvas denoising key/default/clamp between UI and invocation preparation. img2img consumes+ * it; txt2img ignores it.*//** The persisted key inside the canvas widget's `state.values`. */@@ -27,10 +19,6 @@ export const clampCanvasDenoisingStrength = (value: number): number =>? Math.min(MAX_CANVAS_DENOISING_STRENGTH, Math.max(MIN_CANVAS_DENOISING_STRENGTH, value)): DEFAULT_CANVAS_DENOISING_STRENGTH;-/**- * Reads the persisted canvas denoising strength from a widget's `state.values`,- * applying the default when unset and clamping to the valid range.- */export const readCanvasDenoisingStrength = (values: Record<string, unknown> | undefined): number => {const raw = values?.[CANVAS_DENOISING_STRENGTH_KEY];return typeof raw === 'number' && Number.isFinite(raw)diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.tsindex 1aacc0f530..67687518d4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts@@ -228,9 +228,8 @@ const makeHarness = (options: HarnessOptions = {}): Harness => {uploadImage: uploadImage as (blob: Blob) => Promise<CanvasImageUploadResult>,};- // The fake engine seam behind the REAL `composeForGeneration` operation — the- // same fakes the hand-rolled transaction used to wire (stub raster backend,- // counting uploader, spy-able release, harness-scoped dedupe cache).+ // Run real composeForGeneration against stub raster/upload/release dependencies and a harness-owned dedupe+ // cache.const host: GenerationCompositeHost = {captureDocumentSnapshot: () => ({canvas: makeCanvas(options.document ?? makeDoc([rasterLayer('layer-a')])),@@ -511,11 +510,8 @@ describe('runCanvasInvocation', () => {});it('plans from the POST-flush document (re-reads getDocument after the flush barrier)', async () => {- // The flush dispatches `updateCanvasLayerSource` for just-persisted paint- // layers, so the pre-flush snapshot references stale/empty sources. The- // orchestrator must re-read the document after the flush and composite from- // it — otherwise the stale refs build wrong dedupe keys and the empty-paint- // filter reads a `null` bitmap that the flush already replaced.+ // Reread the document after upload flush updates paint sources; pre-flush references would corrupt dedupe and+ // omit newly painted content.const preDoc = makeDoc([rasterLayer('pre')]);const postDoc = makeDoc([rasterLayer('post')]);let flushed = false;@@ -1027,8 +1023,6 @@ describe('runCanvasInvocation', () => {const invokePromise = runCanvasInvocation(harness.deps);await Promise.resolve();- // ...but by the time the flush/composite/compile settles, the user has- // switched to another project.expect(state.activeProjectId).toBe(otherProjectId);releaseFlush();@@ -1240,10 +1234,7 @@ describe('runCanvasInvocation — inpaint / outpaint dispatch', () => {});});-// Task 39, finding 1: a regional reference image is only usable once an image is-// assigned (the settings UI now wires drop/upload → config.image). This guards-// the resolver seam: refs without an image are dropped; refs with an image + a-// compatible model survive into the graph inputs.+// Regional references require an assigned image and compatible model before reaching graph inputs.describe('resolveRegionalReferenceImages', () => {const asset = { imageName: 'ref.png' } as RegionalGuidanceReferenceImageAsset;const ipAdapterModel = { base: 'sd-1', key: 'ipa', name: 'IP Adapter', type: 'ip_adapter' };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.tsindex 44cb7086c3..8361cb9ae7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts@@ -1,33 +1,7 @@/**- * Wires the canvas-generation pipeline into the Invoke button.- *- * `prepareCanvasInvocation` is the thin command-layer entry: it resolves the- * active project's engine and delegates to the React-free- * {@link runCanvasInvocation} orchestrator. The orchestrator runs the whole- * flush → compose → compile → enqueue flow with every side-effecting dependency- * injected, so it is fully node-testable with fakes.- *- * ## Flow (per the plan)- * 1. Resolve the engine (no engine → notice, abort) and normalize/sync the- * generate values exactly as the generate path does.- * 2. `flushPendingUploads()` — the paint-bitmap persistence barrier — so the- * composite reads the latest painted pixels. The composite operation- * captures its document snapshot internally, AFTER this barrier, so it- * plans from the post-flush document (fresh bitmap refs, fresh bbox).- * 3. `composeForGeneration` — Canvas's one deep composite call — produces- * every uploaded image (base / masks / controls / regionals) plus the- * resolved mode. This module supplies the policy: `detectCanvasMode` as the- * mode strategy, control validation as a throwing predicate (an invalid- * enabled nonempty control layer blocks the invoke), and regional-guidance- * rejection as a silent-skip predicate.- * 4. Compile the base-appropriate graph and dispatch it to canvas staging.- * 5. Publish the operation-local dedupe cache only after dispatch returns.- * 6. Any failure (validation throw, upload error, unsupported mode) records a- * notice — the app never gets stuck.- *- * A module-scoped in-flight guard drops an invoke while a prior prepare for the- * same project is still running. The active Ctrl+Enter/topbar path also holds a- * shallower user-facing guard from the instant the command begins.+ * Resolve the active engine, flush paint uploads, compose the fresh snapshot, compile, and enqueue. Invalid+ * controls block; rejected regions skip. Publish dedupe only after dispatch succeeds and report failures as+ * notices. A per-project in-flight guard prevents overlapping preparation.*/import type { CanvasScalingSettings, GenerateModelConfig } from '@features/generation/contracts';@@ -96,10 +70,7 @@ export interface RunCanvasInvocationDeps {* snapshot's destination, so a Canvas source can target the Gallery.*/destination: ResultDestination;- /**- * Canvas's composite-generation operation: snapshot → plan → capture →- * composite → upload, releasing pixel resources on both success and failure.- */+ /** Capture and upload generation composites, releasing pixel resources on success or failure. */composeForGeneration: (options: ComposeForGenerationOptions) => Promise<ComposeForGenerationResult>;/** Expanded positive prompts, resolved by the caller before submitting. */positivePrompts?: string[];@@ -139,13 +110,8 @@ const recordNotice = (};/**- * Control-layer policy + metadata side-channel for the composite operation.- * `shouldComposite` validates each enabled content-bearing control layer in- * z-order and resolves its adapter model from the loaded models: an invalid- * layer throws a shared reason code and blocks the invocation (content-less- * control layers are already excluded by the operation's plan and remain- * harmless). `toGraphInputs` joins the composited image names back with the- * recorded adapter/model metadata.+ * Validate enabled content-bearing controls in z-order and resolve adapters; invalid controls throw and block+ * invocation. Join uploaded names with captured model metadata for graph inputs.*/const createControlLayerCollector = (model: GenerateModelConfig,@@ -269,12 +235,8 @@ export const resolveRegionalReferenceImages = (};/**- * Regional-guidance policy + metadata side-channel for the composite operation.- * `shouldComposite` resolves each region's reference images and rejects regions- * that cannot contribute for the base (no regional support, or nothing the- * base's support matrix honours) with a SILENT skip, mirroring legacy.- * `toGraphInputs` joins the composited mask image names back with the recorded- * prompt/reference metadata.+ * Resolve regional references and silently skip unsupported/noncontributing regions. Join uploaded masks with+ * captured prompt/reference metadata for graph inputs.*/const createRegionalGuidanceCollector = (model: GenerateModelConfig@@ -324,8 +286,7 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promisconst { commands, inFlight, projectId } = deps;const inFlightKey = deps.inFlightKey ?? projectId;- // Concurrency guard: ignore a re-invoke while a prior prepare for this project- // is still settling (the hotkey can be mashed). Cleared in `finally`.+ // Ignore overlapping preparation for the same project; finally clears the guard.if (inFlight.has(inFlightKey)) {return;}@@ -338,18 +299,12 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promisreturn;}- // Resolve model + settings exactly as the generate path does (sync to loaded- // models, then resolve the seed) so canvas and generate stay in lockstep.+ // Sync loaded models and resolve seeds identically to the Generate path.const synced = deps.models ? syncGenerateWidgetValuesWithModels(values, deps.models) : values;const settings = { ...synced, seed: resolveGenerateSeed(synced) };const model: GenerateModelConfig = settings.model;- // Persist any pending paint bitmaps BEFORE compositing from their pixels.- // The composite operation captures its document snapshot internally — after- // this barrier — so it plans from the post-flush document: the flush- // dispatches `updateCanvasLayerSource` for each just-persisted paint layer,- // and a pre-flush snapshot would still reference `paint:empty`/stale bitmap- // names (silent dedupe cache misses) and a possibly-moved bbox.+ // Flush persisted paint before capture so planning sees current bitmap references and bbox.await deps.flushPendingUploads();const controls = createControlLayerCollector(model, deps.models);@@ -470,10 +425,8 @@ export interface PrepareCanvasInvocationArgs {}/**- * Resolves the active project's engine and runs the canvas-invoke orchestrator.- * The returned promise settles after the graph is dispatched or a failure is- * reported, allowing the active command to keep its preparing acknowledgement- * live for the complete pre-queue window. Other callers may still fire-and-track.+ * Settle after dispatch or reported failure so the active command keeps its preparing acknowledgement through the+ * entire pre-queue window.*/export const prepareCanvasInvocation = async (args: PrepareCanvasInvocationArgs): Promise<void> => {const owner = args.owner ?? captureAccountScope();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.tsindex 58fa0e6c1f..de41f803a7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.ts@@ -1,8 +1,6 @@/**- * Pure selection of what the engine should draw as the canvas staged preview:- * the selected finished candidate when visible, otherwise the selected- * placeholder's live denoise-progress frame, otherwise nothing. Kept React-free- * so the candidate-vs-progress decision is unit-testable in node.+ * Prefer the visible finished candidate, then the selected placeholder's live progress frame, otherwise no+ * preview.*/import type { CanvasPlacementContract, StagedPreviewInput } from '@workbench/canvas-engine/api';@@ -24,11 +22,6 @@ export interface StagedPreviewSelection {bboxHeight: number;}-/**- * Resolves the staged-preview source. A selected finished candidate wins when- * candidate previews are visible; otherwise selected-placeholder progress fills- * the bbox. Returns `null` when neither source is available.- */export const selectStagedPreviewSource = ({bboxHeight,bboxWidth,@@ -50,11 +43,7 @@ export const selectStagedPreviewSource = ({return null;};-/**- * A stable string key for a {@link StagedPreviewInput}, so a React effect only- * re-drives the (async, decoding) `setStagedPreview` when the source actually- * changes — including every new progress frame, but not on unrelated renders.- */+/** Key staged preview inputs so decoding reruns for source/progress changes only. */export const stagedPreviewKey = (source: StagedPreviewInput | null): string => {if (source === null) {return 'none';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/surfaceFocus.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/surfaceFocus.test.tsindex 7dc262baa7..658312ce75 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/surfaceFocus.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/surfaceFocus.test.ts@@ -2,12 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { INLINE_EDIT_SELECTOR, shouldFocusCanvasSurface } from './surfaceFocus';-/**- * Minimal DOM stand-in for node-env: `contains` walks the parent chain,- * `closest` reports whether this element (or an ancestor) matches the- * inline-edit selector. Mirrors the FakeElement approach in- * `hotkeys/targetWidget.test.ts`.- */+/** Model contains and inline-editor closest with a minimal parent-chain DOM stand-in. */class FakeElement {parent: FakeElement | null = null;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/surfaceFocus.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/surfaceFocus.tsindex e7fa7f90d9..00e398dfd7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/surfaceFocus.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/surfaceFocus.ts@@ -1,13 +1,6 @@/**- * Pure predicate for the canvas surface's focus-on-pointerdown behavior, kept- * free of React/Chakra so it is node-testable (see `surfaceFocus.test.ts`).- *- * The two `<canvas>` render targets aren't focusable, so a plain click never- * moves DOM focus — it stays wherever it was (e.g. a layers-panel button in a- * DIFFERENT widget), and the hotkey runtime's DOM-focus-based widget resolution- * (`getHotkeyTargetWidget`) keeps routing tool hotkeys (`b`/`e`/…) to that other- * widget. Focusing the surface container on pointerdown moves focus into the- * canvas widget's subtree so its hotkeys fire immediately.+ * Move pointer focus into the canvas subtree so nonfocusable canvas targets do not leave tool hotkeys routed to+ * another widget.*//**@@ -18,24 +11,8 @@export const INLINE_EDIT_SELECTOR = 'input, textarea, select, [contenteditable="true"], [role="textbox"]';/**- * Whether a pointerdown on the canvas surface should focus the surface- * container.- *- * - **Focus already inside the surface → no.** Most importantly the text- * tool's contenteditable (rendered inside the container by `TextEditPortal`):- * clicking the canvas *outside* it is the "click away to commit" gesture,- * which the ENGINE owns (`commitOpenTextSession` in its pointerdown, which- * then swallows the click). Focusing the container here would fire in the- * capture phase — before the engine's bubble-phase handler — synchronously- * blurring the editable, committing + nulling the session via its `onBlur`,- * so the engine would then see no session, not swallow the click, and open a- * stray new text session at the click point. Skipping is also harmless for- * hotkey scope: focus inside the surface already resolves to the canvas- * widget.- * - **Click landing in an inline editor → no.** Belt and suspenders for- * portal-rendered editors whose DOM may sit outside the container (so the- * `contains` check above wouldn't spare them).- * - **Otherwise → yes** (e.g. focus is on a button in another widget's panel).+ * Preserve focus already inside the surface or inline editors. Refocusing during capture would blur-commit before+ * the engine can swallow click-away, creating a stray text session.*/export const shouldFocusCanvasSurface = (container: HTMLElement,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 a8da62eded..c38549bb2f 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@@ -187,10 +187,6 @@ const FilterParamsSettings = ({ engine, isSurfaceInteractionLocked }: ToolFormPr);};-/**- * The operation's sticky footer: the status chip, Reset, Process (hidden while- * auto-process owns it), Apply with its save-as menu, and Cancel.- */const FilterFooter = ({ engine, isExternalInteractionLocked }: ToolFooterProps) => {const { t } = useTranslation();const session = useFilterSession(engine);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsxindex 460d570822..397a5aa1e5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx@@ -38,11 +38,8 @@ interface SelectedGradient {}/**- * Kind, angle and the stop strip. Displayed values follow the selected- * gradient layer, else the tool defaults — where the built-in FG→BG preset- * shows the live pair (resolved for real at gesture start) and editing a stop- * switches to explicit custom stops, independent of later pair edits. Edits- * commit to a selected gradient layer (stop gestures once on release).+ * Edit selected gradients or creation defaults; FG-to-BG follows the live pair until explicit stop edits switch to+ * custom colors. Stop gestures commit once on release.*/const useGradientEditor = (engine: ToolFormProps['engine']) => {const { t } = useTranslation();@@ -125,12 +122,7 @@ const useGradientEditor = (engine: ToolFormProps['engine']) => {const STRIP_CHECKER = 'repeating-conic-gradient(#00000022 0% 25%, transparent 0% 50%) 0 0 / 10px 10px';-/**- * The stop strip: a ramp with draggable stop handles. Click an empty spot to- * add a stop with the ramp's color there; drag or arrow-key a handle to move- * it. Gestures preview locally and commit once on release, so a selected- * gradient records one history entry per gesture.- */+/** Add stops from ramp colors and move by drag/keyboard; preview locally and commit one history entry on release. */const GradientStopStrip = ({onCommit,onSelect,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 b4332d2aea..fcaea23721 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@@ -115,11 +115,7 @@ export const getSamPanelViewModel = (sourceLabel: formatSourceLabel(session.layerName, session.sourceRect.width, session.sourceRect.height),});-/**- * SAM-flavored adapter over {@link OperationStatusSlot}: the always-mounted- * status slot that reserves its width so status/error text appearing never- * shifts the surrounding controls.- */+/** Reserve OperationStatusSlot width so SAM status/error text cannot shift controls. */export const SamStatusSlot = ({error,errorText,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsxindex ec3da93d5b..d6d9e70afd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx@@ -56,9 +56,8 @@ const OpModeButton = ({};/**- * The boolean op mode every pixel-selection tool shares (also settable- * transiently with shift / alt while committing), plus the gesture hint while- * no selection exists. The mode lives in each tool's own options store.+ * Share selection operation mode and empty-selection hints; each tool stores its mode, with transient Shift/Alt+ * overrides.*//** The four op-mode toggles alone; the form places them in a labelled row. */export const SelectionOpModeButtons = ({diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsxindex de18085b3e..618c3801d2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx@@ -37,12 +37,8 @@ interface SelectedShape {const FALLBACK_COLOR = '#000000';/**- * Displayed values follow the selected shape layer, else the creation defaults- * — kind/width/enablement from the tool options and colors from the active- * pair (fill = foreground, stroke = background). A selected shape's edits- * commit to the document (colors record one history entry on release); with- * nothing selected the color chips edit the pair itself, so there is no second- * global shape color.+ * Edit selected shape content or tool defaults with pair colors. Color gestures commit once; without a selected+ * shape they edit the shared pair.*/const useShapeEditor = (engine: ToolFormProps['engine']) => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsxindex f853a8a678..f7aa330880 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx@@ -213,12 +213,8 @@ const AlignButton = ({};/**- * Displayed values: an open editing session's live source, else the selected- * text layer, else the tool defaults — with color from the active foreground- * when neither a session nor a selection owns one, so there is no second- * global text color. Style edits update the defaults, then restyle the live- * session (folded into its single commit) or commit one history entry on the- * selected layer; color edits with nothing to own them edit the pair.+ * Prefer live text session, selected text, then defaults. Style edits update defaults and the current owner;+ * unowned color edits change the foreground pair.*/const useTextEditor = (engine: ToolFormProps['engine']) => {const { t } = useTranslation();@@ -304,9 +300,7 @@ const useTextEditor = (engine: ToolFormProps['engine']) => {t,]);- // The chip names what applyEdit actually writes: the SESSION when one is- // open (its layer's name, or the new-text placeholder in create mode), else- // the selected text layer, else the defaults.+ // Name the actual edit target: live session, selected text layer, or defaults.const sessionLayerName = useActiveProjectSelector((project): string | null => {if (!session?.layerId) {return null;@@ -317,10 +311,6 @@ const useTextEditor = (engine: ToolFormProps['engine']) => {return { active, applyEdit, content, targetName };};-/**- * A live specimen of the active face — family, style, weight, axes and color —- * with the target chip: the one place the form shows what its values add up to.- */export const TextPreview = ({ engine }: ToolPreviewProps) => {const { active, content, targetName } = useTextEditor(engine);// The instanced face the canvas rasterizes with; the engine keeps thediff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsxindex 54b032dda8..f1b1dfa739 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx@@ -87,11 +87,7 @@ export const useLayerTransformEditor = (engine: ToolFormProps['engine'], labelKereturn { patch, transform };};-/**- * The shared Position rows: the frame's document bbox under the Frame tool,- * else the selected layer / transform session. One component for every- * geometry tool, so the X/Y fields keep DOM identity across tool switches.- */+/** Share geometry rows across frame, selected layer, and transform session to preserve X/Y DOM identity. */const GeometryPositionSettings = ({ engine }: ToolFormProps) => {const { t } = useTranslation();const activeTool = useCanvasActiveTool(engine);@@ -116,8 +112,6 @@ const GeometryPositionSettings = ({ engine }: ToolFormProps) => {[bboxEditor, isFrame, layerEditor]));- // The group header already says Position; the fields carry their own X/Y- // prefixes, so a row label would just repeat it.return (<Flex gap="2" w="full"><FormNumberFielddiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/hintForms.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/hintForms.tsxindex 35d434a43e..dc840f86c6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/hintForms.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/hintForms.tsx@@ -4,11 +4,6 @@ import { HintCard } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimport { useMemo } from 'react';import { useTranslation } from 'react-i18next';-/**- * Gesture cards for the tools whose whole interface is the pointer. The rows- * mirror what `pointerPipeline`/the tools actually do — hold-keys included —- * instead of the old single hint sentence.- */const ViewHints = (_props: ToolFormProps) => {const { t } = useTranslation();const rows = useMemo(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/paintForm.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/paintForm.tsxindex 6b0646f1d9..c8b6d4bb84 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/paintForm.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/paintForm.tsx@@ -24,13 +24,7 @@ import {/** The eraser preview's neutral ink: it erases, so no project color applies. */const ERASER_PREVIEW_COLOR = '#9aa2b1';-/**- * The brush/eraser form pieces are SHARED components that read the active tool- * from the engine, rather than per-tool closures: identical component types- * under identical group ids keep the DOM alive across the brush↔eraser- * switch, which is what makes the "stable geometry across related tools"- * invariant hold in the form world.- */+/** Share components/group ids across brush and eraser so switching tools preserves form DOM and geometry. */const usePaintOptions = (engine: ToolFormProps['engine']) => {const activeTool = useCanvasActiveTool(engine);const brush = useBrushOptions(engine);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/selectionForm.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/selectionForm.tsxindex 7ba7f76650..f2992d780f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/selectionForm.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/selectionForm.tsx@@ -21,11 +21,7 @@ import { useTranslation } from 'react-i18next';import { SelectionActions, SelectionOpModeButtons } from './SelectionOptionsRow';-/**- * The shared selection form: the path shape (lasso freehand/polygon or marquee- * rectangle/ellipse), the op mode, and the command cluster. One component set- * reading the active tool, so the rows keep DOM identity lasso↔marquee.- */+/** Share selection rows across lasso/marquee to preserve DOM identity while active-tool stores supply values. */const SelectionModeSettings = ({ engine, isSurfaceInteractionLocked }: ToolFormProps) => {const { t } = useTranslation();const activeTool = useCanvasActiveTool(engine);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/FormControls.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/FormControls.tsxindex e40008e1ef..2159d641d7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/FormControls.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/FormControls.tsx@@ -38,13 +38,8 @@ const START_ELEMENT_PROPS = { ...AFFIX_PROPS, fontWeight: 'medium', pointerEventconst END_ELEMENT_PROPS = { ...AFFIX_PROPS, pe: '1.5', pointerEvents: 'none' } as const;/**- * A fixed-width numeric field with tabular figures whose prefix is a scrub- * handle (drag sideways with the mouse to change the value by `step` per- * pixel). In commit mode a draft survives typing and scrubbing; the owner- * hears one value on blur, Enter or pointer-up, and only when something was- * edited to a different string, so tabbing through fields never commits the- * rounded display back over a precise value. Only the accepted value shows- * afterwards, so a clamped commit never leaves the field disagreeing with its owner.+ * Keep drafts through typing/scrubbing and commit once on blur, Enter, or release only after edits. Do not+ * overwrite precise values by tabbing through rounded displays; show the accepted clamped result.*/export const FormNumberField = ({'aria-label': ariaLabel,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsxindex 567786a6cd..359ed065e0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx@@ -11,10 +11,8 @@ import { setPropertyGroupCollapsed, usePropertyGroupCollapsed } from './propertyconst GROUP_HEADER_HOVER = { color: 'fg' } as const;/**- * One settings row of a tool property form: a fixed label column, a flexible- * control cell, and a fixed trailing cell. Grid, not wrapping flex — a slider- * and its number field are one row at every pane width. No label leaves the- * column empty so a continuation row lines up under the row above.+ * Use fixed label/trailing columns around a flexible control so sliders and numbers never wrap; blank labels+ * preserve continuation alignment.*/export const PropertyControlRow = ({ children, label }: { children: ReactNode; label?: string }) => (<Grid alignItems="center" columnGap="2" gridTemplateColumns="4.5rem minmax(0, 1fr) auto" minH="7" w="full">@@ -154,11 +152,7 @@ export const PropertySegmentedRow = <Value extends string>({);};-/**- * Names what a dual-role form is editing right now: the creation defaults, or- * the selected layer's own content. Shown once at the top of the affected- * form, per the C0 §4 target-chip decision.- */+/** Identify whether the form edits creation defaults or selected content. */export const EditTargetChip = ({ layerName }: { layerName: string | null }) => {const { t } = useTranslation();return (@@ -180,10 +174,6 @@ export const EditTargetChip = ({ layerName }: { layerName: string | null }) => {);};-/**- * A small gesture/keymap table for tools whose whole story is how you point at- * the canvas: a chip naming the gesture, then what it does.- */export const HintCard = ({ rows }: { rows: readonly { gesture: string; effect: string }[] }) => (<Stack gap="1">{rows.map((row) => (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolFormContracts.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolFormContracts.tsindex c5c3dc91e3..6fce508916 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolFormContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolFormContracts.ts@@ -41,9 +41,8 @@ export interface ToolPropertyGroup {}/**- * A tool's purpose-built pane form: an optional preview card on top, then- * named groups of typed rows. Successor to the region adapter; tools migrate- * one by one and the pane renders whichever shape a tool declares.+ * Describe tool panes with optional previews and typed row groups; the pane supports this form alongside migrating+ * region adapters.*/export interface ToolPropertyForm {id: ToolId;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/toolFamilyStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/toolFamilyStore.tsindex 7940501fc4..129489709f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/toolFamilyStore.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/toolFamilyStore.ts@@ -20,11 +20,7 @@ const readStored = (): SelectFamilyTool => {}};-/**- * Which selection tool the strip's Select family slot stands for right now —- * the last one used, remembered per user, so the slot's plain click restores- * the tool the user actually works with.- */+/** Remember the user's last selection subtool so a plain family-slot click restores it. */const store = createExternalStore<{ tool: SelectFamilyTool }>({ tool: readStored() });export const recordSelectFamilyTool = (tool: SelectFamilyTool): void => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useColorSampler.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useColorSampler.tsindex 8bdf4bd373..7bafe28239 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useColorSampler.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useColorSampler.ts@@ -1,15 +1,6 @@/**- * Binds a color picker's eyedropper to the canvas.- *- * The browser's `EyeDropper` API only reads the composited *screen*, which is- * Chromium-only and picks up whatever chrome happens to sit over the canvas.- * The engine already owns a better sampler — the color-picker tool reads the- * composited document through the layer cache — so any picker rendered- * alongside a canvas hands this to `ColorPicker`'s `onSampleColor` instead.- *- * The returned callback is stable, which the `react-perf/jsx-no-new-*-as-prop`- * rules require of anything passed straight into JSX. Without an engine it- * returns `undefined`, so the picker keeps its screen-eyedropper fallback.+ * Prefer the engine's document sampler over Chromium's composited-screen eyedropper. Return a stable callback with+ * an engine, otherwise preserve ColorPicker's fallback.*/import type { CanvasEngineToolCapability } from '@workbench/canvas-engine/api';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/zoomOptions.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/zoomOptions.tsindex 6f8b6c3b04..b869dac9e9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/zoomOptions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/zoomOptions.ts@@ -1,10 +1,4 @@-/**- * Pure zoom-menu helpers for the canvas HUD.- *- * The option set is derived from the engine's single source of truth for zoom- * snap points (`ZOOM_PRESETS`), so the HUD and the viewport's wheel- * snapping always agree. No React, no side effects — unit-testable in node.- */+/** Derive HUD zoom choices from engine ZOOM_PRESETS so menu and wheel snapping agree. */import { ZOOM_PRESETS } from '@workbench/canvas-engine/api';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.browser.test.tsxindex 214a9989b6..8f373140b1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.browser.test.tsx@@ -21,8 +21,6 @@ const settle = (action: () => void): Promise<void> =>type Counts = { embedded: number; failed: number; pending: number; total: number };-// Hoisted: an object or function literal in a JSX attribute is what-// react-perf/jsx-no-new-*-as-prop forbids, tests included.const noop = () => {};const QUARTER: Counts = { embedded: 25, failed: 0, pending: 75, total: 100 };const PART_WAY: Counts = { embedded: 1204, failed: 0, pending: 3108, total: 4312 };@@ -175,9 +173,7 @@ describe('ImageIndexProgressPanel', () => {describe('ImageIndexProgressInline', () => {it('stays inside a footer narrower than its content', async () => {- // The widget resizes down to 280px and the counts can be six digits each.- // `<Text truncate>` is what kept the line this replaced from pushing past- // the panel edge and under the refresh button.+ // Keep six-digit counts inside a 280px panel without overlapping refresh.await mount(<div style={NARROW_HOST}><ImageIndexProgressInline counts={SIX_DIGITS} updatedAt={Date.now()} />@@ -219,8 +215,7 @@ describe('ImageIndexProgressInline', () => {'120px');- // The bar is the glanceable half; letting the flex squash it would leave- // the row saying nothing at all.+ // Prevent flex shrinking from erasing the glanceable progress bar.expect(host!.querySelector('[role="progressbar"]')!.getBoundingClientRect().width).toBeGreaterThanOrEqual(38);});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsxindex aa2476936b..22ff54261b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx@@ -7,12 +7,7 @@ import { useEffect, useState } from 'react';const PROGRESS_LABEL = 'Image indexing progress';-/**- * How often the age of the counts is re-read. The only thing it drives is a- * minutes-scale "no progress" note, so this is deliberately coarse: the same- * interval serves the panel and the footer, and neither announces a number- * that moves every second.- */+/** Update age coarsely for minute-scale stall messages shared by panel and footer. */const TICK_MS = 5_000;/** How long the counts have been standing, re-read on a timer. */@@ -41,14 +36,8 @@ interface ImageIndexProgressProps {}/**- * Backfill progress for the embedding index, shown in place of the map while- * there is nothing to draw yet. The counts are pushed by `image_index_status`- * (admins only, which in single-user mode is everyone), so a non-admin sees- * the plain "nothing to map yet" message instead of a bar that never moves.- *- * The wording stays away from "your images": the backend's counts aggregate- * every user's gallery, so for an admin on a multi-user server this is the- * server's backlog and not necessarily any of their own.+ * Show server-wide embedding progress only to admins receiving status events; non-admins see the empty state+ * instead of a frozen bar.*/export const ImageIndexProgressPanel = ({counts,@@ -93,18 +82,12 @@ export const ImageIndexProgressPanel = ({) : null}</Stack>{error ? (- // `overflowWrap: anywhere` because the message is whatever the server- // said: a URL or a dotted identifier has no break opportunity, and a- // centered flex item sizes to min-content, so it would otherwise run- // off both edges of a widget clipped at 280px with no ellipsis.+ // Wrap server URLs/identifiers anywhere to prevent min-content overflow in narrow panels.<Text color="fg.error" fontSize="xs" maxW="full" minW="0" mt="2" overflowWrap="anywhere" role="alert">{error}</Text>) : null}- {/* The widget's only control in this state — the footer renders nothing- until the map itself is ready. It matters most when the counts are- wrong: a client that was offline for the run's final report sits on a- bar that will never move again, and this re-reads them. */}+ {/* Refresh is the only control before map readiness and recovers counts missed while offline. */}<Button mt={error ? '0' : '2'} onClick={onRetry} size="xs" variant="outline">{error ? 'Retry' : 'Check again'}</Button>@@ -113,20 +96,8 @@ export const ImageIndexProgressPanel = ({};/**- * The same progress as a badge laid over the map itself.- *- * The panel above is only reachable when there is nothing to draw, so on a- * gallery that already has a map — the case for every re-index, including the- * automatic one after the embedding model changes — the view drew the old- * points and said nothing at all about the work in flight. The footer's line- * is 2xs chrome and renders only once `state === 'ready'`, so it is not that- * signal either.- *- * Overlaid rather than substituted: the stale map is still worth using while- * the new one is built, so this must not take the panel over. It also names- * the labels, which disappear for the duration whenever the vocabulary- * embeddings are being rebuilt (a model change, or a supplementary-vocabulary- * edit) — that silence was the other half of the map looking broken.+ * Overlay rebuild progress while the stale map remains usable; explain missing labels during vocabulary embedding+ * rebuilds.*/export const ImageIndexActivityBadge = ({ counts, updatedAt }: ImageIndexProgressProps) => {const progress = describeIndexProgress(counts, useCountsAge(updatedAt));@@ -135,11 +106,7 @@ export const ImageIndexActivityBadge = ({ counts, updatedAt }: ImageIndexProgres: `Indexing ${progress.counts}. The map and its cluster labels update as images finish.`;return (- // The wrapper spans the plot so the badge can sit in its corner, and passes- // every pointer event through: the plot underneath is drag-panned and- // wheel-zoomed across its whole area, and a full-width transparent layer- // that swallowed those would cost more than the badge is worth. The badge- // itself takes its events back so the tooltip still opens.+ // Pass plot-wide pointer events through the wrapper; only the badge intercepts them for its tooltip.<Box inset="0" pointerEvents="none" position="absolute" zIndex="1"><Tooltip content={label}><HStack@@ -174,21 +141,13 @@ export const ImageIndexActivityBadge = ({ counts, updatedAt }: ImageIndexProgres);};-/**- * The same progress in one line, for the widget footer once the map itself is- * on screen: the bar is the glanceable part, the rest is one hover away rather- * than competing with the point count for the width.- */export const ImageIndexProgressInline = ({ counts, updatedAt }: ImageIndexProgressProps) => {const progress = describeIndexProgress(counts, useCountsAge(updatedAt));const label = progress.stale ? `Indexing ${progress.counts} · ${progress.stale}` : `Indexing ${progress.counts}`;return (<Tooltip content={label}>- {/* `minW="0"` and a truncating label, both of which the plain `<Text- truncate>` this replaced got for free: the footer resizes down to- 280px and the counts can be six digits each, and without them the row- grows past the panel edge and slides under the refresh button. */}+ {/* Use minW=0 and truncation so six-digit footer counts cannot cover refresh in narrow panels. */}<HStack gap="1.5" minW="0" overflow="hidden" title={label}><Progress.Root flexShrink="0" max={100} size="xs" value={progress.percent} w="10">{/* The counts go in the name too: at the widget's minimum width thediff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.test.tsindex 2cd3231c1f..86e44146a6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.test.ts@@ -86,9 +86,7 @@ describe('attachImageMapDataRuntime', () => {it('leaves a failed canvas alone instead of remounting it once per event', () => {const detach = attachImageMapDataRuntime();- // The plot's WebGL init failed; the view is showing that, and every- // successful refresh would clear it and remount straight into the same- // failure — once per event for the length of a backfill.+ // Refresh must not repeatedly clear a WebGL failure and remount the broken plot during backfill.imageMapStore.patchSnapshot({ loadState: 'loaded', renderError: 'The map failed to render.' });getHandler('image_map_projection_ready')({ user_id: 'u1' });getHandler('image_index_updated')({ user_id: 'u1' });@@ -106,13 +104,8 @@ describe('attachImageMapDataRuntime', () => {it('does not queue a duplicate fetch for an event during the first load', () => {const detach = attachImageMapDataRuntime();- // `loading` used to pass the guard, so the event set `rerunRequested` and- // forced a second full point set the moment the first settled. The poke- // still must not pass: it fires at indexer quiescence, so a backfill- // running while the map first loads would double every fetch. The- // accepted trade: embedding enqueues no recompute, so a poke landing in- // the first-load window is the only announcement of that image — it stays- // off the map until the next event or a manual refresh.+ // Ignore ordinary pokes during first loading to avoid duplicate full fetches; newly embedded items may wait+ // for a later event/manual refresh.imageMapStore.patchSnapshot({ loadState: 'loading' });getHandler('image_index_updated')({ user_id: 'u1' });@@ -124,12 +117,8 @@ describe('attachImageMapDataRuntime', () => {const detach = attachImageMapDataRuntime();const onReady = getHandler('image_map_projection_ready');- // A recompute can finish while the fetch it was enqueued by is still in- // flight: that fetch was served the projection the recompute replaced, and- // dropping the announcement strands the stale points (with labels the- // mismatch check keeps discarding) until some later event fires. The- // store's dedup turns this call into a single queued rerun, not a parallel- // fetch.+ // Queue one rerun when recompute overtakes its triggering fetch so stale points and mismatched labels do not+ // persist.imageMapStore.patchSnapshot({ loadState: 'loading' });onReady({ user_id: 'u1' });@@ -185,9 +174,7 @@ describe('attachImageMapDataRuntime', () => {mocks.getAuthSession.mockReturnValue({ user: { user_id: 'me' } });imageMapStore.patchSnapshot({ loadState: 'loaded' });- // Admins receive every user's projection events, and an admin refetch- // usually finds its own all-images projection stale and enqueues another- // full recompute.+ // Ignore other users' projection events; admin refetches can otherwise trigger repeated recomputes.onReady({ user_id: 'someone-else' });expect(mocks.refreshImageMapPoints).not.toHaveBeenCalled();@@ -262,9 +249,7 @@ describe('attachImageMapDataRuntime', () => {it('does not refetch when it attaches to an already-connected socket', () => {imageMapStore.patchSnapshot({ loadState: 'loaded' });- // `onConnectionChange` replays the current status synchronously, and every- // Launchpad -> Editor navigation remounts this runtime; treating that- // replay as a reconnect refetched the whole point set on each entry.+ // Treat synchronous connection replay as baseline, not reconnect, on editor remount.const detach = attachImageMapDataRuntime();const onConnection = mocks.onConnectionChange.mock.calls[0][0];diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.tsxindex 107b1778b0..63c6a02709 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.tsx@@ -11,11 +11,8 @@ import {} from '@workbench/image-map/imageMapStore';/**- * Socket-driven refresh for the image map, replacing polling: when the- * backend announces a recomputed projection (or the socket reconnects after- * an outage), the point set refetches. Index progress counts feed the footer.- * Nothing fetches until the widget itself has loaded the map once — a user- * who never opens the Image Map pays nothing.+ * Refresh loaded maps on projection events and reconnects; feed footer counts without fetching for sessions that+ * never open the map.*//*** An event naming a user other than the session's. Admins receive index and@@ -44,12 +41,8 @@ export const attachImageMapDataRuntime = (): (() => void) => {const refreshIfLoaded = () => {const { loadState, renderError } = imageMapStore.getSnapshot();- // Only once the widget has actually loaded the map. `loading` used to pass- // this guard, so an event landing during the first fetch queued a rerun- // and forced a second full point set the moment it settled. It still must- // not pass here — but `image_map_projection_ready` below is the exception:- // that one event can announce a projection newer than the in-flight- // response, where dropping it strands a stale map.+ // Ignore ordinary events during first load; projection-ready is the exception because it may supersede the+ // in-flight response.if (loadState !== 'loaded' && loadState !== 'error') {return;}@@ -65,14 +58,8 @@ export const attachImageMapDataRuntime = (): (() => void) => {void refreshImageMapPoints();};- // A finished projection recompute can overtake the fetch that triggered it:- // the request was served the projection the recompute then replaced, so its- // points are stale and the labels request that follows it answers over the- // new record — discarded on the hash mismatch, with no labels to show for- // it. Dropping the event strands that map until some later one happens to- // fire; admitting `loading` costs one extra point set at most, because the- // store's dedup queues a single rerun when a refresh lands mid-flight (the- // `rerunRequested` comment describes exactly this arrival).+ // Allow projection-ready during loading: recompute can overtake the fetch and invalidate labels. Store dedupe+ // queues at most one rerun.const refreshProjectionReady = () => {const { loadState, renderError } = imageMapStore.getSnapshot();@@ -98,37 +85,20 @@ export const attachImageMapDataRuntime = (): (() => void) => {socketHub.on('image_index_updated', refreshIfLoaded),socketHub.on('image_index_status', (payload: never) => {const event = payload as unknown as ImageIndexStatusEvent;- // Through the store rather than a direct patch: it also folds the counts- // into the throughput estimate the progress UI turns into a time remaining.recordImageIndexStatus({embedded: event.embedded,failed: event.failed ?? 0,pending: event.pending,total: event.total,});- // Quiescence is the moment the point set may have changed: batch- // completions, deletions, and the final sweep after failures all end- // in a pending === 0 emit (permanently-failed images are excluded- // from pending so it always drains). Refetching makes the backend- // compare scope hashes; if the map is stale it enqueues the recompute- // whose projection-ready event closes the loop above. Without this- // poke neither side ever initiates: the backend only recomputes when- // asked, and nothing else asks. Status events are admin-only (the- // counts aggregate every user's images); non-admins get the- // image_index_updated poke above for their own embeds, and manual- // refresh covers their deletions (the backend cannot resolve an- // owner for an already-deleted row).+ // At indexing quiescence, refresh to trigger scope-hash comparison and needed recomputation. Admin counts+ // cover all users; non-admin embed pokes cover their own images, while deletions may need manual refresh.if (event.pending === 0) {refreshIfLoaded();}}),];- // `onConnectionChange` replays the current status synchronously on subscribe,- // and this runtime is remounted by every Launchpad -> Editor navigation. That- // replay only establishes the baseline: an already-connected socket has- // missed nothing, and refetching on it costs a full point set on every entry- // into the editor. Only a real disconnected -> connected transition can have- // gaps to close.+ // Use connection replay only as baseline; refresh on actual disconnected-to-connected transitions.let previousStatus: string | null = null;const detachConnection = socketHub.onConnectionChange((status) => {const isReconnect = previousStatus !== null && previousStatus !== 'connected' && status === 'connected';@@ -138,12 +108,7 @@ export const attachImageMapDataRuntime = (): (() => void) => {if (isReconnect) {refreshIfLoaded();- // Status events are not replayed, so a run that finished during the- // outage never announces it: the counts would sit at their last- // pre-outage value and the progress UI would claim a backfill is still- // running until the page is reloaded. Re-reading them closes that gap —- // behind the same guard, so a session that never opened the map still- // pays nothing for a flapping connection.+ // Reread counts after reconnect because status events are not replayed; retain the map-open guard.if (hasLoadedOnce()) {refreshImageIndexStatus();}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsxindex 452c091528..00783669e4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx@@ -6,11 +6,6 @@ import { useWidgetValuesSelector, useWorkbenchCommands } from '@workbench/Workbeimport { GroupIcon, TagsIcon } from 'lucide-react';import { useCallback } from 'react';-/**- * Header toggles for the map's two click/display modes: whether a click selects- * the whole cluster, and whether cluster labels are drawn. Both persist in the- * widget's values, like the gallery's own view settings.- */export const ImageMapHeaderActions = (_props: WidgetViewProps) => {const { widgets } = useWorkbenchCommands();const clickSelectsCluster = useWidgetValuesSelector('image-map', getImageMapClickSelectsCluster);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsxindex 505ffd3de4..8cee93fe3c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx@@ -71,13 +71,8 @@ const readRanges = (plot: PlotElement): AxisRanges | null => {};/**- * The whole-map view for the first properly-sized render: the percentile box- * expanded to include the current-image marker (so the auto-recenter has no- * reason to immediately shift it), then aspect-corrected to the container.- * The axes are constrained to equal unit scale, and letting plotly resolve an- * over-constrained range pair itself can crop one axis — a first render in a- * still-unmeasured container ends up zoomed into a sliver of the map, which- * the view-preservation on later renders would then keep forever.+ * Fit the percentile box plus current marker once the container is measured, preserving equal axis scale so a+ * zero-size initial fit cannot become the permanent view.*/const computeInitialFit = (points: ImageMapPoint[],@@ -107,12 +102,7 @@ const computeInitialFit = (const findTraceIndex = (plot: PlotElement, name: string): number =>(plot.data ?? []).findIndex((trace) => (trace as { name?: string }).name === name);-/**- * Imperative plotly host. All plotly calls happen in effects against a ref- * div — plotly manages its own DOM and must never render through JSX. This- * module is lazy-loaded so the plotly bundle stays out of the app's critical- * path.- */+/** Lazy-load the imperative Plotly host; Plotly owns its DOM outside JSX. */const ImageMapPlot = ({clickSelectsCluster = false,showClusterLabels = true,@@ -123,24 +113,17 @@ const ImageMapPlot = ({const containerRef = useRef<HTMLDivElement | null>(null);const points = imageMapStore.useSelector((snapshot) => snapshot.data?.points ?? null);const clusterLabels = imageMapStore.useSelector((snapshot) => snapshot.clusterLabels);- // Whether those labels were computed over the clustering now drawn. The- // annotations accept a stale set for the ~1s until fresh ones land (see the- // relayout effect below), but the hover card names one specific cluster by- // id, and a refresh can renumber every id — so it shows no tags rather than- // another cluster's.+ // Require matching clustering for hover tags: refresh may renumber ids even while stale annotations remain+ // briefly visible.const clusterLabelsMatchPoints = imageMapStore.useSelector((snapshot) => snapshot.clusterLabelsHash !== null && snapshot.clusterLabelsHash === snapshot.data?.visibleHash);- // The primary selection as an item key: a selected video is marked on the- // map like any other item, and the key is a string so the refs and the- // recenter comparisons below stay plain equality checks.+ // Use item keys for selection/recentering equality, including videos.const selectedKey = useWidgetValuesSelector('gallery', (values) => {const item = getSelectedGalleryItemFromValues(values);return item ? toGalleryItemKey({ kind: item.kind, name: item.name }) : null;});- // Both the persisted selection and the map's points are kind-tagged, so the- // highlight compares item keys and a selected video marks its own point.const selectedItemKeys = useWidgetValuesSelector('gallery',(values) => getPersistedSelectedGalleryItemKeys(values),@@ -174,9 +157,7 @@ const ImageMapPlot = ({// The points array `fullAnnotationsRef` was built from, so the marker effect// can tell whether those annotations describe the embedding now on screen.const annotationsPointsRef = useRef<ImageMapPoint[] | null>(null);- // The initial whole-map fit must happen exactly once per mount, at the- // first render where the container has real dimensions; these refs let the- // scene effect and the resize observer coordinate without re-running.+ // Coordinate scene and resize paths to perform whole-map fitting once, after real measurement.const initialFitDoneRef = useRef(false);const pointsRef = useRef(points);const selectedKeyRef = useRef(selectedKey);@@ -190,23 +171,12 @@ const ImageMapPlot = ({clusterModeRef.current = clickSelectsCluster;clusterLabelsRef.current = clusterLabels;}, [clickSelectsCluster, clusterLabels, points, selectedKey]);- // The full annotation set for the current data; which of them actually show- // is view-dependent (see applyDeclutteredAnnotations), so the source list- // lives in a ref the relayout listener can re-filter without re-rendering.+ // Keep full annotations in a ref so relayout can refilter visibility without React renders.const fullAnnotationsRef = useRef<ClusterAnnotation[]>([]);const appliedAnnotationsKeyRef = useRef<string | null>(null);- // Zoomed far out, cluster labels pile onto the same few pixels; declutter- // against the CURRENT view so only labels with room to breathe render, and- // zooming back in restores the rest. The applied-key check makes the common- // case (a pan/zoom that changes no label's visibility) a no-op — it also- // keeps this from feeding back into itself through the plotly_relayout- // event its own relayout fires.- //- // The gold target is passed in so it outranks the labels: it draws on the- // WebGL canvas *below* plotly's annotation layer, so a label overlapping it- // wins on z-order no matter how the traces are ordered. Dropping that label- // is what keeps the current position findable in a dense field.+ // Declutter against the current view and skip unchanged visibility to avoid relayout feedback. Reserve space for+ // the gold target beneath Plotly's annotation layer.const applyDeclutteredAnnotations = useCallback((container: PlotElement) => {const ranges = readRanges(container);const selectedItemKey = selectedKeyRef.current;@@ -262,11 +232,8 @@ const ImageMapPlot = ({];let disposed = false;- // Feed the CURRENT view back into react so data refreshes never reset the- // user's pan/zoom (uirevision alone does not preserve ranges set through- // the public relayout API). The first properly-sized render instead gets- // an aspect-corrected whole-map fit — never a preserved view, which- // could be a cropped artifact of a zero-size initial layout.+ // Preserve user ranges across refreshes, but use an aspect-corrected fit for the first measured render rather+ // than retaining zero-size artifacts.let initialRanges = readRanges(container as unknown as PlotElement) ?? computePercentileRanges(points);if (!initialFitDoneRef.current) {@@ -278,18 +245,14 @@ const ImageMapPlot = ({}}- // Annotations are deliberately absent here: they are a layout concern, and- // rebuilding the scene for them is what made labels arriving a second after- // the points re-materialize every trace. See the relayout effect below.- // Since the rebuilt layout carries no annotations, the applied-key must be- // forgotten or the label effect would skip re-adding an identical set.+ // Apply annotations via relayout, not scene reconstruction. Clear their applied key when rebuilding layout so+ // identical labels are restored.appliedAnnotationsKeyRef.current = null;const layout = buildMapLayout(initialRanges);void Plotly.react(container, traces as Plotly.Data[], layout, {displayModeBar: false,- // Custom wheel/pinch zoom below; plotly's own scrollZoom has- // long-standing Safari issues.+ // Use custom wheel/pinch zoom to avoid Plotly scrollZoom issues on Safari.scrollZoom: false,}).then((plot: PlotlyHTMLElement) => {@@ -322,11 +285,8 @@ const ImageMapPlot = ({const clusterKeys = clusterModeRef.current ? collectClusterSelection(points, clicked.key) : null;if (clusterKeys) {- // The backend's cluster label names the filter chip when one has- // arrived; the member count is the fallback (labels can be off,- // still loading, or missing for this cluster). Only the primary- // phrase is used — the alternates belong to the hover card, which- // has room to show them.+ // Use the primary cluster phrase for filter chips, falling back to member count; alternates belong in+ // hover cards.const label = clusterLabelsRef.current?.[String(clicked.cluster)]?.label ?? `${clusterKeys.length} items`;selectCluster(clicked.item, clusterKeys, label);@@ -387,12 +347,7 @@ const ImageMapPlot = ({return;}- // WebGL context creation can fail (blocked GPU, context exhaustion).- // Reported as renderError, not the generic error: the data is fine, it- // is the canvas that is not, so the view has to stop trying to render- // the plot. Signalling this through `error`/`loadState` alone did- // nothing, because the view prefers a non-empty point set over any- // error and would just mount this same failing plot again.+ // Report WebGL initialization as renderError so valid points cannot repeatedly remount the failing plot.imageMapStore.patchSnapshot({ renderError: 'The map failed to render (WebGL unavailable).' });});@@ -419,16 +374,11 @@ const ImageMapPlot = ({swallow(Plotly.restyle(container, toHighlightRestyle(trace), [highlightIndex]));}, [plotRevision, points, selectedKeys]);- // The timer must not outlive the component; the scene effect used to do- // this, but it reruns on every `points` change.+ // Dispose the timer at component lifetime, not on every points update.useEffect(() => clearHover, []);- // Ending the session retires the hover for good. Hiding it alone is not- // enough: an image that leaves the map never fires `plotly_unhover`, so a- // later refresh restoring it would pop the thumbnail back up at coordinates- // captured long before, wherever the pointer has since moved.- // Live gold target on the currently selected gallery image, with a gentle- // recenter (zoom width preserved) when it drifts near or beyond an edge.+ // Retire hover sessions when items leave; hiding alone could resurrect stale pointer coordinates. Recenter the+ // live selected marker near view edges while preserving zoom.useEffect(() => {const container = containerRef.current as PlotElement | null;@@ -442,14 +392,8 @@ const ImageMapPlot = ({return;}- // Moving the marker changes which labels have room for it, but only this- // effect knows the marker moved for a SELECTION change. Anything driven by- // `points` is left to the label effect below, which re-declutters anyway —- // and does it with annotations rebuilt for the new embedding, where this- // effect would still be holding the previous one's. The provenance check- // covers the case where React batches a refresh and a selection change- // into one commit (a finished generation does exactly that): the selection- // did change, but these annotations are not for these points yet.+ // Redeclutter selection moves only with annotations matching current points; refresh effects rebuild+ // annotations separately, including batched selection/refresh commits.const selectionChanged =lastDeclutteredSelectionRef.current !== selectedKey && annotationsPointsRef.current === points;lastDeclutteredSelectionRef.current = selectedKey;@@ -459,13 +403,8 @@ const ImageMapPlot = ({const isSuppressionFresh = suppression !== null && Date.now() - suppression.at < MAP_CLICK_SUPPRESS_MS;const cameFromMapClick = isSuppressionFresh && suppression.name === selectedKey;- // Consume a matching entry; an interleaved external selection keeps a- // pending map click's suppression intact for when it lands. Expired- // entries go regardless — a click whose selection never arrived (the- // image was deleted, or the selection resolved to a non-image) would- // otherwise sit here and swallow the recenter for a later, unrelated- // gallery pick of the same name. Both run before the `!point` return,- // which is the path a never-arriving selection actually takes.+ // Consume matching suppression tickets and expire abandoned ones before missing-point returns; unrelated+ // selections must not consume a pending click's ticket.if (suppression !== null && (cameFromMapClick || !isSuppressionFresh)) {lastMapSelectionRef.current = null;}@@ -484,10 +423,8 @@ const ImageMapPlot = ({swallow(Plotly.restyle(container, { x: [[point.x]], y: [[point.y]] }, [markerIndex]));if (selectionChanged) {- // The marker outranks labels in the declutter pass, so moving it both- // hides a label it now covers and restores the one it just left. A- // recenter below re-runs this through plotly_relayout, but most- // selection changes do not move the view at all.+ // Redeclutter after marker moves to hide newly covered labels and restore uncovered ones, even without+ // recentering.applyDeclutteredAnnotations(container);}@@ -503,13 +440,8 @@ const ImageMapPlot = ({}}, [applyDeclutteredAnnotations, plotRevision, points, selectedKey]);- // Labels arrive about a second after the points they annotate. Applying them- // with `relayout` rather than through the scene effect keeps that from- // re-materializing every coordinate array — and, more visibly, from resetting- // the highlight and current-image traces to empty, which made the gold marker- // and the multi-select highlight blink off and back on with every refresh.- // The annotation builder wants the display strings only; the full label- // info (alternates included) feeds the hover card below.+ // Apply delayed labels via relayout so coordinate arrays and selection traces remain intact; hover cards receive+ // full alternate-tag data separately.const annotationLabels = useMemo(() =>clusterLabels === null@@ -591,30 +523,17 @@ const ImageMapPlot = ({detachZoom();observer.disconnect();Plotly.purge(container);- // Purging drops the layout the flag stands for. Leaving it set costs- // the whole-map fit on any remount of this same component instance —- // StrictMode's double-mount in development, for one.+ // Reset the fit flag on purge because its layout no longer exists, including StrictMode remounts.initialFitDoneRef.current = false;};}, []);- // A live refresh can drop the hovered image from the map, which makes the- // preview stale. Derived from whether the image is still on the map, not- // from `points` changing: that changes on every socket-driven refresh, and- // clearing on it would silently cancel live hovers — they would not come- // back either, since `Plotly.react` resets hover state and no new- // `plotly_hover` fires until the pointer moves.- // Requires a live point set, not just one that does not contradict the- // hover: `points` goes null when the account is invalidated, and the card- // must go with it rather than keep the previous account's thumbnail on- // screen — with a cluster identity that resolves to the noise sentinel.+ // Keep hover across refreshes only while its item remains in live points. Null points on account invalidation+ // must also remove the old thumbnail.const hoverPreview =pendingHoverPreview && points?.some((point) => point.key === pendingHoverPreview.key) ? pendingHoverPreview : null;- // Resolved from the live points, so the id, the size and the tint describe- // the clustering currently drawn even after a refresh has renumbered it- // under a stationary pointer. `hoverPreview` non-null already implies the- // item is in `points`, so there is no missing-point fallback to take.+ // Resolve cluster identity, size, and color from live points so stationary hover follows renumbered clusters.const hoverCluster = useMemo((): HoverCluster => {if (!hoverPreview || !points) {return { cluster: -1, clusterSize: 0 };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsxindex 08972677e0..d935ec745a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx@@ -10,32 +10,20 @@ import { ImageIndexProgressInline } from './ImageIndexProgress';const handleRefresh = () => {void refreshImageMapPoints();- // The counts too: this footer is the surface that shows them once the map- // exists, and counts left stale by a status event missed while offline are- // exactly what its refresh should be able to correct.+ // Refresh counts too, recovering final status events missed while offline.refreshImageIndexStatus();};-/**- * Widget-chrome footer: point count, a stale hint while a recompute is- * pending, embedding-index progress (admins only receive those events), and- * a manual refresh.- */export const ImageMapWidgetFooter = (_props: WidgetViewProps) => {const { data, indexCounts, indexUpdatedAt, loadState } = imageMapStore.useSnapshot();- // Only the states that actually show a map. `disabled`, `model_missing` and- // `empty` all carry data too, and each renders its own explanation — a- // "0 points" line with a Refresh button under "Image indexing is off" says- // nothing, and `computing` already offers its own "Check again".+ // Show footer controls only with a rendered map; other data states own their explanations and retry controls.if (loadState === 'idle' || !data || data.state !== 'ready') {return null;}const indexing = isIndexing(indexCounts);- // Once the queue drains, images given up on are the only reason the index- // can settle short of `total` — without saying so the count simply stops- // below the total with nothing to explain it.+ // Explain failed images when indexing drains below total.const skipped = indexCounts && indexCounts.pending === 0 && indexCounts.failed > 0;return (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsxindex f3f7253153..e001df6c96 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx@@ -11,13 +11,9 @@ vi.mock('@workbench/WorkbenchContext', () => ({useWidgetValuesSelector: () => false,}));-// The real one pulls the ~1.5MB plotly chunk; the badge under test is its-// sibling, not its child, so a stand-in is enough.+// Stub the heavy Plotly sibling; this test owns the progress badge.vi.mock('./ImageMapPlot', () => ({ default: () => <div data-testid="plot" /> }));-// The install link resolves the configured encoder against the starter-// catalog and queues it; both come from the models feature, so the catalog is-// pinned here and the queueing spied on.const models = vi.hoisted(() => {// A real subscribable store, like the one behind `useActiveInstallSources`:// putting the encoder into (and out of) an in-flight install has to re-render@@ -335,10 +331,7 @@ describe('Image Map indexing activity', () => {</ChakraProvider>));- // The plot is `lazy()`, so the first render in the file waits on the- // dynamic import and then on the re-render Suspense schedules once it- // resolves. Polled rather than flushed a fixed number of times: the badge- // has to be asserted against the resolved tree, not the fallback.+ // Poll for the resolved lazy plot tree rather than assuming a fixed number of Suspense flushes.for (let attempt = 0; attempt < 50 && !host?.querySelector('[data-testid="plot"]'); attempt += 1) {await act(async () => {await new Promise((resolve) => {@@ -349,10 +342,7 @@ describe('Image Map indexing activity', () => {};it('reports an index run over the map instead of drawing it silently', async () => {- // The has-points branch preempts the progress panel, which is right — a- // usable stale map beats a progress bar — but it used to do so with no- // sign that anything was happening, which is what a model-change re-index- // looks like from the panel: the old map, no labels, no explanation.+ // Keep a usable stale map during reindexing but show progress so missing labels are explained.await renderMapWithCounts({ embedded: 1204, failed: 0, pending: 16846, total: 18050 });expect(host?.querySelector('[data-testid="plot"]')).not.toBeNull();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsxindex 3f85e35d11..eb3a0b8edd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx@@ -25,21 +25,16 @@ import { lazy, Suspense, useCallback, useEffect, useMemo, useRef } from 'react';import { ImageIndexActivityBadge, ImageIndexProgressPanel } from './ImageIndexProgress';-// Lazy so the plotly bundle (its own vite chunk, ~1.5MB) loads only when the-// widget is actually shown.+// Load Plotly only when the map widget is shown.const ImageMapPlot = lazy(() => import('./ImageMapPlot'));const handleRefresh = () => {void refreshImageMapPoints();- // The counts too: when the retry is the progress panel's, stale counts are- // the likeliest reason the user pressed it.+ // Retry counts as well as points; stale progress is often why retry was requested.refreshImageIndexStatus();};-// The backend reports the configured model name with `model_missing`, but a-// response that predates that field, a server that could not read the config,-// or an `image_index_model: ""` would otherwise leave the sentence with a hole-// where the model belongs; the config default is the right guess for all three.+// Use the configured default model name when older/empty responses cannot name the missing encoder.const DEFAULT_IMAGE_INDEX_MODEL = 'DFN2B-CLIP-ViT-L-14-39B';const EMPTY_STARTERS: readonly StarterModel[] = [];@@ -48,20 +43,13 @@ const selectStarterModels = (snapshot: {response: { starter_models: StarterModel[] } | null;}): readonly StarterModel[] => snapshot.response?.starter_models ?? EMPTY_STARTERS;-// Module scope: an inline element would be a new value on every render, which-// is both what react-perf/jsx-no-jsx-as-prop forbids and pointless here — the-// fallback never varies.const plotLoadingFallback = (<Center h="full"><Spinner size="lg" /></Center>);-/**- * Semantic map of the gallery: every image embedded by the backend's image- * index, projected to 2D with UMAP and colored by cluster. Clicking a point- * selects that image in the gallery (and so in Preview).- */+/** Show backend embeddings projected by UMAP and colored by cluster; point selection drives Gallery and Preview. */export const ImageMapWidgetView = (_props: WidgetViewProps) => {const { data, error, indexCounts, indexUpdatedAt, loadState, renderError } = imageMapStore.useSnapshot();const clickSelectsCluster = useWidgetValuesSelector('image-map', getImageMapClickSelectsCluster);@@ -77,9 +65,7 @@ export const ImageMapWidgetView = (_props: WidgetViewProps) => {setClusterLabelsEnabled(showClusterLabels);}, [showClusterLabels]);- // Checked before the plot: this is the canvas failing, not a fetch, so- // re-mounting the plot would just fail again and render an empty box with no- // way out. A successful refresh clears it and lets the plot retry.+ // Handle render failure before points so the same broken canvas cannot remount until refresh clears it.if (renderError) {return (<CenteredMessage@@ -94,19 +80,10 @@ export const ImageMapWidgetView = (_props: WidgetViewProps) => {// A working map beats a full-screen error: when a refresh fails but prior// points exist, keep showing them (the next successful refresh recovers).if (data && data.points.length > 0) {- // Its own boundary, rather than leaning on WidgetRenderer's. That one wraps- // the whole widget, so suspending on the plotly chunk replaced the entire- // panel — header and actions menu included — with a skeleton frame, and- // then held the resolved content for React's fallback throttle on top. It- // also sits above `loadWidgets`, which preloads only the implementation- // chunk and cannot reach this nested import, so a preset switch onto an- // already-loaded map suspended anyway. Confining it here keeps the frame- // mounted and the spinner where the plot will appear.+ // Keep a nested Suspense boundary around Plotly so its separate lazy load preserves widget chrome and places+ // loading feedback in the plot area.return (- // Positioned so the indexing badge can overlay the plot. That badge is- // the only sign of an index run once there are points to draw: this- // branch preempts the progress panel below, which is right — a usable- // stale map beats a progress bar — but silently, which was not.+ // Overlay indexing status on usable stale points because this branch bypasses the progress panel.<Box h="full" position="relative" w="full"><Suspense fallback={plotLoadingFallback}><ImageMapPlot clickSelectsCluster={clickSelectsCluster} showClusterLabels={showClusterLabels} />@@ -126,10 +103,8 @@ export const ImageMapWidgetView = (_props: WidgetViewProps) => {if (data?.state === 'model_missing') {return (<CenteredMessage- // A standing action, not just an error retry: the server picks a newly- // installed encoder up on a request, and nothing else polls while the- // indexer is inert, so this button is the user's only way to ask again- // without closing the widget.+ // Keep a standing refresh action to discover newly installed encoders while the indexer is otherwise+ // inert.actionLabel={retainedDataError ? 'Retry' : 'Check again'}detail={<>@@ -176,16 +151,8 @@ export const ImageMapWidgetView = (_props: WidgetViewProps) => {);}- // Ahead of both `computing` and the empty state: with nothing to draw yet,- // how far the backfill has got is the one thing that answers "when will- // there be a map?" — a spinner or "nothing to map yet" leaves a user with a- // large gallery unable to tell progress from a stall. `computing` is routine- // here (the backend asks for a projection as soon as anything is embedded),- // so deferring to it would hide the progress for most of a backfill.- //- // A failed refresh is carried into the panel rather than shadowed by it:- // preempting the `error` branch below would otherwise drop both the message- // and the only retry the widget has before the map is ready.+ // Prioritize backfill progress over computing/empty states before points exist. Preserve refresh errors and+ // retry within that panel.if (isIndexing(indexCounts)) {return (<Center h="full" p="6">@@ -268,12 +235,8 @@ const CenteredMessage = ({);/**- * The configured encoder's name, as a one-click install when the starter- * catalog carries it. Naming a model the user then has to go find by hand is- * what made this message unactionable: the starter entry knows the source, so- * the message can queue the download (and its dependencies) itself. Falls back- * to plain text when the catalog has not loaded, does not know the name (a- * hand-configured `image_index_model`), or the download is already running.+ * Offer one-click encoder installation when the starter catalog resolves it; otherwise show text while unknown,+ * loading, or already downloading.*/const ImageIndexModelInstallLink = ({ modelName }: { modelName: string }) => {const starterModels = useStartersSelector(selectStarterModels);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.browser.test.tsxindex c64b5a7327..92883ffdcf 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.browser.test.tsx@@ -52,9 +52,7 @@ afterEach(async () => {describe('MapHoverCard', () => {it('marks a video with the gallery’s play badge and its duration', async () => {- // A video's thumbnail is a still frame, so without this the card is- // indistinguishable from an image's — and the badge matches the gallery- // tile the click will land on.+ // Identify videos because their still thumbnails otherwise look like images.const text = await render({clientX: 10,clientY: 10,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.tsxindex 6741eb6a60..053a7d6bfd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.tsx@@ -24,11 +24,8 @@ export interface HoverPreview {}/**- * Cluster identity for the hovered image, resolved from the CURRENT points.- * Deliberately not captured at hover time: a hover survives a live refresh- * (see `hoverPreview` below), and a refresh re-runs DBSCAN, which can renumber- * every cluster. A frozen id would then be paired with the new clustering's- * labels and color — a card describing a cluster the image is not in.+ * Resolve hovered cluster identity from current points; live reclustering may renumber ids under a stationary+ * pointer.*/export interface HoverCluster {/** DBSCAN cluster of the hovered point; -1 means unclustered noise. */@@ -51,16 +48,8 @@ const HoverTagsRow = ({ prefix, tags }: { prefix: string; tags: string[] }) => ();/**- * The hover card: thumbnail, filename, cluster identity/size, and the top- * cluster and item tags — PhotoMapAI's popup on the app's dropdown chrome,- * with the cluster's palette color confined to a swatch dot. Its size depends- * on async content (the thumbnail and the lazily fetched item tags), so it- * renders invisibly, is measured, and is then placed beside the cursor —- * flipped to the other side when it would leave the viewport. Parents key- * this by item key so a new hover starts clean.- *- * A video's thumbnail is a still frame, so the card says which it is: without- * the badge a clip is indistinguishable from an image until it is opened.+ * Measure asynchronous hover-card content invisibly before cursor-relative placement and viewport flipping. Key by+ * item for clean state and label video thumbnails explicitly.*/export const MapHoverCard = ({preview,@@ -76,10 +65,8 @@ export const MapHoverCard = ({const [imageLoaded, setImageLoaded] = useState(false);const [position, setPosition] = useState<{ left: number; top: number } | null>(null);- // Item tags are computed on demand (network round-trip on first hover of- // an item; session-cached after). The card renders without the row until- // they arrive. Keyed by the item's key rather than by an item object, which- // a refresh re-creates identical and would refetch.+ // Fetch tags lazily by stable item key and use session caching; DTO refresh identity must not retrigger+ // requests.const item = parseGalleryItemKey(preview.key);useEffect(() => {@@ -166,8 +153,6 @@ export const MapHoverCard = ({</HStack><HStack alignItems="flex-start" gap="1.5">{videoDuration !== null ? (- // The gallery's own video mark, so a clip reads the same on the map- // as it does in the grid this click will land on.<Badge display="flex" flexShrink={0} fontVariantNumeric="tabular-nums" gap="1" size="xs" variant="solid"><PlayIcon aria-hidden="true" fill="currentColor" />{videoDuration}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsxindex 0467e86176..52ad523a36 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx@@ -208,9 +208,7 @@ describe('useMapSelection', () => {});it('reveals a clicked video through its own namespace', async () => {- // Resolved as a video, revealed under a video key: hydrating a clip- // through the images endpoint 404s, and an `image:` reveal key never- // matches the grid cell holding it.+ // Resolve videos through their own endpoint and item keys so gallery reveal matches.mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'video', name: 'clip.mp4' });mocks.fetchNames.mockResolvedValue({items: [@@ -257,11 +255,7 @@ describe('useMapSelection', () => {});it("selects the image's board before the image itself", async () => {- // The map spans every accessible board, but selectGalleryItem stamps the- // navigation query from whatever list the gallery is currently showing. A- // cross-board click without this left that query describing a list the- // image was never in, and Preview's next/prev found no cursor and went- // dead until the user re-selected from the grid.+ // Select the destination board before stamping navigation state so cross-board Preview paging has a cursor.mocks.resolve.mockResolvedValue({boardId: 'board-portraits',category: 'general',@@ -339,9 +333,7 @@ describe('useMapSelection', () => {});it('anchors the infinite window at the page of an image past the base reach', async () => {- // The base infinite window cannot load beyond GALLERY_MAX_ROWS, so a- // deeper image is revealed by anchoring the window at its page instead- // of loading toward it; the mounted gallery query fetches on its own.+ // Anchor deep reveals at their page when loading from the base would exceed GALLERY_MAX_ROWS.mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite' };mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'deep.png' });mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 700));@@ -376,9 +368,7 @@ describe('useMapSelection', () => {});it('drops the page landing when the board is not listable in the gallery', async () => {- // The gallery falls back to Uncategorized for a board its boards query- // does not list (archived with "show archived" off); landing on the- // hidden board's page number there would jump to an unrelated page.+ // Do not apply hidden-board page positions to the Uncategorized fallback.mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated' };mocks.fetchBoards.mockResolvedValue([{ id: 'board-other' }]);mocks.resolve.mockResolvedValue({@@ -567,9 +557,6 @@ describe('useMapSelection', () => {});it("selects the primary image's board before the cluster filter", async () => {- // The selection stamps the navigation query from the list the gallery- // is currently showing, so the primary image's board must be current- // before the selection lands.mocks.resolve.mockResolvedValue({boardId: 'board-landscapes',category: 'general',@@ -667,10 +654,7 @@ describe('useMapSelection', () => {});it('ignores a click left in flight across an unmount/remount', async () => {- // The regression this guards: a per-mount counter is reset by the remount,- // so the abandoned click compares against a dead counter, passes, and- // overwrites the newer mount's selection. Reachable by switching the right- // panel away from the map and back while a hydrate is in flight.+ // Fence selections across remounts; abandoned hydrations must not overwrite newer mount intents.const stale = deferred<{ boardId: string; category: string; kind: string; name: string }>();const fresh = deferred<{ boardId: string; category: string; kind: string; name: string }>();@@ -692,10 +676,7 @@ describe('useMapSelection', () => {});it('drops a reveal whose hydrate landed after the user switched projects', async () => {- // The reveal writes a board, a page, a filter reset and a selection. The- // sequence guard does not cover this: nothing newer was clicked, so a- // reveal in flight across a project switch would land every one of those- // writes in the project the user just arrived at.+ // Fence all reveal writes to the original project even without a newer click.const inFlight = deferred<{ boardId: string; category: string; kind: string; name: string }>();mocks.resolve.mockReturnValueOnce(inFlight.promise);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.tsindex 164170e3cd..8fb11f5dba 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts@@ -20,16 +20,8 @@ export interface MapSelectionActions {}/**- * Turns map clicks into gallery navigation. A single click is a full reveal,- * which `revealGalleryItem` owns; the map raises no widget of its own, since it- * sits beside the grid it is scrolling. The sequence guard those reveals claim- * spans BOTH selection kinds, so rapid clicks always resolve to the latest- * click regardless of which mode each went through.- *- * A cluster click instead behaves like a search: the cluster's members (in- * proximity order from the clicked point) become the gallery's list via a- * `cluster` semantic reference, with the clicked item — the list's first- * entry — as the selection.+ * Single clicks use shared gallery reveal without raising widgets. Cluster clicks populate a proximity-ordered+ * semantic list. Both share gesture ordering so the latest click wins.*/export const useMapSelection = (): MapSelectionActions => {const commands = useWorkbenchCommands();@@ -63,10 +55,8 @@ export const useMapSelection = (): MapSelectionActions => {// navigation query from the board the gallery is showing, so land// on the primary item's board first to keep that query coherent.commands.gallery.selectBoard(image.boardId);- // The member list lives in an in-memory registry (it can run to- // thousands of items); the persisted value keeps only the key. The- // page reset and search-term clear mirror setSemanticImageQuery in- // the gallery's own actions.+ // Keep large member lists in memory and persist only their key; reset page/search like gallery semantic+ // queries.const clusterId = registerImageCluster(itemKeys, label);commands.widgets.patchValues('gallery', {@@ -75,10 +65,8 @@ export const useMapSelection = (): MapSelectionActions => {semanticImageQuery: { clusterId, kind: 'cluster', label },semanticSearchText: null,});- // The clicked item is the proximity ordering's first entry, so it- // is selected at the top of the cluster view; Preview follows. The- // reveal brings the grid back to it even when this exact selection- // is already current (re-clicking the cluster after scrolling away).+ // Select and reveal the proximity list's first item even if already selected, restoring scroll after a+ // repeated click.commands.gallery.selectItem(image);requestGalleryItemReveal(toGalleryItemKey(primaryItem));})diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.tsxindex 749bf1e1ee..66ae92ee6c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.tsx@@ -26,11 +26,8 @@ import {import { applyStructuralPreview } from './layerOps';/**- * The dedicated Properties editors of a raster layer's adjustment entries —- * the views their tree sub-selections open. Every edit replaces the layer's- * whole `adjustments` stack through one `patch-config`; a gesture previews- * live and lands exactly one history entry. Enable/remove/reorder live on the- * tree row, never here.+ * Edit adjustment subrows through whole-stack patch-config. Preview gestures live and commit once; tree rows own+ * enable/remove/reorder.*/export type AdjustmentsEngine = CanvasStructuralEngine & CanvasPreparedEngine;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsxindex 81fcc0d9f8..f9e8e16a95 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx@@ -111,8 +111,7 @@ describe('ControlLayerSettings and the capability table', () => {});it('keeps the retry and its focus through a retry that fails again, then offers the adapter kinds', async () => {- // The kind list used to be memoised on the base alone, so it stayed empty after the table- // arrived until the model changed or the panel remounted.+ // Capability arrival must update kinds even when the model base is unchanged.getArchitectureCapabilities.mockRejectedValueOnce(new Error('Fixture capability outage.'));await settle(ensureArchitectureCapabilitiesLoaded);await render();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsxindex 2a73f59351..84559645f1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx@@ -71,14 +71,7 @@ interface ControlLayerSettingsProps {onOperationStarted(): void;}-/**- * Per-layer settings for a selected control layer (plan §1.3): adapter kind +- * model, weight, begin/end step range, control mode (ControlNet only), the- * transparency effect toggle, and a non-destructive filter section (type +- * per-type settings + preview/apply/cancel). Adapter edits go through the canvas- * undo stack (`updateCanvasLayerConfig`); the filter preview runs on the utility- * queue and never mutates the document until "Apply".- */+/** Edit adapters through canvas undo; utility-queue filter previews leave the document untouched until Apply. *//** Contributing control leaves of one adapter kind with content, in generation order. */const contributingControlLayers = (engine: CanvasStructuralEngine & LayerFilterOperationEngine & { readonly document: CanvasDocumentCapability },@@ -132,9 +125,7 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Cont// The request belongs to this retry; a later reload started elsewhere is not this panel's retry.void ensureArchitectureCapabilitiesLoaded().then(() => setHasRequestedCapabilitiesRetry(false));}, [capabilitiesStatus, hasRequestedCapabilitiesRetry]);- // A load that lands unmounts the failure surface, and with it the retry button a keyboard user may- // be on. The ref's cleanup runs while the surface is still in the document, so focus is handed to- // the panel the load filled in before it can fall to <body>.+ // Transfer retry-button focus to the loaded panel during ref cleanup before removal can send it to body.const handOverFocusOnLoad = useCallback((surface: HTMLDivElement | null) => {if (!surface) {return undefined;@@ -145,10 +136,8 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Cont}};}, []);- // Adapter kinds supported by the selected base. Z-Image Control is only shown- // when a compatible Z-Image main model is selected. Read inside the store's- // selector: the answer comes from the capability table, and a call memoised on- // `base` alone keeps the empty list it gave before a retried load succeeded.+ // Read supported adapter kinds inside the capability selector so successful retries replace the pre-load empty+ // list.const kindOptions = useExternalStoreSelector(subscribeArchitectureCapabilities,getArchitectureCapabilitiesSnapshot,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.browser.test.tsxindex 05fbf8fce2..77e6224b3a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.browser.test.tsx@@ -97,8 +97,7 @@ afterEach(async () => {describe('ControlLayerWarningIcon and the capability table', () => {it('flags nothing about a valid adapter while the table is still loading', async () => {- // Without the table every adapter kind reads as unsupported, which used to be shown as exactly- // that -- a warning on a healthy SD-1 ControlNet layer.+ // Missing capabilities must not label a valid adapter unsupported.await render();expect(warning()).toBeNull();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsxindex d0ba5d5695..2cca22ae4e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsx@@ -15,11 +15,6 @@ import { useSelectedMainModel } from './useSelectedMainModel';const selectCapabilitiesStatus = (snapshot: ArchitectureCapabilitiesSnapshot) => snapshot.status;-/**- * Quiet per-row indicator for a control layer that would be rejected at- * generation time (no model, incompatible adapter, …). Renders nothing for- * other layer types and healthy control layers.- *//** `contributing` is the effective enablement; a layer gated by a group is not validated. */export const ControlLayerWarningIcon = ({layer,@@ -50,8 +45,7 @@ export const ControlLayerWarningIcon = ({));- // Without the table nothing can be said about the adapter. While it loads there is nothing to flag;- // once the load has failed, say that and where to retry, instead of calling a valid adapter unsupported.+ // Distinguish loading/failed capabilities from unsupported adapters; failures should point to retry.if (!reason || (reason === 'capabilities_unavailable' && capabilitiesStatus !== 'error')) {return null;}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsxindex 590587bc42..b43e0ecf9e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx@@ -29,11 +29,8 @@ interface InpaintMaskSettingsProps {}/**- * Per-layer settings for a selected inpaint mask: fill colour + style and an- * in-place mask invert. Noise and denoise limit are NOT here — they live as- * child rows in the Layers tree, each opening its own dedicated Properties- * editor (`MaskModifierSettings`). Fill edits go through the canvas undo stack- * as prepared `patch-config` edits; invert is an engine pixel op.+ * Properties owns fill/style and invert; noise/denoise modifiers have tree-child editors. Fill uses undoable+ * config patches, invert uses engine pixels.*/export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps) => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.tsxindex 0f01dac02b..a1e49d6c3d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.tsx@@ -25,11 +25,7 @@ const DOT_UNCHECKED_HOVER = { _before: { borderColor: 'fg.muted' } };const stopPropagation = (event: { stopPropagation: () => void }): void => event.stopPropagation();-/**- * The rows' leading active-toggle dot: solid when contributing, outlined in- * accent when enabled but gated by an ancestor, plain when off. The wrapper- * keeps clicks and focus off the tree item.- */+/** Show contributing, ancestor-gated, and off states distinctly; keep toggle clicks/focus off the tree item. */export const LayerActiveDot = ({checked,disabled,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsxindex 479a2f3e2b..500dde75b4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsx@@ -40,11 +40,6 @@ export const selectBlendTarget = (project: {export const isLayerEditingDisabled = (layer: CanvasNodeContract | null, editingLocked: boolean): boolean =>!layer || editingLocked;-/**- * The fixed blend-mode + opacity row above the layer tree, Photoshop-style. It- * edits the selected layer or raster-stack group and simply disables without- * one — the row never appears or disappears.- */export const LayerBlendRow = ({ engine }: { engine: LayerBlendRowEngine | null }) => {const layer = useActiveProjectSelector(selectBlendTarget);const editingLocked = useCanvasDocumentEditingLocked(engine);@@ -126,17 +121,13 @@ const OpacityRow = ({}) => {const commitPrepared = usePreparedCommit(engine);const { t } = useTranslation();- // The uncommitted opacity edit: captured once per gesture. `before` is the- // pre-gesture value (the undo target); `latest` tracks the live value because- // React may not have re-rendered between the live dispatch and the commit- // trigger (both can fire inside one browser event), so `layer.opacity` from the- // render closure can be stale at commit time.+ // Capture original opacity once and track latest writes outside render closures so same-event commits record+ // current values.const pendingRef = useRef<{ id: string; before: number; latest: number } | null>(null);const disabled = isLayerEditingDisabled(layer, editingLocked);const opacityPercent = useMemo(() => String(Math.round((layer?.opacity ?? 1) * 100)), [layer?.opacity]);- // Records ONE history entry spanning the pending gesture (a spinner press,- // an arrow-key press, or a typed value committed via Enter/blur).+ // Record one history entry per completed opacity gesture.const commitPending = useCallback(() => {const pending = pendingRef.current;pendingRef.current = null;@@ -182,9 +173,7 @@ const OpacityRow = ({[commitPending, engine, layer]);- // Commit per completed interaction: each spinner click (fires on release, so a- // press-and-hold repeat is one gesture), each arrow/paging key release, Enter,- // and blur (typed values).+ // Commit on spinner release, arrow/page-key release, Enter, or typed-value blur.const handleInputKeyUp = useCallback((event: { key: string }) => {if (['ArrowDown', 'ArrowUp', 'End', 'Enter', 'Home', 'PageDown', 'PageUp'].includes(event.key)) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsxindex 4a21155c40..980f7c5c41 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx@@ -75,10 +75,8 @@ interface LayerChildRowProps {}/**- * One projected child row: a modifier the layer above owns, on the tree's- * roving tab stop. The dot toggles it, selecting it routes the Properties- * pane to its editor, and Delete removes it; hide/lock do not apply. The row- * registers a drop target so a layer drag over it lands below its owner.+ * Modifier child rows share tree focus and route Properties; toggle/Delete edit them, while drops land below their+ * owning layer.*/const LayerChildRowComponent = ({ariaSetSize,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex e36cc2a775..6e58105bc7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -201,15 +201,8 @@ interface LayerMenuProps {}/**- * 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.- *- * 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` rather than inside its portal, so they- * survive the menu closing after their action is chosen.+ * Share per-layer actions across panel and canvas menus. Arrange within type groups; merge uses global adjacency.+ * Keep dialogs outside the closing menu portal.*/const LayerMenu = ({dispatch,@@ -252,8 +245,6 @@ const LayerMenu = ({? engine.exports.hasExportableLayerContent(layer.id): hasPureExportableLayerContent(layer, document);const [internalDialogKind, setInternalDialogKind] = useState<LayerMenuDialogKind | null>(null);- // Controlled (canvas) vs. uncontrolled (panel): the canvas parent owns the- // dialog kind so its sibling survives menu close; panel rows keep it locally.const dialogKind = controlledDialogKind !== undefined ? controlledDialogKind : internalDialogKind;const setDialogKind = useCallback((next: LayerMenuDialogKind | null) => {@@ -368,8 +359,7 @@ const LayerMenu = ({return;}} catch {- // A rejected engine transaction leaves the document unchanged; report- // the failure through the menu instead of leaking an event exception.+ // Report rejected transactions in the menu; the document remains unchanged.}notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.copyFailed'));return;@@ -411,8 +401,7 @@ const LayerMenu = ({}, [engine, layer.id]);const handleRasterize = useCallback(() => {- // Bakes the parametric source to pixels; the engine records ONE undoable- // entry (inverse re-converts to the parametric source).+ // Rasterization records one undoable entry restoring the original parametric source.engine?.layers.rasterizeLayer(layer.id);}, [engine, layer.id]);@@ -990,17 +979,8 @@ export interface CanvasLayerContextMenuTarget {}/**- * The canvas-surface right-click menu: the SAME {@link LayerMenu}, anchored at the- * cursor via a 1×1 virtual rect (no trigger DOM), controlled by `target`. The- * canvas widget sets `target` to the hit layer + pointer position after selecting- * it; `null` closes the menu. The layer is resolved from `target.layerId`- * against the live document, so the shared items get the exact same inputs the- * panel passes. Keyed by layer id so switching target resets the- * menu's sibling-dialog state.- *- * Choosing a sibling-dialog action closes the menu, which nulls `target`. The- * wrapper therefore owns the dialog-in-flight state and keeps rendering against- * the last-known (sticky) target until the dialog closes (F1).+ * Anchor {@link LayerMenu} at the cursor for the supplied layer id, resolved against the live document. Keep a+ * sticky dialog target after menu closure so sibling dialogs survive; changing layer resets their state.*/export const CanvasLayerContextMenu = ({beforeDangerItems,@@ -1064,8 +1044,7 @@ export const CanvasLayerContextMenu = ({engine={engine}layer={layer}lazyMount- // The menu itself is visible only while the live target is set; once a- // sibling dialog closes it (target → null), the subtree stays mounted.+ // Hide the menu when target clears while preserving the sibling-dialog subtree.open={!!target}positioning={positioning}showGroupLabels={showGroupLabels}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsxindex af3e4faa8e..f65c372bf2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx@@ -224,9 +224,7 @@ const LayerRowComponent = ({},[commands, finishRename, node.name, row.id]);- // Focus that dropped returns to the row. Focus that left for another element stays there, and is- // set explicitly: committing unmounts the input while the browser is still moving focus, and that- // move is dropped along with the input.+ // Restore dropped focus to the row, but explicitly preserve a destination chosen during input unmount.const handleNameBlur = useCallback((event: FocusEvent<HTMLInputElement>) => {const next = event.relatedTarget;@@ -311,8 +309,7 @@ const LayerRowComponent = ({onKeyDown={handleKeyDown}>{node.colorLabel ? (- // A fixed gutter column regardless of nesting depth, like a desktop- // editor's label swatch; display-only, so it takes no pointer events.+ // Use a fixed, noninteractive swatch gutter at every nesting depth.<Boxbg={colorLabelHex(node.colorLabel)}bottom="1.5"@@ -513,11 +510,6 @@ const groupLeafPreviews = (node: CanvasNodeContract, limit = 3): CanvasLayerContreturn leaves;};-/**- * A group's preview: its first leaves' live thumbnails stacked as a small pile,- * top layer in front, so a closed folder still shows what it holds; an empty- * group keeps the folder glyph.- */const GroupPreview = ({engine,expanded,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRowSurface.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRowSurface.tsxindex a54c09a79a..ae50ee40f5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRowSurface.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRowSurface.tsx@@ -5,11 +5,6 @@ import { Row } from '@platform/ui';const LAYER_ROW_BACKGROUND_TRANSITION = 'background min(40ms, var(--wb-motion-duration-fast)) ease-out';-/**- * The shared visual shell of every Layers-tree row — layer, group, and- * projected child alike: one rhythm, one background transition, and the- * arrow cursor of a tree item rather than the recipe's pointer.- */export const LayerRowSurface = ({active,children,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsxindex ddcdd7c1cd..8ee63b6900 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx@@ -43,9 +43,8 @@ interface LayerStackHeaderProps {const stopPropagation = (event: { stopPropagation: () => void }): void => event.stopPropagation();/**- * One stack's header: a level-one tree item that expands or collapses the stack, with the stack's- * actions as pointer-only buttons inside it. The same actions reach the keyboard through the- * stack menu (Shift+F10) so nothing here is a tab stop of its own.+ * Stack headers own the roving tree stop; pointer-only action buttons remain keyboard-accessible through Shift+F10+ * menus.*/const LayerStackHeaderComponent = ({collapsed,@@ -96,10 +95,8 @@ const LayerStackHeaderComponent = ({const hintId = STACK_HINTS[stack];const descriptionId = `layer-stack-hint-${stack}`;return (- // The informational popover triggers on the whole tree item, so it opens- // for the roving keyboard focus as well as hover; the persistent- // described-by span announces the gist without the card. The action- // buttons carry their own tooltips, so hovering them is excluded.+ // Attach hints to tree-item focus/hover with persistent described-by text; exclude action buttons with their+ // own tooltips.<FeatureHint hint={hintId}><Boxref={element}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerThumbnail.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerThumbnail.tsxindex 9776a191ec..9af799b120 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerThumbnail.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerThumbnail.tsx@@ -29,12 +29,7 @@ export type LayerThumbnailEngine = CanvasCoreStoreCapability & {readonly projectId: string;};-/**- * A layer's thumbnail: the engine's live cache pixels drawn onto a `<canvas>`,- * redrawn whenever the layer's `thumbnailVersion` bumps. Falls back to the- * persisted image thumbnail (for image-source layers) or a placeholder icon- * when there is no engine / no cache yet.- */+/** Redraw live engine thumbnails by version; use persisted thumbnails or icons before cache availability. */const LayerThumbnailContent = ({engine,layer,@@ -66,8 +61,7 @@ const LayerThumbnailContent = ({setFallbackStage('thumbnail');}},- // `version` is a deliberate identity trigger: a repaint bumps it, giving the- // callback a new identity so React re-runs it and re-blits the cache.+ // Version changes intentionally replace the ref callback to re-blit repainted pixels.[engine, layer.id, status, version]);@@ -128,10 +122,7 @@ const LayerThumbnailContent = ({);};-/**- * The keyed boundary resets local draw/fallback state when a row is reused for a- * different project, layer, or persisted image. No effect-based reset is needed.- */+/** Key the boundary by project/layer/image to reset draw and fallback state on row reuse. */export const LayerThumbnail = ({engine,layer,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersHeaderActions.tsxindex b480781a5c..48b6a5338a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersHeaderActions.tsx@@ -36,13 +36,7 @@ const ADD_LAYER_ICONS: Record<AddLayerItemId, LucideIcon> = {regional_reference_image: ImagePlusIcon,};-/**- * The add-layer menu's content: legacy's two labelled groups — "Regional"- * (inpaint mask / regional guidance / regional guidance + reference image) and- * "Layers" (control / raster). Shared by the strip's "+" trigger and the empty- * area's context menu; the per-item creation is delegated to `useAddLayer` so- * every entry point agrees.- */+/** Share grouped add-layer choices between header and empty-area menus; useAddLayer owns creation. */const AddLayerMenuItems = () => {const { t } = useTranslation();const addLayer = useAddLayer();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelFooter.tsxindex 5b1c9d8651..9af48a71c6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelFooter.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelFooter.tsx@@ -18,12 +18,6 @@ interface LayersPanelFooterProps {onFilterChange: (filter: string) => void;}-/**- * The stable footer — the panel's one action strip: name filter and the- * top-frequency selection verbs (duplicate, group, delete). Everything else- * lives in the context menu; nothing here appears or disappears — controls- * disable instead.- */const LayersPanelFooterComponent = ({ commands, degraded, filter, onFilterChange }: LayersPanelFooterProps) => {const { t } = useTranslation();const handleFilter = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsxindex c2c9ff5270..3207a148f5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx@@ -613,12 +613,8 @@ describe('LayersTree selection, surfaces and structure', () => {});expect(scroller.scrollTop).toBeGreaterThan(0);await act(() => pointer('pointermove', document, start.x, rect.top + rect.height / 2));- // The move reaches the scroller through dnd-kit's rAF listener and the- // scroll loop itself is rAF-driven, so settle in frame time, not timer- // time: timers keep firing while rAF is starved under suite load, and a- // timer-based poll can declare "settled" before the queued frames flush.- // Ten consecutive frames with an unchanged scrollTop means both the move- // was delivered and the loop is parked.+ // Wait for ten unchanged animation frames, not timers, because both dnd movement delivery and autoscroll are+ // rAF-driven.const nextFrame = () =>new Promise<void>((resolve) => {requestAnimationFrame(() => resolve());diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsxindex 9df1597e21..a989ec554b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx@@ -107,10 +107,7 @@ interface LayersTreeProps {}/** Which half of the row under the pointer it sits in. */-/**- * Groups expose a middle band that drops INTO them — the only comfortable way- * into an empty group; leaves split at the midline as before.- */+/** Use a group's middle drop band to enter it, including empty groups; leaves split at their midpoint. */const edgeOf = (rect: { top: number; height: number } | undefined,y: number,@@ -161,9 +158,8 @@ const VirtualSlot = ({ children, size, start }: { children: ReactNode; size: num};/**- * The virtualized, keyboard-first layer tree: one scroll container, one drag context, one menu- * host, fixed row heights, and a single roving tab stop over stack headers and rows.- * Rows receive a view model and a command handle; every subscription and commit lives here.+ * Own subscriptions and commits in one virtualized tree with fixed rows, shared drag/menu hosts, and one roving+ * tab stop.*/export const LayersTree = ({degraded,@@ -372,8 +368,7 @@ export const LayersTree = ({[runStructural, t]);- // Deletes the focused row (or the selection it belongs to) and keeps keyboard- // focus in the tree: the nearest surviving row below, else above.+ // After deletion, focus the nearest surviving row below, otherwise above.const removeRows = useCallback((key: string) => {const { document: currentDocument, engine: currentEngine, panel: current, visibleRowIds: rows } = latest.current;@@ -692,8 +687,7 @@ export const LayersTree = ({}}, [primaryId, rowIndexByKey]);- // A properties request from elsewhere (a menu, a hotkey) reveals its row, scrolls to it once it is- // rendered, and then opens the surface on it exactly once; a request for a node that is gone is dropped.+ // Reveal external Properties requests, scroll after render, and open once; discard requests for removed nodes.useLayoutEffect(() => {if (!propertiesRequest) {pendingProperties.current = null;@@ -743,10 +737,7 @@ export const LayersTree = ({}}, [onRevealProperties, panelRows, virtualItems]);- // Focus repair: the browser drops focus to the body when a focused row unmounts, so the tree- // remembers whether it owned focus and puts it back on the item that now holds the tab stop.- // Portaled children (the stack hint card) route focus through this capture- // handler while their DOM lives outside the host; only real host focus counts.+ // Repair focus after row unmount only if the actual tree DOM owned it; portaled focus does not count.const handleFocusCapture = useCallback((event: FocusEvent<HTMLElement>) => {if (event.currentTarget.contains(event.target as Node)) {treeOwnsFocus.current = true;@@ -944,10 +935,8 @@ export const LayersTree = ({rows: stacks[drag.stack].rows,});}, [drag, stacks]);- // Dnd-kit can describe one insertion gap as both "below row N" and "above row N+1". Key the- // model check by the semantic command so virtualized auto-scroll does not repeat the same- // validation. Finishing the drag clears the target, and the prepared commit revalidates against- // the current document before applying the landing.+ // Cache drag validation by semantic move rather than equivalent visual gaps; clear on completion and revalidate+ // the prepared landing against the latest document.const refusalCommandKey = target ? JSON.stringify(reparentCommandForTarget(target)) : null;const refusal = useMemo(() =>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsxindex 824ae965b6..791b74a9b0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx@@ -36,13 +36,6 @@ import { LayerColorPane, LayerEditorPanes } from './panes/LayerEditorPanes';import { useCanvasHistoryHotkeys } from './useCanvasHistoryHotkeys';import { useLayerSelectionCommands } from './useLayerSelectionCommands';-/**- * The layers panel: the Color pane at the top, then the flexible middle region tabbed between- * the layers view (blend/opacity row, the virtualized tree of the four stacks, and the footer- * action strip) and the edit history, with the editor panes (Properties, Transform, Overview)- * at the bottom — the selected layer's other editors live in the Properties pane. Regions keep- * their geometry; their controls disable instead of appearing and disappearing.- */const TREE_TABS_ID_BASE = 'layer-tree';const TREE_TABS: ReadonlyArray<{ id: LayerTreeTabId; labelKey: string }> = [{ id: 'layers', labelKey: 'widgets.labels.layers' },diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/MaskModifierSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/MaskModifierSettings.tsxindex 339f8b627e..8793f60664 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/MaskModifierSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/MaskModifierSettings.tsx@@ -10,12 +10,7 @@ import { useTranslation } from 'react-i18next';import { applyStructuralPreview } from './layerOps';-/**- * The dedicated Properties editor of a mask's noise or denoise-limit child- * row — the view its tree sub-selection opens. Only the magnitude lives here;- * the row's dot enables it and the row's menu removes it. Dragging previews- * live and commits once on release.- */+/** Edit modifier magnitude here with one commit per gesture; tree rows own enabling and removal. */type MaskModifierKind = 'mask-noise' | 'mask-denoise';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.tsxindex eaaa016ec6..1b8dfb3f64 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.tsx@@ -32,11 +32,8 @@ import { useTranslation } from 'react-i18next';import { useSelectedModelBase } from './useSelectedModelBase';/**- * The dedicated Properties editor of one regional reference image — the view a- * Layers-tree sub-selection opens. The region's own settings never list these:- * the tree rows are the only inventory, their dot the only enable toggle, and- * their menu the removal path. Every edit commits the layer's whole- * `referenceImages` array through one `patch-config`.+ * Edit regional references through whole-array patch-config; tree rows remain the sole inventory, enable, and+ * removal controls.*/const IP_ADAPTER_METHODS: readonly RegionalGuidanceIPAdapterMethod[] = [@@ -64,10 +61,6 @@ interface ReferenceImageEditing {uploadReferenceImageAsset(refId: string, file: File): void;}-/**- * The commit surface for a region's reference images, plus the drag monitor- * that routes gallery-image drops onto the per-ref drop zones.- */const useReferenceImageEditing = (engine: CanvasPreparedEngine | null,layer: CanvasRegionalGuidanceLayerContractdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsxindex acd004de23..bd6389fd1d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx@@ -112,9 +112,8 @@ describe('RegionalGuidanceSettings per model base', () => {describe('RegionalGuidanceSettings before the capability table arrives', () => {it('does not accuse a supported model of lacking a regional path', async () => {- // `getRegionalGuidanceSupport` answers `null` for every base while the table is missing. The- // panel used to read that as "unsupported model" and say so in a role="alert" -- for SD-1,- // permanently if the load failed -- while rendering the very controls it called unavailable.+ // Missing capabilities must not announce supported regional models as unsupported while rendering their+ // controls.await render('sd-1', createLayer());expect(alerts()).toEqual([]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsxindex 532b0afaac..756a6073a6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx@@ -53,13 +53,8 @@ interface RegionalGuidanceSettingsProps {}/**- * Per-layer settings for a selected regional-guidance region: a positive +- * negative prompt, an Auto-Negative toggle, and the mask fill colour/style +- * invert. Reference images are NOT listed here — they live as child rows in- * the Layers tree, each opening its own dedicated Properties editor- * (`ReferenceImageSettings`); the same policy applies to every future- * layer modifier. Prompt/toggle/fill edits go through the canvas undo stack- * as prepared `patch-config` edits; invert is an engine pixel op.+ * Edit regional prompts/toggles/fill through undoable config patches and invert through engine pixels. Reference+ * images have dedicated tree-child editors.*/export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettingsProps) => {const { t } = useTranslation();@@ -74,15 +69,8 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettconst [negativePrompt, setNegativePrompt] = useState(layer.negativePrompt ?? '');const fill = layer.mask.fill;- // `getRegionalGuidanceSupport` answers from the capability table, which arrives over the network,- // and it is read here through the store's selector rather than called in the component body: the- // table is module state, so to React Compiler a bare call is a pure function of `base` and would- // be memoised for the panel's lifetime.- //- // Until the table arrives it answers `null` for *every* base, so "this model has no regional- // path" has to stay distinct from "nobody has said yet" -- otherwise a perfectly supported SD-1- // model is accused of being unsupported, permanently if the load failed, while the very controls- // the alert calls unavailable render right underneath it.+ // Resolve support inside the capability selector to update memoized answers. Distinguish unavailable policy from+ // unsupported models.const { hasCapabilities, support } = useExternalStoreSelector(subscribeArchitectureCapabilities,getArchitectureCapabilitiesSnapshot,@@ -94,11 +82,8 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett[base]));- // Negative controls are hidden on bases whose backend ignores regional negatives -- asked as "is- // this the FLUX family?" before, which got krea-2 wrong: it rendered a regional negative prompt- // and an Auto-Negative switch that `addRegionalGuidance` then discarded. The values stay on the- // layer for other models. With no selected model, and until the table arrives, every control is- // offered.+ // Hide negatives only when backend policy rejects them, retaining values for other models; offer controls while+ // no model/policy is known.const showNegativeControls = !hasCapabilities || support?.negativePrompt !== false;const unsupportedModel = hasCapabilities && base !== null && support === null;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.tsindex 0bfb4aa47a..a387c5c4cb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.ts@@ -1,7 +1,6 @@/**- * React-free data and base gating for the layers-panel add-layer surfaces, so- * the grouping is unit-testable. The header menu renders {@link ADD_LAYER_MENU}; each- * stack header's "New" button uses {@link stackAddItemId} to add its own type.+ * Share React-free add-layer grouping/gating; headers use {@link ADD_LAYER_MENU}, stack buttons use {@link+ * stackAddItemId}.*/import type { LayerStackKind } from '@workbench/canvas-engine/api';@@ -29,11 +28,6 @@ export interface AddLayerMenuGroup {items: AddLayerMenuItem[];}-/**- * The add-layer menu, split into legacy's two labelled groups: "Regional" (inpaint- * mask, regional guidance, regional guidance seeded with a reference image) and- * "Layers" (control, raster).- */export const ADD_LAYER_MENU: readonly AddLayerMenuGroup[] = [{items: [diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.tsindex 144c0033be..8054ed77a2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts@@ -13,11 +13,8 @@ import { layerChildRowKey } from '@workbench/layerPanelState';export { layerChildRowKey };/**- * The Layers panel's projected child rows: per-layer modifiers (reference- * images, mask noise and denoise limit) presented as rows beneath the layer- * that owns them. Rows are a pure projection of config the layer already- * carries — the document keeps its closed node union, and every edit- * round-trips through the same `patch-config` seam the Properties pane uses.+ * Project modifier rows from existing layer config without expanding the document node union; edits use the same+ * patch-config seam as Properties.*/export type LayerChildRowKind =@@ -444,11 +441,7 @@ export const layerChildDropCommand = (};};-/**- * The document command a child-row action resolves to, or `null` when the- * layer or item is gone or the action changes nothing. Both sides of the patch- * carry the modifier's whole value, exactly as the Properties editors commit.- */+/** Resolve child actions to whole-value patches, or null for missing/no-op targets. */export const layerChildRowCommand = (document: CanvasDocumentContractV3,target: Pick<ProjectedChildRow, 'layerId' | 'itemId'>,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.tsindex ce89e751b2..f975fdc41f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.ts@@ -1,12 +1,6 @@import type { CanvasLayerContextMenuTarget } from './LayerContextMenu';-/**- * Which layer the canvas right-click menu should render for.- *- * Opening a sibling dialog closes the menu, which nulls the live `target`. The- * wrapper keeps a captured dialog target until that dialog closes so the shared- * subtree remains mounted for rename and workflow actions.- */+/** Retain a captured layer target while sibling dialogs outlive the menu's cleared live target. */export type LayerMenuDialogKind = 'rename' | 'run-workflow';export interface LayerMenuDialogState {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.tsindex 9343aa35de..927a56ffc8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts@@ -1,8 +1,3 @@-/**- * Shared helpers for the layers panel: id minting, the paint-layer factory, the- * blend-mode list, merge-down eligibility, and guarded live previews.- */-import type {CanvasAdjustmentEntry,CanvasBlendMode,@@ -40,11 +35,8 @@ type RegionalGuidanceConfigPatch = {referenceImages?: CanvasRegionalGuidanceLayerContract['referenceImages'];};/**- * Re-exported so existing imports of `isMergeableRasterLayer` from this module- * keep working; the canonical definition lives in the engine's `document/sources`- * (the single source of truth the engine's own `mergeLayerDown` guard uses too —- * see the finding this fixed: the engine used to gate on the broader- * `isRenderableLayer`, which let a mask merge-down corrupt data).+ * Re-export the engine's canonical mergeability predicate so UI and engine exclude unsafe mask merges+ * consistently.*/export { isMergeableRasterLayer };@@ -84,11 +76,7 @@ export const createEmptyPaintLayer = (name: string, id: string = createLayerId()type: 'raster',});-/**- * Legacy-default inpaint mask fill: a diagonal hatch (legacy's- * `getInpaintMaskState` default `style: 'diagonal'`) in the first cycled mask- * fill colour (legacy `rgb(224,117,117)`). Multiple inpaint masks are allowed.- */+/** Use the legacy diagonal inpaint hatch and first fill color; multiple masks are allowed. */export const DEFAULT_INPAINT_MASK_FILL = { color: '#e07575', style: 'diagonal' } as const;/** The next free "Inpaint Mask N" name given the existing layer names (N ≥ 1, first gap). */@@ -142,11 +130,7 @@ export const createInpaintMaskLayer = (name: string, id: string = createLayerId(type: 'inpaint_mask',});-/**- * Legacy's regional-guidance mask fill palette (`DEFAULT_RG_MASK_FILL_COLORS`),- * as hex. New regions cycle through these so overlapping regions stay visually- * distinct.- */+/** Cycle legacy regional fill colors to distinguish overlaps. */export const REGIONAL_GUIDANCE_FILL_COLORS: readonly string[] = ['#799ddb','#83d683',@@ -158,13 +142,8 @@ export const REGIONAL_GUIDANCE_FILL_COLORS: readonly string[] = [];/**- * The next cycled regional-guidance fill colour, derived purely from the document- * (the count of existing regional-guidance layers) rather than session-global- * state. Legacy's cycler was seeded at index 0 and pre-incremented, so the first- * new region (0 existing) gets index 1 (`#83d683`, green); each subsequent region- * advances by one, wrapping modulo the palette length. Being a pure function of- * the document, colours no longer depend on session history or leak across- * projects.+ * Derive colors from document region count with legacy pre-increment ordering: the first region uses palette index+ * 1. Avoid session-global cross-project state.*/export const nextRegionalGuidanceFillColor = (existingRegionalGuidanceCount: number): string =>REGIONAL_GUIDANCE_FILL_COLORS[(existingRegionalGuidanceCount + 1) % REGIONAL_GUIDANCE_FILL_COLORS.length];@@ -188,13 +167,6 @@ export const nextRegionalGuidanceName = (existingNames: readonly string[]): strireturn `Regional Guidance ${n}`;};-/**- * Builds an empty regional-guidance layer with legacy defaults: a solid fill in- * the next cycled palette colour (derived from `existingRegionalGuidanceCount`,- * the number of regional-guidance layers already in the document), opacity 0.5,- * no prompts, autoNegative off, and no reference images (no mask bitmap yet — the- * user paints the region).- */export const createRegionalGuidanceLayer = (name: string,existingRegionalGuidanceCount: number,@@ -276,13 +248,8 @@ export const createIdentityAdjustment = (type: CanvasAdjustmentEntry['type']): C};/**- * A fresh regional reference image, minting the config kind the region's base can- * actually consume: FLUX regions use FLUX Redux (the only kind resolved for FLUX- * in `resolveRegionalReferenceImages`), everything else uses an IP-Adapter (legacy- * `initialRegionalGuidanceIPAdapter`). The model is chosen by the user; the image- * is assigned via drop/upload. Shared by the layer context menu's "Add reference- * image" action and the header add-layer menu's "Regional Reference Image" item,- * so both mint the same shape.+ * Create shared regional-reference defaults: FLUX uses Redux, other bases IP-Adapter. Users choose models and+ * assign images via drop/upload.*/export const createRegionalReferenceImage = (base: string | null,@@ -314,12 +281,6 @@ export const createRegionalReferenceImage = (export const canAddRegionalReferenceImage = (base: string | null): boolean =>base === null || Boolean(getRegionalGuidanceSupport(base)?.referenceImages);-/**- * Builds a regional-guidance layer pre-seeded with ONE empty reference image- * (legacy's "regional guidance with a reference image" add-layer path). Identical- * to `createRegionalGuidanceLayer` except the region starts with a single ref-image- * slot the user then assigns a model + image to via the region's settings popover.- */export const createRegionalGuidanceLayerWithRefImage = (name: string,existingRegionalGuidanceCount: number,@@ -330,12 +291,6 @@ export const createRegionalGuidanceLayerWithRefImage = (referenceImages: [createRegionalReferenceImage(base)],});-/**- * The legacy-default control adapter for a freshly created control layer- * (`features/controlLayers/store/util.ts` `initialControlNet`): a ControlNet with- * weight 0.75, an active range of the first 75% of steps, `balanced` control mode,- * and no model selected yet.- */export { CONTROL_ADAPTER_DEFAULTS };export const CONTROL_WEIGHT_BOUNDS = {@@ -367,12 +322,6 @@ export const nextControlLayerName = (existingNames: readonly string[]): string =return `Control Layer ${n}`;};-/**- * Builds an empty control layer with the legacy-default ControlNet adapter and- * transparency effect ON (legacy `withTransparencyEffect: true`). No source /- * filter yet — the user paints or drops an image, then optionally previews a- * filter.- */export const createControlLayer = (name: string,id: string = createLayerId(),@@ -425,12 +374,7 @@ export const getRegionalGuidanceAutoNegativePatch = (layer: CanvasRegionalGuidanceLayerContract): RegionalGuidanceConfigPatch => ({ autoNegative: !layer.autoNegative, layerType: 'regional_guidance' });-/**- * True when `layer` can be converted to a control layer (and vice-versa): only a- * raster layer with a rasterizable image/paint source, or a control layer,- * qualifies — parametric raster sources (shape/text/gradient) and mask layers do- * not (legacy only offers raster↔control conversion for pixel-backed layers).- */+/** Allow raster/control conversion only for pixel-backed image/paint sources, excluding parametric and mask layers. */export const canConvertRasterControl = (layer: CanvasLayerContract): boolean => {if (layer.type === 'control') {return true;@@ -609,10 +553,8 @@ export const copyRegionalGuidanceToInpaintMask = (});/**- * Converts a raster layer to a control layer (default adapter, transparency on)- * or a control layer back to a raster layer, preserving the pixel source, id,- * name, transform, and base props. Returns `null` when the layer cannot convert- * (parametric/mask sources) or already has the target type.+ * Convert raster/control types while preserving source, identity, transform, and base properties; reject+ * unsupported or unchanged targets.*/export const convertRasterControlLayer = (layer: CanvasLayerContract,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.tsindex b073aaf5b6..4ada130ea8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts@@ -59,9 +59,8 @@ export const isHeaderKey = (key: string): boolean => key.startsWith('header:');export const stackOfHeaderKey = (key: string): LayerStackKind => key.slice('header:'.length) as LayerStackKind;/**- * The one flat list the panel virtualizes: a header per non-empty stack followed by its rendered- * rows unless the stack is collapsed. `forceOpen` keeps a collapsed stack open while something- * inside it must stay reachable, like a pending properties request.+ * Flatten stack headers and visible rows for virtualization; forceOpen keeps pending targets reachable inside+ * collapsed stacks.*/export const flattenPanelRows = (stacks: LayerStackRowsByKind,@@ -142,9 +141,8 @@ const positionsOf = (rows: readonly PanelRow[]): Map<string, number> => {};/**- * The WAI-ARIA tree keyboard model over the flat list, headers included: vertical keys walk every- * rendered item, Home/End jump, Right opens a stack or group or enters it, Left closes one or- * climbs to the parent (a root node's parent is its stack header).+ * Apply tree keyboard navigation across headers/rows: vertical/Home/End traversal, Right open/enter, Left+ * close/parent.*/export const navigateTree = (rows: readonly PanelRow[],diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.tsindex 3c83734614..fe69304a5b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.ts@@ -13,8 +13,8 @@ export interface LayerSurfaceAnchor {}/**- * Everything a row can ask for. One stable object per tree, so a row re-renders only when its- * own view model or selection facts change; the tree owns every store subscription and commit.+ * Share one stable command handle per tree; rows rerender for their own model/selection while the tree owns+ * subscriptions and commits.*/export interface LayerRowCommands {select(id: string, modifiers: LayerSelectionModifiers): void;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowSummary.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowSummary.tsindex d4aeaf5fe6..1d042cd800 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowSummary.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowSummary.ts@@ -1,11 +1,6 @@import type { CanvasLayerContract } from '@workbench/canvas-engine/api';import type { TFunction } from 'i18next';-/**- * The row's secondary line: what this layer contributes, from data the layer already carries. A- * raster names its source and any non-default blend or opacity; a control layer its adapter and- * weight; regional guidance its prompt or reference images; an inpaint mask its denoise bounds.- */export const layerRowSummary = (layer: CanvasLayerContract, t: TFunction): string => {switch (layer.type) {case 'raster': {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.tsindex 1b044c1478..30ce64a037 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.ts@@ -6,12 +6,8 @@ import { isExportableRasterLayer, isNodeHidden } from '@workbench/canvas-engine/export type StackActionId = 'mergeVisible' | 'exportPsd' | 'toggleVisibility' | 'new';/**- * The right-aligned actions for a stack, in left-to-right render order (the "New" action sits- * rightmost, nearest the panel's own add-layer menu). Only the raster stack offers "merge- * visible" + "export to PSD". The overlay stacks offer hide/show-all: their layers are drawn- * only to show where an effect applies, so getting them out of the way is view hygiene. The- * raster stack has no such action — its layers ARE the image, and bulk-disabling the- * generation input is not a workflow, only an accident.+ * Offer merge/export only for raster stacks and hide/show only for overlays, where visibility must not disable+ * image content. Place New nearest the panel add menu.*/export const getStackActions = (stack: LayerStackKind): StackActionId[] => {if (stack === 'raster') {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeDrop.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeDrop.tsindex 3536952523..ad34a7ef66 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeDrop.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeDrop.ts@@ -46,11 +46,8 @@ const subtreeEnds = (rows: readonly LayerTreeRow[]): Int32Array => {};/**- * Projects a drag onto the sortable-tree target it describes: the dragged block leaves the list,- * the pointer's vertical position picks the gap, and its horizontal offset picks the depth- * between the shallowest and deepest parent that gap allows. Returns `null` when nothing valid- * is under the pointer, when the pointer is over the block itself, or when the move would exceed- * the depth limit. Locks and other document refusals stay with the model. Linear in the rows.+ * Project vertical gaps and horizontal depth after removing the dragged block. Reject self/invalid/depth-exceeding+ * targets; model validation owns locks and other refusals. Linear in row count.*/export const projectLayerDrop = (input: LayerDropInput): LayerDropTarget | null => {const { rows } = input;@@ -95,8 +92,7 @@ export const projectLayerDrop = (input: LayerDropInput): LayerDropTarget | nullreturn null;}if (input.edge === 'inside') {- // Straight into the hovered group, at its top — the one comfortable way- // into an empty group. The depth limit still applies to the whole block.+ // Drop into the hovered group's top, respecting the entire block's depth limit.const over = remaining[overIndex]!;if (over.vm.kind !== 'group') {return null;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.tsindex 221bae341e..707e4e818b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.ts@@ -63,10 +63,8 @@ const filteredIds = (};/**- * The rows of every stack for a document, the set of expanded groups, and an optional name filter.- * Rows come from the seam's semantic nodes, so a row keeps its identity while its node, its place,- * its effective state, its sibling position and its expansion are unchanged; memoized row- * components skip unaffected rows. Every node is visited once.+ * Project each node once and preserve row identity while semantic state/placement/expansion remain unchanged so+ * unaffected rows skip renders.*/export const buildLayerStackRows = (stacks: CanvasStackForests,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsxindex d17b61a9a7..e128d9ec23 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsx@@ -38,12 +38,8 @@ const clamp = (value: number, min: number, max: number): number => Math.min(max,const FORMAT_HOVER_PROPS = { bg: 'bg.muted', color: 'fg' };/**- * The color pane's workspace: the active foreground/background pair with an- * explicit target, one picking surface (wheel or box, remembered per user),- * and channel inputs in the shared picker format. The shelves live in the- * sibling Swatches pane. Everything edits the one persisted pair; nothing here- * owns color state of its own beyond the sticky HSV needed to keep hue through- * greys.+ * Edit one persisted foreground/background pair using the user's preferred wheel/box and shared channels. Keep+ * only sticky HSV locally to preserve hue through greys; shelves live in Swatches.*/export const ColorPane = () => {const { t } = useTranslation();@@ -88,9 +84,7 @@ export const ColorPane = () => {},[commands, maskTint, target]);- // Held arrow keys commit per repeat; the recents shelf hears only the- // settled color, not two dozen intermediate hues. An immediate record (hex- // commit, pipette) supersedes the pending one, and unmount flushes it.+ // Record only settled arrow-repeat colors; immediate commits supersede pending recents and unmount flushes them.const pendingRecent = useRef<{ hex: string; timer: ReturnType<typeof setTimeout> } | null>(null);const settlePendingRecent = useCallback((record: boolean) => {if (!pendingRecent.current) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/GroupSelectedNotice.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/GroupSelectedNotice.tsxindex 30f8506be2..d6b4341523 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/GroupSelectedNotice.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/GroupSelectedNotice.tsx@@ -3,11 +3,7 @@ import { getDocumentNode } from '@workbench/canvas-engine/api';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useTranslation } from 'react-i18next';-/**- * Leaf tools and editors cannot act on a group: name the state instead of- * silently refusing. Renders nothing unless a group really is selected, so- * ungated callers stay honest for leaves and for no selection at all.- */+/** Explain group selection when leaf editors cannot act; render nothing for leaves or no selection. */export const GroupSelectedNotice = ({ hint }: { hint?: string }) => {const { t } = useTranslation();const isGroupSelected = useActiveProjectSelector((project) => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/HistoryPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/HistoryPane.tsxindex 90db910c65..e2d3f61aeb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/HistoryPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/HistoryPane.tsx@@ -11,10 +11,8 @@ import { useTranslation } from 'react-i18next';const STEP_HOVER_PROPS = { bg: 'bg.muted', color: 'fg' };/**- * The canvas edit history as a walkable list: every retained step, oldest- * first, with the current position highlighted. Clicking a step replays- * undo/redo up to it; the steps below the current one are the redoable future.- * The list mirrors the engine's own bounded history — it owns nothing.+ * Mirror bounded engine history oldest-first; selecting a step replays undo/redo, with future steps below the+ * current position.*/export const HistoryPane = () => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsxindex 601b2fda7b..8a34a7f487 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx@@ -437,8 +437,6 @@ describe('Properties pane', () => {const xField = page.getByRole('spinbutton', { exact: true, name: 'X' }).element();await act(() => engine!.tools.setTool('bbox'));await settle();- // Same DOM node: the shared Position group survives the switch, now- // editing the frame; the frame's Size and Aspect rows appear.expect(page.getByRole('spinbutton', { exact: true, name: 'X' }).element()).toBe(xField);await expect.element(page.getByRole('spinbutton', { exact: true, name: 'W' })).toBeVisible();@@ -499,8 +497,6 @@ describe('Properties pane', () => {for (const tool of ['eraser', 'view', 'move', 'shape'] as const) {await act(() => engine!.tools.setTool(tool));await settle();- // Same node, same anchor: switching tools swaps rows inside the- // section but never unmounts or repositions the section itself.expect(host!.querySelector('[role="group"][aria-label="Tool"]')).toBe(section);const rect = section.getBoundingClientRect();expect(rect.left).toBe(left);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsxindex e7c4ab9b62..ebad893df2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx@@ -45,11 +45,8 @@ interface PaneBlockLabels {}/**- * One fixed pane block of the Layers panel: a tab strip over a panel, with a- * preferred height, a resize separator on its inner edge, and collapse down to- * the strip. `edge` names which end of the panel the block is docked to — a- * top block grows downward and a bottom block grows upward. The panes are part- * of the panel, never movable widgets.+ * Dock fixed pane blocks at either panel edge with preferred height, resize, and collapse-to-tabs; they are not+ * movable widgets.*/const LayerPaneBlock = ({activePane,@@ -272,11 +269,6 @@ const EDITOR_PANES: ReadonlyArray<{ id: LayerEditorPaneId; labelKey: string }> ={ id: 'overview', labelKey: 'widgets.labels.overview' },];-/**- * The editor panes under the tree: the active tool's Properties, the selected- * layer's Transform, and the document Overview, persisted through the widget's- * project state.- */export const LayerEditorPanes = ({layout,onLayoutChange,@@ -340,11 +332,6 @@ const COLOR_PANES: ReadonlyArray<{ id: LayerColorPaneId; labelKey: string }> = [{ id: 'swatches', labelKey: 'widgets.labels.swatches' },];-/**- * The color panes above the tree: the project foreground/background pair with- * its picker and channels, and the swatch shelves as a sibling tab — the- * layers panel's persistent color workspace.- */export const LayerColorPane = ({layout,onLayoutChange,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsxindex 676f1ed1d5..d1e22961e9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx@@ -42,10 +42,8 @@ const selectSelectedNode = (project: {}): CanvasNodeContract | null => getDocumentNode(project.canvas.document, project.canvas.document.selectedLayerId);/**- * The Layer section of the Properties pane: the selected layer's type-specific- * settings (blend mode and opacity live in the fixed row above the tree —- * `LayerBlendRow`). Every editor commits through the same document seams it- * always did — this is the one implementation, reparented.+ * Render selected-layer editors here; blend/opacity remain in LayerBlendRow and all edits retain their document+ * seams.*/export const LayerSection = ({ disabled }: { disabled: boolean }) => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsxindex 8d2d54666f..bfdadec477 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx@@ -23,12 +23,8 @@ const CHECKERBOARD_CSS = {const VIEW_RECT_TRANSITION = `left ${VIEW_RECT_INTERVAL_MS}ms linear, top ${VIEW_RECT_INTERVAL_MS}ms linear, width ${VIEW_RECT_INTERVAL_MS}ms linear, height ${VIEW_RECT_INTERVAL_MS}ms linear`;/**- * The navigator: a fit-to-pane composite of the whole document over a- * transparency checkerboard, with the live viewport outlined on top. Clicking- * or dragging centers the view there, the wheel zooms about the point under- * the cursor, and arrow keys pan when the preview is focused. Composite- * repaints and outline updates are throttled; the outline is positioned- * imperatively so pan/zoom never re-renders the pane.+ * Show a fitted composite with viewport outline; click/drag centers, wheel zooms, and arrows pan. Throttle+ * painting and update the outline imperatively.*/export const OverviewPane = () => {const { t } = useTranslation();@@ -149,8 +145,7 @@ const ConnectedOverview = ({ engine }: { engine: CanvasEngineHandle }) => {scheduleRedraw();}, [contentEpoch, stacks, frame, scheduleRedraw]);- // The outline is written straight to the DOM on a throttled cadence; the CSS- // transition carries it between updates.+ // Throttle DOM outline updates and let CSS interpolate between them.useEffect(() => {const viewport = engine.viewport.getViewport();let timer: ReturnType<typeof setTimeout> | null = null;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesPane.tsxindex a3b0c40db2..8b266264b5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesPane.tsx@@ -16,12 +16,7 @@ import { GroupSelectedNotice } from './GroupSelectedNotice';import { LayerSection } from './LayerSection';import { PropertiesSection } from './PropertiesSection';-/**- * Full editors for what the canvas is doing: the running operation first, then- * the active tool's form. Reads and writes the engine's option stores and- * document transactions through the same adapters the canvas registers; it- * mirrors no state of its own.- */+/** Show active operation before tool forms; use existing engine stores/transactions without mirrored state. */export const PropertiesPane = () => {const { t } = useTranslation();const engine = useCanvasEngine();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/SwatchesPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/SwatchesPane.tsxindex d8d3e49045..e667ebe0dc 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/SwatchesPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/SwatchesPane.tsx@@ -19,11 +19,7 @@ import { PlusIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-/**- * The swatches pane: the workbench defaults, the account's recent colors, and- * the project palette. A pick writes the active foreground/background target —- * the shelves share the Color pane's one persisted pair and own nothing.- */+/** Share default, account-recent, and project swatches; picks update the same active pair as Color. */export const SwatchesPane = () => {const { t } = useTranslation();const engine = useCanvasEngine();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.tsindex 94fe06a08d..803000dfd3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts@@ -101,16 +101,9 @@ const stopped = (};/**- * A layer run is one run of the project graph, so its seeds follow the same- * rules as a queued submission of one: a random input draws now, a stepping- * input takes its authored seed. The runner plans once the layer has been- * exported and uploaded, and applies `seedAdvances` to the project graph in the- * same turn as the graph build — that is the reservation. The dialog's action- * session serialises layer runs, so two runs take consecutive seeds; a refusal- * before the build consumes nothing, a failure after it has. The project graph- * is the owning document: the dialog runs it, not a library record, and the- * reducer fences each advance on the value and mode the plan read, so an edit- * made meanwhile wins.+ * Reserve seeds after layer upload in the graph-build turn. Serialized runs advance consecutively; pre-build+ * refusals consume none, later failures do. Apply advances to the project graph with value/mode fences so+ * concurrent edits win.*/export const reserveLayerWorkflowSeeds = (document: ProjectGraphState,@@ -149,9 +142,8 @@ export const runLayerWorkflow = async (options: RunLayerWorkflowOptions): Promis}failureStage = 'graph';- // The layer is exported and uploaded, so the run will be submitted: reserve its seeds- // now, in the same turn as the graph build. A refusal above consumed nothing, like a- // queue route that fails validation; a failure below has, like a cancelled queue item.+ // Reserve seeds with graph build after upload; earlier refusals consume none, later failures retain the+ // reservation.const seedPlan = deps.reserveSeeds();if (seedPlan.seedAdvances.length > 0) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.tsindex 916cc27973..39dea1ff59 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts@@ -29,11 +29,8 @@ import {import { useSelectedModelBase } from './useSelectedModelBase';/**- * Returns a single `addLayer(id)` callback that creates a new layer of the given- * kind through the guarded structural commit (one undoable history entry per- * add). Reused by the panel's add-layer menu AND each stack header's "New"- * button so both surfaces stay in lockstep. A new node lands directly above the- * selection, inside its group when the selection is a leaf of one.+ * Share guarded undoable creation across add menus and stack buttons. Insert above the selection, inside its group+ * for selected leaves.*/export const useAddLayer = (): ((id: AddLayerItemId) => void) => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.tsindex 8cd51b3c49..0102e1da00 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.ts@@ -19,11 +19,7 @@ export interface LayerSelectionCommands {groupSelected: () => void;}-/**- * The footer's selection verbs: duplicate, group, delete. Enablement comes- * from the same model authority that runs the command, so nothing here can- * refuse later; everything acts on the panel's current selection.- */+/** Use model-authoritative eligibility for duplicate/group/delete on the current selection. */export const useLayerSelectionCommands = (engine: SelectionEngine | null,projectId: string,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useSelectedModelBase.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useSelectedModelBase.tsindex b1cbf3b0c8..566ef066e1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useSelectedModelBase.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useSelectedModelBase.ts@@ -2,12 +2,7 @@ import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { getSelectedModelBase } from './selectedModel';-/**- * The main model's base (`sd-1` / `sdxl` / `flux` / …), read from the generate- * widget values. Drives which control-adapter kinds and reference-image kinds a- * region can consume. Shared by the control/regional settings and the add-layer- * flow so a freshly created "regional reference image" mints the base-correct kind.- */+/** Share the Generate model base across control/regional settings and layer creation so adapter kinds agree. */export const useSelectedModelBase = (): string | null => {return useActiveProjectSelector(getSelectedModelBase);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsxindex be181f4e97..477a441bc8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx@@ -27,14 +27,6 @@ const STAR_LABEL_KEYS = {video: { off: 'widgets.preview.starVideo', on: 'widgets.preview.unstarVideo' },} as const;-/**- * The header's always-visible action row: Edit leads (the one verb that moves- * the image into actual work — a menu of canvas layer destinations), then- * compare, star, and an "image actions" dropdown that opens the full- * right-click context menu — one source of truth for every image verb,- * mirroring the legacy viewer's menu button. Compact densities collapse to- * star + the dropdown. Details lives beside the toggles, not here.- */export const PreviewActionStrip = ({actions,density,@@ -94,10 +86,7 @@ export const PreviewActionStrip = ({return (<HStack flexShrink={0} gap="0.5">- {/* First and worded, not another glyph in the row: it is the strip's one- verb that moves the image into actual work, so it opens straight onto- the layer destinations. Videos have no canvas destination, so it is- not offered for them — the same guard the context menu uses. */}+ {/* Lead with the labeled canvas-destination action; omit it for videos, matching context-menu eligibility. */}{image ? (<><EditOnCanvasMenu onSend={sendToCanvas} />diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsxindex cc3c58941d..4df132258a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsx@@ -71,16 +71,7 @@ const interact = (action: () => void): Promise<void> =>});});-/**- * Waits until a transition has actually settled on `expected`, rather than- * sleeping a fixed interval and asserting immediately after.- *- * A loaded CI runner can starve the compositor for longer than any constant- * worth waiting for, and the failure mode is silent: the transition has not- * advanced, so the assertion reads the value it started from and reports a- * plausible-looking mismatch. Polling makes the wait as long as the machine- * needs and no longer, and a timeout still fails loudly.- */+/** Poll until transitions settle; fixed waits can read pre-transition values under compositor starvation. */const waitForOpacity = (element: HTMLElement, expected: string, label = '', timeoutMs = 5000): Promise<void> =>act(async () => {const deadline = Date.now() + timeoutMs;@@ -177,13 +168,7 @@ describe('PreviewCompare', () => {const frame = host!.querySelector<HTMLElement>('[aria-label*="Reveal comparison"]')!;const compareOverlay = host!.querySelector<HTMLImageElement>('img[alt="compare"]')?.parentElement as HTMLElement;- // The overlay reveals on focus OR hover OR touch press. The runner's- // cursor stays wherever the previous test left it, so a component that- // mounts underneath it gets a real `pointerenter` and stays revealed- // through blur. Clearing the hover synthetically keeps this test about- // focus, and keeps it independent of where the pointer happens to be.- // Waited for, not asserted outright: if the cursor had been resting on the- // frame, clearing it starts a fade that is still in flight right now.+ // Clear incidental hover to isolate focus behavior, then wait for any resulting fade to settle.await clearMouseHover(frame);await waitForOpacity(compareOverlay, '0', 'initial');await interact(() => frame.focus());diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsxindex 9797523c09..90880a2089 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx@@ -155,9 +155,7 @@ export const PreviewCompare = ({<Stack gap="3" h="full" minH="0" w="full"><PreviewStage fill="flex" padding="6">{mode === 'slider' ? (- // Not FittedFrame: this frame needs the drag cursor and pointer-capture- // handlers below, and FittedFrame's drop shadow would be a visual change- // this Box never had.+ // Use a plain frame for capture/drag behavior without introducing FittedFrame's shadow.<Boxref={containerRef}borderColor="border.emphasized"@@ -399,11 +397,8 @@ const CompareSidePane = ({cursor={isZoomed ? 'grab' : undefined}overflow="hidden"position="relative"- // Keeps the browser's own pan and pinch off the pane, so a two-finger- // gesture reaches the shared loupe instead of zooming the page — but only- // where there is a loupe: mismatched dimensions leave the panes without- // one, and suppressing the browser's gestures there would replace them- // with nothing.+ // Suppress native pan/pinch only when the shared loupe can replace them; mismatched dimensions retain+ // browser gestures.touchAction={pane ? 'none' : undefined}{...pane?.frameProps}>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsxindex d382d91ce9..551c1e674d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsx@@ -7,14 +7,8 @@ import { useTranslation } from 'react-i18next';import { PREVIEW_COMPARE_DROP_DATA, PREVIEW_COMPARE_DROP_ID } from './previewCompareDnd';/**- * A quiet drop ring over the preview frame, visible only while an all-image gallery-item- * drag is in flight. Dropping arms the dragged image for comparison (resolved- * by the widget shell's dnd monitor).- *- * The image already on screen is refused wherever it was dragged from — the- * frame itself, the filmstrip, or the gallery grid — because comparing an image- * with itself does nothing but pause live-follow. Only `items[0]` is tested,- * since that is the item `resolvePreviewCompareDrop` would arm.+ * Show comparison drop targets for image-only drags; reject the first item if already displayed so self-comparison+ * cannot pause live-follow.*/export const PreviewCompareDropZone = ({ currentImageName }: { currentImageName: string | null }) => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsxindex a3848e659b..b3c9352c55 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsx@@ -18,12 +18,8 @@ import { PreviewDetails } from './PreviewMetadataPanel';type InteractOutsideHandler = NonNullable<ComponentProps<typeof Popover.Root>['onInteractOutside']>;/**- * The header's Details toggle and its popover: board position and dimensions- * on the first line, then the legacy tab set (parsed details for images, the- * raw metadata record, workflow, graph). Anchored bottom-end under its trigger- * at the header's far end and bounded by the media stage rather than the- * viewport, so however long the metadata runs it scrolls inside the image area- * and never lies over the filmstrip.+ * Bound Details to the media stage so long metadata scrolls without covering the filmstrip; images offer parsed+ * details alongside raw payload tabs.*/export const PreviewDetailsPopover = ({actions,@@ -55,9 +51,7 @@ export const PreviewDetailsPopover = ({[stageElement]);const handleOpenChange = useCallback(({ open }: { open: boolean }) => onOpenChange(open), [onOpenChange]);- // Reading Details while browsing the board is the point: a click on the- // filmstrip or the stage keeps the popover up (the query re-keys to the new- // item), and focus stays on the preview so the arrow keys keep walking.+ // Keep Details open while stage/filmstrip selection changes and preserve Preview keyboard navigation.const handleInteractOutside = useCallback<InteractOutsideHandler>((event) => {const widget = stageElement?.closest('[role="region"]');@@ -100,8 +94,6 @@ export const PreviewDetailsPopover = ({onInteractOutside={handleInteractOutside}onOpenChange={handleOpenChange}>- {/* Reads like the toggles beside it: the filled variant and `aria-pressed`- carry "open" the way they carry "on" for the filmstrip. */}<Tooltip content={t('widgets.preview.details')} ids={ids}><Popover.Trigger asChild><IconButtondiff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsxindex a1f9440397..5d989d08b0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx@@ -18,16 +18,8 @@ import { useTranslation } from 'react-i18next';import type { PreviewDensity } from './previewDensity';/**- * The current board's thumbnails as a row docked under the stage — the same- * `boardImages` the Details position counter is derived from, made spatial.- * Live sessions lead the row in the gallery's in-progress order, one thumb- * per GPU slot, so however many run the stage keeps one of them large and- * the rest stay a glance (and a click) away; a session that finishes becomes- * its image's thumb in place. It takes its own height rather than floating- * over the media, so the fitted frame is never covered and Details has a- * clean edge to stop above. Item thumbs are standard all-image gallery-item- * drag sources, so they work with every existing drop target (canvas zones,- * boards, drop-to-compare).+ * Render board thumbnails below the stage with live GPU slots leading in gallery order and settling into result+ * thumbnails in place. Reserve height outside media; item drag payloads work with existing gallery targets.*/export const PreviewFilmstrip = ({@@ -65,19 +57,14 @@ export const PreviewFilmstrip = ({}) => {const thumbSize = density === 'full' ? '12' : '8';- // A lone item has nothing to step to; a live session always earns the row,- // or a single running slot on an empty board would have no thumb at all.+ // Show the strip for any live session, even on an otherwise empty board.if (items.length < 2 && sessions.length === 0) {return null;}return (- // Two containment rules keep the strip honest: the ScrollArea root's- // recipe defaults to `height: 100%`, so it MUST get an explicit height or- // it swallows the widget; and `contain: inline-size` zeroes the strip's- // intrinsic width so a long board can never stretch the widget wider than- // its panel (side panels host widgets in a grid ScrollArea.Content that- // otherwise grows to max-content).+ // Set explicit ScrollArea height and inline-size containment so the strip neither consumes widget height nor+ // expands its width.<Scrollablebg="bg.subtle"borderColor="border.subtle"@@ -126,11 +113,8 @@ export const PreviewFilmstrip = ({};/**- * One running, settling, or queued slot. Mirrors the gallery's in-progress- * tile: the latest denoise frame under a progress ring, a device chip in the- * name, `aria-current` while it is the session on the stage, and a pin in- * place of the ring while it is pinned there — so the next click visibly- * unpins. Only a running slot can be followed.+ * Show live/settling/queued slots with progress, device, and selected/pinned state; only running slots can be+ * followed.*/const FilmstripLiveThumb = ({isFollowed,@@ -186,9 +170,7 @@ const FilmstripLiveThumb = ({onFollow?.(session.id);}}, [isPinned, isRunning, onFollow, onUnpin, session.id]);- // Keeps the followed slot in view like the selected item thumb does, and- // hands focus back to the preview when the slot finishes under the- // keyboard — its element goes with it, and nothing else would take over.+ // Keep the followed slot visible and restore preview focus when its thumb disappears.const thumbRef = useCallback((node: HTMLElement | null) => {if (!node) {@@ -313,8 +295,6 @@ const FilmstripThumb = ({},[item, onContextMenu]);- // Ref callbacks re-run when `isSelected` changes, keeping the selected thumb- // in view without an effect.const scrollIntoView = useCallback((node: HTMLElement | null) => {setNodeRef(node);@@ -342,9 +322,7 @@ const FilmstripThumb = ({overflow="hidden"position="relative"rounded="sm"- // Pan, don't drag: the strip scrolls horizontally, so a moving finger- // must scroll it (the hold-to-drag sensor releases the gesture when the- // browser claims it); dragging still works after a sustained hold.+ // Allow horizontal touch pan; sustained holds still activate dragging.touchAction="pan-x"onClick={handleClick}onContextMenu={onContextMenu ? handleContextMenu : undefined}@@ -365,11 +343,7 @@ const FILMSTRIP_CONTAIN_CSS = { contain: 'inline-size' } as const;/** Same touch drag cue as the gallery grid: the source thumb desaturates while dragged. */const FILMSTRIP_THUMB_DRAG_CSS = { filter: 'saturate(0)' } as const;-/**- * Same armed cue as the gallery grid: desaturation while a sustained touch- * hold has armed the drag gate (before movement starts the drag). Set as- * `data-drag-armed` by the hold-to-drag sensor.- */+/** Match Gallery's desaturated data-drag-armed cue before held-touch movement starts dragging. */const FILMSTRIP_THUMB_ARMED_CSS = { '&[data-drag-armed=true]': { filter: 'saturate(0)' } } as const;// The thumb row centers itself with `h="full"`, which needs the contentdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsxindex b1b74b5f18..e42ecc348b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx@@ -46,20 +46,11 @@ interface PreviewFrameProps {dragItem?: GalleryItemRef;frameHeight: number;frameWidth: number;- /**- * Painted over `source` until the browser has decoded it — the last denoise- * frame, so a finished image swaps in over the pixels it grew from rather- * than over a blank card. `onSourceLoaded` fires once the swap has happened.- */+ /** Keep the last denoise frame until source decoding completes, then notify onSourceLoaded. */holdSource?: StreamingImageSource | null;onSourceLoaded?: (src: string) => void;isItemCurrent?: (itemKey: GalleryItemKey) => boolean;- /**- * No live frame carries a caption of any kind. The frame is styled exactly- * like a finished item so nothing about it moves when denoising ends, and- * every progress readout — including which device is rendering — belongs to- * the footer island or the top bar rail.- */+ /** Keep live-frame geometry identical to finished media; progress/device text belongs to external chrome. */isLive: boolean;loupeControlsRef?: Ref<PreviewLoupeControls>;onContextMenu?: (x: number, y: number) => void;@@ -237,9 +228,7 @@ const PreviewImageFrame = ({) : null;if (variant === 'inset') {return (- // Live tiles all reserve the chrome inset, so in a multi-session grid the- // bottom row reserves room it does not need. Its own dot grid still fills- // the cell, so only the fitted frame sits a little lower.+ // Reserve chrome inset consistently across live tiles; their dot grids still fill each cell.<PreviewStage fill="parent">{source ? (<FittedFrame frameHeight={frameHeight} frameWidth={frameWidth}>@@ -259,17 +248,15 @@ const PreviewImageFrame = ({fill="flex"padding={padding}paddingBottom={paddingBottom}- // The whole stage is the loupe's viewport, so it — not just the media- // card — has to keep the browser's own pan and pinch off the surface:- // otherwise the first finger of a pinch is claimed as a page gesture and- // the pointer stream stops mid-zoom. A live render has no loupe to put in- // their place, so it leaves them alone.+ // Suppress browser gestures across the loupe's entire stage; live renders without a loupe retain native+ // behavior.touchAction={isLive ? undefined : 'none'}{...loupe.stageProps}>- {/* Never armed over a live render: arming a comparison pauses live-follow- and would swap the in-progress image for a compare of the stale hidden- selection. The inset live frame never offered this either. */}+ {/*+ * Disable comparison drops over live renders because comparison would pause follow and expose stale+ * selection.+ */}{isLive ? null : <PreviewCompareDropZone currentImageName={dragItem?.kind === 'image' ? dragItem.name : null} />}<FittedFrameref={setContentRef}@@ -313,11 +300,7 @@ const PreviewVideo = ({}) => {const { t } = useTranslation();const videoRef = useRef<HTMLVideoElement | null>(null);- // The `<video controls>` surface cannot be the drag handle the way the image- // frame is: the pointer-move activation threshold would turn every native- // seek-bar scrub into a drag. A corner grip carries the same gallery-item- // payload instead, so the preview and the gallery thumbnail drop the same- // thing everywhere.+ // Use a corner drag grip for video so native seek-bar scrubbing cannot activate gallery dragging.const dragData = useMemo(() => (dragItem ? getGalleryItemDragData([dragItem]) : undefined), [dragItem]);const disabledDragId = useId();const {@@ -407,22 +390,14 @@ const PreviewVideo = ({return isCurrent() ? { ok: true } : { ok: false, reason: 'stale' };}, [isItemCurrent, source.itemKey]);const isCopyAvailable = useCallback(() => isVideoFrameCopyAvailable(videoRef.current), []);- // Span playback: the Video panel's play buttons ask Preview to loop exactly what a- // trim selected, so the window can be watched and heard before a generation is spent- // on it. The span lives in refs rather than state — nothing in the frame renders- // differently while it loops, and re-rendering on each wrap would only fight the- // player.+ // Loop requested trim spans for preview without generation; keep loop state in refs because wraps change no+ // rendered UI.const spanRef = useRef<VideoSpan | null>(null);- // A span that arrived before the element could act on it, with the deadline it must not- // outlive: the request channel checks freshness once, at consume time, so a span parked- // here through a failed load or a hidden keep-alive would otherwise replay unmuted- // minutes later when the user pressed Retry.+ // Expire spans parked before media readiness so retries or hidden remounts cannot start stale audio later.const parkedSpanRef = useRef<{ expiresAt: number; span: VideoSpan; token: number } | null>(null);const spanFrameRef = useRef<number | null>(null);- // The request behind the loop on screen, reported back so the button that made it can- // offer to stop it. Outlives a pause (the loop stays armed, so a native play resumes the- // selection under the same request) and a hide (same reason); retired only when the user- // takes the playhead out of the window or a newer request replaces it.+ // Keep request identity through pause/hide while the loop stays armed; retire it when the playhead leaves or a+ // newer request arrives.const spanTokenRef = useRef<number | null>(null);const seekWithinSpan = useCallback((video: HTMLVideoElement, time: number) => {try {@@ -441,9 +416,7 @@ const PreviewVideo = ({const pauseSpanPlayback = useCallback(() => {videoRef.current?.pause();}, []);- // Reported from the element's own play/pause transitions, never from the request: what- // the panel shows as running has to be what is actually running, whichever control —- // ours, the native bar, or an autoplay refusal — last changed it.+ // Publish actual element play/pause state, including native controls and autoplay refusals.const publishSpanState = useCallback(() => {const token = spanTokenRef.current;const video = videoRef.current;@@ -463,10 +436,7 @@ const PreviewVideo = ({clearVideoSpanPlaybackState(token);}}, []);- // `timeupdate` fires about four times a second, which overruns a two-second selection by- // an eighth of it; a frame loop wraps within a frame while the tab is visible.- // `timeupdate` stays as the backstop for a backgrounded tab, where- // `requestAnimationFrame` does not run at all.+ // Use rAF for precise visible-tab wrapping and timeupdate as the background-tab fallback.const enforceSpan = useCallback(() => {const span = spanRef.current;const video = videoRef.current;@@ -497,10 +467,7 @@ const PreviewVideo = ({(span: VideoSpan, token: number, expiresAt?: number) => {const video = videoRef.current;- // Before metadata there is no duration to clamp against and the element drops the- // seek outright; below, the element is gone entirely because a hidden keep-alive- // boundary detached the ref. Both are picked back up — by `loadedmetadata`, and by- // the mount effect when the view comes back.+ // Defer seeks until metadata and element attachment exist; resume from loadedmetadata or remount.if (!video || video.readyState < HTMLMediaElement.HAVE_METADATA) {// The deadline belongs to the gesture, not to this attempt: minting a fresh one on// every re-park would let hide/show cycles on a clip that never loads extend it@@ -514,17 +481,9 @@ const PreviewVideo = ({const endSeconds = duration === null ? span.endSeconds : Math.min(span.endSeconds, duration);const startSeconds = Math.max(0, Math.min(span.startSeconds, endSeconds));- // Arm on any window with room to play. The test is emptiness, NOT a minimum width:- // the panel's own floor is two frames (`MIN_VIDEO_TRIM_FRAMES`), which is 33ms at- // 60fps and less above that, and those tight selections are exactly the ones the two- // still bounds convey least. A window the clamp collapsed — a clip whose real- // duration falls short of the frame count the panel estimated, or a foreign record- // with inverted bounds — has nowhere to wrap to, so it plays without a loop.+ // Loop any nonempty clamped span, including two-frame trims; collapsed/inverted bounds play without looping.spanRef.current = endSeconds > startSeconds ? { endSeconds, startSeconds } : null;- // A newer request supersedes the loop before it, whatever that one was doing: its- // button reverts to play, and this one's takes over. Only a loop is reported — a- // collapsed window plays once with nothing armed, and a stop for it would stop- // nothing the button promised.+ // New requests replace prior loop ownership; report only an armed loop, not collapsed one-shot playback.retireSpanToken();if (spanRef.current !== null) {@@ -536,21 +495,15 @@ const PreviewVideo = ({// first selected frame with the native controls live and the loop still armed, so// pressing play there plays the selection rather than the whole clip.void video.play().catch(() => {});- // play() resolves asynchronously, so the element can still be paused here and the- // watch would stop after one frame; `onPlay` arms it for that case. Both paths are- // needed — a span arriving mid-playback fires no `play` event, and the same event- // gap is why the state is published here as well as from the handlers.+ // Arm onPlay for asynchronous play(), and immediately for already-playing elements that emit no new play+ // event.startSpanWatch();publishSpanState();},[publishSpanState, retireSpanToken, seekWithinSpan, startSpanWatch]);- // What retires a loop is the playhead LEAVING the window, not who moved it. Asking where- // it landed rather than marking our own seeks is what makes this survive the orderings a- // marker cannot: a seek to where the playhead already sits fires no event at all (the- // Initial Video's trim starts at frame 0, so that is the first press), and the- // first-frame nudge's own seek can be delivered after a span has armed. A scrub that- // stays inside the window is one the loop would have honoured anyway.+ // Retire loops only when seeks land outside the span; own-seek markers fail for no-op or delayed seeks.+ // In-window scrubs preserve looping.const handleSpanSeeking = useCallback(() => {const span = spanRef.current;const video = videoRef.current;@@ -567,8 +520,6 @@ const PreviewVideo = ({return;}- // The user took the playhead somewhere the loop was not going. They own it from here,- // and the panel's button goes back to offering the selection rather than a stop.spanRef.current = null;parkedSpanRef.current = null;stopSpanWatch();@@ -582,17 +533,13 @@ const PreviewVideo = ({stopSpanWatch();publishSpanState();}, [publishSpanState, stopSpanWatch]);- // `load()` — protected-media recovery, or the failure overlay's Retry — flips the element- // to paused WITHOUT firing `pause`; `emptied` is the event it does fire. Left unreported,- // the panel would go on offering a stop for a loop that is no longer running, and the- // stop itself would be a no-op: pausing a paused element fires nothing either.+ // Handle emptied because load() pauses without a pause event; otherwise controls offer a stop that cannot change+ // anything.const handleEmptied = useCallback(() => {publishCopyAvailability();publishSpanState();}, [publishCopyAvailability, publishSpanState]);- // A trim can end on the clip's final frame, where the playhead reaches the window's end- // only as the media ends: `pause` stops the watch and `enforceSpan` bails on a paused- // element, so whether the last `timeupdate` wrapped first was down to the browser.+ // Handle ended explicitly for spans ending at clip duration because pause has already stopped the frame watcher.const handleSpanEnded = useCallback(() => {const span = spanRef.current;const video = videoRef.current;@@ -603,23 +550,12 @@ const PreviewVideo = ({seekWithinSpan(video, span.startSeconds);void video.play().catch(() => {});- // The `pause` that precedes `ended` has just reported the loop stopped; `play()` has- // already flipped the element back, so say so now rather than a task later when the- // `play` event lands — the gap is a paint, and the panel's icon would blink on every- // wrap of a window that ends on the clip's last frame.+ // Publish resumed playback in the same task as end wrapping so the control icon cannot blink between pause and+ // play events.publishSpanState();}, [publishSpanState, seekWithinSpan]);- // Playback must not outlive this view being on screen. A widget the shell- // keeps mounted behind a layout switch is hidden with `display: none`, which- // does not stop media — the clip would keep running, with audio, behind a- // layout the user moved away from and with no reachable controls. Effects are- // torn down whenever the subtree stops being shown, whether that is a real- // unmount or a hidden keep-alive boundary, so pausing here covers both without- // this component needing to know which one happened.- //- // The span subscription rides along: this element is keyed by `source.itemKey`, so- // the key it filters requests by is fixed for the mount, and a request published- // while Preview was closed is waiting to be read on the first pass.+ // Pause on unmount or hidden Activity cleanup so audio cannot outlive reachable controls. Subscribe by fixed+ // item key and consume pending requests on show.useMountEffect(() => {const video = videoRef.current;const itemKey = source.itemKey;@@ -638,9 +574,7 @@ const PreviewVideo = ({playSpan({ endSeconds: request.endSeconds, startSeconds: request.startSeconds }, request.token);}};- // A span parked while the element was detached — the view was hidden mid-load — has- // no second `loadedmetadata` coming once the clip finished loading behind the hidden- // boundary, so coming back on screen is the only chance left to honour it.+ // Resume fresh parked spans on show if metadata finished while the ref was detached.const parked = parkedSpanRef.current;if (parked) {@@ -659,9 +593,7 @@ const PreviewVideo = ({unsubscribe();stopSpanWatch();video?.pause();- // Nothing is on screen to stop, so the panel must not offer to. The token itself- // stays: the loop is still armed, and a native play after a re-show resumes it- // under the request it belongs to.+ // Report nothing stoppable while hidden, but retain loop identity for native playback after showing.const token = spanTokenRef.current;if (token !== null) {@@ -720,38 +652,16 @@ const PreviewVideo = ({void refresh.then(finishRefresh, () => finishRefresh(false));}, [isItemCurrent, publishCopyAvailability, source.itemKey]);- // The preview keeps `poster` — the 256px WebP gallery thumbnail — as its instant- // placeholder, but the browser goes on showing it well after the video's own first frame is- // decoded and ready: by `loadedmetadata` the element is already at readyState 4 with- // `resize` fired, and the poster survives only because the HTML spec's *show-poster flag* is- // still set. Upscaled across the whole stage, that 256px still is what reads as fuzzy.- // Seeking clears the show-poster flag, and that — not any new decoding — is what puts the- // native-resolution frame on screen. Measured on a 1280x720 clip, Laplacian variance of the- // painted stage goes from 254 to 576.- //- // Dropping the `poster` attribute instead does not work: the flag stays set with nothing- // left to draw, and the stage paints black until the user presses play.- //- // The nudge is not free. It pulls more of the clip than `preload="metadata"` alone would —- // measured on a 7MB/20s clip, one 1MB range request becomes three (~3.1MB), which then- // settles rather than running away. A full-resolution poster served by the backend would buy- // the same frame without the extra range traffic, if that ever becomes worth the endpoint.- //- // The guard skips the nudge when the user hit play before metadata arrived — measured, that- // is the one interleaving where `loadedmetadata` observes `paused === false`. It deliberately- // does not claim to protect a mid-playback viewer from a reload: `load()` is the only thing- // that refires `loadedmetadata` on this element, and it has already reset the position to 0- // and `paused` to true by the time the handler runs. The `currentTime` clause is- // belt-and-braces for an engine that does not reset it.+ // Seek slightly after metadata to clear the browser's show-poster flag and display native-resolution frame zero;+ // removing poster alone leaves black. This fetches extra media ranges. Skip when playback already began or the+ // playhead moved.const handleLoadedMetadata = useCallback(() => {const video = videoRef.current;const parked = parkedSpanRef.current;parkedSpanRef.current = null;- // A span the element could not act on yet, honoured only while the gesture behind it- // is still fresh. Its own seek is the sharper version of the nudge below — it lands on- // a frame the user asked for, and clears the show-poster flag the same way.+ // Honor only fresh parked spans; their requested seek also clears the poster flag.if (parked && Date.now() <= parked.expiresAt) {playSpan(parked.span, parked.token, parked.expiresAt);return;@@ -761,12 +671,8 @@ const PreviewVideo = ({return;}- // `load()` — protected-media recovery, or the failure overlay's Retry — rewinds the- // clip and refires this event with the loop still armed. Putting the playhead back- // inside the window is what keeps it scoped, and skipping the NUDGE below is what- // keeps the loop at all: that seek is unmarked, so `seeking` reads it as the user- // taking the playhead back and retires the span outright. Playback stays paused,- // exactly as `load()` left it — a recovery is not a reason to start audio.+ // After load() recovery, restore the armed span's position without starting audio or running a nudge that+ // would retire it.if (spanRef.current) {seekWithinSpan(video, spanRef.current.startSeconds);return;@@ -815,10 +721,7 @@ const PreviewVideo = ({onContextMenu={onContextMenu ? handleContextMenu : undefined}>{dragItem ? (- // Not a button: like the gallery thumbnail and the image frame, the- // drag surface must stay unfocusable — a focusable activator lets the- // KeyboardSensor start an invisible drag on Enter/Space that Tab then- // DROPS on the closest-center droppable.+ // Keep drag grips unfocusable so KeyboardSensor cannot start invisible Enter/Space drags.<Badgeref={setDragHandleRef}{...listeners}@@ -947,17 +850,15 @@ interface VideoSpan {}/**- * How far below a window's start the playhead may land and still count as inside it.- * Engines snap a seek to a decodable point, so a wrap does not land on the exact second- * asked for, and reading its own wrap as the user leaving would retire the loop instantly.+ * Allow slight seek undershoot because decoders may not land exactly at span start; own wraps must not retire the+ * loop.*/const SPAN_SEEK_TOLERANCE_SECONDS = 0.05;/** How long a span waits for an element that could not act on it yet. */const PARKED_SPAN_TTL_MS = 15_000;-// Far enough from zero for browsers to treat it as a real seek, small enough that playback-// still starts on frame 0 at any sane frame rate.+// Seek far enough from zero to clear poster state while staying within frame zero.const FIRST_FRAME_SEEK_SECONDS = 0.0001;const VIDEO_STYLE: CSSProperties = {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameChromeInset.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameChromeInset.browser.test.tsxindex c6f1935f4e..76cb539672 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameChromeInset.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameChromeInset.browser.test.tsx@@ -102,8 +102,7 @@ afterEach(async () => {describe('preview frame chrome clearance', () => {it('drops the fitted media clear of the centre region chrome islands', async () => {- // The islands float over the work surface rather than reserving a row, so- // a height-constrained image used to run under them at fit zoom.+ // Fit media below floating chrome even when height-constrained.await render(true);expect(mediaOffsetFromStageTop()).toBeGreaterThanOrEqual(CENTER_CHROME_INSET_PX);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsxindex 6e9440a368..95d799d6ee 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx@@ -190,10 +190,7 @@ describe('PreviewFrame image drag', () => {});it('gives a second finger the pinch and abandons the drag it interrupted', async () => {- // On a touch screen a pinch starts as one finger on the image, which the- // pointer sensor has already taken as the start of a drag. The second- // finger has to take the gesture over outright: a drag left running would- // keep the image following finger one and drop it somewhere on release.+ // A second touch must cancel image dragging before taking over pinch, avoiding an unintended drop on release.const onDrop = await renderHarness();const image = host!.querySelector<HTMLImageElement>('img[alt="preview.png"]')!;const frame = image.parentElement!;@@ -219,10 +216,7 @@ describe('PreviewFrame image drag', () => {});it('does not offer its own compare target to the image it is showing', async () => {- // Dropping the previewed image back on the frame used to arm a comparison- // of the image with itself: invisible, because compare mode requires the- // two to differ, but it still paused live-follow and left a comparison- // primed to spring open on the next selection.+ // Reject self-comparison drops so they cannot silently pause follow and arm a future comparison.const onDrop = await renderHarness();const image = host!.querySelector<HTMLImageElement>('img[alt="preview.png"]')!;@@ -244,9 +238,7 @@ describe('PreviewFrame video drag', () => {const handle = host!.querySelector<HTMLElement>('[title="Drag video"]')!;expect(handle).not.toBeNull();- // Unfocusable by design: a focusable activator would let the shell's- // KeyboardSensor start an invisible Enter/Space drag that Tab then drops- // on the closest-center droppable.+ // Unfocusable drag surfaces prevent invisible keyboard drags and accidental Tab drops.expect(handle.tabIndex).toBeLessThan(0);expect(handle.closest('button')).toBeNull();const rect = handle.getBoundingClientRect();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsxindex 785135e346..a174645b8c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx@@ -178,8 +178,7 @@ describe('PreviewFrame native video arm', () => {await interact(() => video.dispatchEvent(new Event('loadedmetadata')));- // `preload="metadata"` alone leaves the 256px poster on screen, upscaled to the whole- // stage. The nudge makes the decoder paint frame 0 at the video's native resolution.+ // The metadata nudge replaces the upscaled thumbnail poster with native-resolution frame zero.expect(position.get()).toBeGreaterThan(0);expect(position.get()).toBeLessThan(0.001);// The poster is still the placeholder for the moment before that frame lands, and the@@ -190,9 +189,8 @@ describe('PreviewFrame native video arm', () => {it('leaves the playhead alone when the user started playback before metadata arrived', async () => {await renderVideo();const video = getVideo();- // The one interleaving where `loadedmetadata` observes a non-paused element: `load()`- // resets position and pause state before it fires, so a viewer mid-playback is already- // back at zero by then and there is no playhead left for the guard to protect.+ // Only play-before-metadata leaves loadedmetadata unpaused; load() itself already resets playback and+ // position.const position = stubPlaybackPosition(video, { paused: false });await interact(() => video.dispatchEvent(new Event('loadedmetadata')));@@ -270,8 +268,7 @@ describe('PreviewFrame native video arm', () => {await interact(() => video.dispatchEvent(new Event('loadedmetadata')));- // Preview may have been closed the whole time. Starting audio now would come out of- // nowhere — but the request still has to be retired, not left to fire later.+ // Retire stale requests without starting unexpected audio when Preview was closed.expect(playback.play).not.toHaveBeenCalled();expect(getVideoSpanPlaybackRequest()).toBeNull();expect(playback.getTime()).toBeLessThan(0.001);@@ -304,9 +301,7 @@ describe('PreviewFrame native video arm', () => {await interact(() => video.dispatchEvent(new Event('loadedmetadata')));expect(playback.getTime()).toBe(2);- // `timeupdate` fires about four times a second and would overrun this window by an- // eighth of it; the frame loop is what keeps the wrap tight, and nothing else here- // exercises it.+ // Exercise rAF wrapping; timeupdate alone overshoots short selections.await interact(() => playback.setTime(4.01));await act(async () => {await new Promise<void>((resolve) => {@@ -344,9 +339,7 @@ describe('PreviewFrame native video arm', () => {await interact(() => video.dispatchEvent(new Event('loadedmetadata')));expect(playback.getTime()).toBe(8);- // The playhead reaches this window's end only as the media ends, where `pause` has- // already stopped the watch — without an `ended` handler whether it wrapped was down- // to which event the browser delivered first.+ // Verify end-of-media wrapping independently of pause/timeupdate delivery order.const token = getVideoSpanPlaybackState()?.token;const reports: boolean[] = [];const unsubscribe = subscribeVideoSpanPlaybackState(() => {@@ -357,9 +350,7 @@ describe('PreviewFrame native video arm', () => {expect(playback.getTime()).toBe(8);expect(playback.play).toHaveBeenCalledTimes(2);- // The wrap is reported as running again in the same task as the `pause` that preceded- // `ended`, not a paint later when the `play` event lands: the panel's pause icon must- // not blink on every loop of a window that ends on the clip's last frame.+ // Report end-wrap playback synchronously so the panel icon does not blink each loop.expect(reports).toEqual([false, true]);await interact(() => undefined);@@ -383,15 +374,12 @@ describe('PreviewFrame native video arm', () => {await interact(() => video.dispatchEvent(new Event('loadedmetadata')));expect(playback.getTime()).toBe(2);- // A cookie refresh mid-loop rewinds the clip and refires `loadedmetadata`. The- // first-frame poster nudge used to run there, and its unmarked seek read as the user- // taking the playhead back — the loop was abandoned and the clip sat on frame 0.+ // Media reload must restore the loop instead of running the poster nudge and retiring it.await interact(() => video.dispatchEvent(new Event('error')));await interact(() => undefined);- // Back inside the window, and still paused, exactly as `load()` left it — and reported- // so: `load()` flips the element to paused without a `pause` event, so the panel's- // button would otherwise go on offering a stop that pauses a paused element (a no-op).+ // Restore span position after load() while remaining paused and report that state despite the missing pause+ // event.expect(playback.getTime()).toBe(2);expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: false });@@ -424,9 +412,7 @@ describe('PreviewFrame native video arm', () => {});it('still honours the user when a span seek fires no seeking event', async () => {- // The Initial Video's trim starts at frame 0, so the very first press seeks the- // playhead to where it already sits. A marker left standing there would swallow the- // user's next real scrub and haul them back into the window.+ // A no-op seek at frame zero must not leave a marker that swallows the next real scrub.requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 0 });await renderVideo();const video = getVideo();@@ -446,10 +432,7 @@ describe('PreviewFrame native video arm', () => {});it('loops a window as tight as the panel can make one', async () => {- // The panel's floor is two frames (`MIN_VIDEO_TRIM_FRAMES`), which at 60fps is 33ms —- // narrower than any width threshold worth writing down, and precisely the selection- // the two still bounds convey least. A width floor here silently played the whole- // remainder of the clip instead, with audio.+ // Loop two-frame trims without an arbitrary duration floor.requestVideoSpanPlayback({ endSeconds: 2 + 2 / 60, itemKey: videoSource.itemKey, startSeconds: 2 });await renderVideo();const video = getVideo();@@ -511,9 +494,7 @@ describe('PreviewFrame native video arm', () => {const video = getVideo();const playback = stubSpanPlayback(video);- // Nothing to report until the element has the loop running: before metadata the- // request is parked, and the panel's button must not offer to stop a loop that is not- // yet there.+ // Do not report a stoppable loop while its request is parked before metadata.expect(getVideoSpanPlaybackState()).toBeNull();await interact(() => video.dispatchEvent(new Event('loadedmetadata')));@@ -526,8 +507,6 @@ describe('PreviewFrame native video arm', () => {expect(playback.pauseSpy).toHaveBeenCalledTimes(1);expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: false, token });- // ...so the native play control resumes the selection, under the same request, with- // the wrap still enforced.await interact(() => void video.play());expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token });@@ -557,15 +536,12 @@ describe('PreviewFrame native video arm', () => {await interact(() => undefined);expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token: second });- // A press on another card (or the same one, after a trim change) replaces the loop; the- // earlier button's report goes with it.+ // A newer span request retires the previous button's loop report.const third = requestVideoSpanPlayback({ endSeconds: 9, itemKey: videoSource.itemKey, startSeconds: 8 });await interact(() => undefined);expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token: third });- // Hidden behind a layout switch, the element is paused and nothing is on screen to- // stop, so nothing is offered. Shown again, the loop is still armed: a native play- // resumes it under the request it belongs to.+ // Hiding pauses and clears running status; showing preserves armed identity for native play.await renderKeptVideo('hidden');expect(getVideoSpanPlaybackState()).toBeNull();@@ -581,8 +557,7 @@ describe('PreviewFrame native video arm', () => {const video = getVideo();const playback = stubSpanPlayback(video, { duration: 6 });- // Inverted bounds after clamping: the clip plays once with no loop armed, and a pause- // control for it would promise to stop a selection that is not playing.+ // Collapsed bounds play once without reporting an armed selection loop.await interact(() => requestVideoSpanPlayback({ endSeconds: 9, itemKey: videoSource.itemKey, startSeconds: 8 }));expect(playback.play).toHaveBeenCalledTimes(1);@@ -1095,11 +1070,7 @@ const stubPlaybackPosition = (video: HTMLVideoElement, state: { paused?: booleanreturn { get: () => currentTime };};-/**- * A playable stand-in for the `data:` source, whose seekable range is empty: a real- * `currentTime` assignment clamps back to 0, and `play()` on it never enters a playing- * state, so neither the seek nor the loop would be observable against the element itself.- */+/** Use a playable stand-in because the data source's empty seekable range prevents observable seeks and playback. */const stubSpanPlayback = (video: HTMLVideoElement,{ duration = 10, readyState = HTMLMediaElement.HAVE_METADATA }: { duration?: number; readyState?: number } = {}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsxindex 98452632af..33f9dc6688 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx@@ -18,14 +18,6 @@ import { PreviewZoomMenu } from './PreviewZoomMenu';const Divider = () => <Box bg="border.subtle" flexShrink={0} h="4" w="1px" />;-/**- * The preview widget's header actions, left to right: the zoom readout, the- * image action strip for the current selection (both published by the view- * via `previewHeaderStore`), then the in-progress diffusion and filmstrip- * toggles and the Details toggle, at the far end so its popover hangs off the- * header's right edge. Actions live here — in the frame's standard header- * slot — like every other widget, not in the widget body.- */export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {const { t } = useTranslation();const livePreview = useLivePreviewFollow();@@ -85,15 +77,12 @@ export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {<Divider /></>) : null}- {/* Both toggles go through `ToggleIconButton` so they read as one control- type: the filled variant carries "on", `aria-pressed` carries it for- assistive tech, and the label doubles as the tooltip. */}+<ToggleIconButtonchecked={showProgressImagesInViewer}icon={HourglassIcon}label={label}- // Dimmed while there is nothing in flight to show. Spread after the- // primitive's own props, so it survives.+ // Apply dimming after primitive props so idle-state styling survives.opacity={hasProgressImage || showProgressImagesInViewer ? 1 : 0.7}onCheckedChange={toggleProgressImages}/>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsxindex 8d258c82a2..304e7b4605 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx@@ -244,10 +244,7 @@ describe('PreviewFilmstrip mixed media', () => {const viewportCenterY = viewportRect.top + viewportRect.height / 2;const thumbCenterY = thumbRect.top + thumbRect.height / 2;- // Without the Scrollable `contentProps={{ h: 'full' }}` fix, the content- // wrapper shrinks to the thumb row's own height and the row sticks to- // the viewport's top edge instead of centering in it — a multi-pixel- // offset for the "full" density's 60px strip / 48px thumb combination.+ // Fill the ScrollArea content height so thumbnails center vertically within the strip.expect(Math.abs(thumbCenterY - viewportCenterY)).toBeLessThan(1);});@@ -442,8 +439,6 @@ describe('Preview mixed media actions', () => {expect(actions.sendToCanvas).toHaveBeenCalledWith([expect.objectContaining({ imageName: 'shared' })], 'control');});- // Both remain one click away in the dropdown's quick row, which is why they- // left the strip.it('leaves copy and download to the image-actions dropdown', async () => {const actions = {copyImage: vi.fn(() => Promise.resolve()),diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsxindex f07523d3d1..d662c9678c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx@@ -21,20 +21,15 @@ import { useTranslation } from 'react-i18next';import { parsePreviewMetadata, type PreviewMetadataEntry } from './previewMetadata';/**- * The Details popover's body: how the image was made (prompt, seed, model,- * sampler settings) as quiet label/value rows with per-row copy and the recall- * verbs wired to the existing recall machinery. Video Details expose the- * backend's raw metadata/workflow/graph payloads instead. The query child is- * keyed by account + qualified item identity, so a closed popover (which- * unmounts it) or a changed identity aborts supported transports.+ * Show parsed image details with copy/recall, or raw video payloads. Key query children by account and qualified+ * identity so closure/identity changes abort supported transports.*/const GROUP_HOVER_VISIBLE = { opacity: 1 };/**- * Rows whose value maps onto a single-field recall verb. Rows without a- * dedicated verb (model, steps, scheduler — only recallable via All/Remix)- * keep just the copy button.+ * Offer field recall only where a dedicated verb exists; model/steps/scheduler retain copy and use All/Remix for+ * recall.*/const ENTRY_RECALL_KINDS: Partial<Record<string, { capability: keyof ImageRecallCapabilities; kind: ImageRecallKind }>@@ -107,8 +102,7 @@ const PreviewDetailsQuery = ({return { graph: null, kind: 'image', metadata: null, workflow: null };}- // Metadata carries whatever a workflow's metadata nodes added, so the- // raw record is shown whole alongside the parsed rows, like legacy.+ // Show complete raw metadata alongside parsed fields because workflows may add arbitrary entries.const [metadata, workflow] = await Promise.all([galleryImages.metadata(item.name, signal),galleryImages.workflow(item.name, signal),@@ -232,12 +226,6 @@ const ImageDetails = ({);};-/**- * The legacy metadata viewer's tab set: parsed details (images only), then the- * raw metadata record — where workflow metadata nodes land — and the source- * workflow and graph. Each tab body fills the popover's remaining height and- * scrolls inside it.- */const DetailsTabs = ({children: details,graph,@@ -307,12 +295,7 @@ const RawJsonPreview = ({ label, text }: { label: string; text: string | null })<JsonPreview label={label} maxH="100%" text={text} />);-/**- * A DataList item extended with hover-revealed value actions: recall (when- * the row maps onto a single-field recall verb) and copy. The recall button- * reuses the verb row's icon and label so both affordances read as the same- * action.- */+/** Share recall labels/icons with the verb row; reveal row-level recall and copy actions on hover. */const MetadataRow = ({entry,onRecall,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsxindex a66b17013e..624e17230c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx@@ -368,10 +368,7 @@ const render = async () => {await renderTree(client);};-// Re-renders the mounted tree against the SAME query client, so cached pages-// survive exactly as they do in production and a window change has to earn-// its data. Widget values are read by identity, so callers hand the view a-// fresh values object rather than mutating in place.+// Rerender with the same query client to preserve real cache behavior; supply fresh widget-value identities.const rerender = async () => {if (!queryClient) {throw new Error('Expected render() to have created a query client.');@@ -386,10 +383,8 @@ const setGalleryValues = (patch: Record<string, unknown>) => {state.values = { ...state.values, ...patch };};-// Applies Preview's most recent selection to the gallery values the way the-// real reducer would — item, key, and the stamped page — and re-renders. The-// selection command is a mock, so without this a second arrow press would-// still start from the item the first one left.+// Apply mocked selection results back to Gallery values so subsequent navigation starts from the newly selected+// item.const commitLastSelection = async () => {const lastCall = mocks.commands.gallery.selectItem.mock.lastCall as| [GalleryImageItem, unknown, number | undefined, boolean | undefined]@@ -676,10 +671,7 @@ describe('preview keyboard navigation boundary', () => {});it('keeps a just-completed batch navigable before the backend refetch lands', async () => {- // The batch finished and its queue item is already gone; the backend list- // (staleTime + coalesced invalidation) still only has the older image.- // recentImages is the bridge: every batch image must stay in the sequence,- // or ArrowRight from the newest skips the whole batch onto old images.+ // Bridge completed batches through recentImages until stale backend listings catch up.mocks.project.queue.items = [];mocks.project.widgetInstances.gallery.state.values.recentImages = [{@@ -727,9 +719,7 @@ describe('preview keyboard navigation boundary', () => {});it('walks the starred-only listing the selection was made in, and keeps recents out of it', async () => {- // The grid under the starred filter shows starred items only; Preview's- // arrows must step through that same list, and a fresh (unstarred)- // generation has no place in it.+ // Preview must follow the starred listing and exclude new unstarred generations.const starredNewer = { ...createImageItem('starred-newer', '2026-07-20T00:00:02.000Z'), starred: true };const starredOlder = { ...createImageItem('starred-older', '2026-07-20T00:00:01.000Z'), starred: true };@@ -760,10 +750,7 @@ describe('preview keyboard navigation boundary', () => {});it('keeps settled recents out of an infinite window anchored at a deep reveal', async () => {- // A deep reveal anchors Preview's window ~1800 rows down the board. Recents- // belong at the TOP of the listing: date-sorting them into a slice from- // the middle puts images in Preview that the grid is not showing, and- // stepping onto one files it under a board page it is nowhere near.+ // Do not merge top-of-board recents into deep windows or stamp them with unrelated page positions.const deepNewer = createImageItem('deep-newer', '2026-07-20T00:00:02.000Z');const deepOlder = createImageItem('deep-older', '2026-07-20T00:00:01.000Z');@@ -822,9 +809,7 @@ describe('preview keyboard navigation boundary', () => {});it('stamps the top of the listing on an in-flight image a deep window does not hold', async () => {- // In-flight work still merges into a deep window, and the window has no- // page for it. The page the preview opened on is 30 board pages from- // where the image will land, so it must not be what gets stamped.+ // In-flight entries in a deep window must not inherit its unrelated board page.mocks.project.queue.items = [queueItem];setGalleryValues({galleryPage: 0,@@ -847,9 +832,7 @@ describe('preview keyboard navigation boundary', () => {});it('stamps the top of the listing when the compare image is swapped in', async () => {- // The compare slot holds an arbitrary image the window may not contain.- // Reusing the deep page filed a top-of-board image under row 1800, and- // Preview then queried a slice its own selection was not in.+ // Unknown comparison positions must not inherit a deep window's page.setGalleryValues({compareImage: legacyImage('compare-top', '2026-07-24T00:00:00.000Z'),galleryPage: 0,@@ -879,12 +862,8 @@ describe('preview keyboard navigation boundary', () => {});it('holds a deep window still while the cursor walks across a page boundary and back', async () => {- // An anchored infinite window is one-way: it cannot grow upward past its- // anchor. So the anchor must stay where the selection was made, and every- // step — including one that lands on a page the boundary fetch has just- // added — stamps THAT anchor, not the row it landed on. Stamping the row- // re-keys the window at each boundary, discards the old entry, and makes- // everything the user just walked through unreachable.+ // Preserve the original infinite-window anchor across boundary steps so earlier traversed pages remain+ // reachable.const deepA = createImageItem('deep-a', '2026-07-20T00:00:04.000Z');const deepB = createImageItem('deep-b', '2026-07-20T00:00:03.000Z');const deepC = createImageItem('deep-c', '2026-07-20T00:00:02.000Z');@@ -900,15 +879,11 @@ describe('preview keyboard navigation boundary', () => {mocks.galleryItemPages = deepBoardPages([deepA, deepB], [deepC, deepD]);await render();- // Across the boundary: the fetch adds page 31, and the item selected out- // of it is still stamped with the window's anchor.await pressArrow('ArrowRight');await commitLastSelection();// One more step inside the new page.await pressArrow('ArrowRight');await commitLastSelection();- // And back, twice: the second press crosses the boundary in the direction- // the window cannot grow, and must find page 30 still loaded.await pressArrow('ArrowLeft');await commitLastSelection();await pressArrow('ArrowLeft');@@ -929,10 +904,8 @@ describe('preview keyboard navigation boundary', () => {});it('moves to the top of the listing when a selection is made there from outside Preview', async () => {- // Board, view, order, mode and search are unchanged, so the query identity- // is the same. A grid click on the newest image stamps the grid's page, 0,- // and Preview must follow it — held sticky, the anchor kept querying rows- // 1800+ for a selection at row 0.+ // Follow newly stamped selection pages even when query identity is unchanged; a grid click can move a deep+ // window back to zero.const topNewer = createImageItem('top-newer', '2026-07-22T00:00:02.000Z');const topOlder = createImageItem('top-older', '2026-07-22T00:00:01.000Z');@@ -969,10 +942,7 @@ describe('preview keyboard navigation boundary', () => {});it('hands image actions a page that keeps a deletion successor in the deep window', async () => {- // A successor is chosen from Preview's own list. Selected without a page- // it is stamped with the GRID's page — 0 once a result has landed on the- // board or the project was reloaded — and lands outside the window it- // came from: forward arrow dead, back arrow a 1800-row teleport.+ // Deletion successors from Preview need its own page context rather than the grid's unrelated page.const deepNewer = createImageItem('deep-newer', '2026-07-20T00:00:02.000Z');const deepOlder = createImageItem('deep-older', '2026-07-20T00:00:01.000Z');@@ -995,9 +965,7 @@ describe('preview keyboard navigation boundary', () => {});it('swaps the compare image in and back out without losing the deep window', async () => {- // Swapping a top-of-board image in moves the window to the top, and the- // deep image goes into the compare slot. Swapping back must return to the- // window that image was navigated in, not guess at one.+ // Remember comparison navigation context so swapping back restores the deep window.setGalleryValues({compareImage: legacyImage('compare-top', '2026-07-24T00:00:00.000Z'),galleryPage: 0,@@ -1026,8 +994,6 @@ describe('preview keyboard navigation boundary', () => {true);- // Commit the swap as the reducer would: the top image is selected at page- // 0, and the deep image is now in the compare slot.await commitLastSelection();setGalleryValues({ compareImage: legacyImage('deep-newer', '2026-07-20T00:00:02.000Z') });await rerender();@@ -1042,10 +1008,7 @@ describe('preview keyboard navigation boundary', () => {});it('does not restore a remembered page into a different listing', async () => {- // Between the swap and the swap back the user moved to another board.- // The remembered page named a window of the first board's listing;- // stamped into the second board's query it would anchor that listing- // 1800 rows down around an image that is not in it.+ // Do not reuse a comparison page after changing to another board query.setGalleryValues({compareImage: legacyImage('compare-top', '2026-07-24T00:00:00.000Z'),galleryPage: 0,@@ -1067,8 +1030,6 @@ describe('preview keyboard navigation boundary', () => {await swap();await commitLastSelection();- // The grid: another board, a click on one of its images. The compare slot- // survives that, still holding the deep image from the first board.setGalleryValues({compareImage: legacyImage('deep-newer', '2026-07-20T00:00:02.000Z'),selectedImage: { ...legacyImage('other-board-image', '2026-07-25T00:00:00.000Z'), boardId: 'board-b' },@@ -1150,9 +1111,8 @@ describe('preview keyboard navigation boundary', () => {});it('does not restore a remembered page for an item since moved to another board', async () => {- // Moving the compare image re-boards it in place and leaves the selection's- // query alone, so the memo's key still matches. The page it remembers is a- // window of the OLD board's listing, which the item is no longer in.+ // Invalidate remembered position when the comparison item moves boards, even if selection-query identity+ // remains unchanged.setGalleryValues({compareImage: legacyImage('compare-top', '2026-07-24T00:00:00.000Z'),galleryPage: 0,@@ -1392,11 +1352,8 @@ describe('preview keyboard navigation boundary', () => {};const galleryValues = mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>;- // A deep reveal from the image map stamped board page 30 onto the- // selection; starting the similarity search reset the grid to page 0.- // Carrying that stale page onto a ranked pick strands it: the item picked- // out of a ranking is nowhere near board page 30, so clearing the chip- // would anchor navigation ~1800 rows from both the selection and the grid.+ // Ranked picks must drop stale board-page positions so clearing similarity search cannot anchor far from+ // selection.galleryValues.galleryPage = 0;galleryValues.paginationMode = 'infinite';galleryValues.recentImages = [];@@ -1480,11 +1437,8 @@ describe('preview keyboard navigation boundary', () => {width: image.width,});- // In paginated mode the footer paginates the RANKING, so the grid's page- // is a rank page, not a board page — stamping it would send navigation to- // an unrelated board slice once the chip is cleared. Clearing resets the- // grid to board page 0, so that is what a ranked pick hands back: neither- // the grid's 1 nor the stale 30.+ // Rank pages are not board pages; ranked picks return board page zero rather than the current ranking or stale+ // selection page.galleryValues.galleryPage = 1;galleryValues.paginationMode = 'paginated';galleryValues.recentImages = [];@@ -1616,10 +1570,8 @@ describe('preview keyboard navigation boundary', () => {});it('keeps following a completed slot while its result is still routing', async () => {- // Completed on the backend, image not in the gallery yet: the slot is- // followed (settling) but no longer running. Preview must keep the live- // frame up in the single-frame branch rather than fall back onto the- // previous selection — and must not tile it.+ // Keep settling results in the single live frame after backend completion and before gallery arrival; do not+ // tile them.mocks.project.queue.items = [queueItem];mocks.project.settings.showProgressImagesInViewer = true;mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });@@ -1639,9 +1591,7 @@ describe('preview keyboard navigation boundary', () => {});it("shows the followed slot's own frame even when the store-wide latest frame is gone", async () => {- // A quick image batch finished next to a long video render while the tab was- // hidden: releasing the batch's slot cleared the latest frame. The video slot- // still has its frame and must not render an empty card until its next step.+ // Retain another live slot's frame when a neighboring batch releases its latest frame.mocks.project.queue.items = [queueItem];mocks.project.settings.showProgressImagesInViewer = true;mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });@@ -1675,9 +1625,7 @@ describe('preview keyboard navigation boundary', () => {});it("bridges to the next slot of a batch with the previous slot's last frame", async () => {- // Slot 2 is live but has produced no frame yet (model load, text encoding);- // the latest frame still belongs to slot 1. Without the bridge this was an- // empty card between every two items of a batch.+ // Bridge a newly followed frameless slot with the previous frame until its first progress arrives.mocks.project.queue.items = [{ ...queueItem, backendItemIds: [1, 2], completedBackendItemIds: [1] }];mocks.project.settings.showProgressImagesInViewer = true;mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 2, queueItemId: 'queue-item-live' });@@ -1712,8 +1660,7 @@ describe('preview keyboard navigation boundary', () => {expect(host?.querySelectorAll('[data-preview-filmstrip] img[src^="data:image/png"]')).toHaveLength(2);expect(followedThumb()).toBe('queue-item-live:2');- // Frames from the other slot do not move the stage: following the latest- // frame is what used to flip it several times a second.+ // Frames from other slots must not change the followed session.mocks.useProgressImage.mockReturnValue({dataUrl: 'data:image/png;base64,live',height: 64,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsxindex a3fb580e9e..da26ac7755 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsx@@ -3,13 +3,8 @@ import type { Ref } from 'react';import { Box, Flex, type BoxProps, type FlexProps, type SystemStyleObject } from '@chakra-ui/react';/**- * The chrome every preview surface shares, so the image, video, live, and empty- * branches stop carrying their own copies:- *- * - `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.+ * Share PreviewStage's fitted dot-grid surface and chrome clearance across media/live/empty states; FittedFrame+ * supplies bordered, shadowed media geometry.*/export const previewGridCss = {@@ -35,26 +30,15 @@ export const getFittedFrameCss = (width: number, height: number): SystemStyleObjconst CENTER_CHROME_INSET = 'var(--wb-center-chrome-inset, 0px)';/**- * Top padding for a media stage: its own padding plus room for the islands.- *- * It belongs on the stage rather than on the widget root so the dot grid still- * runs to every edge and passes *behind* the chrome — the same arrangement that- * lets `paddingBottom` pass it behind the footer island. Because the stage is a- * size container, `getFittedFrameCss` reads the shrunken content box and refits- * the media with no further change.+ * Reserve chrome clearance on the stage content box so fitting shrinks media while the dot grid continues behind+ * chrome.*/const getStagePaddingTop = (padding: string | undefined): string =>padding === undefined ? CENTER_CHROME_INSET : `calc(var(--chakra-spacing-${padding}) + ${CENTER_CHROME_INSET})`;/**- * `fill="parent"` is the inset arrangement (`h="full"`, used where the stage IS- * the widget body); `fill="flex"` is the framed one (`flex="1" minH="0"- * overflow="hidden"`, used where overlays float over the stage's lower edge).- *- * Both fills are positioned: absolutely-placed stage children (zoom badge,- * future overlays) anchor to the stage itself, never to whatever happens to- * contain it. (The old inset copy was static; the difference is unobservable- * at its call sites and the uniform rule is the one worth keeping.)+ * Use parent fill for inset widget bodies and flex fill for framed stages. Both establish positioning for absolute+ * overlay children.*/export const PreviewStage = ({fill,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetChrome.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetChrome.tsxindex 18b44b593c..287002c9c9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetChrome.tsx@@ -7,11 +7,8 @@ import { useTranslation } from 'react-i18next';import { usePreviewHeaderContext } from './previewHeaderStore';/**- * The preview widget's header label: `[board] / [image]` for the current- * selection (published by the view via `previewHeaderStore`), falling back to- * the static "Preview" title when nothing is selected — except in the center,- * whose view trigger already names the widget (the gallery label does the- * same).+ * Show board/image context from previewHeaderStore, falling back to Preview except where the center trigger+ * already names it.*/export const PreviewWidgetLabel = ({ region }: WidgetLabelProps) => {const { t } = useTranslation();@@ -29,9 +26,7 @@ export const PreviewWidgetLabel = ({ region }: WidgetLabelProps) => {);}- // `pe` because the frame's header row only pads to `2` and the label sits- // against the action cluster; a middle-truncated name otherwise ends flush- // with the first button.+ // Pad the truncated label away from the first header action.return (<HStack flex="1" gap="1" minW="0" pe="2"><Text flexShrink={0} fontSize="xs" fontWeight="700">diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.tsindex 49409c0102..dc3ae83458 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts@@ -34,10 +34,7 @@ describe('mergePreviewBoardItems', () => {});it('preserves relevance order for a ranked list', () => {- // A similarity result set is ordered by relevance, not by date. Re-sorting- // it here would make the arrows walk a different order from the one on- // screen. (Local generations never reach this call in ranked mode — the- // caller passes only the selection; see the anchor test below.)+ // Preserve relevance order; ranked mode receives selection only, not local generations.const first = item('image', 'first', '2026-07-21T00:00:01.000Z');const second = item('image', 'second', '2026-07-21T00:00:03.000Z', true);const third = item('image', 'third', '2026-07-21T00:00:02.000Z');@@ -60,10 +57,7 @@ describe('mergePreviewBoardItems', () => {});it('anchors a selection that the ranking does not contain, rather than losing the cursor', () => {- // A selection can be made outside the result set — an upload, an image-map- // click, or stepping off the live tile. Dropping it would leave the cursor- // pointing at nothing, which reads as both arrows going dead; keeping it- // at the head lets one press move into the ranked list.+ // Keep out-of-ranking selection at the head so navigation can enter the ranked list.const ranked = item('image', 'ranked', '2026-07-21T00:00:01.000Z');const outsider = item('image', 'outsider', '2026-07-21T00:00:09.000Z');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex 567f9b3cbe..c76844dac5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -169,11 +169,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const displayBoardId = selectedItem?.boardId ?? 'none';const hasSelectedItem = selectedItem !== null;const selectedImageQuery = getGallerySelectedImageQuery(galleryValues);- // The gallery's live similarity search: when one is active the grid shows a- // ranked result set, and navigation has to walk that same list. Memoized on- // the raw value because parsing mints a fresh object each call, which would- // otherwise re-derive the whole navigation list on every unrelated gallery- // change (every recentImages tick during a generation, for one).+ // Memoize parsed ranking by raw value so unrelated Gallery updates do not rebuild navigation.const gallerySemanticQuery = useMemo(() => getGallerySemanticImageQuery({ semanticImageQuery: galleryValues.semanticImageQuery }),[galleryValues.semanticImageQuery]@@ -277,18 +273,8 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {return boardItems.find((item) => toGalleryItemKey(item) === selectedItemKey) ?? selectedItem;}, [boardItems, selectedItem, selectedItemKey]);const exitCompare = useCallback(() => gallery.setCompareItem(null), [gallery]);- // The page the item now in the compare slot was selected at, when Preview- // put it there by swapping. The window may not hold that item any more —- // swapping a top-of-board image in moves the window to the top — so a swap- // back could only guess at its page. This is not a guess: it is the window- // the item was navigated in, and restoring it puts the arrows back where- // they were before the first swap. A page names a window of ONE query,- // though: restored into a different board, view, order, mode or search it- // would anchor that listing 1800 rows down around an image from another,- // so the memo is only honoured in the query it was recorded in — and only- // while the item is still in that query's board. Moving the compare image- // to another board re-boards it in place without touching the selection's- // query, so the key alone would still match.+ // Remember the comparison item's original page for swap-back, but only within its original query and board. Item+ // moves can invalidate the page without changing query identity.const swappedOutRef = useRef<{ boardId: string; key: GalleryItemKey; page: number; queryKey: string } | null>(null);const swapCompareImages = useCallback(() => {if (selectedItem?.kind === 'image' && compareImage) {@@ -379,17 +365,13 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {);const isFilmstripVisible = getPreviewFilmstripVisible(previewValues);- // Drop-to-compare: any all-image gallery-item drag dropped on the frame's drop zone- // arms that image for comparison. The drag payload only carries names, so- // the full contract is fetched before dispatching.+ // Hydrate dropped image names before arming comparison with a complete item contract.const handleCompareDrop = useCallback((event: DragEndEvent) => {if (selectedItem?.kind !== 'image') {return;}- // The image on screen is refused, so this can never resolve to the- // selection itself.const resolution = resolvePreviewCompareDrop(event.active.data.current,event.over?.data.current ?? null,@@ -452,10 +434,8 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);const headerItemName = shouldFollowLive ? null : (selectedItem?.name ?? null);- // Publish the header chrome context (the "[board] / [image]" label and the- // action strip's image + actions) for the widget frame; the chrome renders- // outside this view, so an external store is the sync channel. Cleared on- // unmount so stale chrome never outlives us.+ // Publish selection/actions to hoisted chrome through an external store; clear on unmount to prevent stale+ // headers.const filmstrip = useMemo<PreviewFilmstripProps | null>(() =>isFilmstripVisible && density !== 'minimal'@@ -578,16 +558,12 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {}, [runtime.commands, runtime.hotkeys, selectedItem?.kind, t]);return (- // No padding and no inner card: the dot-grid surface is the widget floor- // and runs to every edge. `containerType` anchors the details panel's- // `cqh` cap to the widget rather than the viewport.+ // Let the dot grid fill the widget; containerType bounds Details cqh sizing to this surface.<Box ref={rootRef} containerType="size" h="full" position="relative" w="full">- {/* Floated, the window is usually parked over a maximized work surface- or on another display, where the top bar's rail is out of view — so- the window that shows the result also shows that it is coming. It- overlays the body's top edge, directly under the title bar's divider,- so appearing costs no reflow. Docked, the top bar's rail is in view- and a second one would only be noise. */}+ {/*+ * Show progress beneath floating Preview's title bar when the main topbar may be out of view; overlay it+ * without reflow.+ */}{region === 'floating' ? <QueueProgressRail css={FLOATING_RAIL_SX} /> : null}{/* Single always-mounted keyboard boundary: DOM focus survives swapsbetween the live, selected, and compare branches, so arrow@@ -679,9 +655,7 @@ const SelectedImagePreview = ({() => (previewImage ? { itemKey: toGalleryItemKey(item), kind: 'image', source: previewImage } : null),[item, previewImage]);- // The last denoise frame of the run that produced this image, when it finished- // moments ago: painted over the finished image until that has decoded, so the- // denoise→done boundary changes only the pixels inside the frame.+ // Bridge finished-image decoding with its run's final denoise frame so only pixels change at completion.const swapProgressImage = useQueueItemSwapProgressImage(item.sourceQueueItemId, item.name);const holdSource = useMemo(() => progressImageToStreamingSource(swapProgressImage, item.name),@@ -752,14 +726,8 @@ interface SelectedMediaPreviewProps {}/**- * The one media arrangement, shared by selected items and the live preview:- * the stage fills, and the filmstrip docks under it as a row of its own, so- * toggling the strip refits the media rather than covering it. Live and- * finished renders MUST pass through the same scaffold — the denoise→done- * boundary may change only the pixels inside the frame, never the geometry- * around it. Several live sessions are the filmstrip's leading thumbs, never- * a grid: the stage shows one of them large and the strip keeps the rest in- * reach.+ * Use the same stage/filmstrip scaffold for live and finished media so completion changes pixels, not geometry;+ * multiple sessions remain filmstrip choices.*/const PreviewMediaScaffold = ({ children }: { children: ReactNode }) => (<Flex direction="column" h="full" minH="0" position="relative" w="full">@@ -822,12 +790,7 @@ const SelectedMediaPreview = ({</PreviewMediaScaffold>);-/**- * The single-session live preview: the denoise stream rendered exactly like a- * finished item — same scaffold, same frame chrome, no badge — so the moment- * generation completes, only the pixels change. Saved-image navigation- * remains in the filmstrip.- */+/** Match finished-frame geometry for live previews; saved-image navigation stays in the filmstrip. */const LivePreview = ({density,filmstrip,@@ -839,9 +802,7 @@ const LivePreview = ({placeholder: QueueActiveSession;shouldAntialiasProgressImage: boolean;}) => {- // The followed slot's own frame, not the store-wide latest: with two slots- // live (a long video next to a quick image batch) the latest belongs to- // whichever stepped last, and releasing that slot must not blank this one.+ // Use the followed slot's own frame so another slot's progress or release cannot replace it.const progressImage = useQueueItemProgressImage(placeholder.queueItemId, placeholder.itemIndex);// The previous slot's last frame stands in until this slot produces one of// its own (model load, text encoding) — otherwise a sequential batch dropsdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewZoomMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewZoomMenu.tsxindex 1533444280..79f30709b9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewZoomMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewZoomMenu.tsx@@ -12,10 +12,8 @@ const ZOOM_PRESETS = [100, 200, 400] as const;const MENU_POSITIONING = { placement: 'bottom-start' } as const;/**- * The header's zoom readout: the fitted image's percent of its own pixels, or- * the loupe's current zoom, with fit and the actual-pixel presets one click- * away. The stage keeps the gestures (wheel, pinch, double-click); this is the- * legible number and the keyboard route.+ * Expose fitted/actual zoom and keyboard presets in the header; the stage owns wheel, pinch, and double-click+ * gestures.*/export const PreviewZoomMenu = ({ zoom }: { zoom: PreviewZoomControls }) => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsxindex 50ea9af4f1..8d4ad57fa2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx@@ -16,10 +16,8 @@ interface LivePreviewFollow {gallerySessions: QueueProgressSession[];pinnedSessionId: string | null;/**- * The session on screen while live-follow is on — pinned, else the running- * session that started last, else the first settling, in the gallery's tile- * order — or null. Gallery and Preview both step from it, so it is decided- * once, here.+ * Shared live target: pinned, then newest-started running session, then first settling session in gallery order,+ * else null.*/followedSessionId: string | null;/** Turns live-follow on and pins `sessionId`: a tile click, or an arrow step onto a tile. */@@ -60,11 +58,7 @@ export const LivePreviewFollowProvider = ({ children }: { children: ReactNode })setSelection({ projectId, sessionId: null });}const pinnedSessionId = isStale ? null : selection.sessionId;- // With several GPUs the stage follows the newest running session (highest- // backend item id — start order for the FIFO queue), so a busy box keeps the- // newest work in view without anyone choosing, and only moves at session- // boundaries. Following whichever slot stepped last would flip the stage- // several times a second (see activeProgressTargetStore). A pin wins.+ // Follow the highest-id running session (FIFO start order), not the latest progress frame; pins take precedence.const newestRunningSessionId = sessions.filter((session) => session.state === 'running').at(-1)?.id ?? null;const preferredSessionId = pinnedSessionId ?? newestRunningSessionId;const followedSessionId = enableddiff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/loupeGestures.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/loupeGestures.tsindex d7f2a9d90e..b4546bde68 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/loupeGestures.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/loupeGestures.ts@@ -1,21 +1,8 @@import type { PanZoomPoint } from '@workbench/panZoom';-/**- * Pointer bookkeeping shared by the preview's two loupes — the stage loupe and- * the side-by-side comparison one. Both track every finger that is down so a- * second one can turn a pan into a pinch; only the coordinate space they zoom- * in differs.- */+/** Share pointer tracking between stage and comparison loupes; each uses its own zoom coordinate space. */-/**- * Records a pointer that just went down and reports the pair that should pinch,- * once there is one.- *- * The first finger of a touch (and any mouse press) starts a fresh set: a- * pointer whose release lands outside the surface is never seen going up, so- * this is what stops a stale entry from pairing into a phantom pinch on the- * next touch.- */+/** Reset on the first touch or mouse press to discard pointers whose releases were missed before arming a pinch. */export const trackPointerDown = (pointers: Map<number, PanZoomPoint>,event: { clientX: number; clientY: number; isPrimary: boolean; pointerId: number }@@ -36,10 +23,8 @@ export const trackPointerDown = (};/**- * Capture, tolerating a pointer that is already gone: the browser can queue a- * `pointerdown` behind the release of another finger, and `setPointerCapture`- * throws for a pointer that is no longer active. A gesture that misses its- * capture still tracks — it only loses the fingers that wander off the surface.+ * Tolerate capture failure for already-released pointers; uncaptured gestures still work while pointers remain on+ * the surface.*/export const capturePointer = (element: Element, pointerId: number): void => {try {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.test.tsindex 3e73cfc8bf..75ef9cf96c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.test.ts@@ -52,9 +52,8 @@ describe('resolvePreviewCompareDrop', () => {});it('refuses to compare the previewed image with itself', () => {- // Not merely a no-op: arming a comparison pauses live-follow, so this used- // to switch off in-progress images and leave a comparison that sprang open- // on the next selection.+ // Self-comparison must be refused because it pauses follow and can reveal a latent comparison on later+ // selection.const activeData = getGalleryItemDragData([{ kind: 'image', name: 'shown.png' }]);expect(resolvePreviewCompareDrop(activeData, PREVIEW_COMPARE_DROP_DATA, 'shown.png')).toBeNull();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.tsindex 0d8e516750..43422a4b9d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.ts@@ -1,11 +1,5 @@import { isGalleryImageDragData } from '@features/gallery/utility';-/**- * dnd-kit contract for the preview's drop-to-compare target: dropping any- * all-image gallery-item drag (gallery grid or preview filmstrip thumbs) onto the- * preview frame arms it as the comparison image.- */-export const PREVIEW_COMPARE_DROP_ID = 'preview-compare-target';export interface PreviewCompareDropData {@@ -18,14 +12,8 @@ export const isPreviewCompareDropData = (value: unknown): value is PreviewCompartypeof value === 'object' && value !== null && (value as PreviewCompareDropData).kind === 'preview-compare-target';/**- * The image to arm for comparison, or null when the drag/drop pair is not ours- * — or when the drop would compare the previewed image with itself. That is not- * merely a no-op: arming a comparison pauses live-follow, so a self-drop would- * quietly switch off in-progress images and leave a comparison that springs- * open on the next selection.- *- * `currentImageName` is required rather than optional so every caller has to- * say what is on screen; a caller with nothing selected passes null.+ * Reject foreign drops and self-comparison, which would pause follow despite displaying nothing. Require callers+ * to provide currentImageName or null.*/export const resolvePreviewCompareDrop = (activeData: unknown,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewDensity.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewDensity.tsindex 88689a7ed9..a351d7c5c4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewDensity.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewDensity.ts@@ -3,15 +3,8 @@ import type { WorkbenchRegion } from '@workbench/widgetContracts';import { useCallback, useLayoutEffect, useRef, useState, type Ref } from 'react';/**- * Single source of truth for the preview widget's responsive behavior. Every- * zone component (frame, filmstrip, footer) branches on this value instead of- * defining its own breakpoints, so side-panel ergonomics are tuned in one place.- *- * - `full` — center region with room to breathe: full action strip,- * filmstrip, metadata rows, footer message line.- * - `compact` — side panels and narrow center: star + overflow menu,- * one-line summaries, no footer message line.- * - `minimal` — very narrow: frame + hairline progress + prev/next only.+ * Share density across Preview zones: full exposes all controls, compact reduces actions/summaries, and minimal+ * keeps frame, progress, and navigation.*/const isRailRegion = (region: string): boolean => region === 'left' || region === 'right';@@ -38,11 +31,7 @@ export const getPreviewDensity = ({return widthPx >= PREVIEW_FULL_MIN_WIDTH_PX ? 'full' : 'compact';};-/**- * Observes the widget root's width and returns the derived density. The- * ResizeObserver lives in a ref callback (with cleanup) so there is no effect- * to keep in sync; state only changes when the density bucket changes.- */+/** Observe root width with a cleaned-up ref callback; update state only when its density bucket changes. */export const usePreviewDensity = (region: WorkbenchRegion): { density: PreviewDensity; rootRef: Ref<HTMLDivElement> } => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.tsindex b7d9bb1f13..a2d8ddd6e7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts@@ -31,12 +31,8 @@ export interface PreviewItemPosition {}/**- * Header context published by the preview view so the widget frame's chrome- * (label + header actions) can render the current selection without refetching- * boards or re-instantiating image actions. The preview is a singleton widget- * (`allowMultiple: false`), so one module-level store is safe. Cleared when- * the view unmounts or nothing is selected; the chrome falls back to the- * static title and hides the action strip.+ * Publish singleton Preview selection/actions for external chrome without refetching. Clear on unmount or empty+ * selection so static chrome returns.*/export interface PreviewHeaderContext {/** The selected item with board/star context, ready for common actions. */@@ -47,11 +43,7 @@ export interface PreviewHeaderContext {copyCurrentVideoFrame: (() => void) | null;isVideoFrameCopyAvailable: boolean;itemName: string | null;- /**- * Opens the view's full image context menu anchored at viewport coordinates.- * The header's "image actions" dropdown reuses the exact right-click menu —- * one source of truth for every image verb.- */+ /** Open the view's shared image context menu from header actions at viewport coordinates. */openItemMenu: ((x: number, y: number) => void) | null;position: PreviewItemPosition | null;/** Null unless the selection is an image the loupe can zoom. */@@ -88,11 +80,7 @@ registerAccountOwnedResource({export const usePreviewHeaderContext = (): PreviewHeaderContext => store.useSelector((snapshot) => snapshot);-/**- * The view's hot-path readouts, written straight from ref callbacks and the- * loupe so a wheel tick re-renders the header's zoom menu and nothing else —- * never the view, its filmstrip, or the context menu.- */+/** Publish hot-path zoom readouts directly so wheel ticks update only the zoom menu. */export interface PreviewStageContext {/** The media stage; the Details popover keeps within it, off the filmstrip. */stageElement: HTMLElement | null;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.tsindex fc85bf9dfe..322bd39feb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.ts@@ -1,8 +1,6 @@/**- * Tolerant display parser for image metadata (`GET /images/i/{name}/metadata`).- * The payload is untyped and varies by generation path (generate, canvas,- * workflow, upscale), so every field is optional and unknown shapes are simply- * skipped — the raw record is still available for the panel's JSON disclosure.+ * Parse variable untyped image metadata tolerantly; skip unknown fields while retaining the complete raw record+ * for JSON display.*/export interface PreviewMetadataEntry {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.test.tsindex 580a9c5cb7..bbe04dc930 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.test.ts@@ -95,8 +95,7 @@ describe('video span playback state', () => {expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token: 1 });expect(listener).toHaveBeenCalledTimes(1);- // The player republishes from every play/pause handler and from the request itself;- // a report identical to the one standing is not a change a subscriber should render.+ // Deduplicate identical playback reports so repeated handlers do not rerender subscribers.publishVideoSpanPlaybackState({ isPlaying: true, pause, token: 1 });expect(listener).toHaveBeenCalledTimes(1);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.tsindex 35cf1c8dd3..f563eccaf5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.ts@@ -1,24 +1,8 @@import type { GalleryItemKey } from '@features/gallery';/**- * "Play this video item from A to B, on a loop" — the gesture behind the Video panel's- * play buttons, which ask Preview to show what a trim actually selected.- *- * An ephemeral intent aimed at whichever player is mounted, not a piece of state: it is- * module-scoped so it is never replayed in a later session, and it carries a token so a- * repeated press on an unchanged window still reads as a new request. The publisher lives- * in App (it has to select the item and raise the widget first); the consumer is this- * widget's `<video>` element, which is why the channel is owned here rather than beside- * the gallery's reveal request — that one's consumer is the gallery grid itself.- *- * The timestamp bounds it. The publisher raises Preview before publishing, so a player- * mounts promptly; a request read long afterwards belongs to a gesture the user has moved- * on from, and honouring it would start unmuted audio out of nowhere.- *- * The return channel is the playback STATE below: the player that honoured a request- * reports, under that request's token, whether the window is running and how to stop it,- * so the button that made the request can show a pause control for as long as — and only- * as long as — its own loop is the one on screen.+ * Publish ephemeral tokenized trim-loop intents after selecting media and raising Preview. Expire stale requests+ * to prevent unexpected delayed audio; the player reports running state and stop control under the same token.*/export interface VideoSpanPlaybackRequest {@@ -81,15 +65,8 @@ export const subscribeVideoSpanPlaybackRequests = (listener: () => void): (() =>};/**- * What the player is doing with the request it last honoured. `null` between loops: before- * any request has been acted on, once the user takes the playhead out of the window, and- * whenever the player leaves the screen.- *- * `isPlaying` follows the element's own `play`/`pause` events rather than the request, so- * a pause from the native controls — or an autoplay refusal — shows in the panel as- * faithfully as one from the panel's button, and a native play resumes it. `pause` leaves- * the loop armed for the same reason the autoplay case does: the native play control then- * resumes the selection, not the whole clip.+ * Report actual element playback for the current loop, null before use, after leaving its span, or while hidden.+ * Pausing keeps the loop armed for native resume.*/export interface VideoSpanPlaybackState {isPlaying: boolean;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsxindex e31408518f..59fbbbdf42 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx@@ -127,8 +127,6 @@ describe('useCompareLoupe', () => {touch('pointerdown', 1, 50, { isPrimary: true });touch('pointerdown', 2, 150);});- // The fingers double their 100px spread around the pane's centre, and the- // pane that was not touched follows — one transform drives both eyes.await interact(() => {touch('pointermove', 1, 0);touch('pointermove', 2, 200);@@ -177,8 +175,7 @@ describe('useCompareLoupe', () => {expect(images[0]?.style.transform).toBe('translate(-200px, -150px) scale(3)');await interact(() => touch('pointerup', 2, 250));- // The remaining finger pans both panes from where it is, then lifts over- // another part of the page — which the pane itself never sees.+ // Track the remaining finger through pan and release outside both panes.await interact(() => touch('pointermove', 1, -30));expect(images[0]?.style.transform).toBe('translate(-180px, -150px) scale(3)');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.tsindex 10184c5d88..4483d2d185 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts@@ -12,14 +12,8 @@ import { useCallback, useRef, useState, type MouseEvent, type PointerEvent as Reimport { capturePointer, releasePointer, trackPointerDown } from './loupeGestures';/**- * Shared zoom/pan for the side-by-side comparison panes: one transform, kept- * in image-fraction space (scale is unitless; translation is a fraction of the- * pane's rendered size), applied imperatively to every registered pane. Zoom- * into the left eye and the right pane's left eye follows. Gated by the caller- * to matching-dimension pairs, where fraction space is exact.- *- * On a touch screen two fingers pinch — zooming and panning in one gesture,- * against the pane they landed on — and one finger pans an already-zoomed pair.+ * Apply one imperative fraction-space transform to matching-size comparison panes. Pinch zooms/pans together; one+ * finger pans an already-zoomed pair.*/const MAX_ACTUAL_ZOOM = 8;@@ -36,11 +30,7 @@ interface PaneElements {image: HTMLImageElement | null;}-/**- * A live two-finger pinch. Like the transform it drives, the gesture is- * measured in the fraction space of the pane it started on, all of it captured- * up front so each move resolves to one transition from where it began.- */+/** Capture pinch origins in pane-fraction space so moves derive from the start rather than compounding deltas. */interface PinchGesture {paneIndex: 0 | 1;pointerIds: [number, number];@@ -181,13 +171,7 @@ export const useCompareLoupe = ({// One stable set of callbacks per pane index; wheel listeners need manual// attachment (`passive: false`) so ref callbacks with cleanup own them.- /**- * The pane a two-finger gesture belongs to: the one containing its midpoint,- * so a pinch spanning both panes is measured in the pane it is centred on- * rather than in whichever pane the second finger happened to land on (which- * would anchor the zoom on that pane's edge, and differently depending on the- * order the fingers touched down).- */+ /** Choose the pane containing the pinch midpoint, independent of finger arrival order. */const getGesturePane = useCallback((center: PanZoomPoint, fallback: 0 | 1): 0 | 1 => {for (const index of [0, 1] as const) {const rect = panesRef.current[index].frame?.getBoundingClientRect();@@ -289,10 +273,7 @@ export const useCompareLoupe = ({}const onWheel = (event: WheelEvent): void => handleWheel(node, event);- // A finger only reports to the pane while it is over it (or captured by- // it), so the document is what keeps the tracked set honest: it sees a- // finger that crosses to the other pane or lifts off both, either of- // which would otherwise leave a phantom entry to pinch against.+ // Track document-level pointers across panes and outside releases to avoid phantom pinch entries.const handleDocumentPointerMove = (event: PointerEvent): void => {const pointers = pointersRef.current;@@ -336,12 +317,8 @@ export const useCompareLoupe = ({};/**- * Arms a pinch on two down pointers, measured in the fraction space of the- * pane the gesture is centred on (`fallbackPane` decides only when the- * midpoint is over neither). Returns null — leaving no gesture — if that- * pane cannot be measured or the fingers landed on the same spot. Both- * fingers are captured for the whole gesture, so one that strays off the- * pane keeps driving it instead of silently sticking.+ * Measure/capture both fingers in the midpoint pane, using fallback only outside both. Reject unmeasurable or+ * coincident-pointer gestures.*/const beginPinch = (fallbackPane: 0 | 1, pointerIds: [number, number]): PinchGesture | null => {const first = pointersRef.current.get(pointerIds[0]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsxindex 0fc087b827..168e2c973c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx@@ -130,8 +130,6 @@ describe('usePreviewLoupe', () => {const { content, stage } = await mountHarness();await interact(() => startPinch(stage));- // Both fingers move outward by 50px: a 100px start becomes 200px, so the- // image doubles around the midpoint they started from.await interact(() => {touch(stage, 'pointermove', 1, 100, 150);touch(stage, 'pointermove', 2, 300, 150);@@ -150,8 +148,6 @@ describe('usePreviewLoupe', () => {});expect(content.style.transform).toBe('translate(-200px, -150px) scale(3)');- // Sliding both fingers 40px right at the same spread pans by 40 without- // changing the zoom — one gesture, both transforms.await interact(() => {touch(stage, 'pointermove', 1, 90, 150);touch(stage, 'pointermove', 2, 390, 150);@@ -170,8 +166,7 @@ describe('usePreviewLoupe', () => {});await interact(() => touch(stage, 'pointerup', 2, 350, 150));- // The remaining finger keeps moving from where it is — no jump back to- // where it first went down, and no release-and-retouch to start panning.+ // Continue panning from the remaining finger's current position after pinch.await interact(() => touch(stage, 'pointermove', 1, 70, 160));expect(content.style.transform).toBe('translate(-180px, -140px) scale(3)');@@ -180,9 +175,7 @@ describe('usePreviewLoupe', () => {it('does not pair a finger whose release was never seen with the next touch', async () => {const { content, stage } = await mountHarness();- // Belt and braces for a pointer whose end went missing entirely — the first- // finger of the next touch clears it, so it cannot pinch against a later- // one. (An ordinary release anywhere on the page is seen; see below.)+ // Clear missed pointer endings on the next first touch to prevent phantom pinches.await interact(() => touch(stage, 'pointerdown', 1, 150, 150, { isPrimary: true }));await interact(() => touch(stage, 'pointerdown', 2, 250, 150, { isPrimary: true }));await interact(() => touch(stage, 'pointermove', 2, 350, 150));@@ -194,10 +187,7 @@ describe('usePreviewLoupe', () => {const { content, stage } = await mountHarness();await interact(() => touch(stage, 'pointerdown', 1, 150, 150, { isPrimary: true }));- // The finger slides off the stage — over a neighbouring panel, which is- // where it now reports. Its tracked position has to follow it there, or the- // pinch below arms on a 100px separation instead of the real 200px and- // doubles every subsequent zoom.+ // Track off-stage positions so pinch separation reflects actual finger distance.await interact(() => touch(stage, 'pointermove', 1, 50, 150, { target: document.body }));await interact(() => touch(stage, 'pointerdown', 2, 250, 150));await interact(() => {@@ -217,9 +207,7 @@ describe('usePreviewLoupe', () => {touch(stage, 'pointermove', 2, 350, 150);});await interact(() => touch(stage, 'pointerup', 2, 350, 150));- // The remaining finger pans, then lifts over another panel: the stage never- // sees that release, so nothing there can end the pan — and a pan left- // armed would keep dragging the image on the next unrelated pointer move.+ // End panning on releases outside the stage to prevent unrelated later movement from dragging media.await interact(() => touch(stage, 'pointerup', 1, 50, 150, { target: document.body }));const transformAtRelease = content.style.transform;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.tsindex ec4f34b899..6af119bdfa 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts@@ -20,16 +20,8 @@ import {import { capturePointer, releasePointer, trackPointerDown } from './loupeGestures';/**- * Lightweight zoom/pan for the preview: wheel zooms around the cursor,- * left-drag pans, double-click toggles fit ⇄ 100%, and on a touch screen two- * fingers pinch (zooming and panning in one gesture) while one finger pans an- * already-zoomed image. The *stage* (the dot-grid area) is the viewport — the- * fitted, framed image scales and pans across the whole stage and clips at its- * edges, instead of being inspected through its own small wrapper. Implemented- * as a CSS transform applied imperatively (rAF-batched) to the fitted content- * box; high-frequency pointer data never passes through React state — only the- * rounded zoom percent does, for the corner chip. `scale === 1` is "fit"; the- * chip reports percent of the image's actual pixels.+ * Use the whole stage for wheel zoom, drag pan, fit/100% toggle, and touch pinch. Apply rAF-batched CSS transforms+ * outside React; publish only rounded actual-pixel zoom, with scale 1 meaning fit.*//** Max zoom, as a fraction of the image's actual pixel size. */@@ -58,12 +50,7 @@ interface LoupeTransform {ty: number;}-/**- * A live two-finger pinch. Everything the gesture needs is captured when it- * starts — the transform it grew from, the pointers' separation and midpoint,- * and the client-space origin of the content box — so each move resolves to a- * single transition from that origin instead of compounding deltas.- */+/** Capture transform, separation, midpoint, and content origin once so pinch moves resolve from a fixed baseline. */interface PinchGesture {/** Client-space position of the content box's untransformed origin. */originLeft: number;@@ -109,10 +96,8 @@ export const usePreviewLoupe = ({const lastSourceTokenRef = useRef<string | null | undefined>(undefined);const [zoomState, setZoomState] = useState<PreviewZoomState>(FIT_UNMEASURED);const publishedRef = useRef<PreviewZoomState>(FIT_UNMEASURED);- // Live read ports, so the gesture math keeps one identity across images. A- // dependency instead would re-create the stage ref callback on every source- // swap, and its cleanup cancels the frame that clears the old transform —- // leaving the new image drawn zoomed while the readout said fit.+ // Keep gesture/ref identity stable across images; callback cleanup must not cancel the frame clearing an old+ // transform.const naturalWidthRef = useRef(naturalWidth);// eslint-disable-next-line react/refsnaturalWidthRef.current = naturalWidth;@@ -193,10 +178,8 @@ export const usePreviewLoupe = ({}, [getActualZoom, publish]);/**- * Called during render with a token identifying the displayed image (or null- * while the loupe is inapplicable, e.g. live frames). A token change resets- * the transform in place — no remount, so the img element (and its decoded- * pixels) survive selection changes without a flash.+ * Reset transforms when the displayed-image token changes without remounting decoded media; null disables the+ * loupe.*/const syncDisplayedSource = (token: string | null): void => {if (lastSourceTokenRef.current === token) {@@ -204,16 +187,11 @@ export const usePreviewLoupe = ({}lastSourceTokenRef.current = token;- // A gesture in flight is measured against the old image's transform and- // layout, so it goes even when the transform itself is already fit —- // otherwise it would keep zooming the new image around the old one's- // centre. Dropping it leaves the fresh fit alone until the fingers lift.+ // Discard old-image gestures even at fit so remaining touches cannot transform the new image.panPointerRef.current = null;pinchRef.current = null;transformRef.current = { scale: 1, tx: 0, ty: 0 };- // Through `apply`, not a bespoke frame: the frame re-derives the style from- // the transform ref when it runs, so a wheel tick that lands before it- // still wins — and the new image's fit percent is measured once laid out.+ // Schedule reset through apply so intervening wheel updates win and fitted percent uses current layout.apply();};@@ -305,10 +283,7 @@ export const usePreviewLoupe = ({useImperativeHandle(controlsRef, () => ({ reset, zoomTo, zoomToActual }), [reset, zoomTo, zoomToActual]);- // The fitted size follows the stage, so the readout has to be re-measured- // whenever the content box is laid out at a new size. `apply` rather than- // `publish`: it re-derives the DOM transform from the transform ref too, so- // a re-attach can never leave the style and the readout disagreeing.+ // Reapply transform and remeasure zoom when fitted content resizes or reattaches so DOM and readout agree.const contentRefCallback = useCallback((node: HTMLDivElement | null) => {contentRef.current = node;@@ -339,12 +314,7 @@ export const usePreviewLoupe = ({};}, []);- /**- * Arms a pinch on two down pointers and returns it, or null — leaving no- * gesture — if the stage cannot be measured or the fingers landed on the same- * spot. Both fingers are captured for the whole gesture, so one that strays- * off the stage keeps driving it instead of silently sticking.- */+ /** Capture both pinch pointers; reject unavailable stage geometry or coincident fingers. */const beginPinch = useCallback((pointerIds: [number, number]): PinchGesture | null => {const stage = stageRef.current;const content = contentRef.current;@@ -428,9 +398,7 @@ export const usePreviewLoupe = ({[beginPan, beginPinch]);- // The wheel listener must be attached manually with `passive: false` —- // React's synthetic wheel events cannot preventDefault. Ref callback with- // cleanup, so there is no effect to keep in sync.+ // Attach non-passive wheel handling with ref cleanup because React synthetic wheel cannot prevent defaults.const stageRefCallback = useCallback((node: HTMLDivElement | null) => {stageRef.current = node;@@ -453,12 +421,8 @@ export const usePreviewLoupe = ({);};- // A finger only reports to the stage while it is over it (or captured by- // it), so a pointer that wanders onto another panel would otherwise leave- // the position last seen — and, if it lifts out there, the pointer itself- // — in the tracked set, ready to arm the next pinch from a phantom start.- // The document sees every pointer wherever it goes, so it is what keeps- // the set honest; the stage's own handlers still drive the gesture.+ // Track pointer positions/releases document-wide so off-stage movement cannot leave phantom pinch origins;+ // stage handlers still drive gestures.const handleDocumentPointerMove = (event: PointerEvent): void => {const pointers = pointersRef.current;@@ -490,14 +454,8 @@ export const usePreviewLoupe = ({);/**- * A pinch can begin with one finger already down on the image, which dnd-kit's- * pointer sensor has taken as the start of dragging it out of the preview. The- * sensor listens for `pointercancel` on the document, so dispatching one there- * aborts that drag — pending or already started — without disturbing the- * stage's own handlers, which never see a document-targeted, non-bubbling- * event. Only a finger that landed on the image itself can have armed the- * sensor, so only then is there a drag to abandon — the event reaches every- * sensor on the page, and nothing else here should have to pay for it.+ * Cancel dnd's pending/active image drag when pinch takes over using a document-targeted non-bubbling+ * pointercancel. Only do so when a finger began on the image, leaving stage handlers untouched.*/const cancelPointerDrag = (): void => {const stage = stageRef.current;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.tsindex 5f1c2546f0..4472dea899 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts@@ -29,17 +29,9 @@ import { useInfiniteQuery, useQuery } from '@tanstack/react-query';import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';/**- * Everything behind the preview's left/right stepping, in one place: the board- * items query, the local/backend merge, the sequence + cursor, the navigate- * action with its boundary-page fetch, and the neighbor prefetch. The view- * consumes the result.- *- * The sequence is the gallery's own order — the in-progress sessions, the- * starred strip, then the listing — so the arrows cross the grid's seams the- * same way. One divergence: Preview walks the whole bounded strip query,- * while the grid shows up to three rows of it (a width it alone knows) and- * folds the rest behind "Show all". Gallery selection and the live-follow- * preference remain the sources of truth; nothing here stores a cursor.+ * Own Preview query merging, cursor derivation, boundary fetches, and neighbor prefetch. Follow Gallery's+ * session/starred/list order, but traverse the full bounded starred query beyond the grid's folded rows;+ * selection/follow remain authoritative.*/const EMPTY_PREVIEW_ITEMS: GalleryItem[] = [];@@ -97,13 +89,8 @@ export const mergePreviewBoardItems = (): GalleryItem[] => {const backendKeys = new Set(backendItems.map(toGalleryItemKey));- // Relevance order IS the list: re-sorting it by date would reorder what the- // user is looking at, and local generations are not members of a ranked- // result set at all (the gallery grid overlays none of them either). The- // caller still passes the SELECTED item, which is kept when the ranking does- // not contain it — a selection made outside the result set (an upload, an- // image-map click, stepping off the live tile) would otherwise leave the- // cursor pointing at nothing, which reads as both arrows going dead.+ // Preserve ranking order and exclude local generations; retain out-of-ranking selection as a cursor anchor so+ // arrows remain usable.if (isRanked) {const anchors = localItems.filter((item) => !backendKeys.has(toGalleryItemKey(item)));@@ -193,23 +180,15 @@ export const usePreviewNavigation = ({const navigationContextKey = `${followedSessionId ?? ''}:${selectedItemKey ?? ''}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${selectedImageQuery.paginationMode}:${selectedImageQuery.page}:${selectedImageQuery.searchTerm}:${navigationStarredOnly}:${navigationSemanticKey}`;const navigationQueryKey = `${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${selectedImageQuery.paginationMode}:${selectedImageQuery.searchTerm}:${navigationStarredOnly}:${navigationSemanticKey}`;- // Lets a boundary fetch that resolves after the user has moved on compare the- // context it started in against the one now on screen, and drop its stale- // result. Written from a LAYOUT effect: layout effects run synchronously- // inside the commit, so no promise continuation can observe the new UI with- // the old key — a passive effect leaves a post-paint gap where exactly that- // interleaving happens. (Render-phase ref writes are rejected by the- // compiler, and an effect event cannot be called from a promise- // continuation.)+ // Publish navigation context in layout effect so boundary-fetch continuations cannot observe new UI with a stale+ // fence.const navigationContextKeyRef = useRef(navigationContextKey);useLayoutEffect(() => {navigationContextKeyRef.current = navigationContextKey;}, [navigationContextKey]);- // A paginated navigation stays anchored to the page the preview opened on,- // and re-anchors only when the underlying query identity changes. Derived- // state rather than a ref so the compiler can see the dependency.+ // Keep paginated navigation anchored until query identity changes; expose the dependency as derived state.const [navigationAnchor, setNavigationAnchor] = useState({page: selectedImageQuery.page,queryKey: navigationQueryKey,@@ -220,16 +199,8 @@ export const usePreviewNavigation = ({setNavigationAnchor({ page: selectedImageQuery.page, queryKey: navigationQueryKey });}- // Stickiness is a PAGINATED concern: stepping across pages stamps each- // item's own page, and the window must not move out from under the cursor- // when it does. An infinite anchor is read live. Preview's own steps never- // rewrite it — they stamp the window's anchor, see selectPreviewItem — so- // the only thing that changes it is a selection made elsewhere: a grid- // click, a reveal, a result arriving under live-follow. Each of those names- // the window that holds the new selection, and Preview has to move to it.- // Held sticky, the anchor outlived every one of them: a click on the newest- // image at the top of the board left Preview walking rows 1800+ for a- // selection at row 0.+ // Only paginated anchors are sticky. Infinite steps preserve their anchor, while external selections must+ // immediately reanchor the window.const navigationAnchorPage =selectedImageQuery.paginationMode === 'paginated'? hasStaleNavigationAnchor@@ -237,14 +208,8 @@ export const usePreviewNavigation = ({: navigationAnchor.page: selectedImageQuery.page;const isPaginatedWindow = selectedImageQuery.paginationMode === 'paginated';- // A selection deeper than the base window's reach (a deep reveal from the- // image map) anchors navigation at its own page — walking from offset 0- // could never arrive at the cursor. Such a window is a slice from the- // middle of the board, and it is one-way by design: it cannot grow upward- // past its anchor, because the grid shares the cache entry and rows spliced- // in above its viewport would shift the content under the user. So the- // anchor must stay where the selection was made, and the exclusions below- // that hinge on "is this window mid-board?" are all derived from it.+ // Anchor deep navigation at the selection page. Shared infinite windows cannot grow upward without shifting grid+ // content, so retain that anchor and derive mid-board exclusions from it.const deepAnchorOffset =!isPaginatedWindow &&navigationSemanticQuery === null &&@@ -252,12 +217,7 @@ export const usePreviewNavigation = ({? navigationAnchorPage * GALLERY_PAGE_SIZE: 0;- // A ranked list mirrors the GRID's paging instead of the stamped context.- // The stamped page indexes the board listing, and a board page applied to a- // ranking lands on an unrelated slice — or, past the end of a ranking that is- // shorter than the board, on an empty one whose only member is the anchored- // selection, leaving both arrows with nowhere to step. Setting a search also- // resets the grid's page, which the stamped record never sees.+ // Rankings follow grid paging, not stamped board pages, which can address unrelated or empty ranking slices.const navigationWindow =navigationSemanticQuery !== null? galleryPaginationMode === 'paginated'@@ -296,10 +256,7 @@ export const usePreviewNavigation = ({enabled: hasNavigationContext,});- // The strip the grid pins above its unstarred listing — the same bounded- // query, so it is already cached whenever the gallery is open. As in the- // grid, no strip applies to a ranked result, to the starred-only listing,- // or to a window anchored mid-board.+ // Share Gallery's bounded starred strip except for ranked, starred-only, or mid-board windows.const hasStrip =hasNavigationContext && !navigationStarredOnly && navigationSemanticQuery === null && deepAnchorOffset === 0;const { data: stripData } = useQuery({ ...galleryStarredStripOptions(listingFilter), enabled: hasStrip });@@ -325,27 +282,8 @@ export const usePreviewNavigation = ({page.items.some((candidate) => toGalleryItemKey(candidate) === itemKey));const pageParam = pageIndex === undefined || pageIndex < 0 ? undefined : data?.pageParams[pageIndex];- // `page` is stamped as a BOARD page and read as one everywhere else, so- // a ranked window's page params — offsets into the ranking — must not be- // written into it. Neither may the grid's own page: in paginated mode- // the footer paginates the RANKING, so that number is a rank page too.- // Carrying the page the preview opened on is no better — the item- // picked out of a ranking is nowhere near the board slice it names, and- // a deep one strands navigation there once the chip is cleared. What- // holds in both modes is the top of the listing: setting a search and- // clearing it both reset the grid to page 0, so that is the board- // context a ranked session hands back.- //- // In an INFINITE window the page is the anchor of the window that holds- // the item, which is what a grid click stamps too (the grid's own page,- // whatever row was clicked). Stamping the item's row instead rolls the- // window forward with the cursor: the anchor is read live, so each step- // past a page boundary re-keys the query at the new row, the old entry- // is discarded, and — a deep window being one-way — everything the user- // just walked through is unreachable. An item the window does not hold- // at all (a strip item, a recent the listing has not caught up with,- // the compare slot's image) is stamped at the top: that is where those- // live, and the base window's reach is the best guess for anything else.+ // Stamp ranked picks with board page zero, never ranking offsets. Infinite picks retain their window anchor+ // to preserve prior pages; items outside the window use the top-of-board context.return navigationSemanticQuery !== null? 0: selectedImageQuery.paginationMode === 'paginated'@@ -379,16 +317,8 @@ export const usePreviewNavigation = ({[queueItems]);const navigationLocalItems = useMemo(() => {- // 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 or starred filter (backend-filtered, local items- // are not), and any window anchored mid-board — paginated, or the infinite window a deep- // reveal anchors — where settled recents would splice in permanently.- // Recents belong at the TOP of the listing, so a window nowhere near the- // top is not theirs to join; the grid draws the same line for its own- // window. There, only in-flight work and the selection merge.+ // Keep recent results until listings catch up, except in filtered or mid-board windows where they do not+ // belong. Those windows merge only in-flight work and selection.const hasActiveSearch =navigationStarredOnly || selectedImageSearch.text.trim() !== '' || selectedImageSearch.range !== undefined;@@ -439,8 +369,7 @@ export const usePreviewNavigation = ({return [selectedItem, ...listingLocalItems];}, [hasStrip, localBoardItems, selectedItem, selectedItemKey]);const backendBoardItems = useMemo(() => flattenPreviewItems(boardItemsData), [boardItemsData]);- // Recents belong to a board listing; a ranked list gets only the selection,- // and only as the cursor anchor described in mergePreviewBoardItems.+ // Rankings accept only selection as cursor anchor, never board recents.const previewMergeItems = useMemo(() =>navigationSemanticQuery === null ? previewLocalBoardItems : selectedItem ? [selectedItem] : EMPTY_PREVIEW_ITEMS,@@ -481,8 +410,7 @@ export const usePreviewNavigation = ({? -1: boardItems.findIndex((item) => toGalleryItemKey(item) === selectedItemKey);- // One navigation action shared by the arrow keys and the footer buttons.- // Comparison never steps through saved images.+ // Share navigation between keyboard and footer; comparison does not step saved images.const navigate = useCallback((offset: -1 | 1) => {if (isComparing) {@@ -585,8 +513,7 @@ export const usePreviewNavigation = ({[isComparing, navigate]);- // Warm the browser cache for the sequence neighbors so arrow-key navigation- // swaps without a decode flash.+ // Prefetch adjacent media to avoid decode flashes during navigation.const previousNeighbor = navigationCursor === -1 ? undefined : boardItems[navigationCursor - 1];const nextNeighbor = navigationCursor === -1 ? undefined : boardItems[navigationCursor + 1];const previousNeighborUrl = previousNeighbor?.kind === 'image' ? previousNeighbor.fullUrl : null;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue-status/QueueStatusWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue-status/QueueStatusWidgetView.tsxindex d0eddabfff..10da81b535 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue-status/QueueStatusWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue-status/QueueStatusWidgetView.tsx@@ -14,9 +14,7 @@ export const QueueStatusWidgetView = ({ presentation }: WidgetViewProps) => {const { t } = useTranslation();const { progress, queueItems } = useActiveQueueProgress();const isPaused = useIsProcessorPaused();- // The chip's remaining/total counts must hold steady as progress advances- // through a running batch's sub-images, so they come from a summary built- // without progress; only the percent label tracks live progress.+ // Derive counts without progress so batch sub-image updates change percent only.const summary = getQueueSummary(queueItems);const chip = getQueueStatusChip(summary, isPaused);const percent = getDeterminateProgressPercent(progress?.percentage);@@ -24,8 +22,6 @@ export const QueueStatusWidgetView = ({ presentation }: WidgetViewProps) => {chip.labelKey === 'idle'? t('widgets.queueStatus.idle'): t(`widgets.queueStatus.${chip.labelKey}`, { count: chip.count });- // The count answers "how much is left"; the percent answers "how far into the- // current one", which is the half the chip was missing.const showPercent = chip.tone === 'running' && percent !== null;const detail = chip.tone === 'running' ? progress?.message.trim() : undefined;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue-status/queueStatusModel.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue-status/queueStatusModel.tsindex 68a5cbc497..db8492dd63 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue-status/queueStatusModel.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue-status/queueStatusModel.ts@@ -20,12 +20,8 @@ export const getQueueStatusChip = (};/**- * The chip's hairline, or `undefined` for no bar at all.- *- * Only the running tone gets one: an idle queue has nothing to fill, and a- * paused one would show a bar that never moves, which reads as a hang. The- * fill itself routes through `getDeterminateProgressFraction` — see that- * function for why zero reads as indeterminate.+ * Show a progress hairline only while running; paused bars look stalled. getDeterminateProgressFraction handles+ * zero as indeterminate.*/export const getQueueStatusProgress = (chip: QueueStatusChip,diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 67a3859501..df21714b1e 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -49,8 +49,7 @@ import {workbenchReducer as reduceWorkbench,} from './workbenchState.testing';-// Generation policy now fails closed without the capability table, and a submission cannot-// happen before app boot has fetched it. Seeding it here is what the running app does.+// Seed capabilities to match app boot; submission fails closed without them.seedArchitectureCapabilities();const generationDeviceMock = vi.hoisted(() => ({@@ -388,10 +387,7 @@ const createInpaintMaskLayer = (id: string): CanvasLayerContract =>}) as CanvasLayerContract;/** Adds layers top-to-bottom in array order (each `addCanvasLayer` inserts at index 0). */-// A new project's canvas now seeds one empty inpaint mask (see-// `createNewCanvasState`). These layer-reducer/staging tests exercise layer-// mechanics where that default mask is incidental, so they start from an empty-// canvas document to keep their expectations focused on the layers under test.+// Start without the default inpaint mask so these tests isolate layer mechanics.const withEmptyCanvas = (state: WorkbenchState): WorkbenchState =>workbenchReducer(state, { document: createEmptyCanvasDocument(), type: 'replaceCanvasDocument' });@@ -496,9 +492,7 @@ describe('generation-device orchestration metadata', () => {describe('workbench hydration invariants', () => {it('seeds a draft when a projectless session hydrates', () => {const initial = createInitialWorkbenchState();- // What `persistEmptySession` caches after the last tab is closed. A load path- // that hands this over verbatim used to leave the store with no active project,- // which the first consumer to read one dereferences.+ // Model the projectless cache written after closing the last tab.const emptySession: WorkbenchState = { ...initial, activeProjectId: '', projects: [] };const hydrated = workbenchReducer(initial, { state: emptySession, type: 'hydrateWorkbench' });@@ -511,9 +505,6 @@ describe('workbench hydration invariants', () => {it('builds that draft from the cached account, not the shipped defaults', () => {const initial = createInitialWorkbenchState();const project = getActiveProject(initial);- // The account's saved override of the default preset is what an empty cache- // still owns; the seeded draft has to inherit it the way the offline load path's- // replacement draft does.const customizedDefault = {...resolveSavedLayoutPreset(initial.account, initial.account.activeLayoutPresetId).snapshot,widgetRegions: {@@ -606,10 +597,7 @@ describe('workbench widget region defaults', () => {});it('hydrates a pre-image-map right rail to the curated rail rather than splicing Image Map in', () => {- // Splicing would leave a rail no preset holds, so an untouched project- // would compare unequal to the preset it was loaded from — the drift dot- // the rail migrations exist to avoid. Adopting the curated rail is the- // only result that both surfaces the widget and keeps the two in step.+ // Untouched legacy rails must adopt the exact curated preset to avoid false drift.const initial = createInitialWorkbenchState();const withRightIds = (instanceIds: Project['widgetRegions']['right']['instanceIds']): WorkbenchState => ({...initial,@@ -670,8 +658,6 @@ describe('workbench widget region defaults', () => {instanceIds: ['layers', 'preview'],});- // The brief Layers-only rail (which dropped the preview) is a shipped- // shape too, so it adopts the current rail and gets the preview back.const hydratedLayersOnly = getActiveProject(workbenchReducer(initial, { state: layersOnlyRail, type: 'hydrateWorkbench' }));@@ -708,8 +694,6 @@ describe('workbench widget region defaults', () => {type: 'hydrateWorkbench',});- // No Video adoption any more: the curated defaults exclude it, so the- // legacy splice adds Upscale alone.expect(getActiveProject(migrated).widgetRegions.left.instanceIds).toEqual(['generate', 'workflow', 'upscale']);expect(getActiveProject(migrated).widgetInstances.upscale?.typeId).toBe('upscale');expect(getActiveProject(customized).widgetRegions.left.instanceIds).toEqual(['generate', 'gallery']);@@ -850,8 +834,6 @@ describe('workbench panel resize bounds', () => {state = workbenchReducer(state, { isCollapsed: true, region: 'left', type: 'setRegionWidgetCollapsed' });expect(getActiveProject(state).widgetRegions.left).toMatchObject({ isCollapsed: true, sizePx: 500 });- // What the rail button does next: the stored active instance still matches,- // so selecting it toggles the collapse back off rather than switching.state = workbenchReducer(state, { region: 'left', type: 'selectRegionWidget', widgetId: activeInstanceId });expect(getActiveProject(state).widgetRegions.left).toMatchObject({ isCollapsed: false, sizePx: 500 });});@@ -1062,11 +1044,7 @@ describe('adopting a project from another realm', () => {});it('drops a session-scoped search and the rank pages set against it', () => {- // A project opened from the server — the Open dialog, a deep link, or a- // conflict fork — arrives in a realm that never ran the session its values- // describe, and never passes the save path where this rule also runs. The- // ranking cannot be rebuilt here, so the pages indexing it would be read- // as board positions.+ // Foreign project rankings cannot resolve in this realm; their rank pages must not become board positions.const values = galleryValuesOf(galleryProject({galleryPage: 3,@@ -1090,10 +1068,7 @@ describe('adopting a project from another realm', () => {});it('keeps a session-scoped search this realm can still resolve', () => {- // Adoption is not only a foreign document arriving: closing and reopening- // a project runs it, and so does the conflict fork that rescues the LIVE- // copy. The registry entry is still here, the ranking is still on screen,- // and deleting it would take the user's search with it.+ // Live reopen and conflict forks retain resolvable rankings; adoption alone does not imply a foreign session.const clusterId = registerImageCluster(['image:a.png', 'image:b.png'], 'beaches');const values = galleryValuesOf(galleryProject({@@ -1108,11 +1083,7 @@ describe('adopting a project from another realm', () => {});it('drops an infinite window anchor on adoption, and keeps a paginated page', () => {- // A reveal anchors the infinite window mid-board for the session that- // made it; adopted anywhere else it strands the gallery there. A- // paginated page is the page the user was reading and survives. A- // gallery that never touched the setting has no paginationMode at all,- // and the default is infinite — that is the common shape.+ // Infinite anchors are session-only; paginated positions persist, and absent paginationMode means infinite.expect(galleryValuesOf(galleryProject({ galleryPage: 5, paginationMode: 'infinite' })).galleryPage).toBe(0);expect(galleryValuesOf(galleryProject({ galleryPage: 5 })).galleryPage).toBe(0);expect(galleryValuesOf(galleryProject({ galleryPage: 5, paginationMode: 'paginated' })).galleryPage).toBe(5);@@ -1924,9 +1895,6 @@ describe('workbench layout presets', () => {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' });@@ -2339,8 +2307,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getRasterLayerImageName(getDocumentLeaves(project.canvas.document)[0])).toBe('candidate.png');expect(project.canvas.document.selectedLayerId).toBe(acceptedLayerId);expect(project.canvas.stagingArea.pendingImages).toEqual([]);- // Deliberate semantic change (P0.2): canvas is engine-owned, so accepting a- // staged image does not create a project-level undo entry.+ // Canvas acceptance uses engine history, not project undo.expect(project.undoRedo.past).toHaveLength(0);state = commitSelectedStagedImage(state);@@ -3194,8 +3161,6 @@ describe('workbenchReducer Phase 5 generation flow', () => {const project = getActiveProject(state);- // A meaningful graph edit lands in the document, creates an undo entry,- // and steers the unlocked invocation route to the project graph.expect(project.projectGraph.nodes).toHaveLength(1);expect(project.undoRedo.past.at(-1)?.label).toBe('Add workflow node');expect(project.invocation.sourceId).toBe('workflow');@@ -3262,8 +3227,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {type: 'submitResolvedInvocationSnapshot',});- // Regression: a one-prompt expansion used to be dropped, falling the submission- // back to `positivePrompt` — which still holds the unexpanded `{…}` syntax.+ // A single expansion is still concrete and must replace authored dynamic syntax.it('records a single expanded prompt rather than falling back to the literal', () => {const state = submitResolvedWithPrompts('a {red} cat', ['a red cat']);@@ -3438,10 +3402,8 @@ describe('workbenchReducer Phase 5 generation flow', () => {});it('notifies when the queued workflow omits metadata the backend would reject', () => {- // `WorkflowWithoutID` rejects more than one `workflow_return` node, and- // the batch is validated before the enqueue route body, so attaching- // such a workflow turns the whole run into a 422. Legacy validates first- // and sends no workflow rather than failing the run.+ // Multiple workflow_return nodes fail WorkflowWithoutID validation with 422; omit invalid workflow metadata+ // rather than reject generation.const returnTemplate = {category: 'workflow',classification: 'stable',@@ -3799,8 +3761,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {});});- // Recall and the history popover both write straight back into the textarea,- // so history has to hold what the user typed, not what generated.+ // History restores textarea drafts, so it must retain authored rather than expanded text.it('records the authored prompt in prompt history', () => {const state = submitGenerate(primeGenerate(undefined, {@@ -4570,11 +4531,8 @@ describe('workbenchReducer Phase 5 generation flow', () => {});it('stamps an explicit page into the navigation query already on a multi-selection', () => {- // A host navigating its own window passes the page that keeps the primary- // item in that window — the same contract as selectGalleryItem with- // preserveNavigationQuery — rather than the grid's page. The query it goes- // into is the one already on the selection: the grid may have moved to- // another board and search since, and the host's list is not that.+ // Host navigation uses the selection's query and page, which may differ from the gallery's current+ // board/search.let state = createInitialWorkbenchState();state = workbenchReducer(state, { boardId: 'board-deep', type: 'selectGalleryBoard' });@@ -4639,8 +4597,6 @@ describe('workbenchReducer Phase 5 generation flow', () => {values = getProjectWidgetValues(getActiveProject(state), 'gallery');expect(values.selectedImageQuery).toMatchObject({ starredOnly: true });- // Releasing the filter is a listing change too: the page resets, and a- // later selection is stamped against the unfiltered listing.state = workbenchReducer(state, { page: 2, type: 'setGalleryPage' });state = workbenchReducer(state, { starredOnly: false, type: 'setGalleryStarredOnly' });state = workbenchReducer(state, {@@ -4654,8 +4610,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {});it('stamps a landing generation against the unfiltered listing', () => {- // A fresh result is never starred, so following it means leaving the- // starred-only listing — the stamp says so, exactly as it clears the search.+ // Following a fresh, unstarred result must leave the starred-only listing.let state = primeGenerate();state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });state = workbenchReducer(state, { starredOnly: true, type: 'setGalleryStarredOnly' });@@ -4677,9 +4632,6 @@ describe('workbenchReducer Phase 5 generation flow', () => {});it('exits a similarity search when the view moves to another board', () => {- // A ranking answers with images from wherever they live, so it is not a- // view OF any board; left up, a board click would be answered with the- // same results under a new board name.let state = createInitialWorkbenchState();state = workbenchReducer(state, { boardId: 'board-a', type: 'selectGalleryBoard' });@@ -4699,9 +4651,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {});it('keeps a similarity search when the board already shown is picked again', () => {- // A text or image reference survives a reload, so a click that changes- // nothing about the view must not erase persisted state — and autosave- // the loss — on what reads as a no-op.+ // Re-selecting the current board must preserve persisted rankings and avoid autosaving their loss.let state = createInitialWorkbenchState();state = workbenchReducer(state, { boardId: 'board-a', type: 'selectGalleryBoard' });@@ -4720,11 +4670,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {});it('leaves the page stamped on the selection alone when a search is dismissed by a board move', () => {- // The selection here was made BEFORE the search, so its page is a real- // board position that the search never rewrote (setSemanticImageQuery- // touches only the grid's page). Zeroing it — as the adoption path must,- // having no better information — would cost Preview the cursor it still- // has and strand its arrows at the top of the board.+ // This selection predates search; its board page remains valid and must not be reset with ranking pages.let state = createInitialWorkbenchState();state = workbenchReducer(state, { boardId: 'board-a', type: 'selectGalleryBoard' });@@ -4750,9 +4696,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {});it('exits a similarity search when the Images/Assets tab is switched, but not when it is re-clicked', () => {- // The two tabs are two listings and the ranking is a view of neither. A- // gallery that never touched the setting has no galleryView at all, and- // that reads as Images — so clicking Images there is not a switch.+ // Absent galleryView already means Images, so selecting Images is not a switch.let state = createInitialWorkbenchState();state = workbenchReducer(state, {@@ -4777,9 +4721,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {});it('exits a similarity search when the board being viewed is deleted', () => {- // Deleting the viewed board moves the view to Uncategorized without- // going through `selectGalleryBoard`, so the rule has to be applied here- // too — otherwise the ranking survives under a board name that is gone.+ // Board deletion bypasses selectGalleryBoard and must independently clear the old ranking.let state = createInitialWorkbenchState();state = workbenchReducer(state, { boardId: 'doomed-board', type: 'selectGalleryBoard' });@@ -4947,10 +4889,6 @@ describe('workbenchReducer Phase 5 generation flow', () => {const galleryValues = (state: WorkbenchState) => getProjectWidgetValues(getActiveProject(state), 'gallery');it('entering carries the text across and ranks it at once; leaving carries it back', () => {- // The sparkle changes what the words mean, not whether they are there.- // A click is deliberate, so entering applies the ranking immediately- // rather than waiting for a typing pause; leaving drops the ranking- // because metadata search has its own listing.let state = createInitialWorkbenchState();state = workbenchReducer(state, { searchTerm: ' sunset ', type: 'setGallerySearchTerm' });@@ -5119,8 +5057,6 @@ describe('workbench account and project settings', () => {const state = workbenchReducer(initial, { state: legacy, type: 'hydrateWorkbench' });- // `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: [],@@ -6741,8 +6677,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {state = workbenchReducer(state, { document: createEmptyCanvasDocument(), type: 'replaceCanvasDocument' });expect(getCanvas(state).documentRevision).toBe(initialRevision + 1);- // restoreCanvasSnapshot is a wholesale swap: bump — even though the restored- // document reuses the saved layer ids at the same dimensions.+ // Snapshot restore is a wholesale swap even when layer ids and dimensions match.state = workbenchReducer(state, { createdAt: 'now', id: 'snap-1', name: 'First', type: 'saveCanvasSnapshot' });expect(getCanvas(state).documentRevision).toBe(initialRevision + 1);state = workbenchReducer(state, { snapshotId: 'snap-1', type: 'restoreCanvasSnapshot' });@@ -7077,8 +7012,6 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =it('drops mid-flight canvas results after a new-canvas swap so cleared staging is not resurrected (F2)', () => {const { queueItemId, state: submitted } = submitCanvasGeneration(createInitialWorkbenchState());- // The user confirms a new canvas while the generation is still in flight: a- // wholesale swap that clears staging and bumps documentRevision (new session).const swapped = workbenchReducer(submitted, {document: createEmptyCanvasDocument(),type: 'replaceCanvasDocument',@@ -7257,8 +7190,7 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =const queueItem = getActiveProject(state).queue.items[0];- // A Canvas source still runs, but the resolved Gallery destination rides- // through so `routeQueueItemResults` keeps it out of canvas staging.+ // Gallery-destined Canvas results must bypass canvas staging.expect(queueItem?.snapshot.sourceId).toBe('canvas');expect(queueItem?.snapshot.destination).toBe('gallery');expect(getActiveProject(state).invocation.destination).toBe('gallery');@@ -7486,8 +7418,7 @@ describe('auto invocation route switching', () => {state = workbenchReducer(state, { destination: 'canvas', type: 'setInvocationDestination' });state = workbenchReducer(state, { sourceId: 'canvas', type: 'setInvocationSource' });- // Canvas compiles from generate values, so the generate panel is also the- // canvas parameter panel — editing it expresses canvas intent here.+ // Generate edits express Canvas intent while serving as its parameter panel.state = workbenchReducer(state, { type: 'patchGenerateSettings', values: { steps: 25 } });state = workbenchReducer(state, { type: 'setGenerateSettings', values: createGenerateValues() });diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.testing.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.testing.tsindex 2622a9ccb8..3f8712743a 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.testing.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.testing.ts@@ -1,10 +1,4 @@-/**- * Reducer-level compatibility facade for invariant tests only.- *- * Production code must use Workbench commands and queries. Keeping this facade- * separate makes reducer coupling visible and lets those tests be retired as- * command-level coverage replaces them.- */+/** Test-only reducer facade; production callers use Workbench commands and queries. */import type { WorkbenchState } from '@workbench/projectContracts';import {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 531d130284..0737a97373 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -457,26 +457,14 @@ const HISTORY_LIMIT = 40;/** A pause this long between same-key edits (typing, dragging) starts a new undo step. */const UNDO_MERGE_WINDOW_MS = 1500;const NOTIFICATION_LIMIT = 100;-// Side panels host real widget UIs (gallery grid, generate form); below-// ~350px their toolbars and grids collapse into unusable slivers, so that is-// the floor rather than a merely-rendered 180px. The ceiling exists for the-// opposite reason: a panel is an inspector, and the work surface it sits-// beside has to keep enough room to be the thing being worked on. Two maxed-// side panels come to 1528px with their rails, so on a narrow laptop that is-// a deliberate, self-inflicted squeeze rather than something a default can-// walk into. The bottom strip is a status row, not a widget host, and keeps-// its own bounds.+// Side-panel bounds keep widget controls usable while reserving work-surface space. The bottom status strip has+// separate bounds.const MIN_PANEL_SIZE_PX = 350;const MAX_PANEL_SIZE_PX = 720;const MIN_STATUS_PANEL_SIZE_PX = 96;const MAX_STATUS_PANEL_SIZE_PX = 420;-/**- * How far a resize drag must push past a region's floor before releasing means- * "collapse to the rail" rather than "stop at the minimum". Wide enough that- * running into the floor never collapses by accident, short enough to find- * without being told it is there.- */+/** Overshoot required to collapse rather than stop at the minimum size. */const PANEL_COLLAPSE_OVERSHOOT_PX = 80;/** The resize bounds for a widget region — shared with the resize handles. */@@ -492,20 +480,11 @@ export const getPanelSizeBounds = (region: WidgetRegion): { max: number; min: nuexport const getPanelCollapseThreshold = (region: WidgetRegion): number =>getPanelSizeBounds(region).min - PANEL_COLLAPSE_OVERSHOOT_PX;-/**- * Whether a live drag should have the panel snapped shut, dockview-style: it- * snaps at the overshoot threshold and reopens halfway back, so the boundary- * has hysteresis instead of flapping a whole panel on one pixel.- */+/** Reopens halfway back from the collapse threshold to prevent boundary flicker. */export const shouldSnapPanelShut = (region: WidgetRegion, rawSizePx: number, isSnapped: boolean): boolean =>shouldSnapPanelShutAt(getPanelCollapseThreshold(region), rawSizePx, isSnapped);-/**- * `shouldSnapPanelShut` against an explicit threshold, for a panel the- * viewport has squeezed below its floor: the overshoot is then measured from- * the width actually on screen, so a drag on a 213px panel collapses it after- * 80px instead of demanding the pointer travel to where the floor would be.- */+/** Measure overshoot from the rendered width when the viewport squeezes a panel below its minimum. */export const shouldSnapPanelShutAt = (thresholdPx: number, rawSizePx: number, isSnapped: boolean): boolean =>rawSizePx <= thresholdPx + (isSnapped ? PANEL_COLLAPSE_OVERSHOOT_PX / 2 : 0);@@ -550,12 +529,8 @@ const createNotification = ({const addNotification = (state: WorkbenchState, notification: WorkbenchNotification): WorkbenchState => {const [newest, ...rest] = state.notifications;- // Coalesce an exact repeat of the newest ERROR notification into an- // occurrence bump on the SAME id, instead of stacking a new one — the- // toaster dedupes toasts by id, so a repeat then stops re-toasting for free- // (e.g. an ambient retry failing the same way every cycle). Restricted to- // errors: non-error kinds (e.g. "Invocation queued") are routine, repeat- // actions that must each surface their own toast.+ // Reuse the newest matching error's id to suppress repeated toasts. Routine success notifications must still+ // toast independently.if (newest &&newest.kind === 'error' &&@@ -1164,10 +1139,7 @@ const cloneWidgetRegions = cloneLayoutPresetWidgetRegions;const cloneWidgetGraphs = (widgetGraphs: Project['widgetGraphs']): Project['widgetGraphs'] =>Object.fromEntries(Object.entries(widgetGraphs).map(([key, graph]) => [key, graph ? cloneGraph(graph) : graph]));-// Canvas is intentionally absent from undo snapshots: the canvas rendering-// engine owns its own pixel-patch history, so project-level undo/redo neither-// snapshots nor restores canvas — `restoreUndoSnapshot` passes the live-// `project.canvas` straight through via the `...project` spread.+// Canvas pixel history belongs to the engine; project undo preserves the live canvas.const createUndoSnapshot = (project: Project,projectGraph = cloneProjectGraph(project.projectGraph)@@ -1183,8 +1155,7 @@ const createUndoSnapshot = (const restoreUndoSnapshot = (project: Project, snapshot: ProjectUndoSnapshot): Project => ({...project,- // Restored WITH widgetRegions — they are one placement fact, and restoring- // one without the other can double-render or orphan a floated instance.+ // Restore floating windows with widgetRegions to avoid duplicate or orphaned placements.floatingWidgets: snapshot.floatingWidgets ? { ...snapshot.floatingWidgets } : undefined,invocation: { ...snapshot.invocation },layout: { ...snapshot.layout, panels: { ...snapshot.layout.panels } },@@ -1194,12 +1165,7 @@ const restoreUndoSnapshot = (project: Project, snapshot: ProjectUndoSnapshot): PwidgetRegions: cloneWidgetRegions(snapshot.widgetRegions),});-/**- * Records the project as it is *before* an edit. A `mergeKey` folds a stream- * of edits (each keystroke in a field, each move of a drag) into the entry- * that opened the stream while they keep arriving within the merge window,- * so one undo reverts the whole burst.- */+/** Capture pre-edit state; edits sharing a mergeKey within the window undo as one burst. */const pushUndo = (project: Project, label: string, projectGraph?: ProjectGraphState, mergeKey?: string): Project => {const previous = project.undoRedo.past.at(-1);const timestamp = now();@@ -1342,21 +1308,11 @@ const ensureLeftRegion = (leftRegion: WidgetRegionState | undefined): WidgetRegi}}- // The Video widget is deliberately absent from the non-video defaults now,- // so nothing backfills it any more; it lives in the Video preset and stays- // addable everywhere.-return region;};-// Every right rail this app has shipped as a default. A project persisted with-// one of these exactly is an untouched default rather than a customization, so-// it adopts the current curated rail wholesale.-//-// Adopting beats splicing the new widget in: the curated presets are the only-// arrangements a rail can hold without reading as drifted, and a spliced rail-// is by construction not one of them — it would show the unsaved-changes dot-// and offer to revert a layout nobody edited.+// Exact historical defaults adopt the current rail wholesale; splicing would incorrectly mark untouched layouts as+// customized.const LEGACY_RIGHT_REGION_WIDGET_IDS: WidgetId[][] = [['queue', 'gallery', 'layers'],// The rail as it shipped before the image map existed.@@ -1383,13 +1339,7 @@ const ensureRightRegion = (rightRegion: WidgetRegionState | undefined): WidgetRereturn rightRegion;};-/**- * Every Edit rail this app shipped as a default: the tabbed rail from while- * the canvas editors were separate widgets, one unreleased build's variant- * without Image Map, and the brief Layers-only rail that dropped the preview.- * An untouched rail of any of those shapes adopts the shipped rail; a- * customized rail stays the user's.- */+/** Exact historical Edit defaults adopt the current rail; customized rails remain unchanged. */const LEGACY_EDIT_RIGHT_REGION_WIDGET_IDS: ReadonlyArray<readonly WidgetInstanceId[]> = [['layers', 'preview', 'gallery', 'image-map', 'queue'],['layers', 'preview', 'gallery', 'queue'],@@ -1425,16 +1375,8 @@ const withoutRetiredInstances = (};};-// The shipped bottom-region default before 'queue-status' was added — a-// persisted project whose bottom rail matches this exactly is still running-// the pre-branch defaults, so it should pick up the new widget the same way-// a fresh project would.-//-// A rail whose 'queue-status' was floated back out matches this shape too, so-// the migration re-docks it on every load. That is left to-// `reconcileFloatingWidgets`, which runs on this region's output and drops any-// instance holding a floating window — the same contract the other rail-// migrations here rely on.+// Adopt queue-status for the historical bottom default. reconcileFloatingWidgets removes any instance already+// hosted in a window.const LEGACY_DEFAULT_BOTTOM_REGION_WIDGET_IDS: readonly WidgetInstanceId[] = ['server-status','gallery:bottom',@@ -1485,15 +1427,12 @@ const ensureCenterRegion = (fallbackCenterViewId: CenterViewId): WidgetRegionState => {const defaultCenterRegion = createWidgetRegions().center;- // A center with no region data at all adopts the default arrangement, but an- // explicitly emptied one is authoritative: the last view may be floating in a- // window (the surface falls back until its dock control returns it), and- // refilling it would inject views the project never placed.+ // Missing region data adopts defaults; an explicitly empty center may have its last view floating and must stay+ // empty.const instanceIds = centerRegion ? centerRegion.instanceIds : defaultCenterRegion.instanceIds;const activeInstanceId = centerRegion?.activeInstanceId ?? getCenterWidgetIdFromViewId(fallbackCenterViewId);- // A pointer that names none of the members is clamped — but an emptied- // center keeps its pointer, which names the instance now floating in a- // window; the boot preload reads it to have that window's chunk ready.+ // An empty center retains the floated instance pointer for boot preloading; nonempty centers clamp invalid+ // pointers.const normalizedActiveInstanceId = instanceIds.includes(activeInstanceId)? activeInstanceId: (instanceIds[0] ?? activeInstanceId);@@ -1517,14 +1456,7 @@ const isFloatingWidgetMode = (value: unknown): value is FloatingWidgetMode =>const isWidgetRegionId = (value: unknown): value is WidgetRegion => WIDGET_REGION_IDS.includes(value as WidgetRegion);-/**- * Put a docking widget back where it was, not on the end.- *- * The rail is an ordered tab strip, so appending turned float-then-dock — a- * gesture that reads as undoing the float — into a permanent reordering, which- * then registered as drift from the preset. The rail may have changed while the- * window was open, so the remembered index is clamped rather than trusted.- */+/** Restore the pre-float tab index, clamped to the current rail, so float/dock does not reorder the layout. */const insertAtReturnIndex = (instanceIds: WidgetInstanceId[],instanceId: WidgetInstanceId,@@ -1542,11 +1474,8 @@ const insertAtReturnIndex = (};/**- * 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.+ * Drop malformed floating entries so widgets remain docked and invalid region names or geometry cannot reach+ * reducers or CSS.*/const normalizeFloatingWidgets = (value: unknown,@@ -1584,9 +1513,7 @@ const normalizeFloatingWidgets = (floatingWidgets[instanceId] = {...clampSizeToMinimum({ heightPx: state.heightPx, widthPx: state.widthPx, x: state.x, y: state.y }),mode: state.mode,- // Carried explicitly, like every other field: this rebuilds the entry- // rather than spreading it, so anything not named here is dropped. A- // nonsensical index is simply omitted — docking falls back to appending.+ // Omit invalid docking indices; docking then appends....(isFiniteNumber(state.returnIndex) && state.returnIndex >= 0? { returnIndex: Math.floor(state.returnIndex) }: {}),@@ -1599,17 +1526,8 @@ const normalizeFloatingWidgets = (};/**- * An instance renders either in a region or in a floating window, never both.- *- * The region migrations above rebuild a rail that reads as an untouched default- * — and a rail missing a floated widget is exactly that shape — so on every- * reload they hand back a widget the person had floated. Floating wins: it is- * the deliberate act, while the region entry is the migration's guess.- *- * That holds for the center too, even when its last view is the one floating:- * the surface falls back to the center's fallback view, and the window's dock- * control is one click from restoring it. Only the destructive placements- * (`toggleRegionWidget`, `closeWidgetPlacement`) still refuse to empty it.+ * Floating placement wins over migrated rail defaults to prevent duplicate rendering, even when it leaves the+ * center on its fallback view.*/const reconcileFloatingWidgets = (widgetRegions: Record<WidgetRegion, WidgetRegionState>,@@ -1684,11 +1602,8 @@ export const normalizeWorkbenchProject = (project: Project,options: {/**- * Whether the document is arriving from another realm (a server record,- * an import) rather than being kept by this one during a live retarget.- * An infinite window's mid-board anchor is a- * "you are here" for the session that revealed it: it is dropped from a- * document that arrives, and kept for one that stays.+ * Drop session-only infinite-window anchors on imported/server documents; preserve them during live+ * retargeting.*/isArriving?: boolean;} = {}@@ -1749,9 +1664,7 @@ const assembleWorkbenchProject = (}}- // Workflow runs used to borrow Generate's iteration count. A project saved before the- // widget owned one has no key; carry the count over once so it keeps the runs it- // effectively had. A fresh project starts with the widget's own default, so it never migrates.+ // Legacy workflows inherit Generate's iteration count once; fresh workflows use their own default.const workflowInstance = widgetInstances.workflow;if (workflowInstance && typeof workflowInstance.state.values.batchCount !== 'number') {@@ -1783,19 +1696,8 @@ const assembleWorkbenchProject = (continue;}- // A project can arrive here from a realm that never ran the session its- // values describe — the Open dialog, a deep link — where a search only- // that session could resolve, and the rank pages set against it, would be- // read as board positions. But this also runs on projects that never- // left: closing, reopening, or retargeting one. So the test is whether the reference resolves- // here, not what kind it is; the latter would delete the ranking the user- // is looking at.- // An infinite window's mid-board anchor goes the same way, for the same- // reason the save path drops it: it is a "you are here" for the session- // that revealed it. Adoption and the boot snapshot have to agree on this,- // because the sync baseline is taken from the adopted document while the- // store is hydrated from the snapshot — a project that has only been- // opened must serialize to its baseline, or the next autosave pushes it.+ // Preserve only rankings resolvable in this session. Drop foreign infinite-window anchors consistently with+ // serialization so hydration matches the sync baseline.const strippedSearchValues = stripUnresolvableGallerySearch(instance.state.values);const strippedValues = isArriving? (stripInfiniteWindowAnchor(strippedSearchValues ?? instance.state.values) ?? strippedSearchValues)@@ -1848,9 +1750,7 @@ const assembleWorkbenchProject = (canvas,events: isArriving ? [] : project.events.slice(0, PROJECT_EVENT_LIMIT),floatingWidgets: placement.floatingWidgets,- // 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.+ // Resolve historical built-in preset ids to their current arrangements to avoid false layout drift.layout: { ...project.layout, presetId: resolveLayoutPresetId(project.layout.presetId) },projectGraph: normalizeProjectGraph(project.projectGraph),promptHistory: normalizePromptHistory((project as Partial<Project>).promptHistory),@@ -1862,17 +1762,8 @@ const assembleWorkbenchProject = (};/**- * Write the server's board id into a *hydrated* project's gallery state.- *- * Patching the document before rehydration is not enough on its own. A project saved by a build- * that never opened its Gallery widget — or one whose document predates widget instances entirely —- * has no gallery values for the patch to land in, and the instance the reducer creates during- * normalization arrives afterwards, empty. Such a project would then show the placeholder board row- * forever and route nothing at its own board, which is the one thing the server is authoritative- * about.- *- * Applied after normalization, so the instance exists. A project whose layout has no gallery widget- * at all is returned untouched: there is nothing to tell.+ * Assign the server board after normalization creates missing gallery instances. Projects with no gallery layout+ * remain unchanged.*/export const withAuthoritativeProjectBoard = (project: Project, boardId: string): Project =>updateProjectWidgetValues(project, 'gallery', (values) =>@@ -1921,11 +1812,7 @@ const getNextProjectIndex = (projects: Project[]): number => {return Math.max(0, ...usedIndices) + 1;};-/**- * A fresh, never-saved project. Ids carry entropy rather than an index so a- * draft can never collide with a project that already exists on the server- * (which an autosave would then silently overwrite).- */+/** Use collision-resistant ids so a draft autosave cannot overwrite an existing server project. */export const createDraftProject = (projects: Project[], account?: WorkbenchState['account']): Project =>createProject(getNextProjectIndex(projects),@@ -1952,11 +1839,7 @@ const updateActiveProject = (state: WorkbenchState, getProject: (project: Projecreturn didChange ? { ...state, projects } : state;};-/**- * Which of `regions` a panel toggle should collapse or expand: empty ones are- * left alone, so toggling never opens a panel with nothing in it (and never- * writes drift into a preset that ships a region collapsed).- */+/** Ignore empty regions so toggling panels cannot open blank panels or alter preset collapse state. */export const resolvePanelToggle = (widgetRegions: Record<WidgetRegion, Pick<WidgetRegionState, 'instanceIds' | 'isCollapsed'>>,regions: readonly WidgetRegion[]@@ -2022,10 +1905,7 @@ const openPanelForRegion = (layout: ProjectLayoutState, region: WidgetRegion): P});const cloneLayoutPresetSnapshot = (snapshot: LayoutPresetSnapshot): LayoutPresetSnapshot => {- // Every account preset is rebuilt through here on load, so a field missing- // from this clone is a field the preset silently loses on the next reload.- // A preset saved while the retired canvas editors were widgets still carries- // their instances; shedding them here keeps an applied preset drift-free.+ // Strip retired editor instances when rebuilding account presets to keep applied layouts drift-free.const retired = new Set(Object.values(snapshot.widgetInstances).filter((instance) => RETIRED_WIDGET_TYPE_IDS.has(instance.typeId))@@ -2276,17 +2156,8 @@ const normalizeWorkbenchState = (state: WorkbenchState): WorkbenchState => {// (they live in the settings store now) and must not resurface here.const account = normalizeWorkbenchAccount(state.account);const restored = state.projects.map((project) => normalizeWorkbenchProject(project));- // An editor always holds a project: `closeProject` refuses the last tab, and a- // session with none is the Home screen, whose cache the load paths are meant to- // replace with a fresh draft before handing the state over. One path does not --- // when a project the canvas gate refused cannot be retained, the cached snapshot- // is returned verbatim, and that cache is projectless whenever the last tab was- // closed before the reload. Hydrating it leaves the store's active project- // undefined, and the first consumer to read it dereferences undefined rather than- // finding an empty editor: the boot widget hint, whose first access happens to be- // `widgetRegions`, before the shell renders anything. Seed the draft here, at the- // one point every load path passes through, so no snapshot can hydrate without a- // project regardless of which path produced it.+ // Every hydrated editor needs an active project, including projectless cached snapshots returned after canvas+ // recovery fails; seed a draft here for all load paths.const projects = restored.length > 0 ? restored : [createDraftProject([], account)];const activeProjectId = projects.some((project) => project.id === state.activeProjectId)? state.activeProjectId@@ -2357,13 +2228,8 @@ const applyLayoutPresetToProject = (project: Project, preset: LayoutPreset): Pro: createWidgetInstance(instance.typeId, instance.id);}- // A preset is a full placement reset, so the project's own floating windows- // go: keeping one would double-render whatever the preset docks. The- // preset's are restored in their place — a preset saved while a widget- // floated has it in no region, and dropping them both would leave the- // instance nowhere at all. Preset bodies reach us from account storage- // without passing through `normalizeWorkbenchProject`, so they are validated- // and reconciled here on the same terms as a persisted project.+ // Presets replace all placements, including floating windows. Validate account-stored windows here because+ // presets bypass normalizeWorkbenchProject.const placement = reconcileFloatingWidgets(cloneLayoutPresetWidgetRegions(snapshot.widgetRegions),normalizeFloatingWidgets(snapshot.floatingWidgets, widgetInstances)@@ -2424,11 +2290,7 @@ const updateActiveInvocation = (};});-/**- * Applies the auto-switch route rule to a project after a high-confidence- * edit. Deliberately no undo entry or event: the route change rides the- * edit's own project update, matching the workflow auto-source precedent.- */+/** Auto-routing shares the triggering edit's update and creates no separate undo entry or event. */const applyAutoRouteForEdit = (project: Project,sourceId: InvocationSourceId,@@ -2443,26 +2305,13 @@ const applyAutoRouteForEdit = (return invocation === project.invocation ? project : { ...project, invocation };};-/**- * The generate widget doubles as Canvas's parameter panel — canvas invocations- * compile from generate values (prepareCanvasInvocation) and canvasDimsSync- * mirrors generate dims onto the bbox — so generate edits never steal the- * route from an active canvas source.- */+/** Generate also supplies Canvas parameters and dimensions, so its edits must not steal an active Canvas route. */const applyAutoRouteForGenerateEdit = (project: Project, context: WorkbenchReducerContext): Project =>project.invocation.sourceId === 'canvas' ? project : applyAutoRouteForEdit(project, 'generate', context);/**- * Bringing a graph-bearing widget to the front is as strong a statement of- * intent as editing one: someone who clicks the Video tab and presses Invoke- * means the video parameters, not whichever surface they last touched. Reveal- * therefore feeds the same policy as an edit, through the same preference and- * lock gates, so the surface in front of you is the surface that runs.- *- * Non-graph widgets (gallery, layers, ...) resolve to no source and leave the- * route alone, and generate keeps its canvas exception for the reason given- * above -- the canvas parameter panel *is* the generate widget, so revealing it- * must not steal the route from an active canvas source.+ * Revealing a graph widget expresses invocation intent through the same lock/preference gates as editing; Generate+ * retains the Canvas exception.*/const applyAutoRouteForWidgetReveal = (project: Project,@@ -2488,14 +2337,8 @@ const applyAutoRouteForRevealedInstance = (): Project => applyAutoRouteForWidgetReveal(project, project.widgetInstances[instanceId]?.typeId, context);/**- * Reveal for the paths where the front widget changes as a *consequence* of- * something else — closing a tab, dragging one out of a rail, reordering — as- * opposed to the paths where the gesture names the widget outright.- *- * Only an actual change of the visible front widget counts. Closing a- * background tab leaves the same panel in front and must not re-target Invoke,- * and a region that ends collapsed (or whose `activeInstanceId` is left- * dangling by the last removal) has revealed nothing at all.+ * Consequential tab changes route only when a different widget becomes visible; background closes, collapsed+ * regions, and dangling pointers reveal nothing.*/const applyAutoRouteForRegionFront = (project: Project,@@ -2530,8 +2373,7 @@ const compileInvocationSnapshot = (const randDevice = resolveRandDeviceMetadata(project.settings.useCpuNoise, getGenerationDevicesSnapshot().options);if (route.sourceId === 'workflow') {- // Compiles the workflow document into an immutable snapshot. Templates are- // read imperatively; route validation already guaranteed they are loaded.+ // Route validation guarantees templates are loaded before this imperative read.const templatesSnapshot = getInvocationTemplatesSnapshot();if (templatesSnapshot.status !== 'loaded') {@@ -2864,9 +2706,8 @@ const removeGalleryItemsFromAllProjects = (return { ...clearDeletedUpscaleInput(values, removedImageNames) };});- // The sweep runs against the RAW slots: normalizing first would let a- // reference masked by the first-frame/initial-video exclusion survive the- // deletion and resurface later as a dangling media name.+ // Sweep raw slots before normalization so mutually excluded media references cannot survive deletion and+ // reappear later.const withoutVideoMedia = updateProjectWidgetValues(withoutUpscaleInput, 'video', (rawValues) =>clearDeletedVideoMedia(rawValues, removedImageNames, removedVideoNames));@@ -2903,8 +2744,6 @@ const reconcileDeletedGalleryBoard = (return {...values,- // Same rule as `selectGalleryBoard`: the view is moving to another- // board, so a ranking shown against the old one goes with it....(selectedBoardWasDeleted? { galleryPage: 0, selectedBoardId: 'none', semanticImageQuery: null, semanticSearchText: null }: {}),@@ -2934,13 +2773,7 @@ const reconcileDeletedGalleryBoard = (return didChangeQueue ? { ...withBoardReferencesCleared, projects } : withBoardReferencesCleared;};-/**- * A deliberate selection pauses live-follow. It is also stamped, so that a- * generation submitted AFTER the pick can still take the preview when it lands- * while one that was already running when the user picked cannot; submitting- * resumes live-follow (`shouldResumeLiveFollowOnSubmit`). An explicit toggle of- * the setting speaks for every generation and lifts the stamp.- */+/** A deliberate selection pauses live-follow; only generations submitted after that selection may take the preview. */const updateGalleryValuesAndPauseLiveFollow = (state: WorkbenchState,getValues: (values: Record<string, unknown>) => Record<string, unknown>,@@ -2963,19 +2796,11 @@ const getLiveFollowPausedAt = (project: Project): string | null => {return typeof pausedAt === 'string' ? pausedAt : null;};-/**- * Submitting new work is the counter-signal to a selection pause: the user- * wants to watch what they just asked for. An explicit opt-out of live-follow- * carries no pause stamp and is left alone.- */+/** Submission resumes selection-paused live-follow, but preserves an explicit opt-out. */const shouldResumeLiveFollowOnSubmit = (project: Project): boolean =>!project.settings.showProgressImagesInViewer && getLiveFollowPausedAt(project) !== null;-/**- * Whether a result may take the selection given the user's last deliberate- * pick: only if its generation was submitted after that pick. The batch that- * was running when the user picked stays out of the way.- */+/** Only generations submitted after the deliberate selection may replace it. */const isSubmittedAfterLiveFollowPause = (project: Project, image: GalleryImage | undefined): boolean => {const pausedAt = getLiveFollowPausedAt(project);@@ -3149,13 +2974,8 @@ const routeQueueItemResults = (project: Project, queueItemId: string, images: Gereturn updateGalleryWithResultImages(nextProject, images);}- // A canvas generation belongs to the canvas SESSION it was submitted against,- // identified by `documentRevision` (bumped only on wholesale swaps — new canvas,- // snapshot restore, project sync — never on ordinary edits, and captured in the- // queue item's canvas snapshot at submit time). If a fresh session started while- // this generation was in flight, its results belong to a document that no longer- // exists; routing them would resurrect staging on the brand-new canvas (F2). Keep- // the completed status, but drop the staged candidates.+ // Stage results only into the submitted documentRevision; wholesale canvas swaps invalidate staging while+ // preserving completion status.if (queueItem && queueItem.snapshot.canvas.documentRevision !== nextProject.canvas.documentRevision) {return nextProject;}@@ -3171,11 +2991,7 @@ const routeQueueItemResults = (project: Project, queueItemId: string, images: Gereturn stageCanvasResultImages(nextProject, queueItemId, images, sourceBackendItemIds, previousSelectedSlot);};-/**- * Enqueues an already-compiled graph snapshot. Shared by the route-validated- * `submitInvocationSnapshot` and the canvas engine's `submitCanvasInvocationSnapshot`,- * whose graph is compiled asynchronously outside the reducer.- */+/** Enqueue compiled snapshots from route validation or asynchronous canvas preparation. */const enqueueCompiledSnapshot = (project: Project,route: InvocationRoute,@@ -3217,22 +3033,11 @@ const enqueueCompiledSnapshot = (: route.sourceId === 'video'? videoSettings: null;- // The prompts that actually generate: the authored text wrapped by the active- // prompt template. Computed once here because this is the only place every- // Generate-shaped route converges — `generate` and `canvas` both land here, as- // do the topbar, hotkey and graph-preview submits. Upscale carries no template- // and merges to identity.+ // Resolve template-merged prompts here, where Generate and Canvas submissions converge; Upscale merges to+ // identity.const effectivePrompts = sourceGenerateSettings ? getEffectivePrompts(sourceGenerateSettings) : null;- // Dynamic prompting is a Generate setting, so only the routes compiled from- // GenerateSettings honour it; Upscale keeps its prompt literal. The caller has- // already expanded, so the queue item records the exact prompts it will submit.- //- // A one-prompt expansion counts: `a {red} cat` and a random sample of one both- // resolve to a single concrete prompt, and dropping it here would fall the- // submission back to the authored text — sending the literal `{…}` to the model.- //- // The gate reads the *merged* prompt: a template may introduce `{a|b}` that the- // authored prompt never had, and the caller expanded the merged text too.+ // Record expansions for Generate routes even when only one prompt results. Inspect merged prompts because+ // templates may introduce dynamic syntax.const expandedPositivePrompts =route.sourceId !== 'upscale' &&route.sourceId !== 'video' &&@@ -3245,10 +3050,7 @@ const enqueueCompiledSnapshot = (const expandedSeedBehaviour = expandedPositivePrompts? (canvasGenerateSettings ?? generateSettings)?.dynamicPromptsSeedBehaviour: undefined;- // The seed was resolved when the graph compiled (random modes drew it then),- // so `seed` is this submission's start. The plan fixes how the batch steps- // from it and where the editable seed goes next; a submission that fails or- // is cancelled later keeps its seeds — the sequence only ever moves forward.+ // Compilation already reserved the starting seed; failures and cancellations do not roll the sequence back.const seedPlan = sourceGenerateSettings? planSeedSubmission({batchCount: sourceGenerateSettings.batchCount,@@ -3269,10 +3071,8 @@ const enqueueCompiledSnapshot = (graph: backendGraph,kind: 'workflow',...(compiled.workflowJson ? { workflow: compiled.workflowJson } : {}),- // Provenance for the completed-run capture: a run submitted from a- // library-bound graph knows which record to stamp, even after the- // editor has moved on to another workflow. An unbound graph stamps- // nothing, so an ad-hoc workflow never writes to the library.+ // Capture the library binding at submission so completion updates the originating workflow even after+ // the editor changes....(project.projectGraph.libraryWorkflowId? { libraryWorkflowId: project.projectGraph.libraryWorkflowId }: {}),@@ -3282,9 +3082,7 @@ const enqueueCompiledSnapshot = (batchCount: sourceGenerateSettings.batchCount,graph: backendGraph,kind: 'generate',- // A disabled negative prompt stays empty, which also suppresses the- // template's negative side — switching the field off must not let a- // template put one back.+ // Disabling the negative prompt also suppresses the template's negative side.negativePrompt: sourceGenerateSettings.negativePromptEnabled ? effectivePrompts.negativePrompt : '',negativePromptNodeId: generate?.negativePromptNodeId ?? 'negative_prompt',positivePrompt: effectivePrompts.positivePrompt,@@ -3347,8 +3145,7 @@ const enqueueCompiledSnapshot = (? 1: backendSubmission.batchCount * (expandedPositivePrompts?.length ?? 1),height: presentationDimensions.height,- // The merged prompt, so the queue row reads the same before and after the- // backend session arrives with its own (already merged) field values.+ // Use merged prompts so queue text stays consistent when the backend session arrives....(effectivePrompts?.positivePrompt ? { positivePrompt: effectivePrompts.positivePrompt } : {}),width: presentationDimensions.width,},@@ -3366,11 +3163,8 @@ const enqueueCompiledSnapshot = (status: 'pending',};- // A stepping mode hands the next seed to the editable settings in the same- // transition that queues the batch, so submissions queued back to back- // continue the sequence. The canvas compiles outside the reducer, so its plan- // may be stale by the time it lands: only settings still at the submitted- // seed and mode are advanced; an edit made meanwhile is the user's, and stays.+ // Advance seeds atomically with enqueueing; for async Canvas submissions, preserve any settings edited since+ // compilation.const advancedProject =seedPlan !== null && seedPlan.nextSeed !== null? updateProjectWidgetValues(project, route.sourceId === 'canvas' ? 'generate' : route.sourceId, (values) =>@@ -3473,8 +3267,6 @@ export const __workbenchReducerInternal = (return { ...state, activeProjectId: project.id, projects: [...state.projects, project] };}case 'openProject': {- // Hydrated from the library (Open dialog or a deep link). Opening an- // already-open project just focuses its tab.if (state.projects.some((project) => project.id === action.project.id)) {return { ...state, activeProjectId: action.project.id };}@@ -3811,8 +3603,7 @@ export const __workbenchReducerInternal = (...project.widgetInstances,[instanceId]: createWidgetInstance(action.widgetId, instanceId, action.initialValues),};- // Placing an instance into a region implicitly docks it: an instance- // must never render in a panel and a floating window at once.+ // Placing an instance docks it to prevent simultaneous region/window rendering.const { [instanceId]: _floated, ...floatingWidgets } = project.floatingWidgets ?? {};return applyAutoRouteForWidgetReveal(@@ -3840,9 +3631,7 @@ export const __workbenchReducerInternal = (return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => {const region = project.widgetRegions[action.region];- // Selecting a slot names the instance as the region's shown surface, so- // it docks: an instance must never render in a panel and a floating- // window at once — the same rule `openRegionWidget` enforces.+ // Selecting a region slot docks the instance to prevent simultaneous region/window rendering.const { [action.widgetId]: _floated, ...floatingWidgets } = project.floatingWidgets ?? {};if (action.region === 'center') {@@ -3860,10 +3649,7 @@ export const __workbenchReducerInternal = ();}- // Clicking the already-active tab toggles the rail's disclosure rather- // than switching tabs. Expanding it puts that panel back on screen and- // is a reveal like any other; collapsing it puts nothing in front, so- // the route stays exactly where it is.+ // Expanding the active tab reveals its widget and may route; collapsing reveals nothing.if (region.activeInstanceId === action.widgetId) {const disclosed = {...project,@@ -3927,9 +3713,6 @@ export const __workbenchReducerInternal = (return project;}- // Closing the front tab promotes a new one, which is a reveal; closing- // a background tab changes nothing on screen and must leave the route- // alone. `applyAutoRouteForRegionFront` draws exactly that line.return applyAutoRouteForRegionFront(nextProject, previousRegion, action.region, context);});}@@ -3939,12 +3722,8 @@ export const __workbenchReducerInternal = (return project;}- // One instance may be a member of several regions (the preview is- // placed in the center and a rail by default), so the region the float- // was asked from — the chrome whose button was clicked — decides where- // the window docks back to. The unhinted fallback takes the first- // member region in the region map's order, which persisted projects- // do not agree on.+ // Use the clicked region as the dock-back origin for multi-region widgets; map order is not a stable+ // origin.const findHost = (match: (regionId: WidgetRegion, region: WidgetRegionState) => boolean) =>(Object.entries(project.widgetRegions) as [WidgetRegion, WidgetRegionState][]).find(([regionId, region]) =>match(regionId, region)@@ -3960,11 +3739,8 @@ export const __workbenchReducerInternal = (const [hostRegionId, hostRegion] = resolvedHostEntry;- // Floating may empty the center, unlike `toggleRegionWidget` and- // `closeWidgetPlacement`, which still refuse the same removal: those- // discard the view outright, while a float keeps it one dock click- // away, and the emptied surface falls back to the center's fallback- // view rather than standing blank.+ // The reducer accepts center-origin floating and preserves its fallback; the UI float control only offers+ // dockable panel origins.const instanceIds = hostRegion.instanceIds.filter((instanceId) => instanceId !== action.instanceId);const fallbackInstanceId = getNextInstanceId(hostRegion, action.instanceId);const floating: FloatingWidgetState = {@@ -3988,10 +3764,7 @@ export const __workbenchReducerInternal = (? (fallbackInstanceId ?? emptiedActiveInstanceId(hostRegionId, hostRegion)): hostRegion.activeInstanceId,instanceIds,- // Floating the last widget out of a rail leaves nothing to show,- // so the rail collapses rather than standing open and empty —- // the same repair `toggleRegionWidget` makes. The center has no- // collapsed state; its fallback view carries the empty surface.+ // Empty rails collapse; an empty center uses its fallback view.isCollapsed: instanceIds.length === 0 && hostRegionId !== 'center' ? true : hostRegion.isCollapsed,},},@@ -4038,8 +3811,6 @@ export const __workbenchReducerInternal = (});}case 'closeFloatingWidget': {- // The window is the instance's only placement, so closing it is one- // change: the entry goes, nothing docks, and no surface is revealed.return updateActiveProject(state, (project) => {if (!project.floatingWidgets?.[action.instanceId]) {return project;@@ -4065,9 +3836,7 @@ export const __workbenchReducerInternal = (y: action.y,});- // A pointer-down/up on the title bar with no movement still commits the- // starting geometry. Without this the project is marked dirty — and- // autosaved — every time someone clicks the window chrome.+ // Ignore unchanged geometry so clicking window chrome does not dirty or autosave the project.if (floating.heightPx === geometry.heightPx &&floating.widthPx === geometry.widthPx &&@@ -4102,20 +3871,13 @@ export const __workbenchReducerInternal = (const floating = project.floatingWidgets?.[action.instanceId];const topOrder = nextStackOrder(project.floatingWidgets) - 1;- // `focusFloatingWidget` is bound to `onPointerDownCapture` on the window- // root, so it fires on every scroll, drag, and button press inside the- // window — not just on a raise. Routing therefore stays behind this- // shortcut: raising a window reveals it, but touching the window that- // is already on top reveals nothing and must not re-target Invoke or- // dirty the project.+ // Pointer capture runs for every interaction inside the window; only raising it should re-route or dirty+ // the project.if (!floating || floating.stackOrder === topOrder) {return project;}- // Renumbered to a compact 1..N rather than appended above the current- // top. `stackOrder` is persisted, so a counter that only ever climbs- // writes ever-larger numbers into the document for what is really a- // reordering of the same few windows.+ // Compact persisted stackOrder to 1..N rather than growing it on every raise.const below = Object.entries(project.floatingWidgets ?? {}).filter(([instanceId]) => instanceId !== action.instanceId).sort(([, left], [, right]) => left.stackOrder - right.stackOrder);@@ -4161,8 +3923,7 @@ export const __workbenchReducerInternal = (},},},- // The dragged widget lands expanded and selected in the target- // region; the tab the source region promotes behind it did not move.+ // The dragged widget is revealed in the target; the promoted source tab stays behind it.action.instanceId,context);@@ -4705,9 +4466,7 @@ export const __workbenchReducerInternal = (selectedImageName: toGalleryItemKey(action.primaryItem),selectedImageNames: action.itemKeys,selectedImagePage,- // An explicit page comes from a host navigating its own window, and- // names a page of the query already on the selection — the same- // contract as `selectGalleryItem` with `preserveNavigationQuery`.+ // An explicit host page belongs to the selection's query, matching preserveNavigationQuery.selectedImageQuery:hasSelectionPage && existingNavigationQuery? { ...existingNavigationQuery, page: selectedImagePage }@@ -4740,20 +4499,8 @@ export const __workbenchReducerInternal = (galleryPage: 0,selectedBoardId: action.boardId,selectedImageNames: [],- // A similarity ranking answers with images from wherever they live,- // so it is not a view OF any board: moving to one asks for that- // board's listing, and leaving the ranking up would answer with the- // same results under a new board name. Dismissed exactly as the- // chip's own clear does it — the query alone — and the semantic- // field leaves with its ranking, text and all. The positions on the- // selection are NOT rewritten here: a selection made before the- // search carries a real board page that the search never touched,- // and zeroing it would cost Preview the cursor it still has.- //- // Only on an actual move. Re-picking the board already shown is not- // a change of view, and a text or image reference survives a reload,- // so treating that click as a dismissal would erase persisted state- // (and autosave the loss) on what reads as a no-op.+ // Only actual board changes clear similarity ranking and semantic text. Preserve selection pages: they+ // may still describe the pre-search board listing....(values.selectedBoardId !== action.boardId ? { semanticImageQuery: null, semanticSearchText: null } : {}),}),action.projectId@@ -4774,12 +4521,7 @@ export const __workbenchReducerInternal = (galleryPage: 0,galleryView: action.galleryView,selectedImageNames: [],- // Same rule as `selectGalleryBoard`, and for the same reason: the- // Images/Assets tabs are two listings, and a ranking is a view of- // neither, so switching tabs asks for the listing rather than the- // same results relabelled. Only on an actual switch — an absent- // `galleryView` reads as Images, so re-clicking the tab already- // shown must stay the no-op it is today.+ // Actual Images/Assets switches clear ranking; an absent galleryView already means Images....((values.galleryView === 'assets' ? 'assets' : 'images') !== action.galleryView? { semanticImageQuery: null, semanticSearchText: null }: {}),@@ -4819,11 +4561,8 @@ export const __workbenchReducerInternal = (return values;}- // The text moves between the two interpretations rather than being- // lost: the sparkle only changes what the words mean. Entering- // applies them at once — a click is a deliberate act, not a- // keystroke to debounce — while leaving drops the ranking, since- // metadata search has its own listing.+ // Retain text across mode changes; entering semantic mode applies immediately, leaving clears its+ // ranking.if (action.enabled) {const text = typeof values.searchTerm === 'string' ? values.searchTerm : '';@@ -4859,10 +4598,7 @@ export const __workbenchReducerInternal = (return updateGalleryValues(state,(values) => {- // A commit arrives on a timer, after whatever it was scheduled- // against may have gone: the field emptied, the mode left, the board- // moved. Applying only what the field still holds makes every late- // timer harmless without the field having to track them.+ // Apply delayed commits only when they still match the current field, mode, and board.if (values.semanticSearchText !== action.text) {return values;}@@ -5319,8 +5055,7 @@ export const __workbenchReducerInternal = (case 'setActiveProjectSettings': {return updateActiveProject(state, (project) => {const settings = normalizeProjectSettings({ ...project.settings, ...action.settings });- // An explicit live-follow choice speaks for every generation, so it also- // lifts the pause a deliberate selection stamped.+ // Explicit live-follow clears any selection-imposed pause.const withoutPause =action.settings.showProgressImagesInViewer !== undefined && getLiveFollowPausedAt(project) !== null? updateProjectWidgetValues(project, 'gallery', ({ liveFollowPausedAt: _pausedAt, ...values }) => values)diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.tsindex f05af9e7b4..d7b2e2f3e1 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts@@ -180,8 +180,7 @@ describe('auto invocation route switching on widget reveal', () => {const region = getRegion(state, 'left');expect(region.instanceIds).toEqual([]);- // The route is left where it was rather than pointed at the emptied rail;- // route validation refuses an unmounted source separately.+ // Leave the route unchanged; validation separately rejects an unmounted source.expect(region.instanceIds).not.toContain(getInvocation(state).sourceId);});@@ -199,8 +198,6 @@ describe('auto invocation route switching on widget reveal', () => {const before = state;const beforeProject = getProject(state);- // The work surface refuses to give up its last view; the whole dispatch- // must therefore change nothing, including the invoke route.state = workbenchReducer(state, { region: 'center', type: 'toggleRegionWidget', widgetId: centerIds[0]! });expect(state).toBe(before);diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex 6635531c82..a3da47fd72 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -27,11 +27,7 @@ import {type __WorkbenchReducerActionInternal,} from './workbenchState';-/**- * Which widgets the shell shows: the active project, each region's active- * instance, and the floating windows. A change hides or replaces widgets, and- * an overlay open inside one would otherwise outlive it in its portal.- */+/** Visible-widget changes dismiss overlays that would otherwise outlive their widgets in portals. */const visibleWidgetsKey = (state: WorkbenchState): string => {const project = state.projects.find((candidate) => candidate.id === state.activeProjectId);if (!project) {@@ -51,11 +47,7 @@ type MechanicalCommand<Type extends WorkbenchAction['type']> = keyof ActionPaylo? () => void: (payload: ActionPayload<Type>) => void;-/**- * Mechanical commands forward one action to the reducer; their public types derive- * from the reducer's action union so the two cannot drift. The action union itself- * stays private — callers only ever see the named command.- */+/** Derive named command types from the private reducer action union to prevent drift. */const createCommandFactory = (dispatch: WorkbenchDispatch) => {function command<Type extends WorkbenchAction['type']>(type: Type): MechanicalCommand<Type>;function command<Type extends WorkbenchAction['type'], Args extends unknown[]>(@@ -172,10 +164,6 @@ const createCommands = (projectId,})),- /**- * TODO(Task 6/8): Remove after Gallery Grid, Preview, and the image- * command palette dispatch canonical items.- */selectImage: (image: GeneratedImageContract & Partial<GalleryImage>,projectId?: string,@@ -508,15 +496,8 @@ const createPersistenceAdapter = (dispatch: WorkbenchDispatch, getState: () => Wreturn {/**- * A project created by persistence learns its board from the create response.- *- * Recording the id is the whole write. It does *not* also select the board: the create response- * arrives a round trip after the draft appears, and forcing a selection then would overwrite- * whatever the person picked in the meantime. Nothing is lost by leaving it —- * `getGallerySelectedBoardId` already falls back to the project's board when the saved- * selection does not resolve, which is exactly this case. It matches hydration, which passes- * `selectBoard: false` for the same reason, and makes this idempotent, which matters because- * an assignment can be applied from a save whose snapshot has already moved on.+ * Record the server-assigned board without selecting it: the user may have changed selection during creation,+ * and unresolved selections already fall back to the project board.*/assignProjectBoard: ({ boardId, projectId }: { boardId: string; projectId: string }) => {dispatch({ boardId, projectId, type: 'setGalleryProjectBoardId' });diff --git a/invokeai/frontend/webv2/src/workbench/workflowRunBinding.test.ts b/invokeai/frontend/webv2/src/workbench/workflowRunBinding.test.tsindex 61fedcc851..370adb1ea3 100644--- a/invokeai/frontend/webv2/src/workbench/workflowRunBinding.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workflowRunBinding.test.ts@@ -1,17 +1,14 @@import type * as workflowReactModule from '@features/workflow/react';import type { WorkbenchState } from '@workbench/projectContracts';-// Feature-private document builders: the dependency policy exempts test files,-// and hand-rolling a compilable graph literal here would only duplicate them.+// Reuse feature-private graph builders under the test dependency exemption.import { buildInvocationNode, createProjectGraph, projectGraphReducer } from '@features/workflow/core/document';import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';import { beforeEach, describe, expect, it, vi } from 'vitest';/**- * The workflow compile site stamps the project graph's library binding onto the- * compiled submission, which is the only place a completed run can learn which- * library record produced it. Templates are read imperatively by both the route- * resolver and the compiler, so they are stubbed as loaded here.+ * Submission captures the originating library binding; stub loaded templates for the imperative resolver and+ * compiler.*/const stringField = { batch: false, cardinality: 'SINGLE' as const, name: 'StringField' };@@ -111,8 +108,6 @@ describe('library binding on the compiled workflow submission', () => {});});- // An ad-hoc workflow belongs to no library record, so a completed run of it- // must have nothing to write back to.it('leaves an unbound workflow run unstamped', () => {expect(submitWorkflow()?.snapshot.backendSubmission).not.toHaveProperty('libraryWorkflowId');});diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex 7b4cb99bde..05e61bed95 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -17,8 +17,7 @@ const ALLOWED_HOSTS = process.env.INVOKEAI_DEV_HOSTS?.split(',').filter(Boolean);const PROJECT_ROOT = fileURLToPath(new URL('.', import.meta.url));-// Modules both routes fetch eagerly. Grouping keeps a module with two-// consumers from being split into its own request on each route.+// Group eager dependencies shared by both routes to avoid extra chunk requests.const ROUTE_SHARED_MODULES = ['/features/fonts/data/keys.ts','/features/fonts/launchpad.tsx',@@ -65,11 +64,7 @@ const ROUTE_SHARED_MODULES = ['/workbench/settings/SettingsDialogHost.tsx',] as const;-// Modules every editor boot fetches (topbar UI plus the realtime runtime the-// widget hosts share), folded into one chunk so they cost bytes, not requests.-// The generation runtime, capability store and prompt-attention modules are-// imported by the app shell and by several lazy widget chunks; left to the-// bundler, each set becomes its own request on every editor route.+// Group dependencies shared by the editor shell and lazy widgets to reduce boot requests.const EDITOR_BOOT_SHARED_MODULES = ['/app/GalleryUiAdapter.tsx','/features/gallery/picker.ts',@@ -95,16 +90,13 @@ const EDITOR_BOOT_SHARED_MODULES = ['/features/generation/queries.ts','/features/generation/runtime.ts','/features/generation/ui/promptFields/promptAttentionHotkeys.ts',- // Shared by the Generate/Upscale/Video seed row and workflow seed inputs; left to rolldown it- // splits into a chunk every editor route would fetch separately.'/platform/ui/SeedInput.tsx','/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx','/workbench/shell/topbar/LayoutPresetStrip.tsx','/workbench/shell/topbar/ProjectSwitcher.tsx',] as const;-// Widget metadata shared by the registry, settings and palette; kept apart-// from editor boot UI so Launchpad settings cannot pull in the editor.+// Keep widget metadata separate so Launchpad settings cannot import editor boot UI.const WIDGET_METADATA_MODULES = ['/features/gallery/settingsContribution.ts','/features/queue/widget.ts',@@ -138,9 +130,7 @@ const GALLERY_STATE_MODULES = ['/features/queue/data/events.ts',] as const;-// The widget hosts the editor mounts once at boot, in one chunk instead of-// one request per host. Small helpers shared by lazy widget chunks ride along:-// every editor route loads this chunk, Launchpad never does.+// Group boot-mounted widget hosts and their shared helpers; Launchpad must not load this chunk.const WIDGET_HOST_MODULES = ['/platform/react/focusIfUnclaimed.ts','/features/queue/ui/QueueDataRuntime.tsx',@@ -148,8 +138,7 @@ const WIDGET_HOST_MODULES = ['/workbench/widgets/image-map/ImageMapDataRuntime.tsx',] as const;-// Canvas and Layers already load these interaction/form modules together.-// Keep their shared text-tool consumers from creating extra activation requests.+// Group Canvas/Layer interaction dependencies to avoid extra text-tool activation requests.const CANVAS_LAYER_SHARED_MODULES = ['/features/workflow/core/layerWorkflow.ts','/workbench/canvas-operations/react.ts',@@ -246,8 +235,7 @@ const getLegacyChunkName = (id: string): string | null => {export default defineConfig({define: {- // A boolean, not a code string: Vitest 5 browser mode injects string- // values as string literals, and "false" is truthy.+ // Use a boolean: Vitest browser mode treats string defines as truthy string literals.__CANVAS_GOLDEN_UPDATE__: false,},base: './',diff --git a/invokeai/frontend/webv2/vitest.browser.config.mts b/invokeai/frontend/webv2/vitest.browser.config.mtsindex c8464f1c33..b0110e5b1b 100644--- a/invokeai/frontend/webv2/vitest.browser.config.mts+++ b/invokeai/frontend/webv2/vitest.browser.config.mts@@ -10,10 +10,7 @@ export default mergeConfig(define: {__CANVAS_GOLDEN_UPDATE__: process.env.CANVAS_GOLDEN_UPDATE === '1',},- // Dependencies reached by browser tests must be prebundled into the initial- // graph. Late optimization reloads invalidate active Vitest suites, and- // React-bound dependencies can also leave two React instances in the graph- // and produce invalid-hook failures.+ // Prebundle browser-test dependencies to prevent optimizer reloads and duplicate React instances.optimizeDeps: {include: ['@chakra-ui/react',