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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: make video upscale method-aware with a pre-submit source-probe plan (#6509)
[._.]/ Adam Eivy7fca209eb109
diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.jsindex a054e04909..d07c916081 100644--- a/server/lib/ffmpeg.js+++ b/server/lib/ffmpeg.js@@ -244,6 +244,58 @@ export const probeFrameCount = async (videoPath) => {return (await run(false)) ?? (await run(true));};+// Probe the video stream geometry in ONE ffprobe call: pixel dimensions, the+// average frame rate, and the header frame count. Callers that need a frame+// count they can trust on any container should still fall back to+// `probeFrameCount` (which pays for a decode pass when the header lacks+// nb_frames) — this returns `frameCount: null` rather than guessing.+//+// Every field is independently nullable: an unreadable axis is "unknown", never+// 0, so a caller cannot read a failed probe as a real measurement.+export const probeVideoStreamInfo = async (videoPath) => {+ const empty = { width: null, height: null, fps: null, frameCount: null };+ if (typeof videoPath !== 'string' || !videoPath) return empty;+ // Keyed output (`nokey=0`), NOT positional: ffprobe prints requested entries in+ // its own internal field order rather than the order they were asked for, so+ // destructuring the lines would silently swap two fields the day that order+ // changes. Reading `key=value` costs nothing and cannot mis-bind.+ const stdout = await runFfprobe([+ '-v', 'error',+ '-select_streams', 'v:0',+ '-show_entries', 'stream=width,height,avg_frame_rate,nb_frames',+ '-of', 'default=noprint_wrappers=1',+ videoPath,+ ]);+ const fields = new Map(stdout.split(/\r?\n/).map((line) => {+ const at = line.indexOf('=');+ return at === -1 ? null : [line.slice(0, at).trim(), line.slice(at + 1).trim()];+ }).filter(Boolean));+ const width = fields.get('width');+ const height = fields.get('height');+ const frameRate = fields.get('avg_frame_rate');+ const frames = fields.get('nb_frames');+ const positiveInt = (value) => {+ const n = parseInt(value, 10);+ return Number.isFinite(n) && n > 0 ? n : null;+ };+ // ffprobe reports avg_frame_rate as a rational ("24000/1001"), and "0/0" for+ // a stream it could not measure.+ const parseRate = (value) => {+ if (!value) return null;+ const [num, den] = value.split('/');+ const n = parseFloat(num);+ const d = den === undefined ? 1 : parseFloat(den);+ if (!Number.isFinite(n) || !Number.isFinite(d) || d === 0 || n <= 0) return null;+ return n / d;+ };+ return {+ width: positiveInt(width),+ height: positiveInt(height),+ fps: parseRate(frameRate),+ frameCount: positiveInt(frames),+ };+};+// Sanity-check that a rendered video file is actually playable: the file// exists on disk, has non-zero bytes, and ffprobe can decode at least one// video frame from it. Returns `{ ok: true }` on success anddiff --git a/server/lib/ffmpeg.test.js b/server/lib/ffmpeg.test.jsindex 862c64c143..0c55d8a010 100644--- a/server/lib/ffmpeg.test.js+++ b/server/lib/ffmpeg.test.js@@ -6,6 +6,7 @@ import { join, resolve } from 'path';import {verifyVideoPlayable, safeUnder, runFfmpegProcess, hasAudioStream, buildTrimConcatArgs,+ probeVideoStreamInfo, findFfmpeg,BT709_TAG_FILTER, BT709_CONTAINER_ARGS, bt709TagFilter, supportsSetparamsFilter, __resetSetparamsProbe,} from './ffmpeg.js';@@ -55,6 +56,48 @@ describe('verifyVideoPlayable', () => {});});+// Geometry probe behind the upscale plan endpoint (#6509). Every field is+// independently nullable, because a plan that reports an unmeasured axis as 0+// would disclose a target size the render then contradicts.+describe('probeVideoStreamInfo', () => {+ let tmpDir;+ beforeAll(() => { tmpDir = mkdtempSync(join(tmpdir(), 'portos-probe-test-')); });+ afterAll(() => { rmSync(tmpDir, { recursive: true, force: true }); });++ it('reports every field as unknown for an invalid path', async () => {+ const unknown = { width: null, height: null, fps: null, frameCount: null };+ expect(await probeVideoStreamInfo('')).toEqual(unknown);+ expect(await probeVideoStreamInfo(null)).toEqual(unknown);+ expect(await probeVideoStreamInfo(undefined)).toEqual(unknown);+ });++ it('reports unknown rather than zero for a file ffprobe cannot read', async () => {+ const junk = join(tmpDir, 'junk.mp4');+ writeFileSync(junk, Buffer.alloc(64, 0));+ expect(await probeVideoStreamInfo(junk)).toEqual({ width: null, height: null, fps: null, frameCount: null });+ });++ it('reads back the real geometry of a clip it just encoded', async () => {+ const ffmpeg = await findFfmpeg();+ // The host may have no ffmpeg; the null-safety contract above still holds+ // and is what the plan endpoint depends on.+ if (!ffmpeg) return;+ const clip = join(tmpDir, 'probe.mp4');+ const made = await runFfmpegProcess({+ bin: ffmpeg,+ args: ['-f', 'lavfi', '-i', 'testsrc=size=96x64:rate=10:duration=1', '-pix_fmt', 'yuv420p', '-y', clip],+ stderrTailBytes: 0,+ });+ if (!made.ok) return;+ const info = await probeVideoStreamInfo(clip);+ expect(info.width).toBe(96);+ expect(info.height).toBe(64);+ expect(info.fps).toBeCloseTo(10, 5);+ // nb_frames is header-dependent; when present it must be the real count.+ if (info.frameCount !== null) expect(info.frameCount).toBe(10);+ });+});+describe('hasAudioStream', () => {it('returns false for an empty/invalid path without shelling out', async () => {expect(await hasAudioStream('')).toBe(false);diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex ad202e135d..3732be4005 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -43,8 +43,14 @@ import {extractLastFrame,stitchVideos,upscaleHistoryItem,+ planUpscaleHistoryItem,resolveFflfLtx2PixelBudget,} from '../services/videoGen/local.js';+// The method enum comes from the pure contract module rather than through+// local.js's re-export: it is a constant, and reading it off the mockable+// provider surface would make every suite that mocks local.js responsible for+// re-declaring it just so this file's route schemas can be built.+import { UPSCALE_METHODS, DEFAULT_UPSCALE_METHOD } from '../services/videoGen/upscalePlan.js';import { cleanupMultipartTemp } from '../services/videoGen/prepareParams.js';import { submitVideoGenJob } from '../services/videoGen/submitJob.js';import { resolveReactorApiKey, mintReactorToken } from '../services/videoGen/reactor.js';@@ -1174,10 +1180,35 @@ router.post('/last-frame/:id', asyncHandler(async (req, res) => {res.json(await extractLastFrame(parsed.data));}));+// An absent body is exactly Lanczos, so every pre-#6509 client keeps its+// current behavior without sending anything new.+const upscaleBodySchema = z.object({+ method: z.enum(UPSCALE_METHODS).default(DEFAULT_UPSCALE_METHOD),+});++// Query form of the same choice, for the read-only plan endpoint.+const upscalePlanQuerySchema = z.object({+ method: z.enum(UPSCALE_METHODS).default(DEFAULT_UPSCALE_METHOD),+});++// What the user must see BEFORE submitting (#6509): source geometry, the target+// the method would produce, the padding the model grid needs, and whether this+// machine can actually run the method. Read-only — it queues no job and pulls+// no weight.+router.get('/upscale/:id/plan', asyncHandler(async (req, res) => {+ const parsed = historyIdSchema.safeParse(req.params.id);+ if (!parsed.success) failValidation(parsed);+ const query = upscalePlanQuerySchema.safeParse(req.query ?? {});+ if (!query.success) failValidation(query);+ res.json({ ok: true, plan: await planUpscaleHistoryItem(parsed.data, query.data) });+}));+router.post('/upscale/:id', asyncHandler(async (req, res) => {const parsed = historyIdSchema.safeParse(req.params.id);if (!parsed.success) failValidation(parsed);- const entry = await upscaleHistoryItem(parsed.data);+ const body = upscaleBodySchema.safeParse(req.body ?? {});+ if (!body.success) failValidation(body);+ const entry = await upscaleHistoryItem(parsed.data, body.data);res.json({ ok: true, video: entry });}));diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 7089ce078a..75a1884c4a 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -119,6 +119,7 @@ vi.mock('../services/videoGen/local.js', () => ({extractLastFrame: vi.fn(),stitchVideos: vi.fn(),upscaleHistoryItem: vi.fn(),+ planUpscaleHistoryItem: vi.fn(),// Mirrors the real export — keeps the route's keyframe-range check in// sync with whatever the service actually defaults to.DEFAULT_NUM_FRAMES: 121,@@ -2824,7 +2825,7 @@ describe('videoGen routes', () => {expect(r.status).toBe(200);expect(r.body.ok).toBe(true);expect(r.body.video).toEqual(upscaled);- expect(videoGenService.upscaleHistoryItem).toHaveBeenCalledWith(validHistoryId);+ expect(videoGenService.upscaleHistoryItem).toHaveBeenCalledWith(validHistoryId, { method: 'lanczos' });});it('forwards a shared-gallery upload id to upscaleHistoryItem', async () => {@@ -2832,7 +2833,7 @@ describe('videoGen routes', () => {videoGenService.upscaleHistoryItem.mockResolvedValue({ id: otherValidId, filename: `${otherValidId}.mp4`, upscaledFrom: uploadId });const r = await request(app).post(`/api/video-gen/upscale/${uploadId}`).send({});expect(r.status).toBe(200);- expect(videoGenService.upscaleHistoryItem).toHaveBeenCalledWith(uploadId);+ expect(videoGenService.upscaleHistoryItem).toHaveBeenCalledWith(uploadId, { method: 'lanczos' });});it('returns the ServerError status when the service rejects', async () => {@@ -2843,6 +2844,78 @@ describe('videoGen routes', () => {expect(r.status).toBe(404);expect(r.body.error).toMatch(/not found/i);});++ // Method selection (#6509). The whole point of the default is that a client+ // written before the option existed keeps its exact behavior, so the+ // no-body request and the explicit Lanczos request must be indistinguishable+ // at the service boundary.+ it('sends an explicit lanczos request identically to a no-body request', async () => {+ videoGenService.upscaleHistoryItem.mockResolvedValue({ id: otherValidId });+ await request(app).post(`/api/video-gen/upscale/${validHistoryId}`).send({});+ await request(app).post(`/api/video-gen/upscale/${validHistoryId}`).send({ method: 'lanczos' });+ const [noBody, explicit] = videoGenService.upscaleHistoryItem.mock.calls;+ expect(explicit).toEqual(noBody);+ });++ it('forwards the generative method to the service', async () => {+ videoGenService.upscaleHistoryItem.mockResolvedValue({ id: otherValidId });+ const r = await request(app).post(`/api/video-gen/upscale/${validHistoryId}`).send({ method: 'ltx' });+ expect(r.status).toBe(200);+ expect(videoGenService.upscaleHistoryItem).toHaveBeenCalledWith(validHistoryId, { method: 'ltx' });+ });++ it('rejects an unknown method with a 400 and never reaches the service', async () => {+ const r = await request(app).post(`/api/video-gen/upscale/${validHistoryId}`).send({ method: 'realesrgan' });+ expect(r.status).toBe(400);+ expect(videoGenService.upscaleHistoryItem).not.toHaveBeenCalled();+ });++ it('surfaces the 501 capability error the service raises for an unavailable runtime', async () => {+ videoGenService.upscaleHistoryItem.mockRejectedValue(+ Object.assign(new Error('needs LTX-2.5 MLX (ltx25)'), { status: 501, code: 'UNSUPPORTED_RUNTIME' }),+ );+ const r = await request(app).post(`/api/video-gen/upscale/${validHistoryId}`).send({ method: 'ltx' });+ expect(r.status).toBe(501);+ expect(r.body.error).toMatch(/ltx25/);+ });+ });++ describe('GET /upscale/:id/plan', () => {+ const validHistoryId = 'aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaa1';++ it('rejects history ids outside known render and upload shapes', async () => {+ const r = await request(app).get('/api/video-gen/upscale/not-a-uuid/plan');+ expect(r.status).toBe(400);+ expect(videoGenService.planUpscaleHistoryItem).not.toHaveBeenCalled();+ });++ it('defaults to lanczos and wraps the plan', async () => {+ const plan = { id: validHistoryId, method: 'lanczos', scale: 2 };+ videoGenService.planUpscaleHistoryItem.mockResolvedValue(plan);+ const r = await request(app).get(`/api/video-gen/upscale/${validHistoryId}/plan`);+ expect(r.status).toBe(200);+ expect(r.body).toEqual({ ok: true, plan });+ expect(videoGenService.planUpscaleHistoryItem).toHaveBeenCalledWith(validHistoryId, { method: 'lanczos' });+ });++ it('forwards the requested method', async () => {+ videoGenService.planUpscaleHistoryItem.mockResolvedValue({ method: 'ltx' });+ await request(app).get(`/api/video-gen/upscale/${validHistoryId}/plan?method=ltx`);+ expect(videoGenService.planUpscaleHistoryItem).toHaveBeenCalledWith(validHistoryId, { method: 'ltx' });+ });++ it('rejects an unknown method with a 400', async () => {+ const r = await request(app).get(`/api/video-gen/upscale/${validHistoryId}/plan?method=realesrgan`);+ expect(r.status).toBe(400);+ expect(videoGenService.planUpscaleHistoryItem).not.toHaveBeenCalled();+ });++ // #6502: nothing may be queued or downloaded before the user submits.+ it('never touches the upscale action', async () => {+ videoGenService.planUpscaleHistoryItem.mockResolvedValue({ method: 'ltx' });+ await request(app).get(`/api/video-gen/upscale/${validHistoryId}/plan?method=ltx`);+ expect(videoGenService.upscaleHistoryItem).not.toHaveBeenCalled();+ });});describe('POST / — federated media provider', () => {diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 65cd253e3f..caed12f41a 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -260,6 +260,9 @@ vi.mock('../../lib/ffmpeg.js', async () => ({// disturbing that default.probeFrameCount: vi.fn(probeMockImpl.probeFrameCount),probeVideoDuration: vi.fn(probeMockImpl.probeVideoDuration),+ // The upscale plan endpoint (#6509) reads source geometry through this one.+ // Unused by the render paths here, but the module graph still links it.+ probeVideoStreamInfo: vi.fn(async () => ({ width: 768, height: 512, fps: 24, frameCount: 25 })),trimVideoFromFrame: vi.fn(async (_videoPath, outPath) => ({ ok: true, outPath })),hasAudioStream: vi.fn(async () => false),// The real builder is pure and covered by ffmpeg.test.js; keep it real herediff --git a/server/services/videoGen/upscalePlan.js b/server/services/videoGen/upscalePlan.jsnew file mode 100644index 0000000000..35c4c5bff4--- /dev/null+++ b/server/services/videoGen/upscalePlan.js@@ -0,0 +1,188 @@+/**+ * Video upscale — method contract, alignment math, and the provenance shape.+ *+ * Two upscale methods share one request contract (#6502 / #6509):+ *+ * - `lanczos` — the historical ffmpeg pass. Pixel-faithful, no model, no+ * alignment constraint, and the DEFAULT for every existing caller.+ * - `ltx` — the LTX-2.5 Pixel Spatial Upscaler adapter, which synthesizes+ * detail on a GPU runtime. Gated on a cached adapter and a supported+ * backend, and constrained by the model's frame/spatial grid.+ *+ * This module holds only the pure parts (the enum, the grid, the padding math+ * and the provenance field list) so the numbers can be tested without touching+ * ffprobe, the HF cache, or the history file.+ */++export const UPSCALE_METHODS = Object.freeze(['lanczos', 'ltx']);+export const DEFAULT_UPSCALE_METHOD = 'lanczos';++// Both methods double each axis. Declared once because the plan endpoint, the+// Lanczos entry builder and the client disclosure all quote it.+export const UPSCALE_SCALE = 2;++// The registry key of the adapter the generative method fuses (#6508).+export const LTX_UPSCALE_WEIGHT_KEY = 'pixel-upscale';++// The BYOV runtime that carries the generative method on each host class.+// macOS runs the MLX pipeline (#6512); every other platform with a CUDA card+// runs the distilled CUDA runner (#6513). A host with neither has no generative+// backend at all, which the plan reports rather than discovering at render time.+export const LTX_UPSCALE_RUNTIME_BY_PLATFORM = Object.freeze({+ darwin: 'ltx25',+ win32: 'ltx25_cuda',+ linux: 'ltx25_cuda',+});++export const ltxUpscaleRuntimeId = (platform = process.platform) => (+ LTX_UPSCALE_RUNTIME_BY_PLATFORM[platform] || null+);++// The LTX-2.5 two-stage grid, mirrored from `validate_args` in+// `scripts/generate_ltx25_cuda.py`: output dimensions must be divisible by 64+// and the frame count must satisfy `frames % 8 == 1` with a floor of 9. The+// MLX runner (#6512) must establish the same rule from the model card; if it+// turns out to differ, this constant is the single place both read.+export const LTX_GRID = Object.freeze({+ spatialMultiple: 64,+ frameModulus: 8,+ frameRemainder: 1,+ minFrames: 9,+});++const roundUpTo = (value, multiple) => Math.ceil(value / multiple) * multiple;++// The smallest frame count >= `frames` that satisfies the grid. `frames % 8 == 1`+// has a solution every 8 frames, so this never overshoots by more than 7.+export const alignFrameCount = (frames, grid = LTX_GRID) => {+ const floor = Math.max(grid.minFrames, Math.max(1, Math.ceil(frames)));+ const remainder = ((floor % grid.frameModulus) + grid.frameModulus) % grid.frameModulus;+ const delta = (grid.frameRemainder - remainder + grid.frameModulus) % grid.frameModulus;+ return floor + delta;+};++/**+ * What the generative method would have to do to a source before it fits the+ * model grid, stated as an explicit plan rather than applied silently.+ *+ * #6502 forbids hidden cropping and hidden duration loss, so this ALWAYS pads+ * and never trims: extra pixels on the right/bottom and extra frames on the+ * tail are recoverable (the caller crops the padding back off the output),+ * whereas a crop or a trim destroys source content the user never agreed to+ * lose. `trimFrames` is reported so the contract can carry a trim if a future+ * backend ever needs one, and is 0 on every path today.+ *+ * Padding is computed on the SOURCE axis (so the disclosure can say "848 →+ * 864") and the target is the padded source scaled by `UPSCALE_SCALE`. Because+ * the scale is 2 and the grid multiple is 64, a source axis conforms exactly+ * when it is divisible by 32.+ */+export const planLtxAlignment = ({ width, height, frameCount } = {}, grid = LTX_GRID) => {+ const sourceMultiple = grid.spatialMultiple / UPSCALE_SCALE;+ const knownWidth = Number.isFinite(width) && width > 0 ? Math.round(width) : null;+ const knownHeight = Number.isFinite(height) && height > 0 ? Math.round(height) : null;+ const knownFrames = Number.isFinite(frameCount) && frameCount > 0 ? Math.round(frameCount) : null;++ const paddedWidth = knownWidth === null ? null : roundUpTo(knownWidth, sourceMultiple);+ const paddedHeight = knownHeight === null ? null : roundUpTo(knownHeight, sourceMultiple);+ const paddedFrames = knownFrames === null ? null : alignFrameCount(knownFrames, grid);++ const padWidth = knownWidth === null ? null : paddedWidth - knownWidth;+ const padHeight = knownHeight === null ? null : paddedHeight - knownHeight;+ const padFrames = knownFrames === null ? null : paddedFrames - knownFrames;++ // "Conforming" is only assertable when every axis was measurable. An+ // unmeasured axis is `null` (unknown), never a silent 0 — a caller must not+ // read "no padding needed" out of a probe that failed.+ const measured = [padWidth, padHeight, padFrames];+ const conforming = measured.every((n) => n !== null) ? measured.every((n) => n === 0) : null;++ return {+ ...grid,+ sourceMultiple,+ padWidth,+ padHeight,+ padFrames,+ trimFrames: 0,+ paddedSource: { width: paddedWidth, height: paddedHeight, frameCount: paddedFrames },+ conforming,+ };+};++// Target dimensions the method produces. Lanczos scales the source verbatim;+// the generative method scales the PADDED source, because that is what the+// model actually renders.+export const planTargetDimensions = ({ method, width, height, frameCount, alignment }) => {+ const scaleAxis = (n) => (Number.isFinite(n) && n > 0 ? Math.round(n) * UPSCALE_SCALE : null);+ if (method !== 'ltx') {+ return {+ width: scaleAxis(width),+ height: scaleAxis(height),+ frameCount: Number.isFinite(frameCount) && frameCount > 0 ? Math.round(frameCount) : null,+ };+ }+ return {+ width: scaleAxis(alignment?.paddedSource?.width),+ height: scaleAxis(alignment?.paddedSource?.height),+ frameCount: alignment?.paddedSource?.frameCount ?? null,+ };+};++/**+ * Provenance an upscaled history entry records (#6509 item 4).+ *+ * A video-history row is a plain JSON object with no sanitizer, so these are a+ * documented contract rather than a schema. Every upscale method writes the+ * full list; the generative dispatch slice (#6511) fills the model-specific+ * ones that Lanczos leaves null:+ *+ * - `upscaledFrom` — source history id. Also the ALREADY_UPSCALED guard.+ * - `upscaleMethod` — `'lanczos' | 'ltx'`.+ * - `width`/`height` — the ACTUAL output dimensions, measured from the file+ * where the method can produce something other than 2x+ * the source (a padded generative render).+ * - `fps` — output frame rate.+ * - `numFrames` — output frame count.+ * - `duration` — output duration in seconds.+ * - `seed` — the generative render's seed, so the pass is+ * reproducible. Lanczos is deterministic and has no seed+ * of its own, so it writes none; read `upscaleMethod`+ * rather than the presence of this key to tell the two+ * apart, because an upscaled row also inherits the SOURCE+ * render's fields.+ * - `upscaleRuntime` — BYOV runtime id that rendered it (`ltx25` /+ * `ltx25_cuda`), or `'ffmpeg'` for Lanczos.+ * - `renderStartedAt`/`renderMs` — measured wall-clock render time (#5878).+ */+export const UPSCALE_PROVENANCE_FIELDS = Object.freeze([+ 'upscaledFrom',+ 'upscaleMethod',+ 'width',+ 'height',+ 'fps',+ 'numFrames',+ 'duration',+ 'seed',+ 'upscaleRuntime',+ 'renderStartedAt',+ 'renderMs',+]);++// The subset of the contract the Lanczos pass writes ITSELF, rather than+// inheriting from the source row it spreads. Asserted against a real Lanczos+// entry, so dropping one of these from the row builder fails a test instead of+// quietly producing a row #6511's readers cannot tell apart from a legacy one.+export const LANCZOS_PROVENANCE_FIELDS = Object.freeze([+ 'upscaledFrom',+ 'upscaleMethod',+ 'upscaleRuntime',+ 'width',+ 'height',+ 'renderStartedAt',+ 'renderMs',+]);++// The runtime id Lanczos records — it is an ffmpeg filter pass, not a BYOV+// runtime, and naming it explicitly keeps `upscaleRuntime` non-null on every+// upscaled row.+export const LANCZOS_RUNTIME_ID = 'ffmpeg';diff --git a/server/services/videoGen/upscalePlan.test.js b/server/services/videoGen/upscalePlan.test.jsnew file mode 100644index 0000000000..3fb559f932--- /dev/null+++ b/server/services/videoGen/upscalePlan.test.js@@ -0,0 +1,120 @@+import { describe, it, expect } from 'vitest';+import {+ alignFrameCount, planLtxAlignment, planTargetDimensions, LTX_GRID, UPSCALE_SCALE,+ ltxUpscaleRuntimeId, UPSCALE_METHODS, UPSCALE_PROVENANCE_FIELDS, LANCZOS_PROVENANCE_FIELDS,+} from './upscalePlan.js';++// The grid is the model's, not ours: `scripts/generate_ltx25_cuda.py`'s+// validate_args rejects a render that violates it, so a plan that quietly+// reports "no padding needed" for a non-conforming source would hand the user a+// disclosure that the render then contradicts.+describe('alignFrameCount', () => {+ it('leaves a conforming count alone', () => {+ for (const frames of [9, 17, 25, 121]) expect(alignFrameCount(frames)).toBe(frames);+ });++ it('rounds UP to the next conforming count, never down', () => {+ // Rounding down would silently drop tail frames — duration loss #6502 forbids.+ expect(alignFrameCount(10)).toBe(17);+ expect(alignFrameCount(16)).toBe(17);+ expect(alignFrameCount(120)).toBe(121);+ expect(alignFrameCount(122)).toBe(129);+ });++ it('honors the model floor for a source shorter than the minimum', () => {+ for (const frames of [1, 5, 8, 9]) expect(alignFrameCount(frames)).toBe(LTX_GRID.minFrames);+ });++ it('never overshoots by a whole period', () => {+ for (let frames = 9; frames <= 400; frames += 1) {+ const aligned = alignFrameCount(frames);+ expect(aligned).toBeGreaterThanOrEqual(frames);+ expect(aligned - frames).toBeLessThan(LTX_GRID.frameModulus);+ expect(aligned % LTX_GRID.frameModulus).toBe(LTX_GRID.frameRemainder);+ }+ });+});++describe('planLtxAlignment', () => {+ // The model constrains the OUTPUT, and the output is 2x the source, so a+ // source axis conforms exactly when it is divisible by 32.+ it('reports zero padding for a source whose 2x output already sits on the grid', () => {+ const plan = planLtxAlignment({ width: 768, height: 512, frameCount: 121 });+ expect(plan).toMatchObject({ padWidth: 0, padHeight: 0, padFrames: 0, trimFrames: 0, conforming: true });+ expect(plan.paddedSource).toEqual({ width: 768, height: 512, frameCount: 121 });+ });++ it('reports the exact padding a non-conforming source needs on every axis', () => {+ const plan = planLtxAlignment({ width: 848, height: 480, frameCount: 100 });+ expect(plan.padWidth).toBe(16); // 848 → 864 (1728 output, divisible by 64)+ expect(plan.padHeight).toBe(0); // 480 is already a multiple of 32+ expect(plan.padFrames).toBe(5); // 100 → 105+ expect(plan.conforming).toBe(false);+ });++ it('pads rather than trims, so the plan can never lose source content', () => {+ for (const frameCount of [10, 63, 100, 122]) {+ const plan = planLtxAlignment({ width: 850, height: 481, frameCount });+ expect(plan.trimFrames).toBe(0);+ expect(plan.padWidth).toBeGreaterThan(0);+ expect(plan.padHeight).toBeGreaterThan(0);+ expect(plan.paddedSource.frameCount).toBeGreaterThanOrEqual(frameCount);+ }+ });++ it('keeps an unmeasured axis null instead of reporting a confident zero', () => {+ const plan = planLtxAlignment({ width: 768, height: 512, frameCount: null });+ expect(plan.padWidth).toBe(0);+ expect(plan.padFrames).toBeNull();+ // A probe that could not read the frame count must not read as "conforming".+ expect(plan.conforming).toBeNull();+ });++ it('produces an output that satisfies the model grid on every padded axis', () => {+ for (const [width, height] of [[848, 480], [1000, 999], [512, 512], [33, 17]]) {+ const plan = planLtxAlignment({ width, height, frameCount: 61 });+ expect((plan.paddedSource.width * UPSCALE_SCALE) % LTX_GRID.spatialMultiple).toBe(0);+ expect((plan.paddedSource.height * UPSCALE_SCALE) % LTX_GRID.spatialMultiple).toBe(0);+ }+ });+});++describe('planTargetDimensions', () => {+ it('doubles the source verbatim for lanczos', () => {+ expect(planTargetDimensions({ method: 'lanczos', width: 848, height: 480, frameCount: 100 }))+ .toEqual({ width: 1696, height: 960, frameCount: 100 });+ });++ it('doubles the PADDED source for the generative method', () => {+ const source = { width: 848, height: 480, frameCount: 100 };+ const alignment = planLtxAlignment(source);+ expect(planTargetDimensions({ method: 'ltx', ...source, alignment }))+ .toEqual({ width: 1728, height: 960, frameCount: 105 });+ });++ it('reports an unmeasurable axis as null rather than zero', () => {+ expect(planTargetDimensions({ method: 'lanczos', width: null, height: 0, frameCount: null }))+ .toEqual({ width: null, height: null, frameCount: null });+ });+});++describe('contract constants', () => {+ it('keeps lanczos first so it stays the historical default', () => {+ expect(UPSCALE_METHODS).toEqual(['lanczos', 'ltx']);+ });++ it('maps each supported host class to the runtime that carries the adapter', () => {+ expect(ltxUpscaleRuntimeId('darwin')).toBe('ltx25');+ expect(ltxUpscaleRuntimeId('win32')).toBe('ltx25_cuda');+ expect(ltxUpscaleRuntimeId('linux')).toBe('ltx25_cuda');+ expect(ltxUpscaleRuntimeId('freebsd')).toBeNull();+ });++ it('keeps what lanczos writes inside the contract the generative slice must satisfy', () => {+ // Two lists drift the moment #6511 adds a field to only one of them; this is+ // the containment that makes the pair readable as one contract.+ for (const field of LANCZOS_PROVENANCE_FIELDS) {+ expect(UPSCALE_PROVENANCE_FIELDS).toContain(field);+ }+ });+});diff --git a/server/services/videoGen/upscaleVideo.js b/server/services/videoGen/upscaleVideo.jsindex 372465a85f..893866e319 100644--- a/server/services/videoGen/upscaleVideo.js+++ b/server/services/videoGen/upscaleVideo.js@@ -5,39 +5,181 @@ import { join } from 'path';import { randomUUID } from 'crypto';import { PATHS, UUID_RE, copyFileGuarded, unlinkGuarded } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';-import { safeUnder, generateThumbnail, upscaleVideo2x } from '../../lib/ffmpeg.js';+import {+ safeUnder, generateThumbnail, upscaleVideo2x,+ probeVideoStreamInfo, probeFrameCount, probeVideoDuration, hasAudioStream,+} from '../../lib/ffmpeg.js';import { loadHistory, mutateVideoHistory } from './history.js';import { omitRenderTiming, renderTimingFields } from '../../lib/renderTiming.js';+import { resolveIcLoraWeightByKey, icLoraSpecByKey, icLoraWeightKey } from '../../lib/icLoraWeights.js';+import { BYOV_RUNTIME_INFO, isByovRuntimeInstalled } from './runtimes.js';+import {+ UPSCALE_METHODS, DEFAULT_UPSCALE_METHOD, UPSCALE_SCALE, LANCZOS_RUNTIME_ID,+ LTX_UPSCALE_WEIGHT_KEY, ltxUpscaleRuntimeId, planLtxAlignment, planTargetDimensions,+} from './upscalePlan.js';++export * from './upscalePlan.js';const UPLOADED_HISTORY_ID_RE = /^upload-[a-f0-9]{8}$/i;-// 2× Lanczos upscale of an existing history item. Writes the upscaled clip-// to a new file (never overwrites the original) and inserts a new history-// entry pointing at it, so the user gets both versions side-by-side in the-// gallery. Doubles width and height; aspect-ratio is preserved exactly.-//-// Returns the new history entry on success; throws ServerError on any-// missing-input / ffmpeg / file-system failure so the route can map it to-// a clean HTTP status.-export async function upscaleHistoryItem(historyId) {- // Validate the input arg first — failing here surfaces a clean 400 even if- // the history file happens to contain a record with a malformed id, and- // it short-circuits the loadHistory I/O for obviously-bogus requests.- // Rendered clips use UUIDs; shared-gallery uploads use their `upload-<uuid8>`- // filename stem as the id. Keep the strict UUID check for render ids while- // allowing the upload producer's documented id shape.+// Normalize the options bag. Every pre-#6509 caller passes a bare id, so an+// absent bag and an absent `method` both mean Lanczos — the historical+// behavior — rather than an error.+const resolveMethod = (options) => {+ const method = options?.method ?? DEFAULT_UPSCALE_METHOD;+ if (!UPSCALE_METHODS.includes(method)) {+ throw new ServerError(+ `Unknown upscale method '${method}' (expected one of: ${UPSCALE_METHODS.join(', ')})`,+ { status: 400, code: 'VALIDATION_ERROR' },+ );+ }+ return method;+};++// Shared id-validate → load → find. Rendered clips use UUIDs; shared-gallery+// uploads use their `upload-<uuid8>` filename stem as the id. Keep the strict+// UUID check for render ids while allowing the upload producer's documented id+// shape. Validating the arg first surfaces a clean 400 even if the history file+// happens to contain a record with a malformed id, and it short-circuits the+// loadHistory I/O for obviously-bogus requests.+const resolveHistoryItem = async (historyId) => {if (typeof historyId !== 'string' || (!UUID_RE.test(historyId) && !UPLOADED_HISTORY_ID_RE.test(historyId))) {throw new ServerError('Invalid history id', { status: 400, code: 'VALIDATION_ERROR' });}const history = await loadHistory();const item = history.find((h) => h.id === historyId);if (!item) throw new ServerError('Video not found', { status: 404, code: 'NOT_FOUND' });- if (item.upscaledFrom) {- throw new ServerError('Cannot upscale an already-upscaled video', { status: 400, code: 'ALREADY_UPSCALED' });- }+ return item;+};++const resolveSourcePath = (item) => {const sourcePath = safeUnder(PATHS.videos, item.filename);if (!sourcePath) throw new ServerError('Invalid video filename', { status: 400, code: 'VALIDATION_ERROR' });if (!existsSync(sourcePath)) throw new ServerError('Video file not found on disk', { status: 404, code: 'NOT_FOUND' });+ return sourcePath;+};++// The BYOV runtime that would carry a generative upscale on this host, plus+// whether it is actually present. `isByovRuntimeInstalled` is a filesystem+// check, NOT the import probe — the plan endpoint must stay read-only and cheap,+// and "the venv exists" is the honest answer to "does this machine have a+// supported backend" at disclosure time.+const describeLtxRuntime = () => {+ const id = ltxUpscaleRuntimeId();+ if (!id) {+ return { id: null, label: null, supported: false, installed: false, reason: `No generative upscale backend exists for ${process.platform}.` };+ }+ const installed = isByovRuntimeInstalled(id);+ const label = BYOV_RUNTIME_INFO[id]?.label || id;+ return {+ id,+ label,+ supported: true,+ installed,+ reason: installed ? null : `The ${label} runtime is not installed on this machine.`,+ };+};++// Cache-only adapter lookup (#6508). `resolveIcLoraWeightByKey` reads the local+// HF cache and, for this `requiresPreDownload` spec, returns `path: null`+// instead of falling back to a repo id — so this never triggers a download,+// which #6502 forbids anywhere outside the explicit action.+const describeLtxAdapter = async () => {+ const spec = icLoraSpecByKey(LTX_UPSCALE_WEIGHT_KEY);+ const resolved = await resolveIcLoraWeightByKey(LTX_UPSCALE_WEIGHT_KEY);+ return {+ key: icLoraWeightKey(spec),+ label: spec?.label ?? null,+ repo: spec?.repo ?? null,+ filename: spec?.filename ?? null,+ sizeBytes: spec?.sizeBytes ?? null,+ gated: spec?.gated === true,+ cached: resolved?.cached === true,+ };+};++/**+ * Everything the user must see BEFORE submitting an upscale (#6509).+ *+ * Read-only by construction: it probes the source with ffprobe, reads the HF+ * cache, and stats a venv path. It queues no job and downloads nothing — the+ * explicit upscale action is the only thing allowed to do either.+ */+export async function planUpscaleHistoryItem(historyId, options = {}) {+ const method = resolveMethod(options);+ const item = await resolveHistoryItem(historyId);+ const alreadyUpscaled = !!item.upscaledFrom;+ const sourcePath = resolveSourcePath(item);++ const [stream, durationSeconds, audio] = await Promise.all([+ probeVideoStreamInfo(sourcePath),+ probeVideoDuration(sourcePath),+ hasAudioStream(sourcePath),+ ]);+ // The header frame count is absent on plenty of containers; fall back to the+ // decode-counting probe rather than reporting "unknown" for a file we can+ // measure. Kept out of the parallel batch above because that fallback can pay+ // for a full decode pass, and most sources never need it. Still nullable when+ // both paths fail.+ const frameCount = stream.frameCount ?? await probeFrameCount(sourcePath);+ const source = {+ width: stream.width,+ height: stream.height,+ fps: stream.fps,+ frameCount,+ durationSeconds,+ hasAudio: audio,+ };++ const alignment = method === 'ltx' ? planLtxAlignment(source) : null;+ const target = planTargetDimensions({ method, ...source, alignment });+ const runtime = method === 'ltx'+ ? describeLtxRuntime()+ : { id: LANCZOS_RUNTIME_ID, label: 'ffmpeg (Lanczos)', supported: true, installed: true, reason: null };+ const adapter = method === 'ltx' ? await describeLtxAdapter() : null;++ return {+ id: item.id,+ method,+ scale: UPSCALE_SCALE,+ alreadyUpscaled,+ source,+ target,+ alignment,+ runtime,+ adapter,+ };+}++// 2× upscale of an existing history item. Writes the upscaled clip to a new+// file (never overwrites the original) and inserts a new history entry pointing+// at it, so the user gets both versions side-by-side in the gallery. Doubles+// width and height; aspect-ratio is preserved exactly.+//+// `options.method` selects the pass: `'lanczos'` (the default, and what every+// pre-#6509 caller gets by omitting the bag) runs the historical ffmpeg filter+// inline. `'ltx'` is accepted by the contract but has no dispatch path until+// #6511 lands, so it fails fast with a capability error naming the runtime it+// would need rather than silently falling back to Lanczos.+//+// Returns the new history entry on success; throws ServerError on any+// missing-input / ffmpeg / file-system failure so the route can map it to+// a clean HTTP status.+export async function upscaleHistoryItem(historyId, options = {}) {+ const method = resolveMethod(options);+ const item = await resolveHistoryItem(historyId);+ if (item.upscaledFrom) {+ throw new ServerError('Cannot upscale an already-upscaled video', { status: 400, code: 'ALREADY_UPSCALED' });+ }+ if (method === 'ltx') {+ const runtime = describeLtxRuntime();+ const named = runtime.id ? `${runtime.label} (${runtime.id})` : `no runtime for ${process.platform}`;+ throw new ServerError(+ `Generative upscale is not available on this install: it needs ${named}, which has no upscale dispatch path yet.`,+ { status: 501, code: 'UNSUPPORTED_RUNTIME' },+ );+ }+ const sourcePath = resolveSourcePath(item);const newId = randomUUID();const newFilename = `${newId}.mp4`;@@ -50,7 +192,7 @@ export async function upscaleHistoryItem(historyId) {// contract intact and means a mid-process kill leaves the source clip// untouched.await copyFileGuarded(sourcePath, newPath);- console.log(`🔍 Upscaling video [${historyId.slice(0, 8)} → ${newId.slice(0, 8)}]: 2×`);+ console.log(`🔍 Upscaling video [${historyId.slice(0, 8)} → ${newId.slice(0, 8)}]: 2× ${method}`);const result = await upscaleVideo2x(newPath);if (!result.ok) {await unlinkGuarded(newPath).catch(() => {});@@ -68,11 +210,18 @@ export async function upscaleHistoryItem(historyId) {...omitRenderTiming(item),id: newId,filename: newFilename,- width: (Number(item.width) || 0) * 2,- height: (Number(item.height) || 0) * 2,+ width: (Number(item.width) || 0) * UPSCALE_SCALE,+ height: (Number(item.height) || 0) * UPSCALE_SCALE,thumbnail,createdAt: new Date().toISOString(),upscaledFrom: item.id,+ // Provenance (#6509): Lanczos is deterministic and seedless, and runs as an+ // ffmpeg filter rather than on a BYOV runtime. Recording both explicitly+ // keeps `upscaleMethod`/`upscaleRuntime` non-null on every upscaled row, so+ // a reader never has to infer "the old one" from an absent key once the+ // generative method starts writing its own.+ upscaleMethod: method,+ upscaleRuntime: LANCZOS_RUNTIME_ID,prompt: item.prompt ? `${item.prompt} (2×)` : '(upscaled 2×)',// Drop hidden so the upscaled version surfaces in the visible gallery// even when the source clip was hidden.diff --git a/server/services/videoGen/upscaleVideo.test.js b/server/services/videoGen/upscaleVideo.test.jsnew file mode 100644index 0000000000..e2a9fd8b18--- /dev/null+++ b/server/services/videoGen/upscaleVideo.test.js@@ -0,0 +1,237 @@+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdirSync, writeFileSync } from 'fs';+import { join } from 'path';+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../../lib/mockPathsDataRoot.js';++// The Lanczos path really copies a file, so PATHS.data must point at a temp+// tree — the install's data/ is the developer's live gallery.+vi.mock('../../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-upscale-') }));+afterAll(cleanupTempDataRoots);++// The method contract (#6509): an absent options bag is exactly the historical+// Lanczos pass, `ltx` is accepted by the contract but has no dispatch path+// until #6511, and the plan endpoint is read-only.++const state = vi.hoisted(() => ({+ history: [],+ stream: { width: 768, height: 512, fps: 24, frameCount: 121 },+ frameCountFallback: null,+ duration: 5.04,+ hasAudio: false,+ runtimeInstalled: true,+ adapterCached: true,+}));++const mutated = vi.hoisted(() => ({ calls: 0 }));++vi.mock('./history.js', () => ({+ loadHistory: vi.fn(async () => state.history),+ mutateVideoHistory: vi.fn(async (mutator) => { mutated.calls += 1; return mutator([...state.history]); }),+}));++vi.mock('../../lib/ffmpeg.js', () => ({+ safeUnder: vi.fn((base, file) => (file ? `${base}/${file}` : null)),+ generateThumbnail: vi.fn(async () => 'thumb.jpg'),+ upscaleVideo2x: vi.fn(async () => ({ ok: true })),+ probeVideoStreamInfo: vi.fn(async () => state.stream),+ probeFrameCount: vi.fn(async () => state.frameCountFallback),+ probeVideoDuration: vi.fn(async () => state.duration),+ hasAudioStream: vi.fn(async () => state.hasAudio),+}));++vi.mock('./runtimes.js', () => ({+ BYOV_RUNTIME_INFO: { ltx25: { label: 'LTX-2.5 MLX' }, ltx25_cuda: { label: 'LTX-2.5 CUDA' } },+ isByovRuntimeInstalled: vi.fn(() => state.runtimeInstalled),+}));++vi.mock('../../lib/icLoraWeights.js', () => ({+ icLoraSpecByKey: vi.fn(() => ({+ id: 'pixel-upscale', label: 'Pixel Spatial Upscaler',+ repo: 'Lightricks/LTX-2.5-22b-IC-LoRA-Pixel-Spatial-Upscaler',+ filename: 'ltx-2.5-22b-ic-lora-pixel-spatial-upscaler-x2-1.0.safetensors',+ sizeBytes: 327_322_640, gated: true,+ })),+ icLoraWeightKey: vi.fn((spec) => spec?.id ?? null),+ resolveIcLoraWeightByKey: vi.fn(async () => ({ path: state.adapterCached ? '/cache/weight.safetensors' : null, cached: state.adapterCached })),+}));++const { upscaleHistoryItem, planUpscaleHistoryItem } = await import('./upscaleVideo.js');+const { PATHS } = await import('../../lib/fileUtils.js');+const { LANCZOS_PROVENANCE_FIELDS } = await import('./upscalePlan.js');+const ffmpeg = await import('../../lib/ffmpeg.js');+const { mutateVideoHistory } = await import('./history.js');++const SOURCE_ID = '11111111-1111-4111-8111-111111111111';+const sourceRow = (extra = {}) => ({+ id: SOURCE_ID, filename: `${SOURCE_ID}.mp4`, prompt: 'a lighthouse',+ modelId: 'ltx2_unified', width: 768, height: 512, numFrames: 121, fps: 24, seed: 7, ...extra,+});++beforeEach(() => {+ // A real (tiny) source clip on disk: the copy-then-transform contract is the+ // thing under test, and stubbing the filesystem out would hide it.+ mkdirSync(PATHS.videos, { recursive: true });+ writeFileSync(join(PATHS.videos, `${SOURCE_ID}.mp4`), 'not really a video');+ state.history = [sourceRow()];+ state.stream = { width: 768, height: 512, fps: 24, frameCount: 121 };+ state.frameCountFallback = null;+ state.duration = 5.04;+ state.hasAudio = false;+ state.runtimeInstalled = true;+ state.adapterCached = true;+ mutated.calls = 0;+ vi.clearAllMocks();+});++describe('upscaleHistoryItem — method selection', () => {+ it('treats an absent options bag as the historical lanczos pass', async () => {+ const entry = await upscaleHistoryItem(SOURCE_ID);+ expect(ffmpeg.upscaleVideo2x).toHaveBeenCalledTimes(1);+ expect(entry).toMatchObject({+ upscaledFrom: SOURCE_ID, upscaleMethod: 'lanczos', upscaleRuntime: 'ffmpeg',+ width: 1536, height: 1024, hidden: false,+ });+ });++ it('produces the same row for an explicit lanczos request', async () => {+ const implicit = await upscaleHistoryItem(SOURCE_ID);+ const explicit = await upscaleHistoryItem(SOURCE_ID, { method: 'lanczos' });+ // Ids, filenames and timing are minted per call; everything describing the+ // PASS must match, or the default was not preserved.+ const shape = ({ id, filename, thumbnail, createdAt, renderStartedAt, renderCompletedAt, renderMs, ...rest }) => rest;+ expect(shape(explicit)).toEqual(shape(implicit));+ });++ it('writes every provenance field lanczos owns', async () => {+ const entry = await upscaleHistoryItem(SOURCE_ID);+ for (const field of LANCZOS_PROVENANCE_FIELDS) {+ expect(entry[field], `missing provenance field ${field}`).toBeDefined();+ }+ });++ it('leaves the source render seed on the row rather than nulling it', async () => {+ // The upscaled row inherits the SOURCE's fields by design; `upscaleMethod`+ // is what tells a reader the seed did not drive this pass.+ const entry = await upscaleHistoryItem(SOURCE_ID);+ expect(entry.seed).toBe(7);+ });++ it('rejects an unknown method before reading the history file', async () => {+ const { loadHistory } = await import('./history.js');+ await expect(upscaleHistoryItem(SOURCE_ID, { method: 'realesrgan' }))+ .rejects.toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });+ expect(loadHistory).not.toHaveBeenCalled();+ });++ it('fails the generative method with a capability error naming the runtime', async () => {+ await expect(upscaleHistoryItem(SOURCE_ID, { method: 'ltx' }))+ .rejects.toMatchObject({ status: 501, code: 'UNSUPPORTED_RUNTIME' });+ });++ it('queues nothing and writes nothing when the generative method is refused', async () => {+ await upscaleHistoryItem(SOURCE_ID, { method: 'ltx' }).catch(() => {});+ expect(ffmpeg.upscaleVideo2x).not.toHaveBeenCalled();+ expect(mutateVideoHistory).not.toHaveBeenCalled();+ });++ it('keeps the already-upscaled guard ahead of the capability error', async () => {+ // Otherwise adding a method would change the status code an existing client+ // sees for a source it must not re-upscale.+ state.history = [sourceRow({ upscaledFrom: 'aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaa1' })];+ for (const options of [undefined, { method: 'ltx' }]) {+ await expect(upscaleHistoryItem(SOURCE_ID, options))+ .rejects.toMatchObject({ status: 400, code: 'ALREADY_UPSCALED' });+ }+ });++it('keeps the missing-id, missing-row and missing-file statuses', async () => {+ await expect(upscaleHistoryItem('not-a-uuid')).rejects.toMatchObject({ status: 400 });+ state.history = [];+ await expect(upscaleHistoryItem(SOURCE_ID)).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });+ state.history = [sourceRow({ filename: 'never-written.mp4' })];+ await expect(upscaleHistoryItem(SOURCE_ID)).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });+ });+});++describe('planUpscaleHistoryItem', () => {+ it('reports the source geometry and a plain 2x target for lanczos', async () => {+ const plan = await planUpscaleHistoryItem(SOURCE_ID);+ expect(plan).toMatchObject({+ id: SOURCE_ID, method: 'lanczos', scale: 2, alreadyUpscaled: false, alignment: null, adapter: null,+ });+ expect(plan.source).toEqual({ width: 768, height: 512, fps: 24, frameCount: 121, durationSeconds: 5.04, hasAudio: false });+ expect(plan.target).toEqual({ width: 1536, height: 1024, frameCount: 121 });+ });++ it('reports zero padding for a generative source that already conforms', async () => {+ const plan = await planUpscaleHistoryItem(SOURCE_ID, { method: 'ltx' });+ expect(plan.alignment).toMatchObject({ padWidth: 0, padHeight: 0, padFrames: 0, trimFrames: 0, conforming: true });+ expect(plan.target).toEqual({ width: 1536, height: 1024, frameCount: 121 });+ });++ it('reports the padding a non-conforming source needs BEFORE submit', async () => {+ state.stream = { width: 848, height: 480, fps: 24, frameCount: 100 };+ const plan = await planUpscaleHistoryItem(SOURCE_ID, { method: 'ltx' });+ expect(plan.alignment).toMatchObject({ padWidth: 16, padHeight: 0, padFrames: 5, trimFrames: 0, conforming: false });+ expect(plan.target).toEqual({ width: 1728, height: 960, frameCount: 105 });+ });++ it('falls back to the decode-counting probe when the container header has no frame count', async () => {+ state.stream = { width: 768, height: 512, fps: 24, frameCount: null };+ state.frameCountFallback = 121;+ const plan = await planUpscaleHistoryItem(SOURCE_ID, { method: 'ltx' });+ expect(plan.source.frameCount).toBe(121);+ expect(plan.alignment.conforming).toBe(true);+ });++ it('reports an unmeasurable frame count as unknown rather than conforming', async () => {+ state.stream = { width: 768, height: 512, fps: 24, frameCount: null };+ state.frameCountFallback = null;+ const plan = await planUpscaleHistoryItem(SOURCE_ID, { method: 'ltx' });+ expect(plan.source.frameCount).toBeNull();+ expect(plan.alignment.conforming).toBeNull();+ });++ it('reports an already-upscaled source instead of throwing', async () => {+ state.history = [sourceRow({ upscaledFrom: 'aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaa1' })];+ const plan = await planUpscaleHistoryItem(SOURCE_ID, { method: 'ltx' });+ expect(plan.alreadyUpscaled).toBe(true);+ });++ it('reports audio presence so the caller can disclose what happens to the track', async () => {+ state.hasAudio = true;+ const plan = await planUpscaleHistoryItem(SOURCE_ID);+ expect(plan.source.hasAudio).toBe(true);+ });++ it('reports runtime and adapter readiness for the generative method', async () => {+ const ready = await planUpscaleHistoryItem(SOURCE_ID, { method: 'ltx' });+ expect(ready.runtime).toMatchObject({ supported: true, installed: true, reason: null });+ expect(ready.adapter).toMatchObject({ key: 'pixel-upscale', cached: true, gated: true });++ state.runtimeInstalled = false;+ state.adapterCached = false;+ const unready = await planUpscaleHistoryItem(SOURCE_ID, { method: 'ltx' });+ expect(unready.runtime.installed).toBe(false);+ expect(unready.runtime.reason).toMatch(/not installed/i);+ expect(unready.adapter.cached).toBe(false);+ });++ it('queues no job, runs no ffmpeg pass and writes no history row', async () => {+ await planUpscaleHistoryItem(SOURCE_ID, { method: 'ltx' });+ await planUpscaleHistoryItem(SOURCE_ID, { method: 'lanczos' });+ expect(ffmpeg.upscaleVideo2x).not.toHaveBeenCalled();+ expect(ffmpeg.generateThumbnail).not.toHaveBeenCalled();+ expect(mutateVideoHistory).not.toHaveBeenCalled();+ expect(mutated.calls).toBe(0);+ });++ it('rejects an unknown method and the same bad-id statuses as the action', async () => {+ await expect(planUpscaleHistoryItem(SOURCE_ID, { method: 'realesrgan' }))+ .rejects.toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });+ await expect(planUpscaleHistoryItem('not-a-uuid')).rejects.toMatchObject({ status: 400 });+ state.history = [];+ await expect(planUpscaleHistoryItem(SOURCE_ID)).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });+ });+});