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

feat(video-gen): add IC-LoRA Control mode to local LTX-2 generation

[._.]/ Adam Eivy018a720dfba0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4fc4dbd3ad..7ce05674bf 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -47,3 +47,7 @@
- The reconciler's blanket "never merge unreviewed work" rule read as a veto on the merge step it was supposed to perform, so it has been replaced by the explicit gate each branch already carries (required CI green, mergeable, and the review it names). Merging still only ever happens through `gh pr merge` on a branch the task was handed.
- Waiting for a Copilot review on an in-review pull request is now time-boxed to 10 minutes — on a repository without Copilot review enabled, the old unbounded wait could strand a green pull request open indefinitely.
- The merge itself is no longer pinned to a merge commit: on a repository that disallows one, the agent retries with squash and then rebase instead of stranding the branch. It also merges from the repository root and tears the worktree down before deleting the branch, so the cleanup can't fail on a branch that's still checked out.
+
+## Video generation
+
+- **[issue-3100] New Control mode for local video generation** — feed a control clip (a depth pass, a pose track, edges) alongside your prompt and the render follows its structure and motion instead of inventing them. The reference can be a fresh upload or any prior render from your history, and a strength slider dials how tightly the output tracks it. A half-res preview toggle skips the refinement pass so you can check whether a control clip fits before committing to a full render. Requires an LTX-2 model; the ~654 MB Control weight downloads with progress from the mode panel and is covered by the existing model verify/repair buttons.
diff --git a/client/src/components/videoGen/AudioPanel.jsx b/client/src/components/videoGen/AudioPanel.jsx
index 376fb132ac..948b33ff21 100644
--- a/client/src/components/videoGen/AudioPanel.jsx
+++ b/client/src/components/videoGen/AudioPanel.jsx
@@ -8,6 +8,7 @@
import { Upload, Music } from 'lucide-react';
import { formatBytes } from '../../utils/formatters';
import FilePickerButton from '../ui/FilePickerButton';
+import Ltx2RuntimeMissingNotice from './Ltx2RuntimeMissingNotice';
export default function AudioPanel({ audioFile, numFrames, fps, hasCompatibleModel, onPick, onClear }) {
return (
@@ -37,14 +38,7 @@ export default function AudioPanel({ audioFile, numFrames, fps, hasCompatibleMod
<p className="text-[10px] text-gray-500 leading-snug">
Audio length should match {`${(numFrames / fps).toFixed(1)}s`} (frames ÷ fps). Longer clips are trimmed to fit; shorter clips fail.
</p>
- {!hasCompatibleModel && (
- <p className="text-[11px] text-port-warning">
- a2v requires an ltx2-runtime model, but none are installed. Add a dgrauet entry to{' '}
- <code>data/media-models.json</code> (or restore <code>ltx23_dgrauet_q4</code> / <code>_q8</code>{' '}
- from the built-in defaults), then provision the runtime via{' '}
- <code>INSTALL_LTX2=1 bash scripts/setup-image-video.sh</code>.
- </p>
- )}
+ {!hasCompatibleModel && <Ltx2RuntimeMissingNotice subject="a2v" />}
</div>
);
}
diff --git a/client/src/components/videoGen/IcLoraPanel.jsx b/client/src/components/videoGen/IcLoraPanel.jsx
new file mode 100644
index 0000000000..fd3d9c1664
--- /dev/null
+++ b/client/src/components/videoGen/IcLoraPanel.jsx
@@ -0,0 +1,151 @@
+/**
+ * IC-LoRA remix panel (issue #3100) — dgrauet/ltx2 runtime only. The user
+ * supplies a reference clip (upload or a prior render) that the fused IC-LoRA
+ * reads structure/motion out of, then dials how strongly it conditions.
+ *
+ * Presentational — the reference upload File, the picked history ids, the
+ * strength dials, the weight's download status, and the "no compatible model
+ * installed" condition are all owned by the VideoGen page. `onPickHistory('')`
+ * clears the history selection.
+ *
+ * The IC-LoRA weight is a separate several-hundred-MB HF pull, so the panel
+ * hosts its own ModelDownloadBadge: without it a first render silently stalls
+ * on an un-progressed download inside the Python child.
+ */
+import { Upload, Film } from 'lucide-react';
+import { formatBytes } from '../../utils/formatters';
+import { icResolutionIssue } from '../../lib/videoGenParams';
+import FilePickerButton from '../ui/FilePickerButton';
+import ModelDownloadBadge from '../media/ModelDownloadBadge';
+import Ltx2RuntimeMissingNotice from './Ltx2RuntimeMissingNotice';
+
+export default function IcLoraPanel({
+ spec, // { mode, label, desc, referenceDownscaleFactor, min/maxReferences }
+ referenceFile, // File | null — fresh upload
+ referenceVideoId, // string — picked prior render (mutually exclusive with the upload)
+ inFlightReferenceNames = [], // display-only basenames of a resumed in-flight render
+ visibleHistory,
+ icStrength,
+ icSkipStage2,
+ width,
+ height,
+ weightStatus, // ModelDownloadBadge status for the IC-LoRA weight
+ hasCompatibleModel,
+ onPickFile,
+ onClearFile,
+ onPickHistory,
+ onStrengthChange,
+ onSkipStage2Change,
+ onDownloadWeight,
+ onCancelWeightDownload,
+}) {
+ // Same helper the page's submit gate uses, so the warning and the disabled
+ // button can't disagree (and both match the server's rejection message).
+ const resolutionIssue = icResolutionIssue(spec, width, height);
+ const strengthId = `ic-strength-${spec.mode}`;
+ const skipId = `ic-skip-stage2-${spec.mode}`;
+
+ return (
+ <div className="border border-port-border/50 rounded-lg p-2 space-y-1.5">
+ <div className="flex items-center justify-between">
+ <span className="text-[11px] font-medium text-gray-400">{spec.label} reference</span>
+ {(referenceFile || referenceVideoId) && (
+ <button
+ type="button"
+ onClick={() => { onClearFile(); onPickHistory(''); }}
+ className="text-[11px] text-port-error hover:underline"
+ >
+ Clear
+ </button>
+ )}
+ </div>
+
+ {referenceFile ? (
+ <div className="flex items-center gap-2 text-[11px] text-gray-300">
+ <Film className="w-3.5 h-3.5 text-port-accent" />
+ <span className="truncate" title={referenceFile.name}>{referenceFile.name}</span>
+ <span className="text-gray-500">{formatBytes(referenceFile.size, 2)}</span>
+ </div>
+ ) : (
+ <>
+ <FilePickerButton
+ accept={`${spec.referenceKind}/*`}
+ onChange={(e) => onPickFile(e.target.files?.[0] || null)}
+ className="flex items-center gap-2 text-[11px] text-gray-400 hover:text-white"
+ >
+ <Upload className="w-3.5 h-3.5" />
+ <span className="truncate">{spec.uploadLabel}</span>
+ </FilePickerButton>
+ <select
+ value={referenceVideoId}
+ onChange={(e) => onPickHistory(e.target.value)}
+ aria-label={`Pick a previous render as the ${spec.label} reference`}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-xs text-white focus:outline-none focus:border-port-accent"
+ >
+ <option value="">…or pick a previous render</option>
+ {visibleHistory.slice(0, 50).map((v) => (
+ <option key={v.id} value={v.id}>
+ {(v.prompt || v.filename || v.id).slice(0, 80)}
+ </option>
+ ))}
+ </select>
+ </>
+ )}
+
+ {!referenceFile && !referenceVideoId && inFlightReferenceNames.length > 0 && (
+ <p className="text-[10px] text-gray-500">
+ In-flight render is conditioned on {inFlightReferenceNames.join(', ')} — re-pick a reference to run a new one.
+ </p>
+ )}
+
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
+ <div>
+ <label htmlFor={strengthId} className="block text-[10px] text-gray-500 mb-1">
+ Reference strength {Number(icStrength).toFixed(2)}
+ </label>
+ <input
+ id={strengthId}
+ type="range"
+ min="0"
+ max="1"
+ step="0.05"
+ value={icStrength}
+ onChange={(e) => onStrengthChange(Number(e.target.value))}
+ className="w-full accent-port-accent"
+ />
+ </div>
+ <label htmlFor={skipId} className="flex items-center gap-2 text-[11px] text-gray-400 sm:mt-4">
+ <input
+ id={skipId}
+ type="checkbox"
+ checked={icSkipStage2}
+ onChange={(e) => onSkipStage2Change(e.target.checked)}
+ className="accent-port-accent"
+ />
+ <span>Half-res preview (skip refine)</span>
+ </label>
+ </div>
+
+ <p className="text-[10px] text-gray-500 leading-snug">
+ {spec.description}. The reference is trimmed to fit the frame count.
+ </p>
+
+ {resolutionIssue && (
+ <p className="text-[11px] text-port-warning">
+ {resolutionIssue} Adjust the resolution first.
+ </p>
+ )}
+
+ {hasCompatibleModel && weightStatus && (
+ <ModelDownloadBadge
+ status={weightStatus}
+ onDownload={onDownloadWeight}
+ onCancel={onCancelWeightDownload}
+ estimateLabel={weightStatus.estimatedBytes ? `~${formatBytes(weightStatus.estimatedBytes, 0)}` : undefined}
+ />
+ )}
+
+ {!hasCompatibleModel && <Ltx2RuntimeMissingNotice subject={spec.label} />}
+ </div>
+ );
+}
diff --git a/client/src/components/videoGen/IcLoraPanel.test.jsx b/client/src/components/videoGen/IcLoraPanel.test.jsx
new file mode 100644
index 0000000000..2c8eabd58a
--- /dev/null
+++ b/client/src/components/videoGen/IcLoraPanel.test.jsx
@@ -0,0 +1,96 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import IcLoraPanel from './IcLoraPanel';
+import { icLoraSpecForMode } from '../../lib/videoGenParams';
+
+const SPEC = icLoraSpecForMode('ic-control');
+
+const baseProps = {
+ spec: SPEC,
+ referenceFile: null,
+ referenceVideoId: '',
+ visibleHistory: [{ id: 'v1', prompt: 'a prior render', filename: 'v1.mp4' }],
+ icStrength: 1,
+ icSkipStage2: false,
+ // Divisible by the Control weight's factor of 2 → no resolution warning.
+ width: 704,
+ height: 448,
+ weightStatus: { id: 'ic-control', repo: 'org/weight', cached: true, sizeBytes: 654 * 1024 * 1024 },
+ hasCompatibleModel: true,
+ onPickFile: vi.fn(),
+ onClearFile: vi.fn(),
+ onPickHistory: vi.fn(),
+ onStrengthChange: vi.fn(),
+ onSkipStage2Change: vi.fn(),
+ onDownloadWeight: vi.fn(),
+ onCancelWeightDownload: vi.fn(),
+};
+
+describe('IcLoraPanel', () => {
+ it('offers both an upload and a history pick when nothing is selected', () => {
+ render(<IcLoraPanel {...baseProps} />);
+ expect(screen.getByText(/Upload a control clip/i)).toBeTruthy();
+ expect(screen.getByLabelText(/Pick a previous render as the Control reference/i)).toBeTruthy();
+ expect(screen.queryByText('Clear')).toBeNull();
+ });
+
+ it('shows the picked upload name and hides the pickers', () => {
+ const file = new File(['x'.repeat(1024)], 'depth.mp4', { type: 'video/mp4' });
+ render(<IcLoraPanel {...baseProps} referenceFile={file} />);
+ expect(screen.getByText('depth.mp4')).toBeTruthy();
+ // Only one reference shape is valid per request, so the alternate inputs go
+ // away rather than letting the user set both.
+ expect(screen.queryByText(/Upload a control clip/i)).toBeNull();
+ expect(screen.queryByLabelText(/Pick a previous render/i)).toBeNull();
+ });
+
+ it('fires onClearFile AND onPickHistory("") from Clear', () => {
+ const onClearFile = vi.fn();
+ const onPickHistory = vi.fn();
+ render(
+ <IcLoraPanel
+ {...baseProps}
+ referenceVideoId="v1"
+ onClearFile={onClearFile}
+ onPickHistory={onPickHistory}
+ />,
+ );
+ fireEvent.click(screen.getByText('Clear'));
+ // Both shapes clear together — a half-cleared state would submit the
+ // survivor unknowingly.
+ expect(onClearFile).toHaveBeenCalled();
+ expect(onPickHistory).toHaveBeenCalledWith('');
+ });
+
+ it('warns when the resolution is not divisible by the reference-downscale factor', () => {
+ render(<IcLoraPanel {...baseProps} width={705} />);
+ expect(screen.getByText(/divisible by 2/i)).toBeTruthy();
+ });
+
+ it('does not warn on a divisible resolution', () => {
+ render(<IcLoraPanel {...baseProps} />);
+ expect(screen.queryByText(/divisible by 2/i)).toBeNull();
+ });
+
+ it('reports the strength dial and skip-stage-2 toggle', () => {
+ const onStrengthChange = vi.fn();
+ const onSkipStage2Change = vi.fn();
+ render(
+ <IcLoraPanel {...baseProps} onStrengthChange={onStrengthChange} onSkipStage2Change={onSkipStage2Change} />,
+ );
+ fireEvent.change(screen.getByLabelText(/Reference strength/i), { target: { value: '0.5' } });
+ expect(onStrengthChange).toHaveBeenCalledWith(0.5);
+ fireEvent.click(screen.getByLabelText(/Half-res preview/i));
+ expect(onSkipStage2Change).toHaveBeenCalledWith(true);
+ });
+
+ it('surfaces the no-ltx2-model warning instead of the weight badge', () => {
+ render(<IcLoraPanel {...baseProps} hasCompatibleModel={false} />);
+ expect(screen.getByText(/requires an ltx2-runtime model/i)).toBeTruthy();
+ });
+
+ it('names the in-flight reference when a resumed render has no re-pickable clip', () => {
+ render(<IcLoraPanel {...baseProps} inFlightReferenceNames={['depth.mp4']} />);
+ expect(screen.getByText(/In-flight render is conditioned on depth\.mp4/i)).toBeTruthy();
+ });
+});
diff --git a/client/src/components/videoGen/Ltx2RuntimeMissingNotice.jsx b/client/src/components/videoGen/Ltx2RuntimeMissingNotice.jsx
new file mode 100644
index 0000000000..e9e44715ba
--- /dev/null
+++ b/client/src/components/videoGen/Ltx2RuntimeMissingNotice.jsx
@@ -0,0 +1,19 @@
+/**
+ * "No ltx2-runtime model installed" notice, shared by every mode panel whose
+ * pipeline only exists on the dgrauet/ltx2 runtime (Audio, the IC-LoRA remix
+ * modes). The install instructions name specific model ids and a setup-script
+ * invocation, so a copy per panel would drift the moment either changes.
+ *
+ * `subject` names the blocked capability ("a2v", "Control") — the rest of the
+ * guidance is identical regardless of which mode is asking.
+ */
+export default function Ltx2RuntimeMissingNotice({ subject }) {
+ return (
+ <p className="text-[11px] text-port-warning">
+ {subject} requires an ltx2-runtime model, but none are installed. Add a dgrauet entry to{' '}
+ <code>data/media-models.json</code> (or restore <code>ltx23_dgrauet_q4</code> / <code>_q8</code>{' '}
+ from the built-in defaults), then provision the runtime via{' '}
+ <code>INSTALL_LTX2=1 bash scripts/setup-image-video.sh</code>.
+ </p>
+ );
+}
diff --git a/client/src/hooks/useModelDownloadStatus.js b/client/src/hooks/useModelDownloadStatus.js
index 5c3bcb5f6d..039572fdc6 100644
--- a/client/src/hooks/useModelDownloadStatus.js
+++ b/client/src/hooks/useModelDownloadStatus.js
@@ -1,10 +1,11 @@
import { useEffect, useState, useCallback, useMemo } from 'react';
import { useSseProgress } from './useSseProgress.js';
+import { isIcLoraMode } from '../lib/videoGenParams.js';
import toast from '../components/ui/Toast';
import {
getImageModelStatuses, getVideoModelStatuses,
verifyImageModels, verifyVideoModels, repairImageModel, repairVideoModel,
- repairTextEncoder,
+ repairTextEncoder, repairIcLora,
} from '../services/apiImageVideo.js';
// Sentinel `modelId` used to drive a text-encoder download instead of a model
@@ -13,6 +14,11 @@ import {
// callers and the hook agree on the magic string.
export const TEXT_ENCODER_DOWNLOAD_ID = '__text_encoder__';
+// IC-LoRA remix weights (issue #3100) are downloadable but aren't registry
+// models, so — like the text encoder — they route to a dedicated endpoint.
+// Callers pass the remix mode itself ('ic-control') as the download id, and
+// membership in the mode registry (NOT a raw `ic-` string prefix) is what
+// identifies one — so an id can never be misrouted by coincidence of naming.
const buildDownloadUrl = (kind, modelId, force = false) => {
if (!modelId) return null;
// A repair-initiated re-download appends `?force=1` so the server re-fetches
@@ -23,6 +29,9 @@ const buildDownloadUrl = (kind, modelId, force = false) => {
if (kind === 'video' && modelId === TEXT_ENCODER_DOWNLOAD_ID) {
return `/api/video-gen/text-encoder/download${q}`;
}
+ if (kind === 'video' && isIcLoraMode(modelId)) {
+ return `/api/video-gen/ic-loras/${encodeURIComponent(modelId)}/download${q}`;
+ }
return `/api/${kind}-gen/models/${encodeURIComponent(modelId)}/download${q}`;
};
@@ -53,7 +62,10 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
setExtra({});
} else if (kind === 'video') {
setStatuses(Array.isArray(body?.models) ? body.models : []);
- setExtra({ textEncoder: body?.textEncoder || null });
+ setExtra({
+ textEncoder: body?.textEncoder || null,
+ icLoras: Array.isArray(body?.icLoras) ? body.icLoras : [],
+ });
} else {
setStatuses(Array.isArray(body) ? body : []);
setExtra({});
@@ -119,9 +131,12 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
// /text-encoder/repair endpoint; the sentinel `start()` below already maps
// to the dedicated /text-encoder/download SSE for the clean re-fetch.
const isTextEncoder = kind === 'video' && modelId === TEXT_ENCODER_DOWNLOAD_ID;
+ const isIcLora = kind === 'video' && isIcLoraMode(modelId);
const run = isTextEncoder
? () => repairTextEncoder({ deep })
- : () => (kind === 'video' ? repairVideoModel : repairImageModel)(modelId, { deep });
+ : isIcLora
+ ? () => repairIcLora(modelId, { deep })
+ : () => (kind === 'video' ? repairVideoModel : repairImageModel)(modelId, { deep });
const result = await run().catch((err) => {
toast.error(err?.message || 'Repair failed');
return null;
@@ -150,19 +165,29 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
// hand a fresh object to every non-active model's badge (only the active
// one re-renders). For inactive models we return the raw entry, which is
// referentially stable across frames.
+ // Look an id up across every download-able collection. IC-LoRA weights
+ // (issue #3100) arrive under `extra.icLoras` rather than `statuses` — they're
+ // not registry models — but they share the `{ id, repo, cached, sizeBytes,
+ // integrity }` badge shape, so one resolver keeps every caller uniform.
+ const findEntry = useCallback((modelId) => {
+ const list = Array.isArray(statuses) ? statuses : [];
+ const found = list.find((s) => s.id === modelId);
+ if (found) return found;
+ const icList = Array.isArray(extra.icLoras) ? extra.icLoras : [];
+ return icList.find((s) => s.id === modelId) || null;
+ }, [statuses, extra.icLoras]);
+
const activeStatus = useMemo(() => {
if (!activeModelId) return null;
- const list = Array.isArray(statuses) ? statuses : [];
- const entry = list.find((s) => s.id === activeModelId);
+ const entry = findEntry(activeModelId);
if (!entry) return null;
return { ...entry, downloading: true, progress: sse.latest };
- }, [activeModelId, statuses, sse.latest]);
+ }, [activeModelId, findEntry, sse.latest]);
const getStatus = useCallback((modelId) => {
if (modelId === activeModelId) return activeStatus;
- const list = Array.isArray(statuses) ? statuses : [];
- return list.find((s) => s.id === modelId) || null;
- }, [statuses, activeModelId, activeStatus]);
+ return findEntry(modelId);
+ }, [findEntry, activeModelId, activeStatus]);
return {
statuses,
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index c16099e11f..a419a9b482 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -58,7 +58,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `imageGenResolutions.js` | Shared resolution presets for image generation. |
| `importerDeepLink.js` | The Importer deep-link contract both ways: `buildImporterLink({ universeId, seriesId, seriesName })` builds the `/importer?…` URL a Series Pipeline page navigates to; `resolveImporterDeepLink(...)` reads those params back into the universe + series names the importer matches on. |
| `muscriptorModels.js` | `MUSCRIPTOR_MODELS` (audio → MIDI size tiers `small`/`medium`/`large`) + `DEFAULT_MUSCRIPTOR_MODEL`. Single source consumed by the transcribe `<select>`s in `MusicVideo.jsx` and `ReferenceAnalysis.jsx`. Mirrors the server's `MUSCRIPTOR_MODELS` in `server/services/audioMidiTranscription.js`. |
-| `videoGenParams.js` | Pure VideoGen param helpers: `FRAME_OPTIONS`/`FPS_OPTIONS`/`VIDEO_EDGE_BOUNDS` constants, `videoModelMemoryGb()` (model memory footprint), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v→ltx2 gate). |
+| `videoGenParams.js` | Pure VideoGen param helpers: `FRAME_OPTIONS`/`FPS_OPTIONS`/`VIDEO_EDGE_BOUNDS` constants, `videoModelMemoryGb()` (model memory footprint), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v + IC-remix → ltx2 gate). Also mirrors the IC-LoRA remix registry (`IC_LORA_MODES`/`IC_LORA_MODE_VALUES`/`isIcLoraMode()`/`icLoraSpecForMode()`/`icResolutionIssue()`) from `server/lib/icLoraWeights.js` so the form validates a reference render pre-submit — pinned by `server/lib/icLoraWeights.parity.test.js`. |
| `videoGenResolutions.js` | Shared resolution presets for video generation (companion to image side; LTX-2 latent-friendly sizes) + `snapAspectToImage()` to pick the closest-aspect preset for an I2V source. |
| `videoTilingOptions.js` | `VIDEO_TILING_OPTIONS` (the `<select>` rows) + `VIDEO_TILING_ENUM_SET` (the value-only Set). Single source consumed by `VideoGen.jsx` and the Remix URL builder in `useMediaPreviewActions`. Mirrors the server's `z.enum` in `server/routes/videoGen.js`. |
diff --git a/client/src/lib/videoGenParams.js b/client/src/lib/videoGenParams.js
index 798865586d..728b42d532 100644
--- a/client/src/lib/videoGenParams.js
+++ b/client/src/lib/videoGenParams.js
@@ -49,13 +49,56 @@ export const computeFflfSafeFrames = (width, height, numFrames, budget) => {
return safeLatent * 8 + 1;
};
-// Mode-compatibility predicate for the Model dropdown. a2v requires the
-// ltx2 runtime (dgrauet's pipeline) — the legacy mlx_video pipeline has no
-// audio-conditioned mode, and Wan/Hunyuan don't either. Server enforces the
-// same rule in routes/videoGen.js (A2V_REQUIRES_LTX2); filtering client-side
-// keeps the dropdown honest so the user can't pick a doomed model.
+// IC-LoRA remix modes (issue #3100) — mirror of the server registry in
+// server/lib/icLoraWeights.js, which is the source of truth. The client needs
+// the labels, the input-surface descriptors, and the reference-count/resolution
+// rules to render the panel and validate before submit; the weight repo/filename
+// stays server-side (the client never resolves a weight path).
+//
+// Field names match the server entry exactly so drift is mechanically
+// detectable: server/lib/icLoraWeights.parity.test.js imports BOTH modules and
+// diffs the mirrored fields, so adding a mode (or changing a bound) without
+// updating this list fails CI instead of silently letting the form accept a
+// render the route rejects.
+export const IC_LORA_MODES = [
+ {
+ mode: 'ic-control',
+ label: 'Control',
+ description: 'Structure + motion from a control clip',
+ uploadLabel: 'Upload a control clip (depth / pose / edges)',
+ // The IC encoder downscales the reference by this factor, and the pipeline
+ // requires the OUTPUT dimensions to divide evenly by it (the server rejects
+ // otherwise with IC_LORA_RESOLUTION_NOT_DIVISIBLE).
+ referenceDownscaleFactor: 2,
+ minReferences: 1,
+ maxReferences: 1,
+ referenceKind: 'video',
+ },
+];
+
+export const IC_LORA_MODE_VALUES = IC_LORA_MODES.map((m) => m.mode);
+export const isIcLoraMode = (mode) => IC_LORA_MODE_VALUES.includes(mode);
+export const icLoraSpecForMode = (mode) => IC_LORA_MODES.find((m) => m.mode === mode) || null;
+
+// Mirror of icResolutionIssue in server/lib/icLoraWeights.js: a human message
+// when the output dimensions aren't divisible by the weight's reference-downscale
+// factor, else null. One implementation so the panel's warning and the submit
+// gate can never disagree.
+export const icResolutionIssue = (spec, width, height) => {
+ const scale = spec?.referenceDownscaleFactor ?? 1;
+ if (scale <= 1) return null;
+ if (Number(width) % scale === 0 && Number(height) % scale === 0) return null;
+ return `${spec.label} mode needs a resolution divisible by ${scale} (its reference encoder downscales by ${scale}); got ${width}×${height}.`;
+};
+
+// Mode-compatibility predicate for the Model dropdown. a2v and the IC-LoRA
+// remix modes require the ltx2 runtime (dgrauet's pipeline) — the legacy
+// mlx_video pipeline has no audio-conditioned mode and no IC pipeline, and
+// Wan/Hunyuan don't either. Server enforces the same rules in
+// routes/videoGen.js (A2V_REQUIRES_LTX2 / IC_LORA_REQUIRES_LTX2); filtering
+// client-side keeps the dropdown honest so the user can't pick a doomed model.
export const isModelAllowedForMode = (model, mode) => {
if (!model) return false;
- if (mode === 'a2v') return model.runtime === 'ltx2';
+ if (mode === 'a2v' || isIcLoraMode(mode)) return model.runtime === 'ltx2';
return true;
};
diff --git a/client/src/lib/videoGenParams.test.js b/client/src/lib/videoGenParams.test.js
index 35df0ebcdc..b390fb5333 100644
--- a/client/src/lib/videoGenParams.test.js
+++ b/client/src/lib/videoGenParams.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';
import {
videoModelMemoryGb, computeFflfSafeFrames, isModelAllowedForMode,
VIDEO_EDGE_BOUNDS, FRAME_OPTIONS, FPS_OPTIONS,
+ IC_LORA_MODES, IC_LORA_MODE_VALUES, isIcLoraMode, icLoraSpecForMode,
} from './videoGenParams.js';
describe('videoModelMemoryGb', () => {
@@ -65,3 +66,35 @@ describe('constants', () => {
expect(FPS_OPTIONS).toEqual([16, 24, 30]);
});
});
+
+describe('IC-LoRA remix modes (#3100)', () => {
+ it('mirrors the server registry shape', () => {
+ expect(IC_LORA_MODE_VALUES).toEqual(['ic-control']);
+ for (const spec of IC_LORA_MODES) {
+ // The `ic-` prefix drives the download-id router in useModelDownloadStatus.
+ expect(spec.mode.startsWith('ic-')).toBe(true);
+ expect(spec.maxReferences).toBeGreaterThanOrEqual(spec.minReferences);
+ expect(spec.referenceDownscaleFactor).toBeGreaterThanOrEqual(1);
+ }
+ });
+ it('identifies IC modes', () => {
+ expect(isIcLoraMode('ic-control')).toBe(true);
+ expect(isIcLoraMode('text')).toBe(false);
+ expect(isIcLoraMode(undefined)).toBe(false);
+ });
+ it('resolves a spec by mode, null otherwise', () => {
+ expect(icLoraSpecForMode('ic-control')?.label).toBe('Control');
+ expect(icLoraSpecForMode('extend')).toBeNull();
+ });
+ it('requires the ltx2 runtime for IC modes', () => {
+ expect(isModelAllowedForMode({ runtime: 'ltx2' }, 'ic-control')).toBe(true);
+ expect(isModelAllowedForMode({ runtime: 'mlx_video' }, 'ic-control')).toBe(false);
+ expect(isModelAllowedForMode({ runtime: 'wan22' }, 'ic-control')).toBe(false);
+ });
+ it('keeps the Control resolution rule aligned with the server (factor 2)', () => {
+ // Mirrors server/lib/icLoraWeights.js — a drift here would let the form
+ // accept a resolution the server rejects with
+ // IC_LORA_RESOLUTION_NOT_DIVISIBLE.
+ expect(icLoraSpecForMode('ic-control').referenceDownscaleFactor).toBe(2);
+ });
+});
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 512e49a3d2..b9414bd3b8 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -16,6 +16,11 @@
* image for a new image-to-video generation
* - a2v: audio-to-video (uploaded WAV/MP3 drives the video's motion +
* audio track) — dgrauet/ltx2 runtime only
+ * - ic-*: IC-LoRA remix modes (issue #3100) — a reference clip drives the
+ * render through ICLoraPipeline with a per-mode IC-LoRA fused into
+ * Stage 1. Today: `ic-control` (structure/motion from a depth/pose/
+ * edge clip). dgrauet/ltx2 runtime only; the mode list comes from
+ * IC_LORA_MODES in lib/videoGenParams.js.
*
* Batch queue: client-side serial executor. The form's "Add to queue" button
* appends a job to the queue (preserving the current params). When no job is
@@ -34,6 +39,7 @@ import FramePanel from '../components/videoGen/FramePanel';
import KeyframePanel from '../components/videoGen/KeyframePanel';
import AudioPanel from '../components/videoGen/AudioPanel';
import ExtendPanel from '../components/videoGen/ExtendPanel';
+import IcLoraPanel from '../components/videoGen/IcLoraPanel';
import RuntimeFingerprint from '../components/videoGen/RuntimeFingerprint';
import ModelRepairBanner from '../components/videoGen/ModelRepairBanner';
import VideoPreviewPanel from '../components/videoGen/VideoPreviewPanel';
@@ -44,7 +50,7 @@ import { normalizeVideo } from '../components/media/normalize';
import { composeStyledPrompt } from '../lib/composeStyledPrompt';
import {
Film, Sparkles, Settings as SettingsIcon, RefreshCw, AlertTriangle,
- Dice5, X, Type, Image as ImageIcon, GitBranch, ListPlus, Music,
+ Dice5, X, Type, Image as ImageIcon, GitBranch, ListPlus, Music, SlidersHorizontal,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import BatchQueuePanel from '../components/media/BatchQueuePanel';
@@ -80,6 +86,7 @@ import { VIDEO_TILING_OPTIONS, VIDEO_TILING_ENUM_SET } from '../lib/videoTilingO
import {
FRAME_OPTIONS, FPS_OPTIONS, VIDEO_EDGE_BOUNDS,
videoModelMemoryGb, computeFflfSafeFrames, isModelAllowedForMode,
+ IC_LORA_MODES, icLoraSpecForMode, icResolutionIssue,
} from '../lib/videoGenParams.js';
const MODES = [
@@ -88,6 +95,9 @@ const MODES = [
{ id: 'fflf', label: 'FFLF', icon: GitBranch, desc: 'First frame + last frame' },
{ id: 'extend', label: 'Extend', icon: Film, desc: 'Continue from a prior render' },
{ id: 'a2v', label: 'Audio', icon: Music, desc: 'Audio-to-video (audio drives motion + sync)' },
+ // IC-LoRA remix modes (issue #3100) — derived from the registry so a new
+ // remix mode appears in the mode bar automatically.
+ ...IC_LORA_MODES.map((m) => ({ id: m.mode, label: m.label, icon: SlidersHorizontal, desc: m.description })),
];
export default function VideoGen() {
@@ -179,6 +189,19 @@ export default function VideoGen() {
// is sent as multipart field name 'audioFile'; the server stages it under
// data/uploads, then the python helper passes it to AudioToVideoPipeline.
const [audioFile, setAudioFile] = useState(null);
+ // IC-LoRA remix modes (issue #3100) — the reference clip is either a fresh
+ // upload (multipart field 'icReference') or a prior render picked by history
+ // id. The two are mutually exclusive server-side, so the panel's Clear drops
+ // both. `icStrength` weights the reference conditioning channel.
+ const [icReferenceFile, setIcReferenceFile] = useState(null);
+ const [icReferenceVideoId, setIcReferenceVideoId] = useState('');
+ const [icStrength, setIcStrength] = useState(1.0);
+ const [icSkipStage2, setIcSkipStage2] = useState(false);
+ // Display-only: the reference clip name(s) of an IN-FLIGHT render restored via
+ // /active. An upload isn't re-derivable from its basename, so this can't
+ // repopulate the picker — it just tells the user what the running job is
+ // conditioned on instead of showing an empty panel.
+ const [icReferenceNames, setIcReferenceNames] = useState([]);
// Image gallery — used by both the start and end frame pickers so the
// user can pull from any prior render in either slot.
@@ -474,11 +497,11 @@ export default function VideoGen() {
const disableAudio = item.disableAudio ?? item.disable_audio;
setDisableAudio(disableAudio === true);
// Reset to text-to-video mode and clear any stale conditioning inputs from
- // image / fflf / extend / a2v modes. Without this, clicking Remix while
- // currently in (e.g.) image mode would carry the old source image into the
- // next submit even though Remix is meant to faithfully reproduce the prior
- // (text-to-video) render. Cross-page Remix already lands the user in text
- // mode because /media/video without `sourceImageFile` defaults that way.
+ // image / fflf / extend / a2v / IC-remix modes. Without this, clicking Remix
+ // while currently in (e.g.) image mode would carry the old source image into
+ // the next submit even though Remix is meant to faithfully reproduce the
+ // prior (text-to-video) render. Cross-page Remix already lands the user in
+ // text mode because /media/video without `sourceImageFile` defaults that way.
setMode('text');
setSourceImageFile(null);
setSourceImageUpload(null);
@@ -486,6 +509,14 @@ export default function VideoGen() {
setLastImageUpload(null);
setExtendFromVideoId('');
setAudioFile(null);
+ // IC-LoRA reference: the record only stamps the clip's BASENAME (history is
+ // user-facing and never carries staging paths), so a remix can't re-derive
+ // the reference — clear it rather than restore a half-set mode the user
+ // would submit unknowingly. The dials DO round-trip.
+ setIcReferenceFile(null);
+ setIcReferenceVideoId('');
+ if (typeof item.icStrength === 'number') setIcStrength(item.icStrength);
+ setIcSkipStage2(item.icSkipStage2 === true);
// Restore the LoRA picker from the render record. `item` here is the RAW
// history record (the gallery passes `handleRemixVideo(item.raw)` and every
// field above — prompt/modelId/width/… — is read off it directly), so the
@@ -632,6 +663,16 @@ export default function VideoGen() {
setKeyframes(p.keyframes.map((kf) => ({ file: kf.file, index: kf.index })));
setKeyframesMode(true);
}
+ // IC-LoRA remix: the dials round-trip, but the reference clip can't —
+ // /active echoes only its basename (an upload isn't re-derivable from
+ // one). That's fine while the job runs (the render already holds the real
+ // path); the panel's submit gate correctly blocks a NEW render until the
+ // user re-picks a reference. The names ride into a read-only hint.
+ if (typeof p.icStrength === 'number') setIcStrength(p.icStrength);
+ if (typeof p.icSkipStage2 === 'boolean') setIcSkipStage2(p.icSkipStage2);
+ if (Array.isArray(p.icReferenceNames) && p.icReferenceNames.length) {
+ setIcReferenceNames(p.icReferenceNames);
+ }
// Restore the LoRA picker — params carry { filename, scale } basenames;
// resolve the display name from the loaded library (falls back to the
// filename if the library hasn't loaded yet or the LoRA was deleted).
@@ -779,6 +820,11 @@ export default function VideoGen() {
// file, indices strictly ascending and within [0, numFrames-1].
const keyframesSupported = currentModel?.runtime === 'ltx2';
const keyframesActive = mode === 'fflf' && keyframesMode && keyframesSupported;
+ // IC-LoRA remix mode is on. `icSpec` is the registry entry (reference count +
+ // the resolution-divisibility rule its encoder imposes); null outside the
+ // family, so every consumer gates on `icModeActive` first.
+ const icSpec = icLoraSpecForMode(mode);
+ const icModeActive = !!icSpec;
// The worker clamps FFLF/ltx2 numFrames down to fit a pixel-frame budget that
// depends on resolution, so at default 768×512 the real frame ceiling is far
// below numFrames. Compute the same cap the server enforces so the picker can
@@ -959,6 +1005,23 @@ export default function VideoGen() {
// keyframe list can't sneak into the next post (the route would 400 on a
// non-fflf mode anyway, but keep the form honest).
if (next !== 'fflf') { setKeyframesMode(false); setKeyframes([]); }
+ const nextIcSpec = icLoraSpecForMode(next);
+ if (nextIcSpec) {
+ // IC conditioning replaces the frame/extend inputs entirely, and chaining
+ // is rejected server-side (IC_LORA_CHUNKS_CONFLICT) — clear them so no
+ // stale value implies it's being used. The reference clip SURVIVES a switch
+ // between two IC modes (same kind of input), which is why it's cleared in
+ // the else branch rather than here.
+ clearSourceImage();
+ clearLastImage();
+ setExtendFromVideoId('');
+ setChunks(1);
+ return;
+ }
+ // The IC-LoRA reference channel only exists in the IC remix modes — the
+ // route 400s IC_LORA_MODE_MISMATCH if one rides along elsewhere.
+ setIcReferenceFile(null);
+ setIcReferenceVideoId('');
if (next === 'text') {
clearSourceImage();
clearLastImage();
@@ -1127,9 +1190,17 @@ export default function VideoGen() {
// Audio File goes through under the multipart field 'audioFile'. Server
// routes it to the durable uploads dir and into the a2v helper.
audioFile: mode === 'a2v' ? (audioFile || '') : '',
- // Keyframes anchor a single clip — the route rejects chunks > 1 with
- // KEYFRAMES_CHUNKS_CONFLICT, so suppress chunking when keyframes are on.
- chunks: mode !== 'a2v' && !keyframesActive && chunks > 1 ? chunks : '',
+ // IC-LoRA remix: the reference clip rides as either the 'icReference'
+ // multipart upload OR an icReferenceVideoIds history id — never both (the
+ // route rejects that with IC_LORA_REFERENCE_CONFLICT).
+ icReference: icModeActive ? (icReferenceFile || '') : '',
+ icReferenceVideoIds: (icModeActive && !icReferenceFile) ? (icReferenceVideoId || '') : '',
+ icStrength: icModeActive ? icStrength : '',
+ icSkipStage2: icModeActive && icSkipStage2 ? 'true' : '',
+ // Keyframes and IC references each anchor a single clip — the route
+ // rejects chunks > 1 with KEYFRAMES_CHUNKS_CONFLICT /
+ // IC_LORA_CHUNKS_CONFLICT, so suppress chunking for both.
+ chunks: mode !== 'a2v' && !keyframesActive && !icModeActive && chunks > 1 ? chunks : '',
};
};
@@ -1215,6 +1286,15 @@ export default function VideoGen() {
// mlx_video runtime has no audio-conditioned pipeline. Block submit when
// either is missing so the request fails the form, not the worker.
const a2vModeBlocked = mode === 'a2v' && (!audioFile || currentModel?.runtime !== 'ltx2');
+ // IC-LoRA remix needs a reference clip AND an ltx2-runtime model, and the
+ // resolution must divide by the weight's reference-downscale factor (the
+ // server rejects otherwise). Block submit for all three so the request fails
+ // the form rather than the worker.
+ const icLoraModeBlocked = icModeActive && (
+ (!icReferenceFile && !icReferenceVideoId)
+ || currentModel?.runtime !== 'ltx2'
+ || !!icResolutionIssue(icSpec, width, height)
+ );
const handleGenerate = async (e) => {
e?.preventDefault?.();
@@ -1223,7 +1303,7 @@ export default function VideoGen() {
// Without these guards the user could press Enter in the prompt
// textarea and fire a request the disabled button would otherwise
// have prevented.
- if (!prompt.trim() || generating || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked || keyframesBlocked))) return;
+ if (!prompt.trim() || generating || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || keyframesBlocked))) return;
await runGeneration(buildGeneratePayload()).catch(() => {});
};
@@ -1232,7 +1312,7 @@ export default function VideoGen() {
// would silently queue a doomed job that fails late in the worker with
// VENV_MISSING, hiding the installer banner from the user. Block at
// enqueue time so the only path forward is the install banner above.
- if (!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked || keyframesBlocked))) return;
+ if (!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || keyframesBlocked))) return;
// useVideoGenQueue strips the File blobs into `_blobs` and snapshots the
// rest as a stable summary for the queue UI.
enqueue(buildGeneratePayload());
@@ -1357,7 +1437,11 @@ export default function VideoGen() {
onClick={() => {
setBackend(id);
if (id === 'grok' && mode !== 'text' && mode !== 'image') {
- setMode((sourceImageFile || sourceImageUpload) ? 'image' : 'text');
+ // Route through handleModeChange (not a bare setMode) so the
+ // snapped-away mode's inputs are cleared too — otherwise a
+ // stale a2v audio file or IC reference clip survives the
+ // switch and reappears if the user flips back.
+ handleModeChange((sourceImageFile || sourceImageUpload) ? 'image' : 'text');
}
}}
className={`flex-1 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-colors ${
@@ -1567,6 +1651,29 @@ export default function VideoGen() {
/>
)}
+ {icModeActive && (
+ <IcLoraPanel
+ spec={icSpec}
+ referenceFile={icReferenceFile}
+ referenceVideoId={icReferenceVideoId}
+ inFlightReferenceNames={icReferenceNames}
+ visibleHistory={visibleHistory}
+ icStrength={icStrength}
+ icSkipStage2={icSkipStage2}
+ width={width}
+ height={height}
+ weightStatus={modelDownload.getStatus(icSpec.mode)}
+ hasCompatibleModel={visibleModels.length > 0}
+ onPickFile={(f) => { setIcReferenceFile(f); if (f) { setIcReferenceVideoId(''); setIcReferenceNames([]); } }}
+ onClearFile={() => setIcReferenceFile(null)}
+ onPickHistory={(id) => { setIcReferenceVideoId(id); if (id) { setIcReferenceFile(null); setIcReferenceNames([]); } }}
+ onStrengthChange={setIcStrength}
+ onSkipStage2Change={setIcSkipStage2}
+ onDownloadWeight={() => modelDownload.start(icSpec.mode)}
+ onCancelWeightDownload={modelDownload.cancel}
+ />
+ )}
+
{isGrok ? (
<div className="grid grid-cols-2 gap-3">
<FormField label="Clip length" labelClassName="block text-xs font-medium text-gray-400 mb-1">
@@ -1827,7 +1934,7 @@ export default function VideoGen() {
) : (
<button
type="submit"
- disabled={!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked || keyframesBlocked))}
+ disabled={!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || keyframesBlocked))}
className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"
title={
byovRuntimeMissing ? `${byovStatus?.label || byovRuntime} runtime is not installed — use the install banner above`
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index acb27c97f4..672ecf5907 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -176,6 +176,14 @@ export const repairTextEncoder = ({ deep = false } = {}) => request('/video-gen/
body: JSON.stringify({ deep }),
silent: true,
});
+// Repair an IC-LoRA remix weight (issue #3100). Keyed by the remix mode
+// ('ic-control', …) rather than a model id — the weights aren't registry models,
+// same reason the text encoder has its own scalar endpoint above.
+export const repairIcLora = (mode, { deep = false } = {}) => request(`/video-gen/ic-loras/${encodeURIComponent(mode)}/repair`, {
+ method: 'POST',
+ body: JSON.stringify({ deep }),
+ silent: true,
+});
// With the cloud lane, video renders are no longer single-flight — pass the
// jobId so the server cancels exactly this render, not "the first running
// video". Omitting it keeps the legacy cancel-the-running-one behavior.
diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.py
index 26cc157f3b..62c6d6ded3 100644
--- a/scripts/generate_ltx2.py
+++ b/scripts/generate_ltx2.py
@@ -23,6 +23,16 @@ Modes (class names shown new→old; we resolve whichever the installed pin has):
fflf → KeyframeInterpolationPipeline.generate_and_save (--image start, --last-image end)
extend → RetakePipeline / ExtendPipeline .extend_from_video (--extend-from-video, --extend-frames, --direction)
a2v → A2VidPipelineTwoStage / AudioToVideoPipeline .generate_and_save (--audio, optional --image)
+ ic → ICLoraPipeline.generate_and_save (--ic-mode, --ic-lora-path, --ic-reference)
+
+IC-LoRA remix modes (--mode ic):
+ The IC ("In-Context") pipeline conditions generation on a *reference video*
+ channel (VideoConditionByReferenceLatent) with a per-mode IC-LoRA fused into
+ the Stage-1 transformer. One pipeline class, several capabilities selected by
+ which IC-LoRA weight you fuse — so `--ic-mode` is a label PortOS carries for
+ logging/validation, not a different code path. `control` drives structure and
+ motion from a depth/pose/edge clip; future modes (ingredients, colorize) reuse
+ the same runner with a different weight and reference count.
Pin compatibility — class renames + frame_rate:
The v0.14.x line of ltx-2-mlx renamed every public pipeline class and
@@ -311,7 +321,7 @@ def configure_negative_prompt(negative_prompt: str) -> None:
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="PortOS ltx-2-mlx bridge")
- p.add_argument("--mode", required=True, choices=["text", "image", "fflf", "extend", "a2v"])
+ p.add_argument("--mode", required=True, choices=["text", "image", "fflf", "extend", "a2v", "ic"])
p.add_argument("--prompt", required=True)
p.add_argument("--negative-prompt", default="")
p.add_argument("--output", required=True, help="Output .mp4 path")
@@ -363,6 +373,34 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--no-audio", action="store_true",
help="Strip audio from output. The dgrauet pipeline always generates A/V; "
"we re-mux without the audio stream when requested.")
+ p.add_argument("--ic-mode", default=None,
+ help="IC-LoRA remix flavor label for --mode ic (e.g. control). Names which "
+ "capability the fused IC-LoRA provides; used for logging only — the "
+ "pipeline itself is identical across flavors, and the real per-mode rules "
+ "arrive as the flags below. Free-form so PortOS' registry, not this "
+ "helper, decides which flavors exist.")
+ p.add_argument("--ic-lora-path", default=None,
+ help="IC-LoRA weight for --mode ic: a local .safetensors path OR a HuggingFace "
+ "repo id (ICLoraPipeline resolves a repo id via snapshot_download). "
+ "Required for ic mode — PortOS resolves the per-mode default on the Node "
+ "side so the weight registry lives in one place.")
+ p.add_argument("--ic-reference", action="append", default=None, metavar="PATH",
+ help="Reference clip for the IC-LoRA video-conditioning channel. Repeatable; "
+ "how many the fused weight expects is set by --ic-min/max-references.")
+ p.add_argument("--ic-min-references", type=int, default=1,
+ help="Fewest --ic-reference entries the fused weight accepts (from PortOS' "
+ "icLoraWeights registry, which owns the per-weight contract).")
+ p.add_argument("--ic-max-references", type=int, default=1,
+ help="Most --ic-reference entries the fused weight accepts.")
+ p.add_argument("--ic-strength", type=float, default=1.0,
+ help="Per-reference conditioning strength (0.0-1.0+) applied to every "
+ "--ic-reference entry.")
+ p.add_argument("--ic-attention-strength", type=float, default=None,
+ help="IC-LoRA conditioning ATTENTION strength in [0.0, 1.0] — 0 ignores the "
+ "reference entirely, 1 is full conditioning. Omit for the pipeline default.")
+ p.add_argument("--ic-skip-stage-2", action="store_true",
+ help="Skip the IC-LoRA pipeline's 2x upscale + refine pass (half-resolution "
+ "output, roughly half the wall time).")
p.add_argument("--no-teacache", action="store_true",
help="Disable TeaCache acceleration for supported LTX-2 denoise loops "
"(extend and a2v Stage 1).")
@@ -776,6 +814,92 @@ def run_a2v(args: argparse.Namespace) -> str:
_A2V_TC_CONFIG = None
+def run_ic_lora(args: argparse.Namespace) -> str:
+ """IC-LoRA reference-conditioned generation (control / ingredients / colorize).
+
+ ICLoraPipeline is a two-stage distilled pipeline whose Stage 1 fuses an
+ IC-LoRA and appends the reference clip(s) as VideoConditionByReferenceLatent
+ tokens; Stage 2 reloads a clean transformer and refines at 2x. The flavor
+ (control/ingredients/colorize) is entirely a function of WHICH IC-LoRA
+ weight is fused — same class, same call — so `--ic-mode` only drives
+ validation + status prose here.
+
+ Notes:
+ - `--ic-lora-path` may be a local .safetensors OR an HF repo id; the
+ pipeline's own _resolve_lora_path handles the download. PortOS normally
+ pre-fetches the weight through its HF-cache surface so the pull shows up
+ with progress instead of stalling silently mid-render.
+ - `reference_downscale_factor` is read off the LoRA's safetensors metadata
+ by the pipeline (Union-Control ships 2, halving the reference clip), and
+ it requires height/width divisible by that factor. A mismatch raises
+ inside the pipeline; we surface the resolution rule in the error so the
+ user knows to nudge the dimensions rather than the reference.
+ - User LoRAs stack ON TOP of the IC-LoRA rather than replacing it: the
+ IC-LoRA rides `lora_paths` (fused by _fuse_loras before Stage 1) while
+ user LoRAs ride the separate `_pending_loras` hook, so an
+ Ingredients x Character stack composes.
+ """
+ ICLoraPipeline = _resolve_pipeline("ICLoraPipeline")
+ ic_mode = args.ic_mode or "control"
+ if not args.ic_lora_path:
+ raise SystemExit("--ic-lora-path is required for ic mode")
+ references = list(args.ic_reference or [])
+ # Bounds come from the caller (PortOS' icLoraWeights registry owns them) so
+ # this helper never carries a second table that can drift. Enforced anyway:
+ # a weight fed the wrong reference count produces plausible-looking garbage
+ # rather than an error, so a direct/script caller needs the guard too.
+ lo, hi = args.ic_min_references, args.ic_max_references
+ if lo < 1 or hi < lo:
+ raise SystemExit(
+ f"--ic-min-references/--ic-max-references must satisfy 1 <= min <= max; got {lo}/{hi}"
+ )
+ if not (lo <= len(references) <= hi):
+ expected = f"exactly {lo}" if lo == hi else f"{lo}-{hi}"
+ raise SystemExit(
+ f"--ic-mode {ic_mode} needs {expected} --ic-reference clip(s); got {len(references)}"
+ )
+ for ref in references:
+ if not Path(ref).exists():
+ raise SystemExit(f"--ic-reference does not exist: {ref}")
+ if args.ic_attention_strength is not None and not (0.0 <= args.ic_attention_strength <= 1.0):
+ raise SystemExit("--ic-attention-strength must be between 0.0 and 1.0")
+
+ emit_status(f"Loading IC-LoRA pipeline ({args.model}, {ic_mode})…")
+ emit_stage(1, 0, 1, "Loading model")
+ pipe = ICLoraPipeline(
+ model_dir=args.model,
+ # Fusion strength 1.0 — the IC-LoRA is the mode, not a stylistic dial, so
+ # PortOS exposes no knob for it (the user-facing dial is --ic-strength,
+ # which weights the reference conditioning). Upstream's CLI defaults the
+ # same way.
+ lora_paths=[(args.ic_lora_path, 1.0)],
+ gemma_model_id=args.gemma,
+ )
+ # User LoRAs go through _pending_loras (fused at DiT load), NOT lora_paths —
+ # so they stack with the IC-LoRA above instead of displacing it.
+ _apply_user_loras(pipe, args.user_lora_specs)
+ bind_output_fps(pipe, args.fps)
+ emit_stage(1, 1, 1, "Loaded")
+ ref_names = ", ".join(Path(r).name for r in references)
+ emit_status(f"Generating IC-LoRA {ic_mode} from {ref_names} (strength {args.ic_strength:g})…")
+ kwargs: dict = dict(
+ prompt=args.prompt,
+ output_path=args.output,
+ video_conditioning=[(ref, args.ic_strength) for ref in references],
+ height=args.height,
+ width=args.width,
+ num_frames=args.num_frames,
+ seed=args.seed,
+ stage1_steps=args.steps,
+ stage2_steps=args.stage2_steps,
+ skip_stage_2=args.ic_skip_stage_2,
+ **_rate_kwargs(pipe.generate_and_save, args.fps),
+ )
+ if args.ic_attention_strength is not None:
+ kwargs["conditioning_attention_strength"] = args.ic_attention_strength
+ return pipe.generate_and_save(**kwargs)
+
+
def maybe_strip_audio(output_path: str) -> None:
"""Remux the output without the audio stream when --no-audio is set.
@@ -825,6 +949,7 @@ def main() -> NoReturn:
"fflf": run_fflf,
"extend": run_extend,
"a2v": run_a2v,
+ "ic": run_ic_lora,
}
runner = runners[args.mode]
saved_path = runner(args)
diff --git a/server/lib/README.md b/server/lib/README.md
index fb49fb9770..ccd60dc781 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -116,6 +116,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `hfErrors.js` | Parse huggingface_hub gated-access errors: `isGatedRepoError(text)` classifies a failure as gated (403/restricted), `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and MIDI transcription (LoRA trainer keeps its own regex to also match bare 401). Pure. |
| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId)` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. Also `verifyModelCache(repoId,{deep})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `verifySafetensorsStructure(path,size)` is the reusable header/size structural check (reads only the header region) — also used by the Civitai/HF LoRA install path to reject truncated downloads. |
| `hfDownload.js` | `downloadHfRepo({repo,onEvent})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in the FLUX.2 venv (fallback: mflux pythonPath) and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. |
+| `icLoraWeights.js` | IC-LoRA weight registry for the local LTX-2 remix modes (`IC_LORA_MODES`, `IC_LORA_MODE_VALUES`, `listIcLoraWeights()`, `isIcLoraMode(mode)`, `icLoraSpecForMode(mode)`, `icLoraRepos()`, `resolveIcLoraWeight(mode)` → `{path,cached,spec}`). Single source of truth mapping `ic-control` → its HF repo/filename, reference-count rule, and input surface. Also owns the two rules derived from that data: `assertIcReferenceCount(spec,count,fail)` / `describeIcReferenceRange(spec)` and `icResolutionIssue(spec,w,h)` (the output-resolution divisibility its reference encoder imposes). Mirrored to `client/src/lib/videoGenParams.js`; `icLoraWeights.parity.test.js` diffs the two. |
| `sseHeaders.js` | `SSE_HEADERS` — the canonical SSE response headers (incl. `X-Accel-Buffering:no`) in a dependency-free module so any producer (`sseDownload.js`, `sseUtils.js`) can share them without pulling in a heavier module's transitive imports. |
| `sseDownload.js` | `startHfDownloadStream({req,res,repo,alreadyDownloadedMessage})`, `openSseStream(res)` (`{send,safeEnd}` SSE boilerplate; uses `SSE_HEADERS` from `sseHeaders.js`) — shared SSE driver used by both image and video gen `/models/:id/download` routes. Owns the cross-route in-flight Map so a double-click (or both pages running) can't spawn two python children against the same repo. |
| `installLogger.js` | `createInstallLogger({installer,target})` → `{start,onEvent,success,failure,cancel}` — server-console chokepoint for install/venv-setup SSE flows (the install-side analogue of `sseDownload.js`). Logs a START line, throttled heartbeats + `stage` milestones (not every raw pip/bash line), and the OUTCOME (success/fail/cancel) with elapsed time. `onEvent(ev)` auto-detects terminal `complete`/`error` SSE events. Used by the music/video runtime installers and the FLUX.2 venv bootstrap. |
diff --git a/server/lib/icLoraWeights.js b/server/lib/icLoraWeights.js
new file mode 100644
index 0000000000..a67d5aefd4
--- /dev/null
+++ b/server/lib/icLoraWeights.js
@@ -0,0 +1,133 @@
+// IC-LoRA weight registry for the local LTX-2 video runtime (issue #3100).
+//
+// The `ltx2` runtime already ships `ltx_pipelines_mlx.ic_lora.ICLoraPipeline`
+// — a two-stage pipeline that conditions generation on a *reference video*
+// channel with an IC ("In-Context") LoRA fused into Stage 1. Which capability
+// you get is entirely a function of WHICH IC-LoRA weight is fused, so this
+// module is the single source of truth mapping a PortOS remix mode
+// (`ic-control`, …) to its weight, HF repo, reference-count rule, and the
+// resolution constraint the weight's metadata imposes.
+//
+// Weights are NOT bundled — each is a separate multi-hundred-MB HF pull, so
+// they ride the same cache-inspect / download-SSE / verify / repair surface as
+// the model weights themselves (see routes/videoGen.js). `resolveIcLoraWeight`
+// returns a local cached file path when present and falls back to the HF repo
+// id, which ICLoraPipeline._resolve_lora_path resolves on its own — so a render
+// still works if the user skipped the explicit pre-download (it just stalls
+// silently on the pull instead of showing progress).
+//
+// All registered weights are un-gated (no HF token required).
+
+import { join } from 'node:path';
+import { existsSync } from 'node:fs';
+import { inspectModelCache } from './hfCache.js';
+
+// One entry per shipped remix mode. `minReferences`/`maxReferences` are the
+// weight's contract: the Python helper receives them as flags (never a second
+// hardcoded table) so this registry stays the single source of truth across
+// both languages.
+//
+// `referenceDownscaleFactor` is informational (the pipeline reads the real
+// value from the weight's safetensors metadata): the IC encoder divides the
+// reference clip by it, and it requires the OUTPUT height/width to be
+// divisible by that factor — so surfacing it lets the route reject a bad
+// resolution up-front instead of failing deep inside the pipeline.
+//
+// The MIRRORED fields (label/description/referenceKind/uploadLabel/the counts/
+// the factor) are duplicated in client/src/lib/videoGenParams.js so the form can
+// validate pre-submit; icLoraWeights.parity.test.js diffs the two so a change
+// here can't silently leave the client accepting what the server rejects.
+export const IC_LORA_MODES = Object.freeze({
+ control: Object.freeze({
+ id: 'control',
+ mode: 'ic-control',
+ label: 'Control',
+ description: 'Structure + motion from a control clip',
+ // Drives the panel's upload copy + `accept` filter, so a new mode needs no
+ // component change to describe its own input (see referenceKind).
+ uploadLabel: 'Upload a control clip (depth / pose / edges)',
+ repo: 'Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control',
+ filename: 'ltx-2.3-22b-ic-lora-union-control-ref0.5.safetensors',
+ // ~654 MB — used for the download badge's size estimate before the pull.
+ sizeBytes: 654 * 1024 * 1024,
+ referenceDownscaleFactor: 2,
+ minReferences: 1,
+ maxReferences: 1,
+ referenceKind: 'video',
+ }),
+});
+
+// Every registered spec, in declaration order. Consumers use this instead of
+// reaching into IC_LORA_MODES directly so the container shape stays private.
+export const listIcLoraWeights = () => Object.values(IC_LORA_MODES);
+
+// PortOS `mode` values that route to the IC-LoRA pipeline. Every entry is
+// `ic-<id>` so a single prefix test identifies the family, and the route enum
+// stays a closed list derived from the registry (never hand-maintained).
+export const IC_LORA_MODE_VALUES = Object.freeze(
+ Object.values(IC_LORA_MODES).map((m) => m.mode),
+);
+
+export const isIcLoraMode = (mode) => typeof mode === 'string' && IC_LORA_MODE_VALUES.includes(mode);
+
+// `ic-control` → the registry entry, or null for anything else. Accepts the
+// bare id (`control`) too so callers that already stripped the prefix work.
+export const icLoraSpecForMode = (mode) => {
+ if (typeof mode !== 'string' || !mode) return null;
+ const id = mode.startsWith('ic-') ? mode.slice(3) : mode;
+ return IC_LORA_MODES[id] || null;
+};
+
+// Every IC-LoRA HF repo, for the integrity-scan / status surface.
+export const icLoraRepos = () => listIcLoraWeights().map((m) => m.repo);
+
+// "exactly 1" / "2-8" — the human phrasing of a spec's reference-count rule.
+// Lives here so the route and the arg builder can't word (or bound) it
+// differently, and so the Python helper's flags come from one place.
+export const describeIcReferenceRange = (spec) => (
+ spec.minReferences === spec.maxReferences
+ ? `exactly ${spec.minReferences}`
+ : `${spec.minReferences}-${spec.maxReferences}`
+);
+
+// Throw when `count` violates the weight's reference contract. `fail` builds the
+// caller's error (the route needs a ServerError with its own staging cleanup
+// already done; the worker needs a plain one), so the MESSAGE and the BOUNDS
+// stay single-sourced even though the throw sites differ.
+export const assertIcReferenceCount = (spec, count, fail) => {
+ if (count >= spec.minReferences && count <= spec.maxReferences) return;
+ throw fail(
+ `${spec.label} mode needs ${describeIcReferenceRange(spec)} reference ${spec.referenceKind}(s); got ${count}.`,
+ );
+};
+
+// The IC encoder downscales the reference by `referenceDownscaleFactor`, which
+// requires the OUTPUT dimensions to divide evenly by it. Returns a human message
+// when they don't, else null. Mirrored client-side (icResolutionIssue in
+// client/src/lib/videoGenParams.js) so the form can warn before submit.
+export const icResolutionIssue = (spec, width, height) => {
+ const scale = spec?.referenceDownscaleFactor ?? 1;
+ if (scale <= 1) return null;
+ if (Number(width) % scale === 0 && Number(height) % scale === 0) return null;
+ return `${spec.label} mode needs a resolution divisible by ${scale} (its reference encoder downscales by ${scale}); got ${width}×${height}.`;
+};
+
+// Resolve the weight to hand the Python helper. Prefers the exact filename
+// inside the newest HF cache snapshot (so we pin the file rather than letting
+// the pipeline glob-pick among several `.safetensors` in a multi-weight repo),
+// then any cached snapshot path for the repo, and finally the bare repo id —
+// which ICLoraPipeline downloads itself.
+//
+// Returns `{ path, cached }`: `cached` is true only when a real local file was
+// found, so callers can warn the user that an un-cached weight means a silent
+// multi-hundred-MB pull at render time.
+export const resolveIcLoraWeight = async (mode) => {
+ const spec = icLoraSpecForMode(mode);
+ if (!spec) return null;
+ const { snapshotPath } = await inspectModelCache(spec.repo);
+ if (snapshotPath) {
+ const exact = join(snapshotPath, spec.filename);
+ if (existsSync(exact)) return { path: exact, cached: true, spec };
+ }
+ return { path: spec.repo, cached: false, spec };
+};
diff --git a/server/lib/icLoraWeights.parity.test.js b/server/lib/icLoraWeights.parity.test.js
new file mode 100644
index 0000000000..a4e2f48226
--- /dev/null
+++ b/server/lib/icLoraWeights.parity.test.js
@@ -0,0 +1,70 @@
+/**
+ * Cross-package parity for the IC-LoRA remix-mode registry (issue #3100).
+ *
+ * `server/lib/icLoraWeights.js` is the source of truth; the `IC_LORA_MODES` list
+ * in `client/src/lib/videoGenParams.js` is a hand-maintained mirror (the client
+ * can't import the server module — it reaches into node:fs and the HF cache).
+ *
+ * This suite imports BOTH and asserts the fields the form relies on stay
+ * identical, so a server-side change that isn't mirrored fails CI here instead
+ * of silently letting the form accept a render the route rejects. The concrete
+ * failure it prevents: a new weight ships with `referenceDownscaleFactor: 4`,
+ * the client mirror keeps 2, and the resolution gate green-lights a request the
+ * server 400s with IC_LORA_RESOLUTION_NOT_DIVISIBLE.
+ *
+ * It lives server-side because the server module can't load under the client
+ * (jsdom) runner, but the pure client mirror loads fine here.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { listIcLoraWeights, icResolutionIssue as serverIcResolutionIssue } from './icLoraWeights.js';
+import {
+ IC_LORA_MODES as CLIENT_MODES,
+ IC_LORA_MODE_VALUES as CLIENT_MODE_VALUES,
+ icResolutionIssue as clientIcResolutionIssue,
+} from '../../client/src/lib/videoGenParams.js';
+
+// The fields the client mirror MUST match the server on — everything the panel
+// renders or validates against. `repo` / `filename` / `sizeBytes` / `id` are
+// server-only (the client never resolves a weight path) and intentionally not
+// mirrored; `sizeBytes` reaches the client as `estimatedBytes` off /models/status.
+const MIRRORED_FIELDS = [
+ 'label', 'description', 'uploadLabel',
+ 'referenceKind', 'referenceDownscaleFactor',
+ 'minReferences', 'maxReferences',
+];
+
+const SERVER_MODES = listIcLoraWeights();
+
+describe('IC-LoRA registry — server↔client parity', () => {
+ it('exposes the same mode ids in the same order', () => {
+ expect(CLIENT_MODES.map((m) => m.mode)).toEqual(SERVER_MODES.map((m) => m.mode));
+ expect(CLIENT_MODE_VALUES).toEqual(SERVER_MODES.map((m) => m.mode));
+ });
+
+ it('matches every mirrored field for each mode', () => {
+ for (const s of SERVER_MODES) {
+ const c = CLIENT_MODES.find((m) => m.mode === s.mode);
+ expect(c, `client mirror missing mode ${s.mode}`).toBeTruthy();
+ for (const f of MIRRORED_FIELDS) {
+ expect(c[f], `${s.mode}.${f} drifted between server and client`).toEqual(s[f]);
+ }
+ }
+ });
+
+ it('icResolutionIssue agrees across server and client', () => {
+ // Covers divisible, both-odd, one-odd, and the factor-1 (no-rule) case for
+ // every registered mode — the client's warning text is also the server's
+ // rejection message, so a wording drift fails here too.
+ const dims = [[704, 448], [705, 448], [704, 449], [705, 449], [768, 512]];
+ for (const spec of SERVER_MODES) {
+ const client = CLIENT_MODES.find((m) => m.mode === spec.mode);
+ for (const [w, h] of dims) {
+ expect(clientIcResolutionIssue(client, w, h), `${spec.mode} ${w}x${h}`)
+ .toBe(serverIcResolutionIssue(spec, w, h));
+ }
+ }
+ expect(clientIcResolutionIssue({ referenceDownscaleFactor: 1 }, 705, 449)).toBeNull();
+ expect(serverIcResolutionIssue({ referenceDownscaleFactor: 1 }, 705, 449)).toBeNull();
+ });
+});
diff --git a/server/lib/icLoraWeights.test.js b/server/lib/icLoraWeights.test.js
new file mode 100644
index 0000000000..7fcece90d5
--- /dev/null
+++ b/server/lib/icLoraWeights.test.js
@@ -0,0 +1,101 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { join } from 'node:path';
+
+// Both dependencies are filesystem-facing: inspectModelCache walks the real HF
+// cache and existsSync probes the pinned weight file. Mock them so these tests
+// cover the registry + resolution logic rather than the user's ~/.cache layout
+// (hfCache.test.js already covers the cache walk).
+const { mockInspectModelCache, mockExistsSync } = vi.hoisted(() => ({
+ mockInspectModelCache: vi.fn(),
+ mockExistsSync: vi.fn(),
+}));
+vi.mock('./hfCache.js', () => ({ inspectModelCache: mockInspectModelCache }));
+vi.mock('node:fs', () => ({ existsSync: mockExistsSync }));
+
+const {
+ IC_LORA_MODES, IC_LORA_MODE_VALUES, isIcLoraMode, icLoraSpecForMode,
+ icLoraRepos, resolveIcLoraWeight,
+} = await import('./icLoraWeights.js');
+
+beforeEach(() => {
+ mockInspectModelCache.mockReset();
+ mockExistsSync.mockReset();
+});
+
+describe('IC-LoRA registry', () => {
+ it('exposes ic-prefixed mode values derived from the registry', () => {
+ expect(IC_LORA_MODE_VALUES).toEqual(['ic-control']);
+ // The `ic-` prefix is load-bearing: the client's download-id router and the
+ // route's mode enum both key off it.
+ for (const v of IC_LORA_MODE_VALUES) expect(v.startsWith('ic-')).toBe(true);
+ });
+
+ it('identifies IC modes and rejects everything else', () => {
+ expect(isIcLoraMode('ic-control')).toBe(true);
+ expect(isIcLoraMode('text')).toBe(false);
+ expect(isIcLoraMode('a2v')).toBe(false);
+ expect(isIcLoraMode(undefined)).toBe(false);
+ expect(isIcLoraMode('')).toBe(false);
+ });
+
+ it('resolves a spec from either the prefixed mode or the bare id', () => {
+ expect(icLoraSpecForMode('ic-control')).toBe(IC_LORA_MODES.control);
+ expect(icLoraSpecForMode('control')).toBe(IC_LORA_MODES.control);
+ expect(icLoraSpecForMode('ic-nope')).toBeNull();
+ expect(icLoraSpecForMode(null)).toBeNull();
+ });
+
+ it('lists every weight repo for the integrity-scan surface', () => {
+ expect(icLoraRepos()).toEqual(['Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control']);
+ });
+
+ it('keeps every entry internally consistent', () => {
+ for (const spec of Object.values(IC_LORA_MODES)) {
+ expect(spec.mode).toBe(`ic-${spec.id}`);
+ expect(spec.filename.endsWith('.safetensors')).toBe(true);
+ expect(spec.repo).toMatch(/^[^/]+\/[^/]+$/);
+ expect(spec.minReferences).toBeGreaterThanOrEqual(1);
+ expect(spec.maxReferences).toBeGreaterThanOrEqual(spec.minReferences);
+ expect(spec.referenceDownscaleFactor).toBeGreaterThanOrEqual(1);
+ }
+ });
+});
+
+describe('resolveIcLoraWeight', () => {
+ it('pins the exact filename inside the cached snapshot', async () => {
+ mockInspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 1, snapshotPath: '/hf/snap' });
+ mockExistsSync.mockReturnValue(true);
+
+ const resolved = await resolveIcLoraWeight('ic-control');
+ // Pinning the filename (rather than returning the snapshot dir or the repo
+ // id) is what stops the pipeline's glob from picking a sibling weight.
+ expect(resolved.path).toBe(join('/hf/snap', IC_LORA_MODES.control.filename));
+ expect(resolved.cached).toBe(true);
+ expect(resolved.spec).toBe(IC_LORA_MODES.control);
+ });
+
+ it('falls back to the repo id when no snapshot exists', async () => {
+ mockInspectModelCache.mockResolvedValue({ cached: false, sizeBytes: 0, snapshotPath: null });
+
+ const resolved = await resolveIcLoraWeight('ic-control');
+ expect(resolved.path).toBe(IC_LORA_MODES.control.repo);
+ expect(resolved.cached).toBe(false);
+ });
+
+ it('falls back to the repo id when the snapshot lacks the pinned file', async () => {
+ // A partial download leaves the snapshot dir present but the weight absent —
+ // returning the dir-joined path would hand the pipeline a missing file, so
+ // the repo-id fallback (which re-downloads) is the correct degrade.
+ mockInspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 1, snapshotPath: '/hf/snap' });
+ mockExistsSync.mockReturnValue(false);
+
+ const resolved = await resolveIcLoraWeight('ic-control');
+ expect(resolved.path).toBe(IC_LORA_MODES.control.repo);
+ expect(resolved.cached).toBe(false);
+ });
+
+ it('returns null for an unknown mode without touching the cache', async () => {
+ expect(await resolveIcLoraWeight('ic-nope')).toBeNull();
+ expect(mockInspectModelCache).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index b1a7f4295e..ca613bc1b4 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -96,6 +96,7 @@ export * from './hfToken.js';
export * from './hfErrors.js';
export * from './hfCache.js';
export * from './hfDownload.js';
+export * from './icLoraWeights.js';
export * from './sseDownload.js';
export * from './sseHeaders.js';
export * from './installLogger.js';
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 34a4c1dbef..64485683c1 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -46,6 +46,10 @@ import {
import { enqueueJob, attachSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
import { repoForModel, getTextEncoderRepo, isHfRepoId } from '../lib/mediaModels.js';
import { videoLoraFamily } from '../lib/runners.js';
+import {
+ IC_LORA_MODE_VALUES, icLoraSpecForMode, icLoraRepos, listIcLoraWeights,
+ assertIcReferenceCount,
+} from '../lib/icLoraWeights.js';
import { inspectModelCache, verifyModelCache, repairModelCache, summarizeVerify } from '../lib/hfCache.js';
import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
import { createInstallLogger } from '../lib/installLogger.js';
@@ -72,18 +76,23 @@ export const isAudioMime = (mime, filename) => {
};
// FFLF accepts up to two image uploads (start and end frame); a2v takes
-// one audio upload (audioFile). 100MB covers audio cases too (LTX-2's a2v
+// one audio upload (audioFile); the IC-LoRA remix modes take one reference
+// video upload (icReference). 100MB covers audio cases too (LTX-2's a2v
// expects only seconds of audio in practice). Per-fieldname mime filter
// rejects mismatched parts up-front so a stray .mp4 drag-drop can't get
// staged under any of these fields.
-const frameImageUpload = uploadFields(['sourceImage', 'lastImage', 'audioFile'], {
+const frameImageUpload = uploadFields(['sourceImage', 'lastImage', 'audioFile', 'icReference'], {
limits: { fileSize: 100 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
const isImageField = file.fieldname === 'sourceImage' || file.fieldname === 'lastImage';
const isAudioField = file.fieldname === 'audioFile';
+ const isVideoField = file.fieldname === 'icReference';
const okImage = isImageField && file.mimetype.startsWith('image/');
const okAudio = isAudioField && isAudioMime(file.mimetype, file.originalname);
- cb(null, okImage || okAudio);
+ // IC-LoRA references are clips — the control weight reads structure/motion
+ // out of a depth/pose/edge video, so only video/* is meaningful here.
+ const okVideo = isVideoField && file.mimetype.startsWith('video/');
+ cb(null, okImage || okAudio || okVideo);
},
});
@@ -143,7 +152,9 @@ const generateBodySchema = z.object({
lastImageFile: z.string().max(512).optional(),
// UI mode hint — backend only uses it for logging/branching; absence
// falls back to inferring (sourceImage→i2v, no source→t2v).
- mode: z.enum(['text', 'image', 'fflf', 'extend', 'a2v']).optional(),
+ // IC-LoRA remix modes (`ic-control`, …) come from the weight registry so the
+ // enum can never drift from what's actually installable.
+ mode: z.enum(['text', 'image', 'fflf', 'extend', 'a2v', ...IC_LORA_MODE_VALUES]).optional(),
// Chain N renders end-to-end: each chunk's last frame becomes the next
// chunk's start frame, then ffmpeg concats them into one clip. 1..8 to
// keep the worst-case wall time bounded (8 × ~5min ≈ 40min on M3 Max).
@@ -153,6 +164,31 @@ const generateBodySchema = z.object({
// the entire source video's latent rather than a single last frame).
// The legacy chained-i2v path keeps using sourceImageFile.
extendFromVideoId: z.string().guid().optional(),
+ // IC-LoRA remix reference clip picked from render history instead of uploaded
+ // (the `icReference` multipart upload wins when both are present, mirroring
+ // the sourceImage/sourceImageFile precedence). Control/Colorize take exactly
+ // one reference; Ingredients (a later phase) will take 2-8, hence the array.
+ icReferenceVideoIds: z.preprocess(
+ (v) => {
+ if (v == null || v === '') return undefined;
+ if (typeof v === 'string') {
+ // Multipart sends a SINGLE value as a bare string and repeated keys as
+ // an array; also accept a JSON-encoded list from a JSON client.
+ if (v.trim().startsWith('[')) { try { return JSON.parse(v); } catch { return [v]; } }
+ return [v];
+ }
+ return v;
+ },
+ z.array(z.string().guid()).min(1).max(8).optional(),
+ ),
+ // Reference-video conditioning strength for the IC-LoRA channel. Distinct
+ // from the IC-LoRA's own fusion strength (fixed at 1.0 server-side) and from
+ // `icAttentionStrength`, which scales the conditioning ATTENTION.
+ icStrength: optionalNum(0, 2, 'icStrength'),
+ icAttentionStrength: optionalNum(0, 1, 'icAttentionStrength'),
+ // Skip the IC pipeline's 2x upscale + refine — half-resolution output at
+ // roughly half the wall time, useful for previewing a control clip's fit.
+ icSkipStage2: z.union([z.boolean(), z.literal('true'), z.literal('false')]).optional(),
// Multi-keyframe interpolation (ltx2 + mode='fflf'). Each entry pins one
// gallery image at a specific pixel-frame index. Indices must be strictly
// ascending and within [0, numFrames-1]. When set, overrides the legacy
@@ -446,6 +482,10 @@ const reposToVerify = (modelId) => {
const repos = listVideoModels().map(repoForModel).filter(Boolean);
const enc = getTextEncoderRepo();
if (isHfRepoId(enc)) repos.push(enc);
+ // IC-LoRA remix weights are separate HF pulls that the render path depends
+ // on, so an unscoped integrity scan must cover them too — otherwise a
+ // corrupt IC weight only surfaces as a garbled render.
+ repos.push(...icLoraRepos());
return [...new Set(repos)];
};
@@ -453,31 +493,43 @@ const reposToVerify = (modelId) => {
// shape contract. We also surface the active text-encoder repo so the
// video form can warn when the Gemma encoder isn't downloaded yet (a
// surprise multi-GB pull on top of the model itself).
+// Cache + integrity for one HF repo, in the `{ cached, sizeBytes, integrity }`
+// shape every download badge consumes. The integrity check only runs for a repo
+// that's actually downloaded — a not-yet-cached repo gets the Download badge,
+// not a Repair banner. Shared by all three lanes of /models/status below so the
+// badge semantics can't drift between models, the encoder, and IC weights.
+const repoCacheStatus = async (repo) => {
+ const { cached, sizeBytes } = await inspectModelCache(repo);
+ return { cached, sizeBytes, integrity: cached ? summarizeVerify(await verifyModelCache(repo)) : null };
+};
+
router.get('/models/status', asyncHandler(async (_req, res) => {
// Text encoder is shared across all video renders. A registry entry with
// `localPath` (e.g. an LM Studio install) trumps the HF cache check, so
// surface both the repo-cache status and the resolved local path so the UI
// can distinguish "not downloaded" from "served from LM Studio".
const encoderRepo = getTextEncoderRepo();
- const [models, textEncoder] = await Promise.all([
+ const [models, textEncoder, icLoras] = await Promise.all([
Promise.all(listVideoModels().map(async (m) => {
const repo = repoForModel(m);
if (!repo) return { id: m.id, repo: null, cached: null, sizeBytes: 0, integrity: null };
- const { cached, sizeBytes } = await inspectModelCache(repo);
- // Only run the (header-reading) integrity check for repos that are
- // actually downloaded — a not-yet-cached model gets the Download badge,
- // not a Repair banner.
- const integrity = cached ? summarizeVerify(await verifyModelCache(repo)) : null;
- return { id: m.id, repo, cached, sizeBytes, integrity };
+ return { id: m.id, repo, ...await repoCacheStatus(repo) };
})),
(async () => {
if (!isHfRepoId(encoderRepo)) return { repo: encoderRepo, cached: true, sizeBytes: 0, integrity: null };
- const enc = await inspectModelCache(encoderRepo);
- const integrity = enc.cached ? summarizeVerify(await verifyModelCache(encoderRepo)) : null;
- return { repo: encoderRepo, ...enc, integrity };
+ return { repo: encoderRepo, ...await repoCacheStatus(encoderRepo) };
})(),
+ // IC-LoRA remix weights (issue #3100). Each is a separate several-hundred-MB
+ // pull the IC render path needs, so they get the same cached/size/integrity
+ // shape as the models — that's what lets the mode panel render a Download
+ // badge and a Repair banner with the existing components.
+ Promise.all(listIcLoraWeights().map(async (spec) => ({
+ id: spec.mode, repo: spec.repo, label: spec.label,
+ estimatedBytes: spec.sizeBytes,
+ ...await repoCacheStatus(spec.repo),
+ }))),
]);
- res.json({ models, textEncoder });
+ res.json({ models, textEncoder, icLoras });
}));
// POST /models/verify — force an integrity re-scan on demand. `deep:true` adds
@@ -528,6 +580,36 @@ router.get('/models/:modelId/download', asyncHandler(async (req, res) => {
await startHfDownloadStream({ req, res, repo, force: req.query.force === '1' });
}));
+// IC-LoRA remix weights (issue #3100) get their own download/repair pair for
+// the same reason the text encoder does: they're required by the render path
+// but are NOT listVideoModels() entries, so the model-id-keyed routes above
+// can't reach them. Keyed by the PortOS remix mode ('ic-control', …) so the
+// client uses the same identifier it puts in the render payload.
+const icLoraSpecFromParam = (mode) => {
+ const spec = icLoraSpecForMode(mode);
+ if (!spec) {
+ throw new ServerError(
+ `Unknown IC-LoRA remix mode: ${mode} (expected one of ${IC_LORA_MODE_VALUES.join(', ')})`,
+ { status: 404, code: 'IC_LORA_UNKNOWN_MODE' },
+ );
+ }
+ return spec;
+};
+
+router.get('/ic-loras/:mode/download', asyncHandler(async (req, res) => {
+ const spec = icLoraSpecFromParam(req.params.mode);
+ await startHfDownloadStream({ req, res, repo: spec.repo, force: req.query.force === '1' });
+}));
+
+router.post('/ic-loras/:mode/repair', asyncHandler(async (req, res) => {
+ const spec = icLoraSpecFromParam(req.params.mode);
+ const parsed = z.object({ deep: z.boolean().optional() }).safeParse(req.body || {});
+ if (!parsed.success) failValidation(parsed);
+ const deep = parsed.data.deep || false;
+ const result = await repairModelCache(spec.repo, { deep });
+ res.json({ deep, deleted: result.deleted.map((name) => ({ repo: result.repoId, name })), repos: [spec.repo] });
+}));
+
// POST /text-encoder/repair — delete the flagged (corrupt/truncated) weight
// files for the active text encoder repo so the existing /text-encoder/download
// SSE re-fetches clean copies. The encoder is shared across all video renders
@@ -677,6 +759,80 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
{ status: 400, code: 'VIDEO_GEN_AUDIO_MODE_MISMATCH' },
);
}
+ // IC-LoRA remix (mode='ic-control', …). Mirrors the a2v pairing checks: the
+ // reference channel is what makes the mode meaningful, and an IC upload
+ // outside an IC mode would be silently dropped by the worker.
+ const icSpec = icLoraSpecForMode(body.mode);
+ if (icSpec) {
+ // The grok backend short-circuits below this point (it only reads
+ // prompt/dims/source-image), so an IC request routed there would enqueue a
+ // plain grok render with the reference clip silently dropped. The client's
+ // mode bar snaps grok back to text/image, but reject explicitly so a direct
+ // caller gets an error instead of a wrong-looking clip.
+ if (body.backend === 'grok') {
+ await cleanupAllStaged();
+ throw new ServerError(
+ `${icSpec.label} mode runs on the local ltx2 runtime — it isn't available on the Grok backend.`,
+ { status: 400, code: 'IC_LORA_REQUIRES_LOCAL_BACKEND' },
+ );
+ }
+ // The upload wins over gallery picks, so a request carrying both would
+ // silently drop the picks. Force one shape per request instead. Checked
+ // BEFORE the count bounds below, which would otherwise report a misleading
+ // "needs exactly 1, got 2" for what is really a mixed-shape request.
+ if (uploads.icReference && body.icReferenceVideoIds?.length) {
+ await cleanupAllStaged();
+ throw new ServerError(
+ 'icReference upload cannot be combined with icReferenceVideoIds — pass one reference shape per request.',
+ { status: 400, code: 'IC_LORA_REFERENCE_CONFLICT' },
+ );
+ }
+ // Reference count is the weight's contract, asserted once here against the
+ // registry that owns the bounds. Checked before staging so a bad request only
+ // unlinks the cheap OS temp file, and resolution below can't change the
+ // count: an upload is exactly 1 and every id resolves 1:1 or throws.
+ const refCount = (uploads.icReference ? 1 : 0) + (body.icReferenceVideoIds?.length || 0);
+ if (refCount === 0) {
+ // Special-cased ahead of the bounds assertion purely for actionability —
+ // "needs exactly 1; got 0" doesn't tell the caller HOW to supply one.
+ await cleanupAllStaged();
+ throw new ServerError(
+ `${icSpec.label} mode requires a reference ${icSpec.referenceKind} — upload one (multipart field: icReference) or pick a prior render (icReferenceVideoIds).`,
+ { status: 400, code: 'IC_LORA_REFERENCE_REQUIRED' },
+ );
+ }
+ if (refCount < icSpec.minReferences || refCount > icSpec.maxReferences) {
+ await cleanupAllStaged();
+ assertIcReferenceCount(icSpec, refCount, (msg) => new ServerError(msg, {
+ status: 400, code: 'IC_LORA_REFERENCE_COUNT',
+ }));
+ }
+ // IC-LoRA remix is an LTX-2 primitive (ICLoraPipeline). Fail before enqueue
+ // so a bad modelId can't pollute the persisted queue with a doomed job.
+ if (effectiveModel && effectiveModel.runtime !== 'ltx2') {
+ await cleanupAllStaged();
+ throw new ServerError(
+ `${icSpec.label} mode requires an ltx2-runtime model. Model "${effectiveModelId}" runs on "${effectiveModel.runtime || 'mlx_video'}".`,
+ { status: 400, code: 'IC_LORA_REQUIRES_LTX2' },
+ );
+ }
+ // Chained renders re-seed each chunk from the previous chunk's last frame;
+ // an IC render is conditioned on a whole reference clip instead, so there's
+ // no defined semantic for chunk 2+ and it would silently ignore the mode.
+ if (body.chunks != null && Number(body.chunks) > 1) {
+ await cleanupAllStaged();
+ throw new ServerError(
+ `${icSpec.label} mode cannot be combined with chunks > 1 — the reference clip anchors a single render.`,
+ { status: 400, code: 'IC_LORA_CHUNKS_CONFLICT' },
+ );
+ }
+ } else if (uploads.icReference || body.icReferenceVideoIds?.length) {
+ await cleanupAllStaged();
+ throw new ServerError(
+ `IC-LoRA reference inputs are only valid with an IC remix mode (${IC_LORA_MODE_VALUES.join(', ')}); got mode='${body.mode || 'unset'}'.`,
+ { status: 400, code: 'IC_LORA_MODE_MISMATCH' },
+ );
+ }
// a2v needs the dgrauet runtime — the legacy mlx_video pipeline has no
// audio-conditioned mode. The worker also catches this in buildArgs (with
// A2V_REQUIRES_LTX2), but checking here keeps the route's "fail fast
@@ -693,9 +849,10 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
let sourceImagePath = null;
let lastImagePath = null;
let audioFilePath = null;
+ let icReferenceUploadPath = null;
let uploadedTempPath = null;
const extraUploadedTempPaths = [];
- if (uploads.sourceImage || uploads.lastImage || uploads.audioFile) {
+ if (uploads.sourceImage || uploads.lastImage || uploads.audioFile || uploads.icReference) {
// Ensure the durable uploads dir exists before staging. Wrapped in
// try/catch so a permission/disk failure here still cleans up the
// multipart temp uploads instead of leaking them in the OS temp dir.
@@ -784,6 +941,13 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
audioFilePath = await stageUploadDurable(uploads.audioFile, 'audio');
extraUploadedTempPaths.push(audioFilePath);
}
+ if (uploads.icReference) {
+ // IC-LoRA reference clip — same durable staging + cleanup tracking as the
+ // audio upload above. A history-picked reference needs neither (it already
+ // lives under data/videos/ and must survive the render).
+ icReferenceUploadPath = await stageUploadDurable(uploads.icReference, 'ic-ref');
+ extraUploadedTempPaths.push(icReferenceUploadPath);
+ }
// Multi-keyframe interpolation: resolve each gallery filename to an
// absolute path under PATHS.images via the same path-traversal guard as
@@ -875,34 +1039,71 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
}
}
- // Native extend (ltx2 runtime): resolve the history id to a video file
- // path under data/videos/ and forward it as extendFromVideoPath. Reject
- // a missing/tampered id rather than silently falling back to t2v —
- // surfaces a clear error to the user instead of producing wrong content.
- let extendFromVideoPath = null;
- if (body.extendFromVideoId) {
- const history = await loadHistory();
- const videoEntry = history.find((h) => h.id === body.extendFromVideoId);
+ // Resolve a render-history id to its on-disk video under data/videos/.
+ // Shared by native extend and the IC-LoRA reference channel: both let the
+ // user point at a prior render, and both must reject a missing/tampered id
+ // rather than silently degrading to a text render (which would produce
+ // wrong-looking content with no error). `label` names the field in the error
+ // so the two callers stay distinguishable.
+ const resolveHistoryVideoPath = async (id, { history, label, notFoundCode, missingFileCode }) => {
+ const videoEntry = history.find((h) => h.id === id);
if (!videoEntry) {
// cleanupAllStaged covers durable copies that may have been written
- // before this validation point — extend mode and image uploads are
+ // before this validation point — these modes and image uploads are
// mutually exclusive in the UI but the route doesn't enforce that,
// so be defensive.
await cleanupAllStaged();
- throw new ServerError(
- `extendFromVideoId not found in history: ${body.extendFromVideoId}`,
- { status: 404, code: 'EXTEND_SOURCE_NOT_FOUND' },
- );
+ throw new ServerError(`${label} not found in history: ${id}`, { status: 404, code: notFoundCode });
}
const candidate = safeUnder(PATHS.videos, videoEntry.filename);
if (!candidate || !existsSync(candidate)) {
await cleanupAllStaged();
throw new ServerError(
- `extendFromVideoId resolved to a missing file: ${videoEntry.filename}`,
- { status: 404, code: 'EXTEND_SOURCE_FILE_MISSING' },
+ `${label} resolved to a missing file: ${videoEntry.filename}`,
+ { status: 404, code: missingFileCode },
);
}
- extendFromVideoPath = candidate;
+ return candidate;
+ };
+
+ // Render history is read by both the extend and IC reference paths. Load it
+ // lazily and at most once — the file grows with every render, so a request
+ // carrying both would otherwise re-read and re-parse megabytes.
+ let historyCache = null;
+ const getHistory = async () => (historyCache ??= await loadHistory());
+
+ // Native extend (ltx2 runtime): forward the resolved path as
+ // extendFromVideoPath.
+ let extendFromVideoPath = null;
+ if (body.extendFromVideoId) {
+ extendFromVideoPath = await resolveHistoryVideoPath(body.extendFromVideoId, {
+ history: await getHistory(),
+ label: 'extendFromVideoId',
+ notFoundCode: 'EXTEND_SOURCE_NOT_FOUND',
+ missingFileCode: 'EXTEND_SOURCE_FILE_MISSING',
+ });
+ }
+
+ // IC-LoRA reference channel: either the staged upload or the picked prior
+ // render(s). The route already rejected the both-present case (and asserted
+ // the count against the weight's bounds) above, so at most one branch
+ // contributes and each id resolves 1:1 or throws.
+ let icReferencePaths = null;
+ if (icSpec) {
+ if (icReferenceUploadPath) {
+ icReferencePaths = [icReferenceUploadPath];
+ } else {
+ const history = await getHistory();
+ icReferencePaths = [];
+ for (const id of body.icReferenceVideoIds || []) {
+ icReferencePaths.push(await resolveHistoryVideoPath(id, {
+ history,
+ label: 'icReferenceVideoIds entry',
+ notFoundCode: 'IC_LORA_REFERENCE_NOT_FOUND',
+ missingFileCode: 'IC_LORA_REFERENCE_FILE_MISSING',
+ }));
+ }
+ }
}
// Collapse the parallel loraFilenames/loraScales arrays into the internal
@@ -930,7 +1131,10 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
);
}
- const effectiveChunks = body.mode === 'a2v' ? 1 : (body.chunks ?? 1);
+ // a2v and the IC remix modes both anchor a single render (audio track /
+ // reference clip), so chaining is meaningless — pin to 1 chunk. The IC path
+ // also hard-rejects an explicit chunks>1 above; this covers the default.
+ const effectiveChunks = (body.mode === 'a2v' || icSpec) ? 1 : (body.chunks ?? 1);
// Enqueue rather than spawn synchronously — the mediaJobQueue worker will
// run this when no other render is in flight. Caller never sees BUSY.
@@ -961,6 +1165,10 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
imageStrength: body.imageStrength,
chunks: effectiveChunks,
loras,
+ icReferencePaths,
+ icStrength: body.icStrength,
+ icAttentionStrength: body.icAttentionStrength,
+ icSkipStage2: body.icSkipStage2 === true || body.icSkipStage2 === 'true',
// Director-board attach tag (#1760 Phase 1). Rides into persisted
// job.params so the completion hook can file the clip onto the scene even
// if the board unmounted; absent for ordinary VideoGen-page renders.
@@ -999,6 +1207,10 @@ const ACTIVE_JOB_PARAM_FIELDS = [
// loras are { filename, scale } basenames (no server filesystem paths), so
// they're safe to echo back for the resuming picker to repopulate.
'loras',
+ // IC-LoRA remix dials — plain scalars, safe to echo. The reference clip
+ // itself rides a separate basename mapping below (its param is an absolute
+ // path, which the whitelist exists to keep off this surface).
+ 'icStrength', 'icAttentionStrength', 'icSkipStage2',
];
const pickJobParams = (params) => {
if (!params || typeof params !== 'object') return {};
@@ -1018,6 +1230,17 @@ const pickJobParams = (params) => {
.map((kf) => ({ file: basename(kf.path), index: kf.index }));
if (mapped.length) out.keyframes = mapped;
}
+ // IC-LoRA references are absolute paths for the same reason keyframes are —
+ // echo only the basename so the resuming form can show WHICH clip is in
+ // flight without leaking the staging/data layout. The client can't re-submit
+ // from a basename alone (an upload isn't re-derivable), so this is display
+ // only; the resumed render is already queued with the real path.
+ if (Array.isArray(params.icReferencePaths)) {
+ const names = params.icReferencePaths
+ .filter((p) => typeof p === 'string' && p)
+ .map((p) => basename(p));
+ if (names.length) out.icReferenceNames = names;
+ }
return out;
};
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 03ac5bf634..efff60fcdd 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -851,6 +851,146 @@ describe('videoGen routes', () => {
expect(r.status).toBe(200);
expect(mediaJobQueue.enqueueJob).toHaveBeenCalledTimes(1);
});
+
+ // ── IC-LoRA remix modes (#3100) ─────────────────────────────────────────
+ // The reference channel is what makes an IC render meaningful, so every
+ // pairing rule fails fast at the route rather than in the worker.
+ describe('IC-LoRA remix modes (#3100)', () => {
+ const icUpload = {
+ fieldname: 'icReference',
+ path: '/tmp/upload-fake.mp4',
+ originalname: 'depth.mp4',
+ mimetype: 'video/mp4',
+ size: 4321,
+ };
+
+ it('rejects ic-control with no reference (IC_LORA_REFERENCE_REQUIRED)', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'follow the depth clip', mode: 'ic-control',
+ });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/requires a reference video/i);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('stages an icReference upload and forwards icReferencePaths', async () => {
+ setPendingUpload(icUpload);
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'follow the depth clip', mode: 'ic-control', icStrength: 0.8,
+ });
+ expect(r.status).toBe(200);
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ params: expect.objectContaining({
+ mode: 'ic-control',
+ icStrength: 0.8,
+ icReferencePaths: [expect.stringMatching(/\/mock\/uploads\/video-ic-ref-.*\.mp4$/)],
+ // Tracked for worker cleanup the same way the audio upload is.
+ uploadedTempPaths: expect.arrayContaining([
+ expect.stringMatching(/\/mock\/uploads\/video-ic-ref-.*\.mp4$/),
+ ]),
+ // Chaining is meaningless for a reference-anchored render.
+ chunks: 1,
+ }),
+ }));
+ });
+
+ it('resolves an icReferenceVideoIds history pick to its on-disk path', async () => {
+ const id = '33333333-3333-4333-8333-333333333333';
+ videoGenService.loadHistory.mockResolvedValueOnce([{ id, filename: `${id}.mp4` }]);
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'follow the prior render', mode: 'ic-control', icReferenceVideoIds: id,
+ });
+ expect(r.status).toBe(200);
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ params: expect.objectContaining({
+ icReferencePaths: [`/mock/videos/${id}.mp4`],
+ }),
+ }));
+ });
+
+ it('rejects an icReferenceVideoIds id that is not in history', async () => {
+ videoGenService.loadHistory.mockResolvedValueOnce([]);
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'follow it', mode: 'ic-control',
+ icReferenceVideoIds: '44444444-4444-4444-8444-444444444444',
+ });
+ expect(r.status).toBe(404);
+ expect(r.body.error).toMatch(/not found in history/i);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('rejects an upload combined with a history pick (IC_LORA_REFERENCE_CONFLICT)', async () => {
+ setPendingUpload(icUpload);
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'follow it', mode: 'ic-control',
+ icReferenceVideoIds: '55555555-5555-4555-8555-555555555555',
+ });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/one reference shape per request/i);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('rejects more picks than the weight accepts (IC_LORA_REFERENCE_COUNT)', async () => {
+ // Control is single-reference; the bounds come from the registry, so this
+ // fires before any staging or history I/O.
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'follow them', mode: 'ic-control',
+ icReferenceVideoIds: [
+ '66666666-6666-4666-8666-666666666666',
+ '77777777-7777-4777-8777-777777777777',
+ ],
+ });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/needs exactly 1 reference video/i);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('rejects an IC reference outside an IC mode (IC_LORA_MODE_MISMATCH)', async () => {
+ setPendingUpload(icUpload);
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'plain render', mode: 'text',
+ });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/only valid with an IC remix mode/i);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('rejects an IC mode on a non-ltx2 model (IC_LORA_REQUIRES_LTX2)', async () => {
+ videoGenService.listVideoModels.mockReturnValueOnce([
+ { id: 'ltx_legacy', name: 'LTX legacy', runtime: 'mlx_video' },
+ ]);
+ setPendingUpload(icUpload);
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'follow it', mode: 'ic-control', modelId: 'ltx_legacy',
+ });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/ltx2-runtime model/i);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('rejects an IC mode on the grok backend (IC_LORA_REQUIRES_LOCAL_BACKEND)', async () => {
+ // The grok short-circuit runs before IC staging, so without this guard
+ // the reference clip would be silently dropped and a plain grok render
+ // queued instead.
+ setPendingUpload(icUpload);
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'follow it', mode: 'ic-control', backend: 'grok',
+ });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/isn't available on the Grok backend/i);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('rejects an IC mode combined with chunks > 1 (IC_LORA_CHUNKS_CONFLICT)', async () => {
+ setPendingUpload(icUpload);
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'follow it', mode: 'ic-control', chunks: 3,
+ });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/chunks > 1/i);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+ });
});
describe('GET /active', () => {
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 6b02159c30..2be55bc49c 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -31,6 +31,10 @@ import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess } from './generateVideoHelpers.js';
import { assertSafeLoraFilename } from '../loras.js';
import { isMlxVideoLtxLoraCapable } from '../../lib/runners.js';
+import {
+ isIcLoraMode, icLoraSpecForMode, resolveIcLoraWeight,
+ assertIcReferenceCount, icResolutionIssue,
+} from '../../lib/icLoraWeights.js';
import {
LTX2_VENV_PYTHON,
LTX2_HELPER_SCRIPT,
@@ -283,7 +287,67 @@ export const resolveVideoLoras = (loras) => {
// The helper lives in the ltx-2-mlx venv (so its `import ltx_pipelines_mlx`
// resolves) but the script file lives in the PortOS repo so updates ship
// with PortOS releases instead of the user's HF cache.
-const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, loras }) => {
+// Validate an IC-LoRA render against its weight's contract, then emit the
+// helper flags. The rules themselves (reference count, resolution divisibility)
+// live in the registry that owns the numbers; this asserts them and translates
+// to argv.
+//
+// `icLoraWeightPath` is resolved asynchronously up in generateVideo (the HF
+// cache lookup is I/O) and threaded down, so this stays synchronous like every
+// other buildArgs branch.
+//
+// Exported for direct unit testing: generateVideo floors each edge to a
+// multiple of 64 before buildArgs runs, so a factor-2 weight's
+// resolution-divisibility branch is unreachable through the public entry point
+// (64-step flooring always yields an even number). It becomes live the moment a
+// weight ships with `referenceDownscaleFactor > 2`, so it's tested here rather
+// than left unverified.
+export const icLoraArgs = ({ mode, width, height, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
+ const spec = icLoraSpecForMode(mode);
+ if (!spec) {
+ throw new ServerError(`Unknown IC-LoRA remix mode: ${mode}`, { status: 400, code: 'IC_LORA_UNKNOWN_MODE' });
+ }
+ if (!icLoraWeightPath) {
+ throw new ServerError(
+ `IC-LoRA weight for "${spec.mode}" could not be resolved — download ${spec.repo} from the model panel first.`,
+ { status: 400, code: 'IC_LORA_WEIGHT_UNRESOLVED' },
+ );
+ }
+ const refs = Array.isArray(icReferencePaths) ? icReferencePaths : [];
+ assertIcReferenceCount(spec, refs.length, (msg) => new ServerError(msg, {
+ status: 400, code: 'IC_LORA_REFERENCE_COUNT',
+ }));
+ for (const ref of refs) {
+ if (!ref || !existsSync(ref)) {
+ throw new ServerError(
+ `IC-LoRA reference not found on disk: ${ref || '(missing)'}`,
+ { status: 400, code: 'IC_LORA_REFERENCE_MISSING' },
+ );
+ }
+ }
+ // Inside the pipeline a bad resolution surfaces as a bare ValueError mid-render,
+ // after the model has already loaded — catch it here instead.
+ const resolutionIssue = icResolutionIssue(spec, width, height);
+ if (resolutionIssue) {
+ throw new ServerError(resolutionIssue, { status: 400, code: 'IC_LORA_RESOLUTION_NOT_DIVISIBLE' });
+ }
+ const args = [
+ '--ic-mode', spec.id,
+ '--ic-lora-path', icLoraWeightPath,
+ '--ic-strength', String(icStrength ?? 1.0),
+ // Pass the bounds rather than letting the helper carry its own table: the
+ // registry stays the single source of truth across both languages, and the
+ // helper still enforces them for a direct/script caller.
+ '--ic-min-references', String(spec.minReferences),
+ '--ic-max-references', String(spec.maxReferences),
+ ];
+ for (const ref of refs) args.push('--ic-reference', ref);
+ if (icAttentionStrength != null) args.push('--ic-attention-strength', String(icAttentionStrength));
+ if (icSkipStage2) args.push('--ic-skip-stage-2');
+ return args;
+};
+
+const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
assertByovRuntimeInstalled('ltx2');
// Map PortOS UI modes to the helper's subcommand. Native extend on ltx2
// routes to ExtendPipeline.extend_from_video — conditions on the entire
@@ -299,7 +363,8 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames
// their keyframes dropped on the floor. The route handler always sets
// mode='fflf' when keyframes are present, but defense-in-depth here covers
// callers that bypass the route (e.g. Writers Room batch dispatch).
- const helperMode = mode === 'fflf' ? 'fflf'
+ const helperMode = isIcLoraMode(mode) ? 'ic'
+ : mode === 'fflf' ? 'fflf'
: mode === 'a2v' ? 'a2v'
: wantsNativeExtend ? 'extend'
: mode === 'image' || mode === 'extend' ? 'image'
@@ -437,6 +502,12 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames
// so motion + audio sync to the chosen still.
if (sourceImagePath) args.push('--image', sourceImagePath);
}
+ if (helperMode === 'ic') {
+ args.push(...icLoraArgs({
+ mode, width, height, icReferencePaths, icLoraWeightPath,
+ icStrength, icAttentionStrength, icSkipStage2,
+ }));
+ }
return { bin: LTX2_VENV_PYTHON, args };
};
@@ -511,12 +582,22 @@ const buildHunyuanArgs = ({ model, prompt, negativePrompt, width, height, numFra
return { bin: HUNYUAN_VENV_PYTHON, args };
};
-const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, textEncoderRepo, outputPath, loras }) => {
+const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, textEncoderRepo, outputPath, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
// Route to the dgrauet/ltx-2-mlx helper when the model declares the new
// runtime. Existing notapalindrome models default to runtime: 'mlx_video'
// (or undefined in legacy registries — see backfillRuntime in mediaModels.js).
if (model.runtime === 'ltx2') {
- return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, loras });
+ return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 });
+ }
+ // IC-LoRA remix modes are an LTX-2 primitive (ICLoraPipeline) — no other
+ // runtime has an equivalent. The route guards this too, but a non-route
+ // caller (test, persisted queue replay) would otherwise fall through to a
+ // plain t2v render with the user's reference clip silently dropped.
+ if (isIcLoraMode(mode)) {
+ throw new ServerError(
+ `IC-LoRA remix modes require an ltx2-runtime model. Model "${modelId}" runs on "${model.runtime || 'mlx_video'}".`,
+ { status: 400, code: 'IC_LORA_REQUIRES_LTX2' },
+ );
}
const hasLoras = Array.isArray(loras) && loras.length > 0;
// Defense-in-depth: LoRAs fuse only on ltx2 (handled above) or a non-quantized
@@ -622,7 +703,7 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,
// use (avoiding drift between two hardcoded constants).
export const DEFAULT_NUM_FRAMES = 121;
-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = DEFAULT_NUM_FRAMES, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, mode = null, imageStrength = null, loras = null, hidden = false, jobId: providedJobId = null }) {
+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = DEFAULT_NUM_FRAMES, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, mode = null, imageStrength = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, hidden = false, jobId: providedJobId = null }) {
uploadedTempPaths = Array.isArray(uploadedTempPaths) ? uploadedTempPaths : [];
if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
// Single-flight is now enforced by the mediaJobQueue worker upstream — only
@@ -653,6 +734,22 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// no-op there.
const resolvedLoras = resolveVideoLoras(loras);
+ // IC-LoRA remix: resolve the per-mode weight before any GPU work. A cached
+ // weight resolves to the exact file inside the HF snapshot; an un-cached one
+ // falls back to the repo id, which ICLoraPipeline downloads itself — log that
+ // so a several-hundred-MB pull mid-render isn't a mystery in the server log.
+ let icLoraWeightPath = null;
+ if (isIcLoraMode(mode)) {
+ const resolved = await resolveIcLoraWeight(mode);
+ if (!resolved) {
+ throw new ServerError(`Unknown IC-LoRA remix mode: ${mode}`, { status: 400, code: 'IC_LORA_UNKNOWN_MODE' });
+ }
+ icLoraWeightPath = resolved.path;
+ if (!resolved.cached) {
+ console.log(`⬇️ IC-LoRA weight not cached — ${resolved.spec.repo} will download at render time`);
+ }
+ }
+
await ensureDir(PATHS.videos);
await ensureDir(PATHS.videoThumbnails);
@@ -683,6 +780,13 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
}
// Caller may pass null/'' to use mlx_video's default (1.0 = preserve source).
const actualImageStrength = imageStrength != null && imageStrength !== '' ? Number(imageStrength) : null;
+ // IC-LoRA dials. `icStrength` weights the reference-video conditioning
+ // channel (default 1.0 matches the pipeline); `icAttentionStrength` stays
+ // null when unset so the pipeline applies its own default rather than us
+ // pinning 1.0 and shadowing a future upstream change.
+ const actualIcStrength = icStrength != null && icStrength !== '' ? Number(icStrength) : 1.0;
+ const actualIcAttentionStrength = icAttentionStrength != null && icAttentionStrength !== ''
+ ? Number(icAttentionStrength) : null;
const actualTextEncoderRepo = getTextEncoderRepo();
const parsedNumFrames = Number(numFrames);
const parsedFps = Number(fps);
@@ -801,6 +905,18 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// render apart from a user who happened to pick 8 steps — comparing it
// against the default Standard render is the whole point of the knob.
...(t2vTwoStage ? { twoStageT2v: true, stage2Steps: actualStage2Steps } : {}),
+ // IC-LoRA remix settings, stamped so the lightbox Remix flow can round-trip
+ // them. The reference clip is recorded by BASENAME (not the absolute
+ // staging path) — history is user-facing and a durable upload path is both
+ // noise and machine-specific.
+ ...(isIcLoraMode(mode) ? {
+ icStrength: actualIcStrength,
+ ...(actualIcAttentionStrength != null ? { icAttentionStrength: actualIcAttentionStrength } : {}),
+ ...(icSkipStage2 ? { icSkipStage2: true } : {}),
+ ...(Array.isArray(icReferencePaths) && icReferencePaths.length
+ ? { icReferenceNames: icReferencePaths.map((p) => basename(p)) }
+ : {}),
+ } : {}),
// Stamp applied LoRAs using the SAME parallel-array contract image renders
// use (`loraFilenames` + `loraScales`) so the existing history consumers —
// normalizeVideo / getRenderConfigForItem (client/src/components/media/
@@ -824,7 +940,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// logic of the spawn-error handler so failure modes converge.
let bin, args;
try {
- ({ bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath, loras: resolvedLoras }));
+ ({ bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath, loras: resolvedLoras, icReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2 }));
} catch (err) {
job.status = 'error';
const reason = err.message || 'Failed to build video gen args';
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 44a41fe81d..57c20c9585 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -71,6 +71,19 @@ vi.mock('../../lib/hfToken.js', () => ({
getHfToken: vi.fn(async () => null),
}));
+// resolveIcLoraWeight() inspects the HF cache to pin the exact weight file.
+// That's real async fs work against the user's ~/.cache — mock the inspection
+// layer so the IC-LoRA arg tests exercise the registry + arg plumbing, not the
+// cache walk (which hfCache.test.js covers). `snapshotPath` non-null + the
+// always-true existsSync mock below means the weight resolves to its exact
+// pinned filename; a test that wants the un-cached fallback overrides this.
+const { mockInspectModelCache } = vi.hoisted(() => ({
+ mockInspectModelCache: vi.fn(async () => ({ cached: true, sizeBytes: 1000, snapshotPath: '/mock/hf/snap' })),
+}));
+vi.mock('../../lib/hfCache.js', () => ({
+ inspectModelCache: mockInspectModelCache,
+}));
+
vi.mock('fs', () => ({
existsSync: vi.fn(() => true),
statSync: vi.fn(() => ({ size: 1000 })),
@@ -1619,3 +1632,199 @@ describe('generateVideo — chunk-boundary marker parsing (#2463)', () => {
expect(statusFrames(vi.mocked(broadcastSse), 'Finalizing')).toHaveLength(1);
});
});
+
+describe('generateVideo — IC-LoRA remix arg threading (#3100)', () => {
+ // 704×448 is divisible by the Control weight's referenceDownscaleFactor of 2,
+ // so these renders clear the resolution gate. Frames stay small so the FFLF
+ // pixel-budget clamp (fflf-only anyway) never enters the picture.
+ const baseIcRender = {
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'a dancer following the depth clip',
+ width: 704, height: 448, numFrames: 25, fps: 24,
+ mode: 'ic-control',
+ icReferencePaths: ['/mock/data/videos/depth.mp4'],
+ };
+
+ const findIcCall = (spawnMock) => spawnMock.mock.calls.find(
+ ([bin, args]) => String(bin).includes('.portos/ltx-2-mlx/.venv/bin/python3')
+ && Array.isArray(args) && args.includes('--ic-mode'),
+ );
+
+ beforeEach(() => {
+ mockInspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 1000, snapshotPath: '/mock/hf/snap' });
+ });
+
+ it('routes ic-control to --mode ic with the pinned weight, reference, and strength', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+
+ await generateVideo({ ...baseIcRender, jobId: 'ic-basic', icStrength: 0.75 });
+
+ const call = findIcCall(spawnMock);
+ expect(call).toBeTruthy();
+ const args = call[1];
+ expect(args[args.indexOf('--mode') + 1]).toBe('ic');
+ expect(args[args.indexOf('--ic-mode') + 1]).toBe('control');
+ expect(args[args.indexOf('--ic-reference') + 1]).toBe('/mock/data/videos/depth.mp4');
+ expect(args[args.indexOf('--ic-strength') + 1]).toBe('0.75');
+ // Cached snapshot → the exact pinned filename, not the bare repo id, so a
+ // multi-weight repo can't glob-pick the wrong file.
+ expect(args[args.indexOf('--ic-lora-path') + 1])
+ .toBe(join('/mock/hf/snap', 'ltx-2.3-22b-ic-lora-union-control-ref0.5.safetensors'));
+ // The reference-count bounds are PASSED to the helper rather than hardcoded
+ // there, so the registry stays the single source of truth across languages.
+ expect(args[args.indexOf('--ic-min-references') + 1]).toBe('1');
+ expect(args[args.indexOf('--ic-max-references') + 1]).toBe('1');
+ });
+
+ it('falls back to the HF repo id when the weight is not cached', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+ mockInspectModelCache.mockResolvedValue({ cached: false, sizeBytes: 0, snapshotPath: null });
+
+ await generateVideo({ ...baseIcRender, jobId: 'ic-uncached' });
+
+ const args = findIcCall(spawnMock)[1];
+ expect(args[args.indexOf('--ic-lora-path') + 1])
+ .toBe('Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control');
+ });
+
+ it('defaults --ic-strength to 1.0 and omits the optional dials', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+
+ await generateVideo({ ...baseIcRender, jobId: 'ic-defaults' });
+
+ const args = findIcCall(spawnMock)[1];
+ // JS stringifies 1.0 as "1" — argparse's float parse accepts either.
+ expect(args[args.indexOf('--ic-strength') + 1]).toBe('1');
+ // Omitted so the pipeline applies its own defaults rather than us pinning
+ // values that would shadow a future upstream change.
+ expect(args).not.toContain('--ic-attention-strength');
+ expect(args).not.toContain('--ic-skip-stage-2');
+ });
+
+ it('emits --ic-attention-strength and --ic-skip-stage-2 when requested', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+
+ await generateVideo({
+ ...baseIcRender, jobId: 'ic-dials',
+ icAttentionStrength: 0.4, icSkipStage2: true,
+ });
+
+ const args = findIcCall(spawnMock)[1];
+ expect(args[args.indexOf('--ic-attention-strength') + 1]).toBe('0.4');
+ expect(args).toContain('--ic-skip-stage-2');
+ });
+
+ it('stacks user LoRAs alongside the IC-LoRA rather than replacing it', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+
+ await generateVideo({
+ ...baseIcRender, jobId: 'ic-plus-user-lora',
+ loras: [{ filename: 'character.safetensors', scale: 0.9 }],
+ });
+
+ const args = findIcCall(spawnMock)[1];
+ // Both channels present: the IC weight rides --ic-lora-path (fused via
+ // lora_paths) and the character LoRA rides --user-loras (_pending_loras).
+ expect(args).toContain('--ic-lora-path');
+ const userLoras = JSON.parse(args[args.indexOf('--user-loras') + 1]);
+ expect(userLoras).toEqual([
+ { path: join(MOCK_PATHS.loras, 'character.safetensors'), strength: 0.9 },
+ ]);
+ });
+
+ it('rejects a reference count outside the weight contract', async () => {
+ // Control is a single-reference weight; two clips would silently produce
+ // plausible garbage rather than an error inside the pipeline.
+ await expect(generateVideo({
+ ...baseIcRender, jobId: 'ic-too-many-refs',
+ icReferencePaths: ['/mock/data/videos/a.mp4', '/mock/data/videos/b.mp4'],
+ })).rejects.toThrow(/needs exactly 1 reference video/);
+ await expect(generateVideo({
+ ...baseIcRender, jobId: 'ic-no-refs', icReferencePaths: [],
+ })).rejects.toThrow(/needs exactly 1 reference video/);
+ });
+
+ it('rejects a reference clip that is not on disk', async () => {
+ const { existsSync } = await import('fs');
+ // The reference path is the one existence check that matters here; every
+ // other existsSync caller in this flow is satisfied by the default mock.
+ vi.mocked(existsSync).mockImplementation((p) => p !== '/mock/data/videos/gone.mp4');
+ await expect(generateVideo({
+ ...baseIcRender, jobId: 'ic-missing-ref',
+ icReferencePaths: ['/mock/data/videos/gone.mp4'],
+ })).rejects.toThrow(/IC-LoRA reference not found on disk/);
+ vi.mocked(existsSync).mockImplementation(() => true);
+ });
+
+ it('rejects an IC render on a non-ltx2 runtime', async () => {
+ await expect(generateVideo({
+ ...baseIcRender, jobId: 'ic-wrong-runtime', modelId: 'ltx23_unified',
+ })).rejects.toThrow(/require an ltx2-runtime model/);
+ });
+
+ it('stamps the IC dials + reference basename onto the history record', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ vi.mocked(spawnDetached).mockClear();
+ const started = [];
+ const onStarted = (p) => started.push(p);
+ videoGenEvents.on('started', onStarted);
+
+ await generateVideo({
+ ...baseIcRender, jobId: 'ic-history-stamp',
+ icStrength: 0.6, icSkipStage2: true,
+ });
+
+ videoGenEvents.off('started', onStarted);
+ const meta = started.find((s) => s.generationId === 'ic-history-stamp');
+ expect(meta).toBeTruthy();
+ expect(meta.mode).toBe('ic-control');
+ expect(meta.icStrength).toBe(0.6);
+ expect(meta.icSkipStage2).toBe(true);
+ // BASENAME only — the absolute staging path is machine-specific and never
+ // belongs in a user-facing history record.
+ expect(meta.icReferenceNames).toEqual(['depth.mp4']);
+ });
+});
+
+describe('icLoraArgs — direct validation (#3100)', () => {
+ let icLoraArgs;
+ beforeEach(async () => { ({ icLoraArgs } = await import('./local.js')); });
+
+ const base = {
+ mode: 'ic-control',
+ width: 704, height: 448,
+ icReferencePaths: ['/mock/data/videos/depth.mp4'],
+ icLoraWeightPath: '/mock/hf/snap/control.safetensors',
+ icStrength: 1.0,
+ };
+
+ it('rejects an output resolution not divisible by the reference-downscale factor', () => {
+ // Unreachable via generateVideo (edges are floored to multiples of 64, so
+ // always even) but live the moment a weight ships with a factor > 2 — an odd
+ // dimension here proves the guard fires instead of failing mid-render.
+ expect(() => icLoraArgs({ ...base, width: 705 }))
+ .toThrow(/divisible by 2/);
+ expect(() => icLoraArgs({ ...base, height: 449 }))
+ .toThrow(/divisible by 2/);
+ });
+
+ it('rejects an unknown remix mode', () => {
+ expect(() => icLoraArgs({ ...base, mode: 'ic-nope' })).toThrow(/Unknown IC-LoRA remix mode/);
+ });
+
+ it('rejects an unresolved weight path', () => {
+ expect(() => icLoraArgs({ ...base, icLoraWeightPath: null }))
+ .toThrow(/could not be resolved/);
+ });
+});