Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add a swappable prompt conditioner to MiniMax H3 video renders
[._.]/ Adam Eivy1daf25576c09
diff --git a/.changelog/next/added-agent-a6a78c1a.md b/.changelog/next/added-agent-a6a78c1a.mdnew file mode 100644index 0000000000..369fd35233--- /dev/null+++ b/.changelog/next/added-agent-a6a78c1a.md@@ -0,0 +1 @@+- Video Gen: swappable text encoder for MiniMax H3 — pick the stock Qwen3-VL-32B conditioner or an uncensored Ultra-Heretic substitute per render, with its own download/repair lanediff --git a/client/src/components/videoGen/TextEncoderPicker.jsx b/client/src/components/videoGen/TextEncoderPicker.jsxnew file mode 100644index 0000000000..b1001af699--- /dev/null+++ b/client/src/components/videoGen/TextEncoderPicker.jsx@@ -0,0 +1,83 @@+/**+ * Prompt-conditioner picker for models that offer a choice (#4081).+ *+ * MiniMax H3 reads the unnormalized hidden state after Qwen3-VL language layer+ * 49 and never evaluates the rest of the language model, so the conditioner can+ * be swapped for another checkpoint carrying the same layers — which changes how+ * the model *reads* a prompt without touching the diffusion weights. This is the+ * control for that choice.+ *+ * Presentational: options, selection, and download status are all owned by the+ * VideoGen page. Rendered only when the model actually offers more than one+ * option (the server decorates the list per model), so no runtime check lives+ * here.+ *+ * A substitute is a separate multi-GB pull, so its Download badge sits inline+ * with the select rather than behind the collapsed Advanced panel — the user has+ * to see the cost at the moment they pick it, and the page gates Generate on the+ * same status.+ */+import ModelDownloadBadge from '../media/ModelDownloadBadge';+import { formatBytes } from '../../utils/formatters.js';++const inputCls = 'w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50';++export default function TextEncoderPicker({+ options = [],+ value,+ onChange,+ status = null,+ onDownload,+ onCancel,+ disabled = false,+}) {+ if (options.length < 2) return null;+ const selected = options.find((option) => option.id === value) || options[0];+ // Formatted from the option's exact published byte count rather than a second+ // "~N GB" literal on the registry entry, so the option text, the Download+ // button and the post-download "Available · N" badge can never disagree.+ const sizeLabel = selected.sizeBytes ? formatBytes(selected.sizeBytes) : null;+ // Built-in conditioners ship inside the model's own weights, so they have no+ // separate download of their own to badge.+ const needsDownload = !selected.builtIn && (status === null || status.cached === false || status.downloading);++ return (+ <div className="mt-2">+ <label htmlFor="video-text-encoder" className="block text-xs font-medium text-gray-400 mb-1">+ Text encoder+ </label>+ <select+ id="video-text-encoder"+ value={selected.id}+ onChange={(e) => onChange(e.target.value)}+ disabled={disabled}+ className={inputCls}+ >+ {options.map((option) => (+ <option key={option.id} value={option.id}>+ {option.label}+ {option.sizeBytes ? ` (~${formatBytes(option.sizeBytes)} download)` : ''}+ </option>+ ))}+ </select>+ {selected.description && (+ <p className="text-[10px] text-gray-500 leading-snug mt-1">{selected.description}</p>+ )}+ {/* An uncensored conditioner is a deliberate choice, not a default —+ state what changed rather than leaving it to the model card. */}+ {selected.advisory && (+ <p className="text-[10px] text-port-warning leading-snug mt-1">{selected.advisory}</p>+ )}+ {needsDownload && (+ <div className="mt-1">+ <ModelDownloadBadge+ status={status}+ onDownload={() => onDownload?.(selected.id)}+ onCancel={onCancel}+ estimateLabel={sizeLabel ? `~${sizeLabel}` : undefined}+ />+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/videoGen/TextEncoderPicker.test.jsx b/client/src/components/videoGen/TextEncoderPicker.test.jsxnew file mode 100644index 0000000000..e9906a6bf8--- /dev/null+++ b/client/src/components/videoGen/TextEncoderPicker.test.jsx@@ -0,0 +1,112 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import TextEncoderPicker from './TextEncoderPicker';++const STOCK = { id: 'stock', label: 'Stock — H3 Qwen3-VL-32B', description: 'Ships with the model.', builtIn: true };+const HERETIC = {+ id: 'heretic-bf16',+ label: 'Ultra-Heretic uncensored',+ description: 'Abliterated Qwen3-VL-32B conditioner.',+ builtIn: false,+ sizeBytes: 51506295440,+ advisory: 'This conditioner has had its refusal behavior removed.',+};+const OPTIONS = [STOCK, HERETIC];++describe('TextEncoderPicker', () => {+ // The empty/one-entry list is how a runtime with no substitutions hides the+ // control — rendering a select with a single unchangeable option would be+ // pure noise on every non-H3 model.+ it.each([[[]], [[STOCK]]])('renders nothing for %j options', (options) => {+ const { container } = render(<TextEncoderPicker options={options} value="stock" onChange={vi.fn()} />);+ expect(container).toBeEmptyDOMElement();+ });++ it('pairs its label to the select and reports the chosen id', async () => {+ const onChange = vi.fn();+ render(<TextEncoderPicker options={OPTIONS} value="stock" onChange={onChange} />);+ const select = screen.getByLabelText('Text encoder');+ expect(select).toHaveValue('stock');+ await userEvent.selectOptions(select, 'heretic-bf16');+ expect(onChange).toHaveBeenCalledWith('heretic-bf16');+ });++ it('surfaces the download size in the option text', () => {+ render(<TextEncoderPicker options={OPTIONS} value="stock" onChange={vi.fn()} />);+ expect(screen.getByRole('option', { name: /Ultra-Heretic uncensored \(~48 GB download\)/ })).toBeInTheDocument();+ // The built-in option has no separate download, so no size is invented for it.+ expect(screen.getByRole('option', { name: 'Stock — H3 Qwen3-VL-32B' })).toBeInTheDocument();+ });++ // An uncensored conditioner is a deliberate choice, so the picker states what+ // changed instead of leaving it to an external model card.+ it('shows the advisory only for the option that carries one', () => {+ const { rerender } = render(<TextEncoderPicker options={OPTIONS} value="stock" onChange={vi.fn()} />);+ expect(screen.queryByText(HERETIC.advisory)).not.toBeInTheDocument();+ expect(screen.getByText(STOCK.description)).toBeInTheDocument();++ rerender(<TextEncoderPicker options={OPTIONS} value="heretic-bf16" onChange={vi.fn()} />);+ expect(screen.getByText(HERETIC.advisory)).toBeInTheDocument();+ expect(screen.getByText(HERETIC.description)).toBeInTheDocument();+ });++ // The built-in option ships inside the model's own weights — badging it would+ // offer a download for something that isn't separately downloadable.+ it('badges a download only for a substitute that needs one', () => {+ const { rerender } = render(+ <TextEncoderPicker options={OPTIONS} value="stock" onChange={vi.fn()} status={null} />,+ );+ expect(screen.queryByRole('button', { name: /Download/ })).not.toBeInTheDocument();++ rerender(+ <TextEncoderPicker+ options={OPTIONS}+ value="heretic-bf16"+ onChange={vi.fn()}+ status={{ id: 'heretic-bf16', repo: 'org/heretic', cached: false, sizeBytes: 0 }}+ />,+ );+ expect(screen.getByRole('button', { name: /Download \(~48 GB\)/ })).toBeInTheDocument();+ });++ it('passes the selected id to the download handler', async () => {+ const onDownload = vi.fn();+ render(+ <TextEncoderPicker+ options={OPTIONS}+ value="heretic-bf16"+ onChange={vi.fn()}+ status={{ id: 'heretic-bf16', repo: 'org/heretic', cached: false, sizeBytes: 0 }}+ onDownload={onDownload}+ />,+ );+ await userEvent.click(screen.getByRole('button', { name: /Download/ }));+ expect(onDownload).toHaveBeenCalledWith('heretic-bf16');+ });++ it('drops the badge once the substitute is cached', () => {+ render(+ <TextEncoderPicker+ options={OPTIONS}+ value="heretic-bf16"+ onChange={vi.fn()}+ status={{ id: 'heretic-bf16', repo: 'org/heretic', cached: true, sizeBytes: 51506295440 }}+ />,+ );+ expect(screen.queryByRole('button', { name: /Download/ })).not.toBeInTheDocument();+ });++ // A value with no matching option would leave the browser rendering the first+ // entry while the parent believes something else is selected; fall back+ // visibly to the first (stock) option instead.+ it('falls back to the first option for an unknown value', () => {+ render(<TextEncoderPicker options={OPTIONS} value="gone" onChange={vi.fn()} />);+ expect(screen.getByLabelText('Text encoder')).toHaveValue('stock');+ });++ it('disables the select while a render is in flight', () => {+ render(<TextEncoderPicker options={OPTIONS} value="stock" onChange={vi.fn()} disabled />);+ expect(screen.getByLabelText('Text encoder')).toBeDisabled();+ });+});diff --git a/client/src/hooks/useModelDownloadStatus.js b/client/src/hooks/useModelDownloadStatus.jsindex 9d8d13c06e..36f619facf 100644--- a/client/src/hooks/useModelDownloadStatus.js+++ b/client/src/hooks/useModelDownloadStatus.js@@ -5,7 +5,7 @@ import toast from '../components/ui/Toast';import {getImageModelStatuses, getVideoModelStatuses,verifyImageModels, verifyVideoModels, repairImageModel, repairVideoModel,- repairTextEncoder, repairIcLora,+ repairTextEncoder, repairTextEncoderOption, repairIcLora,} from '../services/apiImageVideo.js';// Sentinel `modelId` used to drive a text-encoder download instead of a model@@ -19,6 +19,12 @@ export const TEXT_ENCODER_DOWNLOAD_ID = '__text_encoder__';// 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.+// Namespace for a substitutable prompt-conditioner download id (#4081). The+// video form passes `textEncoderDownloadId(option.id)` to start()/repair(); the+// prefix keeps those ids from ever colliding with a registry model id.+export const TEXT_ENCODER_OPTION_PREFIX = '__text_encoder_option__:';+export const textEncoderDownloadId = (id) => `${TEXT_ENCODER_OPTION_PREFIX}${id}`;+export const buildDownloadUrl = (kind, modelId, force = false) => {if (!modelId) return null;// A repair-initiated re-download appends `?force=1` so the server re-fetches@@ -34,6 +40,14 @@ export const buildDownloadUrl = (kind, modelId, force = false) => {if (kind === 'video' && isIcLoraMode(modelId)) {return `/api/video-gen/ic-loras/${encodeURIComponent(modelId)}/download${q}`;}+ // Substitutable prompt conditioners (#4081) are downloadable but aren't+ // registry models either. Identified by the TEXT_ENCODER_OPTION_PREFIX the+ // caller wraps the registry id in, rather than by the bare id — otherwise a+ // future model whose id happened to match one would be misrouted.+ if (kind === 'video' && String(modelId).startsWith(TEXT_ENCODER_OPTION_PREFIX)) {+ const id = String(modelId).slice(TEXT_ENCODER_OPTION_PREFIX.length);+ return `/api/video-gen/text-encoders/${encodeURIComponent(id)}/download${q}`;+ }return `/api/${kind}-gen/models/${encodeURIComponent(modelId)}/download${q}`;};@@ -72,6 +86,7 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {setStatuses(Array.isArray(body?.models) ? body.models : []);setExtra({textEncoder: body?.textEncoder || null,+ textEncoderOptions: Array.isArray(body?.textEncoderOptions) ? body.textEncoderOptions : [],icLoras: Array.isArray(body?.icLoras) ? body.icLoras : [],});} else {@@ -152,11 +167,14 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {// 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 isEncoderOption = kind === 'video' && String(modelId).startsWith(TEXT_ENCODER_OPTION_PREFIX);const run = isTextEncoder? () => repairTextEncoder({ deep }): isIcLora? () => repairIcLora(modelId, { deep })- : () => (kind === 'video' ? repairVideoModel : repairImageModel)(modelId, { deep });+ : isEncoderOption+ ? () => repairTextEncoderOption(String(modelId).slice(TEXT_ENCODER_OPTION_PREFIX.length), { deep })+ : () => (kind === 'video' ? repairVideoModel : repairImageModel)(modelId, { deep });const result = await run().catch((err) => {toast.error(err?.message || 'Repair failed');return null;@@ -195,8 +213,17 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {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 ic = icList.find((s) => s.id === modelId);+ if (ic) return ic;+ // Conditioner entries are keyed by their BARE registry id in the status+ // payload, so unwrap the download namespace before matching.+ if (String(modelId).startsWith(TEXT_ENCODER_OPTION_PREFIX)) {+ const bare = String(modelId).slice(TEXT_ENCODER_OPTION_PREFIX.length);+ const list = Array.isArray(extra.textEncoderOptions) ? extra.textEncoderOptions : [];+ return list.find((s) => s.id === bare) || null;+ }+ return null;+ }, [statuses, extra.icLoras, extra.textEncoderOptions]);const activeStatus = useMemo(() => {if (!activeModelId) return null;diff --git a/client/src/hooks/useModelDownloadStatus.test.js b/client/src/hooks/useModelDownloadStatus.test.jsindex 40ebc0f895..356e429d38 100644--- a/client/src/hooks/useModelDownloadStatus.test.js+++ b/client/src/hooks/useModelDownloadStatus.test.js@@ -1,5 +1,7 @@import { describe, expect, it } from 'vitest';-import { buildDownloadUrl, TEXT_ENCODER_DOWNLOAD_ID } from './useModelDownloadStatus.js';+import {+ buildDownloadUrl, TEXT_ENCODER_DOWNLOAD_ID, textEncoderDownloadId,+} from './useModelDownloadStatus.js';describe('buildDownloadUrl', () => {it('builds a plain model download URL', () => {@@ -19,4 +21,30 @@ describe('buildDownloadUrl', () => {'/api/video-gen/text-encoder/download?force=1',);});++ // Substitutable prompt conditioners (#4081) route to their own lane, and the+ // SHARED install-wide encoder keeps its separate scalar route — the two must+ // not collapse into one another.+ it('routes a substitutable text encoder to the per-id lane', () => {+ expect(buildDownloadUrl('video', textEncoderDownloadId('heretic-bf16'))).toBe(+ '/api/video-gen/text-encoders/heretic-bf16/download',+ );+ expect(buildDownloadUrl('video', textEncoderDownloadId('heretic-bf16'), true)).toBe(+ '/api/video-gen/text-encoders/heretic-bf16/download?force=1',+ );+ });++ // Routing keys on the namespace prefix, not the bare id, so a registry model+ // that ever shared an encoder's name can't be misrouted into the encoder lane.+ it('does not treat a bare encoder-shaped model id as an encoder', () => {+ expect(buildDownloadUrl('video', 'heretic-bf16')).toBe(+ '/api/video-gen/models/heretic-bf16/download',+ );+ });++ it('leaves image-gen ids on the model lane whatever they are named', () => {+ expect(buildDownloadUrl('image', textEncoderDownloadId('heretic-bf16'))).toBe(+ `/api/image-gen/models/${encodeURIComponent(textEncoderDownloadId('heretic-bf16'))}/download`,+ );+ });});diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.jsindex 88fc00ac77..d62950c29d 100644--- a/client/src/hooks/useVideoGenForm.js+++ b/client/src/hooks/useVideoGenForm.js@@ -17,6 +17,7 @@ import {supportsVideoAudioControls, supportsVideoAudioPromptControls,normalizeFramesForModel, normalizeFpsForModel,icLoraSpecForMode, icResolutionIssue,+ STOCK_TEXT_ENCODER_ID, textEncoderOptionsForModel, normalizeTextEncoderForModel,} from '../lib/videoGenParams.js';/**@@ -84,6 +85,11 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })const [imageStrength, setImageStrength] = useState('');const [seed, setSeed] = useState('');const [tiling, setTiling] = useState('auto');+ // Which prompt conditioner reads the prompt. Only MiniMax H3 offers a choice+ // today (`model.textEncoderOptions`, decorated server-side); everywhere else+ // the list is empty and this stays on the stock sentinel, which the submit+ // builder drops from the payload entirely.+ const [textEncoderId, setTextEncoderId] = useState(STOCK_TEXT_ENCODER_ID);const [disableAudio, setDisableAudio] = useState(false);// Video LoRAs (ltx2 runtime only) — `{ filename, name, scale }` entries the// LoraPicker owns; `availableLoras` is the full installed library filtered@@ -404,12 +410,23 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })// Remix/deep-link/resume paths set model + sampler fields independently.// Reconcile them once the model is known so a legacy LTX 8n+1 frame count// cannot reach a Wan 4n+1 runner (and a model-specific fps stays selectable).+ // Reconciled here rather than in applyModelSelection so the remix / resume /+ // deep-link paths are covered too: they set modelId and textEncoderId+ // independently, and a conditioner the newly-resolved model can't load would+ // otherwise sit in the <select> with no matching <option> until submit 400'd.useEffect(() => {if (!currentModel) return;setNumFrames((current) => normalizeFramesForModel(current, currentModel));setFps((current) => normalizeFpsForModel(current, currentModel));+ setTextEncoderId((current) => normalizeTextEncoderForModel(current, currentModel));}, [currentModel]);+ // Substitutable prompt conditioners the selected model can load, straight off+ // the server-decorated entry. Empty for every runtime without substitutions,+ // which is what hides the picker — the page never re-derives that from a+ // runtime name.+ const textEncoderOptions = textEncoderOptionsForModel(currentModel);+// Video-LoRA family for the selected model — 'ltx-video' on ltx2, else null.// When null the picker is hidden and no LoRAs ride along on submit (the// route would 400 with LORAS_REQUIRE_LTX2). Derived, not state, so it tracks@@ -866,6 +883,14 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })// store a boolean here — silently ignore unknown values so the <select>// stays valid and the next POST doesn't 400.if (typeof item.tiling === 'string' && VIDEO_TILING_ENUM_SET.has(item.tiling)) setTiling(item.tiling);+ // ALWAYS set explicitly (like steps/guidanceScale above): history records the+ // conditioner only when it wasn't the stock one, so a missing field means+ // 'stock' and must clear a leftover override rather than silently reusing it+ // on a render the user asked to reproduce faithfully. The currentModel effect+ // snaps an id this model can't load back to stock.+ setTextEncoderId(typeof item.textEncoderId === 'string' && item.textEncoderId+ ? item.textEncoderId+ : STOCK_TEXT_ENCODER_ID);// disableAudio: always set explicitly (true/false) so the toggle reliably// matches the remixed render. Skipping the false branch would leave the// toggle stuck ON when the user remixes a clip that had audio enabled.@@ -963,6 +988,10 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })if (p.guidanceScale != null) setGuidanceScale(String(p.guidanceScale));if (p.seed != null) setSeed(String(p.seed));if (p.tiling) setTiling(p.tiling);+ // Resume echoes the field only for a non-stock render, so absence is 'stock'.+ setTextEncoderId(typeof p.textEncoderId === 'string' && p.textEncoderId+ ? p.textEncoderId+ : STOCK_TEXT_ENCODER_ID);if (typeof p.disableAudio === 'boolean') setDisableAudio(p.disableAudio);if (p.mode === 'grok') {// Grok job: 'grok' is the queue discriminator, not a semantic video@@ -1157,6 +1186,12 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })guidanceScale: guidanceScale || '',seed: seed || '',tiling: currentModel?.supportsTiling === false ? 'auto' : tiling,+ // Dropped entirely for the stock conditioner so an unswapped render posts+ // exactly the body it did before this knob existed — and re-snapped to the+ // model's own list in case a restore raced the reconciliation effect.+ textEncoderId: normalizeTextEncoderForModel(textEncoderId, currentModel) === STOCK_TEXT_ENCODER_ID+ ? undefined+ : textEncoderId,disableAudio: effectiveDisableAudio ? 'true' : 'false',mode,imageStrength: imageStrength || '',@@ -1241,6 +1276,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })imageStrength, setImageStrength,seed, setSeed, handleRandomSeed,tiling, setTiling,+ textEncoderId, setTextEncoderId, textEncoderOptions,disableAudio, setDisableAudio,noMusic, setNoMusic,// Framesdiff --git a/client/src/hooks/useVideoGenForm.test.jsx b/client/src/hooks/useVideoGenForm.test.jsxindex ccdb72759e..b2b4c79457 100644--- a/client/src/hooks/useVideoGenForm.test.jsx+++ b/client/src/hooks/useVideoGenForm.test.jsx@@ -34,6 +34,13 @@ const H3 = {{ label: '768x1344', w: 768, h: 1344 },],supportsNegativePrompt: false, supportsTiling: false, supportsDisableAudio: false,+ // Server-decorated per model (videoGen/local.js#decorateVideoModel) — the+ // client never derives this from a runtime name, so the fixture carries it+ // exactly as the /models payload does.+ textEncoderOptions: [+ { id: 'stock', label: 'Stock', description: 'Ships with the model.', builtIn: true },+ { id: 'heretic-bf16', label: 'Ultra-Heretic', description: 'Uncensored.', builtIn: false, sizeBytes: 51506295440 },+ ],};const MODELS = [MLX, LTX2];const STATUS = { connected: true, defaultModel: MLX.id };@@ -287,6 +294,82 @@ describe('useVideoGenForm', () => {expect(payload.prompt).toBe('a fox watches the rain\n\nno music, no soundtrack');});+ // Substitutable prompt conditioner (#4081).+ describe('text encoder selection', () => {+ const renderWithH3 = async () => {+ const rendered = render({ models: [MLX, H3], status: { connected: true, defaultModel: MLX.id } });+ await waitFor(() => expect(rendered.result.current.modelId).toBe(MLX.id));+ act(() => rendered.result.current.handleModelChange(H3.id));+ await waitFor(() => expect(rendered.result.current.modelId).toBe(H3.id));+ return rendered;+ };++ // An empty list is what hides the picker; a model with substitutions+ // exposes them straight off the server-decorated entry.+ it('exposes only the selected model’s options', async () => {+ const { result } = render({ models: [MLX, H3], status: { connected: true, defaultModel: MLX.id } });+ await waitFor(() => expect(result.current.modelId).toBe(MLX.id));+ expect(result.current.textEncoderOptions).toEqual([]);+ act(() => result.current.handleModelChange(H3.id));+ await waitFor(() => expect(result.current.textEncoderOptions).toHaveLength(2));+ });++ // The stock choice must submit the same body a request that never knew+ // about this knob would — the server treats absence and 'stock' identically,+ // so sending the sentinel would only add noise to persisted job params.+ it('drops the stock choice from the payload', async () => {+ const { result } = await renderWithH3();+ expect(result.current.textEncoderId).toBe('stock');+ act(() => result.current.setPrompt('a fox'));+ expect(result.current.buildGeneratePayload().textEncoderId).toBeUndefined();+ });++ it('submits an explicitly chosen substitute', async () => {+ const { result } = await renderWithH3();+ act(() => {+ result.current.setPrompt('a fox');+ result.current.setTextEncoderId('heretic-bf16');+ });+ await waitFor(() => expect(result.current.textEncoderId).toBe('heretic-bf16'));+ expect(result.current.buildGeneratePayload().textEncoderId).toBe('heretic-bf16');+ });++ // Switching to a model that can't load the selection has to snap it back,+ // or the <select> sits on a value with no matching <option> and the submit+ // 400s with VIDEO_TEXT_ENCODER_UNSUPPORTED.+ it('resets to stock when the model changes to one without that option', async () => {+ const { result } = await renderWithH3();+ act(() => result.current.setTextEncoderId('heretic-bf16'));+ await waitFor(() => expect(result.current.textEncoderId).toBe('heretic-bf16'));++ act(() => result.current.handleModelChange(MLX.id));+ await waitFor(() => expect(result.current.textEncoderId).toBe('stock'));+ act(() => result.current.setPrompt('a fox'));+ expect(result.current.buildGeneratePayload().textEncoderId).toBeUndefined();+ });++ // History records the conditioner only for a non-stock render, so a remix+ // of a stock render must CLEAR a leftover selection rather than carry it+ // into a render the user asked to reproduce faithfully.+ it.each([+ ['restores a recorded substitute', { textEncoderId: 'heretic-bf16' }, 'heretic-bf16'],+ ['clears the selection when the record has none', {}, 'stock'],+ ])('%s on remix', async (_label, extra, expected) => {+ const { result } = await renderWithH3();+ act(() => result.current.setTextEncoderId('heretic-bf16'));+ await waitFor(() => expect(result.current.textEncoderId).toBe('heretic-bf16'));++ act(() => result.current.applyRemix({ modelId: H3.id, prompt: 'a fox', ...extra }));+ await waitFor(() => expect(result.current.textEncoderId).toBe(expected));+ });++ it('restores a resumed in-flight render’s conditioner', async () => {+ const { result } = await renderWithH3();+ act(() => result.current.applyResumedParams({ modelId: H3.id, prompt: 'a fox', textEncoderId: 'heretic-bf16' }));+ await waitFor(() => expect(result.current.textEncoderId).toBe('heretic-bf16'));+ });+ });+it('preserves H3 native 32px-grid geometry in the submitted payload', async () => {const { result } = render({models: [MLX, H3],diff --git a/client/src/lib/videoGenParams.js b/client/src/lib/videoGenParams.jsindex c3030d425f..3b1c2e18a8 100644--- a/client/src/lib/videoGenParams.js+++ b/client/src/lib/videoGenParams.js@@ -79,6 +79,26 @@ export const supportsVideoAudioControls = (model) => model?.supportsDisableAudio// Disable audio checkbox must stay hidden.export const supportsVideoAudioPromptControls = (model) => model?.supportsAudioPrompting !== false;+// Substitutable prompt conditioners (#4081). The OPTIONS themselves are not+// mirrored here — the server decorates each model entry with its own+// `textEncoderOptions` (label, description, size, advisory) in+// `videoGen/local.js#decorateVideoModel`, so the picker renders whatever this+// build's runner can actually key-map and a stale client can't offer one it+// can't. Only the "no override" sentinel is duplicated, and it must stay equal+// to `STOCK_TEXT_ENCODER_ID` in `server/lib/videoTextEncoders.js`: the submit+// builder drops the field when it holds this value, and the server treats an+// absent field and this id identically.+export const STOCK_TEXT_ENCODER_ID = 'stock';+export const textEncoderOptionsForModel = (model) => (+ Array.isArray(model?.textEncoderOptions) ? model.textEncoderOptions : []+);+// Snap a selection onto what the (possibly just-switched) model offers. A model+// with no substitutions answers with the stock sentinel rather than '', so the+// <select> is never left on a value with no matching <option>.+export const normalizeTextEncoderForModel = (id, model) => (+ textEncoderOptionsForModel(model).some((option) => option.id === id) ? id : STOCK_TEXT_ENCODER_ID+);+// Per-edge bounds for video: mirrors the videoGen route (64..2048). The base// grid is 64px, while a model may declare a finer resolutionStep (H3 uses 32).// Shared by the ResolutionField control and the submit-time clamp so adiff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 986ef55cf7..8c43814621 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -68,7 +68,8 @@ import MediaJobsQueue from '../components/media/MediaJobsQueue';import ModelSelect from '../components/ModelSelect';import { FormField } from '../components/ui/FormField';import ModelDownloadBadge, { deriveSizeEstimate } from '../components/media/ModelDownloadBadge';-import { useModelDownloadStatus, TEXT_ENCODER_DOWNLOAD_ID } from '../hooks/useModelDownloadStatus';+import { useModelDownloadStatus, TEXT_ENCODER_DOWNLOAD_ID, textEncoderDownloadId } from '../hooks/useModelDownloadStatus';+import TextEncoderPicker from '../components/videoGen/TextEncoderPicker';import { useMediaJobSse } from '../hooks/useMediaJobSse';import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';import { useMediaAnnotations } from '../hooks/useMediaAnnotations';@@ -154,6 +155,7 @@ export default function VideoGen() {contextFrames, setContextFrames,steps, setSteps, guidanceScale, setGuidanceScale, imageStrength, setImageStrength,seed, setSeed, handleRandomSeed, tiling, setTiling,+ textEncoderId, setTextEncoderId, textEncoderOptions,disableAudio, setDisableAudio, noMusic, setNoMusic,sourceImageFile, sourceImageUpload, sourceUploadUrl,pickSourceImage, uploadSourceImage, clearSourceImage,@@ -469,6 +471,17 @@ export default function VideoGen() {? { ...textEncoderInfo, downloading: true, progress: modelDownload.progress }: textEncoderInfo): null;+ // Substitutable prompt conditioner (#4081). A built-in option ships inside+ // the model's own weights, so only a substitute has a download of its own to+ // track — and only then can it gate Generate.+ const selectedTextEncoder = textEncoderOptions.find((option) => option.id === textEncoderId) || null;+ const textEncoderOptionNeedsWeights = !!selectedTextEncoder && !selectedTextEncoder.builtIn;+ const textEncoderOptionDownloadId = textEncoderOptionNeedsWeights+ ? textEncoderDownloadId(selectedTextEncoder.id)+ : null;+ const textEncoderOptionStatus = textEncoderOptionDownloadId+ ? modelDownload.getStatus(textEncoderOptionDownloadId)+ : null;const icWeightStatus = icSpec ? modelDownload.getStatus(icSpec.mode) : null;const modelWeightsBlocked = !isGrok&& (statusLoading || !modelId || !currentModel || modelDownload.loading@@ -477,10 +490,14 @@ export default function VideoGen() {&& (modelDownload.loading || textEncoderStatus === null || textEncoderStatus?.cached === false);const icWeightsBlocked = !isGrok && icModeActive&& (modelDownload.loading || icWeightStatus === null || icWeightStatus?.cached === false);- const weightsGateBlocked = modelWeightsBlocked || textEncoderWeightsBlocked || icWeightsBlocked;+ const textEncoderOptionBlocked = !isGrok && textEncoderOptionNeedsWeights+ && (modelDownload.loading || textEncoderOptionStatus === null || textEncoderOptionStatus?.cached === false);+ const weightsGateBlocked = modelWeightsBlocked || textEncoderWeightsBlocked+ || textEncoderOptionBlocked || icWeightsBlocked;const activeWeightErrorIds = [modelId,usesSharedTextEncoder ? TEXT_ENCODER_DOWNLOAD_ID : null,+ textEncoderOptionDownloadId,icModeActive ? icSpec?.mode : null,].filter(Boolean);const activeWeightError = activeWeightErrorIds.includes(modelDownload.lastError?.modelId)@@ -1050,6 +1067,20 @@ export default function VideoGen() {</button></div>)}+ {/* Prompt conditioner. Sits with the Model field rather than in+ the collapsed Advanced panel: a substitute is its own+ multi-GB pull and gates Generate, so its badge has to be+ visible at the moment it's picked. Renders nothing unless+ the model offers a real choice. */}+ <TextEncoderPicker+ options={textEncoderOptions}+ value={textEncoderId}+ onChange={setTextEncoderId}+ status={textEncoderOptionStatus}+ onDownload={(id) => modelDownload.start(textEncoderDownloadId(id))}+ onCancel={modelDownload.cancel}+ disabled={generating}+ />{usesSharedTextEncoder && textEncoderStatus && (textEncoderStatus.cached === false || textEncoderStatus.downloading) && (<div className="mt-1"><p className="text-[10px] text-gray-500">Text encoder ({textEncoderStatus.repo}) is also required:</p>@@ -1177,6 +1208,7 @@ export default function VideoGen() {: termsGateBlocked ? 'Confirm the selected model eligibility and license terms above before generating': modelWeightsBlocked ? 'Download the selected model weights before generating': textEncoderWeightsBlocked ? 'Download the shared text encoder before generating'+ : textEncoderOptionBlocked ? `Download the ${selectedTextEncoder?.label || 'selected'} text encoder before generating`: icWeightsBlocked ? `Download the ${icSpec?.label || 'IC-LoRA'} weight before generating`: extendModeBlocked ? 'Pick a prior render and wait for the last frame to extract before generating': a2vModeBlocked ? (currentModel?.runtime !== 'ltx2'diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex e0073f0069..d3d640356b 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -187,6 +187,14 @@ export const repairTextEncoder = ({ deep = false } = {}) => request('/video-gen/body: JSON.stringify({ deep }),silent: true,});+// Repair a substitutable prompt conditioner (#4081) — a single pinned file+// keyed by its registry id ('heretic-bf16', …). Distinct from repairTextEncoder+// above, which targets the SHARED install-wide LTX encoder repo.+export const repairTextEncoderOption = (id, { deep = false } = {}) => request(`/video-gen/text-encoders/${encodeURIComponent(id)}/repair`, {+ method: 'POST',+ 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.diff --git a/docs/README.md b/docs/README.mdindex d65336b0f0..df0385f78e 100644--- a/docs/README.md+++ b/docs/README.md@@ -37,7 +37,7 @@ Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system]Knowledge: [brain-system](./features/brain-system.md) · [messages-security](./features/messages-security.md)-Create: [writers-room](./features/writers-room.md) · [cybercity-v2](./features/cybercity-v2.md) · [sprite-export-contract](./features/sprite-export-contract.md)+Create: [writers-room](./features/writers-room.md) · [cybercity-v2](./features/cybercity-v2.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md)Comms & voice: [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([pre-build audit](./research/2026-03-31-openclaw-operator-chat-audit.md)) · [stacker-news](./features/stacker-news.md) · [voice](./features/voice.md)diff --git a/docs/features/video-text-encoders.md b/docs/features/video-text-encoders.mdnew file mode 100644index 0000000000..8c3ca41322--- /dev/null+++ b/docs/features/video-text-encoders.md@@ -0,0 +1,140 @@+# Swappable video text encoders++Video Gen lets a MiniMax H3 render choose which **prompt conditioner** (text+encoder) reads the prompt. The picker sits under the Model field and defaults to+the conditioner that ships with the model, so nothing changes unless you pick+something else.++## Why H3's conditioner is swappable at all++H3 does not use its Qwen3-VL-32B conditioner as a language model. The DiT reads+the **unnormalized hidden state after language layer 49** and feeds it straight+into `condition_proj`. Layers 50–63, the final norm and `lm_head` are never+evaluated — the MLX port doesn't even load them.++That makes the conditioner unusually easy to substitute: any checkpoint carrying+the same Qwen3-VL embedding, language layers 0–49 and vision tower produces a+conditioning signal of the same shape. Swapping it changes **how the model reads+a prompt** — vocabulary, phrasing sensitivity, refusal behavior — without+touching the diffusion weights, the VAEs or the sampler.++Everything else about the render is unchanged: same DiT, same 8-point sigma+schedule, same joint video+audio output.++## What ships++| Option | What it is | Extra download |+|--------|-----------|----------------|+| **Stock** | The conditioner inside `MiniMaxAI/MiniMax-H3`'s `FL2VA/text_encoder/` | none — already downloaded with the model |+| **Ultra-Heretic uncensored** | `ethanfel/Qwen3-VL-32B-Ultra-Heretic-H3-ComfyUI-INT8-ConvRot`, bf16 variant — Qwen3-VL-32B-Instruct abliterated with Heretic v1.2.0 (attention-targeted), repackaged for H3 | ~48 GB, one pinned file |++The Ultra-Heretic option has had its refusal behavior removed. It follows+prompts the stock conditioner declines; the picker says so inline.++Only the **bf16** file is usable here. The repo's INT8 ConvRot and NVFP4/AWQ+variants use ComfyUI's own quantization (learned row-wise rotation matrices,+group size 256) that the MLX loader cannot dequantize, and the `50_63`+generation tails belong to ComfyUI's H3 Prompt Enhancer node — a feature PortOS+does not implement. That's why the download is scoped to one file rather than a+repo snapshot: the full repo is ~130 GB for ~48 GB of usable weights.++## Using it++1. Pick **MiniMax H3** on `/media/video`. A **Text encoder** select appears under+ the model's download badge.+2. Choose a substitute. If it isn't downloaded, a Download button appears and+ **Generate stays disabled** until it's resident — the same gate the model+ weights and IC-LoRA weights use.+3. Render. The chosen conditioner is recorded in history, so **Remix** reproduces+ the render faithfully; a stock render records nothing and remixes as stock.++Switching to a model whose runtime can't load your selection snaps the picker+back to Stock rather than leaving it on a value the server would reject.++## How the swap works++The pinned MLX runtime (`PipeNetwork/minimax-h3-mlx`) is verified clean before+every render — PortOS never edits it. Two adapters in+`scripts/generate_minimax_h3.py` bridge the gap instead:++**1. A composed checkpoint root.** `build_encoder_shim()` creates a directory of+symlinks under `~/.portos/minimax-h3-encoder-shims/<id>/` — everything from the+upstream `FL2VA/` snapshot (`model_index.json`, both VAEs, the tokenizer, the+processor) linked straight through, with only `text_encoder/` replaced by the+substitute plus the stock `config.json`. The runtime's own `from_pretrained()`+then loads it with no argument it doesn't already take. The shim lives outside+the pinned checkout deliberately: anything written inside would read as untracked+in the pin verification.++The substitute ships weights only. Its config, tokenizer and processor come from+upstream — correct, because abliteration changes weights, not the vocabulary or+the vision geometry.++**2. A key-prefix rewrite.** A ComfyUI-packaged conditioner flattens the+transformers namespace (`model.layers.N.…` / `visual.…`) while the port's loader+matches the Hugging Face one (`model.language_model.layers.N.…` /+`model.visual.…`). `install_key_prefix_map()` wraps the loader's `_wanted` method+so keys are translated **before** it sees them, then delegates every real+decision — which layers are past the conditioning depth, what `lm_head` maps to —+back to the pinned implementation. Rules are applied longest-source-first so a+broad rule can't shadow a narrower one. If a future pin drops `_wanted`, the+swap fails with a message naming the cause rather than silently mis-loading.++**3. A synthesized final norm.** The Ultra-Heretic checkpoint omits+`norm.weight` (its metadata records `minimax_h3_final_norm: "false"`) — correct,+since H3 reads the state *before* the norm. But the port instantiates the whole+module tree and refuses to load with any parameter missing. The runner writes a+ones-filled companion shard, which the loader's `*.safetensors` glob picks up+alongside the substitute. It is never applied; ones is the identity if a future+revision ever does apply it. The key is written in the *substitute's* namespace+(`model.norm.weight`) so the prefix map rewrites it like any other key.++Verified against the real pinned runtime: the 902 tensors in the bf16 file plus+the synthesized norm map onto exactly the 903 parameters the loader builds — 552+language, 351 vision, zero missing, zero extra, zero skipped.++## Adding another conditioner++Add an entry to `TEXT_ENCODERS_BY_RUNTIME` in+[`server/lib/videoTextEncoders.js`](../../server/lib/videoTextEncoders.js).+Nothing else needs to change — the picker, the download/repair lane, the+integrity scan and the render path all read from that table.++```js+{+ id: 'my-encoder', // also the shim directory name+ label: '…', // shown in the picker+ description: '…',+ repo: 'org/repo',+ revision: '<40-char sha>', // pinned, never a branch+ file: 'weights.safetensors', // one file; never a repo snapshot+ keyPrefixMap: { 'model.': 'model.language_model.', 'visual.': 'model.visual.' },+ finalNormKey: 'model.norm.weight', // omit if the checkpoint ships its own norm+ sizeBytes: 12345, // exact published size — the UI formats this+ disclosure: { modelCardUrl, weightsLicense, baseModel, estimatedDownloadGb, reviewedAt },+ advisory: '…', // required when behavior differs from stock+}+```++These live in code rather than `data/media-models.json` on purpose: a stale+registry file must never be able to name a checkpoint this build's runner has no+key map for.++To confirm a candidate is really a drop-in before downloading tens of GB, read+its safetensors header with an HTTP range request, apply the prefix map, and diff+the result against the parameter set the loader builds. That's how the shipped+entry was validated.++## Cost note++A substitute is an *additional* download — the stock conditioner's shards stay+resident so you can switch back instantly. Resident memory during a render is+unchanged (the same 50 layers + vision tower are loaded either way); only disk+grows.++## Related++- `server/lib/videoTextEncoders.js` — the registry, and the one place a new entry goes+- `scripts/generate_minimax_h3.py` — the shim builder and key remap+- `server/services/videoGen/local.js` — cache resolution and argv+- `client/src/components/videoGen/TextEncoderPicker.jsx` — the controldiff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.pyindex 6c6a922fba..65b64e0691 100644--- a/scripts/generate_minimax_h3.py+++ b/scripts/generate_minimax_h3.py@@ -59,6 +59,17 @@ def parse_args() -> argparse.Namespace:help="user LoRA safetensors applied at runtime (repeatable)")parser.add_argument("--lora-scale", action="append", type=float, default=[],help="strength for each --lora, in the same order")+ parser.add_argument("--text-encoder-id",+ help="id of the substituted prompt conditioner (shim directory name)")+ parser.add_argument("--text-encoder-file",+ help="already-cached safetensors to condition with instead of the checkpoint's own")+ parser.add_argument("--text-encoder-shim-root",+ help="directory the composed checkpoint root is built under")+ parser.add_argument("--text-encoder-key-prefix", action="append", default=[],+ metavar="FROM=TO",+ help="rewrite this checkpoint-key prefix before the loader matches it (repeatable)")+ parser.add_argument("--text-encoder-final-norm-key",+ help="synthesize a ones-filled final norm under this key (for a conditioner published without one)")parser.add_argument("--output", required=True)return parser.parse_args()@@ -120,6 +131,121 @@ def resolve_transformer_snapshot(repo: str, revision: str) -> Path:return root+def parse_key_prefixes(pairs: list[str]) -> list[tuple[str, str]]:+ """Parse `--text-encoder-key-prefix FROM=TO` into longest-prefix-first rules.++ Sorting by descending source length means a more specific rule can never be+ shadowed by a shorter one that also matches, so PortOS can declare the pairs+ in whatever order reads best on its side.+ """+ rules: list[tuple[str, str]] = []+ for pair in pairs:+ source, sep, target = pair.partition("=")+ if not sep or not source:+ raise SystemExit(f"--text-encoder-key-prefix must be FROM=TO; got {pair!r}.")+ rules.append((source, target))+ return sorted(rules, key=lambda rule: -len(rule[0]))+++def install_key_prefix_map(rules: list[tuple[str, str]]) -> None:+ """Rewrite checkpoint-key prefixes before the pinned loader matches them.++ A conditioner repackaged for ComfyUI flattens the transformers namespace+ (`model.layers.N.…` / `visual.…`) while the port's `_wanted` matches the+ Hugging Face one (`model.language_model.layers.N.…` / `model.visual.…`).+ Wrapping that single method translates the namespace for the duration of the+ load and delegates every real decision — which layers are past the+ conditioning depth, what `lm_head` maps to — back to the pinned+ implementation, so this adapter cannot drift from the port's own contract.++ Deliberately NOT a source edit: the checkout is verified clean above, and it+ must stay that way.+ """+ from minimax_h3_mlx.text_encoder import MiniMaxH3TextEncoder++ original = getattr(MiniMaxH3TextEncoder, "_wanted", None)+ if original is None:+ raise RuntimeError(+ "The pinned MiniMax H3 runtime no longer exposes MiniMaxH3TextEncoder._wanted, "+ "so a substituted text encoder cannot be key-mapped onto it. Render with the "+ "stock text encoder, or update PortOS for the new pin."+ )++ def _wanted(self, key: str):+ for source, target in rules:+ if key.startswith(source):+ key = target + key[len(source):]+ break+ return original(self, key)++ MiniMaxH3TextEncoder._wanted = _wanted+++def write_final_norm_shard(path: Path, key: str, hidden_size: int) -> None:+ """Write the one tensor a norm-less conditioner is missing.++ H3 conditions on the hidden state *before* the final norm, so a checkpoint+ published for H3 correctly omits it — but the port instantiates the whole+ module tree and refuses to load with any parameter absent. The value is+ therefore never read; ones is the identity, which keeps the file honest if a+ future revision ever does apply it.++ Written under the SUBSTITUTE's own key namespace so the prefix map above+ rewrites it exactly like every other key in the checkpoint.+ """+ import mlx.core as mx++ mx.save_safetensors(str(path), {key: mx.ones((hidden_size,), dtype=mx.bfloat16)})+++def build_encoder_shim(+ checkpoint_dir: Path,+ shim_root: Path,+ encoder_id: str,+ encoder_file: Path,+ final_norm_key: str | None,+) -> Path:+ """Compose a checkpoint root whose `text_encoder/` is the substitute.++ Everything else — `model_index.json`, both VAEs, the tokenizer and the+ processor — is symlinked straight through from the upstream snapshot, so the+ pinned `from_pretrained` loads this directory with no argument it doesn't+ already take and no knowledge that anything was swapped. The substitute+ ships weights only; its tokenizer/processor/config come from upstream, which+ is correct because abliteration changes weights, not the vocabulary or the+ vision geometry.++ Rebuilt from scratch on every render: the links are free, and a stale shim+ pointing at a blob the user has since re-downloaded would otherwise load+ silently-wrong weights.+ """+ if not encoder_file.is_file():+ raise RuntimeError(f"Substituted text encoder is missing: {encoder_file}")++ root = shim_root / encoder_id+ shutil.rmtree(root, ignore_errors=True)+ (root / "text_encoder").mkdir(parents=True, exist_ok=True)++ for entry in checkpoint_dir.iterdir():+ if entry.name == "text_encoder":+ continue+ (root / entry.name).symlink_to(entry)++ stock_config = checkpoint_dir / "text_encoder" / "config.json"+ if not stock_config.is_file():+ raise RuntimeError(f"Upstream text-encoder config is missing: {stock_config}")+ (root / "text_encoder" / "config.json").symlink_to(stock_config)+ (root / "text_encoder" / encoder_file.name).symlink_to(encoder_file)++ if final_norm_key:+ hidden_size = json.loads(stock_config.read_text(encoding="utf-8"))["text_config"]["hidden_size"]+ # `_load_weights` globs *.safetensors in this directory, so a companion+ # shard is picked up alongside the substitute with no loader change.+ write_final_norm_shard(root / "text_encoder" / "_portos_final_norm.safetensors", final_norm_key, hidden_size)++ return root++def require_ffmpeg() -> str:"""Fail before loading ~83 GB of weights when muxing cannot succeed."""path = shutil.which("ffmpeg")@@ -217,6 +343,19 @@ def validate_args(args: argparse.Namespace) -> None:for path in args.lora:if not Path(path).is_file():raise SystemExit(f"LoRA file is missing: {path}")+ # The substitution is all-or-nothing: without the id there is nowhere to+ # build the shim, and without the shim root there is nowhere to put it.+ # Accepting a partial set would silently fall back to the stock conditioner+ # and hand the user a render they'd have no way to tell apart.+ encoder_flags = (args.text_encoder_id, args.text_encoder_file, args.text_encoder_shim_root)+ if any(encoder_flags) and not all(encoder_flags):+ raise SystemExit(+ "--text-encoder-id, --text-encoder-file and --text-encoder-shim-root must be given together."+ )+ if args.text_encoder_id and not re.fullmatch(r"[A-Za-z0-9._-]+", args.text_encoder_id):+ raise SystemExit(f"--text-encoder-id must be a bare directory-safe name; got {args.text_encoder_id!r}.")+ if not args.text_encoder_file and (args.text_encoder_key_prefix or args.text_encoder_final_norm_key):+ raise SystemExit("--text-encoder-key-prefix / --text-encoder-final-norm-key need --text-encoder-file.")def load_keyframes(paths: list[str]) -> list:@@ -289,6 +428,27 @@ def main() -> int:from minimax_h3_mlx.media import save_mp4from minimax_h3_mlx.pipeline import MiniMaxH3Pipeline+ # Substituted prompt conditioner. H3 reads the unnormalized hidden state+ # after Qwen3-VL language layer 49, so any checkpoint carrying the same+ # embedding + layers 0-49 + vision tower conditions the DiT identically in+ # shape while reading the prompt differently. The swap is expressed as a+ # composed checkpoint root plus a key-prefix rewrite, both of which leave the+ # pinned runtime source untouched.+ if args.text_encoder_file:+ # Bare phase marker plus a separate STATUS line: the SSE parser reads+ # field 2 of a STAGE frame as `step`/`heartbeat`, so the encoder id+ # cannot ride along in the marker itself.+ print("STAGE:swap-text-encoder", file=sys.stderr, flush=True)+ print(f"STATUS:Conditioning with the {args.text_encoder_id} text encoder", file=sys.stderr, flush=True)+ install_key_prefix_map(parse_key_prefixes(args.text_encoder_key_prefix))+ checkpoint_dir = build_encoder_shim(+ checkpoint_dir,+ Path(args.text_encoder_shim_root),+ args.text_encoder_id,+ Path(args.text_encoder_file),+ args.text_encoder_final_norm_key,+ )+print("STAGE:load-pipeline", file=sys.stderr, flush=True)with heartbeat("minimax-h3-load"):pipe = MiniMaxH3Pipeline.from_pretrained(diff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.jsindex b7e93a4cd2..297756e8bf 100644--- a/scripts/generate_minimax_h3.test.js+++ b/scripts/generate_minimax_h3.test.js@@ -10,6 +10,19 @@ const runPython = (source) => execFileSync(pyBin, ['-c', source, script], {encoding: 'utf8',});+// The final-norm synthesis is the one helper here that actually needs mlx (it+// writes a real safetensors). CI's bare python3 is Linux and has no mlx wheel,+// so probe once and skip just that case rather than making the whole file+// macOS-only — every other helper is import-free by design.+const hasMlx = (() => {+ try {+ execFileSync(pyBin, ['-c', 'import mlx.core'], { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+})();+const importRunner = ['import importlib.util, sys','from pathlib import Path',@@ -19,6 +32,32 @@ const importRunner = ['spec.loader.exec_module(runner)',].join('\n');+// validate_args reads the namespace argparse produces, so every field it touches+// has to be present here — a hand-built literal per test drifts the moment a flag+// is added (and fails as an AttributeError rather than an assertion). One builder+// carries the parser's own defaults; each test overrides only what it exercises.+const VALIDATE_ARGS_DEFAULTS = {+ fps: 24,+ width: 512,+ height: 320,+ num_frames: 124,+ steps: 8,+ image: [],+ anchor: [],+ lora: [],+ lora_scale: [],+ text_encoder_id: null,+ text_encoder_file: null,+ text_encoder_shim_root: null,+ text_encoder_key_prefix: [],+ text_encoder_final_norm_key: null,+};+const argsExpr = (overrides = {}) => {+ const fields = Object.entries({ ...VALIDATE_ARGS_DEFAULTS, ...overrides })+ .map(([key, value]) => `${key}=${value === null ? 'None' : JSON.stringify(value)}`);+ return `args = SimpleNamespace(${fields.join(', ')})`;+};+describe('generate_minimax_h3.py', () => {it('keeps the lexical HF snapshot root when cache entries are blob symlinks', () => {const output = runPython(`${importRunner}\n${[@@ -74,7 +113,7 @@ describe('generate_minimax_h3.py', () => {it('rejects zero dimensions at the execution boundary', () => {const output = runPython(`${importRunner}\n${['from types import SimpleNamespace',- 'args = SimpleNamespace(fps=24, width=0, height=320, num_frames=124, steps=8, lora=[], lora_scale=[], image=[], anchor=[])',+ argsExpr({ width: 0 }),'try:',' runner.validate_args(args)','except SystemExit as exc:',@@ -88,7 +127,7 @@ describe('generate_minimax_h3.py', () => {it('accepts the upstream 4-second aligned frame count and native 32px canvas grid', () => {const output = runPython(`${importRunner}\n${['from types import SimpleNamespace',- 'args = SimpleNamespace(fps=24, width=1536, height=672, num_frames=107, steps=8, lora=[], lora_scale=[], image=[], anchor=[])',+ argsExpr({ width: 1536, height: 672, num_frames: 107 }),'runner.validate_args(args)','print("ok")',].join('\n')}`);@@ -103,7 +142,7 @@ describe('generate_minimax_h3.py', () => {])('rejects mismatched keyframe anchors (%j / %j)', (images, anchors, pattern) => {const output = runPython(`${importRunner}\n${['from types import SimpleNamespace',- `args = SimpleNamespace(fps=24, width=512, height=320, num_frames=124, steps=8, lora=[], lora_scale=[], image=${JSON.stringify(images)}, anchor=${JSON.stringify(anchors)})`,+ argsExpr({ image: images, anchor: anchors }),'try:',' runner.validate_args(args)','except SystemExit as exc:',@@ -117,7 +156,7 @@ describe('generate_minimax_h3.py', () => {it('accepts a paired first/last keyframe request', () => {const output = runPython(`${importRunner}\n${['from types import SimpleNamespace',- 'args = SimpleNamespace(fps=24, width=512, height=320, num_frames=124, steps=8, lora=[], lora_scale=[], image=["a.png", "b.png"], anchor=["first", "last"])',+ argsExpr({ image: ['a.png', 'b.png'], anchor: ['first', 'last'] }),'runner.validate_args(args)','print("ok")',].join('\n')}`);@@ -133,7 +172,7 @@ describe('generate_minimax_h3.py', () => {])('rejects mismatched or missing LoRA arguments (%j / %j)', (loras, scales, pattern) => {const output = runPython(`${importRunner}\n${['from types import SimpleNamespace',- `args = SimpleNamespace(fps=24, width=512, height=320, num_frames=124, steps=8, image=[], anchor=[], lora=${JSON.stringify(loras)}, lora_scale=${JSON.stringify(scales)})`,+ argsExpr({ lora: loras, lora_scale: scales }),'try:',' runner.validate_args(args)','except SystemExit as exc:',@@ -187,6 +226,245 @@ describe('generate_minimax_h3.py', () => {expect(output).toMatch(/Conditioning image is missing: \/nonexistent\/last\.png/);});+ // ---- substituted prompt conditioner (#4081) --------------------------------++ // A partial flag set would silently fall back to the stock conditioner and+ // hand back a render the user has no way to tell apart from the one they asked+ // for, so the boundary rejects it instead of choosing for them.+ it.each([+ [{ text_encoder_id: 'heretic-bf16' }, /must be given together/i],+ [{ text_encoder_file: '/tmp/e.safetensors' }, /must be given together/i],+ [{ text_encoder_id: 'heretic-bf16', text_encoder_file: '/tmp/e.safetensors' }, /must be given together/i],+ // A traversal-shaped id would put the shim tree outside the root PortOS+ // chose (and `rmtree` it from there).+ [+ {+ text_encoder_id: '../escape',+ text_encoder_file: '/tmp/e.safetensors',+ text_encoder_shim_root: '/tmp/shims',+ },+ /bare directory-safe name/i,+ ],+ // Loader mechanics with nothing to apply them to: accepting these would+ // rewrite the STOCK conditioner's keys and fail deep inside the load.+ [{ text_encoder_key_prefix: ['model.=model.language_model.'] }, /need --text-encoder-file/i],+ [{ text_encoder_final_norm_key: 'model.norm.weight' }, /need --text-encoder-file/i],+ ])('rejects an incoherent text-encoder argument set (%j)', (overrides, pattern) => {+ const output = runPython(`${importRunner}\n${[+ 'from types import SimpleNamespace',+ argsExpr(overrides),+ 'try:',+ ' runner.validate_args(args)',+ 'except SystemExit as exc:',+ ' print(str(exc))',+ 'else:',+ ' raise SystemExit("incoherent text-encoder args were accepted")',+ ].join('\n')}`);+ expect(output).toMatch(pattern);+ });++ it('accepts a complete text-encoder argument set', () => {+ const output = runPython(`${importRunner}\n${[+ 'from types import SimpleNamespace',+ argsExpr({+ text_encoder_id: 'heretic-bf16',+ text_encoder_file: '/tmp/e.safetensors',+ text_encoder_shim_root: '/tmp/shims',+ text_encoder_key_prefix: ['model.=model.language_model.', 'visual.=model.visual.'],+ text_encoder_final_norm_key: 'model.norm.weight',+ }),+ 'runner.validate_args(args)',+ 'print("ok")',+ ].join('\n')}`);+ expect(output.trim()).toBe('ok');+ });++ // Sorted longest-source-first so a broader rule can never shadow a narrower+ // one that also matches, whatever order PortOS declares them in.+ it('parses key-prefix rules longest-source-first', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json',+ 'print(json.dumps(runner.parse_key_prefixes(["model.=A.", "model.layers.=B.", "visual.=C."])))',+ ].join('\n')}`);+ expect(JSON.parse(output)).toEqual([+ ['model.layers.', 'B.'],+ ['visual.', 'C.'],+ ['model.', 'A.'],+ ]);+ });++ it.each(['model.', 'model.=', '=model.'])('rejects a malformed key-prefix rule (%j)', (rule) => {+ const output = runPython(`${importRunner}\n${[+ 'try:',+ ` print(runner.parse_key_prefixes(${JSON.stringify([rule])}))`,+ 'except SystemExit as exc:',+ ' print("REJECTED", str(exc))',+ ].join('\n')}`);+ // `model.=` is a legal rule (strip the prefix), so only the two without a+ // usable source are rejected — assert the split rather than blanket-failing.+ if (rule === 'model.=') expect(output).toMatch(/\[\('model\.', ''\)\]/);+ else expect(output).toMatch(/REJECTED/);+ });++ // The remap has to translate the SUBSTITUTE's namespace onto the one the+ // pinned loader matches, then delegate every real decision (which layers are+ // past the conditioning depth, what lm_head maps to) back to it — so the+ // adapter can't drift from the port's own contract.+ it('remaps checkpoint keys through the pinned loader rather than replacing it', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, sys, types',+ // Stand in for the pinned module: `_wanted` records what it was handed.+ 'seen = []',+ 'class FakeEncoder:',+ ' def _wanted(self, key):',+ ' seen.append(key)',+ ' return ("language", key) if key.startswith("model.language_model.") else None',+ 'module = types.ModuleType("minimax_h3_mlx.text_encoder")',+ 'module.MiniMaxH3TextEncoder = FakeEncoder',+ 'package = types.ModuleType("minimax_h3_mlx")',+ 'sys.modules["minimax_h3_mlx"] = package',+ 'sys.modules["minimax_h3_mlx.text_encoder"] = module',+ 'runner.install_key_prefix_map(runner.parse_key_prefixes(["model.=model.language_model.", "visual.=model.visual."]))',+ 'encoder = FakeEncoder()',+ 'results = [encoder._wanted(k) for k in ["model.layers.0.mlp.up_proj.weight", "visual.blocks.0.attn.qkv.weight", "unrelated.weight"]]',+ 'print(json.dumps({"seen": seen, "results": results}))',+ ].join('\n')}`);+ const { seen, results } = JSON.parse(output);+ expect(seen).toEqual([+ 'model.language_model.layers.0.mlp.up_proj.weight',+ 'model.visual.blocks.0.attn.qkv.weight',+ 'unrelated.weight',+ ]);+ // The delegate's verdict is returned untouched — including its `None` for a+ // key it doesn't want, which is what keeps unmapped tensors skipped.+ expect(results).toEqual([+ ['language', 'model.language_model.layers.0.mlp.up_proj.weight'],+ null,+ null,+ ]);+ });++ // A pin whose loader no longer exposes `_wanted` must say so, not swap in a+ // conditioner whose keys nothing will map.+ it('refuses to swap a conditioner onto a pin with no _wanted hook', () => {+ const output = runPython(`${importRunner}\n${[+ 'import sys, types',+ 'class Bare: pass',+ 'module = types.ModuleType("minimax_h3_mlx.text_encoder")',+ 'module.MiniMaxH3TextEncoder = Bare',+ 'sys.modules["minimax_h3_mlx"] = types.ModuleType("minimax_h3_mlx")',+ 'sys.modules["minimax_h3_mlx.text_encoder"] = module',+ 'try:',+ ' runner.install_key_prefix_map([("model.", "model.language_model.")])',+ 'except RuntimeError as exc:',+ ' print(str(exc))',+ 'else:',+ ' raise SystemExit("a pin with no _wanted hook was accepted")',+ ].join('\n')}`);+ expect(output).toMatch(/no longer exposes MiniMaxH3TextEncoder\._wanted/);+ });++ // The shim is what lets the PINNED `from_pretrained` load a swapped+ // conditioner unmodified: everything but `text_encoder/` is linked straight+ // through, and the tokenizer/processor the encoder reads from its parent+ // directory have to come along or the load fails after the weights are read.+ it('composes a checkpoint root with only text_encoder swapped', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, tempfile',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp)',+ ' checkpoint = root / "FL2VA"',+ ' for name in ("video_vae", "audio_vae", "tokenizer", "processor", "text_encoder"):',+ ' (checkpoint / name).mkdir(parents=True)',+ ' (checkpoint / "model_index.json").write_text("{}")',+ ' (checkpoint / "text_encoder" / "config.json").write_text(json.dumps({"text_config": {"hidden_size": 8}}))',+ ' (checkpoint / "text_encoder" / "model-00001-of-00002.safetensors").write_text("stock")',+ ' substitute = root / "substitute.safetensors"',+ ' substitute.write_text("swapped")',+ ' shim = runner.build_encoder_shim(checkpoint, root / "shims", "heretic-bf16", substitute, None)',+ ' print(json.dumps({',+ ' "name": shim.name,',+ ' "root": sorted(p.name for p in shim.iterdir()),',+ ' "encoder": sorted(p.name for p in (shim / "text_encoder").iterdir()),',+ ' "tokenizer_links": (shim / "tokenizer").resolve() == (checkpoint / "tokenizer").resolve(),',+ ' }))',+ ].join('\n')}`);+ const result = JSON.parse(output);+ expect(result.name).toBe('heretic-bf16');+ expect(result.root).toEqual(['audio_vae', 'model_index.json', 'processor', 'text_encoder', 'tokenizer', 'video_vae']);+ // The stock shards are NOT linked in — the loader globs *.safetensors, so+ // leaving them would load both conditioners' weights over each other.+ expect(result.encoder).toEqual(['config.json', 'substitute.safetensors']);+ // The encoder resolves its tokenizer/processor from `_model_dir.parent`.+ expect(result.tokenizer_links).toBe(true);+ });++ // H3 reads the hidden state BEFORE the final norm, so a conditioner published+ // for it correctly omits that tensor — but the pinned loader builds the whole+ // module tree and refuses to load with any parameter missing.+ it.skipIf(!hasMlx)('synthesizes the missing final norm in the substitute key namespace', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, tempfile',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp)',+ ' checkpoint = root / "FL2VA"',+ ' (checkpoint / "text_encoder").mkdir(parents=True)',+ ' (checkpoint / "text_encoder" / "config.json").write_text(json.dumps({"text_config": {"hidden_size": 8}}))',+ ' substitute = root / "substitute.safetensors"',+ ' substitute.write_text("swapped")',+ ' shim = runner.build_encoder_shim(checkpoint, root / "shims", "heretic-bf16", substitute, "model.norm.weight")',+ ' import mlx.core as mx',+ ' loaded = mx.load(str(shim / "text_encoder" / "_portos_final_norm.safetensors"))',+ ' key = next(iter(loaded))',+ ' print(json.dumps({"key": key, "shape": list(loaded[key].shape), "values": loaded[key].tolist()}))',+ ].join('\n')}`);+ const result = JSON.parse(output);+ // Written under the SUBSTITUTE's namespace so the prefix map rewrites it+ // like every other key — writing the post-map name would leave it unmapped+ // and the parameter still missing.+ expect(result.key).toBe('model.norm.weight');+ expect(result.shape).toEqual([8]);+ expect(result.values).toEqual(Array(8).fill(1));+ });++ it('rebuilds the shim from scratch so a stale link cannot survive', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, tempfile',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp)',+ ' checkpoint = root / "FL2VA"',+ ' (checkpoint / "text_encoder").mkdir(parents=True)',+ ' (checkpoint / "text_encoder" / "config.json").write_text(json.dumps({"text_config": {"hidden_size": 8}}))',+ ' stale = root / "shims" / "heretic-bf16" / "text_encoder"',+ ' stale.mkdir(parents=True)',+ ' (stale / "old.safetensors").write_text("stale")',+ ' substitute = root / "substitute.safetensors"',+ ' substitute.write_text("swapped")',+ ' shim = runner.build_encoder_shim(checkpoint, root / "shims", "heretic-bf16", substitute, None)',+ ' print(json.dumps(sorted(p.name for p in (shim / "text_encoder").iterdir())))',+ ].join('\n')}`);+ expect(JSON.parse(output)).toEqual(['config.json', 'substitute.safetensors']);+ });++ it('fails a missing substitute before anything is composed', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, tempfile',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp)',+ ' checkpoint = root / "FL2VA"',+ ' (checkpoint / "text_encoder").mkdir(parents=True)',+ ' try:',+ ' runner.build_encoder_shim(checkpoint, root / "shims", "heretic-bf16", root / "absent.safetensors", None)',+ ' except RuntimeError as exc:',+ ' print(json.dumps({"error": str(exc), "built": (root / "shims").exists()}))',+ ' else:',+ ' raise SystemExit("a missing substitute was accepted")',+ ].join('\n')}`);+ const result = JSON.parse(output);+ expect(result.error).toMatch(/Substituted text encoder is missing/);+ expect(result.built).toBe(false);+ });+it('emits the video_path JSON completion contract on stdout', () => {const output = runPython(`${importRunner}\nrunner.emit_result(Path("/tmp/example.mp4"))`);expect(JSON.parse(output)).toEqual({ video_path: '/tmp/example.mp4' });diff --git a/server/lib/README.md b/server/lib/README.mdindex 7515b0f7e3..cec5912fe7 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -117,6 +117,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `videoDisclosure.js` | Video Gen provenance/licensing + backend policy-scope facts (#3674). `VIDEO_MODEL_DISCLOSURES` maps each shipped video model id to `{ shippedRepo, disclosure }` (model card URL, weights license, runtime license, pinned-snapshot download size in decimal GB, review date) — every value checked against a primary upstream source, and any fact that could not be established is OMITTED so the UI renders "Unknown" instead of guessing. `applyVideoDisclosures(list)` is the load-time backfill (twin of migration 237) with the same preservation guards: an existing `disclosure` key wins, a custom id is skipped, and a `repo` pointed at a fork keeps Unknown. `VIDEO_BACKEND_DISCLOSURES` / `videoBackendDisclosure(id)` state where inference runs (`execution: local or hosted`) and whose policy applies — execution facts only, never a restrictiveness ranking. || `videoFinishProfiles.js` | Draft → delivery ("Finish") relationships between video models (#3696). `VIDEO_FINISH_PROFILES` declares each fast draft entry id → `{ shippedRepo, finishModelId }`, only for pairs that share a runtime, base repo and supported modes (the same weights at a different step budget), so re-rendering the draft's seed reproduces its composition instead of re-rolling it. `applyVideoFinishProfiles(list)` is the load-time backfill (twin of migration 238) with the usual preservation guards (existing key wins, custom id skipped, forked `repo` skipped); `validateFinishProfileGraph(list)` returns the graph problems (missing / self-referencing / chained target, runtime / repo / supportedModes mismatch) and `sanitizeFinishProfiles(list)` warns + strips them at load so a typo can never surface a Finish button targeting nothing. `finishTargetForModel(model, availableModels)` resolves the delivery entry scoped to what this install can run. || `videoModeProfiles.js` | The shipped `supportedModes` fact per video runtime (#3737), so "which modes does this model support?" has one answer on the registry entry instead of 25+ `runtime === '…'` comparisons. `VIDEO_RUNTIME_MODES` maps each runtime to the base semantic modes its helper's argv can actually render (`mlx_video`/`ltx2` text+image+fflf+extend, `wan22` text+image, `minimax_h3` text+image+fflf — also the mode ceiling in `videoGen/modeContract.js` — `hunyuan` text only, replacing the legacy unread `mode: 't2v'` field); `VIDEO_BASE_MODES` is the fallback for an unknown (user-added or peer-synced) runtime, deliberately the full base set so a custom model doesn't vanish from every picker. `resolveVideoSupportedModes(entry)` (declared non-empty list always wins) and `applyVideoSupportedModes(list)` — the read-time decoration `mediaModels.js#getVideoModels` applies, so the derived list never lands in `data/media-models.json` where it would read back as a *declared* list no later correction could reach. a2v and the IC-LoRA remix ids are NOT enumerated here: they're ltx2 pipeline capabilities, gated by runtime (`A2V_REQUIRES_LTX2` / `IC_LORA_REQUIRES_LTX2`). |+| `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision/file, in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns them stock-first (empty when the runtime has no substitutions, so the picker is absent rather than single-entry), `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED`, and `downloadableVideoTextEncoders()` / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. || `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`) plus reasoning-effort helpers for the claude/codex/agy CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `hasEffortFlag`, and `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`) plus codex startup-arg helpers (`CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal). || `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. || `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 037da6e734..506073dd69 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -121,6 +121,7 @@ export * from './videoContinuity.js';export * from './videoDisclosure.js';export * from './videoFinishProfiles.js';export * from './videoModeProfiles.js';+export * from './videoTextEncoders.js';export * from './promptPartials.js';export * from './promptRunner.js';export * from './promptSystemStages.js';diff --git a/server/lib/videoTextEncoders.js b/server/lib/videoTextEncoders.jsnew file mode 100644index 0000000000..7ebd7cd714--- /dev/null+++ b/server/lib/videoTextEncoders.js@@ -0,0 +1,184 @@+/**+ * Swappable text-encoder (prompt conditioner) registry for local video runtimes.+ *+ * MiniMax H3 does not use its Qwen3-VL-32B conditioner as a language model: the+ * DiT reads the **unnormalized** hidden state after language layer 49 and feeds+ * it straight into `condition_proj`. Layers 50-63, the final norm and `lm_head`+ * are never evaluated. That makes the conditioner unusually easy to substitute —+ * any checkpoint carrying the same Qwen3-VL embedding + layers 0-49 + vision+ * tower produces a drop-in conditioning signal, and swapping it changes how the+ * model *reads* a prompt without touching the diffusion weights at all.+ *+ * This module is the single source of truth for which substitutions PortOS+ * ships. Entries are pinned upstream artifacts rather than user-tunable config,+ * so they live in code (mirroring `lib/icLoraWeights.js`) instead of the+ * media-models registry — no seed file, no migration, and no way for a stale+ * `data/media-models.json` to reference a file the runner can't map.+ *+ * The one non-obvious field is `keyPrefixMap`. A ComfyUI-packaged conditioner+ * flattens the transformers namespace (`model.layers.N.…` / `visual.…`) while+ * the MLX port's loader matches the HF namespace (`model.language_model.layers.N.…`+ * / `model.visual.…`). The map is applied by scripts/generate_minimax_h3.py to+ * every checkpoint key BEFORE the pinned loader sees it, so a repackaged file+ * loads with no change to (and no fork of) the pinned runtime source.+ *+ * `finalNormKey` exists for the same reason: the pinned loader instantiates the+ * full module tree (including `norm`, which it deliberately never applies) and+ * refuses to load with any parameter missing. A conditioner published without+ * the final norm — correct, since H3 reads the state before it — would trip+ * that check, so the runner synthesizes a ones-filled `norm.weight` under this+ * key. Absent means "the checkpoint ships its own norm".+ */++import { ServerError } from './errorHandler.js';++// Every runtime's built-in conditioner option. Selected by default and always+// present, so the picker never renders a single-option select and a render that+// omits `textEncoderId` behaves exactly as it did before this feature existed.+export const STOCK_TEXT_ENCODER_ID = 'stock';++const STOCK_MINIMAX_H3 = Object.freeze({+ id: STOCK_TEXT_ENCODER_ID,+ label: 'Stock — MiniMax H3 Qwen3-VL-32B',+ description: 'The conditioner published inside the H3 checkpoint. Already downloaded with the model.',+ builtIn: true,+});++// Substitutable conditioners, keyed by the runtime whose loader can consume+// them. A runtime absent from this table has no picker at all.+const TEXT_ENCODERS_BY_RUNTIME = Object.freeze({+ minimax_h3: Object.freeze([+ STOCK_MINIMAX_H3,+ Object.freeze({+ id: 'heretic-bf16',+ label: 'Ultra-Heretic uncensored — Qwen3-VL-32B bf16',+ description:+ 'Abliterated Qwen3-VL-32B conditioner (Heretic v1.2.0, attention-targeted) repackaged for H3. '+ + 'Reads prompts the stock conditioner refuses or waters down; the diffusion weights are unchanged.',+ repo: 'ethanfel/Qwen3-VL-32B-Ultra-Heretic-H3-ComfyUI-INT8-ConvRot',+ revision: 'e8967f6a39ea5b4939a1aff81be3e8706490c0e8',+ file: 'qwen3vl_32b_h3_ultra_uncensored_heretic_bf16.safetensors',+ // ComfyUI namespace -> the HF namespace the pinned MLX loader matches.+ // Longest-prefix-first is applied at the runner, so these two disjoint+ // rules can be declared in any order.+ keyPrefixMap: Object.freeze({+ 'model.': 'model.language_model.',+ 'visual.': 'model.visual.',+ }),+ // Published without the final norm (`minimax_h3_final_norm: "false"` in+ // its safetensors metadata) — synthesized by the runner in THIS file's+ // own namespace, so the prefix map above rewrites it like any other key.+ finalNormKey: 'model.norm.weight',+ // The exact published size of THIS file. Single source of truth for every+ // size the UI shows — the picker formats it rather than carrying a second,+ // driftable "~N GB" literal.+ sizeBytes: 51506295440,+ disclosure: Object.freeze({+ modelCardUrl: 'https://huggingface.co/ethanfel/Qwen3-VL-32B-Ultra-Heretic-H3-ComfyUI-INT8-ConvRot',+ weightsLicense: Object.freeze({+ name: 'Apache-2.0',+ url: 'https://huggingface.co/Qwen/Qwen3-VL-32B-Instruct',+ }),+ baseModel: 'Qwen/Qwen3-VL-32B-Instruct',+ // Decimal GB, matching lib/videoDisclosure.js's convention.+ estimatedDownloadGb: 51.5,+ reviewedAt: '2026-08-14',+ }),+ // The stock conditioner is aligned; this one is deliberately not. Surface+ // that in the picker rather than burying it in a model card.+ advisory:+ 'This conditioner has had its refusal behavior removed. It will follow prompts the stock '+ + 'conditioner declines. You remain responsible for what you generate.',+ }),+ ]),+});++/**+ * Every conditioner option a model can render with, stock first.+ * Returns `[]` for a runtime with no substitutions — the caller renders no+ * picker rather than a select with one entry.+ */+export const videoTextEncoderOptions = (model) => {+ const list = TEXT_ENCODERS_BY_RUNTIME[model?.runtime];+ return list && list.length > 1 ? list : [];+};++/** Resolve one option by id, or `null` when the model can't render with it. */+export const videoTextEncoderOption = (model, id) =>+ videoTextEncoderOptions(model).find((entry) => entry.id === id) || null;++/**+ * `true` when `id` is absent or names the runtime's built-in conditioner —+ * i.e. the render needs no override plumbing at all. A model with no+ * substitutions accepts only the stock id (and absence).+ */+export const isStockTextEncoder = (id) => !id || id === STOCK_TEXT_ENCODER_ID;++/**+ * `true` when this model can actually render with `id` — i.e. the id names one+ * of its runtime's substitutable conditioners. Non-throwing, so the request+ * path can reject early (releasing staged uploads on its own terms) while the+ * service path uses `resolveVideoTextEncoder` below.+ */+export const supportsVideoTextEncoder = (model, id) => {+ const option = videoTextEncoderOption(model, id);+ return !!option && !option.builtIn;+};++/** The 400 both the request path and the service path raise for a bad id. */+export const videoTextEncoderUnsupportedError = (model, id) => {+ const offered = videoTextEncoderOptions(model).map((entry) => entry.id);+ return new ServerError(+ offered.length > 0+ ? `Model "${model?.id}" has no text encoder "${id}" (offers ${offered.join(', ')}).`+ : `Model "${model?.id}" does not support a substitute text encoder.`,+ { status: 400, code: 'VIDEO_TEXT_ENCODER_UNSUPPORTED' },+ );+};++/**+ * Resolve a requested conditioner for a render, or throw a 400 naming what the+ * model actually offers. Returns `null` for the stock choice so the caller can+ * branch on "no override" without a second predicate.+ */+export const resolveVideoTextEncoder = (model, id) => {+ if (isStockTextEncoder(id)) return null;+ if (!supportsVideoTextEncoder(model, id)) throw videoTextEncoderUnsupportedError(model, id);+ return videoTextEncoderOption(model, id);+};++/**+ * Every downloadable conditioner across all runtimes, deduped by id — what the+ * /models/status lane and the download/repair routes enumerate. The built-in+ * options are excluded: they ride the model's own download.+ */+export const downloadableVideoTextEncoders = () => {+ const seen = new Map();+ for (const list of Object.values(TEXT_ENCODERS_BY_RUNTIME)) {+ for (const entry of list) {+ if (!entry.builtIn && !seen.has(entry.id)) seen.set(entry.id, entry);+ }+ }+ return [...seen.values()];+};++/** Resolve a downloadable conditioner by id for the download/repair routes. */+export const downloadableVideoTextEncoder = (id) =>+ downloadableVideoTextEncoders().find((entry) => entry.id === id) || null;++/**+ * The client-facing projection of an option. Deliberately drops `keyPrefixMap`+ * and `finalNormKey` — loader mechanics the UI has no use for and that would+ * only invite a client-side reimplementation of the remap.+ */+export const publicTextEncoderOption = (entry) => ({+ id: entry.id,+ label: entry.label,+ description: entry.description,+ builtIn: !!entry.builtIn,+ ...(entry.repo ? { repo: entry.repo } : {}),+ ...(entry.file ? { file: entry.file } : {}),+ ...(entry.sizeBytes ? { sizeBytes: entry.sizeBytes } : {}),+ ...(entry.advisory ? { advisory: entry.advisory } : {}),+ ...(entry.disclosure ? { disclosure: entry.disclosure } : {}),+});diff --git a/server/lib/videoTextEncoders.test.js b/server/lib/videoTextEncoders.test.jsnew file mode 100644index 0000000000..c78ff53232--- /dev/null+++ b/server/lib/videoTextEncoders.test.js@@ -0,0 +1,144 @@+import { describe, expect, it } from 'vitest';+import {+ STOCK_TEXT_ENCODER_ID,+ videoTextEncoderOptions,+ videoTextEncoderOption,+ isStockTextEncoder,+ supportsVideoTextEncoder,+ resolveVideoTextEncoder,+ downloadableVideoTextEncoders,+ downloadableVideoTextEncoder,+ publicTextEncoderOption,+} from './videoTextEncoders.js';++const H3 = { id: 'minimax_h3_8bit', runtime: 'minimax_h3' };+const LTX = { id: 'ltx2_unified', runtime: 'ltx2' };++describe('videoTextEncoders', () => {+ // An empty list is the signal the client uses to hide the picker entirely, so+ // a runtime with nothing to substitute must NOT report its built-in option —+ // otherwise every model renders a one-entry select that does nothing.+ it('offers nothing for a runtime with no substitutions', () => {+ expect(videoTextEncoderOptions(LTX)).toEqual([]);+ expect(videoTextEncoderOptions({ runtime: 'wan22' })).toEqual([]);+ expect(videoTextEncoderOptions(null)).toEqual([]);+ });++ it('lists the stock option first for a runtime that has substitutions', () => {+ const options = videoTextEncoderOptions(H3);+ expect(options.length).toBeGreaterThan(1);+ expect(options[0].id).toBe(STOCK_TEXT_ENCODER_ID);+ expect(options[0].builtIn).toBe(true);+ expect(options.slice(1).every((option) => !option.builtIn)).toBe(true);+ });++ // Absence and the stock sentinel have to mean the same thing everywhere: the+ // route drops the sentinel from persisted params, so a resumed render sends+ // absence where the original sent 'stock'.+ it.each([undefined, null, '', STOCK_TEXT_ENCODER_ID])('treats %j as no override', (id) => {+ expect(isStockTextEncoder(id)).toBe(true);+ expect(resolveVideoTextEncoder(H3, id)).toBeNull();+ // Even on a runtime that offers no substitutions at all.+ expect(resolveVideoTextEncoder(LTX, id)).toBeNull();+ });++ it('resolves a substitute with the loader mechanics the runner needs', () => {+ const option = resolveVideoTextEncoder(H3, 'heretic-bf16');+ expect(option.repo).toBeTruthy();+ // A floating revision would let the upstream repo change the weights under+ // a pinned PortOS build.+ expect(option.revision).toMatch(/^[0-9a-f]{40}$/);+ expect(option.file).toMatch(/\.safetensors$/);+ expect(Object.keys(option.keyPrefixMap).length).toBeGreaterThan(0);+ });++ // The remap has to land on the namespace the pinned MLX loader matches+ // (`model.language_model.` / `model.visual.`), or every tensor is skipped and+ // the load fails with "missing N tensors" after reading ~48 GB.+ it('maps the ComfyUI namespace onto the loader namespace', () => {+ const { keyPrefixMap } = resolveVideoTextEncoder(H3, 'heretic-bf16');+ expect(keyPrefixMap['model.']).toBe('model.language_model.');+ expect(keyPrefixMap['visual.']).toBe('model.visual.');+ // Declared in the SUBSTITUTE's own namespace so the map above rewrites it+ // like any other key — a post-map name would stay unmapped.+ const { finalNormKey } = resolveVideoTextEncoder(H3, 'heretic-bf16');+ expect(finalNormKey.startsWith('model.')).toBe(true);+ expect(finalNormKey.startsWith('model.language_model.')).toBe(false);+ });++ it('rejects an id the model cannot load', () => {+ expect(supportsVideoTextEncoder(H3, 'nope')).toBe(false);+ expect(() => resolveVideoTextEncoder(H3, 'nope')).toThrow(/has no text encoder "nope"/);+ // The message names what IS available so the caller can correct it.+ expect(() => resolveVideoTextEncoder(H3, 'nope')).toThrow(/heretic-bf16/);+ });++ it('rejects a substitute on a runtime with no remap for it', () => {+ expect(supportsVideoTextEncoder(LTX, 'heretic-bf16')).toBe(false);+ expect(() => resolveVideoTextEncoder(LTX, 'heretic-bf16'))+ .toThrow(/does not support a substitute text encoder/);+ });++ // A built-in option ships inside the model's weights and has no repo of its+ // own, so it must never reach the download lane — that would 404 or, worse,+ // try to snapshot a repo that doesn't exist.+ it('excludes built-in options from the download lane', () => {+ const ids = downloadableVideoTextEncoders().map((entry) => entry.id);+ expect(ids).not.toContain(STOCK_TEXT_ENCODER_ID);+ expect(ids).toContain('heretic-bf16');+ expect(downloadableVideoTextEncoder(STOCK_TEXT_ENCODER_ID)).toBeNull();+ expect(downloadableVideoTextEncoder('heretic-bf16')).toBeTruthy();+ for (const entry of downloadableVideoTextEncoders()) {+ expect(entry.repo).toBeTruthy();+ expect(entry.file).toBeTruthy();+ }+ });++ // The client projection must not carry loader mechanics — publishing them+ // invites a client-side reimplementation of the remap that can then drift+ // from the runner's.+ it('keeps loader mechanics off the client projection', () => {+ const projected = publicTextEncoderOption(videoTextEncoderOption(H3, 'heretic-bf16'));+ expect(projected.keyPrefixMap).toBeUndefined();+ expect(projected.finalNormKey).toBeUndefined();+ expect(projected.revision).toBeUndefined();+ // …while keeping everything the picker renders.+ expect(projected).toMatchObject({+ id: 'heretic-bf16',+ builtIn: false,+ label: expect.any(String),+ description: expect.any(String),+ advisory: expect.any(String),+ // The exact published byte count — the picker formats it, so there is no+ // second "~N GB" literal that could drift from the real download.+ sizeBytes: expect.any(Number),+ });+ });++ it('projects the stock option as built-in with no download of its own', () => {+ const projected = publicTextEncoderOption(videoTextEncoderOption(H3, STOCK_TEXT_ENCODER_ID));+ expect(projected).toMatchObject({ id: STOCK_TEXT_ENCODER_ID, builtIn: true });+ expect(projected.repo).toBeUndefined();+ expect(projected.sizeBytes).toBeUndefined();+ });++ // Size is declared once, as bytes. A GB figure also appears in `disclosure`+ // (the convention lib/videoDisclosure.js uses for its own entries), so pin it+ // against the byte count rather than letting the two drift.+ it('keeps the disclosure GB figure consistent with the byte count', () => {+ for (const entry of downloadableVideoTextEncoders()) {+ const declaredGb = entry.disclosure?.estimatedDownloadGb;+ expect(declaredGb).toBeGreaterThan(0);+ expect(declaredGb).toBeCloseTo(entry.sizeBytes / 1e9, 0);+ }+ });++ // An uncensored conditioner is a deliberate choice; the picker states what+ // changed rather than leaving it to an external model card.+ it('carries an advisory on every non-built-in option', () => {+ for (const entry of downloadableVideoTextEncoders()) {+ expect(entry.advisory).toBeTruthy();+ expect(entry.disclosure?.modelCardUrl).toMatch(/^https:\/\/huggingface\.co\//);+ }+ });+});diff --git a/server/routes/videoGen.integrity.test.js b/server/routes/videoGen.integrity.test.jsindex 0eb50705dd..15616658cb 100644--- a/server/routes/videoGen.integrity.test.js+++ b/server/routes/videoGen.integrity.test.js@@ -109,6 +109,7 @@ import {verifyModelCache, repairModelCache, verifyCachedRepoFiles, repairCachedRepoFiles,} from '../lib/hfCache.js';import { isHfRepoId } from '../lib/mediaModels.js';+import { downloadableVideoTextEncoders } from '../lib/videoTextEncoders.js';describe('Video Gen integrity routes', () => {let app;@@ -211,4 +212,80 @@ describe('Video Gen integrity routes', () => {expect(res.status).toBe(400);expect(res.body.code).toBe('NOT_DOWNLOADABLE');});++ // Substitutable prompt conditioners (#4081) — their own lane, keyed by the+ // registry id rather than a model id (they aren't listVideoModels() entries).+ // Every operation is scoped to the ONE pinned file: the upstream repo also+ // publishes INT8 ConvRot / NVFP4 quantizations and 50-63 generation tails this+ // MLX loader can't read, so a repo-wide pull would cost ~130 GB for ~48 GB of+ // usable weights — and a repo-wide verify would flag those as corrupt.+ describe('substitutable text encoders', () => {+ const encoder = () => downloadableVideoTextEncoders()[0];++ it('GET /models/status reports each substitute with the badge shape', async () => {+ const res = await request(app).get('/api/video-gen/models/status');+ expect(res.status).toBe(200);+ const entry = res.body.textEncoderOptions.find((o) => o.id === encoder().id);+ expect(entry).toMatchObject({+ id: encoder().id,+ repo: encoder().repo,+ cached: false,+ label: expect.any(String),+ });+ // The mocked verify reports 'bad', but an uncached file gets the Download+ // badge rather than a Repair banner — same rule as repoCacheStatus.+ expect(entry.integrity).toBeNull();+ expect(verifyCachedRepoFiles).toHaveBeenCalledWith(+ encoder().repo, [encoder().file], { revision: encoder().revision },+ );+ });++ it('GET /text-encoders/:id/download pulls only the pinned file at its pinned revision', async () => {+ const res = await request(app).get(`/api/video-gen/text-encoders/${encoder().id}/download`);+ expect(res.status).toBe(200);+ expect(sseDownload.start).toHaveBeenCalledWith(expect.objectContaining({+ repos: [{ repo: encoder().repo, revision: encoder().revision, only: [encoder().file] }],+ force: false,+ }));+ });++ it('GET /text-encoders/:id/download threads force=1 for a repair re-fetch', async () => {+ const res = await request(app).get(`/api/video-gen/text-encoders/${encoder().id}/download?force=1`);+ expect(res.status).toBe(200);+ expect(sseDownload.start).toHaveBeenCalledWith(expect.objectContaining({ force: true }));+ });++ it('POST /text-encoders/:id/repair deletes only the pinned file', async () => {+ const res = await request(app).post(`/api/video-gen/text-encoders/${encoder().id}/repair`).send({ deep: true });+ expect(res.status).toBe(200);+ expect(res.body.deep).toBe(true);+ expect(res.body.deleted).toEqual([{ repo: encoder().repo, name: encoder().file }]);+ expect(repairCachedRepoFiles).toHaveBeenCalledWith(+ encoder().repo, [encoder().file], { deep: true, revision: encoder().revision },+ );+ });++ it.each(['download', 'repair'])('404s an unknown encoder id on /%s', async (action) => {+ const res = action === 'download'+ ? await request(app).get('/api/video-gen/text-encoders/nope/download')+ : await request(app).post('/api/video-gen/text-encoders/nope/repair').send({});+ expect(res.status).toBe(404);+ expect(res.body.code).toBe('VIDEO_TEXT_ENCODER_UNKNOWN');+ });++ // The built-in option ships inside the model's own weights and has no repo,+ // so it must never reach this lane — otherwise the UI could offer a Download+ // button for something that isn't separately downloadable.+ it('404s the built-in stock option', async () => {+ const res = await request(app).get('/api/video-gen/text-encoders/stock/download');+ expect(res.status).toBe(404);+ });++ it('POST /models/verify covers every substitute in an unscoped scan', async () => {+ await request(app).post('/api/video-gen/models/verify').send({});+ expect(verifyCachedRepoFiles).toHaveBeenCalledWith(+ encoder().repo, [encoder().file], { deep: false, revision: encoder().revision },+ );+ });+ });});diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 5f83d05107..57c376f2d3 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -53,6 +53,10 @@ import {IC_LORA_MODE_VALUES, icLoraSpecForMode, icLoraRepos, listIcLoraWeights,icLoraWeightCandidates, findCachedIcLoraWeight,} from '../lib/icLoraWeights.js';+import {+ downloadableVideoTextEncoders, downloadableVideoTextEncoder, publicTextEncoderOption,+ isStockTextEncoder,+} from '../lib/videoTextEncoders.js';import {inspectModelCache, verifyModelCache, repairModelCache, repairCachedFile,verifyCachedRepoFiles, repairCachedRepoFiles, summarizeVerify, aggregateVerifies,@@ -158,6 +162,11 @@ export const LOCAL_ONLY_VIDEO_PARAMS = Object.freeze({seed: optionalNum(0, Number.MAX_SAFE_INTEGER, 'seed'),imageStrength: optionalNum(0, 1, 'imageStrength'),tiling: z.enum(['auto', 'none', 'spatial', 'temporal']).optional(),+ // Which prompt conditioner reads the prompt (lib/videoTextEncoders.js).+ // Validated loosely here and resolved against the MODEL's own option list in+ // the service — the set is per-runtime, so a route-level enum would either+ // have to enumerate every runtime's options or reject a legitimate one.+ textEncoderId: z.string().min(1).max(64).optional(),});const generateBodySchema = z.object({@@ -612,6 +621,16 @@ const modelDownloadTargets = (model) => {return targets;};+// One download target per substitutable prompt conditioner. Each is a single+// pinned file inside a repo that also publishes quantizations and generation+// tails PortOS's MLX loader can't read, so these are ALWAYS scoped to `only:+// [file]` — a repo-wide snapshot would pull ~130 GB of unusable variants.+const textEncoderDownloadTargets = () => downloadableVideoTextEncoders().map((entry) => ({+ repo: entry.repo,+ revision: entry.revision || null,+ only: [entry.file],+}));+const targetKey = (target) => `${target.repo}@${target.revision || 'latest'}::${target.only.join(',')}`;const targetVerifyOptions = (target, deep) => ({deep,@@ -632,6 +651,10 @@ const reposToVerify = (modelId) => {const targets = listVideoModels().flatMap(modelDownloadTargets);const enc = getTextEncoderRepo();if (isHfRepoId(enc)) targets.push({ repo: enc, only: [] });+ // Substitutable prompt conditioners are single pinned files the render path+ // depends on, so an unscoped scan must reach them too — a truncated one+ // otherwise only surfaces as a load failure minutes into a render.+ targets.push(...textEncoderDownloadTargets());// 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.@@ -679,7 +702,7 @@ router.get('/models/status', asyncHandler(async (_req, res) => {// can distinguish "not downloaded" from "served from LM Studio".const encoderRepo = getTextEncoderRepo();const verifyCache = new Map();- const [models, textEncoder, icLoras] = await Promise.all([+ const [models, textEncoder, textEncoderOptions, icLoras] = await Promise.all([Promise.all(listVideoModels().map(async (m) => {return { id: m.id, ...await modelCacheStatus(m, verifyCache) };})),@@ -687,6 +710,26 @@ router.get('/models/status', asyncHandler(async (_req, res) => {if (!isHfRepoId(encoderRepo)) return { repo: encoderRepo, cached: true, sizeBytes: 0, integrity: null };return { repo: encoderRepo, ...await repoCacheStatus(encoderRepo) };})(),+ // Substitutable prompt conditioners (lib/videoTextEncoders.js) — the same+ // `{ id, repo, cached, sizeBytes, integrity }` badge shape as the models and+ // the IC weights, so the video form renders their Download button and+ // Repair banner with the existing components. Scoped to the ONE pinned file+ // (never the repo) for the reason in textEncoderDownloadTargets.+ Promise.all(downloadableVideoTextEncoders().map(async (entry) => {+ const verify = await verifyCachedRepoFiles(entry.repo, [entry.file], {+ ...(entry.revision ? { revision: entry.revision } : {}),+ });+ const cached = verify.status === 'ok';+ return {+ ...publicTextEncoderOption(entry),+ estimatedBytes: entry.sizeBytes,+ cached,+ sizeBytes: verify.sizeBytes || 0,+ // Same rule as repoCacheStatus: a not-yet-downloaded file gets the+ // Download badge, not a Repair banner.+ integrity: cached ? summarizeVerify(verify) : null,+ };+ })),// 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@@ -720,7 +763,7 @@ router.get('/models/status', asyncHandler(async (_req, res) => {};})),]);- res.json({ models, textEncoder, icLoras });+ res.json({ models, textEncoder, textEncoderOptions, icLoras });}));// POST /models/verify — force an integrity re-scan on demand. `deep:true` adds@@ -841,6 +884,56 @@ router.post('/ic-loras/:mode/repair', asyncHandler(async (req, res) => {res.json({ deep, deleted: result.deleted.map((name) => ({ repo: result.repoId, name })), repos: [spec.repo] });}));+// Substitutable prompt conditioners (lib/videoTextEncoders.js) get their own+// download/repair pair for the same reason the IC-LoRA weights do: the render+// path depends on them but they are NOT listVideoModels() entries, so the+// model-id-keyed routes can't reach them. Keyed by the registry id the client+// also puts in the render payload.+//+// Distinct from the /text-encoder/* pair below, which is the SHARED LTX encoder+// (one repo, install-wide, selected in the media-models registry). These are+// per-model alternatives chosen per render.+const textEncoderFromParam = (id) => {+ const entry = downloadableVideoTextEncoder(id);+ if (!entry) {+ const known = downloadableVideoTextEncoders().map((e) => e.id);+ throw new ServerError(+ `Unknown text encoder: ${id}${known.length ? ` (expected one of ${known.join(', ')})` : ''}`,+ { status: 404, code: 'VIDEO_TEXT_ENCODER_UNKNOWN' },+ );+ }+ return entry;+};++// Always single-file, never a snapshot: the upstream repo also publishes INT8+// ConvRot / NVFP4 quantizations and 50-63 generation tails that this MLX loader+// cannot read, so a repo-wide pull would cost ~130 GB for ~48 GB of usable+// weights.+router.get('/text-encoders/:id/download', asyncHandler(async (req, res) => {+ const entry = textEncoderFromParam(req.params.id);+ await startHfDownloadStream({+ req,+ res,+ repos: [{ repo: entry.repo, revision: entry.revision || null, only: [entry.file] }],+ force: req.query.force === '1',+ });+}));++router.post('/text-encoders/:id/repair', asyncHandler(async (req, res) => {+ const entry = textEncoderFromParam(req.params.id);+ const parsed = z.object({ deep: z.boolean().optional() }).safeParse(req.body || {});+ if (!parsed.success) failValidation(parsed);+ const result = await repairCachedRepoFiles(entry.repo, [entry.file], {+ deep: parsed.data.deep || false,+ ...(entry.revision ? { revision: entry.revision } : {}),+ });+ res.json({+ deep: parsed.data.deep || false,+ deleted: result.deleted.map((name) => ({ repo: entry.repo, name })),+ repos: [entry.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@@ -951,6 +1044,11 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {guidanceScale: body.guidanceScale,seed: body.seed,tiling: body.tiling || 'auto',+ // Only a SUBSTITUTE is persisted: an explicit `textEncoderId: 'stock'` is+ // semantically identical to omitting the field, so storing it would make a+ // resumed/remixed render carry a knob that never applied — and would differ+ // from what the service records in history for the same render.+ ...(isStockTextEncoder(body.textEncoderId) ? {} : { textEncoderId: body.textEncoderId }),disableAudio: body.disableAudio === true || body.disableAudio === 'true',sourceImagePath,audioFilePath,@@ -1006,6 +1104,9 @@ const ACTIVE_JOB_PARAM_FIELDS = ['width', 'height', 'numFrames', 'fps','steps', 'guidanceScale', 'seed','tiling', 'disableAudio', 'mode', 'chunks', 'chunkPrompts', 'contextFrames', 'imageStrength',+ // A registry id, not a path — safe to echo so a reloading page restores the+ // conditioner the in-flight render is actually using.+ 'textEncoderId','audioStartSec',// Grok jobs (#2859 phase 2): the semantic t2v/i2v mode ('mode' holds the// 'grok' discriminator for them) and the clip duration — both plaindiff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 04c3feb9e1..91ded86239 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -712,6 +712,10 @@ describe('videoGen routes', () => {'seed','imageStrength','tiling',+ // Not in the it.each table above: the route deliberately DROPS the+ // stock value from persisted params, so the generic round-trip+ // assertion can't cover it. Its own case is below.+ 'textEncoderId',]);const { getSettings } = await import('../services/settings.js');getSettings.mockResolvedValueOnce({ imageGen: grokReady, videoGen: { mode: 'grok' } });@@ -722,6 +726,21 @@ describe('videoGen routes', () => {expect(call[0].params[param]).toBe(value);});+ // grok has no conditioner knob, so naming one must keep the render local —+ // even for the stock id, which the route then drops from persisted params+ // (an unswapped render's job params stay byte-identical to a request that+ // never sent the field). Both halves matter: keeping it local without+ // dropping it would persist a knob that never applied.+ it('keeps textEncoderId on the local path under a grok pin, without persisting the stock value', async () => {+ const { getSettings } = await import('../services/settings.js');+ getSettings.mockResolvedValueOnce({ imageGen: grokReady, videoGen: { mode: 'grok' } });+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a fox', textEncoderId: 'stock' });+ expect(r.status).toBe(200);+ const [call] = mediaJobQueue.enqueueJob.mock.calls;+ expect(call[0].params.mode).not.toBe('grok');+ expect(call[0].params.textEncoderId).toBeUndefined();+ });+it('a grok pin degrades to local when the request carries local-only machinery', async () => {const { getSettings } = await import('../services/settings.js');getSettings.mockResolvedValueOnce({diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 11e59c3472..59393911a4 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -44,6 +44,9 @@ import { videoLoraFamily } from '../../lib/runners.js';import {isVideoModelTermsAccepted, acceptedVideoModelTerms, videoModelTermsGateId, videoModelTermsError,} from '../../lib/videoDisclosure.js';+import {+ videoTextEncoderOptions, publicTextEncoderOption, resolveVideoTextEncoder,+} from '../../lib/videoTextEncoders.js';import { getSettings } from '../settings.js';import {isIcLoraMode, icLoraSpecForMode, resolveIcLoraWeight,@@ -57,6 +60,7 @@ import {MINIMAX_H3_VENV_PYTHON,MINIMAX_H3_HELPER_SCRIPT,MINIMAX_H3_REPO_DIR,+ MINIMAX_H3_ENCODER_SHIM_DIR,MINIMAX_H3_EXPECTED_REVISION,HUNYUAN_VENV_PYTHON,HUNYUAN_HELPER_SCRIPT,@@ -162,10 +166,16 @@ export const VIDEO_MODELS = Object.fromEntries(getVideoModels().map((m) => [m.id// them off the model instead of keeping their own lists. Applied by BOTH model// resolvers, so the render path and the API payload can never disagree about// what a model supports.+// Also attached: the substitutable prompt conditioners the model's runtime can+// load (lib/videoTextEncoders.js). Decorated rather than declared on the+// registry entry so the picker can never offer an option this build's runner+// has no key-remap for — and empty for every runtime without substitutions, so+// the client renders no picker instead of a one-entry select.const decorateVideoModel = (m) => (m ? {...m,lastFrameAnchored: modelAnchorsLastFrame(m),runtimeLoraCapable: byovRuntimeLoraCapable(m.runtime),+ textEncoderOptions: videoTextEncoderOptions(m).map(publicTextEncoderOption),} : m);export const resolveVideoModel = (modelId) =>@@ -631,7 +641,7 @@ const buildWan22Args = ({ model, wanModelPath, wanRequiredWeights, prompt, negat// Build args for PipeNetwork's pinned MiniMax H3 MLX port. The helper resolves// only exact, already-cached HF revisions; every network download remains an// explicit Video Gen UI action guarded by the model's terms acknowledgement.-const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, loras }) => {+const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, loras, textEncoder }) => {assertByovRuntimeInstalled('minimax_h3');assertRenderModeContract({model,@@ -715,6 +725,22 @@ const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numF// has already rejected LoRAs unless the probe proved this checkout can apply// them to the quantized DiT (see runtimes.js `loraProbeArgs`).for (const l of loras ?? []) args.push('--lora', l.path, '--lora-scale', String(l.strength));+ // Substituted prompt conditioner (lib/videoTextEncoders.js). Absent for the+ // stock choice, so the argv of an unswapped render is byte-identical to what+ // it was before this feature existed. `textEncoder.path` was already resolved+ // against the HF cache by generateVideo — the helper never downloads.+ if (textEncoder) {+ args.push('--text-encoder-id', textEncoder.id);+ args.push('--text-encoder-file', textEncoder.path);+ args.push('--text-encoder-shim-root', MINIMAX_H3_ENCODER_SHIM_DIR);+ for (const [from, to] of Object.entries(textEncoder.keyPrefixMap || {})) {+ args.push('--text-encoder-key-prefix', `${from}=${to}`);+ }+ // Only for a conditioner published without the final norm — H3 reads the+ // hidden state before it, but the pinned loader builds the full module tree+ // and refuses to load with any parameter missing.+ if (textEncoder.finalNormKey) args.push('--text-encoder-final-norm-key', textEncoder.finalNormKey);+ }return { bin: MINIMAX_H3_VENV_PYTHON, args };};@@ -756,7 +782,7 @@ const buildHunyuanArgs = ({ model, prompt, negativePrompt, width, height, numFrareturn { bin: HUNYUAN_VENV_PYTHON, args };};-const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeights, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, textEncoderRepo, outputPath, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {+const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeights, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, textEncoderRepo, textEncoder, 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).@@ -796,7 +822,7 @@ const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeightreturn buildWan22Args({ model, wanModelPath, wanRequiredWeights, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, mode, outputPath });}if (model.runtime === 'minimax_h3') {- return buildMiniMaxH3Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, loras });+ return buildMiniMaxH3Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, loras, textEncoder });}if (model.runtime === 'hunyuan') {return buildHunyuanArgs({ model, prompt, negativePrompt, width, height, numFrames, steps, guidance, seed, outputPath });@@ -903,7 +929,7 @@ const resolveVideoDimensions = (model, width, height) => ({height: height ?? configuredVideoDimension(model?.defaultHeight, 512),});-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, hidden = false, jobId: providedJobId = null }) {+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, textEncoderId = null, 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@@ -998,6 +1024,32 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m}}}+ // Substituted prompt conditioner (#4081). `resolveVideoTextEncoder` returns+ // null for the stock choice — the whole override path stays dormant then —+ // and throws a 400 when the model's runtime has no remap for the requested+ // id. The weight is resolved against the HF cache HERE rather than in the+ // helper so a missing download fails as a clean 400 before any GPU work,+ // matching how wan22's required weights are handled above.+ const textEncoderOption = resolveVideoTextEncoder(model, textEncoderId);+ let resolvedTextEncoder = null;+ if (textEncoderOption) {+ const encoderPath = await findCachedRepoFile(+ textEncoderOption.repo, textEncoderOption.file, { revision: textEncoderOption.revision },+ );+ if (!encoderPath) {+ throw new ServerError(+ `Text encoder "${textEncoderOption.label}" is not downloaded. Download it in Video Gen before rendering.`,+ { status: 400, code: 'VIDEO_TEXT_ENCODER_NOT_CACHED' },+ );+ }+ resolvedTextEncoder = {+ id: textEncoderOption.id,+ path: encoderPath,+ keyPrefixMap: textEncoderOption.keyPrefixMap,+ finalNormKey: textEncoderOption.finalNormKey,+ };+ }+// Only require the legacy mlx_video pythonPath when the chosen runtime// actually uses it. ltx2/wan22/hunyuan resolve their own venv path inside// buildArgs — gating them on the unrelated mlx_video setting locks users@@ -1283,6 +1335,11 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mguidanceScale: actualGuidance,tiling,disableAudio,+ // Which prompt conditioner read this prompt. Only recorded when it wasn't+ // the stock one, so pre-feature history and every unswapped render stay+ // byte-identical — and so a Remix of a stock render can't resurrect an+ // override the user has since deselected.+ ...(resolvedTextEncoder ? { textEncoderId: resolvedTextEncoder.id } : {}),filename,createdAt: new Date().toISOString(),// History mode reflects the EFFECTIVE mode — buildLtx2Args infers fflf@@ -1345,7 +1402,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: loraCapableModel, wanModelPath, wanRequiredWeights, 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, audioStartSec, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2 }));+ ({ bin, args } = buildArgs({ pythonPath, modelId, model: loraCapableModel, wanModelPath, wanRequiredWeights, 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, audioStartSec, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, textEncoder: resolvedTextEncoder, outputPath, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, 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.jsindex 8c26f35866..9881ad50c4 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -2215,6 +2215,88 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {expect(hfChildEnv).not.toHaveBeenCalled();});+ // Substituted prompt conditioner (#4081). The whole override path has to stay+ // dormant unless it was asked for — an unswapped render's argv must be+ // byte-identical to what it was before the feature existed.+ it.each([undefined, null, 'stock'])('adds no text-encoder argv for %j', async (textEncoderId) => {+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ const spawnMock = vi.mocked(spawnDetached);+ spawnMock.mockClear();++ await generateVideo({+ jobId: 'h3-stock-encoder',+ modelId: 'minimax_h3_8bit',+ prompt: 'a fox watches the rain',+ mode: 'text',+ textEncoderId,+ });++ const [, args] = spawnMock.mock.calls.find(([, a]) => (+ Array.isArray(a) && a.some((arg) => basename(String(arg)) === 'generate_minimax_h3.py')+ ));+ expect(args.filter((arg) => String(arg).startsWith('--text-encoder'))).toEqual([]);+ });++ it('forwards a substituted text encoder as a resolved path plus its key remap', async () => {+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ const spawnMock = vi.mocked(spawnDetached);+ spawnMock.mockClear();++ await generateVideo({+ jobId: 'h3-swapped-encoder',+ modelId: 'minimax_h3_8bit',+ prompt: 'a fox watches the rain',+ mode: 'text',+ textEncoderId: 'heretic-bf16',+ });++ const [, args] = spawnMock.mock.calls.find(([, a]) => (+ Array.isArray(a) && a.some((arg) => basename(String(arg)) === 'generate_minimax_h3.py')+ ));+ expect(args[args.indexOf('--text-encoder-id') + 1]).toBe('heretic-bf16');+ // A resolved cache path, never a repo id — the helper runs fully offline+ // (HF_HUB_OFFLINE=1) and cannot look one up.+ expect(args[args.indexOf('--text-encoder-file') + 1])+ .toBe(join('/mock/hf/snap', 'qwen3vl_32b_h3_ultra_uncensored_heretic_bf16.safetensors'));+ // Outside the pinned checkout: anything written inside it would read as+ // untracked in the pin verification the helper itself runs.+ const shimRoot = args[args.indexOf('--text-encoder-shim-root') + 1];+ expect(shimRoot).toContain(join('.portos', 'minimax-h3-encoder-shims'));+ expect(shimRoot).not.toContain(join('.portos', 'minimax-h3-mlx'));+ expect(args.flatMap((arg, i) => (arg === '--text-encoder-key-prefix' ? [args[i + 1]] : [])))+ .toEqual(['model.=model.language_model.', 'visual.=model.visual.']);+ expect(args[args.indexOf('--text-encoder-final-norm-key') + 1]).toBe('model.norm.weight');+ });++ // A ~48 GB weight that isn't downloaded must fail as a clean 400 on the+ // request, not minutes into the render when the helper's cache probe misses.+ it('rejects a substituted text encoder that is not downloaded', async () => {+ mockFindCachedRepoFile.mockImplementation(async (_repo, filename) => (+ filename.includes('ultra_uncensored_heretic') ? null : join('/mock/hf/snap', filename)+ ));+ try {+ await expect(generateVideo({+ jobId: 'h3-encoder-missing',+ modelId: 'minimax_h3_8bit',+ prompt: 'a fox watches the rain',+ mode: 'text',+ textEncoderId: 'heretic-bf16',+ })).rejects.toMatchObject({ status: 400, code: 'VIDEO_TEXT_ENCODER_NOT_CACHED' });+ } finally {+ mockFindCachedRepoFile.mockImplementation(async (_repo, filename) => join('/mock/hf/snap', filename));+ }+ });++ it('rejects a text encoder the model has no remap for', async () => {+ await expect(generateVideo({+ jobId: 'h3-encoder-unknown',+ modelId: 'minimax_h3_8bit',+ prompt: 'a fox watches the rain',+ mode: 'text',+ textEncoderId: 'not-a-real-encoder',+ })).rejects.toMatchObject({ status: 400, code: 'VIDEO_TEXT_ENCODER_UNSUPPORTED' });+ });+it('uses H3 native dimensions when an internal caller omits resolution', async () => {const { spawnDetached } = await import('../../lib/detachedSpawn.js');const spawnMock = vi.mocked(spawnDetached);diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.jsindex 0f713dd634..007c247c34 100644--- a/server/services/videoGen/prepareParams.js+++ b/server/services/videoGen/prepareParams.js@@ -35,6 +35,9 @@ import { safeUnder } from '../../lib/ffmpeg.js';import { RENDER_TARGET } from '../../lib/renderTargets.js';import { isVideoModelTermsAccepted, acceptedVideoModelTerms, videoModelTermsError } from '../../lib/videoDisclosure.js';import { videoLoraFamily } from '../../lib/runners.js';+import {+ isStockTextEncoder, supportsVideoTextEncoder, videoTextEncoderUnsupportedError,+} from '../../lib/videoTextEncoders.js';import { resolveContextFrames } from '../../lib/videoContinuity.js';import {IC_LORA_MODE_VALUES, icLoraSpecForMode,@@ -159,6 +162,16 @@ export async function prepareVideoGenParams({ body, uploads, localOnlyParamKeys{ status: 400, code: 'VIDEO_GEN_UNKNOWN_MODEL' },);}+ // Substituted prompt conditioner (#4081). A pure registry lookup with no+ // dependency on anything staged, so it belongs with the other pre-staging+ // model gates: the request that named the bad conditioner is the only place+ // that can report it, and rejecting later would first write durable copies of+ // every upload for a render that was never going to run.+ if (effectiveModel && !isStockTextEncoder(body.textEncoderId)+ && !supportsVideoTextEncoder(effectiveModel, body.textEncoderId)) {+ await cleanupMultipartTemp(uploads);+ throw videoTextEncoderUnsupportedError(effectiveModel, body.textEncoderId);+ }// Reject a gated model here so the caller gets a synchronous, actionable 403// instead of a doomed queue entry. The render itself re-checks (local.js) —// this is the early half of the same gate, authorized by the same recordeddiff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.jsindex 4f480e292d..cd259a4c70 100644--- a/server/services/videoGen/prepareParams.test.js+++ b/server/services/videoGen/prepareParams.test.js@@ -291,6 +291,25 @@ describe('prepareVideoGenParams', () => {.rejects.toMatchObject({ status: 400, code: 'MUSIC_VIDEO_SOURCE_REQUIRED' });});+ // Rejected here rather than in the worker: the request that named the bad+ // conditioner is the only place that can report it, and a persisted job+ // would otherwise sit in the queue only to die on dispatch.+ it('rejects a text encoder the selected model cannot load, before staging', async () => {+ await expect(prepare(+ { textEncoderId: 'heretic-bf16' },+ { sourceImage: upload('sourceImage') },+ )).rejects.toMatchObject({ status: 400, code: 'VIDEO_TEXT_ENCODER_UNSUPPORTED' });+ expect(unlink).toHaveBeenCalledWith('/tmp/multipart-sourceImage-frame.png');+ expect(unlinkedDurablePaths()).toEqual([]);+ });++ // 'stock' and absence are the same request, so neither may reject — the+ // route drops the sentinel from persisted params, which means a resumed+ // render sends absence where the original sent 'stock'.+ it.each([undefined, 'stock'])('accepts %j on a model with no substitutions', async (textEncoderId) => {+ await expect(prepare({ textEncoderId })).resolves.toMatchObject({ effectiveModelId: 'ltx2_unified' });+ });+it('rejects a history id that is not in the render history', async () => {await expect(prepare({ extendFromVideoId: '22222222-2222-4222-8222-222222222222' })).rejects.toMatchObject({ status: 404, code: 'EXTEND_SOURCE_NOT_FOUND' });diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.jsindex 4c4e6c083d..a98a15b266 100644--- a/server/services/videoGen/runtimes.js+++ b/server/services/videoGen/runtimes.js@@ -41,6 +41,13 @@ export const MINIMAX_H3_RUNTIME_PROBE_SCRIPT = join(PATHS.root, 'scripts', 'miniexport const MINIMAX_H3_LORA_PROBE_SCRIPT = join(PATHS.root, 'scripts', 'minimax_h3_lora_probe.py');export const MINIMAX_H3_REPO_DIR = join(homedir(), '.portos', 'minimax-h3-mlx');export const MINIMAX_H3_EXPECTED_REVISION = 'fcd9e9b79a1d6018d91ac477c0968de1fa067e49';+// Composed checkpoint roots for a substituted prompt conditioner+// (lib/videoTextEncoders.js). Each is a tree of symlinks into the upstream+// FL2VA snapshot with only `text_encoder/` replaced, so the pinned runtime's+// own `from_pretrained` loads it unmodified. Deliberately OUTSIDE+// MINIMAX_H3_REPO_DIR: anything written inside the checkout would show up as+// untracked in the pin verification that both /status and the render helper run.+export const MINIMAX_H3_ENCODER_SHIM_DIR = join(homedir(), '.portos', 'minimax-h3-encoder-shims');// HunyuanVideo MLX runtime — gaurav-nelson/HunyuanVideo_MLX cloned at// ~/.portos/hunyuan-video-mlx/. ~60 GB resident at bf16 so practical only