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 mixed media video viewer

joshistoast7f84519dda99
diff --git a/.superpowers/sdd/mixed-media-gallery-parity/task-8-report.md b/.superpowers/sdd/mixed-media-gallery-parity/task-8-report.md
new file mode 100644
index 0000000000..3a4f97ebad
--- /dev/null
+++ b/.superpowers/sdd/mixed-media-gallery-parity/task-8-report.md
@@ -0,0 +1,217 @@
+# Task 8 Report: Native mixed-media Preview and protected video recovery
+
+## Status
+
+Complete.
+
+Preview now consumes canonical `GalleryItem` contracts end to end. Images keep
+their existing streaming, loupe, compare, and main-frame drag behavior, while
+videos render through the only production `<video>` element in
+`PreviewFrame.tsx`. Mixed navigation, filmstrip identity, header/common
+actions, footer status, context-menu targets, and deletion context all use
+qualified `GalleryItemKey`/`GalleryItemRef` identity.
+
+Protected videos get one account-scoped cookie refresh and automatic
+`video.load()` retry. Stale account/item completions are ignored, a second
+failure shows a localized poster-backed Retry state, and manual Retry starts a
+fresh one-refresh budget without synchronization effects.
+
+## TDD evidence
+
+All frontend commands ran from `invokeai/frontend/webv2`.
+
+### Identity single-flight
+
+The first focused RED was:
+
+```sh
+pnpm test src/features/identity/session.test.ts
+```
+
+```text
+Test Files 1 failed (1)
+Tests 3 failed | 15 passed (18)
+```
+
+The failures covered same-epoch single-flight, new-epoch isolation/stale
+completion, and failure-as-`false`. After exporting
+`refreshProtectedMediaCookie()`, the focused file passed all 18 tests.
+
+### Qualified mixed navigation
+
+Converting the pure navigation tests to canonical same-name image/video items
+produced:
+
+```text
+Test Files 1 failed (1)
+Tests 13 failed | 3 passed (16)
+```
+
+After the sequence, cursor, and target model moved to `GalleryItemKey`, all 16
+tests passed.
+
+The first full Preview integration RED was:
+
+```text
+Test Files 1 failed (1)
+Tests 9 failed | 1 passed (10)
+```
+
+It covered canonical selection, same-name image/video order, native video
+rendering, video comparison suppression, and image-only neighbor prefetch.
+
+### Mixed filmstrip, footer, and actions
+
+The new mixed chrome browser file initially failed all four tests. It passed
+after:
+
+- filmstrip keys and DnD IDs became source-qualified;
+- static image/video posters selected canonical items;
+- footer status added localized duration/fps and tabular dimensions;
+- common star/download remained available for video while compare/copy stayed
+ image-only.
+
+The initial native frame contract also failed three tests across the frame and
+drag files before the source union and keyed video arm were introduced.
+
+### Protected video retry
+
+The tightened retry RED was:
+
+```sh
+pnpm test:browser src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx
+```
+
+```text
+Test Files 1 failed (1)
+Tests 6 failed | 2 passed (8)
+```
+
+Those failures required the first-error refresh/load, account and selected-item
+stale guards, poster-backed terminal state, manual fresh budget, and keyed
+per-item reset. The focused file then passed all 8 tests.
+
+The combined Task 8 browser set passed:
+
+```text
+Test Files 5 passed (5)
+Tests 37 passed (37)
+```
+
+The focused unit set passed:
+
+```text
+Test Files 3 passed (3)
+Tests 38 passed (38)
+```
+
+Final review caught that Preview still supplied both Task 7's canonical
+deletion-successor context and the legacy image callback. The regression test
+failed 1 of 11 tests, then passed all 11 after removing the competing callback.
+
+## Implementation
+
+### Mixed Preview surface
+
+- `PreviewWidgetView` derives, merges, navigates, and selects canonical mixed
+ items in backend order.
+- Qualified keys preserve same-name image/video independence through cursor,
+ page-boundary, filmstrip, header, context-menu, and action contexts.
+- Selecting a video clears comparison in the canonical reducer; Preview also
+ gates compare rendering, compare drops, swap, loupe, and zoom commands to
+ images.
+- Neighbor prefetch creates `Image` requests only for image neighbors and
+ never assigns a full video URL.
+- The common Task 7 deletion context supplies ordered mixed refs once; the
+ obsolete image-only successor callback is no longer registered.
+
+### Native video arm
+
+- `PreviewFrame` owns a local `PreviewMediaSource` union and delegates video to
+ a child keyed by `itemKey`.
+- The keyed child contains the sole production `<video>` with `controls`,
+ `playsInline`, `preload="metadata"`, `poster`, and protected full `src`.
+- The video arm registers no draggable, DnD listeners, compare drop zone,
+ loupe/pan/wheel handlers, or `touchAction: none`.
+- Video failure state retains the poster, localized failure text, and a manual
+ Retry button.
+
+### Protected-cookie recovery
+
+- `refreshProtectedMediaCookie()` is account-epoch scoped and shares one
+ in-flight transport promise per epoch.
+- A new epoch never reuses the prior promise, and transport failure/stale
+ completion resolves `false` rather than escaping into a media event.
+- `PreviewVideo` captures the account epoch, element, and selected key before
+ refresh; all three must still be current before calling `load()`.
+- Refs and keyed component lifetime implement retry synchronization without a
+ new `useEffect`.
+
+## 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 4977 passed (4977)
+```
+
+```sh
+pnpm test:browser
+```
+
+```text
+Test Files 66 passed (66)
+Tests 307 passed (307)
+```
+
+The browser suite emitted its existing React `act(...)`,
+missing-i18n-instance, and intentional error-boundary diagnostics and exited
+successfully.
+
+```sh
+pnpm test:fixtures
+```
+
+```text
+Tests 4 passed (4)
+```
+
+## Source-policy 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.
+
+`git diff --check` also passed.
+
+## Retained Task 9 seams
+
+- Video Details/metadata, workflow/graph rendering, and copy-current-frame are
+ intentionally absent.
+- `actionImage` remains `null` for video, preserving the strict image-only
+ metadata/recall boundary for Task 9.
+- `PreviewVideo` remains local to `PreviewFrame.tsx`; Task 9 can extend its
+ video-only UI without adding another media element or weakening image
+ contracts.
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 81284df9f5..4cbca7120b 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1218,15 +1218,20 @@
"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",
"hideFilmstrip": "Hide filmstrip",
"exitCompare": "Exit Compare",
"hideInProgressDiffusion": "Hide in-progress diffusion",
"imageCount_one": "{{count}} image",
"imageCount_other": "{{count}} images",
+ "itemCount_one": "{{count}} item",
+ "itemCount_other": "{{count}} items",
"loadingBoard": "Loading board",
"loadingMetadata": "Loading metadata",
+ "nextItemInBoard": "Next item in board",
"nextImageInBoard": "Next image in board",
"noGallerySelection": "No gallery selection",
+ "previousItemInBoard": "Previous item in board",
"recallNotAvailable": "Not recallable for this image",
"previousImageInBoard": "Previous image in board",
"resetZoom": "Reset zoom",
@@ -1237,6 +1242,10 @@
"hover": "Hover",
"hoverComparisonAriaLabel": "Reveal comparison image on hover, focus, or touch",
"sourceRun": "Source run {{id}}",
+ "videoDuration": "Duration {{duration}}",
+ "videoFailed": "Video could not be loaded",
+ "videoLabel": "Video {{name}}",
+ "videoRetry": "Retry",
"viewing": "Viewing"
},
"queue": {
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
index 6ba93fb6e6..a5f2b79615 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
@@ -1,5 +1,5 @@
/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-object-as-prop */
-import type { GalleryItem, GalleryItemRef, GeneratedImageContract } from '@features/gallery/contracts';
+import type { GalleryItem, GalleryItemRef } from '@features/gallery/contracts';
import type { StreamingImageSource } from '@platform/ui/streaming-image/streamingImageSource';
import { ChakraProvider } from '@chakra-ui/react';
@@ -139,15 +139,6 @@ const createItem = (kind: GalleryItem['kind'], name: string, overrides: Partial<
: ({ ...base, kind } as GalleryItem);
};
-const createPreviewImage = (name: string): GeneratedImageContract => ({
- height: 96,
- imageName: name,
- imageUrl: `/full/image/${name}`,
- queuedAt: '2026-07-30T00:00:00.000Z',
- sourceQueueItemId: 'queue-1',
- thumbnailUrl: `/thumbnail/image/${name}`,
- width: 128,
-});
const previewSource: StreamingImageSource = {
alt: 'shared',
height: 96,
@@ -351,13 +342,13 @@ const Harness = ({
isLive={false}
liveBadgeLabel="Generating"
shouldAntialiasLiveImage
- source={previewSource}
+ source={{ itemKey: 'image:shared', kind: 'image', source: previewSource }}
variant="framed"
/>
<PreviewFilmstrip
density="full"
- images={[createPreviewImage('shared'), createPreviewImage('other.png')]}
- selectedImageName="shared"
+ items={[createItem('image', 'shared'), createItem('image', 'other.png')]}
+ selectedItemKey="image:shared"
onSelect={noop}
/>
</>
diff --git a/invokeai/frontend/webv2/src/features/identity/index.ts b/invokeai/frontend/webv2/src/features/identity/index.ts
index bdd46b0b3c..11181bdf3a 100644
--- a/invokeai/frontend/webv2/src/features/identity/index.ts
+++ b/invokeai/frontend/webv2/src/features/identity/index.ts
@@ -11,6 +11,7 @@ export {
LoginAttemptSupersededError,
loginWithCredentials,
logoutSession,
+ refreshProtectedMediaCookie,
subscribeAuthSession,
useAuthSession,
type AuthSession,
diff --git a/invokeai/frontend/webv2/src/features/identity/session.test.ts b/invokeai/frontend/webv2/src/features/identity/session.test.ts
index 8d004b30b4..058a62dd03 100644
--- a/invokeai/frontend/webv2/src/features/identity/session.test.ts
+++ b/invokeai/frontend/webv2/src/features/identity/session.test.ts
@@ -462,3 +462,51 @@ describe('media cookie recovery on restore', () => {
expect(api.refreshMediaCookie).not.toHaveBeenCalled();
});
});
+
+describe('protected media cookie recovery', () => {
+ it('shares one in-flight refresh between concurrent callers in the same account epoch', async () => {
+ await resolveSignedOutMultiuserSession();
+ await session.loginWithCredentials(user.email, 'password', true);
+ const refresh = createDeferred<{ success: boolean }>();
+ api.refreshMediaCookie.mockReturnValueOnce(refresh.promise);
+
+ const first = session.refreshProtectedMediaCookie();
+ const second = session.refreshProtectedMediaCookie();
+
+ expect(api.refreshMediaCookie).toHaveBeenCalledTimes(1);
+
+ refresh.resolve({ success: true });
+
+ await expect(Promise.all([first, second])).resolves.toEqual([true, true]);
+ });
+
+ it('starts a separate refresh for a new account epoch and rejects the stale completion', async () => {
+ await resolveSignedOutMultiuserSession();
+ await session.loginWithCredentials(user.email, 'password', true);
+ const oldRefresh = createDeferred<{ success: boolean }>();
+ const newRefresh = createDeferred<{ success: boolean }>();
+ api.refreshMediaCookie.mockReturnValueOnce(oldRefresh.promise).mockReturnValueOnce(newRefresh.promise);
+
+ const staleOutcome = session.refreshProtectedMediaCookie();
+
+ api.login.mockResolvedValueOnce({ expires_in: 3600, token: 'token-b', user: userB });
+ await session.loginWithCredentials(userB.email, 'password', true);
+ const currentOutcome = session.refreshProtectedMediaCookie();
+
+ expect(api.refreshMediaCookie).toHaveBeenCalledTimes(2);
+
+ newRefresh.resolve({ success: true });
+ await expect(currentOutcome).resolves.toBe(true);
+
+ oldRefresh.resolve({ success: true });
+ await expect(staleOutcome).resolves.toBe(false);
+ });
+
+ it('returns false without throwing when the refresh request fails', async () => {
+ await resolveSignedOutMultiuserSession();
+ await session.loginWithCredentials(user.email, 'password', true);
+ api.refreshMediaCookie.mockRejectedValueOnce(new Error('network down'));
+
+ await expect(session.refreshProtectedMediaCookie()).resolves.toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/identity/session.ts b/invokeai/frontend/webv2/src/features/identity/session.ts
index c4958c87f8..b682225741 100644
--- a/invokeai/frontend/webv2/src/features/identity/session.ts
+++ b/invokeai/frontend/webv2/src/features/identity/session.ts
@@ -255,6 +255,42 @@ export const ensureAuthSession = (): Promise<AuthSession> => {
return pendingResolve;
};
+interface ProtectedMediaCookieRefresh {
+ accountEpoch: number;
+ promise: Promise<boolean>;
+}
+
+let pendingProtectedMediaCookieRefresh: ProtectedMediaCookieRefresh | null = null;
+
+/**
+ * Re-issue the cookie used by native media elements without leaking request
+ * failures or completions across authenticated account lifetimes.
+ */
+export const refreshProtectedMediaCookie = (): Promise<boolean> => {
+ const session = store.getSnapshot();
+
+ if (session.phase !== 'ready' || (session.multiuserEnabled && session.user === null)) {
+ return Promise.resolve(false);
+ }
+
+ if (pendingProtectedMediaCookieRefresh?.accountEpoch === session.accountEpoch) {
+ return pendingProtectedMediaCookieRefresh.promise;
+ }
+
+ const accountEpoch = session.accountEpoch;
+ const promise = refreshMediaCookie()
+ .then((result) => result.success && store.getSnapshot().accountEpoch === accountEpoch)
+ .catch(() => false)
+ .finally(() => {
+ if (pendingProtectedMediaCookieRefresh?.promise === promise) {
+ pendingProtectedMediaCookieRefresh = null;
+ }
+ });
+
+ pendingProtectedMediaCookieRefresh = { accountEpoch, promise };
+ return promise;
+};
+
export type ReadyAuthSession = AuthSession & { phase: 'ready' };
/**
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx
index eed028fd20..959fba1ffa 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx
@@ -1,7 +1,8 @@
-import type { GalleryImage } from '@features/gallery';
+import type { GalleryItem } from '@features/gallery';
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 { useCallback, type MouseEvent } from 'react';
@@ -18,22 +19,23 @@ import type { PreviewDensity } from './previewDensity';
export const PreviewActionStrip = ({
actions,
density,
- image,
+ item,
onOpenMenu,
}: {
actions: ImageActions;
density: PreviewDensity;
- image: GalleryImage;
+ item: GalleryItem;
/** Opens the view's image context menu at viewport coordinates. */
onOpenMenu: ((x: number, y: number) => void) | null;
}) => {
+ const image = isGalleryImageItem(item) ? galleryImageItemToGalleryImage(item) : null;
const toggleStar = useCallback(
- () => void actions.setImagesStarred([image.imageName], !image.starred),
- [actions, image.imageName, image.starred]
+ () => void actions.setItemsStarred([toGalleryItemRef(item)], !item.starred),
+ [actions, item]
);
- const selectForCompare = useCallback(() => actions.selectForCompare(image), [actions, image]);
- const copyImage = useCallback(() => void actions.copyImage(image), [actions, image]);
- const downloadImage = useCallback(() => void actions.downloadImage(image), [actions, image]);
+ const selectForCompare = useCallback(() => image && actions.selectForCompare(image), [actions, image]);
+ const copyImage = useCallback(() => image && void actions.copyImage(image), [actions, image]);
+ const downloadItem = useCallback(() => void actions.downloadItem(item), [actions, item]);
const openMenu = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
@@ -42,11 +44,12 @@ export const PreviewActionStrip = ({
},
[onOpenMenu]
);
- const starLabel = image.starred ? 'Unstar image' : 'Star image';
+ const itemKindLabel = item.kind === 'video' ? 'video' : 'image';
+ const starLabel = `${item.starred ? 'Unstar' : 'Star'} ${itemKindLabel}`;
const starButton = (
<Tooltip content={starLabel}>
<IconButton aria-label={starLabel} color="fg.muted" size="2xs" variant="ghost" onClick={toggleStar}>
- <Icon as={StarIcon} boxSize="3.5" fill={image.starred ? 'currentColor' : 'none'} />
+ <Icon as={StarIcon} boxSize="3.5" fill={item.starred ? 'currentColor' : 'none'} />
</IconButton>
</Tooltip>
);
@@ -70,9 +73,9 @@ export const PreviewActionStrip = ({
return (
<HStack flexShrink={0} gap="0.5">
{starButton}
- <StripIconButton icon={ImagesIcon} label="Select for Compare" onClick={selectForCompare} />
- <StripIconButton icon={CopyIcon} label="Copy to clipboard" onClick={copyImage} />
- <StripIconButton icon={DownloadIcon} label="Download image" onClick={downloadImage} />
+ {image ? <StripIconButton icon={ImagesIcon} label="Select for Compare" onClick={selectForCompare} /> : null}
+ {image ? <StripIconButton icon={CopyIcon} label="Copy to clipboard" onClick={copyImage} /> : null}
+ <StripIconButton icon={DownloadIcon} label={`Download ${itemKindLabel}`} onClick={downloadItem} />
{menuButton}
</HStack>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx
index 79ea129893..87b7ac5ad4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx
@@ -1,7 +1,8 @@
-import type { GeneratedImageContract } from '@features/gallery';
+import type { GalleryItem, GalleryItemKey } from '@features/gallery';
import { Box, HStack, ScrollArea } from '@chakra-ui/react';
import { useDraggable } from '@dnd-kit/core';
+import { toGalleryItemKey, toGalleryItemRef } from '@features/gallery/contracts';
import { getGalleryItemDragData, getGalleryItemDragId } from '@features/gallery/utility';
import { useCallback, useMemo } from 'react';
@@ -15,22 +16,20 @@ import type { PreviewDensity } from './previewDensity';
* with every existing drop target (canvas zones, boards, drop-to-compare).
*/
-type FilmstripImage = GeneratedImageContract & { boardId?: string };
-
export const PreviewFilmstrip = ({
density,
- images,
- selectedImageName,
+ items,
+ selectedItemKey,
onSelect,
}: {
density: PreviewDensity;
- images: FilmstripImage[];
- selectedImageName: string | null;
- onSelect: (image: GeneratedImageContract) => void;
+ items: GalleryItem[];
+ selectedItemKey: GalleryItemKey | null;
+ onSelect: (item: GalleryItem) => void;
}) => {
const thumbSize = density === 'full' ? '12' : '8';
- if (images.length < 2) {
+ if (items.length < 2) {
return null;
}
@@ -53,15 +52,19 @@ export const PreviewFilmstrip = ({
<ScrollArea.Viewport h="full" w="full">
<ScrollArea.Content asChild>
<HStack align="center" gap="1" h="full">
- {images.map((image) => (
- <FilmstripThumb
- key={image.imageName}
- image={image}
- isSelected={image.imageName === selectedImageName}
- size={thumbSize}
- onSelect={onSelect}
- />
- ))}
+ {items.map((item) => {
+ const itemKey = toGalleryItemKey(item);
+
+ return (
+ <FilmstripThumb
+ key={itemKey}
+ item={item}
+ isSelected={itemKey === selectedItemKey}
+ size={thumbSize}
+ onSelect={onSelect}
+ />
+ );
+ })}
</HStack>
</ScrollArea.Content>
</ScrollArea.Viewport>
@@ -73,22 +76,23 @@ export const PreviewFilmstrip = ({
};
const FilmstripThumb = ({
- image,
+ item,
isSelected,
size,
onSelect,
}: {
- image: FilmstripImage;
+ item: GalleryItem;
isSelected: boolean;
size: string;
- onSelect: (image: GeneratedImageContract) => void;
+ onSelect: (item: GalleryItem) => void;
}) => {
- const dragData = useMemo(() => getGalleryItemDragData([{ kind: 'image', name: image.imageName }]), [image.imageName]);
+ const itemRef = useMemo(() => toGalleryItemRef(item), [item]);
+ const dragData = useMemo(() => getGalleryItemDragData([itemRef]), [itemRef]);
const { listeners, setNodeRef } = useDraggable({
data: dragData,
- id: getGalleryItemDragId(dragData.items[0]!, 'preview-filmstrip'),
+ id: getGalleryItemDragId(itemRef, 'preview-filmstrip'),
});
- const handleClick = useCallback(() => onSelect(image), [image, onSelect]);
+ const handleClick = useCallback(() => onSelect(item), [item, onSelect]);
// Ref callbacks re-run when `isSelected` changes, keeping the selected thumb
// in view without an effect.
const scrollIntoView = useCallback(
@@ -108,7 +112,7 @@ const FilmstripThumb = ({
{...listeners}
as="button"
aria-current={isSelected || undefined}
- aria-label={image.imageName}
+ aria-label={item.kind === 'video' ? `Video ${item.name}` : item.name}
borderColor={isSelected ? 'border.emphasized' : 'border.subtle'}
borderWidth="1px"
boxSize={size}
@@ -120,12 +124,7 @@ const FilmstripThumb = ({
touchAction="none"
onClick={handleClick}
>
- <img
- alt={image.imageName}
- loading="lazy"
- src={image.thumbnailUrl || image.imageUrl}
- style={FILMSTRIP_IMG_STYLE}
- />
+ <img alt={item.name} loading="lazy" src={item.thumbnailUrl || item.fullUrl} style={FILMSTRIP_IMG_STYLE} />
{isSelected ? <Box bg="accent.solid" bottom="0" h="2px" left="0" position="absolute" right="0" /> : null}
</Box>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx
index 0d8adf0eac..a362b16f6a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx
@@ -1,12 +1,12 @@
-import type { GalleryImage, GeneratedImageContract } from '@features/gallery';
+import type { GalleryImage, GalleryItem } from '@features/gallery';
import type { ImageActions } from '@workbench/image-actions';
import { HStack, Stack, Text } from '@chakra-ui/react';
+import { formatGalleryVideoDuration } from '@features/gallery/contracts';
import { Button } from '@platform/ui';
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { PreviewLiveStatusLine } from './PreviewLiveReadout';
import { PreviewMetadataPanel } from './PreviewMetadataPanel';
/**
@@ -18,12 +18,10 @@ import { PreviewMetadataPanel } from './PreviewMetadataPanel';
export const PreviewFooter = ({
actionImage,
actions,
- boardImageCount,
- image,
- isLive,
+ boardItemCount,
isLoadingBoard,
isMetadataOpen,
- liveQueueItemId,
+ item,
onNext,
onPrevious,
onToggleMetadata,
@@ -32,24 +30,25 @@ export const PreviewFooter = ({
/** The selected image with board/star context, for the metadata/recall panel. */
actionImage: GalleryImage | null;
actions: ImageActions;
- boardImageCount: number;
- image: GeneratedImageContract;
- isLive: boolean;
+ boardItemCount: number;
isLoadingBoard: boolean;
isMetadataOpen: boolean;
- /** The live run's local queue item id, when a progress readout should replace the dimensions. */
- liveQueueItemId?: string | null;
+ item: GalleryItem;
onNext: () => void;
onPrevious: () => void;
onToggleMetadata: () => void;
selectedIndex: number;
}) => {
- const { t } = useTranslation();
+ const { i18n, t } = useTranslation();
const positionLabel = isLoadingBoard
? t('widgets.preview.loadingBoard')
: selectedIndex === -1
- ? t('widgets.preview.imageCount', { count: boardImageCount })
- : t('common.countOfTotal', { count: selectedIndex + 1, total: boardImageCount });
+ ? t('widgets.preview.itemCount', { count: boardItemCount })
+ : t('common.countOfTotal', { count: selectedIndex + 1, total: boardItemCount });
+ const fps =
+ item.kind === 'video' && item.fps !== undefined
+ ? new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 3 }).format(item.fps)
+ : null;
return (
<Stack borderWidth="1px" borderColor="border.subtle" gap="2" p="3" rounded="lg">
@@ -61,17 +60,18 @@ export const PreviewFooter = ({
<Text color="fg.subtle" flexShrink={0} fontSize="2xs">
·
</Text>
- {isLive && typeof liveQueueItemId === 'string' ? (
- <PreviewLiveStatusLine queueItemId={liveQueueItemId} />
- ) : (
- <Text color="fg.subtle" flexShrink={0} fontSize="2xs">
- {isLive ? t('common.generating') : `${image.width} × ${image.height}`}
- </Text>
- )}
+ <Text color="fg.subtle" flexShrink={0} fontSize="2xs" fontVariantNumeric="tabular-nums">
+ {item.width} × {item.height}
+ {item.kind === 'video'
+ ? ` · ${t('widgets.preview.videoDuration', {
+ duration: formatGalleryVideoDuration(item.durationSeconds),
+ })}${fps === null ? '' : ` · ${t('widgets.preview.framesPerSecond', { count: fps })}`}`
+ : ''}
+ </Text>
</HStack>
<HStack flexShrink={0} gap="1">
<Button
- aria-label={t('widgets.preview.previousImageInBoard')}
+ aria-label={t('widgets.preview.previousItemInBoard')}
disabled={selectedIndex <= 0}
size="2xs"
variant="outline"
@@ -80,8 +80,8 @@ export const PreviewFooter = ({
<ChevronLeftIcon />
</Button>
<Button
- aria-label={t('widgets.preview.nextImageInBoard')}
- disabled={selectedIndex === -1 || selectedIndex >= boardImageCount - 1}
+ aria-label={t('widgets.preview.nextItemInBoard')}
+ disabled={selectedIndex === -1 || selectedIndex >= boardItemCount - 1}
size="2xs"
variant="outline"
onClick={onNext}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
index 9e1bb6e80b..26f950a469 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
@@ -1,11 +1,22 @@
-import type { GalleryItemRef } from '@features/gallery';
+import type { GalleryItemKey, GalleryItemRef } from '@features/gallery';
/* eslint-disable react/react-compiler */
import type { StreamingImageSource } from '@platform/ui/streaming-image/streamingImageSource';
-import { Badge, Box, Flex, type SystemStyleObject } from '@chakra-ui/react';
+import { Badge, Box, Button, Flex, Text, type SystemStyleObject } from '@chakra-ui/react';
import { useDraggable } from '@dnd-kit/core';
import { getGalleryItemDragData, getGalleryItemDragId } from '@features/gallery/utility';
-import { useCallback, useId, useMemo, type CSSProperties, type MouseEvent, type ReactNode, type Ref } from 'react';
+import { getAuthSession, refreshProtectedMediaCookie } from '@features/identity';
+import {
+ useCallback,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+ type CSSProperties,
+ type MouseEvent,
+ type ReactNode,
+ type Ref,
+} from 'react';
import { useTranslation } from 'react-i18next';
import { PreviewCompareDropZone } from './PreviewCompareDropZone';
@@ -34,27 +45,19 @@ export const getFittedFrameCss = (width: number, height: number): SystemStyleObj
width: `min(100cqw, calc(100cqh * ${width / height}))`,
});
-export const PreviewFrame = ({
- children,
- dragItem,
- frameHeight,
- frameWidth,
- isLive,
- liveBadgeLabel,
- liveQueueItemId,
- loupeControlsRef,
- onContextMenu,
- padding,
- shouldAntialiasLiveImage,
- source,
- variant,
-}: {
+export type PreviewMediaSource =
+ | { itemKey: GalleryItemKey; kind: 'image'; source: StreamingImageSource }
+ | { itemKey: GalleryItemKey; kind: 'video'; label: string; poster: string; src: string };
+
+interface PreviewFrameProps {
/** Rendered instead of the fitted frame when there is no image source (inset variant only). */
children?: ReactNode;
/** Saved gallery image represented by this frame. Live progress frames are never draggable. */
dragItem?: GalleryItemRef;
frameHeight: number;
frameWidth: number;
+ /** Live selected-key read used by protected-video retry guards. */
+ isItemCurrent?: (itemKey: GalleryItemKey) => boolean;
isLive: boolean;
liveBadgeLabel: string;
/** When set, the static live badge is replaced by the live progress readout for this run. */
@@ -64,10 +67,44 @@ export const PreviewFrame = ({
onContextMenu?: (x: number, y: number) => void;
padding?: string;
shouldAntialiasLiveImage: boolean;
- source: StreamingImageSource | null;
- /** `framed` = bordered surface for a selected image; `inset` = flush surface for the empty state. */
+ source: PreviewMediaSource | null;
+ /** `framed` = bordered surface for a selected item; `inset` = flush surface for the empty state. */
variant: 'framed' | 'inset';
-}) => {
+}
+
+export const PreviewFrame = (props: PreviewFrameProps) => {
+ if (props.source?.kind === 'video') {
+ return (
+ <PreviewVideo
+ key={props.source.itemKey}
+ frameHeight={props.frameHeight}
+ frameWidth={props.frameWidth}
+ isItemCurrent={props.isItemCurrent}
+ onContextMenu={props.onContextMenu}
+ padding={props.padding}
+ source={props.source}
+ />
+ );
+ }
+
+ return <PreviewImageFrame {...props} source={props.source?.source ?? null} />;
+};
+
+const PreviewImageFrame = ({
+ children,
+ dragItem,
+ frameHeight,
+ frameWidth,
+ isLive,
+ liveBadgeLabel,
+ liveQueueItemId,
+ loupeControlsRef,
+ onContextMenu,
+ padding,
+ shouldAntialiasLiveImage,
+ source,
+ variant,
+}: Omit<PreviewFrameProps, 'isItemCurrent' | 'source'> & { source: StreamingImageSource | null }) => {
const { t } = useTranslation();
const loupe = usePreviewLoupe({
controlsRef: loupeControlsRef,
@@ -238,3 +275,180 @@ export const PreviewFrame = ({
</Flex>
);
};
+
+const PreviewVideo = ({
+ frameHeight,
+ frameWidth,
+ isItemCurrent,
+ onContextMenu,
+ padding,
+ source,
+}: {
+ frameHeight: number;
+ frameWidth: number;
+ isItemCurrent?: (itemKey: GalleryItemKey) => boolean;
+ onContextMenu?: (x: number, y: number) => void;
+ padding?: string;
+ source: Extract<PreviewMediaSource, { kind: 'video' }>;
+}) => {
+ 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 handleVideoError = useCallback(() => {
+ const video = videoRef.current;
+
+ if (!video || pendingRefreshRef.current) {
+ return;
+ }
+
+ if (automaticRefreshUsedRef.current) {
+ setHasFailed(true);
+ return;
+ }
+
+ automaticRefreshUsedRef.current = true;
+ const accountEpoch = getAuthSession().accountEpoch;
+ const refresh = refreshProtectedMediaCookie();
+ pendingRefreshRef.current = refresh;
+
+ const finishRefresh = (refreshed: boolean): void => {
+ if (pendingRefreshRef.current !== refresh) {
+ return;
+ }
+
+ pendingRefreshRef.current = null;
+
+ if (
+ videoRef.current !== video ||
+ getAuthSession().accountEpoch !== accountEpoch ||
+ (isItemCurrent && !isItemCurrent(source.itemKey))
+ ) {
+ return;
+ }
+
+ if (refreshed) {
+ video.load();
+ } else {
+ setHasFailed(true);
+ }
+ };
+
+ void refresh.then(finishRefresh, () => finishRefresh(false));
+ }, [isItemCurrent, source.itemKey]);
+ const handleRetry = useCallback(() => {
+ const video = videoRef.current;
+
+ if (!video) {
+ return;
+ }
+
+ automaticRefreshUsedRef.current = false;
+ pendingRefreshRef.current = null;
+ setHasFailed(false);
+ video.load();
+ }, []);
+ const handleContextMenu = useCallback(
+ (event: MouseEvent<HTMLDivElement>) => {
+ if (onContextMenu) {
+ event.preventDefault();
+ onContextMenu(event.clientX, event.clientY);
+ }
+ },
+ [onContextMenu]
+ );
+
+ return (
+ <Flex
+ align="center"
+ borderWidth="1px"
+ borderColor="border.subtle"
+ color="fg.grid"
+ containerType="size"
+ css={previewGridCss}
+ flex="1"
+ justify="center"
+ minH="0"
+ overflow="hidden"
+ p={padding}
+ position="relative"
+ rounded="lg"
+ w="full"
+ >
+ <Box
+ bg="black"
+ borderWidth="1px"
+ borderColor="border.emphasized"
+ boxShadow="0 24px 80px rgba(0,0,0,0.42)"
+ css={getFittedFrameCss(frameWidth, frameHeight)}
+ overflow="hidden"
+ position="relative"
+ rounded="lg"
+ onContextMenu={onContextMenu ? handleContextMenu : undefined}
+ >
+ {/* User-provided gallery videos do not include a caption-track contract. */}
+ {/* oxlint-disable-next-line jsx-a11y/media-has-caption */}
+ <video
+ ref={setVideoRef}
+ aria-label={source.label}
+ controls
+ playsInline
+ poster={source.poster}
+ preload="metadata"
+ src={source.src}
+ style={VIDEO_STYLE}
+ onError={handleVideoError}
+ />
+ {hasFailed ? (
+ <>
+ <img
+ aria-hidden="true"
+ alt=""
+ draggable={false}
+ height={frameHeight}
+ src={source.poster}
+ style={VIDEO_FAILURE_POSTER_STYLE}
+ width={frameWidth}
+ />
+ <Flex
+ align="center"
+ bg="blackAlpha.700"
+ direction="column"
+ gap="3"
+ inset="0"
+ justify="center"
+ position="absolute"
+ zIndex="1"
+ >
+ <Text color="white" fontSize="sm" fontWeight="semibold">
+ {t('widgets.preview.videoFailed')}
+ </Text>
+ <Button aria-label={t('widgets.preview.videoRetry')} size="sm" onClick={handleRetry}>
+ {t('widgets.preview.videoRetry')}
+ </Button>
+ </Flex>
+ </>
+ ) : null}
+ </Box>
+ </Flex>
+ );
+};
+
+const VIDEO_STYLE: CSSProperties = {
+ display: 'block',
+ height: '100%',
+ objectFit: 'contain',
+ width: '100%',
+};
+
+const VIDEO_FAILURE_POSTER_STYLE: CSSProperties = {
+ height: '100%',
+ inset: 0,
+ objectFit: 'contain',
+ position: 'absolute',
+ width: '100%',
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx
index 08d417b4d7..5795c66b47 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx
@@ -93,7 +93,7 @@ const renderHarness = async () => {
isLive={false}
liveBadgeLabel="Generating"
shouldAntialiasLiveImage
- source={source}
+ source={{ itemKey: 'image:preview.png', kind: 'image', source }}
variant="framed"
/>
</div>
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
new file mode 100644
index 0000000000..6f23f5e767
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx
@@ -0,0 +1,342 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type { GalleryItemKey } from '@features/gallery';
+
+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 { 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';
+
+const identityMocks = vi.hoisted(() => ({
+ accountEpoch: 7,
+ refreshProtectedMediaCookie: vi.fn<() => Promise<boolean>>(),
+}));
+
+vi.mock('@features/identity', () => ({
+ getAuthSession: () => ({ accountEpoch: identityMocks.accountEpoch }),
+ refreshProtectedMediaCookie: identityMocks.refreshProtectedMediaCookie,
+}));
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ initAsync: false,
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ widgets: {
+ preview: {
+ dropToCompare: 'Drop to compare',
+ resetZoom: 'Reset zoom',
+ videoFailed: 'Video could not be loaded',
+ videoRetry: 'Retry',
+ },
+ },
+ },
+ },
+ },
+});
+
+type VideoSource = Extract<PreviewMediaSource, { kind: 'video' }>;
+
+const videoSource: VideoSource = {
+ itemKey: 'video:clip.mp4' as const,
+ kind: 'video' as const,
+ label: 'Video clip.mp4',
+ poster: 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="9"/>',
+ src: 'data:video/mp4;base64,AAAA',
+};
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+let onDragStart = vi.fn();
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const interact = (action: () => void, delay = 0): Promise<void> =>
+ act(async () => {
+ action();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, delay);
+ });
+ });
+
+const pointer = (type: string, target: EventTarget, clientX: number, clientY: number): void => {
+ target.dispatchEvent(
+ new PointerEvent(type, { bubbles: true, button: 0, clientX, clientY, isPrimary: true, pointerId: 1 })
+ );
+};
+
+const DragMonitor = () => {
+ useDndMonitor({
+ onDragStart: (event: DragStartEvent) => onDragStart(event.active.data.current),
+ });
+ return null;
+};
+
+const VideoHarness = ({
+ isItemCurrent = () => true,
+ source = videoSource,
+}: {
+ isItemCurrent?: (itemKey: GalleryItemKey) => boolean;
+ source?: VideoSource;
+}) => {
+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
+
+ return (
+ <DndContext sensors={sensors}>
+ <DragMonitor />
+ <div style={{ display: 'flex', height: 260, width: 420 }}>
+ <PreviewFrame
+ frameHeight={1080}
+ frameWidth={1920}
+ isLive={false}
+ liveBadgeLabel="Generating"
+ shouldAntialiasLiveImage
+ source={source}
+ variant="framed"
+ isItemCurrent={isItemCurrent}
+ />
+ </div>
+ </DndContext>
+ );
+};
+
+beforeEach(() => {
+ identityMocks.accountEpoch = 7;
+ identityMocks.refreshProtectedMediaCookie.mockReset().mockResolvedValue(true);
+ onDragStart = vi.fn();
+ host = document.createElement('div');
+ host.style.cssText = 'height:320px;left:20px;position:fixed;top:20px;width:480px;';
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await interact(() => root?.unmount());
+ vi.restoreAllMocks();
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('PreviewFrame native video arm', () => {
+ it('renders the native player with the protected media contract attributes', async () => {
+ await interact(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <VideoHarness />
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+
+ const video = host?.querySelector<HTMLVideoElement>('video');
+
+ expect(video).not.toBeNull();
+ expect(host?.querySelectorAll('video')).toHaveLength(1);
+ expect(video?.controls).toBe(true);
+ expect(video?.playsInline).toBe(true);
+ expect(video?.getAttribute('preload')).toBe('metadata');
+ expect(video?.getAttribute('poster')).toBe(videoSource.poster);
+ expect(video?.getAttribute('src')).toBe(videoSource.src);
+ expect(video?.getAttribute('aria-label')).toBe(videoSource.label);
+ expect(host?.querySelector('img[alt="Video clip.mp4"]')).toBeNull();
+ });
+
+ it('does not arm a drag or cancel wheel events from the video surface and native controls', async () => {
+ await interact(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <VideoHarness />
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+
+ const video = host!.querySelector<HTMLVideoElement>('video')!;
+ const content = video.parentElement;
+
+ expect(content).not.toBeNull();
+ expect(content ? getComputedStyle(content).touchAction : '').not.toBe('none');
+
+ const wheel = new WheelEvent('wheel', { bubbles: true, cancelable: true, deltaY: 100 });
+ video.dispatchEvent(wheel);
+ expect(wheel.defaultPrevented).toBe(false);
+
+ await interact(() => pointer('pointerdown', video, 220, 230), 20);
+ await interact(() => pointer('pointermove', video.ownerDocument, 260, 230), 50);
+ await interact(() => pointer('pointerup', video.ownerDocument, 260, 230), 300);
+
+ expect(onDragStart).not.toHaveBeenCalled();
+ expect(document.body.textContent).not.toContain('Drop to compare');
+ });
+
+ it('refreshes the protected-media cookie once and reloads after the first media failure', async () => {
+ const refresh = deferred<boolean>();
+ identityMocks.refreshProtectedMediaCookie.mockReturnValueOnce(refresh.promise);
+ await renderVideo();
+ const video = getVideo();
+ const load = vi.spyOn(video, 'load').mockImplementation(() => undefined);
+
+ await interact(() => video.dispatchEvent(new Event('error')));
+
+ expect(identityMocks.refreshProtectedMediaCookie).toHaveBeenCalledTimes(1);
+ expect(load).not.toHaveBeenCalled();
+
+ await interact(() => refresh.resolve(true));
+
+ expect(load).toHaveBeenCalledTimes(1);
+ expect(host?.textContent).not.toContain('Video could not be loaded');
+ });
+
+ it('does not reload or publish failure after the account changes while refresh is pending', async () => {
+ const refresh = deferred<boolean>();
+ identityMocks.refreshProtectedMediaCookie.mockReturnValueOnce(refresh.promise);
+ await renderVideo();
+ const video = getVideo();
+ const load = vi.spyOn(video, 'load').mockImplementation(() => undefined);
+
+ await interact(() => video.dispatchEvent(new Event('error')));
+ expect(identityMocks.refreshProtectedMediaCookie).toHaveBeenCalledTimes(1);
+ identityMocks.accountEpoch = 8;
+ await interact(() => refresh.resolve(true));
+
+ expect(load).not.toHaveBeenCalled();
+ expect(host?.textContent).not.toContain('Video could not be loaded');
+ });
+
+ it('does not reload or publish failure after a different item becomes current', async () => {
+ let isCurrent = true;
+ const refresh = deferred<boolean>();
+ identityMocks.refreshProtectedMediaCookie.mockReturnValueOnce(refresh.promise);
+ await renderVideo(() => isCurrent);
+ const video = getVideo();
+ const load = vi.spyOn(video, 'load').mockImplementation(() => undefined);
+
+ await interact(() => video.dispatchEvent(new Event('error')));
+ expect(identityMocks.refreshProtectedMediaCookie).toHaveBeenCalledTimes(1);
+ isCurrent = false;
+ await interact(() => refresh.resolve(true));
+
+ expect(load).not.toHaveBeenCalled();
+ expect(host?.textContent).not.toContain('Video could not be loaded');
+ });
+
+ it('shows a poster-backed failure state when refresh fails or the automatic reload fails', async () => {
+ identityMocks.refreshProtectedMediaCookie.mockResolvedValueOnce(false);
+ await renderVideo();
+ const firstVideo = getVideo();
+ vi.spyOn(firstVideo, 'load').mockImplementation(() => undefined);
+
+ await interact(() => firstVideo.dispatchEvent(new Event('error')));
+
+ expect(host?.textContent).toContain('Video could not be loaded');
+ expect(host?.querySelector<HTMLButtonElement>('button')?.textContent).toBe('Retry');
+ expect(
+ [...(host?.querySelectorAll<HTMLImageElement>('img') ?? [])].some(
+ (image) => image.getAttribute('src') === videoSource.poster
+ )
+ ).toBe(true);
+
+ identityMocks.refreshProtectedMediaCookie.mockResolvedValueOnce(true);
+ await renderVideo(() => true, { ...videoSource, itemKey: 'video:second.mp4' });
+ const secondVideo = getVideo();
+ const load = vi.spyOn(secondVideo, 'load').mockImplementation(() => undefined);
+
+ await interact(() => secondVideo.dispatchEvent(new Event('error')));
+ expect(load).toHaveBeenCalledTimes(1);
+ await interact(() => secondVideo.dispatchEvent(new Event('error')));
+
+ expect(identityMocks.refreshProtectedMediaCookie).toHaveBeenCalledTimes(2);
+ expect(host?.textContent).toContain('Video could not be loaded');
+ });
+
+ it('gives a manual retry a fresh automatic refresh budget', async () => {
+ await renderVideo();
+ const video = getVideo();
+ const load = vi.spyOn(video, 'load').mockImplementation(() => undefined);
+
+ await interact(() => video.dispatchEvent(new Event('error')));
+ await interact(() => video.dispatchEvent(new Event('error')));
+ expect(identityMocks.refreshProtectedMediaCookie).toHaveBeenCalledTimes(1);
+
+ await interact(() => host?.querySelector<HTMLButtonElement>('button')?.click());
+ expect(load).toHaveBeenCalledTimes(2);
+ expect(host?.textContent).not.toContain('Video could not be loaded');
+
+ const secondRefresh = deferred<boolean>();
+ identityMocks.refreshProtectedMediaCookie.mockReturnValueOnce(secondRefresh.promise);
+ await interact(() => video.dispatchEvent(new Event('error')));
+ expect(identityMocks.refreshProtectedMediaCookie).toHaveBeenCalledTimes(2);
+ await interact(() => secondRefresh.resolve(true));
+
+ expect(load).toHaveBeenCalledTimes(3);
+ });
+
+ it('keys retry state to the selected video item', async () => {
+ await renderVideo();
+ const firstVideo = getVideo();
+ vi.spyOn(firstVideo, 'load').mockImplementation(() => undefined);
+
+ await interact(() => firstVideo.dispatchEvent(new Event('error')));
+ await interact(() => firstVideo.dispatchEvent(new Event('error')));
+ expect(host?.textContent).toContain('Video could not be loaded');
+
+ const nextSource = {
+ ...videoSource,
+ itemKey: 'video:next.mp4' as const,
+ label: 'Video next.mp4',
+ src: 'data:video/mp4;base64,BBBB',
+ };
+ await renderVideo(() => true, nextSource);
+ const nextVideo = getVideo();
+ vi.spyOn(nextVideo, 'load').mockImplementation(() => undefined);
+
+ expect(host?.textContent).not.toContain('Video could not be loaded');
+ await interact(() => nextVideo.dispatchEvent(new Event('error')));
+
+ expect(identityMocks.refreshProtectedMediaCookie).toHaveBeenCalledTimes(2);
+ });
+});
+
+const renderVideo = async (
+ isItemCurrent?: (itemKey: GalleryItemKey) => boolean,
+ source: VideoSource = videoSource
+): Promise<void> => {
+ await interact(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <VideoHarness isItemCurrent={isItemCurrent} source={source} />
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+};
+
+const getVideo = (): HTMLVideoElement => {
+ const video = host?.querySelector<HTMLVideoElement>('video');
+
+ if (!video) {
+ throw new Error('Expected the preview video to be mounted.');
+ }
+
+ return video;
+};
+
+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/PreviewHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx
index 4ea0db77fc..38f162cad2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx
@@ -23,7 +23,7 @@ export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {
const { t } = useTranslation();
const showProgressImagesInViewer = useActiveProjectSelector((project) => project.settings.showProgressImagesInViewer);
const hasProgressImage = useProgressImage() !== null;
- const { actionImage, actions, openImageMenu } = usePreviewHeaderContext();
+ const { actionItem, actions, openItemMenu } = usePreviewHeaderContext();
const isFilmstripVisible = useActiveProjectSelector((project) =>
getPreviewFilmstripVisible(getProjectWidgetValues(project, 'preview'))
);
@@ -43,13 +43,13 @@ export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {
return (
<HStack gap="1">
- {actionImage && actions ? (
+ {actionItem && actions ? (
<>
<PreviewActionStrip
actions={actions}
density={region === 'center' ? 'full' : 'compact'}
- image={actionImage}
- onOpenMenu={openImageMenu}
+ item={actionItem}
+ 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
new file mode 100644
index 0000000000..a7fb77b76a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx
@@ -0,0 +1,248 @@
+/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */
+import type { GalleryImageItem, GalleryVideoItem } from '@features/gallery';
+import type { ImageActions } from '@workbench/image-actions';
+
+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, type ReactNode } 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 { PreviewActionStrip } from './PreviewActionStrip';
+import { PreviewFilmstrip } from './PreviewFilmstrip';
+import { PreviewFooter } from './PreviewFooter';
+
+const sharedImage: GalleryImageItem = {
+ boardId: 'none',
+ category: 'general',
+ createdAt: '2026-07-30T12:00:00Z',
+ fullUrl: '/images/shared/full',
+ height: 720,
+ isIntermediate: false,
+ kind: 'image',
+ name: 'shared',
+ starred: false,
+ thumbnailUrl: '/images/shared/thumbnail',
+ width: 1280,
+};
+
+const sharedVideo: GalleryVideoItem = {
+ boardId: 'none',
+ category: 'general',
+ createdAt: '2026-07-30T11:00:00Z',
+ durationSeconds: 65.1,
+ fps: 23.976,
+ fullUrl: '/videos/shared/full',
+ height: 1080,
+ isIntermediate: false,
+ kind: 'video',
+ name: 'shared',
+ starred: true,
+ thumbnailUrl: '/videos/shared/thumbnail',
+ width: 1920,
+};
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ initAsync: false,
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ common: { countOfTotal: '{{count}} of {{total}}' },
+ widgets: {
+ preview: {
+ framesPerSecond: '{{count}} fps',
+ itemCount_one: '{{count}} item',
+ itemCount_other: '{{count}} items',
+ nextItemInBoard: 'Next item in board',
+ previousItemInBoard: 'Previous item in board',
+ videoDuration: 'Duration {{duration}}',
+ },
+ },
+ },
+ },
+ },
+});
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+let onFilmstripDragStart = vi.fn();
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const interact = (action: () => void, delay = 0): Promise<void> =>
+ act(async () => {
+ action();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, delay);
+ });
+ });
+
+const render = async (node: ReactNode) => {
+ await interact(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>{node}</ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+};
+
+const pointer = (type: string, target: EventTarget, clientX: number, clientY: number): void => {
+ target.dispatchEvent(
+ new PointerEvent(type, { bubbles: true, button: 0, clientX, clientY, isPrimary: true, pointerId: 1 })
+ );
+};
+
+const FilmstripDragMonitor = () => {
+ useDndMonitor({
+ onDragStart: (event: DragStartEvent) =>
+ onFilmstripDragStart({ data: event.active.data.current, id: event.active.id }),
+ });
+ return null;
+};
+
+const FilmstripDragHarness = () => {
+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
+
+ return (
+ <DndContext sensors={sensors}>
+ <FilmstripDragMonitor />
+ <PreviewFilmstrip
+ density="full"
+ items={[sharedImage, sharedVideo]}
+ selectedItemKey="image:shared"
+ onSelect={() => undefined}
+ />
+ </DndContext>
+ );
+};
+
+beforeEach(() => {
+ onFilmstripDragStart = vi.fn();
+ host = document.createElement('div');
+ host.style.cssText = 'height:320px;left:20px;position:fixed;top:20px;width:640px;';
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await interact(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('PreviewFilmstrip mixed media', () => {
+ it('keeps same-name media independent and selects the clicked video poster', async () => {
+ const onSelect = vi.fn();
+
+ await render(
+ <DndContext>
+ <PreviewFilmstrip
+ density="full"
+ items={[sharedImage, sharedVideo]}
+ selectedItemKey="video:shared"
+ onSelect={onSelect}
+ />
+ </DndContext>
+ );
+
+ const posters = host!.querySelectorAll<HTMLImageElement>('img');
+ const imageButton = posters[0]?.closest<HTMLButtonElement>('button');
+ const videoButton = posters[1]?.closest<HTMLButtonElement>('button');
+
+ expect(posters).toHaveLength(2);
+ expect(posters[0]?.getAttribute('src')).toContain('/images/shared/thumbnail');
+ expect(posters[1]?.getAttribute('src')).toContain('/videos/shared/thumbnail');
+ expect(imageButton?.getAttribute('aria-current')).toBeNull();
+ expect(videoButton?.getAttribute('aria-current')).toBe('true');
+
+ await interact(() => videoButton?.click());
+
+ expect(onSelect).toHaveBeenCalledWith(sharedVideo);
+ });
+
+ it('drags a video poster with a qualified filmstrip id and video ref payload', async () => {
+ await render(<FilmstripDragHarness />);
+
+ const videoPoster = Array.from(host!.querySelectorAll<HTMLImageElement>('img')).find((image) =>
+ image.src.includes('/videos/shared/thumbnail')
+ );
+ const videoButton = videoPoster?.closest<HTMLButtonElement>('button');
+
+ if (!videoButton) {
+ throw new Error('Expected the video poster button.');
+ }
+
+ await interact(() => pointer('pointerdown', videoButton, 120, 80), 20);
+ await interact(() => pointer('pointermove', videoButton.ownerDocument, 150, 80), 50);
+
+ expect(onFilmstripDragStart).toHaveBeenCalledWith({
+ data: { items: [{ kind: 'video', name: 'shared' }], kind: 'gallery-item' },
+ id: 'preview-filmstrip:video:shared',
+ });
+
+ await interact(() => pointer('pointerup', videoButton.ownerDocument, 150, 80), 300);
+ });
+});
+
+describe('Preview mixed media footer and actions', () => {
+ it('shows mixed position, dimensions, duration, and localized fps with tabular numerals', async () => {
+ await render(
+ <PreviewFooter
+ actionImage={null}
+ actions={{} as ImageActions}
+ boardItemCount={3}
+ isLoadingBoard={false}
+ isMetadataOpen={false}
+ item={sharedVideo}
+ selectedIndex={1}
+ onNext={() => undefined}
+ onPrevious={() => undefined}
+ onToggleMetadata={() => undefined}
+ />
+ );
+
+ expect(host?.textContent).toContain('2 of 3');
+ expect(host?.textContent).toContain('1920 × 1080');
+ expect(host?.textContent).toContain('Duration 1:06');
+ expect(host?.textContent).toContain('23.976 fps');
+
+ const status = Array.from(host!.querySelectorAll<HTMLElement>('p')).find((element) =>
+ element.textContent?.includes('1920 × 1080')
+ );
+ expect(status ? getComputedStyle(status).fontVariantNumeric : '').toContain('tabular-nums');
+ expect(host?.querySelector('[aria-label="Previous item in board"]')).not.toBeNull();
+ 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 () => {
+ const actions = {
+ downloadItem: vi.fn(() => Promise.resolve()),
+ setItemsStarred: vi.fn(() => Promise.resolve()),
+ } as unknown as ImageActions;
+
+ await render(
+ <PreviewActionStrip actions={actions} density="full" item={sharedVideo} onOpenMenu={() => undefined} />
+ );
+
+ expect(host?.querySelector('[aria-label="Select for Compare"]')).toBeNull();
+ expect(host?.querySelector('[aria-label="Copy to clipboard"]')).toBeNull();
+
+ const star = host?.querySelector<HTMLButtonElement>('[aria-label="Unstar video"]');
+ const download = host?.querySelector<HTMLButtonElement>('[aria-label="Download video"]');
+ expect(star).not.toBeNull();
+ expect(download).not.toBeNull();
+
+ await interact(() => star?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })));
+ await interact(() => download?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })));
+
+ expect(actions.setItemsStarred).toHaveBeenCalledWith([{ kind: 'video', name: 'shared' }], false);
+ expect(actions.downloadItem).toHaveBeenCalledWith(sharedVideo);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
index aeca0c0549..80f30ee859 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
@@ -1,5 +1,5 @@
/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
-import type { GalleryImage, GalleryItemsPage } from '@features/gallery';
+import type { GalleryImage, GalleryImageItem, GalleryItemsPage, GalleryVideoItem } from '@features/gallery';
import type { QueueItem } from '@features/queue/contracts';
import type { WidgetViewProps } from '@workbench/widgetContracts';
@@ -29,6 +29,37 @@ const queueItem: QueueItem = {
status: 'running',
};
+const createImageItem = (name: string, createdAt: string): GalleryImageItem => ({
+ boardId: 'none',
+ category: 'general',
+ createdAt,
+ fullUrl: `/images/${name}/full`,
+ height: 720,
+ isIntermediate: false,
+ kind: 'image',
+ name,
+ sourceQueueItemId: `queue-${name}`,
+ starred: false,
+ thumbnailUrl: `/images/${name}/thumbnail`,
+ width: 1280,
+});
+
+const createVideoItem = (name: string, createdAt: string): GalleryVideoItem => ({
+ boardId: 'none',
+ category: 'general',
+ createdAt,
+ durationSeconds: 65.1,
+ fps: 23.976,
+ fullUrl: `data:video/mp4;base64,${name}`,
+ height: 1080,
+ isIntermediate: false,
+ kind: 'video',
+ name,
+ starred: false,
+ thumbnailUrl: `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" data-name="${name}"/>`,
+ width: 1920,
+});
+
const mocks = vi.hoisted(() => {
const recentImages = [
{
@@ -54,7 +85,7 @@ const mocks = vi.hoisted(() => {
return {
commands: {
account: { updateProjectPreferences: vi.fn() },
- gallery: { selectImage: vi.fn(), setCompareImage: vi.fn() },
+ gallery: { selectImage: vi.fn(), selectItem: vi.fn(), setCompareImage: vi.fn(), setCompareItem: vi.fn() },
notifications: { reportError: vi.fn() },
widgets: { patchValues: vi.fn() },
},
@@ -77,6 +108,14 @@ const mocks = vi.hoisted(() => {
},
galleryItemPageOffsets: [] as number[],
galleryItemPages: [] as GalleryItemsPage[],
+ imageActionOptions: null as null | {
+ getItemActionContext?: () => {
+ items: Array<GalleryImageItem | GalleryVideoItem>;
+ loadOrderedRefs: (signal: AbortSignal) => Promise<Array<{ kind: 'image' | 'video'; name: string }>>;
+ selectedItemKey: string | null;
+ };
+ onImagesDeleted?: (imageNames: string[]) => void;
+ },
recentImages,
useActiveProgressTarget: vi.fn(() => null as unknown),
useProgressImage: vi.fn(() => null as unknown),
@@ -88,6 +127,7 @@ vi.mock('@workbench/WorkbenchContext', () => ({
useActiveProjectSelector: (selector: (project: typeof mocks.project) => unknown) => selector(mocks.project),
useWidgetValuesSelector: () => ({}),
useWorkbenchCommands: () => mocks.commands,
+ useWorkbenchQueries: () => ({ getSnapshot: () => ({ activeProject: mocks.project }) }),
}));
vi.mock('@features/queue/react', async (importOriginal) => ({
@@ -149,7 +189,10 @@ vi.mock('@workbench/image-actions', () => ({
getImageRecallTitle: () => '',
getSelectedGalleryImage: () => null,
getSelectedGalleryImageFromValues: () => null,
- useImageActions: () => ({}),
+ useImageActions: (options: typeof mocks.imageActionOptions) => {
+ mocks.imageActionOptions = options;
+ return {};
+ },
}));
vi.mock('@features/generation/react', () => ({
@@ -166,7 +209,27 @@ vi.mock('@features/generation/react', () => ({
import { PreviewWidgetView } from './PreviewWidgetView';
const i18n = i18next.createInstance();
-await i18n.use(initReactI18next).init({ fallbackLng: 'en', lng: 'en', resources: { en: { translation: {} } } });
+await i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ common: { countOfTotal: '{{count}} of {{total}}' },
+ widgets: {
+ preview: {
+ framesPerSecond: '{{count}} fps',
+ itemCount_one: '{{count}} item',
+ itemCount_other: '{{count}} items',
+ nextItemInBoard: 'Next item in board',
+ previousItemInBoard: 'Previous item in board',
+ videoDuration: 'Duration {{duration}}',
+ },
+ },
+ },
+ },
+ },
+});
const disposer = () => {};
const runtime = {
@@ -224,6 +287,7 @@ const pressArrow = async (key: 'ArrowLeft' | 'ArrowRight') => {
beforeEach(() => {
mocks.commands.account.updateProjectPreferences.mockClear();
mocks.commands.gallery.selectImage.mockClear();
+ mocks.commands.gallery.selectItem.mockClear();
mocks.project.queue.items = [];
mocks.project.settings.showProgressImagesInViewer = false;
delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).compareImage;
@@ -237,6 +301,7 @@ beforeEach(() => {
};
mocks.project.widgetInstances.gallery.state.values.selectedImageName = 'newest';
mocks.galleryItemPageOffsets.length = 0;
+ mocks.imageActionOptions = null;
mocks.galleryItemPages = [
{
items: mocks.recentImages.map((image) => ({
@@ -279,9 +344,9 @@ describe('preview keyboard navigation boundary', () => {
await render();
await pressArrow('ArrowRight');
- expect(mocks.commands.gallery.selectImage).toHaveBeenCalledTimes(1);
- expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(
- expect.objectContaining({ imageName: 'oldest' }),
+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledTimes(1);
+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'image', name: 'oldest' }),
undefined,
expect.any(Number),
true
@@ -351,15 +416,15 @@ describe('preview keyboard navigation boundary', () => {
await pressArrow('ArrowRight');
await vi.waitFor(() => {
- expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(
- expect.objectContaining({ imageName: 'oldest' }),
+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'image', name: 'oldest' }),
undefined,
expect.any(Number),
true
);
});
expect(mocks.galleryItemPageOffsets).toEqual([60]);
- expect(mocks.commands.gallery.selectImage).toHaveBeenCalledTimes(1);
+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledTimes(1);
});
it('anchors Preview navigation to the selected paginated Gallery page', async () => {
@@ -431,8 +496,8 @@ describe('preview keyboard navigation boundary', () => {
await render();
await pressArrow('ArrowRight');
- expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(
- expect.objectContaining({ imageName: neighbor.imageName }),
+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'image', name: neighbor.imageName }),
undefined,
1,
true
@@ -458,7 +523,7 @@ describe('preview keyboard navigation boundary', () => {
expect(mocks.commands.account.updateProjectPreferences).toHaveBeenCalledWith({
showProgressImagesInViewer: true,
});
- expect(mocks.commands.gallery.selectImage).not.toHaveBeenCalled();
+ expect(mocks.commands.gallery.selectItem).not.toHaveBeenCalled();
});
it('keeps arrow navigation working while following live', async () => {
@@ -481,9 +546,9 @@ describe('preview keyboard navigation boundary', () => {
// steps back onto the newest completed image.
await pressArrow('ArrowRight');
- expect(mocks.commands.gallery.selectImage).toHaveBeenCalledTimes(1);
- expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(
- expect.objectContaining({ imageName: 'newest' }),
+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledTimes(1);
+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'image', name: 'newest' }),
undefined,
expect.any(Number),
true
@@ -508,8 +573,8 @@ describe('preview keyboard navigation boundary', () => {
await render();
await pressArrow('ArrowRight');
- expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(
- expect.objectContaining({ boardId: 'board-live', imageName: 'live-board-image' }),
+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(
+ expect.objectContaining({ boardId: 'board-live', kind: 'image', name: 'live-board-image' }),
undefined,
expect.any(Number),
true
@@ -522,8 +587,8 @@ describe('preview keyboard navigation boundary', () => {
await render();
await pressArrow('ArrowLeft');
- expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(
- expect.objectContaining({ imageName: 'oldest' }),
+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'image', name: 'oldest' }),
undefined,
expect.any(Number),
true
@@ -541,10 +606,97 @@ describe('preview keyboard navigation boundary', () => {
await render();
await pressArrow('ArrowRight');
- expect(mocks.commands.gallery.selectImage).not.toHaveBeenCalled();
+ expect(mocks.commands.gallery.selectItem).not.toHaveBeenCalled();
expect(documentKeydown).toHaveBeenCalledTimes(1);
} finally {
document.removeEventListener('keydown', documentKeydown);
}
});
+
+ it('renders and navigates same-name image and video items independently in server order', async () => {
+ const sameNameImage = createImageItem('shared', '2026-07-30T13:00:00Z');
+ const sameNameVideo = createVideoItem('shared', '2026-07-30T12:00:00Z');
+ const oldestImage = createImageItem('oldest-mixed', '2026-07-30T11:00:00Z');
+ const galleryValues = mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>;
+
+ galleryValues.compareImage = {
+ ...mocks.recentImages[0],
+ imageName: 'comparison.png',
+ };
+ galleryValues.recentImages = [];
+ galleryValues.selectedImage = sameNameVideo;
+ galleryValues.selectedImageName = 'video:shared';
+ mocks.galleryItemPages = [{ items: [sameNameImage, sameNameVideo, oldestImage], total: 3 }];
+
+ await render();
+
+ const video = host?.querySelector<HTMLVideoElement>('video');
+ const filmstripPosters = host?.querySelectorAll<HTMLImageElement>('button img');
+
+ expect(video?.getAttribute('src')).toBe(sameNameVideo.fullUrl);
+ expect(video?.getAttribute('poster')).toBe(sameNameVideo.thumbnailUrl);
+ expect(filmstripPosters).toHaveLength(3);
+ expect(host?.textContent).toContain('2 of 3');
+ expect(host?.textContent).toContain('1920 × 1080');
+ expect(host?.textContent).toContain('Duration 1:06');
+ expect(host?.textContent).toContain('23.976 fps');
+ expect(host?.textContent).not.toContain('Drop to compare');
+
+ await pressArrow('ArrowLeft');
+
+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(sameNameImage, undefined, 0, true);
+ });
+
+ it('uses the common mixed deletion context without the legacy image successor callback', async () => {
+ const sameNameImage = createImageItem('shared', '2026-07-30T13:00:00Z');
+ const sameNameVideo = createVideoItem('shared', '2026-07-30T12:00:00Z');
+ const galleryValues = mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>;
+
+ galleryValues.recentImages = [];
+ galleryValues.selectedImage = sameNameVideo;
+ galleryValues.selectedImageName = 'video:shared';
+ mocks.galleryItemPages = [{ items: [sameNameImage, sameNameVideo], total: 2 }];
+
+ await render();
+
+ expect(mocks.imageActionOptions?.onImagesDeleted).toBeUndefined();
+ const context = mocks.imageActionOptions?.getItemActionContext?.();
+ expect(context?.selectedItemKey).toBe('video:shared');
+ expect(context?.items).toEqual([sameNameImage, sameNameVideo]);
+ await expect(context?.loadOrderedRefs(new AbortController().signal)).resolves.toEqual([
+ { kind: 'image', name: 'shared' },
+ { kind: 'video', name: 'shared' },
+ ]);
+ });
+
+ it('prefetches an image neighbor but never assigns a full video URL to Image', async () => {
+ const previousImage = createImageItem('prefetch-previous', '2026-07-30T13:00:00Z');
+ const selectedImage = createImageItem('prefetch-selected', '2026-07-30T12:00:00Z');
+ const nextVideo = createVideoItem('prefetch-next', '2026-07-30T11:00:00Z');
+ const galleryValues = mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>;
+ const preloadedSources: string[] = [];
+ const NativeImage = globalThis.Image;
+
+ class PreloadImage {
+ set src(value: string) {
+ preloadedSources.push(value);
+ }
+ }
+
+ Object.defineProperty(globalThis, 'Image', { configurable: true, value: PreloadImage, writable: true });
+
+ try {
+ galleryValues.recentImages = [];
+ galleryValues.selectedImage = selectedImage;
+ galleryValues.selectedImageName = 'image:prefetch-selected';
+ mocks.galleryItemPages = [{ items: [previousImage, selectedImage, nextVideo], total: 3 }];
+
+ await render();
+
+ expect(preloadedSources).toContain(previousImage.fullUrl);
+ expect(preloadedSources).not.toContain(nextVideo.fullUrl);
+ } finally {
+ Object.defineProperty(globalThis, 'Image', { configurable: true, value: NativeImage, writable: true });
+ }
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetChrome.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetChrome.tsx
index 986da00e68..5a80342089 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetChrome.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetChrome.tsx
@@ -12,9 +12,9 @@ import { usePreviewHeaderContext } from './previewHeaderStore';
*/
export const PreviewWidgetLabel = (_props: WidgetLabelProps) => {
const { t } = useTranslation();
- const { boardName, imageName } = usePreviewHeaderContext();
+ const { boardName, itemName } = usePreviewHeaderContext();
- if (!imageName || !boardName) {
+ if (!itemName || !boardName) {
return (
<Text fontSize="xs" fontWeight="700">
{t('widgets.labels.preview')}
@@ -31,7 +31,7 @@ export const PreviewWidgetLabel = (_props: WidgetLabelProps) => {
/
</Text>
<Text color="fg.muted" fontSize="xs" truncate>
- {imageName}
+ {itemName}
</Text>
</HStack>
);
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 7a75740812..557edb9d1e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts
@@ -1,7 +1,9 @@
+import type { GalleryItem } from '@features/gallery';
+
import { GALLERY_MAX_ROWS } from '@features/gallery/queries';
import { describe, expect, it } from 'vitest';
-import { getMatchingProgressImage, mergePreviewBoardImages } from './PreviewWidgetView';
+import { getMatchingProgressImage, mergePreviewBoardItems } from './PreviewWidgetView';
describe('getMatchingProgressImage', () => {
const placeholder = {
@@ -31,54 +33,60 @@ describe('getMatchingProgressImage', () => {
});
});
-describe('mergePreviewBoardImages', () => {
- const image = (imageName: string, queuedAt: string, starred = false) => ({
- height: 64,
- imageName,
- imageUrl: `/images/${imageName}`,
- queuedAt,
- sourceQueueItemId: 'queue-1',
- starred,
- thumbnailUrl: `/images/${imageName}/thumbnail`,
- width: 64,
- });
+describe('mergePreviewBoardItems', () => {
+ const item = (kind: GalleryItem['kind'], name: string, createdAt: string, starred = false): GalleryItem => {
+ const base = {
+ boardId: 'none',
+ category: 'general' as const,
+ createdAt,
+ fullUrl: `/${kind}/${name}`,
+ height: 64,
+ isIntermediate: false,
+ name,
+ starred,
+ thumbnailUrl: `/${kind}/${name}/thumbnail`,
+ width: 64,
+ };
- it('deduplicates and chronologically merges optimistic images in either direction', () => {
- const oldest = image('oldest', '2026-07-21T00:00:01.000Z');
- const middle = image('middle', '2026-07-21T00:00:02.000Z');
- const newest = image('newest', '2026-07-21T00:00:03.000Z');
+ return kind === 'video' ? { ...base, durationSeconds: 1, kind } : { ...base, kind };
+ };
- expect(mergePreviewBoardImages([newest, oldest], [middle, newest], 'DESC', false)).toEqual([
- newest,
- middle,
- oldest,
- ]);
- expect(mergePreviewBoardImages([oldest, newest], [middle, oldest], 'ASC', false)).toEqual([oldest, middle, newest]);
+ it('deduplicates and chronologically merges optimistic items in either direction', () => {
+ const oldest = item('image', 'oldest', '2026-07-21T00:00:01.000Z');
+ const middle = item('image', 'middle', '2026-07-21T00:00:02.000Z');
+ const newest = item('image', 'newest', '2026-07-21T00:00:03.000Z');
+
+ expect(mergePreviewBoardItems([newest, oldest], [middle, newest], 'DESC', false)).toEqual([newest, middle, oldest]);
+ expect(mergePreviewBoardItems([oldest, newest], [middle, oldest], 'ASC', false)).toEqual([oldest, middle, newest]);
});
- it('keeps starred backend images ahead of optimistic unstarred images', () => {
- const starred = image('starred', '2026-07-21T00:00:01.000Z', true);
- const optimistic = image('optimistic', '2026-07-21T00:00:03.000Z');
- const existing = image('existing', '2026-07-21T00:00:02.000Z');
+ it('keeps starred backend items ahead of optimistic unstarred items', () => {
+ const starred = item('video', 'starred', '2026-07-21T00:00:01.000Z', true);
+ const optimistic = item('image', 'optimistic', '2026-07-21T00:00:03.000Z');
+ const existing = item('video', 'existing', '2026-07-21T00:00:02.000Z');
- expect(mergePreviewBoardImages([starred, existing], [optimistic], 'DESC', true)).toEqual([
+ expect(mergePreviewBoardItems([starred, existing], [optimistic], 'DESC', true)).toEqual([
starred,
optimistic,
existing,
]);
});
- it('never renders more than the bounded Gallery window after merging optimistic images', () => {
+ it('keeps same-name media independent and bounds the merged Gallery window', () => {
const backend = Array.from({ length: GALLERY_MAX_ROWS }, (_, index) =>
- image(`backend-${index}`, new Date(index * 1_000).toISOString())
+ item('image', `backend-${index}`, new Date(index * 1_000).toISOString())
);
const optimistic = Array.from({ length: 60 }, (_, index) =>
- image(`optimistic-${index}`, new Date((GALLERY_MAX_ROWS + index) * 1_000).toISOString())
+ item('video', `optimistic-${index}`, new Date((GALLERY_MAX_ROWS + index) * 1_000).toISOString())
);
+ backend[GALLERY_MAX_ROWS - 1] = item('image', 'shared', new Date((GALLERY_MAX_ROWS - 1) * 1_000).toISOString());
+ optimistic[0] = item('video', 'shared', new Date((GALLERY_MAX_ROWS + 1) * 1_000).toISOString());
- const merged = mergePreviewBoardImages(backend, optimistic, 'DESC', false);
+ const merged = mergePreviewBoardItems(backend, optimistic, 'DESC', false);
expect(merged).toHaveLength(GALLERY_MAX_ROWS);
- expect(merged[0]?.imageName).toBe('optimistic-59');
+ expect(merged[0]?.name).toBe('optimistic-59');
+ expect(merged).toContainEqual(expect.objectContaining({ kind: 'image', name: 'shared' }));
+ expect(merged).toContainEqual(expect.objectContaining({ kind: 'video', name: 'shared' }));
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index 13a017858a..cad72386f7 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -7,8 +7,11 @@ import {
galleryImages,
type GalleryBoard,
type GalleryImage,
+ type GalleryImageItem,
+ type GalleryItem,
+ type GalleryItemKey,
+ type GalleryItemRef,
type GalleryView,
- type GeneratedImageContract,
} from '@features/gallery';
import {
getGalleryCompareImage,
@@ -16,13 +19,14 @@ import {
getGalleryLiveSlots,
getGallerySelectedImageQuery,
getGallerySettings,
- getSelectedGalleryImageFromValues,
getSelectedGalleryItemFromValues,
getBoundedRecentImages,
galleryImageItemToGalleryImage,
isGalleryImageItem,
+ legacyGeneratedImageToGalleryItem,
normalizeGalleryImage,
- parseGalleryItemKey,
+ toGalleryItemKey,
+ toGalleryItemRef,
type GalleryItemsPage,
type GalleryQueuePlaceholder,
} from '@features/gallery/contracts';
@@ -62,6 +66,7 @@ import {
useActiveProjectSelector,
useWidgetValuesSelector,
useWorkbenchCommands,
+ useWorkbenchQueries,
} from '@workbench/WorkbenchContext';
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState, type KeyboardEvent, type Ref } from 'react';
import { useTranslation } from 'react-i18next';
@@ -73,7 +78,7 @@ import { resolvePreviewCompareDrop } from './previewCompareDnd';
import { usePreviewDensity, type PreviewDensity } from './previewDensity';
import { PreviewFilmstrip } from './PreviewFilmstrip';
import { PreviewFooter } from './PreviewFooter';
-import { PreviewFrame } from './PreviewFrame';
+import { PreviewFrame, type PreviewMediaSource } from './PreviewFrame';
import { previewHeaderStore } from './previewHeaderStore';
import {
getPreviewNavigationCursor,
@@ -87,8 +92,7 @@ import {
type PreviewComparisonMode,
} from './previewSettings';
-type PreviewImage = GeneratedImageContract & Partial<Pick<GalleryImage, 'boardId' | 'imageCategory' | 'starred'>>;
-const EMPTY_PREVIEW_IMAGES: PreviewImage[] = [];
+const EMPTY_PREVIEW_ITEMS: GalleryItem[] = [];
const fallbackBoards: GalleryBoard[] = [
{
@@ -102,55 +106,42 @@ const fallbackBoards: GalleryBoard[] = [
},
];
-const getGalleryImages = (values: Record<string, unknown>, queueItems: QueueItem[]): PreviewImage[] => {
+const getLocalGalleryItems = (values: Record<string, unknown>, queueItems: QueueItem[]): GalleryImageItem[] => {
const queueBoardIds = new Map(queueItems.map((item) => [item.id, item.snapshot.galleryBoardId ?? 'none'] as const));
return getBoundedRecentImages(values.recentImages).map((image) =>
- normalizeGalleryImage(image, queueBoardIds.get(image.sourceQueueItemId))
+ legacyGeneratedImageToGalleryItem(normalizeGalleryImage(image, queueBoardIds.get(image.sourceQueueItemId)))
);
};
-const getSelectedImage = (values: Record<string, unknown>, localImages: PreviewImage[]): PreviewImage | null => {
+const getSelectedItem = (values: Record<string, unknown>, localItems: GalleryImageItem[]): GalleryItem | null => {
const selectedItem = getSelectedGalleryItemFromValues(values);
- if (selectedItem?.kind === 'video') {
- return null;
- }
-
- const selectedImage = getSelectedGalleryImageFromValues(values);
-
- if (selectedImage) {
- return localImages.find((candidate) => candidate.imageName === selectedImage.imageName) ?? selectedImage;
- }
-
- if (typeof values.selectedImageName === 'string' && parseGalleryItemKey(values.selectedImageName).kind === 'video') {
- return null;
+ if (selectedItem) {
+ const selectedItemKey = toGalleryItemKey(selectedItem);
+ return localItems.find((candidate) => toGalleryItemKey(candidate) === selectedItemKey) ?? selectedItem;
}
- return localImages[0] ?? null;
+ return localItems[0] ?? null;
};
-/**
- * TODO(Task 8): Remove when Preview navigates `GalleryItem` directly.
- * The compatibility projection narrows before creating image contracts.
- */
-const flattenPreviewImages = (data: InfiniteData<GalleryItemsPage, number> | undefined): GalleryImage[] =>
- flattenGalleryItemsData(data).filter(isGalleryImageItem).map(galleryImageItemToGalleryImage);
+const flattenPreviewItems = (data: InfiniteData<GalleryItemsPage, number> | undefined): GalleryItem[] =>
+ flattenGalleryItemsData(data);
-const getOrderedPreviewImages = (
- images: PreviewImage[],
+const getOrderedPreviewItems = (
+ items: GalleryItem[],
imageOrderDir: 'ASC' | 'DESC',
starredFirst: boolean,
inputOrder: 'display' | 'newest-first'
-): PreviewImage[] =>
- images
- .map((image, index) => ({ image, index }))
+): GalleryItem[] =>
+ items
+ .map((item, index) => ({ index, item }))
.sort((a, b) => {
- if (starredFirst && Boolean(a.image.starred) !== Boolean(b.image.starred)) {
- return a.image.starred ? -1 : 1;
+ if (starredFirst && a.item.starred !== b.item.starred) {
+ return a.item.starred ? -1 : 1;
}
- const chronological = a.image.queuedAt.localeCompare(b.image.queuedAt);
+ const chronological = a.item.createdAt.localeCompare(b.item.createdAt);
if (chronological !== 0) {
return imageOrderDir === 'DESC' ? -chronological : chronological;
@@ -158,47 +149,45 @@ const getOrderedPreviewImages = (
return inputOrder === 'newest-first' && imageOrderDir === 'ASC' ? b.index - a.index : a.index - b.index;
})
- .map(({ image }) => image);
+ .map(({ item }) => item);
-const getOrderedLocalImages = ({
+const getOrderedLocalItems = ({
boardId,
galleryView,
- images,
+ items,
imageOrderDir,
starredFirst,
}: {
boardId: string;
galleryView: GalleryView;
- images: PreviewImage[];
+ items: GalleryItem[];
imageOrderDir: 'ASC' | 'DESC';
starredFirst: boolean;
-}): PreviewImage[] =>
- getOrderedPreviewImages(
- images.filter((image) => getImageBoardId(image) === boardId && getImageGalleryView(image) === galleryView),
+}): GalleryItem[] =>
+ getOrderedPreviewItems(
+ items.filter((item) => item.boardId === boardId && getItemGalleryView(item) === galleryView),
imageOrderDir,
starredFirst,
'newest-first'
);
-export const mergePreviewBoardImages = (
- backendImages: PreviewImage[],
- localImages: PreviewImage[],
+export const mergePreviewBoardItems = (
+ backendItems: GalleryItem[],
+ localItems: GalleryItem[],
imageOrderDir: 'ASC' | 'DESC',
starredFirst: boolean
-): PreviewImage[] => {
- const backendNames = new Set(backendImages.map((image) => image.imageName));
- const missingLocalImages = localImages.filter((image) => !backendNames.has(image.imageName));
+): GalleryItem[] => {
+ const backendKeys = new Set(backendItems.map(toGalleryItemKey));
+ const missingLocalItems = localItems.filter((item) => !backendKeys.has(toGalleryItemKey(item)));
- if (missingLocalImages.length === 0) {
- return backendImages.slice(0, GALLERY_MAX_ROWS);
+ if (missingLocalItems.length === 0) {
+ return backendItems.slice(0, GALLERY_MAX_ROWS);
}
- return getOrderedPreviewImages(
- [...backendImages, ...missingLocalImages],
- imageOrderDir,
- starredFirst,
- 'display'
- ).slice(0, GALLERY_MAX_ROWS);
+ return getOrderedPreviewItems([...backendItems, ...missingLocalItems], imageOrderDir, starredFirst, 'display').slice(
+ 0,
+ GALLERY_MAX_ROWS
+ );
};
/**
@@ -207,24 +196,12 @@ export const mergePreviewBoardImages = (
* the board list sort must not reshuffle the preview. Freshly generated local
* images (no boardId yet) fall back to the gallery selection for display only.
*/
-const getImageBoardId = (image: PreviewImage): string => (typeof image.boardId === 'string' ? image.boardId : 'none');
-
/**
- * Which gallery tab an image belongs to. Mirrors the category split the
+ * Which gallery tab an item belongs to. Mirrors the category split the
* gallery filters on: `general` is a gallery image, everything else (canvas
- * pixels, control layers, uploads) is an asset. A freshly generated local
- * image carries no category yet and is a gallery image by default.
+ * pixels, control layers, uploads) is an asset.
*/
-const getImageGalleryView = (image: PreviewImage): GalleryView =>
- (image.imageCategory ?? 'general') === 'general' ? 'images' : 'assets';
-
-const getDisplayBoardId = (image: PreviewImage, values: Record<string, unknown>): string => {
- if (typeof image.boardId === 'string') {
- return image.boardId;
- }
-
- return typeof values.selectedBoardId === 'string' ? values.selectedBoardId : 'none';
-};
+const getItemGalleryView = (item: GalleryItem): GalleryView => (item.category === 'general' ? 'images' : 'assets');
const getBoardName = (
boards: GalleryBoard[],
@@ -264,23 +241,26 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
const activeProgressTarget = useActiveProgressTarget();
const activeProgressTargets = useActiveProgressTargets();
const { account, gallery, notifications, widgets } = useWorkbenchCommands();
+ const queries = useWorkbenchQueries();
const { density, rootRef } = usePreviewDensity(region);
const recentImages = galleryValues.recentImages;
- const localImages = useMemo(() => getGalleryImages({ recentImages }, queueItems), [queueItems, recentImages]);
- const selectedImage = useMemo(() => getSelectedImage(galleryValues, localImages), [galleryValues, localImages]);
+ const localItems = useMemo(() => getLocalGalleryItems({ recentImages }, queueItems), [queueItems, recentImages]);
+ const selectedItem = useMemo(() => getSelectedItem(galleryValues, localItems), [galleryValues, localItems]);
const compareImage = getGalleryCompareImage(galleryValues);
const comparisonMode = getPreviewComparisonMode(previewValues);
- const displayBoardId = selectedImage ? getDisplayBoardId(selectedImage, galleryValues) : 'none';
- const hasSelectedImage = selectedImage !== null;
+ const displayBoardId = selectedItem?.boardId ?? 'none';
+ const hasSelectedItem = selectedItem !== null;
const { imageOrderDir, starredFirst } = getGallerySettings(galleryValues);
const selectedImageQuery = getGallerySelectedImageQuery(galleryValues);
const selectedImageSearch = useMemo(
() => parseDateTokens(selectedImageQuery.searchTerm),
[selectedImageQuery.searchTerm]
);
- const selectedImageName = selectedImage?.imageName ?? null;
+ const selectedItemKey = selectedItem ? toGalleryItemKey(selectedItem) : null;
const isComparing =
- selectedImage !== null && compareImage !== null && compareImage.imageName !== selectedImage.imageName;
+ selectedItem?.kind === 'image' &&
+ compareImage !== null &&
+ toGalleryItemKey({ kind: 'image', name: compareImage.imageName }) !== selectedItemKey;
const generationSequence = useMemo(
() => getGalleryGenerationSequence(queueItems, activeProgressTarget),
[activeProgressTarget, queueItems]
@@ -298,10 +278,10 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
const navigationGalleryView = shouldFollowLive ? 'images' : selectedImageQuery.galleryView;
const navigationOrderDir = shouldFollowLive ? imageOrderDir : selectedImageQuery.imageOrderDir;
const navigationStarredFirst = shouldFollowLive ? starredFirst : selectedImageQuery.starredFirst;
- const hasNavigationContext = shouldFollowLive || hasSelectedImage;
+ const hasNavigationContext = shouldFollowLive || hasSelectedItem;
const { t } = useTranslation();
const loupeControlsRef = useRef<PreviewLoupeControls | null>(null);
- const navigationContextKey = `${shouldFollowLive}:${selectedImageName ?? ''}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${navigationStarredFirst}:${selectedImageQuery.paginationMode}:${selectedImageQuery.page}:${selectedImageQuery.searchTerm}`;
+ 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}`;
// Lets a boundary fetch that resolves after the user has moved on compare the
@@ -332,17 +312,17 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
const boardsQuery = useQuery({
...galleryBoardsOptions(),
- enabled: hasSelectedImage,
+ enabled: hasSelectedItem,
});
const {
- data: boardImagesData,
- fetchNextPage: fetchNextBoardImagesPage,
- fetchPreviousPage: fetchPreviousBoardImagesPage,
- hasNextPage: hasNextBoardImagesPage,
- hasPreviousPage: hasPreviousBoardImagesPage,
- isFetching: isFetchingBoardImages,
- isFetchingNextPage: isFetchingNextBoardImagesPage,
- isFetchingPreviousPage: isFetchingPreviousBoardImagesPage,
+ data: boardItemsData,
+ fetchNextPage: fetchNextBoardItemsPage,
+ fetchPreviousPage: fetchPreviousBoardItemsPage,
+ hasNextPage: hasNextBoardItemsPage,
+ hasPreviousPage: hasPreviousBoardItemsPage,
+ isFetching: isFetchingBoardItems,
+ isFetchingNextPage: isFetchingNextBoardItemsPage,
+ isFetchingPreviousPage: isFetchingPreviousBoardItemsPage,
} = useInfiniteQuery({
...galleryItemsInfiniteOptions(
{
@@ -360,18 +340,19 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
),
enabled: hasNavigationContext,
});
- const selectPreviewImage = useCallback(
- (image: GeneratedImageContract) => {
- const pageIndex = boardImagesData?.pages.findIndex((page) =>
- page.items.some((candidate) => isGalleryImageItem(candidate) && candidate.name === image.imageName)
+ const selectPreviewItem = useCallback(
+ (item: GalleryItem) => {
+ const itemKey = toGalleryItemKey(item);
+ const pageIndex = boardItemsData?.pages.findIndex((page) =>
+ page.items.some((candidate) => toGalleryItemKey(candidate) === itemKey)
);
- const pageParam = pageIndex === undefined || pageIndex < 0 ? undefined : boardImagesData?.pageParams[pageIndex];
+ const pageParam = pageIndex === undefined || pageIndex < 0 ? undefined : boardItemsData?.pageParams[pageIndex];
const selectionPage =
typeof pageParam === 'number' ? Math.floor(pageParam / GALLERY_PAGE_SIZE) : selectedImageQuery.page;
- gallery.selectImage(image, undefined, selectionPage, true);
+ gallery.selectItem(item, undefined, selectionPage, true);
},
- [boardImagesData, gallery, selectedImageQuery.page]
+ [boardItemsData, gallery, selectedImageQuery.page]
);
const boards = boardsQuery.data ?? fallbackBoards;
const optimisticQueueItemIds = useMemo(
@@ -381,51 +362,49 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
),
[queueItems]
);
- const navigationLocalImages = useMemo(() => {
+ const navigationLocalItems = useMemo(() => {
const refreshingSelectedSourceId =
- !shouldFollowLive && isFetchingBoardImages ? selectedImage?.sourceQueueItemId : null;
-
- return localImages.filter(
- (image) =>
- optimisticQueueItemIds.has(image.sourceQueueItemId) || image.sourceQueueItemId === refreshingSelectedSourceId
+ !shouldFollowLive && isFetchingBoardItems && selectedItem?.kind === 'image'
+ ? selectedItem.sourceQueueItemId
+ : null;
+
+ return localItems.filter(
+ (item) =>
+ (item.sourceQueueItemId !== undefined && optimisticQueueItemIds.has(item.sourceQueueItemId)) ||
+ item.sourceQueueItemId === refreshingSelectedSourceId
);
- }, [isFetchingBoardImages, localImages, optimisticQueueItemIds, selectedImage?.sourceQueueItemId, shouldFollowLive]);
- const localBoardImages = useMemo(
+ }, [isFetchingBoardItems, localItems, optimisticQueueItemIds, selectedItem, shouldFollowLive]);
+ const localBoardItems = useMemo(
() =>
- getOrderedLocalImages({
+ getOrderedLocalItems({
boardId: navigationBoardId,
galleryView: navigationGalleryView,
- images: navigationLocalImages,
+ items: navigationLocalItems,
imageOrderDir: navigationOrderDir,
starredFirst: navigationStarredFirst,
}),
- [navigationBoardId, navigationGalleryView, navigationLocalImages, navigationOrderDir, navigationStarredFirst]
+ [navigationBoardId, navigationGalleryView, navigationLocalItems, navigationOrderDir, navigationStarredFirst]
);
- const previewLocalBoardImages = useMemo(() => {
+ const previewLocalBoardItems = useMemo(() => {
if (
shouldFollowLive ||
- !selectedImage ||
- localBoardImages.some((image) => image.imageName === selectedImage.imageName)
+ !selectedItem ||
+ localBoardItems.some((item) => toGalleryItemKey(item) === selectedItemKey)
) {
- return localBoardImages;
+ return localBoardItems;
}
- return [selectedImage, ...localBoardImages];
- }, [localBoardImages, selectedImage, shouldFollowLive]);
- const backendBoardImages = useMemo(() => flattenPreviewImages(boardImagesData), [boardImagesData]);
- const boardImages = useMemo(
+ return [selectedItem, ...localBoardItems];
+ }, [localBoardItems, selectedItem, selectedItemKey, shouldFollowLive]);
+ const backendBoardItems = useMemo(() => flattenPreviewItems(boardItemsData), [boardItemsData]);
+ const boardItems = useMemo(
() =>
!hasNavigationContext
- ? EMPTY_PREVIEW_IMAGES
- : mergePreviewBoardImages(
- backendBoardImages,
- previewLocalBoardImages,
- navigationOrderDir,
- navigationStarredFirst
- ),
- [backendBoardImages, hasNavigationContext, navigationOrderDir, navigationStarredFirst, previewLocalBoardImages]
+ ? EMPTY_PREVIEW_ITEMS
+ : mergePreviewBoardItems(backendBoardItems, previewLocalBoardItems, navigationOrderDir, navigationStarredFirst),
+ [backendBoardItems, hasNavigationContext, navigationOrderDir, navigationStarredFirst, previewLocalBoardItems]
);
- const isLoadingBoard = hasNavigationContext && isFetchingBoardImages;
+ const isLoadingBoard = hasNavigationContext && isFetchingBoardItems;
const boardName = getBoardName(
boards,
displayBoardId,
@@ -437,14 +416,14 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
getPreviewNavigationSequence({
activePlaceholder: activeGalleryPlaceholder,
boardId: navigationBoardId,
- boardImages,
+ boardImages: boardItems,
galleryView: navigationGalleryView,
imageOrderDir: navigationOrderDir,
starredFirst: navigationStarredFirst,
}),
[
activeGalleryPlaceholder,
- boardImages,
+ boardItems,
navigationBoardId,
navigationGalleryView,
navigationOrderDir,
@@ -453,7 +432,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
);
const navigationCursor = getPreviewNavigationCursor(navigationSequence, {
isFollowingLive: shouldFollowLive,
- selectedImageName,
+ selectedItemKey,
});
// One navigation action shared by the arrow keys and the footer buttons.
@@ -466,58 +445,62 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
const target = getPreviewNavigationTarget(navigationSequence, navigationCursor, offset);
const isAtLoadedBackendBoundary =
- selectedImageName !== null &&
+ selectedItemKey !== null &&
(offset === 1
- ? backendBoardImages.at(-1)?.imageName === selectedImageName && hasNextBoardImagesPage
- : backendBoardImages[0]?.imageName === selectedImageName && hasPreviousBoardImagesPage);
+ ? backendBoardItems.at(-1) !== undefined &&
+ toGalleryItemKey(backendBoardItems.at(-1)!) === selectedItemKey &&
+ hasNextBoardItemsPage
+ : backendBoardItems[0] !== undefined &&
+ toGalleryItemKey(backendBoardItems[0]) === selectedItemKey &&
+ hasPreviousBoardItemsPage);
if (!isAtLoadedBackendBoundary) {
if (!target) {
return;
}
- if (target.kind === 'image') {
- selectPreviewImage(target.image);
+ if (target.kind === 'item') {
+ selectPreviewItem(target.item);
} else {
account.updateProjectPreferences({ showProgressImagesInViewer: true });
}
return;
}
- if (offset === 1 ? isFetchingNextBoardImagesPage : isFetchingPreviousBoardImagesPage) {
+ if (offset === 1 ? isFetchingNextBoardItemsPage : isFetchingPreviousBoardItemsPage) {
return;
}
- const fetchBoundaryPage = offset === 1 ? fetchNextBoardImagesPage : fetchPreviousBoardImagesPage;
+ const fetchBoundaryPage = offset === 1 ? fetchNextBoardItemsPage : fetchPreviousBoardItemsPage;
void fetchBoundaryPage().then((result) => {
if (result.isError || navigationContextKeyRef.current !== navigationContextKey) {
return;
}
- const nextBackendBoardImages = flattenPreviewImages(result.data);
- const nextBoardImages = mergePreviewBoardImages(
- nextBackendBoardImages,
- previewLocalBoardImages,
+ const nextBackendBoardItems = flattenPreviewItems(result.data);
+ const nextBoardItems = mergePreviewBoardItems(
+ nextBackendBoardItems,
+ previewLocalBoardItems,
navigationOrderDir,
navigationStarredFirst
);
const nextNavigationSequence = getPreviewNavigationSequence({
activePlaceholder: activeGalleryPlaceholder,
boardId: navigationBoardId,
- boardImages: nextBoardImages,
+ boardImages: nextBoardItems,
galleryView: navigationGalleryView,
imageOrderDir: navigationOrderDir,
starredFirst: navigationStarredFirst,
});
const nextNavigationCursor = getPreviewNavigationCursor(nextNavigationSequence, {
isFollowingLive: shouldFollowLive,
- selectedImageName,
+ selectedItemKey,
});
const nextTarget = getPreviewNavigationTarget(nextNavigationSequence, nextNavigationCursor, offset);
- if (nextTarget?.kind === 'image') {
- selectPreviewImage(nextTarget.image);
+ if (nextTarget?.kind === 'item') {
+ selectPreviewItem(nextTarget.item);
} else if (nextTarget?.kind === 'placeholder') {
account.updateProjectPreferences({ showProgressImagesInViewer: true });
}
@@ -526,14 +509,14 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
[
account,
activeGalleryPlaceholder,
- backendBoardImages,
- fetchNextBoardImagesPage,
- fetchPreviousBoardImagesPage,
- hasNextBoardImagesPage,
- hasPreviousBoardImagesPage,
+ backendBoardItems,
+ fetchNextBoardItemsPage,
+ fetchPreviousBoardItemsPage,
+ hasNextBoardItemsPage,
+ hasPreviousBoardItemsPage,
isComparing,
- isFetchingNextBoardImagesPage,
- isFetchingPreviousBoardImagesPage,
+ isFetchingNextBoardItemsPage,
+ isFetchingPreviousBoardItemsPage,
navigationBoardId,
navigationContextKey,
navigationCursor,
@@ -541,9 +524,9 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
navigationOrderDir,
navigationSequence,
navigationStarredFirst,
- previewLocalBoardImages,
- selectedImageName,
- selectPreviewImage,
+ previewLocalBoardItems,
+ selectedItemKey,
+ selectPreviewItem,
shouldFollowLive,
]
);
@@ -568,62 +551,53 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
);
const [contextMenuTarget, setContextMenuTarget] = useState<ImageContextMenuTarget | null>(null);
- const onImagesDeleted = useCallback(
- (imageNames: string[]) => {
- const deletedNames = new Set(imageNames);
- const images = boardImages;
- const anchorName = selectedImage?.imageName ?? null;
-
- if (!anchorName || !deletedNames.has(anchorName)) {
- return;
- }
-
- const anchorIndex = images.findIndex((image) => image.imageName === anchorName);
-
- if (anchorIndex === -1) {
- return;
- }
-
- const remaining = images.filter((image) => !deletedNames.has(image.imageName));
- const remainingBeforeAnchor = images
- .slice(0, anchorIndex)
- .filter((image) => !deletedNames.has(image.imageName)).length;
- const nextImage = remaining[remainingBeforeAnchor] ?? remaining[remainingBeforeAnchor - 1] ?? null;
-
- if (nextImage) {
- selectPreviewImage(nextImage);
- }
- },
- [boardImages, selectPreviewImage, selectedImage]
+ const getItemActionContext = useCallback(
+ () => ({
+ filterIdentity: navigationQueryKey,
+ items: boardItems,
+ loadOrderedRefs: (signal: AbortSignal) => {
+ signal.throwIfAborted();
+ return Promise.resolve(boardItems.map(toGalleryItemRef));
+ },
+ selectedItemKey,
+ }),
+ [boardItems, navigationQueryKey, selectedItemKey]
);
const projectId = useActiveProjectId();
const imageActions = useImageActions({
boards,
generateValues,
- onImagesDeleted,
+ getItemActionContext,
projectId,
});
- const contextMenuImage = useMemo<GalleryImage | null>(() => {
- if (!selectedImage) {
+ const contextMenuItem = useMemo<GalleryItem | null>(() => {
+ if (!selectedItem) {
return null;
}
- const boardImage = boardImages.find((image) => image.imageName === selectedImage.imageName);
-
- return {
- ...selectedImage,
- boardId: boardImage?.boardId ?? displayBoardId,
- imageCategory: boardImage?.imageCategory ?? selectedImage.imageCategory ?? 'general',
- starred: boardImage?.starred ?? selectedImage.starred ?? false,
- };
- }, [boardImages, displayBoardId, selectedImage]);
- const exitCompare = useCallback(() => gallery.setCompareImage(null), [gallery]);
+ return boardItems.find((item) => toGalleryItemKey(item) === selectedItemKey) ?? selectedItem;
+ }, [boardItems, selectedItem, selectedItemKey]);
+ const actionImage = useMemo<GalleryImage | null>(
+ () =>
+ contextMenuItem && isGalleryImageItem(contextMenuItem) ? galleryImageItemToGalleryImage(contextMenuItem) : null,
+ [contextMenuItem]
+ );
+ const exitCompare = useCallback(() => gallery.setCompareItem(null), [gallery]);
const swapCompareImages = useCallback(() => {
- if (selectedImage && compareImage) {
- selectPreviewImage(compareImage);
- gallery.setCompareImage(selectedImage);
+ if (selectedItem?.kind === 'image' && compareImage) {
+ selectPreviewItem(legacyGeneratedImageToGalleryItem(compareImage));
+ gallery.setCompareItem(selectedItem);
}
- }, [compareImage, gallery, selectPreviewImage, selectedImage]);
+ }, [compareImage, gallery, selectPreviewItem, selectedItem]);
+ const isItemCurrent = useCallback(
+ (itemKey: GalleryItemKey) => {
+ const currentValues = getProjectWidgetValues(queries.getSnapshot().activeProject, 'gallery');
+ const currentItem = getSelectedGalleryItemFromValues(currentValues);
+
+ return currentItem !== null && toGalleryItemKey(currentItem) === itemKey;
+ },
+ [queries]
+ );
const setComparisonMode = useCallback(
(comparisonMode: PreviewComparisonMode) => widgets.patchValues('preview', { comparisonMode }),
[widgets]
@@ -634,13 +608,16 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
[isMetadataOpen, widgets]
);
const isFilmstripVisible = getPreviewFilmstripVisible(previewValues);
- const selectImage = selectPreviewImage;
// Drop-to-compare: any all-image gallery-item drag dropped on the frame's drop zone
// arms that image for comparison. The drag payload only carries names, so
// the full contract is fetched before dispatching.
const handleCompareDrop = useCallback(
(event: DragEndEvent) => {
+ if (selectedItem?.kind !== 'image') {
+ return;
+ }
+
const resolution = resolvePreviewCompareDrop(event.active.data.current, event.over?.data.current ?? null);
if (!resolution) {
@@ -649,12 +626,12 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
// Prefer images we already hold (board context includes fresh local
// generations that would 404 on a backend by-name fetch).
- const localImage =
- boardImages.find((image) => image.imageName === resolution.imageName) ??
- (selectedImage?.imageName === resolution.imageName ? selectedImage : null);
+ const localImageItem =
+ boardItems.find((item) => item.kind === 'image' && item.name === resolution.imageName) ??
+ (selectedItem.name === resolution.imageName ? selectedItem : null);
- if (localImage) {
- gallery.setCompareImage(localImage);
+ if (localImageItem?.kind === 'image') {
+ gallery.setCompareItem(localImageItem);
return;
}
@@ -669,21 +646,26 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
});
});
},
- [boardImages, gallery, notifications, selectedImage]
+ [boardItems, gallery, notifications, selectedItem]
);
useDndMonitor({ onDragEnd: handleCompareDrop });
- const openImageContextMenu = useCallback(
+ const openItemContextMenu = useCallback(
(x: number, y: number) => {
- if (contextMenuImage) {
- setContextMenuTarget({ images: [contextMenuImage], x, y });
+ if (contextMenuItem) {
+ setContextMenuTarget({
+ itemRefs: [toGalleryItemRef(contextMenuItem)],
+ items: [contextMenuItem],
+ x,
+ y,
+ });
}
},
- [contextMenuImage]
+ [contextMenuItem]
);
- const selectNextImage = useCallback(() => navigate(1), [navigate]);
- const selectPreviousImage = useCallback(() => navigate(-1), [navigate]);
+ const selectNextItem = useCallback(() => navigate(1), [navigate]);
+ const selectPreviousItem = useCallback(() => navigate(-1), [navigate]);
const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);
- const headerImageName = shouldFollowLive ? null : selectedImageName;
+ const headerItemName = shouldFollowLive ? null : (selectedItem?.name ?? null);
// Publish the header chrome context (the "[board] / [image]" label and the
// action strip's image + actions) for the widget frame; the chrome renders
@@ -691,13 +673,13 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
// unmount so stale chrome never outlives us.
useEffect(() => {
previewHeaderStore.set({
- actionImage: shouldFollowLive ? null : contextMenuImage,
+ actionItem: shouldFollowLive ? null : contextMenuItem,
actions: shouldFollowLive ? null : imageActions,
- boardName: headerImageName === null ? null : boardName,
- imageName: headerImageName,
- openImageMenu: shouldFollowLive ? null : openImageContextMenu,
+ boardName: headerItemName === null ? null : boardName,
+ itemName: headerItemName,
+ openItemMenu: shouldFollowLive ? null : openItemContextMenu,
});
- }, [boardName, contextMenuImage, headerImageName, imageActions, openImageContextMenu, shouldFollowLive]);
+ }, [boardName, contextMenuItem, headerItemName, imageActions, openItemContextMenu, shouldFollowLive]);
useEffect(() => () => previewHeaderStore.clear(), []);
@@ -705,8 +687,10 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
// swaps without a decode flash.
const previousNeighbor = navigationSequence[navigationCursor - 1];
const nextNeighbor = navigationSequence[navigationCursor + 1];
- const previousNeighborUrl = previousNeighbor?.kind === 'image' ? previousNeighbor.image.imageUrl : null;
- const nextNeighborUrl = nextNeighbor?.kind === 'image' ? nextNeighbor.image.imageUrl : null;
+ const previousNeighborUrl =
+ previousNeighbor?.kind === 'item' && previousNeighbor.item.kind === 'image' ? previousNeighbor.item.fullUrl : null;
+ const nextNeighborUrl =
+ nextNeighbor?.kind === 'item' && nextNeighbor.item.kind === 'image' ? nextNeighbor.item.fullUrl : null;
useEffect(() => {
[previousNeighborUrl, nextNeighborUrl].forEach((url) => {
@@ -721,23 +705,23 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
return;
}
- if (commandId === 'viewer.swapImages' && selectedImage && compareImage) {
- selectPreviewImage(compareImage);
- gallery.setCompareImage(selectedImage);
+ if (commandId === 'viewer.swapImages' && selectedItem?.kind === 'image' && compareImage) {
+ selectPreviewItem(legacyGeneratedImageToGalleryItem(compareImage));
+ gallery.setCompareItem(selectedItem);
return;
}
- if (commandId === 'viewer.deleteImage' && selectedImage && !shouldFollowLive) {
- void imageActions.deleteImages([selectedImage.imageName]);
+ if (commandId === 'viewer.deleteImage' && selectedItem && !shouldFollowLive) {
+ void imageActions.deleteItems([toGalleryItemRef(selectedItem)]);
return;
}
- if (commandId === 'viewer.zoomToActual') {
+ if (commandId === 'viewer.zoomToActual' && selectedItem?.kind === 'image') {
loupeControlsRef.current?.zoomToActual();
return;
}
- if (commandId === 'viewer.zoomToFit') {
+ if (commandId === 'viewer.zoomToFit' && selectedItem?.kind === 'image') {
loupeControlsRef.current?.reset();
return;
}
@@ -793,11 +777,11 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
progressImage={matchingProgressImage}
shouldAntialiasProgressImage={antialiasProgressImages}
/>
- ) : selectedImage ? (
+ ) : selectedItem ? (
<>
- {isComparing && compareImage ? (
+ {isComparing && compareImage && selectedItem.kind === 'image' ? (
<PreviewCompare
- baseImage={selectedImage}
+ baseImage={galleryImageItemToGalleryImage(selectedItem)}
compareImage={compareImage}
mode={comparisonMode}
runtime={runtime}
@@ -805,22 +789,41 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
onModeChange={setComparisonMode}
onSwap={swapCompareImages}
/>
- ) : (
+ ) : selectedItem.kind === 'image' ? (
<SelectedImagePreview
- actionImage={contextMenuImage}
+ actionImage={actionImage}
actions={imageActions}
- filmstripImages={isFilmstripVisible && density !== 'minimal' ? boardImages : null}
+ boardItemCount={navigationSequence.length}
+ density={density}
+ filmstripItems={isFilmstripVisible && density !== 'minimal' ? boardItems : null}
+ isItemCurrent={isItemCurrent}
+ isLoadingBoard={isLoadingBoard}
+ isMetadataOpen={isMetadataOpen}
+ item={selectedItem}
loupeControlsRef={loupeControlsRef}
- boardImageCount={navigationSequence.length}
+ selectedIndex={navigationCursor}
+ onContextMenu={openItemContextMenu}
+ onNext={selectNextItem}
+ onPrevious={selectPreviousItem}
+ onSelectItem={selectPreviewItem}
+ onToggleMetadata={toggleMetadata}
+ />
+ ) : (
+ <SelectedVideoPreview
+ actionImage={null}
+ actions={imageActions}
+ boardItemCount={navigationSequence.length}
density={density}
- image={selectedImage}
+ filmstripItems={isFilmstripVisible && density !== 'minimal' ? boardItems : null}
+ isItemCurrent={isItemCurrent}
isLoadingBoard={isLoadingBoard}
isMetadataOpen={isMetadataOpen}
+ item={selectedItem}
selectedIndex={navigationCursor}
- onContextMenu={openImageContextMenu}
- onNext={selectNextImage}
- onPrevious={selectPreviousImage}
- onSelectImage={selectImage}
+ onContextMenu={openItemContextMenu}
+ onNext={selectNextItem}
+ onPrevious={selectPreviousItem}
+ onSelectItem={selectPreviewItem}
onToggleMetadata={toggleMetadata}
/>
)}
@@ -839,82 +842,132 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
);
};
-const SelectedImagePreview = ({
- actionImage,
- actions,
- boardImageCount,
- density,
- filmstripImages,
- image,
- isLoadingBoard,
- isMetadataOpen,
- loupeControlsRef,
- selectedIndex,
- onContextMenu,
- onNext,
- onPrevious,
- onSelectImage,
- onToggleMetadata,
-}: {
+const SelectedImagePreview = ({ item, ...props }: SelectedMediaPreviewProps & { item: GalleryImageItem }) => {
+ const previewImage = useStreamingImageSource({
+ fallbackImage: imageUrlToStreamingSource({
+ alt: item.name,
+ height: item.height,
+ kind: 'fallback',
+ src: item.fullUrl,
+ width: item.width,
+ }),
+ });
+ const source = useMemo<PreviewMediaSource | null>(
+ () => (previewImage ? { itemKey: toGalleryItemKey(item), kind: 'image', source: previewImage } : null),
+ [item, previewImage]
+ );
+
+ return (
+ <SelectedMediaPreview
+ {...props}
+ dragItem={toGalleryItemRef(item)}
+ frameHeight={previewImage?.height ?? item.height}
+ frameWidth={previewImage?.width ?? item.width}
+ item={item}
+ source={source}
+ />
+ );
+};
+
+const SelectedVideoPreview = ({
+ item,
+ ...props
+}: SelectedMediaPreviewProps & { item: Extract<GalleryItem, { kind: 'video' }> }) => {
+ const { t } = useTranslation();
+ const source = useMemo<PreviewMediaSource>(
+ () => ({
+ itemKey: toGalleryItemKey(item),
+ kind: 'video',
+ label: t('widgets.preview.videoLabel', { defaultValue: `Video ${item.name}`, name: item.name }),
+ poster: item.thumbnailUrl,
+ src: item.fullUrl,
+ }),
+ [item, t]
+ );
+
+ return (
+ <SelectedMediaPreview {...props} frameHeight={item.height} frameWidth={item.width} item={item} source={source} />
+ );
+};
+
+interface SelectedMediaPreviewProps {
actionImage: GalleryImage | null;
actions: ImageActions;
- boardImageCount: number;
+ boardItemCount: number;
density: PreviewDensity;
/** Board thumbnails for the filmstrip, or null when the strip is hidden. */
- filmstripImages: PreviewImage[] | null;
- image: GeneratedImageContract;
+ filmstripItems: GalleryItem[] | null;
+ isItemCurrent: (itemKey: GalleryItemKey) => boolean;
isLoadingBoard: boolean;
isMetadataOpen: boolean;
+ item: GalleryItem;
loupeControlsRef?: Ref<PreviewLoupeControls>;
selectedIndex: number;
onContextMenu: (x: number, y: number) => void;
onNext: () => void;
onPrevious: () => void;
- onSelectImage: (image: GeneratedImageContract) => void;
+ onSelectItem: (item: GalleryItem) => void;
onToggleMetadata: () => void;
+}
+
+const SelectedMediaPreview = ({
+ actionImage,
+ actions,
+ boardItemCount,
+ density,
+ dragItem,
+ filmstripItems,
+ frameHeight,
+ frameWidth,
+ isItemCurrent,
+ isLoadingBoard,
+ isMetadataOpen,
+ item,
+ loupeControlsRef,
+ selectedIndex,
+ source,
+ onContextMenu,
+ onNext,
+ onPrevious,
+ onSelectItem,
+ onToggleMetadata,
+}: SelectedMediaPreviewProps & {
+ dragItem?: GalleryItemRef;
+ frameHeight: number;
+ frameWidth: number;
+ source: Parameters<typeof PreviewFrame>[0]['source'];
}) => {
const { t } = useTranslation();
- const previewImage = useStreamingImageSource({
- fallbackImage: imageUrlToStreamingSource({
- alt: image.imageName,
- height: image.height,
- kind: 'fallback',
- src: image.imageUrl,
- width: image.width,
- }),
- });
- const previewWidth = previewImage?.width ?? image.width;
- const previewHeight = previewImage?.height ?? image.height;
- const dragItem = useMemo(() => ({ kind: 'image', name: image.imageName }) as const, [image.imageName]);
+
return (
<Stack gap="2" h="full" minH="0" w="full">
<PreviewFrame
dragItem={dragItem}
- frameHeight={previewHeight}
- frameWidth={previewWidth}
+ frameHeight={frameHeight}
+ frameWidth={frameWidth}
+ isItemCurrent={isItemCurrent}
isLive={false}
liveBadgeLabel={t('common.generating')}
loupeControlsRef={loupeControlsRef}
padding={density === 'full' ? '6' : '3'}
shouldAntialiasLiveImage
- source={previewImage}
+ source={source}
variant="framed"
onContextMenu={onContextMenu}
/>
- {filmstripImages ? (
+ {filmstripItems ? (
<PreviewFilmstrip
density={density}
- images={filmstripImages}
- selectedImageName={image.imageName}
- onSelect={onSelectImage}
+ items={filmstripItems}
+ selectedItemKey={toGalleryItemKey(item)}
+ onSelect={onSelectItem}
/>
) : null}
<PreviewFooter
actionImage={actionImage}
actions={actions}
- boardImageCount={boardImageCount}
- image={image}
- isLive={false}
+ boardItemCount={boardItemCount}
+ item={item}
isLoadingBoard={isLoadingBoard}
isMetadataOpen={isMetadataOpen}
selectedIndex={selectedIndex}
@@ -939,6 +992,17 @@ const LivePreview = ({
const previewImage = useStreamingImageSource({
liveImage: progressImageToStreamingSource(progressImage),
});
+ const source = useMemo<PreviewMediaSource | null>(
+ () =>
+ previewImage
+ ? {
+ itemKey: `image:live:${placeholder.id}`,
+ kind: 'image',
+ source: previewImage,
+ }
+ : null,
+ [placeholder.id, previewImage]
+ );
return (
<PreviewFrame
@@ -948,7 +1012,7 @@ const LivePreview = ({
liveBadgeLabel={t('common.generating')}
liveQueueItemId={placeholder.queueItemId}
shouldAntialiasLiveImage={shouldAntialiasProgressImage}
- source={previewImage}
+ source={source}
variant="inset"
/>
);
@@ -976,6 +1040,17 @@ const LivePreviewTile = ({
const previewImage = useStreamingImageSource({
liveImage: progressImageToStreamingSource(progressImage),
});
+ const source = useMemo<PreviewMediaSource | null>(
+ () =>
+ previewImage
+ ? {
+ itemKey: `image:live:${placeholder.id}`,
+ kind: 'image',
+ source: previewImage,
+ }
+ : null,
+ [placeholder.id, previewImage]
+ );
return (
<PreviewFrame
@@ -987,7 +1062,7 @@ const LivePreviewTile = ({
}
liveQueueItemId={placeholder.queueItemId}
shouldAntialiasLiveImage={shouldAntialiasProgressImage}
- source={previewImage}
+ source={source}
variant="inset"
/>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
index ec88457614..8c48ae4bb4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
@@ -1,4 +1,4 @@
-import type { GalleryImage } from '@features/gallery';
+import type { GalleryItem } from '@features/gallery';
import type { ImageActions } from '@workbench/image-actions';
import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
@@ -13,26 +13,26 @@ import { createExternalStore } from '@platform/state/externalStore';
* static title and hides the action strip.
*/
export interface PreviewHeaderContext {
- /** The selected image with board/star context, ready for image actions. */
- actionImage: GalleryImage | null;
+ /** The selected item with board/star context, ready for common actions. */
+ actionItem: GalleryItem | null;
/** The view's `useImageActions` instance (carries delete-neighbor handling). */
actions: ImageActions | null;
boardName: string | null;
- imageName: string | null;
+ itemName: string | null;
/**
* Opens the view's full image context menu anchored at viewport coordinates.
* The header's "image actions" dropdown reuses the exact right-click menu —
* one source of truth for every image verb.
*/
- openImageMenu: ((x: number, y: number) => void) | null;
+ openItemMenu: ((x: number, y: number) => void) | null;
}
const emptyContext: PreviewHeaderContext = {
- actionImage: null,
+ actionItem: null,
actions: null,
boardName: null,
- imageName: null,
- openImageMenu: null,
+ itemName: null,
+ openItemMenu: null,
};
const store = createExternalStore<PreviewHeaderContext>(emptyContext);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.ts
index c6cc334a2f..e1f1f024ed 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.ts
@@ -1,4 +1,4 @@
-import type { GalleryQueuePlaceholder } from '@features/gallery/contracts';
+import type { GalleryItemKind, GalleryItemKey, GalleryQueuePlaceholder } from '@features/gallery/contracts';
import { describe, expect, it } from 'vitest';
@@ -9,8 +9,9 @@ import {
type PreviewNavigationItem,
} from './previewNavigation';
-interface TestImage {
- imageName: string;
+interface TestItem {
+ kind: GalleryItemKind;
+ name: string;
starred?: boolean;
}
@@ -24,16 +25,16 @@ const placeholder: GalleryQueuePlaceholder = {
width: 1024,
};
-const image = (imageName: string, starred = false): TestImage => ({ imageName, starred });
+const item = (kind: GalleryItemKind, name: string, starred = false): TestItem => ({ kind, name, starred });
-const names = (sequence: PreviewNavigationItem<TestImage>[]): string[] =>
- sequence.map((item) => (item.kind === 'image' ? item.image.imageName : 'placeholder'));
+const keys = (sequence: PreviewNavigationItem<TestItem>[]): string[] =>
+ sequence.map((entry) => (entry.kind === 'item' ? `${entry.item.kind}:${entry.item.name}` : 'placeholder'));
-const buildSequence = (overrides: Partial<Parameters<typeof getPreviewNavigationSequence<TestImage>>[0]> = {}) =>
- getPreviewNavigationSequence<TestImage>({
+const buildSequence = (overrides: Partial<Parameters<typeof getPreviewNavigationSequence<TestItem>>[0]> = {}) =>
+ getPreviewNavigationSequence<TestItem>({
activePlaceholder: placeholder,
boardId: 'none',
- boardImages: [image('newest'), image('middle'), image('oldest')],
+ boardImages: [item('image', 'newest'), item('video', 'middle'), item('image', 'oldest')],
galleryView: 'images',
imageOrderDir: 'DESC',
starredFirst: false,
@@ -42,49 +43,75 @@ const buildSequence = (overrides: Partial<Parameters<typeof getPreviewNavigation
describe('getPreviewNavigationSequence', () => {
it('places the placeholder at the newest position in descending order', () => {
- expect(names(buildSequence())).toEqual(['placeholder', 'newest', 'middle', 'oldest']);
+ expect(keys(buildSequence())).toEqual(['placeholder', 'image:newest', 'video:middle', 'image:oldest']);
});
it('places the placeholder at the latest chronological position in ascending order', () => {
- expect(names(buildSequence({ imageOrderDir: 'ASC' }))).toEqual(['newest', 'middle', 'oldest', 'placeholder']);
+ expect(keys(buildSequence({ imageOrderDir: 'ASC' }))).toEqual([
+ 'image:newest',
+ 'video:middle',
+ 'image:oldest',
+ 'placeholder',
+ ]);
});
it('places the placeholder after the leading starred block when starred-first sorts descending', () => {
expect(
- names(
+ keys(
buildSequence({
- boardImages: [image('starred-a', true), image('starred-b', true), image('newest'), image('oldest')],
+ boardImages: [
+ item('video', 'starred-a', true),
+ item('image', 'starred-b', true),
+ item('image', 'newest'),
+ item('video', 'oldest'),
+ ],
starredFirst: true,
})
)
- ).toEqual(['starred-a', 'starred-b', 'placeholder', 'newest', 'oldest']);
+ ).toEqual(['video:starred-a', 'image:starred-b', 'placeholder', 'image:newest', 'video:oldest']);
});
- it('places the placeholder last when every image is starred', () => {
+ it('places the placeholder last when every item is starred', () => {
expect(
- names(buildSequence({ boardImages: [image('starred-a', true), image('starred-b', true)], starredFirst: true }))
- ).toEqual(['starred-a', 'starred-b', 'placeholder']);
+ keys(
+ buildSequence({
+ boardImages: [item('image', 'starred-a', true), item('video', 'starred-b', true)],
+ starredFirst: true,
+ })
+ )
+ ).toEqual(['image:starred-a', 'video:starred-b', 'placeholder']);
});
it('keeps the placeholder last in ascending order even with starred-first', () => {
expect(
- names(
+ keys(
buildSequence({
- boardImages: [image('starred-a', true), image('newest')],
+ boardImages: [item('video', 'starred-a', true), item('image', 'newest')],
imageOrderDir: 'ASC',
starredFirst: true,
})
)
- ).toEqual(['starred-a', 'newest', 'placeholder']);
+ ).toEqual(['video:starred-a', 'image:newest', 'placeholder']);
});
it('excludes the placeholder when it belongs to another board or the assets view', () => {
- expect(names(buildSequence({ boardId: 'board-2' }))).toEqual(['newest', 'middle', 'oldest']);
- expect(names(buildSequence({ galleryView: 'assets' }))).toEqual(['newest', 'middle', 'oldest']);
+ expect(keys(buildSequence({ boardId: 'board-2' }))).toEqual(['image:newest', 'video:middle', 'image:oldest']);
+ expect(keys(buildSequence({ galleryView: 'assets' }))).toEqual(['image:newest', 'video:middle', 'image:oldest']);
+ });
+
+ it('returns only completed media items when there is no active placeholder', () => {
+ expect(keys(buildSequence({ activePlaceholder: null }))).toEqual(['image:newest', 'video:middle', 'image:oldest']);
});
- it('returns only images when there is no active placeholder', () => {
- expect(names(buildSequence({ activePlaceholder: null }))).toEqual(['newest', 'middle', 'oldest']);
+ it('keeps same-name images and videos as independent navigation entries', () => {
+ expect(
+ keys(
+ buildSequence({
+ activePlaceholder: null,
+ boardImages: [item('image', 'shared'), item('video', 'shared')],
+ })
+ )
+ ).toEqual(['image:shared', 'video:shared']);
});
});
@@ -92,16 +119,28 @@ describe('getPreviewNavigationCursor', () => {
const sequence = buildSequence();
it('resolves to the placeholder while following live', () => {
- expect(getPreviewNavigationCursor(sequence, { isFollowingLive: true, selectedImageName: 'middle' })).toBe(0);
+ expect(getPreviewNavigationCursor(sequence, { isFollowingLive: true, selectedItemKey: 'video:middle' })).toBe(0);
});
- it('resolves to the selected image otherwise', () => {
- expect(getPreviewNavigationCursor(sequence, { isFollowingLive: false, selectedImageName: 'middle' })).toBe(2);
+ it('resolves the selected media kind and name otherwise', () => {
+ expect(getPreviewNavigationCursor(sequence, { isFollowingLive: false, selectedItemKey: 'video:middle' })).toBe(2);
+
+ const sameName = buildSequence({
+ activePlaceholder: null,
+ boardImages: [item('image', 'shared'), item('video', 'shared')],
+ });
+ expect(getPreviewNavigationCursor(sameName, { isFollowingLive: false, selectedItemKey: 'image:shared' })).toBe(0);
+ expect(getPreviewNavigationCursor(sameName, { isFollowingLive: false, selectedItemKey: 'video:shared' })).toBe(1);
});
- it('is unresolved when the selected image is absent from the sequence', () => {
- expect(getPreviewNavigationCursor(sequence, { isFollowingLive: false, selectedImageName: 'missing' })).toBe(-1);
- expect(getPreviewNavigationCursor(sequence, { isFollowingLive: false, selectedImageName: null })).toBe(-1);
+ it('is unresolved when the selected item is absent from the sequence', () => {
+ expect(
+ getPreviewNavigationCursor(sequence, {
+ isFollowingLive: false,
+ selectedItemKey: 'image:missing' as GalleryItemKey,
+ })
+ ).toBe(-1);
+ expect(getPreviewNavigationCursor(sequence, { isFollowingLive: false, selectedItemKey: null })).toBe(-1);
});
});
@@ -109,20 +148,32 @@ describe('getPreviewNavigationTarget', () => {
const sequence = buildSequence();
it('moves exactly one position in either direction', () => {
- expect(getPreviewNavigationTarget(sequence, 2, -1)).toEqual({ image: image('newest'), kind: 'image' });
- expect(getPreviewNavigationTarget(sequence, 2, 1)).toEqual({ image: image('oldest'), kind: 'image' });
+ expect(getPreviewNavigationTarget(sequence, 2, -1)).toEqual({
+ item: item('image', 'newest'),
+ kind: 'item',
+ });
+ expect(getPreviewNavigationTarget(sequence, 2, 1)).toEqual({
+ item: item('image', 'oldest'),
+ kind: 'item',
+ });
});
- it('steps between the newest image and the placeholder in descending order', () => {
+ it('steps between the newest item and the placeholder in descending order', () => {
expect(getPreviewNavigationTarget(sequence, 1, -1)).toEqual({ kind: 'placeholder', placeholder });
- expect(getPreviewNavigationTarget(sequence, 0, 1)).toEqual({ image: image('newest'), kind: 'image' });
+ expect(getPreviewNavigationTarget(sequence, 0, 1)).toEqual({
+ item: item('image', 'newest'),
+ kind: 'item',
+ });
});
- it('steps between the oldest image and the placeholder in ascending order', () => {
+ it('steps between the oldest item and the placeholder in ascending order', () => {
const ascending = buildSequence({ imageOrderDir: 'ASC' });
expect(getPreviewNavigationTarget(ascending, 2, 1)).toEqual({ kind: 'placeholder', placeholder });
- expect(getPreviewNavigationTarget(ascending, 3, -1)).toEqual({ image: image('oldest'), kind: 'image' });
+ expect(getPreviewNavigationTarget(ascending, 3, -1)).toEqual({
+ item: item('image', 'oldest'),
+ kind: 'item',
+ });
});
it('clamps at both sequence boundaries', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.ts
index c9c68aab97..687e3ba246 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.ts
@@ -1,6 +1,12 @@
-import type { GalleryOrderDir, GalleryQueuePlaceholder, GalleryView } from '@features/gallery/contracts';
+import type {
+ GalleryItemKind,
+ GalleryItemKey,
+ GalleryOrderDir,
+ GalleryQueuePlaceholder,
+ GalleryView,
+} from '@features/gallery/contracts';
-import { getGalleryPlaceholderInsertionIndex } from '@features/gallery/contracts';
+import { getGalleryPlaceholderInsertionIndex, toGalleryItemKey } from '@features/gallery/contracts';
/**
* Pure navigation model for the preview widget's left/right stepping.
@@ -11,16 +17,17 @@ import { getGalleryPlaceholderInsertionIndex } from '@features/gallery/contracts
* of truth; the cursor is re-resolved from them on every render, never stored.
*/
-interface NavigableImage {
- imageName: string;
+interface NavigableItem {
+ kind: GalleryItemKind;
+ name: string;
starred?: boolean;
}
-export type PreviewNavigationItem<TImage extends NavigableImage> =
- | { kind: 'image'; image: TImage }
+export type PreviewNavigationItem<TItem extends NavigableItem> =
+ | { kind: 'item'; item: TItem }
| { kind: 'placeholder'; placeholder: GalleryQueuePlaceholder };
-export const getPreviewNavigationSequence = <TImage extends NavigableImage>({
+export const getPreviewNavigationSequence = <TItem extends NavigableItem>({
activePlaceholder,
boardId,
boardImages,
@@ -30,15 +37,15 @@ export const getPreviewNavigationSequence = <TImage extends NavigableImage>({
}: {
/** The live slot from getGalleryGenerationSequence, or null. */
activePlaceholder: GalleryQueuePlaceholder | null;
- /** The board backing boardImages — the selected image's own board. */
+ /** The board backing boardImages — the selected item's own board. */
boardId: string;
- /** Board images in the gallery's display order. */
- boardImages: TImage[];
+ /** Board items in the gallery's display order. */
+ boardImages: TItem[];
galleryView: GalleryView;
imageOrderDir: GalleryOrderDir;
starredFirst: boolean;
-}): PreviewNavigationItem<TImage>[] => {
- const items: PreviewNavigationItem<TImage>[] = boardImages.map((image) => ({ image, kind: 'image' }));
+}): PreviewNavigationItem<TItem>[] => {
+ const items: PreviewNavigationItem<TItem>[] = boardImages.map((item) => ({ item, kind: 'item' }));
const includePlaceholder =
activePlaceholder !== null && galleryView === 'images' && activePlaceholder.boardId === boardId;
@@ -54,23 +61,23 @@ export const getPreviewNavigationSequence = <TImage extends NavigableImage>({
return items;
};
-export const getPreviewNavigationCursor = <TImage extends NavigableImage>(
- sequence: PreviewNavigationItem<TImage>[],
- { isFollowingLive, selectedImageName }: { isFollowingLive: boolean; selectedImageName: string | null }
+export const getPreviewNavigationCursor = <TItem extends NavigableItem>(
+ sequence: PreviewNavigationItem<TItem>[],
+ { isFollowingLive, selectedItemKey }: { isFollowingLive: boolean; selectedItemKey: GalleryItemKey | null }
): number => {
if (isFollowingLive) {
return sequence.findIndex((item) => item.kind === 'placeholder');
}
- if (selectedImageName === null) {
+ if (selectedItemKey === null) {
return -1;
}
- return sequence.findIndex((item) => item.kind === 'image' && item.image.imageName === selectedImageName);
+ return sequence.findIndex((entry) => entry.kind === 'item' && toGalleryItemKey(entry.item) === selectedItemKey);
};
-export const getPreviewNavigationTarget = <TImage extends NavigableImage>(
- sequence: PreviewNavigationItem<TImage>[],
+export const getPreviewNavigationTarget = <TItem extends NavigableItem>(
+ sequence: PreviewNavigationItem<TItem>[],
cursorIndex: number,
offset: -1 | 1
-): PreviewNavigationItem<TImage> | null => (cursorIndex === -1 ? null : (sequence[cursorIndex + offset] ?? null));
+): PreviewNavigationItem<TItem> | null => (cursorIndex === -1 ? null : (sequence[cursorIndex + offset] ?? null));