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.

feat(preview): add video frame copy and details

joshistoasta73580044fa6
diff --git a/.superpowers/sdd/mixed-media-gallery-parity/task-9-report.md b/.superpowers/sdd/mixed-media-gallery-parity/task-9-report.md
new file mode 100644
index 0000000000..6e4d83cd8f
--- /dev/null
+++ b/.superpowers/sdd/mixed-media-gallery-parity/task-9-report.md
@@ -0,0 +1,248 @@
+# Task 9 Report: Video copy-current-frame and raw Details
+
+## Status
+
+Complete.
+
+Preview videos now expose a readiness-gated Copy Current Frame action and
+video Details from the header action strip, Preview context menu, and footer
+disclosure. Frame capture stays inside the existing keyed `PreviewVideo`
+boundary in `PreviewFrame.tsx`, which remains the sole owner of a production
+`<video>`.
+
+Details work is query-driven only while the disclosure is open. Query identity
+includes the account epoch and qualified `GalleryItemKey`; video metadata and
+workflow/graph requests start concurrently with the same abort signal. Images
+retain parsed metadata rows, source-run identity, and existing recall actions,
+while videos render raw Metadata, Workflow, and Graph JSON with no recall
+controls.
+
+## TDD evidence
+
+All frontend commands ran from `invokeai/frontend/webv2`.
+
+### Copy-current-frame controller
+
+The first focused RED extended the existing native-video browser contract:
+
+```sh
+pnpm test:browser src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx
+```
+
+```text
+Test Files 1 failed (1)
+Tests 9 failed | 8 passed (17)
+```
+
+Those failures covered:
+
+- Clipboard API support, `HAVE_CURRENT_DATA`, and nonzero intrinsic dimensions;
+- exact intrinsic-size canvas drawing and PNG `ClipboardItem` writes;
+- unsupported, not-ready, canvas draw/taint, null/thrown encoding, and
+ ClipboardItem/write failures;
+- account-epoch and selected-item staleness after an asynchronous clipboard
+ write.
+
+After the local keyed video controller was implemented, the file passed all 17
+tests.
+
+### Query-driven Details and Preview-only actions
+
+Before production edits, the consolidated Task 9 browser RED was:
+
+```text
+Test Files 4 failed (4)
+Tests 18 failed | 20 passed (38)
+```
+
+The new Details file required closed-state inactivity, epoch + qualified-item
+query keys, concurrent video requests with one query signal, close/item/epoch
+abort and stale-result isolation, raw JSON tabs without recall, and the parsed
+image metadata/recall regression. It passed all 7 tests after implementation.
+
+The action-strip and shared-menu tests required localized Preview video
+actions while retaining image copy and keeping Gallery video menus free of
+frame copy. The focused action/menu set passed all 14 tests.
+
+The notification translator was added from a focused unit RED:
+
+```text
+Test Files 1 failed (1)
+Tests 7 failed | 5 passed (12)
+```
+
+It then passed all 12 tests, proving one success notice and distinct localized
+notices for all six failure results. The combined Task 9 browser set passed:
+
+```text
+Test Files 4 passed (4)
+Tests 38 passed (38)
+```
+
+### Full-suite timing regression
+
+The first full browser run exposed a timing-sensitive assertion in the
+pre-existing protected-video retry test:
+
+```text
+Test Files 1 failed | 66 passed (67)
+Tests 1 failed | 327 passed (328)
+```
+
+Its intentionally invalid data-video URL could emit a trusted native media
+error after the test's deterministic manual error when the full suite was
+busy. That second event correctly entered the terminal retry state, racing the
+first-retry assertion. The test harness now suppresses only trusted native
+media errors for that invalid URL; its explicit untrusted recovery events are
+unchanged. The focused file remained green at 17/17 and the repeated full
+browser gate passed 328/328.
+
+### Completion-review follow-up
+
+The completion review found no critical issues and three important edge cases.
+All three were captured before follow-up production edits:
+
+```text
+Test Files 3 failed (3)
+Tests 4 failed | 34 passed (38)
+```
+
+The REDs proved that:
+
+- image recall-capability metadata work did not yet receive the Details query
+ signal;
+- pending image Details had lost the prior disabled recall-button skeleton;
+- a captured video A context menu could show actions bound to newly selected
+ video B.
+
+The recall-capability port now accepts the caller signal and combines it with
+the account-lifecycle signal through `AbortSignal.any`. Image Details keep
+their recall row mounted and disabled while pending. Preview video context
+extras now carry their selected `GalleryItemKey` and render only when it
+matches the menu's captured single-video target.
+
+The same three files then passed all 38 tests. The Details file passed 9/9
+without its prior `act(...)` diagnostics after its asynchronous query
+assertions were wrapped correctly.
+
+## Implementation
+
+### Preview-owned frame capture
+
+- `PreviewFrame` exposes a typed imperative controller through the existing
+ `PreviewFrame`/keyed `PreviewVideo` boundary.
+- Readiness is published from media events and ref lifetime, with no
+ synchronization effect.
+- Capture verifies ClipboardItem/write support, current-frame data, and
+ nonzero dimensions before drawing.
+- The canvas uses `videoWidth`/`videoHeight`, draws the selected native player,
+ encodes `image/png`, and performs one clipboard write.
+- Canvas draw/taint, encoding, clipboard, unsupported, not-ready, and stale
+ outcomes stay distinct.
+- Account epoch, selected `GalleryItemKey`, and video element identity are
+ checked before the write and again before success.
+- `PreviewWidgetView` translates every result into exactly one localized
+ success/error notification.
+
+### Preview action surfaces
+
+- Full-density Preview video headers expose Copy Current Frame and Video
+ Details; copy remains disabled until the controller publishes readiness.
+- Preview's shared context-menu port is opt-in and video-only. Gallery callers
+ omit the port, so Gallery video/mixed context menus still hide frame copy.
+- The opt-in port is qualified by `GalleryItemKey`; stale captured menus never
+ operate on a newly selected video.
+- Image copy, compare, metadata, and recall behavior remain on the strict
+ image arm.
+- Video Details explicitly opens the existing footer disclosure.
+
+### Query-driven Details
+
+- The old image metadata synchronization effect was removed.
+- The query observer is mounted only while Details is open and is keyed by
+ `['preview', 'details', accountEpoch, itemKey]`.
+- Unmounting on close/item/epoch change cancels supported transports through
+ the TanStack Query signal.
+- Image recall-capability metadata combines that signal with its account-owned
+ signal, so closing Details aborts both image metadata transports.
+- Video metadata and workflow/graph requests use `Promise.all` and the same
+ signal.
+- Video Metadata, Workflow, and Graph use `JsonPreview` from the direct
+ `@platform/ui/JsonPreview` subpath and never render recall controls.
+- Image Details retain `parsePreviewMetadata`, Source Run, recall capability
+ loading, and a stable disabled-while-pending `RecallActionButtons` skeleton.
+
+## Full verification
+
+```sh
+pnpm lint
+```
+
+```text
+format: passed
+OXC: passed
+tsc --noEmit: passed
+architecture: 3 files, 34 tests passed
+```
+
+```sh
+pnpm test
+```
+
+```text
+Test Files 376 passed (376)
+Tests 4985 passed (4985)
+```
+
+```sh
+pnpm test:browser
+```
+
+```text
+Test Files 67 passed (67)
+Tests 332 passed (332)
+```
+
+The first final full-browser attempt passed every Task 9 test but an unrelated
+existing platform Tabs hover test hit its 15-second timeout under suite load.
+That file immediately passed 1/1 focused; the complete browser rerun above then
+passed 332/332. The full suite retained non-failing React `act(...)`,
+missing-i18n-instance, and intentional error-boundary diagnostics from
+pre-existing files.
+
+```sh
+pnpm test:fixtures
+```
+
+```text
+Tests 4 passed (4)
+```
+
+## Source-policy and contract scans
+
+```sh
+rg -n '^[[:space:]]*<video' src --glob '!**/*.test.*' --glob '!**/*.spec.*'
+```
+
+Only `src/workbench/widgets/preview/PreviewFrame.tsx` matched.
+
+```sh
+git diff -U0 -- '*.ts' '*.tsx' | rg '^\+.*\buseEffect\b'
+```
+
+No added `useEffect` matched.
+
+The only added platform UI import is the required direct
+`@platform/ui/JsonPreview` subpath. No production module, file rename,
+migration exception, architecture/performance baseline, or additional
+`@platform/ui` barrel importer was added.
+
+`src/features/gallery/core/types.ts`, which owns
+`GeneratedImageContract`, is byte-for-byte identical to reviewed head
+`35644ab5be4bde2beb91cb9c52f6b92f7f2a3a65`; both SHA-256 values are:
+
+```text
+79398f2e0e0dd4c72409612531ba990cc0b6b5df64ee8e13c47a93f1b1190979
+```
+
+`git diff --check` also passed.
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 4cbca7120b..110e5dae74 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1215,10 +1215,20 @@
"zoomToFit": "Zoom preview to fit"
},
"compare": "Compare",
+ "copyCurrentFrame": "Copy Current Frame",
+ "copyCurrentFrameDrawFailed": "Could not read the current video frame",
+ "copyCurrentFrameEncodeFailed": "Could not encode the current video frame",
+ "copyCurrentFrameNotReady": "The video does not have a current frame yet",
+ "copyCurrentFrameStale": "The selected video changed before the frame was copied",
+ "copyCurrentFrameSuccess": "Current video frame copied",
+ "copyCurrentFrameUnsupported": "This browser cannot copy video frames",
+ "copyCurrentFrameWriteFailed": "Could not write the current video frame to the clipboard",
"details": "Details",
"dropToCompare": "Drop to compare",
"emptyDescription": "Generate to Gallery, then select a thumbnail in the Gallery widget to inspect it here.",
"framesPerSecond": "{{count}} fps",
+ "graph": "Graph",
+ "graphJsonLabel": "Video graph JSON",
"hideFilmstrip": "Hide filmstrip",
"exitCompare": "Exit Compare",
"hideInProgressDiffusion": "Hide in-progress diffusion",
@@ -1228,6 +1238,8 @@
"itemCount_other": "{{count}} items",
"loadingBoard": "Loading board",
"loadingMetadata": "Loading metadata",
+ "metadata": "Metadata",
+ "metadataJsonLabel": "Video metadata JSON",
"nextItemInBoard": "Next item in board",
"nextImageInBoard": "Next image in board",
"noGallerySelection": "No gallery selection",
@@ -1243,10 +1255,13 @@
"hoverComparisonAriaLabel": "Reveal comparison image on hover, focus, or touch",
"sourceRun": "Source run {{id}}",
"videoDuration": "Duration {{duration}}",
+ "videoDetails": "Video Details",
"videoFailed": "Video could not be loaded",
"videoLabel": "Video {{name}}",
"videoRetry": "Retry",
- "viewing": "Viewing"
+ "viewing": "Viewing",
+ "workflow": "Workflow",
+ "workflowJsonLabel": "Video workflow JSON"
},
"queue": {
"allScopedItemsRequested": "All scoped queue items were requested.",
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.tsx
index f5e50c618c..e158bb22fe 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
@@ -1,4 +1,4 @@
-import type { GalleryImage, GalleryItem } from '@features/gallery';
+import type { GalleryImage, GalleryItem, GalleryItemKey } from '@features/gallery';
import type { GalleryItemContextMenuTarget } from '@features/gallery/react';
/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
@@ -142,7 +142,16 @@ const item = (kind: GalleryItem['kind'], name: string): GalleryItem => {
return kind === 'video' ? { ...base, durationSeconds: 12, kind } : { ...base, kind };
};
-const renderItemMenu = async (actions: ImageActions, target: GalleryItemContextMenuTarget) => {
+const renderItemMenu = async (
+ actions: ImageActions,
+ target: GalleryItemContextMenuTarget,
+ previewVideoActions?: {
+ isCopyCurrentFrameAvailable: boolean;
+ itemKey: GalleryItemKey;
+ onCopyCurrentFrame: () => void;
+ onOpenDetails: () => void;
+ }
+) => {
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
@@ -153,6 +162,7 @@ const renderItemMenu = async (actions: ImageActions, target: GalleryItemContextM
<ImageContextMenu
actions={actions}
boards={NO_BOARDS}
+ previewVideoActions={previewVideoActions}
target={target as unknown as ImageContextMenuTarget}
onClose={vi.fn()}
/>
@@ -274,12 +284,59 @@ describe('ImageContextMenu mixed-media action visibility', () => {
expect(document.body.textContent).toContain('Change Board');
expect(document.body.textContent).toContain('Delete Video');
expect(document.body.textContent).not.toContain('Copy to clipboard');
+ expect(document.body.textContent).not.toContain('widgets.preview.copyCurrentFrame');
expect(document.body.textContent).not.toContain('Recall Metadata');
expect(document.body.textContent).not.toContain('Send to Upscale');
expect(document.body.textContent).not.toContain('Select for Compare');
expect(document.body.textContent).not.toContain('New from Image');
});
+ it('shows frame copy and Details only when a Preview host opts a single video into them', async () => {
+ const video = item('video', 'preview.mp4');
+ const onCopyCurrentFrame = vi.fn();
+ const onOpenDetails = vi.fn();
+ await renderItemMenu(
+ createActions(vi.fn()),
+ {
+ itemRefs: [{ kind: 'video', name: video.name }],
+ items: [video],
+ x: 20,
+ y: 20,
+ },
+ { isCopyCurrentFrameAvailable: false, itemKey: 'video:preview.mp4', onCopyCurrentFrame, onOpenDetails }
+ );
+
+ const copy = getMenuItem('widgets.preview.copyCurrentFrame');
+ const details = getMenuItem('widgets.preview.videoDetails');
+ expect(copy.getAttribute('aria-disabled')).toBe('true');
+
+ await interact(() => details.click());
+ expect(onOpenDetails).toHaveBeenCalledOnce();
+ expect(onCopyCurrentFrame).not.toHaveBeenCalled();
+ });
+
+ it('hides Preview video extras when the captured menu target is no longer the selected video', async () => {
+ const video = item('video', 'stale-menu.mp4');
+ await renderItemMenu(
+ createActions(vi.fn()),
+ {
+ itemRefs: [{ kind: 'video', name: video.name }],
+ items: [video],
+ x: 20,
+ y: 20,
+ },
+ {
+ isCopyCurrentFrameAvailable: true,
+ itemKey: 'video:new-selection.mp4',
+ onCopyCurrentFrame: vi.fn(),
+ onOpenDetails: vi.fn(),
+ }
+ );
+
+ expect(document.body.textContent).not.toContain('widgets.preview.copyCurrentFrame');
+ expect(document.body.textContent).not.toContain('widgets.preview.videoDetails');
+ });
+
it('opens the primary video from a video-only multi-selection and keeps image-only actions hidden', async () => {
const primaryVideo = item('video', 'primary.mp4');
const secondaryVideo = item('video', 'secondary.mp4');
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
index be5743097f..9fc4ed34cc 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
@@ -1,4 +1,4 @@
-import type { GalleryBoard, GalleryImage, GalleryItem, GalleryItemRef } from '@features/gallery';
+import type { GalleryBoard, GalleryImage, GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery';
import type { GalleryItemContextMenuTarget } from '@features/gallery/react';
/* eslint-disable react/react-compiler */
import type { GalleryCanvasImportDestination } from '@workbench/canvas-operations/api';
@@ -22,6 +22,7 @@ import {
ExternalLinkIcon,
EyeIcon,
FileImageIcon,
+ FileJsonIcon,
FolderIcon,
ImageIcon,
ImagesIcon,
@@ -54,6 +55,18 @@ export interface LegacyImageContextMenuTarget {
export type ImageContextMenuTarget = LegacyImageContextMenuTarget | GalleryItemContextMenuTarget;
+/**
+ * Extra actions owned by Preview's selected native video. Other hosts omit
+ * this port, so gallery/grid video menus retain their common-action-only
+ * contract and never gain a frame-copy item.
+ */
+export interface PreviewVideoContextActions {
+ isCopyCurrentFrameAvailable: boolean;
+ itemKey: GalleryItemKey;
+ onCopyCurrentFrame: () => void;
+ onOpenDetails: () => void;
+}
+
/** Extras on top of the shared MenuContent surface styling. */
const MENU_CONTENT_PROPS = {
minW: '13rem',
@@ -146,11 +159,13 @@ export const getImageContextMenuRecallRequestKey = (image: GalleryImage | null,
export const ImageContextMenu = ({
actions,
boards,
+ previewVideoActions,
target,
onClose,
}: {
actions: ImageActions;
boards: GalleryBoard[];
+ previewVideoActions?: PreviewVideoContextActions;
target: ImageContextMenuTarget | null;
onClose: () => void;
}) => {
@@ -207,6 +222,7 @@ export const ImageContextMenu = ({
key={`${itemTarget.itemRefs[0] ? toGalleryItemKey(itemTarget.itemRefs[0]) : 'item'}:${itemTarget.itemRefs.length}`}
actions={actions}
boards={boards}
+ previewVideoActions={previewVideoActions}
target={itemTarget}
onClose={onClose}
onRequestDeletion={requestDeletion}
@@ -241,12 +257,14 @@ export const ImageContextMenu = ({
const GalleryItemContextMenuContent = ({
actions,
boards,
+ previewVideoActions,
target,
onClose,
onRequestDeletion,
}: {
actions: ImageActions;
boards: GalleryBoard[];
+ previewVideoActions?: PreviewVideoContextActions;
target: GalleryItemContextMenuTarget;
onClose: () => void;
onRequestDeletion: (itemRefs: GalleryItemRef[]) => void;
@@ -302,6 +320,7 @@ const GalleryItemContextMenuContent = ({
boards={boards}
item={item}
itemRef={itemRef}
+ previewVideoActions={previewVideoActions}
onRequestDeletion={onRequestDeletion}
/>
)}
@@ -317,14 +336,17 @@ const SingleItemMenuItems = ({
boards,
item,
itemRef,
+ previewVideoActions,
onRequestDeletion,
}: {
actions: ImageActions;
boards: GalleryBoard[];
item: GalleryItem;
itemRef: GalleryItemRef;
+ previewVideoActions?: PreviewVideoContextActions;
onRequestDeletion: (itemRefs: GalleryItemRef[]) => void;
}) => {
+ const { t } = useTranslation();
const mediaLabel = item.kind === 'video' ? 'video' : 'item';
const handleOpenInNewTab = useCallback(() => actions.openItemInNewTab(item), [actions, item]);
const handleDownload = useCallback(() => void actions.downloadItem(item), [actions, item]);
@@ -363,6 +385,24 @@ const SingleItemMenuItems = ({
/>
</HStack>
<Menu.Separator borderColor="border.subtle" />
+ {item.kind === 'video' && previewVideoActions && previewVideoActions.itemKey === toGalleryItemKey(item) ? (
+ <>
+ <ContextMenuItem
+ disabled={!previewVideoActions.isCopyCurrentFrameAvailable}
+ icon={CopyIcon}
+ label={t('widgets.preview.copyCurrentFrame')}
+ value="copy-current-video-frame"
+ onClick={previewVideoActions.onCopyCurrentFrame}
+ />
+ <ContextMenuItem
+ icon={FileJsonIcon}
+ label={t('widgets.preview.videoDetails')}
+ value="open-video-details"
+ onClick={previewVideoActions.onOpenDetails}
+ />
+ <Menu.Separator borderColor="border.subtle" />
+ </>
+ ) : null}
<ChangeBoardSubMenu boards={boards} currentBoardId={item.boardId} onMove={handleMove} />
<Menu.Separator borderColor="border.subtle" />
<ContextMenuItem
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.tsx
index 42aa69a70b..29cee86a2c 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
@@ -1,4 +1,4 @@
-import type { GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery';
+import type { GalleryImage, GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
@@ -19,6 +19,7 @@ const mocks = vi.hoisted(() => ({
galleryPatchItems: vi.fn(),
gallerySelectItem: vi.fn(),
gallerySetItemMultiSelection: vi.fn(),
+ imageMetadata: vi.fn(),
invalidateGallery: vi.fn(),
invalidateGalleryItems: vi.fn(),
itemDelete: vi.fn(),
@@ -34,7 +35,7 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock('@features/gallery', () => ({
- galleryImages: { metadata: vi.fn() },
+ galleryImages: { metadata: (...args: unknown[]) => mocks.imageMetadata(...args) },
galleryItemOrganization: {
delete: (...args: unknown[]) => mocks.itemDelete(...args),
moveToBoard: (...args: unknown[]) => mocks.itemMoveToBoard(...args),
@@ -60,8 +61,15 @@ vi.mock('@features/gallery/queries', () => ({
vi.mock('@features/models', () => ({
ensureModelsLoaded: vi.fn(() => Promise.resolve()),
- getModelsSnapshot: () => ({ models: [] }),
- useModelsSelector: (selector: (snapshot: { models: never[] }) => unknown) => selector({ models: [] }),
+ getModelsSnapshot: () => ({
+ models: [{ base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' }],
+ }),
+ useModelsSelector: (
+ selector: (snapshot: { models: Array<{ base: 'sdxl'; key: string; name: string; type: 'main' }> }) => unknown
+ ) =>
+ selector({
+ models: [{ base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' }],
+ }),
}));
vi.mock('@workbench/useOpenWorkbenchWidget', () => ({
@@ -121,7 +129,7 @@ let currentItemActionContext: ItemActionContext | null = null;
const Probe = ({ ref }: { ref: Ref<ImageActions> }) => {
const actions = useImageActions({
boards: [],
- generateValues: {},
+ generateValues: { modelKey: 'sdxl-model' },
getItemActionContext: () => currentItemActionContext,
projectId: 'project-1',
});
@@ -156,6 +164,52 @@ afterEach(async () => {
root = null;
});
+describe('image recall capability cancellation', () => {
+ it('combines a caller signal with the account lifecycle signal for metadata transport', async () => {
+ let resolveMetadata!: (value: null) => void;
+ const metadata = new Promise<null>((resolve) => {
+ resolveMetadata = resolve;
+ });
+ mocks.imageMetadata.mockReturnValueOnce(metadata);
+ const controller = new AbortController();
+ const image: GalleryImage = {
+ boardId: 'none',
+ height: 512,
+ imageCategory: 'general',
+ imageName: 'recall.png',
+ imageUrl: '/full/recall.png',
+ queuedAt: '2026-07-30T00:00:00.000Z',
+ sourceQueueItemId: 'queue-recall',
+ starred: false,
+ thumbnailUrl: '/thumb/recall.png',
+ width: 512,
+ };
+ const getCapabilities = actionsRef.current?.getImageRecallCapabilities as unknown as (
+ image: GalleryImage,
+ signal?: AbortSignal
+ ) => Promise<unknown>;
+ let result!: Promise<unknown>;
+
+ await act(async () => {
+ result = getCapabilities(image, controller.signal);
+ await Promise.resolve();
+ });
+
+ expect(mocks.imageMetadata).toHaveBeenCalledWith('recall.png', expect.any(AbortSignal));
+ const transportSignal = mocks.imageMetadata.mock.calls[0]?.[1] as AbortSignal;
+ expect(transportSignal).toBeInstanceOf(AbortSignal);
+ expect(transportSignal.aborted).toBe(false);
+
+ controller.abort();
+
+ expect(transportSignal.aborted).toBe(true);
+ resolveMetadata(null);
+ await act(async () => {
+ await result;
+ });
+ });
+});
+
describe('partial image mutation outcomes', () => {
it('moves and patches only images confirmed by the backend', async () => {
mocks.itemMoveToBoard.mockResolvedValue({
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index 1a479249e2..642cc11d30 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -61,7 +61,7 @@ export interface ImageActions extends GalleryItemActions {
deleteImages: (imageNames: string[]) => Promise<void>;
downloadImage: (image: GalleryImage) => Promise<void>;
downloadImages: (imageNames: string[]) => Promise<void>;
- getImageRecallCapabilities: (image: GalleryImage) => Promise<ImageRecallCapabilities>;
+ getImageRecallCapabilities: (image: GalleryImage, signal?: AbortSignal) => Promise<ImageRecallCapabilities>;
moveImagesToBoard: (imageNames: string[], boardId: string) => Promise<void>;
openImageInPreview: (image: GalleryImage) => void;
recallImageData: (image: GalleryImage, kind: ImageRecallKind) => Promise<void>;
@@ -519,7 +519,7 @@ export const useImageActions = ({
}
},
downloadImages: (imageNames) => downloadItems(imageNames.map((name) => ({ kind: 'image', name }))),
- getImageRecallCapabilities: async (image) => {
+ getImageRecallCapabilities: async (image, signal) => {
const owner = captureAccountScope();
if (!currentGenerateValues) {
@@ -527,7 +527,8 @@ export const useImageActions = ({
}
try {
- const metadata = await galleryImages.metadata(image.imageName, owner.signal);
+ const requestSignal = signal ? AbortSignal.any([signal, owner.signal]) : owner.signal;
+ const metadata = await galleryImages.metadata(image.imageName, requestSignal);
assertAccountScopeCurrent(owner);
return getImageRecallCapabilities({
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx
index 959fba1ffa..211c86f2ff 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx
@@ -4,8 +4,17 @@ import type { ImageActions } from '@workbench/image-actions';
import { HStack, Icon } from '@chakra-ui/react';
import { galleryImageItemToGalleryImage, isGalleryImageItem, toGalleryItemRef } from '@features/gallery/contracts';
import { IconButton, Tooltip } from '@platform/ui';
-import { CopyIcon, DownloadIcon, EllipsisVerticalIcon, ImagesIcon, StarIcon, type LucideIcon } from 'lucide-react';
+import {
+ CopyIcon,
+ DownloadIcon,
+ EllipsisVerticalIcon,
+ FileJsonIcon,
+ ImagesIcon,
+ StarIcon,
+ type LucideIcon,
+} from 'lucide-react';
import { useCallback, type MouseEvent } from 'react';
+import { useTranslation } from 'react-i18next';
import type { PreviewDensity } from './previewDensity';
@@ -19,15 +28,22 @@ import type { PreviewDensity } from './previewDensity';
export const PreviewActionStrip = ({
actions,
density,
+ isVideoFrameCopyAvailable = false,
item,
+ onCopyCurrentFrame,
+ onOpenDetails,
onOpenMenu,
}: {
actions: ImageActions;
density: PreviewDensity;
+ isVideoFrameCopyAvailable?: boolean;
item: GalleryItem;
+ onCopyCurrentFrame?: () => void;
+ onOpenDetails?: () => void;
/** Opens the view's image context menu at viewport coordinates. */
onOpenMenu: ((x: number, y: number) => void) | null;
}) => {
+ const { t } = useTranslation();
const image = isGalleryImageItem(item) ? galleryImageItemToGalleryImage(item) : null;
const toggleStar = useCallback(
() => void actions.setItemsStarred([toGalleryItemRef(item)], !item.starred),
@@ -35,6 +51,8 @@ export const PreviewActionStrip = ({
);
const selectForCompare = useCallback(() => image && actions.selectForCompare(image), [actions, image]);
const copyImage = useCallback(() => image && void actions.copyImage(image), [actions, image]);
+ const copyCurrentFrame = useCallback(() => onCopyCurrentFrame?.(), [onCopyCurrentFrame]);
+ const openDetails = useCallback(() => onOpenDetails?.(), [onOpenDetails]);
const downloadItem = useCallback(() => void actions.downloadItem(item), [actions, item]);
const openMenu = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
@@ -75,15 +93,36 @@ export const PreviewActionStrip = ({
{starButton}
{image ? <StripIconButton icon={ImagesIcon} label="Select for Compare" onClick={selectForCompare} /> : null}
{image ? <StripIconButton icon={CopyIcon} label="Copy to clipboard" onClick={copyImage} /> : null}
+ {item.kind === 'video' && onCopyCurrentFrame ? (
+ <StripIconButton
+ disabled={!isVideoFrameCopyAvailable}
+ icon={CopyIcon}
+ label={t('widgets.preview.copyCurrentFrame')}
+ onClick={copyCurrentFrame}
+ />
+ ) : null}
+ {item.kind === 'video' && onOpenDetails ? (
+ <StripIconButton icon={FileJsonIcon} label={t('widgets.preview.videoDetails')} onClick={openDetails} />
+ ) : null}
<StripIconButton icon={DownloadIcon} label={`Download ${itemKindLabel}`} onClick={downloadItem} />
{menuButton}
</HStack>
);
};
-const StripIconButton = ({ icon, label, onClick }: { icon: LucideIcon; label: string; onClick: () => void }) => (
+const StripIconButton = ({
+ disabled,
+ icon,
+ label,
+ onClick,
+}: {
+ disabled?: boolean;
+ icon: LucideIcon;
+ label: string;
+ onClick: () => void;
+}) => (
<Tooltip content={label}>
- <IconButton aria-label={label} color="fg.muted" size="2xs" variant="ghost" onClick={onClick}>
+ <IconButton aria-label={label} color="fg.muted" disabled={disabled} size="2xs" variant="ghost" onClick={onClick}>
<Icon as={icon} boxSize="3.5" />
</IconButton>
</Tooltip>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx
new file mode 100644
index 0000000000..fa1d238656
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx
@@ -0,0 +1,425 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
+import type { GalleryImage, GalleryImageItem, GalleryVideoItem } from '@features/gallery';
+import type * as GalleryModule from '@features/gallery';
+import type * as IdentityModule from '@features/identity';
+import type { ImageActions, ImageRecallCapabilities } from '@workbench/image-actions';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { PreviewFooter } from './PreviewFooter';
+
+const galleryMocks = vi.hoisted(() => ({
+ imageMetadata: vi.fn(),
+ videoMetadata: vi.fn(),
+ videoWorkflow: vi.fn(),
+}));
+const identityMocks = vi.hoisted(() => ({ accountEpoch: 7 }));
+
+vi.mock('@features/gallery', async (importOriginal) => {
+ const actual = await importOriginal<typeof GalleryModule>();
+
+ return {
+ ...actual,
+ galleryImages: { ...actual.galleryImages, metadata: galleryMocks.imageMetadata },
+ galleryVideos: {
+ metadata: galleryMocks.videoMetadata,
+ workflow: galleryMocks.videoWorkflow,
+ },
+ };
+});
+vi.mock('@features/identity', async (importOriginal) => {
+ const actual = await importOriginal<typeof IdentityModule>();
+
+ return {
+ ...actual,
+ useAuthSession: () => ({
+ accountEpoch: identityMocks.accountEpoch,
+ multiuserEnabled: true,
+ phase: 'ready',
+ sessionExpired: false,
+ setupRequired: false,
+ strictPasswordChecking: true,
+ user: null,
+ }),
+ };
+});
+
+const imageItem: GalleryImageItem = {
+ boardId: 'none',
+ category: 'general',
+ createdAt: '2026-07-30T12:00:00Z',
+ fullUrl: '/images/still.png',
+ height: 768,
+ isIntermediate: false,
+ kind: 'image',
+ name: 'still.png',
+ sourceQueueItemId: 'queue-image',
+ starred: false,
+ thumbnailUrl: '/thumbnails/still.webp',
+ width: 512,
+};
+const actionImage: GalleryImage = {
+ boardId: imageItem.boardId,
+ height: imageItem.height,
+ imageCategory: imageItem.category,
+ imageName: imageItem.name,
+ imageUrl: imageItem.fullUrl,
+ queuedAt: imageItem.createdAt,
+ sourceQueueItemId: imageItem.sourceQueueItemId ?? 'backend-gallery',
+ starred: imageItem.starred,
+ thumbnailUrl: imageItem.thumbnailUrl,
+ width: imageItem.width,
+};
+const videoItem: GalleryVideoItem = {
+ boardId: 'none',
+ category: 'general',
+ createdAt: '2026-07-30T11:00:00Z',
+ durationSeconds: 15,
+ fullUrl: '/videos/clip.mp4',
+ height: 1080,
+ isIntermediate: false,
+ kind: 'video',
+ name: 'clip.mp4',
+ starred: false,
+ thumbnailUrl: '/thumbnails/clip.webp',
+ width: 1920,
+};
+const ALL_RECALL_CAPABILITIES: ImageRecallCapabilities = {
+ all: true,
+ clipSkip: true,
+ dimensions: true,
+ prompts: true,
+ remix: true,
+ seed: true,
+};
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ initAsync: false,
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ common: { countOfTotal: '{{count}} of {{total}}', copy: 'Copy' },
+ widgets: {
+ preview: {
+ details: 'Details',
+ framesPerSecond: '{{count}} fps',
+ graph: 'Graph',
+ graphJsonLabel: 'Video graph JSON',
+ itemCount_one: '{{count}} item',
+ itemCount_other: '{{count}} items',
+ loadingMetadata: 'Loading metadata',
+ metadata: 'Metadata',
+ metadataJsonLabel: 'Video metadata JSON',
+ nextItemInBoard: 'Next item in board',
+ previousItemInBoard: 'Previous item in board',
+ recallNotAvailable: 'Not recallable for this image',
+ videoDuration: 'Duration {{duration}}',
+ workflow: 'Workflow',
+ workflowJsonLabel: 'Video workflow JSON',
+ },
+ },
+ },
+ },
+ },
+});
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+let queryClient: QueryClient;
+let actions: ImageActions;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const interact = (action: () => void, delay = 100): Promise<void> =>
+ act(async () => {
+ action();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, delay);
+ });
+ });
+
+const renderFooter = async ({
+ isOpen,
+ item,
+}: {
+ isOpen: boolean;
+ item: GalleryImageItem | GalleryVideoItem;
+}): Promise<void> => {
+ await interact(() => {
+ root?.render(
+ <QueryClientProvider client={queryClient}>
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <PreviewFooter
+ actionImage={item.kind === 'image' ? actionImage : null}
+ actions={actions}
+ boardItemCount={2}
+ isLoadingBoard={false}
+ isMetadataOpen={isOpen}
+ item={item}
+ selectedIndex={0}
+ onNext={() => undefined}
+ onPrevious={() => undefined}
+ onToggleMetadata={() => undefined}
+ />
+ </ChakraProvider>
+ </I18nextProvider>
+ </QueryClientProvider>
+ );
+ });
+};
+
+beforeEach(() => {
+ identityMocks.accountEpoch = 7;
+ galleryMocks.imageMetadata.mockReset().mockResolvedValue(null);
+ galleryMocks.videoMetadata.mockReset().mockResolvedValue(null);
+ galleryMocks.videoWorkflow.mockReset().mockResolvedValue({ graph: null, workflow: null });
+ actions = {
+ getImageRecallCapabilities: vi.fn(() => Promise.resolve(ALL_RECALL_CAPABILITIES)),
+ recallImageData: vi.fn(() => Promise.resolve()),
+ } as unknown as ImageActions;
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { gcTime: Infinity, retry: false } },
+ });
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await interact(() => root?.unmount(), 0);
+ queryClient.clear();
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('Preview query-driven Details', () => {
+ it('shows the video Details disclosure but starts no request while it is closed', async () => {
+ await renderFooter({ isOpen: false, item: videoItem });
+
+ expect(galleryMocks.videoMetadata).not.toHaveBeenCalled();
+ expect(galleryMocks.videoWorkflow).not.toHaveBeenCalled();
+ expect(getButton('Details')).not.toBeNull();
+ });
+
+ it('keeps the disabled image recall skeleton mounted while Details is pending', async () => {
+ galleryMocks.imageMetadata.mockReturnValueOnce(
+ new Promise(() => {
+ // Intentionally pending.
+ })
+ );
+ actions.getImageRecallCapabilities = vi.fn(
+ () =>
+ new Promise<ImageRecallCapabilities>(() => {
+ // Intentionally pending.
+ })
+ );
+
+ await renderFooter({ isOpen: true, item: imageItem });
+
+ expect(host?.textContent).toContain('Loading metadata');
+ expect(getButton('Recall All').disabled).toBe(true);
+ });
+
+ it('passes the Details query signal to image recall capability work and aborts it on close', async () => {
+ const metadata = deferred<null>();
+ const capabilities = deferred<ImageRecallCapabilities>();
+ const getImageRecallCapabilities = vi.fn((_image: GalleryImage, _signal?: AbortSignal) => capabilities.promise);
+ galleryMocks.imageMetadata.mockReturnValueOnce(metadata.promise);
+ actions.getImageRecallCapabilities = getImageRecallCapabilities;
+
+ await renderFooter({ isOpen: true, item: imageItem });
+
+ const metadataSignal = galleryMocks.imageMetadata.mock.calls[0]?.[1] as AbortSignal;
+ const capabilitiesSignal = getImageRecallCapabilities.mock.calls[0]?.[1];
+ expect(capabilitiesSignal).toBe(metadataSignal);
+
+ await renderFooter({ isOpen: false, item: imageItem });
+
+ expect(metadataSignal.aborted).toBe(true);
+ expect(capabilitiesSignal?.aborted).toBe(true);
+ await interact(() => {
+ metadata.resolve(null);
+ capabilities.resolve(ALL_RECALL_CAPABILITIES);
+ }, 0);
+ });
+
+ it('starts video metadata and workflow/graph concurrently under an epoch + GalleryItemKey query', async () => {
+ const metadata = deferred<Record<string, unknown> | null>();
+ const workflow = deferred<{ graph: string | null; workflow: string | null }>();
+ galleryMocks.videoMetadata.mockReturnValueOnce(metadata.promise);
+ galleryMocks.videoWorkflow.mockReturnValueOnce(workflow.promise);
+
+ await renderFooter({ isOpen: true, item: videoItem });
+
+ expect(galleryMocks.videoMetadata).toHaveBeenCalledOnce();
+ expect(galleryMocks.videoWorkflow).toHaveBeenCalledOnce();
+ expect(galleryMocks.videoMetadata.mock.calls[0]?.[0]).toBe('clip.mp4');
+ expect(galleryMocks.videoWorkflow.mock.calls[0]?.[0]).toBe('clip.mp4');
+ expect(galleryMocks.videoMetadata.mock.calls[0]?.[1]).toBeInstanceOf(AbortSignal);
+ expect(galleryMocks.videoWorkflow.mock.calls[0]?.[1]).toBe(galleryMocks.videoMetadata.mock.calls[0]?.[1]);
+ expect(queryClient.getQueryCache().find({ queryKey: ['preview', 'details', 7, 'video:clip.mp4'] })).toBeDefined();
+
+ await interact(() => {
+ metadata.resolve({ codec: 'h264' });
+ workflow.resolve({ graph: '{"nodes":[]}', workflow: '{"name":"clip"}' });
+ });
+ });
+
+ it('aborts in-flight supported transports when Details closes', async () => {
+ const metadata = deferred<Record<string, unknown> | null>();
+ const workflow = deferred<{ graph: string | null; workflow: string | null }>();
+ galleryMocks.videoMetadata.mockReturnValueOnce(metadata.promise);
+ galleryMocks.videoWorkflow.mockReturnValueOnce(workflow.promise);
+ await renderFooter({ isOpen: true, item: videoItem });
+ const metadataSignal = galleryMocks.videoMetadata.mock.calls[0]?.[1] as AbortSignal;
+ const workflowSignal = galleryMocks.videoWorkflow.mock.calls[0]?.[1] as AbortSignal;
+
+ await renderFooter({ isOpen: false, item: videoItem });
+
+ expect(metadataSignal.aborted).toBe(true);
+ expect(workflowSignal.aborted).toBe(true);
+ expect(galleryMocks.videoMetadata).toHaveBeenCalledOnce();
+ expect(galleryMocks.videoWorkflow).toHaveBeenCalledOnce();
+ });
+
+ it('aborts and isolates stale item results behind qualified keys', async () => {
+ const oldMetadata = deferred<Record<string, unknown> | null>();
+ const oldWorkflow = deferred<{ graph: string | null; workflow: string | null }>();
+ galleryMocks.videoMetadata.mockImplementation((name: string) =>
+ name === 'clip.mp4' ? oldMetadata.promise : Promise.resolve({ marker: 'new-item' })
+ );
+ galleryMocks.videoWorkflow.mockImplementation((name: string) =>
+ name === 'clip.mp4'
+ ? oldWorkflow.promise
+ : Promise.resolve({ graph: '{"marker":"new-graph"}', workflow: '{"marker":"new-workflow"}' })
+ );
+ await renderFooter({ isOpen: true, item: videoItem });
+ const oldSignal = galleryMocks.videoMetadata.mock.calls[0]?.[1] as AbortSignal;
+ const nextItem = {
+ ...videoItem,
+ fullUrl: '/videos/next.mp4',
+ name: 'next.mp4',
+ thumbnailUrl: '/thumbnails/next.webp',
+ };
+
+ await renderFooter({ isOpen: true, item: nextItem });
+
+ expect(oldSignal.aborted).toBe(true);
+ expect(galleryMocks.videoMetadata).toHaveBeenNthCalledWith(2, 'next.mp4', expect.any(AbortSignal));
+ await act(async () => {
+ await vi.waitFor(() => expect(host?.textContent).toContain('new-item'));
+ });
+
+ await interact(() => {
+ oldMetadata.resolve({ marker: 'stale-item' });
+ oldWorkflow.resolve({ graph: '{"marker":"stale-graph"}', workflow: '{"marker":"stale-workflow"}' });
+ });
+ expect(host?.textContent).not.toContain('stale-item');
+ });
+
+ it('aborts and isolates stale account results behind the account epoch', async () => {
+ const oldMetadata = deferred<Record<string, unknown> | null>();
+ const oldWorkflow = deferred<{ graph: string | null; workflow: string | null }>();
+ galleryMocks.videoMetadata
+ .mockReturnValueOnce(oldMetadata.promise)
+ .mockResolvedValueOnce({ marker: 'new-account' });
+ galleryMocks.videoWorkflow
+ .mockReturnValueOnce(oldWorkflow.promise)
+ .mockResolvedValueOnce({ graph: '{"epoch":8}', workflow: '{"epoch":8}' });
+ await renderFooter({ isOpen: true, item: videoItem });
+ const oldSignal = galleryMocks.videoMetadata.mock.calls[0]?.[1] as AbortSignal;
+
+ identityMocks.accountEpoch = 8;
+ await renderFooter({ isOpen: true, item: videoItem });
+
+ expect(oldSignal.aborted).toBe(true);
+ expect(galleryMocks.videoMetadata).toHaveBeenCalledTimes(2);
+ expect(queryClient.getQueryCache().find({ queryKey: ['preview', 'details', 8, 'video:clip.mp4'] })).toBeDefined();
+ await act(async () => {
+ await vi.waitFor(() => expect(host?.textContent).toContain('new-account'));
+ });
+
+ await interact(() => {
+ oldMetadata.resolve({ marker: 'stale-account' });
+ oldWorkflow.resolve({ graph: '{"epoch":7}', workflow: '{"epoch":7}' });
+ });
+ expect(host?.textContent).not.toContain('stale-account');
+ });
+
+ it('renders raw Metadata, Workflow, and Graph JSON tabs without image recall controls', async () => {
+ galleryMocks.videoMetadata.mockResolvedValueOnce({ codec: 'h264', duration: 15 });
+ galleryMocks.videoWorkflow.mockResolvedValueOnce({
+ graph: '{"nodes":[{"id":"video"}]}',
+ workflow: '{"name":"Video workflow"}',
+ });
+
+ await renderFooter({ isOpen: true, item: videoItem });
+
+ await act(async () => {
+ await vi.waitFor(() => expect(host?.textContent).toContain('"codec": "h264"'));
+ });
+ expect(getButton('Metadata')).not.toBeNull();
+ expect(getButton('Workflow')).not.toBeNull();
+ expect(getButton('Graph')).not.toBeNull();
+ expect(host?.textContent).not.toContain('Recall All');
+
+ await interact(() => getButton('Workflow').click());
+ expect(host?.textContent).toContain('"name":"Video workflow"');
+ await interact(() => getButton('Graph').click());
+ expect(host?.textContent).toContain('"id":"video"');
+ expect(host?.querySelector('[aria-label="Video graph JSON"]')).not.toBeNull();
+ });
+
+ it('keeps parsed image rows, source run, and recall controls while moving the fetch to Query', async () => {
+ galleryMocks.imageMetadata.mockResolvedValueOnce({
+ model: { name: 'Test Model' },
+ positive_prompt: 'query-driven prompt',
+ seed: 42,
+ });
+
+ await renderFooter({ isOpen: true, item: imageItem });
+
+ expect(galleryMocks.imageMetadata).toHaveBeenCalledWith('still.png', expect.any(AbortSignal));
+ expect(queryClient.getQueryCache().find({ queryKey: ['preview', 'details', 7, 'image:still.png'] })).toBeDefined();
+ await act(async () => {
+ await vi.waitFor(() => expect(host?.textContent).toContain('query-driven prompt'));
+ });
+ expect(host?.textContent).toContain('Test Model');
+ expect(host?.textContent).toContain('queue-image');
+
+ await interact(() => getButton('Recall All').click());
+ expect(actions.recallImageData).toHaveBeenCalledWith(actionImage, 'all');
+ });
+});
+
+const getButton = (text: string): HTMLButtonElement => {
+ const button = Array.from((host ?? document).querySelectorAll<HTMLButtonElement>('button')).find(
+ (candidate) => candidate.textContent?.trim() === text
+ );
+
+ if (!button) {
+ throw new Error(`Expected button: ${text}`);
+ }
+
+ return button;
+};
+
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+
+ return { promise, resolve };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx
index 63d4696892..a2a9ed8337 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx
@@ -90,14 +90,13 @@ export const PreviewFooter = ({
</Button>
</HStack>
</HStack>
- {actionImage ? (
- <PreviewMetadataPanel
- actions={actions}
- image={actionImage}
- isOpen={isMetadataOpen}
- onToggle={onToggleMetadata}
- />
- ) : null}
+ <PreviewMetadataPanel
+ actions={actions}
+ image={actionImage}
+ isOpen={isMetadataOpen}
+ item={item}
+ onToggle={onToggleMetadata}
+ />
</Stack>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
index a8e9964873..29f0f08462 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
@@ -10,6 +10,7 @@ import { Button } from '@platform/ui/Button';
import {
useCallback,
useId,
+ useImperativeHandle,
useMemo,
useRef,
useState,
@@ -66,9 +67,12 @@ interface PreviewFrameProps {
/** Imperative zoom controls, for hotkeys registered by the widget shell. */
loupeControlsRef?: Ref<PreviewLoupeControls>;
onContextMenu?: (x: number, y: number) => void;
+ onVideoCopyAvailabilityChange?: (itemKey: GalleryItemKey, isAvailable: boolean) => void;
padding?: string;
shouldAntialiasLiveImage: boolean;
source: PreviewMediaSource | null;
+ /** Preview-owned controller for the selected video's current frame. */
+ videoControllerRef?: Ref<PreviewVideoFrameController>;
/** `framed` = bordered surface for a selected item; `inset` = flush surface for the empty state. */
variant: 'framed' | 'inset';
}
@@ -82,8 +86,10 @@ export const PreviewFrame = (props: PreviewFrameProps) => {
frameWidth={props.frameWidth}
isItemCurrent={props.isItemCurrent}
onContextMenu={props.onContextMenu}
+ onCopyAvailabilityChange={props.onVideoCopyAvailabilityChange}
padding={props.padding}
source={props.source}
+ videoControllerRef={props.videoControllerRef}
/>
);
}
@@ -105,7 +111,9 @@ const PreviewImageFrame = ({
shouldAntialiasLiveImage,
source,
variant,
-}: Omit<PreviewFrameProps, 'isItemCurrent' | 'source'> & { source: StreamingImageSource | null }) => {
+}: Omit<PreviewFrameProps, 'isItemCurrent' | 'onVideoCopyAvailabilityChange' | 'source' | 'videoControllerRef'> & {
+ source: StreamingImageSource | null;
+}) => {
const { t } = useTranslation();
const loupe = usePreviewLoupe({
controlsRef: loupeControlsRef,
@@ -282,25 +290,111 @@ const PreviewVideo = ({
frameWidth,
isItemCurrent,
onContextMenu,
+ onCopyAvailabilityChange,
padding,
source,
+ videoControllerRef,
}: {
frameHeight: number;
frameWidth: number;
isItemCurrent?: (itemKey: GalleryItemKey) => boolean;
onContextMenu?: (x: number, y: number) => void;
+ onCopyAvailabilityChange?: (itemKey: GalleryItemKey, isAvailable: boolean) => void;
padding?: string;
source: Extract<PreviewMediaSource, { kind: 'video' }>;
+ videoControllerRef?: Ref<PreviewVideoFrameController>;
}) => {
const { t } = useTranslation();
const videoRef = useRef<HTMLVideoElement | null>(null);
const automaticRefreshUsedRef = useRef(false);
const pendingRefreshRef = useRef<Promise<boolean> | null>(null);
const [hasFailed, setHasFailed] = useState(false);
- const setVideoRef = useCallback((video: HTMLVideoElement | null) => {
- videoRef.current = video;
- }, []);
+ const publishCopyAvailability = useCallback(() => {
+ onCopyAvailabilityChange?.(source.itemKey, isVideoFrameCopyAvailable(videoRef.current));
+ }, [onCopyAvailabilityChange, source.itemKey]);
+ const setVideoRef = useCallback(
+ (video: HTMLVideoElement | null) => {
+ videoRef.current = video;
+ onCopyAvailabilityChange?.(source.itemKey, isVideoFrameCopyAvailable(video));
+ },
+ [onCopyAvailabilityChange, source.itemKey]
+ );
+ const copyCurrentFrame = useCallback(async (): Promise<PreviewVideoFrameCopyResult> => {
+ const video = videoRef.current;
+ const clipboardItem = globalThis.ClipboardItem;
+ const write = navigator.clipboard?.write?.bind(navigator.clipboard);
+
+ if (!clipboardItem || !write) {
+ return { ok: false, reason: 'unsupported' };
+ }
+
+ if (!isVideoFrameReady(video)) {
+ return { ok: false, reason: 'not-ready' };
+ }
+
+ const accountEpoch = getAuthSession().accountEpoch;
+ const itemKey = source.itemKey;
+ const width = video.videoWidth;
+ const height = video.videoHeight;
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ const context = canvas.getContext('2d');
+
+ if (!context) {
+ return { ok: false, reason: 'draw-failed' };
+ }
+
+ try {
+ context.drawImage(video, 0, 0, width, height);
+ } catch {
+ return { ok: false, reason: 'draw-failed' };
+ }
+
+ let blob: Blob | null;
+
+ try {
+ blob = await encodeCanvasPng(canvas);
+ } catch (error: unknown) {
+ return { ok: false, reason: isCanvasSecurityError(error) ? 'draw-failed' : 'encode-failed' };
+ }
+
+ if (!blob) {
+ return { ok: false, reason: 'encode-failed' };
+ }
+
+ const isCurrent = (): boolean =>
+ videoRef.current === video &&
+ getAuthSession().accountEpoch === accountEpoch &&
+ (!isItemCurrent || isItemCurrent(itemKey));
+
+ if (!isCurrent()) {
+ return { ok: false, reason: 'stale' };
+ }
+
+ let item: ClipboardItem;
+
+ try {
+ item = new clipboardItem({ 'image/png': blob });
+ await write([item]);
+ } catch {
+ return { ok: false, reason: 'clipboard-failed' };
+ }
+
+ return isCurrent() ? { ok: true } : { ok: false, reason: 'stale' };
+ }, [isItemCurrent, source.itemKey]);
+ const isCopyAvailable = useCallback(() => isVideoFrameCopyAvailable(videoRef.current), []);
+ useImperativeHandle(
+ videoControllerRef,
+ () => ({
+ copyCurrentFrame,
+ isCopyAvailable,
+ itemKey: source.itemKey,
+ }),
+ [copyCurrentFrame, isCopyAvailable, source.itemKey]
+ );
const handleVideoError = useCallback(() => {
+ publishCopyAvailability();
const video = videoRef.current;
if (!video || pendingRefreshRef.current) {
@@ -340,7 +434,7 @@ const PreviewVideo = ({
};
void refresh.then(finishRefresh, () => finishRefresh(false));
- }, [isItemCurrent, source.itemKey]);
+ }, [isItemCurrent, publishCopyAvailability, source.itemKey]);
const handleRetry = useCallback(() => {
const video = videoRef.current;
@@ -352,7 +446,8 @@ const PreviewVideo = ({
pendingRefreshRef.current = null;
setHasFailed(false);
video.load();
- }, []);
+ publishCopyAvailability();
+ }, [publishCopyAvailability]);
const handleContextMenu = useCallback(
(event: MouseEvent<HTMLDivElement>) => {
if (onContextMenu) {
@@ -402,7 +497,14 @@ const PreviewVideo = ({
preload="metadata"
src={source.src}
style={VIDEO_STYLE}
+ onCanPlay={publishCopyAvailability}
+ onEmptied={publishCopyAvailability}
onError={handleVideoError}
+ onLoadedData={publishCopyAvailability}
+ onPlaying={publishCopyAvailability}
+ onResize={publishCopyAvailability}
+ onSeeked={publishCopyAvailability}
+ onWaiting={publishCopyAvailability}
/>
{hasFailed ? (
<>
@@ -439,6 +541,44 @@ const PreviewVideo = ({
);
};
+export type PreviewVideoFrameCopyFailureReason =
+ | 'clipboard-failed'
+ | 'draw-failed'
+ | 'encode-failed'
+ | 'not-ready'
+ | 'stale'
+ | 'unsupported';
+
+export type PreviewVideoFrameCopyResult = { ok: true } | { ok: false; reason: PreviewVideoFrameCopyFailureReason };
+
+export interface PreviewVideoFrameController {
+ copyCurrentFrame(): Promise<PreviewVideoFrameCopyResult>;
+ isCopyAvailable(): boolean;
+ readonly itemKey: GalleryItemKey;
+}
+
+const isVideoFrameReady = (video: HTMLVideoElement | null): video is HTMLVideoElement =>
+ Boolean(
+ video && video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA && video.videoWidth > 0 && video.videoHeight > 0
+ );
+
+const isVideoFrameCopyAvailable = (video: HTMLVideoElement | null): boolean =>
+ typeof globalThis.ClipboardItem !== 'undefined' &&
+ typeof navigator.clipboard?.write === 'function' &&
+ isVideoFrameReady(video);
+
+const encodeCanvasPng = (canvas: HTMLCanvasElement): Promise<Blob | null> =>
+ new Promise((resolve, reject) => {
+ try {
+ canvas.toBlob(resolve, 'image/png');
+ } catch (error: unknown) {
+ reject(error instanceof Error ? error : new Error(String(error)));
+ }
+ });
+
+const isCanvasSecurityError = (error: unknown): boolean =>
+ error instanceof DOMException && error.name === 'SecurityError';
+
const VIDEO_STYLE: CSSProperties = {
display: 'block',
height: '100%',
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.tsx
index 6f23f5e767..2842facbd5 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
@@ -5,12 +5,17 @@ import { ChakraProvider } from '@chakra-ui/react';
import { DndContext, PointerSensor, useDndMonitor, useSensor, useSensors, type DragStartEvent } from '@dnd-kit/core';
import { system } from '@theme/system';
import { createInstance } from 'i18next';
-import { act } from 'react';
+import { act, createRef, type Ref } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { PreviewFrame, type PreviewMediaSource } from './PreviewFrame';
+import {
+ PreviewFrame,
+ type PreviewMediaSource,
+ type PreviewVideoFrameController,
+ type PreviewVideoFrameCopyResult,
+} from './PreviewFrame';
const identityMocks = vi.hoisted(() => ({
accountEpoch: 7,
@@ -58,6 +63,12 @@ let root: Root | null = null;
let onDragStart = vi.fn();
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const suppressNativeMediaError = (event: Event): void => {
+ if (event.isTrusted && event.target instanceof HTMLMediaElement) {
+ event.stopImmediatePropagation();
+ }
+};
+
const interact = (action: () => void, delay = 0): Promise<void> =>
act(async () => {
action();
@@ -81,10 +92,14 @@ const DragMonitor = () => {
const VideoHarness = ({
isItemCurrent = () => true,
+ onCopyAvailabilityChange,
source = videoSource,
+ videoControllerRef,
}: {
isItemCurrent?: (itemKey: GalleryItemKey) => boolean;
+ onCopyAvailabilityChange?: (itemKey: GalleryItemKey, isAvailable: boolean) => void;
source?: VideoSource;
+ videoControllerRef?: Ref<PreviewVideoFrameController>;
}) => {
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
@@ -101,6 +116,8 @@ const VideoHarness = ({
source={source}
variant="framed"
isItemCurrent={isItemCurrent}
+ onVideoCopyAvailabilityChange={onCopyAvailabilityChange}
+ videoControllerRef={videoControllerRef}
/>
</div>
</DndContext>
@@ -113,6 +130,9 @@ beforeEach(() => {
onDragStart = vi.fn();
host = document.createElement('div');
host.style.cssText = 'height:320px;left:20px;position:fixed;top:20px;width:480px;';
+ // The deliberately invalid data URL may fail at any time under browser-suite
+ // load. Recovery tests dispatch deterministic, untrusted error events.
+ host.addEventListener('error', suppressNativeMediaError, true);
document.body.append(host);
root = createRoot(host);
});
@@ -305,17 +325,216 @@ describe('PreviewFrame native video arm', () => {
expect(identityMocks.refreshProtectedMediaCookie).toHaveBeenCalledTimes(2);
});
+
+ it('enables frame copy only for current intrinsic frame data and ClipboardItem write support', async () => {
+ setClipboardUnsupported();
+ const controllerRef = createRef<PreviewVideoFrameController>();
+ const onCopyAvailabilityChange = vi.fn();
+ await renderVideo(() => true, videoSource, controllerRef, onCopyAvailabilityChange);
+ const video = getVideo();
+
+ setVideoFrameState(video, { height: 1080, readyState: HTMLMediaElement.HAVE_CURRENT_DATA, width: 1920 });
+ await interact(() => video.dispatchEvent(new Event('loadeddata')));
+
+ expect(controllerRef.current?.isCopyAvailable()).toBe(false);
+ expect(onCopyAvailabilityChange).toHaveBeenLastCalledWith(videoSource.itemKey, false);
+
+ installClipboardSupport();
+ setVideoFrameState(video, { height: 0, readyState: HTMLMediaElement.HAVE_CURRENT_DATA, width: 1920 });
+ await interact(() => video.dispatchEvent(new Event('resize')));
+ expect(controllerRef.current?.isCopyAvailable()).toBe(false);
+
+ setVideoFrameState(video, { height: 1080, readyState: HTMLMediaElement.HAVE_METADATA, width: 1920 });
+ await interact(() => video.dispatchEvent(new Event('waiting')));
+ expect(controllerRef.current?.isCopyAvailable()).toBe(false);
+
+ setVideoFrameState(video, { height: 1080, readyState: HTMLMediaElement.HAVE_CURRENT_DATA, width: 1920 });
+ await interact(() => video.dispatchEvent(new Event('canplay')));
+
+ expect(controllerRef.current?.isCopyAvailable()).toBe(true);
+ expect(onCopyAvailabilityChange).toHaveBeenLastCalledWith(videoSource.itemKey, true);
+ });
+
+ it('draws the intrinsic video frame, encodes PNG, and writes one ClipboardItem', async () => {
+ const controllerRef = createRef<PreviewVideoFrameController>();
+ const { clipboardItems, write } = installClipboardSupport();
+ const drawImage = vi.fn();
+ const canvases: HTMLCanvasElement[] = [];
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function (this: HTMLCanvasElement) {
+ canvases.push(this);
+ return { drawImage } as unknown as CanvasRenderingContext2D;
+ });
+ const png = new Blob(['frame'], { type: 'image/png' });
+ vi.spyOn(HTMLCanvasElement.prototype, 'toBlob').mockImplementation((callback, type) => {
+ expect(type).toBe('image/png');
+ callback(png);
+ });
+ await renderVideo(() => true, videoSource, controllerRef);
+ const video = getVideo();
+ setVideoFrameState(video, { height: 720, readyState: HTMLMediaElement.HAVE_CURRENT_DATA, width: 1280 });
+
+ const result = await copyFrame(controllerRef);
+
+ expect(result).toEqual({ ok: true });
+ expect(canvases[0]?.width).toBe(1280);
+ expect(canvases[0]?.height).toBe(720);
+ expect(drawImage).toHaveBeenCalledWith(video, 0, 0, 1280, 720);
+ expect(clipboardItems).toHaveLength(1);
+ expect(clipboardItems[0]?.['image/png']).toBe(png);
+ expect(write).toHaveBeenCalledOnce();
+ });
+
+ it('distinguishes unsupported Clipboard APIs from media without a current frame', async () => {
+ const controllerRef = createRef<PreviewVideoFrameController>();
+ setClipboardUnsupported();
+ await renderVideo(() => true, videoSource, controllerRef);
+ const video = getVideo();
+ setVideoFrameState(video, { height: 1080, readyState: HTMLMediaElement.HAVE_CURRENT_DATA, width: 1920 });
+
+ await expect(copyFrame(controllerRef)).resolves.toEqual({ ok: false, reason: 'unsupported' });
+
+ installClipboardSupport();
+ setVideoFrameState(video, { height: 1080, readyState: HTMLMediaElement.HAVE_METADATA, width: 1920 });
+
+ await expect(copyFrame(controllerRef)).resolves.toEqual({ ok: false, reason: 'not-ready' });
+ });
+
+ it('reports canvas draw and taint failures without touching the clipboard', async () => {
+ const controllerRef = createRef<PreviewVideoFrameController>();
+ const { write } = installClipboardSupport();
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
+ drawImage: () => {
+ throw new DOMException('The canvas is tainted.', 'SecurityError');
+ },
+ } as unknown as CanvasRenderingContext2D);
+ await renderVideo(() => true, videoSource, controllerRef);
+ setVideoFrameState(getVideo(), { height: 1080, readyState: HTMLMediaElement.HAVE_CURRENT_DATA, width: 1920 });
+
+ await expect(copyFrame(controllerRef)).resolves.toEqual({ ok: false, reason: 'draw-failed' });
+ expect(write).not.toHaveBeenCalled();
+
+ vi.mocked(HTMLCanvasElement.prototype.getContext).mockReturnValue({
+ drawImage: vi.fn(),
+ } as unknown as CanvasRenderingContext2D);
+ vi.spyOn(HTMLCanvasElement.prototype, 'toBlob').mockImplementation(() => {
+ throw new DOMException('The canvas is tainted.', 'SecurityError');
+ });
+
+ await expect(copyFrame(controllerRef)).resolves.toEqual({ ok: false, reason: 'draw-failed' });
+ expect(write).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ {
+ configure: () => vi.spyOn(HTMLCanvasElement.prototype, 'toBlob').mockImplementation((callback) => callback(null)),
+ label: 'null PNG encoding',
+ },
+ {
+ configure: () =>
+ vi.spyOn(HTMLCanvasElement.prototype, 'toBlob').mockImplementation(() => {
+ throw new Error('encoder rejected');
+ }),
+ label: 'rejected PNG encoding',
+ },
+ ])('reports $label without writing', async ({ configure }) => {
+ const controllerRef = createRef<PreviewVideoFrameController>();
+ const { write } = installClipboardSupport();
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
+ drawImage: vi.fn(),
+ } as unknown as CanvasRenderingContext2D);
+ configure();
+ await renderVideo(() => true, videoSource, controllerRef);
+ setVideoFrameState(getVideo(), { height: 1080, readyState: HTMLMediaElement.HAVE_CURRENT_DATA, width: 1920 });
+
+ await expect(copyFrame(controllerRef)).resolves.toEqual({ ok: false, reason: 'encode-failed' });
+ expect(write).not.toHaveBeenCalled();
+ });
+
+ it('reports ClipboardItem construction and clipboard write rejection', async () => {
+ const controllerRef = createRef<PreviewVideoFrameController>();
+ const { write } = installClipboardSupport();
+ installSuccessfulCanvas();
+ await renderVideo(() => true, videoSource, controllerRef);
+ setVideoFrameState(getVideo(), { height: 1080, readyState: HTMLMediaElement.HAVE_CURRENT_DATA, width: 1920 });
+ Object.defineProperty(globalThis, 'ClipboardItem', {
+ configurable: true,
+ value: class {
+ constructor() {
+ throw new Error('ClipboardItem rejected');
+ }
+ },
+ });
+
+ await expect(copyFrame(controllerRef)).resolves.toEqual({ ok: false, reason: 'clipboard-failed' });
+
+ installClipboardSupport().write.mockRejectedValueOnce(new Error('permission denied'));
+ await expect(copyFrame(controllerRef)).resolves.toEqual({ ok: false, reason: 'clipboard-failed' });
+ expect(write).not.toHaveBeenCalled();
+ });
+
+ it('does not report success after the account epoch changes during clipboard write', async () => {
+ const controllerRef = createRef<PreviewVideoFrameController>();
+ const writeResult = deferred<void>();
+ const { write } = installClipboardSupport();
+ write.mockReturnValueOnce(writeResult.promise);
+ installSuccessfulCanvas();
+ await renderVideo(() => true, videoSource, controllerRef);
+ setVideoFrameState(getVideo(), { height: 1080, readyState: HTMLMediaElement.HAVE_CURRENT_DATA, width: 1920 });
+
+ const result = copyFrame(controllerRef);
+ await interact(() => undefined);
+ identityMocks.accountEpoch = 8;
+ await interact(() => writeResult.resolve());
+
+ await expect(result).resolves.toEqual({ ok: false, reason: 'stale' });
+ });
+
+ it('does not report success after a different GalleryItemKey becomes current', async () => {
+ let isCurrent = true;
+ const controllerRef = createRef<PreviewVideoFrameController>();
+ const writeResult = deferred<void>();
+ const { write } = installClipboardSupport();
+ write.mockReturnValueOnce(writeResult.promise);
+ installSuccessfulCanvas();
+ await renderVideo(() => isCurrent, videoSource, controllerRef);
+ setVideoFrameState(getVideo(), { height: 1080, readyState: HTMLMediaElement.HAVE_CURRENT_DATA, width: 1920 });
+
+ const result = copyFrame(controllerRef);
+ await interact(() => undefined);
+ isCurrent = false;
+ await interact(() => writeResult.resolve());
+
+ await expect(result).resolves.toEqual({ ok: false, reason: 'stale' });
+ });
});
const renderVideo = async (
isItemCurrent?: (itemKey: GalleryItemKey) => boolean,
- source: VideoSource = videoSource
+ source: VideoSource = videoSource,
+ videoControllerRef?: Ref<PreviewVideoFrameController>,
+ onCopyAvailabilityChange?: (itemKey: GalleryItemKey, isAvailable: boolean) => void
): Promise<void> => {
+ if (videoControllerRef) {
+ // The intentionally invalid data URL may emit a browser media error. Copy
+ // tests exercise the frame controller, not protected-media recovery, so
+ // keep that unrelated async branch pending and silent.
+ identityMocks.refreshProtectedMediaCookie.mockReturnValue(
+ new Promise<boolean>(() => {
+ // Intentionally pending for this render's lifetime.
+ })
+ );
+ }
+
await interact(() => {
root?.render(
<I18nextProvider i18n={i18n}>
<ChakraProvider value={system}>
- <VideoHarness isItemCurrent={isItemCurrent} source={source} />
+ <VideoHarness
+ isItemCurrent={isItemCurrent}
+ onCopyAvailabilityChange={onCopyAvailabilityChange}
+ source={source}
+ videoControllerRef={videoControllerRef}
+ />
</ChakraProvider>
</I18nextProvider>
);
@@ -340,3 +559,77 @@ const deferred = <T,>() => {
return { promise, resolve };
};
+
+const originalClipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard');
+const originalClipboardItemDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'ClipboardItem');
+
+const restoreClipboardGlobals = (): void => {
+ if (originalClipboardDescriptor) {
+ Object.defineProperty(navigator, 'clipboard', originalClipboardDescriptor);
+ } else {
+ Reflect.deleteProperty(navigator, 'clipboard');
+ }
+
+ if (originalClipboardItemDescriptor) {
+ Object.defineProperty(globalThis, 'ClipboardItem', originalClipboardItemDescriptor);
+ } else {
+ Reflect.deleteProperty(globalThis, 'ClipboardItem');
+ }
+};
+
+afterEach(restoreClipboardGlobals);
+
+const setClipboardUnsupported = (): void => {
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined });
+ Reflect.deleteProperty(globalThis, 'ClipboardItem');
+};
+
+const installClipboardSupport = () => {
+ const clipboardItems: Record<string, Blob>[] = [];
+ const write = vi.fn<(items: ClipboardItems) => Promise<void>>().mockResolvedValue(undefined);
+
+ class TestClipboardItem {
+ constructor(data: Record<string, Blob>) {
+ clipboardItems.push(data);
+ }
+ }
+
+ Object.defineProperty(globalThis, 'ClipboardItem', { configurable: true, value: TestClipboardItem });
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { write } });
+
+ return { clipboardItems, write };
+};
+
+const setVideoFrameState = (
+ video: HTMLVideoElement,
+ state: { height: number; readyState: number; width: number }
+): void => {
+ Object.defineProperties(video, {
+ readyState: { configurable: true, value: state.readyState },
+ videoHeight: { configurable: true, value: state.height },
+ videoWidth: { configurable: true, value: state.width },
+ });
+};
+
+const installSuccessfulCanvas = (): void => {
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
+ drawImage: vi.fn(),
+ } as unknown as CanvasRenderingContext2D);
+ vi.spyOn(HTMLCanvasElement.prototype, 'toBlob').mockImplementation((callback) => {
+ callback(new Blob(['frame'], { type: 'image/png' }));
+ });
+};
+
+const copyFrame = (controllerRef: {
+ current: PreviewVideoFrameController | null;
+}): Promise<PreviewVideoFrameCopyResult> => {
+ const controller = controllerRef.current;
+
+ expect(controller).not.toBeNull();
+
+ if (!controller) {
+ return Promise.reject(new Error('Expected a video frame controller.'));
+ }
+
+ return controller.copyCurrentFrame();
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx
index 38f162cad2..6b7c4df311 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx
@@ -23,7 +23,8 @@ export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {
const { t } = useTranslation();
const showProgressImagesInViewer = useActiveProjectSelector((project) => project.settings.showProgressImagesInViewer);
const hasProgressImage = useProgressImage() !== null;
- const { actionItem, actions, openItemMenu } = usePreviewHeaderContext();
+ const { actionItem, actions, copyCurrentVideoFrame, isVideoFrameCopyAvailable, openItemMenu, openVideoDetails } =
+ usePreviewHeaderContext();
const isFilmstripVisible = useActiveProjectSelector((project) =>
getPreviewFilmstripVisible(getProjectWidgetValues(project, 'preview'))
);
@@ -48,7 +49,10 @@ export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {
<PreviewActionStrip
actions={actions}
density={region === 'center' ? 'full' : 'compact'}
+ isVideoFrameCopyAvailable={isVideoFrameCopyAvailable}
item={actionItem}
+ onCopyCurrentFrame={copyCurrentVideoFrame ?? undefined}
+ onOpenDetails={openVideoDetails ?? undefined}
onOpenMenu={openItemMenu}
/>
<Box bg="border.subtle" flexShrink={0} h="4" w="1px" />
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.tsx
index 8b95b6454c..8b3dbff585 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
@@ -56,11 +56,13 @@ void i18n.use(initReactI18next).init({
common: { countOfTotal: '{{count}} of {{total}}' },
widgets: {
preview: {
+ copyCurrentFrame: 'Copy Current Frame',
framesPerSecond: '{{count}} fps',
itemCount_one: '{{count}} item',
itemCount_other: '{{count}} items',
nextItemInBoard: 'Next item in board',
previousItemInBoard: 'Previous item in board',
+ videoDetails: 'Video Details',
videoDuration: 'Duration {{duration}}',
},
},
@@ -251,28 +253,82 @@ describe('Preview mixed media footer and actions', () => {
expect(host?.querySelector('[aria-label="Next item in board"]')).not.toBeNull();
});
- it('keeps common video actions and hides image-only compare and clipboard actions', async () => {
+ it('keeps common video actions, adds Preview-only frame/details actions, and hides image-only actions', async () => {
const actions = {
downloadItem: vi.fn(() => Promise.resolve()),
setItemsStarred: vi.fn(() => Promise.resolve()),
} as unknown as ImageActions;
+ const onCopyCurrentFrame = vi.fn();
+ const onOpenDetails = vi.fn();
await render(
- <PreviewActionStrip actions={actions} density="full" item={sharedVideo} onOpenMenu={() => undefined} />
+ <PreviewActionStrip
+ actions={actions}
+ density="full"
+ isVideoFrameCopyAvailable={false}
+ item={sharedVideo}
+ onCopyCurrentFrame={onCopyCurrentFrame}
+ onOpenDetails={onOpenDetails}
+ onOpenMenu={() => undefined}
+ />
);
expect(host?.querySelector('[aria-label="Select for Compare"]')).toBeNull();
expect(host?.querySelector('[aria-label="Copy to clipboard"]')).toBeNull();
+ const copyFrame = host?.querySelector<HTMLButtonElement>('[aria-label="Copy Current Frame"]');
+ const details = host?.querySelector<HTMLButtonElement>('[aria-label="Video Details"]');
const star = host?.querySelector<HTMLButtonElement>('[aria-label="Unstar video"]');
const download = host?.querySelector<HTMLButtonElement>('[aria-label="Download video"]');
+ expect(copyFrame).not.toBeNull();
+ expect(copyFrame?.disabled).toBe(true);
+ expect(details).not.toBeNull();
expect(star).not.toBeNull();
expect(download).not.toBeNull();
+ await interact(() => details?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })));
await interact(() => star?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })));
await interact(() => download?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })));
+ expect(onOpenDetails).toHaveBeenCalledOnce();
+ expect(onCopyCurrentFrame).not.toHaveBeenCalled();
expect(actions.setItemsStarred).toHaveBeenCalledWith([{ kind: 'video', name: 'shared' }], false);
expect(actions.downloadItem).toHaveBeenCalledWith(sharedVideo);
+
+ await render(
+ <PreviewActionStrip
+ actions={actions}
+ density="full"
+ isVideoFrameCopyAvailable
+ item={sharedVideo}
+ onCopyCurrentFrame={onCopyCurrentFrame}
+ onOpenDetails={onOpenDetails}
+ onOpenMenu={() => undefined}
+ />
+ );
+ const enabledCopyFrame = host?.querySelector<HTMLButtonElement>('[aria-label="Copy Current Frame"]');
+ expect(enabledCopyFrame?.disabled).toBe(false);
+
+ await interact(() => enabledCopyFrame?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })));
+ expect(onCopyCurrentFrame).toHaveBeenCalledOnce();
+ });
+
+ it('keeps the existing image clipboard action unchanged', async () => {
+ const actions = {
+ copyImage: vi.fn(() => Promise.resolve()),
+ downloadItem: vi.fn(() => Promise.resolve()),
+ selectForCompare: vi.fn(),
+ setItemsStarred: vi.fn(() => Promise.resolve()),
+ } as unknown as ImageActions;
+
+ await render(
+ <PreviewActionStrip actions={actions} density="full" item={sharedImage} onOpenMenu={() => undefined} />
+ );
+ const copyImage = host?.querySelector<HTMLButtonElement>('[aria-label="Copy to clipboard"]');
+
+ expect(copyImage).not.toBeNull();
+ expect(host?.querySelector('[aria-label="Copy Current Frame"]')).toBeNull();
+ await interact(() => copyImage?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })));
+ expect(actions.copyImage).toHaveBeenCalledWith(expect.objectContaining({ imageName: 'shared' }));
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx
index 9a9d7895db..3173775c91 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx
@@ -1,8 +1,12 @@
-import type { GalleryImage, GalleryImageMetadata } from '@features/gallery';
+import type { GalleryImage, GalleryImageMetadata, GalleryItem, GalleryItemKey } from '@features/gallery';
-import { Box, DataList, HStack, Icon, Stack, Text } from '@chakra-ui/react';
-import { galleryImages } from '@features/gallery';
+import { Box, DataList, HStack, Icon, Stack, Tabs, Text } from '@chakra-ui/react';
+import { galleryImages, galleryVideos } from '@features/gallery';
+import { toGalleryItemKey } from '@features/gallery/contracts';
+import { useAuthSession } from '@features/identity';
import { IconButton, Tooltip } from '@platform/ui';
+import { JsonPreview } from '@platform/ui/JsonPreview';
+import { useQuery } from '@tanstack/react-query';
import {
EMPTY_IMAGE_RECALL_CAPABILITIES,
RecallActionButtons,
@@ -11,7 +15,7 @@ import {
type ImageRecallKind,
} from '@workbench/image-actions';
import { ChevronDownIcon, ChevronRightIcon, CopyIcon } from 'lucide-react';
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { parsePreviewMetadata, type PreviewMetadataEntry } from './previewMetadata';
@@ -19,9 +23,10 @@ import { parsePreviewMetadata, type PreviewMetadataEntry } from './previewMetada
/**
* The footer's collapsible "Details" section: 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. Metadata is
- * fetched only while expanded; the parent keys this component per image so
- * stale rows never survive a selection change.
+ * 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 exists only while expanded and is keyed by account + qualified item
+ * identity, so closing or changing identity aborts supported transports.
*/
const GROUP_HOVER_VISIBLE = { opacity: 1 };
@@ -30,66 +35,18 @@ export const PreviewMetadataPanel = ({
actions,
image,
isOpen,
+ item,
onToggle,
}: {
actions: ImageActions;
- image: GalleryImage;
+ image: GalleryImage | null;
isOpen: boolean;
+ item: GalleryItem;
onToggle: () => void;
}) => {
const { t } = useTranslation();
- const [loaded, setLoaded] = useState<{
- capabilities: ImageRecallCapabilities;
- imageName: string;
- metadata: GalleryImageMetadata | null;
- } | null>(null);
- // Stale-while-loading: when the selection changes, the previous image's rows
- // stay in place (slightly dimmed) until the new metadata arrives, so
- // navigating never collapses the panel or shifts the layout.
- const isCurrent = loaded?.imageName === image.imageName;
- const isLoading = isOpen && loaded === null;
-
- useEffect(() => {
- if (!isOpen || loaded?.imageName === image.imageName) {
- return;
- }
-
- let isStale = false;
-
- Promise.all([galleryImages.metadata(image.imageName), actions.getImageRecallCapabilities(image)])
- .then(([metadata, capabilities]) => {
- if (!isStale) {
- setLoaded({ capabilities, imageName: image.imageName, metadata });
- }
- })
- .catch(() => {
- if (!isStale) {
- setLoaded({ capabilities: EMPTY_IMAGE_RECALL_CAPABILITIES, imageName: image.imageName, metadata: null });
- }
- });
-
- return () => {
- isStale = true;
- };
- }, [actions, image, isOpen, loaded?.imageName]);
-
- // Source run is identity the status bar no longer shows; it reads as one
- // more metadata fact here.
- const entries = [
- ...parsePreviewMetadata(loaded?.metadata ?? null),
- { key: 'sourceRun', label: 'Source Run', value: image.sourceQueueItemId },
- ];
- const handleRecall = useCallback(
- (kind: ImageRecallKind) => void actions.recallImageData(image, kind),
- [actions, image]
- );
- // The recall row is part of the panel's fixed skeleton — never unmounted on
- // navigation, so it can't cause layout shift. While the next image's
- // capabilities load, the previous ones stay displayed (the panel dims to
- // signal staleness); clicks remain safe because `recallImageData` targets
- // the CURRENT image and re-validates against its fresh metadata. Only the
- // first-ever load shows all verbs disabled.
- const capabilities = loaded?.capabilities ?? EMPTY_IMAGE_RECALL_CAPABILITIES;
+ const accountEpoch = useAuthSession().accountEpoch;
+ const itemKey = toGalleryItemKey(item);
return (
<Stack gap="2">
@@ -108,37 +65,206 @@ export const PreviewMetadataPanel = ({
</Text>
</HStack>
{isOpen ? (
- <Stack
- gap="2"
- maxH="40cqh"
- opacity={isCurrent || loaded === null ? 1 : 0.6}
- overflowY="auto"
- pe="1"
- transitionDuration="var(--wb-motion-duration-fast)"
- transitionProperty="opacity"
- >
- {isLoading ? (
- <Text color="fg.subtle" fontSize="2xs">
- {t('widgets.preview.loadingMetadata')}
- </Text>
- ) : (
- <DataList.Root gap="1.5" orientation="horizontal" size="sm">
- {entries.map((entry) => (
- <MetadataRow key={entry.key} entry={entry} />
- ))}
- </DataList.Root>
- )}
- <RecallActionButtons
- capabilities={capabilities}
- disabledReason={t('widgets.preview.recallNotAvailable')}
- onRecall={handleRecall}
- />
- </Stack>
+ <PreviewDetailsQuery
+ key={`${accountEpoch}:${itemKey}`}
+ accountEpoch={accountEpoch}
+ actions={actions}
+ image={image}
+ item={item}
+ itemKey={itemKey}
+ />
) : null}
</Stack>
);
};
+type PreviewDetailsData =
+ | {
+ capabilities: ImageRecallCapabilities;
+ kind: 'image';
+ metadata: GalleryImageMetadata | null;
+ }
+ | {
+ graph: string | null;
+ kind: 'video';
+ metadata: Record<string, unknown> | null;
+ workflow: string | null;
+ };
+
+const PreviewDetailsQuery = ({
+ accountEpoch,
+ actions,
+ image,
+ item,
+ itemKey,
+}: {
+ accountEpoch: number;
+ actions: ImageActions;
+ image: GalleryImage | null;
+ item: GalleryItem;
+ itemKey: GalleryItemKey;
+}) => {
+ const { t } = useTranslation();
+ const detailsQuery = useQuery({
+ queryFn: async ({ signal }): Promise<PreviewDetailsData> => {
+ if (item.kind === 'image') {
+ if (!image) {
+ return { capabilities: EMPTY_IMAGE_RECALL_CAPABILITIES, kind: 'image', metadata: null };
+ }
+
+ const [metadata, capabilities] = await Promise.all([
+ galleryImages.metadata(item.name, signal),
+ actions.getImageRecallCapabilities(image, signal),
+ ]);
+
+ return { capabilities, kind: 'image', metadata };
+ }
+
+ const [metadata, workflow] = await Promise.all([
+ galleryVideos.metadata(item.name, signal),
+ galleryVideos.workflow(item.name, signal),
+ ]);
+
+ return { graph: workflow.graph, kind: 'video', metadata, workflow: workflow.workflow };
+ },
+ queryKey: ['preview', 'details', accountEpoch, itemKey],
+ retry: false,
+ });
+
+ if (item.kind === 'video') {
+ if (detailsQuery.isPending) {
+ return (
+ <Text color="fg.subtle" fontSize="2xs">
+ {t('widgets.preview.loadingMetadata')}
+ </Text>
+ );
+ }
+
+ const details = isVideoDetails(detailsQuery.data) ? detailsQuery.data : null;
+
+ return (
+ <VideoDetails
+ graph={details?.graph ?? null}
+ metadata={details?.metadata ?? null}
+ workflow={details?.workflow ?? null}
+ />
+ );
+ }
+
+ const details = isImageDetails(detailsQuery.data) ? detailsQuery.data : null;
+
+ return (
+ <ImageDetails
+ actions={actions}
+ capabilities={details?.capabilities ?? EMPTY_IMAGE_RECALL_CAPABILITIES}
+ image={image}
+ isLoading={detailsQuery.isPending}
+ metadata={details?.metadata ?? null}
+ />
+ );
+};
+
+const isVideoDetails = (
+ value: PreviewDetailsData | undefined
+): value is Extract<PreviewDetailsData, { kind: 'video' }> => value?.kind === 'video';
+
+const isImageDetails = (
+ value: PreviewDetailsData | undefined
+): value is Extract<PreviewDetailsData, { kind: 'image' }> => value?.kind === 'image';
+
+const ImageDetails = ({
+ actions,
+ capabilities,
+ image,
+ isLoading,
+ metadata,
+}: {
+ actions: ImageActions;
+ capabilities: ImageRecallCapabilities;
+ image: GalleryImage | null;
+ isLoading: boolean;
+ metadata: GalleryImageMetadata | null;
+}) => {
+ const { t } = useTranslation();
+ const entries = [
+ ...parsePreviewMetadata(metadata),
+ ...(image ? [{ key: 'sourceRun', label: 'Source Run', value: image.sourceQueueItemId }] : []),
+ ];
+ const handleRecall = useCallback(
+ (kind: ImageRecallKind) => {
+ if (image) {
+ void actions.recallImageData(image, kind);
+ }
+ },
+ [actions, image]
+ );
+
+ return (
+ <Stack gap="2" maxH="40cqh" overflowY="auto" pe="1">
+ {isLoading ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ {t('widgets.preview.loadingMetadata')}
+ </Text>
+ ) : (
+ <DataList.Root gap="1.5" orientation="horizontal" size="sm">
+ {entries.map((entry) => (
+ <MetadataRow key={entry.key} entry={entry} />
+ ))}
+ </DataList.Root>
+ )}
+ <RecallActionButtons
+ capabilities={capabilities}
+ disabledReason={t('widgets.preview.recallNotAvailable')}
+ onRecall={handleRecall}
+ />
+ </Stack>
+ );
+};
+
+const VideoDetails = ({
+ graph,
+ metadata,
+ workflow,
+}: {
+ graph: string | null;
+ metadata: Record<string, unknown> | null;
+ workflow: string | null;
+}) => {
+ const { t } = useTranslation();
+
+ return (
+ <Tabs.Root defaultValue="metadata" lazyMount size="sm" unmountOnExit variant="outline">
+ <Tabs.List>
+ <Tabs.Trigger fontSize="2xs" value="metadata">
+ {t('widgets.preview.metadata')}
+ </Tabs.Trigger>
+ <Tabs.Trigger fontSize="2xs" value="workflow">
+ {t('widgets.preview.workflow')}
+ </Tabs.Trigger>
+ <Tabs.Trigger fontSize="2xs" value="graph">
+ {t('widgets.preview.graph')}
+ </Tabs.Trigger>
+ </Tabs.List>
+ <Tabs.Content value="metadata">
+ <JsonPreview label={t('widgets.preview.metadataJsonLabel')} maxH="40cqh" value={metadata} />
+ </Tabs.Content>
+ <Tabs.Content value="workflow">
+ <RawJsonPreview label={t('widgets.preview.workflowJsonLabel')} text={workflow} />
+ </Tabs.Content>
+ <Tabs.Content value="graph">
+ <RawJsonPreview label={t('widgets.preview.graphJsonLabel')} text={graph} />
+ </Tabs.Content>
+ </Tabs.Root>
+ );
+};
+
+const RawJsonPreview = ({ label, text }: { label: string; text: string | null }) =>
+ text === null ? (
+ <JsonPreview label={label} maxH="40cqh" value={null} />
+ ) : (
+ <JsonPreview label={label} maxH="40cqh" text={text} />
+ );
+
/** A DataList item extended with a hover-revealed copy button on the value. */
const MetadataRow = ({ entry }: { entry: PreviewMetadataEntry }) => {
const { t } = useTranslation();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts
index cb00f5026d..cf4157e079 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts
@@ -3,7 +3,7 @@ import type { GalleryItem } from '@features/gallery';
import { GALLERY_MAX_ROWS } from '@features/gallery/queries';
import { describe, expect, it } from 'vitest';
-import { getMatchingProgressImage, mergePreviewBoardItems } from './PreviewWidgetView';
+import { getMatchingProgressImage, getVideoFrameCopyNotice, mergePreviewBoardItems } from './PreviewWidgetView';
describe('getMatchingProgressImage', () => {
const placeholder = {
@@ -111,3 +111,17 @@ describe('mergePreviewBoardItems', () => {
expect(merged).toContainEqual(expect.objectContaining({ kind: 'video', name: 'shared' }));
});
});
+
+describe('getVideoFrameCopyNotice', () => {
+ it.each([
+ [{ ok: true } as const, 'success', 'widgets.preview.copyCurrentFrameSuccess'],
+ [{ ok: false, reason: 'unsupported' } as const, 'error', 'widgets.preview.copyCurrentFrameUnsupported'],
+ [{ ok: false, reason: 'not-ready' } as const, 'error', 'widgets.preview.copyCurrentFrameNotReady'],
+ [{ ok: false, reason: 'draw-failed' } as const, 'error', 'widgets.preview.copyCurrentFrameDrawFailed'],
+ [{ ok: false, reason: 'encode-failed' } as const, 'error', 'widgets.preview.copyCurrentFrameEncodeFailed'],
+ [{ ok: false, reason: 'clipboard-failed' } as const, 'error', 'widgets.preview.copyCurrentFrameWriteFailed'],
+ [{ ok: false, reason: 'stale' } as const, 'error', 'widgets.preview.copyCurrentFrameStale'],
+ ])('maps %o to one localized notification', (result, kind, key) => {
+ expect(getVideoFrameCopyNotice(result, (translationKey) => translationKey)).toEqual({ kind, title: key });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index ebcbf031d9..d09435f463 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -79,7 +79,12 @@ import { resolvePreviewCompareDrop } from './previewCompareDnd';
import { usePreviewDensity, type PreviewDensity } from './previewDensity';
import { PreviewFilmstrip } from './PreviewFilmstrip';
import { PreviewFooter } from './PreviewFooter';
-import { PreviewFrame, type PreviewMediaSource } from './PreviewFrame';
+import {
+ PreviewFrame,
+ type PreviewMediaSource,
+ type PreviewVideoFrameController,
+ type PreviewVideoFrameCopyResult,
+} from './PreviewFrame';
import { previewHeaderStore } from './previewHeaderStore';
import {
getPreviewNavigationCursor,
@@ -95,6 +100,23 @@ import {
const EMPTY_PREVIEW_ITEMS: GalleryItem[] = [];
+const VIDEO_FRAME_COPY_FAILURE_KEYS = {
+ 'clipboard-failed': 'widgets.preview.copyCurrentFrameWriteFailed',
+ 'draw-failed': 'widgets.preview.copyCurrentFrameDrawFailed',
+ 'encode-failed': 'widgets.preview.copyCurrentFrameEncodeFailed',
+ 'not-ready': 'widgets.preview.copyCurrentFrameNotReady',
+ stale: 'widgets.preview.copyCurrentFrameStale',
+ unsupported: 'widgets.preview.copyCurrentFrameUnsupported',
+} as const;
+
+export const getVideoFrameCopyNotice = (
+ result: PreviewVideoFrameCopyResult,
+ translate: (key: string) => string
+): { kind: 'error' | 'success'; title: string } =>
+ result.ok
+ ? { kind: 'success', title: translate('widgets.preview.copyCurrentFrameSuccess') }
+ : { kind: 'error', title: translate(VIDEO_FRAME_COPY_FAILURE_KEYS[result.reason]) };
+
const fallbackBoards: GalleryBoard[] = [
{
archived: false,
@@ -278,6 +300,8 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
const hasNavigationContext = shouldFollowLive || hasSelectedItem;
const { t } = useTranslation();
const loupeControlsRef = useRef<PreviewLoupeControls | null>(null);
+ const videoControllerRef = useRef<PreviewVideoFrameController | null>(null);
+ const [copyAvailableItemKey, setCopyAvailableItemKey] = useState<GalleryItemKey | null>(null);
const navigationContextKey = `${shouldFollowLive}:${selectedItemKey ?? ''}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${navigationStarredFirst}:${selectedImageQuery.paginationMode}:${selectedImageQuery.page}:${selectedImageQuery.searchTerm}`;
const navigationQueryKey = `${shouldFollowLive}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${navigationStarredFirst}:${selectedImageQuery.paginationMode}:${selectedImageQuery.searchTerm}`;
@@ -608,6 +632,48 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
() => widgets.patchValues('preview', { metadataOpen: !isMetadataOpen }),
[isMetadataOpen, widgets]
);
+ const openVideoDetails = useCallback(() => widgets.patchValues('preview', { metadataOpen: true }), [widgets]);
+ const handleVideoCopyAvailabilityChange = useCallback((itemKey: GalleryItemKey, isAvailable: boolean) => {
+ setCopyAvailableItemKey((current) => (isAvailable ? itemKey : current === itemKey ? null : current));
+ }, []);
+ const isVideoFrameCopyAvailable =
+ contextMenuItem?.kind === 'video' && copyAvailableItemKey === toGalleryItemKey(contextMenuItem);
+ const copyCurrentVideoFrame = useCallback(() => {
+ const run = async (): Promise<void> => {
+ const controller = videoControllerRef.current;
+ let result: PreviewVideoFrameCopyResult;
+
+ if (
+ contextMenuItem?.kind !== 'video' ||
+ !controller ||
+ controller.itemKey !== toGalleryItemKey(contextMenuItem)
+ ) {
+ result = { ok: false, reason: 'stale' };
+ } else {
+ try {
+ result = await controller.copyCurrentFrame();
+ } catch {
+ result = { ok: false, reason: 'clipboard-failed' };
+ }
+ }
+
+ notifications.add(getVideoFrameCopyNotice(result, t));
+ };
+
+ void run();
+ }, [contextMenuItem, notifications, t]);
+ const previewVideoContextActions = useMemo(
+ () =>
+ contextMenuItem?.kind === 'video'
+ ? {
+ isCopyCurrentFrameAvailable: isVideoFrameCopyAvailable,
+ itemKey: toGalleryItemKey(contextMenuItem),
+ onCopyCurrentFrame: copyCurrentVideoFrame,
+ onOpenDetails: openVideoDetails,
+ }
+ : undefined,
+ [contextMenuItem, copyCurrentVideoFrame, isVideoFrameCopyAvailable, openVideoDetails]
+ );
const isFilmstripVisible = getPreviewFilmstripVisible(previewValues);
// Drop-to-compare: any all-image gallery-item drag dropped on the frame's drop zone
@@ -677,10 +743,23 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
actionItem: shouldFollowLive ? null : contextMenuItem,
actions: shouldFollowLive ? null : imageActions,
boardName: headerItemName === null ? null : boardName,
+ copyCurrentVideoFrame: !shouldFollowLive && contextMenuItem?.kind === 'video' ? copyCurrentVideoFrame : null,
+ isVideoFrameCopyAvailable: !shouldFollowLive && isVideoFrameCopyAvailable,
itemName: headerItemName,
openItemMenu: shouldFollowLive ? null : openItemContextMenu,
+ openVideoDetails: !shouldFollowLive && contextMenuItem?.kind === 'video' ? openVideoDetails : null,
});
- }, [boardName, contextMenuItem, headerItemName, imageActions, openItemContextMenu, shouldFollowLive]);
+ }, [
+ boardName,
+ contextMenuItem,
+ copyCurrentVideoFrame,
+ headerItemName,
+ imageActions,
+ isVideoFrameCopyAvailable,
+ openItemContextMenu,
+ openVideoDetails,
+ shouldFollowLive,
+ ]);
useEffect(() => () => previewHeaderStore.clear(), []);
@@ -824,8 +903,10 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
isLoadingBoard={isLoadingBoard}
isMetadataOpen={isMetadataOpen}
item={selectedItem}
+ videoControllerRef={videoControllerRef}
selectedIndex={navigationCursor}
onContextMenu={openItemContextMenu}
+ onCopyAvailabilityChange={handleVideoCopyAvailabilityChange}
onNext={selectNextItem}
onPrevious={selectPreviousItem}
onSelectItem={selectPreviewItem}
@@ -835,6 +916,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
<ImageContextMenu
actions={imageActions}
boards={boards}
+ previewVideoActions={previewVideoContextActions}
target={contextMenuTarget}
onClose={closeContextMenu}
/>
@@ -907,12 +989,14 @@ interface SelectedMediaPreviewProps {
isMetadataOpen: boolean;
item: GalleryItem;
loupeControlsRef?: Ref<PreviewLoupeControls>;
+ onCopyAvailabilityChange?: (itemKey: GalleryItemKey, isAvailable: boolean) => void;
selectedIndex: number;
onContextMenu: (x: number, y: number) => void;
onNext: () => void;
onPrevious: () => void;
onSelectItem: (item: GalleryItem) => void;
onToggleMetadata: () => void;
+ videoControllerRef?: Ref<PreviewVideoFrameController>;
}
const SelectedMediaPreview = ({
@@ -929,6 +1013,7 @@ const SelectedMediaPreview = ({
isMetadataOpen,
item,
loupeControlsRef,
+ onCopyAvailabilityChange,
selectedIndex,
source,
onContextMenu,
@@ -936,6 +1021,7 @@ const SelectedMediaPreview = ({
onPrevious,
onSelectItem,
onToggleMetadata,
+ videoControllerRef,
}: SelectedMediaPreviewProps & {
dragItem?: GalleryItemRef;
frameHeight: number;
@@ -954,10 +1040,12 @@ const SelectedMediaPreview = ({
isLive={false}
liveBadgeLabel={t('common.generating')}
loupeControlsRef={loupeControlsRef}
+ onVideoCopyAvailabilityChange={onCopyAvailabilityChange}
padding={density === 'full' ? '6' : '3'}
shouldAntialiasLiveImage
source={source}
variant="framed"
+ videoControllerRef={videoControllerRef}
onContextMenu={onContextMenu}
/>
{filmstripItems ? (
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
index 8c48ae4bb4..ef0ef2bebe 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
@@ -18,6 +18,8 @@ export interface PreviewHeaderContext {
/** The view's `useImageActions` instance (carries delete-neighbor handling). */
actions: ImageActions | null;
boardName: string | null;
+ copyCurrentVideoFrame: (() => void) | null;
+ isVideoFrameCopyAvailable: boolean;
itemName: string | null;
/**
* Opens the view's full image context menu anchored at viewport coordinates.
@@ -25,14 +27,18 @@ export interface PreviewHeaderContext {
* one source of truth for every image verb.
*/
openItemMenu: ((x: number, y: number) => void) | null;
+ openVideoDetails: (() => void) | null;
}
const emptyContext: PreviewHeaderContext = {
actionItem: null,
actions: null,
boardName: null,
+ copyCurrentVideoFrame: null,
+ isVideoFrameCopyAvailable: false,
itemName: null,
openItemMenu: null,
+ openVideoDetails: null,
};
const store = createExternalStore<PreviewHeaderContext>(emptyContext);