Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(canvas): context menu on staged results
Josh Corbett49de7dff11c2
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 8c8238aa6d..136963c7ef 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2623,6 +2623,7 @@"autoSwitchProgress": "In progress","generating": "Generating…","moreAcceptOptions": "More accept options",+ "recall": "Recall settings","saveAsDisabledLayer": "Save & Continue","saveError": "Couldn't save to gallery","saveToGallery": "Save to gallery",diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsxindex 312a51fe15..780f8e7c66 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsx@@ -35,6 +35,9 @@ const RECALL_ACTION_ITEMS: {{ capability: 'clipSkip', icon: ScissorsIcon, kind: 'clipSkip', label: 'Use CLIP Skip' },];+/** 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 recalldiff --git a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts b/invokeai/frontend/webv2/src/workbench/image-actions/index.tsindex 6a3f08a804..b1110b183b 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/index.ts@@ -16,7 +16,7 @@ export {type ImageRecallResult,} from './imageRecall';export { executeImageRecall, getCurrentGenerateValues } from './executeImageRecall';-export { getImageRecallVerb, RecallActionButtons } from './RecallActionButtons';+export { getImageRecallVerb, IMAGE_RECALL_KINDS, RecallActionButtons } from './RecallActionButtons';export { getSelectedGalleryImage, getSelectedGalleryImageFromValues } from './selectedImage';export { useImageActions, type ImageActions } from './useImageActions';export { useDeletionConfirmation, type RequestDeletionConfirmation } from './useDeletionConfirmation';diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsxindex b0cec281b3..13332a65be 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx@@ -1,116 +1,29 @@import type { QueueItemReadModel } from '@features/queue/contracts';import { Dialog, Icon, Portal } from '@chakra-ui/react';-import { createGenerateFormValuesSelector } from '@features/generation/react';-import { isSupportedGenerateModel } from '@features/generation/settings';-import { ensureModelsLoaded, useModelsSelector } from '@features/models';import { extractGenerationMeta } from '@features/queue/contracts';-import { useMountEffect } from '@platform/react/useMountEffect';import { Button, CloseButton } from '@platform/ui/Button';import { JsonPreview } from '@platform/ui/JsonPreview';-import {- EMPTY_IMAGE_RECALL_CAPABILITIES,- getCurrentGenerateValues,- getImageRecallTitle,- RecallActionButtons,- type ImageRecallKind,-} from '@workbench/image-actions';+import { RecallActionButtons } from '@workbench/image-actions';import { useNotify } from '@workbench/useNotify';-import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';-import { useWidgetValuesSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { FileTextIcon, WandSparklesIcon } from 'lucide-react';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { getQueueRecallCapabilities, getVideoQueueRecallCapabilities, planQueueRecall } from './queueRecall';-import { useLocalRecallSnapshot } from './useLocalRecallSnapshot';--const selectGenerateRecallValues = createGenerateFormValuesSelector();+import { useQueueItemRecall } from './useQueueItemRecall';/*** Per-item actions for the RECENT details panel. Recall uses the shared* {@link RecallActionButtons} verbs (same look as the preview's metadata- * panel): items this client submitted recall from the exact submission- * snapshot; foreign items still offer prompts + the executed seed from the- * session. "View JSON" opens the raw queue item in a dialog.+ * panel) over {@link useQueueItemRecall}. "View JSON" opens the raw queue+ * item in a dialog.*/export const QueueItemActions = ({ item }: { item: QueueItemReadModel }) => {const { t } = useTranslation();- const { generation, widgets } = useWorkbenchCommands();- const openWidget = useOpenWorkbenchWidget();const notify = useNotify();- const recall = useLocalRecallSnapshot(item.origin);- const isRecallPending = recall === undefined;- const localGenerateValues = recall?.generateValues ?? null;- const videoSnapshot = recall?.videoValues ?? null;- const isVideoItem = recall?.sourceId === 'video';const [jsonOpen, setJsonOpen] = useState(false);- const generateValues = useWidgetValuesSelector('generate', selectGenerateRecallValues);- const models = useModelsSelector((snapshot) => snapshot.models);- const supportedModels = useMemo(() => models.filter(isSupportedGenerateModel), [models]);const meta = useMemo(() => extractGenerationMeta(item), [item]);- const capabilities = useMemo(- () =>- isRecallPending- ? EMPTY_IMAGE_RECALL_CAPABILITIES- : isVideoItem- ? getVideoQueueRecallCapabilities(videoSnapshot, meta)- : getQueueRecallCapabilities(localGenerateValues, meta),- [isRecallPending, isVideoItem, localGenerateValues, meta, videoSnapshot]- );-- useMountEffect(() => {- void ensureModelsLoaded();- });-- const onRecall = useCallback(- (kind: ImageRecallKind) => {- if (isRecallPending) {- return;- }- const current = getCurrentGenerateValues({ generateValues, supportedModels });- const plan = planQueueRecall(kind, { current, isVideoItem, meta, snapshot: localGenerateValues, videoSnapshot });-- if (!plan) {- notify.info(- getImageRecallTitle(kind),- // The Generate copy names a missing Generate model, which is not why- // a video recall would come back empty.- t(isVideoItem ? 'widgets.queue.recallUnavailableForItem' : 'widgets.queue.recallUnavailable')- );- return;- }-- // Both branches write to the ACTIVE project, not the project that owns the- // item: with the default `all` queue scope Recent lists other projects'- // items too, and "recall" means "load this into the panel I am looking at".- // `openWidget` follows the same rule, so the write and the reveal agree.- if (plan.target === 'video') {- widgets.patchValues('video', plan.patch);- openWidget('video', { preferredRegions: ['left'] });- notify.success(getImageRecallTitle(kind), t('widgets.queue.settingsRecalledIntoVideoDescription'));- return;- }-- generation.setSettings(plan.values);- openWidget('generate', { preferredRegions: ['left'] });- notify.success(getImageRecallTitle(kind), t('widgets.queue.settingsRecalledDescription'));- },- [- generateValues,- generation,- isVideoItem,- isRecallPending,- localGenerateValues,- meta,- notify,- openWidget,- supportedModels,- t,- widgets,- videoSnapshot,- ]- );+ const { capabilities, recall: onRecall } = useQueueItemRecall(item.origin, meta);const onSendToCanvas = useCallback(() => notify.info(t('widgets.queue.sendToCanvas'), t('widgets.queue.sendToCanvasComingSoon')),diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsxnew file mode 100644index 0000000000..edd9e96a83--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsx@@ -0,0 +1,122 @@+import type { GenerateWidgetValues } from '@features/generation/contracts';+import type * as ModelsModule from '@features/models';+import type { QueueGenerationMeta } from '@features/queue/contracts';+import type { ImageRecallKind } from '@workbench/image-actions';+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';++import { createDefaultVideoWidgetValues } from '@features/video';+import { act, createRef, type Ref, useImperativeHandle } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { LocalRecallSnapshot } from './useLocalRecallSnapshot';++import { useQueueItemRecall } from './useQueueItemRecall';++const mocks = vi.hoisted(() => ({+ notifyInfo: vi.fn(),+ notifySuccess: vi.fn(),+ openWidget: vi.fn(),+ patchValues: vi.fn(),+ setSettings: vi.fn(),+ snapshot: undefined as LocalRecallSnapshot | null | undefined,+}));++vi.mock('./useLocalRecallSnapshot', () => ({ useLocalRecallSnapshot: () => mocks.snapshot }));+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({+ ...(await importOriginal<typeof WorkbenchContextModule>()),+ useWidgetValuesSelector: () => ({}),+ useWorkbenchCommands: () => ({+ generation: { setSettings: mocks.setSettings },+ widgets: { patchValues: mocks.patchValues },+ }),+}));+vi.mock('@features/models', async (importOriginal) => ({+ ...(await importOriginal<typeof ModelsModule>()),+ ensureModelsLoaded: () => Promise.resolve(),+ useModelsSelector: () => [],+}));+vi.mock('@workbench/useNotify', () => ({+ useNotify: () => ({ error: vi.fn(), info: mocks.notifyInfo, success: mocks.notifySuccess }),+}));+vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => mocks.openWidget }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++const NO_META: QueueGenerationMeta = {};+const generateSnapshot = {+ positivePrompt: 'snapshot prompt',+ seed: 7,+ shouldRandomizeSeed: false,+} as GenerateWidgetValues;++type Handle = ReturnType<typeof useQueueItemRecall>;+const handle = createRef<Handle>();+const Probe = ({ meta, ref }: { meta: QueueGenerationMeta; ref: Ref<Handle> }) => {+ const value = useQueueItemRecall('webv2:p:project-1:q:item-1', meta);+ useImperativeHandle(ref, () => value, [value]);+ return null;+};++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 (snapshot: LocalRecallSnapshot | null | undefined, meta: QueueGenerationMeta = NO_META) => {+ mocks.snapshot = snapshot;+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() => root?.render(<Probe meta={meta} ref={handle} />));+};+const recall = (kind: ImageRecallKind) => act(() => handle.current!.recall(kind));++beforeEach(() => vi.clearAllMocks());+afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('useQueueItemRecall', () => {+ it('offers nothing and stays inert while the durable snapshot lookup is pending', async () => {+ await render(undefined);+ expect(Object.values(handle.current!.capabilities).some(Boolean)).toBe(false);+ await recall('all');+ expect(mocks.setSettings).not.toHaveBeenCalled();+ expect(mocks.notifyInfo).not.toHaveBeenCalled();+ });++ it('recalls a generate submission into the Generate panel and reveals it', async () => {+ await render({ generateValues: generateSnapshot, sourceId: 'canvas' });+ expect(handle.current!.capabilities).toMatchObject({ all: true, prompts: true, seed: true });++ await recall('all');++ expect(mocks.setSettings).toHaveBeenCalledWith(generateSnapshot);+ expect(mocks.openWidget).toHaveBeenCalledWith('generate', { preferredRegions: ['left'] });+ expect(mocks.notifySuccess).toHaveBeenCalledWith(expect.any(String), 'widgets.queue.settingsRecalledDescription');+ });++ it('patches a video submission into the Video panel instead', async () => {+ const videoValues = { ...createDefaultVideoWidgetValues(), positivePrompt: 'video prompt' };+ await render({ sourceId: 'video', videoValues });++ await recall('all');++ expect(mocks.patchValues).toHaveBeenCalledWith('video', videoValues);+ expect(mocks.setSettings).not.toHaveBeenCalled();+ expect(mocks.openWidget).toHaveBeenCalledWith('video', { preferredRegions: ['left'] });+ });++ it('explains an unavailable recall instead of writing anything', async () => {+ // A foreign item: no snapshot, only the executed prompt from the session.+ await render(null, { positivePrompt: 'session prompt' });+ expect(handle.current!.capabilities).toMatchObject({ all: false, prompts: true, seed: false });++ await recall('seed');++ expect(mocks.setSettings).not.toHaveBeenCalled();+ expect(mocks.notifyInfo).toHaveBeenCalledWith(expect.any(String), 'widgets.queue.recallUnavailable');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.tsnew file mode 100644index 0000000000..dadaa4c94a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts@@ -0,0 +1,108 @@+import type { QueueGenerationMeta } from '@features/queue/contracts';+import type { ImageRecallCapabilities, ImageRecallKind } from '@workbench/image-actions';++import { createGenerateFormValuesSelector } from '@features/generation/react';+import { isSupportedGenerateModel } from '@features/generation/settings';+import { ensureModelsLoaded, useModelsSelector } from '@features/models';+import { useMountEffect } from '@platform/react/useMountEffect';+import {+ EMPTY_IMAGE_RECALL_CAPABILITIES,+ getCurrentGenerateValues,+ getImageRecallTitle,+} from '@workbench/image-actions';+import { useNotify } from '@workbench/useNotify';+import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';+import { useWidgetValuesSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { getQueueRecallCapabilities, getVideoQueueRecallCapabilities, planQueueRecall } from './queueRecall';+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.+ */+export const useQueueItemRecall = (+ origin: string | null | undefined,+ meta: QueueGenerationMeta+): { capabilities: ImageRecallCapabilities; isPending: boolean; recall: (kind: ImageRecallKind) => void } => {+ const { t } = useTranslation();+ const { generation, widgets } = useWorkbenchCommands();+ const openWidget = useOpenWorkbenchWidget();+ const notify = useNotify();+ const snapshot = useLocalRecallSnapshot(origin);+ const isPending = snapshot === undefined;+ const localGenerateValues = snapshot?.generateValues ?? null;+ const videoSnapshot = snapshot?.videoValues ?? null;+ const isVideoItem = snapshot?.sourceId === 'video';+ const generateValues = useWidgetValuesSelector('generate', selectGenerateRecallValues);+ const models = useModelsSelector((state) => state.models);+ const supportedModels = useMemo(() => models.filter(isSupportedGenerateModel), [models]);+ const capabilities = useMemo(+ () =>+ isPending+ ? EMPTY_IMAGE_RECALL_CAPABILITIES+ : isVideoItem+ ? getVideoQueueRecallCapabilities(videoSnapshot, meta)+ : getQueueRecallCapabilities(localGenerateValues, meta),+ [isPending, isVideoItem, localGenerateValues, meta, videoSnapshot]+ );++ useMountEffect(() => {+ void ensureModelsLoaded();+ });++ const recall = useCallback(+ (kind: ImageRecallKind) => {+ if (isPending) {+ return;+ }+ const current = getCurrentGenerateValues({ generateValues, supportedModels });+ const plan = planQueueRecall(kind, { current, isVideoItem, meta, snapshot: localGenerateValues, videoSnapshot });++ if (!plan) {+ notify.info(+ getImageRecallTitle(kind),+ // The Generate copy names a missing Generate model, which is not why+ // a video recall would come back empty.+ t(isVideoItem ? 'widgets.queue.recallUnavailableForItem' : 'widgets.queue.recallUnavailable')+ );+ return;+ }++ if (plan.target === 'video') {+ widgets.patchValues('video', plan.patch);+ openWidget('video', { preferredRegions: ['left'] });+ notify.success(getImageRecallTitle(kind), t('widgets.queue.settingsRecalledIntoVideoDescription'));+ return;+ }++ generation.setSettings(plan.values);+ openWidget('generate', { preferredRegions: ['left'] });+ notify.success(getImageRecallTitle(kind), t('widgets.queue.settingsRecalledDescription'));+ },+ [+ generateValues,+ generation,+ isPending,+ isVideoItem,+ localGenerateValues,+ meta,+ notify,+ openWidget,+ supportedModels,+ t,+ videoSnapshot,+ widgets,+ ]+ );++ return { capabilities, isPending, recall };+};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 c46c536eb5..92a1e67ff6 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@@ -12,6 +12,14 @@ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';import { CanvasBottomOverlay } from './CanvasBottomOverlay';import { StagingBar } from './StagingBar';+const contextMenu = vi.hoisted(() => ({ targets: [] as { slotId: string; x: number; y: number }[] }));+vi.mock('./StagingItemContextMenu', () => ({+ StagingItemContextMenu: ({ target }: { target: { slot: { id: string }; x: number; y: number } }) => {+ contextMenu.targets.push({ slotId: target.slot.id, x: target.x, y: target.y });+ return <div data-testid="staging-context-menu" />;+ },+}));+/** Roughly the width of a canvas widget on a laptop — wide enough for the bar, far too narrow for 24 thumbnails. */const CANVAS_WIDTH = 900;const TRANSPARENT_PIXEL = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';@@ -39,6 +47,15 @@ const makeSlot = (index: number): CanvasStagingSlot => ({width: 512,});+const makePlaceholder = (index: number): CanvasStagingSlot => ({+ height: 512,+ id: `slot-${index}`,+ itemIndex: index,+ kind: 'placeholder',+ queueItemId: 'queue-item',+ width: 512,+});+let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -55,9 +72,11 @@ const renderStagingBar = async (slotCount: number,selectedImageIndex = 0,onSaveToLayerAndContinue: () => void = noop,- onPreloadCandidate: (imageName: string) => void = noop+ onPreloadCandidate: (imageName: string) => void = noop,+ onSelectImage: (index: number) => void = noop,+ slotAt: (index: number) => CanvasStagingSlot = makeSlot) => {- const slots = Array.from({ length: slotCount }, (_, index) => makeSlot(index));+ const slots = Array.from({ length: slotCount }, (_, index) => slotAt(index));const selectedSlot = slots[selectedImageIndex];if (!host) {@@ -91,7 +110,7 @@ const renderStagingBar = async (onDiscardAll={noop}onDiscardSelected={noop}onPreloadCandidate={onPreloadCandidate}- onSelectImage={noop}+ onSelectImage={onSelectImage}onSaveToLayerAndContinue={onSaveToLayerAndContinue}onSetAutoSwitch={noop}onToggleThumbnails={noop}@@ -196,6 +215,52 @@ describe('StagingBar thumbnail strip', () => {expect(onPreloadCandidate).toHaveBeenCalledWith('image-2');});+ it('selects a right-clicked candidate and opens its context menu at the pointer', async () => {+ const onSelectImage = vi.fn();+ const { thumbnails } = await renderStagingBar(3, 2, noop, noop, onSelectImage);++ const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 80 });+ await interact(() => thumbnails[2]!.dispatchEvent(event));++ expect(event.defaultPrevented).toBe(true);+ expect(onSelectImage).toHaveBeenCalledWith(2);+ expect(contextMenu.targets.at(-1)).toEqual({ slotId: 'slot-2', x: 120, y: 80 });+ expect(document.querySelector('[data-testid="staging-context-menu"]')).not.toBeNull();+ });++ it('leaves the native menu alone on an in-progress placeholder', async () => {+ const { thumbnails } = await renderStagingBar(3, 0, noop, noop, noop, makePlaceholder);+ const before = contextMenu.targets.length;++ const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 10, clientY: 10 });+ await interact(() => thumbnails[1]!.dispatchEvent(event));++ expect(event.defaultPrevented).toBe(false);+ expect(contextMenu.targets).toHaveLength(before);+ });++ it('anchors a keyboard-opened context menu to the thumbnail itself', async () => {+ const { thumbnails } = await renderStagingBar(3, 1);+ const rect = thumbnails[1]!.getBoundingClientRect();++ await interact(() => thumbnails[1]!.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true })));++ expect(contextMenu.targets.at(-1)).toEqual({ slotId: 'slot-1', x: rect.left + rect.width / 2, y: rect.top });+ });++ it('closes the context menu once the selection moves off its candidate', async () => {+ const { thumbnails } = await renderStagingBar(3, 1);+ await interact(() =>+ thumbnails[1]!.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 50, clientY: 50 }))+ );+ expect(document.querySelector('[data-testid="staging-context-menu"]')).not.toBeNull();++ // An auto-switch lands a newer result: the bar re-renders with that one selected.+ await renderStagingBar(3, 2);++ expect(document.querySelector('[data-testid="staging-context-menu"]')).toBeNull();+ });+it('offers a split-button action that saves without ending staging', async () => {const onSaveToLayerAndContinue = vi.fn();await renderStagingBar(1, 0, onSaveToLayerAndContinue);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsxindex ff68978ddb..aff668d7d3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx@@ -36,10 +36,11 @@ import {Trash2Icon,XIcon,} from 'lucide-react';-import { useCallback, useState } from 'react';+import { useCallback, useState, type MouseEvent as ReactMouseEvent } from 'react';import { useTranslation } from 'react-i18next';import { CanvasFloatingBarDivider } from './CanvasFloatingBar';+import { StagingItemContextMenu, type StagingItemContextMenuTarget } from './StagingItemContextMenu';type AutoSwitchMode = CanvasStagingAreaContractV2['autoSwitchMode'];@@ -107,6 +108,14 @@ export const StagingBar = ({}: StagingBarProps) => {const { t } = useTranslation();const [isSaving, setIsSaving] = useState(false);+ const [contextMenuTarget, setContextMenuTarget] = useState<StagingItemContextMenuTarget | null>(null);+ const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);+ // The menu's candidate actions act on the selection, so it only stays open+ // while its slot is the selected one: an auto-switch to a newer result+ // closes it rather than letting Discard hit the wrong candidate.+ if (contextMenuTarget && selectedSlot?.id !== contextMenuTarget.slot.id) {+ setContextMenuTarget(null);+ }const hasSlots = slots.length > 0;const cancelableQueueItemId = getCancelableCanvasStagingQueueItemId(selectedSlot);@@ -131,6 +140,16 @@ export const StagingBar = ({return (<Stack align="center" gap="2" w="full">+ {contextMenuTarget ? (+ <StagingItemContextMenu+ canAccept={canAccept}+ target={contextMenuTarget}+ onAccept={onAccept}+ onClose={closeContextMenu}+ onDiscard={onDiscardSelected}+ onSaveToGallery={() => void handleSaveToGallery()}+ />+ ) : 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@@ -162,6 +181,22 @@ export const StagingBar = ({index={index}isSelected={index === selectedImageIndex}slot={slot}+ onContextMenu={(event) => {+ if (slot.kind !== 'candidate') {+ return;+ }+ // The menu acts on the selected candidate, so a right-click selects first.+ // The keyboard's context-menu key reports no pointer; anchor to the thumbnail.+ event.preventDefault();+ onSelectImage(index);+ const rect = event.currentTarget.getBoundingClientRect();+ const fromKeyboard = event.clientX === 0 && event.clientY === 0;+ setContextMenuTarget({+ slot,+ x: fromKeyboard ? rect.left + rect.width / 2 : event.clientX,+ y: fromKeyboard ? rect.top : event.clientY,+ });+ }}onPreloadCandidate={onPreloadCandidate}onSelect={() => onSelectImage(index)}/>@@ -371,6 +406,7 @@ const StagingThumbnail = ({index,isSelected,slot,+ onContextMenu,onPreloadCandidate,onSelect,}: {@@ -378,6 +414,7 @@ const StagingThumbnail = ({index: number;isSelected: boolean;slot: CanvasStagingSlot;+ onContextMenu: (event: ReactMouseEvent<HTMLElement>) => void;onPreloadCandidate: (imageName: string) => void;onSelect: () => void;}) => {@@ -418,6 +455,7 @@ const StagingThumbnail = ({shadow={isSelected ? '0 0 0 1px {colors.accent.solid}' : 'md'}style={{ aspectRatio: '1 / 1' }}onClick={onSelect}+ onContextMenu={onContextMenu}>{slot.kind === 'candidate' ? (<imgdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.browser.test.tsxnew file mode 100644index 0000000000..d0bb7c94eb--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.browser.test.tsx@@ -0,0 +1,182 @@+import type { CanvasCandidateSlot } from '@workbench/canvasStagingView';+import type { ImageRecallCapabilities, ImageRecallKind } from '@workbench/image-actions';+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';++import { ChakraProvider } from '@chakra-ui/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { StagingItemContextMenu } from './StagingItemContextMenu';++const mocks = vi.hoisted(() => ({+ capabilities: {+ all: true,+ clipSkip: false,+ dimensions: true,+ prompts: true,+ remix: true,+ seed: false,+ } as ImageRecallCapabilities,+ meta: null as unknown,+ origin: null as string | null,+ recall: vi.fn<(kind: ImageRecallKind) => void>(),+}));++vi.mock('@features/queue/queries', () => ({+ getQueueReadModelOptions: (scope: { originPrefix: string }) => ({+ queryFn: () =>+ Promise.resolve({+ items: [+ {+ fieldValues: [+ { nodePath: 'positive_prompt', value: 'a staged cat' },+ { nodePath: 'seed', value: 4242 },+ ],+ id: 77,+ },+ ],+ }),+ queryKey: ['queue-read-model', scope.originPrefix],+ }),+}));++vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({+ ...(await importOriginal<typeof WorkbenchContextModule>()),+ useActiveProjectId: () => 'project-1',+}));+vi.mock('@workbench/queue-integration/useQueueItemRecall', () => ({+ useQueueItemRecall: (origin: string, meta: unknown) => {+ mocks.origin = origin;+ mocks.meta = meta;+ return { capabilities: mocks.capabilities, isPending: false, recall: mocks.recall };+ },+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++const slot: CanvasCandidateSlot = {+ candidate: {+ height: 512,+ imageName: 'staged.png',+ imageUrl: '/staged.png',+ placement: { height: 512, opacity: 1, width: 512, x: 0, y: 0 },+ queuedAt: '2026-01-01T00:00:00.000Z',+ sourceBackendItemId: 77,+ sourceQueueItemId: 'local-queue-item',+ thumbnailUrl: '/staged-thumb.png',+ width: 512,+ },+ height: 512,+ id: 'slot-1',+ imageName: 'staged.png',+ kind: 'candidate',+ queueItemId: 'local-queue-item',+ width: 512,+};++const target = { slot, x: 40, y: 40 };++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 interact = (action: () => void): Promise<void> =>+ act(async () => {+ action();+ await new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, 50);+ });+ });++const menuItem = (label: string): HTMLElement => {+ const item = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find(+ (candidate) => candidate.textContent?.trim() === label+ );+ if (!item) {+ throw new Error(`Could not find menu item: ${label}`);+ }+ return item;+};++/** Selects a menu item the way a mouse does: highlight it (zag selects the highlighted item), then click. */+const activate = async (label: string): Promise<void> => {+ await interact(() =>+ menuItem(label).dispatchEvent(new PointerEvent('pointermove', { bubbles: true, pointerType: 'mouse' }))+ );+ await interact(() => menuItem(label).click());+};++const render = async (handlers: Partial<Parameters<typeof StagingItemContextMenu>[0]> = {}) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await interact(() =>+ root?.render(+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ <ChakraProvider value={system}>+ <StagingItemContextMenu+ canAccept+ target={target}+ onAccept={vi.fn()}+ onClose={vi.fn()}+ onDiscard={vi.fn()}+ onSaveToGallery={vi.fn()}+ {...handlers}+ />+ </ChakraProvider>+ </QueryClientProvider>+ )+ );+};++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+ vi.clearAllMocks();+});++describe('StagingItemContextMenu', () => {+ it('recalls from the staged result’s own queue item and disables verbs its snapshot cannot back', async () => {+ await render();++ expect(mocks.origin).toBe('webv2:p:project-1:q:local-queue-item');+ // The executed prompt and seed come from the backend item that produced the result.+ await vi.waitFor(() => expect(mocks.meta).toEqual({ positivePrompt: 'a staged cat', seed: 4242 }));+ expect(menuItem('Use Seed').getAttribute('aria-disabled')).toBe('true');+ expect(menuItem('Use CLIP Skip').getAttribute('aria-disabled')).toBe('true');+ expect(menuItem('Recall All').getAttribute('aria-disabled')).toBeNull();++ await activate('Use Prompt');+ expect(mocks.recall).toHaveBeenCalledWith('prompts');++ // A greyed verb must stay inert: the row is only visually disabled.+ await activate('Use Seed');+ expect(mocks.recall).not.toHaveBeenCalledWith('seed');+ });++ it('keeps Accept inert while accepting is not allowed', async () => {+ const handlers = { canAccept: false, onAccept: vi.fn() };+ await render(handlers);++ expect(menuItem('widgets.canvas.acceptToLayer').getAttribute('aria-disabled')).toBe('true');+ await activate('widgets.canvas.acceptToLayer');+ expect(handlers.onAccept).not.toHaveBeenCalled();+ });++ it.each([+ ['widgets.canvas.staging.saveToGallery', 'onSaveToGallery'],+ ['widgets.canvas.acceptToLayer', 'onAccept'],+ ['common.discard', 'onDiscard'],+ ] as const)('%s runs the bar’s %s action for the candidate', async (label, handler) => {+ const handlers = { onAccept: vi.fn(), onDiscard: vi.fn(), onSaveToGallery: vi.fn() };+ await render(handlers);++ await activate(label);++ expect(handlers[handler]).toHaveBeenCalledOnce();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.tsxnew file mode 100644index 0000000000..309e3538e9--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.tsx@@ -0,0 +1,133 @@+import type { QueueGenerationMeta, QueueReadModel } from '@features/queue/contracts';+import type { CanvasCandidateSlot } from '@workbench/canvasStagingView';+import type { ImageRecallKind } from '@workbench/image-actions';++import { Menu, Portal } from '@chakra-ui/react';+import {+ buildProjectQueueItemOriginPrefix,+ buildQueueItemOrigin,+ extractGenerationMeta,+} from '@features/queue/contracts';+import { getQueueReadModelOptions } from '@features/queue/queries';+import { MenuActionItem, MenuContent } from '@platform/ui/Menu';+import { useQuery } from '@tanstack/react-query';+import { getImageRecallVerb, IMAGE_RECALL_KINDS } from '@workbench/image-actions';+import { useQueueItemRecall } from '@workbench/queue-integration/useQueueItemRecall';+import { useActiveProjectId } from '@workbench/WorkbenchContext';+import { CheckIcon, SaveIcon, XIcon } from 'lucide-react';+import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++export interface StagingItemContextMenuTarget {+ slot: CanvasCandidateSlot;+ x: number;+ y: number;+}++/** 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.+ */+const useStagedCandidateMeta = (projectId: string, backendItemId: number | undefined): QueueGenerationMeta => {+ const scope = useMemo(() => ({ originPrefix: buildProjectQueueItemOriginPrefix(projectId) }), [projectId]);+ const select = useCallback(+ (model: QueueReadModel): QueueGenerationMeta => {+ const item = model.items.find((candidate) => candidate.id === backendItemId);+ return item ? extractGenerationMeta(item) : NO_META;+ },+ [backendItemId]+ );+ return 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,+ onClose,+ onDiscard,+ onSaveToGallery,+ target,+}: {+ canAccept: boolean;+ onAccept: () => void;+ onClose: () => void;+ onDiscard: () => void;+ onSaveToGallery: () => void;+ target: StagingItemContextMenuTarget;+}) => {+ const { t } = useTranslation();+ const projectId = useActiveProjectId();+ const meta = useStagedCandidateMeta(projectId, target.slot.candidate.sourceBackendItemId);+ const { capabilities, recall } = useQueueItemRecall(buildQueueItemOrigin(target.slot.queueItemId, projectId), meta);+ const positioning = useMemo(+ () => ({+ getAnchorRect: () => ({ height: 1, width: 1, x: target.x, y: target.y }),+ placement: 'top-start' as const,+ }),+ [target.x, target.y]+ );+ const onOpenChange = useCallback(+ (details: { open: boolean }) => {+ if (!details.open) {+ onClose();+ }+ },+ [onClose]+ );++ return (+ <Menu.Root lazyMount open positioning={positioning} unmountOnExit onOpenChange={onOpenChange}>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="13rem" py="1">+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel>{t('widgets.canvas.staging.recall')}</Menu.ItemGroupLabel>+ {IMAGE_RECALL_KINDS.map((kind) => (+ <RecallItem key={kind} disabled={!capabilities[kind]} kind={kind} onRecall={recall} />+ ))}+ </Menu.ItemGroup>+ <Menu.Separator borderColor="border.subtle" />+ <MenuActionItem+ icon={SaveIcon}+ label={t('widgets.canvas.staging.saveToGallery')}+ value="save"+ onSelect={onSaveToGallery}+ />+ <MenuActionItem+ disabled={!canAccept}+ icon={CheckIcon}+ label={t('widgets.canvas.acceptToLayer')}+ value="accept"+ onSelect={onAccept}+ />+ <MenuActionItem icon={XIcon} label={t('common.discard')} value="discard" onSelect={onDiscard} />+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};++const RecallItem = ({+ disabled,+ kind,+ onRecall,+}: {+ disabled: boolean;+ kind: ImageRecallKind;+ onRecall: (kind: ImageRecallKind) => void;+}) => {+ const verb = getImageRecallVerb(kind);+ const onSelect = useCallback(() => onRecall(kind), [kind, onRecall]);+ return <MenuActionItem disabled={disabled} icon={verb.icon} label={verb.label} value={kind} onSelect={onSelect} />;+};