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.

fix(webv2): carry media_origin on the video record, not a second request

Lincoln Stein9375901f158a
diff --git a/invokeai/app/services/gallery/gallery_common.py b/invokeai/app/services/gallery/gallery_common.py
index 473c497953..6dd3eab592 100644
--- a/invokeai/app/services/gallery/gallery_common.py
+++ b/invokeai/app/services/gallery/gallery_common.py
@@ -46,6 +46,11 @@ class GalleryItem(BaseModelExcludeNull):
# Video-only fields. None for images.
duration: Optional[float] = Field(default=None, description="Video duration in seconds. None for images.")
fps: Optional[float] = Field(default=None, description="Video frames per second. None for images.")
+ media_origin: Optional[str] = Field(
+ default=None,
+ description="How a video entered the gallery, if it was marked: 'audio_upload' for an uploaded audio file "
+ "the server wrapped into a waveform video. None for images and for unmarked videos.",
+ )
class GalleryItemNamesResult(BaseModel):
diff --git a/invokeai/app/services/gallery/gallery_default.py b/invokeai/app/services/gallery/gallery_default.py
index bb4bc44b1c..20888c9c9a 100644
--- a/invokeai/app/services/gallery/gallery_default.py
+++ b/invokeai/app/services/gallery/gallery_default.py
@@ -15,6 +15,7 @@ from invokeai.app.services.invoker import Invoker
from invokeai.app.services.shared.pagination import OffsetPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
+from invokeai.app.services.video_records.video_records_common import MEDIA_ORIGIN_JSON_EXPR, coerce_media_origin
from invokeai.app.services.virtual_boards.virtual_boards_common import VirtualSubBoardDTO
@@ -451,7 +452,7 @@ class SqliteGalleryService(GalleryServiceABC):
Returns `(query_with_select, params, count_query)`. Both halves emit the same columns so
UNION ALL is shape-compatible: `kind`, `name`, `width`, `height`, `category`, `starred`,
- `is_intermediate`, `board_id`, `created_at`, `duration`, `fps`.
+ `is_intermediate`, `board_id`, `created_at`, `duration`, `fps`, `media_origin`.
`names_only=True` selects only `kind`, `name`, `starred`, `created_at` (the minimum needed
for ordering + the counts result).
@@ -464,6 +465,7 @@ class SqliteGalleryService(GalleryServiceABC):
origin_col = "image_origin"
duration_expr = "NULL"
fps_expr = "NULL"
+ media_origin_expr = "NULL"
elif kind == "video":
base_table = "videos"
join_table = "board_videos"
@@ -472,6 +474,7 @@ class SqliteGalleryService(GalleryServiceABC):
origin_col = "video_origin"
duration_expr = f"{base_table}.duration"
fps_expr = f"{base_table}.fps"
+ media_origin_expr = MEDIA_ORIGIN_JSON_EXPR
else:
raise ValueError(f"Unknown kind: {kind}")
@@ -512,7 +515,8 @@ class SqliteGalleryService(GalleryServiceABC):
f"{board_id_expr} AS board_id, "
f"{base_table}.created_at AS created_at, "
f"{duration_expr} AS duration, "
- f"{fps_expr} AS fps"
+ f"{fps_expr} AS fps, "
+ f"{media_origin_expr} AS media_origin"
)
conditions = ""
@@ -584,11 +588,13 @@ class SqliteGalleryService(GalleryServiceABC):
thumbnail_url = urls.get_image_url(name, thumbnail=True)
duration = None
fps = None
+ media_origin = None
else:
full_url = urls.get_video_url(name)
thumbnail_url = urls.get_video_url(name, thumbnail=True)
duration = row["duration"]
fps = row["fps"]
+ media_origin = coerce_media_origin(row["media_origin"])
return GalleryItem(
kind=kind,
name=name,
@@ -603,4 +609,5 @@ class SqliteGalleryService(GalleryServiceABC):
created_at=row["created_at"],
duration=duration,
fps=fps,
+ media_origin=media_origin,
)
diff --git a/invokeai/app/services/video_records/video_records_common.py b/invokeai/app/services/video_records/video_records_common.py
index d67ae657ec..153710e2fd 100644
--- a/invokeai/app/services/video_records/video_records_common.py
+++ b/invokeai/app/services/video_records/video_records_common.py
@@ -1,5 +1,5 @@
import datetime
-from typing import Optional, Union
+from typing import Any, Optional, Union
from pydantic import BaseModel, Field, StrictBool, StrictStr
@@ -32,6 +32,45 @@ class VideoRecordDeleteException(Exception):
super().__init__(message)
+# The `media_origin` marker, projected out of the `metadata` JSON blob. Kept as a bare
+# expression so the polymorphic gallery query can alias it into its own UNION half.
+#
+# The `json_valid` guard is not decoration: `json_extract` RAISES on unparseable text, and
+# this expression now runs on every row of every video listing. An unguarded call would let
+# a single malformed blob fail the whole page rather than one video -- and the column is
+# plain TEXT with no CHECK constraint, so nothing but convention keeps one out. Every
+# in-tree writer goes through `MetadataField`, so this is insurance, not a live bug.
+MEDIA_ORIGIN_JSON_EXPR = (
+ "CASE WHEN json_valid(videos.metadata) THEN json_extract(videos.metadata, '$.media_origin') END"
+)
+MEDIA_ORIGIN_SQL_EXPR = f"{MEDIA_ORIGIN_JSON_EXPR} AS media_origin"
+
+# The longest marker worth carrying. Only `audio_upload` has meaning today, but the field is
+# an open vocabulary, so this is a sanity bound rather than an allowlist. It matters because
+# upload metadata is client-supplied and unbounded, and this one key now rides EVERY row of
+# EVERY listing: without a cap, one upload with a 200 KB marker is echoed back on every
+# gallery page that includes it.
+MEDIA_ORIGIN_MAX_LENGTH = 64
+
+
+def coerce_media_origin(value: Any) -> Optional[str]:
+ """The `media_origin` marker as a string, or None for anything that is not one.
+
+ Upload metadata is validated only as a JSON *object* (`MetadataField` is a
+ `RootModel[dict[str, Any]]`), so a client may store any JSON value under this key, and
+ `json_extract` hands back the matching SQLite type — an int for a JSON number, 0/1 for a
+ JSON boolean. Feeding one of those to the `Optional[str]` field would raise a
+ `ValidationError` while *deserializing the row*, which does not merely mislabel the
+ video: it makes the record, its DTO, and every gallery listing that contains it fail to
+ build. One odd upload would take out the gallery. An unrecognized marker means the same
+ thing as an absent one, so it is dropped here rather than propagated -- including one
+ past :data:`MEDIA_ORIGIN_MAX_LENGTH`, which no real marker reaches.
+ """
+ if not isinstance(value, str) or len(value) > MEDIA_ORIGIN_MAX_LENGTH:
+ return None
+ return value
+
+
VIDEO_DTO_COLS = ", ".join(
[
"videos." + c
@@ -54,11 +93,17 @@ VIDEO_DTO_COLS = ", ".join(
"video_subfolder",
]
]
+ # `media_origin` is not a column: it is the one key of the `metadata` JSON blob the
+ # frontend needs on every row (it marks an upload the ingest converter wrapped from an
+ # audio file). Extracting just that key keeps listings from carrying whole metadata
+ # blobs. `json_extract` yields NULL for a NULL or non-object blob; what it yields for a
+ # non-string value is `coerce_media_origin`'s problem, not the query's.
+ + [MEDIA_ORIGIN_SQL_EXPR]
)
class VideoRecord(BaseModelExcludeNull):
- """Deserialized video record without metadata."""
+ """Deserialized video record: the columns, plus the one `media_origin` key projected out of metadata."""
video_name: str = Field(description="The unique name of the video.")
video_origin: ResourceOrigin = Field(description="The origin of the video.")
@@ -78,6 +123,11 @@ class VideoRecord(BaseModelExcludeNull):
starred: bool = Field(description="Whether this video is starred.")
has_workflow: bool = Field(description="Whether this video has a workflow associated.")
video_subfolder: str = Field(default="", description="The subfolder where the video is stored on disk.")
+ media_origin: Optional[str] = Field(
+ default=None,
+ description="How this video entered the gallery, if it was marked: 'audio_upload' for an uploaded audio "
+ "file the server wrapped into a waveform video.",
+ )
class VideoRecordChanges(BaseModelExcludeNull, extra="allow"):
@@ -108,6 +158,7 @@ def deserialize_video_record(video_dict: dict) -> VideoRecord:
starred = video_dict.get("starred", False)
has_workflow = video_dict.get("has_workflow", False)
video_subfolder = video_dict.get("video_subfolder", "")
+ media_origin = coerce_media_origin(video_dict.get("media_origin", None))
return VideoRecord(
video_name=video_name,
@@ -126,6 +177,7 @@ def deserialize_video_record(video_dict: dict) -> VideoRecord:
starred=starred,
has_workflow=has_workflow,
video_subfolder=video_subfolder,
+ media_origin=media_origin,
)
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 0e95193fe8..0ca8d7451c 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -37707,6 +37707,18 @@
],
"title": "Fps",
"description": "Video frames per second. None for images."
+ },
+ "media_origin": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Media Origin",
+ "description": "How a video entered the gallery, if it was marked: 'audio_upload' for an uploaded audio file the server wrapped into a waveform video. None for images and for unmarked videos."
}
},
"type": "object",
@@ -97712,6 +97724,18 @@
"description": "The subfolder where the video is stored on disk.",
"default": ""
},
+ "media_origin": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Media Origin",
+ "description": "How this video entered the gallery, if it was marked: 'audio_upload' for an uploaded audio file the server wrapped into a waveform video."
+ },
"board_id": {
"anyOf": [
{
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index b041ac4597..94d09a32ea 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -15455,6 +15455,11 @@ export type components = {
* @description Video frames per second. None for images.
*/
fps?: number | null;
+ /**
+ * Media Origin
+ * @description How a video entered the gallery, if it was marked: 'audio_upload' for an uploaded audio file the server wrapped into a waveform video. None for images and for unmarked videos.
+ */
+ media_origin?: string | null;
};
/**
* GalleryItemKind
@@ -43419,6 +43424,11 @@ export type components = {
* @default
*/
video_subfolder?: string;
+ /**
+ * Media Origin
+ * @description How this video entered the gallery, if it was marked: 'audio_upload' for an uploaded audio file the server wrapped into a waveform video.
+ */
+ media_origin?: string | null;
/**
* Board Id
* @description The id of the board the video belongs to, if one exists.
diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
index f06397959d..e46ca4fc5b 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
@@ -32,6 +32,8 @@ export const MOCK_BACKEND_PROFILE_COUNTS = Object.freeze({
export const MOCK_BACKEND_FIXED_EPOCH = '2026-01-15T12:00:00.000Z';
export const MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME = 'fixture-video-001.mp4';
+/** The wrapped-audio upload fixture: a waveform video marked `media_origin: audio_upload`. */
+export const MOCK_BACKEND_WRAPPED_AUDIO_VIDEO_NAME = 'fixture-video-audio.mp4';
const FIXED_EPOCH_MS = Date.parse(MOCK_BACKEND_FIXED_EPOCH);
const range = (length, build) => Array.from({ length }, (_, index) => build(index));
@@ -278,6 +280,27 @@ const createVideos = () => [
width: 64,
workflow: null,
},
+ {
+ // An uploaded audio file, as the server stores one: a waveform video carrying
+ // `media_origin: audio_upload`. Video references made from it start on "Audio only".
+ board_id: null,
+ created_at: timestampAt(3),
+ duration: 1,
+ fps: 24,
+ graph: null,
+ height: 360,
+ is_intermediate: false,
+ metadata: { media_origin: 'audio_upload' },
+ owner_user_id: 'fixture-user',
+ starred: false,
+ thumbnail_url: `/api/v1/videos/i/${MOCK_BACKEND_WRAPPED_AUDIO_VIDEO_NAME}/thumbnail`,
+ video_category: 'user',
+ video_name: MOCK_BACKEND_WRAPPED_AUDIO_VIDEO_NAME,
+ video_origin: 'external',
+ video_url: `/api/v1/videos/i/${MOCK_BACKEND_WRAPPED_AUDIO_VIDEO_NAME}/full`,
+ width: 640,
+ workflow: null,
+ },
];
/**
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 97f7df94ca..72b4412883 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -208,6 +208,8 @@ const getOptionalBoolean = (url, name) => {
return value === null ? undefined : value === 'true';
};
+// `media_origin` is the one metadata key the DTO surfaces (the real server projects it out
+// of the metadata blob in SQL); the rest of a fixture's metadata stays behind /metadata.
const toVideoDto = (video) => ({
board_id: video.board_id,
created_at: video.created_at,
@@ -215,6 +217,7 @@ const toVideoDto = (video) => ({
fps: video.fps,
height: video.height,
is_intermediate: video.is_intermediate,
+ media_origin: video.metadata?.media_origin ?? null,
starred: video.starred,
thumbnail_url: video.thumbnail_url,
video_category: video.video_category,
@@ -248,6 +251,7 @@ const toGalleryItem = (kind, value) =>
height: value.height,
is_intermediate: value.is_intermediate,
kind,
+ media_origin: value.metadata?.media_origin ?? null,
name: value.video_name,
starred: value.starred,
thumbnail_url: value.thumbnail_url,
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/items.ts b/invokeai/frontend/webv2/src/features/gallery/core/items.ts
index 6cdc34e1f5..2e33304f48 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/items.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/items.ts
@@ -35,6 +35,12 @@ export interface GalleryVideoItem extends GalleryItemBase {
durationSeconds: number;
fps?: number;
kind: 'video';
+ /**
+ * How the video entered the gallery, when the server marked it. `'audio_upload'` means an
+ * uploaded audio file the ingest converter wrapped into a rendered-waveform video — its
+ * frames are a picture of the sound, not footage.
+ */
+ mediaOrigin?: string;
}
export type GalleryItem = GalleryImageItem | GalleryVideoItem;
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
index a298b116ad..f8f928366f 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
@@ -553,6 +553,50 @@ describe('mixed gallery item details', () => {
expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/videos/i/folder%2Fclip.mp4', { signal: undefined });
});
+ it('carries the media-origin marker so a reference needs no follow-up metadata fetch', async () => {
+ mocks.apiFetchJson.mockResolvedValue({
+ board_id: null,
+ created_at: '2026-07-20T10:00:00.000Z',
+ duration: 4.5,
+ fps: 24,
+ height: 360,
+ is_intermediate: false,
+ media_origin: 'audio_upload',
+ starred: false,
+ thumbnail_url: '/thumbnails/song.webp',
+ video_category: 'user',
+ video_name: 'song.mp4',
+ video_url: '/videos/song.mp4',
+ width: 640,
+ });
+
+ const item = await galleryItems.resolve({ kind: 'video', name: 'song.mp4' });
+
+ expect(item).toMatchObject({ kind: 'video', mediaOrigin: 'audio_upload' });
+ });
+
+ it('leaves the marker off a video the server did not mark', async () => {
+ mocks.apiFetchJson.mockResolvedValue({
+ board_id: null,
+ created_at: '2026-07-20T10:00:00.000Z',
+ duration: 4.5,
+ fps: 24,
+ height: 360,
+ is_intermediate: false,
+ media_origin: null,
+ starred: false,
+ thumbnail_url: '/thumbnails/clip.webp',
+ video_category: 'user',
+ video_name: 'clip.mp4',
+ video_url: '/videos/clip.mp4',
+ width: 640,
+ });
+
+ const item = await galleryItems.resolve({ kind: 'video', name: 'clip.mp4' });
+
+ expect(item && 'mediaOrigin' in item).toBe(false);
+ });
+
it('fetches focused video metadata and workflow details', async () => {
const controller = new AbortController();
mocks.apiFetchJson
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index a60133e0bd..cef6484563 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -163,6 +163,7 @@ export interface BackendGalleryItemDTO {
height: number;
is_intermediate: boolean;
kind: 'image' | 'video';
+ media_origin?: string | null;
name: string;
starred: boolean;
thumbnail_url: string;
@@ -176,6 +177,7 @@ interface BackendVideoDTO {
fps?: number | null;
height: number;
is_intermediate: boolean;
+ media_origin?: string | null;
starred: boolean;
thumbnail_url: string;
video_category: GalleryItemCategory;
@@ -308,9 +310,17 @@ const mapImage = (image: BackendImageDTO): GalleryImage => ({
width: image.width,
});
+/**
+ * The `media_origin` marker as a string, or absent. The server coerces this, but the mapper
+ * validates what it is handed here the same way it validates `duration` -- a marker of any
+ * other shape means the same thing as no marker.
+ */
+const mediaOriginOf = (value: string | null | undefined): { mediaOrigin?: string } =>
+ typeof value === 'string' && value ? { mediaOrigin: value } : {};
+
const mapGalleryItemBase = (
item: BackendGalleryItemDTO
-): Omit<GalleryItem, 'durationSeconds' | 'fps' | 'kind' | 'sourceQueueItemId'> => ({
+): Omit<GalleryItem, 'durationSeconds' | 'fps' | 'kind' | 'mediaOrigin' | 'sourceQueueItemId'> => ({
boardId: item.board_id ?? 'none',
category: item.category,
createdAt: item.created_at,
@@ -339,6 +349,7 @@ const mapGalleryItem = (item: BackendGalleryItemDTO): GalleryItem => {
durationSeconds: item.duration,
...(item.fps === null || item.fps === undefined ? {} : { fps: item.fps }),
kind: 'video',
+ ...mediaOriginOf(item.media_origin),
};
};
@@ -372,6 +383,7 @@ const mapVideo = (video: BackendVideoDTO): GalleryVideoItem => {
height: video.height,
isIntermediate: video.is_intermediate,
kind: 'video',
+ ...mediaOriginOf(video.media_origin),
name: video.video_name,
starred: video.starred,
thumbnailUrl: absolutizeApiUrl(video.thumbnail_url),
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 0543ba668b..2e31b6d2ae 100644
--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
@@ -247,6 +247,23 @@ describe('createVideoSourceClip', () => {
});
});
+ it('carries the media-origin marker so a derived reference needs no metadata fetch', () => {
+ const wrapped = createVideoSourceClip({
+ durationSeconds: 5,
+ fps: 24,
+ height: 360,
+ mediaOrigin: 'audio_upload',
+ name: 'song.mp4',
+ width: 640,
+ });
+
+ expect(wrapped.mediaOrigin).toBe('audio_upload');
+ // An unmarked clip stays clean rather than carrying an explicit undefined.
+ expect(
+ 'mediaOrigin' in createVideoSourceClip({ durationSeconds: 5, fps: 24, height: 360, name: 'c.mp4', width: 640 })
+ ).toBe(false);
+ });
+
it('falls back to 16 fps when the probe recorded none, mirroring extract_video_range', () => {
const clip = createVideoSourceClip({ durationSeconds: 2, height: 480, name: 'clip.mp4', width: 832 });
@@ -271,18 +288,16 @@ describe('createVideoSourceClip', () => {
describe('getDefaultReferenceConditioning', () => {
it('starts a wrapped audio upload on its soundtrack alone', () => {
- expect(getDefaultReferenceConditioning({ media_origin: 'audio_upload' })).toBe('audio');
+ expect(getDefaultReferenceConditioning('audio_upload')).toBe('audio');
});
it('keeps video + audio for ordinary videos', () => {
- expect(getDefaultReferenceConditioning({ generation_mode: 'minimax_h3_ref2v' })).toBe('video_audio');
- expect(getDefaultReferenceConditioning({ media_origin: 'something_else' })).toBe('video_audio');
+ expect(getDefaultReferenceConditioning('some_other_origin')).toBe('video_audio');
});
- it('keeps video + audio when there is no metadata to read', () => {
+ it('keeps video + audio when the video carries no marker', () => {
expect(getDefaultReferenceConditioning(null)).toBe('video_audio');
expect(getDefaultReferenceConditioning(undefined)).toBe('video_audio');
- expect(getDefaultReferenceConditioning({})).toBe('video_audio');
});
});
@@ -738,6 +753,21 @@ describe('reference-extend linkage', () => {
// The panel's default; every choice is on the 17n+5 grid.
const FRAMES = 141;
+ it('anchors on video + audio even for a wrapped audio clip -- the role needs visual rows', () => {
+ const [ordinary] = applyReferenceExtendSourceVideo([], source24, 3, FRAMES);
+
+ expect(ordinary).toMatchObject({ conditioning: 'video_audio', fromSourceVideo: true });
+
+ // The marker now rides on the clip, so deriving the anchor's conditioning from it is an
+ // easy mistake to make. It would be wrong: the anchor is what the generated frames
+ // continue from, an 'audio' reference emits no visual rows at all, and the all-audio
+ // validation does not fire when other references are visual -- so the seam would go
+ // silently discontinuous. `anchorReferenceConditioning` promotes in the other direction.
+ const [wrapped] = applyReferenceExtendSourceVideo([], { ...source24, mediaOrigin: 'audio_upload' }, 3, FRAMES);
+
+ expect(wrapped).toMatchObject({ conditioning: 'video_audio', fromSourceVideo: true });
+ });
+
it('derives the tail trim: the window ending at the cutpoint, clamped at 0', () => {
expect(deriveReferenceExtendClip(source24, FRAMES)).toMatchObject({ endFrame: 400, startFrame: 260 });
// Shorter than the tail window: fall back to the largest ON-GRID budget the
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.ts
index b5a2cbdf16..68d6b1a52e 100644
--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts
@@ -534,6 +534,7 @@ export const createVideoSourceClip = (item: {
durationSeconds: number;
fps?: number;
height: number;
+ mediaOrigin?: string;
name: string;
width: number;
}): VideoSourceClip => {
@@ -545,6 +546,7 @@ export const createVideoSourceClip = (item: {
endFrame: Math.max(1, numFrames - 2),
fps,
height: item.height,
+ ...(item.mediaOrigin ? { mediaOrigin: item.mediaOrigin } : {}),
numFrames,
startFrame: 0,
video_name: item.name,
@@ -556,15 +558,22 @@ export const createVideoSourceClip = (item: {
* The conditioning a video reference starts on when it is added from the gallery or an
* upload.
*
+ * NOT used for the reference-extend anchor: that role requires visual rows, so it takes
+ * `video_audio` regardless of the clip and promotes an adopted audio-only entry via
+ * {@link anchorReferenceConditioning}.
+ *
* Audio uploads are stored as videos: the server wraps an uploaded audio file into a
- * rendered-waveform clip at ingest and stamps `media_origin: audio_upload` on it. Those
- * frames are a picture of the sound rather than footage anyone means to condition on, so
+ * rendered-waveform clip at ingest and marks it `audio_upload`. Those frames are a picture
+ * of the sound rather than footage anyone means to condition on — and conditioning on them
+ * is not free, it costs a video reference slot and roughly doubles the packed sequence — so
* such a reference defaults to its soundtrack alone. Everything else keeps video + audio.
* This is only the starting value — the card's selector still offers all three.
+ *
+ * Takes the marker rather than a metadata bag: it rides on the gallery item and on
+ * `VideoSourceClip`, so no caller needs a second request to decide this.
*/
-export const getDefaultReferenceConditioning = (
- metadata: Record<string, unknown> | null | undefined
-): VideoReferenceConditioning => (metadata?.media_origin === 'audio_upload' ? 'audio' : 'video_audio');
+export const getDefaultReferenceConditioning = (mediaOrigin: string | null | undefined): VideoReferenceConditioning =>
+ mediaOrigin === 'audio_upload' ? 'audio' : 'video_audio';
/**
* Whether a video reference can serve as the reference-extend ANCHOR.
diff --git a/invokeai/frontend/webv2/src/features/video/core/types.ts b/invokeai/frontend/webv2/src/features/video/core/types.ts
index d1793520b5..b4afa0fc89 100644
--- a/invokeai/frontend/webv2/src/features/video/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/types.ts
@@ -22,6 +22,11 @@ export interface VideoSourceClip {
/** Inclusive trim bounds forwarded to `extract_video_range`; negative indices count from the end. */
startFrame: number;
endFrame: number;
+ /**
+ * The clip's `mediaOrigin` marker, carried so the conditioning a derived reference starts
+ * on can be decided without re-fetching the video's metadata. See `GalleryVideoItem`.
+ */
+ mediaOrigin?: string;
}
/**
diff --git a/invokeai/frontend/webv2/src/features/video/index.ts b/invokeai/frontend/webv2/src/features/video/index.ts
index 385c309972..17f29d4646 100644
--- a/invokeai/frontend/webv2/src/features/video/index.ts
+++ b/invokeai/frontend/webv2/src/features/video/index.ts
@@ -21,6 +21,7 @@ export {
clearDeletedVideoMedia,
cloneVideoWidgetValues,
createVideoSourceClip,
+ getDefaultReferenceConditioning,
isImageWithDims,
isVideoAspectRatioId,
isVideoReferenceItem,
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
index dd95adc890..d1065f946c 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
@@ -10,7 +10,7 @@ import type { ChangeEvent } from 'react';
import { Badge, Box, createListCollection, HStack, Icon, Image, Input, Spinner, Stack, Text } from '@chakra-ui/react';
import { useDndContext, useDndMonitor, useDroppable } from '@dnd-kit/core';
-import { galleryItems, galleryTransfers, galleryVideos, toGalleryItemKey } from '@features/gallery';
+import { galleryItems, galleryTransfers, toGalleryItemKey } from '@features/gallery';
import { GalleryPickerPopover } from '@features/gallery/picker';
import { galleryImageUrls, galleryVideoUrls, isGalleryItemDragData } from '@features/gallery/utility';
import { resolveMiniMaxH3ReferenceImage } from '@features/video/core/dimensions';
@@ -545,10 +545,12 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({
);
const addVideoItem = useCallback(
- // The conditioning is passed in rather than derived here: only a caller holding the
- // clip's metadata can tell a wrapped audio upload from footage. Callers without it get
- // the ordinary video default -- and the entry back, so a late answer can correct it.
- (item: GalleryVideoItem, conditioning: VideoReferenceConditioning = 'video_audio') => {
+ // The conditioning is derived here, from the marker the gallery item carries: it tells a
+ // wrapped audio upload from footage without a second request, so every caller gets the
+ // right answer synchronously.
+ (item: GalleryVideoItem) => {
+ const conditioning = getDefaultReferenceConditioning(item.mediaOrigin);
+ // `createVideoSourceClip` reads `mediaOrigin` off the item too, so the clip carries it.
const clip = createVideoSourceClip(item);
// Built outside the updater so the caller holds the same object the list does: it is
// the only durable handle on this entry once reordering moves it.
@@ -591,17 +593,10 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({
setIsLoading(true);
try {
- // Fetched alongside the resolve, not after it: the metadata only picks the
- // card's starting conditioning, and it must not add a round trip to the add.
- // A missing or unreadable record is not a failure -- it just means the
- // ordinary video default.
- const [item, metadata] = await Promise.all([
- galleryItems.resolve({ kind: 'video', name: videoName }),
- galleryVideos.metadata(videoName).catch(() => null),
- ]);
+ const item = await galleryItems.resolve({ kind: 'video', name: videoName });
if (item?.kind === 'video') {
- addVideoItem(item, getDefaultReferenceConditioning(metadata));
+ addVideoItem(item);
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
@@ -705,47 +700,16 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({
);
const addPickedVideo = useCallback(
(item: GalleryVideoItem) => {
- // The card goes in SYNCHRONOUSLY and is corrected afterwards, rather than waiting on
- // the metadata the way the drop and upload paths do. The picker stays open and judges
- // each click against the reference list as it stands -- an add that had not landed yet
- // would leave the tile pickable (a second click would duplicate it), leave the
- // remaining count stale, and let two picks land in whichever order their fetches
- // finished, which for references is a different generation.
- const entry = addVideoItem(item);
-
- if (!entry) {
- return;
- }
-
- // The metadata is the only thing that tells a wrapped audio upload from footage. An
- // unreadable record is not a failure -- the ordinary video default just stands.
- void galleryVideos
- .metadata(item.name)
- .then((metadata) => {
- const conditioning = getDefaultReferenceConditioning(metadata);
-
- if (conditioning === entry.conditioning) {
- return;
- }
- // The window is re-derived with the conditioning, not carried over: this path adds
- // BEFORE it knows the answer, so the card is holding the footage default, and
- // leaving it would give a picked soundtrack a shorter window than the same clip
- // dropped or uploaded. Safe to recompute -- the identity match below already
- // establishes that the window is still the one this code chose.
- //
- // Matched by identity, not index: a card the user has since edited is a different
- // object and keeps their choice, and a removed one is simply no longer there.
- onChange((current) =>
- current.map((existing) =>
- existing === entry
- ? { ...entry, clip: getDefaultReferenceClip(entry.clip, conditioning), conditioning }
- : existing
- )
- );
- })
- .catch(() => undefined);
+ // Fully synchronous, which the picker requires: it stays open and judges each click
+ // against the reference list as it stands, so an add that had not landed yet would
+ // leave the tile pickable (a second click would duplicate it), leave the remaining
+ // count stale, and let two picks land in whichever order their fetches finished --
+ // which for references is a different generation. This path used to add on the
+ // footage default and correct the card once a metadata fetch answered; the marker
+ // rides on the picked item, so there is nothing left to correct.
+ addVideoItem(item);
},
- [addVideoItem, onChange]
+ [addVideoItem]
);
const handlePick = useCallback(
(item: GalleryItem) => {
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx
index de197cd281..1d8044686b 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx
@@ -101,6 +101,7 @@ export const VideoSourceClipField = memo(
durationSeconds: item.durationSeconds,
fps: item.fps,
height: item.height,
+ mediaOrigin: item.mediaOrigin,
name: item.name,
width: item.width,
})
@@ -153,6 +154,7 @@ export const VideoSourceClipField = memo(
durationSeconds: uploaded.durationSeconds,
fps: uploaded.fps,
height: uploaded.height,
+ mediaOrigin: uploaded.mediaOrigin,
name: uploaded.name,
width: uploaded.width,
})
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.tsx
new file mode 100644
index 0000000000..c084c78ef2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx
@@ -0,0 +1,160 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
+import type { GalleryVideoItem } from '@features/gallery';
+import type * as GalleryModule from '@features/gallery';
+import type { VideoReferenceItem, VideoWidgetValues } from '@features/video/core/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { VideoUiProvider } from '@features/video/ui/VideoUiContext';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { VideoReferenceListField } from './VideoReferenceListField';
+
+/**
+ * The starting conditioning of an added video reference is decided from the resolved gallery
+ * item's `mediaOrigin`. That decision is one call in one callback, and the helper behind it is
+ * unit-tested on its own -- so without this test, deleting the call and hardcoding
+ * `'video_audio'` again leaves the suite green while every wrapped audio upload silently goes
+ * back to conditioning the model on a picture of its own waveform.
+ */
+
+const galleryMocks = vi.hoisted(() => ({ resolve: vi.fn(), uploadVideo: vi.fn() }));
+
+vi.mock('@features/gallery', async (importOriginal) => {
+ const actual = await importOriginal<typeof GalleryModule>();
+
+ return {
+ ...actual,
+ galleryItems: { ...actual.galleryItems, resolve: galleryMocks.resolve },
+ galleryTransfers: { ...actual.galleryTransfers, uploadVideo: galleryMocks.uploadVideo },
+ };
+});
+
+const i18n = createInstance();
+
+void i18n.use(initReactI18next).init({ fallbackLng: 'en', initAsync: false, lng: 'en', resources: { en: {} } });
+
+const videoItem = (mediaOrigin?: string): GalleryVideoItem => ({
+ boardId: 'none',
+ category: 'user',
+ createdAt: '2026-09-01T12:00:00Z',
+ durationSeconds: 4,
+ fps: 24,
+ fullUrl: '/videos/clip.mp4',
+ height: 360,
+ isIntermediate: false,
+ kind: 'video',
+ ...(mediaOrigin ? { mediaOrigin } : {}),
+ name: 'clip.mp4',
+ starred: false,
+ thumbnailUrl: '/thumbnails/clip.webp',
+ width: 640,
+});
+
+const adapter = {
+ getUploadBoardId: () => 'none',
+ patchValues: (_values: Partial<VideoWidgetValues>) => undefined,
+ projectId: 'project-1',
+ rawValues: {},
+ reportError: () => undefined,
+ showPromptSyntaxHighlighting: false,
+ touchGalleryImages: () => undefined,
+};
+
+const NO_REFERENCES: VideoReferenceItem[] = [];
+
+let container: HTMLDivElement;
+let root: Root;
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+beforeEach(() => {
+ galleryMocks.resolve.mockReset();
+ galleryMocks.uploadVideo.mockReset();
+ container = document.createElement('div');
+ document.body.append(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+/** Uploads one video file through the list's own picker and returns the reference it added. */
+const addUploadedVideo = async (mediaOrigin?: string): Promise<VideoReferenceItem[]> => {
+ galleryMocks.uploadVideo.mockResolvedValue({ name: 'clip.mp4' });
+ galleryMocks.resolve.mockResolvedValue(videoItem(mediaOrigin));
+
+ let references: VideoReferenceItem[] = [];
+ const onChange = (update: (current: VideoReferenceItem[]) => VideoReferenceItem[]) => {
+ references = update(references);
+ };
+
+ act(() => {
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <VideoUiProvider adapter={adapter}>
+ <DndContext>
+ <VideoReferenceListField
+ maxImages={9}
+ maxVideos={3}
+ references={NO_REFERENCES}
+ targetArea={null}
+ onChange={onChange}
+ />
+ </DndContext>
+ </VideoUiProvider>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+
+ // The video picker is the file input that also accepts audio -- audio uploads are how a
+ // wrapped waveform clip enters the list in the first place.
+ const inputs = [...container.querySelectorAll<HTMLInputElement>('input[type="file"]')];
+ const videoInput = inputs.find((input) => input.accept.includes('audio/*'));
+
+ expect(videoInput).toBeDefined();
+
+ const file = new File([new Uint8Array([0])], 'song.mp3', { type: 'audio/mpeg' });
+ const transfer = new DataTransfer();
+
+ transfer.items.add(file);
+
+ await act(async () => {
+ Object.defineProperty(videoInput!, 'files', { configurable: true, value: transfer.files });
+ videoInput!.dispatchEvent(new Event('change', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ return references;
+};
+
+describe('the conditioning an added video reference starts on', () => {
+ it('starts a wrapped audio upload on its soundtrack alone', async () => {
+ const references = await addUploadedVideo('audio_upload');
+
+ expect(references).toHaveLength(1);
+ expect(references[0]).toMatchObject({ conditioning: 'audio', kind: 'video' });
+ });
+
+ it('starts an ordinary video on video + audio', async () => {
+ const references = await addUploadedVideo();
+
+ expect(references).toHaveLength(1);
+ expect(references[0]).toMatchObject({ conditioning: 'video_audio', kind: 'video' });
+ });
+
+ it('resolves the item once, with no second metadata request to fall back from', async () => {
+ await addUploadedVideo('audio_upload');
+
+ expect(galleryMocks.resolve).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
index 9a44965466..0ea63404dc 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
@@ -388,6 +388,7 @@ const SingleItemMenuItems = ({
durationSeconds: item.durationSeconds,
fps: item.fps,
height: item.height,
+ mediaOrigin: item.mediaOrigin,
name: item.name,
width: item.width,
}),
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
index 0f968a01f7..3e9d3c917d 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
@@ -8,6 +8,7 @@ import { galleryImages, galleryItems, galleryVideos } from '@features/gallery';
import {
createDefaultVideoWidgetValues,
createVideoSourceClip,
+ getDefaultReferenceConditioning,
getVideoModelPolicy,
normalizeVideoWidgetValues,
syncVideoWidgetValuesWithModels,
@@ -157,6 +158,7 @@ export const executeVideoRecall = async ({
durationSeconds: sourceItem.durationSeconds,
fps: sourceItem.fps,
height: sourceItem.height,
+ mediaOrigin: sourceItem.mediaOrigin,
name: sourceItem.name,
width: sourceItem.width,
});
@@ -222,6 +224,7 @@ export const executeVideoRecall = async ({
durationSeconds: item.durationSeconds,
fps: item.fps,
height: item.height,
+ mediaOrigin: item.mediaOrigin,
name: item.name,
width: item.width,
});
@@ -230,10 +233,15 @@ export const executeVideoRecall = async ({
const endFrame = recorded.trim
? Math.min(Math.max(recorded.trim.endFrame, startFrame), clip.numFrames - 1)
: clip.numFrames - 1;
+ // A recorded conditioning is what the run actually used, so it wins. Absent one
+ // (metadata from a build that did not record it), fall back to the same default
+ // the add path would pick rather than a literal -- a wrapped audio upload has
+ // its marker in hand here, and defaulting it to video + audio would spend a
+ // video reference slot on a picture of its own waveform.
const conditioning =
recorded.conditioning === 'video' || recorded.conditioning === 'audio'
? recorded.conditioning
- : 'video_audio';
+ : getDefaultReferenceConditioning(item.mediaOrigin);
references.push({ clip: { ...clip, endFrame, startFrame }, conditioning, kind: 'video' });
} catch {
diff --git a/tests/app/services/gallery/test_gallery_default.py b/tests/app/services/gallery/test_gallery_default.py
index 1c617015f5..e4c775cb7c 100644
--- a/tests/app/services/gallery/test_gallery_default.py
+++ b/tests/app/services/gallery/test_gallery_default.py
@@ -776,3 +776,73 @@ class TestOrderingTieBreakers:
# One stable choice across refetches: the kind/name-descending winner (b.mp4).
assert covers == {(None, "b.mp4")}
+
+
+def _save_marked_video(store: SqliteVideoRecordStorage, name: str, user_id: str, metadata: str | None) -> None:
+ store.save(
+ video_name=name,
+ video_origin=ResourceOrigin.EXTERNAL,
+ video_category=ImageCategory.USER,
+ width=640,
+ height=360,
+ duration=1.0,
+ fps=24.0,
+ has_workflow=False,
+ is_intermediate=False,
+ metadata=metadata,
+ user_id=user_id,
+ )
+
+
+class TestMediaOriginOnListedItems:
+ """The listing carries `media_origin`, so a clip picked straight off the gallery grid
+ can be conditioned correctly without a follow-up /metadata request.
+
+ "Extend in Video" builds its source clip from a listed item rather than a resolve, so
+ the marker has to survive the polymorphic UNION as well as the video DTO.
+ """
+
+ def test_a_wrapped_audio_upload_is_marked(self, services) -> None:
+ _save_marked_video(services["videos"], "wrapped.mp4", "alice", '{"media_origin": "audio_upload"}')
+
+ listed = services["gallery"].list_items(user_id="alice", is_admin=False)
+
+ assert [(item.name, item.media_origin) for item in listed.items] == [("wrapped.mp4", "audio_upload")]
+
+ def test_ordinary_videos_and_images_carry_no_marker(self, services) -> None:
+ _save_marked_video(services["videos"], "plain.mp4", "alice", '{"note": "kept"}')
+ _save_marked_video(services["videos"], "bare.mp4", "alice", None)
+ _save_image(services["images"], "still.png", user_id="alice")
+
+ listed = services["gallery"].list_items(user_id="alice", is_admin=False)
+ origins = {item.name: item.media_origin for item in listed.items}
+
+ assert origins == {"plain.mp4": None, "bare.mp4": None, "still.png": None}
+
+ def test_a_non_string_marker_does_not_break_the_listing(self, services) -> None:
+ """One video with an odd `media_origin` must not fail the whole gallery page.
+
+ Upload metadata is validated only as a JSON object, so the extracted value can be an
+ int; building `GalleryItem` from it used to raise, and the listing is a UNION over
+ every item, so the failure was not confined to the offending video.
+ """
+ _save_marked_video(services["videos"], "odd.mp4", "alice", '{"media_origin": 7}')
+ _save_marked_video(services["videos"], "wrapped.mp4", "alice", '{"media_origin": "audio_upload"}')
+
+ listed = services["gallery"].list_items(user_id="alice", is_admin=False)
+ origins = {item.name: item.media_origin for item in listed.items}
+
+ assert origins == {"odd.mp4": None, "wrapped.mp4": "audio_upload"}
+
+ def test_a_malformed_metadata_blob_does_not_fail_the_page(self, services) -> None:
+ """The listing is a UNION over every item, so an unguarded `json_extract` raise here
+ would 500 the whole gallery page for one bad row — and for an admin, for everyone."""
+ _save_marked_video(services["videos"], "bad.mp4", "alice", "not json at all")
+ _save_marked_video(services["videos"], "wrapped.mp4", "alice", '{"media_origin": "audio_upload"}')
+
+ listed = services["gallery"].list_items(user_id="alice", is_admin=False)
+
+ assert {item.name: item.media_origin for item in listed.items} == {
+ "bad.mp4": None,
+ "wrapped.mp4": "audio_upload",
+ }
diff --git a/tests/app/services/video_records/test_video_records_sqlite.py b/tests/app/services/video_records/test_video_records_sqlite.py
index d44858bfbb..caa06f39c9 100644
--- a/tests/app/services/video_records/test_video_records_sqlite.py
+++ b/tests/app/services/video_records/test_video_records_sqlite.py
@@ -7,6 +7,7 @@ and a non-admin caller saw every user's videos. The fix added an
behaviour so the regression cannot reappear.
"""
+import json
import sqlite3
import pytest
@@ -258,3 +259,119 @@ def test_exists_propagates_a_storage_error(store: SqliteVideoRecordStorage):
with pytest.raises(sqlite3.OperationalError):
store.exists("video-1.mp4")
+
+
+def _save_with_metadata(store: SqliteVideoRecordStorage, name: str, metadata: str | None) -> None:
+ store.save(
+ video_name=name,
+ video_origin=ResourceOrigin.EXTERNAL,
+ video_category=ImageCategory.USER,
+ width=640,
+ height=360,
+ duration=1.0,
+ fps=24.0,
+ has_workflow=False,
+ is_intermediate=False,
+ metadata=metadata,
+ user_id="alice",
+ )
+
+
+def test_media_origin_is_projected_out_of_the_metadata_blob(store: SqliteVideoRecordStorage) -> None:
+ """The record carries `media_origin` so clients need no separate /metadata request.
+
+ An audio upload the ingest converter wrapped into a waveform video is marked
+ `audio_upload`; the frontend starts such a reference on its soundtrack alone, and a
+ wrong value there costs a video reference slot and roughly doubles the packed sequence.
+ """
+ _save_with_metadata(store, "wrapped.mp4", '{"media_origin": "audio_upload", "note": "kept"}')
+
+ assert store.get("wrapped.mp4").media_origin == "audio_upload"
+ # The rest of the blob stays behind the /metadata route rather than riding every row.
+ assert store.get_metadata("wrapped.mp4") is not None
+
+
+ "metadata",
+ [
+ pytest.param(None, id="no metadata at all"),
+ pytest.param("{}", id="metadata without the key"),
+ pytest.param('{"note": "kept"}', id="metadata with other keys"),
+ ],
+)
+def test_media_origin_is_none_when_unmarked(store: SqliteVideoRecordStorage, metadata: str | None) -> None:
+ """`json_extract` over a NULL or key-less blob yields NULL rather than raising."""
+ _save_with_metadata(store, "plain.mp4", metadata)
+
+ assert store.get("plain.mp4").media_origin is None
+
+
+def test_media_origin_survives_a_listing(store: SqliteVideoRecordStorage) -> None:
+ """`get_many` selects the same columns, so a listed row carries the marker too."""
+ _save_with_metadata(store, "wrapped.mp4", '{"media_origin": "audio_upload"}')
+ _save_with_metadata(store, "plain.mp4", None)
+
+ listed = store.get_many(offset=0, limit=10, order_dir=SQLiteDirection.Descending, user_id="alice", is_admin=False)
+ origins = {record.video_name: record.media_origin for record in listed.items}
+
+ assert origins == {"wrapped.mp4": "audio_upload", "plain.mp4": None}
+
+
+ "raw",
+ [
+ pytest.param("1", id="a JSON number"),
+ pytest.param("true", id="a JSON boolean"),
+ pytest.param("1.5", id="a JSON float"),
+ ],
+)
+def test_a_non_string_marker_does_not_break_the_record(store: SqliteVideoRecordStorage, raw: str) -> None:
+ """A client may store any JSON value under `media_origin`; the row must still deserialize.
+
+ `MetadataField` validates only that the blob is an object, so `json_extract` can hand
+ back an int or a float. Passing one to the `Optional[str]` field raised while building
+ the record -- which took out the video's DTO *and* every gallery listing containing it,
+ so one odd upload broke the gallery.
+ """
+ _save_with_metadata(store, "odd.mp4", '{"media_origin": ' + raw + "}")
+
+ assert store.get("odd.mp4").media_origin is None
+
+
+def test_metadata_that_is_not_an_object_leaves_the_marker_unset(store: SqliteVideoRecordStorage) -> None:
+ """`json_extract` over a non-object blob yields NULL rather than raising."""
+ _save_with_metadata(store, "array.mp4", "[1, 2, 3]")
+
+ assert store.get("array.mp4").media_origin is None
+
+
+def test_a_malformed_metadata_blob_does_not_fail_the_query(store: SqliteVideoRecordStorage) -> None:
+ """`json_extract` RAISES on unparseable text, and this expression runs on every listed row.
+
+ Unguarded, one malformed blob would fail the whole page — `get_many` deserializes rows in
+ a comprehension — rather than the one video. The column is plain TEXT with no CHECK, so
+ only convention keeps such a row out; the `json_valid` guard makes that not matter.
+ """
+ _save_with_metadata(store, "bad.mp4", "not json at all")
+ _save_with_metadata(store, "good.mp4", '{"media_origin": "audio_upload"}')
+
+ listed = store.get_many(offset=0, limit=10, order_dir=SQLiteDirection.Descending, user_id="alice", is_admin=False)
+
+ assert {record.video_name: record.media_origin for record in listed.items} == {
+ "bad.mp4": None,
+ "good.mp4": "audio_upload",
+ }
+
+
+def test_an_overlong_marker_is_dropped_rather_than_echoed_on_every_row(store: SqliteVideoRecordStorage) -> None:
+ """Upload metadata is client-supplied and unbounded, and this key now rides every row.
+
+ Without a cap, one upload carrying a huge marker is echoed back on every gallery page
+ that includes the video.
+ """
+ _save_with_metadata(store, "huge.mp4", json.dumps({"media_origin": "A" * 5000}))
+
+ assert store.get("huge.mp4").media_origin is None
+ # A marker of a plausible length still passes.
+ _save_with_metadata(store, "fine.mp4", json.dumps({"media_origin": "audio_upload"}))
+ assert store.get("fine.mp4").media_origin == "audio_upload"