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 button pauses the reference-clip loop it started
Lincoln Steinc88991da604e
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex 8ad42fbb50..6a0f4629a0 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -337,7 +337,7 @@"initialRawBytes": 2992581,"largestAssetRawBytes": 747218,"otherAssetRawBytes": 0,- "ownedRawBytes": 132915,+ "ownedRawBytes": 132994,"requestCount": 106,"scriptRequestCount": 90,"sourceOwners": [@@ -1034,7 +1034,7 @@"initialRawBytes": 3022507,"largestAssetRawBytes": 754691,"otherAssetRawBytes": 0,- "ownedRawBytes": 132915,+ "ownedRawBytes": 132994,"requestCount": 106,"scriptRequestCount": 90},diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 86d473b510..987dfd8fac 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -163,9 +163,9 @@"largestAssetRawBytes": 747209,"otherRawBytes": 152221,"requestCount": 122,- "scriptRawBytes": 3511549,+ "scriptRawBytes": 3547734,"scriptRequestCount": 117,- "totalRawBytes": 3844356+ "totalRawBytes": 3882808},"resourceLimits": {"cssRawBytes": 2181,@@ -174,9 +174,9 @@"largestAssetRawBytes": 754682,"otherRawBytes": 153744,"requestCount": 122,- "scriptRawBytes": 3546665,+ "scriptRawBytes": 3583212,"scriptRequestCount": 117,- "totalRawBytes": 3882800+ "totalRawBytes": 3921637},"routeReadyMedianMs": 427,"scriptSourceOwnerSet": "editor-minimal-static",@@ -223,9 +223,9 @@"largestAssetRawBytes": 747209,"otherRawBytes": 152221,"requestCount": 122,- "scriptRawBytes": 3511549,+ "scriptRawBytes": 3547734,"scriptRequestCount": 117,- "totalRawBytes": 3844356+ "totalRawBytes": 3882808},"resourceLimits": {"cssRawBytes": 2181,@@ -234,9 +234,9 @@"largestAssetRawBytes": 754682,"otherRawBytes": 153744,"requestCount": 122,- "scriptRawBytes": 3546665,+ "scriptRawBytes": 3583212,"scriptRequestCount": 117,- "totalRawBytes": 3882800+ "totalRawBytes": 3921637},"routeReadyMedianMs": 434.1000000014901,"scriptSourceOwnerSet": "editor-minimal-static",@@ -523,9 +523,9 @@"largestAssetRawBytes": 747209,"otherRawBytes": 152221,"requestCount": 122,- "scriptRawBytes": 3511549,+ "scriptRawBytes": 3547734,"scriptRequestCount": 117,- "totalRawBytes": 3844356+ "totalRawBytes": 3882808},"resourceLimits": {"cssRawBytes": 2181,@@ -534,9 +534,9 @@"largestAssetRawBytes": 754682,"otherRawBytes": 153744,"requestCount": 122,- "scriptRawBytes": 3546665,+ "scriptRawBytes": 3583212,"scriptRequestCount": 117,- "totalRawBytes": 3882800+ "totalRawBytes": 3921637},"routeReadyMedianMs": 1309.3999999985099,"scriptSourceOwnerSet": "editor-minimal-static",@@ -583,9 +583,9 @@"largestAssetRawBytes": 747209,"otherRawBytes": 152221,"requestCount": 122,- "scriptRawBytes": 3511549,+ "scriptRawBytes": 3547734,"scriptRequestCount": 117,- "totalRawBytes": 3844356+ "totalRawBytes": 3882808},"resourceLimits": {"cssRawBytes": 2181,@@ -594,9 +594,9 @@"largestAssetRawBytes": 754682,"otherRawBytes": 153744,"requestCount": 122,- "scriptRawBytes": 3546665,+ "scriptRawBytes": 3583212,"scriptRequestCount": 117,- "totalRawBytes": 3882800+ "totalRawBytes": 3921637},"routeReadyMedianMs": 1329.0999999940395,"scriptSourceOwnerSet": "editor-minimal-static",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 5051714d92..743ffd0637 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).",+ "pauseSelection": "Pause selection in Preview","playSelection": "Play selection in Preview","removeClip": "Remove video","sampleLength": "Sample Length (Frames)",diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsxindex 28d04e754c..3f16844d15 100644--- a/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx@@ -5,8 +5,10 @@ import type { ReactNode } from 'react';import { getGalleryRevealRequest } from '@features/gallery/core/selection';import {+ clearVideoSpanPlaybackState,consumeVideoSpanPlaybackRequest,getVideoSpanPlaybackRequest,+ publishVideoSpanPlaybackState,} from '@workbench/widgets/preview/spanPlaybackRequest';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -84,11 +86,32 @@ afterEach(async () => {}});+describe('videoSpanPlayback', () => {+ it("hands the panel the player's report and its changes", () => {+ const listener = vi.fn();+ const unsubscribe = adapter.videoSpanPlayback.subscribe(listener);+ const pause = vi.fn();++ expect(adapter.videoSpanPlayback.getState()).toBeNull();++ publishVideoSpanPlaybackState({ isPlaying: true, pause, token: 41 });++ expect(listener).toHaveBeenCalledTimes(1);+ expect(adapter.videoSpanPlayback.getState()).toMatchObject({ isPlaying: true, token: 41 });++ unsubscribe();+ clearVideoSpanPlaybackState(41);+ });+});+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));+ let token: number | null = null;+ act(() => {+ token = adapter.playVideoSpanInPreview(span);+ });expect(selectItem).toHaveBeenCalledWith(videoItem, 'project-1');expect(getVideoSpanPlaybackRequest()).toMatchObject({@@ -96,6 +119,8 @@ describe('playVideoSpanInPreview', () => {itemKey: 'video:clip.mp4',startSeconds: 2,});+ // The button keeps the token to recognise the player's report on this request.+ expect(token).toBe(getVideoSpanPlaybackRequest()?.token);// 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.@@ -105,13 +130,18 @@ describe('playVideoSpanInPreview', () => {it('changes nothing at all when Preview refuses to open', () => {openResult = { ok: false, reason: 'unavailable' };- act(() => adapter.playVideoSpanInPreview(span));+ let token: number | null = 0;+ act(() => {+ token = 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();+ // Nothing was asked, so there is no report to wait for.+ expect(token).toBeNull();});it('drops a press whose lookup landed after the user switched projects', async () => {diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsxindex 959d632d84..8c161949ad 100644--- a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx@@ -7,7 +7,11 @@ 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 {+ getVideoSpanPlaybackState,+ requestVideoSpanPlayback,+ subscribeVideoSpanPlaybackState,+} from '@workbench/widgets/preview/spanPlaybackRequest';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { useCallback, useEffect, useMemo, useRef } from 'react';@@ -85,15 +89,16 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>// 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;+ return null;}if (!openWorkbenchWidget('preview', { preferredRegions: ['center'], requireCenterView: true }).ok) {- return;+ return null;}commands.gallery.selectItem(item, projectId);- requestVideoSpanPlayback({ endSeconds, itemKey: toGalleryItemKey(item), startSeconds });++ return requestVideoSpanPlayback({ endSeconds, itemKey: toGalleryItemKey(item), startSeconds });},[commands, openWorkbenchWidget, projectId]);@@ -107,6 +112,7 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>reportError,showPromptSyntaxHighlighting,touchGalleryImages,+ videoSpanPlayback: VIDEO_SPAN_PLAYBACK_PORT,}),[getUploadBoardId,@@ -121,3 +127,10 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>return <VideoUiProvider adapter={adapter}>{children}</VideoUiProvider>;};++// The player's report is module-scoped in the Preview widget, so the port is one constant+// object: subscribing to it never re-renders on a project switch.+const VIDEO_SPAN_PLAYBACK_PORT: VideoUiAdapter['videoSpanPlayback'] = {+ getState: getVideoSpanPlaybackState,+ subscribe: subscribeVideoSpanPlaybackState,+};diff --git a/invokeai/frontend/webv2/src/features/video/index.ts b/invokeai/frontend/webv2/src/features/video/index.tsindex 266d7b99b6..7f3eaa9686 100644--- a/invokeai/frontend/webv2/src/features/video/index.ts+++ b/invokeai/frontend/webv2/src/features/video/index.ts@@ -105,4 +105,11 @@ export {resolveVideoSeed,syncVideoWidgetValuesWithModels,} from './core/widgetValues';-export { VideoUiProvider, useVideoUi, useVideoUiActions, type VideoUiAdapter } from './ui/VideoUiContext';+export {+ VideoUiProvider,+ useVideoUi,+ useVideoUiActions,+ type VideoSpanPlaybackPort,+ type VideoSpanPlaybackState,+ type VideoUiAdapter,+} from './ui/VideoUiContext';diff --git a/invokeai/frontend/webv2/src/features/video/ui/PlayClipSpanButton.tsx b/invokeai/frontend/webv2/src/features/video/ui/PlayClipSpanButton.tsxindex 0404fdd1de..6056f4187f 100644--- a/invokeai/frontend/webv2/src/features/video/ui/PlayClipSpanButton.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/PlayClipSpanButton.tsx@@ -4,20 +4,28 @@ 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 { PauseIcon, PlayIcon } from 'lucide-react';+import { memo, useCallback, useMemo, useState, useSyncExternalStore } from 'react';import { useTranslation } from 'react-i18next';import { useVideoUiActions } from './VideoUiContext';/**- * Plays a clip's trimmed window in the Preview widget, looping it.+ * Plays a clip's trimmed window in the Preview widget, looping it — and, while that loop+ * is the one running, offers to stop 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.*+ * The button is a pause control only for its own loop: the player reports under the token+ * of the request it honoured, so a sibling card playing the same clip, or a native play of+ * something else, leaves this one offering play. Pausing leaves the window armed in the+ * player (the native play control resumes the selection), but the NEXT press here is a+ * fresh request rather than a resume — the trim can have moved in between, and the press+ * has to play what the rows now show, from its start.+ ** 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,@@ -28,11 +36,19 @@ import { useVideoUiActions } from './VideoUiContext';export const PlayClipSpanButton = memo(function PlayClipSpanButton({ clip }: { clip: VideoSourceClip }) {const { t } = useTranslation();- const { playVideoSpanInPreview, reportError } = useVideoUiActions();+ const { playVideoSpanInPreview, reportError, videoSpanPlayback } = useVideoUiActions();const [isResolving, setIsResolving] = useState(false);+ // The token of this button's last request; what the player's report is matched against.+ const [requestToken, setRequestToken] = useState<number | null>(null);+ const playback = useSyncExternalStore(+ videoSpanPlayback.subscribe,+ videoSpanPlayback.getState,+ videoSpanPlayback.getState+ );+ const isPlaying = playback !== null && playback.token === requestToken && playback.isPlaying;const span = useMemo(() => videoClipSpanSeconds(clip), [clip]);const videoName = clip.video_name;- const handlePlay = useCallback(() => {+ const handlePress = 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@@ -41,6 +57,11 @@ export const PlayClipSpanButton = memo(function PlayClipSpanButton({ clip }: { creturn;}+ if (isPlaying) {+ playback.pause();+ return;+ }+const owner = captureAccountScope();setIsResolving(true);@@ -48,7 +69,13 @@ export const PlayClipSpanButton = memo(function PlayClipSpanButton({ clip }: { c.resolve({ kind: 'video', name: videoName }, owner.signal).then((item) => {if (item.kind === 'video' && isAccountScopeCurrent(owner)) {- playVideoSpanInPreview({ ...span, item });+ const token = playVideoSpanInPreview({ ...span, item });++ // A refusal (Preview could not be raised) asked nothing of the player, so the+ // loop this button last started — paused, still armed — stays its own to stop.+ if (token !== null) {+ setRequestToken(token);+ }}}).catch((error: unknown) => {@@ -57,24 +84,26 @@ export const PlayClipSpanButton = memo(function PlayClipSpanButton({ clip }: { c}}).finally(() => setIsResolving(false));- }, [isResolving, playVideoSpanInPreview, reportError, span, videoName]);+ }, [isPlaying, isResolving, playVideoSpanInPreview, playback, reportError, span, videoName]);if (!span) {return null;}+ const label = isPlaying ? t('widgets.video.pauseSelection') : t('widgets.video.playSelection');+return (<IconButtonaria-busy={isResolving}aria-disabled={isResolving}- aria-label={t('widgets.video.playSelection')}+ aria-label={label}opacity={isResolving ? 0.5 : undefined}size="2xs"- title={t('widgets.video.playSelection')}+ title={label}variant="ghost"- onClick={handlePlay}+ onClick={handlePress}>- <PlayIcon size={12} />+ {isPlaying ? <PauseIcon size={12} /> : <PlayIcon size={12} />}</IconButton>);});diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsxindex d00355e5b6..aeeb656f7b 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx@@ -21,19 +21,49 @@ export interface VideoUiAdapter {* 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.+ *+ * Returns the request's token, which `videoSpanPlayback` reports under once+ * the player has the loop running; `null` when Preview could not be raised+ * and nothing was asked of it.*/- playVideoSpanInPreview(span: { endSeconds: number; item: GalleryVideoItem; startSeconds: number }): void;+ playVideoSpanInPreview(span: { endSeconds: number; item: GalleryVideoItem; startSeconds: number }): number | null;projectId: string;rawValues: Record<string, unknown>;reportError(message: string): void;showPromptSyntaxHighlighting: boolean;touchGalleryImages(): void;+ /** What Preview is doing with the last span it was asked to play, for the button that asked. */+ videoSpanPlayback: VideoSpanPlaybackPort;+}++/**+ * The player's side of a span request: reported under the request's token, so a button+ * can tell its own loop from a sibling card's, and gone (`null`) once nothing is armed —+ * the user scrubbed out of the window, a newer request took over, or the player left the+ * screen. `isPlaying` tracks the element itself, so a native pause shows in the panel+ * too; `pause` stops the element and leaves the loop armed, so a native play resumes the+ * selection rather than the whole clip.+ */+export interface VideoSpanPlaybackState {+ isPlaying: boolean;+ pause(): void;+ token: number;+}++export interface VideoSpanPlaybackPort {+ getState(): VideoSpanPlaybackState | null;+ subscribe(listener: () => void): () => void;}/** The adapter's callbacks, which are stable for the lifetime of a project. */export type VideoUiActions = Pick<VideoUiAdapter,- 'getUploadBoardId' | 'patchValues' | 'playVideoSpanInPreview' | 'reportError' | 'touchGalleryImages'+ | 'getUploadBoardId'+ | 'patchValues'+ | 'playVideoSpanInPreview'+ | 'reportError'+ | 'touchGalleryImages'+ | 'videoSpanPlayback'>;const VideoUiContext = createContext<VideoUiAdapter | null>(null);@@ -46,10 +76,18 @@ const VideoUiContext = createContext<VideoUiAdapter | null>(null);const VideoUiActionsContext = createContext<VideoUiActions | null>(null);export const VideoUiProvider = ({ adapter, children }: { adapter: VideoUiAdapter; children: ReactNode }) => {- const { getUploadBoardId, patchValues, playVideoSpanInPreview, reportError, touchGalleryImages } = adapter;+ const { getUploadBoardId, patchValues, playVideoSpanInPreview, reportError, touchGalleryImages, videoSpanPlayback } =+ adapter;const actions = useMemo<VideoUiActions>(- () => ({ getUploadBoardId, patchValues, playVideoSpanInPreview, reportError, touchGalleryImages }),- [getUploadBoardId, patchValues, playVideoSpanInPreview, reportError, touchGalleryImages]+ () => ({+ getUploadBoardId,+ patchValues,+ playVideoSpanInPreview,+ reportError,+ touchGalleryImages,+ videoSpanPlayback,+ }),+ [getUploadBoardId, patchValues, playVideoSpanInPreview, reportError, touchGalleryImages, videoSpanPlayback]);return (diff --git a/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsxindex 91b22c0014..631ebaaa41 100644--- a/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx@@ -59,12 +59,13 @@ const videoItem = (mediaOrigin?: string): GalleryVideoItem => ({const adapter = {getUploadBoardId: () => 'none',patchValues: (_values: Partial<VideoWidgetValues>) => undefined,- playVideoSpanInPreview: () => undefined,+ playVideoSpanInPreview: () => null,projectId: 'project-1',rawValues: {},reportError: () => undefined,showPromptSyntaxHighlighting: false,touchGalleryImages: () => undefined,+ videoSpanPlayback: { getState: () => null, subscribe: () => () => undefined },};const NO_REFERENCES: VideoReferenceItem[] = [];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.tsxindex 18a2fee4a1..6994f8a4f2 100644--- a/invokeai/frontend/webv2/src/features/video/ui/videoReferencePlaySpan.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/videoReferencePlaySpan.browser.test.tsx@@ -5,14 +5,14 @@ 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 { act, useCallback, useEffect, 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';+import { VideoUiProvider, type VideoSpanPlaybackState, type VideoUiAdapter } from './VideoUiContext';/*** The trim rows show two still frames, which cannot say what is between them — and for an@@ -42,6 +42,7 @@ await i18n.use(initReactI18next).init({chooseReference: 'Choose from Gallery',moveReferenceDown: 'Move reference down',moveReferenceUp: 'Move reference up',+ pauseSelection: 'Pause selection in Preview',playSelection: 'Play selection in Preview',referenceConditioningVideo: 'Video only',referenceConditioningVideoAudio: 'Video + audio',@@ -71,15 +72,39 @@ 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 playVideoSpanInPreview = vi.fn<VideoUiAdapter['playVideoSpanInPreview']>();const reportError = vi.fn();+/** A stand-in for the Preview player's report, driven by the test. */+let playbackState: VideoSpanPlaybackState | null = null;+const playbackListeners = new Set<() => void>();+const reportPlayback = (state: VideoSpanPlaybackState | null): void => {+ playbackState = state;++ for (const listener of playbackListeners) {+ listener();+ }+};+const pausePlayback = vi.fn(() => {+ if (playbackState) {+ reportPlayback({ ...playbackState, isPlaying: false });+ }+});+const adapter = {getUploadBoardId: () => 'none',patchValues: vi.fn(),playVideoSpanInPreview,reportError,touchGalleryImages: vi.fn(),+ videoSpanPlayback: {+ getState: () => playbackState,+ subscribe: (listener: () => void) => {+ playbackListeners.add(listener);++ return () => playbackListeners.delete(listener);+ },+ },} as unknown as VideoUiAdapter;const galleryVideoItem = {@@ -133,6 +158,36 @@ const InitialVideoHarness = ({ disabled }: { disabled: boolean }) => {return <VideoSourceClipField disabled={disabled} sourceVideo={source} onChange={setSource} />;};+/** The reference list with its trim reachable from the test, as a slider drag would move it. */+let retrim: ((update: Partial<VideoSourceClip>) => void) | null = null;++const RetrimmableHarness = () => {+ const [references, setReferences] = useState<VideoReferenceItem[]>([videoReference()]);+ const handleChange = useCallback((update: (current: VideoReferenceItem[]) => VideoReferenceItem[]) => {+ setReferences((current) => update(current));+ }, []);++ useEffect(() => {+ retrim = (update) => {+ setReferences((current) =>+ current.map((reference) =>+ reference.kind === 'video' ? { ...reference, clip: { ...reference.clip, ...update } } : reference+ )+ );+ };+ }, []);++ return (+ <VideoReferenceListField+ maxImages={9}+ maxVideos={3}+ references={references}+ targetArea={null}+ onChange={handleChange}+ />+ );+};+const renderTree = async (element: ReactNode): Promise<void> => {await act(() =>root.render(@@ -153,6 +208,10 @@ const playButtons = (): HTMLButtonElement[] => [...document.querySelectorAll<HTMLButtonElement>('button[aria-label="Play selection in Preview"]'),];+const pauseButtons = (): HTMLButtonElement[] => [+ ...document.querySelectorAll<HTMLButtonElement>('button[aria-label="Pause selection in Preview"]'),+];+const deferred = <T,>() => {let resolve!: (value: T) => void;const promise = new Promise<T>((resolvePromise) => {@@ -171,8 +230,11 @@ const press = async (button: HTMLButtonElement): Promise<void> => {beforeEach(() => {galleryMocks.resolve.mockReset().mockResolvedValue(galleryVideoItem);- playVideoSpanInPreview.mockReset();+ playVideoSpanInPreview.mockReset().mockReturnValue(7);reportError.mockReset();+ pausePlayback.mockClear();+ playbackState = null;+ retrim = null;host = document.createElement('div');document.body.append(host);root = createRoot(host);@@ -254,6 +316,100 @@ describe('video reference span playback', () => {expect(button?.getAttribute('aria-disabled')).toBe('false');});+ it('turns into a pause control only for the loop it started, and stops it', async () => {+ await render([videoReference(), videoReference({ startFrame: 0, endFrame: 15 })]);+ const [first, second] = playButtons();++ // The player reporting on somebody else's request — a loop the sibling card started,+ // or one from before this session — is not this button's to stop.+ await act(() => reportPlayback({ isPlaying: true, pause: pausePlayback, token: 3 }));+ expect(pauseButtons()).toHaveLength(0);++ await press(first!);+ expect(playVideoSpanInPreview).toHaveBeenCalledTimes(1);++ // Preview has the loop running: this card offers to stop it, its sibling still to play.+ await act(() => reportPlayback({ isPlaying: true, pause: pausePlayback, token: 7 }));+ expect(pauseButtons()).toEqual([first]);+ expect(playButtons()).toEqual([second]);++ await press(first!);++ // A stop, not another request: the clip pauses where it is.+ expect(pausePlayback).toHaveBeenCalledTimes(1);+ expect(playVideoSpanInPreview).toHaveBeenCalledTimes(1);+ expect(galleryMocks.resolve).toHaveBeenCalledTimes(1);+ expect(pauseButtons()).toHaveLength(0);+ expect(playButtons()).toEqual([first, second]);+ });++ it('plays the trim as it now stands when pressed again after a pause', async () => {+ await renderTree(<RetrimmableHarness />);+ const [button] = playButtons();++ await press(button!);+ await act(() => reportPlayback({ isPlaying: true, pause: pausePlayback, token: 7 }));+ await press(button!);+ expect(pausePlayback).toHaveBeenCalledTimes(1);++ // The user moved the window while it sat paused. The next press is a fresh request for+ // the window the rows now show — from its start — not a resume of the old one.+ playVideoSpanInPreview.mockReturnValue(8);+ await act(() => retrim?.({ endFrame: 79, startFrame: 64 }));+ await press(button!);++ expect(playVideoSpanInPreview).toHaveBeenCalledTimes(2);+ expect(playVideoSpanInPreview).toHaveBeenLastCalledWith({ endSeconds: 5, item: galleryVideoItem, startSeconds: 4 });++ // And it is the new request's report the button now answers to.+ await act(() => reportPlayback({ isPlaying: true, pause: pausePlayback, token: 7 }));+ expect(pauseButtons()).toHaveLength(0);+ await act(() => reportPlayback({ isPlaying: true, pause: pausePlayback, token: 8 }));+ expect(pauseButtons()).toEqual([button]);+ });++ it('keeps its paused loop when a fresh press is refused', async () => {+ await render([videoReference()]);+ const [button] = playButtons();++ await press(button!);+ await act(() => reportPlayback({ isPlaying: true, pause: pausePlayback, token: 7 }));+ await press(button!);+ expect(pauseButtons()).toHaveLength(0);++ // Preview could not be raised for the re-press (no center view after a layout change):+ // nothing was asked of the player, whose loop is still armed under the first request.+ // A native play resumes that loop, and it is still this button's to stop.+ playVideoSpanInPreview.mockReturnValueOnce(null);+ await press(button!);+ expect(playVideoSpanInPreview).toHaveBeenCalledTimes(2);++ await act(() => reportPlayback({ isPlaying: true, pause: pausePlayback, token: 7 }));+ expect(pauseButtons()).toEqual([button]);+ });++ it('follows the player when the loop is stopped or lost elsewhere', async () => {+ await render([videoReference()]);+ const [button] = playButtons();++ await press(button!);+ await act(() => reportPlayback({ isPlaying: true, pause: pausePlayback, token: 7 }));+ expect(pauseButtons()).toEqual([button]);++ // A pause from the native controls shows here too: the selection is not playing.+ await act(() => reportPlayback({ isPlaying: false, pause: pausePlayback, token: 7 }));+ expect(pauseButtons()).toHaveLength(0);++ // A native play resumes it, and this is still the loop that button started.+ await act(() => reportPlayback({ isPlaying: true, pause: pausePlayback, token: 7 }));+ expect(pauseButtons()).toEqual([button]);++ // The user scrubbed out, or Preview closed: nothing left to stop.+ await act(() => reportPlayback(null));+ expect(pauseButtons()).toHaveLength(0);+ expect(playButtons()).toEqual([button]);+ });+it('reports a failed lookup instead of leaving the control stuck', async () => {galleryMocks.resolve.mockRejectedValueOnce(new Error('clip is gone'));await render([videoReference()]);diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoReferencePromptLabels.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoReferencePromptLabels.browser.test.tsxindex 8cbe8339e3..987d9c9ea9 100644--- a/invokeai/frontend/webv2/src/features/video/ui/videoReferencePromptLabels.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/videoReferencePromptLabels.browser.test.tsx@@ -66,6 +66,7 @@ const adapter = {playVideoSpanInPreview: vi.fn(),reportError: vi.fn(),touchGalleryImages: vi.fn(),+ videoSpanPlayback: { getState: () => null, subscribe: () => () => undefined },} as unknown as VideoUiAdapter;const imageReference = (name: string): VideoReferenceItem => ({diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoReferenceReorderFocus.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoReferenceReorderFocus.browser.test.tsxindex 777a9a32c9..3c40711724 100644--- a/invokeai/frontend/webv2/src/features/video/ui/videoReferenceReorderFocus.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/videoReferenceReorderFocus.browser.test.tsx@@ -56,6 +56,7 @@ const adapter = {patchValues: vi.fn(),reportError: vi.fn(),touchGalleryImages: vi.fn(),+ videoSpanPlayback: { getState: () => null, subscribe: () => () => undefined },} as unknown as VideoUiAdapter;const imageReference = (name: string): VideoReferenceItem => ({diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsxindex 1c055c429e..8c9296f75b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx@@ -28,9 +28,11 @@ import { useTranslation } from 'react-i18next';import { PreviewCompareDropZone } from './PreviewCompareDropZone';import { FittedFrame, PreviewStage } from './PreviewStage';import {+ clearVideoSpanPlaybackState,consumeVideoSpanPlaybackRequest,getVideoSpanPlaybackRequest,isVideoSpanPlaybackFresh,+ publishVideoSpanPlaybackState,subscribeVideoSpanPlaybackRequests,} from './spanPlaybackRequest';import { usePreviewLoupe, type PreviewLoupeControls } from './usePreviewLoupe';@@ -431,8 +433,13 @@ const PreviewVideo = ({// 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 parkedSpanRef = useRef<{ expiresAt: number; span: VideoSpan; token: number } | null>(null);const spanFrameRef = useRef<number | null>(null);+ // The request behind the loop on screen, reported back so the button that made it can+ // offer to stop it. Outlives a pause (the loop stays armed, so a native play resumes the+ // selection under the same request) and a hide (same reason); retired only when the user+ // takes the playhead out of the window or a newer request replaces it.+ const spanTokenRef = useRef<number | null>(null);const seekWithinSpan = useCallback((video: HTMLVideoElement, time: number) => {try {video.currentTime = time;@@ -447,6 +454,31 @@ const PreviewVideo = ({spanFrameRef.current = null;}}, []);+ const pauseSpanPlayback = useCallback(() => {+ videoRef.current?.pause();+ }, []);+ // Reported from the element's own play/pause transitions, never from the request: what+ // the panel shows as running has to be what is actually running, whichever control —+ // ours, the native bar, or an autoplay refusal — last changed it.+ const publishSpanState = useCallback(() => {+ const token = spanTokenRef.current;+ const video = videoRef.current;++ if (token === null || !video) {+ return;+ }++ publishVideoSpanPlaybackState({ isPlaying: !video.paused, pause: pauseSpanPlayback, token });+ }, [pauseSpanPlayback]);+ const retireSpanToken = useCallback(() => {+ const token = spanTokenRef.current;++ spanTokenRef.current = null;++ if (token !== null) {+ clearVideoSpanPlaybackState(token);+ }+ }, []);// `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@@ -478,7 +510,7 @@ const PreviewVideo = ({spanFrameRef.current = requestAnimationFrame(tick);}, [enforceSpan]);const playSpan = useCallback(- (span: VideoSpan, expiresAt?: number) => {+ (span: VideoSpan, token: number, expiresAt?: number) => {const video = videoRef.current;// Before metadata there is no duration to clamp against and the element drops the@@ -489,7 +521,7 @@ const PreviewVideo = ({// 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 };+ parkedSpanRef.current = { expiresAt: expiresAt ?? Date.now() + PARKED_SPAN_TTL_MS, span, token };return;}@@ -505,6 +537,16 @@ const PreviewVideo = ({// 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;+ // A newer request supersedes the loop before it, whatever that one was doing: its+ // button reverts to play, and this one's takes over. Only a loop is reported — a+ // collapsed window plays once with nothing armed, and a stop for it would stop+ // nothing the button promised.+ retireSpanToken();++ if (spanRef.current !== null) {+ spanTokenRef.current = token;+ }+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@@ -512,10 +554,12 @@ const PreviewVideo = ({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.+ // needed — a span arriving mid-playback fires no `play` event, and the same event+ // gap is why the state is published here as well as from the handlers.startSpanWatch();+ publishSpanState();},- [seekWithinSpan, startSpanWatch]+ [publishSpanState, retireSpanToken, 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@@ -539,11 +583,29 @@ const PreviewVideo = ({return;}- // The user took the playhead somewhere the loop was not going. They own it from here.+ // The user took the playhead somewhere the loop was not going. They own it from here,+ // and the panel's button goes back to offering the selection rather than a stop.spanRef.current = null;parkedSpanRef.current = null;stopSpanWatch();- }, [stopSpanWatch]);+ retireSpanToken();+ }, [retireSpanToken, stopSpanWatch]);+ const handlePlay = useCallback(() => {+ startSpanWatch();+ publishSpanState();+ }, [publishSpanState, startSpanWatch]);+ const handlePause = useCallback(() => {+ stopSpanWatch();+ publishSpanState();+ }, [publishSpanState, stopSpanWatch]);+ // `load()` — protected-media recovery, or the failure overlay's Retry — flips the element+ // to paused WITHOUT firing `pause`; `emptied` is the event it does fire. Left unreported,+ // the panel would go on offering a stop for a loop that is no longer running, and the+ // stop itself would be a no-op: pausing a paused element fires nothing either.+ const handleEmptied = useCallback(() => {+ publishCopyAvailability();+ publishSpanState();+ }, [publishCopyAvailability, publishSpanState]);// 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.@@ -557,7 +619,12 @@ const PreviewVideo = ({seekWithinSpan(video, span.startSeconds);void video.play().catch(() => {});- }, [seekWithinSpan]);+ // The `pause` that precedes `ended` has just reported the loop stopped; `play()` has+ // already flipped the element back, so say so now rather than a task later when the+ // `play` event lands — the gap is a paint, and the panel's icon would blink on every+ // wrap of a window that ends on the clip's last frame.+ publishSpanState();+ }, [publishSpanState, 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@@ -584,7 +651,7 @@ const PreviewVideo = ({consumeVideoSpanPlaybackRequest(request.token);if (isVideoSpanPlaybackFresh(request.requestedAt)) {- playSpan({ endSeconds: request.endSeconds, startSeconds: request.startSeconds });+ playSpan({ endSeconds: request.endSeconds, startSeconds: request.startSeconds }, request.token);}};// A span parked while the element was detached — the view was hidden mid-load — has@@ -596,7 +663,7 @@ const PreviewVideo = ({parkedSpanRef.current = null;if (Date.now() <= parked.expiresAt) {- playSpan(parked.span, parked.expiresAt);+ playSpan(parked.span, parked.token, parked.expiresAt);}}@@ -608,6 +675,14 @@ const PreviewVideo = ({unsubscribe();stopSpanWatch();video?.pause();+ // Nothing is on screen to stop, so the panel must not offer to. The token itself+ // stays: the loop is still armed, and a native play after a re-show resumes it+ // under the request it belongs to.+ const token = spanTokenRef.current;++ if (token !== null) {+ clearVideoSpanPlaybackState(token);+ }};});useImperativeHandle(@@ -694,7 +769,7 @@ const PreviewVideo = ({// 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);+ playSpan(parked.span, parked.token, parked.expiresAt);return;}@@ -794,13 +869,13 @@ const PreviewVideo = ({src={source.src}style={VIDEO_STYLE}onCanPlay={publishCopyAvailability}- onEmptied={publishCopyAvailability}+ onEmptied={handleEmptied}onError={handleVideoError}onLoadedData={publishCopyAvailability}onEnded={handleSpanEnded}onLoadedMetadata={handleLoadedMetadata}- onPause={stopSpanWatch}- onPlay={startSpanWatch}+ onPause={handlePause}+ onPlay={handlePlay}onPlaying={publishCopyAvailability}onResize={publishCopyAvailability}onSeeked={publishCopyAvailability}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 b5cb528a58..785135e346 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@@ -17,9 +17,12 @@ import {type PreviewVideoFrameCopyResult,} from './PreviewFrame';import {+ clearVideoSpanPlaybackState,consumeVideoSpanPlaybackRequest,getVideoSpanPlaybackRequest,+ getVideoSpanPlaybackState,requestVideoSpanPlayback,+ subscribeVideoSpanPlaybackState,} from './spanPlaybackRequest';const identityMocks = vi.hoisted(() => ({@@ -344,10 +347,26 @@ describe('PreviewFrame native video arm', () => {// 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());+ const token = getVideoSpanPlaybackState()?.token;+ const reports: boolean[] = [];+ const unsubscribe = subscribeVideoSpanPlaybackState(() => {+ reports.push(getVideoSpanPlaybackState()?.isPlaying ?? false);+ });++ playback.playToEnd();expect(playback.getTime()).toBe(8);expect(playback.play).toHaveBeenCalledTimes(2);+ // The wrap is reported as running again in the same task as the `pause` that preceded+ // `ended`, not a paint later when the `play` event lands: the panel's pause icon must+ // not blink on every loop of a window that ends on the clip's last frame.+ expect(reports).toEqual([false, true]);++ await interact(() => undefined);++ expect(reports).toEqual([false, true]);+ expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token });+ unsubscribe();});it('keeps the window scoped across a protected-media reload', async () => {@@ -357,6 +376,7 @@ describe('PreviewFrame native video arm', () => {const playback = stubSpanPlayback(video);vi.spyOn(video, 'load').mockImplementation(() => {playback.reload();+ video.dispatchEvent(new Event('emptied'));video.dispatchEvent(new Event('loadedmetadata'));});@@ -369,8 +389,11 @@ describe('PreviewFrame native video arm', () => {await interact(() => video.dispatchEvent(new Event('error')));await interact(() => undefined);- // Back inside the window, and still paused, exactly as `load()` left it.+ // Back inside the window, and still paused, exactly as `load()` left it — and reported+ // so: `load()` flips the element to paused without a `pause` event, so the panel's+ // button would otherwise go on offering a stop that pauses a paused element (a no-op).expect(playback.getTime()).toBe(2);+ expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: false });await interact(() => void video.play());await interact(() => {@@ -482,6 +505,90 @@ describe('PreviewFrame native video arm', () => {expect(playback.getTime()).toBe(9);});+ it('reports the loop under its request, stops it on demand, and resumes it from the native control', async () => {+ const token = requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 2 });+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video);++ // Nothing to report until the element has the loop running: before metadata the+ // request is parked, and the panel's button must not offer to stop a loop that is not+ // yet there.+ expect(getVideoSpanPlaybackState()).toBeNull();++ await interact(() => video.dispatchEvent(new Event('loadedmetadata')));++ expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token });++ // The panel's pause stops the element and leaves the window armed...+ await interact(() => getVideoSpanPlaybackState()?.pause());++ expect(playback.pauseSpy).toHaveBeenCalledTimes(1);+ expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: false, token });++ // ...so the native play control resumes the selection, under the same request, with+ // the wrap still enforced.+ await interact(() => void video.play());++ expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token });++ await interact(() => {+ playback.setTime(4.02);+ video.dispatchEvent(new Event('timeupdate'));+ });++ expect(playback.getTime()).toBe(2);+ });++ it('withdraws the report when the user scrubs out, a newer request takes over, or the view leaves the screen', async () => {+ const first = requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 2 });+ await renderKeptVideo('visible');+ const video = getVideo();+ const playback = stubSpanPlayback(video);++ await interact(() => video.dispatchEvent(new Event('loadedmetadata')));+ expect(getVideoSpanPlaybackState()?.token).toBe(first);++ // The user took the playhead somewhere else: the button goes back to offering play.+ await interact(() => playback.scrubTo(8));+ expect(getVideoSpanPlaybackState()).toBeNull();++ const second = requestVideoSpanPlayback({ endSeconds: 7, itemKey: videoSource.itemKey, startSeconds: 5 });+ await interact(() => undefined);+ expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token: second });++ // A press on another card (or the same one, after a trim change) replaces the loop; the+ // earlier button's report goes with it.+ const third = requestVideoSpanPlayback({ endSeconds: 9, itemKey: videoSource.itemKey, startSeconds: 8 });+ await interact(() => undefined);+ expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token: third });++ // Hidden behind a layout switch, the element is paused and nothing is on screen to+ // stop, so nothing is offered. Shown again, the loop is still armed: a native play+ // resumes it under the request it belongs to.+ await renderKeptVideo('hidden');+ expect(getVideoSpanPlaybackState()).toBeNull();++ await renderKeptVideo('visible');+ expect(getVideoSpanPlaybackState()).toBeNull();++ await interact(() => void video.play());+ expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token: third });+ });++ it('does not offer a stop for a window the clamp collapsed', async () => {+ await renderVideo();+ const video = getVideo();+ const playback = stubSpanPlayback(video, { duration: 6 });++ // Inverted bounds after clamping: the clip plays once with no loop armed, and a pause+ // control for it would promise to stop a selection that is not playing.+ await interact(() => requestVideoSpanPlayback({ endSeconds: 9, itemKey: videoSource.itemKey, startSeconds: 8 }));++ expect(playback.play).toHaveBeenCalledTimes(1);+ expect(getVideoSpanPlaybackState()).toBeNull();+ });+it('does not arm a drag or cancel wheel events from the video surface and native controls', async () => {await interact(() => {root?.render(@@ -1019,15 +1126,21 @@ const stubSpanPlayback = (readyState: { configurable: true, get: () => currentReadyState },});+ // `paused` flips synchronously; the `play` event is a queued task, as in a real engine.const play = vi.spyOn(video, 'play').mockImplementation(() => {paused = false;- video.dispatchEvent(new Event('play'));+ queueMicrotask(() => video.dispatchEvent(new Event('play')));return Promise.resolve();});+ const pause = vi.spyOn(video, 'pause').mockImplementation(() => {+ paused = true;+ video.dispatchEvent(new Event('pause'));+ });return {play,+ pauseSpy: pause,/** What `load()` does to the element before it refires `loadedmetadata`. */reload: () => {currentTime = 0;@@ -1035,13 +1148,12 @@ const stubSpanPlayback = (silentSeek = false;},getTime: () => currentTime,- pause: () => {- paused = true;- video.dispatchEvent(new Event('pause'));- },+ pause: () => video.pause(),+ /** Engines fire `pause` first, then `ended`. */playToEnd: () => {currentTime = duration;paused = true;+ video.dispatchEvent(new Event('pause'));video.dispatchEvent(new Event('ended'));},scrubTo: (value: number) => {@@ -1067,6 +1179,12 @@ const clearSpanRequest = (): void => {if (request) {consumeVideoSpanPlaybackRequest(request.token);}++ const state = getVideoSpanPlaybackState();++ if (state) {+ clearVideoSpanPlaybackState(state.token);+ }};const setVideoFrameState = (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.test.tsindex 90326345f0..580a9c5cb7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.test.ts@@ -1,11 +1,15 @@import { afterEach, describe, expect, it, vi } from 'vitest';import {+ clearVideoSpanPlaybackState,consumeVideoSpanPlaybackRequest,getVideoSpanPlaybackRequest,+ getVideoSpanPlaybackState,isVideoSpanPlaybackFresh,+ publishVideoSpanPlaybackState,requestVideoSpanPlayback,subscribeVideoSpanPlaybackRequests,+ subscribeVideoSpanPlaybackState,VIDEO_SPAN_PLAYBACK_TTL_MS,} from './spanPlaybackRequest';@@ -15,6 +19,12 @@ const retireOutstandingRequest = (): void => {if (request) {consumeVideoSpanPlaybackRequest(request.token);}++ const state = getVideoSpanPlaybackState();++ if (state) {+ clearVideoSpanPlaybackState(state.token);+ }};afterEach(() => {@@ -41,7 +51,8 @@ describe('video span playback requests', () => {expect(second?.token).not.toBe(first?.token);unsubscribe();- requestVideoSpanPlayback(span);+ // The publisher gets the token back: it is what the player's report is matched on.+ expect(requestVideoSpanPlayback(span)).toBe(getVideoSpanPlaybackRequest()?.token);expect(listener).toHaveBeenCalledTimes(2);});@@ -73,3 +84,45 @@ describe('video span playback requests', () => {expect(isVideoSpanPlaybackFresh(request?.requestedAt ?? 0)).toBe(false);});});++describe('video span playback state', () => {+ it('reports one loop at a time and tells subscribers only about changes', () => {+ const listener = vi.fn();+ const unsubscribe = subscribeVideoSpanPlaybackState(listener);+ const pause = vi.fn();++ publishVideoSpanPlaybackState({ isPlaying: true, pause, token: 1 });+ expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token: 1 });+ expect(listener).toHaveBeenCalledTimes(1);++ // The player republishes from every play/pause handler and from the request itself;+ // a report identical to the one standing is not a change a subscriber should render.+ publishVideoSpanPlaybackState({ isPlaying: true, pause, token: 1 });+ expect(listener).toHaveBeenCalledTimes(1);++ publishVideoSpanPlaybackState({ isPlaying: false, pause, token: 1 });+ expect(getVideoSpanPlaybackState()?.isPlaying).toBe(false);+ expect(listener).toHaveBeenCalledTimes(2);++ // A newer loop replaces the report outright: two cannot be on screen at once.+ publishVideoSpanPlaybackState({ isPlaying: true, pause, token: 2 });+ expect(getVideoSpanPlaybackState()?.token).toBe(2);++ unsubscribe();+ clearVideoSpanPlaybackState(2);+ expect(getVideoSpanPlaybackState()).toBeNull();+ expect(listener).toHaveBeenCalledTimes(3);+ });++ it('retires only the loop the caller was reporting on', () => {+ const pause = vi.fn();++ publishVideoSpanPlaybackState({ isPlaying: true, pause, token: 1 });+ publishVideoSpanPlaybackState({ isPlaying: true, pause, token: 2 });+ // A player unmounting late — the hidden keep-alive of a clip a newer request has+ // already replaced — must not take the live loop's report down with it.+ clearVideoSpanPlaybackState(1);++ expect(getVideoSpanPlaybackState()?.token).toBe(2);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.tsindex f59e120635..35cf1c8dd3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.ts@@ -14,6 +14,11 @@ import type { GalleryItemKey } from '@features/gallery';* 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.+ *+ * The return channel is the playback STATE below: the player that honoured a request+ * reports, under that request's token, whether the window is running and how to stop it,+ * so the button that made the request can show a pause control for as long as — and only+ * as long as — its own loop is the one on screen.*/export interface VideoSpanPlaybackRequest {@@ -38,14 +43,17 @@ const notifyListeners = (): void => {}};+/** Publishes a request and returns its token, the handle playback state is reported under. */export const requestVideoSpanPlayback = (span: {endSeconds: number;itemKey: GalleryItemKey;startSeconds: number;-}): void => {+}): number => {nextToken += 1;currentRequest = { ...span, requestedAt: Date.now(), token: nextToken };notifyListeners();++ return nextToken;};export const getVideoSpanPlaybackRequest = (): VideoSpanPlaybackRequest | null => currentRequest;@@ -71,3 +79,65 @@ export const subscribeVideoSpanPlaybackRequests = (listener: () => void): (() =>listeners.delete(listener);};};++/**+ * What the player is doing with the request it last honoured. `null` between loops: before+ * any request has been acted on, once the user takes the playhead out of the window, and+ * whenever the player leaves the screen.+ *+ * `isPlaying` follows the element's own `play`/`pause` events rather than the request, so+ * a pause from the native controls — or an autoplay refusal — shows in the panel as+ * faithfully as one from the panel's button, and a native play resumes it. `pause` leaves+ * the loop armed for the same reason the autoplay case does: the native play control then+ * resumes the selection, not the whole clip.+ */+export interface VideoSpanPlaybackState {+ isPlaying: boolean;+ pause: () => void;+ token: number;+}++let currentState: VideoSpanPlaybackState | null = null;++const stateListeners = new Set<() => void>();++const notifyStateListeners = (): void => {+ for (const listener of stateListeners) {+ listener();+ }+};++/** The player's report. Replaces whatever stood before: one loop is on screen at a time. */+export const publishVideoSpanPlaybackState = (state: VideoSpanPlaybackState): void => {+ if (+ currentState !== null &&+ currentState.token === state.token &&+ currentState.isPlaying === state.isPlaying &&+ currentState.pause === state.pause+ ) {+ return;+ }++ currentState = state;+ notifyStateListeners();+};++/** Retires `token`'s state. A report from a newer loop is left alone. */+export const clearVideoSpanPlaybackState = (token: number): void => {+ if (currentState?.token !== token) {+ return;+ }++ currentState = null;+ notifyStateListeners();+};++export const getVideoSpanPlaybackState = (): VideoSpanPlaybackState | null => currentState;++export const subscribeVideoSpanPlaybackState = (listener: () => void): (() => void) => {+ stateListeners.add(listener);++ return () => {+ stateListeners.delete(listener);+ };+};