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

fix: preserve Reactor video when stream timestamps are absent (#6339)

Adam Eivy7802fc23e1e4
diff --git a/scripts/reactor-render.py b/scripts/reactor-render.py
index d3964e5e54..9ce947a157 100644
--- a/scripts/reactor-render.py
+++ b/scripts/reactor-render.py
@@ -10,6 +10,7 @@ import math
import signal
import sys
import shutil
+import time
from pathlib import Path
from reactor_sdk import Reactor
@@ -53,7 +54,7 @@ async def render(params):
finished = asyncio.Event()
state = {
"active": False, "frames": 0, "error": None, "size": None, "audio": None,
- "videoBuffers": [], "audioBuffers": [], "timestamps": [], "sizes": [],
+ "videoBuffers": [], "audioBuffers": [], "timestamps": [], "sizes": [], "arrivals": [],
}
def on_message(message):
@@ -81,9 +82,19 @@ async def render(params):
with raw_video.open("wb") as video, raw_audio.open("wb") as audio:
def on_video(bgra, width, height, frame_id, timestamp_us, user_data):
if state["active"] and len(state["videoBuffers"]) < 370:
+ # memoryview rejects integer pointers instead of bytes(int)'s
+ # silent allocation of that many zero bytes.
+ try:
+ frame = memoryview(bgra).tobytes()
+ except (TypeError, ValueError):
+ frame = b""
+ if width <= 0 or height <= 0 or len(frame) != width * height * 4:
+ state["error"] = "Invalid Reactor video frame buffer"
+ return
+ state["arrivals"].append(time.monotonic_ns() // 1000)
state["timestamps"].append(timestamp_us)
state["sizes"].append((width, height))
- state["videoBuffers"].append(bytes(bgra))
+ state["videoBuffers"].append(frame)
def on_audio(pcm, num_samples, sample_rate, num_channels):
if state["active"]:
@@ -139,6 +150,11 @@ async def render(params):
state["size"] = dominant
state["frames"] = len(keep)
timestamps = [state["timestamps"][index] for index in keep]
+ # SDK timestamp_us=0 means no metadata, not presentation time.
+ # Resampling equal timestamps selects the final (often black)
+ # frame for the entire clip. Use receive time in that case.
+ if any(t <= 0 for t in timestamps) or any(b <= a for a, b in zip(timestamps, timestamps[1:])):
+ timestamps = [state["arrivals"][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]
@@ -157,7 +173,7 @@ async def render(params):
raise RuntimeError(state["error"])
phase = "capture"
expected = clip.get("frames", round(seconds * 24))
- (scratch_path / "capture.json").write_text(json.dumps({"frames": state["frames"], "expected": expected, "size": state["size"], "audio": state["audio"], "clipId": clip["clip_id"]}))
+ (scratch_path / "capture.json").write_text(json.dumps({"frames": state["frames"], "expected": expected, "size": state["size"], "audio": state["audio"], "clipId": clip["clip_id"], "timestampUnique": len(set(state["timestamps"]))}))
emit("status", message=f"Captured {state['frames']} of {expected} frames; audio={bool(state['audio'])}")
if state["frames"] < expected * 0.8 or not state["audio"]:
raise RuntimeError(f"Incomplete stream capture: {state['frames']} of {expected} video frames")
@@ -183,10 +199,12 @@ async def render(params):
await encoder.wait()
if encoder.returncode or not output.is_file() or output.stat().st_size == 0:
raise RuntimeError("Could not encode the captured Reactor clip")
+ emit("status", message="Capture timestamp diagnostic", unique=len(set(state["timestamps"])))
shutil.rmtree(scratch_path)
- emit("complete", clipId=clip["clip_id"], seconds=expected / 24)
+ emit("complete", clipId=clip["clip_id"], seconds=expected / 24, frames=state["frames"])
except Exception as error:
- emit("error", phase=phase, errorType=type(error).__name__)
+ emit("error", phase=phase, errorType=type(error).__name__,
+ **({"code": "INVALID_FRAME_BUFFER"} if state["error"] == "Invalid Reactor video frame buffer" else {}))
raise
finally:
try:
diff --git a/scripts/reactor_render_test.py b/scripts/reactor_render_test.py
index 9444cf8edb..dab6742e57 100644
--- a/scripts/reactor_render_test.py
+++ b/scripts/reactor_render_test.py
@@ -113,7 +113,7 @@ class CaptureLifecycleTest(unittest.IsolatedAsyncioTestCase):
spawn = AsyncMock(side_effect=encode)
events = await self.run_capture(reactor, spawn)
self.assertEqual([name for name, _ in reactor.commands], ["set_canvas", "enqueue", "play"])
- self.assertEqual(events[-1], {"type": "complete", "clipId": "example-clip", "seconds": 6.0})
+ self.assertEqual(events[-1], {"type": "complete", "clipId": "example-clip", "seconds": 6.0, "frames": 116})
self.assertTrue(reactor.disconnected)
self.assertFalse(Path(str(self.output) + ".capture").exists())
spawn.assert_awaited_once()
@@ -193,6 +193,41 @@ class CaptureLifecycleTest(unittest.IsolatedAsyncioTestCase):
self.assertEqual(encoder.wait.await_count, 3)
self.assertTrue(reactor.disconnected)
+ async def test_absent_timestamps_use_receive_time_instead_of_repeating_the_final_frame(self):
+ reactor = FakeReactor()
+ original = reactor.frame
+ clock = [0]
+
+ def frame(index, size=(2, 2)):
+ clock[0] = 9_000_000_000 + round(index * 1_000_000_000 / 24)
+ callback = reactor.callbacks["video"]
+ reactor.callbacks["video"] = lambda data, w, h, fid, pts, ud: callback(data, w, h, fid, 0, ud)
+ original(index, size)
+ reactor.callbacks["video"] = callback
+
+ reactor.frame = frame
+
+ async def encode(*command, **kwargs):
+ video = Path(command[command.index("-i") + 1]).read_bytes()
+ self.assertEqual(video[:16], bytes(16))
+ self.assertGreater(len(set(video[::16])), 100)
+ self.output.write_bytes(b"example-mp4")
+ return SimpleNamespace(returncode=0, wait=AsyncMock(return_value=0))
+
+ with patch.object(self.runner.time, "monotonic_ns", side_effect=lambda: clock[0]):
+ await self.run_capture(reactor, AsyncMock(side_effect=encode))
+
+ async def test_invalid_buffers_fail_without_encoding_even_when_an_integer_matches_the_size(self):
+ for buffer in (16, bytes(15), bytes(20)):
+ with self.subTest(buffer=type(buffer).__name__):
+ reactor = FakeReactor()
+ reactor.frame = lambda index, size=(2, 2): reactor.callbacks["video"](buffer, 2, 2, index, 0, None)
+ spawn = AsyncMock()
+ with self.assertRaisesRegex(RuntimeError, "Invalid Reactor video frame buffer"):
+ await self.run_capture(reactor, spawn)
+ spawn.assert_not_awaited()
+ self.assertTrue(reactor.disconnected)
+
async def test_invalid_request_never_constructs_a_session(self):
with patch.object(self.runner, "Reactor") as factory:
for change in ({"prompt": ""}, {"seconds": float("nan")}, {"sourceImagePath": str(Path(self.temp.name) / "missing.png")}):
diff --git a/server/services/videoGen/reactor.js b/server/services/videoGen/reactor.js
index 21a6603a21..6aaf8d865d 100644
--- a/server/services/videoGen/reactor.js
+++ b/server/services/videoGen/reactor.js
@@ -16,6 +16,8 @@ import {
REACTOR_MIN_CLIP_SECONDS, REACTOR_MAX_CLIP_SECONDS, REACTOR_DEFAULT_CLIP_LENGTH,
REACTOR_ASPECTS, reactorCanvas,
} from '../../lib/reactorVideoClip.js';
+import { extractEvaluationFrames } from '../../lib/ffmpeg.js';
+import { describeFrameStats, isDegenerateFrame } from '../../lib/imageFrameStats.js';
import { prepareReactorStartingFrame } from '../../lib/reactorStartingFrame.js';
export const REACTOR_API_BASE = 'https://api.reactor.inc';
@@ -168,7 +170,8 @@ function captureClip(entry, input, pythonPath, job, jobId) {
try {
const message = JSON.parse(line);
if (message.type === 'complete' && typeof message.clipId === 'string' && Number.isFinite(message.seconds)) complete = message;
- if (message.type === 'error' && /^[a-z]+$/.test(message.phase) && /^[A-Za-z]+$/.test(message.errorType)) failure = new Error(`Reactor ${message.phase} failed (${message.errorType})`);
+ if (message.type === 'error' && message.code === 'INVALID_FRAME_BUFFER') failure = new Error('Reactor supplied an invalid video frame buffer; expected width × height × 4 bytes');
+ if (!failure && message.type === 'error' && /^[a-z]+$/.test(message.phase) && /^[A-Za-z]+$/.test(message.errorType)) failure = new Error(`Reactor ${message.phase} failed (${message.errorType})`);
if (message.type === 'status') {
if (typeof message.message === 'string' && /^Captured [0-9.]+ of [0-9.]+ frames; audio=(True|False)$/.test(message.message)) console.log(`🎬 ${message.message}`);
broadcastSse(job, { type: 'status', message: 'Reactor session rendering…' });
@@ -277,6 +280,16 @@ async function runReactorVideo(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');
+ const samples = await extractEvaluationFrames(outputPath, `${jobId}-capture`, 5);
+ try {
+ const verdicts = await Promise.all(samples.map((name) => describeFrameStats(join(PATHS.videoThumbnails, name))));
+ if (verdicts.length && verdicts.every(isDegenerateFrame)) {
+ throw new Error(`Reactor streamed ${result.frames ?? Math.round(result.seconds * 24)} frames but every sampled frame was blank`);
+ }
+ } finally {
+ await Promise.all(samples.map((name) => rm(join(PATHS.videoThumbnails, name), { force: true }).catch(() => {})));
+ }
+ if (entry.aborted) return finalizeCanceled(job, jobId);
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) {
diff --git a/server/services/videoGen/reactor.test.js b/server/services/videoGen/reactor.test.js
index cbdf090aba..40e65e7629 100644
--- a/server/services/videoGen/reactor.test.js
+++ b/server/services/videoGen/reactor.test.js
@@ -5,13 +5,14 @@ import { join } from 'path';
import { tmpdir } from 'os';
const root = join(tmpdir(), `reactor-test-${process.pid}`);
-const mocks = vi.hoisted(() => ({ spawn: vi.fn(), finalize: vi.fn(), settings: vi.fn() }));
+const mocks = vi.hoisted(() => ({ spawn: vi.fn(), finalize: vi.fn(), settings: vi.fn(), samples: vi.fn() }));
vi.mock('../../lib/childProcess.js', async (importOriginal) => ({ ...await importOriginal(), spawn: mocks.spawn }));
+vi.mock('../../lib/ffmpeg.js', () => ({ extractEvaluationFrames: mocks.samples }));
vi.mock('./generateVideoHelpers.js', () => ({ finalizeGeneratedVideo: mocks.finalize }));
vi.mock('../settings.js', () => ({ getSettings: mocks.settings }));
vi.mock('../../lib/fileUtils.js', async () => {
const actual = await vi.importActual('../../lib/fileUtils.js');
- return { ...actual, PATHS: { ...actual.PATHS, videos: join(root, 'videos'), data: root }, ensureDir: (dir) => mkdir(dir, { recursive: true }) };
+ return { ...actual, PATHS: { ...actual.PATHS, videos: join(root, 'videos'), videoThumbnails: root, data: root }, ensureDir: (dir) => mkdir(dir, { recursive: true }) };
});
const reactor = await import('./reactor.js');
const { videoGenEvents } = await import('./events.js');
@@ -25,6 +26,7 @@ beforeEach(async () => {
vi.stubEnv('REACTOR_PYTHON_PATH', join(root, 'python'));
vi.stubEnv('REACTOR_API_KEY', '');
mocks.settings.mockResolvedValue(settings);
+ mocks.samples.mockResolvedValue([]);
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ jwt: 'example-jwt' }) })));
mocks.spawn.mockImplementation(() => {
child = new EventEmitter();
@@ -63,6 +65,40 @@ describe('Reactor SDK adapter', () => {
await vi.waitFor(() => expect(mocks.finalize).toHaveBeenCalledWith(expect.objectContaining({ jobId: job.jobId, meta: expect.objectContaining({ clipId: 'clip-example', seconds: 6 }) })));
});
+ it('rejects all blank samples before history publication and removes the output', async () => {
+ const sharp = (await import('sharp')).default;
+ await sharp({ create: { width: 32, height: 32, channels: 3, background: '#000000' } }).png().toFile(join(root, 'blank.png'));
+ mocks.samples.mockResolvedValue(Array(5).fill('blank.png'));
+ await started();
+ await writeFile(input.outputPath, 'example-video');
+ const failed = once(videoGenEvents, 'failed');
+ child.stdout.emit('data', Buffer.from('{"type":"complete","clipId":"clip-example","seconds":6,"frames":116}\n'));
+ child.emit('close', 0);
+ const [event] = await failed;
+ expect(event.error).toContain('Reactor streamed 116 frames but every sampled frame was blank');
+ expect(mocks.finalize).not.toHaveBeenCalled();
+ await expect(stat(input.outputPath)).rejects.toBeTruthy();
+ await expect(stat(join(root, 'blank.png'))).rejects.toBeTruthy();
+ });
+
+ it.each(['dark-content', 'unmeasurable'])('accepts a black opening when a later sample is %s', async (kind) => {
+ const sharp = (await import('sharp')).default;
+ await sharp({ create: { width: 32, height: 32, channels: 3, background: '#000000' } }).png().toFile(join(root, 'blank.png'));
+ const later = join(root, 'later.png');
+ if (kind === 'unmeasurable') await writeFile(later, 'undecodable');
+ else {
+ const pixels = Buffer.from(Array.from({ length: 32 * 32 * 3 }, (_, i) => Math.floor(i / 3) % 8));
+ await sharp(pixels, { raw: { width: 32, height: 32, channels: 3 } }).png().toFile(later);
+ }
+ mocks.samples.mockResolvedValue(['blank.png', 'blank.png', 'later.png', 'blank.png', 'blank.png']);
+ await started();
+ 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).toHaveBeenCalledOnce());
+ expect(mocks.samples).toHaveBeenCalledWith(input.outputPath, expect.stringContaining('-capture'), 5);
+ });
+
it('rejects unsupported requests before minting or spending', async () => {
for (const options of [
{ prompt: 'x'.repeat(801) },