Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(videogen): let Reactor renders pick the fast-h3 canvas that fits the image
Adam Eivy5122aad7e3e7
diff --git a/client/src/components/videoGen/ReactorPanel.jsx b/client/src/components/videoGen/ReactorPanel.jsxindex 87c0810ee5..4e6a040e4b 100644--- a/client/src/components/videoGen/ReactorPanel.jsx+++ b/client/src/components/videoGen/ReactorPanel.jsx@@ -13,8 +13,14 @@* - **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.+ * - **Canvas** is fast-h3's resolution control, and it is an ASPECT rather than+ * a width/height pair: every canvas holds a 768px short edge, so the aspect+ * string is the whole choice. Auto is the default because reactor FITS a+ * starting frame to whatever canvas the session opened with — pinning 16:9,+ * as every render did before, is what turned a portrait input into a clip+ * with clean audio and nothing worth watching.*/-import { REACTOR_CLIP_LENGTHS, reactorClipLengthLabel } from '../../lib/reactorVideoClip.js';+import { REACTOR_CANVASES, REACTOR_CLIP_LENGTHS, reactorClipLengthLabel } from '../../lib/reactorVideoClip.js';import { FormField } from '../ui/FormField';export default function ReactorPanel({@@ -26,6 +32,8 @@ export default function ReactorPanel({onSecondsChange,seed,onSeedChange,+ aspect,+ onAspectChange,}) {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;@@ -61,6 +69,20 @@ export default function ReactorPanel({))}</select></FormField>+ <FormField label="Canvas" labelClassName="block text-xs font-medium text-gray-400 mb-1">+ <select+ value={aspect}+ onChange={(e) => onAspectChange(e.target.value)}+ className={fieldClass}+ >+ <option value="">+ {imageModeActive ? 'Auto — match starting image' : 'Auto — landscape 16:9'}+ </option>+ {REACTOR_CANVASES.map((canvas) => (+ <option key={canvas.aspect} value={canvas.aspect}>{canvas.label}</option>+ ))}+ </select>+ </FormField><FormField label="Seed" labelClassName="block text-xs font-medium text-gray-400 mb-1"><inputtype="number"@@ -76,6 +98,11 @@ export default function ReactorPanel({continued frame-accurately by picking it above. Reactor decides how long it keeps a clipcontinuable, so an older one may come back rejected. Counts against your reactor.inc balance.</p>+ <p className="col-span-2 text-[11px] text-gray-500 leading-snug">+ {imageModeActive+ ? 'A starting image is centre-cropped to the canvas before it is sent, so pick the canvas that matches its shape — Auto does that for you. Cropping to a canvas the image does not fit throws away everything outside it.'+ : 'Every canvas renders at a 768px short edge; the aspect is the whole resolution choice.'}+ </p></div>);}diff --git a/client/src/hooks/useVideoGenFieldState.js b/client/src/hooks/useVideoGenFieldState.jsindex 8ab79893b9..56cbe69c7a 100644--- a/client/src/hooks/useVideoGenFieldState.js+++ b/client/src/hooks/useVideoGenFieldState.js@@ -27,6 +27,9 @@ export function useVideoGenFieldState({const [reactorClipId, setReactorClipId] = useState('');const [reactorSeconds, setReactorSeconds] = useState(REACTOR_DEFAULT_CLIP_LENGTH);const [reactorSeed, setReactorSeed] = useState('');+ // '' is the picker's Auto entry: submit no aspect and let the server derive+ // the fast-h3 canvas from the starting frame (text renders fall back to 16:9).+ const [reactorAspect, setReactorAspect] = useState('');const [mode, setMode] = useState(incomingAudioFilename ? 'a2v' : (incomingSourceImage ? 'image' : 'text'));const [prompt, setPrompt] = useState(incomingPrompt || '');const [negativePrompt, setNegativePrompt] = useState(incomingNegativePrompt || '');@@ -93,6 +96,7 @@ export function useVideoGenFieldState({reactorClipId, setReactorClipId,reactorSeconds, setReactorSeconds,reactorSeed, setReactorSeed,+ reactorAspect, setReactorAspect,guidanceScale, setGuidanceScale,height, setHeight,i2vReferenceMode, setI2vReferenceMode,diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.jsindex dc2902a3de..bb4c7a1c5b 100644--- a/client/src/hooks/useVideoGenForm.js+++ b/client/src/hooks/useVideoGenForm.js@@ -106,6 +106,7 @@ export function useVideoGenForm({reactorClipId, setReactorClipId,reactorSeconds, setReactorSeconds,reactorSeed, setReactorSeed,+ reactorAspect, setReactorAspect,guidanceScale, setGuidanceScale,height, setHeight,i2vReferenceMode, setI2vReferenceMode,@@ -1219,6 +1220,7 @@ export function useVideoGenForm({if (p.continueFromClipId) setReactorClipId(p.continueFromClipId);if (p.seconds) setReactorSeconds(p.seconds);if (p.seed !== undefined && p.seed !== null) setReactorSeed(p.seed);+ if (p.aspect) setReactorAspect(p.aspect);} else if (p.mode) setMode(p.mode);if (p.chunks && p.chunks > 1) setChunks(p.chunks);// 0 is a real restored value ("last frame only"), so this can't gate on@@ -1292,7 +1294,7 @@ export function useVideoGenForm({// stays pure so all three backend contracts can be tested independently.const submissionState = {isGrok, grokDuration, isFal, falDuration, falModelId,- isReactor, reactorClipId, reactorSeconds, reactorSeed, remoteSubmissionFields,+ isReactor, reactorClipId, reactorSeconds, reactorSeed, reactorAspect, remoteSubmissionFields,displaySleepEnabled,prompt, negativePrompt, stylePreset, selectedUniverse,width, height, mode, sourceImageFile, sourceImageUpload,@@ -1316,6 +1318,7 @@ export function useVideoGenForm({reactorClipId, setReactorClipId,reactorSeconds, setReactorSeconds,reactorSeed, setReactorSeed,+ reactorAspect, setReactorAspect,mode, handleModeChange,// Prompt + styleprompt, setPrompt,diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 327f7c66c2..6136ffbf28 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -52,7 +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()`. |+| `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`, the picker list `REACTOR_CLIP_LENGTHS` + `REACTOR_DEFAULT_CLIP_LENGTH` + `reactorClipLengthLabel()`, and the canvas contract `REACTOR_CANVASES` / `REACTOR_ASPECTS` / `REACTOR_DEFAULT_ASPECT` / `reactorCanvas()` / `nearestReactorAspect()` the aspect picker builds from. || `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/reactorVideoClip.js b/client/src/lib/reactorVideoClip.jsindex 50ee664ebc..293739006d 100644--- a/client/src/lib/reactorVideoClip.js+++ b/client/src/lib/reactorVideoClip.js@@ -34,3 +34,47 @@ export const reactorClipLengthLabel = (seconds) => (: seconds === REACTOR_MAX_CLIP_SECONDS ? `${seconds} seconds (max)`: `${seconds} seconds`);++/**+ * The canvases fast-h3 renders. The aspect string is the whole choice — every+ * canvas holds a 768px short edge, so the pixel size falls out of it. Reactor+ * FITS a starting frame to the session canvas, so picking the canvas that+ * matches the image is what keeps a portrait photo from being squeezed into a+ * landscape session. Widest-first so the picker reads landscape → portrait.+ */+export const REACTOR_CANVASES = Object.freeze([+ Object.freeze({ aspect: '16:9', width: 1344, height: 768, label: 'Landscape 16:9 · 1344×768' }),+ Object.freeze({ aspect: '4:3', width: 1024, height: 768, label: 'Standard 4:3 · 1024×768' }),+ Object.freeze({ aspect: '1:1', width: 768, height: 768, label: 'Square 1:1 · 768×768' }),+ Object.freeze({ aspect: '9:16', width: 768, height: 1344, label: 'Portrait 9:16 · 768×1344' }),+]);++/** Just the aspect strings — the closed set `set_canvas` accepts. */+export const REACTOR_ASPECTS = Object.freeze(REACTOR_CANVASES.map((c) => c.aspect));++/** Canvas a text-only render (or an unreadable starting frame) falls back to. */+export const REACTOR_DEFAULT_ASPECT = '16:9';++/** Canvas record for an aspect string; the default canvas for anything else. */+export const reactorCanvas = (aspect) => (+ REACTOR_CANVASES.find((c) => c.aspect === aspect)+ || REACTOR_CANVASES.find((c) => c.aspect === REACTOR_DEFAULT_ASPECT)+);++/**+ * The fast-h3 canvas closest to a starting frame's own shape, compared in log+ * space so twice-as-wide and half-as-wide score the same distance. Ties keep+ * the earlier (wider) canvas; anything unmeasurable answers the default.+ */+export const nearestReactorAspect = (width, height) => {+ const w = Number(width);+ const h = Number(height);+ if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0) return REACTOR_DEFAULT_ASPECT;+ const target = Math.log(w / h);+ let best = null;+ for (const canvas of REACTOR_CANVASES) {+ const distance = Math.abs(Math.log(canvas.width / canvas.height) - target);+ if (best === null || distance < best.distance) best = { aspect: canvas.aspect, distance };+ }+ return best.aspect;+};diff --git a/client/src/lib/videoGenSubmission.js b/client/src/lib/videoGenSubmission.jsindex d26ab2546c..4fe58d42b0 100644--- a/client/src/lib/videoGenSubmission.js+++ b/client/src/lib/videoGenSubmission.js@@ -45,7 +45,7 @@ export function envelopVideoPrompt(text, {export function buildVideoGenSubmission({isGrok, grokDuration, isFal, falDuration, falModelId,- isReactor, reactorClipId, reactorSeconds, reactorSeed, remoteSubmissionFields,+ isReactor, reactorClipId, reactorSeconds, reactorSeed, reactorAspect, remoteSubmissionFields,displaySleepEnabled,prompt, negativePrompt, stylePreset, selectedUniverse,width, height, mode, sourceImageFile, sourceImageUpload,@@ -117,8 +117,12 @@ export function buildVideoGenSubmission({// and reactor.js's own buildRequestBody already preserve 0 correctly,// so only the client-side send needs the nullish check).reactorSeed: reactorSeed === '' || reactorSeed === null || reactorSeed === undefined ? undefined : reactorSeed,- // No width/height: unlike grok/fal, reactor.js reads no dimension- // field — submitJob's reactor lane never forwards them.+ // No width/height: fast-h3's resolution is its session CANVAS, and every+ // canvas holds a 768px short edge, so the aspect string is the whole+ // choice. '' is the picker's Auto entry — sending nothing asks the server+ // to derive the canvas from the starting frame instead of opening the+ // 16:9 session that squeezed a portrait image into a landscape render.+ reactorAspect: reactorAspect || undefined,mode: mode === 'image' ? 'image' : 'text',sourceImageFile: mode === 'image' ? (sourceImageFile || '') : '',sourceImage: mode === 'image' ? (sourceImageUpload || '') : '',diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex e97a8f944f..f002612efb 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -212,6 +212,7 @@ export default function VideoGen() {backend, isGrok, isFal, isReactor, handleBackendChange, grokDuration, setGrokDuration,falDuration, setFalDuration, falModelId, setFalModelId,reactorClipId, setReactorClipId, reactorSeconds, setReactorSeconds, reactorSeed, setReactorSeed,+ reactorAspect, setReactorAspect,mode, handleModeChange,prompt, setPrompt, envelopedPrompt, negativePrompt, setNegativePrompt, stylePreset, setStylePreset,selectedUniverse, setSelectedUniverse, remixModelFallback,@@ -1581,6 +1582,8 @@ export default function VideoGen() {onSecondsChange={setReactorSeconds}seed={reactorSeed}onSeedChange={setReactorSeed}+ aspect={reactorAspect}+ onAspectChange={setReactorAspect}/>) : (<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">diff --git a/client/src/pages/VideoGen.reactor.test.jsx b/client/src/pages/VideoGen.reactor.test.jsxindex 72f998ec11..a1e33e3ffa 100644--- a/client/src/pages/VideoGen.reactor.test.jsx+++ b/client/src/pages/VideoGen.reactor.test.jsx@@ -12,6 +12,7 @@ import {} from '../test/videoGenPageMocks.jsx';import {REACTOR_MAX_PROMPT_LENGTH, REACTOR_MIN_CLIP_SECONDS, REACTOR_MAX_CLIP_SECONDS,+ REACTOR_ASPECTS,} from '../lib/reactorVideoClip.js';// A local model that DOES take a negative prompt, so "the box is gone" can only@@ -110,6 +111,32 @@ describe('VideoGen reactor.inc lane', () => {expect((await submit()).reactorSeconds).toBe(REACTOR_MAX_CLIP_SECONDS);});+ // fast-h3's resolution IS its session canvas, and the canvas is an aspect+ // (every one has a 768px short edge). Sending nothing is the Auto entry: the+ // server derives the canvas from the starting frame instead of opening the+ // 16:9 session that squeezed a portrait image into a landscape render.+ it('offers the fast-h3 canvases and defaults to deriving one from the frame', async () => {+ await renderVideoGenPage();+ await selectReactor();++ const canvas = screen.getByLabelText('Canvas');+ expect(canvas.tagName).toBe('SELECT');+ expect([...canvas.options].map((option) => option.value)).toEqual(['', ...REACTOR_ASPECTS]);+ expect(canvas.value).toBe('');++ fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'a fox watches the rain' } });+ expect((await submit()).reactorAspect).toBeUndefined();+ });++ it('submits the canvas the user picked over the derived one', async () => {+ await renderVideoGenPage();+ await selectReactor();++ fireEvent.change(screen.getByLabelText('Canvas'), { target: { value: '9:16' } });+ fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'a fox watches the rain' } });+ expect((await submit()).reactorAspect).toBe('9:16');+ });+// 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.diff --git a/docs/features/fableloom.md b/docs/features/fableloom.mdindex 0f76ee3650..1053eebf56 100644--- a/docs/features/fableloom.md+++ b/docs/features/fableloom.md@@ -384,6 +384,16 @@ are rejected rather than silently losing dialogue. Reactor accepts 5.167–14.37seconds and snaps durations to its frame grid. Local interactive voice profilesare independent of Reactor's generated audio.+FastH3's resolution is its **session canvas**, chosen as an aspect rather than a+width/height pair: `16:9` (1344×768), `4:3` (1024×768), `1:1` (768×768) or `9:16`+(768×1344) — every canvas holds a 768px short edge, so the aspect is the whole+choice. Reactor *fits* a starting frame to whatever canvas the session opened+with, so the canvas has to match the image. The Video Gen **Canvas** picker+defaults to **Auto**, which derives the canvas from the starting frame's own+shape and then centre-crops that frame to the canvas's exact pixel size before+upload; a text render falls back to 16:9. Pick a canvas explicitly to override+the derived one — the frame is cropped to it, so anything outside is discarded.+Clip chaining is best effort. Every finished Reactor render stores the clip IDReactor 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,diff --git a/scripts/reactor-render.py b/scripts/reactor-render.pyindex 62aed08de6..d3964e5e54 100644--- a/scripts/reactor-render.py+++ b/scripts/reactor-render.py@@ -14,6 +14,13 @@ from pathlib import Pathfrom reactor_sdk import Reactor+# The canvases fast-h3 renders, mirroring server/lib/reactorVideoClip.js. Every+# one holds a 768px short edge, so `set_canvas`'s aspect string is the whole+# choice. Pinning "16:9" for every render is what squeezed a portrait starting+# frame into a landscape session and returned a clip with audio and no picture.+CANVASES = {"16:9": (1344, 768), "4:3": (1024, 768), "1:1": (768, 768), "9:16": (768, 1344)}+DEFAULT_ASPECT = "16:9"+def emit(kind, **fields):print(json.dumps({"type": kind, **fields}), flush=True)@@ -30,6 +37,9 @@ async def render(params):raise ValueError("A prompt of 1–800 characters and duration of 5.167–14.375 seconds are required")if not params.get("jwt") or not params.get("outputPath"):raise ValueError("Session token and output path are required")+ aspect = params.get("aspect") or DEFAULT_ASPECT+ if aspect not in CANVASES:+ raise ValueError(f"Canvas aspect must be one of {', '.join(CANVASES)}")source = params.get("sourceImagePath")continue_from = (params.get("continueFromClipId") or "").strip()if source and continue_from:@@ -43,7 +53,7 @@ async def render(params):finished = asyncio.Event()state = {"active": False, "frames": 0, "error": None, "size": None, "audio": None,- "videoBuffers": [], "audioBuffers": [], "timestamps": [],+ "videoBuffers": [], "audioBuffers": [], "timestamps": [], "sizes": [],}def on_message(message):@@ -72,9 +82,8 @@ async def render(params):def on_video(bgra, width, height, frame_id, timestamp_us, user_data):if state["active"] and len(state["videoBuffers"]) < 370:state["timestamps"].append(timestamp_us)- state["size"] = (width, height)+ state["sizes"].append((width, height))state["videoBuffers"].append(bytes(bgra))- state["frames"] += 1def on_audio(pcm, num_samples, sample_rate, num_channels):if state["active"]:@@ -84,7 +93,7 @@ async def render(params):reactor.tracks.with_direction("recvonly").with_kind("video").one().on_raw_frame(on_video)reactor.tracks.with_direction("recvonly").with_kind("audio").one().on_raw_frame(on_audio)phase = "canvas"- await reactor.send_command("set_canvas", {"aspect": "16:9"})+ await reactor.send_command("set_canvas", {"aspect": aspect})request = {"prompt": prompt, "seconds": seconds}if params.get("seed") is not None:request["seed"] = int(params["seed"])@@ -114,11 +123,26 @@ async def render(params):await asyncio.sleep(0.5)state["active"] = Falseframes = state.pop("videoBuffers")+ sizes = state.pop("sizes")expected = int(clip.get("frames", round(seconds * 24)))- # WebRTC may skip decoded frames. Keep presentation time (and audio- # sync) by holding the previous frame across timestamp gaps.+ # A WebRTC track may renegotiate its resolution mid-stream. Every+ # BGRA buffer is then a different length while ffmpeg is told ONE+ # -video_size, so a single odd-sized frame shifts the stride for+ # everything after it and the muxed clip decodes as noise or black+ # while its audio plays fine. Keep only the resolution that carried+ # the most frames; the hold-across-gaps loop below covers the rest.+ if frames:+ # Ties resolve to the larger frame, so the choice is stable+ # rather than set-iteration order.+ dominant = max(set(sizes), key=lambda wh: (sizes.count(wh), wh[0] * wh[1]))+ keep = [index for index, wh in enumerate(sizes) if wh == dominant]+ state["size"] = dominant+ state["frames"] = len(keep)+ timestamps = [state["timestamps"][index] for index in keep]+ # Rebinding frees the discarded buffers here rather than at the+ # `del` below, which the 370-frame ceiling makes worth doing.+ frames = [frames[index] for index in keep]if frames:- timestamps = state["timestamps"]first = timestamps[0]cursor = 0for index in range(expected):diff --git a/scripts/reactor_render_test.py b/scripts/reactor_render_test.pyindex 65d57d6dad..9444cf8edb 100644--- a/scripts/reactor_render_test.py+++ b/scripts/reactor_render_test.py@@ -53,10 +53,11 @@ class FakeReactor:def on_raw_frame(self, callback):self.callbacks[self.kind] = callback- def frame(self, index):+ def frame(self, index, size=(2, 2)):# Nonzero PTS origin, and integer microseconds like the decoded SDK track.timestamp = 9_000_000 + int(index * 1_000_000 / 24)- self.callbacks["video"](bytes([index]) * 16, 2, 2, index, timestamp, None)+ width, height = size+ self.callbacks["video"](bytes([index]) * (width * height * 4), width, height, index, timestamp, None)async def send_command(self, name, data):self.commands.append((name, data))@@ -117,6 +118,58 @@ class CaptureLifecycleTest(unittest.IsolatedAsyncioTestCase):self.assertFalse(Path(str(self.output) + ".capture").exists())spawn.assert_awaited_once()+ async def test_canvas_opens_on_the_requested_aspect_and_rejects_one_fast_h3_cannot_render(self):+ reactor = FakeReactor()++ async def encode(*command, **kwargs):+ self.output.write_bytes(b"example-mp4")+ return SimpleNamespace(returncode=0, wait=AsyncMock(return_value=0))++ self.params["aspect"] = "9:16"+ await self.run_capture(reactor, AsyncMock(side_effect=encode))+ self.assertEqual(reactor.commands[0], ("set_canvas", {"aspect": "9:16"}))+ # An unrenderable aspect must fail before a paid session is constructed.+ with patch.object(self.runner, "Reactor") as factory:+ with self.assertRaises(ValueError):+ await self.runner.render({**self.params, "aspect": "21:9"})+ factory.assert_not_called()++ async def test_mid_stream_resolution_change_never_reaches_the_encoder(self):+ # A renegotiated WebRTC track delivers a differently-sized BGRA buffer.+ # ffmpeg is told ONE -video_size, so keeping both shifts the stride for+ # every later frame and the clip decodes as noise (or black) while its+ # audio plays fine — the "audio but no visuals" report.+ reactor = FakeReactor()++ async def drain_with_resize(delay):+ for index in reactor.delivered[2:]:+ reactor.frame(index)+ if index in (60, 61):+ # A renegotiated track: a differently-sized buffer landing+ # between two good frames, at a timestamp inside the clip,+ # so the hold-across-gaps loop would otherwise select it.+ timestamp = 9_000_000 + int(index * 1_000_000 / 24) + 20_000+ reactor.callbacks["video"](bytes([200]) * 64, 4, 4, index, timestamp, None)++ reactor.drain = drain_with_resize++ async def encode(*command, **kwargs):+ self.assertEqual(command[command.index("-video_size") + 1], "2x2")+ video = Path(command[command.index("-i") + 1]).read_bytes()+ self.assertEqual(len(video), 144 * 2 * 2 * 4)+ self.assertNotIn(bytes([200]) * 64, video)+ # The scratch dir is removed on success, so read it here.+ capture = json.loads(Path(str(self.output) + ".capture/capture.json").read_text())+ self.assertEqual(capture["size"], [2, 2])+ self.assertEqual(capture["frames"], 116)+ self.output.write_bytes(b"example-mp4")+ return SimpleNamespace(returncode=0, wait=AsyncMock(return_value=0))++ spawn = AsyncMock(side_effect=encode)+ events = await self.run_capture(reactor, spawn)+ self.assertEqual(events[-1]["type"], "complete")+ spawn.assert_awaited_once()+async def test_capture_just_below_eighty_percent_disconnects_without_encoding_or_retrying(self):reactor = FakeReactor(complete=False)spawn = AsyncMock()diff --git a/server/lib/README.md b/server/lib/README.mdindex d00208e045..f909678dfc 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -212,7 +212,8 @@ 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`. |+| `reactorStartingFrame.js` | Fits a reactor.inc `starting_frame` to the fast-h3 session canvas before it is uploaded. `readImageSize(path)` → `{width,height}` or `null` (never a guessed dimension), and `prepareReactorStartingFrame(sourceImagePath, requestedAspect, outputPath)` → `{ aspect, canvas, framePath, fittedPath }`: an absent `requestedAspect` DERIVES the canvas from the frame's own shape (`nearestReactorAspect`), then centre cover-crops the frame to that canvas's exact pixel size so reactor's own "fitted to the session canvas" step is a no-op. `fittedPath` is the temp file the caller deletes; `null` means the original was uploaded unchanged. A frame sharp cannot decode (or a resize that fails) passes through untouched on the default canvas rather than failing a render PortOS merely could not measure — reactor decodes more containers than sharp does. |+| `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). Also the CANVAS contract `set_canvas` accepts: `REACTOR_CANVASES` (`16:9` 1344×768, `4:3` 1024×768, `1:1` 768×768, `9:16` 768×1344 — every one a 768px short edge, so the aspect string is the whole choice), `REACTOR_ASPECTS`, `REACTOR_DEFAULT_ASPECT`, `reactorCanvas(aspect)` and `nearestReactorAspect(width, height)` (closest canvas in log-ratio space; anything unmeasurable answers the default rather than deriving one). 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.jsindex 9b75a18e3f..9347876425 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 './reactorStartingFrame.js';export * from './reactorVideoClip.js';export * from './heavyJobClaim.js';export * from './hfErrors.js';diff --git a/server/lib/reactorStartingFrame.js b/server/lib/reactorStartingFrame.jsnew file mode 100644index 0000000000..ac3dd44e59--- /dev/null+++ b/server/lib/reactorStartingFrame.js@@ -0,0 +1,75 @@+/**+ * Fit a reactor.inc `starting_frame` to the fast-h3 session canvas.+ *+ * fast-h3 renders at ONE resolution per session — whichever `set_canvas`+ * aspect the session opened with (`reactorVideoClip.js#REACTOR_CANVASES`) — and+ * the API's own contract for a starting frame is "common formats decode; the+ * frame is fitted to the session canvas." That fitting is reactor's, not+ * PortOS's, and it is the part a caller cannot see: hand a 3024×4032 phone+ * photo to a 1344×768 session and what conditions the render is whatever+ * reactor's fit left of it, which is how a portrait input came back as a clip+ * with clean audio and no usable picture.+ *+ * So PortOS does the fit itself, deterministically, and tells the caller which+ * canvas it fitted TO:+ *+ * - The canvas is chosen from the frame's own shape when the request didn't+ * name one, so a portrait photo opens a portrait session instead of being+ * squeezed into a landscape one.+ * - The frame is then cover-cropped from the centre to the canvas's exact pixel+ * size, so reactor's own fit is a no-op and the render is conditioned on+ * pixels the user can predict.+ *+ * A frame that sharp cannot decode is passed through untouched with the+ * default canvas — reactor accepts more container formats than sharp does, and+ * refusing a render PortOS merely failed to measure would be worse than letting+ * reactor fit it.+ */+import sharp from 'sharp';+import {+ REACTOR_DEFAULT_ASPECT, nearestReactorAspect, reactorCanvas,+} from './reactorVideoClip.js';++/** `{ width, height }` of an image, or `null` when it could not be measured. */+export const readImageSize = async (path) => {+ const meta = await sharp(path).metadata().catch(() => null);+ const width = Number(meta?.width);+ const height = Number(meta?.height);+ return Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0+ ? { width, height }+ : null;+};++/**+ * Resolve the canvas one render opens with, and the frame it starts from.+ *+ * `requestedAspect` absent means "derive it" — that is the picker's Auto entry+ * and the shape every non-UI caller (FableLoom, the API) gets by default.+ *+ * Returns `{ aspect, canvas, framePath, fittedPath }` where `framePath` is what+ * to upload and `fittedPath` is the temp file the caller must delete afterwards+ * (`null` when nothing was written).+ */+export async function prepareReactorStartingFrame(sourceImagePath, requestedAspect, outputPath) {+ if (!sourceImagePath) {+ const aspect = requestedAspect || REACTOR_DEFAULT_ASPECT;+ return { aspect, canvas: reactorCanvas(aspect), framePath: null, fittedPath: null };+ }+ const size = await readImageSize(sourceImagePath);+ const aspect = requestedAspect+ || (size ? nearestReactorAspect(size.width, size.height) : REACTOR_DEFAULT_ASPECT);+ const canvas = reactorCanvas(aspect);+ const passthrough = { aspect, canvas, framePath: sourceImagePath, fittedPath: null };+ // Unmeasurable, or already exactly the canvas: nothing to gain from a re-encode.+ if (!size || (size.width === canvas.width && size.height === canvas.height)) return passthrough;+ const fittedPath = `${outputPath}.start.png`;+ const written = await sharp(sourceImagePath)+ .resize({ width: canvas.width, height: canvas.height, fit: 'cover', position: 'centre' })+ .png()+ .toFile(fittedPath)+ .then(() => true)+ .catch(() => false);+ if (!written) return passthrough;+ console.log(`🖼️ Reactor starting frame fitted ${size.width}x${size.height} → ${canvas.width}x${canvas.height} (${aspect})`);+ return { aspect, canvas, framePath: fittedPath, fittedPath };+}diff --git a/server/lib/reactorStartingFrame.test.js b/server/lib/reactorStartingFrame.test.jsnew file mode 100644index 0000000000..2d1a5ea2c0--- /dev/null+++ b/server/lib/reactorStartingFrame.test.js@@ -0,0 +1,61 @@+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import sharp from 'sharp';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { prepareReactorStartingFrame, readImageSize } from './reactorStartingFrame.js';++let dir;+const writeImage = async (name, width, height) => {+ const path = join(dir, name);+ await sharp({ create: { width, height, channels: 3, background: '#204080' } }).png().toFile(path);+ return path;+};++beforeAll(async () => { dir = await mkdtemp(join(tmpdir(), 'reactor-frame-')); });+afterAll(async () => { await rm(dir, { recursive: true, force: true }); });++describe('prepareReactorStartingFrame', () => {+ // The reported failure: a tall phone photo opened a 1344x768 session, so+ // reactor's own fit left almost nothing of it to animate.+ it('opens a portrait session for a portrait frame and crops it to that canvas', async () => {+ const source = await writeImage('portrait.png', 900, 1600);+ const out = join(dir, 'portrait-render.mp4');+ const frame = await prepareReactorStartingFrame(source, undefined, out);+ expect(frame.aspect).toBe('9:16');+ expect(frame.framePath).toBe(`${out}.start.png`);+ expect(frame.fittedPath).toBe(frame.framePath);+ await expect(readImageSize(frame.framePath)).resolves.toEqual({ width: 768, height: 1344 });+ });++ it('honours an explicitly requested canvas over the frame it was given', async () => {+ const source = await writeImage('explicit.png', 900, 1600);+ const out = join(dir, 'explicit-render.mp4');+ const frame = await prepareReactorStartingFrame(source, '1:1', out);+ expect(frame.aspect).toBe('1:1');+ await expect(readImageSize(frame.framePath)).resolves.toEqual({ width: 768, height: 768 });+ });++ // A re-encode of an already-correct frame is a lossy no-op plus a temp file+ // the caller then has to delete.+ it('uploads a frame that already matches the canvas untouched', async () => {+ const source = await writeImage('exact.png', 1344, 768);+ const frame = await prepareReactorStartingFrame(source, undefined, join(dir, 'exact-render.mp4'));+ expect(frame).toMatchObject({ aspect: '16:9', framePath: source, fittedPath: null });+ });++ // reactor decodes more container formats than sharp does, so failing to+ // MEASURE a frame must not fail a render reactor could have fitted itself.+ it('passes an unreadable frame through on the default canvas', async () => {+ const frame = await prepareReactorStartingFrame(join(dir, 'missing.heic'), undefined, join(dir, 'missing-render.mp4'));+ expect(frame).toMatchObject({ aspect: '16:9', framePath: join(dir, 'missing.heic'), fittedPath: null });+ expect(frame.canvas).toMatchObject({ width: 1344, height: 768 });+ });++ it('resolves a text render to the requested canvas with no frame at all', async () => {+ expect(await prepareReactorStartingFrame(null, '9:16', join(dir, 't.mp4')))+ .toMatchObject({ aspect: '9:16', framePath: null, fittedPath: null });+ expect(await prepareReactorStartingFrame(null, undefined, join(dir, 't.mp4')))+ .toMatchObject({ aspect: '16:9', framePath: null, fittedPath: null });+ });+});diff --git a/server/lib/reactorVideoClip.js b/server/lib/reactorVideoClip.jsindex 073e13e57d..d7cc55cb63 100644--- a/server/lib/reactorVideoClip.js+++ b/server/lib/reactorVideoClip.js@@ -51,3 +51,54 @@ export const reactorClipLengthLabel = (seconds) => (: seconds === REACTOR_MAX_CLIP_SECONDS ? `${seconds} seconds (max)`: `${seconds} seconds`);++/**+ * The canvases fast-h3 renders, in `set_canvas`'s own `aspect` vocabulary.+ *+ * Every one holds a 768px SHORT edge — the model's native resolution — so the+ * aspect string is the whole choice and the pixel size falls out of it. PortOS+ * pinned `16:9` for every render before #6336, which is why a portrait starting+ * frame came back as a clip with audio and no usable picture: reactor fits the+ * starting frame to the SESSION canvas, so a 9:16 photo squeezed into a 1344×768+ * session had almost nothing left to animate.+ *+ * Ordered widest-first so a picker reads landscape → square → portrait.+ */+export const REACTOR_CANVASES = Object.freeze([+ Object.freeze({ aspect: '16:9', width: 1344, height: 768, label: 'Landscape 16:9 · 1344×768' }),+ Object.freeze({ aspect: '4:3', width: 1024, height: 768, label: 'Standard 4:3 · 1024×768' }),+ Object.freeze({ aspect: '1:1', width: 768, height: 768, label: 'Square 1:1 · 768×768' }),+ Object.freeze({ aspect: '9:16', width: 768, height: 1344, label: 'Portrait 9:16 · 768×1344' }),+]);++/** Just the aspect strings — the closed set `set_canvas` accepts. */+export const REACTOR_ASPECTS = Object.freeze(REACTOR_CANVASES.map((c) => c.aspect));++/** Canvas a text-only render (or an unreadable starting frame) falls back to. */+export const REACTOR_DEFAULT_ASPECT = '16:9';++/** Canvas record for an aspect string; the default canvas for anything else. */+export const reactorCanvas = (aspect) => (+ REACTOR_CANVASES.find((c) => c.aspect === aspect)+ || REACTOR_CANVASES.find((c) => c.aspect === REACTOR_DEFAULT_ASPECT)+);++/**+ * The fast-h3 canvas closest to a starting frame's own shape, compared in log+ * space so "twice as wide as the canvas" and "half as wide" score the same+ * distance. Ties keep the earlier (wider) canvas. Anything unmeasurable —+ * a missing dimension, a zero, a NaN — answers the default rather than+ * pretending to have derived one.+ */+export const nearestReactorAspect = (width, height) => {+ const w = Number(width);+ const h = Number(height);+ if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0) return REACTOR_DEFAULT_ASPECT;+ const target = Math.log(w / h);+ let best = null;+ for (const canvas of REACTOR_CANVASES) {+ const distance = Math.abs(Math.log(canvas.width / canvas.height) - target);+ if (best === null || distance < best.distance) best = { aspect: canvas.aspect, distance };+ }+ return best.aspect;+};diff --git a/server/lib/reactorVideoClip.test.js b/server/lib/reactorVideoClip.test.jsindex 8482beea5f..32597b2552 100644--- a/server/lib/reactorVideoClip.test.js+++ b/server/lib/reactorVideoClip.test.js@@ -2,6 +2,8 @@ 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,+ REACTOR_CANVASES, REACTOR_ASPECTS, REACTOR_DEFAULT_ASPECT,+ reactorCanvas, nearestReactorAspect,reactorClipLengthLabel,} from './reactorVideoClip.js';@@ -31,6 +33,38 @@ describe('reactorVideoClip', () => {expect(Number.isInteger(REACTOR_MAX_CLIP_SECONDS * REACTOR_CLIP_FPS)).toBe(true);});+ // fast-h3 renders at a 768px short edge on every canvas, so a canvas whose+ // short edge drifted would be a resolution PortOS asks for and the API does+ // not render.+ it('offers only canvases fast-h3 renders, each on a 768px short edge', () => {+ expect(REACTOR_ASPECTS).toEqual(['16:9', '4:3', '1:1', '9:16']);+ for (const canvas of REACTOR_CANVASES) {+ expect(Math.min(canvas.width, canvas.height)).toBe(768);+ expect(canvas.label).toContain(`${canvas.width}\u00d7${canvas.height}`);+ }+ expect(REACTOR_ASPECTS).toContain(REACTOR_DEFAULT_ASPECT);+ expect(reactorCanvas('9:16')).toMatchObject({ width: 768, height: 1344 });+ });++ // The whole bug: a portrait starting frame used to open a 1344x768 session.+ it('derives the canvas closest to a starting frame, and never guesses one it cannot measure', () => {+ expect(nearestReactorAspect(3024, 4032)).toBe('9:16');+ expect(nearestReactorAspect(1080, 1920)).toBe('9:16');+ expect(nearestReactorAspect(1920, 1080)).toBe('16:9');+ expect(nearestReactorAspect(1000, 1000)).toBe('1:1');+ expect(nearestReactorAspect(1600, 1200)).toBe('4:3');+ for (const bad of [[0, 100], [100, 0], [NaN, 100], [undefined, undefined], [-16, -9]]) {+ expect(nearestReactorAspect(...bad)).toBe(REACTOR_DEFAULT_ASPECT);+ }+ });++ // An unknown aspect must land on a real canvas rather than `undefined`, or+ // the caller reads `.width` off nothing while fitting a frame.+ it('falls back to the default canvas for an aspect it does not render', () => {+ expect(reactorCanvas('21:9')).toMatchObject({ aspect: REACTOR_DEFAULT_ASPECT });+ expect(reactorCanvas(undefined)).toMatchObject({ aspect: REACTOR_DEFAULT_ASPECT });+ });+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)');@@ -54,5 +88,14 @@ describe('reactorVideoClip client mirror', () => {for (const seconds of REACTOR_CLIP_LENGTHS) {expect(clientMirror.reactorClipLengthLabel(seconds)).toBe(reactorClipLengthLabel(seconds));}+ // The canvas picker builds from the mirror, so a canvas that drifted would+ // offer a resolution the service refuses (or omit one it renders).+ expect(clientMirror.REACTOR_DEFAULT_ASPECT).toBe(REACTOR_DEFAULT_ASPECT);+ expect([...clientMirror.REACTOR_ASPECTS]).toEqual([...REACTOR_ASPECTS]);+ expect(clientMirror.REACTOR_CANVASES.map((c) => ({ ...c })))+ .toEqual(REACTOR_CANVASES.map((c) => ({ ...c })));+ for (const [w, h] of [[3024, 4032], [1920, 1080], [768, 768], [0, 0]]) {+ expect(clientMirror.nearestReactorAspect(w, h)).toBe(nearestReactorAspect(w, h));+ }});});diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 1b217bdec2..9a1be7cb1b 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -18,6 +18,7 @@ import {import { grokVideoDurationSchema } from '../lib/sharedSchemas.js';import {REACTOR_MAX_CLIP_ID_LENGTH, REACTOR_MIN_CLIP_SECONDS, REACTOR_MAX_CLIP_SECONDS,+ REACTOR_ASPECTS,} from '../lib/reactorVideoClip.js';import { MIN_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES } from '../lib/videoContinuity.js';import { I2V_REFERENCE_MODES } from '../lib/videoReferenceModes.js';@@ -284,6 +285,16 @@ const generateBodySchema = z.object({(v) => (v == null || v === '' ? undefined : Number(v)),optionalNum(0, 2 ** 32 - 1, 'reactorSeed'),),+ // fast-h3 session canvas — a `set_canvas` aspect, NOT width/height: every+ // canvas holds a 768px short edge so the aspect is the whole choice. Omitted+ // means "derive it from the starting frame" (the picker's Auto entry), which+ // is what keeps a portrait image off the 1344x768 canvas every render used to+ // open with. Multipart bodies arrive as strings, so the empty-string sentinel+ // has to read as omitted rather than as an invalid enum value.+ reactorAspect: z.preprocess(+ (v) => (v === '' ? undefined : v),+ z.enum(REACTOR_ASPECTS).optional(),+ ),prompt: z.string().min(1).max(8000),negativePrompt: z.string().max(8000).optional(),modelId: z.string().max(64).optional(),@@ -920,10 +931,11 @@ const ACTIVE_JOB_PARAM_FIELDS = [// 'grok' discriminator for them) and the clip duration — both plain// values, safe to echo for the reloading page's form restore.'videoMode', 'duration',- // reactor.inc jobs (#6214): the clip to chain from and the clip length —- // both plain scalars (no filesystem path), safe to echo for the reloading- // page's form restore. `seed` above already covers reactor's seed field.- 'continueFromClipId', 'seconds',+ // reactor.inc jobs (#6214): the clip to chain from, the clip length, and the+ // fast-h3 session canvas — all plain scalars (no filesystem path), safe to+ // echo for the reloading page's form restore. `seed` above already covers+ // reactor's seed field.+ 'continueFromClipId', 'seconds', 'aspect',// loras are { filename, scale } basenames (no server filesystem paths), so// they're safe to echo back for the resuming picker to repopulate.'loras',diff --git a/server/services/videoGen/reactor.js b/server/services/videoGen/reactor.jsindex 7d38481e79..21a6603a21 100644--- a/server/services/videoGen/reactor.js+++ b/server/services/videoGen/reactor.js@@ -14,7 +14,9 @@ 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,+ REACTOR_ASPECTS, reactorCanvas,} from '../../lib/reactorVideoClip.js';+import { prepareReactorStartingFrame } from '../../lib/reactorStartingFrame.js';export const REACTOR_API_BASE = 'https://api.reactor.inc';export const REACTOR_MODEL_ID = 'fast-h3';@@ -93,7 +95,7 @@ export const cancelAll = () => {};export function validateReactorRequest({- prompt, continueFromClipId, sourceImagePath, seconds = REACTOR_DEFAULT_CLIP_LENGTH, seed,+ prompt, continueFromClipId, sourceImagePath, seconds = REACTOR_DEFAULT_CLIP_LENGTH, seed, aspect,}) {if (typeof prompt !== 'string' || !prompt.trim() || prompt.trim().length > REACTOR_MAX_PROMPT_LENGTH) {throw new ServerError(`Reactor prompts must contain 1–${REACTOR_MAX_PROMPT_LENGTH} characters; shorten the shot prompt before rendering`, { status: 400, code: 'VALIDATION_ERROR' });@@ -115,11 +117,19 @@ export function validateReactorRequest({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' });}+ // An absent aspect is the request to DERIVE the canvas from the starting+ // frame (see lib/reactorStartingFrame.js) — a text render falls back to the+ // default there. An unrecognized one is rejected rather than silently+ // rendered on 16:9, which is how every render used to land there.+ if (aspect != null && aspect !== '' && !REACTOR_ASPECTS.includes(aspect)) {+ throw new ServerError(`Reactor canvas aspect must be one of ${REACTOR_ASPECTS.join(', ')}`, { status: 400, code: 'VALIDATION_ERROR' });+ }return {prompt: prompt.trim(),seconds: Number(seconds),...(continueFromClipId ? { continueFromClipId } : {}),...(seed != null && seed !== '' ? { seed: Number(seed) } : {}),+ ...(aspect ? { aspect } : {}),};}@@ -189,10 +199,10 @@ function captureClip(entry, input, pythonPath, job, jobId) {export async function generateVideo({settings, prompt = '', negativePrompt,- continueFromClipId, seconds, seed,+ continueFromClipId, seconds, seed, aspect,sourceImagePath = null, jobId: providedJobId = null,}) {- const request = validateReactorRequest({ prompt, continueFromClipId, sourceImagePath, seconds, seed });+ const request = validateReactorRequest({ prompt, continueFromClipId, sourceImagePath, seconds, seed, aspect });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' }); }@@ -248,20 +258,26 @@ export async function generateVideo({}async function runReactorVideo(job, jobId, {- apiKey, prompt, seconds, seed, continueFromClipId, pythonPath, sourceImagePath, outputPath, filename, meta,+ apiKey, prompt, seconds, seed, aspect, continueFromClipId, pythonPath, sourceImagePath, outputPath, filename, meta,}) {const entry = { aborted: false, stop: null };activeRequests.set(jobId, entry);+ // Declared outside the try so the finally can still delete a fitted frame+ // whose render failed after it was written.+ let frame = { aspect, canvas: reactorCanvas(aspect), framePath: sourceImagePath, fittedPath: null };try {+ // Resolved before the token is minted, so a starting frame PortOS could not+ // fit costs nothing on the reactor side.+ frame = await prepareReactorStartingFrame(sourceImagePath, aspect, outputPath);const { jwt } = await mintReactorToken(apiKey);if (entry.aborted) return finalizeCanceled(job, jobId);const result = await captureClip(entry, {- jwt, prompt, seconds, seed, continueFromClipId, sourceImagePath, outputPath,+ jwt, prompt, seconds, seed, continueFromClipId, aspect: frame.aspect, sourceImagePath: frame.framePath, 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');- await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta: { ...meta, clipId: result.clipId, seconds: result.seconds }, actualSeed: seed ?? null, mutateHistory: mutateVideoHistory });+ await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta: { ...meta, aspect: frame.aspect, width: frame.canvas.width, height: frame.canvas.height, clipId: result.clipId, seconds: result.seconds }, actualSeed: seed ?? null, mutateHistory: mutateVideoHistory });closeJobAfterDelay(jobs, jobId);} catch (err) {await rm(outputPath, { force: true }).catch(() => {});@@ -273,6 +289,7 @@ async function runReactorVideo(job, jobId, {: '';finalizeError(job, jobId, entry.aborted ? 'Canceled' : `Reactor video generation failed: ${err?.message || 'unknown error'}${continuationHint}`, { force: true });} finally {+ if (frame.fittedPath) await rm(frame.fittedPath, { force: true }).catch(() => {});if (entry.aborted) await rm(outputPath, { force: true }).catch(() => {});activeRequests.delete(jobId);activeJobs.delete(jobId);diff --git a/server/services/videoGen/reactor.test.js b/server/services/videoGen/reactor.test.jsindex c2ec424b1b..cbdf090aba 100644--- a/server/services/videoGen/reactor.test.js+++ b/server/services/videoGen/reactor.test.js@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { EventEmitter, once } from 'events';-import { mkdir, rm, writeFile } from 'fs/promises';+import { mkdir, rm, stat, writeFile } from 'fs/promises';import { join } from 'path';import { tmpdir } from 'os';@@ -71,6 +71,9 @@ describe('Reactor SDK adapter', () => {// 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' },+ // A canvas fast-h3 cannot open must fail here rather than silently+ // rendering on 16:9 — the shape of the original bug.+ { aspect: '21:9' },]) {await expect(reactor.generateVideo({ prompt: 'A gate', ...options })).rejects.toBeTruthy();}@@ -78,6 +81,36 @@ describe('Reactor SDK adapter', () => {expect(mocks.spawn).not.toHaveBeenCalled();});+ // fast-h3 FITS a starting frame to whatever canvas the session opened with,+ // and PortOS pinned 16:9 for every render — which is why a portrait image+ // came back as a clip with clean audio and no usable picture.+ it('opens a portrait session for a portrait frame and uploads it pre-cropped', async () => {+ const sourceImagePath = join(root, 'portrait.png');+ const sharp = (await import('sharp')).default;+ await sharp({ create: { width: 900, height: 1600, channels: 3, background: '#204080' } }).png().toFile(sourceImagePath);+ const job = await started({ sourceImagePath });+ expect(input.aspect).toBe('9:16');+ // The upload is the fitted copy, not the oversized original.+ expect(input.sourceImagePath).toBe(`${input.outputPath}.start.png`);+ await writeFile(input.outputPath, 'example-video');+ child.stdout.emit('data', Buffer.from('{"type":"complete","clipId":"clip-example","seconds":6}\n'));+ child.emit('close', 0);+ await vi.waitFor(() => expect(mocks.finalize).toHaveBeenCalledWith(expect.objectContaining({+ jobId: job.jobId,+ meta: expect.objectContaining({ aspect: '9:16', width: 768, height: 1344 }),+ })));+ // The fitted copy is scratch, not a render output left beside the clip.+ await expect(stat(input.sourceImagePath)).rejects.toBeTruthy();+ });++ it('opens the canvas the request named, over the one the frame implies', async () => {+ const sourceImagePath = join(root, 'explicit.png');+ const sharp = (await import('sharp')).default;+ await sharp({ create: { width: 900, height: 1600, channels: 3, background: '#204080' } }).png().toFile(sourceImagePath);+ await started({ sourceImagePath, aspect: '1:1' });+ expect(input.aspect).toBe('1:1');+ });+// 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.diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.jsindex aef4d58d39..6f1d761515 100644--- a/server/services/videoGen/submitJob.js+++ b/server/services/videoGen/submitJob.js@@ -233,6 +233,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {continueFromClipId: body.reactorClipId,seconds: body.reactorSeconds,seed: body.reactorSeed,+ aspect: body.reactorAspect,sourceImagePath,uploadedTempPath,...(body.musicVideo ? { musicVideo: body.musicVideo } : {}),