Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: video history list takes a bounded/compact query so pages stop stat-ing every file (#12996)

[._.]/ Adam Eivyc7e18e47e998
diff --git a/client/src/components/videoGen/GalleryVideoPicker.jsx b/client/src/components/videoGen/GalleryVideoPicker.jsx
index 2c06df6853..4e85d2bf0f 100644
--- a/client/src/components/videoGen/GalleryVideoPicker.jsx
+++ b/client/src/components/videoGen/GalleryVideoPicker.jsx
@@ -1,6 +1,7 @@
// Visual picker over video history — the video counterpart of GalleryImagePicker.
-// Opens as a modal, fetches GET /api/video-gen/history on open, lets the user
-// search (same haystack as MediaHistory) and click a thumbnail. With
+// Opens as a modal, fetches one bounded compact page of GET /api/video-gen/history, lets the user
+// search (server-side, so prompt text beyond the card preview still matches)
+// and click a thumbnail. With
// `allowUpload`, a header Upload button saves the file via POST /api/uploads
// and selects it as `{ kind: 'upload', filename }` so the reverse-prompt
// endpoint can sample frames from PATHS.uploads. With `uploadToGallery`
@@ -10,7 +11,7 @@
// REFERENCED by a synced record (e.g. a mood-board item), because
// /api/uploads' scratch dir does not federate.
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { Search, X, RefreshCw, Upload } from 'lucide-react';
import Modal from '../ui/Modal';
import FilePickerButton from '../ui/FilePickerButton';
@@ -18,16 +19,15 @@ import MediaCard from '../media/MediaCard';
import { normalizeVideo } from '../media/normalize';
import { listVideoHistory, uploadGalleryVideo } from '../../services/apiImageVideo';
import { uploadFile } from '../../services/apiMedia';
-import { buildMediaHaystack, tokenizeQuery, matchHaystack } from '../../lib/mediaSearch';
import useListResource from '../../hooks/useListResource';
+import useCancelableDebounce from '../../hooks/useCancelableDebounce';
import ListLoadError from '../ui/ListLoadError';
import toast from '../ui/Toast';
const VIDEO_ACCEPT = 'video/mp4,video/webm,video/quicktime,video/x-m4v,.mp4,.webm,.mov,.m4v';
-const fetchVideoItems = () => listVideoHistory({ silent: true }).then((videos) => (
- (Array.isArray(videos) ? videos : []).map(normalizeVideo).filter((it) => !it.hidden)
-));
+const PICKER_PAGE_LIMIT = 60;
+const SEARCH_DEBOUNCE_MS = 250;
export default function GalleryVideoPicker({
open,
@@ -37,9 +37,15 @@ export default function GalleryVideoPicker({
uploadToGallery = false,
accept = VIDEO_ACCEPT,
}) {
- const { items, state, error, retry } = useListResource(fetchVideoItems, { enabled: open });
const [uploading, setUploading] = useState(false);
const [query, setQuery] = useState('');
+ const [searchTerm, setSearchTerm] = useState('');
+ const [scheduleSearch, cancelSearch] = useCancelableDebounce();
+ const fetchVideoItems = useCallback(() => listVideoHistory({
+ silent: true,
+ query: { limit: PICKER_PAGE_LIMIT, compact: true, hidden: false, q: searchTerm.trim() },
+ }).then((videos) => (Array.isArray(videos) ? videos : []).map(normalizeVideo).filter((it) => !it.hidden)), [searchTerm]);
+ const { items, state, error, retry } = useListResource(fetchVideoItems, { enabled: open });
// Invalidate on every open/close transition and on unmount. A host can
// change its selected record while an upload is reading or posting; a late
// completion must leave the saved gallery asset unselected.
@@ -54,15 +60,14 @@ export default function GalleryVideoPicker({
}, [open]);
useEffect(() => {
- if (!open) setQuery('');
- }, [open]);
+ if (!open) { cancelSearch(); setQuery(''); setSearchTerm(''); }
+ }, [open, cancelSearch]);
- const haystacks = useMemo(() => items.map(buildMediaHaystack), [items]);
- const tokens = useMemo(() => tokenizeQuery(query), [query]);
- const filtered = useMemo(() => {
- if (!tokens.length) return items;
- return items.filter((_, idx) => matchHaystack(haystacks[idx], tokens));
- }, [items, haystacks, tokens]);
+ const updateQuery = (value) => {
+ setQuery(value);
+ scheduleSearch(() => setSearchTerm(value), SEARCH_DEBOUNCE_MS);
+ };
+ const clearQuery = () => { cancelSearch(); setQuery(''); setSearchTerm(''); };
const handleUpload = async (event) => {
const file = event.target.files?.[0];
@@ -140,7 +145,7 @@ export default function GalleryVideoPicker({
id="video-picker-search"
type="text"
value={query}
- onChange={(e) => setQuery(e.target.value)}
+ onChange={(e) => updateQuery(e.target.value)}
placeholder="Search prompt, model, seed…"
className="w-full pl-7 pr-7 py-1.5 text-xs bg-port-bg border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
autoFocus
@@ -148,7 +153,7 @@ export default function GalleryVideoPicker({
{query && (
<button
type="button"
- onClick={() => setQuery('')}
+ onClick={clearQuery}
className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white"
aria-label="Clear search"
>
@@ -165,13 +170,13 @@ export default function GalleryVideoPicker({
</div>
) : state === 'error' ? (
<ListLoadError what="your video gallery" error={error} onRetry={retry} />
- ) : filtered.length === 0 ? (
+ ) : items.length === 0 ? (
<div className="text-xs text-gray-500 py-10 text-center">
- {items.length === 0 ? 'No videos in your gallery yet.' : 'No videos match your search.'}
+ {!searchTerm.trim() ? 'No videos in your gallery yet.' : 'No videos match your search.'}
</div>
) : (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
- {filtered.map((item) => (
+ {items.map((item) => (
<MediaCard
key={item.key}
item={item}
diff --git a/client/src/components/videoGen/GalleryVideoPicker.test.jsx b/client/src/components/videoGen/GalleryVideoPicker.test.jsx
index 34e6750136..8f6deda9dc 100644
--- a/client/src/components/videoGen/GalleryVideoPicker.test.jsx
+++ b/client/src/components/videoGen/GalleryVideoPicker.test.jsx
@@ -54,6 +54,18 @@ describe('GalleryVideoPicker', () => {
expect(onClose).toHaveBeenCalled();
});
+ it('asks the server for a bounded compact page and searches server-side', async () => {
+ render(<GalleryVideoPicker open onClose={vi.fn()} onSelect={vi.fn()} />);
+ await waitFor(() => expect(screen.getByText('a neon chase')).toBeInTheDocument());
+ expect(listVideoHistory).toHaveBeenLastCalledWith({
+ silent: true, query: { limit: 60, compact: true, hidden: false, q: '' },
+ });
+ fireEvent.change(screen.getByLabelText('Search videos'), { target: { value: ' forest ' } });
+ await waitFor(() => expect(listVideoHistory).toHaveBeenLastCalledWith({
+ silent: true, query: { limit: 60, compact: true, hidden: false, q: 'forest' },
+ }));
+ });
+
it('shows a load error with Retry instead of the empty copy when the history read fails', async () => {
listVideoHistory.mockRejectedValueOnce(new Error('History unavailable'));
render(<GalleryVideoPicker open onClose={vi.fn()} onSelect={vi.fn()} />);
diff --git a/client/src/lib/videoTimelineModel.js b/client/src/lib/videoTimelineModel.js
index 93069ba181..4de060e6cf 100644
--- a/client/src/lib/videoTimelineModel.js
+++ b/client/src/lib/videoTimelineModel.js
@@ -29,6 +29,10 @@ import {
export { fitFades } from '../../../server/lib/videoTimelineFades.js';
export { historySourceDuration };
+// Query for GET /api/video-gen/history that returns every clip as stat-free,
+// card-sized rows (id, filename, numFrames, fps, thumbnail, timelineProjectId).
+export const CLIP_CATALOG_QUERY = Object.freeze({ compact: true });
+
export const IMAGE_ASSET_KINDS = ['images', 'video-thumbnails'];
export const AUDIO_ASSET_KINDS = ['audio', 'music'];
diff --git a/client/src/pages/PipelineExport.jsx b/client/src/pages/PipelineExport.jsx
index 72e6bf1d86..f855133929 100644
--- a/client/src/pages/PipelineExport.jsx
+++ b/client/src/pages/PipelineExport.jsx
@@ -25,6 +25,7 @@ import {
getGalleryImages,
listVideoHistory,
} from '../services/api';
+import { CLIP_CATALOG_QUERY } from '../lib/videoTimelineModel';
import { useAsyncAction } from '../hooks/useAsyncAction';
import { normalizeImage, normalizeVideo } from '../components/media/normalize';
import AttributionList from '../components/media/AttributionList';
@@ -97,7 +98,7 @@ export default function PipelineExport() {
const fetchSeriesAssets = useCallback(async () => {
const [collections, videos] = await Promise.all([
listMediaCollections({ silent: true }),
- listVideoHistory({ silent: true }),
+ listVideoHistory({ silent: true, query: CLIP_CATALOG_QUERY }),
]);
const list = Array.isArray(collections) ? collections : [];
const collection = list.find((c) => c.seriesId === seriesId || c.id === `sc-${seriesId}`);
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 4d9e1495c2..4906ff3017 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -89,7 +89,7 @@ import ModelInputPreview from '../components/media/ModelInputPreview';
import RemoteMediaTargetPicker from '../components/federatedMedia/RemoteMediaTargetPicker';
import {
getVideoGenStatus, getVideoGenModelContext, generateVideo, cancelVideoGen, previewVideoPrompt,
- listVideoHistory, deleteVideoHistoryItem, setVideoHidden,
+ listVideoHistory, getVideoHistoryItem, deleteVideoHistoryItem, setVideoHidden,
patchSettingsSlice,
getActiveVideoJob,
getSettings,
@@ -133,6 +133,9 @@ const MODES = [
// Stable fetcher for useListResource — the hook re-runs on identity change.
const loadLoraLibrary = () => listLorasFull({ silent: true });
+// The gallery shows the newest records; older ones are reached by id (Remix) or Media History.
+const HISTORY_PAGE_LIMIT = 200;
+
export default function VideoGen() {
const [searchParams, setSearchParams] = useSearchParams();
const settingsOpen = searchParams.get('settings') === '1';
@@ -411,7 +414,7 @@ export default function VideoGen() {
// gallery simply staying empty), so the shared toast would double it.
const refreshHistory = useCallback(() => {
historyInFlightRef.current += 1;
- return listVideoHistory({ silent: true })
+ return listVideoHistory({ silent: true, query: { limit: HISTORY_PAGE_LIMIT } })
.then((items) => {
setHistory(Array.isArray(items) ? items : []);
setHistoryLoad('loaded');
@@ -573,10 +576,15 @@ export default function VideoGen() {
if (record) {
applyRemix(record);
setRemixHandoffProblem(null);
- } else {
- setRemixHandoffProblem('missing');
+ consumeRemixHandoff();
+ return;
}
- consumeRemixHandoff();
+ // The page loads only the newest HISTORY_PAGE_LIMIT records, so an older
+ // clip is hydrated by id before it is called missing.
+ getVideoHistoryItem(remixHandoffId, { silent: true })
+ .then((older) => { applyRemix(older); setRemixHandoffProblem(null); })
+ .catch(() => setRemixHandoffProblem('missing'))
+ .finally(consumeRemixHandoff);
}, [remixHandoffId, historyLoad, history, applyRemix, consumeRemixHandoff]);
// Back to 'loading' first, so a retry that fails again still moves the state
// ('loading' → 'error') and re-runs the effect above.
diff --git a/client/src/pages/VideoTimeline.jsx b/client/src/pages/VideoTimeline.jsx
index 48414e362c..1b55304288 100644
--- a/client/src/pages/VideoTimeline.jsx
+++ b/client/src/pages/VideoTimeline.jsx
@@ -7,10 +7,10 @@ import toast from '../components/ui/Toast';
import useListResource from '../hooks/useListResource';
import * as api from '../services/api';
import { formatDurationSec } from '../utils/formatters';
-import { projectSummary, historySourceDuration } from '../lib/videoTimelineModel';
+import { projectSummary, historySourceDuration, CLIP_CATALOG_QUERY } from '../lib/videoTimelineModel';
const loadTimelineProjects = () => api.listTimelineProjects({ silent: true });
-const loadVideoHistory = () => api.listVideoHistory({ silent: true });
+const loadVideoHistory = () => api.listVideoHistory({ silent: true, query: CLIP_CATALOG_QUERY });
export default function VideoTimeline() {
const navigate = useNavigate();
diff --git a/client/src/pages/VideoTimeline.test.jsx b/client/src/pages/VideoTimeline.test.jsx
index a30ba95cb8..ddd0862743 100644
--- a/client/src/pages/VideoTimeline.test.jsx
+++ b/client/src/pages/VideoTimeline.test.jsx
@@ -42,6 +42,12 @@ describe('VideoTimeline page', () => {
expect(screen.getByText(/No timeline projects yet/)).toBeInTheDocument();
});
+ it('reads the stat-free compact clip catalog, not the full history', async () => {
+ render(<MemoryRouter><VideoTimeline /></MemoryRouter>);
+ await act(async () => {});
+ expect(listVideoHistory).toHaveBeenCalledWith({ silent: true, query: { compact: true } });
+ });
+
it('renders ListLoadError on failed video history load', async () => {
listVideoHistory.mockRejectedValueOnce(new Error('History 500 error'));
render(
diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsx
index 184ddf8a3f..64a7bae825 100644
--- a/client/src/pages/VideoTimelineEditor.jsx
+++ b/client/src/pages/VideoTimelineEditor.jsx
@@ -43,6 +43,7 @@ import {
segmentVolumeAt,
resolvePlaybackLanes,
historySourceDuration,
+ CLIP_CATALOG_QUERY,
bedAssetId,
clampTrim,
fitFadePatch,
@@ -209,7 +210,7 @@ function TimelineProjectEditor({ projectId }) {
if (isCurrent()) setError(err.message);
return null;
}),
- api.listVideoHistory({ silent: true }).catch(() => null),
+ api.listVideoHistory({ silent: true, query: CLIP_CATALOG_QUERY }).catch(() => null),
api.listMusicLibrary({ silent: true }).catch(() => null),
]);
if (!isCurrent()) return;
@@ -262,7 +263,7 @@ function TimelineProjectEditor({ projectId }) {
const generation = ++catalogGenerationRef.current[kind];
setCatalogStatus((prev) => ({ ...prev, [kind]: { ...prev[kind], pending: true } }));
const fetchCatalog = kind === 'clips' ? api.listVideoHistory : api.listMusicLibrary;
- const result = await fetchCatalog({ silent: true }).catch(() => null);
+ const result = await fetchCatalog(kind === 'clips' ? { silent: true, query: CLIP_CATALOG_QUERY } : { silent: true }).catch(() => null);
if (!activeRef.current || catalogGenerationRef.current[kind] !== generation) return;
const ok = kind === 'clips' ? Array.isArray(result) : !!result;
if (ok) {
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 7c71711953..4e7c0f4acd 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -269,7 +269,16 @@ export const getVideoGenRuntimeStatus = (runtime, { signal } = {}) =>
// resume progress display after a page reload. Silent so a 5xx during status
// poll doesn't double-toast on every navigation.
export const getActiveVideoJob = () => request('/video-gen/active', { silent: true });
-export const listVideoHistory = (options = {}) => request('/video-gen/history', options);
+// No `query` returns every full record (stat-ing each file). `query` opts into
+// { limit (<=200), offset, q, hidden, compact } — a bounded newest-first page
+// and/or the stat-free compact projection (`{ compact: true }` = every clip as
+// card-sized rows: id, filename, numFrames, fps, thumbnail); the result is still a plain array.
+export const listVideoHistory = ({ query, ...options } = {}) => {
+ const params = new URLSearchParams();
+ for (const [key, value] of Object.entries(query || {})) if (value !== undefined && value !== '') params.set(key, value);
+ const qs = params.toString();
+ return request(`/video-gen/history${qs ? `?${qs}` : ''}`, options);
+};
// ONE history entry by id (#4165) — for a surface that holds only a video-history
// id and needs the file it actually points at. A history id is not the filename
// stem (a timeline render mints `timeline-*.mp4` beside a randomUUID() id), and
diff --git a/client/src/test/videoGenPageMocks.jsx b/client/src/test/videoGenPageMocks.jsx
index 270b56830f..5f3bc29972 100644
--- a/client/src/test/videoGenPageMocks.jsx
+++ b/client/src/test/videoGenPageMocks.jsx
@@ -191,6 +191,7 @@ vi.mock('../services/api', () => ({
previewVideoPrompt: (...args) => state.previewVideoPrompt(...args),
cancelVideoGen: vi.fn(async () => ({})),
listVideoHistory: (...args) => state.listVideoHistory(...args),
+ getVideoHistoryItem: vi.fn(async () => { throw new Error('Video history entry not found'); }),
deleteVideoHistoryItem: vi.fn(async () => ({})),
setVideoHidden: vi.fn(async () => ({})),
extractLastFrame: vi.fn(async () => ({})),
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 7cb09e01d7..7c6235c5ea 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -7,6 +7,7 @@
*/
import { withMediaFileSizes } from '../lib/mediaFileInfo.js';
+import { historyListQuerySchema, isHistoryListQuery, listVideoHistoryQuery } from '../services/videoGen/historyList.js';
import { Router } from 'express';
import { updateVideoPoster, createSharingCopy } from '../services/videoGen/poster.js';
import { basename } from 'path';
@@ -1214,8 +1215,11 @@ const updatePromptSchema = z.object({ prompt: z.string().max(8000) });
// request into a silent unhide.
const visibilitySchema = z.object({ hidden: z.boolean() });
-router.get('/history', asyncHandler(async (_req, res) => {
- res.json(await withMediaFileSizes(await loadHistory(), 'video'));
+router.get('/history', asyncHandler(async (req, res) => {
+ // No query keeps the legacy full array; see historyList.js for the opt-in form.
+ if (!isHistoryListQuery(req.query)) return res.json(await withMediaFileSizes(await loadHistory(), 'video'));
+ const options = validateRequest(historyListQuerySchema, req.query);
+ res.json(await listVideoHistoryQuery(options, await loadHistory()));
}));
// One history entry by id (#4165) — see videoHistoryRead.js.
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 0aa8f88d2a..44e63e757a 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -3034,6 +3034,14 @@ describe('videoGen routes', () => {
expect(r.status).toBe(200);
expect(r.body).toHaveLength(2);
});
+
+ it('validates the opt-in query and returns a bounded page', async () => {
+ videoGenService.loadHistory.mockResolvedValue([{ id: 'a', createdAt: '2026-01-01' }, { id: 'b', createdAt: '2026-02-01' }]);
+ const page = await request(app).get('/api/video-gen/history?limit=1&compact=true');
+ expect(page.status).toBe(200);
+ expect(page.body.map((i) => i.id)).toEqual(['b']);
+ expect((await request(app).get('/api/video-gen/history?limit=999')).status).toBe(400);
+ });
});
describe('GET /history/:id', () => {
diff --git a/server/services/videoGen/historyList.js b/server/services/videoGen/historyList.js
new file mode 100644
index 0000000000..fc93d62fa6
--- /dev/null
+++ b/server/services/videoGen/historyList.js
@@ -0,0 +1,47 @@
+// Opt-in query form of GET /api/video-gen/history (#12996). No query keeps the
+// legacy full array; callers that migrated ask for a bounded page and/or the
+// stat-free compact projection instead.
+import { z } from 'zod';
+import { compactGalleryRecord } from '../mediaAssetIndex/logic.js';
+import { withMediaFileSizes } from '../../lib/mediaFileInfo.js';
+
+export const historyListQuerySchema = z.object({
+ limit: z.coerce.number().int().min(1).max(200).optional(),
+ offset: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
+ q: z.string().max(500).default(''),
+ hidden: z.enum(['true', 'false']).optional().transform(v => v === undefined ? undefined : v === 'true'),
+ compact: z.enum(['true', 'false']).optional().transform(v => v === 'true'),
+});
+
+export const isHistoryListQuery = query =>
+ Object.keys(historyListQuerySchema.shape).some(key => query[key] !== undefined);
+
+// The shared card projection plus the two lineage/ownership scalars the timeline
+// surfaces read (the gallery's compact source drops them).
+const catalogRow = entry => ({
+ ...compactGalleryRecord(entry),
+ ...(entry.timelineProjectId ? { timelineProjectId: entry.timelineProjectId } : {}),
+ ...(entry.trimmedFrom ? { trimmedFrom: entry.trimmedFrom } : {}),
+});
+
+const time = value => Date.parse(value) || 0;
+
+/**
+ * Always an array, like the legacy list. `limit`/`offset` bound it to one
+ * newest-first page; without `limit` it is every matching row in stored order
+ * (callers that need every clip, e.g. the timeline editor). Only the returned
+ * rows are `stat`ed, and compact rows are never `stat`ed.
+ */
+export async function listVideoHistoryQuery({ limit, offset, q, hidden, compact }, history) {
+ const tokens = q.trim().toLowerCase().split(/\s+/).filter(Boolean);
+ const matching = (Array.isArray(history) ? history : []).filter(entry => entry
+ && (hidden === undefined || !!entry.hidden === hidden)
+ && (!tokens.length || tokens.every(token => JSON.stringify(entry).toLowerCase().includes(token))));
+ const paged = limit !== undefined;
+ const ordered = paged
+ ? [...matching].sort((a, b) => time(b.createdAt) - time(a.createdAt) || String(a.id).localeCompare(String(b.id)))
+ : matching;
+ const rows = paged ? ordered.slice(offset, offset + limit) : ordered;
+ const items = compact ? rows.map(catalogRow) : await withMediaFileSizes(rows, 'video');
+ return items;
+}
diff --git a/server/services/videoGen/historyList.test.js b/server/services/videoGen/historyList.test.js
new file mode 100644
index 0000000000..e848fccda7
--- /dev/null
+++ b/server/services/videoGen/historyList.test.js
@@ -0,0 +1,52 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const withMediaFileSizes = vi.hoisted(() => vi.fn());
+vi.mock('../../lib/mediaFileInfo.js', () => ({ withMediaFileSizes }));
+
+const { listVideoHistoryQuery, historyListQuerySchema, isHistoryListQuery } = await import('./historyList.js');
+
+const parse = query => historyListQuerySchema.parse(query);
+const long = 'x'.repeat(400);
+const history = [
+ { id: 'old', filename: 'old.mp4', createdAt: '2026-01-01T00:00:00Z', prompt: 'a fox', numFrames: 49, fps: 24 },
+ { id: 'new', filename: 'new.mp4', createdAt: '2026-03-01T00:00:00Z', prompt: `${long} needle`, numFrames: 97, fps: 30, timelineProjectId: 'p1', hidden: true },
+ { id: 'mid', filename: 'mid.mp4', createdAt: '2026-02-01T00:00:00Z', prompt: 'a bear' },
+];
+
+describe('listVideoHistoryQuery', () => {
+ beforeEach(() => {
+ withMediaFileSizes.mockReset();
+ withMediaFileSizes.mockImplementation(async rows => rows.map(r => ({ ...r, fileSizeBytes: 1 })));
+ });
+
+ it('recognises only the opt-in query keys', () => {
+ expect(isHistoryListQuery({})).toBe(false);
+ expect(isHistoryListQuery({ compact: 'true' })).toBe(true);
+ });
+
+ it('serves the whole compact catalog without stat-ing and keeps what the timeline editor reads', async () => {
+ const rows = await listVideoHistoryQuery(parse({ compact: 'true' }), history);
+ expect(withMediaFileSizes).not.toHaveBeenCalled();
+ expect(rows.map(r => r.id)).toEqual(['old', 'new', 'mid']);
+ expect(rows[0]).toMatchObject({ id: 'old', filename: 'old.mp4', numFrames: 49, fps: 24 });
+ expect(rows[1].timelineProjectId).toBe('p1');
+ expect(rows[1].prompt.length).toBeLessThan(long.length);
+ });
+
+ it('stats only the requested page, newest first', async () => {
+ const page = await listVideoHistoryQuery(parse({ limit: '1', offset: '1' }), history);
+ expect(page.map(r => r.id)).toEqual(['mid']);
+ expect(withMediaFileSizes).toHaveBeenCalledWith([history[2]], 'video');
+ });
+
+ it('searches the full prompt beyond the compact preview and honors hidden', async () => {
+ const hit = await listVideoHistoryQuery(parse({ q: 'needle', compact: 'true' }), history);
+ expect(hit.map(r => r.id)).toEqual(['new']);
+ const visible = await listVideoHistoryQuery(parse({ hidden: 'false', compact: 'true' }), history);
+ expect(visible.map(r => r.id)).toEqual(['old', 'mid']);
+ });
+
+ it('rejects an oversized page', () => {
+ expect(() => parse({ limit: '500' })).toThrow();
+ });
+});