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
fix(webv2): contain title-bar chrome failures and keep its gestures scoped
Lincoln Stein8fcf8d89fc05
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 71e21b8caa..47644ecf7d 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@@ -1,6 +1,11 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop */import type { FloatingWidgetState } from '@workbench/layoutContracts';-import type { RegisteredWidget, WidgetImplementation, WidgetManifest } from '@workbench/widgetContracts';+import type {+ RegisteredWidget,+ WidgetImplementation,+ WidgetManifest,+ WidgetViewProps,+} from '@workbench/widgetContracts';import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';@@ -20,7 +25,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';*/const windowMocks = vi.hoisted(() => ({+ actionsRegion: null as string | null,dockFloating: vi.fn(),+ useFailingWidget: false,focusFloating: vi.fn(),setFloatingGeometry: vi.fn(),setFloatingMode: vi.fn(),@@ -45,7 +52,7 @@ vi.mock('@workbench/WorkbenchContext', () => ({vi.mock('@workbench/WorkbenchWidgetRegistryContext', () => ({useWorkbenchWidgetRegistry: () => ({- getWidgetById: () => registeredWidget,+ getWidgetById: () => (windowMocks.useFailingWidget ? failingWidget : registeredWidget),getWidgetsForRegion: () => [],}),}));@@ -56,6 +63,9 @@ vi.mock('./createWidgetRuntime', () => ({ useWidgetRuntime: () => ({}) }));import { FloatingWidgetWindow } from './FloatingWidgetWindow';+// `settingsSection` and `headerMenu` are what separate the widget's own+// actions from the full header cluster: were the window to mount the `actions`+// slot instead, the settings gear and the overflow trigger would appear here.const manifest = {allowFloating: true,allowedRegions: ['center', 'left', 'right'],@@ -63,15 +73,21 @@ const manifest = {icon: MapIcon,id: 'image-map',label: () => 'Image Map',+ settingsSection: 'image-map',version: 1,} as unknown as WidgetManifest;const implementation: WidgetImplementation = {- headerActions: () => (- <button aria-label="Toggle cluster labels" type="button">- <TagsIcon />- </button>- ),+ headerActions: ({ region }: WidgetViewProps) => {+ windowMocks.actionsRegion = region;++ return (+ <button aria-label="Toggle cluster labels" type="button">+ <TagsIcon />+ </button>+ );+ },+ headerMenu: () => <div data-testid="header-menu" />,view: () => <div data-testid="map-body" />,};@@ -82,6 +98,18 @@ const registeredWidget = {status: 'enabled',} as unknown as RegisteredWidget;+const failedLoad = Promise.reject(new Error('chunk unavailable'));+// Nothing awaits this before the render that consumes it; an unhandled+// rejection would fail the run on its own.+failedLoad.catch(() => undefined);+const failingWidget = {+ implementation: { load: () => failedLoad, retry: () => {} },+ // The body isolates its own failure, so only the title bar's containment is+ // under test here.+ manifest: { ...manifest, failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' } },+ status: 'enabled',+} as unknown as RegisteredWidget;+const state: FloatingWidgetState = {heightPx: 400,mode: 'windowed',@@ -131,7 +159,10 @@ const renderWindow = async (floatingState: FloatingWidgetState = state) => {};beforeEach(() => {+ windowMocks.actionsRegion = null;+ windowMocks.useFailingWidget = false;windowMocks.dockFloating.mockClear();+ windowMocks.setFloatingGeometry.mockClear();host = document.createElement('div');document.body.append(host);root = createRoot(host);@@ -145,11 +176,62 @@ afterEach(async () => {});describe('FloatingWidgetWindow chrome', () => {- it("mounts the widget's own header actions in the title bar", async () => {+ it("mounts the widget's own header actions in the title bar, for the floating region", async () => {await renderWindow();expect(host?.querySelector('button[aria-label="Toggle cluster labels"]')).not.toBeNull();expect(host?.querySelector('[data-testid="map-body"]')).not.toBeNull();+ expect(windowMocks.actionsRegion).toBe('floating');+ });++ it('leaves the frame-level chrome to the window, which carries its own', async () => {+ await renderWindow();++ // The manifest has a settings section and the implementation a header+ // menu, so the full actions cluster would put both in this bar.+ expect(host?.querySelector('button[aria-label*="settings"]')).toBeNull();+ expect(host?.querySelector('button[aria-label*="actions"]')).toBeNull();+ expect(host?.querySelector('button[aria-label="Float Window"]')).toBeNull();+ expect(host?.querySelector<HTMLButtonElement>('button[aria-label="Dock to panel"]')).not.toBeNull();+ });++ it('keeps the window usable when the widget implementation fails to load', async () => {+ windowMocks.useFailingWidget = true;++ 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.+ expect(host?.querySelector('button[aria-label="Toggle cluster labels"]')).toBeNull();+ expect(host?.querySelector<HTMLButtonElement>('button[aria-label="Dock to panel"]')).not.toBeNull();+ });++ it('does not move the window when an arrow key is pressed on a widget action', async () => {+ await renderWindow();++ const toggle = host?.querySelector<HTMLButtonElement>('button[aria-label="Toggle cluster labels"]');++ await act(async () => {+ toggle?.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowRight' }));+ await Promise.resolve();+ });++ expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();+ });++ it('still moves the window when an arrow key is pressed on the title bar itself', async () => {+ await renderWindow();++ const titleBar = host?.querySelector<HTMLElement>('[aria-label="Move Image Map window"]');++ await act(async () => {+ titleBar?.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowRight' }));+ await Promise.resolve();+ });++ expect(windowMocks.setFloatingGeometry).toHaveBeenCalled();});it('keeps the widget actions reachable while the window is shaded', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsxindex b566ded519..5590a393d6 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx@@ -23,6 +23,7 @@ import {TriangleAlertIcon,} from 'lucide-react';import {+ Component,Suspense,useCallback,useEffect,@@ -31,6 +32,7 @@ import {type KeyboardEvent as ReactKeyboardEvent,type MouseEvent as ReactMouseEvent,type PointerEvent as ReactPointerEvent,+ type ReactNode,} from 'react';import { useTranslation } from 'react-i18next';@@ -42,6 +44,43 @@ const FLOATING_BASE_Z_INDEX = 800;/** Keyboard step for moving and resizing, matching the panel resize handles. */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.+ */+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.+ */+class FloatingChromeBoundary extends Component<{ children: ReactNode }, { hasFailed: boolean }> {+ state = { hasFailed: false };++ static getDerivedStateFromError(): { hasFailed: boolean } {+ return { hasFailed: true };+ }++ render() {+ return this.state.hasFailed ? null : this.props.children;+ }+}+/*** One detached widget window: fixed-position chrome with a draggable title* bar, a corner resize handle, shade/maximize/dock controls, and the standard@@ -172,7 +211,12 @@ export const FloatingWidgetWindow = ({};const offset = offsets[event.key];- if (!offset || state.mode === 'maximized') {+ // 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.+ if (!offset || state.mode === 'maximized' || event.target !== event.currentTarget) {return;}@@ -320,9 +364,13 @@ export const FloatingWidgetWindow = ({without this the docked header's controls would simply vanish onfloat. Frame-level actions stay out — this bar carries its own. */}{isEnabled && widget ? (- <Suspense fallback={null}>- <WidgetChromeSlotById instanceId={instanceId} region="floating" slot="viewActions" widget={widget} />- </Suspense>+ <FloatingChromeBoundary>+ <Suspense fallback={null}>+ <Box onDoubleClick={stopChromeEvent} onPointerDown={stopChromeEvent}>+ <WidgetChromeSlotById instanceId={instanceId} region="floating" slot="viewActions" widget={widget} />+ </Box>+ </Suspense>+ </FloatingChromeBoundary>) : null}<Tooltip content={isShaded ? t('widgets.floating.unshade') : t('widgets.floating.shade')}><IconButtondiff --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 39aa57a759..5cae5619f2 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@@ -138,8 +138,4 @@ describe('WidgetFloatButton', () => {expect(await renderButton('center')).not.toBeNull();});-- it('renders nothing inside a floating window, which carries the dock control', async () => {- expect(await renderButton('floating')).toBeNull();- });});diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsxindex ada7f19078..20475f4c62 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx@@ -43,7 +43,13 @@ type WidgetChromeSlotName = 'actions' | 'label' | 'viewActions';interface WidgetChromeSlotByIdProps {instanceId: string;- /** The region the hoisted chrome acts for. Defaults to the center region. */+ /**+ * 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.+ */region?: WorkbenchRegion;slot: WidgetChromeSlotName;widget: RegisteredWidget;