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
refactor: decompose local model and video forms (#4905)
[._.]/ Adam Eivy6eab983fea6c
diff --git a/client/src/components/settings/LocalLlmInstalledModels.jsx b/client/src/components/settings/LocalLlmInstalledModels.jsxnew file mode 100644index 0000000000..071f654f3f--- /dev/null+++ b/client/src/components/settings/LocalLlmInstalledModels.jsx@@ -0,0 +1,135 @@+import { useMemo } from 'react';+import { Link } from 'react-router';+import { ArrowRightLeft, FlaskConical, RefreshCw, Trash2 } from 'lucide-react';+import { localLlmTargetKey } from '../../lib/localLlmTargetKey.js';+import { formatBytes, formatContextLength } from '../../utils/formatters.js';+import BrailleSpinner from '../BrailleSpinner.jsx';+import CapabilityBadges from '../models/CapabilityBadges.jsx';+import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';++const redownloadInstallId = (model, backend) => {+ if (backend !== 'lmstudio') return model.id;+ if (/@/.test(model.id || '')) return model.id;+ return model?.quantization ? `${model.id}@${model.quantization}` : null;+};++export default function LocalLlmInstalledModels({+ actionInProgress,+ backend,+ busy,+ cancelDelete,+ compareTargets,+ confirmDelete,+ install,+ isConfirmingDelete,+ models,+ onCompare,+ onToggleCompare,+ remove,+ requestDelete,+}) {+ const compareTargetKeys = useMemo(+ () => new Set(compareTargets.map(localLlmTargetKey)),+ [compareTargets],+ );++ return (+ <div className="space-y-2 pt-2 border-t border-port-border/50">+ <div className="flex items-center justify-between gap-3 flex-wrap">+ <h3 className="text-xs font-medium text-gray-400">Installed on {backend === 'ollama' ? 'Ollama' : 'LM Studio'} ({models.length})</h3>+ {compareTargets.length > 0 && (+ <div className="flex items-center gap-2">+ <span className="text-xs text-gray-500">{compareTargets.length} selected</span>+ <button+ onClick={onCompare}+ disabled={compareTargets.length < 2}+ className="px-2.5 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded disabled:opacity-50 flex items-center gap-1"+ >+ <ArrowRightLeft size={12} />+ Compare selected+ </button>+ </div>+ )}+ </div>+ {models.length === 0 ? (+ <p className="text-xs text-gray-500">No models installed yet.</p>+ ) : models.map((model) => {+ const redownloadId = redownloadInstallId(model, backend);+ return (+ <div key={model.id} className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 bg-port-bg border border-port-border rounded-lg p-3">+ <div className="flex items-start gap-3 min-w-0 flex-1">+ <label className="shrink-0 flex items-center pt-0.5" title={`Include ${model.name || model.id} in a comparison`}>+ <input+ type="checkbox"+ checked={compareTargetKeys.has(localLlmTargetKey({ backend, modelId: model.id }))}+ onChange={() => onToggleCompare(backend, model.id)}+ className="h-4 w-4 accent-port-accent"+ aria-label={`Select ${model.name || model.id} for comparison`}+ />+ </label>+ <div className="min-w-0 flex-1">+ <div className="text-sm text-white break-all">{model.name}</div>+ <div className="text-xs text-gray-500 break-words">+ {[+ model.params,+ model.quantization,+ model.family,+ formatContextLength(model.contextLength),+ model.size != null ? formatBytes(model.size) : null,+ ].filter(Boolean).join(' · ')}+ </div>+ {(model.capabilities || []).length > 0 && (+ <div className="flex items-center gap-1 flex-wrap mt-1">+ <CapabilityBadges capabilities={model.capabilities} />+ </div>+ )}+ </div>+ </div>+ <div className="flex items-center gap-2 shrink-0 justify-end flex-wrap">+ <Link+ to={`/local-llm/playground?backend=${encodeURIComponent(backend)}&model=${encodeURIComponent(model.id)}`}+ className="px-2.5 py-1 text-xs bg-port-accent-2/15 hover:bg-port-accent-2/25 text-port-accent-2 rounded flex items-center gap-1 shrink-0 no-underline"+ title={`Chat with ${model.name || model.id}`}+ >+ <FlaskConical size={12} />+ Chat+ </Link>+ {redownloadId && (+ <button+ onClick={() => install(redownloadId, { force: true })}+ disabled={busy}+ title="Pull this build again. Updated GGUF files keep the same name, so an existing install will not refresh until you redownload."+ className="px-2.5 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded disabled:opacity-50 flex items-center gap-1 shrink-0"+ aria-label={`Redownload ${model.name || model.id}`}+ >+ {actionInProgress === `install-${redownloadId}` ? <BrailleSpinner /> : <RefreshCw size={12} />}+ Redownload+ </button>+ )}+ {isConfirmingDelete(model.id) ? (+ <ConfirmButtonPair+ prompt="Delete?"+ confirmIcon={Trash2}+ busy={busy}+ className="shrink-0"+ onConfirm={() => confirmDelete(() => remove(model.id))}+ onCancel={cancelDelete}+ />+ ) : (+ <button+ onClick={() => requestDelete(model.id)}+ disabled={busy}+ className="px-2.5 py-1 text-xs bg-port-error/20 hover:bg-port-error/40 text-port-error rounded disabled:opacity-50 flex items-center gap-1 shrink-0"+ aria-label={`Delete ${model.name}`}+ >+ {actionInProgress === `delete-${model.id}` ? <BrailleSpinner /> : <Trash2 size={12} />}+ Delete+ </button>+ )}+ </div>+ </div>+ );+ })}+ </div>+ );+}diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 2c5e45d2f8..8434778f5d 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -1,8 +1,7 @@import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import { Link, useNavigate } from 'react-router';-import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Power, PowerOff, AlertTriangle, FlaskConical, Zap, ChevronDown, ChevronUp, Terminal } from 'lucide-react';+import { Cpu, Box, Download, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Power, PowerOff, AlertTriangle, Zap, ChevronDown, ChevronUp, Terminal } from 'lucide-react';import toast from '../ui/Toast';-import ConfirmButtonPair from '../ui/ConfirmButtonPair';import BrailleSpinner from '../BrailleSpinner';import { formatAgeDays, formatBytes, formatContextLength, timeAgo, recommendedRamGb, formatDateNumeric } from '../../utils/formatters';import { localLlmTargetKey } from '../../lib/localLlmTargetKey';@@ -21,6 +20,7 @@ import SpecDecodeWeightRow from './SpecDecodeWeightRow.jsx';import RuntimeServersCard from './RuntimeServersCard.jsx';import MtplxServerCard from './MtplxServerCard.jsx';import LocalLlmBackendCard from './LocalLlmBackendCard.jsx';+import LocalLlmInstalledModels from './LocalLlmInstalledModels.jsx';const BACKENDS = [{ id: 'ollama', label: 'Ollama', icon: Cpu },@@ -28,18 +28,6 @@ const BACKENDS = [];const labelFor = (id) => BACKENDS.find((b) => b.id === id)?.label || id;-// LM Studio's installed list is folder-scoped (`publisher/repo`) plus a separate-// `quantization` field. A force redownload has to target a tagged id so the-// server evicts that GGUF instead of no-op'ing on a bare repo.-const redownloadInstallId = (model, backend) => {- if (backend !== 'lmstudio') return model.id;- if (/@/.test(model.id || '')) return model.id;- if (model?.quantization) return `${model.id}@${model.quantization}`;- // /v1/models fallback has no quantization — a bare repo force-redownload- // would skip existing GGUFs and still toast success.- return null;-};-// The speculative-decoding presets come from the server// (`server/lib/specDecodePresets.js`, surfaced on the llama-server status// response) rather than a table here: each preset names a multi-gigabyte GGUF,@@ -564,7 +552,6 @@ export function LocalLlmTab() {const selectedOllamaStartupAction = selectedData?.service?.supported ? 'enable' : 'start';const selectedOllamaStartupLabel = selectedData?.service?.supported ? 'Run at Startup' : 'Start Ollama';const installedModels = selectedData?.models || [];- const compareTargetKeys = useMemo(() => new Set(compareTargets.map(localLlmTargetKey)), [compareTargets]);const catalogCategories = useMemo(() => {const counts = new Map();for (const model of catalog) {@@ -1778,105 +1765,21 @@ export function LocalLlmTab() {)}</div>- {/* Installed models */}- <div className="space-y-2 pt-2 border-t border-port-border/50">- <div className="flex items-center justify-between gap-3 flex-wrap">- <h3 className="text-xs font-medium text-gray-400">Installed on {labelFor(selected)} ({installedModels.length})</h3>- {compareTargets.length > 0 && (- <div className="flex items-center gap-2">- <span className="text-xs text-gray-500">{compareTargets.length} selected</span>- <button- onClick={openCompare}- disabled={compareTargets.length < 2}- className="px-2.5 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded disabled:opacity-50 flex items-center gap-1"- >- <ArrowRightLeft size={12} />- Compare selected- </button>- </div>- )}- </div>- {installedModels.length === 0 ? (- <p className="text-xs text-gray-500">No models installed yet.</p>- ) : installedModels.map((m) => (- // Mobile: identity stacks above the action row so the (often very- // long) `hf.co/…` model id gets the full row width and wraps instead- // of being ellipsised down to "hf.co/sja…". Desktop keeps the single- // line with actions trailing on the right.- <div key={m.id} className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 bg-port-bg border border-port-border rounded-lg p-3">- <div className="flex items-start gap-3 min-w-0 flex-1">- <label className="shrink-0 flex items-center pt-0.5" title={`Include ${m.name || m.id} in a comparison`}>- <input- type="checkbox"- checked={compareTargetKeys.has(localLlmTargetKey({ backend: selected, modelId: m.id }))}- onChange={() => toggleCompareTarget(selected, m.id)}- className="h-4 w-4 accent-port-accent"- aria-label={`Select ${m.name || m.id} for comparison`}- />- </label>- <div className="min-w-0 flex-1">- <div className="text-sm text-white break-all">{m.name}</div>- <div className="text-xs text-gray-500 break-words">- {[- m.params,- m.quantization,- m.family,- formatContextLength(m.contextLength),- m.size != null ? formatBytes(m.size) : null- ].filter(Boolean).join(' · ')}- </div>- {(m.capabilities || []).length > 0 && (- <div className="flex items-center gap-1 flex-wrap mt-1">- <CapabilityBadges capabilities={m.capabilities} />- </div>- )}- </div>- </div>- <div className="flex items-center gap-2 shrink-0 justify-end flex-wrap">- <Link- to={`/local-llm/playground?backend=${encodeURIComponent(selected)}&model=${encodeURIComponent(m.id)}`}- className="px-2.5 py-1 text-xs bg-port-accent-2/15 hover:bg-port-accent-2/25 text-port-accent-2 rounded flex items-center gap-1 shrink-0 no-underline"- title={`Chat with ${m.name || m.id}`}- >- <FlaskConical size={12} />- Chat- </Link>- {redownloadInstallId(m, selected) && (- <button- onClick={() => install(redownloadInstallId(m, selected), { force: true })}- disabled={busy}- title="Pull this build again. Updated GGUF files keep the same name, so an existing install will not refresh until you redownload."- className="px-2.5 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded disabled:opacity-50 flex items-center gap-1 shrink-0"- aria-label={`Redownload ${m.name || m.id}`}- >- {actionInProgress === `install-${redownloadInstallId(m, selected)}` ? <BrailleSpinner /> : <RefreshCw size={12} />}- Redownload- </button>- )}- {isConfirmingDelete(m.id) ? (- <ConfirmButtonPair- prompt="Delete?"- confirmIcon={Trash2}- busy={busy}- className="shrink-0"- onConfirm={() => confirmDelete(() => remove(m.id))}- onCancel={cancelDelete}- />- ) : (- <button- onClick={() => requestDelete(m.id)}- disabled={busy}- className="px-2.5 py-1 text-xs bg-port-error/20 hover:bg-port-error/40 text-port-error rounded disabled:opacity-50 flex items-center gap-1 shrink-0"- aria-label={`Delete ${m.name}`}- >- {actionInProgress === `delete-${m.id}` ? <BrailleSpinner /> : <Trash2 size={12} />}- Delete- </button>- )}- </div>- </div>- ))}- </div>+ <LocalLlmInstalledModels+ actionInProgress={actionInProgress}+ backend={selected}+ busy={busy}+ cancelDelete={cancelDelete}+ compareTargets={compareTargets}+ confirmDelete={confirmDelete}+ install={install}+ isConfirmingDelete={isConfirmingDelete}+ models={installedModels}+ onCompare={openCompare}+ onToggleCompare={toggleCompareTarget}+ remove={remove}+ requestDelete={requestDelete}+ /></div></div>);diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 4fcb2ced57..bb356e5a1b 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -204,8 +204,11 @@ grep -i "what you want to do" client/src/hooks/README.md| `useMoltworldWs` | Moltworld WebSocket feed. | Moltworld surfaces only. || `useYoutubeIngest` | One YouTube brain-ingest job slot: start/cancel + SSE progress + terminal-frame handling via `POST /api/brain/youtube/ingest`. Returns `{ active, percent, stage, start(body), cancel }` — `start` takes the whole payload (`{ url, captureTranscript, downloadVideo, ingestAudio, agentPrompt, tags }`), not a bare URL. `onComplete(ingest)` fires with the stored ingest record; non-fatal `warnings[]` on the terminal frame are toasted automatically. | Quick Capture's YouTube path, and any other surface that ingests a video into the brain. || `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). |+| `useVideoGenFieldState` | Mutable VideoGen field values, setters, and lifecycle refs initialized from URL handoff values. | Internal state slice composed by `useVideoGenForm`; keep model reconciliation and submission behavior in their focused units. || `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. |+| `useVideoGenSubmitFlow` | Builds the current VideoGen wire payload and enveloped prompt from a form-state snapshot. | Internal submission slice composed by `useVideoGenForm`; all local, Grok, and federated request shaping remains in `videoGenSubmission`. |+| `useVideoGenValidation` | Derives keyframe errors and all VideoGen submit-blocking predicates from the current fields and model capabilities. | Internal validation slice composed by `useVideoGenForm`; also exports `validateVideoKeyframes` for focused tests. || `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. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 5d95fd63ec..745adf8a5f 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -203,6 +203,9 @@ export * from './useSystemResourceReport.js';export * from './useTwinEvaluationSuite.js';export * from './useUniverseNav.js';export * from './useVideoFileSrc.js';+export * from './useVideoGenFieldState.js';export * from './useVideoGenForm.js';export * from './useVideoGenQueue.js';+export * from './useVideoGenSubmitFlow.js';+export * from './useVideoGenValidation.js';export * from './useVoiceUiSync.js';diff --git a/client/src/hooks/useVideoGenFieldState.js b/client/src/hooks/useVideoGenFieldState.jsnew file mode 100644index 0000000000..fc6c7f4b75--- /dev/null+++ b/client/src/hooks/useVideoGenFieldState.js@@ -0,0 +1,115 @@+import { useRef, useState } from 'react';+import { GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokVideoClip.js';+import { DEFAULT_I2V_REFERENCE_MODE } from '../lib/videoReferenceModes.js';+import {+ DEFAULT_CONTEXT_FRAMES,+ DEFAULT_SPEED_PROFILE_ID,+ STOCK_TEXT_ENCODER_ID,+} from '../lib/videoGenParams.js';++/**+ * Owns the mutable fields and lifecycle refs for the VideoGen form.+ * URL-derived values are sampled on mount; reconciliation effects stay in the+ * orchestration hook where they can react to the loaded model catalog.+ */+export function useVideoGenFieldState({+ incomingAudioFilename,+ incomingNegativePrompt,+ incomingPrompt,+ incomingSourceImage,+}) {+ const [backend, setBackend] = useState('local');+ const [grokDuration, setGrokDuration] = useState(GROK_VIDEO_DEFAULT_DURATION);+ const [mode, setMode] = useState(incomingAudioFilename ? 'a2v' : (incomingSourceImage ? 'image' : 'text'));+ const [prompt, setPrompt] = useState(incomingPrompt || '');+ const [negativePrompt, setNegativePrompt] = useState(incomingNegativePrompt || '');+ const [stylePreset, setStylePreset] = useState(null);+ const [modelId, setModelId] = useState('');+ const [remixSourceModel, setRemixSourceModel] = useState(null);+ const [remixModelFallback, setRemixModelFallback] = useState(null);+ const [width, setWidth] = useState(768);+ const [height, setHeight] = useState(512);+ const sizeManuallySetRef = useRef(false);+ const [numFrames, setNumFrames] = useState(121);+ const [fps, setFps] = useState(24);+ const [chunks, setChunks] = useState(1);+ const [chunkPrompts, setChunkPrompts] = useState([]);+ const [contextFrames, setContextFrames] = useState(DEFAULT_CONTEXT_FRAMES);+ const [steps, setSteps] = useState('');+ const [guidanceScale, setGuidanceScale] = useState('');+ const [imageStrength, setImageStrength] = useState('');+ const [i2vReferenceMode, setI2vReferenceMode] = useState(DEFAULT_I2V_REFERENCE_MODE);+ const [seed, setSeed] = useState('');+ const [tiling, setTiling] = useState('auto');+ const [textEncoderId, setTextEncoderId] = useState(STOCK_TEXT_ENCODER_ID);+ const [speedProfileId, setSpeedProfileId] = useState(DEFAULT_SPEED_PROFILE_ID);+ const [disableAudio, setDisableAudio] = useState(false);+ const [selectedLoras, setSelectedLoras] = useState([]);+ const [noMusic, setNoMusic] = useState(false);+ const [sourceImageFile, setSourceImageFile] = useState(incomingSourceImage || null);+ const [sourceImageUpload, setSourceImageUpload] = useState(null);+ const [lastImageFile, setLastImageFile] = useState(null);+ const [lastImageUpload, setLastImageUpload] = useState(null);+ const [keyframesMode, setKeyframesMode] = useState(false);+ const [keyframes, setKeyframes] = useState([]);+ const [extendFromVideoId, setExtendFromVideoId] = useState('');+ const [extendingFrame, setExtendingFrame] = useState(false);+ const [audioFile, setAudioFile] = useState(null);+ const audioHandoffRef = useRef(null);+ const [icReferenceFile, setIcReferenceFile] = useState(null);+ const [icReferenceVideoId, setIcReferenceVideoId] = useState('');+ const [icReferenceImageFiles, setIcReferenceImageFiles] = useState([]);+ const [icStrength, setIcStrength] = useState(1.0);+ const [icSkipStage2, setIcSkipStage2] = useState(false);+ const [icReferenceNames, setIcReferenceNames] = useState([]);+ const staleModelToastRef = useRef(null);++ return {+ audioFile, setAudioFile, audioHandoffRef,+ backend, setBackend,+ chunks, setChunks,+ chunkPrompts, setChunkPrompts,+ contextFrames, setContextFrames,+ disableAudio, setDisableAudio,+ extendingFrame, setExtendingFrame,+ extendFromVideoId, setExtendFromVideoId,+ fps, setFps,+ grokDuration, setGrokDuration,+ guidanceScale, setGuidanceScale,+ height, setHeight,+ i2vReferenceMode, setI2vReferenceMode,+ icReferenceFile, setIcReferenceFile,+ icReferenceImageFiles, setIcReferenceImageFiles,+ icReferenceNames, setIcReferenceNames,+ icReferenceVideoId, setIcReferenceVideoId,+ icSkipStage2, setIcSkipStage2,+ icStrength, setIcStrength,+ imageStrength, setImageStrength,+ keyframes, setKeyframes,+ keyframesMode, setKeyframesMode,+ lastImageFile, setLastImageFile,+ lastImageUpload, setLastImageUpload,+ mode, setMode,+ modelId, setModelId,+ negativePrompt, setNegativePrompt,+ noMusic, setNoMusic,+ numFrames, setNumFrames,+ prompt, setPrompt,+ remixModelFallback, setRemixModelFallback,+ remixSourceModel, setRemixSourceModel,+ seed, setSeed,+ selectedLoras, setSelectedLoras,+ sizeManuallySetRef,+ speedProfileId, setSpeedProfileId,+ staleModelToastRef,+ steps, setSteps,+ stylePreset, setStylePreset,+ sourceImageFile, setSourceImageFile,+ sourceImageUpload, setSourceImageUpload,+ textEncoderId, setTextEncoderId,+ tiling, setTiling,+ width, setWidth,+ };+}++export default useVideoGenFieldState;diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.jsindex ed34095be7..a8fd156088 100644--- a/client/src/hooks/useVideoGenForm.js+++ b/client/src/hooks/useVideoGenForm.js@@ -12,18 +12,19 @@ import { randomSeed } from '../lib/genUtils';import {resolutionOptionsForModel, defaultResolutionForModel, snapAspectToImage,} from '../lib/videoGenResolutions';-import { GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokVideoClip.js';import { VIDEO_TILING_ENUM_SET } from '../lib/videoTilingOptions';-import { buildVideoGenSubmission, envelopVideoPrompt } from '../lib/videoGenSubmission';import {- MAX_CHUNKS, DEFAULT_CONTEXT_FRAMES,- videoModelMemoryGb, computeFflfSafeFrames, isModelAllowedForMode,+ MAX_CHUNKS,+ videoModelMemoryGb, isModelAllowedForMode,normalizeFramesForModel, normalizeFpsForModel,- icLoraSpecForMode, icResolutionIssue,- STOCK_TEXT_ENCODER_ID, textEncoderOptionsForModel, normalizeTextEncoderForModel,+ icLoraSpecForMode,+ textEncoderOptionsForModel, normalizeTextEncoderForModel,textEncoderIdFromRecord,- DEFAULT_SPEED_PROFILE_ID, normalizeSpeedProfileForModel, speedProfileIdFromRecord,+ normalizeSpeedProfileForModel, speedProfileIdFromRecord,} from '../lib/videoGenParams.js';+import { useVideoGenFieldState } from './useVideoGenFieldState.js';+import { useVideoGenSubmitFlow } from './useVideoGenSubmitFlow.js';+import { useVideoGenValidation } from './useVideoGenValidation.js';// A Remix is an editing starting point. A fixed sampler profile (for example,// MiniMax H3) cannot honor a negative prompt, steps, or CFG override, so@@ -75,99 +76,57 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, rconst incomingWidth = searchParams.get('w');const incomingHeight = searchParams.get('h');- // Grok Build CLI video backend (#2859 phase 2) — surfaced only when the- // user enabled Grok in Settings → Image Gen (one toggle covers image +- // video). 'local' keeps every existing flow untouched.- const [backend, setBackend] = useState('local');- const [grokDuration, setGrokDuration] = useState(GROK_VIDEO_DEFAULT_DURATION);-- const [mode, setMode] = useState(incomingAudioFilename ? 'a2v' : (incomingSourceImage ? 'image' : 'text'));- const [prompt, setPrompt] = useState(incomingPrompt || '');- const [negativePrompt, setNegativePrompt] = useState(incomingNegativePrompt || '');- const [stylePreset, setStylePreset] = useState(null);- const [modelId, setModelId] = useState('');- // Source model awaiting the catalog load. Both cross-page and in-page Remix- // arrive before/after models independently, so this state gives them one- // reconciliation path once the model capabilities are known. Recorded- // model-specific conditioning (a substitute text encoder or LoRAs) cannot- // survive a model swap, so it explicitly keeps that source model selected- // for a faithful remix.- const [remixSourceModel, setRemixSourceModel] = useState(null);- const [remixModelFallback, setRemixModelFallback] = useState(null);- const [width, setWidth] = useState(768);- const [height, setHeight] = useState(512);- // Set once the size has been chosen deliberately — the user picking a preset,- // or an explicit size arriving via Continue/Remix/restore. While it's false,- // selecting an I2V source image auto-snaps W×H to the source's aspect ratio- // (so the default frame doesn't cover-crop the subject). The snap itself does- // NOT set this, so re-picking a different source still re-snaps until the user- // takes the size into their own hands.- const sizeManuallySetRef = useRef(false);- const [numFrames, setNumFrames] = useState(121);- const [fps, setFps] = useState(24);- const [chunks, setChunks] = useState(1);- // Per-chunk prompt beats (#3695) — one editable string per chained chunk, so- // a longer shot can progress instead of replaying the same prompt at each- // seam. Kept as a plain sparse-by-blank array (index i steers chunk i); a- // blank entry means "use the main prompt for this chunk". Grown on demand by- // `setChunkPromptAt` rather than eagerly resized on every chunk change, so- // lowering then raising the count doesn't lose typed text.- const [chunkPrompts, setChunkPrompts] = useState([]);- // Continuation context window — how many of the previous chunk's frames each- // chained chunk conditions on. 0 means "last frame only"; the server clamps- // and ignores it on a runtime with no extend pipeline.- const [contextFrames, setContextFrames] = useState(DEFAULT_CONTEXT_FRAMES);- const [steps, setSteps] = useState('');- const [guidanceScale, setGuidanceScale] = useState('');- const [imageStrength, setImageStrength] = useState('');- // What the source image PROMISES (#4874): Anchor reproduces it as frame one,- // Inspire uses it for subject/style guidance and generates frame one. The- // effect below snaps this back to the default whenever the selected model or- // mode can't keep the promise, so the form can never submit a mode the server- // would reject — or, worse, display a promise the render would not honor.- const [i2vReferenceMode, setI2vReferenceMode] = useState(DEFAULT_I2V_REFERENCE_MODE);- const [seed, setSeed] = useState('');- const [tiling, setTiling] = useState('auto');- // Which prompt conditioner reads the prompt. Only MiniMax H3 offers a choice- // today (`model.textEncoderOptions`, decorated server-side); everywhere else- // the list is empty and this stays on the stock sentinel, which the submit- // builder drops from the payload entirely.- const [textEncoderId, setTextEncoderId] = useState(STOCK_TEXT_ENCODER_ID);- // Named sampler schedule (#4875). Defaults to Quality, the shipped contract —- // it is a real selectable value rather than '' so the <select> always has a- // matching <option>, and the submit builder drops it as "unchanged".- const [speedProfileId, setSpeedProfileId] = useState(DEFAULT_SPEED_PROFILE_ID);- const [disableAudio, setDisableAudio] = useState(false);- // Video LoRAs (ltx2 runtime only) — `{ filename, name, scale }` entries the- // LoraPicker owns; `availableLoras` is the full installed library filtered- // by the picker to the model's video family. See videoLoraFamily().- const [selectedLoras, setSelectedLoras] = useState([]);- // "No music" appends a soundscape constraint at submit time. LTX-2 and- // MiniMax H3 both steer generated audio from prompt text — adding "no music,- // no soundtrack" pushes them toward ambient/diegetic sound (footsteps, room- // tone) and away from generated background music.- const [noMusic, setNoMusic] = useState(false);- const [sourceImageFile, setSourceImageFile] = useState(incomingSourceImage || null);- const [sourceImageUpload, setSourceImageUpload] = useState(null);- const [lastImageFile, setLastImageFile] = useState(null);- const [lastImageUpload, setLastImageUpload] = useState(null);- // Multi-keyframe FFLF (ltx2 runtime only): the user anchors 2–8 gallery- // images at specific pixel-frame indices and the model interpolates between- // them. This is a distinct server path from the legacy first/last pair- // (the route rejects mixing the two) — `keyframesMode` flips fflf between- // the two pickers. Each entry is { file, index } where file is a gallery- // basename; the route resolves it to an absolute path. Keyframes are- // gallery-only (no per-frame upload) because the route only accepts- // gallery references for them.- const [keyframesMode, setKeyframesMode] = useState(false);- const [keyframes, setKeyframes] = useState([]);- const [extendFromVideoId, setExtendFromVideoId] = useState('');- const [extendingFrame, setExtendingFrame] = useState(false);- // a2v mode — direct audio upload only (no gallery for audio yet). The File- // is sent as multipart field name 'audioFile'; the server stages it under- // data/uploads, then the python helper passes it to AudioToVideoPipeline.- const [audioFile, setAudioFile] = useState(null);- const audioHandoffRef = useRef(null);+ const {+ audioFile, setAudioFile, audioHandoffRef,+ backend, setBackend,+ chunks, setChunks,+ chunkPrompts, setChunkPrompts,+ contextFrames, setContextFrames,+ disableAudio, setDisableAudio,+ extendingFrame, setExtendingFrame,+ extendFromVideoId, setExtendFromVideoId,+ fps, setFps,+ grokDuration, setGrokDuration,+ guidanceScale, setGuidanceScale,+ height, setHeight,+ i2vReferenceMode, setI2vReferenceMode,+ icReferenceFile, setIcReferenceFile,+ icReferenceImageFiles, setIcReferenceImageFiles,+ icReferenceNames, setIcReferenceNames,+ icReferenceVideoId, setIcReferenceVideoId,+ icSkipStage2, setIcSkipStage2,+ icStrength, setIcStrength,+ imageStrength, setImageStrength,+ keyframes, setKeyframes,+ keyframesMode, setKeyframesMode,+ lastImageFile, setLastImageFile,+ lastImageUpload, setLastImageUpload,+ mode, setMode,+ modelId, setModelId,+ negativePrompt, setNegativePrompt,+ noMusic, setNoMusic,+ numFrames, setNumFrames,+ prompt, setPrompt,+ remixModelFallback, setRemixModelFallback,+ remixSourceModel, setRemixSourceModel,+ seed, setSeed,+ selectedLoras, setSelectedLoras,+ sizeManuallySetRef,+ speedProfileId, setSpeedProfileId,+ staleModelToastRef,+ steps, setSteps,+ stylePreset, setStylePreset,+ sourceImageFile, setSourceImageFile,+ sourceImageUpload, setSourceImageUpload,+ textEncoderId, setTextEncoderId,+ tiling, setTiling,+ width, setWidth,+ } = useVideoGenFieldState({+ incomingAudioFilename,+ incomingNegativePrompt,+ incomingPrompt,+ incomingSourceImage,+ });// Music renders live in the shared library rather than in the browser's// local file picker. Turn a render's deep-link filename into the same File@@ -199,29 +158,6 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r});return () => { cancelled = true; };}, [incomingAudioFilename, setSearchParams]);- // IC-LoRA remix modes (issue #3100) — the reference clip is either a fresh- // upload (multipart field 'icReference') or a prior render picked by history- // id. The two are mutually exclusive server-side, so the panel's Clear drops- // both. `icStrength` weights the reference conditioning channel.- const [icReferenceFile, setIcReferenceFile] = useState(null);- const [icReferenceVideoId, setIcReferenceVideoId] = useState('');- // Image-kind IC references (Ingredients, #3112) — 2-8 gallery basenames rather- // than the single clip above. Gallery-only, mirroring the route: the reference- // list is a separate submit field (icReferenceImageFiles) so a clip can never- // ride into an image-kind weight (which would silently produce garbage).- const [icReferenceImageFiles, setIcReferenceImageFiles] = useState([]);- const [icStrength, setIcStrength] = useState(1.0);- const [icSkipStage2, setIcSkipStage2] = useState(false);- // Display-only: the reference clip name(s) of an IN-FLIGHT render restored via- // /active. An upload isn't re-derivable from its basename, so this can't- // repopulate the picker — it just tells the user what the running job is- // conditioned on instead of showing an empty panel.- const [icReferenceNames, setIcReferenceNames] = useState([]);- // Tracks the last stale modelId we already toasted about so the- // validateModelId effect fires the "original model gone" toast exactly once- // per unique stale id, even if the effect re-runs (e.g. models list updates).- const staleModelToastRef = useRef(null);-// Seed the model dropdown from the server's default once /status lands,// without clobbering a Remix/deep-link/user pick that already set it.useEffect(() => {@@ -654,33 +590,6 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r// below numFrames. Compute the same cap the server enforces so the picker can// gate indices (and the auto-seed) against it. Falls back to numFrames when// the budget hasn't loaded yet (server still enforces the real cap).- const maxSafeFrames = useMemo(- () => computeFflfSafeFrames(width, height, numFrames, status?.fflfLtx2PixelBudget),- [width, height, numFrames, status?.fflfLtx2PixelBudget],- );- const keyframesError = useMemo(() => {- if (!keyframesActive) return null;- if (keyframes.length < 2) return 'Add at least 2 keyframes.';- if (keyframes.length > 8) return 'Use at most 8 keyframes.';- let prev = -1;- for (let i = 0; i < keyframes.length; i++) {- const kf = keyframes[i];- if (!kf.file) return `Keyframe ${i + 1} needs a gallery image.`;- if (!Number.isInteger(kf.index) || kf.index < 0) return `Keyframe ${i + 1} needs a frame index ≥ 0.`;- if (kf.index > numFrames - 1) return `Keyframe ${i + 1} frame ${kf.index} must be below numFrames (${numFrames}).`;- // Effective cap from the resolution-dependent pixel budget (< numFrames at- // higher resolutions). Mirrors the worker's clamp so we don't POST a- // render that 400s with LTX2_FFLF_PIXEL_BUDGET_EXCEEDED.- if (maxSafeFrames < numFrames && kf.index > maxSafeFrames - 1) {- return `Keyframe ${i + 1} frame ${kf.index} exceeds the ${width}×${height} pixel budget (max frame ${maxSafeFrames - 1}). Lower the resolution or raise FFLF_LTX2_PIXEL_BUDGET.`;- }- if (kf.index <= prev) return 'Keyframe frame indices must be strictly ascending.';- prev = kf.index;- }- return null;- }, [keyframesActive, keyframes, numFrames, maxSafeFrames, width, height]);- const keyframesBlocked = keyframesActive && !!keyframesError;-// Preset pick or custom W×H edit — mark the size as manually set so aspect-snap// on image upload stops overriding it (same flag the remix/deep-link paths set).// ResolutionField passes a transient 0 mid-edit and blur-snaps each edge to the@@ -740,6 +649,36 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, rsetLastImageUpload(file);};+ const {+ a2vModeBlocked,+ chainingActive,+ extendModeBlocked,+ icLoraModeBlocked,+ keyframesBlocked,+ keyframesError,+ maxSafeFrames,+ } = useVideoGenValidation({+ audioFile,+ chunks,+ currentModel,+ extendFromVideoId,+ extendingFrame,+ height,+ icImageKind,+ icModeActive,+ icReferenceFile,+ icReferenceImageFiles,+ icReferenceVideoId,+ icSpec,+ keyframes,+ keyframesActive,+ mode,+ numFrames,+ pixelBudget: status?.fflfLtx2PixelBudget,+ sourceImageFile,+ width,+ });+// The last addressable frame index — the smaller of numFrames and the// resolution-dependent pixel-budget cap (maxSafeFrames), minus 1. Seeding new// keyframe rows against this keeps the auto-seeded index inside the budget the@@ -1227,49 +1166,6 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r}};- // In Extend mode the source image is populated asynchronously after the- // user picks a prior video — until that extraction lands, sourceImageFile- // is empty and the request would silently fall back to T2V while still- // sending mode='extend'. Block submit/enqueue until the extend frame is- // actually ready (and unblocks the disabled state on the buttons too).- // ltx2-extend doesn't need a frame extraction — the route resolves the- // video id directly. Block only on extendFromVideoId being unset (and on- // legacy runtime, also wait for the extracted frame).- const extendModeBlocked = mode === 'extend' && (- !extendFromVideoId- || (!isLtx2FamilyRuntime(currentModel?.runtime) && (extendingFrame || !sourceImageFile))- );- // a2v requires an audio upload AND an ltx2-runtime model — the legacy- // mlx_video runtime has no audio-conditioned pipeline. Block submit when- // either is missing so the request fails the form, not the worker.- const a2vModeBlocked = mode === 'a2v' && (!audioFile || !isLtx2FamilyRuntime(currentModel?.runtime));- // IC-LoRA remix needs a reference clip AND an ltx2-runtime model, and the- // resolution must divide by the weight's reference-downscale factor (the- // server rejects otherwise). Block submit for all three so the request fails- // the form rather than the worker.- // An image-kind weight is satisfied by min..max FILLED gallery rows (blank rows- // are dropped from the payload, so an unfilled row must block rather than- // silently submit a short list the route would 400).- const icFilledImageRefs = icReferenceImageFiles.filter(Boolean).length;- const icLoraModeBlocked = icModeActive && (- (icImageKind- ? (icFilledImageRefs < icSpec.minReferences || icFilledImageRefs > icSpec.maxReferences)- : (!icReferenceFile && !icReferenceVideoId))- || !isLtx2FamilyRuntime(currentModel?.runtime)- || !!icResolutionIssue(icSpec, width, height)- );- // Chaining seeds each chunk from the previous one's last frame, so it needs- // i2v — asked through the shared predicate so the picker, this gate and the- // server's videoChainUnsupportedError can't answer differently.- const modelSupportsChaining = isModelAllowedForMode(currentModel, 'image');- // The single predicate for "this request really chains" — keyframes, IC- // references and a2v each anchor a SINGLE clip, so the route pins them to one- // chunk (KEYFRAMES_CHUNKS_CONFLICT / IC_LORA_CHUNKS_CONFLICT). Derived once so- // the submitted `chunks`, the submitted `chunkPrompts`, and the per-chunk beat- // editor can never disagree about whether chaining is active.- const chainingActive = mode !== 'a2v' && !keyframesActive && !icModeActive- && modelSupportsChaining && chunks > 1;-// Edit one beat. The backing array is only ever GROWN (never truncated on a// chunk-count change) so lowering the count and raising it again restores the// text the user already typed; submit and the editor slice to the live count.@@ -1297,7 +1193,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, ricReferenceImageFiles, icStrength, icSkipStage2,chainingActive, chunks, chunkPrompts, contextFrames,};- const buildGeneratePayload = () => buildVideoGenSubmission(submissionState);+ const { buildGeneratePayload, envelopedPrompt } = useVideoGenSubmitFlow(submissionState);return {// Backend + mode@@ -1309,7 +1205,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r// The exact prompt a render would be submitted with right now (style preset// + no-music envelope). The LoRA picker's #4665 trigger hint reads THIS, not// the raw textarea, so it can never disagree with the server-side weave.- envelopedPrompt: envelopVideoPrompt(prompt, submissionState),+ envelopedPrompt,negativePrompt, setNegativePrompt,stylePreset, setStylePreset,remixModelFallback,diff --git a/client/src/hooks/useVideoGenSubmitFlow.js b/client/src/hooks/useVideoGenSubmitFlow.jsnew file mode 100644index 0000000000..7787fdfa6c--- /dev/null+++ b/client/src/hooks/useVideoGenSubmitFlow.js@@ -0,0 +1,17 @@+import { useCallback } from 'react';+import { buildVideoGenSubmission, envelopVideoPrompt } from '../lib/videoGenSubmission.js';++/** Keeps request shaping behind one focused boundary for every VideoGen lane. */+export function useVideoGenSubmitFlow(submissionState) {+ const buildGeneratePayload = useCallback(+ () => buildVideoGenSubmission(submissionState),+ [submissionState],+ );++ return {+ buildGeneratePayload,+ envelopedPrompt: envelopVideoPrompt(submissionState.prompt, submissionState),+ };+}++export default useVideoGenSubmitFlow;diff --git a/client/src/hooks/useVideoGenValidation.js b/client/src/hooks/useVideoGenValidation.jsnew file mode 100644index 0000000000..158aaaebad--- /dev/null+++ b/client/src/hooks/useVideoGenValidation.js@@ -0,0 +1,97 @@+import { useMemo } from 'react';+import { isLtx2FamilyRuntime } from '../lib/runnerFamilies.js';+import {+ computeFflfSafeFrames,+ icResolutionIssue,+ isModelAllowedForMode,+} from '../lib/videoGenParams.js';++export function validateVideoKeyframes({+ active, frames, height, keyframes, maxSafeFrames, width,+}) {+ if (!active) return null;+ if (keyframes.length < 2) return 'Add at least 2 keyframes.';+ if (keyframes.length > 8) return 'Use at most 8 keyframes.';++ let previousIndex = -1;+ for (let index = 0; index < keyframes.length; index += 1) {+ const keyframe = keyframes[index];+ if (!keyframe.file) return `Keyframe ${index + 1} needs a gallery image.`;+ if (!Number.isInteger(keyframe.index) || keyframe.index < 0) {+ return `Keyframe ${index + 1} needs a frame index ≥ 0.`;+ }+ if (keyframe.index > frames - 1) {+ return `Keyframe ${index + 1} frame ${keyframe.index} must be below numFrames (${frames}).`;+ }+ if (maxSafeFrames < frames && keyframe.index > maxSafeFrames - 1) {+ return `Keyframe ${index + 1} frame ${keyframe.index} exceeds the ${width}×${height} pixel budget (max frame ${maxSafeFrames - 1}). Lower the resolution or raise FFLF_LTX2_PIXEL_BUDGET.`;+ }+ if (keyframe.index <= previousIndex) return 'Keyframe frame indices must be strictly ascending.';+ previousIndex = keyframe.index;+ }+ return null;+}++/** Derives every submit-blocking predicate from the current VideoGen fields. */+export function useVideoGenValidation({+ audioFile,+ chunks,+ currentModel,+ extendFromVideoId,+ extendingFrame,+ height,+ icImageKind,+ icModeActive,+ icReferenceFile,+ icReferenceImageFiles,+ icReferenceVideoId,+ icSpec,+ keyframes,+ keyframesActive,+ mode,+ numFrames,+ pixelBudget,+ sourceImageFile,+ width,+}) {+ const maxSafeFrames = useMemo(+ () => computeFflfSafeFrames(width, height, numFrames, pixelBudget),+ [height, numFrames, pixelBudget, width],+ );+ const keyframesError = useMemo(() => validateVideoKeyframes({+ active: keyframesActive,+ frames: numFrames,+ height,+ keyframes,+ maxSafeFrames,+ width,+ }), [height, keyframes, keyframesActive, maxSafeFrames, numFrames, width]);++ const ltx2Runtime = isLtx2FamilyRuntime(currentModel?.runtime);+ const extendModeBlocked = mode === 'extend' && (+ !extendFromVideoId || (!ltx2Runtime && (extendingFrame || !sourceImageFile))+ );+ const a2vModeBlocked = mode === 'a2v' && (!audioFile || !ltx2Runtime);+ const filledImageRefs = icReferenceImageFiles.filter(Boolean).length;+ const icLoraModeBlocked = icModeActive && (+ (icImageKind+ ? (filledImageRefs < icSpec.minReferences || filledImageRefs > icSpec.maxReferences)+ : (!icReferenceFile && !icReferenceVideoId))+ || !ltx2Runtime+ || !!icResolutionIssue(icSpec, width, height)+ );+ const chainingActive = mode !== 'a2v' && !keyframesActive && !icModeActive+ && isModelAllowedForMode(currentModel, 'image') && chunks > 1;++ return {+ a2vModeBlocked,+ chainingActive,+ extendModeBlocked,+ icLoraModeBlocked,+ keyframesBlocked: keyframesActive && !!keyframesError,+ keyframesError,+ maxSafeFrames,+ };+}++export default useVideoGenValidation;