Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): play a reference clip's trimmed window in Preview
Lincoln Stein1a9c60810efa
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex 6e12bd0707..b9abb0f416 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -10,7 +10,7 @@"initialRawBytes": 2010846,"largestAssetRawBytes": 747218,"otherAssetRawBytes": 0,- "ownedRawBytes": 74441,+ "ownedRawBytes": 74443,"requestCount": 44,"scriptRequestCount": 28,"sourceOwners": [@@ -319,7 +319,7 @@"initialRawBytes": 2030955,"largestAssetRawBytes": 754691,"otherAssetRawBytes": 0,- "ownedRawBytes": 74441,+ "ownedRawBytes": 74443,"requestCount": 44,"scriptRequestCount": 28},@@ -337,7 +337,7 @@"initialRawBytes": 2990384,"largestAssetRawBytes": 747218,"otherAssetRawBytes": 0,- "ownedRawBytes": 131266,+ "ownedRawBytes": 131729,"requestCount": 106,"scriptRequestCount": 90,"sourceOwners": [@@ -1011,6 +1011,7 @@"source:src/workbench/widgets/preview/manifest.ts","source:src/workbench/widgets/preview/previewSettings.ts","source:src/workbench/widgets/preview/settingsContribution.ts",+ "source:src/workbench/widgets/preview/spanPlaybackRequest.ts","source:src/workbench/widgets/project/manifest.ts","source:src/workbench/widgets/queue-status/manifest.ts","source:src/workbench/widgets/queue/manifest.ts",@@ -1031,7 +1032,7 @@"initialRawBytes": 3020288,"largestAssetRawBytes": 754691,"otherAssetRawBytes": 0,- "ownedRawBytes": 131266,+ "ownedRawBytes": 131729,"requestCount": 106,"scriptRequestCount": 90},diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 1f5e3c60a4..aa359f297f 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -1938,6 +1938,7 @@"source:src/workbench/widgets/preview/previewNavigation.ts","source:src/workbench/widgets/preview/previewSettings.ts","source:src/workbench/widgets/preview/settingsContribution.ts",+ "source:src/workbench/widgets/preview/spanPlaybackRequest.ts","source:src/workbench/widgets/preview/useCompareLoupe.ts","source:src/workbench/widgets/preview/usePreviewLoupe.ts","source:src/workbench/widgets/preview/usePreviewNavigation.ts",@@ -3112,6 +3113,7 @@"source:src/workbench/widgets/preview/previewNavigation.ts","source:src/workbench/widgets/preview/previewSettings.ts","source:src/workbench/widgets/preview/settingsContribution.ts",+ "source:src/workbench/widgets/preview/spanPlaybackRequest.ts","source:src/workbench/widgets/preview/useCompareLoupe.ts","source:src/workbench/widgets/preview/usePreviewLoupe.ts","source:src/workbench/widgets/preview/usePreviewNavigation.ts",@@ -4205,6 +4207,7 @@"source:src/workbench/widgets/preview/previewNavigation.ts","source:src/workbench/widgets/preview/previewSettings.ts","source:src/workbench/widgets/preview/settingsContribution.ts",+ "source:src/workbench/widgets/preview/spanPlaybackRequest.ts","source:src/workbench/widgets/preview/useCompareLoupe.ts","source:src/workbench/widgets/preview/usePreviewLoupe.ts","source:src/workbench/widgets/preview/usePreviewNavigation.ts",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 4776d84857..f8cf756503 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -3816,6 +3816,7 @@"lastFrame": "Last Frame","lastFrameExtendHelp": "Optional destination: the extension ends on this image.","lastFrameHelp": "Optional: the video ends on this image (interpolates from the first frame).",+ "playSelection": "Play selection in Preview","removeClip": "Remove video","sampleLength": "Sample Length (Frames)","sampleLengthWithSeconds": "Sample Length · {{seconds}}s",diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsxnew file mode 100644index 0000000000..28d04e754c--- /dev/null+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx@@ -0,0 +1,131 @@+import type { GalleryVideoItem } from '@features/gallery';+import type { VideoUiAdapter } from '@features/video';+import type { OpenWorkbenchWidgetResult } from '@workbench/useOpenWorkbenchWidget';+import type { ReactNode } from 'react';++import { getGalleryRevealRequest } from '@features/gallery/core/selection';+import {+ consumeVideoSpanPlaybackRequest,+ getVideoSpanPlaybackRequest,+} from '@workbench/widgets/preview/spanPlaybackRequest';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { VideoUiAdapterProvider } from './VideoUiAdapter';++/**+ * The panel's play button is one gesture spread over three subsystems — the Preview+ * widget's placement, gallery selection, and the span request the player reads — and this+ * adapter is the only place they are put in order. What it has to protect is the user's+ * gallery selection: it is theirs, it persists, and moving it is not undoable.+ *+ * A browser test because the provider has to render, and the unit config carries no DOM —+ * the same reason `GalleryUiAdapter.browser.test.tsx` lives there.+ */++let adapter: VideoUiAdapter;+let openResult: OpenWorkbenchWidgetResult;+let activeProjectId: string;++const openWorkbenchWidget = vi.fn(() => openResult);+const selectItem = vi.fn();++vi.mock('@features/video', () => ({+ VideoUiProvider: ({ adapter: next, children }: { adapter: VideoUiAdapter; children: ReactNode }) => {+ adapter = next;+ return children;+ },+}));+vi.mock('@features/gallery/queries', () => ({ invalidateGallery: vi.fn() }));+vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({}) }));+vi.mock('@workbench/settings/store', () => ({ useWorkbenchPreferenceSelector: () => false }));+vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => openWorkbenchWidget }));+vi.mock('@workbench/WorkbenchContext', () => ({+ useActiveProjectSelector: (selector: (project: unknown) => unknown) =>+ selector({ id: activeProjectId, widgetInstances: {} }),+ useWorkbenchCommands: () => ({+ gallery: { selectItem },+ notifications: { reportError: vi.fn() },+ widgets: { patchValues: vi.fn() },+ }),+}));++const videoItem = { kind: 'video', name: 'clip.mp4' } as unknown as GalleryVideoItem;+const span = { endSeconds: 3, item: videoItem, startSeconds: 2 };++let host: HTMLDivElement;+let root: Root;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const renderAdapter = async (): Promise<void> => {+ await act(() => root.render(<VideoUiAdapterProvider>{null}</VideoUiAdapterProvider>));+};++beforeEach(async () => {+ openResult = { ok: true, region: 'center' };+ activeProjectId = 'project-1';+ openWorkbenchWidget.mockClear();+ selectItem.mockClear();+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await renderAdapter();+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();++ const outstanding = getVideoSpanPlaybackRequest();++ if (outstanding) {+ consumeVideoSpanPlaybackRequest(outstanding.token);+ }+});++describe('playVideoSpanInPreview', () => {+ it('puts the clip in front of the user without disturbing their place in the gallery', () => {+ const revealBefore = getGalleryRevealRequest()?.token;++ act(() => adapter.playVideoSpanInPreview(span));++ expect(selectItem).toHaveBeenCalledWith(videoItem, 'project-1');+ expect(getVideoSpanPlaybackRequest()).toMatchObject({+ endSeconds: 3,+ itemKey: 'video:clip.mp4',+ startSeconds: 2,+ });+ // Deliberately no reveal: auditioning a trim must not scroll the gallery grid out+ // from under a user who is browsing it, and the gallery's own "open in Preview"+ // does not reveal either.+ expect(getGalleryRevealRequest()?.token).toBe(revealBefore);+ });++ it('changes nothing at all when Preview refuses to open', () => {+ openResult = { ok: false, reason: 'unavailable' };++ act(() => adapter.playVideoSpanInPreview(span));++ // A press that cannot play must not cost the user their selection — that is a change+ // they did not ask for and cannot undo. And a span nothing is there to read would sit+ // until the next player showed this clip, starting audio out of nowhere.+ expect(selectItem).not.toHaveBeenCalled();+ expect(getVideoSpanPlaybackRequest()).toBeNull();+ });++ it('drops a press whose lookup landed after the user switched projects', async () => {+ // The button resolves its gallery item over the network and calls back with the+ // callback it captured. Writing that selection now would land it in the project the+ // user just left, where it persists.+ const stalePress = adapter.playVideoSpanInPreview;++ activeProjectId = 'project-2';+ await renderAdapter();++ act(() => stalePress(span));++ expect(selectItem).not.toHaveBeenCalled();+ expect(getVideoSpanPlaybackRequest()).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsxindex a710c7de54..959d632d84 100644--- a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx@@ -1,10 +1,13 @@import type { VideoUiAdapter } from '@features/video';import type { ReactNode } from 'react';+import { toGalleryItemKey } from '@features/gallery/contracts';import { invalidateGallery } from '@features/gallery/queries';import { VideoUiProvider } from '@features/video';import { useQueryClient } from '@tanstack/react-query';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';+import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';+import { requestVideoSpanPlayback } from '@workbench/widgets/preview/spanPlaybackRequest';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { useCallback, useEffect, useMemo, useRef } from 'react';@@ -44,9 +47,13 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>// Ref-backed so the port's actions keep their stable-for-the-project identity: a// board click must not re-render every useVideoUiActions consumer in the panel.const uploadBoardIdRef = useRef(uploadBoardId);+ // The live project, for callbacks that outlive the render that built them: a play press+ // resolves its clip over the network and can land after a project switch.+ const activeProjectIdRef = useRef(project.projectId);useEffect(() => {uploadBoardIdRef.current = uploadBoardId;- }, [uploadBoardId]);+ activeProjectIdRef.current = project.projectId;+ }, [project.projectId, uploadBoardId]);const commands = useWorkbenchCommands();const queryClient = useQueryClient();// The port's callbacks are keyed to the project, not to its contents: rebuilding@@ -62,17 +69,54 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>[commands]);const touchGalleryImages = useCallback(() => void invalidateGallery(queryClient), [queryClient]);+ const openWorkbenchWidget = useOpenWorkbenchWidget();+ // Preview renders the gallery selection, so putting a reference clip in front of the user+ // is the gallery's own "open in Preview" gesture: select the item, raise the widget into+ // the center view. Deliberately WITHOUT that gesture's sibling reveal — auditioning a+ // trim should not also scroll the gallery grid out from under a browsing user, and+ // `openItemInPreview` does not reveal either.+ //+ // Raising Preview comes first so a refusal costs the user nothing: the selection is+ // theirs, and moving it for a press that cannot play would be a change they did not ask+ // for and cannot undo. The span request goes last, once the widget is on its way.+ const playVideoSpanInPreview = useCallback<VideoUiAdapter['playVideoSpanInPreview']>(+ ({ endSeconds, item, startSeconds }) => {+ // The press resolved its gallery item over the network, and the user can have+ // switched projects in that window. This callback still carries the project it was+ // built for, so writing a selection now would land it in the project they left.+ if (activeProjectIdRef.current !== projectId) {+ return;+ }++ if (!openWorkbenchWidget('preview', { preferredRegions: ['center'], requireCenterView: true }).ok) {+ return;+ }++ commands.gallery.selectItem(item, projectId);+ requestVideoSpanPlayback({ endSeconds, itemKey: toGalleryItemKey(item), startSeconds });+ },+ [commands, openWorkbenchWidget, projectId]+ );const getUploadBoardId = useCallback(() => uploadBoardIdRef.current, []);const adapter = useMemo<VideoUiAdapter>(() => ({...project,getUploadBoardId,patchValues,+ playVideoSpanInPreview,reportError,showPromptSyntaxHighlighting,touchGalleryImages,}),- [getUploadBoardId, patchValues, project, reportError, showPromptSyntaxHighlighting, touchGalleryImages]+ [+ getUploadBoardId,+ patchValues,+ playVideoSpanInPreview,+ project,+ reportError,+ showPromptSyntaxHighlighting,+ touchGalleryImages,+ ]);return <VideoUiProvider adapter={adapter}>{children}</VideoUiProvider>;diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.tsindex 0543ba668b..924f7d5879 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts@@ -26,6 +26,7 @@ import {normalizeVideoSettings,normalizeVideoWidgetValues,resolveVideoMode,+ videoClipSpanSeconds,VIDEO_SOURCE_FALLBACK_FPS,} from './settings';import { getDefaultVideoSettings } from './videoPolicies';@@ -210,6 +211,23 @@ describe('isVideoSourceClip', () => {});});+describe('videoClipSpanSeconds', () => {+ it('runs to the far edge of the last selected frame', () => {+ // 16 fps, frames 0..79 inclusive: stopping at 79/16 would cut the final frame short.+ expect(videoClipSpanSeconds(SOURCE_VIDEO)).toEqual({ endSeconds: 5, startSeconds: 0 });+ expect(videoClipSpanSeconds({ ...SOURCE_VIDEO, endFrame: 47, startFrame: 32 })).toEqual({+ endSeconds: 3,+ startSeconds: 2,+ });+ });++ it('has no span to offer for a clip with no usable frame rate', () => {+ // A persisted clip only has to hold a FINITE fps to hydrate, and a zero would put the+ // whole clip behind a control that claims to play the selection.+ expect(videoClipSpanSeconds({ ...SOURCE_VIDEO, fps: 0 })).toBeNull();+ });+});+describe('normalizeVideoWidgetValues / cloneVideoWidgetValues', () => {const model = { base: 'wan', key: 'wan-key', name: 'Wan', type: 'main' as const, variant: 't2v_a14b' };diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.tsindex b5a2cbdf16..661162cc73 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts@@ -652,6 +652,20 @@ export const getDefaultReferenceImageDetail = (references: VideoReferenceItem[])/** The minimum frames a trim must keep — video_concat's crossfade consumes a 2-frame tail. */export const MIN_VIDEO_TRIM_FRAMES = 2;+/**+ * The trim as playable seconds, for previewing the window a clip actually selects.+ *+ * The bounds are INCLUSIVE frame indices, so the window runs to the far edge of+ * `endFrame`'s display interval rather than to its start — playing to `endFrame / fps`+ * would cut the last selected frame. Null when the record carries no usable frame rate:+ * a persisted clip only has to hold a finite `fps` to hydrate, and a zero would put the+ * whole clip's length behind a play button that claims to play the selection.+ */+export const videoClipSpanSeconds = (clip: VideoSourceClip): { endSeconds: number; startSeconds: number } | null =>+ Number.isFinite(clip.fps) && clip.fps > 0+ ? { endSeconds: (clip.endFrame + 1) / clip.fps, startSeconds: clip.startFrame / clip.fps }+ : null;+/*** The MAXIMUM lead-in the reference-extend tail reference samples ahead of the* cutpoint, expressed at 24 fps: ~5s, and exactly on the 17n+5 frame griddiff --git a/invokeai/frontend/webv2/src/features/video/ui/PlayClipSpanButton.tsx b/invokeai/frontend/webv2/src/features/video/ui/PlayClipSpanButton.tsxnew file mode 100644index 0000000000..0404fdd1de--- /dev/null+++ b/invokeai/frontend/webv2/src/features/video/ui/PlayClipSpanButton.tsx@@ -0,0 +1,80 @@+import type { VideoSourceClip } from '@features/video/core/types';++import { galleryItems } from '@features/gallery';+import { videoClipSpanSeconds } from '@features/video/core/settings';+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { IconButton } from '@platform/ui/Button';+import { PlayIcon } from 'lucide-react';+import { memo, useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useVideoUiActions } from './VideoUiContext';++/**+ * Plays a clip's trimmed window in the Preview widget, looping it.+ *+ * The trim rows show two still frames, which answer where the window starts and ends but+ * not what is inside it — and for an audio reference, whose frames are a drawing of the+ * sound, nothing at all. This is the panel's only way to hear or watch the selection+ * before a generation is spent on it.+ *+ * Never gated on the panel's edit-disabled state: playing changes nothing, and a clip the+ * user can see is one they should be able to audition. The gallery record is resolved on+ * press rather than held on the reference, because the panel stores a clip (name,+ * dimensions, frame rate) while Preview needs the item itself — one small request against+ * something the user already has open, paid for by the press rather than by every card on+ * mount.+ */++export const PlayClipSpanButton = memo(function PlayClipSpanButton({ clip }: { clip: VideoSourceClip }) {+ const { t } = useTranslation();+ const { playVideoSpanInPreview, reportError } = useVideoUiActions();+ const [isResolving, setIsResolving] = useState(false);+ const span = useMemo(() => videoClipSpanSeconds(clip), [clip]);+ const videoName = clip.video_name;+ const handlePlay = useCallback(() => {+ // `aria-disabled` rather than `disabled` while the lookup is in flight: disabling a+ // focused button blurs it to <body>, dropping a keyboard user out of the card mid-+ // gesture — the same hazard the reference list's move arrows carry a focus handoff+ // for. So the press has to be refused here instead of by the DOM.+ if (!span || isResolving) {+ return;+ }++ const owner = captureAccountScope();++ setIsResolving(true);+ galleryItems+ .resolve({ kind: 'video', name: videoName }, owner.signal)+ .then((item) => {+ if (item.kind === 'video' && isAccountScopeCurrent(owner)) {+ playVideoSpanInPreview({ ...span, item });+ }+ })+ .catch((error: unknown) => {+ if (isAccountScopeCurrent(owner)) {+ reportError(error instanceof Error ? error.message : String(error));+ }+ })+ .finally(() => setIsResolving(false));+ }, [isResolving, playVideoSpanInPreview, reportError, span, videoName]);++ if (!span) {+ return null;+ }++ return (+ <IconButton+ aria-busy={isResolving}+ aria-disabled={isResolving}+ aria-label={t('widgets.video.playSelection')}+ opacity={isResolving ? 0.5 : undefined}+ size="2xs"+ title={t('widgets.video.playSelection')}+ variant="ghost"+ onClick={handlePlay}+ >+ <PlayIcon size={12} />+ </IconButton>+ );+});diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsxindex dd95adc890..7685286faf 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx@@ -40,6 +40,7 @@ import { ArrowDownIcon, ArrowUpIcon, ChevronDownIcon, FilmIcon, ImagePlusIcon, Uimport { memo, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { PlayClipSpanButton } from './PlayClipSpanButton';import { TrimBoundThumb } from './TrimBoundThumb';import { useVideoUiActions } from './VideoUiContext';@@ -276,9 +277,15 @@ const ReferenceCard = memo(function ReferenceCard({return (<Box borderWidth="1px" p="2" rounded="md"><HStack align="start" gap="2">- <Badge fontVariantNumeric="tabular-nums" size="xs" variant="solid">- {index + 1}- </Badge>+ <Stack align="center" flexShrink={0} gap="1">+ <Badge fontVariantNumeric="tabular-nums" size="xs" variant="solid">+ {index + 1}+ </Badge>+ {/* Leading the card, left of every thumbnail it shows: plays what the trim+ below actually selected, which the two still bounds cannot convey — and for+ an audio reference, whose frames are a drawing of the sound, nothing can. */}+ {reference.kind === 'video' ? <PlayClipSpanButton clip={reference.clip} /> : null}+ </Stack>{reference.kind === 'image' ? (<Box bg="blackAlpha.300" flexShrink={0} h="12" overflow="hidden" rounded="sm" w="16"><Image alt="" fit="cover" h="100%" src={galleryImageUrls.thumbnail(name)} w="100%" />diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsxindex de197cd281..bfb13836cb 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx@@ -23,6 +23,7 @@ import { ChevronDownIcon, FilmIcon, UploadIcon, XIcon } from 'lucide-react';import { memo, useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { PlayClipSpanButton } from './PlayClipSpanButton';import { TrimBoundThumb } from './TrimBoundThumb';import { useVideoUiActions } from './VideoUiContext';@@ -310,48 +311,53 @@ export const VideoSourceClipField = memo(</Text>) : null}<Field helpText={t('widgets.video.trimHelp')} label={t('widgets.video.trim')}>- <Stack gap="1" w="full">- <HStack gap="2">- <TrimBoundThumb- fps={sourceVideo.fps}- frame={sourceVideo.startFrame}- label={t('widgets.video.trimStartShort')}- src={previewSrc}- />- <Box flex="1" minW="0">- <SliderNumberField- ariaLabel={t('widgets.video.trimStart')}- disabled={disabled}- max={maxFrameIndex}- min={0}- showStepper- step={1}- value={sourceVideo.startFrame}- onChange={setStartFrame}+ {/* The play button leads both bound rows rather than sitting in one of+ them: it plays the range they bracket, not either edge. */}+ <HStack align="center" gap="2" w="full">+ <PlayClipSpanButton clip={sourceVideo} />+ <Stack flex="1" gap="1" minW="0">+ <HStack gap="2">+ <TrimBoundThumb+ fps={sourceVideo.fps}+ frame={sourceVideo.startFrame}+ label={t('widgets.video.trimStartShort')}+ src={previewSrc}/>- </Box>- </HStack>- <HStack gap="2">- <TrimBoundThumb- fps={sourceVideo.fps}- frame={sourceVideo.endFrame}- label={t('widgets.video.trimEndShort')}- src={previewSrc}- />- <Box flex="1" minW="0">- <SliderNumberField- ariaLabel={t('widgets.video.trimEnd')}- disabled={disabled}- max={maxFrameIndex}- min={0}- showStepper- step={1}- value={sourceVideo.endFrame}- onChange={setEndFrame}+ <Box flex="1" minW="0">+ <SliderNumberField+ ariaLabel={t('widgets.video.trimStart')}+ disabled={disabled}+ max={maxFrameIndex}+ min={0}+ showStepper+ step={1}+ value={sourceVideo.startFrame}+ onChange={setStartFrame}+ />+ </Box>+ </HStack>+ <HStack gap="2">+ <TrimBoundThumb+ fps={sourceVideo.fps}+ frame={sourceVideo.endFrame}+ label={t('widgets.video.trimEndShort')}+ src={previewSrc}/>- </Box>- </HStack>- </Stack>+ <Box flex="1" minW="0">+ <SliderNumberField+ ariaLabel={t('widgets.video.trimEnd')}+ disabled={disabled}+ max={maxFrameIndex}+ min={0}+ showStepper+ step={1}+ value={sourceVideo.endFrame}+ onChange={setEndFrame}+ />+ </Box>+ </HStack>+ </Stack>+ </HStack></Field><HStack justify="end"><Button disabled={isLoading} size="xs" variant="ghost" onClick={handleClear}>diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsxindex e00b50f810..d00355e5b6 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx@@ -1,3 +1,4 @@+import type { GalleryVideoItem } from '@features/gallery';import type { VideoWidgetValues } from '@features/video/core/types';import type { ReactNode } from 'react';@@ -15,6 +16,13 @@ export interface VideoUiAdapter {*/getUploadBoardId(): string;patchValues(values: Partial<VideoWidgetValues>, origin?: 'user' | 'system'): void;+ /**+ * Show `item` in the Preview widget and loop the given window of it — how the+ * panel's play buttons let a trim be judged before it is generated against.+ * Selecting the item is part of the gesture: Preview shows the gallery+ * selection, and the panel has no other way to put a clip in front of it.+ */+ playVideoSpanInPreview(span: { endSeconds: number; item: GalleryVideoItem; startSeconds: number }): void;projectId: string;rawValues: Record<string, unknown>;reportError(message: string): void;@@ -25,7 +33,7 @@ export interface VideoUiAdapter {/** The adapter's callbacks, which are stable for the lifetime of a project. */export type VideoUiActions = Pick<VideoUiAdapter,- 'getUploadBoardId' | 'patchValues' | 'reportError' | 'touchGalleryImages'+ 'getUploadBoardId' | 'patchValues' | 'playVideoSpanInPreview' | 'reportError' | 'touchGalleryImages'>;const VideoUiContext = createContext<VideoUiAdapter | null>(null);@@ -38,10 +46,10 @@ const VideoUiContext = createContext<VideoUiAdapter | null>(null);const VideoUiActionsContext = createContext<VideoUiActions | null>(null);export const VideoUiProvider = ({ adapter, children }: { adapter: VideoUiAdapter; children: ReactNode }) => {- const { getUploadBoardId, patchValues, reportError, touchGalleryImages } = adapter;+ const { getUploadBoardId, patchValues, playVideoSpanInPreview, reportError, touchGalleryImages } = adapter;const actions = useMemo<VideoUiActions>(- () => ({ getUploadBoardId, patchValues, reportError, touchGalleryImages }),- [getUploadBoardId, patchValues, reportError, touchGalleryImages]+ () => ({ getUploadBoardId, patchValues, playVideoSpanInPreview, reportError, touchGalleryImages }),+ [getUploadBoardId, patchValues, playVideoSpanInPreview, reportError, touchGalleryImages]);return (diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoReferencePlaySpan.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoReferencePlaySpan.browser.test.tsxnew file mode 100644index 0000000000..18a2fee4a1--- /dev/null+++ b/invokeai/frontend/webv2/src/features/video/ui/videoReferencePlaySpan.browser.test.tsx@@ -0,0 +1,268 @@+import type { GalleryVideoItem } from '@features/gallery';+import type { VideoReferenceItem, VideoSourceClip } from '@features/video/core/types';++import { ChakraProvider } from '@chakra-ui/react';+import { DndContext } from '@dnd-kit/core';+import { system } from '@theme/system';+import i18next from 'i18next';+import { act, useCallback, useState, 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 { VideoReferenceListField } from './VideoReferenceListField';+import { VideoSourceClipField } from './VideoSourceClipField';+import { VideoUiProvider, type VideoUiAdapter } from './VideoUiContext';++/**+ * The trim rows show two still frames, which cannot say what is between them — and for an+ * audio reference, whose frames are a drawing of the sound, say nothing at all. The play+ * button is the panel's answer, and what it has to get right is the arithmetic: the trim+ * is inclusive frame indices, Preview wants seconds.+ */++const galleryMocks = vi.hoisted(() => ({ resolve: vi.fn() }));++vi.mock('@features/gallery', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ galleryItems: { resolve: galleryMocks.resolve },+}));++const i18n = i18next.createInstance();+await i18n.use(initReactI18next).init({+ fallbackLng: 'en',+ lng: 'en',+ resources: {+ en: {+ translation: {+ widgets: {+ gallery: { picker: { dropHint: 'Drop', upload: 'Upload' } },+ video: {+ addReference: 'Add reference',+ chooseReference: 'Choose from Gallery',+ moveReferenceDown: 'Move reference down',+ moveReferenceUp: 'Move reference up',+ playSelection: 'Play selection in Preview',+ referenceConditioningVideo: 'Video only',+ referenceConditioningVideoAudio: 'Video + audio',+ referenceDetailMatch: 'Match generation size',+ referenceDetailMax: 'Max detail',+ initialVideoBlocked: 'blocked',+ referencesHelp: 'help',+ removeReference: 'Remove reference',+ sampleLength: 'Sample Length',+ removeClip: 'Remove video',+ trim: 'Trim',+ trimEnd: 'End Frame',+ trimEndShort: 'End',+ trimHelp: 'help',+ trimStart: 'Start Frame',+ trimStartShort: 'Start',+ uploadImageReference: 'Upload image',+ uploadVideoReference: 'Upload video',+ },+ },+ },+ },+ },+});++let host: HTMLDivElement;+let root: Root;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const playVideoSpanInPreview = vi.fn();+const reportError = vi.fn();++const adapter = {+ getUploadBoardId: () => 'none',+ patchValues: vi.fn(),+ playVideoSpanInPreview,+ reportError,+ touchGalleryImages: vi.fn(),+} as unknown as VideoUiAdapter;++const galleryVideoItem = {+ kind: 'video',+ name: 'clip.mp4',+} as unknown as GalleryVideoItem;++const clip = (overrides: Partial<VideoSourceClip> = {}): VideoSourceClip => ({+ endFrame: 47,+ fps: 16,+ height: 480,+ numFrames: 200,+ startFrame: 32,+ video_name: 'clip.mp4',+ width: 832,+ ...overrides,+});++const videoReference = (overrides: Partial<VideoSourceClip> = {}): VideoReferenceItem => ({+ clip: clip(overrides),+ conditioning: 'video_audio',+ kind: 'video',+});++const imageReference: VideoReferenceItem = {+ detail: 'match',+ image: { height: 512, image_name: 'still.png', width: 512 },+ kind: 'image',+};++const Harness = ({ initial }: { initial: VideoReferenceItem[] }) => {+ const [references, setReferences] = useState(initial);+ const handleChange = useCallback((update: (current: VideoReferenceItem[]) => VideoReferenceItem[]) => {+ setReferences((current) => update(current));+ }, []);++ return (+ <VideoReferenceListField+ maxImages={9}+ maxVideos={3}+ references={references}+ targetArea={null}+ onChange={handleChange}+ />+ );+};++const InitialVideoHarness = ({ disabled }: { disabled: boolean }) => {+ const [source, setSource] = useState<VideoSourceClip | null>(clip());++ return <VideoSourceClipField disabled={disabled} sourceVideo={source} onChange={setSource} />;+};++const renderTree = async (element: ReactNode): Promise<void> => {+ await act(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <DndContext>+ <VideoUiProvider adapter={adapter}>{element}</VideoUiProvider>+ </DndContext>+ </ChakraProvider>+ </I18nextProvider>+ )+ );+};++const render = (initial: VideoReferenceItem[]): Promise<void> => renderTree(<Harness initial={initial} />);++const playButtons = (): HTMLButtonElement[] => [+ ...document.querySelectorAll<HTMLButtonElement>('button[aria-label="Play selection in Preview"]'),+];++const deferred = <T,>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((resolvePromise) => {+ resolve = resolvePromise;+ });++ return { promise, resolve };+};++const press = async (button: HTMLButtonElement): Promise<void> => {+ await act(async () => {+ button.click();+ await Promise.resolve();+ });+};++beforeEach(() => {+ galleryMocks.resolve.mockReset().mockResolvedValue(galleryVideoItem);+ playVideoSpanInPreview.mockReset();+ reportError.mockReset();+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+});++describe('video reference span playback', () => {+ it('asks Preview for the window the trim selected, in seconds', async () => {+ await render([videoReference()]);+ const [button] = playButtons();++ expect(button).toBeDefined();+ await press(button!);++ // The lookup is cancelled with the account lifetime, like every other gallery read.+ expect(galleryMocks.resolve).toHaveBeenCalledWith(+ { kind: 'video', name: 'clip.mp4' },+ expect.any(AbortSignal) as AbortSignal+ );+ // Frames 32..47 inclusive at 16 fps: the window ends at the far edge of frame 47, so+ // the last selected frame is played rather than cut short.+ expect(playVideoSpanInPreview).toHaveBeenCalledWith({+ endSeconds: 3,+ item: galleryVideoItem,+ startSeconds: 2,+ });+ });++ it('offers the control only where there is something to play', async () => {+ // An image reference is already fully visible as its own thumbnail; there is no window+ // to audition, so the control is absent rather than dead.+ await render([imageReference]);++ expect(playButtons()).toHaveLength(0);+ });++ it("plays the Initial Video clip's window, and stays live while the field is disabled", async () => {+ // Playing changes nothing, so a clip the user can see is one they can audition — the+ // field is disabled whenever a first-frame image or a full reference stack blocks+ // EDITING it, and its trim rows stay on screen throughout.+ await renderTree(<InitialVideoHarness disabled />);+ const [button] = playButtons();++ expect(button).toBeDefined();+ await press(button!);++ expect(playVideoSpanInPreview).toHaveBeenCalledWith({ endSeconds: 3, item: galleryVideoItem, startSeconds: 2 });+ });++ it('refuses a second press without dropping keyboard focus', async () => {+ const pending = deferred<GalleryVideoItem>();+ galleryMocks.resolve.mockReturnValueOnce(pending.promise);+ await render([videoReference()]);+ const [button] = playButtons();++ button!.focus();+ await press(button!);++ // aria-disabled, never the DOM's `disabled`: disabling a focused button blurs it to+ // <body>, which would drop a keyboard user out of the card for the length of a+ // network round trip.+ expect(button?.getAttribute('aria-disabled')).toBe('true');+ expect(button?.disabled).toBe(false);+ expect(document.activeElement).toBe(button);++ await press(button!);+ expect(galleryMocks.resolve).toHaveBeenCalledTimes(1);++ await act(async () => {+ pending.resolve(galleryVideoItem);+ await Promise.resolve();+ });++ expect(playVideoSpanInPreview).toHaveBeenCalledTimes(1);+ expect(button?.getAttribute('aria-disabled')).toBe('false');+ });++ it('reports a failed lookup instead of leaving the control stuck', async () => {+ galleryMocks.resolve.mockRejectedValueOnce(new Error('clip is gone'));+ await render([videoReference()]);+ const [button] = playButtons();++ await press(button!);++ expect(reportError).toHaveBeenCalledWith('clip is gone');+ expect(playVideoSpanInPreview).not.toHaveBeenCalled();+ expect(button?.disabled).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsxindex 3d6bdaacfe..1c055c429e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx@@ -27,6 +27,12 @@ import { useTranslation } from 'react-i18next';import { PreviewCompareDropZone } from './PreviewCompareDropZone';import { FittedFrame, PreviewStage } from './PreviewStage';+import {+ consumeVideoSpanPlaybackRequest,+ getVideoSpanPlaybackRequest,+ isVideoSpanPlaybackFresh,+ subscribeVideoSpanPlaybackRequests,+} from './spanPlaybackRequest';import { usePreviewLoupe, type PreviewLoupeControls } from './usePreviewLoupe';export type PreviewMediaSource =@@ -415,6 +421,143 @@ const PreviewVideo = ({return isCurrent() ? { ok: true } : { ok: false, reason: 'stale' };}, [isItemCurrent, source.itemKey]);const isCopyAvailable = useCallback(() => isVideoFrameCopyAvailable(videoRef.current), []);+ // Span playback: the Video panel's play buttons ask Preview to loop exactly what a+ // trim selected, so the window can be watched and heard before a generation is spent+ // on it. The span lives in refs rather than state — nothing in the frame renders+ // differently while it loops, and re-rendering on each wrap would only fight the+ // player.+ const spanRef = useRef<VideoSpan | null>(null);+ // A span that arrived before the element could act on it, with the deadline it must not+ // outlive: the request channel checks freshness once, at consume time, so a span parked+ // here through a failed load or a hidden keep-alive would otherwise replay unmuted+ // minutes later when the user pressed Retry.+ const parkedSpanRef = useRef<{ expiresAt: number; span: VideoSpan } | null>(null);+ const spanFrameRef = useRef<number | null>(null);+ const seekWithinSpan = useCallback((video: HTMLVideoElement, time: number) => {+ try {+ video.currentTime = time;+ } catch {+ // Some browsers throw while the seekable range is still empty; the watch retries on+ // its next tick.+ }+ }, []);+ const stopSpanWatch = useCallback(() => {+ if (spanFrameRef.current !== null) {+ cancelAnimationFrame(spanFrameRef.current);+ spanFrameRef.current = null;+ }+ }, []);+ // `timeupdate` fires about four times a second, which overruns a two-second selection by+ // an eighth of it; a frame loop wraps within a frame while the tab is visible.+ // `timeupdate` stays as the backstop for a backgrounded tab, where+ // `requestAnimationFrame` does not run at all.+ const enforceSpan = useCallback(() => {+ const span = spanRef.current;+ const video = videoRef.current;++ if (!span || !video || video.paused || video.currentTime < span.endSeconds) {+ return;+ }++ seekWithinSpan(video, span.startSeconds);+ }, [seekWithinSpan]);+ const startSpanWatch = useCallback(() => {+ if (spanRef.current === null || spanFrameRef.current !== null) {+ return;+ }++ const tick = (): void => {+ spanFrameRef.current = null;+ enforceSpan();++ if (spanRef.current !== null && videoRef.current?.paused === false) {+ spanFrameRef.current = requestAnimationFrame(tick);+ }+ };++ spanFrameRef.current = requestAnimationFrame(tick);+ }, [enforceSpan]);+ const playSpan = useCallback(+ (span: VideoSpan, expiresAt?: number) => {+ const video = videoRef.current;++ // Before metadata there is no duration to clamp against and the element drops the+ // seek outright; below, the element is gone entirely because a hidden keep-alive+ // boundary detached the ref. Both are picked back up — by `loadedmetadata`, and by+ // the mount effect when the view comes back.+ if (!video || video.readyState < HTMLMediaElement.HAVE_METADATA) {+ // The deadline belongs to the gesture, not to this attempt: minting a fresh one on+ // every re-park would let hide/show cycles on a clip that never loads extend it+ // indefinitely, which is the one thing the deadline exists to stop.+ parkedSpanRef.current = { expiresAt: expiresAt ?? Date.now() + PARKED_SPAN_TTL_MS, span };+ return;+ }++ parkedSpanRef.current = null;+ const duration = Number.isFinite(video.duration) ? video.duration : null;+ const endSeconds = duration === null ? span.endSeconds : Math.min(span.endSeconds, duration);+ const startSeconds = Math.max(0, Math.min(span.startSeconds, endSeconds));++ // Arm on any window with room to play. The test is emptiness, NOT a minimum width:+ // the panel's own floor is two frames (`MIN_VIDEO_TRIM_FRAMES`), which is 33ms at+ // 60fps and less above that, and those tight selections are exactly the ones the two+ // still bounds convey least. A window the clamp collapsed — a clip whose real+ // duration falls short of the frame count the panel estimated, or a foreign record+ // with inverted bounds — has nowhere to wrap to, so it plays without a loop.+ spanRef.current = endSeconds > startSeconds ? { endSeconds, startSeconds } : null;+ seekWithinSpan(video, startSeconds);+ // Autoplay policy can refuse an unmuted play(). That leaves the clip parked on the+ // first selected frame with the native controls live and the loop still armed, so+ // pressing play there plays the selection rather than the whole clip.+ void video.play().catch(() => {});+ // play() resolves asynchronously, so the element can still be paused here and the+ // watch would stop after one frame; `onPlay` arms it for that case. Both paths are+ // needed — a span arriving mid-playback fires no `play` event.+ startSpanWatch();+ },+ [seekWithinSpan, startSpanWatch]+ );+ // What retires a loop is the playhead LEAVING the window, not who moved it. Asking where+ // it landed rather than marking our own seeks is what makes this survive the orderings a+ // marker cannot: a seek to where the playhead already sits fires no event at all (the+ // Initial Video's trim starts at frame 0, so that is the first press), and the+ // first-frame nudge's own seek can be delivered after a span has armed. A scrub that+ // stays inside the window is one the loop would have honoured anyway.+ const handleSpanSeeking = useCallback(() => {+ const span = spanRef.current;+ const video = videoRef.current;++ if (!video) {+ return;+ }++ if (+ span &&+ video.currentTime >= span.startSeconds - SPAN_SEEK_TOLERANCE_SECONDS &&+ video.currentTime <= span.endSeconds+ ) {+ return;+ }++ // The user took the playhead somewhere the loop was not going. They own it from here.+ spanRef.current = null;+ parkedSpanRef.current = null;+ stopSpanWatch();+ }, [stopSpanWatch]);+ // A trim can end on the clip's final frame, where the playhead reaches the window's end+ // only as the media ends: `pause` stops the watch and `enforceSpan` bails on a paused+ // element, so whether the last `timeupdate` wrapped first was down to the browser.+ const handleSpanEnded = useCallback(() => {+ const span = spanRef.current;+ const video = videoRef.current;++ if (!span || !video) {+ return;+ }++ seekWithinSpan(video, span.startSeconds);+ void video.play().catch(() => {});+ }, [seekWithinSpan]);// Playback must not outlive this view being on screen. A widget the shell// keeps mounted behind a layout switch is hidden with `display: none`, which// does not stop media — the clip would keep running, with audio, behind a@@ -422,10 +565,48 @@ const PreviewVideo = ({// torn down whenever the subtree stops being shown, whether that is a real// unmount or a hidden keep-alive boundary, so pausing here covers both without// this component needing to know which one happened.+ //+ // The span subscription rides along: this element is keyed by `source.itemKey`, so+ // the key it filters requests by is fixed for the mount, and a request published+ // while Preview was closed is waiting to be read on the first pass.useMountEffect(() => {const video = videoRef.current;+ const itemKey = source.itemKey;+ const consumeSpanRequest = (): void => {+ const request = getVideoSpanPlaybackRequest();++ if (!request || request.itemKey !== itemKey) {+ return;+ }++ // Retired whether or not it is still honourable, so a request the user has moved on+ // from cannot wait around for the next player that shows this clip.+ consumeVideoSpanPlaybackRequest(request.token);++ if (isVideoSpanPlaybackFresh(request.requestedAt)) {+ playSpan({ endSeconds: request.endSeconds, startSeconds: request.startSeconds });+ }+ };+ // A span parked while the element was detached — the view was hidden mid-load — has+ // no second `loadedmetadata` coming once the clip finished loading behind the hidden+ // boundary, so coming back on screen is the only chance left to honour it.+ const parked = parkedSpanRef.current;++ if (parked) {+ parkedSpanRef.current = null;++ if (Date.now() <= parked.expiresAt) {+ playSpan(parked.span, parked.expiresAt);+ }+ }++ consumeSpanRequest();++ const unsubscribe = subscribeVideoSpanPlaybackRequests(consumeSpanRequest);return () => {+ unsubscribe();+ stopSpanWatch();video?.pause();};});@@ -503,10 +684,36 @@ const PreviewVideo = ({// that refires `loadedmetadata` on this element, and it has already reset the position to 0// and `paused` to true by the time the handler runs. The `currentTime` clause is// belt-and-braces for an engine that does not reset it.- const handleFirstFrameSeek = useCallback(() => {+ const handleLoadedMetadata = useCallback(() => {const video = videoRef.current;+ const parked = parkedSpanRef.current;++ parkedSpanRef.current = null;++ // A span the element could not act on yet, honoured only while the gesture behind it+ // is still fresh. Its own seek is the sharper version of the nudge below — it lands on+ // a frame the user asked for, and clears the show-poster flag the same way.+ if (parked && Date.now() <= parked.expiresAt) {+ playSpan(parked.span, parked.expiresAt);+ return;+ }++ if (!video) {+ return;+ }- if (!video || !video.paused || video.currentTime > 0) {+ // `load()` — protected-media recovery, or the failure overlay's Retry — rewinds the+ // clip and refires this event with the loop still armed. Putting the playhead back+ // inside the window is what keeps it scoped, and skipping the NUDGE below is what+ // keeps the loop at all: that seek is unmarked, so `seeking` reads it as the user+ // taking the playhead back and retires the span outright. Playback stays paused,+ // exactly as `load()` left it — a recovery is not a reason to start audio.+ if (spanRef.current) {+ seekWithinSpan(video, spanRef.current.startSeconds);+ return;+ }++ if (!video.paused || video.currentTime > 0) {return;}@@ -515,7 +722,7 @@ const PreviewVideo = ({} catch {// Some browsers throw if the seekable range is not populated yet; the poster stays up.}- }, []);+ }, [playSpan, seekWithinSpan]);const handleRetry = useCallback(() => {const video = videoRef.current;@@ -590,10 +797,15 @@ const PreviewVideo = ({onEmptied={publishCopyAvailability}onError={handleVideoError}onLoadedData={publishCopyAvailability}- onLoadedMetadata={handleFirstFrameSeek}+ onEnded={handleSpanEnded}+ onLoadedMetadata={handleLoadedMetadata}+ onPause={stopSpanWatch}+ onPlay={startSpanWatch}onPlaying={publishCopyAvailability}onResize={publishCopyAvailability}onSeeked={publishCopyAvailability}+ onSeeking={handleSpanSeeking}+ onTimeUpdate={enforceSpan}onWaiting={publishCopyAvailability}/>{hasFailed ? (@@ -669,6 +881,22 @@ const encodeCanvasPng = (canvas: HTMLCanvasElement): Promise<Blob | null> =>const isCanvasSecurityError = (error: unknown): boolean =>error instanceof DOMException && error.name === 'SecurityError';+/** A trimmed window of a clip, in seconds, as the Video panel's play buttons request it. */+interface VideoSpan {+ endSeconds: number;+ startSeconds: number;+}++/**+ * How far below a window's start the playhead may land and still count as inside it.+ * Engines snap a seek to a decodable point, so a wrap does not land on the exact second+ * asked for, and reading its own wrap as the user leaving would retire the loop instantly.+ */+const SPAN_SEEK_TOLERANCE_SECONDS = 0.05;++/** How long a span waits for an element that could not act on it yet. */+const PARKED_SPAN_TTL_MS = 15_000;+// Far enough from zero for browsers to treat it as a real seek, small enough that playback// still starts on frame 0 at any sane frame rate.const FIRST_FRAME_SEEK_SECONDS = 0.0001;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.tsxindex fa138df387..b5cb528a58 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx@@ -16,6 +16,11 @@ import {type PreviewVideoFrameController,type PreviewVideoFrameCopyResult,} from './PreviewFrame';+import {+ consumeVideoSpanPlaybackRequest,+ getVideoSpanPlaybackRequest,+ requestVideoSpanPlayback,+} from './spanPlaybackRequest';const identityMocks = vi.hoisted(() => ({accountEpoch: 7,@@ -131,6 +136,8 @@ beforeEach(() => {afterEach(async () => {await interact(() => root?.unmount());vi.restoreAllMocks();+ vi.useRealTimers();+ clearSpanRequest();host?.remove();host = null;root = null;@@ -190,6 +197,291 @@ describe('PreviewFrame native video arm', () => {expect(position.get()).toBe(0);});+ it('plays and loops the span a request published before the player mounted asked for', async () => {+ requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 2 });+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video);++ // Published before the mount, because the Video panel selects the clip and raises+ // Preview first: the player has to read the standing request on its first pass.+ await interact(() => video.dispatchEvent(new Event('loadedmetadata')));++ expect(playback.getTime()).toBe(2);+ expect(playback.play).toHaveBeenCalledTimes(1);+ // Retired on arrival, so the next player to show this clip does not replay it.+ expect(getVideoSpanPlaybackRequest()).toBeNull();++ await interact(() => {+ playback.setTime(4.02);+ video.dispatchEvent(new Event('timeupdate'));+ });++ expect(playback.getTime()).toBe(2);+ });++ it('applies a span published while the clip is already on screen', async () => {+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video);++ await interact(() => requestVideoSpanPlayback({ endSeconds: 7, itemKey: videoSource.itemKey, startSeconds: 5 }));++ expect(playback.getTime()).toBe(5);+ expect(playback.play).toHaveBeenCalledTimes(1);+ });++ it('clamps the span to the clip and ignores a request aimed at another item', async () => {+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video, { duration: 6 });++ await interact(() => requestVideoSpanPlayback({ endSeconds: 9, itemKey: 'video:other.mp4', startSeconds: 8 }));++ expect(playback.play).not.toHaveBeenCalled();+ // Left standing: it belongs to whichever player shows that clip, not to this one.+ expect(getVideoSpanPlaybackRequest()?.itemKey).toBe('video:other.mp4');+ clearSpanRequest();++ // A panel frame count is an estimate (duration x fps), so a window can run past the+ // clip's real end; the loop has to wrap there rather than at the requested end.+ await interact(() => requestVideoSpanPlayback({ endSeconds: 9, itemKey: videoSource.itemKey, startSeconds: 5 }));+ expect(playback.getTime()).toBe(5);++ await interact(() => {+ playback.setTime(6);+ video.dispatchEvent(new Event('timeupdate'));+ });++ expect(playback.getTime()).toBe(5);+ });++ it('drops a request the user has long since moved on from', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] });+ requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 2 });+ vi.setSystemTime(Date.now() + 60_000);++ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video);++ await interact(() => video.dispatchEvent(new Event('loadedmetadata')));++ // Preview may have been closed the whole time. Starting audio now would come out of+ // nowhere — but the request still has to be retired, not left to fire later.+ expect(playback.play).not.toHaveBeenCalled();+ expect(getVideoSpanPlaybackRequest()).toBeNull();+ expect(playback.getTime()).toBeLessThan(0.001);+ });++ it('holds a span that arrives before metadata and prefers it to the first-frame nudge', async () => {+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video, { readyState: HTMLMediaElement.HAVE_NOTHING });++ await interact(() => requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 2 }));++ // Nothing to clamp against and the element drops the seek outright before metadata.+ expect(playback.getTime()).toBe(0);+ expect(playback.play).not.toHaveBeenCalled();++ playback.setReadyState(HTMLMediaElement.HAVE_METADATA);+ await interact(() => video.dispatchEvent(new Event('loadedmetadata')));++ expect(playback.getTime()).toBe(2);+ expect(playback.play).toHaveBeenCalledTimes(1);+ });++ it('wraps on its own animation frame, without waiting for a timeupdate', async () => {+ requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 2 });+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video);++ await interact(() => video.dispatchEvent(new Event('loadedmetadata')));+ expect(playback.getTime()).toBe(2);++ // `timeupdate` fires about four times a second and would overrun this window by an+ // eighth of it; the frame loop is what keeps the wrap tight, and nothing else here+ // exercises it.+ await interact(() => playback.setTime(4.01));+ await act(async () => {+ await new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+ });++ expect(playback.getTime()).toBe(2);+ });++ it('keeps looping across a pause and a resume', async () => {+ requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 2 });+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video);++ await interact(() => video.dispatchEvent(new Event('loadedmetadata')));+ await interact(() => playback.pause());+ // Pausing to look at a frame is not handing the playhead back — only scrubbing is.+ await interact(() => void video.play());+ await interact(() => {+ playback.setTime(4.02);+ video.dispatchEvent(new Event('timeupdate'));+ });++ expect(playback.getTime()).toBe(2);+ });++ it('wraps a window that ends on the clip itself', async () => {+ requestVideoSpanPlayback({ endSeconds: 10, itemKey: videoSource.itemKey, startSeconds: 8 });+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video, { duration: 10 });++ await interact(() => video.dispatchEvent(new Event('loadedmetadata')));+ expect(playback.getTime()).toBe(8);++ // The playhead reaches this window's end only as the media ends, where `pause` has+ // already stopped the watch — without an `ended` handler whether it wrapped was down+ // to which event the browser delivered first.+ await interact(() => playback.playToEnd());++ expect(playback.getTime()).toBe(8);+ expect(playback.play).toHaveBeenCalledTimes(2);+ });++ it('keeps the window scoped across a protected-media reload', async () => {+ requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 2 });+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video);+ vi.spyOn(video, 'load').mockImplementation(() => {+ playback.reload();+ video.dispatchEvent(new Event('loadedmetadata'));+ });++ await interact(() => video.dispatchEvent(new Event('loadedmetadata')));+ expect(playback.getTime()).toBe(2);++ // A cookie refresh mid-loop rewinds the clip and refires `loadedmetadata`. The+ // first-frame poster nudge used to run there, and its unmarked seek read as the user+ // taking the playhead back — the loop was abandoned and the clip sat on frame 0.+ await interact(() => video.dispatchEvent(new Event('error')));+ await interact(() => undefined);++ // Back inside the window, and still paused, exactly as `load()` left it.+ expect(playback.getTime()).toBe(2);++ await interact(() => void video.play());+ await interact(() => {+ playback.setTime(4.02);+ video.dispatchEvent(new Event('timeupdate'));+ });++ expect(playback.getTime()).toBe(2);+ });++ it('does not replay a span parked behind a failed load once the gesture is stale', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] });+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video, { readyState: HTMLMediaElement.HAVE_NOTHING });++ await interact(() => requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 2 }));+ expect(playback.play).not.toHaveBeenCalled();++ // The request itself was consumed on arrival, so only the parked span is left to keep+ // the gesture honest — a Retry pressed ten minutes later must not start audio.+ vi.setSystemTime(Date.now() + 600_000);+ playback.setReadyState(HTMLMediaElement.HAVE_METADATA);+ await interact(() => video.dispatchEvent(new Event('loadedmetadata')));++ expect(playback.play).not.toHaveBeenCalled();+ expect(playback.getTime()).toBeLessThan(0.001);+ });++ it('still honours the user when a span seek fires no seeking event', async () => {+ // The Initial Video's trim starts at frame 0, so the very first press seeks the+ // playhead to where it already sits. A marker left standing there would swallow the+ // user's next real scrub and haul them back into the window.+ requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 0 });+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video);++ playback.setSilentSeek(true);+ await interact(() => video.dispatchEvent(new Event('loadedmetadata')));+ playback.setSilentSeek(false);++ await interact(() => playback.scrubTo(8));+ await interact(() => {+ playback.setTime(9);+ video.dispatchEvent(new Event('timeupdate'));+ });++ expect(playback.getTime()).toBe(9);+ });++ it('loops a window as tight as the panel can make one', async () => {+ // The panel's floor is two frames (`MIN_VIDEO_TRIM_FRAMES`), which at 60fps is 33ms —+ // narrower than any width threshold worth writing down, and precisely the selection+ // the two still bounds convey least. A width floor here silently played the whole+ // remainder of the clip instead, with audio.+ requestVideoSpanPlayback({ endSeconds: 2 + 2 / 60, itemKey: videoSource.itemKey, startSeconds: 2 });+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video);++ await interact(() => video.dispatchEvent(new Event('loadedmetadata')));+ await interact(() => {+ playback.setTime(2.1);+ video.dispatchEvent(new Event('timeupdate'));+ });++ expect(playback.getTime()).toBe(2);+ });++ it("does not extend a parked span's deadline by re-showing the view", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] });+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video, { readyState: HTMLMediaElement.HAVE_NOTHING });++ await interact(() => requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 2 }));++ // Hiding and re-showing re-parks the span. Its deadline belongs to the press, so a+ // clip that never loads cannot have it renewed indefinitely.+ vi.setSystemTime(Date.now() + 10_000);+ await renderVideo();+ vi.setSystemTime(Date.now() + 10_000);++ const reshown = getVideo();+ const reshownPlayback = stubSpanPlayback(reshown, { readyState: HTMLMediaElement.HAVE_METADATA });++ await interact(() => reshown.dispatchEvent(new Event('loadedmetadata')));++ expect(reshownPlayback.play).not.toHaveBeenCalled();+ expect(playback.play).not.toHaveBeenCalled();+ });++ it('hands the playhead back for good once the user scrubs', async () => {+ requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 2 });+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video);++ await interact(() => video.dispatchEvent(new Event('loadedmetadata')));+ expect(playback.getTime()).toBe(2);++ await interact(() => playback.scrubTo(8));+ await interact(() => {+ playback.setTime(9);+ video.dispatchEvent(new Event('timeupdate'));+ });++ expect(playback.getTime()).toBe(9);+ });+it('does not arm a drag or cancel wheel events from the video surface and native controls', async () => {await interact(() => {root?.render(@@ -696,6 +988,87 @@ const stubPlaybackPosition = (video: HTMLVideoElement, state: { paused?: booleanreturn { get: () => currentTime };};+/**+ * A playable stand-in for the `data:` source, whose seekable range is empty: a real+ * `currentTime` assignment clamps back to 0, and `play()` on it never enters a playing+ * state, so neither the seek nor the loop would be observable against the element itself.+ */+const stubSpanPlayback = (+ video: HTMLVideoElement,+ { duration = 10, readyState = HTMLMediaElement.HAVE_METADATA }: { duration?: number; readyState?: number } = {}+) => {+ let currentTime = 0;+ let paused = true;+ let silentSeek = false;+ let currentReadyState = readyState;++ Object.defineProperties(video, {+ currentTime: {+ configurable: true,+ get: () => currentTime,+ set: (value: number) => {+ currentTime = value;++ if (!silentSeek) {+ video.dispatchEvent(new Event('seeking'));+ }+ },+ },+ duration: { configurable: true, get: () => duration },+ paused: { configurable: true, get: () => paused },+ readyState: { configurable: true, get: () => currentReadyState },+ });++ const play = vi.spyOn(video, 'play').mockImplementation(() => {+ paused = false;+ video.dispatchEvent(new Event('play'));++ return Promise.resolve();+ });++ return {+ play,+ /** What `load()` does to the element before it refires `loadedmetadata`. */+ reload: () => {+ currentTime = 0;+ paused = true;+ silentSeek = false;+ },+ getTime: () => currentTime,+ pause: () => {+ paused = true;+ video.dispatchEvent(new Event('pause'));+ },+ playToEnd: () => {+ currentTime = duration;+ paused = true;+ video.dispatchEvent(new Event('ended'));+ },+ scrubTo: (value: number) => {+ currentTime = value;+ video.dispatchEvent(new Event('seeking'));+ },+ /** Engines fire no `seeking` for a seek the playhead cannot act on. */+ setSilentSeek: (value: boolean) => {+ silentSeek = value;+ },+ setReadyState: (value: number) => {+ currentReadyState = value;+ },+ setTime: (value: number) => {+ currentTime = value;+ },+ };+};++const clearSpanRequest = (): void => {+ const request = getVideoSpanPlaybackRequest();++ if (request) {+ consumeVideoSpanPlaybackRequest(request.token);+ }+};+const setVideoFrameState = (video: HTMLVideoElement,state: { height: number; readyState: number; width: number }diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.test.tsnew file mode 100644index 0000000000..90326345f0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.test.ts@@ -0,0 +1,75 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ consumeVideoSpanPlaybackRequest,+ getVideoSpanPlaybackRequest,+ isVideoSpanPlaybackFresh,+ requestVideoSpanPlayback,+ subscribeVideoSpanPlaybackRequests,+ VIDEO_SPAN_PLAYBACK_TTL_MS,+} from './spanPlaybackRequest';++const retireOutstandingRequest = (): void => {+ const request = getVideoSpanPlaybackRequest();++ if (request) {+ consumeVideoSpanPlaybackRequest(request.token);+ }+};++afterEach(() => {+ retireOutstandingRequest();+ vi.useRealTimers();+});++describe('video span playback requests', () => {+ it('mints a fresh token per gesture, even on an unchanged span', () => {+ const listener = vi.fn();+ const unsubscribe = subscribeVideoSpanPlaybackRequests(listener);+ const span = { endSeconds: 4, itemKey: 'video:clip.mp4', startSeconds: 2 } as const;++ requestVideoSpanPlayback(span);+ const first = getVideoSpanPlaybackRequest();++ requestVideoSpanPlayback(span);+ const second = getVideoSpanPlaybackRequest();++ expect(listener).toHaveBeenCalledTimes(2);+ expect(second).toMatchObject(span);+ // Pressing play again on a window the user has not touched must still read as a new+ // request: the player has already retired the first one.+ expect(second?.token).not.toBe(first?.token);++ unsubscribe();+ requestVideoSpanPlayback(span);+ expect(listener).toHaveBeenCalledTimes(2);+ });++ it('retires only the request the consumer actually read', () => {+ requestVideoSpanPlayback({ endSeconds: 4, itemKey: 'video:first.mp4', startSeconds: 2 });+ const stale = getVideoSpanPlaybackRequest();++ requestVideoSpanPlayback({ endSeconds: 9, itemKey: 'video:second.mp4', startSeconds: 8 });+ // A player that reads late must not clear the gesture that superseded it — pressing+ // play on a second reference while the first is still resolving is exactly that race.+ consumeVideoSpanPlaybackRequest(stale?.token ?? -1);++ expect(getVideoSpanPlaybackRequest()?.itemKey).toBe('video:second.mp4');++ consumeVideoSpanPlaybackRequest(getVideoSpanPlaybackRequest()?.token ?? -1);++ expect(getVideoSpanPlaybackRequest()).toBeNull();+ });++ it('stops vouching for a gesture the user has moved on from', () => {+ vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] });+ requestVideoSpanPlayback({ endSeconds: 4, itemKey: 'video:clip.mp4', startSeconds: 2 });+ const request = getVideoSpanPlaybackRequest();++ expect(isVideoSpanPlaybackFresh(request?.requestedAt ?? 0)).toBe(true);++ vi.setSystemTime(Date.now() + VIDEO_SPAN_PLAYBACK_TTL_MS + 1);++ expect(isVideoSpanPlaybackFresh(request?.requestedAt ?? 0)).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.tsnew file mode 100644index 0000000000..f59e120635--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.ts@@ -0,0 +1,73 @@+import type { GalleryItemKey } from '@features/gallery';++/**+ * "Play this video item from A to B, on a loop" — the gesture behind the Video panel's+ * play buttons, which ask Preview to show what a trim actually selected.+ *+ * An ephemeral intent aimed at whichever player is mounted, not a piece of state: it is+ * module-scoped so it is never replayed in a later session, and it carries a token so a+ * repeated press on an unchanged window still reads as a new request. The publisher lives+ * in App (it has to select the item and raise the widget first); the consumer is this+ * widget's `<video>` element, which is why the channel is owned here rather than beside+ * the gallery's reveal request — that one's consumer is the gallery grid itself.+ *+ * The timestamp bounds it. The publisher raises Preview before publishing, so a player+ * mounts promptly; a request read long afterwards belongs to a gesture the user has moved+ * on from, and honouring it would start unmuted audio out of nowhere.+ */++export interface VideoSpanPlaybackRequest {+ endSeconds: number;+ itemKey: GalleryItemKey;+ requestedAt: number;+ startSeconds: number;+ token: number;+}++/** How long a published span request stays honourable. */+export const VIDEO_SPAN_PLAYBACK_TTL_MS = 15_000;++let currentRequest: VideoSpanPlaybackRequest | null = null;+let nextToken = 0;++const listeners = new Set<() => void>();++const notifyListeners = (): void => {+ for (const listener of listeners) {+ listener();+ }+};++export const requestVideoSpanPlayback = (span: {+ endSeconds: number;+ itemKey: GalleryItemKey;+ startSeconds: number;+}): void => {+ nextToken += 1;+ currentRequest = { ...span, requestedAt: Date.now(), token: nextToken };+ notifyListeners();+};++export const getVideoSpanPlaybackRequest = (): VideoSpanPlaybackRequest | null => currentRequest;++/** True while `requestedAt` is recent enough to act on. */+export const isVideoSpanPlaybackFresh = (requestedAt: number): boolean =>+ Date.now() - requestedAt <= VIDEO_SPAN_PLAYBACK_TTL_MS;++/** Retires `token`, whether or not the player could act on it. A newer request is left alone. */+export const consumeVideoSpanPlaybackRequest = (token: number): void => {+ if (currentRequest?.token !== token) {+ return;+ }++ currentRequest = null;+ notifyListeners();+};++export const subscribeVideoSpanPlaybackRequests = (listener: () => void): (() => void) => {+ listeners.add(listener);++ return () => {+ listeners.delete(listener);+ };+};