Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: extract local LLM and video submit units

Adam Eivy5d66ef1a2041
diff --git a/client/src/components/settings/LocalLlmBackendCard.jsx b/client/src/components/settings/LocalLlmBackendCard.jsx
new file mode 100644
index 0000000000..cfd2a20889
--- /dev/null
+++ b/client/src/components/settings/LocalLlmBackendCard.jsx
@@ -0,0 +1,150 @@
+import { ArrowRightLeft, ArrowUpCircle, Power, PowerOff, Star } from 'lucide-react';
+import BrailleSpinner from '../BrailleSpinner';
+import { formatContextLength } from '../../utils/formatters';
+import {
+ patchSettingsSlice,
+ switchLocalLlmBackend,
+ upgradeLocalLlmBackend,
+} from '../../services/api';
+
+const btnClass = 'flex items-center gap-1.5 px-2 py-1 text-xs font-medium rounded transition-colors disabled:opacity-50';
+
+const labelForBackend = (id) => ({ ollama: 'Ollama', lmstudio: 'LM Studio' }[id] || id);
+
+export default function LocalLlmBackendCard({
+ backend, status, isDefault, busy, actionInProgress, runAction, setConfirmAction,
+}) {
+ const data = status?.[backend.id];
+ const Icon = backend.icon;
+ const other = backend.id === 'ollama' ? 'lmstudio' : 'ollama';
+ const otherData = status?.[other];
+ const startupService = backend.id === 'ollama' ? data?.service : null;
+ const runsAtStartup = Boolean(startupService?.runAtStartup);
+ // The window resident models were ACTUALLY loaded at — Ollama picks it from
+ // VRAM (4K/32K/256K), and an agent harness that overruns it dies mid-task with
+ // a 400. Null while nothing is resident, since Ollama hasn't committed yet.
+ const runtimeContext = backend.id === 'ollama' ? data?.contextLength?.runtime ?? null : null;
+ const runtimeContextLabel = formatContextLength(runtimeContext);
+ const contextBelowAgentFloor = runtimeContext != null
+ && runtimeContext < (data?.contextLength?.agentMinimum ?? 0);
+
+ return (
+ <div className="bg-port-bg border border-port-border rounded-lg p-3 space-y-2">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2 text-sm text-gray-400">
+ <Icon size={14} />
+ {backend.label}
+ </div>
+ <div className="flex items-center gap-1.5">
+ {isDefault && (
+ <span
+ className="text-xs px-1.5 py-0.5 bg-port-accent/20 text-port-accent rounded"
+ title="PortOS routes local-LLM runs here by default. This is independent of whether the server is running — see Local Runtime Servers above."
+ >
+ Default
+ </span>
+ )}
+ </div>
+ </div>
+
+ <div className="text-xs text-gray-400">
+ {data?.modelCount ?? 0} model{(data?.modelCount ?? 0) === 1 ? '' : 's'} installed
+ {data?.version && <> · v{data.version}</>}
+ {backend.id === 'ollama' && data?.updateAvailable && data?.latestVersion && (
+ <span className="text-port-warning" title={`Ollama v${data.latestVersion} is available (you have v${data.version})`}>
+ {' · '}v{data.latestVersion} available
+ </span>
+ )}
+ {startupService?.supported && <> · {runsAtStartup ? 'runs at login' : 'startup off'}</>}
+ {runtimeContextLabel && (
+ <span
+ className={contextBelowAgentFloor ? 'text-port-warning' : undefined}
+ title={contextBelowAgentFloor
+ ? `Loaded models are running at ${runtimeContextLabel} — below what an agent harness (Claude Ollama / OpenCode Ollama) usually needs. Set "Local num_ctx" on that provider in AI Providers to reload Ollama at a larger window.`
+ : `Loaded models are running at ${runtimeContextLabel}`}
+ >
+ {' · '}{runtimeContextLabel}
+ </span>
+ )}
+ </div>
+
+ {data?.installed && (
+ <div className="flex flex-wrap gap-1.5 pt-1 border-t border-port-border/50">
+ {backend.id === 'ollama' && data?.updateAvailable && (
+ data?.canUpgrade ? (
+ <button
+ onClick={() => runAction(
+ 'upgrade-ollama',
+ () => upgradeLocalLlmBackend('ollama'),
+ (r) => r?.note ? `Ollama updated — ${r.note}` : `Ollama updated to v${data.latestVersion}`,
+ )}
+ disabled={busy}
+ className={`${btnClass} bg-port-success/20 hover:bg-port-success/30 text-port-success`}
+ title={`Update Ollama from v${data.version} to v${data.latestVersion} in place (downloads the latest release and restarts it)`}
+ >
+ {actionInProgress === 'upgrade-ollama' ? <BrailleSpinner /> : <ArrowUpCircle size={12} />}
+ Update to v{data.latestVersion}
+ </button>
+ ) : (
+ <a
+ href={data.downloadUrl}
+ target="_blank"
+ rel="noreferrer"
+ className={`${btnClass} bg-port-warning/20 hover:bg-port-warning/30 text-port-warning no-underline`}
+ title={`Ollama v${data.latestVersion} is available — automatic updates aren't supported on this platform`}
+ >
+ <ArrowUpCircle size={12} />
+ Update available
+ </a>
+ )
+ )}
+ {!isDefault && (
+ <button
+ onClick={() => runAction(`switch-${backend.id}`, () => switchLocalLlmBackend(backend.id), `${backend.label} is now the default backend`)}
+ disabled={busy}
+ className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}
+ title="Route PortOS local-LLM runs here by default — doesn't move any models or stop the other backend"
+ >
+ {actionInProgress === `switch-${backend.id}` ? <BrailleSpinner /> : <Star size={12} />}
+ Set as Default
+ </button>
+ )}
+ {otherData?.available && (
+ <button
+ onClick={() => setConfirmAction({
+ type: 'migrate',
+ to: backend.id,
+ from: other,
+ label: `Bring ${labelForBackend(other)}'s models onto ${backend.label}?`,
+ detail: `Provisions the ${otherData.modelCount ?? 0} model${(otherData.modelCount ?? 0) === 1 ? '' : 's'} on ${labelForBackend(other)} onto ${backend.label} — your default backend is unchanged. Link shares each GGUF on disk (no extra space, falls back to a copy across filesystems); Copy makes an independent duplicate. Portable single-file GGUF models move with no re-download; MLX-format, sharded, or multimodal models that can't be shared/copied are re-pulled.`,
+ })}
+ disabled={busy}
+ className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}
+ title={`Copy or link the models installed on ${labelForBackend(other)} onto ${backend.label}`}
+ >
+ <ArrowRightLeft size={12} />
+ Import from {labelForBackend(other)}
+ </button>
+ )}
+ </div>
+ )}
+
+ <div className="flex items-center justify-between gap-2 pt-1 border-t border-port-border/50">
+ <span className="text-xs text-gray-500">{data?.disabled ? 'PortOS will not expect this backend to be running.' : 'Show a warning when this backend is offline.'}</span>
+ <button
+ onClick={() => runAction(
+ `toggle-disabled-${backend.id}`,
+ () => patchSettingsSlice(`localLlm.${backend.id}`, { disabled: !data?.disabled }),
+ data?.disabled ? `${backend.label} enabled` : `${backend.label} marked as disabled`,
+ )}
+ disabled={busy}
+ className={`${btnClass} ${data?.disabled ? 'bg-port-border hover:bg-port-border/70 text-white' : 'bg-port-warning/20 hover:bg-port-warning/30 text-port-warning'}`}
+ title={data?.disabled ? `Re-enable ${backend.label} availability warnings` : `Mark ${backend.label} as intentionally disabled`}
+ >
+ {actionInProgress === `toggle-disabled-${backend.id}` ? <BrailleSpinner /> : data?.disabled ? <Power size={12} /> : <PowerOff size={12} />}
+ {data?.disabled ? 'Enable warnings' : 'Mark disabled'}
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index 10ae6d561e..01e45cc0cb 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -1,6 +1,6 @@
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, ArrowUpCircle, Zap, ChevronDown, ChevronUp, Terminal } from 'lucide-react';
+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 toast from '../ui/Toast';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
import BrailleSpinner from '../BrailleSpinner';
@@ -9,7 +9,7 @@ import { localLlmTargetKey } from '../../lib/localLlmTargetKey';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import {
getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,
- deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService,
+ deleteLocalLlmModel, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService,
installAudioModel, patchSettingsSlice, getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer,
downloadSpecDecodeModel, controlLmStudioService, getMtplxServerStatus, stopMtplxServer, installMtplx,
searchMtplxModels, pullMtplxModel, removeMtplxModel,
@@ -20,6 +20,7 @@ import CapabilityBadges from '../models/CapabilityBadges.jsx';
import SpecDecodeWeightRow from './SpecDecodeWeightRow.jsx';
import RuntimeServersCard from './RuntimeServersCard.jsx';
import MtplxServerCard from './MtplxServerCard.jsx';
+import LocalLlmBackendCard from './LocalLlmBackendCard.jsx';
const BACKENDS = [
{ id: 'ollama', label: 'Ollama', icon: Cpu },
@@ -158,142 +159,6 @@ function summarizeMigrate(r) {
return `${labelFor(r.from)} → ${labelFor(r.to)}: ${parts.join(', ') || 'nothing to move'}`;
}
-function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAction, setConfirmAction }) {
- const data = status?.[backend.id];
- const Icon = backend.icon;
- const other = backend.id === 'ollama' ? 'lmstudio' : 'ollama';
- const otherData = status?.[other];
- const startupService = backend.id === 'ollama' ? data?.service : null;
- const runsAtStartup = Boolean(startupService?.runAtStartup);
- // The window resident models were ACTUALLY loaded at — Ollama picks it from
- // VRAM (4K/32K/256K), and an agent harness that overruns it dies mid-task with
- // a 400. Null while nothing is resident, since Ollama hasn't committed yet.
- const runtimeContext = backend.id === 'ollama' ? data?.contextLength?.runtime ?? null : null;
- const runtimeContextLabel = formatContextLength(runtimeContext);
- const contextBelowAgentFloor = runtimeContext != null
- && runtimeContext < (data?.contextLength?.agentMinimum ?? 0);
-
- return (
- <div className="bg-port-bg border border-port-border rounded-lg p-3 space-y-2">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2 text-sm text-gray-400">
- <Icon size={14} />
- {backend.label}
- </div>
- <div className="flex items-center gap-1.5">
- {isDefault && (
- <span
- className="text-xs px-1.5 py-0.5 bg-port-accent/20 text-port-accent rounded"
- title="PortOS routes local-LLM runs here by default. This is independent of whether the server is running — see Local Runtime Servers above."
- >
- Default
- </span>
- )}
- </div>
- </div>
-
- <div className="text-xs text-gray-400">
- {data?.modelCount ?? 0} model{(data?.modelCount ?? 0) === 1 ? '' : 's'} installed
- {data?.version && <> · v{data.version}</>}
- {backend.id === 'ollama' && data?.updateAvailable && data?.latestVersion && (
- <span className="text-port-warning" title={`Ollama v${data.latestVersion} is available (you have v${data.version})`}>
- {' · '}v{data.latestVersion} available
- </span>
- )}
- {startupService?.supported && <> · {runsAtStartup ? 'runs at login' : 'startup off'}</>}
- {runtimeContextLabel && (
- <span
- className={contextBelowAgentFloor ? 'text-port-warning' : undefined}
- title={contextBelowAgentFloor
- ? `Loaded models are running at ${runtimeContextLabel} — below what an agent harness (Claude Ollama / OpenCode Ollama) usually needs. Set "Local num_ctx" on that provider in AI Providers to reload Ollama at a larger window.`
- : `Loaded models are running at ${runtimeContextLabel}`}
- >
- {' · '}{runtimeContextLabel}
- </span>
- )}
- </div>
-
- {data?.installed && (
- <div className="flex flex-wrap gap-1.5 pt-1 border-t border-port-border/50">
- {backend.id === 'ollama' && data?.updateAvailable && (
- data?.canUpgrade ? (
- <button
- onClick={() => runAction(
- 'upgrade-ollama',
- () => upgradeLocalLlmBackend('ollama'),
- (r) => r?.note ? `Ollama updated — ${r.note}` : `Ollama updated to v${data.latestVersion}`
- )}
- disabled={busy}
- className={`${btnClass} bg-port-success/20 hover:bg-port-success/30 text-port-success`}
- title={`Update Ollama from v${data.version} to v${data.latestVersion} in place (downloads the latest release and restarts it)`}
- >
- {actionInProgress === 'upgrade-ollama' ? <BrailleSpinner /> : <ArrowUpCircle size={12} />}
- Update to v{data.latestVersion}
- </button>
- ) : (
- <a
- href={data.downloadUrl}
- target="_blank"
- rel="noreferrer"
- className={`${btnClass} bg-port-warning/20 hover:bg-port-warning/30 text-port-warning no-underline`}
- title={`Ollama v${data.latestVersion} is available — automatic updates aren't supported on this platform`}
- >
- <ArrowUpCircle size={12} />
- Update available
- </a>
- )
- )}
- {!isDefault && (
- <button
- onClick={() => runAction(`switch-${backend.id}`, () => switchLocalLlmBackend(backend.id), `${backend.label} is now the default backend`)}
- disabled={busy}
- className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}
- title="Route PortOS local-LLM runs here by default — doesn't move any models or stop the other backend"
- >
- {actionInProgress === `switch-${backend.id}` ? <BrailleSpinner /> : <Star size={12} />}
- Set as Default
- </button>
- )}
- {otherData?.available && (
- <button
- onClick={() => setConfirmAction({
- type: 'migrate',
- to: backend.id,
- from: other,
- label: `Bring ${labelFor(other)}'s models onto ${backend.label}?`,
- detail: `Provisions the ${otherData.modelCount ?? 0} model${(otherData.modelCount ?? 0) === 1 ? '' : 's'} on ${labelFor(other)} onto ${backend.label} — your default backend is unchanged. Link shares each GGUF on disk (no extra space, falls back to a copy across filesystems); Copy makes an independent duplicate. Portable single-file GGUF models move with no re-download; MLX-format, sharded, or multimodal models that can't be shared/copied are re-pulled.`
- })}
- disabled={busy}
- className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}
- title={`Copy or link the models installed on ${labelFor(other)} onto ${backend.label}`}
- >
- <ArrowRightLeft size={12} />
- Import from {labelFor(other)}
- </button>
- )}
- </div>
- )}
-
- <div className="flex items-center justify-between gap-2 pt-1 border-t border-port-border/50">
- <span className="text-xs text-gray-500">{data?.disabled ? 'PortOS will not expect this backend to be running.' : 'Show a warning when this backend is offline.'}</span>
- <button
- onClick={() => runAction(
- `toggle-disabled-${backend.id}`,
- () => patchSettingsSlice(`localLlm.${backend.id}`, { disabled: !data?.disabled }),
- data?.disabled ? `${backend.label} enabled` : `${backend.label} marked as disabled`
- )}
- disabled={busy}
- className={`${btnClass} ${data?.disabled ? 'bg-port-border hover:bg-port-border/70 text-white' : 'bg-port-warning/20 hover:bg-port-warning/30 text-port-warning'}`}
- title={data?.disabled ? `Re-enable ${backend.label} availability warnings` : `Mark ${backend.label} as intentionally disabled`}
- >
- {actionInProgress === `toggle-disabled-${backend.id}` ? <BrailleSpinner /> : data?.disabled ? <Power size={12} /> : <PowerOff size={12} />}
- {data?.disabled ? 'Enable warnings' : 'Mark disabled'}
- </button>
- </div>
- </div>
- );
-}
-
export function LocalLlmTab() {
const navigate = useNavigate();
const [status, setStatus] = useState(null);
@@ -1080,7 +945,7 @@ export function LocalLlmTab() {
<>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{BACKENDS.map((b) => (
- <BackendCard
+ <LocalLlmBackendCard
key={b.id} backend={b} status={status} isDefault={status.backend === b.id}
busy={busy} actionInProgress={actionInProgress}
runAction={runAction} setConfirmAction={setConfirmAction}
diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.js
index 4969bfe4bf..ed34095be7 100644
--- a/client/src/hooks/useVideoGenForm.js
+++ b/client/src/hooks/useVideoGenForm.js
@@ -3,7 +3,6 @@ import { useSearchParams } from 'react-router';
import toast from '../components/ui/Toast';
import { extractLastFrame } from '../services/api';
import { trackAudioUrl } from '../services/apiTracks.js';
-import { composeStyledPrompt } from '../lib/composeStyledPrompt';
import { videoLoraFamily, isVideoLoraFamily, loraFamilyOf, VIDEO_LORA_FAMILIES, isLtx2FamilyRuntime } from '../lib/runnerFamilies';
import {
DEFAULT_I2V_REFERENCE_MODE, isDefaultI2vReferenceMode, normalizeI2vReferenceMode,
@@ -13,19 +12,17 @@ import { randomSeed } from '../lib/genUtils';
import {
resolutionOptionsForModel, defaultResolutionForModel, snapAspectToImage,
} from '../lib/videoGenResolutions';
-import { clampImageEdge } from '../lib/imageGenResolutions';
import { GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokVideoClip.js';
import { VIDEO_TILING_ENUM_SET } from '../lib/videoTilingOptions';
+import { buildVideoGenSubmission, envelopVideoPrompt } from '../lib/videoGenSubmission';
import {
- VIDEO_EDGE_BOUNDS, videoEdgeBoundsForModel, MAX_CHUNKS, DEFAULT_CONTEXT_FRAMES,
+ MAX_CHUNKS, DEFAULT_CONTEXT_FRAMES,
videoModelMemoryGb, computeFflfSafeFrames, isModelAllowedForMode,
- supportsVideoAudioControls, supportsVideoAudioPromptControls,
normalizeFramesForModel, normalizeFpsForModel,
icLoraSpecForMode, icResolutionIssue,
STOCK_TEXT_ENCODER_ID, textEncoderOptionsForModel, normalizeTextEncoderForModel,
textEncoderIdFromRecord,
DEFAULT_SPEED_PROFILE_ID, normalizeSpeedProfileForModel, speedProfileIdFromRecord,
- selectedSpeedProfile, videoChainChunkModes,
} from '../lib/videoGenParams.js';
// A Remix is an editing starting point. A fixed sampler profile (for example,
@@ -1285,191 +1282,22 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r
});
};
- // Snapshot the current form into a generate-payload. Used both by the
- // inline Generate button and by enqueue, so the two paths stay in lockstep.
-
- // A hidden mute checkbox from a prior model must not suppress H3's visible
- // prompt-audio steering. Treat mute as effective only on a model that can
- // actually disable its generated audio track.
- const effectiveDisableAudio = supportsVideoAudioControls(currentModel) && disableAudio;
- // The style preset and the no-music constraint are ENVELOPE, not content —
- // they have to wrap a per-chunk beat exactly as they wrap the main prompt.
- // Shipping a beat raw would render the chunks the user steered in a
- // different style (and with the soundtrack they disabled) than the chunks
- // that fall back to the main prompt — a visible change at every seam, which
- // is the artifact chaining exists to avoid.
- // Idempotent on "no music": if the text already says it, don't double-append.
- //
- // Hoisted out of buildGeneratePayload so the LoRA picker's trigger-word hint
- // (#4665) can be judged against the EXACT text the render will receive. The
- // server weaves against the enveloped prompt; a hint reading the raw textarea
- // would contradict it whenever the envelope already supplies the token.
- const withEnvelope = (text) => {
- const c = composeStyledPrompt(text, negativePrompt, stylePreset);
- return (supportsVideoAudioPromptControls(currentModel) && noMusic && !effectiveDisableAudio && !/no music/i.test(c.prompt))
- ? `${c.prompt}\n\nno music, no soundtrack`
- : c.prompt;
- };
-
- const buildGeneratePayload = () => {
- const composed = composeStyledPrompt(prompt, negativePrompt, stylePreset);
- // Beats for the LIVE chunks only — the backing array is never truncated on
- // a chunk-count change, so slicing here is what keeps a stale tail off the
- // wire. A short list is fine: the server falls back to the main prompt for
- // any chunk the list doesn't cover. A blank beat stays blank (NOT enveloped)
- // so it still reads as "absent" and triggers that same fallback.
- const beats = chainingActive
- ? chunkPrompts.slice(0, chunks).map((b) => (b?.trim() ? withEnvelope(b) : ''))
- : [];
- if (isGrok) {
- // Grok's image-first flow reads only these fields; width/height ride
- // along so the server maps them to the closest supported aspect ratio.
- return {
- backend: 'grok',
- prompt: composed.prompt,
- negativePrompt: composed.negativePrompt,
- grokDuration,
- width: clampImageEdge(width, VIDEO_EDGE_BOUNDS),
- height: clampImageEdge(height, VIDEO_EDGE_BOUNDS),
- mode: mode === 'image' ? 'image' : 'text',
- sourceImageFile: mode === 'image' ? (sourceImageFile || '') : '',
- sourceImage: mode === 'image' ? (sourceImageUpload || '') : '',
- };
- }
- if (remoteSubmissionFields) {
- // Text-to-video only: the wire carries no source/end frame, keyframes,
- // source clip, audio track, IC references or LoRA weights, and the page
- // blocks submission while any of those are set rather than dropping them
- // here. `mode` and `backend` are pinned to the only combination the
- // provider route accepts, so a stale mode cannot ride along and 400.
- // The peer negotiates frames/fps/canvas against its own capability
- // (negotiateVideoConstraints), so these go as requested, not pre-snapped
- // to a LOCAL model this render never touches.
- return {
- backend: 'local',
- mode: 'text',
- prompt: composed.prompt,
- negativePrompt: composed.negativePrompt,
- width: clampImageEdge(width, VIDEO_EDGE_BOUNDS),
- height: clampImageEdge(height, VIDEO_EDGE_BOUNDS),
- numFrames,
- fps,
- steps: steps || '',
- guidanceScale: guidanceScale || '',
- seed: seed || '',
- ...remoteSubmissionFields,
- };
- }
- // Append "no music, no soundtrack" only when the toggle is on AND audio
- // generation is itself active — there's no point steering audio output
- // when audio is disabled outright. Idempotent: if the user already
- // typed "no music" we avoid double-appending.
- const promptOut = withEnvelope(prompt);
- // Legacy first/last-frame fflf: the two-image picker is mutually exclusive
- // with multi-keyframe mode on the server, so its image fields only ride
- // along when keyframes aren't active.
- const legacyFflf = mode === 'fflf' && !keyframesActive;
- const localEdgeBounds = videoEdgeBoundsForModel(currentModel);
- return {
- // The page's backend toggle IS an explicit choice — send it so the
- // server's #3231 video pin ladder can't reroute a Local render to a
- // pinned grok backend behind the UI's back.
- backend: 'local',
- prompt: promptOut,
- negativePrompt: currentModel?.supportsNegativePrompt === false ? '' : composed.negativePrompt,
- modelId,
- // Clamp/floor to the runner's edge bounds so a transient 0 (field cleared
- // mid-edit) or off-grid value can't 400 the server — mirrors ImageGen's
- // submit-time clampImageEdge guard.
- width: clampImageEdge(width, localEdgeBounds),
- height: clampImageEdge(height, localEdgeBounds),
- numFrames,
- fps,
- steps: steps || '',
- guidanceScale: guidanceScale || '',
- seed: seed || '',
- tiling: currentModel?.supportsTiling === false ? 'auto' : tiling,
- // Dropped entirely for the stock conditioner so an unswapped render posts
- // exactly the body it did before this knob existed — and re-snapped to the
- // model's own list in case a restore raced the reconciliation effect.
- textEncoderId: normalizeTextEncoderForModel(textEncoderId, currentModel) === STOCK_TEXT_ENCODER_ID
- ? undefined
- : textEncoderId,
- // Dropped for Quality on the same rule as the conditioner above, so a
- // default render posts the body it did before this knob existed.
- //
- // Gated on the SAME mode/chain-filtered set the picker uses, not merely
- // on what the model declares: selecting Fast in text mode and then
- // switching to fflf (or raising Chunks with window continuity) hides the
- // picker and unlocks Steps/CFG, and posting the profile anyway would
- // persist a knob that never applied — echoed back on reload and seeded
- // into a Retry as a schedule the render never used. Exactly what the
- // sibling textEncoderId rule exists to prevent.
- speedProfileId: selectedSpeedProfile(speedProfileId, currentModel, videoChainChunkModes({
- model: currentModel, mode, chaining: chainingActive, contextFrames,
- }))?.id,
- disableAudio: effectiveDisableAudio ? 'true' : 'false',
- mode,
- imageStrength: imageStrength || '',
- // Dropped entirely on the default so an anchored render posts exactly the
- // body it did before this knob existed. The snap-back effect guarantees a
- // non-default value here is one the selected model + mode can honor.
- i2vReferenceMode: isDefaultI2vReferenceMode(i2vReferenceMode) ? '' : i2vReferenceMode,
- // ltx2-extend bypasses the last-frame i2v path: we send the source
- // video's history id directly so the server resolves it to a disk
- // path and routes through ExtendPipeline. Legacy extend (mlx_video)
- // still uses sourceImageFile populated from extractLastFrame.
- // keyframes goes as a JSON string — buildFormData would otherwise
- // stringify each {file,index} object to "[object Object]" (it appends
- // arrays element-by-element); the route's zod preprocess JSON-parses it
- // and strips any unknown keys, so sending the entries verbatim is safe.
- keyframes: keyframesActive ? JSON.stringify(keyframes) : '',
- // Video LoRAs (ltx2 only) ride as the universal parallel-array contract
- // (loraFilenames + loraScales) — the SAME shape ImageGen submits and a
- // history requeue emits — so buildFormData appends them as repeated
- // multipart keys and the route needs no bespoke shape. Only sent when the
- // model's runtime supports LoRAs (else the route 400s LORAS_REQUIRE_LTX2);
- // undefined fields are dropped by buildFormData.
- loraFilenames: (loraFamily && selectedLoras.length) ? selectedLoras.map((l) => l.filename) : undefined,
- loraScales: (loraFamily && selectedLoras.length) ? selectedLoras.map((l) => l.scale) : undefined,
- sourceImageFile: (mode === 'image' || legacyFflf
- || (mode === 'extend' && !isLtx2FamilyRuntime(currentModel?.runtime)))
- ? (sourceImageFile || '') : '',
- sourceImage: (mode === 'image' || legacyFflf) ? (sourceImageUpload || '') : '',
- lastImageFile: legacyFflf ? (lastImageFile || '') : '',
- lastImage: legacyFflf ? (lastImageUpload || '') : '',
- extendFromVideoId: (mode === 'extend' && isLtx2FamilyRuntime(currentModel?.runtime))
- ? (extendFromVideoId || '') : '',
- // Audio File goes through under the multipart field 'audioFile'. Server
- // routes it to the durable uploads dir and into the a2v helper.
- audioFile: mode === 'a2v' ? (audioFile || '') : '',
- // IC-LoRA remix: the reference clip rides as either the 'icReference'
- // multipart upload OR an icReferenceVideoIds history id — never both (the
- // route rejects that with IC_LORA_REFERENCE_CONFLICT).
- // Image-kind weights take gallery stills on their own field; the clip
- // fields stay empty for them (the route rejects mixing the two kinds with
- // IC_LORA_REFERENCE_KIND_MISMATCH).
- icReference: (icModeActive && !icImageKind) ? (icReferenceFile || '') : '',
- icReferenceVideoIds: (icModeActive && !icImageKind && !icReferenceFile) ? (icReferenceVideoId || '') : '',
- icReferenceImageFiles: icImageKind ? icReferenceImageFiles.filter(Boolean) : undefined,
- icStrength: icModeActive ? icStrength : '',
- icSkipStage2: icModeActive && icSkipStage2 ? 'true' : '',
- // Keyframes and IC references each anchor a single clip — the route
- // rejects chunks > 1 with KEYFRAMES_CHUNKS_CONFLICT /
- // IC_LORA_CHUNKS_CONFLICT, so suppress chunking for both.
- chunks: chainingActive ? chunks : '',
- // Per-chunk beats (#3695) go as a JSON string, like `keyframes` above:
- // buildFormData appends arrays as repeated keys, which would collapse a
- // one-entry list to a bare string server-side and — worse — lose the
- // POSITION of a blank middle beat. Omitted entirely when chaining is off
- // or every beat is blank, so a non-chained submit sends nothing.
- chunkPrompts: beats.some((p) => p.trim()) ? JSON.stringify(beats) : '',
- // Rides only when the request actually chains — same rule as `chunks`.
- // String()'d rather than sent raw so a deliberate 0 survives buildFormData
- // (which drops falsy values); '' is what "not sent" looks like here.
- contextFrames: chainingActive ? String(contextFrames) : '',
- };
+ // Snapshot the current validated state into a wire payload. The submit flow
+ // stays pure so all three backend contracts can be tested independently.
+ const submissionState = {
+ isGrok, grokDuration, remoteSubmissionFields,
+ prompt, negativePrompt, stylePreset,
+ width, height, mode, sourceImageFile, sourceImageUpload,
+ numFrames, fps, steps, guidanceScale, seed,
+ currentModel, modelId, tiling, textEncoderId, speedProfileId,
+ disableAudio, noMusic, imageStrength, i2vReferenceMode,
+ keyframesActive, keyframes, loraFamily, selectedLoras,
+ lastImageFile, lastImageUpload, extendFromVideoId, audioFile,
+ icModeActive, icImageKind, icReferenceFile, icReferenceVideoId,
+ icReferenceImageFiles, icStrength, icSkipStage2,
+ chainingActive, chunks, chunkPrompts, contextFrames,
};
+ const buildGeneratePayload = () => buildVideoGenSubmission(submissionState);
return {
// Backend + mode
@@ -1481,7 +1309,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: withEnvelope(prompt),
+ envelopedPrompt: envelopVideoPrompt(prompt, submissionState),
negativePrompt, setNegativePrompt,
stylePreset, setStylePreset,
remixModelFallback,
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 1574fd4fa9..4a222102a5 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -76,6 +76,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `videoFinish.js` | Finish-a-draft gate (#3696). `isReproducibleTextToVideo(record)` is true only for a single text-to-video render whose history record already carries everything a re-render needs — `renderInputsVersion` (the positive marker that its conditioning inventory is trustworthy, so legacy records degrade to not-finishable rather than reading as unconditioned), an empty `conditioning` array, a resolved seed, a real prompt, and no stitched/chained/upscaled provenance. `finishTargetForRecord(record, models)` additionally resolves the draft model's server-declared `finishModelId` against the models this install can actually run, returning the delivery model entry or `null`. Mirrors `finishTargetForModel` in `server/lib/videoFinishProfiles.js`; the pair table itself stays server-side. |
| `videoGenParams.js` | Pure VideoGen param helpers: `FRAME_OPTIONS`/`FPS_OPTIONS`/`VIDEO_EDGE_BOUNDS`/`MAX_CHUNKS`/`CHUNK_OPTIONS`/`DEFAULT_CONTEXT_FRAMES`/`CONTEXT_FRAME_OPTIONS` constants, model-aware frame/fps/resolution-grid normalization, separate mute vs prompt-audio capability checks, `supportsContextWindow(model)` (does this runtime have an extend pipeline to feed a continuation window to — display mirror of `server/lib/videoContinuity.js`, pinned by `server/lib/videoContinuity.parity.test.js`), `videoModelMemoryGb()` (model memory footprint), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v + IC-remix → ltx2 gate). Speed profiles (#4875) mirror the conditioner shape: `DEFAULT_SPEED_PROFILE_ID` (must equal `SPEED_PROFILE_DEFAULT_ID` in `server/lib/videoSpeedProfiles.js` — absence and `'quality'` are the same request), `isDefaultSpeedProfileId()` mirrors the server's absence-is-the-default rule, `speedProfilesForModel()` reads the server-decorated `speedProfiles` off the entry, `speedProfilesForMode(model, mode)` applies the SAME mode gate the server's `speedProfileDeclineReason` does (so a profile the server would decline is never offered, nor allowed to lock the dials), `normalizeSpeedProfileForModel()` snaps a selection onto what a just-switched model declares (mode-independent, so switching to fflf hides the picker without rewriting the choice), `speedProfileIdFromRecord()` reads one back out of a history entry / resumed job, `selectedSpeedProfile(id, model, mode)` resolves the profile actually driving the render — what the picker shows and what disables Steps+CFG — and `videoChainChunkModes({ model, mode, chaining, contextFrames, hasSourceImage })` derives the modes a CHAINED request’s chunks will run in (chunk 0 the request’s, chunks 1+ `extend` on a window-continuity chain or `image` on a frame hop), mirroring `generateChainedVideo`’s dispatch and `resolveContinuityStrategy`; `resolveContextFramesForDisplay()` is the absent/invalid→`DEFAULT_CONTEXT_FRAMES` half of `resolveContextFrames` that gate depends on. All pinned by `server/lib/videoSpeedProfiles.parity.test.js`. Also mirrors the IC-LoRA remix registry (`IC_LORA_MODES`/`IC_LORA_MODE_VALUES`/`isIcLoraMode()`/`icLoraSpecForMode()`/`icResolutionIssue()`) from `server/lib/icLoraWeights.js` so the form validates a reference render pre-submit — pinned by `server/lib/icLoraWeights.parity.test.js`. |
| `videoGenResolutions.js` | Shared resolution presets/default for video generation, model-specific preset/default resolvers (for native canvases such as MiniMax H3), and `snapAspectToImage()` to pick the closest-aspect preset for an I2V source. |
+| `videoGenSubmission.js` | Builds the local, Grok, and federated video-generation request bodies from validated form state, including prompt envelopes and empty-value wire sentinels. |
| `videoReferenceModes.js` | Mirror of `server/lib/videoReferenceModes.js` (parity enforced by `server/lib/videoReferenceModes.mirror.test.js`) — the i2v reference-mode contract: `I2V_REFERENCE_MODES`, `I2V_REFERENCE_MODE_OPTIONS` (label + the promise sentence `AdvancedParamsPanel` and the source-frame note print), `runtimeSupportsI2vReferenceMode` (gates which options the picker offers), `resolveI2vReferenceStrength` (the effective strength the panel displays), and `i2vReferenceModeViolation` for pre-submit feedback. |
| `videoStagePreview.js` | VideoGen main-stage preview resolver (#4588). `resolveVideoStagePreview({ generating, currentImage, width, height, result, extendSource, sourceImageFile/Url, lastImageFile/Url, keyframes })` → `{ kind: 'live'|'loop'|'still'|'result'|'empty', src, poster, label, aspectRatio }` — what the stage should show at each moment of a render, with mid-render vs idle precedence. Plus `videoStageAspectRatio()` (a NUMBER for an inline `aspect-ratio` style — a computed Tailwind `aspect-[w/h]` class never reaches the JIT build; `null` means unknown geometry, not 16:9), `videoPreviewFrameSrc()` (the runners' `currentImage` is polymorphic — raw base64 from imageGen, a served URL from loraTraining — so classify before prefixing), and `videoStageSignature()` for the hold/return guard in `components/videoGen/LiveVideoStage.jsx`. |
| `videoTilingOptions.js` | `VIDEO_TILING_OPTIONS` (the `<select>` rows) + `VIDEO_TILING_ENUM_SET` (the value-only Set). Single source consumed by `VideoGen.jsx` and the Remix URL builder in `useMediaPreviewActions`. Mirrors the server's `z.enum` in `server/routes/videoGen.js`. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index ed47b0b8f0..30804b1d37 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -55,6 +55,7 @@ export * from './slashdoCatalog.js';
export * from './videoFinish.js';
export * from './videoGenParams.js';
export * from './videoGenResolutions.js';
+export * from './videoGenSubmission.js';
export * from './videoReferenceModes.js';
export * from './videoStagePreview.js';
export * from './videoTilingOptions.js';
diff --git a/client/src/lib/videoGenSubmission.js b/client/src/lib/videoGenSubmission.js
new file mode 100644
index 0000000000..9cfeec0995
--- /dev/null
+++ b/client/src/lib/videoGenSubmission.js
@@ -0,0 +1,129 @@
+import { composeStyledPrompt } from './composeStyledPrompt';
+import { isLtx2FamilyRuntime } from './runnerFamilies';
+import { isDefaultI2vReferenceMode } from './videoReferenceModes';
+import { clampImageEdge } from './imageGenResolutions';
+import {
+ VIDEO_EDGE_BOUNDS,
+ videoEdgeBoundsForModel,
+ supportsVideoAudioControls,
+ supportsVideoAudioPromptControls,
+ normalizeTextEncoderForModel,
+ STOCK_TEXT_ENCODER_ID,
+ selectedSpeedProfile,
+ videoChainChunkModes,
+} from './videoGenParams.js';
+
+// The form owns state transitions and validation. This module owns the three
+// request contracts the video route accepts: Grok, federated, and local.
+export function envelopVideoPrompt(text, {
+ currentModel, negativePrompt, stylePreset, noMusic, disableAudio,
+}) {
+ const composed = composeStyledPrompt(text, negativePrompt, stylePreset);
+ const effectiveDisableAudio = supportsVideoAudioControls(currentModel) && disableAudio;
+ return (supportsVideoAudioPromptControls(currentModel) && noMusic && !effectiveDisableAudio && !/no music/i.test(composed.prompt))
+ ? `${composed.prompt}\n\nno music, no soundtrack`
+ : composed.prompt;
+}
+
+export function buildVideoGenSubmission({
+ isGrok, grokDuration, remoteSubmissionFields,
+ prompt, negativePrompt, stylePreset,
+ width, height, mode, sourceImageFile, sourceImageUpload,
+ numFrames, fps, steps, guidanceScale, seed,
+ currentModel, modelId, tiling, textEncoderId, speedProfileId,
+ disableAudio, noMusic, imageStrength, i2vReferenceMode,
+ keyframesActive, keyframes, loraFamily, selectedLoras,
+ lastImageFile, lastImageUpload, extendFromVideoId, audioFile,
+ icModeActive, icImageKind, icReferenceFile, icReferenceVideoId,
+ icReferenceImageFiles, icStrength, icSkipStage2,
+ chainingActive, chunks, chunkPrompts, contextFrames,
+}) {
+ const composed = composeStyledPrompt(prompt, negativePrompt, stylePreset);
+ const effectiveDisableAudio = supportsVideoAudioControls(currentModel) && disableAudio;
+ const withEnvelope = (text) => envelopVideoPrompt(text, {
+ currentModel, negativePrompt, stylePreset, noMusic, disableAudio,
+ });
+ // The backing array is deliberately not truncated as chunks change. Only
+ // slice live chunks at the wire boundary.
+ const beats = chainingActive
+ ? chunkPrompts.slice(0, chunks).map((beat) => (beat?.trim() ? withEnvelope(beat) : ''))
+ : [];
+
+ if (isGrok) {
+ return {
+ backend: 'grok',
+ prompt: composed.prompt,
+ negativePrompt: composed.negativePrompt,
+ grokDuration,
+ width: clampImageEdge(width, VIDEO_EDGE_BOUNDS),
+ height: clampImageEdge(height, VIDEO_EDGE_BOUNDS),
+ mode: mode === 'image' ? 'image' : 'text',
+ sourceImageFile: mode === 'image' ? (sourceImageFile || '') : '',
+ sourceImage: mode === 'image' ? (sourceImageUpload || '') : '',
+ };
+ }
+
+ if (remoteSubmissionFields) {
+ return {
+ backend: 'local',
+ mode: 'text',
+ prompt: composed.prompt,
+ negativePrompt: composed.negativePrompt,
+ width: clampImageEdge(width, VIDEO_EDGE_BOUNDS),
+ height: clampImageEdge(height, VIDEO_EDGE_BOUNDS),
+ numFrames,
+ fps,
+ steps: steps || '',
+ guidanceScale: guidanceScale || '',
+ seed: seed || '',
+ ...remoteSubmissionFields,
+ };
+ }
+
+ const legacyFflf = mode === 'fflf' && !keyframesActive;
+ const localEdgeBounds = videoEdgeBoundsForModel(currentModel);
+ return {
+ backend: 'local',
+ prompt: withEnvelope(prompt),
+ negativePrompt: currentModel?.supportsNegativePrompt === false ? '' : composed.negativePrompt,
+ modelId,
+ width: clampImageEdge(width, localEdgeBounds),
+ height: clampImageEdge(height, localEdgeBounds),
+ numFrames,
+ fps,
+ steps: steps || '',
+ guidanceScale: guidanceScale || '',
+ seed: seed || '',
+ tiling: currentModel?.supportsTiling === false ? 'auto' : tiling,
+ textEncoderId: normalizeTextEncoderForModel(textEncoderId, currentModel) === STOCK_TEXT_ENCODER_ID
+ ? undefined
+ : textEncoderId,
+ speedProfileId: selectedSpeedProfile(speedProfileId, currentModel, videoChainChunkModes({
+ model: currentModel, mode, chaining: chainingActive, contextFrames,
+ }))?.id,
+ disableAudio: effectiveDisableAudio ? 'true' : 'false',
+ mode,
+ imageStrength: imageStrength || '',
+ i2vReferenceMode: isDefaultI2vReferenceMode(i2vReferenceMode) ? '' : i2vReferenceMode,
+ keyframes: keyframesActive ? JSON.stringify(keyframes) : '',
+ loraFilenames: (loraFamily && selectedLoras.length) ? selectedLoras.map((lora) => lora.filename) : undefined,
+ loraScales: (loraFamily && selectedLoras.length) ? selectedLoras.map((lora) => lora.scale) : undefined,
+ sourceImageFile: (mode === 'image' || legacyFflf
+ || (mode === 'extend' && !isLtx2FamilyRuntime(currentModel?.runtime)))
+ ? (sourceImageFile || '') : '',
+ sourceImage: (mode === 'image' || legacyFflf) ? (sourceImageUpload || '') : '',
+ lastImageFile: legacyFflf ? (lastImageFile || '') : '',
+ lastImage: legacyFflf ? (lastImageUpload || '') : '',
+ extendFromVideoId: (mode === 'extend' && isLtx2FamilyRuntime(currentModel?.runtime))
+ ? (extendFromVideoId || '') : '',
+ audioFile: mode === 'a2v' ? (audioFile || '') : '',
+ icReference: (icModeActive && !icImageKind) ? (icReferenceFile || '') : '',
+ icReferenceVideoIds: (icModeActive && !icImageKind && !icReferenceFile) ? (icReferenceVideoId || '') : '',
+ icReferenceImageFiles: icImageKind ? icReferenceImageFiles.filter(Boolean) : undefined,
+ icStrength: icModeActive ? icStrength : '',
+ icSkipStage2: icModeActive && icSkipStage2 ? 'true' : '',
+ chunks: chainingActive ? chunks : '',
+ chunkPrompts: beats.some((beat) => beat.trim()) ? JSON.stringify(beats) : '',
+ contextFrames: chainingActive ? String(contextFrames) : '',
+ };
+}