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

feat(videogen): make the Reactor render form match what fast-h3 accepts

Adam Eivy8c326b6288de
diff --git a/client/src/components/videoGen/ReactorPanel.jsx b/client/src/components/videoGen/ReactorPanel.jsx
new file mode 100644
index 0000000000..c4eef621ac
--- /dev/null
+++ b/client/src/components/videoGen/ReactorPanel.jsx
@@ -0,0 +1,81 @@
+/**
+ * reactor.inc fast-h3 render controls.
+ *
+ * Presentational — every value is owned by the VideoGen page. Two of the three
+ * fields exist because fast-h3's contract is narrower than a free-text box can
+ * express:
+ *
+ * - **Continue from clip** picks a clip id off a PREVIOUS reactor render (the
+ * id is stamped on its history record) and chains this one onto it with
+ * `continue_from_clip_id`. Typing an id was the old shape, and there was no
+ * way for a user to know one; it is exclusive with a starting image, since
+ * both say "begin from this picture".
+ * - **Clip length** offers only lengths fast-h3 renders (see
+ * `lib/reactorVideoClip.js`) — the accepted range neither starts nor ends on
+ * a round number, so a number box mostly offered a way to type a rejected one.
+ */
+import { REACTOR_CLIP_LENGTHS, reactorClipLengthLabel } from '../../lib/reactorVideoClip.js';
+import { FormField } from '../ui/FormField';
+
+export default function ReactorPanel({
+ clipId,
+ onClipIdChange,
+ continuableClips,
+ imageModeActive,
+ seconds,
+ onSecondsChange,
+ seed,
+ onSeedChange,
+}) {
+ const fieldClass = 'w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50';
+ const continuationBlocked = imageModeActive || continuableClips.length === 0;
+ return (
+ <div className="grid grid-cols-2 gap-3">
+ <FormField label="Continue from clip" labelClassName="block text-xs font-medium text-gray-400 mb-1">
+ <select
+ value={clipId}
+ disabled={continuationBlocked}
+ onChange={(e) => onClipIdChange(e.target.value)}
+ className={fieldClass}
+ >
+ <option value="">
+ {imageModeActive
+ ? 'Not available with a starting image'
+ : continuableClips.length === 0
+ ? 'No Reactor clips rendered yet'
+ : 'Start a fresh shot'}
+ </option>
+ {continuableClips.map((clip) => (
+ <option key={clip.clipId} value={clip.clipId}>{clip.label}</option>
+ ))}
+ </select>
+ </FormField>
+ <FormField label="Clip length" labelClassName="block text-xs font-medium text-gray-400 mb-1">
+ <select
+ value={seconds}
+ onChange={(e) => onSecondsChange(Number(e.target.value))}
+ className={fieldClass}
+ >
+ {REACTOR_CLIP_LENGTHS.map((length) => (
+ <option key={length} value={length}>{reactorClipLengthLabel(length)}</option>
+ ))}
+ </select>
+ </FormField>
+ <FormField label="Seed" labelClassName="block text-xs font-medium text-gray-400 mb-1">
+ <input
+ type="number"
+ min={0}
+ value={seed}
+ onChange={(e) => onSeedChange(e.target.value)}
+ placeholder="random"
+ className={fieldClass}
+ />
+ </FormField>
+ <p className="col-span-2 text-[11px] text-gray-500 leading-snug">
+ Renders on reactor.inc&apos;s fast-h3 API — near-realtime, and every finished clip can be
+ continued frame-accurately by picking it above. Reactor decides how long it keeps a clip
+ continuable, so an older one may come back rejected. Counts against your reactor.inc balance.
+ </p>
+ </div>
+ );
+}
diff --git a/client/src/hooks/useVideoGenFieldState.js b/client/src/hooks/useVideoGenFieldState.js
index a22048c3c0..8ab79893b9 100644
--- a/client/src/hooks/useVideoGenFieldState.js
+++ b/client/src/hooks/useVideoGenFieldState.js
@@ -1,5 +1,6 @@
import { useRef, useState } from 'react';
import { GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokVideoClip.js';
+import { REACTOR_DEFAULT_CLIP_LENGTH } from '../lib/reactorVideoClip.js';
import { DEFAULT_I2V_REFERENCE_MODE } from '../lib/videoReferenceModes.js';
import {
DEFAULT_CONTEXT_FRAMES,
@@ -24,7 +25,7 @@ export function useVideoGenFieldState({
const [falDuration, setFalDuration] = useState('');
const [falModelId, setFalModelId] = useState('');
const [reactorClipId, setReactorClipId] = useState('');
- const [reactorSeconds, setReactorSeconds] = useState('');
+ const [reactorSeconds, setReactorSeconds] = useState(REACTOR_DEFAULT_CLIP_LENGTH);
const [reactorSeed, setReactorSeed] = useState('');
const [mode, setMode] = useState(incomingAudioFilename ? 'a2v' : (incomingSourceImage ? 'image' : 'text'));
const [prompt, setPrompt] = useState(incomingPrompt || '');
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 80f5ba4e6d..1f1b2a23fe 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -52,6 +52,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `fableLoomReadiness.js` | Ordered FableLoom readiness plus the twelve-stage producer workflow spanning foundation, challenges, outlines, editorial, continuity, media, and final hosting. |
| `glbFailure.js` | Turns a 3D asset failure into an actionable sentence. `glbFailureHint(error)` matches the message against a shared table (an HTML body reaching the glTF parser, a WebGL context failure, a 404) and returns `null` when nothing recognizes it — so a caller can tell "we know the cause" from "we don't" and fall back to the raw text. `glbErrorText(error)` reads a message off whatever shape was thrown. Shared because the CoS avatars load remote GLBs too: every caught error there used to be reported as "this display has no WebGL", sending the user to change an unrelated setting (#4688). Consumed by `media/GlbViewer.jsx` and `cos/CoSCanvasGuard.jsx`. |
| `grokVideoClip.js` | Mirror of `server/lib/grokVideoClip.js` — `GROK_VIDEO_DURATIONS` (`[6, 10]`) + `GROK_VIDEO_DEFAULT_DURATION`, the clip lengths grok's `image_to_video` actually delivers. |
+| `reactorVideoClip.js` | Mirror of `server/lib/reactorVideoClip.js` — `REACTOR_MAX_PROMPT_LENGTH` (800, counted in the VideoGen prompt field before submit), `REACTOR_MIN_CLIP_SECONDS` / `REACTOR_MAX_CLIP_SECONDS`, and the picker list `REACTOR_CLIP_LENGTHS` + `REACTOR_DEFAULT_CLIP_LENGTH` + `reactorClipLengthLabel()`. |
| `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). |
| `reviewerModels.js` | `reviewerModelsFromDefaults` / `reviewerModelsToDefaults` / `reviewerEffortsFromDefaults` / `reviewerEffortsToDefaults` — adapt the Code Review Defaults' per-reviewer SCALARS (`codexModel`, `ollamaModel`, `claudeEffort`, …) to and from the token-keyed maps `ReviewerPicker`'s Model and Effort columns take. Mirrors `reviewerModelsFromDefaults` / `reviewerEffortsFromDefaults` in `server/lib/reviewerConfig.js`. |
| `reviewerPins.js` | Client mirror of the whole reviewer vocabulary — the roster (`REVIEWER_VALUES`), `REVIEWER_ALIASES`, `DEFAULT_REVIEWER(S)`, `normalizeReviewers`, the review-username pattern/cap (`MAX_REVIEW_USERNAMES` / `cleanReviewUsername` / `normalizeReviewUsernames`), `MAX_REVIEWER_MAX_ROUNDS`, `REVIEW_STOP_MODES` / `DEFAULT_REVIEW_STOP_MODE`, plus the per-reviewer pin vocabularies (`MODEL_SELECTABLE_REVIEWERS` / `EFFORT_SELECTABLE_REVIEWERS` / `REVIEWER_EFFORT_LEVELS` / `reviewerEffortLevels` / `normalizeReviewerSlug` / `sanitizeReviewerModelInput`) and their bounds. Dependency-free on purpose: the server suite imports it to pin the mirror against `server/lib/reviewerConfig.js`, so it must not reach for a client-only package. Re-exported by `components/cos/constants.js`. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 7b678e7b6a..25fd076a53 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -35,6 +35,7 @@ export * from './falVideoHandoff.js';
export * from './fableLoomReadiness.js';
export * from './glbFailure.js';
export * from './grokVideoClip.js';
+export * from './reactorVideoClip.js';
export * from './imageCleaners.js';
export * from './imageGenBackends.js';
// Namespace export: imageGenBackends re-exports every imageGenModes symbol
diff --git a/client/src/lib/reactorVideoClip.js b/client/src/lib/reactorVideoClip.js
new file mode 100644
index 0000000000..50ee664ebc
--- /dev/null
+++ b/client/src/lib/reactorVideoClip.js
@@ -0,0 +1,36 @@
+// Client mirror of `server/lib/reactorVideoClip.js` — the reactor.inc fast-h3
+// clip contract the VideoGen form has to respect BEFORE it submits: the 800
+// character prompt cap (fast-h3 rejects a longer prompt outright, so the form
+// counts characters rather than letting the render 400) and the clip lengths
+// its picker offers. Enforced by the "client mirror" suite in
+// `server/lib/reactorVideoClip.test.js`: if this drifts from the server file,
+// that test fails. Update the SERVER file first, then this one.
+
+/** Longest prompt fast-h3 accepts, in characters. */
+export const REACTOR_MAX_PROMPT_LENGTH = 800;
+
+/** Shortest clip fast-h3 accepts (124 frames at 24fps). */
+export const REACTOR_MIN_CLIP_SECONDS = 5.167;
+
+/** Longest clip fast-h3 accepts (345 frames at 24fps). */
+export const REACTOR_MAX_CLIP_SECONDS = 14.375;
+
+/**
+ * Clip lengths the picker offers, ascending — the two exact endpoints plus
+ * every whole second between them. fast-h3 accepts a continuous value in that
+ * range, so a free-text seconds box mostly offered a way to type one it
+ * refuses; whole seconds are frame-aligned at 24fps.
+ */
+export const REACTOR_CLIP_LENGTHS = Object.freeze([
+ REACTOR_MIN_CLIP_SECONDS, 6, 7, 8, 9, 10, 11, 12, 13, 14, REACTOR_MAX_CLIP_SECONDS,
+]);
+
+/** Fallback when no clip length is chosen. */
+export const REACTOR_DEFAULT_CLIP_LENGTH = 6;
+
+/** Human label for one picker entry — the endpoints are odd enough to need naming. */
+export const reactorClipLengthLabel = (seconds) => (
+ seconds === REACTOR_MIN_CLIP_SECONDS ? `${seconds} seconds (min)`
+ : seconds === REACTOR_MAX_CLIP_SECONDS ? `${seconds} seconds (max)`
+ : `${seconds} seconds`
+);
diff --git a/client/src/lib/videoGenSubmission.js b/client/src/lib/videoGenSubmission.js
index 50f405eb03..d26ab2546c 100644
--- a/client/src/lib/videoGenSubmission.js
+++ b/client/src/lib/videoGenSubmission.js
@@ -23,6 +23,16 @@ const stylePresetsFor = (selectedUniverse, stylePreset) => [
stylePreset,
].filter(Boolean);
+/**
+ * The prompt the cloud lanes actually submit: the user's text with any universe
+ * / style-preset prompt folded in front of it. Exported because reactor.inc caps
+ * the SUBMITTED prompt at 800 characters — the form's counter has to measure the
+ * same string this module builds, not the raw textarea, or a preset silently
+ * pushes a "safe" prompt over the cap.
+ */
+export const styledVideoPrompt = (text, { negativePrompt, stylePreset, selectedUniverse } = {}) =>
+ composeStyledPrompt(text, negativePrompt, stylePresetsFor(selectedUniverse, stylePreset)).prompt;
+
export function envelopVideoPrompt(text, {
currentModel, negativePrompt, stylePreset, selectedUniverse, noMusic, disableAudio,
}) {
@@ -77,7 +87,8 @@ export function buildVideoGenSubmission({
return {
backend: 'fal',
prompt: composed.prompt,
- negativePrompt: composed.negativePrompt,
+ // No negativePrompt: fal's buildRequestBody never sends one, so posting it
+ // only stamped a promise on the history record that nothing honored.
falDuration,
falModelId: falModelId || undefined,
width: clampImageEdge(width, VIDEO_EDGE_BOUNDS),
@@ -92,8 +103,14 @@ export function buildVideoGenSubmission({
return {
backend: 'reactor',
prompt: composed.prompt,
- negativePrompt: composed.negativePrompt,
- reactorClipId: reactorClipId || undefined,
+ // No negativePrompt: fast-h3's enqueue command has no such field (same as
+ // the fal lane above).
+ // The clip id chains this render onto a previous reactor clip via
+ // continue_from_clip_id; the picker only offers ids off completed reactor
+ // history records. Dropped in Image mode because continuation and a
+ // starting frame are exclusive — the service rejects a request carrying
+ // both, and the picker is already disabled there.
+ reactorClipId: (mode === 'image' ? '' : reactorClipId) || undefined,
reactorSeconds: reactorSeconds || undefined,
// Unlike falDuration/falModelId, a seed of 0 is a real, meaningful
// value — `|| undefined` would silently drop it (the reactor route
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 6afc1114d7..5d6cc64c8b 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -97,6 +97,10 @@ import { loomEpisodeToDraftScenes } from '../lib/episodeSceneImport.js';
import LoraPicker from '../components/imageGen/LoraPicker';
import { VIDEO_RESOLUTIONS, resolutionOptionsForModel } from '../lib/videoGenResolutions';
import { GROK_VIDEO_DURATIONS } from '../lib/grokVideoClip.js';
+import { REACTOR_MAX_PROMPT_LENGTH } from '../lib/reactorVideoClip.js';
+import { styledVideoPrompt } from '../lib/videoGenSubmission.js';
+import ReactorPanel from '../components/videoGen/ReactorPanel';
+import { timeAgo } from '../utils/formatters';
import ResolutionField from '../components/media/ResolutionField';
import { VIDEO_EDGE_BOUNDS, videoEdgeBoundsForModel, IC_LORA_MODES } from '../lib/videoGenParams.js';
import { finishTargetForRecord, isDeliveryVideoModel } from '../lib/videoFinish.js';
@@ -994,10 +998,43 @@ export default function VideoGen() {
const modelFieldVisible = !modelsLoading || modelContextLoading;
const notConnected = !!status && status.connected === false && !needsByovProbe;
+ // reactor.inc rejects a prompt over 800 characters outright, and the limit
+ // applies to what PortOS SUBMITS — style presets prefix the user's text, so
+ // the counter measures the same string buildVideoGenSubmission builds rather
+ // than the textarea. Gating Generate on it turns a post-click 400 into a
+ // number the user can watch while writing.
+ const submittedPromptLength = useMemo(
+ () => (isReactor
+ ? styledVideoPrompt(prompt, { negativePrompt, stylePreset, selectedUniverse }).length
+ : prompt.length),
+ [isReactor, prompt, negativePrompt, stylePreset, selectedUniverse],
+ );
+ const promptOverLimit = isReactor && submittedPromptLength > REACTOR_MAX_PROMPT_LENGTH;
+
+ // Only grok folds a negative prompt into its request (as an "Avoid:" line);
+ // fal's queue body and reactor's enqueue command have no such field, and a
+ // CFG-distilled local model ignores one. Hide the box rather than showing a
+ // dead field that quietly does nothing.
+ // A federated render is the peer's model to judge, so the local selection's
+ // gate must not hide a field that lane does submit.
+ const negativePromptSupported = isGrok || remoteTarget.isRemote
+ || (!isFal && !isReactor && currentModel?.supportsNegativePrompt !== false);
+
+ // Every completed reactor render stamps its fast-h3 clip id on the history
+ // record; those ids are the only thing continue_from_clip_id can address, so
+ // the picker is built from them rather than asking the user to know one.
+ const reactorContinuableClips = useMemo(() => visibleHistory
+ .filter((v) => v.clipId && String(v.modelId || '').startsWith('reactor:'))
+ .slice(0, 50)
+ .map((v) => ({
+ clipId: v.clipId,
+ label: `${(v.prompt || v.filename || v.clipId).slice(0, 60)} · ${timeAgo(v.createdAt, 'unknown')}`,
+ })), [visibleHistory]);
+
// A federated render answers to the PEER’s readiness, not to this machine’s
// runtime gates — none of the local probes below describe the hardware it
// will actually run on.
- const canEnqueue = prompt.trim() && !remixHandoffPending && (remoteTarget.isRemote
+ const canEnqueue = prompt.trim() && !remixHandoffPending && !promptOverLimit && (remoteTarget.isRemote
? remoteBlocked === null
: (isGrok || isFal || isReactor || (!notConnected && !extendModeBlocked
&& !a2vModeBlocked && !icLoraModeBlocked && !byovGateBlocked
@@ -1274,7 +1311,7 @@ export default function VideoGen() {
value={stylePreset?.id || ''}
onChange={setStylePreset}
/>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ <div className={`grid grid-cols-1 gap-3 ${negativePromptSupported ? 'md:grid-cols-2' : ''}`}>
<FormField label="Prompt" labelClassName="block text-xs font-medium text-gray-400 mb-1">
<AutoSizeTextarea
value={prompt}
@@ -1283,19 +1320,38 @@ export default function VideoGen() {
className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 min-h-[80px]"
placeholder="Describe the video you want to generate..."
/>
+ {/* The count is the SUBMITTED length, so a style preset that
+ pushes a short-looking prompt past reactor's cap is visible
+ here instead of surfacing as a 400 after Generate. */}
+ <p className={`mt-1 text-[11px] leading-snug ${promptOverLimit ? 'text-port-error' : 'text-gray-500'}`}>
+ {isReactor
+ ? `${submittedPromptLength} / ${REACTOR_MAX_PROMPT_LENGTH} characters`
+ : `${submittedPromptLength} characters`}
+ </p>
+ {/* Only crossing the cap is worth announcing; the count itself
+ changes on every keystroke and would be pure noise. */}
+ {promptOverLimit && (
+ <p className="mt-1 text-[11px] text-port-error leading-snug" role="status">
+ Reactor will reject this — shorten the prompt. Style presets count toward the limit.
+ </p>
+ )}
+ {!negativePromptSupported && !isFal && !isReactor && (
+ <p className="mt-1 text-[11px] text-gray-500 leading-snug">
+ This model does not use a negative prompt.
+ </p>
+ )}
</FormField>
- <FormField label="Negative Prompt" labelClassName="block text-xs font-medium text-gray-400 mb-1">
- <AutoSizeTextarea
- value={negativePrompt}
- onChange={(e) => setNegativePrompt(e.target.value)}
- disabled={!isGrok && !isFal && !isReactor && currentModel?.supportsNegativePrompt === false}
- rows={3}
- className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 min-h-[80px]"
- placeholder={!isGrok && !isFal && !isReactor && currentModel?.supportsNegativePrompt === false
- ? 'This CFG-distilled model does not use a negative prompt.'
- : 'What to avoid...'}
- />
- </FormField>
+ {negativePromptSupported && (
+ <FormField label="Negative Prompt" labelClassName="block text-xs font-medium text-gray-400 mb-1">
+ <AutoSizeTextarea
+ value={negativePrompt}
+ onChange={(e) => setNegativePrompt(e.target.value)}
+ rows={3}
+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 min-h-[80px]"
+ placeholder="What to avoid..."
+ />
+ </FormField>
+ )}
</div>
{/* Keep Enhance live while a render is in flight so the next clip
@@ -1305,8 +1361,8 @@ export default function VideoGen() {
kind="video"
prompt={prompt}
setPrompt={setPrompt}
- negativePrompt={negativePrompt}
- setNegativePrompt={setNegativePrompt}
+ negativePrompt={negativePromptSupported ? negativePrompt : ''}
+ setNegativePrompt={negativePromptSupported ? setNegativePrompt : undefined}
renderConfig={{ stylePreset: stylePreset?.id, mode, model: modelId }}
/>
@@ -1504,41 +1560,16 @@ export default function VideoGen() {
</p>
</div>
) : isReactor ? (
- <div className="grid grid-cols-2 gap-3">
- <FormField label="Continue from clip" labelClassName="block text-xs font-medium text-gray-400 mb-1">
- <input
- type="text"
- value={reactorClipId}
- onChange={(e) => setReactorClipId(e.target.value)}
- placeholder="clip id (optional)"
- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
- />
- </FormField>
- <FormField label="Clip length (sec)" labelClassName="block text-xs font-medium text-gray-400 mb-1">
- <input
- type="number"
- min={1}
- max={60}
- value={reactorSeconds}
- onChange={(e) => setReactorSeconds(e.target.value)}
- placeholder="model default"
- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
- />
- </FormField>
- <FormField label="Seed" labelClassName="block text-xs font-medium text-gray-400 mb-1">
- <input
- type="number"
- min={0}
- value={reactorSeed}
- onChange={(e) => setReactorSeed(e.target.value)}
- placeholder="random"
- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
- />
- </FormField>
- <p className="col-span-2 text-[11px] text-gray-500 leading-snug">
- Renders on reactor.inc's fast-h3 API — near-realtime with native frame-accurate chaining via "Continue from clip". Counts against your reactor.inc balance.
- </p>
- </div>
+ <ReactorPanel
+ clipId={reactorClipId}
+ onClipIdChange={setReactorClipId}
+ continuableClips={reactorContinuableClips}
+ imageModeActive={mode === 'image'}
+ seconds={reactorSeconds}
+ onSecondsChange={setReactorSeconds}
+ seed={reactorSeed}
+ onSeedChange={setReactorSeed}
+ />
) : (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
{/* The peer advertises its own models; the local list would name
@@ -1819,7 +1850,7 @@ export default function VideoGen() {
kindDefault="both"
applyKind="video"
setPrompt={setPrompt}
- setNegativePrompt={setNegativePrompt}
+ setNegativePrompt={negativePromptSupported ? setNegativePrompt : undefined}
alwaysOpen
/>
</div>
diff --git a/client/src/pages/VideoGen.reactor.test.jsx b/client/src/pages/VideoGen.reactor.test.jsx
new file mode 100644
index 0000000000..89fc73d1b0
--- /dev/null
+++ b/client/src/pages/VideoGen.reactor.test.jsx
@@ -0,0 +1,140 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import { fireEvent, screen, waitFor } from '@testing-library/react';
+
+import {
+ loadVideoGenPage,
+ renderVideoGenPage,
+ resetVideoGenMockState,
+ state,
+ videoGenModel,
+ videoGenModelContext,
+ videoGenStatus,
+} from '../test/videoGenPageMocks.jsx';
+import {
+ REACTOR_MAX_PROMPT_LENGTH, REACTOR_MIN_CLIP_SECONDS, REACTOR_MAX_CLIP_SECONDS,
+} from '../lib/reactorVideoClip.js';
+
+// A local model that DOES take a negative prompt, so "the box is gone" can only
+// be explained by the reactor lane rather than by the model's own gate.
+const MODEL = videoGenModel('local-model', { supportsNegativePrompt: true });
+
+const REACTOR_RENDER = {
+ id: 'video-1',
+ prompt: 'A camera holds on a quiet gate',
+ filename: 'video-1.mp4',
+ modelId: 'reactor:fast-h3',
+ clipId: 'clip-example',
+ createdAt: new Date().toISOString(),
+};
+const LOCAL_RENDER = {
+ id: 'video-2',
+ prompt: 'A local render with no reactor clip',
+ filename: 'video-2.mp4',
+ modelId: 'local-model',
+ createdAt: new Date().toISOString(),
+};
+
+await loadVideoGenPage();
+
+const selectReactor = async () => {
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Reactor.inc' })).toBeInTheDocument());
+ fireEvent.click(screen.getByRole('button', { name: 'Reactor.inc' }));
+ await screen.findByLabelText('Clip length');
+};
+
+const submit = async () => {
+ await waitFor(() => expect(screen.getByRole('button', { name: /Add to queue/ })).toBeEnabled());
+ fireEvent.click(screen.getByRole('button', { name: /Add to queue/ }));
+ await waitFor(() => expect(state.generateVideo).toHaveBeenCalled());
+ return state.generateVideo.mock.calls[0][0];
+};
+
+describe('VideoGen reactor.inc lane', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ resetVideoGenMockState();
+ state.getVideoGenModelContext.mockResolvedValue(videoGenModelContext([MODEL]));
+ state.getVideoGenStatus.mockResolvedValue(videoGenStatus([MODEL], { reactorEnabled: true }));
+ state.modelStatuses = { [MODEL.id]: { id: MODEL.id, repo: MODEL.repo, cached: true, sizeBytes: 100 } };
+ state.listVideoHistory.mockResolvedValue([REACTOR_RENDER, LOCAL_RENDER]);
+ state.generateVideo.mockResolvedValue({ jobId: 'job-1' });
+ state.attach.mockReturnValue(new Promise(() => {}));
+ });
+
+ // The 800-character cap used to surface only as a 400 after Generate, naming
+ // a number the form never showed.
+ it('counts the prompt against the cap and refuses to submit an over-long one', async () => {
+ await renderVideoGenPage();
+ await selectReactor();
+
+ const promptField = screen.getByLabelText('Prompt');
+ fireEvent.change(promptField, { target: { value: 'a fox watches the rain' } });
+ expect(screen.getByText(`22 / ${REACTOR_MAX_PROMPT_LENGTH} characters`)).toBeInTheDocument();
+
+ fireEvent.change(promptField, { target: { value: 'x'.repeat(REACTOR_MAX_PROMPT_LENGTH + 1) } });
+ await waitFor(() => expect(screen.getByText(/Reactor will reject this/)).toBeInTheDocument());
+ expect(screen.getByRole('button', { name: /Add to queue/ })).toBeDisabled();
+
+ fireEvent.change(promptField, { target: { value: 'x'.repeat(REACTOR_MAX_PROMPT_LENGTH) } });
+ await waitFor(() => expect(screen.getByRole('button', { name: /Add to queue/ })).toBeEnabled());
+ });
+
+ // fast-h3's enqueue command has no negative-prompt field, so the box only
+ // ever collected text nothing would submit.
+ it('drops the negative prompt the backend has no field for', async () => {
+ await renderVideoGenPage();
+ expect(await screen.findByLabelText('Negative Prompt')).toBeInTheDocument();
+
+ await selectReactor();
+ expect(screen.queryByLabelText('Negative Prompt')).toBeNull();
+
+ fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'a fox watches the rain' } });
+ expect(await submit()).not.toHaveProperty('negativePrompt');
+ });
+
+ // The accepted range neither starts nor ends on a round number, so the old
+ // free-text seconds box mostly offered a way to type a rejected value.
+ it('offers clip lengths fast-h3 accepts instead of a free-text duration', async () => {
+ await renderVideoGenPage();
+ await selectReactor();
+
+ const lengths = screen.getByLabelText('Clip length');
+ expect(lengths.tagName).toBe('SELECT');
+ const offered = [...lengths.options].map((option) => Number(option.value));
+ expect(offered[0]).toBe(REACTOR_MIN_CLIP_SECONDS);
+ expect(offered[offered.length - 1]).toBe(REACTOR_MAX_CLIP_SECONDS);
+ expect(Number(lengths.value)).toBe(6);
+
+ fireEvent.change(lengths, { target: { value: String(REACTOR_MAX_CLIP_SECONDS) } });
+ fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'a fox watches the rain' } });
+ expect((await submit()).reactorSeconds).toBe(REACTOR_MAX_CLIP_SECONDS);
+ });
+
+ // The clip id is stamped on every finished reactor render precisely so a
+ // later one can chain off it — a text box asked the user to know an id they
+ // are never shown.
+ it('picks a continuation from the clip ids previous reactor renders stored', async () => {
+ await renderVideoGenPage();
+ await selectReactor();
+
+ const picker = screen.getByLabelText('Continue from clip');
+ const offered = [...picker.options].map((option) => option.value);
+ expect(offered).toEqual(['', REACTOR_RENDER.clipId]);
+ expect(screen.getByRole('option', { name: /A camera holds on a quiet gate/ })).toBeInTheDocument();
+
+ fireEvent.change(picker, { target: { value: REACTOR_RENDER.clipId } });
+ fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'the gate swings open' } });
+ expect((await submit()).reactorClipId).toBe(REACTOR_RENDER.clipId);
+ });
+
+ it('offers no continuation until a reactor render has stored a clip id', async () => {
+ state.listVideoHistory.mockResolvedValue([LOCAL_RENDER]);
+ await renderVideoGenPage();
+ await selectReactor();
+
+ const picker = screen.getByLabelText('Continue from clip');
+ expect(picker).toBeDisabled();
+ expect(picker.options).toHaveLength(1);
+ expect(picker.options[0].textContent).toMatch(/No Reactor clips rendered yet/);
+ });
+});
diff --git a/docs/features/fableloom.md b/docs/features/fableloom.md
index 7adb9c36ef..0f76ee3650 100644
--- a/docs/features/fableloom.md
+++ b/docs/features/fableloom.md
@@ -382,5 +382,13 @@ Keep preview batches small before authorizing an episode render. Each request
uses its reference image and a prompt of at most 800 characters; longer prompts
are rejected rather than silently losing dialogue. Reactor accepts 5.167–14.375
seconds and snaps durations to its frame grid. Local interactive voice profiles
-are independent of Reactor's generated audio. Cross-request clip chaining is not
-supported because Reactor clip IDs belong to the session that generated them.
+are independent of Reactor's generated audio.
+
+Clip chaining is best effort. Every finished Reactor render stores the clip ID
+Reactor assigned it, and a later render can pass that ID back as
+`continue_from_clip_id` — the Video Gen form offers the stored IDs as a picker,
+and continuous-video episodes chain "continue" cuts the same way. Each render
+opens its own session, so whether an earlier clip is still addressable is
+Reactor's decision: a rejected ID fails that render with a message naming the
+continuation (episodes re-establish the shot fresh instead). A continuation and
+a starting image are mutually exclusive.
diff --git a/scripts/reactor-render.py b/scripts/reactor-render.py
index 576ad0d48d..62aed08de6 100644
--- a/scripts/reactor-render.py
+++ b/scripts/reactor-render.py
@@ -31,6 +31,9 @@ async def render(params):
if not params.get("jwt") or not params.get("outputPath"):
raise ValueError("Session token and output path are required")
source = params.get("sourceImagePath")
+ continue_from = (params.get("continueFromClipId") or "").strip()
+ if source and continue_from:
+ raise ValueError("A clip continuation and a starting frame are mutually exclusive")
if source and not Path(source).is_file():
raise ValueError("Starting frame is missing")
output = Path(params["outputPath"])
@@ -85,6 +88,12 @@ async def render(params):
request = {"prompt": prompt, "seconds": seconds}
if params.get("seed") is not None:
request["seed"] = int(params["seed"])
+ if continue_from:
+ # Frame-accurate continuation of a clip fast-h3 already
+ # rendered (its id is stamped on the PortOS history record).
+ # Reactor owns clip retention, so an id it no longer holds
+ # fails here in "enqueue" rather than rendering a fresh shot.
+ request["continue_from_clip_id"] = continue_from
if source:
phase = "uploading"
request["starting_frame"] = await reactor.upload_file(source)
diff --git a/server/lib/README.md b/server/lib/README.md
index 5451571ff8..48c0f93b37 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -212,6 +212,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `cursor.js` | Cursor Agent (`cursor-agent`) provider helpers — the `CURSOR_COMMAND` binary constant, the `isCursorCommand` predicate, and the `ensureCursorHeadlessArgs` (`--print --force`, folding any pinned reasoning effort into `--model`) / `ensureCursorTuiArgs` (`--force`) argv builders. `--force` is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its `auto` router is a real model id passed straight to `--model`. |
| `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). |
| `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. |
+| `reactorVideoClip.js` | The reactor.inc `fast-h3` clip contract, dependency-free so the route schema, the FableLoom prompt compiler and the VideoGen picker all read one copy — `REACTOR_MAX_PROMPT_LENGTH` (800; the API rejects a longer prompt rather than truncating it), `REACTOR_MIN_CLIP_SECONDS` / `REACTOR_MAX_CLIP_SECONDS` (5.167–14.375, i.e. 124–345 frames at the `REACTOR_CLIP_FPS` 24 it delivers), `REACTOR_MAX_CLIP_ID_LENGTH`, and the picker list `REACTOR_CLIP_LENGTHS` + `REACTOR_DEFAULT_CLIP_LENGTH` + `reactorClipLengthLabel()` (the two exact endpoints plus every whole second between them, since the accepted range is continuous but starts and ends off a round number). Mirrored to `client/src/lib/reactorVideoClip.js`, parity pinned by `reactorVideoClip.test.js`. |
| `kimi.js` | Moonshot AI Kimi Code (`kimi`) provider helpers — id constants (`KIMI_CLI_ID`/`KIMI_TUI_ID`), `isKimiCommand`/`isKimiCliProvider`/`isKimiTuiProvider` predicates, `ensureKimiHeadlessArgs` (model flag only — non-interactive mode is implicit in `--prompt`, and kimi has no `--print`/`--afk` and refuses approval flags alongside `--prompt`) / `ensureKimiTuiArgs` (`--yolo`) argv builders (model selection uses the `KIMI_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Grok/Antigravity), and `prepareKimiPrompt` (delivers the prompt as the `--prompt <value>` argv, not stdin). |
| `runners.js` | Image-runner family constants (`RUNNER_FAMILIES`, `loraCompatKey`), video LoRA families, MiniMax H3 runtime predicates, and the shared `AUDIO_TO_VIDEO_RUNTIMES` / `isAudioToVideoRuntime` capability gate (LTX plus H3 Ref2VA). Mirrored to `client/src/lib/runnerFamilies.js`. |
| `codexAccount.js` | The ChatGPT-subscription half of the Codex providers (#5589), pure. The fixed `codex app-server` invocation, the `account/*` method + notification names, `CODEX_ACCOUNT_STATUS` (`runtime-missing` / `unknown` / `signed-out` / `login-pending` / `ready` / `quota-exhausted` / `reauth-required`) and `CODEX_ERROR_CODES`, `isCodexSubscriptionProvider` (keyed on the `codex` COMMAND, so a renamed clone still resolves), the `normalizeCodexAccount` / `normalizeCodexRateLimits` / `normalizeCodexLoginStart` payload normalizers, `redactCodexPayload` (every log/error/response path runs through it, so "PortOS never writes down a Codex token" is one function rather than a rule per call site), and `deriveCodexAccountStatus`. Sentinels are load-bearing: `runtimeInstalled: null` = NOT PROBED, `accountFetched: false` ≠ signed out, `rateLimits: null` (failed fetch) ≠ a fetched window with nothing to report. The process half is `services/codexAppServer.js`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 0cc386d9d2..205403b73e 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -144,6 +144,7 @@ export * from './contextBudget.js';
export * from './cursor.js';
export * from './grok.js';
export * from './grokVideoClip.js';
+export * from './reactorVideoClip.js';
export * from './heavyJobClaim.js';
export * from './hfErrors.js';
export * from './hfCache.js';
diff --git a/server/lib/reactorVideoClip.js b/server/lib/reactorVideoClip.js
new file mode 100644
index 0000000000..073e13e57d
--- /dev/null
+++ b/server/lib/reactorVideoClip.js
@@ -0,0 +1,53 @@
+/**
+ * The reactor.inc `fast-h3` clip contract: what one enqueued clip may ask for.
+ *
+ * fast-h3 renders 24fps clips and its `enqueue` command accepts a CONTINUOUS
+ * `seconds` value bounded to 5.167–14.375 (124–345 frames at 24fps — the same
+ * bounds `scripts/reactor-render.py` re-checks before it opens a session). The
+ * prompt is capped at 800 characters; a longer one is rejected by the API, not
+ * truncated, so PortOS has to stop it at the form.
+ *
+ * Its own dependency-free module rather than living inside
+ * `services/videoGen/reactor.js` for the `grokVideoClip.js` reason: the route
+ * schema, the FableLoom prompt compiler and the VideoGen picker all need these
+ * numbers, and hand-copied literals in a schema are how a schema and its
+ * service drift apart — `routes/videoGen.js` already accepted 1–60 seconds for
+ * a backend that rejects everything outside 5.167–14.375.
+ *
+ * `REACTOR_CLIP_LENGTHS` is a PICKER list, not an API constraint: because the
+ * accepted range is continuous but does not start or end on a round number, a
+ * free-text seconds box mostly offers the user a way to type a value the API
+ * refuses. The list is the two exact endpoints plus every whole second between
+ * them — whole seconds are frame-aligned at 24fps, so each entry is a real
+ * frame count.
+ */
+
+/** Longest prompt fast-h3 accepts, in characters. */
+export const REACTOR_MAX_PROMPT_LENGTH = 800;
+
+/** Frame rate fast-h3 delivers; the seconds bounds below are frame counts over it. */
+export const REACTOR_CLIP_FPS = 24;
+
+/** Shortest clip fast-h3 accepts (124 frames). */
+export const REACTOR_MIN_CLIP_SECONDS = 5.167;
+
+/** Longest clip fast-h3 accepts (345 frames). */
+export const REACTOR_MAX_CLIP_SECONDS = 14.375;
+
+/** Clip lengths the VideoGen picker offers, ascending. See the module note. */
+export const REACTOR_CLIP_LENGTHS = Object.freeze([
+ REACTOR_MIN_CLIP_SECONDS, 6, 7, 8, 9, 10, 11, 12, 13, 14, REACTOR_MAX_CLIP_SECONDS,
+]);
+
+/** Fallback when a caller omits a clip length. */
+export const REACTOR_DEFAULT_CLIP_LENGTH = 6;
+
+/** Longest `continue_from_clip_id` PortOS will forward, in characters. */
+export const REACTOR_MAX_CLIP_ID_LENGTH = 200;
+
+/** Human label for one picker entry — the endpoints are odd enough to need naming. */
+export const reactorClipLengthLabel = (seconds) => (
+ seconds === REACTOR_MIN_CLIP_SECONDS ? `${seconds} seconds (min)`
+ : seconds === REACTOR_MAX_CLIP_SECONDS ? `${seconds} seconds (max)`
+ : `${seconds} seconds`
+);
diff --git a/server/lib/reactorVideoClip.test.js b/server/lib/reactorVideoClip.test.js
new file mode 100644
index 0000000000..8482beea5f
--- /dev/null
+++ b/server/lib/reactorVideoClip.test.js
@@ -0,0 +1,58 @@
+import { describe, it, expect } from 'vitest';
+import {
+ REACTOR_MAX_PROMPT_LENGTH, REACTOR_CLIP_FPS, REACTOR_MIN_CLIP_SECONDS,
+ REACTOR_MAX_CLIP_SECONDS, REACTOR_CLIP_LENGTHS, REACTOR_DEFAULT_CLIP_LENGTH,
+ reactorClipLengthLabel,
+} from './reactorVideoClip.js';
+
+describe('reactorVideoClip', () => {
+ it('offers only lengths fast-h3 accepts, in ascending order', () => {
+ expect(Object.isFrozen(REACTOR_CLIP_LENGTHS)).toBe(true);
+ expect([...REACTOR_CLIP_LENGTHS]).toEqual([...REACTOR_CLIP_LENGTHS].sort((a, b) => a - b));
+ for (const seconds of REACTOR_CLIP_LENGTHS) {
+ expect(seconds).toBeGreaterThanOrEqual(REACTOR_MIN_CLIP_SECONDS);
+ expect(seconds).toBeLessThanOrEqual(REACTOR_MAX_CLIP_SECONDS);
+ }
+ expect(REACTOR_CLIP_LENGTHS).toContain(REACTOR_MIN_CLIP_SECONDS);
+ expect(REACTOR_CLIP_LENGTHS).toContain(REACTOR_MAX_CLIP_SECONDS);
+ expect(REACTOR_CLIP_LENGTHS).toContain(REACTOR_DEFAULT_CLIP_LENGTH);
+ });
+
+ // The whole reason a picker replaced a free-text seconds box is that every
+ // offered value has to be one the API can actually render. Anything between
+ // the endpoints must land on a whole frame at 24fps.
+ it('offers only frame-aligned interior lengths', () => {
+ const interior = REACTOR_CLIP_LENGTHS
+ .filter((s) => s !== REACTOR_MIN_CLIP_SECONDS && s !== REACTOR_MAX_CLIP_SECONDS);
+ expect(interior.length).toBeGreaterThan(0);
+ for (const seconds of interior) {
+ expect(Number.isInteger(seconds * REACTOR_CLIP_FPS)).toBe(true);
+ }
+ expect(Number.isInteger(REACTOR_MAX_CLIP_SECONDS * REACTOR_CLIP_FPS)).toBe(true);
+ });
+
+ it('names the endpoints so the odd numbers read as bounds, not typos', () => {
+ expect(reactorClipLengthLabel(REACTOR_MIN_CLIP_SECONDS)).toBe('5.167 seconds (min)');
+ expect(reactorClipLengthLabel(REACTOR_MAX_CLIP_SECONDS)).toBe('14.375 seconds (max)');
+ expect(reactorClipLengthLabel(8)).toBe('8 seconds');
+ });
+});
+
+describe('reactorVideoClip client mirror', () => {
+ it('matches client/src/lib/reactorVideoClip.js', async () => {
+ // The VideoGen prompt counter and clip-length picker build from the client
+ // mirror, which can't import server code. Without this guard the form could
+ // go on accepting an 800+ character prompt the API rejects, or offering a
+ // clip length the service refuses — exactly the drift that made a long
+ // prompt fail at Generate instead of in the field.
+ const clientMirror = await import('../../client/src/lib/reactorVideoClip.js');
+ expect(clientMirror.REACTOR_MAX_PROMPT_LENGTH).toBe(REACTOR_MAX_PROMPT_LENGTH);
+ expect(clientMirror.REACTOR_MIN_CLIP_SECONDS).toBe(REACTOR_MIN_CLIP_SECONDS);
+ expect(clientMirror.REACTOR_MAX_CLIP_SECONDS).toBe(REACTOR_MAX_CLIP_SECONDS);
+ expect(clientMirror.REACTOR_DEFAULT_CLIP_LENGTH).toBe(REACTOR_DEFAULT_CLIP_LENGTH);
+ expect([...clientMirror.REACTOR_CLIP_LENGTHS]).toEqual([...REACTOR_CLIP_LENGTHS]);
+ for (const seconds of REACTOR_CLIP_LENGTHS) {
+ expect(clientMirror.reactorClipLengthLabel(seconds)).toBe(reactorClipLengthLabel(seconds));
+ }
+ });
+});
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index e43e3b7eb6..1b217bdec2 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -16,6 +16,9 @@ import {
validateRequest, videoModelTermsSchema,
} from '../lib/validation.js';
import { grokVideoDurationSchema } from '../lib/sharedSchemas.js';
+import {
+ REACTOR_MAX_CLIP_ID_LENGTH, REACTOR_MIN_CLIP_SECONDS, REACTOR_MAX_CLIP_SECONDS,
+} from '../lib/reactorVideoClip.js';
import { MIN_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES } from '../lib/videoContinuity.js';
import { I2V_REFERENCE_MODES } from '../lib/videoReferenceModes.js';
import {
@@ -269,11 +272,13 @@ const generateBodySchema = z.object({
),
// reactor.inc fast-h3 (#6214): the clip id to chain from
// (continue_from_clip_id — frame-accurate continuation, unlike fal/grok
- // which start a fresh render each time) and clip length in seconds.
- reactorClipId: z.string().min(1).max(200).optional(),
+ // which start a fresh render each time) and clip length in seconds. The
+ // bounds come from lib/reactorVideoClip.js rather than a hand-copied 1-60,
+ // which accepted lengths the fast-h3 API rejects outright.
+ reactorClipId: z.string().min(1).max(REACTOR_MAX_CLIP_ID_LENGTH).optional(),
reactorSeconds: z.preprocess(
(v) => (v == null || v === '' ? undefined : Number(v)),
- optionalNum(1, 60, 'reactorSeconds'),
+ optionalNum(REACTOR_MIN_CLIP_SECONDS, REACTOR_MAX_CLIP_SECONDS, 'reactorSeconds'),
),
reactorSeed: z.preprocess(
(v) => (v == null || v === '' ? undefined : Number(v)),
diff --git a/server/services/fableLoom/visualConditioning.js b/server/services/fableLoom/visualConditioning.js
index fbf1bd683e..f4e5cc82b8 100644
--- a/server/services/fableLoom/visualConditioning.js
+++ b/server/services/fableLoom/visualConditioning.js
@@ -16,6 +16,7 @@ import {
matchCharactersInText, matchObjectsInText, matchPlacesInText,
} from '../../lib/scenePrompt.js';
import { resolveFableLoomProtagonistPresence } from '../../lib/fableLoomPlayback.js';
+import { REACTOR_MAX_PROMPT_LENGTH } from '../../lib/reactorVideoClip.js';
import {
mergeNegativePromptTokens, stripStyleClause, universeVisualStyleTokens,
} from '../../lib/universeVisualStyle.js';
@@ -396,7 +397,7 @@ export async function compileFableLoomVisualRequest({
node.visualCanon?.shotNotes,
bindings.protagonistPresence === 'offscreen' && `Keep ${protagonistName} off-screen.`,
]).join('\n');
- if (positive.length > 800) throw new ServerError('Reactor requires a complete shot prompt within 800 characters. Shorten the shot direction or split the dialogue; no render was queued.', { status: 422, code: 'FABLELOOM_REACTOR_PROMPT_TOO_LONG' });
+ if (positive.length > REACTOR_MAX_PROMPT_LENGTH) throw new ServerError(`Reactor requires a complete shot prompt within ${REACTOR_MAX_PROMPT_LENGTH} characters. Shorten the shot direction or split the dialogue; no render was queued.`, { status: 422, code: 'FABLELOOM_REACTOR_PROMPT_TOO_LONG' });
}
const identityAvoid = bindings.boundCharacters.flatMap(({ character }) => character.identityPack?.avoid || []);
const negativePrompt = mergeNegativePromptTokens([
diff --git a/server/services/videoGen/reactor.js b/server/services/videoGen/reactor.js
index bece88c440..7d38481e79 100644
--- a/server/services/videoGen/reactor.js
+++ b/server/services/videoGen/reactor.js
@@ -11,10 +11,13 @@ import { videoGenEvents } from './events.js';
import { finalizeGeneratedVideo } from './generateVideoHelpers.js';
import { mutateVideoHistory } from './history.js';
import { getSettings } from '../settings.js';
+import {
+ REACTOR_MAX_PROMPT_LENGTH, REACTOR_MAX_CLIP_ID_LENGTH,
+ REACTOR_MIN_CLIP_SECONDS, REACTOR_MAX_CLIP_SECONDS, REACTOR_DEFAULT_CLIP_LENGTH,
+} from '../../lib/reactorVideoClip.js';
export const REACTOR_API_BASE = 'https://api.reactor.inc';
export const REACTOR_MODEL_ID = 'fast-h3';
-export const REACTOR_MAX_PROMPT_LENGTH = 800;
const REACTOR_TOKEN_TIMEOUT_MS = 15_000;
const REACTOR_RENDER_TIMEOUT_MS = (() => {
@@ -89,18 +92,35 @@ export const cancelAll = () => {
return true;
};
-export function validateReactorRequest({ prompt, continueFromClipId, seconds = 6, seed }) {
+export function validateReactorRequest({
+ prompt, continueFromClipId, sourceImagePath, seconds = REACTOR_DEFAULT_CLIP_LENGTH, seed,
+}) {
if (typeof prompt !== 'string' || !prompt.trim() || prompt.trim().length > REACTOR_MAX_PROMPT_LENGTH) {
- throw new ServerError('Reactor prompts must contain 1–800 characters; shorten the shot prompt before rendering', { status: 400, code: 'VALIDATION_ERROR' });
+ throw new ServerError(`Reactor prompts must contain 1–${REACTOR_MAX_PROMPT_LENGTH} characters; shorten the shot prompt before rendering`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (continueFromClipId) {
+ // A clip id addresses a clip fast-h3 already rendered, so continuation and
+ // a starting frame are two ways to say the same thing — accepting both
+ // would leave which one wins up to the SDK.
+ if (sourceImagePath) {
+ throw new ServerError('Reactor renders continue from a clip OR start from an image, not both; clear one before rendering', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (typeof continueFromClipId !== 'string' || continueFromClipId.length > REACTOR_MAX_CLIP_ID_LENGTH) {
+ throw new ServerError('Reactor clip id must be a string identifying a previous Reactor render', { status: 400, code: 'VALIDATION_ERROR' });
+ }
}
- if (continueFromClipId) throw new ServerError('Reactor clip continuity requires the same active session; use a starting image for independent renders', { status: 400, code: 'REACTOR_SESSION_CONTINUITY_UNSUPPORTED' });
- if (!Number.isFinite(Number(seconds)) || Number(seconds) < 5.167 || Number(seconds) > 14.375) {
- throw new ServerError('Reactor duration must be between 5.167 and 14.375 seconds', { status: 400, code: 'VALIDATION_ERROR' });
+ if (!Number.isFinite(Number(seconds)) || Number(seconds) < REACTOR_MIN_CLIP_SECONDS || Number(seconds) > REACTOR_MAX_CLIP_SECONDS) {
+ throw new ServerError(`Reactor duration must be between ${REACTOR_MIN_CLIP_SECONDS} and ${REACTOR_MAX_CLIP_SECONDS} seconds`, { status: 400, code: 'VALIDATION_ERROR' });
}
if (seed != null && seed !== '' && (!Number.isSafeInteger(Number(seed)) || Number(seed) < 0)) {
throw new ServerError('Reactor seed must be a non-negative integer', { status: 400, code: 'VALIDATION_ERROR' });
}
- return { prompt: prompt.trim(), seconds: Number(seconds), ...(seed != null && seed !== '' ? { seed: Number(seed) } : {}) };
+ return {
+ prompt: prompt.trim(),
+ seconds: Number(seconds),
+ ...(continueFromClipId ? { continueFromClipId } : {}),
+ ...(seed != null && seed !== '' ? { seed: Number(seed) } : {}),
+ };
}
function captureClip(entry, input, pythonPath, job, jobId) {
@@ -172,7 +192,7 @@ export async function generateVideo({
continueFromClipId, seconds, seed,
sourceImagePath = null, jobId: providedJobId = null,
}) {
- const request = validateReactorRequest({ prompt, continueFromClipId, seconds, seed });
+ const request = validateReactorRequest({ prompt, continueFromClipId, sourceImagePath, seconds, seed });
const pythonPath = process.env.REACTOR_PYTHON_PATH || join(PATHS.data, 'venvs', 'reactor', ...(process.platform === 'win32' ? ['Scripts', 'python.exe'] : ['bin', 'python']));
const runtime = await stat(pythonPath).catch(() => null);
if (!runtime?.isFile()) { throw new ServerError('Reactor runtime is missing. Run npm run setup:reactor, or set REACTOR_PYTHON_PATH', { status: 400, code: 'REACTOR_RUNTIME_MISSING' }); }
@@ -228,14 +248,16 @@ export async function generateVideo({
}
async function runReactorVideo(job, jobId, {
- apiKey, prompt, seconds, seed, pythonPath, sourceImagePath, outputPath, filename, meta,
+ apiKey, prompt, seconds, seed, continueFromClipId, pythonPath, sourceImagePath, outputPath, filename, meta,
}) {
const entry = { aborted: false, stop: null };
activeRequests.set(jobId, entry);
try {
const { jwt } = await mintReactorToken(apiKey);
if (entry.aborted) return finalizeCanceled(job, jobId);
- const result = await captureClip(entry, { jwt, prompt, seconds, seed, sourceImagePath, outputPath }, pythonPath, job, jobId);
+ const result = await captureClip(entry, {
+ jwt, prompt, seconds, seed, continueFromClipId, sourceImagePath, outputPath,
+ }, pythonPath, job, jobId);
if (entry.aborted) return finalizeCanceled(job, jobId);
const output = await stat(outputPath).catch(() => null);
if (!output?.isFile() || !output.size) throw new Error('Reactor completed without a playable output file');
@@ -243,7 +265,13 @@ async function runReactorVideo(job, jobId, {
closeJobAfterDelay(jobs, jobId);
} catch (err) {
await rm(outputPath, { force: true }).catch(() => {});
- finalizeError(job, jobId, entry.aborted ? 'Canceled' : `Reactor video generation failed: ${err?.message || 'unknown error'}`, { force: true });
+ // A continuation names a clip reactor rendered in an EARLIER session, and
+ // reactor decides whether it still holds it. Say so on the failure rather
+ // than leaving the user re-reading a prompt that was never the problem.
+ const continuationHint = continueFromClipId
+ ? ' — reactor may no longer hold that clip; clear "Continue from clip" and render fresh, or start from an image'
+ : '';
+ finalizeError(job, jobId, entry.aborted ? 'Canceled' : `Reactor video generation failed: ${err?.message || 'unknown error'}${continuationHint}`, { force: true });
} finally {
if (entry.aborted) await rm(outputPath, { force: true }).catch(() => {});
activeRequests.delete(jobId);
diff --git a/server/services/videoGen/reactor.test.js b/server/services/videoGen/reactor.test.js
index 900ea6b0e3..c2ec424b1b 100644
--- a/server/services/videoGen/reactor.test.js
+++ b/server/services/videoGen/reactor.test.js
@@ -64,13 +64,43 @@ describe('Reactor SDK adapter', () => {
});
it('rejects unsupported requests before minting or spending', async () => {
- for (const options of [{ prompt: 'x'.repeat(801) }, { seconds: 5 }, { seconds: 15 }, { continueFromClipId: 'old-session-clip' }]) {
+ for (const options of [
+ { prompt: 'x'.repeat(801) },
+ { seconds: 5 },
+ { seconds: 15 },
+ // Continuation and a starting frame both say "begin from this picture",
+ // so accepting both would leave the winner up to the SDK.
+ { continueFromClipId: 'clip-example', sourceImagePath: '/example/first-frame.png' },
+ ]) {
await expect(reactor.generateVideo({ prompt: 'A gate', ...options })).rejects.toBeTruthy();
}
expect(fetch).not.toHaveBeenCalled();
expect(mocks.spawn).not.toHaveBeenCalled();
});
+ // The clip id is stamped on every completed reactor history record precisely
+ // so a later render can chain off it; forwarding it as continue_from_clip_id
+ // is what makes that stored id worth anything.
+ it('forwards a stored clip id as the continuation the SDK understands', async () => {
+ await started({ continueFromClipId: 'clip-example' });
+ expect(input).toMatchObject({ continueFromClipId: 'clip-example' });
+ expect(input.sourceImagePath).toBeFalsy();
+ });
+
+ // A continuation names a clip reactor rendered in an earlier session, and
+ // reactor owns whether it still holds it — a failure there must not read as
+ // "your prompt was bad".
+ it('says the clip may be gone when a continuation fails', async () => {
+ const job = await started({ continueFromClipId: 'clip-example' });
+ const failed = once(videoGenEvents, 'failed');
+ child.stdout.emit('data', Buffer.from('{"type":"error","phase":"enqueue","errorType":"RuntimeError"}\n'));
+ child.emit('close', 1);
+ const [event] = await failed;
+ expect(event.generationId).toBe(job.jobId);
+ expect(event.error).toContain('Continue from clip');
+ expect(mocks.finalize).not.toHaveBeenCalled();
+ });
+
it('fails missing runtime before minting a token', async () => {
vi.stubEnv('REACTOR_PYTHON_PATH', join(root, 'missing-python'));
await expect(reactor.generateVideo({ prompt: 'A gate' })).rejects.toMatchObject({ code: 'REACTOR_RUNTIME_MISSING' });