Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: integrate MiniMax H3 MLX video generation
[._.]/ Adam Eivyffac284f9c4e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 018a25c653..25d3971a4e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -123,6 +123,8 @@- Internal: the Autonomous-mode Options popover's saved-default/per-run-override plumbing moved onto a shared `usePersistedOptions` hook. Each option was seven hand-copied edits scattered across a 1000-line component, and forgetting one silently produced the "I toggled it and ran, but it did not apply" bug; an option is now a single spec row that owns its default, its saved-value reader, its clamp and its persist behavior. No behavior change.+- **Video Gen can now run MiniMax H3 locally on a 128 GB Apple Silicon Mac.** The new text-to-video profile uses PipeNetwork's source-audited MLX port and an 8-bit transformer, with every runtime and weight revision pinned and a reproducible isolated environment. Its roughly 103.3 GB of required files stay off the machine until the user explicitly installs the runtime and downloads the weights; generation itself is cache-only and receives no Hugging Face credential. H3 produces joint 24 fps video and stereo audio on its supported 17n+5 frame grid, while PortOS hides or rejects controls the released port cannot honor (image conditioning, negative prompts, silent output, tiling and chained clips). The MiniMax H3 Community License grants rights only in its Applicable Territory and explicitly excludes the EU, UK, Republic of Korea and United States, so both download and generation require the exact versioned acknowledgement shown beside the pinned license; PortOS does not guess a user's location or eligibility.+- **Video Gen now tells you what runs where, and under whose terms.** Model names such as "LTX-2.3 Distilled Q4 (~22 GB)" carried the only provenance a user got, and the local/hosted backend switch offered a one-line tooltip — so "local" was easy to read as "no rules apply", which is wrong: a local runtime only means PortOS isn't sending your prompt to a hosted provider, it doesn't waive the weights or runtime license. A compact disclosure now sits under the backend and model controls and updates with them, showing whether inference runs on this machine or is submitted to xAI, the model card and pinned revision, the weights license and the (often different) runtime license, the pinned-snapshot download size, the memory minimum against what this machine actually has, supported modes and runtime name. Every value was checked against a primary upstream source — the HuggingFace model card's own license metadata, the runtime project's LICENSE file, the file listing at the pinned revision — and anything that could not be established renders as "Unknown" rather than being guessed from a repo name. Custom models you added yourself show Unknown throughout, and so does a shipped model whose repo you re-pointed at a fork. The local wording says plainly that PortOS applies no model-level prompt filter *and* that the licenses still apply; the hosted wording says the request leaves the machine and xAI's terms and retention apply independently. Nothing about downloads, verification, render arguments or prompt handling changed — this is disclosure only, and it deliberately avoids ranking backends as more or less restrictive.- Internal: recorded a feasibility spike on Krea Realtime 14B as a local Apple Silicon video backend (`docs/research/2026-08-09-krea-realtime-apple-silicon.md`). The answer is **no-go for now** and nothing shipped: Krea's own runtime initializes CUDA at module import and pins `triton`, which publishes no macOS wheel, so it cannot even install on a Mac; its inference code is CC BY-NC-SA 4.0 (the weights are Apache-2.0 — two different licenses that PortOS has to track separately), and the only native-MLX implementation of the pipeline is a third party's unpublished, in-progress crate inside a product monorepo. The report pins every revision it inspected, distinguishes Krea 2 RAW/Turbo (image) from Krea Realtime 14B (video), marks every benchmark explicitly "not run" with the reason rather than guessing, and names the specific upstream change that would justify reevaluating.diff --git a/client/src/components/media/ModelDownloadBadge.jsx b/client/src/components/media/ModelDownloadBadge.jsxindex 8d4c235936..3a5d8a6e67 100644--- a/client/src/components/media/ModelDownloadBadge.jsx+++ b/client/src/components/media/ModelDownloadBadge.jsx@@ -24,6 +24,9 @@ export default function ModelDownloadBadge({onDownload, // () => voidonCancel, // () => voidestimateLabel, // e.g. "~8 GB" — caller derives from model entry name+ disabled = false,+ disabledReason,+ disabledReasonId,}) {if (!status) {return <p className="text-[10px] text-gray-500 mt-1">Checking model cache…</p>;@@ -87,8 +90,12 @@ export default function ModelDownloadBadge({<buttontype="button"onClick={onDownload}- className="mt-1 inline-flex items-center gap-1.5 text-[11px] text-port-accent hover:text-white border border-port-border hover:border-port-accent rounded px-2 py-1"- title={status.repo ? `Pre-download ${status.repo} into ~/.cache/huggingface/hub/` : 'Pre-download model weights'}+ disabled={disabled}+ aria-describedby={disabled && disabledReason ? disabledReasonId : undefined}+ className="mt-1 inline-flex items-center gap-1.5 text-[11px] text-port-accent hover:text-white border border-port-border hover:border-port-accent rounded px-2 py-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:text-port-accent disabled:hover:border-port-border"+ title={disabled+ ? disabledReason+ : status.repo ? `Pre-download ${status.repo} into ~/.cache/huggingface/hub/` : 'Pre-download model weights'}><Download className="w-3.5 h-3.5" /><span>Download{estimateLabel ? ` (${estimateLabel})` : ''}</span>diff --git a/client/src/components/media/ModelDownloadBadge.test.jsx b/client/src/components/media/ModelDownloadBadge.test.jsxindex 6b1a6ea7a8..6f21414b63 100644--- a/client/src/components/media/ModelDownloadBadge.test.jsx+++ b/client/src/components/media/ModelDownloadBadge.test.jsx@@ -1,5 +1,6 @@-import { describe, expect, it } from 'vitest';-import { deriveSizeEstimate } from './ModelDownloadBadge.jsx';+import { describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import ModelDownloadBadge, { deriveSizeEstimate } from './ModelDownloadBadge.jsx';describe('deriveSizeEstimate', () => {it('preserves decimal and binary gigabyte labels', () => {@@ -12,3 +13,22 @@ describe('deriveSizeEstimate', () => {expect(deriveSizeEstimate(null)).toBeNull();});});++describe('ModelDownloadBadge', () => {+ it('disables a gated download and explains why', () => {+ const onDownload = vi.fn();+ render(<ModelDownloadBadge+ status={{ repo: 'example/model', cached: false }}+ onDownload={onDownload}+ disabled+ disabledReason="Accept the model terms first"+ disabledReasonId="model-terms"+ />);+ const button = screen.getByRole('button', { name: /Download/ });+ expect(button).toBeDisabled();+ expect(button).toHaveAttribute('title', 'Accept the model terms first');+ expect(button).toHaveAttribute('aria-describedby', 'model-terms');+ fireEvent.click(button);+ expect(onDownload).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/videoGen/AdvancedParamsPanel.jsx b/client/src/components/videoGen/AdvancedParamsPanel.jsxindex 8e52909552..4480e6d2d1 100644--- a/client/src/components/videoGen/AdvancedParamsPanel.jsx+++ b/client/src/components/videoGen/AdvancedParamsPanel.jsx@@ -20,7 +20,10 @@import { useState } from 'react';import { ChevronDown, Dice5 } from 'lucide-react';import { FormField } from '../ui/FormField';-import { frameOptionsForModel, fpsOptionsForModel, CHUNK_OPTIONS } from '../../lib/videoGenParams.js';+import {+ frameOptionsForModel, fpsOptionsForModel, CHUNK_OPTIONS,+ isModelAllowedForMode, supportsVideoAudioControls,+} from '../../lib/videoGenParams.js';import { VIDEO_TILING_OPTIONS } from '../../lib/videoTilingOptions';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';@@ -44,9 +47,10 @@ export default function AdvancedParamsPanel({// a2v derives its length + audio track from the uploaded audio, so chunking// and the audio flags don't apply there.const showAudioFlags = mode !== 'a2v';+ const showModelAudioControls = showAudioFlags && supportsVideoAudioControls(currentModel);const showChunks = mode !== 'a2v'- && !(currentModel?.runtime === 'wan22'- && !currentModel?.supportedModes?.includes('image'));+ && (!Array.isArray(currentModel?.supportedModes)+ || currentModel.supportedModes.includes('image'));// ltx2 extend conditions on the source's latent rather than a single frame,// so image strength is meaningless for it.const showImageStrength = mode === 'image' || (mode === 'extend' && currentModel?.runtime !== 'ltx2');@@ -80,7 +84,7 @@ export default function AdvancedParamsPanel({>{frameOptions.map((f) => <option key={f} value={f}>{f} ({(f / fps).toFixed(1)}s @ {fps}fps)</option>)}</select>- {numFrames > 241 && (+ {numFrames > 241 && isModelAllowedForMode(currentModel, 'extend') && (<p className="text-[10px] text-gray-500 leading-snug mt-1">Past 241 frames a single-pass render may swap or OOM at 48 GB. For reliable longer clips, render up to ~10s and then use <strong>Extend</strong> on the result — it conditions on the source's full latent rather than a single last frame.</p>@@ -208,7 +212,8 @@ export default function AdvancedParamsPanel({{samplerLocked && (<p className="col-span-2 sm:col-span-3 text-[10px] text-port-accent leading-snug">- Lightning keeps its validated {currentModel.steps}-step sampler, CFG {currentModel.guidance}, and model-specific schedule locked.+ {currentModel?.samplerNote+ || `Lightning keeps its validated ${currentModel.steps}-step sampler, CFG ${currentModel.guidance}, and model-specific schedule locked.`}</p>)}@@ -229,17 +234,19 @@ export default function AdvancedParamsPanel({</div>)}- <FormField className="col-span-2 sm:col-span-3" label="Tiling" labelClassName="block text-xs font-medium text-gray-400 mb-1">- <select- value={tiling}- onChange={(e) => onTilingChange(e.target.value)}- className={inputCls}- >- {VIDEO_TILING_OPTIONS.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}- </select>- </FormField>+ {currentModel?.supportsTiling !== false && (+ <FormField className="col-span-2 sm:col-span-3" label="Tiling" labelClassName="block text-xs font-medium text-gray-400 mb-1">+ <select+ value={tiling}+ onChange={(e) => onTilingChange(e.target.value)}+ className={inputCls}+ >+ {VIDEO_TILING_OPTIONS.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}+ </select>+ </FormField>+ )}- {showAudioFlags && (+ {showModelAudioControls && (<label className="col-span-2 sm:col-span-3 flex items-center gap-2 text-xs text-gray-400 cursor-pointer"><inputtype="checkbox"@@ -250,7 +257,7 @@ export default function AdvancedParamsPanel({Disable audio (LTX-2 only — speeds up generation)</label>)}- {showAudioFlags && (+ {showModelAudioControls && (<labelclassName={`col-span-2 sm:col-span-3 flex items-center gap-2 text-xs cursor-pointer ${disableAudio ? 'text-gray-600 cursor-not-allowed' : 'text-gray-400'}`}title="LTX-2 conditions audio on the prompt — appending 'no music, no soundtrack' at submit time pushes the model toward ambient/diegetic sound only"diff --git a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx b/client/src/components/videoGen/AdvancedParamsPanel.test.jsxindex 9c8b1d4d36..ad6943d69f 100644--- a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx+++ b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx@@ -142,6 +142,28 @@ describe('AdvancedParamsPanel', () => {expect(screen.getByLabelText(/No music/).disabled).toBe(true);});+ it('hides LTX audio controls and Extend advice for a text-only joint-A/V model', () => {+ renderPanel({+ numFrames: 362,+ currentModel: {+ runtime: 'minimax_h3',+ supportedModes: ['text'],+ frameOptions: [124, 243, 362],+ supportsDisableAudio: false,+ },+ });+ fireEvent.click(toggle());+ expect(screen.queryByText(/Disable audio/)).toBeNull();+ expect(screen.queryByText(/No music/)).toBeNull();+ expect(screen.queryByText(/use Extend/i)).toBeNull();+ });++ it('keeps the long-render Extend guidance for models that support Extend', () => {+ renderPanel({ numFrames: 313, currentModel: { runtime: 'ltx2' } });+ fireEvent.click(toggle());+ expect(screen.getByText(/Past 241 frames/i)).toBeInTheDocument();+ });+describe('per-chunk prompt beats (#3695)', () => {it('hides the beat editor when the request does not chain', () => {renderPanel({ chunks: 4, chainingActive: false });diff --git a/client/src/components/videoGen/ModelDisclosure.jsx b/client/src/components/videoGen/ModelDisclosure.jsxindex cfabe8d0f0..f834748e90 100644--- a/client/src/components/videoGen/ModelDisclosure.jsx+++ b/client/src/components/videoGen/ModelDisclosure.jsx@@ -14,7 +14,7 @@//// It is deliberately NOT part of `ModelSelect` — that component selects models// and must stay a plain picker.-import { ExternalLink, Server, Cloud } from 'lucide-react';+import { ExternalLink, Server, Cloud, ShieldAlert, CheckCircle } from 'lucide-react';const UNKNOWN = 'Unknown';@@ -77,7 +77,15 @@ function MemoryFact({ model, systemMemoryGb }) {);}-export default function ModelDisclosure({ backend = 'local', backendDisclosures, model, systemMemoryGb }) {+export default function ModelDisclosure({+ backend = 'local',+ backendDisclosures,+ model,+ systemMemoryGb,+ termsAccepted = false,+ onTermsAcceptedChange,+ termsDescriptionId,+}) {const list = Array.isArray(backendDisclosures) ? backendDisclosures : [];const backendInfo = list.find((b) => b?.id === backend) || null;const hosted = backendInfo?.execution === 'hosted';@@ -85,6 +93,9 @@ export default function ModelDisclosure({ backend = 'local', backendDisclosures,// provider picks the model, so showing local model facts would be wrong.const showModelFacts = !hosted && !!model;const disclosure = model?.disclosure && typeof model.disclosure === 'object' ? model.disclosure : null;+ const termsGate = showModelFacts && model?.termsGate && typeof model.termsGate === 'object'+ ? model.termsGate+ : null;if (!backendInfo && !showModelFacts) return null;@@ -93,7 +104,45 @@ export default function ModelDisclosure({ backend = 'local', backendDisclosures,: null;return (- <details className="bg-port-card border border-port-border rounded-xl overflow-hidden">+ <div className="space-y-2">+ {termsGate && (+ <section+ id={termsDescriptionId}+ aria-label="Model terms acceptance"+ className={`rounded-xl border px-3 py-3 text-xs ${termsAccepted+ ? 'border-port-success/40 bg-port-success/10 text-gray-300'+ : 'border-port-warning/50 bg-port-warning/10 text-port-warning'}`}+ >+ <div className="flex items-start gap-2">+ {termsAccepted+ ? <CheckCircle className="w-4 h-4 mt-0.5 shrink-0 text-port-success" aria-hidden="true" />+ : <ShieldAlert className="w-4 h-4 mt-0.5 shrink-0" aria-hidden="true" />}+ <div className="min-w-0 space-y-1.5">+ <p className="font-semibold text-gray-200">{termsGate.title || 'Model terms required'}</p>+ <p className="leading-snug">{termsGate.summary}</p>+ {termsGate.licenseUrl && (+ <p>+ <FactLink href={termsGate.licenseUrl}>Read the Community License and Acceptable Use Policy</FactLink>+ </p>+ )}+ <label className="flex items-start gap-2 text-gray-200 cursor-pointer">+ <input+ type="checkbox"+ checked={termsAccepted}+ onChange={(event) => onTermsAcceptedChange?.(event.target.checked)}+ className="mt-0.5 rounded"+ />+ <span>{termsGate.acknowledgement}</span>+ </label>+ <p className="text-[10px] text-gray-500">+ PortOS cannot determine your location or legal eligibility. Do not accept if this statement is not true.+ </p>+ </div>+ </div>+ </section>+ )}++ <details className="bg-port-card border border-port-border rounded-xl overflow-hidden"><summary className="cursor-pointer list-none px-3 py-2 text-[11px] text-gray-400 flex flex-wrap items-center gap-x-2 gap-y-1 hover:text-gray-200">{hosted? <Cloud className="w-3.5 h-3.5 shrink-0 text-port-warning" aria-hidden="true" />@@ -156,6 +205,7 @@ export default function ModelDisclosure({ backend = 'local', backendDisclosures,</section>)}</div>- </details>+ </details>+ </div>);}diff --git a/client/src/components/videoGen/ModelDisclosure.test.jsx b/client/src/components/videoGen/ModelDisclosure.test.jsxindex bc7bdc2656..8c33c02ab5 100644--- a/client/src/components/videoGen/ModelDisclosure.test.jsx+++ b/client/src/components/videoGen/ModelDisclosure.test.jsx@@ -1,5 +1,5 @@-import { describe, it, expect } from 'vitest';-import { render, screen, within } from '@testing-library/react';+import { describe, it, expect, vi } from 'vitest';+import { fireEvent, render, screen, within } from '@testing-library/react';import ModelDisclosure from './ModelDisclosure.jsx';const BACKENDS = [@@ -133,4 +133,32 @@ describe('ModelDisclosure', () => {const { container: empty } = render(<ModelDisclosure backend="grok" backendDisclosures={[]} model={null} />);expect(empty.querySelector('details')).toBeNull();});++ it('renders and controls a restricted model terms gate', () => {+ const onChange = vi.fn();+ const restricted = {+ ...SHIPPED_MODEL,+ termsGate: {+ id: 'example-license-v1',+ title: 'Territory and terms',+ summary: 'This model is available only in its applicable territory.',+ acknowledgement: 'I confirm I am eligible and accept the license.',+ licenseUrl: 'https://example.com/license',+ },+ };+ renderDisclosure({+ backend: 'local',+ model: restricted,+ termsAccepted: false,+ onTermsAcceptedChange: onChange,+ termsDescriptionId: 'model-terms',+ });+ const gate = screen.getByLabelText('Model terms acceptance');+ expect(gate).toHaveAttribute('id', 'model-terms');+ expect(within(gate).getByText(/cannot determine your location or legal eligibility/i)).toBeInTheDocument();+ expect(within(gate).getByRole('link', { name: /Community License/i }))+ .toHaveAttribute('href', 'https://example.com/license');+ fireEvent.click(within(gate).getByRole('checkbox'));+ expect(onChange).toHaveBeenCalledWith(true);+ });});diff --git a/client/src/components/videoGen/ModelRepairBanner.jsx b/client/src/components/videoGen/ModelRepairBanner.jsxindex 7e76a572f5..f158b1f0d2 100644--- a/client/src/components/videoGen/ModelRepairBanner.jsx+++ b/client/src/components/videoGen/ModelRepairBanner.jsx@@ -6,7 +6,7 @@ import { AlertTriangle, RefreshCw } from 'lucide-react';// Repair affordance keyed on the cheap structural check the status poll already// ran. `message` is the case-specific copy; `onRepair`/`onDismiss` and the// button label/disabled/spinner state come from the caller.-export default function ModelRepairBanner({ message, repairLabel, onRepair, onDismiss, disabled, repairing }) {+export default function ModelRepairBanner({ message, repairLabel, onRepair, onDismiss, disabled, repairing, disabledReasonId }) {return (<div className="rounded-lg border border-port-error/40 bg-port-error/10 px-3 py-3 text-xs text-port-error flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2"><div className="flex items-start gap-2">@@ -18,6 +18,7 @@ export default function ModelRepairBanner({ message, repairLabel, onRepair, onDitype="button"onClick={onRepair}disabled={disabled}+ aria-describedby={disabled ? disabledReasonId : undefined}className="whitespace-nowrap inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-error text-white text-xs font-medium hover:bg-port-error/80 disabled:opacity-50"><RefreshCw className={`w-3.5 h-3.5 ${repairing ? 'animate-spin' : ''}`} />diff --git a/client/src/hooks/useModelDownloadStatus.js b/client/src/hooks/useModelDownloadStatus.jsindex 6934297e4d..374103f0eb 100644--- a/client/src/hooks/useModelDownloadStatus.js+++ b/client/src/hooks/useModelDownloadStatus.js@@ -19,13 +19,16 @@ 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.-const buildDownloadUrl = (kind, modelId, force = false) => {+export const buildDownloadUrl = (kind, modelId, force = false, termsAcceptance = null) => {if (!modelId) return null;// A repair-initiated re-download appends `?force=1` so the server re-fetches// even when the repo still looks cached — repairModelCache() deleted the bad// file(s), but a multi-shard repo's surviving shards otherwise mask the gap// and the deleted shard would never be pulled back.- const q = force ? '?force=1' : '';+ const params = new URLSearchParams();+ if (force) params.set('force', '1');+ if (termsAcceptance) params.set('termsAcceptance', termsAcceptance);+ const q = params.size > 0 ? `?${params.toString()}` : '';if (kind === 'video' && modelId === TEXT_ENCODER_DOWNLOAD_ID) {return `/api/video-gen/text-encoder/download${q}`;}@@ -53,6 +56,7 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {// True only for a repair-initiated re-download — appends `?force=1` so the// server re-fetches a repo whose surviving shards still read as cached.const [forceDownload, setForceDownload] = useState(false);+ const [termsAcceptance, setTermsAcceptance] = useState(null);const fetchStatuses = useCallback(async () => {setLoading(true);@@ -84,7 +88,7 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {// EventSource for the active download. `null` URL = idle (useSseProgress's// `enabled: false` cleanup tears the connection down on cancel).- const downloadUrl = buildDownloadUrl(kind, activeModelId, forceDownload);+ const downloadUrl = buildDownloadUrl(kind, activeModelId, forceDownload, termsAcceptance);const sse = useSseProgress(downloadUrl, { enabled: !!downloadUrl });// Refetch on natural stream close. useSseProgress flips `closed:true` once@@ -111,12 +115,14 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {setActiveModelId(null);activeModelIdRef.current = null;setForceDownload(false);+ setTermsAcceptance(null);}}, [sse.closed, sse.latest, fetchStatuses]);- const start = useCallback((modelId, { force = false } = {}) => {+ const start = useCallback((modelId, { force = false, termsAcceptance: acceptedTerms = null } = {}) => {setLastError(null);setForceDownload(force);+ setTermsAcceptance(acceptedTerms);activeModelIdRef.current = modelId;setActiveModelId(modelId);}, []);@@ -142,7 +148,7 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {// on completion come for free). `repairing` gates the button while the// deletion request is in flight.const [repairing, setRepairing] = useState(false);- const repair = useCallback(async (modelId, { deep = false } = {}) => {+ const repair = useCallback(async (modelId, { deep = false, termsAcceptance: acceptedTerms = null } = {}) => {if (!modelId) return;setRepairing(true);// The shared text encoder isn't a model id, so its repair hits the scalar@@ -163,7 +169,7 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {// Force the re-download: repair deleted the bad file(s), but a multi-shard// repo's surviving shards keep it reading as cached, so a non-forced pull// would skip the deleted shard.- if (result) start(modelId, { force: true });+ if (result) start(modelId, { force: true, termsAcceptance: acceptedTerms });return result;}, [kind, start]);@@ -177,6 +183,7 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {setActiveModelId(null);activeModelIdRef.current = null;setForceDownload(false);+ setTermsAcceptance(null);fetchStatuses();}, [sse, fetchStatuses]);diff --git a/client/src/hooks/useModelDownloadStatus.test.js b/client/src/hooks/useModelDownloadStatus.test.jsnew file mode 100644index 0000000000..362091e7f8--- /dev/null+++ b/client/src/hooks/useModelDownloadStatus.test.js@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';+import { buildDownloadUrl, TEXT_ENCODER_DOWNLOAD_ID } from './useModelDownloadStatus.js';++describe('buildDownloadUrl', () => {+ it('carries the exact terms key on a model download', () => {+ expect(buildDownloadUrl(+ 'video',+ 'minimax_h3_8bit',+ false,+ 'minimax-h3-community-license-2026-08-02',+ )).toBe('/api/video-gen/models/minimax_h3_8bit/download?termsAcceptance=minimax-h3-community-license-2026-08-02');+ });++ it('combines repair and acceptance query parameters without changing special routes', () => {+ expect(buildDownloadUrl('video', 'minimax_h3_8bit', true, 'license v1')).toBe(+ '/api/video-gen/models/minimax_h3_8bit/download?force=1&termsAcceptance=license+v1',+ );+ expect(buildDownloadUrl('video', TEXT_ENCODER_DOWNLOAD_ID, true)).toBe(+ '/api/video-gen/text-encoder/download?force=1',+ );+ });+});diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.jsindex f91d94528e..04da0a6008 100644--- a/client/src/hooks/useVideoGenForm.js+++ b/client/src/hooks/useVideoGenForm.js@@ -12,6 +12,7 @@ import { VIDEO_TILING_ENUM_SET } from '../lib/videoTilingOptions';import {VIDEO_EDGE_BOUNDS, MAX_CHUNKS,videoModelMemoryGb, computeFflfSafeFrames, isModelAllowedForMode,+ supportsVideoAudioControls,normalizeFramesForModel, normalizeFpsForModel,icLoraSpecForMode, icResolutionIssue,} from '../lib/videoGenParams.js';@@ -966,8 +967,8 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })|| currentModel?.runtime !== 'ltx2'|| !!icResolutionIssue(icSpec, width, height));- const modelSupportsChaining = currentModel?.runtime !== 'wan22'- || currentModel?.supportedModes?.includes('image');+ const modelSupportsChaining = !Array.isArray(currentModel?.supportedModes)+ || currentModel.supportedModes.includes('image');// The single predicate for "this request really chains" — keyframes, IC// references and a2v each anchor a SINGLE clip, so the route pins them to one// chunk (KEYFRAMES_CHUNKS_CONFLICT / IC_LORA_CHUNKS_CONFLICT). Derived once so@@ -1003,7 +1004,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })// Idempotent on "no music": if the text already says it, don't double-append.const withEnvelope = (text) => {const c = composeStyledPrompt(text, negativePrompt, stylePreset);- return (noMusic && !disableAudio && !/no music/i.test(c.prompt))+ return (supportsVideoAudioControls(currentModel) && noMusic && !disableAudio && !/no music/i.test(c.prompt))? `${c.prompt}\n\nno music, no soundtrack`: c.prompt;};@@ -1045,7 +1046,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })// pinned grok backend behind the UI's back.backend: 'local',prompt: promptOut,- negativePrompt: composed.negativePrompt,+ negativePrompt: currentModel?.supportsNegativePrompt === false ? '' : composed.negativePrompt,modelId,// Clamp/floor to the runner's edge bounds so a transient 0 (field cleared// mid-edit) or off-grid value can't 400 the server — mirrors ImageGen's@@ -1057,8 +1058,8 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })steps: steps || '',guidanceScale: guidanceScale || '',seed: seed || '',- tiling,- disableAudio: disableAudio ? 'true' : 'false',+ tiling: currentModel?.supportsTiling === false ? 'auto' : tiling,+ disableAudio: supportsVideoAudioControls(currentModel) ? (disableAudio ? 'true' : 'false') : 'false',mode,imageStrength: imageStrength || '',// ltx2-extend bypasses the last-frame i2v path: we send the sourcediff --git a/client/src/hooks/useVideoGenForm.test.jsx b/client/src/hooks/useVideoGenForm.test.jsxindex 432977c161..cb59d5182a 100644--- a/client/src/hooks/useVideoGenForm.test.jsx+++ b/client/src/hooks/useVideoGenForm.test.jsx@@ -17,6 +17,11 @@ const LTX2 = { id: 'ltx2-model', name: 'LTX-2.3', runtime: 'ltx2' };const MLX = { id: 'mlx-model', name: 'LTX distilled', runtime: 'mlx_video' };const WAN_T2V = { id: 'wan-t2v', name: 'Wan T2V', runtime: 'wan22', supportedModes: ['text'], frameStride: 4 };const WAN_TI2V = { id: 'wan-ti2v', name: 'Wan TI2V', runtime: 'wan22', supportedModes: ['text', 'image'], frameStride: 4 };+const H3 = {+ id: 'minimax-h3', name: 'MiniMax H3', runtime: 'minimax_h3', supportedModes: ['text'],+ frameOptions: [124, 141, 158], fpsOptions: [24], defaultFrames: 124,+ supportsNegativePrompt: false, supportsTiling: false, supportsDisableAudio: false,+};const MODELS = [MLX, LTX2];const STATUS = { connected: true, defaultModel: MLX.id };@@ -191,6 +196,42 @@ describe('useVideoGenForm', () => {expect(result.current.buildGeneratePayload().chunks).toBe('');});+ it('normalizes MiniMax H3 to its text-only temporal and sampler contract', async () => {+ const { result } = render({+ models: [MLX, H3],+ status: { connected: true, defaultModel: MLX.id },+ });+ await waitFor(() => expect(result.current.modelId).toBe(MLX.id));+ act(() => {+ result.current.setPrompt('a fox watches the rain');+ result.current.setNegativePrompt('blurry');+ result.current.setNumFrames(129);+ result.current.setFps(30);+ result.current.setChunks(3);+ result.current.setTiling('full');+ result.current.setDisableAudio(true);+ result.current.setNoMusic(true);+ result.current.handleModelChange(H3.id);+ });+ await waitFor(() => expect(result.current.modelId).toBe(H3.id));+ await waitFor(() => expect(result.current.numFrames).toBe(124));++ expect(result.current.mode).toBe('text');+ expect(result.current.chainingActive).toBe(false);+ const payload = result.current.buildGeneratePayload();+ expect(payload).toMatchObject({+ modelId: H3.id,+ mode: 'text',+ negativePrompt: '',+ numFrames: 124,+ fps: 24,+ chunks: '',+ tiling: 'auto',+ disableAudio: 'false',+ });+ expect(payload.prompt).toBe('a fox watches the rain');+ });+describe('per-chunk prompt beats (#3695)', () => {const chained = async (count = 3) => {const { result } = render();diff --git a/client/src/lib/videoGenParams.js b/client/src/lib/videoGenParams.jsindex 68cf5495db..8529242491 100644--- a/client/src/lib/videoGenParams.js+++ b/client/src/lib/videoGenParams.js@@ -23,14 +23,19 @@ export const WAN_FRAME_OPTIONS = [...new Set([])].sort((a, b) => a - b);export const isValidFrameCountForModel = (value, model) => {- const stride = Number(model?.frameStride);const frames = Number(value);+ if (Array.isArray(model?.frameOptions) && model.frameOptions.length > 0) {+ return Number.isInteger(frames) && model.frameOptions.includes(frames);+ }+ const stride = Number(model?.frameStride);return Number.isInteger(frames) && frames > 0&& Number.isFinite(stride) && stride > 0&& (frames - 1) % stride === 0;};export const frameOptionsForModel = (model, currentValue = null) => {- const options = Number(model?.frameStride) === 4 ? WAN_FRAME_OPTIONS : FRAME_OPTIONS;+ const options = Array.isArray(model?.frameOptions) && model.frameOptions.length > 0+ ? model.frameOptions+ : Number(model?.frameStride) === 4 ? WAN_FRAME_OPTIONS : FRAME_OPTIONS;const frames = Number(currentValue);return isValidFrameCountForModel(frames, model) && !options.includes(frames)? [...options, frames].sort((a, b) => a - b)@@ -48,6 +53,12 @@ export const normalizeFramesForModel = (value, model) => isValidFrameCountForMod: nearestOption(value, frameOptionsForModel(model));export const normalizeFpsForModel = (value, model) => nearestOption(value, fpsOptionsForModel(model));+// One capability predicate for both the Advanced audio controls and prompt+// shaping. A model that cannot disable its jointly-generated audio (MiniMax+// H3) also cannot honor LTX's "No music" prompt-envelope control; hidden state+// must never continue altering the payload after a model switch.+export const supportsVideoAudioControls = (model) => model?.supportsDisableAudio !== false;+// Per-edge bounds for video: mirrors the videoGen route (64..2048) and the// server's floor-to-multiple-of-64 (generateVideo in local.js). Shared by the// ResolutionField control and the submit-time clamp so a hand-typed / mid-edit@@ -162,7 +173,7 @@ export const icResolutionIssue = (spec, width, height) => {export const isModelAllowedForMode = (model, mode) => {if (!model) return false;if (mode === 'a2v' || isIcLoraMode(mode)) return model.runtime === 'ltx2';- if (model.runtime === 'wan22') {+ if (Array.isArray(model.supportedModes) && model.supportedModes.length > 0) {return Array.isArray(model.supportedModes) && model.supportedModes.includes(mode);}return true;diff --git a/client/src/lib/videoGenParams.test.js b/client/src/lib/videoGenParams.test.jsindex c518d1e609..d9b5b1b6a0 100644--- a/client/src/lib/videoGenParams.test.js+++ b/client/src/lib/videoGenParams.test.js@@ -4,6 +4,7 @@ import {VIDEO_EDGE_BOUNDS, FRAME_OPTIONS, FPS_OPTIONS,WAN_FRAME_OPTIONS, frameOptionsForModel, fpsOptionsForModel,normalizeFramesForModel, normalizeFpsForModel,+ supportsVideoAudioControls,IC_LORA_MODES, IC_LORA_MODE_VALUES, isIcLoraMode, icLoraSpecForMode,icResolutionIssue,} from './videoGenParams.js';@@ -63,6 +64,12 @@ describe('isModelAllowedForMode', () => {expect(isModelAllowedForMode(i2v, 'image')).toBe(true);expect(isModelAllowedForMode(ti2v, 'fflf')).toBe(false);});+ it('filters any model with an explicit supportedModes contract', () => {+ const h3 = { runtime: 'minimax_h3', supportedModes: ['text'] };+ expect(isModelAllowedForMode(h3, 'text')).toBe(true);+ expect(isModelAllowedForMode(h3, 'image')).toBe(false);+ expect(isModelAllowedForMode(h3, 'fflf')).toBe(false);+ });it('requires the ltx2 runtime for a2v', () => {expect(isModelAllowedForMode({ runtime: 'ltx2' }, 'a2v')).toBe(true);expect(isModelAllowedForMode({ runtime: 'mlx_video' }, 'a2v')).toBe(false);@@ -89,6 +96,17 @@ describe('constants', () => {expect(normalizeFramesForModel(98, wan)).toBe(97);expect(normalizeFpsForModel(30, wan)).toBe(24);});+ it('uses an explicit model frame list and fixed fps for MiniMax H3', () => {+ const h3 = { frameOptions: [124, 141, 158], fpsOptions: [24] };+ expect(frameOptionsForModel(h3)).toEqual([124, 141, 158]);+ expect(frameOptionsForModel(h3, 175)).toEqual([124, 141, 158]);+ expect(normalizeFramesForModel(140, h3)).toBe(141);+ expect(normalizeFpsForModel(30, h3)).toBe(24);+ });+ it('uses one explicit capability for visible and submitted audio controls', () => {+ expect(supportsVideoAudioControls({ runtime: 'mlx_video' })).toBe(true);+ expect(supportsVideoAudioControls({ supportsDisableAudio: false })).toBe(false);+ });});describe('IC-LoRA remix modes (#3100)', () => {diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex a03ed67cc3..ff2db6b4cb 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -89,6 +89,7 @@ import { GROK_VIDEO_DURATIONS, GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokViimport ResolutionField from '../components/media/ResolutionField';import { VIDEO_EDGE_BOUNDS, IC_LORA_MODES } from '../lib/videoGenParams.js';import { finishTargetForRecord } from '../lib/videoFinish.js';+import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';const MODES = [{ id: 'text', label: 'Text', icon: Type, desc: 'Text-to-video' },@@ -165,6 +166,31 @@ export default function VideoGen() {applyRemix, applyFinish, applyResumedParams, buildGeneratePayload,} = useVideoGenForm({ models, status, availableLoras, grokEnabled });+ // Restricted model terms are accepted per exact reviewed license id. Keep+ // the convenience bit in guarded localStorage, but send the versioned id on+ // every download/generation request so the server enforces the same gate.+ const termsGate = !isGrok && currentModel?.termsGate ? currentModel.termsGate : null;+ const [acceptedTermsId, setAcceptedTermsId] = useState(null);+ useEffect(() => {+ const key = termsGate?.id ? `video-gen:terms:${termsGate.id}` : null;+ setAcceptedTermsId(key && safeReadStorage(key) === '1' ? termsGate.id : null);+ }, [termsGate?.id]);+ // Key state by the accepted license, not a shared boolean. That makes a+ // model switch fail closed during the effect boundary: acceptance for one+ // terms id can never be momentarily applied to another id.+ const termsAccepted = !!termsGate?.id && acceptedTermsId === termsGate.id;+ const handleTermsAcceptedChange = (accepted) => {+ setAcceptedTermsId(accepted ? termsGate?.id || null : null);+ if (termsGate?.id) safeWriteStorage(`video-gen:terms:${termsGate.id}`, accepted ? '1' : '0');+ };+ const termsGateBlocked = !!termsGate && !termsAccepted;+ const termsDescriptionId = termsGate ? 'video-model-terms-requirement' : undefined;+ const acceptedTermsKey = termsGate && termsAccepted ? termsGate.id : null;+ const buildAcceptedGeneratePayload = () => ({+ ...buildGeneratePayload(),+ ...(acceptedTermsKey ? { termsAcceptance: acceptedTermsKey } : {}),+ });+// Image gallery — used by both the start and end frame pickers so the// user can pull from any prior render in either slot.const [imageGallery, setImageGallery] = useState([]);@@ -567,8 +593,8 @@ export default function VideoGen() {// Without these guards the user could press Enter in the prompt// textarea and fire a request the disabled button would otherwise// have prevented.- if (!prompt.trim() || generating || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || weightsGateBlocked || keyframesBlocked))) return;- await runGeneration(buildGeneratePayload()).catch(() => {});+ if (!prompt.trim() || generating || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || weightsGateBlocked || keyframesBlocked || termsGateBlocked))) return;+ await runGeneration(buildAcceptedGeneratePayload()).catch(() => {});};const handleEnqueue = () => {@@ -576,10 +602,10 @@ export default function VideoGen() {// would silently queue a doomed job that fails late in the worker with// VENV_MISSING, hiding the installer banner from the user. Block at// enqueue time so the only path forward is the install banner above.- if (!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || weightsGateBlocked || keyframesBlocked))) return;+ if (!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || weightsGateBlocked || keyframesBlocked || termsGateBlocked))) return;// useVideoGenQueue strips the File blobs into `_blobs` and snapshots the// rest as a stable summary for the queue UI.- enqueue(buildGeneratePayload());+ enqueue(buildAcceptedGeneratePayload());};const handleCancel = async () => {@@ -621,7 +647,7 @@ export default function VideoGen() {const canEnqueue = prompt.trim() && (isGrok || (!notConnected && !extendModeBlocked&& !a2vModeBlocked && !icLoraModeBlocked && !byovGateBlocked- && !weightsGateBlocked && !keyframesBlocked));+ && !weightsGateBlocked && !keyframesBlocked && !termsGateBlocked));return (<div className="space-y-3">@@ -767,9 +793,13 @@ export default function VideoGen() {Repair deletes the bad file{integrityBadCount === 1 ? '' : 's'} and re-downloads clean copies.</>}repairLabel="Repair model"- onRepair={() => { setDismissedIntegrityKey(integrityKey); modelDownload.repair(modelId); }}+ onRepair={() => {+ setDismissedIntegrityKey(integrityKey);+ modelDownload.repair(modelId, { termsAcceptance: acceptedTermsKey });+ }}onDismiss={() => setDismissedIntegrityKey(integrityKey)}- disabled={modelDownload.repairing || modelDownload.downloading}+ disabled={termsGateBlocked || modelDownload.repairing || modelDownload.downloading}+ disabledReasonId={termsGateBlocked ? termsDescriptionId : undefined}repairing={modelDownload.repairing}/>)}@@ -818,9 +848,12 @@ export default function VideoGen() {<textareavalue={negativePrompt}onChange={(e) => setNegativePrompt(e.target.value)}+ disabled={!isGrok && currentModel?.supportsNegativePrompt === false}rows={3}className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y"- placeholder="What to avoid..."+ placeholder={!isGrok && currentModel?.supportsNegativePrompt === false+ ? 'This CFG-distilled model does not use a negative prompt.'+ : 'What to avoid...'}/></FormField></div>@@ -963,9 +996,12 @@ export default function VideoGen() {{modelStatus && (<ModelDownloadBadgestatus={modelStatus}- onDownload={() => modelDownload.start(modelId)}+ onDownload={() => modelDownload.start(modelId, { termsAcceptance: acceptedTermsKey })}onCancel={modelDownload.cancel}estimateLabel={deriveSizeEstimate(currentModel?.name)}+ disabled={termsGateBlocked}+ disabledReason="Accept the selected model's eligibility and license terms below before downloading."+ disabledReasonId={termsDescriptionId}/>)}{activeWeightError && (@@ -1055,15 +1091,17 @@ export default function VideoGen() {</div>)}- {/* Provenance / licensing / policy-scope disclosure for the selected- backend + model (#3674). Sits directly below the backend and model- controls and updates with them; purely informational — it never- gates or alters a render. */}+ {/* Provenance / licensing / policy scope for the selected backend ++ model (#3674). Restricted models also render their explicit,+ server-enforced terms gate here before Advanced / Generate. */}<ModelDisclosurebackend={backend}backendDisclosures={status?.backendDisclosures}model={isGrok ? null : currentModel}systemMemoryGb={status?.systemMemoryGb}+ termsAccepted={termsAccepted}+ onTermsAcceptedChange={handleTermsAcceptedChange}+ termsDescriptionId={termsDescriptionId}/>{/* Sampler/output knobs live behind a closed-by-default disclosure so@@ -1099,11 +1137,13 @@ export default function VideoGen() {) : (<buttontype="submit"- disabled={!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || weightsGateBlocked || keyframesBlocked))}+ disabled={!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || weightsGateBlocked || keyframesBlocked || termsGateBlocked))}+ aria-describedby={termsGateBlocked ? termsDescriptionId : undefined}className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"title={byovRuntimeMissing ? `${byovStatus?.label || byovRuntime} runtime is not installed — use the install banner above`: byovGateBlocked ? `Checking ${byovRuntime} runtime status…`+ : 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': icWeightsBlocked ? `Download the ${icSpec?.label || 'IC-LoRA'} weight before generating`@@ -1122,9 +1162,11 @@ export default function VideoGen() {type="button"onClick={handleEnqueue}disabled={!canEnqueue}+ aria-describedby={termsGateBlocked ? termsDescriptionId : undefined}className="flex items-center gap-2 px-4 py-2 border border-port-border text-gray-200 hover:text-white hover:bg-port-border/40 disabled:opacity-50 disabled:cursor-not-allowed text-sm font-medium rounded-lg min-h-[40px]"title={canEnqueue ? 'Add this configuration to the batch queue': icWeightsBlocked ? `Download the ${icSpec?.label || 'IC-LoRA'} weight before queueing`+ : termsGateBlocked ? 'Confirm the selected model eligibility and license terms above before queueing': weightsGateBlocked ? 'Finish required model downloads before queueing': 'Complete the required inputs before queueing'}>diff --git a/client/src/pages/VideoGen.terms.test.jsx b/client/src/pages/VideoGen.terms.test.jsxnew file mode 100644index 0000000000..1235a85116--- /dev/null+++ b/client/src/pages/VideoGen.terms.test.jsx@@ -0,0 +1,241 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++const TERMS_ONE = 'minimax-h3-license-v1';+const TERMS_TWO = 'minimax-h3-license-v2';+const model = (id, termsId) => ({+ id,+ name: `MiniMax ${id}`,+ repo: `example-org/${id}`,+ revision: '1111111111111111111111111111111111111111',+ runtime: 'minimax_h3',+ supportedModes: ['text'],+ defaultFrames: 124,+ frameOptions: [124, 141],+ fpsOptions: [24],+ steps: 8,+ guidance: 0,+ samplerLocked: true,+ supportsNegativePrompt: false,+ supportsTiling: false,+ supportsDisableAudio: false,+ termsGate: {+ id: termsId,+ title: `Terms for ${id}`,+ summary: 'This model is available only in its applicable territory.',+ acknowledgement: `I am eligible and accept ${termsId}.`,+ licenseUrl: 'https://example.com/license',+ },+});+const H3_ONE = model('h3-one', TERMS_ONE);+const H3_TWO = model('h3-two', TERMS_TWO);++const state = vi.hoisted(() => ({+ modelStatuses: {},+ generateVideo: vi.fn(),+ startDownload: vi.fn(),+ repairModel: vi.fn(),+ enqueue: vi.fn(),+ attach: vi.fn(),+ eventSourceRef: { current: null },+}));++vi.mock('../services/api', () => ({+ getVideoGenStatus: vi.fn(async () => ({+ connected: true,+ pythonPath: '/opt/example/python3',+ defaultModel: 'h3-one',+ models: [H3_ONE, H3_TWO],+ byovRuntimes: [],+ systemMemoryGb: 128,+ backendDisclosures: [],+ })),+ generateVideo: (...args) => state.generateVideo(...args),+ cancelVideoGen: vi.fn(async () => ({})),+ listVideoHistory: vi.fn(async () => []),+ deleteVideoHistoryItem: vi.fn(async () => ({})),+ setVideoHidden: vi.fn(async () => ({})),+ extractLastFrame: vi.fn(async () => ({})),+ upscaleVideo: vi.fn(async () => ({})),+ listImageGallery: vi.fn(async () => []),+ patchSettingsSlice: vi.fn(async () => ({})),+ getActiveVideoJob: vi.fn(async () => ({ activeJob: null })),+ getSettings: vi.fn(async () => ({ imageGen: { grok: { enabled: false } } })),+ getVideoGenRuntimeStatus: vi.fn(async () => ({ installed: true, ready: true, current: true })),+ listLorasFull: vi.fn(async () => []),+}));++vi.mock('../hooks/useModelDownloadStatus', () => ({+ TEXT_ENCODER_DOWNLOAD_ID: '__text_encoder__',+ useModelDownloadStatus: () => ({+ extra: {},+ loading: false,+ statusError: null,+ activeModelId: null,+ progress: null,+ lastError: null,+ downloading: false,+ repairing: false,+ getStatus: (id) => state.modelStatuses[id] || null,+ start: state.startDownload,+ cancel: vi.fn(),+ repair: state.repairModel,+ refresh: vi.fn(),+ }),+}));++vi.mock('../hooks/useMediaJobSse', () => ({+ useMediaJobSse: () => ({ attach: state.attach, eventSourceRef: state.eventSourceRef }),+}));+vi.mock('../hooks/useMediaCompletionRefresh', () => ({ useMediaCompletionRefresh: vi.fn() }));+vi.mock('../hooks/useMediaAnnotations', () => ({+ useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: vi.fn(), getCardProps: vi.fn(() => ({})) }),+}));+vi.mock('../hooks/usePreviewRoute', () => ({ default: () => [null, vi.fn()] }));+vi.mock('../hooks/useVideoGenQueue.js', () => ({+ useVideoGenQueue: () => ({+ queue: [],+ enqueue: state.enqueue,+ removeFromQueue: vi.fn(),+ clearFinishedQueue: vi.fn(),+ cancelRunning: vi.fn(),+ }),+}));+vi.mock('../components/ui/Toast', () => ({+ default: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), loading: vi.fn() }),+}));++// Keep the policy-bearing controls real; replace unrelated, heavyweight page+// surfaces so this is a focused orchestration test rather than a gallery/SSE+// integration suite.+vi.mock('../components/Drawer', () => ({ default: () => null }));+vi.mock('../components/settings/ImageGenTab', () => ({ ImageGenTab: () => null }));+vi.mock('../components/settings/LocalSetupPanel', () => ({ default: () => null }));+vi.mock('../components/install/RuntimeInstallModal', () => ({ default: () => null }));+vi.mock('../components/videoGen/FramePanel', () => ({ default: () => null }));+vi.mock('../components/videoGen/KeyframePanel', () => ({ default: () => null }));+vi.mock('../components/videoGen/AudioPanel', () => ({ default: () => null }));+vi.mock('../components/videoGen/ExtendPanel', () => ({ default: () => null }));+vi.mock('../components/videoGen/IcLoraPanel', () => ({ default: () => null }));+vi.mock('../components/videoGen/AdvancedParamsPanel', () => ({ default: () => null }));+vi.mock('../components/videoGen/RuntimeFingerprint', () => ({ default: () => null }));+vi.mock('../components/videoGen/VideoPreviewPanel', () => ({ default: () => null }));+vi.mock('../components/videoGen/VideoGenGallery', () => ({ default: () => null }));+vi.mock('../components/media/MediaPreview', () => ({ default: () => null }));+vi.mock('../components/media/StylePresetPicker', () => ({ default: () => null }));+vi.mock('../components/media/BatchQueuePanel', () => ({ default: () => null }));+vi.mock('../components/media/MediaJobsQueue', () => ({ default: () => null }));+vi.mock('../components/imageGen/LoraPicker', () => ({ default: () => null }));+vi.mock('../components/media/ResolutionField', () => ({ default: () => null }));++const { default: VideoGen } = await import('./VideoGen.jsx');++const renderPage = async () => {+ let view;+ await act(async () => {+ view = render(+ <MemoryRouter initialEntries={['/media/video']}>+ <VideoGen />+ </MemoryRouter>,+ );+ });+ return view;+};++const prompt = () => screen.getByLabelText('Prompt');+const generate = () => screen.getByRole('button', { name: /^Generate$/ });+const enqueue = () => screen.getByRole('button', { name: /Add to queue/ });+const termsCheckbox = () => screen.getByRole('checkbox', { name: /I am eligible/ });++describe('VideoGen restricted-model orchestration', () => {+ beforeEach(() => {+ localStorage.clear();+ state.modelStatuses = {+ [H3_ONE.id]: { id: H3_ONE.id, repo: H3_ONE.repo, cached: true, sizeBytes: 100 },+ [H3_TWO.id]: { id: H3_TWO.id, repo: H3_TWO.repo, cached: true, sizeBytes: 100 },+ };+ state.generateVideo.mockReset().mockResolvedValue({ jobId: 'job-1' });+ state.startDownload.mockReset();+ state.repairModel.mockReset().mockResolvedValue({ ok: true });+ state.enqueue.mockReset();+ state.eventSourceRef.current = null;+ state.attach.mockReset().mockImplementation(async (_jobId, handlers) => {+ handlers.onComplete({ result: { filename: 'example.mp4' } });+ return { filename: 'example.mp4' };+ });+ });++ it('restores only the exact license, gates model switches, submit, queue, and revocation', async () => {+ localStorage.setItem(`video-gen:terms:${TERMS_ONE}`, '1');+ await renderPage();++ await waitFor(() => expect(screen.getByLabelText('Model')).toHaveValue(H3_ONE.id));+ await waitFor(() => expect(termsCheckbox()).toBeChecked());+ fireEvent.change(prompt(), { target: { value: 'a fox watches the rain' } });++ await waitFor(() => expect(enqueue()).toBeEnabled());+ fireEvent.click(enqueue());+ expect(state.enqueue).toHaveBeenCalledWith(expect.objectContaining({+ modelId: H3_ONE.id,+ termsAcceptance: TERMS_ONE,+ }));++ // A form submit models keyboard/Enter submission and must use the same+ // gate + exact key as clicking Generate.+ await act(async () => {+ fireEvent.submit(prompt().closest('form'));+ });+ await waitFor(() => expect(state.generateVideo).toHaveBeenCalledWith(expect.objectContaining({+ modelId: H3_ONE.id,+ termsAcceptance: TERMS_ONE,+ })));++ fireEvent.change(screen.getByLabelText('Model'), { target: { value: H3_TWO.id } });+ await waitFor(() => expect(screen.getByLabelText('Model')).toHaveValue(H3_TWO.id));+ expect(termsCheckbox()).not.toBeChecked();+ expect(generate()).toBeDisabled();+ expect(enqueue()).toBeDisabled();+ expect(generate()).toHaveAttribute('aria-describedby', 'video-model-terms-requirement');+ expect(state.generateVideo).toHaveBeenCalledTimes(1);++ fireEvent.change(screen.getByLabelText('Model'), { target: { value: H3_ONE.id } });+ await waitFor(() => expect(termsCheckbox()).toBeChecked());+ fireEvent.click(termsCheckbox());+ expect(localStorage.getItem(`video-gen:terms:${TERMS_ONE}`)).toBe('0');+ expect(generate()).toBeDisabled();+ expect(enqueue()).toBeDisabled();+ });++ it('blocks download until acceptance and forwards the exact key', async () => {+ state.modelStatuses[H3_ONE.id] = { id: H3_ONE.id, repo: H3_ONE.repo, cached: false, sizeBytes: 0 };+ await renderPage();++ const download = await screen.findByRole('button', { name: /Download/ });+ expect(download).toBeDisabled();+ expect(download).toHaveAttribute('aria-describedby', 'video-model-terms-requirement');+ fireEvent.click(termsCheckbox());+ await waitFor(() => expect(download).toBeEnabled());+ fireEvent.click(download);+ expect(state.startDownload).toHaveBeenCalledWith(H3_ONE.id, { termsAcceptance: TERMS_ONE });+ });++ it('blocks integrity repair until acceptance and forwards the exact key', async () => {+ state.modelStatuses[H3_ONE.id] = {+ id: H3_ONE.id,+ repo: H3_ONE.repo,+ cached: true,+ sizeBytes: 100,+ integrity: { status: 'bad', badFiles: [{ name: 'model.safetensors' }] },+ };+ await renderPage();++ const repair = await screen.findByRole('button', { name: /Repair model/ });+ expect(repair).toBeDisabled();+ expect(repair).toHaveAttribute('aria-describedby', 'video-model-terms-requirement');+ fireEvent.click(termsCheckbox());+ await waitFor(() => expect(repair).toBeEnabled());+ fireEvent.click(repair);+ expect(state.repairModel).toHaveBeenCalledWith(H3_ONE.id, { termsAcceptance: TERMS_ONE });+ });+});diff --git a/data.reference/media-models.json b/data.reference/media-models.jsonindex e217b8103b..7814659fc7 100644--- a/data.reference/media-models.json+++ b/data.reference/media-models.json@@ -100,6 +100,105 @@"reviewedAt": "2026-08-09"}},+ {+ "id": "minimax_h3_8bit",+ "name": "MiniMax H3 MLX 8-bit (joint video + audio, ~103 GB download, 128 GB RAM)",+ "repo": "pipenetwork/MiniMax-H3-MLX-8bit",+ "revision": "3ac52081470b0488921c3ec3ba84a39097bf2361",+ "runtime": "minimax_h3",+ "supportedModes": [+ "text"+ ],+ "defaultFrames": 124,+ "frameOptions": [+ 124,+ 141,+ 158,+ 175,+ 192,+ 209,+ 226,+ 243,+ 260,+ 277,+ 294,+ 311,+ 328,+ 345,+ 362+ ],+ "fpsOptions": [+ 24+ ],+ "memoryGb": 128,+ "steps": 8,+ "guidance": 0,+ "samplerLocked": true,+ "samplerNote": "MiniMax H3 is CFG-distilled; this profile locks the validated 8-point sigma schedule and does not use CFG.",+ "supportsNegativePrompt": false,+ "supportsTiling": false,+ "supportsDisableAudio": false,+ "requiredWeights": [+ {+ "repo": "MiniMaxAI/MiniMax-H3",+ "revision": "6818f6c32d12b210915e44ad56a4228c2608f160",+ "files": [+ "LICENSE",+ "FL2VA/model_index.json",+ "FL2VA/audio_vae/config.json",+ "FL2VA/audio_vae/metadata.json",+ "FL2VA/audio_vae/model.safetensors",+ "FL2VA/text_encoder/config.json",+ "FL2VA/text_encoder/model-00001-of-00014.safetensors",+ "FL2VA/text_encoder/model-00002-of-00014.safetensors",+ "FL2VA/text_encoder/model-00003-of-00014.safetensors",+ "FL2VA/text_encoder/model-00004-of-00014.safetensors",+ "FL2VA/text_encoder/model-00005-of-00014.safetensors",+ "FL2VA/text_encoder/model-00006-of-00014.safetensors",+ "FL2VA/text_encoder/model-00007-of-00014.safetensors",+ "FL2VA/text_encoder/model-00008-of-00014.safetensors",+ "FL2VA/text_encoder/model-00009-of-00014.safetensors",+ "FL2VA/text_encoder/model-00010-of-00014.safetensors",+ "FL2VA/text_encoder/model-00011-of-00014.safetensors",+ "FL2VA/text_encoder/model-00014-of-00014.safetensors",+ "FL2VA/text_encoder/model.safetensors.index.json",+ "FL2VA/tokenizer/merges.txt",+ "FL2VA/tokenizer/tokenizer.json",+ "FL2VA/tokenizer/tokenizer_config.json",+ "FL2VA/tokenizer/vocab.json",+ "FL2VA/video_vae/config.json",+ "FL2VA/video_vae/source/config.json",+ "FL2VA/video_vae/source/model.safetensors"+ ]+ }+ ],+ "disclosure": {+ "modelCardUrl": "https://huggingface.co/pipenetwork/MiniMax-H3-MLX-8bit",+ "weightsLicense": {+ "name": "MiniMax H3 Community License",+ "url": "https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/6818f6c32d12b210915e44ad56a4228c2608f160/LICENSE"+ },+ "runtimeLicense": {+ "name": "Apache-2.0",+ "url": "https://github.com/PipeNetwork/minimax-h3-mlx/blob/fcd9e9b79a1d6018d91ac477c0968de1fa067e49/LICENSE"+ },+ "estimatedDownloadGb": 103.3,+ "reviewedAt": "2026-08-09"+ },+ "termsGate": {+ "id": "minimax-h3-community-license-2026-08-02",+ "title": "MiniMax H3 eligibility and terms",+ "summary": "MiniMax grants use only in its Applicable Territory. The license excludes the European Union, United Kingdom, Republic of Korea, and United States of America.",+ "acknowledgement": "I confirm I am in the Applicable Territory and agree to the MiniMax H3 Community License and its Acceptable Use Policy.",+ "licenseUrl": "https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/6818f6c32d12b210915e44ad56a4228c2608f160/LICENSE",+ "excludedTerritories": [+ "European Union",+ "United Kingdom",+ "Republic of Korea",+ "United States of America"+ ]+ }+ },{"id": "wan22_ti2v_5b","name": "Wan 2.2 TI2V 5B Q8 (~17 GiB download, text + image)",diff --git a/scripts/_runner_common.py b/scripts/_runner_common.pyindex 7175ef2c31..55f558ac10 100644--- a/scripts/_runner_common.py+++ b/scripts/_runner_common.py@@ -19,6 +19,7 @@ walker that turns a buried `GatedRepoError` into a friendly link — belongs her"""import json+import importlib.utilimport loggingimport osimport platform@@ -36,6 +37,27 @@ from pathlib import Path# Hunyuan venv during a partial bootstrap).+def register_source_namespace(package_name: str, package_dir: "str | Path"):+ """Register one source-only namespace package without exposing its parent.++ Adding a third-party checkout root to ``sys.path`` lets unrelated files at+ that root (for example an untracked ``numpy.py``) shadow packages from the+ locked venv. A namespace package needs only its own directory in+ ``__path__``; relative imports keep working while sibling checkout files are+ never considered as top-level modules.+ """+ source_dir = Path(package_dir).absolute()+ if not source_dir.is_dir():+ raise RuntimeError(f"Source package directory is missing: {source_dir}")+ spec = importlib.util.spec_from_loader(package_name, loader=None, is_package=True)+ if spec is None:+ raise RuntimeError(f"Could not register source package: {package_name}")+ spec.submodule_search_locations = [str(source_dir)]+ package = importlib.util.module_from_spec(spec)+ sys.modules[package_name] = package+ return package++@contextmanagerdef heartbeat(stage: str, interval: float = 20.0):"""Emit a periodic STAGE:<stage>:heartbeat:Ns marker so the JS idlediff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.pynew file mode 100644index 0000000000..36b73ae875--- /dev/null+++ b/scripts/generate_minimax_h3.py@@ -0,0 +1,277 @@+#!/usr/bin/env python3+"""Cache-only PortOS runner for the pinned MiniMax H3 MLX runtime.++The Video Gen UI owns every network operation. This helper resolves only the+exact revisions already present in Hugging Face's cache, loads PipeNetwork's+pinned source checkout, emits PortOS progress/runtime frames, and writes one+joint video-and-audio MP4.+"""++from __future__ import annotations++import argparse+import json+import os+import re+import shutil+import subprocess+import sys+from contextlib import redirect_stdout+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _runner_common import emit_runtime_fingerprint, heartbeat, register_source_namespace # noqa: E402+++FPS = 24+MIN_FRAMES = 124 # first 17n+5 grid point at or above 5 seconds+MAX_FRAMES = 362 # first 17n+5 grid point at or above 15 seconds+FRAME_MODULUS = 17+FRAME_REMAINDER = 5+STEP_RE = re.compile(r"\bstep\s+(\d+)/(\d+)\b", re.IGNORECASE)+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--runtime-dir", required=True)+ parser.add_argument("--runtime-revision", required=True)+ parser.add_argument("--model-repo", required=True)+ parser.add_argument("--model-revision", required=True)+ parser.add_argument("--checkpoint-repo", required=True)+ parser.add_argument("--checkpoint-revision", required=True)+ parser.add_argument("--checkpoint-file", action="append", default=[])+ parser.add_argument("--prompt", required=True)+ parser.add_argument("--width", type=int, required=True)+ parser.add_argument("--height", type=int, required=True)+ parser.add_argument("--num-frames", type=int, required=True)+ parser.add_argument("--fps", type=int, default=FPS)+ parser.add_argument("--steps", type=int, default=8)+ parser.add_argument("--seed", type=int, default=0)+ parser.add_argument("--output", required=True)+ return parser.parse_args()+++def snapshot_root(resolved_file: str | Path, repo_filename: str) -> Path:+ """Return the HF snapshot directory containing one resolved repo file."""+ levels = len(Path(repo_filename).parts)+ # Hugging Face snapshot entries are normally symlinks into `blobs/`.+ # Resolving the symlink would therefore walk OUT of the snapshot and hand+ # the pipeline a blob directory. `hf_hub_download` already returns an+ # absolute snapshot path, so preserve that lexical path deliberately.+ return Path(resolved_file).absolute().parents[levels - 1]+++def resolve_cached_snapshot(repo: str, revision: str, required_files: list[str]) -> Path:+ """Resolve exact cached files without ever permitting a network fallback."""+ if not required_files:+ raise RuntimeError(f"No required files declared for {repo}.")++ from huggingface_hub import hf_hub_download++ resolved: list[tuple[str, Path]] = []+ for filename in required_files:+ try:+ path = hf_hub_download(+ repo_id=repo,+ filename=filename,+ revision=revision,+ local_files_only=True,+ )+ except Exception as exc:+ raise RuntimeError(+ f"Required cached weight is missing: {repo}@{revision[:12]}/{filename}. "+ "Use Download in Video Gen before generating."+ ) from exc+ resolved.append((filename, Path(path)))++ roots = {snapshot_root(path, filename) for filename, path in resolved}+ if len(roots) != 1:+ raise RuntimeError(f"Cached files for {repo}@{revision[:12]} span multiple snapshots; repair the model in Video Gen.")+ return roots.pop()+++def resolve_transformer_snapshot(repo: str, revision: str) -> Path:+ """Resolve the quantized transformer and every shard named by its index."""+ root = resolve_cached_snapshot(+ repo,+ revision,+ ["config.json", "quant_config.json", "model.safetensors.index.json"],+ )+ index_path = root / "model.safetensors.index.json"+ index = json.loads(index_path.read_text(encoding="utf-8"))+ shards = sorted(set(index.get("weight_map", {}).values()))+ if not shards:+ raise RuntimeError(f"Transformer index has no weight shards: {repo}@{revision[:12]}.")+ shard_root = resolve_cached_snapshot(repo, revision, shards)+ if shard_root != root:+ raise RuntimeError(f"Transformer files for {repo}@{revision[:12]} span multiple snapshots; repair the model in Video Gen.")+ return root+++def require_ffmpeg() -> str:+ """Fail before loading ~83 GB of weights when muxing cannot succeed."""+ path = shutil.which("ffmpeg")+ if path is None:+ raise RuntimeError("ffmpeg is required to mux MiniMax H3 video and audio; install it before generating.")+ return path+++def verify_runtime_checkout(runtime_dir: Path, expected_revision: str) -> None:+ """Require the exact commit and a clean executable source package."""+ try:+ result = subprocess.run(+ [+ "git", "-C", str(runtime_dir), "status", "--porcelain=v2",+ "--branch", "--untracked-files=all", "--", "minimax_h3_mlx",+ ],+ check=True,+ capture_output=True,+ text=True,+ timeout=10,+ )+ except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:+ raise RuntimeError("Could not verify the pinned MiniMax H3 runtime checkout; use Repair in Video Gen.") from exc+ lines = [line for line in result.stdout.splitlines() if line]+ oid = next((line.removeprefix("# branch.oid ") for line in lines if line.startswith("# branch.oid ")), None)+ dirty = [line for line in lines if not line.startswith("# ")]+ if oid != expected_revision or dirty:+ raise RuntimeError("MiniMax H3 runtime source differs from the pinned checkout; use Repair in Video Gen.")+++def emit_result(output: Path) -> None:+ """Emit the completion contract that arms PortOS's teardown watchdog."""+ print(json.dumps({"video_path": str(output)}), flush=True)+++class ProgressWriter:+ """Translate the port's human step lines into PortOS STAGE progress."""++ def __init__(self) -> None:+ self._carry = ""++ def write(self, text: str) -> int:+ self._carry += text+ while "\n" in self._carry:+ line, self._carry = self._carry.split("\n", 1)+ self._emit(line)+ return len(text)++ def flush(self) -> None:+ if self._carry:+ self._emit(self._carry)+ self._carry = ""++ @staticmethod+ def _emit(line: str) -> None:+ clean = line.strip()+ if not clean:+ return+ match = STEP_RE.search(clean)+ if match:+ step, total = match.groups()+ print(+ f"STAGE:minimax-h3:step:{step}:{total}:MiniMax H3 step {step}/{total}",+ file=sys.stderr,+ flush=True,+ )+ return+ print(clean, file=sys.stderr, flush=True)+++def validate_args(args: argparse.Namespace) -> None:+ if args.fps != FPS:+ raise SystemExit(f"MiniMax H3 runs at a fixed {FPS} fps; got {args.fps}.")+ if args.width <= 0 or args.height <= 0 or args.width % 32 or args.height % 32:+ raise SystemExit(f"MiniMax H3 dimensions must be positive multiples of 32; got {args.width}x{args.height}.")+ if not MIN_FRAMES <= args.num_frames <= MAX_FRAMES:+ raise SystemExit(f"MiniMax H3 supports approximately 5-15 seconds ({MIN_FRAMES}-{MAX_FRAMES} aligned frames).")+ if args.num_frames % FRAME_MODULUS != FRAME_REMAINDER:+ raise SystemExit(f"MiniMax H3 frame count must be 17n+5; got {args.num_frames}.")+ if args.steps < 2:+ raise SystemExit("MiniMax H3 needs at least 2 sigma grid points.")+++def main() -> int:+ args = parse_args()+ validate_args(args)++ # PortOS cancels this helper by process group; ffmpeg inherits the group and+ # cannot remain behind muxing after the user presses Cancel. Establish the+ # group before the git pin probe, which is the first child process.+ if hasattr(os, "setpgid"):+ try:+ os.setpgid(0, 0)+ except OSError:+ pass++ require_ffmpeg()++ runtime_dir = Path(args.runtime_dir).resolve()+ verify_runtime_checkout(runtime_dir, args.runtime_revision)++ emit_runtime_fingerprint(+ "minimax_h3",+ ["mlx", "mlx-metal", "mlx-vlm", "transformers", "huggingface-hub"],+ )++ print("STAGE:resolve-cache", file=sys.stderr, flush=True)+ checkpoint_snapshot = resolve_cached_snapshot(+ args.checkpoint_repo,+ args.checkpoint_revision,+ args.checkpoint_file,+ )+ checkpoint_dir = checkpoint_snapshot / "FL2VA"+ transformer_dir = resolve_transformer_snapshot(args.model_repo, args.model_revision)++ package_dir = runtime_dir / "minimax_h3_mlx"+ if not (package_dir / "pipeline.py").is_file():+ raise RuntimeError(f"MiniMax H3 runtime source is missing under {runtime_dir}.")+ register_source_namespace("minimax_h3_mlx", package_dir)++ from minimax_h3_mlx.media import save_mp4+ from minimax_h3_mlx.pipeline import MiniMaxH3Pipeline++ print("STAGE:load-pipeline", file=sys.stderr, flush=True)+ with heartbeat("minimax-h3-load"):+ pipe = MiniMaxH3Pipeline.from_pretrained(+ checkpoint_dir,+ transformer_dir=transformer_dir,+ load_vision=False,+ )++ print("STAGE:inference", file=sys.stderr, flush=True)+ progress = ProgressWriter()+ with heartbeat("minimax-h3-inference"), redirect_stdout(progress):+ result = pipe(+ args.prompt,+ duration_seconds=args.num_frames / FPS,+ num_inference_steps=args.steps,+ seed=args.seed,+ height=args.height,+ width=args.width,+ drop_adaln=True,+ )+ progress.flush()++ output = Path(args.output)+ output.parent.mkdir(parents=True, exist_ok=True)+ wav_path = output.with_suffix(".wav")+ print("STAGE:mux", file=sys.stderr, flush=True)+ try:+ save_mp4(output, result.video, result.fps, result.audio, result.sample_rate)+ finally:+ wav_path.unlink(missing_ok=True)++ if not output.is_file() or output.stat().st_size == 0:+ raise RuntimeError(f"MiniMax H3 completed but did not write {output}.")+ print(+ f"STATUS:MiniMax H3 saved {output.name} ({result.video.shape[0]} frames with stereo audio)",+ file=sys.stderr,+ flush=True,+ )+ emit_result(output)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.jsnew file mode 100644index 0000000000..82eeee9b6b--- /dev/null+++ b/scripts/generate_minimax_h3.test.js@@ -0,0 +1,126 @@+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { describe, expect, it } from 'vitest';++const script = join(dirname(fileURLToPath(import.meta.url)), 'generate_minimax_h3.py');++const runPython = (source) => execFileSync('python3', ['-c', source, script], {+ encoding: 'utf8',+});++const importRunner = [+ 'import importlib.util, sys',+ 'from pathlib import Path',+ 'script = Path(sys.argv[1])',+ 'spec = importlib.util.spec_from_file_location("generate_minimax_h3", script)',+ 'runner = importlib.util.module_from_spec(spec)',+ 'spec.loader.exec_module(runner)',+].join('\n');++describe('generate_minimax_h3.py', () => {+ it('keeps the lexical HF snapshot root when cache entries are blob symlinks', () => {+ const output = runPython(`${importRunner}\n${[+ 'import tempfile',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp)',+ ' blob = root / "blobs" / "abc"',+ ' blob.parent.mkdir(parents=True)',+ ' blob.write_text("weights")',+ ' entry = root / "snapshots" / "revision" / "FL2VA" / "config.json"',+ ' entry.parent.mkdir(parents=True)',+ ' entry.symlink_to(blob)',+ ' print(runner.snapshot_root(entry, "FL2VA/config.json"))',+ ].join('\n')}`);+ expect(output.trim()).toMatch(/snapshots[/\\]revision$/);+ });++ it('preflights transformer config, quant config, index, and every indexed shard', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, tempfile',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp)',+ ' (root / "model.safetensors.index.json").write_text(json.dumps({"weight_map": {"a": "model-1.safetensors", "b": "model-2.safetensors"}}))',+ ' calls = []',+ ' def fake_resolve(repo, revision, files):',+ ' calls.append(files)',+ ' return root',+ ' runner.resolve_cached_snapshot = fake_resolve',+ ' resolved = runner.resolve_transformer_snapshot("example/model", "revision")',+ ' print(json.dumps({"calls": calls, "resolved": str(resolved)}))',+ ].join('\n')}`);+ const result = JSON.parse(output);+ expect(result.calls).toEqual([+ ['config.json', 'quant_config.json', 'model.safetensors.index.json'],+ ['model-1.safetensors', 'model-2.safetensors'],+ ]);+ expect(result.resolved).toBeTruthy();+ });++ it('fails the ffmpeg preflight before any model load can begin', () => {+ const output = runPython(`${importRunner}\n${[+ 'runner.shutil.which = lambda _name: None',+ 'try:',+ ' runner.require_ffmpeg()',+ 'except RuntimeError as exc:',+ ' print(str(exc))',+ 'else:',+ ' raise SystemExit("missing preflight did not fail")',+ ].join('\n')}`);+ expect(output).toMatch(/ffmpeg is required/i);+ });++ 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)',+ 'try:',+ ' runner.validate_args(args)',+ 'except SystemExit as exc:',+ ' print(str(exc))',+ 'else:',+ ' raise SystemExit("zero dimensions were accepted")',+ ].join('\n')}`);+ expect(output).toMatch(/dimensions must be positive multiples of 32/i);+ });++ 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' });+ });++ it('loads only the pinned namespace and cannot import a root-level shadow module', () => {+ const output = runPython(`${importRunner}\n${[+ 'import importlib, tempfile',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp) / "runtime"',+ ' package = root / "minimax_h3_mlx"',+ ' trusted = Path(temp) / "venv"',+ ' package.mkdir(parents=True)',+ ' trusted.mkdir()',+ ' (root / "mlx_vlm.py").write_text("SOURCE = \'runtime-shadow\'")',+ ' (trusted / "mlx_vlm.py").write_text("SOURCE = \'locked-venv\'")',+ ' (package / "pipeline.py").write_text("from mlx_vlm import SOURCE")',+ ' sys.path.insert(0, str(trusted))',+ ' runner.register_source_namespace("minimax_h3_mlx", package)',+ ' pipeline = importlib.import_module("minimax_h3_mlx.pipeline")',+ ' print(pipeline.SOURCE)',+ ' print(str(root) in sys.path)',+ ].join('\n')}`);+ expect(output.trim().split(/\r?\n/)).toEqual(['locked-venv', 'False']);+ });++ it('bounds the git checkout verification probe', () => {+ const output = runPython(`${importRunner}\n${[+ 'from types import SimpleNamespace',+ 'seen = {}',+ 'def fake_run(*_args, **kwargs):',+ ' seen.update(kwargs)',+ ' return SimpleNamespace(stdout="# branch.oid expected\\n# branch.head (detached)\\n")',+ 'runner.subprocess.run = fake_run',+ 'runner.verify_runtime_checkout(Path("/tmp/runtime"), "expected")',+ 'print(seen["timeout"])',+ ].join('\n')}`);+ expect(output.trim()).toBe('10');+ });+});diff --git a/scripts/migrations/242-minimax-h3-mlx-model.js b/scripts/migrations/242-minimax-h3-mlx-model.jsnew file mode 100644index 0000000000..e71c5f7422--- /dev/null+++ b/scripts/migrations/242-minimax-h3-mlx-model.js@@ -0,0 +1,98 @@+/**+ * Add the never-before-shipped MiniMax H3 MLX profile to existing macOS+ * registries. Fresh installs receive it from data.reference/media-models.json.+ *+ * Registries that predate `_shippedDefaults` need a migration: their normal+ * bootstrap deliberately treats every current default id as already shipped+ * to preserve historical deletions, which would otherwise hide this new row.+ * The bootstrap snapshot built here mirrors mediaModels.js exactly, while the+ * explicit H3 append is the one new-model exception for this release.+ */++import { readFile } from 'fs/promises';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';+import { atomicWrite } from '../../server/lib/fileUtils.js';++const REL_PATH = 'data/media-models.json';+const H3_ID = 'minimax_h3_8bit';+const REFERENCE_PATH = join(+ dirname(fileURLToPath(import.meta.url)),+ '..', '..', 'data.reference', 'media-models.json',+);++const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);+const ids = (entries) => (Array.isArray(entries)+ ? entries.map((entry) => entry?.id).filter((id) => typeof id === 'string')+ : []);+const bootstrapIds = (userEntries, defaultEntries) => (Array.isArray(userEntries)+ ? [...new Set([...ids(userEntries), ...ids(defaultEntries)])]+ : []);++const parseJson = (raw, label) => {+ try {+ return JSON.parse(raw);+ } catch (err) {+ throw new Error(`Cannot migrate ${label}: invalid JSON (${err.message})`, { cause: err });+ }+};++export default {+ async up({ rootDir }) {+ const path = join(rootDir, REL_PATH);+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return;++ const config = parseJson(raw, REL_PATH);+ const macos = Array.isArray(config?.video?.macos) ? config.video.macos : null;+ if (!macos) return;++ const reference = parseJson(await readFile(REFERENCE_PATH, 'utf-8'), 'data.reference/media-models.json');+ const referenceMacos = Array.isArray(reference?.video?.macos) ? reference.video.macos : [];+ const h3 = referenceMacos.find((entry) => entry?.id === H3_ID);+ if (!h3) throw new Error(`Cannot migrate ${REL_PATH}: shipped ${H3_ID} reference is missing`);++ const shippedRoot = isObject(config._shippedDefaults) ? config._shippedDefaults : null;+ const shippedVideo = isObject(shippedRoot?.video) ? shippedRoot.video : null;+ const shippedMacos = Array.isArray(shippedVideo?.macos) ? shippedVideo.macos : null;+ const wasAlreadyShipped = shippedMacos?.includes(H3_ID) === true;+ const existing = macos.find((entry) => entry?.id === H3_ID);+ let changed = false;++ // A recorded-but-missing id is a user deletion and stays deleted. An+ // existing row may be user-customized and is never overwritten.+ if (!existing && !wasAlreadyShipped) {+ macos.push(structuredClone(h3));+ changed = true;+ }++ if (shippedMacos) {+ if (macos.some((entry) => entry?.id === H3_ID) && !shippedMacos.includes(H3_ID)) {+ shippedMacos.push(H3_ID);+ changed = true;+ }+ } else {+ // Once we introduce the snapshot key, populate it with the same union+ // mediaModels.js would use for a legacy registry. A partial [H3]-only+ // snapshot would make every historically deleted default look new and+ // silently repopulate the user's curated list on the next load.+ const nextRoot = shippedRoot || {};+ const nextVideo = shippedVideo || {};+ nextVideo.macos = bootstrapIds(macos, referenceMacos);+ if (!shippedVideo) {+ nextVideo.windows = bootstrapIds(config.video.windows, reference?.video?.windows);+ }+ nextRoot.video = nextVideo;+ config._shippedDefaults = nextRoot;+ changed = true;+ }++ if (changed) {+ await atomicWrite(path, `${JSON.stringify(config, null, 2)}\n`);+ console.log(`📝 ${REL_PATH}: added the MiniMax H3 MLX video profile`);+ }+ },+};diff --git a/scripts/migrations/242-minimax-h3-mlx-model.test.js b/scripts/migrations/242-minimax-h3-mlx-model.test.jsnew file mode 100644index 0000000000..6d287acc77--- /dev/null+++ b/scripts/migrations/242-minimax-h3-mlx-model.test.js@@ -0,0 +1,101 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './242-minimax-h3-mlx-model.js';++const H3_ID = 'minimax_h3_8bit';+const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++const legacyRegistry = () => ({+ video: {+ macos: [{ id: 'ltx23_distilled_q4', name: 'My tuned default', steps: 17 }],+ windows: [{ id: 'ltx_video', name: 'LTX Windows' }],+ defaultMacos: 'ltx23_distilled_q4',+ defaultWindows: 'ltx_video',+ },+ image: [{ id: 'my-image', name: 'My image model' }],+});++describe('migration 242 — MiniMax H3 MLX model', () => {+ let rootDir;+ let path;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-242-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ path = join(rootDir, 'data', 'media-models.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('adds H3 to a pre-snapshot registry and bootstraps a deletion-safe shipped list', async () => {+ const before = legacyRegistry();+ writeJson(path, before);+ await migration.up({ rootDir });++ const got = readJson(path);+ expect(got.video.macos[0]).toEqual(before.video.macos[0]);+ expect(got.video.defaultMacos).toBe('ltx23_distilled_q4');+ expect(got.image).toEqual(before.image);+ const h3 = got.video.macos.find((entry) => entry.id === H3_ID);+ expect(h3).toMatchObject({+ repo: 'pipenetwork/MiniMax-H3-MLX-8bit',+ revision: '3ac52081470b0488921c3ec3ba84a39097bf2361',+ runtime: 'minimax_h3',+ termsGate: { id: 'minimax-h3-community-license-2026-08-02' },+ });+ expect(got._shippedDefaults.video.macos).toContain(H3_ID);+ expect(got._shippedDefaults.video.macos).toContain('ltx23_unified');+ expect(got._shippedDefaults.video.windows).toContain('ltx_video');+ });++ it('adds and records H3 when a post-snapshot registry has not received it', async () => {+ const config = legacyRegistry();+ config._shippedDefaults = { video: { macos: ['ltx23_distilled_q4'], windows: ['ltx_video'] } };+ writeJson(path, config);+ await migration.up({ rootDir });+ const got = readJson(path);+ expect(got.video.macos.filter((entry) => entry.id === H3_ID)).toHaveLength(1);+ expect(got._shippedDefaults.video.macos).toContain(H3_ID);+ });++ it('preserves an existing customized H3 row while recording its id', async () => {+ const config = legacyRegistry();+ const custom = { id: H3_ID, name: 'My H3 profile', repo: 'example-org/h3-fork', steps: 5 };+ config.video.macos.push(custom);+ config._shippedDefaults = { video: { macos: ['ltx23_distilled_q4'], windows: ['ltx_video'] } };+ writeJson(path, config);+ await migration.up({ rootDir });+ const got = readJson(path);+ expect(got.video.macos.find((entry) => entry.id === H3_ID)).toEqual(custom);+ expect(got._shippedDefaults.video.macos).toContain(H3_ID);+ });++ it('does not recreate H3 after a recorded user deletion', async () => {+ const config = legacyRegistry();+ config._shippedDefaults = { video: { macos: ['ltx23_distilled_q4', H3_ID], windows: ['ltx_video'] } };+ writeJson(path, config);+ await migration.up({ rootDir });+ expect(readJson(path).video.macos.some((entry) => entry.id === H3_ID)).toBe(false);+ });++ it('is idempotent', async () => {+ writeJson(path, legacyRegistry());+ await migration.up({ rootDir });+ const once = readFileSync(path, 'utf-8');+ await migration.up({ rootDir });+ expect(readFileSync(path, 'utf-8')).toBe(once);+ });++ it('skips silently when the installed registry is missing', async () => {+ await migration.up({ rootDir });+ expect(existsSync(path)).toBe(false);+ });++ it('throws a clear error for malformed installed JSON', async () => {+ writeFileSync(path, '{not-json');+ await expect(migration.up({ rootDir })).rejects.toThrow(/invalid JSON/);+ });+});diff --git a/scripts/minimax_h3_runtime_probe.py b/scripts/minimax_h3_runtime_probe.pynew file mode 100644index 0000000000..2b76003ff6--- /dev/null+++ b/scripts/minimax_h3_runtime_probe.py@@ -0,0 +1,27 @@+#!/usr/bin/env python3+"""Import-probe a pinned MiniMax H3 source package without trusting its root."""++from __future__ import annotations++import importlib+import sys+from pathlib import Path++from _runner_common import register_source_namespace+++def main() -> int:+ if len(sys.argv) != 2:+ raise SystemExit("usage: minimax_h3_runtime_probe.py <runtime-dir>")+ runtime_dir = Path(sys.argv[1]).resolve()+ package_dir = runtime_dir / "minimax_h3_mlx"+ if not (package_dir / "pipeline.py").is_file():+ raise RuntimeError(f"MiniMax H3 runtime source is missing under {runtime_dir}.")+ register_source_namespace("minimax_h3_mlx", package_dir)+ importlib.import_module("minimax_h3_mlx.pipeline")+ importlib.import_module("mlx_vlm.models.qwen3_vl.language")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/requirements-minimax-h3-mlx.lock.txt b/scripts/requirements-minimax-h3-mlx.lock.txtnew file mode 100644index 0000000000..3d6ae77a26--- /dev/null+++ b/scripts/requirements-minimax-h3-mlx.lock.txt@@ -0,0 +1,55 @@+annotated-doc==0.0.5+annotated-types==0.8.0+anyio==4.14.2+certifi==2026.7.22+cffi==2.1.1+charset-normalizer==3.4.9+click==8.4.2+fastapi==0.141.1+filelock==3.32.2+fsspec==2026.7.0+h11==0.16.0+hf-xet==1.6.0+httpcore==1.0.9+httpx==0.28.1+huggingface-hub==1.27.0+idna==3.18+jinja2==3.1.6+llguidance==1.7.6+markdown-it-py==4.2.0+markupsafe==3.0.3+mdurl==0.1.2+miniaudio==1.71+mlx==0.32.0+mlx-audio==0.4.7+mlx-lm==0.31.3+mlx-metal==0.32.0+mlx-vlm==0.6.10+numpy==2.4.6+opencv-python==5.0.0.93+packaging==26.3+pillow==12.3.0+protobuf==7.35.1+pycparser==3.0+pydantic==2.13.4+pydantic-core==2.46.4+pygments==2.20.0+python-multipart==0.0.32+pyyaml==6.0.3+regex==2026.7.19+requests==2.34.2+rich==15.0.0+safetensors==0.8.0+scipy==1.17.1+sentencepiece==0.2.2+shellingham==1.5.4+sounddevice==0.5.5+starlette==1.6.0+tokenizers==0.22.2+tqdm==4.70.0+transformers==5.14.1+typer==0.27.1+typing-extensions==4.16.0+typing-inspection==0.4.2+urllib3==2.7.0+uvicorn==0.52.1diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.shindex 9a7022008c..226be06a2d 100755--- a/scripts/setup-image-video.sh+++ b/scripts/setup-image-video.sh@@ -10,6 +10,7 @@# PORTOS_DATA Path to PortOS data dir (default: ./data, resolved from $REPO_ROOT)# INSTALL_VIDEO '1' to also install mlx_video for LTX video generation (default: 1 on macOS, 0 on Windows)# INSTALL_LTX2 '1' to also clone + uv-sync dgrauet/ltx-2-mlx at ~/.portos/ltx-2-mlx for the second-gen LTX-2.3 pipeline (proper keyframe interpolation, true video extend, audio-to-video). Default: 0; opt in with INSTALL_LTX2=1.+# INSTALL_MINIMAX_H3 '1' to install the pinned MiniMax H3 MLX runtime at ~/.portos/minimax-h3-mlx. Weights remain a separate explicit Video Gen download. Default: 0.# INSTALL_FLUX2 '1' to also bootstrap a separate venv at ~/.portos/venv-flux2 for FLUX.2-klein (default: 1 on macOS, 0 elsewhere)# INSTALL_MUSICGEN '1' to bootstrap a venv at ~/.portos/venv-musicgen + clone ml-explore/mlx-examples to ~/.portos/mlx-examples for local MusicGen (MLX) background-music generation (pipeline audio stage). Default: 0; opt in with INSTALL_MUSICGEN=1 (macOS / Apple Silicon only).# MLX_EXAMPLES_PIN commit SHA of ml-explore/mlx-examples to check out for MusicGen (default: main).@@ -53,7 +54,7 @@ mkdir -p "${PORTOS_DATA}/videos"mkdir -p "${PORTOS_DATA}/video-thumbnails"# When the user only wants a specific BYOV runtime (set via INSTALL_LTX2 /-# INSTALL_WAN22 / INSTALL_HUNYUAN — or one of the self-contained MUSIC venvs+# INSTALL_WAN22 / INSTALL_HUNYUAN / INSTALL_MINIMAX_H3 — or one of the self-contained MUSIC venvs# INSTALL_MUSICGEN / INSTALL_AUDIOLDM2 / INSTALL_ACESTEP — typically from the# in-app installer), skip the mflux + legacy mlx_video preamble. Those# bring-your-own-venv runtimes are self-contained and don't depend on mflux;@@ -62,8 +63,8 @@ mkdir -p "${PORTOS_DATA}/video-thumbnails"# install ever starts — which on Linux/CPU/CUDA blocks the advertised# `INSTALL_ACESTEP=1 bash …` path. A bare `bash setup-image-video.sh` still# installs mflux as before.-ANY_BYOV="${INSTALL_LTX2:-0}${INSTALL_WAN22:-0}${INSTALL_HUNYUAN:-0}${INSTALL_MUSICGEN:-0}${INSTALL_AUDIOLDM2:-0}${INSTALL_ACESTEP:-0}${INSTALL_MUSCRIPTOR:-0}"-if [[ "$ANY_BYOV" == "0000000" ]]; then+ANY_BYOV="${INSTALL_LTX2:-0}${INSTALL_WAN22:-0}${INSTALL_HUNYUAN:-0}${INSTALL_MINIMAX_H3:-0}${INSTALL_MUSICGEN:-0}${INSTALL_AUDIOLDM2:-0}${INSTALL_ACESTEP:-0}${INSTALL_MUSCRIPTOR:-0}"+if [[ "$ANY_BYOV" == "00000000" ]]; thenDEFAULT_INSTALL_MFLUX=1DEFAULT_INSTALL_VIDEO=$(is_macos && echo 1 || echo 0)DEFAULT_INSTALL_FLUX2=$(is_macos && echo 1 || echo 0)@@ -316,6 +317,65 @@ if [[ "$INSTALL_WAN22" == "1" ]]; thenecho "✅ MLX-Gen Wan runtime ready: ${WAN22_PY}"fi+INSTALL_MINIMAX_H3="${INSTALL_MINIMAX_H3:-0}"+if [[ "$INSTALL_MINIMAX_H3" == "1" ]]; then+ # PipeNetwork/minimax-h3-mlx is a source checkout rather than a wheel. Keep+ # both its commit and the complete Python dependency graph immutable; an MLX+ # or transformers drift on a ~100 GB model is expensive to diagnose after a+ # long render. This block is reached only from the explicit runtime Install /+ # Repair action (or the matching terminal opt-in), never from PortOS boot.+ if ! is_macos || [[ "$(uname -m)" != "arm64" ]]; then+ echo "❌ MiniMax H3 MLX requires an Apple-Silicon Mac." >&2+ exit 1+ fi+ if ! have git; then+ echo "❌ INSTALL_MINIMAX_H3=1 requires git." >&2+ exit 1+ fi++ MINIMAX_H3_UV_TOOL_DIR="${HOME}/.portos/tools/uv-0.8.14"+ MINIMAX_H3_UV="${MINIMAX_H3_UV_TOOL_DIR}/bin/uv"+ if [[ ! -x "$MINIMAX_H3_UV" ]] || [[ "$("$MINIMAX_H3_UV" --version 2>/dev/null || true)" != "uv 0.8.14" ]]; then+ echo "📦 Bootstrapping pinned uv 0.8.14 for MiniMax H3 MLX..."+ "$PYTHON_BIN" -m venv --clear "$MINIMAX_H3_UV_TOOL_DIR"+ "${MINIMAX_H3_UV_TOOL_DIR}/bin/python3" -m pip install --disable-pip-version-check "uv==0.8.14"+ fi++ MINIMAX_H3_PIN="${MINIMAX_H3_PIN:-fcd9e9b79a1d6018d91ac477c0968de1fa067e49}"+ MINIMAX_H3_DIR="${HOME}/.portos/minimax-h3-mlx"+ MINIMAX_H3_PY="${MINIMAX_H3_DIR}/.venv/bin/python3"+ MINIMAX_H3_LOCK="${SCRIPT_DIR}/requirements-minimax-h3-mlx.lock.txt"+ mkdir -p "${HOME}/.portos"+ if [[ ! -d "${MINIMAX_H3_DIR}/.git" ]]; then+ echo "📦 Cloning MiniMax H3 MLX..."+ git clone https://github.com/PipeNetwork/minimax-h3-mlx.git "$MINIMAX_H3_DIR"+ else+ echo "📦 Fetching MiniMax H3 MLX updates..."+ git -C "$MINIMAX_H3_DIR" fetch origin+ fi+ git_checkout_pin "$MINIMAX_H3_DIR" "$MINIMAX_H3_PIN"+ # This runtime imports directly from the checkout, so HEAD alone is not an+ # integrity guarantee: tracked edits or an untracked Python module inside+ # the package would execute ahead of the pinned source. Install / Repair is+ # an explicit user action, so restore and clean only the executable package+ # (never the whole checkout, where large model/output folders may live).+ git -C "$MINIMAX_H3_DIR" restore --source=HEAD --staged --worktree -- minimax_h3_mlx+ git -C "$MINIMAX_H3_DIR" clean -fd -- minimax_h3_mlx+ if [[ ! -x "$MINIMAX_H3_PY" ]]; then+ echo "📦 Creating MiniMax H3 MLX venv with Python 3.11..."+ "$MINIMAX_H3_UV" venv --python 3.11 "${MINIMAX_H3_DIR}/.venv"+ fi+ echo "📦 Syncing pinned MiniMax H3 MLX packages..."+ "$MINIMAX_H3_UV" pip sync --python "$MINIMAX_H3_PY" "$MINIMAX_H3_LOCK"+ if ! "$MINIMAX_H3_PY" "${SCRIPT_DIR}/minimax_h3_runtime_probe.py" "$MINIMAX_H3_DIR" 2>/dev/null; then+ echo "❌ MiniMax H3 MLX synced but its pipeline import failed." >&2+ echo " Use Repair / Upgrade from the Video Gen runtime panel to retry." >&2+ exit 1+ fi+ echo "✅ MiniMax H3 MLX runtime ready: ${MINIMAX_H3_PY}"+ echo " Weights remain uninstalled until you accept the model terms and choose Download in Video Gen."+fi+INSTALL_HUNYUAN="${INSTALL_HUNYUAN:-0}"if [[ "$INSTALL_HUNYUAN" == "1" ]]; then# gaurav-nelson/HunyuanVideo_MLX — community MLX port of Tencent's@@ -643,6 +703,10 @@ if [[ "$INSTALL_WAN22" == "1" ]]; thenecho " Wan 2.2: ${HOME}/.portos/mlx-gen/.venv/bin/python3 (MLX-Gen @ ${WAN22_PIN:0:12})"echo " Weights remain uninstalled until Download is chosen in Video Gen."fi+if [[ "$INSTALL_MINIMAX_H3" == "1" ]]; then+ echo " MiniMax H3: ${HOME}/.portos/minimax-h3-mlx/.venv/bin/python3 (MLX port @ ${MINIMAX_H3_PIN:0:12})"+ echo " Weights remain uninstalled until accepted and downloaded in Video Gen."+fiif [[ "$INSTALL_MUSICGEN" == "1" ]] && is_macos; thenecho " MusicGen: ${HOME}/.portos/venv-musicgen/bin/python3 (separate venv, MLX runtime @ ${HOME}/.portos/mlx-examples/musicgen)"fidiff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 3b57802d6e..a2200b2cb2 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -68,6 +68,66 @@ const DEFAULT_REGISTRY = {// via `INSTALL_LTX2=1 bash scripts/setup-image-video.sh`.{ id: 'ltx23_dgrauet_q4', name: 'LTX-2.3 dgrauet Q4 (~16 GB, true keyframes)', repo: 'dgrauet/ltx-2.3-mlx-q4', runtime: 'ltx2', steps: 8, guidance: 3.0 },{ id: 'ltx23_dgrauet_q8', name: 'LTX-2.3 dgrauet Q8 (~25 GB, true keyframes)', repo: 'dgrauet/ltx-2.3-mlx-q8', runtime: 'ltx2', steps: 8, guidance: 3.0 },+ // MiniMax H3 joint video+audio through PipeNetwork's pinned MLX port.+ // The quantized DiT is one HF snapshot; the released conditioner + VAEs+ // are an exact selective file set from MiniMax's upstream snapshot. Both+ // downloads are explicit in Video Gen, and render-time resolution is+ // cache-only. The server-owned disclosure attaches the mandatory,+ // versioned territory/license acceptance gate.+ {+ id: 'minimax_h3_8bit',+ name: 'MiniMax H3 MLX 8-bit (joint video + audio, ~103 GB download, 128 GB RAM)',+ repo: 'pipenetwork/MiniMax-H3-MLX-8bit',+ revision: '3ac52081470b0488921c3ec3ba84a39097bf2361',+ runtime: 'minimax_h3',+ supportedModes: ['text'],+ defaultFrames: 124,+ frameOptions: [124, 141, 158, 175, 192, 209, 226, 243, 260, 277, 294, 311, 328, 345, 362],+ fpsOptions: [24],+ memoryGb: 128,+ steps: 8,+ guidance: 0,+ samplerLocked: true,+ samplerNote: 'MiniMax H3 is CFG-distilled; this profile locks the validated 8-point sigma schedule and does not use CFG.',+ supportsNegativePrompt: false,+ supportsTiling: false,+ supportsDisableAudio: false,+ requiredWeights: [{+ repo: 'MiniMaxAI/MiniMax-H3',+ revision: '6818f6c32d12b210915e44ad56a4228c2608f160',+ files: [+ 'LICENSE',+ 'FL2VA/model_index.json',+ 'FL2VA/audio_vae/config.json',+ 'FL2VA/audio_vae/metadata.json',+ 'FL2VA/audio_vae/model.safetensors',+ 'FL2VA/text_encoder/config.json',+ 'FL2VA/text_encoder/model-00001-of-00014.safetensors',+ 'FL2VA/text_encoder/model-00002-of-00014.safetensors',+ 'FL2VA/text_encoder/model-00003-of-00014.safetensors',+ 'FL2VA/text_encoder/model-00004-of-00014.safetensors',+ 'FL2VA/text_encoder/model-00005-of-00014.safetensors',+ 'FL2VA/text_encoder/model-00006-of-00014.safetensors',+ 'FL2VA/text_encoder/model-00007-of-00014.safetensors',+ 'FL2VA/text_encoder/model-00008-of-00014.safetensors',+ 'FL2VA/text_encoder/model-00009-of-00014.safetensors',+ 'FL2VA/text_encoder/model-00010-of-00014.safetensors',+ 'FL2VA/text_encoder/model-00011-of-00014.safetensors',+ // The pinned port truncates Qwen3-VL at layer 50. Index shards+ // 12/13 contain only layers 53-63 and are intentionally omitted;+ // shard 14 remains necessary for the final norm tensor.+ 'FL2VA/text_encoder/model-00014-of-00014.safetensors',+ 'FL2VA/text_encoder/model.safetensors.index.json',+ 'FL2VA/tokenizer/merges.txt',+ 'FL2VA/tokenizer/tokenizer.json',+ 'FL2VA/tokenizer/tokenizer_config.json',+ 'FL2VA/tokenizer/vocab.json',+ 'FL2VA/video_vae/config.json',+ 'FL2VA/video_vae/source/config.json',+ 'FL2VA/video_vae/source/model.safetensors',+ ],+ }],+ },// Wan 2.2 through pinned MLX-Gen. Generation is cache-only: PortOS owns// the explicit base/adaptor downloads and uses the saved HF token.{diff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.jsindex 2b4ee7d878..5c5ba8d679 100644--- a/server/lib/mediaModels.test.js+++ b/server/lib/mediaModels.test.js@@ -57,6 +57,41 @@ describe('mediaModels registry', () => {expect(list.every((m) => m.id && m.name)).toBe(true);});+ it('ships MiniMax H3 as a pinned, text-only 128 GB BYOV profile', async () => {+ const { getVideoModels } = await import('./mediaModels.js');+ const h3 = getVideoModels().find((model) => model.id === 'minimax_h3_8bit');+ expect(h3).toMatchObject({+ runtime: 'minimax_h3',+ repo: 'pipenetwork/MiniMax-H3-MLX-8bit',+ revision: '3ac52081470b0488921c3ec3ba84a39097bf2361',+ supportedModes: ['text'],+ defaultFrames: 124,+ fpsOptions: [24],+ memoryGb: 128,+ samplerLocked: true,+ steps: 8,+ });+ expect(h3.frameOptions).toEqual([124, 141, 158, 175, 192, 209, 226, 243, 260, 277, 294, 311, 328, 345, 362]);+ expect(h3.requiredWeights[0]).toMatchObject({+ repo: 'MiniMaxAI/MiniMax-H3',+ revision: '6818f6c32d12b210915e44ad56a4228c2608f160',+ });+ // The pinned port builds only decoder layers 0-49. Shards 12/13 contain+ // only layers 53-63, which its _wanted() loader deliberately skips; shard+ // 14 remains required for the final norm. Keep this selective 12-shard+ // contract explicit so a generic "download every index shard" rewrite+ // does not add roughly 10 GB of weights the H3 text path never loads.+ expect(h3.requiredWeights[0].files.filter((file) => /model-\d{5}-of-00014\.safetensors$/.test(file)))+ .toEqual([+ ...Array.from(+ { length: 11 },+ (_, index) => `FL2VA/text_encoder/model-${String(index + 1).padStart(5, '0')}-of-00014.safetensors`,+ ),+ 'FL2VA/text_encoder/model-00014-of-00014.safetensors',+ ]);+ expect(h3.termsGate.id).toBe('minimax-h3-community-license-2026-08-02');+ });+it('hides models with broken === current platform', async () => {const here = process.platform === 'win32' ? 'windows' : 'macos';const elsewhere = process.platform === 'win32' ? 'macos' : 'windows';@@ -381,8 +416,10 @@ describe('mediaModels registry', () => {// ltx23_dgrauet_q8 is a current DEFAULT_REGISTRY entry not yet shipped →// should be added to the user's listexpect(reg.video.macos.some((e) => e.id === 'ltx23_dgrauet_q8')).toBe(true);+ expect(reg.video.macos.some((e) => e.id === 'minimax_h3_8bit')).toBe(true);// And should now be recorded in _shippedDefaultsexpect(reg._shippedDefaults.video.macos).toContain('ltx23_dgrauet_q8');+ expect(reg._shippedDefaults.video.macos).toContain('minimax_h3_8bit');// Persisted to diskconst onDisk = JSON.parse(readFileSync(registryFile, 'utf-8'));expect(onDisk._shippedDefaults.video.macos).toContain('ltx23_dgrauet_q8');diff --git a/server/lib/videoDisclosure.js b/server/lib/videoDisclosure.jsindex 11c41a08d5..89ed2e68b2 100644--- a/server/lib/videoDisclosure.js+++ b/server/lib/videoDisclosure.js@@ -36,6 +36,11 @@ const TENCENT_HUNYUAN_WEIGHTS = {name: 'Tencent Hunyuan Community License',url: 'https://huggingface.co/tencent/HunyuanVideo/blob/main/LICENSE',};+const MINIMAX_H3_LICENSE_URL = 'https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/6818f6c32d12b210915e44ad56a4228c2608f160/LICENSE';+const MINIMAX_H3_WEIGHTS = {+ name: 'MiniMax H3 Community License',+ url: MINIMAX_H3_LICENSE_URL,+};// Runtime (inference code) licenses, keyed by the registry's `runtime` value.// Distinct from the weights license — a permissively-licensed runtime does not@@ -46,6 +51,10 @@ const RUNTIME_LICENSE = {mlx_video: { name: 'MIT', url: 'https://pypi.org/project/mlx-video-with-audio/' },ltx2: { name: 'MIT', url: 'https://github.com/dgrauet/ltx-2-mlx/blob/main/LICENSE' },wan22: { name: 'MIT', url: 'https://github.com/lpalbou/mlx-gen/blob/main/LICENSE' },+ minimax_h3: {+ name: 'Apache-2.0',+ url: 'https://github.com/PipeNetwork/minimax-h3-mlx/blob/fcd9e9b79a1d6018d91ac477c0968de1fa067e49/LICENSE',+ },hunyuan: {name: 'Tencent Hunyuan Community License',url: 'https://github.com/gaurav-nelson/HunyuanVideo_MLX/blob/main/LICENSE.txt',@@ -75,6 +84,35 @@ const customLicense = (repo) => ({ name: 'Custom — see model card', url: hfMod* LoRA files.*/export const VIDEO_MODEL_DISCLOSURES = Object.freeze({+ minimax_h3_8bit: {+ shippedRepo: 'pipenetwork/MiniMax-H3-MLX-8bit',+ disclosure: {+ modelCardUrl: hfModelCard('pipenetwork/MiniMax-H3-MLX-8bit'),+ weightsLicense: MINIMAX_H3_WEIGHTS,+ runtimeLicense: RUNTIME_LICENSE.minimax_h3,+ // 35.302 GB quantized transformer + 67.996 GB selective upstream+ // conditioner / video VAE / audio VAE files used by text-to-video.+ estimatedDownloadGb: 103.3,+ reviewedAt: VIDEO_DISCLOSURE_REVIEWED_AT,+ },+ // Unlike an informational disclosure, this is an execution gate. The+ // upstream license grants rights solely in its Applicable Territory and+ // makes use itself acceptance, so PortOS requires the exact versioned key+ // on both download and generation requests.+ termsGate: {+ id: 'minimax-h3-community-license-2026-08-02',+ title: 'MiniMax H3 eligibility and terms',+ summary: 'MiniMax grants use only in its Applicable Territory. The license excludes the European Union, United Kingdom, Republic of Korea, and United States of America.',+ acknowledgement: 'I confirm I am in the Applicable Territory and agree to the MiniMax H3 Community License and its Acceptable Use Policy.',+ licenseUrl: MINIMAX_H3_LICENSE_URL,+ excludedTerritories: [+ 'European Union',+ 'United Kingdom',+ 'Republic of Korea',+ 'United States of America',+ ],+ },+ },ltx2_unified: {shippedRepo: 'notapalindrome/ltx2-mlx-av',disclosure: {@@ -207,6 +245,10 @@ for (const spec of Object.values(VIDEO_MODEL_DISCLOSURES)) {if (value && typeof value === 'object') Object.freeze(value);}Object.freeze(spec.disclosure);+ if (spec.termsGate) {+ Object.freeze(spec.termsGate.excludedTerritories);+ Object.freeze(spec.termsGate);+ }Object.freeze(spec);}@@ -224,14 +266,28 @@ export const applyVideoDisclosures = (list) => {if (!Array.isArray(list)) return list;return list.map((entry) => {if (!entry || typeof entry !== 'object' || typeof entry.id !== 'string') return entry;- if ('disclosure' in entry) return entry;const spec = VIDEO_MODEL_DISCLOSURES[entry.id];if (!spec) return entry;if (spec.shippedRepo !== null && entry.repo !== spec.shippedRepo) return entry;- return { ...entry, disclosure: spec.disclosure };+ return {+ ...entry,+ ...(!('disclosure' in entry) ? { disclosure: spec.disclosure } : {}),+ // A shipped restricted model cannot silently lose its required gate+ // through an old/user-edited registry entry. Forked repos are excluded by+ // the guard above because PortOS has not established their terms.+ ...(spec.termsGate ? { termsGate: spec.termsGate } : {}),+ };});};+// Exact-key comparison keeps acceptance scoped to one reviewed license+// version. A true-ish boolean from an old UI (or another model's acceptance)+// cannot authorize a newly reviewed terms block by accident.+export const isVideoModelTermsAccepted = (model, acceptanceKey) => {+ const required = model?.termsGate?.id;+ return typeof required !== 'string' || required.length === 0 || acceptanceKey === required;+};+/*** Execution + policy scope for each Video Gen render backend. Server-owned so* the client never has to author (or drift on) the wording.diff --git a/server/lib/videoDisclosure.test.js b/server/lib/videoDisclosure.test.jsindex ca696eb764..dd622d32b7 100644--- a/server/lib/videoDisclosure.test.js+++ b/server/lib/videoDisclosure.test.js@@ -4,6 +4,7 @@ import {VIDEO_BACKEND_DISCLOSURES,VIDEO_DISCLOSURE_REVIEWED_AT,applyVideoDisclosures,+ isVideoModelTermsAccepted,videoBackendDisclosure,} from './videoDisclosure.js';@@ -74,6 +75,19 @@ describe('VIDEO_MODEL_DISCLOSURES', () => {expect(() => { VIDEO_MODEL_DISCLOSURES.wan22_ti2v_5b.disclosure.weightsLicense.name = 'hacked'; }).toThrow();expect(VIDEO_MODEL_DISCLOSURES.wan22_ti2v_5b.disclosure.weightsLicense.name).toBe(before);});++ it('publishes the exact MiniMax H3 territory gate and pinned license', () => {+ const h3 = VIDEO_MODEL_DISCLOSURES.minimax_h3_8bit;+ expect(h3.disclosure.estimatedDownloadGb).toBe(103.3);+ expect(h3.termsGate.id).toBe('minimax-h3-community-license-2026-08-02');+ expect(h3.termsGate.excludedTerritories).toEqual([+ 'European Union',+ 'United Kingdom',+ 'Republic of Korea',+ 'United States of America',+ ]);+ expect(h3.termsGate.licenseUrl).toContain('/blob/6818f6c32d12b210915e44ad56a4228c2608f160/LICENSE');+ });});describe('applyVideoDisclosures', () => {@@ -120,6 +134,31 @@ describe('applyVideoDisclosures', () => {expect(applyVideoDisclosures(null)).toBe(null);expect(applyVideoDisclosures([null, 42, { name: 'no id' }])).toEqual([null, 42, { name: 'no id' }]);});++ it('reattaches the shipped H3 execution gate even if an old registry omitted it', () => {+ const [entry] = applyVideoDisclosures([{+ id: 'minimax_h3_8bit',+ repo: 'pipenetwork/MiniMax-H3-MLX-8bit',+ runtime: 'minimax_h3',+ }]);+ expect(entry.termsGate).toBe(VIDEO_MODEL_DISCLOSURES.minimax_h3_8bit.termsGate);+ });+});++describe('isVideoModelTermsAccepted', () => {+ const restricted = { termsGate: VIDEO_MODEL_DISCLOSURES.minimax_h3_8bit.termsGate };++ it('requires the exact versioned key for a restricted model', () => {+ expect(isVideoModelTermsAccepted(restricted)).toBe(false);+ expect(isVideoModelTermsAccepted(restricted, true)).toBe(false);+ expect(isVideoModelTermsAccepted(restricted, 'another-license')).toBe(false);+ expect(isVideoModelTermsAccepted(restricted, restricted.termsGate.id)).toBe(true);+ });++ it('does not gate an unrestricted or malformed model entry', () => {+ expect(isVideoModelTermsAccepted({})).toBe(true);+ expect(isVideoModelTermsAccepted(null)).toBe(true);+ });});describe('VIDEO_BACKEND_DISCLOSURES', () => {diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 28be99091b..b8f352984c 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -16,7 +16,7 @@ import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.jimport { uploadFields } from '../lib/multipart.js';import { PATHS } from '../lib/fileUtils.js';import { grokVideoDurationSchema } from '../lib/validation.js';-import { VIDEO_BACKEND_DISCLOSURES } from '../lib/videoDisclosure.js';+import { VIDEO_BACKEND_DISCLOSURES, isVideoModelTermsAccepted } from '../lib/videoDisclosure.js';import { IMAGE_GEN_MODE } from '../services/imageGen/modes.js';import { getSettings } from '../services/settings.js';import { checkPackages, isAllowedPython } from '../lib/pythonSetup.js';@@ -170,6 +170,10 @@ const generateBodySchema = z.object({),prompt: z.string().min(1).max(8000),negativePrompt: z.string().max(8000).optional(),+ // Exact, versioned acceptance key for a model carrying `termsGate`. A+ // boolean is deliberately insufficient: accepting one reviewed license must+ // not authorize a later license revision or an unrelated restricted model.+ termsAcceptance: z.string().min(1).max(128).optional(),modelId: z.string().max(64).optional(),width: optionalNum(64, 2048, 'width'),height: optionalNum(64, 2048, 'height'),@@ -361,8 +365,11 @@ router.get('/setup/runtime-status', asyncHandler(async (req, res) => {);}const binaryPresent = isByovRuntimeInstalled(info.id);- const packagesReady = binaryPresent ? await isByovRuntimeReady(info.id) : false;- const current = packagesReady ? await isByovRuntimeCurrent(info.id) : false;+ // Check the immutable source pin before the import probe. Source-only+ // runtimes execute checkout code while importing, so an outdated or dirty+ // checkout must surface Upgrade / Repair without being loaded first.+ const current = binaryPresent ? await isByovRuntimeCurrent(info.id) : false;+ const packagesReady = current ? await isByovRuntimeReady(info.id) : false;res.json({runtime: info.id,label: info.label,@@ -370,7 +377,7 @@ router.get('/setup/runtime-status', asyncHandler(async (req, res) => {binaryPresent,packagesReady,current,- upgradeAvailable: binaryPresent && packagesReady && !current,+ upgradeAvailable: binaryPresent && !current,venvPath: info.venvPython,repoDir: info.repoDir,repoUrl: info.repoUrl,@@ -431,9 +438,9 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {// needs Upgrade; treating either as "already installed" strands the user// behind a button that can never perform the action it advertises.const alreadyInstalled = isByovRuntimeInstalled(info.id);- const alreadyReady = alreadyInstalled && await isByovRuntimeReady(info.id);+ const alreadyCurrent = alreadyInstalled && await isByovRuntimeCurrent(info.id);if (aborted) return safeEnd();- const alreadyCurrent = alreadyReady && await isByovRuntimeCurrent(info.id);+ const alreadyReady = alreadyCurrent && await isByovRuntimeReady(info.id);if (aborted) return safeEnd();if (alreadyInstalled && alreadyReady && alreadyCurrent) {runtimeInstallInFlight.delete(info.id);@@ -503,8 +510,8 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {// packages. Probe both the binary AND the import surface so the// success message can't lie. The banner gate uses the same probe.const binaryPresent = isByovRuntimeInstalled(info.id);- const packagesReady = binaryPresent && await isByovRuntimeReady(info.id);- const current = packagesReady && await isByovRuntimeCurrent(info.id);+ const current = binaryPresent && await isByovRuntimeCurrent(info.id);+ const packagesReady = current && await isByovRuntimeReady(info.id);if (code === 0 && binaryPresent && packagesReady && current) {emit({ type: 'complete', message: `${info.label} ready: ${info.venvPython}` });} else if (code === 0 && !binaryPresent) {@@ -717,6 +724,12 @@ router.post('/models/:modelId/repair', asyncHandler(async (req, res) => {router.get('/models/:modelId/download', asyncHandler(async (req, res) => {const model = listVideoModels().find((m) => m.id === req.params.modelId);if (!model) throw new ServerError(`Unknown video model: ${req.params.modelId}`, { status: 404 });+ if (!isVideoModelTermsAccepted(model, req.query.termsAcceptance)) {+ throw new ServerError(+ `${model.name} requires acknowledgement of its territory restrictions, Community License, and Acceptable Use Policy before download.`,+ { status: 403, code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED' },+ );+ }const repos = modelDownloadTargets(model);if (repos.length === 0) throw new ServerError(`Model "${model.id}" has no HuggingFace repo on file.`, { status: 400, code: 'NO_REPO_FOR_MODEL' });const runtimeInfo = BYOV_RUNTIME_INFO[model.runtime];@@ -887,6 +900,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {pythonPath,prompt: body.prompt,negativePrompt: body.negativePrompt || '',+ ...(body.termsAcceptance ? { termsAcceptance: body.termsAcceptance } : {}),modelId: body.modelId,width: body.width,height: body.height,diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 8cf5d47215..1ef50e8eed 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -71,11 +71,17 @@ vi.mock('../services/videoGen/local.js', () => ({// hunyuan bring their own venv). Mirror the real export so the// "accepts BYOV-runtime when pythonPath missing" case passes and the// negative case (legacy mlx_video model) still 400s.- BYOV_VIDEO_RUNTIMES: new Set(['ltx2', 'wan22', 'hunyuan']),+ BYOV_VIDEO_RUNTIMES: new Set(['ltx2', 'wan22', 'minimax_h3', 'hunyuan']),// The route's /status response now surfaces the BYOV runtime list so the// client can drop its hardcoded copy. Mirror the real shape — only the// `id` and a couple of UI-display fields are read by /status.BYOV_RUNTIME_INFO: {+ minimax_h3: {+ id: 'minimax_h3', label: 'MiniMax H3 MLX', venvPython: '/tmp/minimax-h3.py',+ installEnvVar: 'INSTALL_MINIMAX_H3', pinEnvVar: 'MINIMAX_H3_PIN',+ expectedRevision: 'fcd9e9b79a1d6018d91ac477c0968de1fa067e49',+ repoUrl: 'x', repoDir: '/tmp',+ },ltx2: { id: 'ltx2', label: 'LTX-2 MLX', venvPython: '/tmp/ltx2.py', installEnvVar: 'INSTALL_LTX2', repoUrl: 'x', repoDir: '/tmp' },wan22: {id: 'wan22', label: 'Wan 2.2 MLX', venvPython: '/tmp/wan22.py',@@ -98,6 +104,23 @@ vi.mock('../services/videoGen/local.js', () => ({})),}));+const sseDownload = vi.hoisted(() => ({+ start: vi.fn(async ({ res }) => {+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });+ res.end('data: {"type":"complete"}\n\n');+ }),+}));+vi.mock('../lib/sseDownload.js', () => ({+ startHfDownloadStream: sseDownload.start,+ openSseStream: (res) => {+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });+ return {+ send: (event) => { if (!res.writableEnded) res.write(`data: ${JSON.stringify(event)}\n\n`); },+ safeEnd: () => { if (!res.writableEnded) res.end(); },+ };+ },+}));+// Render submissions go through the mediaJobQueue. Mock its surface so the// route tests stay synchronous and don't kick off the worker loop.vi.mock('../services/mediaJobQueue/index.js', () => ({@@ -340,15 +363,15 @@ describe('videoGen routes', () => {});});- it('offers an upgrade for a ready runtime on an outdated checkout', async () => {+ it('offers an upgrade without importing an outdated checkout', async () => {videoGenService.isByovRuntimeInstalled.mockReturnValueOnce(true);- videoGenService.isByovRuntimeReady.mockResolvedValueOnce(true);videoGenService.isByovRuntimeCurrent.mockResolvedValueOnce(false);const r = await request(app).get('/api/video-gen/setup/runtime-status?runtime=wan22');expect(r.body).toMatchObject({- installed: false, binaryPresent: true, packagesReady: true,+ installed: false, binaryPresent: true, packagesReady: false,current: false, upgradeAvailable: true,});+ expect(videoGenService.isByovRuntimeReady).not.toHaveBeenCalled();});});@@ -400,6 +423,85 @@ describe('videoGen routes', () => {});});+ describe('GET /models/:modelId/download — restricted terms', () => {+ const h3CheckpointFiles = ['LICENSE', 'FL2VA/model_index.json', 'FL2VA/video_vae/source/model.safetensors'];+ const h3 = {+ id: 'minimax_h3_8bit',+ name: 'MiniMax H3 MLX 8-bit',+ runtime: 'minimax_h3',+ repo: 'pipenetwork/MiniMax-H3-MLX-8bit',+ revision: '3ac52081470b0488921c3ec3ba84a39097bf2361',+ termsGate: { id: 'minimax-h3-community-license-2026-08-02' },+ supportedModes: ['text'],+ defaultFrames: 124,+ frameOptions: [124, 141, 158],+ fpsOptions: [24],+ steps: 8,+ guidance: 0,+ samplerLocked: true,+ requiredWeights: [{+ repo: 'MiniMaxAI/MiniMax-H3',+ revision: '6818f6c32d12b210915e44ad56a4228c2608f160',+ files: h3CheckpointFiles,+ }],+ };++ it('rejects a missing or stale acceptance key before opening a download stream', async () => {+ videoGenService.listVideoModels+ .mockReturnValueOnce([h3])+ .mockReturnValueOnce([h3]);++ const missing = await request(app).get('/api/video-gen/models/minimax_h3_8bit/download');+ expect(missing.status).toBe(403);+ expect(missing.body.code).toBe('VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED');++ const stale = await request(app)+ .get('/api/video-gen/models/minimax_h3_8bit/download?termsAcceptance=old-license');+ expect(stale.status).toBe(403);+ expect(stale.body.code).toBe('VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED');+ });++ it('downloads both exact snapshots after the exact acceptance key', async () => {+ videoGenService.listVideoModels.mockReturnValueOnce([h3]);+ const accepted = await request(app).get(+ '/api/video-gen/models/minimax_h3_8bit/download?termsAcceptance=minimax-h3-community-license-2026-08-02',+ );+ expect(accepted.status).toBe(200);+ expect(sseDownload.start).toHaveBeenCalledWith(expect.objectContaining({+ repos: [+ {+ repo: 'pipenetwork/MiniMax-H3-MLX-8bit',+ revision: '3ac52081470b0488921c3ec3ba84a39097bf2361',+ only: [],+ },+ {+ repo: 'MiniMaxAI/MiniMax-H3',+ revision: '6818f6c32d12b210915e44ad56a4228c2608f160',+ only: h3CheckpointFiles,+ },+ ],+ }));+ });++ it('persists the exact acceptance key on the queued render', async () => {+ videoGenService.listVideoModels.mockReturnValueOnce([h3]);+ const accepted = await request(app).post('/api/video-gen/').send({+ prompt: 'a fox watches the rain',+ modelId: h3.id,+ mode: 'text',+ termsAcceptance: h3.termsGate.id,+ });+ expect(accepted.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'video',+ params: expect.objectContaining({+ modelId: h3.id,+ termsAcceptance: h3.termsGate.id,+ }),+ }));+ });+ });+describe('POST / — grok backend (#2859 phase 2)', () => {it('enqueues a grok video job with the saved grok config and no local-python dependency', async () => {const { getSettings } = await import('../services/settings.js');diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 5fe1e81908..d9078462c3 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -32,6 +32,7 @@ import { safeChildProcessEnv } from '../../lib/processEnv.js';import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess, describeSignalDeath, describeRenderConditioning, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';import { assertSafeLoraFilename } from '../loras.js';import { isMlxVideoLtxLoraCapable } from '../../lib/runners.js';+import { isVideoModelTermsAccepted } from '../../lib/videoDisclosure.js';import {isIcLoraMode, icLoraSpecForMode, resolveIcLoraWeight,assertIcReferenceCount, icResolutionIssue,@@ -41,6 +42,10 @@ import {LTX2_HELPER_SCRIPT,WAN22_VENV_PYTHON,WAN22_HELPER_SCRIPT,+ MINIMAX_H3_VENV_PYTHON,+ MINIMAX_H3_HELPER_SCRIPT,+ MINIMAX_H3_REPO_DIR,+ MINIMAX_H3_EXPECTED_REVISION,HUNYUAN_VENV_PYTHON,HUNYUAN_HELPER_SCRIPT,HUNYUAN_REPO_DIR,@@ -568,6 +573,122 @@ const buildWan22Args = ({ model, wanModelPath, wanRequiredWeights, prompt, negatreturn { bin: WAN22_VENV_PYTHON, args };};+// 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 assertMiniMaxH3TextOnly = ({+ mode,+ sourceImagePath,+ uploadedTempPath,+ uploadedTempPaths,+ lastImagePath,+ keyframes,+ extendFromVideoPath,+ audioFilePath,+ audioStartSec,+ icReferencePaths,+}) => {+ const requestedMode = mode || ((sourceImagePath || uploadedTempPath) ? 'image' : 'text');+ const hasUploadedKeyframes = Array.isArray(uploadedTempPaths) && uploadedTempPaths.length > 0;+ const hasIcReferences = Array.isArray(icReferencePaths)+ ? icReferencePaths.length > 0+ : icReferencePaths != null;+ if (+ requestedMode !== 'text'+ || sourceImagePath+ || uploadedTempPath+ || hasUploadedKeyframes+ || lastImagePath+ || keyframes != null+ || extendFromVideoPath+ || audioFilePath+ || audioStartSec != null+ || hasIcReferences+ ) {+ throw new ServerError(+ 'MiniMax H3 MLX currently supports text-to-video only; remove image, keyframe, video, audio, or reference conditioning.',+ { status: 400, code: 'MINIMAX_H3_MODE_UNSUPPORTED' },+ );+ }+};++const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath }) => {+ assertByovRuntimeInstalled('minimax_h3');+ assertMiniMaxH3TextOnly({+ mode,+ sourceImagePath,+ lastImagePath,+ keyframes,+ extendFromVideoPath,+ audioFilePath,+ audioStartSec,+ icReferencePaths,+ });+ if (negativePrompt?.trim()) {+ throw new ServerError(+ 'MiniMax H3 is CFG-distilled and does not accept a negative prompt.',+ { status: 400, code: 'MINIMAX_H3_NEGATIVE_PROMPT_UNSUPPORTED' },+ );+ }+ if (disableAudio) {+ throw new ServerError(+ 'MiniMax H3 jointly generates video and audio; its audio track cannot be disabled.',+ { status: 400, code: 'MINIMAX_H3_AUDIO_REQUIRED' },+ );+ }+ if (tiling && tiling !== 'auto') {+ throw new ServerError(+ 'MiniMax H3 does not expose a tiling mode.',+ { status: 400, code: 'MINIMAX_H3_TILING_UNSUPPORTED' },+ );+ }+ if (!Array.isArray(model.frameOptions) || !model.frameOptions.includes(Number(numFrames))) {+ throw new ServerError(+ `MiniMax H3 requires a 17n+5 frame count between 124 and 362; got ${numFrames}.`,+ { status: 400, code: 'MINIMAX_H3_INVALID_FRAME_COUNT' },+ );+ }+ if (Number(fps) !== 24) {+ throw new ServerError(+ `MiniMax H3 runs at a fixed 24 fps; got ${fps}.`,+ { status: 400, code: 'MINIMAX_H3_INVALID_FPS' },+ );+ }+ if (typeof model.repo !== 'string' || typeof model.revision !== 'string') {+ throw new ServerError(+ `MiniMax H3 model "${model.id}" is missing its pinned transformer repo or revision.`,+ { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },+ );+ }+ const checkpoint = Array.isArray(model.requiredWeights) ? model.requiredWeights[0] : null;+ const files = Array.isArray(checkpoint?.files) ? checkpoint.files : [];+ if (!checkpoint?.repo || !checkpoint?.revision || files.length === 0) {+ throw new ServerError(+ `MiniMax H3 model "${model.id}" is missing its pinned upstream checkpoint files.`,+ { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },+ );+ }+ const args = [+ MINIMAX_H3_HELPER_SCRIPT,+ '--runtime-dir', MINIMAX_H3_REPO_DIR,+ '--runtime-revision', MINIMAX_H3_EXPECTED_REVISION,+ '--model-repo', model.repo,+ '--model-revision', model.revision,+ '--checkpoint-repo', checkpoint.repo,+ '--checkpoint-revision', checkpoint.revision,+ '--prompt', prompt,+ '--width', String(width),+ '--height', String(height),+ '--num-frames', String(numFrames),+ '--fps', String(fps),+ '--steps', String(steps),+ '--seed', String(seed),+ '--output', outputPath,+ ];+ for (const file of files) args.push('--checkpoint-file', file);+ return { bin: MINIMAX_H3_VENV_PYTHON, args };+};+// Allowed precision tokens for runners that expose dtype as a CLI flag. The// Python side already gates argparse with `choices=`, but a bogus value in// data/media-models.json would otherwise reach the helper and surface as a@@ -642,6 +763,9 @@ const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeightif (model.runtime === 'wan22') {return 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 });+ }if (model.runtime === 'hunyuan') {return buildHunyuanArgs({ model, prompt, negativePrompt, width, height, numFrames, steps, guidance, seed, outputPath });}@@ -735,7 +859,7 @@ export const DEFAULT_NUM_FRAMES = 121;// a still regardless of how many frames carry it.export const IC_STILL_REFERENCE_FRAMES = 9;-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = DEFAULT_NUM_FRAMES, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, 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 = '', termsAcceptance = null, modelId = defaultVideoModelId(), width = 768, height = 512, 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 }) {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@@ -745,6 +869,35 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mconst model = resolveVideoModel(modelId);if (!model) throw new ServerError(`Unknown video model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });+ // Final execution-boundary gate. Route preparation also rejects early, but+ // internal producers, persisted jobs, and retry all reach this function+ // directly. The exact versioned key makes old queued jobs fail closed after+ // a future license revision instead of inheriting stale acceptance.+ if (!isVideoModelTermsAccepted(model, termsAcceptance)) {+ throw new ServerError(+ `${model.name} requires acknowledgement of its territory restrictions, Community License, and Acceptable Use Policy before generation.`,+ { status: 403, code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED' },+ );+ }+ // Validate H3's strict T2V-only contract before cache lookups, image resize,+ // or staging-file work. Internal producers and persisted/retried jobs bypass+ // route preparation, so silently dropping one of these inputs here would+ // render a materially different video than the caller requested.+ if (model.runtime === 'minimax_h3') {+ assertMiniMaxH3TextOnly({+ mode,+ sourceImagePath,+ uploadedTempPath,+ uploadedTempPaths,+ lastImagePath,+ keyframes,+ extendFromVideoPath,+ audioFilePath,+ audioStartSec,+ icReferencePaths,+ });+ }+ numFrames = numFrames ?? model.defaultFrames ?? DEFAULT_NUM_FRAMES;let wanModelPath = null;const wanRequiredWeights = [];if (model.runtime === 'wan22') {@@ -1165,13 +1318,24 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// python helpers can authenticate snapshot_download() against gated repos// (mirrors the imageGen child-spawn pattern). LTX-2 doesn't currently use// a gated repo, but the merge is harmless when no token is configured.- const childEnv = await hfChildEnv();+ const childEnv = model.runtime === 'minimax_h3'+ ? safeChildProcessEnv()+ : await hfChildEnv();delete childEnv.PYTHONPATH;// Force unbuffered Python I/O so tqdm + loguru + our own STAGE: prints flush// immediately. Without this, child stdio is line-buffered against a pipe and// long inference loops emit nothing to handleLine() for minutes — the UI// looks dead even when the model is making progress.childEnv.PYTHONUNBUFFERED = '1';+ if (model.runtime === 'minimax_h3') {+ // The H3 repositories are public and the runner is cache-only. Do not hand+ // it an ambient saved HF credential it neither needs nor may transmit.+ delete childEnv.HF_TOKEN;+ delete childEnv.HUGGING_FACE_HUB_TOKEN;+ childEnv.HF_HUB_DISABLE_IMPLICIT_TOKEN = '1';+ childEnv.HF_HUB_OFFLINE = '1';+ childEnv.TRANSFORMERS_OFFLINE = '1';+ }// `spawnDetached` double-forks the render child so it reparents to init// (PPID=1) and leaves pm2's process tree — without this a `pm2 restart// portos-server` (e.g. on the memory ceiling) SIGINTs the in-flight render@@ -1185,7 +1349,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', menv: childEnv,controlDir: join(PATHS.videos, '.detached', jobId),cleanup: true,- killProcessGroup: model.runtime === 'wan22',+ killProcessGroup: model.runtime === 'wan22' || model.runtime === 'minimax_h3',});activeProcess = proc;@@ -1501,11 +1665,15 @@ export async function generateChainedVideo({ chunks, chunkPrompts, jobId: outerJif (!outerJobId) throw new ServerError('generateChainedVideo requires jobId', { status: 500, code: 'INTERNAL' });const chainModel = resolveVideoModel(rest.modelId || defaultVideoModelId());- if (chainModel?.runtime === 'wan22'- && !(Array.isArray(chainModel.supportedModes) && chainModel.supportedModes.includes('image'))) {+ if (Array.isArray(chainModel?.supportedModes) && !chainModel.supportedModes.includes('image')) {throw new ServerError(`${chainModel.name} cannot generate chunks > 1 because continuation requires image-to-video support.`,- { status: 400, code: 'WAN22_CHAIN_REQUIRES_IMAGE_MODE' },+ {+ status: 400,+ code: chainModel.runtime === 'wan22'+ ? 'WAN22_CHAIN_REQUIRES_IMAGE_MODE'+ : 'VIDEO_CHAIN_REQUIRES_IMAGE_MODE',+ },);}diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex a19bb65703..f0cf98164d 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -42,6 +42,20 @@ vi.mock('../../lib/mediaModels.js', () => ({{ id: 'ltx23_unified', name: 'LTX-2.3 Unified Beta', runtime: 'mlx_video', repo: 'notapalindrome/ltx23-mlx-av', steps: 25, guidance: 3.0 },// quantized mlx_video model — NOT LoRA-capable (out of scope).{ id: 'ltx23_distilled_q4', name: 'LTX-2.3 Distilled Q4', runtime: 'mlx_video', repo: 'notapalindrome/ltx23-mlx-av-q4', steps: 25, guidance: 3.0 },+ {+ id: 'minimax_h3_8bit', name: 'MiniMax H3 MLX 8-bit', runtime: 'minimax_h3',+ repo: 'pipenetwork/MiniMax-H3-MLX-8bit',+ revision: '3ac52081470b0488921c3ec3ba84a39097bf2361',+ supportedModes: ['text'], defaultFrames: 124,+ frameOptions: [124, 141, 158], fpsOptions: [24],+ steps: 8, guidance: 0, samplerLocked: true,+ termsGate: { id: 'minimax-h3-community-license-2026-08-02' },+ requiredWeights: [{+ repo: 'MiniMaxAI/MiniMax-H3',+ revision: '6818f6c32d12b210915e44ad56a4228c2608f160',+ files: ['LICENSE', 'FL2VA/vae/video/config.json'],+ }],+ },{id: 'wan22_ti2v_5b', name: 'Wan TI2V', runtime: 'wan22',repo: 'AbstractFramework/wan2.2-ti2v-5b-diffusers-8bit',@@ -1734,6 +1748,104 @@ describe('generateVideo — Wan MLX-Gen contract', () => {});});+describe('generateVideo — MiniMax H3 MLX contract', () => {+ it('requires the exact reviewed terms key at the render boundary', async () => {+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ vi.mocked(spawnDetached).mockClear();+ const base = {+ jobId: 'h3-terms',+ modelId: 'minimax_h3_8bit',+ prompt: 'a fox watches the rain',+ width: 512, height: 320, numFrames: 141, fps: 24,+ mode: 'text',+ };++ await expect(generateVideo(base)).rejects.toMatchObject({+ status: 403,+ code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED',+ });+ await expect(generateVideo({ ...base, termsAcceptance: 'old-license' })).rejects.toMatchObject({+ status: 403,+ code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED',+ });+ expect(spawnDetached).not.toHaveBeenCalled();+ });++ it.each([+ ['uploaded image', { uploadedTempPath: '/mock/source.png' }],+ ['keyframes', { keyframes: [{ path: '/mock/first.png', frame: 0 }, { path: '/mock/last.png', frame: 140 }] }],+ ['extension video', { extendFromVideoPath: '/mock/prior.mp4' }],+ ['audio file', { audioFilePath: '/mock/audio.wav' }],+ ['IC reference', { icReferencePaths: ['/mock/reference.mp4'] }],+ ])('rejects direct %s conditioning before any child is spawned', async (_label, conditioning) => {+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ vi.mocked(spawnDetached).mockClear();++ await expect(generateVideo({+ jobId: 'h3-conditioning',+ modelId: 'minimax_h3_8bit',+ termsAcceptance: 'minimax-h3-community-license-2026-08-02',+ prompt: 'a fox watches the rain',+ width: 512, height: 320, numFrames: 141, fps: 24,+ ...conditioning,+ })).rejects.toMatchObject({ code: 'MINIMAX_H3_MODE_UNSUPPORTED' });++ expect(spawnDetached).not.toHaveBeenCalled();+ });++ it('uses the pinned cache-only helper, locked sampler and credential-free environment', async () => {+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ const { hfChildEnv } = await import('../../lib/hfToken.js');+ const spawnMock = vi.mocked(spawnDetached);+ spawnMock.mockClear();+ vi.mocked(hfChildEnv).mockClear();+ const priorToken = process.env.HF_TOKEN;+ const priorHubToken = process.env.HUGGING_FACE_HUB_TOKEN;+ process.env.HF_TOKEN = 'test-secret';+ process.env.HUGGING_FACE_HUB_TOKEN = 'test-secret-2';++ try {+ await generateVideo({+ jobId: 'h3-args',+ modelId: 'minimax_h3_8bit',+ termsAcceptance: 'minimax-h3-community-license-2026-08-02',+ prompt: 'a fox watches the rain',+ width: 512, height: 320, numFrames: 141, fps: 24,+ steps: 99, guidanceScale: 12, mode: 'text',+ });+ } finally {+ if (priorToken === undefined) delete process.env.HF_TOKEN; else process.env.HF_TOKEN = priorToken;+ if (priorHubToken === undefined) delete process.env.HUGGING_FACE_HUB_TOKEN;+ else process.env.HUGGING_FACE_HUB_TOKEN = priorHubToken;+ }++ const call = spawnMock.mock.calls.find(([, args]) => (+ Array.isArray(args) && args.some((arg) => String(arg).endsWith('/generate_minimax_h3.py'))+ ));+ expect(call).toBeDefined();+ const [bin, args, options] = call;+ expect(bin).toMatch(/\.portos\/minimax-h3-mlx\/\.venv\/bin\/python3$/);+ expect(args[args.indexOf('--model-repo') + 1]).toBe('pipenetwork/MiniMax-H3-MLX-8bit');+ expect(args[args.indexOf('--model-revision') + 1]).toBe('3ac52081470b0488921c3ec3ba84a39097bf2361');+ expect(args[args.indexOf('--runtime-revision') + 1]).toBe('fcd9e9b79a1d6018d91ac477c0968de1fa067e49');+ expect(args[args.indexOf('--checkpoint-repo') + 1]).toBe('MiniMaxAI/MiniMax-H3');+ expect(args[args.indexOf('--checkpoint-revision') + 1]).toBe('6818f6c32d12b210915e44ad56a4228c2608f160');+ expect(args[args.indexOf('--steps') + 1]).toBe('8');+ expect(args.flatMap((arg, i) => arg === '--checkpoint-file' ? [args[i + 1]] : []))+ .toEqual(['LICENSE', 'FL2VA/vae/video/config.json']);+ expect(options.killProcessGroup).toBe(true);+ expect(options.env).toMatchObject({+ HF_HUB_DISABLE_IMPLICIT_TOKEN: '1',+ HF_HUB_OFFLINE: '1',+ TRANSFORMERS_OFFLINE: '1',+ PYTHONUNBUFFERED: '1',+ });+ expect(options.env).not.toHaveProperty('HF_TOKEN');+ expect(options.env).not.toHaveProperty('HUGGING_FACE_HUB_TOKEN');+ expect(hfChildEnv).not.toHaveBeenCalled();+ });+});+describe('runtime fingerprint (/status)', () => {it('hostRuntimeFingerprint reports chip/os/platform/arch/node', async () => {const { hostRuntimeFingerprint } = await import('./local.js');diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.jsindex 381172213c..db2f301af7 100644--- a/server/services/videoGen/prepareParams.js+++ b/server/services/videoGen/prepareParams.js@@ -33,6 +33,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { PATHS, ensureDir, resolveGalleryImage } from '../../lib/fileUtils.js';import { safeUnder } from '../../lib/ffmpeg.js';import { RENDER_TARGET } from '../../lib/renderTargets.js';+import { isVideoModelTermsAccepted } from '../../lib/videoDisclosure.js';import { videoLoraFamily } from '../../lib/runners.js';import {IC_LORA_MODE_VALUES, icLoraSpecForMode,@@ -153,6 +154,13 @@ export async function prepareVideoGenParams({ body, uploads, localOnlyParamKeys{ status: 400, code: 'VIDEO_GEN_UNKNOWN_MODEL' },);}+ if (backend !== VIDEO_GEN_MODE.GROK && effectiveModel && !isVideoModelTermsAccepted(effectiveModel, body.termsAcceptance)) {+ await cleanupMultipartTemp(uploads);+ throw new ServerError(+ `${effectiveModel.name} requires acknowledgement of its territory restrictions, Community License, and Acceptable Use Policy before generation.`,+ { status: 403, code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED' },+ );+ }// Reject up-front when the local python isn't configured AND the model's// runtime needs it. ltx2/wan22/hunyuan bring their own venv (resolved// inside buildArgs), so they must NOT be blocked by the legacy mlx_video@@ -385,6 +393,66 @@ async function resolvePreparedParams({{ status: 400, code: 'A2V_REQUIRES_LTX2' },);}+ // MiniMax H3's released MLX path is text-only, fixed-24fps, joint A/V and+ // CFG-distilled. Fail before queue persistence so a direct API caller cannot+ // enqueue a request whose controls the runtime would silently ignore.+ if (effectiveModel?.runtime === 'minimax_h3') {+ const hasImageInput = Boolean(+ uploads.sourceImage || uploads.lastImage || body.sourceImageFile+ || body.lastImageFile || body.keyframes?.length || body.extendFromVideoId,+ );+ if ((body.mode && body.mode !== 'text') || hasImageInput) {+ await cleanupStaged();+ throw new ServerError(+ 'MiniMax H3 MLX currently supports text-to-video only; remove image/keyframe conditioning.',+ { status: 400, code: 'MINIMAX_H3_MODE_UNSUPPORTED' },+ );+ }+ if (body.negativePrompt?.trim()) {+ await cleanupStaged();+ throw new ServerError(+ 'MiniMax H3 is CFG-distilled and does not accept a negative prompt.',+ { status: 400, code: 'MINIMAX_H3_NEGATIVE_PROMPT_UNSUPPORTED' },+ );+ }+ if (body.disableAudio === true || body.disableAudio === 'true') {+ await cleanupStaged();+ throw new ServerError(+ 'MiniMax H3 jointly generates video and audio; its audio track cannot be disabled.',+ { status: 400, code: 'MINIMAX_H3_AUDIO_REQUIRED' },+ );+ }+ if (body.tiling && body.tiling !== 'auto') {+ await cleanupStaged();+ throw new ServerError(+ 'MiniMax H3 does not expose a tiling mode.',+ { status: 400, code: 'MINIMAX_H3_TILING_UNSUPPORTED' },+ );+ }+ if (body.chunks != null && Number(body.chunks) > 1) {+ await cleanupStaged();+ throw new ServerError(+ `${effectiveModel.name} cannot generate chunks > 1 because continuation requires image-to-video support.`,+ { status: 400, code: 'VIDEO_CHAIN_REQUIRES_IMAGE_MODE' },+ );+ }+ const frames = Number(body.numFrames ?? effectiveModel.defaultFrames);+ if (!Array.isArray(effectiveModel.frameOptions) || !effectiveModel.frameOptions.includes(frames)) {+ await cleanupStaged();+ throw new ServerError(+ `MiniMax H3 requires a 17n+5 frame count between 124 and 362; got ${frames}.`,+ { status: 400, code: 'MINIMAX_H3_INVALID_FRAME_COUNT' },+ );+ }+ const fps = Number(body.fps ?? 24);+ if (fps !== 24) {+ await cleanupStaged();+ throw new ServerError(+ `MiniMax H3 runs at a fixed 24 fps; got ${fps}.`,+ { status: 400, code: 'MINIMAX_H3_INVALID_FPS' },+ );+ }+ }// Wan profiles have narrower mode + temporal-shape contracts than the// shared request schema can express. Mirror the worker's guards here so a// direct API caller cannot persist a job that is already known to fail.diff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.jsindex 884f65ef16..8d781912ad 100644--- a/server/services/videoGen/prepareParams.test.js+++ b/server/services/videoGen/prepareParams.test.js@@ -13,7 +13,7 @@ vi.mock('./local.js', () => ({listVideoModels: vi.fn(() => [{ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2' }]),defaultVideoModelId: vi.fn(() => 'ltx2_unified'),loadHistory: vi.fn(async () => []),- BYOV_VIDEO_RUNTIMES: new Set(['ltx2', 'wan22', 'hunyuan']),+ BYOV_VIDEO_RUNTIMES: new Set(['ltx2', 'wan22', 'minimax_h3', 'hunyuan']),DEFAULT_NUM_FRAMES: 121,}));@@ -45,7 +45,7 @@ import { unlink } from 'fs/promises';import { resolveGalleryImage } from '../../lib/fileUtils.js';import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';import { getTrack } from '../tracks/index.js';-import { listVideoModels, loadHistory } from './local.js';+import { listVideoModels, defaultVideoModelId, loadHistory } from './local.js';import { prepareVideoGenParams, withStagedRollback, cleanupMultipartTemp } from './prepareParams.js';// Field names the route owns Zod schemas for; the service only needs the keys@@ -64,6 +64,18 @@ const prepare = (body, uploads = {}) => prepareVideoGenParams({localOnlyParamKeys: LOCAL_ONLY_KEYS,});+const H3_TERMS = 'minimax-h3-community-license-2026-08-02';+const H3_MODEL = {+ id: 'minimax_h3_8bit',+ name: 'MiniMax H3 MLX 8-bit',+ runtime: 'minimax_h3',+ supportedModes: ['text'],+ defaultFrames: 124,+ frameOptions: [124, 141, 158],+ fpsOptions: [24],+ termsGate: { id: H3_TERMS },+};+// Paths unlinked under PATHS.uploads — i.e. the durable copies the service// staged, as opposed to the OS temp files the multipart parser wrote.const unlinkedDurablePaths = () => unlink.mock.calls@@ -356,3 +368,58 @@ describe('prepareVideoGenParams', () => {});});});++describe('prepareVideoGenParams — MiniMax H3 contract', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ listVideoModels.mockReturnValue([H3_MODEL]);+ loadHistory.mockResolvedValue([]);+ });++ it('requires the exact reviewed terms key before generation', async () => {+ await expect(prepare({ modelId: H3_MODEL.id, mode: 'text' }))+ .rejects.toMatchObject({ status: 403, code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED' });+ await expect(prepare({ modelId: H3_MODEL.id, mode: 'text', termsAcceptance: 'wrong' }))+ .rejects.toMatchObject({ status: 403, code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED' });++ const prepared = await prepare({ modelId: H3_MODEL.id, mode: 'text', termsAcceptance: H3_TERMS });+ expect(prepared.effectiveModelId).toBe(H3_MODEL.id);+ expect(prepared.effectiveChunks).toBe(1);+ });++ it('does not apply the local MiniMax gate to an explicit Grok render', async () => {+ defaultVideoModelId.mockReturnValueOnce(H3_MODEL.id);+ const prepared = await prepare({ backend: 'grok' });+ expect(prepared.backend).toBe('grok');+ expect(prepared.grok).toMatchObject({ grokPath: '/usr/bin/grok' });+ });++ it.each([+ [{ mode: 'image' }, 'MINIMAX_H3_MODE_UNSUPPORTED'],+ [{ extendFromVideoId: '00000000-0000-4000-8000-000000000001' }, 'MINIMAX_H3_MODE_UNSUPPORTED'],+ [{ negativePrompt: 'blur' }, 'MINIMAX_H3_NEGATIVE_PROMPT_UNSUPPORTED'],+ [{ disableAudio: true }, 'MINIMAX_H3_AUDIO_REQUIRED'],+ [{ tiling: 'full' }, 'MINIMAX_H3_TILING_UNSUPPORTED'],+ [{ chunks: 2 }, 'VIDEO_CHAIN_REQUIRES_IMAGE_MODE'],+ [{ numFrames: 125 }, 'MINIMAX_H3_INVALID_FRAME_COUNT'],+ [{ fps: 30 }, 'MINIMAX_H3_INVALID_FPS'],+ ])('rejects an unsupported H3 request (%o)', async (fields, code) => {+ await expect(prepare({+ modelId: H3_MODEL.id,+ mode: 'text',+ termsAcceptance: H3_TERMS,+ ...fields,+ })).rejects.toMatchObject({ status: 400, code });+ });++ it('accepts another supported temporal shape at fixed 24 fps', async () => {+ const prepared = await prepare({+ modelId: H3_MODEL.id,+ mode: 'text',+ termsAcceptance: H3_TERMS,+ numFrames: 158,+ fps: 24,+ });+ expect(prepared.effectiveModelId).toBe(H3_MODEL.id);+ });+});diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.jsindex a82378f883..726b657e20 100644--- a/server/services/videoGen/runtimes.js+++ b/server/services/videoGen/runtimes.js@@ -31,6 +31,15 @@ export const WAN22_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_wan22.pexport const WAN22_REPO_DIR = join(homedir(), '.portos', 'mlx-gen');export const WAN22_EXPECTED_REVISION = '2452f0c12edcc8886eebf15772205ce9c417a618';+// MiniMax H3 MLX runtime — PipeNetwork's Apple-Silicon port, provisioned only+// after the user selects Install in Video Gen. The model weights remain a+// separate, explicitly accepted/downloaded Hugging Face operation.+export const MINIMAX_H3_VENV_PYTHON = join(homedir(), '.portos', 'minimax-h3-mlx', '.venv', 'bin', 'python3');+export const MINIMAX_H3_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_minimax_h3.py');+export const MINIMAX_H3_RUNTIME_PROBE_SCRIPT = join(PATHS.root, 'scripts', 'minimax_h3_runtime_probe.py');+export const MINIMAX_H3_REPO_DIR = join(homedir(), '.portos', 'minimax-h3-mlx');+export const MINIMAX_H3_EXPECTED_REVISION = 'fcd9e9b79a1d6018d91ac477c0968de1fa067e49';+// HunyuanVideo MLX runtime — gaurav-nelson/HunyuanVideo_MLX cloned at// ~/.portos/hunyuan-video-mlx/. ~60 GB resident at bf16 so practical only// with the 4-bit Gemma text encoder + everything else evicted. Provisioned@@ -51,13 +60,32 @@ const RUNTIME_FINGERPRINT_SCRIPT = join(PATHS.root, 'scripts', 'runtime_fingerpr// source of truth: the BYOV_VIDEO_RUNTIMES Set + the /setup/runtime-* routes// + the client install banner all derive from this map's keys.//-// `importProbe` is a tiny Python expression run by isByovRuntimeReady() to+// `importProbe` (or `probeArgs` for a dedicated script) is run by+// isByovRuntimeReady() to// confirm the venv's *packages* are actually installed (not just the venv// binary). A partial install (e.g. setup script aborted after `uv venv`// before `uv pip install`) leaves the binary present but no torch — without// this probe the UI would hide the install banner and renders would fail// with a deep ImportError inside the runner script.export const BYOV_RUNTIME_INFO = Object.freeze({+ minimax_h3: {+ id: 'minimax_h3',+ label: 'MiniMax H3 MLX',+ venvPython: MINIMAX_H3_VENV_PYTHON,+ repoDir: MINIMAX_H3_REPO_DIR,+ installEnvVar: 'INSTALL_MINIMAX_H3',+ repoUrl: 'https://github.com/PipeNetwork/minimax-h3-mlx',+ expectedRevision: MINIMAX_H3_EXPECTED_REVISION,+ // Source-only runtime: both status and the render helper verify this+ // package is clean so a modified/untracked module cannot shadow the pin.+ sourcePath: 'minimax_h3_mlx',+ pinEnvVar: 'MINIMAX_H3_PIN',+ // The port is source-only rather than pip-installed. The dedicated probe+ // registers only the source package namespace; it never prepends the whole+ // checkout, where an untracked root module could shadow a locked venv dep.+ probeArgs: [MINIMAX_H3_RUNTIME_PROBE_SCRIPT, MINIMAX_H3_REPO_DIR],+ fingerprintPackages: ['mlx', 'mlx-metal', 'mlx-vlm', 'transformers', 'huggingface-hub'],+ },hunyuan: {id: 'hunyuan',label: 'HunyuanVideo MLX',@@ -125,9 +153,14 @@ export async function isByovRuntimeReady(runtimeId) {const info = BYOV_RUNTIME_INFO[runtimeId];if (!info) return false;if (!existsSync(info.venvPython)) return false;+ // Never execute a source checkout until its immutable revision and scoped+ // executable package have passed the clean-status check. Keep this ahead of+ // the positive readiness cache too: a checkout can be edited after an+ // earlier successful probe.+ if (info.expectedRevision && !await isByovRuntimeCurrent(runtimeId)) return false;if (readyCache.get(runtimeId) === true) return true;const probeOk = await new Promise((resolve) => {- const child = spawn(info.venvPython, ['-c', info.importProbe], {+ const child = spawn(info.venvPython, info.probeArgs || ['-c', info.importProbe], {env: safeChildProcessEnv(),stdio: ['ignore', 'ignore', 'ignore'],});@@ -142,19 +175,34 @@ export async function isByovRuntimeReady(runtimeId) {// Resolve a checkout's exact revision without trusting a mutable tag/branch.// Runtimes without an expectedRevision remain current by definition. A stale// pinned checkout makes the UI offer Repair / Upgrade; nothing runs at boot.+export function isPinnedSourceStatusClean(stdout, expectedRevision) {+ const lines = String(stdout).split(/\r?\n/).filter(Boolean);+ const oid = lines.find((line) => line.startsWith('# branch.oid '))?.slice('# branch.oid '.length);+ return oid === expectedRevision && lines.every((line) => line.startsWith('# '));+}+export async function isByovRuntimeCurrent(runtimeId) {const info = BYOV_RUNTIME_INFO[runtimeId];if (!info?.expectedRevision) return true;if (!existsSync(join(info.repoDir, '.git'))) return false;return new Promise((resolve) => {let stdout = '';- const child = spawn('git', ['-C', info.repoDir, 'rev-parse', 'HEAD'], {+ const args = info.sourcePath+ ? ['-C', info.repoDir, 'status', '--porcelain=v2', '--branch', '--untracked-files=all', '--', info.sourcePath]+ : ['-C', info.repoDir, 'rev-parse', 'HEAD'];+ const child = spawn('git', args, {env: safeChildProcessEnv(),stdio: ['ignore', 'pipe', 'ignore'],});const timer = setTimeout(() => { if (!child.killed) child.kill('SIGKILL'); resolve(false); }, 10000);child.stdout.on('data', (chunk) => { if (stdout.length < 128) stdout += chunk.toString(); });- child.on('close', (code) => { clearTimeout(timer); resolve(code === 0 && stdout.trim() === info.expectedRevision); });+ child.on('close', (code) => {+ clearTimeout(timer);+ const current = info.sourcePath+ ? isPinnedSourceStatusClean(stdout, info.expectedRevision)+ : stdout.trim() === info.expectedRevision;+ resolve(code === 0 && current);+ });child.on('error', () => { clearTimeout(timer); resolve(false); });});}diff --git a/server/services/videoGen/runtimes.test.js b/server/services/videoGen/runtimes.test.jsnew file mode 100644index 0000000000..193386c73f--- /dev/null+++ b/server/services/videoGen/runtimes.test.js@@ -0,0 +1,70 @@+import { EventEmitter } from 'node:events';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const runtimeMocks = vi.hoisted(() => ({+ existsSync: vi.fn(() => true),+ spawn: vi.fn(),+}));++vi.mock('fs', async (importOriginal) => ({+ ...await importOriginal(),+ existsSync: runtimeMocks.existsSync,+}));+vi.mock('child_process', async (importOriginal) => ({+ ...await importOriginal(),+ spawn: runtimeMocks.spawn,+}));++import { invalidateByovReadyCache, isByovRuntimeReady, isPinnedSourceStatusClean } from './runtimes.js';++const REVISION = 'fcd9e9b79a1d6018d91ac477c0968de1fa067e49';++const statusChild = (stdout) => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.kill = vi.fn();+ queueMicrotask(() => {+ child.stdout.emit('data', Buffer.from(stdout));+ child.emit('close', 0);+ });+ return child;+};++beforeEach(() => {+ invalidateByovReadyCache();+ runtimeMocks.existsSync.mockReset().mockReturnValue(true);+ runtimeMocks.spawn.mockReset();+});++describe('isPinnedSourceStatusClean', () => {+ it('accepts the exact revision when the scoped source package is clean', () => {+ expect(isPinnedSourceStatusClean([+ `# branch.oid ${REVISION}`,+ '# branch.head (detached)',+ '',+ ].join('\n'), REVISION)).toBe(true);+ });++ it.each([+ [`# branch.oid ${'0'.repeat(40)}\n# branch.head main\n`, 'stale revision'],+ [`# branch.oid ${REVISION}\n1 .M N... 100644 100644 100644 abc abc minimax_h3_mlx/pipeline.py\n`, 'tracked edit'],+ [`# branch.oid ${REVISION}\n? minimax_h3_mlx/shadow.py\n`, 'untracked module'],+ ])('rejects a %s', (stdout) => {+ expect(isPinnedSourceStatusClean(stdout, REVISION)).toBe(false);+ });+});++describe('isByovRuntimeReady', () => {+ it('does not execute the import probe when the H3 source checkout is stale', async () => {+ runtimeMocks.spawn.mockImplementationOnce(() => statusChild([+ `# branch.oid ${'0'.repeat(40)}`,+ '# branch.head main',+ '',+ ].join('\n')));++ await expect(isByovRuntimeReady('minimax_h3')).resolves.toBe(false);++ expect(runtimeMocks.spawn).toHaveBeenCalledTimes(1);+ expect(runtimeMocks.spawn.mock.calls[0][0]).toBe('git');+ });+});