Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(webv2): badge Ref2VA references with their prompt labels

Lincoln Stein1ef4840d4604
diff --git a/invokeai/backend/minimax_h3/text_conditioning.py b/invokeai/backend/minimax_h3/text_conditioning.py
index 4285d541b1..189da011d9 100644
--- a/invokeai/backend/minimax_h3/text_conditioning.py
+++ b/invokeai/backend/minimax_h3/text_conditioning.py
@@ -149,6 +149,11 @@ def build_ref2va_presentation(
sound is labelled `"<Audio j>: "` *before* `"<Video k>: "`, mirroring the order its rows are packed in. The
prompt follows verbatim, with no chat template and no special tokens.
+ These labels are how a user's prompt addresses a reference, so the webv2 Video panel badges each reference
+ card with the ones it earns here; `referencePromptLabels` in
+ `invokeai/frontend/webv2/src/features/video/core/settings.ts` mirrors this numbering and must change with it.
+ A badge that names a label the prompt cannot resolve fails silently -- the model simply ignores the mention.
+
Returns:
`tuple[list[int], list[int]]`: the token ids and their modality tags.
"""
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index f8cf756503..5051714d92 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -3870,7 +3870,7 @@
"referenceVideoCapRace": "All {{max}} video or audio reference slots filled while this one was loading, so it was not added.",
"referenceFromInitialVideo": "Initial video",
"references": "References",
- "referencesHelp": "Up to 3 videos and 9 images condition the generation, in order — reordering references changes the result. A video reference can contribute its image track, its soundtrack, or both. An uploaded audio file becomes a waveform clip that fills a video slot and conditions on its soundtrack. Every reference adds rows to each denoising step, so the first image reference starts at maximum detail and later ones match the generation size.",
+ "referencesHelp": "Up to 3 videos and 9 images condition the generation, in order — reordering references changes the result. A video reference can contribute its image track, its soundtrack, or both. Each reference is badged with the label the prompt refers to it by — <Picture 1>, <Video 1>, <Audio 1> — numbered separately per kind, so a video contributing both tracks carries two labels. An uploaded audio file becomes a waveform clip that fills a video slot and conditions on its soundtrack. Every reference adds rows to each denoising step, so the first image reference starts at maximum detail and later ones match the generation size.",
"removeReference": "Remove reference",
"staleReferences": "References are set but the selected model cannot use them.",
"uploadVideoReference": "Upload video or audio"
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
index 1d881402a3..bec0108af0 100644
--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
@@ -18,6 +18,7 @@ import {
cloneVideoWidgetValues,
createVideoSourceClip,
deriveReferenceExtendClip,
+ formatReferencePromptLabels,
getDefaultReferenceClip,
getDefaultReferenceConditioning,
getDefaultReferenceImageDetail,
@@ -25,6 +26,7 @@ import {
isVideoSourceClip,
normalizeVideoSettings,
normalizeVideoWidgetValues,
+ referencePromptLabels,
resolveVideoMode,
videoClipSpanSeconds,
VIDEO_SOURCE_FALLBACK_FPS,
@@ -619,6 +621,80 @@ describe('anchorReferenceConditioning', () => {
});
});
+describe('referencePromptLabels', () => {
+ const withConditioning = (conditioning: 'video_audio' | 'video' | 'audio'): VideoReferenceItem => ({
+ ...VIDEO_REFERENCE,
+ conditioning,
+ });
+
+ // The numbering the model is handed (`build_ref2va_presentation`): one counter per
+ // modality, advanced in attachment order, so no label number is the card's position.
+ it('numbers each modality on its own counter', () => {
+ expect(
+ referencePromptLabels([
+ withConditioning('audio'),
+ IMAGE_REFERENCE,
+ withConditioning('video_audio'),
+ IMAGE_REFERENCE,
+ withConditioning('video'),
+ ]).map(formatReferencePromptLabels)
+ ).toEqual([['<Audio 1>'], ['<Picture 1>'], ['<Video 1>', '<Audio 2>'], ['<Picture 2>'], ['<Video 2>']]);
+ });
+
+ it('gives an audio-only reference no video number, which the next video then takes', () => {
+ expect(referencePromptLabels([withConditioning('audio'), withConditioning('video')])).toEqual([
+ { audio: 1, picture: null, video: null },
+ { audio: null, picture: null, video: 1 },
+ ]);
+ });
+
+ it('renumbers on reorder, since order is what the numbering follows', () => {
+ const first = { ...IMAGE_REFERENCE, image: { ...IMAGE_REFERENCE.image, image_name: 'first.png' } };
+ const second = { ...IMAGE_REFERENCE, image: { ...IMAGE_REFERENCE.image, image_name: 'second.png' } };
+ const numbered = (references: VideoReferenceItem[]) =>
+ Object.fromEntries(
+ references.map((reference, index) => [
+ reference.kind === 'image' ? reference.image.image_name : reference.clip.video_name,
+ referencePromptLabels(references)[index],
+ ])
+ );
+
+ // The same three references in two orders: the numbers follow the list, so the swap
+ // trades the two images' picture numbers and leaves the video's alone.
+ expect(numbered([first, withConditioning('video_audio'), second])).toEqual({
+ 'first.png': { audio: null, picture: 1, video: null },
+ 'ref.mp4': { audio: 1, picture: null, video: 1 },
+ 'second.png': { audio: null, picture: 2, video: null },
+ });
+ expect(numbered([second, withConditioning('video_audio'), first])).toEqual({
+ 'first.png': { audio: null, picture: 2, video: null },
+ 'ref.mp4': { audio: 1, picture: null, video: 1 },
+ 'second.png': { audio: null, picture: 1, video: null },
+ });
+ });
+
+ it('numbers a full list, where the widest label lives', () => {
+ const images = Array.from({ length: 9 }, (_unused, index) => ({
+ ...IMAGE_REFERENCE,
+ image: { ...IMAGE_REFERENCE.image, image_name: `image-${index}.png` },
+ }));
+
+ expect(
+ referencePromptLabels([
+ ...images,
+ withConditioning('video'),
+ withConditioning('video_audio'),
+ withConditioning('audio'),
+ ]).map(formatReferencePromptLabels)
+ ).toEqual([
+ ...images.map((_unused, index) => [`<Picture ${index + 1}>`]),
+ ['<Video 1>'],
+ ['<Video 2>', '<Audio 1>'],
+ ['<Audio 2>'],
+ ]);
+ });
+});
+
describe('reference-extend anchor: audio-only references', () => {
const longSource = { ...SOURCE_VIDEO, endFrame: 400, numFrames: 402, video_name: 'long.mp4' };
const source24 = { ...longSource, fps: 24 };
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.ts
index 2d89a802fc..63b7d274d9 100644
--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts
@@ -620,6 +620,75 @@ const canAnchorReferenceExtend = (entry: VideoReferenceItem): boolean =>
export const anchorReferenceConditioning = (conditioning: VideoReferenceConditioning): VideoReferenceConditioning =>
conditioning === 'audio' ? 'video_audio' : conditioning;
+/**
+ * The structured-prompt labels one reference answers to, or `null` where it has none.
+ *
+ * Ref2VA presents every reference to the model under a per-MODALITY label numbered in
+ * attachment order — `<Picture i>` for an image, `<Video k>` for conditioned footage,
+ * `<Audio j>` for a soundtrack — and the prompt refers to references only by those labels.
+ * The three counters run independently, so a reference's label numbers are not its position
+ * in the list: the second card can be `<Picture 1>`, and a video contributing both streams
+ * claims one number from each of two counters.
+ *
+ * Mirrors the backend's `build_ref2va_presentation` numbering (audio on 'video_audio' and
+ * 'audio', a `<Video k>` on everything else video-kind), which is the numbering the model
+ * actually sees. The two must not drift: a label shown here that the prompt cannot address
+ * is worse than no label at all.
+ */
+export type VideoReferencePromptLabels = {
+ audio: number | null;
+ picture: number | null;
+ video: number | null;
+};
+
+/**
+ * The labels, spelled the way the prompt must spell them.
+ *
+ * Never translated and never reformatted: these are tokens the text encoder matches
+ * literally, so what the badge shows is exactly what the user types into the prompt. The
+ * visual track leads a reference that carries both, since that is what the card depicts.
+ */
+export const formatReferencePromptLabels = (labels: VideoReferencePromptLabels): string[] => {
+ const formatted: string[] = [];
+
+ if (labels.picture !== null) {
+ formatted.push(`<Picture ${labels.picture}>`);
+ }
+ if (labels.video !== null) {
+ formatted.push(`<Video ${labels.video}>`);
+ }
+ if (labels.audio !== null) {
+ formatted.push(`<Audio ${labels.audio}>`);
+ }
+
+ return formatted;
+};
+
+/** {@link VideoReferencePromptLabels} for every reference, positionally. */
+export const referencePromptLabels = (references: readonly VideoReferenceItem[]): VideoReferencePromptLabels[] => {
+ const counts = { audio: 0, picture: 0, video: 0 };
+
+ return references.map((reference) => {
+ if (reference.kind === 'image') {
+ counts.picture += 1;
+ return { audio: null, picture: counts.picture, video: null };
+ }
+
+ if (reference.conditioning !== 'audio') {
+ counts.video += 1;
+ }
+ if (reference.conditioning !== 'video') {
+ counts.audio += 1;
+ }
+
+ return {
+ audio: reference.conditioning === 'video' ? null : counts.audio,
+ picture: null,
+ video: reference.conditioning === 'audio' ? null : counts.video,
+ };
+ });
+};
+
/**
* The sample window a newly added video reference starts on.
*
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
index 200e4c393c..4252b82d8d 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
@@ -17,9 +17,11 @@ import { resolveMiniMaxH3ReferenceImage } from '@features/video/core/dimensions'
import {
clampReferenceSampleFrames,
createVideoSourceClip,
+ formatReferencePromptLabels,
getDefaultReferenceClip,
getDefaultReferenceConditioning,
getDefaultReferenceImageDetail,
+ referencePromptLabels,
referenceSampleFrames,
resizeReferenceSampleWindow,
slideReferenceSampleWindow,
@@ -36,7 +38,7 @@ import { Field, FieldLabel } from '@platform/ui/Field';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { Select } from '@platform/ui/Select';
import { SliderNumberField } from '@platform/ui/SliderNumberField';
-import { ArrowDownIcon, ArrowUpIcon, ChevronDownIcon, FilmIcon, ImagePlusIcon, UploadIcon, XIcon } from 'lucide-react';
+import { ArrowDownIcon, ArrowUpIcon, ChevronDownIcon, ImagePlusIcon, UploadIcon, XIcon } from 'lucide-react';
import { memo, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -45,10 +47,11 @@ import { TrimBoundThumb } from './TrimBoundThumb';
import { useVideoUiActions } from './VideoUiContext';
/**
- * The ordered Ref2VA reference list: numbered cards (order is part of the request — a
- * different order is a different generation), one gallery drop target that accepts a single
- * image or video, per-kind file uploads, a per-video conditioning selector and trim, and a
- * per-image detail selector.
+ * The ordered Ref2VA reference list: one card per reference, badged with the labels the
+ * structured prompt addresses it by (order is part of the request — a different order is a
+ * different generation), one gallery drop target that accepts a single image or video,
+ * per-kind file uploads, a per-video conditioning selector and trim, and a per-image detail
+ * selector.
*/
const DROP_ID = 'video-reference-list';
@@ -112,6 +115,7 @@ type ReferenceCollections = {
};
const ReferenceCard = memo(function ReferenceCard({
+ audioLabel,
collections,
disabled,
index,
@@ -120,14 +124,27 @@ const ReferenceCard = memo(function ReferenceCard({
onMove,
onRemove,
onUpdate,
+ pictureLabel,
reference,
targetArea,
+ videoLabel,
}: {
+ /**
+ * The card's structured-prompt label numbers, flattened to scalars rather than passed as
+ * the object `referencePromptLabels` returns: they are derived from the WHOLE list, so an
+ * object would be a fresh prop on every card on every edit to any reference. `updateReference`
+ * keeps the identity of the entries it did not touch, which is what lets the other cards bail
+ * out of a trim drag entirely; a per-card object would re-render all twelve — each one a zag
+ * Select and two SliderNumberFields — once per pointer step.
+ */
+ audioLabel: number | null;
collections: ReferenceCollections;
disabled: boolean;
index: number;
canMoveDown: boolean;
canMoveUp: boolean;
+ pictureLabel: number | null;
+ videoLabel: number | null;
onMove: (index: number, direction: -1 | 1) => void;
onRemove: (index: number) => void;
onUpdate: (index: number, reference: VideoReferenceItem) => void;
@@ -139,6 +156,10 @@ const ReferenceCard = memo(function ReferenceCard({
const moveUpRef = useRef<HTMLButtonElement>(null);
const moveDownRef = useRef<HTMLButtonElement>(null);
const name = reference.kind === 'video' ? reference.clip.video_name : reference.image.image_name;
+ const promptLabels = useMemo(
+ () => formatReferencePromptLabels({ audio: audioLabel, picture: pictureLabel, video: videoLabel }),
+ [audioLabel, pictureLabel, videoLabel]
+ );
const selectValue = useMemo(
() => [reference.kind === 'video' ? reference.conditioning : reference.detail],
[reference]
@@ -275,17 +296,14 @@ const ReferenceCard = memo(function ReferenceCard({
const handleRemove = useCallback(() => onRemove(index), [index, onRemove]);
return (
- <Box borderWidth="1px" p="2" rounded="md">
+ /* Named after the labels the prompt uses, so the twelve identical Remove/Move/trim
+ controls a full list can hold announce which reference they belong to. */
+ <Box aria-label={[...promptLabels, name].join(' ')} borderWidth="1px" p="2" role="group" rounded="md">
<HStack align="start" gap="2">
- <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>
+ {/* 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}
{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%" />
@@ -293,7 +311,19 @@ const ReferenceCard = memo(function ReferenceCard({
) : null}
<Stack flex="1" gap="1" minW="0">
<HStack gap="1">
- {reference.kind === 'video' ? <FilmIcon size={12} /> : <ImagePlusIcon size={12} />}
+ {/* The names the prompt has to use for this reference, leading the row that
+ names it and standing in for the kind icon that used to sit here: the label
+ already says which kind it is, and for a waveform clip conditioning on its
+ soundtrack alone it says so more honestly than a film icon would. The number
+ is NOT the card's slot — the three modality counters advance independently —
+ so it goes beside the filename rather than in a gutter that would cost every
+ card a fixed 64px. Rendered verbatim, brackets and LTR order included,
+ because the badge is the token to type. */}
+ {promptLabels.map((label) => (
+ <Badge key={label} dir="ltr" flexShrink={0} size="xs" userSelect="text" variant="solid">
+ {label}
+ </Badge>
+ ))}
<MiddleTruncate flex="1" fontSize="xs" text={name} />
{reference.kind === 'video' && reference.fromSourceVideo === true ? (
<Badge flexShrink={0} size="xs" variant="outline">
@@ -772,6 +802,7 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({
return `${identity}-${occurrence}`;
});
}, [references]);
+ const promptLabels = useMemo(() => referencePromptLabels(references), [references]);
const moveReference = useCallback(
(index: number, direction: -1 | 1) => {
@@ -800,13 +831,16 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({
{references.map((reference, index) => (
<ReferenceCard
key={referenceKeys[index]}
+ audioLabel={promptLabels[index]?.audio ?? null}
collections={collections}
disabled={isInert}
index={index}
canMoveDown={index < references.length - 1 && index + 1 !== anchorIndex}
canMoveUp={index > 0 && index !== anchorIndex}
+ pictureLabel={promptLabels[index]?.picture ?? null}
reference={reference}
targetArea={targetArea}
+ videoLabel={promptLabels[index]?.video ?? null}
onMove={moveReference}
onRemove={removeReference}
onUpdate={updateReference}
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.tsx
new file mode 100644
index 0000000000..8cbe8339e3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/ui/videoReferencePromptLabels.browser.test.tsx
@@ -0,0 +1,216 @@
+import type { VideoReferenceConditioning, VideoReferenceItem } 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 } 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 { VideoUiProvider, type VideoUiAdapter } from './VideoUiContext';
+
+/**
+ * Each card is badged with the labels the prompt must use for that reference. The numbers
+ * come from three independent per-modality counters over the WHOLE list, so they are not a
+ * card's own business: a move renumbers cards the user never touched, and the cards are
+ * memoized against exactly that kind of re-render.
+ */
+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',
+ referenceConditioningAudio: 'Audio only',
+ referenceConditioningVideo: 'Video only',
+ referenceConditioningVideoAudio: 'Video + audio',
+ referenceDetailMatch: 'Match generation size',
+ referenceDetailMax: 'Max detail',
+ referenceFromInitialVideo: 'Initial video',
+ referenceImageCost: '{{width}}×{{height}} · {{rows}} rows per step',
+ referencesHelp: 'help',
+ removeReference: 'Remove reference',
+ sampleLength: 'Sample Length',
+ sampleLengthWithSeconds: 'Sample Length ({{seconds}}s)',
+ trimEndShort: 'End',
+ 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 adapter = {
+ getUploadBoardId: () => 'none',
+ patchValues: vi.fn(),
+ playVideoSpanInPreview: vi.fn(),
+ reportError: vi.fn(),
+ touchGalleryImages: vi.fn(),
+} as unknown as VideoUiAdapter;
+
+const imageReference = (name: string): VideoReferenceItem => ({
+ detail: 'match',
+ image: { height: 512, image_name: name, width: 512 },
+ kind: 'image',
+});
+
+const videoReference = (name: string, conditioning: VideoReferenceConditioning): VideoReferenceItem => ({
+ clip: { endFrame: 47, fps: 24, height: 480, numFrames: 48, startFrame: 0, video_name: name, width: 832 },
+ conditioning,
+ kind: 'video',
+});
+
+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 render = async (initial: VideoReferenceItem[]): Promise<void> => {
+ await act(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <DndContext>
+ <VideoUiProvider adapter={adapter}>
+ <Harness initial={initial} />
+ </VideoUiProvider>
+ </DndContext>
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+};
+
+/** The rendered label badges, in document order -- the trim thumbs badge their frames too. */
+const badges = (): string[] =>
+ [...host.querySelectorAll<HTMLElement>('.chakra-badge')]
+ .map((badge) => badge.textContent!)
+ .filter((text) => /^<(?:Picture|Video|Audio) \d+>$/.test(text));
+
+/**
+ * Each card's accessible name, in card order: the labels it carries followed by its media
+ * name. Asserting the pairing rather than a flat list of badges is what catches a card
+ * rendering someone else's labels — which is the failure an identity-keyed, memoized list
+ * of same-named references can produce.
+ */
+const cards = (): string[] =>
+ // `[aria-label]` narrows past the unnamed groups Chakra's own slider and select markup adds.
+ [...host.querySelectorAll<HTMLElement>('[role="group"][aria-label]')].map((card) => card.getAttribute('aria-label')!);
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+});
+
+describe('video reference prompt labels', () => {
+ it('badges each card with the labels its reference answers to', async () => {
+ await render([
+ videoReference('voiceover.mp4', 'audio'),
+ imageReference('portrait.png'),
+ videoReference('street.mp4', 'video_audio'),
+ imageReference('backdrop.png'),
+ videoReference('b-roll.mp4', 'video'),
+ ]);
+
+ // The badges carry the tokens verbatim, brackets included -- they are what the user
+ // copies into the prompt.
+ expect(badges()).toEqual(['<Audio 1>', '<Picture 1>', '<Video 1>', '<Audio 2>', '<Picture 2>', '<Video 2>']);
+ // An audio-only reference takes an audio number and no video number; the sounded video
+ // takes one from each counter, so neither number is the card's position in the list.
+ expect(cards()).toEqual([
+ '<Audio 1> voiceover.mp4',
+ '<Picture 1> portrait.png',
+ '<Video 1> <Audio 2> street.mp4',
+ '<Picture 2> backdrop.png',
+ '<Video 2> b-roll.mp4',
+ ]);
+ });
+
+ it('renumbers a card whose own reference did not change', async () => {
+ await render([videoReference('v1.mp4', 'video'), videoReference('v2.mp4', 'video_audio')]);
+ expect(cards()).toEqual(['<Video 1> v1.mp4', '<Video 2> <Audio 1> v2.mp4']);
+
+ const trigger = host.querySelector<HTMLButtonElement>('[role="combobox"]');
+
+ await act(() => trigger!.click());
+ const option = document.querySelector<HTMLElement>('[role="option"][data-value="audio"]');
+
+ expect(option).not.toBeNull();
+ await act(() => option!.click());
+
+ // Dropping the FIRST reference's image track hands its video number to the second card,
+ // whose own reference and slot are untouched -- the card is memoized, so its labels have
+ // to arrive as props that change, not be derived from what it holds.
+ expect(cards()).toEqual(['<Audio 1> v1.mp4', '<Video 1> <Audio 2> v2.mp4']);
+ });
+ it('keeps the token in prompt order inside an RTL document', async () => {
+ // The brackets are bidi-neutral, so in an RTL paragraph they flip and the badge reads
+ // '>Picture 1<' -- a token the encoder will not match, shown to a user who is being
+ // told to type it. Arabic and Hebrew set dir on the document root (I18nController), and
+ // widgets.video has no translations yet, so these badges DO get rendered in an RTL
+ // document today.
+ host.dir = 'rtl';
+ await render([imageReference('portrait.png')]);
+
+ const badge = host.querySelector<HTMLElement>('.chakra-badge')!;
+
+ expect(badge.textContent).toBe('<Picture 1>');
+ expect(getComputedStyle(badge).direction).toBe('ltr');
+ });
+
+ it('moves the labels with the card, not with the slot', async () => {
+ // Twins: same media name, so the list's identity keys collide by design and React
+ // reuses the card instances in place rather than moving them. Only the labels arriving
+ // as props keeps the pairing honest through the move.
+ await render([videoReference('twin.mp4', 'video'), videoReference('twin.mp4', 'video_audio')]);
+ expect(cards()).toEqual(['<Video 1> twin.mp4', '<Video 2> <Audio 1> twin.mp4']);
+
+ const [moveDown] = [...host.querySelectorAll<HTMLButtonElement>('button[aria-label="Move reference down"]')];
+
+ await act(async () => {
+ moveDown!.click();
+ await Promise.resolve();
+ });
+
+ // The sounded twin is now first, so it takes <Video 1> and the silent one takes <Video 2>.
+ expect(cards()).toEqual(['<Video 1> <Audio 1> twin.mp4', '<Video 2> twin.mp4']);
+ });
+});