Skip to content

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.

fix(webv2): report dropped preset activations

joshistoast6e1bd519db55
diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.ts
index 6a617cfacf..b2706cf4e8 100644
--- a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.ts
@@ -28,13 +28,47 @@ describe('layout preset activation', () => {
const editActivation = activator.activate(layoutPresets[1]);
editLoad.resolve();
- await editActivation;
+ await expect(editActivation).resolves.toBe('edit');
composeLoad.resolve();
- await composeActivation;
+ await expect(composeActivation).resolves.toBeNull();
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.
+ it('reports the dropped activation when the active project changed under it', async () => {
+ const appliedPresetIds: string[] = [];
+ let activeProjectId = 'project-a';
+ const activator = createLayoutPresetActivator({
+ apply: (presetId) => appliedPresetIds.push(presetId),
+ applyDeadlineMs: 0,
+ getActiveProjectId: () => activeProjectId,
+ isCurrent: () => true,
+ load: () => new Promise(() => {}),
+ });
+
+ const activation = activator.activate(layoutPresets[0]);
+ activeProjectId = 'project-b';
+
+ await expect(activation).resolves.toBeNull();
+ expect(appliedPresetIds).toEqual([]);
+ });
+
+ it('reports the dropped activation when the preset definition was replaced under it', async () => {
+ const appliedPresetIds: string[] = [];
+ const activator = createLayoutPresetActivator({
+ apply: (presetId) => appliedPresetIds.push(presetId),
+ applyDeadlineMs: 0,
+ getActiveProjectId: () => 'project-a',
+ isCurrent: () => false,
+ load: () => new Promise(() => {}),
+ });
+
+ await expect(activator.activate(layoutPresets[0])).resolves.toBeNull();
+ expect(appliedPresetIds).toEqual([]);
+ });
+
it('applies at the deadline when a widget implementation is still loading', async () => {
const appliedPresetIds: string[] = [];
const activator = createLayoutPresetActivator({
@@ -45,7 +79,7 @@ describe('layout preset activation', () => {
load: () => new Promise(() => {}),
});
- await activator.activate(layoutPresets[0]);
+ await expect(activator.activate(layoutPresets[0])).resolves.toBe(layoutPresets[0].id);
expect(appliedPresetIds).toEqual([layoutPresets[0].id]);
});
@@ -63,7 +97,7 @@ describe('layout preset activation', () => {
const activation = activator.activate(layoutPresets[0]);
activator.invalidate();
- await activation;
+ await expect(activation).resolves.toBeNull();
expect(appliedPresetIds).toEqual([]);
});
diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.ts
index fc142f3e89..890d5d42dd 100644
--- a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.ts
+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.ts
@@ -47,14 +47,28 @@ export const createLayoutPresetActivator = ({
let latestRequestId = 0;
return {
- activate: async (preset: LayoutPreset): Promise<void> => {
+ /**
+ * Resolves to the preset id that was applied, or `null` if this activation
+ * was dropped — superseded by a later request, overtaken by a project
+ * switch, or aimed at a preset definition the account has since replaced.
+ *
+ * The outcome is reported rather than swallowed because callers paint the
+ * selection optimistically: a dropped activation that stayed silent would
+ * leave a control showing a preset the store never adopted, with nothing
+ * left to correct it.
+ */
+ activate: async (preset: LayoutPreset): Promise<LayoutPresetId | null> => {
const projectId = getActiveProjectId();
const requestId = ++latestRequestId;
await waitForLoadOrDeadline(load(preset), applyDeadlineMs);
- if (requestId === latestRequestId && projectId === getActiveProjectId() && isCurrent(preset)) {
- apply(preset.id);
+ if (requestId !== latestRequestId || projectId !== getActiveProjectId() || !isCurrent(preset)) {
+ return null;
}
+
+ apply(preset.id);
+
+ return preset.id;
},
invalidate: (): void => {
latestRequestId += 1;
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.tsx
index 72e5bae29c..c4e1e5dcaf 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
@@ -88,6 +88,21 @@ const mouse = (type: string, target: EventTarget, clientX: number, clientY: numb
);
};
+// A real press emits `pointerdown` before `mousedown`. dnd-kit's `MouseSensor`
+// only listens to the latter, but the strip acknowledges on the former, so a
+// drag simulation that skips it does not exercise what a user actually does.
+const pressDown = (target: EventTarget, clientX: number, clientY: number): void => {
+ target.dispatchEvent(
+ new PointerEvent('pointerdown', { bubbles: true, button: 0, cancelable: true, clientX, clientY })
+ );
+ mouse('mousedown', target, clientX, clientY);
+};
+
+const nextFrame = (): Promise<void> =>
+ new Promise((resolve) => {
+ requestAnimationFrame(() => resolve());
+ });
+
const touch = (
type: string,
target: EventTarget,
@@ -137,10 +152,13 @@ describe('LayoutPresetStrip', () => {
expect(store.getSnapshot().activeProject.layout.presetId).toBe('edit');
});
- it('reorders a dragged tab without activating it', async () => {
+ // 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.
+ it('selects a dragged tab on the press and reorders it in the same gesture', async () => {
await renderStrip();
await act(() => userEvent.click(presetTab('edit')!));
- const activeBeforeDrag = store.getSnapshot().activeProject.layout.presetId;
+ expect(store.getSnapshot().activeProject.layout.presetId).toBe('edit');
const source = presetTab('compose');
const target = presetTab('automate');
expect(source).not.toBeNull();
@@ -151,13 +169,18 @@ describe('LayoutPresetStrip', () => {
const startY = start.top + start.height / 2;
const endX = end.left + end.width / 2;
- await act(() => mouse('mousedown', source!, startX, startY));
+ await act(() => pressDown(source!, startX, startY));
+
+ expect(presetTab('compose')).toHaveAttribute('aria-selected', 'true');
+ expect(presetTab('edit')).toHaveAttribute('aria-selected', 'false');
+
await act(() => mouse('mousemove', source!.ownerDocument, startX + 8, startY));
await act(() => mouse('mousemove', source!.ownerDocument, endX, startY));
await act(() => mouse('mouseup', source!.ownerDocument, endX, startY));
+ await act(() => nextFrame());
expect(store.getSnapshot().account.layoutPresetOrder).toEqual(['custom-1', 'edit', 'automate', 'compose']);
- expect(store.getSnapshot().activeProject.layout.presetId).toBe(activeBeforeDrag);
+ expect(store.getSnapshot().activeProject.layout.presetId).toBe('compose');
});
it('supports keyboard reordering with sortable drag semantics', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx
index ab20c31ec4..5a6e07e229 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx
@@ -53,13 +53,6 @@ import { useActiveLayoutPresetId, useLayoutDrift } from './useLayoutDrift';
import { useTopbarShortcut } from './useTopbarShortcut';
const PRESET_MENU_ATTRIBUTE = 'data-preset-menu';
-// The selected paint is ours, not the tabs machine's: React writes this
-// attribute in the same commit as the press, so the tab cannot lag the press
-// even by a machine transition. Same tokens the `subtle` tabs recipe emits for
-// `_selected`, so the tab is pixel-identical to the one it replaces.
-const PRESET_TAB_ACTIVE_CSS = {
- '&[data-preset-active]': { bg: 'colorPalette.subtle', color: 'colorPalette.fg' },
-} as const;
const PRESET_SCROLL_CSS = { '&::-webkit-scrollbar': { display: 'none' }, scrollbarWidth: 'none' } as const;
const PRESET_TAB_KEYS_BLOCKED_DURING_DRAG = new Set(['ArrowDown', 'ArrowLeft', 'ArrowRight', 'End', 'Home']);
const DND_MODIFIERS = [restrictToHorizontalAxis, restrictToParentElement];
@@ -127,7 +120,15 @@ export const LayoutPresetStrip = () => {
(presetId: LayoutPresetId) => {
setPendingPresetId(presetId);
requestAnimationFrame(() => {
- void layout.activatePreset(presetId);
+ 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.
+ if (appliedPresetId !== presetId) {
+ setPendingPresetId((pending) => (pending === presetId ? null : pending));
+ }
+ });
});
},
[layout]
@@ -306,17 +307,21 @@ const PresetTab = ({
[onOpenMenu, preset]
);
- // The press, not the click, is what the user is waiting on. Chakra's tabs
- // machine would still land the selection correctly, but only after the click
- // it never sees until the button is released.
+ // 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.
const handlePointerDown = useCallback(
(event: PointerEvent<HTMLButtonElement>) => {
- // dnd-kit owns the drag gesture; chain rather than replace.
+ // 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.
(listeners as { onPointerDown?: (value: unknown) => void } | undefined)?.onPointerDown?.(event);
- const trigger = event.target instanceof Element ? event.target.closest(`[${PRESET_MENU_ATTRIBUTE}]`) : null;
-
- if (!trigger && !isActive) {
+ if (event.button === 0 && !isActive) {
onRequest(preset.id);
}
},
@@ -363,10 +368,8 @@ const PresetTab = ({
{...listeners}
aria-label={showDrift ? `${preset.label}, ${t('topbar.presets.unsaved')}` : preset.label}
aria-keyshortcuts={isActive ? 'ArrowDown' : undefined}
- css={PRESET_TAB_ACTIVE_CSS}
cursor={isDragging ? 'grabbing' : 'pointer'}
data-layout-preset-id={preset.id}
- data-preset-active={isActive ? '' : undefined}
gap="1.5"
style={dndStyle}
touchAction="pan-x"
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.tsx
index c89555b244..eebdeae500 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
@@ -10,15 +10,26 @@ import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
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.
let store: WorkbenchInternalStore;
-let activatePreset: (presetId: LayoutPresetId) => Promise<void> = () => Promise.resolve();
+
+// Rebuilt per render rather than read from a module slot at call time. The
+// strip dispatches activation from a `requestAnimationFrame`, so a frame that
+// outlives its test would otherwise reach into the *next* test's spy and
+// satisfy its assertions with a stale call.
+const noop = () => undefined;
+let commands = { layout: { activatePreset: (() => Promise.resolve(null)) as ActivatePreset } };
+
+const createCommands = (activatePreset: ActivatePreset) => ({
+ layout: { activatePreset, createPreset: noop, reorderPresets: noop, reset: noop, savePreset: noop },
+});
vi.mock('@workbench/WorkbenchContext', () => {
const useSnapshot = () => useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
- const noop = () => undefined;
return {
shallowEqual: Object.is,
@@ -27,15 +38,7 @@ vi.mock('@workbench/WorkbenchContext', () => {
) => selector(useSnapshot().activeProject),
useDebouncedWorkbenchSelector: <Selected,>(selector: (snapshot: ReturnType<typeof useSnapshot>) => Selected) =>
selector(useSnapshot()),
- useWorkbenchCommands: () => ({
- layout: {
- activatePreset: (presetId: LayoutPresetId) => activatePreset(presetId),
- createPreset: noop,
- reorderPresets: noop,
- reset: noop,
- savePreset: noop,
- },
- }),
+ useWorkbenchCommands: () => commands,
useWorkbenchSelector: <Selected,>(selector: (snapshot: ReturnType<typeof useSnapshot>) => Selected) =>
selector(useSnapshot()),
};
@@ -56,11 +59,15 @@ let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-const render = async (options: {
- activatePreset: (presetId: LayoutPresetId) => Promise<void>;
- activePresetId: LayoutPresetId;
-}) => {
- activatePreset = options.activatePreset;
+const nextFrame = (): Promise<void> =>
+ act(async () => {
+ await new Promise((resolve) => {
+ requestAnimationFrame(() => resolve(null));
+ });
+ });
+
+const render = async (options: { activatePreset: ActivatePreset; activePresetId: LayoutPresetId }) => {
+ commands = createCommands(options.activatePreset);
store = createWorkbenchStore();
store.commands.layout.applyPreset(options.activePresetId);
host = document.createElement('div');
@@ -90,68 +97,55 @@ const presetTab = (id: string): HTMLElement => {
return tab;
};
-const press = (element: Element): Promise<void> =>
+const press = (element: Element, button = 0): Promise<void> =>
act(async () => {
- element.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, cancelable: true }));
+ element.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button, cancelable: true }));
await Promise.resolve();
});
-const nextFrame = (): Promise<void> =>
- act(async () => {
- await new Promise((resolve) => {
- requestAnimationFrame(() => resolve(null));
- });
- });
-
afterEach(async () => {
+ // Drained while the tree that queued it is still mounted, so no activation
+ // frame can leak into the next test.
+ await nextFrame();
await act(() => root?.unmount());
host?.remove();
host = null;
root = null;
- activatePreset = () => Promise.resolve();
+ commands = createCommands(() => Promise.resolve(null));
});
describe('LayoutPresetStrip acknowledgment', () => {
- it('marks the pressed tab active on pointerdown, before any store update', async () => {
+ // 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.
+ it('selects the pressed tab on pointerdown, before any store update', async () => {
// activatePreset never resolves: the store is deliberately frozen.
- const activate = vi.fn(() => new Promise<void>(() => {}));
+ const activate = vi.fn<ActivatePreset>(() => new Promise<LayoutPresetId | null>(() => {}));
await render({ activatePreset: activate, activePresetId: 'compose' });
- const editTab = presetTab('edit');
-
- expect(editTab.hasAttribute('data-preset-active')).toBe(false);
-
- await press(editTab);
-
- expect(presetTab('edit').hasAttribute('data-preset-active')).toBe(true);
- expect(presetTab('compose').hasAttribute('data-preset-active')).toBe(false);
- expect(store.getSnapshot().activeProject.layout.presetId).toBe('compose');
- });
-
- // The performance gate watches `aria-selected`, and assistive technology reads
- // it: the acknowledgment is only real if the tabs machine moves with it.
- it('moves the tabs machine selection in the same commit as the acknowledgment', async () => {
- const activate = vi.fn(() => new Promise<void>(() => {}));
-
- await render({ activatePreset: activate, activePresetId: 'compose' });
+ expect(presetTab('edit').getAttribute('aria-selected')).toBe('false');
await press(presetTab('edit'));
expect(presetTab('edit').getAttribute('aria-selected')).toBe('true');
+ expect(presetTab('edit').hasAttribute('data-selected')).toBe(true);
expect(presetTab('compose').getAttribute('aria-selected')).toBe('false');
expect(presetTab('compose').hasAttribute('data-selected')).toBe(false);
+ expect(store.getSnapshot().activeProject.layout.presetId).toBe('compose');
});
it('activates on the frame after the acknowledgment, not inside the handler', async () => {
- const activate = vi.fn(() => Promise.resolve());
+ const activate = vi.fn<ActivatePreset>(() => Promise.resolve('edit'));
await render({ activatePreset: activate, activePresetId: 'compose' });
const editTab = presetTab('edit');
await act(async () => {
- editTab.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, cancelable: true }));
+ editTab.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0, cancelable: true }));
// Checked before yielding: the handler itself must not have dispatched.
expect(activate).not.toHaveBeenCalled();
@@ -164,7 +158,7 @@ describe('LayoutPresetStrip acknowledgment', () => {
});
it('does not re-activate the preset that is already active', async () => {
- const activate = vi.fn(() => Promise.resolve());
+ const activate = vi.fn<ActivatePreset>(() => Promise.resolve('compose'));
await render({ activatePreset: activate, activePresetId: 'compose' });
@@ -173,4 +167,54 @@ describe('LayoutPresetStrip acknowledgment', () => {
expect(activate).not.toHaveBeenCalled();
});
+
+ // `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.
+ it('ignores a secondary-button press', async () => {
+ const activate = vi.fn<ActivatePreset>(() => Promise.resolve('edit'));
+
+ await render({ activatePreset: activate, activePresetId: 'compose' });
+
+ await press(presetTab('edit'), 2);
+ await nextFrame();
+
+ expect(activate).not.toHaveBeenCalled();
+ expect(presetTab('edit').getAttribute('aria-selected')).toBe('false');
+ 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.
+ 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 whichever
+ // microtask turn happens to win the race.
+ let reportOutcome!: (appliedPresetId: LayoutPresetId | null) => void;
+ const outcome = new Promise<LayoutPresetId | null>((resolve) => {
+ reportOutcome = resolve;
+ });
+ const activate = vi.fn<ActivatePreset>(() => outcome);
+
+ await render({ activatePreset: activate, activePresetId: 'compose' });
+
+ await press(presetTab('edit'));
+
+ expect(presetTab('edit').getAttribute('aria-selected')).toBe('true');
+
+ await nextFrame();
+
+ expect(activate).toHaveBeenCalledWith('edit');
+ expect(presetTab('edit').getAttribute('aria-selected')).toBe('true');
+
+ await act(async () => {
+ reportOutcome(null);
+ await outcome;
+ });
+
+ expect(presetTab('edit').getAttribute('aria-selected')).toBe('false');
+ expect(presetTab('compose').getAttribute('aria-selected')).toBe('true');
+ });
});