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
make restricted video-model license acceptance an install-wide record, and show the gate where renders start
[._.]/ Adam Eivy953d3f351421
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 11eb3629dc..ca0b428e23 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,9 @@# Unreleased+## Media++- **Accepting a restricted model's license now counts everywhere, and the acceptance appears where you're blocked.** Generating a music video scene with MiniMax H3 failed with "requires acknowledgement of its territory restrictions, Community License, and Acceptable Use Policy" — even for someone who had already ticked exactly that box on the Video Gen page, because the acknowledgement was only remembered in that page's browser storage and no other screen had a way to show it. The acknowledgement is now a property of the install: accept it once, on any screen, and every render path is authorized — the Video Gen page, the music video scene board, and background producers like pipeline stages and scheduled agent runs that have no way to ask you. The music video board also shows the acknowledgement panel inline next to its renderer picker, so the terms are readable and acceptable on the screen that triggers the render; when a render is refused anyway, the message now says where the acceptance is made instead of naming rules with no way to reach them. Acceptance is keyed to the exact reviewed license version, so a future revision asks again rather than inheriting an old approval. And because the recorded acknowledgement is the *only* thing that authorizes a render — a request can no longer assert its own — withdrawing it takes effect everywhere at once, including on work already sitting in the render queue.+## Music Video- **[issue-3718] Scene frames, scene clips, and the final render open full-size in the shared media lightbox.** The scene board no longer traps generated media at thumbnail size — click a reference frame, or the expand control on a clip or the finished render, to inspect it full-size with prev/next across every asset in the project and a deep-linkable URL. Clip and final-render expand controls sit in the corner so the inline players' play/pause still work; the final render uses its real resolved filename so a `music-video-*.mp4` plays instead of a 404.diff --git a/PLAN.md b/PLAN.mdindex 5f87c603c7..9b751cca81 100644--- a/PLAN.md+++ b/PLAN.md@@ -346,3 +346,7 @@ is not reliably announced.### Collapse the dashboard grid's two coordinate systems into one- [ ] Since widget cells became content-measured (`packVertically` in `client/src/components/dashboard/DashboardGrid.jsx`), `y` and `h` carry two contradictory jobs. The renderer packs in PIXELS and treats `y` as reading order only; but `placeAndCompact` still resolves rectangle collisions on `{x,y,w,h}`, `reflowToOrder` still tracks `rowMaxH`, and `GRID_ROW_MAX` still clamps `y` as a position. `toPackSpace` exists purely to reconcile the two, so every gesture round-trips pixels → rows → compact → rows to keep them agreeing. Not a correctness bug — the round-trip is what makes them agree — but anyone touching drag has to hold both models at once, which is why `toPackSpace` needs a six-line comment to justify itself. **The call to make:** demote the persisted shape to `{ id, x, w, order, h?, fixedH? }`, delete `overlaps` + the y-compaction entirely, and let the pack own vertical placement outright. Keep `h` as the first-paint/older-client fallback (that compatibility story is the reason it survives at all — see the `fixedH` note in the dashboard CLAUDE.md). Blocked on nothing technical; it needs a migration in `scripts/migrations/` that rewrites each stored layout's grid to the new shape (`data/dashboard-layouts.json`, plus the seven `DEFAULT_LAYOUTS`/`INTENT_LAYOUTS` grids in `server/services/dashboardLayouts.js`) and a version-gated read so an install that has not upgraded still gets usable geometry. Surfaced by the /simplify altitude review.++### Show the restricted-model license gate on the remaining video render surfaces++- [ ] A restricted video model's license acknowledgement is now an install-wide recorded fact (`settings.videoGen.acceptedModelTerms`, written through `POST /api/video-gen/model-terms`), and `ModelTermsGate` + `useVideoModelTerms` are shared so any surface can render the acceptance UI. Two do: `client/src/pages/VideoGen.jsx` and the music-video board (`client/src/pages/MusicVideo.jsx` via `useMusicVideoModelSettings`). The other surfaces that let a user pin a video model still dead-end on the server's 403 the first time — before anything has been accepted anywhere: `client/src/pages/CreativeDirector.jsx` (`<ModelSelect>` per project), `client/src/components/creative-commission/CommissionConfigForm.jsx` (`videoModelId`, including cron-scheduled runs), `client/src/components/pipeline/stages/EpisodeVideoStage.jsx`, `client/src/components/media/MediaJobsQueue.jsx`'s edit-and-retry (free-text `modelId`, re-enqueued via `server/routes/mediaJobs.js` so it never passes through `prepareVideoGenParams`), and `client/src/components/media/PromptRefineModal.jsx`'s requeue. **The call to make:** don't hand-wire a gate into five components — handle `VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED` once, centrally, so future surfaces are covered for free: catch the code in `client/src/services/apiCore.js`'s error path (and in the media-job failure channel, where a queue-time rejection arrives as a message with no `code` — `server/lib/videoDisclosure.js#videoModelTermsError` is the single wording to match on) and open a `ModelTermsGate` modal seeded from the failing model's `termsGate`. The interim mitigation already shipped: that error names where the acknowledgement is made, so a blocked user on any surface has a path. Surfaced by the /simplify altitude review.diff --git a/client/src/components/musicVideo/ProjectToolbar.jsx b/client/src/components/musicVideo/ProjectToolbar.jsxindex d915f58bf0..d212c1056c 100644--- a/client/src/components/musicVideo/ProjectToolbar.jsx+++ b/client/src/components/musicVideo/ProjectToolbar.jsx@@ -98,10 +98,11 @@ export default function ProjectToolbar({</button><buttononClick={sceneMedia.generateMissingVideos}- disabled={videoSettings.saving || sceneCount === 0 || missingVideoCount === 0 || referenceFrameCount !== sceneCount || generatingVideos || (videoSettings.audioReactiveSelected && !videoSettings.audioReactiveReady)}- title={referenceFrameCount !== sceneCount- ? 'Generate every reference frame first'- : (missingVideoCount > 0 ? `Generate ${missingVideoCount} missing scene video${missingVideoCount === 1 ? '' : 's'}` : 'Every scene has a video')}+ disabled={videoSettings.saving || sceneCount === 0 || missingVideoCount === 0 || referenceFrameCount !== sceneCount || generatingVideos || !!videoSettings.videoBlockedReason}+ title={videoSettings.videoBlockedReason+ || (referenceFrameCount !== sceneCount+ ? 'Generate every reference frame first'+ : (missingVideoCount > 0 ? `Generate ${missingVideoCount} missing scene video${missingVideoCount === 1 ? '' : 's'}` : 'Every scene has a video'))}className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50"><Video size={15} /> Videos {renderableSceneCount}/{sceneCount}diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsxindex c732d2e7f9..6ae3535aea 100644--- a/client/src/components/musicVideo/SceneCard.jsx+++ b/client/src/components/musicVideo/SceneCard.jsx@@ -17,7 +17,7 @@ const SCENE_TIME_FIELDS = [['Start', 'startSec'], ['End', 'endSec']];*/export default function SceneCard({scene, index, isLast, generatingFrame, generatingVideo,- settingsSaving, videoBlocked, canContinueShot,+ settingsSaving, videoBlockedReason, canContinueShot,onMove, onDelete, onEditLocal, onSave,onGenerateFrame, onGenerateVideo, onContinueVideo,onOpenPreview,@@ -137,9 +137,10 @@ export default function SceneCard({</div>)}<button onClick={() => onGenerateVideo(scene)}- disabled={settingsSaving || !scene.referenceImageId || !!generatingVideo || videoBlocked}+ disabled={settingsSaving || !scene.referenceImageId || !!generatingVideo || !!videoBlockedReason}className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"- title={scene.referenceImageId ? "Generate this scene's video from its reference frame (i2v)" : 'Generate a reference frame first'}>+ title={videoBlockedReason+ || (scene.referenceImageId ? "Generate this scene's video from its reference frame (i2v)" : 'Generate a reference frame first')}>{generatingVideo ? <Activity size={14} className="animate-spin" /> : <Video size={14} />}{generatingVideo ? 'Generating video…' : (scene.videoHistoryId ? 'Regenerate video' : 'Generate video')}</button>diff --git a/client/src/components/videoGen/FactLink.jsx b/client/src/components/videoGen/FactLink.jsxnew file mode 100644index 0000000000..bed94f6719--- /dev/null+++ b/client/src/components/videoGen/FactLink.jsx@@ -0,0 +1,18 @@+// Outbound link to a primary source (a model card, a license text) as rendered+// by the disclosure surfaces. Shared by ModelDisclosure and ModelTermsGate so+// the two halves of one panel can't drift apart on link affordance.+import { ExternalLink } from 'lucide-react';++export default function FactLink({ href, children }) {+ return (+ <a+ href={href}+ target="_blank"+ rel="noreferrer noopener"+ className="inline-flex items-center gap-1 text-port-accent hover:underline break-all"+ >+ {children}+ <ExternalLink className="w-3 h-3 shrink-0" aria-hidden="true" />+ </a>+ );+}diff --git a/client/src/components/videoGen/ModelDisclosure.jsx b/client/src/components/videoGen/ModelDisclosure.jsxindex f834748e90..f465e97bff 100644--- a/client/src/components/videoGen/ModelDisclosure.jsx+++ b/client/src/components/videoGen/ModelDisclosure.jsx@@ -13,8 +13,11 @@// place (server/lib/videoDisclosure.js) and can't drift here.//// It is deliberately NOT part of `ModelSelect` — that component selects models-// and must stay a plain picker.-import { ExternalLink, Server, Cloud, ShieldAlert, CheckCircle } from 'lucide-react';+// and must stay a plain picker, and it is deliberately NOT where a restricted+// model's terms gate lives: that is an execution gate every render surface+// needs, so it is its own component (`ModelTermsGate`) rendered beside this one.+import { Server, Cloud } from 'lucide-react';+import FactLink from './FactLink.jsx';const UNKNOWN = 'Unknown';@@ -31,20 +34,6 @@ function Fact({ label, children }) {);}-function FactLink({ href, children }) {- return (- <a- href={href}- target="_blank"- rel="noreferrer noopener"- className="inline-flex items-center gap-1 text-port-accent hover:underline break-all"- >- {children}- <ExternalLink className="w-3 h-3 shrink-0" aria-hidden="true" />- </a>- );-}-function LicenseFact({ label, license }) {return (<Fact label={label}>@@ -82,9 +71,6 @@ export default function ModelDisclosure({backendDisclosures,model,systemMemoryGb,- termsAccepted = false,- onTermsAcceptedChange,- termsDescriptionId,}) {const list = Array.isArray(backendDisclosures) ? backendDisclosures : [];const backendInfo = list.find((b) => b?.id === backend) || null;@@ -93,9 +79,6 @@ export default function ModelDisclosure({// 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;@@ -104,45 +87,7 @@ export default function ModelDisclosure({: null;return (- <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">+ <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" />@@ -205,7 +150,6 @@ export default function ModelDisclosure({</section>)}</div>- </details>- </div>+ </details>);}diff --git a/client/src/components/videoGen/ModelDisclosure.test.jsx b/client/src/components/videoGen/ModelDisclosure.test.jsxindex 8c33c02ab5..b01b6da876 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, vi } from 'vitest';-import { fireEvent, render, screen, within } from '@testing-library/react';+import { describe, it, expect } from 'vitest';+import { render, screen, within } from '@testing-library/react';import ModelDisclosure from './ModelDisclosure.jsx';const BACKENDS = [@@ -134,31 +134,13 @@ describe('ModelDisclosure', () => {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',- },- };+ // The restricted-model terms gate is NOT part of this component — it is an+ // execution gate every render surface renders for itself (ModelTermsGate).+ it('never renders a terms gate, even for a model that declares one', () => {renderDisclosure({backend: 'local',- model: restricted,- termsAccepted: false,- onTermsAcceptedChange: onChange,- termsDescriptionId: 'model-terms',+ model: { ...SHIPPED_MODEL, termsGate: { id: 'example-license-v1', title: 'Territory and 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);+ expect(screen.queryByLabelText('Model terms acceptance')).toBeNull();});});diff --git a/client/src/components/videoGen/ModelTermsGate.jsx b/client/src/components/videoGen/ModelTermsGate.jsxnew file mode 100644index 0000000000..7707d30a4c--- /dev/null+++ b/client/src/components/videoGen/ModelTermsGate.jsx@@ -0,0 +1,64 @@+// Restricted-model license gate — the acknowledgement UI for a video model+// whose registry entry carries a `termsGate` (server/lib/videoDisclosure.js).+//+// It lives in its own component because the gate is not a Video Gen page+// concern: any surface that can start a render (the music video director+// board, a future storyboard renderer) must be able to show it. A render+// surface that only reports the server's 403 leaves the user with no way to+// resolve it — so wherever a gated model can be selected, this renders.+//+// Wording comes verbatim from the server's gate block; nothing is authored here.+import { ShieldAlert, CheckCircle } from 'lucide-react';+import FactLink from './FactLink.jsx';++export default function ModelTermsGate({+ termsGate,+ accepted = false,+ onAcceptedChange,+ disabled = false,+ descriptionId,+ inputId = 'model-terms-accept',+}) {+ if (!termsGate || typeof termsGate !== 'object') return null;+ return (+ <section+ id={descriptionId}+ aria-label="Model terms acceptance"+ className={`rounded-xl border px-3 py-3 text-xs ${accepted+ ? '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">+ {accepted+ ? <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 htmlFor={inputId} className="flex items-start gap-2 text-gray-200 cursor-pointer">+ <input+ id={inputId}+ type="checkbox"+ checked={accepted}+ disabled={disabled}+ onChange={(event) => onAcceptedChange?.(event.target.checked)}+ className="mt-0.5 rounded disabled:opacity-50"+ />+ <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.+ Accepting applies to every render on this install.+ </p>+ </div>+ </div>+ </section>+ );+}diff --git a/client/src/components/videoGen/ModelTermsGate.test.jsx b/client/src/components/videoGen/ModelTermsGate.test.jsxnew file mode 100644index 0000000000..dbc7562271--- /dev/null+++ b/client/src/components/videoGen/ModelTermsGate.test.jsx@@ -0,0 +1,41 @@+import { describe, it, expect, vi } from 'vitest';+import { fireEvent, render, screen, within } from '@testing-library/react';+import ModelTermsGate from './ModelTermsGate.jsx';++const GATE = {+ 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',+};++describe('ModelTermsGate', () => {+ it('renders the server-authored terms and reports an acceptance', () => {+ const onChange = vi.fn();+ render(+ <ModelTermsGate termsGate={GATE} accepted={false} onAcceptedChange={onChange} descriptionId="model-terms" />,+ );+ const gate = screen.getByLabelText('Model terms acceptance');+ // The id is what a blocked Generate/Download button points its+ // aria-describedby at, so a screen reader gets the reason it's disabled.+ expect(gate).toHaveAttribute('id', 'model-terms');+ expect(within(gate).getByText(GATE.summary)).toBeInTheDocument();+ expect(within(gate).getByText(/cannot determine your location or legal eligibility/i)).toBeInTheDocument();+ expect(within(gate).getByRole('link', { name: /Community License/i }))+ .toHaveAttribute('href', GATE.licenseUrl);+ fireEvent.click(within(gate).getByRole('checkbox'));+ expect(onChange).toHaveBeenCalledWith(true);+ });++ it('locks the checkbox while the acceptance is being persisted', () => {+ render(<ModelTermsGate termsGate={GATE} accepted onAcceptedChange={vi.fn()} disabled />);+ expect(screen.getByRole('checkbox')).toBeChecked();+ expect(screen.getByRole('checkbox')).toBeDisabled();+ });++ it('renders nothing for an ungated model', () => {+ const { container } = render(<ModelTermsGate termsGate={null} />);+ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 80acbcbeb1..bd5d8c82c0 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -192,13 +192,14 @@ grep -i "what you want to do" client/src/hooks/README.md| `useYoutubeTrackImport` | One YouTube-audio-import job slot (#1945): start/cancel + SSE progress + terminal-frame handling via `POST /api/tracks/import/youtube`. Returns `{ active, percent, start(url, context), cancel }`; `onComplete(track, context)` fires with the finished Track. Call once per UI surface that can independently kick off an import — a shared slot would let one surface's kickoff orphan another's in-flight job. | Any picker that lets a user paste a YouTube URL to create a Track (Music Video's create form and track-change row). || `useVideoGenForm` | `useVideoGenForm({ models, status, availableLoras, grokEnabled })` → every VideoGen form field + setter, the URL-param prefill paths (ImageGen handoff, Continue, Remix, `?lora=`), the mode/backend transitions that clear stale inputs, the derived model/keyframe/IC gates (`extendModeBlocked`, `a2vModeBlocked`, `icLoraModeBlocked`, `keyframesError`), `applyRemix` / `applyResumedParams`, and `buildGeneratePayload()`. | The /media/video form — the single client-side source of truth for the payload `server/routes/videoGen.js` validates. Reuse it for any second entry point that generates video. || `useVideoGenQueue` | `useVideoGenQueue({ generating, runGeneration })` → `{ queue, runningQueueId, enqueue, removeFromQueue, clearFinishedQueue, cancelRunning }`. Client-side serial batch queue for VideoGen: owns the queue array + running marker + the worker effect that pumps the head whenever nothing is generating (with BUSY-backoff retry + unmount/staleness guards). | The VideoGen "Add to queue" batch flow. |+| `useVideoModelTerms` | `useVideoModelTerms()` → `{ accepted, loaded, saving, isAccepted(termsId), setAcceptance(termsId, value), refresh }`. The install-wide acknowledgement list for restricted video-model license gates (`model.termsGate`), read/written through `/api/video-gen/model-terms` so accepting once authorizes every render surface (and every background producer). `accepted` is `null` until loaded — distinct from `[]`. | Any surface that can select or render a gated video model — pair it with `ModelTermsGate` so the acknowledgement the server demands is resolvable where the render is triggered, instead of surfacing as a bare 403. || `useVideoDownload` | One full-video-download job slot (#1946): start/cancel + SSE progress + terminal-frame handling via `POST /api/devtools/video-download`. Returns `{ active, percent, stage, start(url), cancel }`; `onComplete(video)` fires with the finished video-history entry. | The Dev Tools Video Downloader page. || `useReferenceAudioImport` | One round reference-audio-import job slot (#2120): start/cancel + SSE progress + terminal-frame handling via `POST /api/rounds/reference-audio/import`. Returns `{ active, percent, stage, start(url, context), cancel }`; `onComplete(filename, context)` fires with the uploads-dir filename to persist on the reference. Call once per surface that can independently kick off a download. | The reference-audio attach controls (`ReferenceAudioAttach`) — the "Download from URL" convenience. || `useMidiTranscription` | One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass `startRequest`/`eventsUrl`/`cancelRequest`). Returns `{ active, stage, stageLabel, context, start(context), cancel }` (`stageLabel` is the ready-to-render human label for the current STAGE — including a distinct "Downloading model…" for the first-use weight download, which also fires a one-time toast; `context` is the in-flight job's captured target, for per-target UI gates); `onComplete(frame, context)` fires with the terminal frame (`filename`, `model`, any server-merged extras). | The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. || `useMusicVideoYoutubeImport` | The Music Video page's two independent `useYoutubeTrackImport` slots (create form + detail-view track row) plus their URL drafts, the detail slot's captured target project, and the URL-nav backstop that bounces a deep link / Back / ⌘K jump away from an in-flight import back to its project. Returns `{ createUrl, setCreateUrl, editUrl, setEditUrl, createJob, editJob, startCreate, startEdit, switchBlockedMessage }`. | The Music Video page. Reuse `switchBlockedMessage` for any additional guard (delete, list picker) so every surface says the same thing. || `useMusicVideoMidiJob` | `useMidiTranscription` bound to the music-video API surface, plus the MuScriptor model-size picker state (read fresh at each kickoff). Returns the slot (`active`/`stage`/`stageLabel`/`context`/`start(projectId)`/`cancel`/`installGate`/`gatedGate`) plus `{ model, setModel }`; `onTranscribed(projectId, midiTranscription)` fires on a non-discarded terminal frame. | The Music Video MIDI button + model select. || `useMusicVideoRenderJob` | The final-render job (#1760 Phase 2): kickoff (409 → attach to the existing job), SSE progress, terminal-frame handling and non-terminal stream-close recovery. Returns `{ job, progress, start(projectId), cancel }`; `onRendered(projectId, result)` / `onFailed(projectId)` key on the projectId captured at kickoff. | The Music Video "Render final" control. |-| `useMusicVideoModelSettings` | A project's saved render pins — video backend/model/generation-mode/audio-reactive LoRA + the image-side frame pin — with the Video Gen catalog they read from. Optimistic-local + silent PATCH, rollback + toast on failure; `saving` gates the dependent generate buttons. Returns `{ models, modelsLoading, defaultModel, saving, settings, effectiveModelId, activeModel, audioReactiveModels, audioReactiveLoras, detectedAudioReactiveLora, audioReactiveReady, audioReactiveSelected, change, changeFramePin }`. | The Music Video renderer selects and anything building a scene-clip job payload from them. |+| `useMusicVideoModelSettings` | A project's saved render pins — video backend/model/generation-mode/audio-reactive LoRA + the image-side frame pin — with the Video Gen catalog they read from. Optimistic-local + silent PATCH, rollback + toast on failure; `saving` gates the dependent generate buttons. Returns `{ models, modelsLoading, defaultModel, saving, settings, effectiveModelId, activeModel, audioReactiveModels, audioReactiveLoras, detectedAudioReactiveLora, audioReactiveReady, audioReactiveSelected, termsGate, termsAccepted, termsSaving, videoBlockedReason, acceptTerms, refreshTerms, change, changeFramePin }`. `videoBlockedReason` is the single "why can't I generate" string (unaccepted model license terms, or an unavailable audio-reactive setup) shared by the disabled buttons, their tooltips, and the blocked-call toast. | The Music Video renderer selects and anything building a scene-clip job payload from them. || `useMusicVideoSceneMedia` | Both per-scene generation lanes (reference frame + scene clip) over `useSceneRenderLifecycle`, the frame/shot prompt builders (concept-style suffix), and the batch "generate the missing ones" actions. Returns `{ genScenes, genVideoScenes, buildFramePrompt, buildShotPrompt, generateFrame, generateSceneVideo, continueSceneVideo, generateMissingFrames, generateMissingVideos }`. | The Music Video scene board — don't re-wire the two lanes or re-derive the i2v/a2v/extend payloads. || `useMusicVideoManualTempo` | The manual-tempo fallback for a project whose auto-detected BPM is null: BPM/offset drafts (reset on project switch), tap-tempo estimation, and the persisted `setMusicVideoManualTempo` call. Returns `{ bpm, setBpm, offset, setOffset, saving, tap, submit }`. | The Music Video "No tempo detected" row. || `useCanvasDprSize` | DevicePixelRatio-aware canvas sizing shared by the piano-roll renderers (`<PianoRoll>`, `<MidiPianoRoll>`): sizes the bitmap to container-width × height at the DPR, applies the transform, and redraws via a `drawRef` on mount + every `ResizeObserver` resize (observer created once per height, never churned by draw-closure changes). Returns a ref holding the current CSS width so draw code doesn't measure the DOM per frame. | Both piano-roll canvases. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 9f5fcfc34c..43d0d8015d 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -186,5 +186,6 @@ export * from './useTwinEvaluationSuite.js';export * from './useUniverseNav.js';export * from './useVideoFileSrc.js';export * from './useVideoGenForm.js';+export { default as useVideoModelTerms } from './useVideoModelTerms.js';export * from './useVideoGenQueue.js';export * from './useVoiceUiSync.js';diff --git a/client/src/hooks/useModelDownloadStatus.js b/client/src/hooks/useModelDownloadStatus.jsindex 374103f0eb..9d8d13c06e 100644--- a/client/src/hooks/useModelDownloadStatus.js+++ b/client/src/hooks/useModelDownloadStatus.js@@ -19,7 +19,7 @@ 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.-export const buildDownloadUrl = (kind, modelId, force = false, termsAcceptance = null) => {+export const buildDownloadUrl = (kind, modelId, force = false) => {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@@ -27,7 +27,6 @@ export const buildDownloadUrl = (kind, modelId, force = false, termsAcceptance =// and the deleted shard would never be pulled back.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}`;@@ -56,7 +55,6 @@ 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);@@ -88,7 +86,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, termsAcceptance);+ const downloadUrl = buildDownloadUrl(kind, activeModelId, forceDownload);const sse = useSseProgress(downloadUrl, { enabled: !!downloadUrl });// Refetch on natural stream close. useSseProgress flips `closed:true` once@@ -115,14 +113,12 @@ 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, termsAcceptance: acceptedTerms = null } = {}) => {+ const start = useCallback((modelId, { force = false } = {}) => {setLastError(null);setForceDownload(force);- setTermsAcceptance(acceptedTerms);activeModelIdRef.current = modelId;setActiveModelId(modelId);}, []);@@ -148,7 +144,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, termsAcceptance: acceptedTerms = null } = {}) => {+ const repair = useCallback(async (modelId, { deep = false } = {}) => {if (!modelId) return;setRepairing(true);// The shared text encoder isn't a model id, so its repair hits the scalar@@ -169,7 +165,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, termsAcceptance: acceptedTerms });+ if (result) start(modelId, { force: true });return result;}, [kind, start]);@@ -183,7 +179,6 @@ 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.jsindex 362091e7f8..40ebc0f895 100644--- a/client/src/hooks/useModelDownloadStatus.test.js+++ b/client/src/hooks/useModelDownloadStatus.test.js@@ -2,18 +2,18 @@ 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('builds a plain model download URL', () => {+ // A restricted model's license acknowledgement is NOT a query parameter —+ // the server resolves it from the install record, so a download can't be+ // self-authorized by whoever builds this URL.+ expect(buildDownloadUrl('video', 'minimax_h3_8bit')).toBe(+ '/api/video-gen/models/minimax_h3_8bit/download',+ );});- 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',+ it('adds the repair force flag without changing special routes', () => {+ expect(buildDownloadUrl('video', 'minimax_h3_8bit', true)).toBe(+ '/api/video-gen/models/minimax_h3_8bit/download?force=1',);expect(buildDownloadUrl('video', TEXT_ENCODER_DOWNLOAD_ID, true)).toBe('/api/video-gen/text-encoder/download?force=1',diff --git a/client/src/hooks/useMusicVideoModelSettings.js b/client/src/hooks/useMusicVideoModelSettings.jsindex 638819c057..9227eadab2 100644--- a/client/src/hooks/useMusicVideoModelSettings.js+++ b/client/src/hooks/useMusicVideoModelSettings.js@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';import toast from '../components/ui/Toast';import { updateMusicVideoProject } from '../services/apiMusicVideo.js';import { getVideoGenStatus, listLorasFull } from '../services/apiImageVideo.js';+import useVideoModelTerms from './useVideoModelTerms.js';const isLtx23 = (model) => !!model&& model.runtime === 'ltx2'@@ -76,6 +77,28 @@ export default function useMusicVideoModelSettings({ project, onProjectPatch } =const audioReactiveReady = !!(isLtx23(activeModel) && detectedAudioReactiveLora);const audioReactiveSelected = settings.backend === 'local' && settings.generationMode === 'audioReactive';+ // Restricted-model license gate. A gated model reached from this board used+ // to 403 at generate time with no way to resolve it from here — the+ // acknowledgement UI only existed on the Video Gen page. Acceptance is now+ // install-wide, so this board both reads it and can capture it inline.+ // Grok renders never touch the local registry, so no gate applies there.+ const modelTerms = useVideoModelTerms();+ const termsGate = settings.backend !== 'grok' && activeModel?.termsGate ? activeModel.termsGate : null;+ const termsAccepted = modelTerms.isAccepted(termsGate?.id);+ const termsBlocked = !!termsGate && !termsAccepted;+ const acceptTerms = (accepted) => {+ if (termsGate?.id) modelTerms.setAcceptance(termsGate.id, accepted);+ };++ // One reason string for every scene-video kickoff gate, so the disabled+ // buttons, their tooltips, and the toast a blocked call raises all say the+ // same resolvable thing. `null` means nothing is blocking.+ const videoBlockedReason = termsBlocked+ ? `${termsGate.title || 'This model’s license terms'} must be accepted before generating`+ : (audioReactiveSelected && !audioReactiveReady+ ? 'Audio-reactive generation requires an installed LTX-2.3 audio-reactive LoRA and an LTX-2.3 local model'+ : null);+const change = (patch) => {if (!project || saving) return;const projectId = project.id;@@ -138,6 +161,15 @@ export default function useMusicVideoModelSettings({ project, onProjectPatch } =detectedAudioReactiveLora,audioReactiveReady,audioReactiveSelected,+ termsGate,+ termsAccepted,+ termsSaving: modelTerms.saving,+ videoBlockedReason,+ acceptTerms,+ // Re-read after a render is rejected for terms, so a gate accepted (or+ // withdrawn) elsewhere repaints this board instead of stranding the user+ // on a 403 whose cause is invisible here.+ refreshTerms: modelTerms.refresh,change,changeFramePin,};diff --git a/client/src/hooks/useMusicVideoSceneMedia.js b/client/src/hooks/useMusicVideoSceneMedia.jsindex 48e6dae2cd..e0243ef1aa 100644--- a/client/src/hooks/useMusicVideoSceneMedia.js+++ b/client/src/hooks/useMusicVideoSceneMedia.js@@ -105,6 +105,17 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applySvideoLane.trackJob(jobId, sceneId);};+ // A restricted model's license gate is enforced server-side, so a render can+ // still be rejected for terms the board thought were accepted (accepted on+ // another peer, withdrawn since this page loaded). Refresh the gate state so+ // the acknowledgement panel appears with the checkbox the message is asking+ // for, rather than leaving a 403 the user has nowhere to act on.+ const handleVideoError = (err, sceneId, fallbackMessage) => {+ if (err?.code === 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED') videoSettings?.refreshTerms?.();+ toast.error(err?.message || fallbackMessage);+ videoLane.clearScene(sceneId);+ };+/*** Generate this scene's video from its chosen reference frame via the video* route's image (i2v) mode. The render always rides the media-job queue, so we@@ -117,11 +128,8 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applySif (!scene.referenceImageId) { toast.error('Generate a reference frame first'); return; }const basePrompt = buildShotPrompt(scene);if (!basePrompt) { toast.error('Add a shot prompt first'); return; }- const { settings, audioReactiveSelected, audioReactiveReady, detectedAudioReactiveLora } = videoSettings;- if (audioReactiveSelected && !audioReactiveReady) {- toast.error('Audio-reactive generation requires an installed LTX-2.3 audio-reactive LoRA and an LTX-2.3 local model');- return;- }+ const { settings, audioReactiveSelected, detectedAudioReactiveLora, videoBlockedReason } = videoSettings;+ if (videoBlockedReason) { toast.error(videoBlockedReason); return; }const prompt = audioReactiveSelected? `${basePrompt}. ${AUDIO_REACTIVE_PERFORMANCE_GUARD}`: basePrompt;@@ -147,10 +155,7 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applySmusicVideo: JSON.stringify({ projectId: project.id, sceneId: scene.sceneId }),}).then((res) => trackVideoJob(res, scene.sceneId))- .catch((err) => {- toast.error(err?.message || 'Scene video generation failed');- videoLane.clearScene(scene.sceneId);- });+ .catch((err) => handleVideoError(err, scene.sceneId, 'Scene video generation failed'));};/**@@ -162,11 +167,12 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS*/const continueSceneVideo = (scene) => {if (!scene.videoHistoryId || !scene.referenceImageId) return;- const { settings, activeModel, effectiveModelId } = videoSettings;+ const { settings, activeModel, effectiveModelId, videoBlockedReason } = videoSettings;if (settings.backend !== 'local' || activeModel?.runtime !== 'ltx2') {toast.error('Choose an LTX local model with native continuation support');return;}+ if (videoBlockedReason) { toast.error(videoBlockedReason); return; }videoLane.startScene(scene.sceneId);generateVideo({prompt: buildShotPrompt(scene),@@ -179,10 +185,7 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applySmusicVideo: JSON.stringify({ projectId: project.id, sceneId: scene.sceneId }),}).then((res) => trackVideoJob(res, scene.sceneId))- .catch((err) => {- toast.error(err?.message || 'Shot continuation failed');- videoLane.clearScene(scene.sceneId);- });+ .catch((err) => handleVideoError(err, scene.sceneId, 'Shot continuation failed'));};const scenes = project?.scenes || [];diff --git a/client/src/hooks/useVideoModelTerms.js b/client/src/hooks/useVideoModelTerms.jsnew file mode 100644index 0000000000..6b767fbd7f--- /dev/null+++ b/client/src/hooks/useVideoModelTerms.js@@ -0,0 +1,49 @@+import { useCallback, useEffect, useState } from 'react';+import useAsyncAction from './useAsyncAction.js';+import { getVideoModelTerms, setVideoModelTerms } from '../services/apiImageVideo.js';++/**+ * Install-wide acknowledgement of restricted video-model license gates+ * (`model.termsGate`), persisted in settings rather than in this browser.+ *+ * One person operates a PortOS install, and they reach the same restricted+ * model from several surfaces — the Video Gen page, a music video board, a+ * pipeline stage, an agent run. Acceptance therefore belongs to the install:+ * accepting once here authorizes every render path, and the server enforces+ * the same exact versioned id it stores (a revised license fails closed).+ *+ * `accepted` is `null` until the list is fetched — distinct from `[]`+ * ("fetched, nothing accepted") so a surface can tell "still loading" from+ * "genuinely unaccepted". A failed fetch also leaves it null, and `isAccepted`+ * stays false either way, so the gate fails closed and the user gets the+ * acceptance UI instead of a dead end.+ */+export default function useVideoModelTerms() {+ const [accepted, setAccepted] = useState(null);++ const refresh = useCallback(() => getVideoModelTerms({ silent: true })+ .then((res) => setAccepted(Array.isArray(res?.accepted) ? res.accepted : []))+ .catch(() => {}), []);++ useEffect(() => { refresh(); }, [refresh]);++ const isAccepted = useCallback(+ (termsId) => !!termsId && Array.isArray(accepted) && accepted.includes(termsId),+ [accepted],+ );++ const [writeAcceptance, saving] = useAsyncAction(+ (termsId, value) => setVideoModelTerms(termsId, value, { silent: true })+ .then((res) => setAccepted(Array.isArray(res?.accepted) ? res.accepted : [])),+ { errorMessage: 'Failed to save model terms acceptance' },+ );++ // Resolves to whether the write landed, so a caller can chain a retry of the+ // render the user was blocked on. useAsyncAction resolves to null when the+ // request throws (having already toasted it).+ const setAcceptance = (termsId, value) => (termsId+ ? writeAcceptance(termsId, value).then((result) => result !== null)+ : Promise.resolve(false));++ return { accepted, loaded: accepted !== null, saving, isAccepted, setAcceptance, refresh };+}diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 95879f36d1..c116b0a742 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -36,6 +36,7 @@ import TrackPanel from '../components/musicVideo/TrackPanel.jsx';import RenderStatusPanel from '../components/musicVideo/RenderStatusPanel.jsx';import AnalysisPanel from '../components/musicVideo/AnalysisPanel.jsx';import SceneCard from '../components/musicVideo/SceneCard.jsx';+import ModelTermsGate from '../components/videoGen/ModelTermsGate.jsx';import { autoArrangeScenes } from '../lib/beatGrid.js';import { videoSrcForJob, videoPosterForJob } from '../lib/creativeDirectorPreview.js';@@ -356,7 +357,6 @@ export default function MusicVideo() {const canContinueShot = videoSettings.settings.backend === 'local'&& videoSettings.settings.generationMode === 'image'&& videoSettings.activeModel?.runtime === 'ltx2';- const videoBlocked = videoSettings.audioReactiveSelected && !videoSettings.audioReactiveReady;// Final render filename is NOT the history id — resolve once at page level so// the lightbox item and the inline player share the same lookup (#3718).@@ -502,6 +502,21 @@ export default function MusicVideo() {onClone={handleClone}onDelete={() => handleDelete(selected.id)}/>+ {/* Restricted-model license gate for the saved scene-video+ renderer. Rendered right under the renderer picker so the+ acknowledgement the server demands is resolvable from the+ board that triggers the render — not only on Video Gen. */}+ {videoSettings.termsGate && (+ <div className="mt-2">+ <ModelTermsGate+ termsGate={videoSettings.termsGate}+ accepted={videoSettings.termsAccepted}+ onAcceptedChange={videoSettings.acceptTerms}+ disabled={videoSettings.termsSaving}+ inputId="mv-model-terms-accept"+ />+ </div>+ )}{/* Concept & style — optional global direction for the whole video,set before "AI Plan" (see commitConcept above for what reads it). */}<div className="mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2">@@ -578,7 +593,7 @@ export default function MusicVideo() {generatingFrame={sceneMedia.genScenes[scene.sceneId]}generatingVideo={sceneMedia.genVideoScenes[scene.sceneId]}settingsSaving={videoSettings.saving}- videoBlocked={videoBlocked}+ videoBlockedReason={videoSettings.videoBlockedReason}canContinueShot={canContinueShot}onMove={moveScene}onDelete={handleDeleteScene}diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex c79135d896..268f065994 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -80,6 +80,10 @@ vi.mock('../services/apiImageVideo.js', () => ({],})),listVideoHistory: vi.fn(async () => [{ id: 'rh-9', filename: 'final.mp4' }]),+ // Restricted-model license gate — none of the models above carry a+ // `termsGate`, so the board renders no acceptance panel and nothing blocks.+ getVideoModelTerms: vi.fn(async () => ({ accepted: [] })),+ setVideoModelTerms: vi.fn(async () => ({ accepted: [] })),}));vi.mock('../services/apiTracks.js', () => ({listTracks: vi.fn(async () => []),@@ -108,7 +112,9 @@ import {deleteMusicVideoProject, transcribeMusicVideoMidi,} from '../services/apiMusicVideo.js';import { importTrackFromYoutube, trackImportEventsUrl, listTracks } from '../services/apiTracks.js';-import { generateVideo } from '../services/apiImageVideo.js';+import {+ generateVideo, getVideoGenStatus, getVideoModelTerms, setVideoModelTerms,+} from '../services/apiImageVideo.js';const PROJECT_ANALYZED = {...PROJECT_NO_CLIP,@@ -364,6 +370,56 @@ describe('MusicVideo project video renderer', () => {});});+// A restricted model selected here used to 403 at generate time with the+// acknowledgement UI living only on the Video Gen page — the user saw an error+// naming terms they had no way to accept from this board.+describe('MusicVideo restricted-model license gate', () => {+ const GATE = {+ id: 'example-community-license-2026-01-01',+ title: 'Example model eligibility and terms',+ summary: 'This model is licensed only in its applicable territory.',+ acknowledgement: 'I am eligible and accept the Example Community License.',+ licenseUrl: 'https://example.com/license',+ };+ const gatedStatus = (accepted) => {+ getVideoGenStatus.mockResolvedValueOnce({+ connected: true,+ defaultModel: 'gated_model',+ models: [{ id: 'gated_model', name: 'Gated Model', runtime: 'ltx2', termsGate: GATE }],+ });+ getVideoModelTerms.mockResolvedValueOnce({ accepted });+ };++ it('shows the acknowledgement inline and blocks generation until it is accepted', async () => {+ gatedStatus([]);+ setVideoModelTerms.mockResolvedValueOnce({ accepted: [GATE.id] });+ await openProject(PROJECT_NO_CLIP);++ const checkbox = await screen.findByRole('checkbox', { name: /I am eligible/ });+ expect(checkbox).not.toBeChecked();+ const generate = screen.getByRole('button', { name: /^Generate video$/ });+ expect(generate).toBeDisabled();+ expect(generate.title).toMatch(/must be accepted before generating/);++ fireEvent.click(checkbox);+ // Persisted install-wide, so every other render surface is authorized too.+ await waitFor(() => expect(setVideoModelTerms).toHaveBeenCalledWith(GATE.id, true, { silent: true }));+ await waitFor(() => expect(screen.getByRole('button', { name: /^Generate video$/ })).toBeEnabled());+ });++ it('does not re-ask when the install already accepted these exact terms', async () => {+ gatedStatus([GATE.id]);+ generateVideo.mockResolvedValue({ jobId: 'gated-job' });+ await openProject(PROJECT_NO_CLIP);++ const generate = await screen.findByRole('button', { name: /^Generate video$/ });+ await waitFor(() => expect(generate).toBeEnabled());+ expect(screen.getByRole('checkbox', { name: /I am eligible/ })).toBeChecked();+ fireEvent.click(generate);+ await waitFor(() => expect(generateVideo).toHaveBeenCalled());+ });+});+describe('MusicVideo project versions', () => {it('forks the open project and navigates to the editable next version', async () => {cloneMusicVideoProject.mockResolvedValue({diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex e544ec7be7..6442538037 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -49,6 +49,7 @@ import IcLoraPanel from '../components/videoGen/IcLoraPanel';import AdvancedParamsPanel from '../components/videoGen/AdvancedParamsPanel';import RuntimeFingerprint from '../components/videoGen/RuntimeFingerprint';import ModelDisclosure from '../components/videoGen/ModelDisclosure';+import ModelTermsGate from '../components/videoGen/ModelTermsGate';import ModelRepairBanner from '../components/videoGen/ModelRepairBanner';import VideoPreviewPanel from '../components/videoGen/VideoPreviewPanel';import VideoGenGallery from '../components/videoGen/VideoGenGallery';@@ -90,6 +91,7 @@ import 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';+import useVideoModelTerms from '../hooks/useVideoModelTerms.js';const MODES = [{ id: 'text', label: 'Text', icon: Type, desc: 'Text-to-video' },@@ -166,30 +168,37 @@ 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.+ // Restricted model terms are accepted per exact reviewed license id, and the+ // acceptance is persisted server-side so it authorizes every other render+ // surface (music video board, pipeline, agent runs) — not just this page in+ // this browser. The versioned id still rides every download/generation+ // request so the server enforces the same gate on both inputs.const termsGate = !isGrok && currentModel?.termsGate ? currentModel.termsGate : null;- const [acceptedTermsId, setAcceptedTermsId] = useState(null);+ const modelTerms = useVideoModelTerms();+ // Key acceptance by the exact license id, never a shared boolean, so a model+ // switch can't momentarily apply one model's acceptance to another's terms.+ const termsAccepted = modelTerms.isAccepted(termsGate?.id);+ // One-time carry-forward of the browser-local acceptance bit this page used+ // to keep: the user already performed this exact acknowledgement (same+ // versioned id) here, so re-home it into settings instead of asking again.+ // The legacy key is cleared afterwards so it can never re-assert a later+ // withdrawal, and `migratedTerms` keeps the re-home to one attempt per id —+ // the effect re-runs on any acceptance-list change, and the PATCH is not+ // instantaneous.+ const migratedTerms = useRef(new Set());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 id = termsGate?.id;+ if (!id || !modelTerms.loaded || modelTerms.isAccepted(id) || migratedTerms.current.has(id)) return;+ const legacyKey = `video-gen:terms:${id}`;+ if (safeReadStorage(legacyKey) !== '1') return;+ migratedTerms.current.add(id);+ modelTerms.setAcceptance(id, true).then((saved) => { if (saved) safeWriteStorage(legacyKey, '0'); });+ }, [termsGate?.id, modelTerms.loaded, modelTerms.isAccepted, modelTerms.setAcceptance]);const handleTermsAcceptedChange = (accepted) => {- setAcceptedTermsId(accepted ? termsGate?.id || null : null);- if (termsGate?.id) safeWriteStorage(`video-gen:terms:${termsGate.id}`, accepted ? '1' : '0');+ if (termsGate?.id) modelTerms.setAcceptance(termsGate.id, accepted);};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.@@ -594,7 +603,7 @@ export default function VideoGen() {// textarea and fire a request the disabled button would otherwise// have prevented.if (!prompt.trim() || generating || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || icLoraModeBlocked || byovGateBlocked || weightsGateBlocked || keyframesBlocked || termsGateBlocked))) return;- await runGeneration(buildAcceptedGeneratePayload()).catch(() => {});+ await runGeneration(buildGeneratePayload()).catch(() => {});};const handleEnqueue = () => {@@ -605,7 +614,7 @@ export default function VideoGen() {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(buildAcceptedGeneratePayload());+ enqueue(buildGeneratePayload());};const handleCancel = async () => {@@ -795,7 +804,7 @@ export default function VideoGen() {repairLabel="Repair model"onRepair={() => {setDismissedIntegrityKey(integrityKey);- modelDownload.repair(modelId, { termsAcceptance: acceptedTermsKey });+ modelDownload.repair(modelId);}}onDismiss={() => setDismissedIntegrityKey(integrityKey)}disabled={termsGateBlocked || modelDownload.repairing || modelDownload.downloading}@@ -996,7 +1005,7 @@ export default function VideoGen() {{modelStatus && (<ModelDownloadBadgestatus={modelStatus}- onDownload={() => modelDownload.start(modelId, { termsAcceptance: acceptedTermsKey })}+ onDownload={() => modelDownload.start(modelId)}onCancel={modelDownload.cancel}estimateLabel={deriveSizeEstimate(currentModel?.name)}disabled={termsGateBlocked}@@ -1091,18 +1100,25 @@ export default function VideoGen() {</div>)}- {/* Provenance / licensing / policy scope for the selected backend +- model (#3674). Restricted models also render their explicit,- server-enforced terms gate here before Advanced / Generate. */}- <ModelDisclosure- backend={backend}- backendDisclosures={status?.backendDisclosures}- model={isGrok ? null : currentModel}- systemMemoryGb={status?.systemMemoryGb}- termsAccepted={termsAccepted}- onTermsAcceptedChange={handleTermsAcceptedChange}- termsDescriptionId={termsDescriptionId}- />+ {/* A restricted model's server-enforced terms gate, then provenance /+ licensing / policy scope for the selected backend + model (#3674)+ — both before Advanced / Generate. */}+ <div className="space-y-2">+ <ModelTermsGate+ termsGate={termsGate}+ accepted={termsAccepted}+ onAcceptedChange={handleTermsAcceptedChange}+ disabled={modelTerms.saving}+ descriptionId={termsDescriptionId}+ inputId="video-gen-terms-accept"+ />+ <ModelDisclosure+ backend={backend}+ backendDisclosures={status?.backendDisclosures}+ model={isGrok ? null : currentModel}+ systemMemoryGb={status?.systemMemoryGb}+ />+ </div>{/* Sampler/output knobs live behind a closed-by-default disclosure soGenerate stays above the fold — the sibling /media/image tab keepsdiff --git a/client/src/pages/VideoGen.terms.test.jsx b/client/src/pages/VideoGen.terms.test.jsxindex 1235a85116..474054e7a3 100644--- a/client/src/pages/VideoGen.terms.test.jsx+++ b/client/src/pages/VideoGen.terms.test.jsx@@ -39,6 +39,18 @@ const state = vi.hoisted(() => ({enqueue: vi.fn(),attach: vi.fn(),eventSourceRef: { current: null },+ // Stands in for the persisted install-wide acceptance list+ // (settings.videoGen.acceptedModelTerms) the terms endpoints read and write.+ acceptedTerms: [],+ setVideoModelTerms: vi.fn(),+}));++// Acceptance lives on the server, not in this browser, so a single+// acknowledgement authorizes every render surface. The page reads and writes it+// through these two endpoints.+vi.mock('../services/apiImageVideo.js', () => ({+ getVideoModelTerms: vi.fn(async () => ({ accepted: [...state.acceptedTerms] })),+ setVideoModelTerms: (...args) => state.setVideoModelTerms(...args),}));vi.mock('../services/api', () => ({@@ -159,6 +171,13 @@ describe('VideoGen restricted-model orchestration', () => {state.startDownload.mockReset();state.repairModel.mockReset().mockResolvedValue({ ok: true });state.enqueue.mockReset();+ state.acceptedTerms = [];+ state.setVideoModelTerms.mockReset().mockImplementation(async (termsId, accepted) => {+ state.acceptedTerms = accepted+ ? [...new Set([...state.acceptedTerms, termsId])]+ : state.acceptedTerms.filter((id) => id !== termsId);+ return { accepted: [...state.acceptedTerms] };+ });state.eventSourceRef.current = null;state.attach.mockReset().mockImplementation(async (_jobId, handlers) => {handlers.onComplete({ result: { filename: 'example.mp4' } });@@ -167,29 +186,35 @@ describe('VideoGen restricted-model orchestration', () => {});it('restores only the exact license, gates model switches, submit, queue, and revocation', async () => {+ // A pre-existing browser-local acknowledgement of this exact license id is+ // carried forward into the install-wide list once, then cleared — the user+ // already performed this acknowledgement and must not be asked again.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());+ expect(state.setVideoModelTerms).toHaveBeenCalledWith(TERMS_ONE, true, { silent: true });+ await waitFor(() => expect(localStorage.getItem(`video-gen:terms:${TERMS_ONE}`)).toBe('0'));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,- }));+ // The payload carries no acceptance of its own — the server resolves it+ // from the install record, so nothing renders without a recorded (and+ // therefore withdrawable) acknowledgement.+ expect(state.enqueue).toHaveBeenCalledWith(expect.objectContaining({ modelId: H3_ONE.id }));+ expect(state.enqueue.mock.calls[0][0]).not.toHaveProperty('termsAcceptance');- // A form submit models keyboard/Enter submission and must use the same- // gate + exact key as clicking Generate.+ // A form submit models keyboard/Enter submission and must pass the same+ // gate 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,})));+ expect(state.generateVideo.mock.calls[0][0]).not.toHaveProperty('termsAcceptance');fireEvent.change(screen.getByLabelText('Model'), { target: { value: H3_TWO.id } });await waitFor(() => expect(screen.getByLabelText('Model')).toHaveValue(H3_TWO.id));@@ -202,12 +227,12 @@ describe('VideoGen restricted-model orchestration', () => {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(state.setVideoModelTerms).toHaveBeenLastCalledWith(TERMS_ONE, false, { silent: true });+ await waitFor(() => expect(generate()).toBeDisabled());expect(enqueue()).toBeDisabled();});- it('blocks download until acceptance and forwards the exact key', async () => {+ it('blocks download until the acknowledgement is recorded', async () => {state.modelStatuses[H3_ONE.id] = { id: H3_ONE.id, repo: H3_ONE.repo, cached: false, sizeBytes: 0 };await renderPage();@@ -217,10 +242,10 @@ describe('VideoGen restricted-model orchestration', () => {fireEvent.click(termsCheckbox());await waitFor(() => expect(download).toBeEnabled());fireEvent.click(download);- expect(state.startDownload).toHaveBeenCalledWith(H3_ONE.id, { termsAcceptance: TERMS_ONE });+ expect(state.startDownload).toHaveBeenCalledWith(H3_ONE.id);});- it('blocks integrity repair until acceptance and forwards the exact key', async () => {+ it('blocks integrity repair until the acknowledgement is recorded', async () => {state.modelStatuses[H3_ONE.id] = {id: H3_ONE.id,repo: H3_ONE.repo,@@ -236,6 +261,6 @@ describe('VideoGen restricted-model orchestration', () => {fireEvent.click(termsCheckbox());await waitFor(() => expect(repair).toBeEnabled());fireEvent.click(repair);- expect(state.repairModel).toHaveBeenCalledWith(H3_ONE.id, { termsAcceptance: TERMS_ONE });+ expect(state.repairModel).toHaveBeenCalledWith(H3_ONE.id);});});diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex 9c5f0ff59e..e0073f0069 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -154,6 +154,16 @@ export async function createImageGenVenv() {// Video genexport const getVideoGenStatus = (options = {}) => request('/video-gen/status', options);export const listVideoModels = (options) => request('/video-gen/models', options);+// Install-wide acknowledgement of a restricted model's reviewed license, keyed+// by the exact `termsGate.id`. Persisted server-side so accepting once (on any+// render surface) authorizes every other one, including background producers.+// Both return `{ accepted: [termsId, ...] }`.+export const getVideoModelTerms = (options = {}) => request('/video-gen/model-terms', options);+export const setVideoModelTerms = (termsId, accepted, options = {}) => request('/video-gen/model-terms', {+ method: 'POST',+ body: JSON.stringify({ termsId, accepted }),+ ...options,+});// `{ models: [...], textEncoder: { repo, cached, sizeBytes } }`. Same shape// contract as the image variant + a text-encoder block since the active// encoder is a separate multi-GB pull.diff --git a/server/lib/validation.js b/server/lib/validation.jsindex bbaf6c81f3..59433aa97d 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1121,6 +1121,19 @@ export const renderDefaultsSettingsSchema = z.object(export const videoGenSettingsSchema = z.object({mode: videoModePinSchema,defaultModelId: z.preprocess(emptyToNull, z.string().trim().max(64).nullable().optional()),+ // Install-wide acknowledgement of restricted-model license gates, stored as+ // the exact reviewed-license ids (`termsGate.id`). Written through+ // POST /api/video-gen/model-terms; typed here so a Settings save can't put+ // junk where the render gate reads authorization from.+ acceptedModelTerms: z.array(z.string().trim().min(1).max(128)).max(50).optional(),+});++// POST /api/video-gen/model-terms — record (or withdraw) the acknowledgement of+// one restricted model's reviewed license. `termsId` is the exact versioned+// gate id; the route rejects ids no shipped model declares.+export const videoModelTermsSchema = z.object({+ termsId: z.string().trim().min(1).max(128),+ accepted: z.boolean(),});// Per-RECORD render pin (#3231 Phase 3) — the flat `imageMode`/`imageModelId`diff --git a/server/lib/videoDisclosure.js b/server/lib/videoDisclosure.jsindex 654ebff88f..866effd30b 100644--- a/server/lib/videoDisclosure.js+++ b/server/lib/videoDisclosure.js@@ -23,6 +23,8 @@* are deliberately NOT duplicated here.*/+import { ServerError } from './errorHandler.js';+// Every shipped disclosure was checked against its upstream source on this// date. Bump it (and re-check) whenever an entry below changes.export const VIDEO_DISCLOSURE_REVIEWED_AT = '2026-08-09';@@ -281,14 +283,60 @@ export const applyVideoDisclosures = (list) => {});};-// 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) => {+// The exact reviewed-license id a model requires, or null when it is ungated.+export const videoModelTermsGateId = (model) => {const required = model?.termsGate?.id;- return typeof required !== 'string' || required.length === 0 || acceptanceKey === required;+ return typeof required === 'string' && required.length > 0 ? required : null;+};++/**+ * The install's persisted acknowledgements (`settings.videoGen.acceptedModelTerms`).+ *+ * Acceptance is an install-wide fact about the operator, not a property of one+ * request or one browser: the same person drives the Video Gen page, the music+ * video director board, and every scheduled/agent render. Persisting it here is+ * what lets a single acknowledgement authorize all of them — see the+ * `POST /api/video-gen/model-terms` route.+ *+ * Returns a de-duplicated array of non-empty strings; anything else on disk is+ * ignored rather than trusted.+ */+export const acceptedVideoModelTerms = (settings) => {+ const stored = settings?.videoGen?.acceptedModelTerms;+ if (!Array.isArray(stored)) return [];+ return [...new Set(stored.filter((id) => typeof id === 'string' && id.length > 0))];};+// Exact-id comparison keeps acceptance scoped to one reviewed license version:+// acknowledging one license must never authorize a later revision of it, or an+// unrelated restricted model. The install's recorded acknowledgements+// (`acceptedVideoModelTerms`) are the ONLY authorization — there is no+// per-request "I accept" a caller can assert, so every authorized render traces+// back to a recorded acknowledgement and withdrawing one takes effect+// everywhere, including work already sitting in the queue.+export const isVideoModelTermsAccepted = (model, acceptedKeys) => {+ const required = videoModelTermsGateId(model);+ if (required === null) return true;+ return Array.isArray(acceptedKeys) && acceptedKeys.includes(required);+};++/**+ * The rejection every gated code path throws, so the wording (and the way out+ * of it) can't drift between the download route, request preparation, and the+ * render itself.+ *+ * A render can be started from surfaces that have no acknowledgement UI of+ * their own — and from producers with no UI at all, whose only channel to the+ * user is this message on a failed job. So the message must name where the+ * acknowledgement lives, not just state that one is missing.+ */+export const videoModelTermsError = (model, action = 'generation') => new ServerError(+ `${model?.name || 'This model'} requires acknowledgement of its territory restrictions, `+ + `Community License, and Acceptable Use Policy before ${action}. `+ + 'Accept it on the Video Gen page (Media → Video) — one acknowledgement authorizes every render on this install.',+ { status: 403, code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_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 dd622d32b7..edd078ba64 100644--- a/server/lib/videoDisclosure.test.js+++ b/server/lib/videoDisclosure.test.js@@ -5,6 +5,9 @@ import {VIDEO_DISCLOSURE_REVIEWED_AT,applyVideoDisclosures,isVideoModelTermsAccepted,+ acceptedVideoModelTerms,+ videoModelTermsGateId,+ videoModelTermsError,videoBackendDisclosure,} from './videoDisclosure.js';@@ -148,11 +151,15 @@ describe('applyVideoDisclosures', () => {describe('isVideoModelTermsAccepted', () => {const restricted = { termsGate: VIDEO_MODEL_DISCLOSURES.minimax_h3_8bit.termsGate };- it('requires the exact versioned key for a restricted model', () => {+ it('requires the exact versioned id in the install acknowledgement list', () => {+ const id = restricted.termsGate.id;+ expect(isVideoModelTermsAccepted(restricted, [id])).toBe(true);+ expect(isVideoModelTermsAccepted(restricted, ['another-license'])).toBe(false);+ expect(isVideoModelTermsAccepted(restricted, [])).toBe(false);expect(isVideoModelTermsAccepted(restricted)).toBe(false);+ // A truthy non-array (a sloppy caller's "accepted" boolean) must never+ // stand in for the exact id.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', () => {@@ -161,6 +168,43 @@ describe('isVideoModelTermsAccepted', () => {});});+describe('videoModelTermsError', () => {+ it('names the model and where the acknowledgement is made', () => {+ const err = videoModelTermsError({ name: 'Example Model' }, 'download');+ expect(err.status).toBe(403);+ expect(err.code).toBe('VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED');+ expect(err.message).toContain('Example Model');+ expect(err.message).toContain('before download');+ // A producer with no UI reports this message verbatim on a failed job, so+ // it has to say where the acceptance lives.+ expect(err.message).toMatch(/Video Gen page/);+ });+});++describe('acceptedVideoModelTerms', () => {+ it('reads the persisted list, dropping non-string and duplicate entries', () => {+ expect(acceptedVideoModelTerms({ videoGen: { acceptedModelTerms: ['a', 'a', '', 3, null, 'b'] } }))+ .toEqual(['a', 'b']);+ });++ it('treats a missing, malformed, or absent settings shape as no acknowledgement', () => {+ expect(acceptedVideoModelTerms(undefined)).toEqual([]);+ expect(acceptedVideoModelTerms({})).toEqual([]);+ expect(acceptedVideoModelTerms({ videoGen: {} })).toEqual([]);+ expect(acceptedVideoModelTerms({ videoGen: { acceptedModelTerms: 'a' } })).toEqual([]);+ });+});++describe('videoModelTermsGateId', () => {+ it('returns the exact id for a gated model and null for everything else', () => {+ const gate = VIDEO_MODEL_DISCLOSURES.minimax_h3_8bit.termsGate;+ expect(videoModelTermsGateId({ termsGate: gate })).toBe(gate.id);+ expect(videoModelTermsGateId({ termsGate: { id: '' } })).toBe(null);+ expect(videoModelTermsGateId({})).toBe(null);+ expect(videoModelTermsGateId(null)).toBe(null);+ });+});+describe('VIDEO_BACKEND_DISCLOSURES', () => {it('covers the local and grok backends with an execution discriminator', () => {expect(VIDEO_BACKEND_DISCLOSURES.map((b) => b.id)).toEqual(['local', 'grok']);diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 754c781886..6c63bd80df 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -58,26 +58,41 @@ const redactExternalTokens = (settings) => {return next;};-// Write-path counterpart to the redaction above. Because GET /api/settings no-// longer returns these tokens, a client that GETs settings, rebuilds a full-// top-level object and PUTs it back (e.g. `patchSettingsSlice('imageGen.local',-// …)`) would otherwise drop the persisted token — `updateSettings` shallow--// merges top-level keys, so an incoming `imageGen`/`civitai` replaces the-// stored object wholesale. PUT /api/settings is never the write path for these-// tokens (the dedicated /setup/hf-token and /loras/auth/civitai routes are), so-// re-inject the persisted value whenever an incoming parent object omits it.-// A parent absent from the patch needs nothing — the top-level merge keeps the-// stored object (token included) untouched.-const preserveWriteOnlyTokens = (next, current) => {- const carryOver = (parentKey, tokenKey) => {+// Sub-keys this route must never clobber, because it isn't their write path.+// `updateSettings` shallow-merges TOP-LEVEL keys, so an incoming `imageGen` /+// `civitai` / `videoGen` object replaces the stored one wholesale — and a+// client that GETs settings, rebuilds the parent and PUTs it back (e.g.+// `patchSettingsSlice('imageGen.local', …)`) would drop any sub-key it never+// saw or never rendered. A parent absent from the patch needs nothing — the+// top-level merge keeps the stored object untouched.+//+// - imageGen.hfToken / civitai.apiKey: write-only tokens, redacted out of+// GET, owned by /setup/hf-token and /loras/auth/civitai. Re-injected only+// when the incoming parent omits them, so those routes can still write.+// - videoGen.acceptedModelTerms: the install's restricted-model license+// acknowledgements, owned exclusively by /api/video-gen/model-terms — which+// is where an id is checked against a model that actually declares it. The+// stored value ALWAYS wins here, so a settings save can neither drop an+// acknowledgement (silently 403ing every gated render) nor mint one that+// no model's terms gate would ever match.+const preserveExternallyOwnedKeys = (next, current) => {+ const carryOver = (parentKey, childKey, { alwaysStored = false } = {}) => {const incoming = next[parentKey];- const stored = current?.[parentKey]?.[tokenKey];- if (isPlainObject(incoming) && !(tokenKey in incoming) && stored !== undefined) {- next[parentKey] = { ...incoming, [tokenKey]: stored };+ const stored = current?.[parentKey]?.[childKey];+ if (!isPlainObject(incoming)) return;+ if (!alwaysStored && childKey in incoming) return;+ if (stored === undefined) {+ if (alwaysStored && childKey in incoming) {+ const { [childKey]: _dropped, ...rest } = incoming;+ next[parentKey] = rest;+ }+ return;}+ next[parentKey] = { ...incoming, [childKey]: stored };};carryOver('imageGen', 'hfToken');carryOver('civitai', 'apiKey');+ carryOver('videoGen', 'acceptedModelTerms', { alwaysStored: true });return next;};@@ -252,9 +267,9 @@ router.put('/', asyncHandler(async (req, res) => {const { secrets: _ignoredSecrets, catalogUserTypes: _ignoredTypes, ...settingsPatch } = req.body || {};// updateSettingsWith (not updateSettings) so we can re-inject persisted// write-only tokens the incoming patch omits, against the freshest snapshot- // inside the write queue (see preserveWriteOnlyTokens).+ // inside the write queue (see preserveExternallyOwnedKeys).const merged = await updateSettingsWith((current) =>- preserveWriteOnlyTokens({ ...current, ...settingsPatch }, current));+ preserveExternallyOwnedKeys({ ...current, ...settingsPatch }, current));// The queue caches codex.parallelLimit in-process; sync it from the// merged value so a save takes effect without a restart and without// re-reading the file.diff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex b5c25b6f2f..dcc3dc66bb 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -12,7 +12,8 @@ vi.mock('../services/settings.js', () => ({return { ...store };}),// The PUT handler uses updateSettingsWith so it can re-inject persisted- // write-only tokens omitted by the patch (see preserveWriteOnlyTokens).+ // sub-keys this route does not own but the patch omits (see+ // preserveExternallyOwnedKeys).updateSettingsWith: vi.fn(async (mutate) => {store = await mutate({ ...store });return { ...store };@@ -243,4 +244,40 @@ describe('Settings routes — videoGen slice (#3231 Phase 4)', () => {.send({ videoGen: { mode: 'codex' } });expect(res.status).toBe(400);});++ // Restricted-model license acknowledgements are owned by+ // /api/video-gen/model-terms. Losing them to an unrelated Settings save would+ // silently start 403ing every gated render again.+ it('preserves acceptedModelTerms when a settings save replaces the videoGen slice without it', async () => {+ store = { videoGen: { mode: null, acceptedModelTerms: ['minimax-h3-community-license-2026-08-02'] } };+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ videoGen: { mode: 'grok' } });+ expect(res.status).toBe(200);+ expect(res.body.videoGen).toEqual({+ mode: 'grok',+ acceptedModelTerms: ['minimax-h3-community-license-2026-08-02'],+ });+ });++ // /api/video-gen/model-terms is where an id is checked against a model that+ // actually declares it, so this route can't be a second write path — it would+ // let arbitrary strings accumulate in the list that authorizes renders.+ it('ignores an acceptedModelTerms written through the settings patch', async () => {+ store = { videoGen: { acceptedModelTerms: ['recorded-license'] } };+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ videoGen: { acceptedModelTerms: ['smuggled-license'] } });+ expect(res.status).toBe(200);+ expect(res.body.videoGen.acceptedModelTerms).toEqual(['recorded-license']);+ });++ it('does not let a settings patch mint the list on an install that has accepted nothing', async () => {+ store = { videoGen: { mode: null } };+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ videoGen: { mode: 'local', acceptedModelTerms: ['smuggled-license'] } });+ expect(res.status).toBe(200);+ expect(res.body.videoGen).toEqual({ mode: 'local' });+ });});diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex b8f352984c..fdccc4b467 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -15,10 +15,13 @@ import { z } from 'zod';import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';import { uploadFields } from '../lib/multipart.js';import { PATHS } from '../lib/fileUtils.js';-import { grokVideoDurationSchema } from '../lib/validation.js';-import { VIDEO_BACKEND_DISCLOSURES, isVideoModelTermsAccepted } from '../lib/videoDisclosure.js';+import { grokVideoDurationSchema, videoModelTermsSchema } from '../lib/validation.js';+import {+ VIDEO_BACKEND_DISCLOSURES, isVideoModelTermsAccepted, acceptedVideoModelTerms,+ videoModelTermsGateId, videoModelTermsError,+} from '../lib/videoDisclosure.js';import { IMAGE_GEN_MODE } from '../services/imageGen/modes.js';-import { getSettings } from '../services/settings.js';+import { getSettings, updateSettingsWith } from '../services/settings.js';import { checkPackages, isAllowedPython } from '../lib/pythonSetup.js';import { safeChildProcessEnv } from '../lib/processEnv.js';import { createLineReader } from '../lib/streamLines.js';@@ -170,10 +173,6 @@ 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'),@@ -347,6 +346,39 @@ router.get('/status', asyncHandler(async (_req, res) => {});}));+// Restricted-model license acknowledgement (#3674 follow-up). Acceptance is a+// fact about the operator of this install, not about one browser or one+// request, so it lives in settings and every render surface reads it: the+// Video Gen page, the music video director board, and producers with no UI to+// prompt through (queued jobs, pipeline stages, agent runs).+router.get('/model-terms', asyncHandler(async (_req, res) => {+ res.json({ accepted: acceptedVideoModelTerms(await getSettings()) });+}));++router.post('/model-terms', asyncHandler(async (req, res) => {+ const parsed = videoModelTermsSchema.safeParse(req.body || {});+ if (!parsed.success) failValidation(parsed);+ const { termsId, accepted } = parsed.data;+ // Only ids a shipped model actually declares are storable — otherwise a+ // typo'd or stale id accumulates in settings and silently authorizes+ // nothing, which reads to the user as "I accepted and it still fails".+ const known = listVideoModels().some((model) => videoModelTermsGateId(model) === termsId);+ if (!known) {+ throw new ServerError(+ `Unknown model terms id: ${termsId}`,+ { status: 400, code: 'VIDEO_MODEL_TERMS_UNKNOWN_ID' },+ );+ }+ const next = await updateSettingsWith((current) => {+ const existing = acceptedVideoModelTerms(current);+ const updated = accepted+ ? [...new Set([...existing, termsId])]+ : existing.filter((id) => id !== termsId);+ return { ...current, videoGen: { ...(current.videoGen || {}), acceptedModelTerms: updated } };+ });+ res.json({ accepted: acceptedVideoModelTerms(next) });+}));+// `installed` here means "fully ready to render" — both the venv binary// exists AND its python packages are importable. The sync existsSync gate// alone is too permissive: a partial install (clone done, `uv pip install`@@ -724,11 +756,11 @@ 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' },- );+ // Only a gated model needs the recorded acknowledgement list — skip the+ // settings read (and its deep clone) for every ordinary model.+ if (videoModelTermsGateId(model)+ && !isVideoModelTermsAccepted(model, acceptedVideoModelTerms(await getSettings()))) {+ throw videoModelTermsError(model, 'download');}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' });@@ -900,7 +932,6 @@ 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 1ef50e8eed..c357f1ccb4 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -30,6 +30,7 @@ vi.mock('child_process', async (importOriginal) => ({vi.mock('../services/settings.js', () => ({getSettings: vi.fn(async () => ({ imageGen: { local: { pythonPath: '/usr/bin/python3' } } })),+ updateSettingsWith: vi.fn(async (mutate) => mutate({ imageGen: { local: { pythonPath: '/usr/bin/python3' } } })),}));vi.mock('../services/musicVideo/projects.js', () => ({@@ -446,26 +447,29 @@ describe('videoGen routes', () => {}],};- it('rejects a missing or stale acceptance key before opening a download stream', async () => {- videoGenService.listVideoModels- .mockReturnValueOnce([h3])- .mockReturnValueOnce([h3]);+ it('rejects a download until the install has recorded this exact acknowledgement', async () => {+ const { getSettings } = await import('../services/settings.js');+ 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');+ // The message is the only channel a blocked caller has, so it must point+ // at where the acknowledgement is made.+ expect(missing.body.error).toMatch(/Video Gen page/);- const stale = await request(app)- .get('/api/video-gen/models/minimax_h3_8bit/download?termsAcceptance=old-license');+ // A superseded license revision is not this one.+ getSettings.mockResolvedValueOnce({ videoGen: { acceptedModelTerms: ['minimax-h3-community-license-2025-01-01'] } });+ const stale = await request(app).get('/api/video-gen/models/minimax_h3_8bit/download');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 () => {+ it('downloads both exact snapshots once the acknowledgement is recorded', async () => {+ const { getSettings } = await import('../services/settings.js');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',- );+ getSettings.mockResolvedValueOnce({ videoGen: { acceptedModelTerms: [h3.termsGate.id] } });+ const accepted = await request(app).get('/api/video-gen/models/minimax_h3_8bit/download');expect(accepted.status).toBe(200);expect(sseDownload.start).toHaveBeenCalledWith(expect.objectContaining({repos: [@@ -483,22 +487,85 @@ describe('videoGen routes', () => {}));});- 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({+ // The install-wide acknowledgement is what makes a single "I accept" click+ // authorize every other surface — the music video board, a pipeline stage,+ // an agent run — instead of each one 403ing with no UI to resolve it. It is+ // also the ONLY authorization: a request cannot assert its own acceptance,+ // so nothing renders without a recorded acknowledgement to withdraw.+ it('queues the render on the recorded acknowledgement, and never on a self-asserted key', async () => {+ const { getSettings } = await import('../services/settings.js');+ videoGenService.listVideoModels.mockReturnValue([h3]);+ getSettings.mockResolvedValueOnce({+ imageGen: { local: { pythonPath: '/usr/bin/python3' } },+ videoGen: { acceptedModelTerms: [h3.termsGate.id] },+ });+ const render = 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(render.status).toBe(200);+ // Nothing about the acceptance rides the job: the render re-resolves it+ // from settings, so a withdrawal reaches work already in the queue.expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({kind: 'video',- params: expect.objectContaining({- modelId: h3.id,- termsAcceptance: h3.termsGate.id,- }),+ params: expect.not.objectContaining({ termsAcceptance: expect.anything() }),}));++ const asserted = await request(app).post('/api/video-gen/').send({+ prompt: 'a fox watches the rain',+ modelId: h3.id,+ mode: 'text',+ termsAcceptance: h3.termsGate.id,+ });+ expect(asserted.status).toBe(403);+ expect(asserted.body.code).toBe('VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED');+ videoGenService.listVideoModels.mockReset();+ });+ });++ describe('POST /model-terms — install-wide acknowledgement', () => {+ const h3 = {+ id: 'minimax_h3_8bit',+ name: 'MiniMax H3 MLX 8-bit',+ termsGate: { id: 'minimax-h3-community-license-2026-08-02' },+ };++ it('records and withdraws the acknowledgement for a known gate id', async () => {+ const { updateSettingsWith } = await import('../services/settings.js');+ videoGenService.listVideoModels.mockReturnValueOnce([h3]);+ updateSettingsWith.mockImplementationOnce(async (mutate) => mutate({}));+ const accept = await request(app)+ .post('/api/video-gen/model-terms')+ .send({ termsId: h3.termsGate.id, accepted: true });+ expect(accept.status).toBe(200);+ expect(accept.body.accepted).toEqual([h3.termsGate.id]);++ videoGenService.listVideoModels.mockReturnValueOnce([h3]);+ updateSettingsWith.mockImplementationOnce(async (mutate) =>+ mutate({ videoGen: { acceptedModelTerms: [h3.termsGate.id] } }));+ const withdraw = await request(app)+ .post('/api/video-gen/model-terms')+ .send({ termsId: h3.termsGate.id, accepted: false });+ expect(withdraw.status).toBe(200);+ expect(withdraw.body.accepted).toEqual([]);+ });++ it('rejects an id no shipped model declares rather than storing a no-op acceptance', async () => {+ videoGenService.listVideoModels.mockReturnValueOnce([h3]);+ const bogus = await request(app)+ .post('/api/video-gen/model-terms')+ .send({ termsId: 'not-a-real-license', accepted: true });+ expect(bogus.status).toBe(400);+ expect(bogus.body.code).toBe('VIDEO_MODEL_TERMS_UNKNOWN_ID');+ });++ it('reports the persisted acknowledgements', async () => {+ const { getSettings } = await import('../services/settings.js');+ getSettings.mockResolvedValueOnce({ videoGen: { acceptedModelTerms: [h3.termsGate.id, ''] } });+ const listed = await request(app).get('/api/video-gen/model-terms');+ expect(listed.status).toBe(200);+ expect(listed.body.accepted).toEqual([h3.termsGate.id]);});});diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex e3398943ae..0b56e6de68 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -32,7 +32,10 @@ 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 {+ isVideoModelTermsAccepted, acceptedVideoModelTerms, videoModelTermsGateId, videoModelTermsError,+} from '../../lib/videoDisclosure.js';+import { getSettings } from '../settings.js';import {isIcLoraMode, icLoraSpecForMode, resolveIcLoraWeight,assertIcReferenceCount, icResolutionIssue,@@ -853,7 +856,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 = '', 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 }) {+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', 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@@ -863,15 +866,17 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', tconst 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' },- );+ // Final execution-boundary gate for a restricted model's license. Route+ // preparation also rejects early, but internal producers, persisted jobs, and+ // retries all reach this function directly — so authorization is resolved+ // HERE, from the install's recorded acknowledgements, rather than trusted+ // from a caller-supplied parameter. Read at execution time, so a withdrawn+ // acknowledgement (or a license revision that mints a new id) fails a job+ // that was queued while it was still accepted. Ungated models never pay for+ // the settings read.+ if (videoModelTermsGateId(model)+ && !isVideoModelTermsAccepted(model, acceptedVideoModelTerms(await getSettings()))) {+ throw videoModelTermsError(model);}// Validate H3's mode contract before cache lookups, image resize, or staging// work. Internal producers and persisted/retried jobs bypass routediff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 0e8c880c64..8b301b3177 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -35,6 +35,15 @@ tryReadFile: vi.fn().mockResolvedValue(null),UUID_RE: /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,}));+// The restricted-model license gate resolves authorization from the install's+// recorded acknowledgements at render time, so these tests declare whether this+// "install" has accepted MiniMax H3's license.+const H3_TERMS = 'minimax-h3-community-license-2026-08-02';+const settingsState = vi.hoisted(() => ({ acceptedModelTerms: [] }));+vi.mock('../settings.js', () => ({+ getSettings: vi.fn(async () => ({ videoGen: { acceptedModelTerms: [...settingsState.acceptedModelTerms] } })),+}));+vi.mock('../../lib/mediaModels.js', () => ({getVideoModels: vi.fn(() => [{ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2', repo: 'Lightricks/LTX-Video', steps: 30, guidance: 3.5 },@@ -1749,7 +1758,12 @@ describe('generateVideo — Wan MLX-Gen contract', () => {});describe('generateVideo — MiniMax H3 MLX contract', () => {- it('requires the exact reviewed terms key at the render boundary', async () => {+ // Every test below renders H3, which is license-gated: authorization comes+ // from the install's recorded acknowledgement, re-read here at the render+ // boundary rather than trusted from the caller's params.+ beforeEach(() => { settingsState.acceptedModelTerms = [H3_TERMS]; });++ it('resolves the license gate from the install record at the render boundary', async () => {const { spawnDetached } = await import('../../lib/detachedSpawn.js');vi.mocked(spawnDetached).mockClear();const base = {@@ -1760,11 +1774,20 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {mode: 'text',};+ settingsState.acceptedModelTerms = [];await expect(generateVideo(base)).rejects.toMatchObject({status: 403,code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED',});- await expect(generateVideo({ ...base, termsAcceptance: 'old-license' })).rejects.toMatchObject({+ // A superseded license revision does not carry forward — a job queued while+ // the old one was accepted fails closed at execution.+ settingsState.acceptedModelTerms = ['old-license'];+ await expect(generateVideo(base)).rejects.toMatchObject({+ status: 403,+ code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED',+ });+ // A caller cannot assert its own acceptance — only the install record counts.+ await expect(generateVideo({ ...base, termsAcceptance: H3_TERMS })).rejects.toMatchObject({status: 403,code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED',});@@ -1785,7 +1808,7 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {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,@@ -1808,7 +1831,7 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {await expect(generateVideo({jobId: 'h3-image-shape',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,...fields,@@ -1832,7 +1855,7 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {await generateVideo({jobId: 'h3-keyframes',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,...fields,@@ -1863,7 +1886,7 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {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',diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.jsindex 0db210718f..71005fecdf 100644--- a/server/services/videoGen/prepareParams.js+++ b/server/services/videoGen/prepareParams.js@@ -33,7 +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 { isVideoModelTermsAccepted, acceptedVideoModelTerms, videoModelTermsError } from '../../lib/videoDisclosure.js';import { videoLoraFamily } from '../../lib/runners.js';import {IC_LORA_MODE_VALUES, icLoraSpecForMode,@@ -157,12 +157,14 @@ 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)) {+ // Reject a gated model here so the caller gets a synchronous, actionable 403+ // instead of a doomed queue entry. The render itself re-checks (local.js) —+ // this is the early half of the same gate, authorized by the same recorded+ // acknowledgement (POST /api/video-gen/model-terms).+ if (backend !== VIDEO_GEN_MODE.GROK && effectiveModel+ && !isVideoModelTermsAccepted(effectiveModel, acceptedVideoModelTerms(settings))) {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' },- );+ throw videoModelTermsError(effectiveModel);}// Reject up-front when the local python isn't configured AND the model's// runtime needs it. ltx2/wan22/hunyuan bring their own venv (resolveddiff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.jsindex a60d1aa068..2c3657e437 100644--- a/server/services/videoGen/prepareParams.test.js+++ b/server/services/videoGen/prepareParams.test.js@@ -45,6 +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 { getSettings } from '../settings.js';import { listVideoModels, defaultVideoModelId, loadHistory } from './local.js';import { prepareVideoGenParams, withStagedRollback, cleanupMultipartTemp } from './prepareParams.js';@@ -370,19 +371,37 @@ describe('prepareVideoGenParams', () => {});describe('prepareVideoGenParams — MiniMax H3 contract', () => {+ // H3 is license-gated, and the only authorization is the acknowledgement+ // recorded in settings — so every test below that is about H3's *mode*+ // contract runs on an install that has already accepted its terms.+ const settingsWith = (acceptedModelTerms) => ({+ imageGen: {+ local: { pythonPath: '/usr/bin/python3' },+ grok: { enabled: true, grokPath: '/usr/bin/grok', aspectRatio: '16:9' },+ },+ videoGen: { acceptedModelTerms },+ });beforeEach(() => {vi.clearAllMocks();listVideoModels.mockReturnValue([H3_MODEL]);loadHistory.mockResolvedValue([]);+ getSettings.mockResolvedValue(settingsWith([H3_TERMS]));});- it('requires the exact reviewed terms key before generation', async () => {+ // A render kicked off from a surface with no terms UI of its own (the music+ // video board, a pipeline stage) is authorized by the acknowledgement the+ // user recorded once — anywhere — rather than 403ing with nowhere to go.+ it('requires the install to have recorded this exact reviewed license', async () => {+ getSettings.mockResolvedValueOnce(settingsWith(undefined));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' }))++ // A superseded license revision does not carry forward to this one.+ getSettings.mockResolvedValueOnce(settingsWith(['some-older-license']));+ await expect(prepare({ modelId: H3_MODEL.id, mode: 'text' })).rejects.toMatchObject({ status: 403, code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED' });- const prepared = await prepare({ modelId: H3_MODEL.id, mode: 'text', termsAcceptance: H3_TERMS });+ const prepared = await prepare({ modelId: H3_MODEL.id, mode: 'text' });expect(prepared.effectiveModelId).toBe(H3_MODEL.id);expect(prepared.effectiveChunks).toBe(1);});@@ -409,7 +428,7 @@ describe('prepareVideoGenParams — MiniMax H3 contract', () => {])('rejects an unsupported H3 request (%o)', async (fields, code) => {await expect(prepare({modelId: H3_MODEL.id,- termsAcceptance: H3_TERMS,+...fields,})).rejects.toMatchObject({ status: 400, code });});@@ -417,12 +436,12 @@ describe('prepareVideoGenParams — MiniMax H3 contract', () => {it('rejects chunks > 1 only while the entry lacks image-to-video', async () => {listVideoModels.mockReturnValue([{ ...H3_MODEL, supportedModes: ['text'] }]);await expect(prepare({- modelId: H3_MODEL.id, mode: 'text', termsAcceptance: H3_TERMS, chunks: 2,+ modelId: H3_MODEL.id, mode: 'text', chunks: 2,})).rejects.toMatchObject({ status: 400, code: 'VIDEO_CHAIN_REQUIRES_IMAGE_MODE' });listVideoModels.mockReturnValue([H3_MODEL]);const prepared = await prepare({- modelId: H3_MODEL.id, mode: 'text', termsAcceptance: H3_TERMS, chunks: 2,+ modelId: H3_MODEL.id, mode: 'text', chunks: 2,});expect(prepared.effectiveChunks).toBe(2);});@@ -433,7 +452,7 @@ describe('prepareVideoGenParams — MiniMax H3 contract', () => {])('accepts %s keyframe conditioning', async (_label, fields) => {const prepared = await prepare({modelId: H3_MODEL.id,- termsAcceptance: H3_TERMS,+...fields,});expect(prepared.effectiveModelId).toBe(H3_MODEL.id);@@ -444,7 +463,7 @@ describe('prepareVideoGenParams — MiniMax H3 contract', () => {const prepared = await prepare({modelId: H3_MODEL.id,mode: 'text',- termsAcceptance: H3_TERMS,+numFrames: 158,fps: 24,});