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(video gen): show a provider round trip, not local weight loading, for cloud renders

Adam Eivycc864a877783
diff --git a/client/src/components/videoGen/RenderStatusCard.jsx b/client/src/components/videoGen/RenderStatusCard.jsx
index 9d24a4d82e..fbc5767cfb 100644
--- a/client/src/components/videoGen/RenderStatusCard.jsx
+++ b/client/src/components/videoGen/RenderStatusCard.jsx
@@ -12,7 +12,10 @@
* conditioning still to say something a status line says better.
*
* Three things a stalled-looking render needs and a percentage can't give:
- * - the named step it is on, drawn from the runner's own STAGE: markers;
+ * - the named step it is on, drawn from the runner's own STAGE: markers —
+ * or, when `remote` says an external provider owns the render, from the
+ * much shorter submit / render / fetch round trip that is all this machine
+ * can actually observe;
* - elapsed wall clock, so "silent" is visibly distinct from "stuck";
* - the display-sleep warning, BEFORE the screen goes dark. An MLX render
* sleeps the display on purpose (the Apple GPU watchdog panics when
@@ -54,8 +57,9 @@ export default function RenderStatusCard({
error = null,
startedAt = null,
sleepsDisplay = false,
+ remote = false,
}) {
- const { steps, activeId } = resolveVideoRenderSteps({ generating, phase, progressPct });
+ const { steps, activeId } = resolveVideoRenderSteps({ generating, phase, progressPct, remote });
return (
<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-3">
diff --git a/client/src/components/videoGen/RenderStatusCard.test.jsx b/client/src/components/videoGen/RenderStatusCard.test.jsx
index d9cec00f89..d3890deef3 100644
--- a/client/src/components/videoGen/RenderStatusCard.test.jsx
+++ b/client/src/components/videoGen/RenderStatusCard.test.jsx
@@ -38,6 +38,20 @@ describe('RenderStatusCard', () => {
expect(screen.getByTestId('render-step-queued')).toHaveAttribute('data-state', 'active');
});
+ // reactor.inc / Grok / fal.ai render on the provider's hardware, so the local
+ // ladder's weight-download and model-load steps describe work that never
+ // happens here — and with no local STAGE: markers to advance it, the card sat
+ // on "Loading model" for the whole render and then jumped straight to done.
+ it('shows the provider round trip, not the local weight/model steps, for a cloud render', () => {
+ render(<RenderStatusCard generating remote statusMsg="Reactor session rendering…" phase="render" />);
+
+ expect(screen.queryByTestId('render-step-download')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('render-step-load')).not.toBeInTheDocument();
+ expect(screen.getByTestId('render-step-submit')).toHaveAttribute('data-state', 'done');
+ expect(screen.getByTestId('render-step-render')).toHaveAttribute('data-state', 'active');
+ expect(screen.getByTestId('render-step-fetch')).toHaveAttribute('data-state', 'pending');
+ });
+
it('shows the error instead of the step list when a render fails', () => {
render(<RenderStatusCard generating={false} error="Runner exited with code 1" />);
expect(screen.getByText('Runner exited with code 1')).toBeInTheDocument();
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 3a0842dd73..b22360f2b8 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -92,7 +92,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `videoGenResolutions.js` | Shared resolution presets/default for video generation, model-specific preset/default resolvers (for native canvases such as MiniMax H3), and `snapAspectToImage()` to pick the closest-aspect preset for an I2V source. |
| `videoGenSubmission.js` | Builds the local, Grok, and federated video-generation request bodies from validated form state, including prompt envelopes and empty-value wire sentinels. |
| `videoReferenceModes.js` | Re-export of `server/lib/videoReferenceModes.js` — the i2v reference-mode vocabulary and its per-mode rules. |
-| `videoRenderPhase.js` | Video render phase → named progress step (#5872). `resolveVideoRenderSteps({ generating, phase, progressPct })` → `{ activeId, steps: [{ id, label, state: 'done'|'active'|'pending' }] }`, collapsing the runners' fine-grained `STAGE:` vocabulary (`load-transformer`, `encode-prompt`, `sampling`, `mux`, …) onto six steps a person can read — the queue's own `queued` is one of them, so a caller needs no separate flag. Family prefixes (`download-*`, `load-*`, `wan-*`, …) absorb markers a future runner adds; `videoRenderStepFor(phase)` returns `null` for a genuinely unknown one, never step 0. Consumed by `components/videoGen/RenderStatusCard.jsx`. |
+| `videoRenderPhase.js` | Video render phase → named progress step (#5872). `resolveVideoRenderSteps({ generating, phase, progressPct, remote })` → `{ activeId, steps: [{ id, label, state: 'done'|'active'|'pending' }] }`, collapsing the runners' fine-grained `STAGE:` vocabulary (`load-transformer`, `encode-prompt`, `sampling`, `mux`, …) onto six steps a person can read — the queue's own `queued` is one of them, so a caller needs no separate flag. Family prefixes (`download-*`, `load-*`, `wan-*`, …) absorb markers a future runner adds; `videoRenderStepFor(phase, { remote })` returns `null` for a genuinely unknown one, never step 0. `remote: true` swaps in the four-step provider ladder (`REMOTE_VIDEO_RENDER_STEPS`: queued → submit → render → fetch) for a render an external API owns, where the local weight/load/encode steps describe work this machine never does. Consumed by `components/videoGen/RenderStatusCard.jsx`. |
| `videoTilingOptions.js` | `VIDEO_TILING_OPTIONS` (the `<select>` rows), `VIDEO_TILING_ENUM_SET` (the value-only Set), and `normalizeVideoTiling` (omit legacy/unknown values). Single source consumed by `VideoGen.jsx`, saved-video normalization, and Remix/requeue callers. Mirrors the server's `z.enum` in `server/routes/videoGen.js`. |
## Graph & sim
diff --git a/client/src/lib/videoRenderPhase.js b/client/src/lib/videoRenderPhase.js
index 727e689dcc..6568599486 100644
--- a/client/src/lib/videoRenderPhase.js
+++ b/client/src/lib/videoRenderPhase.js
@@ -14,6 +14,12 @@
* list of steps a person can actually read, so the UI can say "Loading model —
* step 2 of 5" instead of nothing. Pure: the caller owns every input.
*
+ * External provider backends (Grok, fal.ai, reactor.inc) get their own, shorter
+ * ladder: they render on someone else's hardware, so every local step below the
+ * handover describes work that never happens here — and with none of those
+ * markers able to arrive, the card pinned "Loading model" from submit to
+ * completion. See REMOTE_VIDEO_RENDER_STEPS.
+ *
* The step list is deliberately coarse. Runners disagree on how finely they
* subdivide their work (`load-transformer` / `load-text-encoder` /
* `from-pretrained` / `move-to-device` are all one wait as far as the user is
@@ -31,7 +37,21 @@ export const VIDEO_RENDER_STEPS = Object.freeze([
{ id: 'finalize', label: 'Decoding and saving' },
].map(Object.freeze));
-const STEP_INDEX = Object.fromEntries(VIDEO_RENDER_STEPS.map((step, index) => [step.id, index]));
+/**
+ * Ordered coarse steps for a render this machine does not run: an external
+ * provider API (Grok, fal.ai, reactor.inc). The provider owns the weights, the
+ * sampler and the encode, so the local ladder above describes work that never
+ * happens here — and because none of its markers can ever arrive, the card used
+ * to sit on "Loading model" from submit to completion and then jump straight to
+ * done. What a caller CAN observe is the round trip: hand the job over, wait for
+ * the provider to render it, pull the finished file back.
+ */
+export const REMOTE_VIDEO_RENDER_STEPS = Object.freeze([
+ { id: 'queued', label: 'Queued' },
+ { id: 'submit', label: 'Submitting' },
+ { id: 'render', label: 'Rendering' },
+ { id: 'fetch', label: 'Downloading result' },
+].map(Object.freeze));
// Exact runner `STAGE:` id → coarse step, for the markers that carry no useful
// family prefix. Keys are what the helpers under `scripts/` actually emit (grep
@@ -103,36 +123,62 @@ const PHASE_PREFIX_STEP = Object.freeze([
['wan-', 'render'],
]);
+// Provider phase → remote step. The cloud lanes in server/services/videoGen/
+// emit `submit` / `render` / `fetch` (CLOUD_RENDER_PHASE) on their status
+// frames, plus the queue's own `queued`; the few one-word synonyms beside them
+// spare a future lane from matching the vocabulary letter for letter.
+// Deliberately NOT merged into PHASE_STEP: `download` means "streaming weights
+// onto this GPU" there and "pulling the finished clip back" here, so one table
+// would have to answer both and no single answer is right.
+const REMOTE_PHASE_STEP = Object.freeze(Object.assign(Object.create(null), {
+ queued: 'queued',
+ submit: 'submit',
+ submitting: 'submit',
+ render: 'render',
+ rendering: 'render',
+ fetch: 'fetch',
+ download: 'fetch',
+}));
+
/**
* The coarse step a runner phase belongs to, or `null` when the phase is
* unrecognized. Case-insensitive because BYOV helpers are not required to agree
* on capitalization (the server normalizes STAGE tags the same way).
+ *
+ * `remote: true` resolves against the provider ladder instead — a render an
+ * external API owns speaks a different, much shorter vocabulary.
*/
-export function videoRenderStepFor(phase) {
+export function videoRenderStepFor(phase, { remote = false } = {}) {
if (typeof phase !== 'string' || !phase) return null;
// Null-prototype lookup (see PHASE_STEP): a runner is free to emit
// `STAGE:constructor`, and on a plain object literal that would resolve to
// `Object` and hand the caller a step id no list contains.
const id = phase.toLowerCase();
+ if (remote) return REMOTE_PHASE_STEP[id] || null;
if (PHASE_STEP[id]) return PHASE_STEP[id];
return PHASE_PREFIX_STEP.find(([prefix]) => id.startsWith(prefix))?.[1] || null;
}
// One frozen step list per possible active step, plus the all-pending list.
// `resolveVideoRenderSteps` is called on every render of a page that re-renders
-// on each keystroke and each SSE frame, and there are only seven answers — so
-// they are built once at import and shared, which also gives callers a stable
-// identity to memo on.
-const STEPS_BY_ACTIVE_ID = Object.freeze(Object.fromEntries(
- [null, ...VIDEO_RENDER_STEPS.map((step) => step.id)].map((activeId) => [
- String(activeId),
- Object.freeze(VIDEO_RENDER_STEPS.map((step, index) => Object.freeze({
- ...step,
- state: index === STEP_INDEX[activeId] ? 'active'
- : index < STEP_INDEX[activeId] ? 'done' : 'pending',
- }))),
- ]),
-));
+// on each keystroke and each SSE frame, and there is only a handful of answers
+// per ladder — so they are built once at import and shared, which also gives
+// callers a stable identity to memo on.
+const stepsByActiveId = (steps) => {
+ const stepIndex = Object.fromEntries(steps.map((step, index) => [step.id, index]));
+ return Object.freeze(Object.fromEntries(
+ [null, ...steps.map((step) => step.id)].map((activeId) => [
+ String(activeId),
+ Object.freeze(steps.map((step, index) => Object.freeze({
+ ...step,
+ state: index === stepIndex[activeId] ? 'active'
+ : index < stepIndex[activeId] ? 'done' : 'pending',
+ }))),
+ ]),
+ ));
+};
+const STEPS_BY_ACTIVE_ID = stepsByActiveId(VIDEO_RENDER_STEPS);
+const REMOTE_STEPS_BY_ACTIVE_ID = stepsByActiveId(REMOTE_VIDEO_RENDER_STEPS);
/**
* Project a render's live state onto the step list.
@@ -143,18 +189,23 @@ const STEPS_BY_ACTIVE_ID = Object.freeze(Object.fromEntries(
* runner that reports numeric progress is rendering even if its phase marker
* never arrived.
*
+ * `remote` selects the provider ladder (REMOTE_VIDEO_RENDER_STEPS) for a render
+ * an external API owns. Its silent default is `submit`, not `load`: nothing is
+ * loading on this machine, and the job has demonstrably been handed over.
+ *
* Returns `{ steps, activeId }` where each step carries `state`:
* `'done' | 'active' | 'pending'`. `activeId` is `null` only when there is
* nothing to show (not generating).
*/
-export function resolveVideoRenderSteps({ generating = false, phase = null, progressPct = null } = {}) {
+export function resolveVideoRenderSteps({ generating = false, phase = null, progressPct = null, remote = false } = {}) {
+ const byActiveId = remote ? REMOTE_STEPS_BY_ACTIVE_ID : STEPS_BY_ACTIVE_ID;
// Order of preference: an explicit phase, then "the sampler is visibly
// running", then the honest default for a render that has started but told us
- // nothing yet — which is loading, not rendering.
+ // nothing yet — which is loading, or, on the provider ladder, submitting.
const activeId = !generating ? null
- : videoRenderStepFor(phase)
- || (Number.isFinite(progressPct) && progressPct > 0 ? 'render' : 'load');
- // `?? STEPS_BY_ACTIVE_ID.null` so an id outside the step list can never hand
- // the caller `undefined` to map over.
- return { activeId, steps: STEPS_BY_ACTIVE_ID[String(activeId)] ?? STEPS_BY_ACTIVE_ID.null };
+ : videoRenderStepFor(phase, { remote })
+ || (Number.isFinite(progressPct) && progressPct > 0 ? 'render' : (remote ? 'submit' : 'load'));
+ // `?? byActiveId.null` so an id outside the step list can never hand the
+ // caller `undefined` to map over.
+ return { activeId, steps: byActiveId[String(activeId)] ?? byActiveId.null };
}
diff --git a/client/src/lib/videoRenderPhase.test.js b/client/src/lib/videoRenderPhase.test.js
index 4b46280812..424f6bde85 100644
--- a/client/src/lib/videoRenderPhase.test.js
+++ b/client/src/lib/videoRenderPhase.test.js
@@ -94,3 +94,44 @@ describe('resolveVideoRenderSteps', () => {
expect(activeLabel(resolveVideoRenderSteps({ generating: true, progressPct: 0 }))).toBe('Loading model');
});
});
+
+// The reported bug: a reactor.inc / Grok / fal.ai render is done on someone
+// else's hardware, so none of the local STAGE: markers can ever arrive — the
+// card sat on "Loading model" (with "Downloading weights" ticked off as though
+// this machine had streamed a checkpoint) from submit until the clip appeared.
+describe('resolveVideoRenderSteps on the provider ladder', () => {
+ it('drops the local weight/encode steps a provider render never performs', () => {
+ const { steps } = resolveVideoRenderSteps({ generating: true, remote: true });
+ expect(steps.map((s) => s.label))
+ .toEqual(['Queued', 'Submitting', 'Rendering', 'Downloading result']);
+ });
+
+ it('defaults a started-but-silent provider render to submitting, not loading', () => {
+ expect(activeLabel(resolveVideoRenderSteps({ generating: true, remote: true }))).toBe('Submitting');
+ });
+
+ it('advances through the provider round trip', () => {
+ const at = (phase) => activeLabel(resolveVideoRenderSteps({ generating: true, remote: true, phase }));
+ expect(at('queued')).toBe('Queued');
+ expect(at('submit')).toBe('Submitting');
+ expect(at('render')).toBe('Rendering');
+ expect(at('fetch')).toBe('Downloading result');
+ });
+
+ // `download` is the one id both ladders claim, and it means opposite things:
+ // weights arriving on this GPU locally, the finished clip arriving here
+ // remotely. Reading it against the wrong ladder would put a provider render
+ // back near the start of its list.
+ it('reads a shared phase id against the ladder it was asked for', () => {
+ expect(videoRenderStepFor('download')).toBe('download');
+ expect(videoRenderStepFor('download', { remote: true })).toBe('fetch');
+ });
+
+ it('returns null for a local-only marker rather than guessing a provider step', () => {
+ expect(videoRenderStepFor('load-transformer', { remote: true })).toBeNull();
+ expect(videoRenderStepFor('constructor', { remote: true })).toBeNull();
+ // …and an unmappable phase still falls back to the ladder's own default.
+ expect(activeLabel(resolveVideoRenderSteps({ generating: true, remote: true, phase: 'load-transformer' })))
+ .toBe('Submitting');
+ });
+});
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index e59da76bef..7278d1e1cc 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -320,6 +320,16 @@ export default function VideoGen() {
&& !remoteTarget.isRemote && !isGrok && !isFal && !isReactor;
const rendersSleepDisplay = canSleepDisplay && displaySleepEnabled;
+ // Does an external provider API own this render? Its weights, sampler and
+ // encoder are all on the far side of an HTTP call, so the local STAGE: ladder
+ // (download weights → load model → encode → sample → mux) describes work this
+ // machine never does and no marker ever lands on — which left the status card
+ // pinned on "Loading model" for the whole render. The status card swaps in the
+ // short submit / render / fetch ladder instead. A federated PEER is
+ // deliberately excluded: it really does load the weights and run the sampler,
+ // it just does so out of view.
+ const rendersOffMachine = isGrok || isFal || isReactor;
+
// Every gallery-image slot on this page (both frame panels, each multi-keyframe
// row, each IC-LoRA reference row) opens the SAME GalleryImagePicker modal the
// Image Gen i2i form uses — a searchable thumbnail grid over the whole gallery.
@@ -1899,6 +1909,7 @@ export default function VideoGen() {
error={error}
startedAt={renderStartedAt}
sleepsDisplay={rendersSleepDisplay}
+ remote={rendersOffMachine}
/>
<MediaJobsQueue kind="video" />
diff --git a/server/services/videoGen/fal.js b/server/services/videoGen/fal.js
index 44f01ee9d3..41bdfc32c0 100644
--- a/server/services/videoGen/fal.js
+++ b/server/services/videoGen/fal.js
@@ -25,7 +25,7 @@ import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';
import { detectImageFormat } from '../../lib/mimeTypes.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
import { videoGenEvents } from './events.js';
-import { finalizeGeneratedVideo } from './generateVideoHelpers.js';
+import { finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';
import { mutateVideoHistory } from './history.js';
import { getSettings } from '../settings.js';
import { nearestAspectRatio } from '../imageGen/modes.js';
@@ -204,7 +204,7 @@ export async function generateVideo({
console.log(`🎬 Generating video [${jobId.slice(0, 8)}] fal (${modelId}): ${prompt.slice(0, 60)}…`);
videoGenEvents.emit('started', { generationId: jobId, totalSteps: 1, ...meta });
activeJobs.set(jobId, { ...meta, generationId: jobId, totalSteps: 1, step: 0, progress: 0 });
- broadcastSse(job, { type: 'status', message: 'Submitting to fal.ai…' });
+ emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.SUBMIT, 'Submitting to fal.ai…');
runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePrompt, duration, aspectRatio: effectiveAspectRatio, sourceImagePath, outputPath, filename, meta })
.catch((err) => {
@@ -238,7 +238,11 @@ async function runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePrompt
if (status.status === 'ERROR') {
return finalizeError(job, jobId, `fal.ai render failed: ${status.error || 'unknown error'}`);
}
- broadcastSse(job, { type: 'status', message: status.status === 'IN_PROGRESS' ? 'Rendering…' : 'Queued…' });
+ // fal's own queue maps to SUBMIT rather than to the queued step: the
+ // ladder's `queued` is PortOS's local queue, and stepping back to it
+ // after the handover would read as the render having lost its place.
+ if (status.status === 'IN_PROGRESS') emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.RENDER, 'Rendering…');
+ else emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.SUBMIT, 'Queued at fal.ai…');
await new Promise((r) => setTimeout(r, FAL_POLL_INTERVAL_MS));
}
if (entry.aborted) return finalizeCanceled(job, jobId);
@@ -252,7 +256,7 @@ async function runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePrompt
return finalizeError(job, jobId, 'fal.ai completed but returned no video URL');
}
- broadcastSse(job, { type: 'status', message: 'Downloading video…' });
+ emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.FETCH, 'Downloading video…');
const videoRes = await fetchWithTimeout(videoUrl, {}, FAL_DOWNLOAD_TIMEOUT_MS);
if (!videoRes.ok) {
return finalizeError(job, jobId, `fal.ai video download failed: HTTP ${videoRes.status}`);
diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.js
index eb14492e97..044c03c23b 100644
--- a/server/services/videoGen/generateVideoHelpers.js
+++ b/server/services/videoGen/generateVideoHelpers.js
@@ -89,6 +89,21 @@ export function formatDownloadMessage(rawText, byteInfo) {
export const PROMPT_ENCODE_BEGIN_MARKER = 'STAGE:encode-prompt';
export const PROMPT_ENCODE_END_MARKER = 'STAGE:encode-prompt-done';
+/**
+ * A render status line goes out on BOTH wires, always: the videoGen job's own
+ * SSE stream, and `videoGenEvents` for the mediaJobQueue dispatcher to forward
+ * to the page's stream. Publishing on one alone is the bug this collapses —
+ * the cloud lanes broadcast only on the first, so the Video Gen page saw
+ * nothing between "Starting render…" and completion.
+ *
+ * `frame` carries the message and the phase (and, for a download line, its byte
+ * counts); the client maps the phase to a named render step.
+ */
+function publishRenderStatus(job, jobId, frame) {
+ broadcastSse(job, { type: 'status', ...frame });
+ videoGenEvents.emit('status', { generationId: jobId, ...frame });
+}
+
/**
* Build the stdout/stderr line handler for one generation. Parses the
* python child's STATUS:/STAGE:/DOWNLOAD:/tqdm protocol into SSE frames
@@ -114,16 +129,10 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {
// a missed `started` event. Omitted entirely when there is no estimate — an
// absent key, never `etaMs: 0`, which a UI would render as "done".
const etaField = () => (Number.isFinite(job?.etaMs) ? { etaMs: job.etaMs } : {});
- // Every status line goes out twice: on the videoGen job's own SSE stream, and
- // on videoGenEvents for the mediaJobQueue dispatcher to forward to the page's
- // stream. Both carry the phase the last STAGE: marker put us in — the client
- // maps it to a named render step ("Loading model" / "Rendering" / …), and a
- // bare STATUS line is often the ONLY thing a runner emits for minutes at a
- // time, so without the phase it can only be shown as undifferentiated text.
- const emitStatus = (message, extra = {}) => {
- broadcastSse(job, { type: 'status', message, phase: currentPhase, ...extra });
- videoGenEvents.emit('status', { generationId: jobId, message, phase: currentPhase, ...extra });
- };
+ // Carries the phase the last STAGE: marker put us in — a bare STATUS line is
+ // often the ONLY thing a runner emits for minutes at a time, so without the
+ // phase it can only be shown as undifferentiated text.
+ const emitStatus = (message, extra = {}) => publishRenderStatus(job, jobId, { message, phase: currentPhase, ...extra });
return (raw) => {
const line = raw.trim();
@@ -599,3 +608,42 @@ export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename,
}
return thumbnail;
}
+
+/**
+ * The three phases a render owned by an external provider API (Grok, fal.ai,
+ * reactor.inc) actually passes through as far as THIS machine can see. The
+ * provider holds the weights and runs the sampler, so none of the local
+ * `STAGE:` vocabulary applies; the client's `videoRenderPhase.js` maps these
+ * ids onto its short provider step ladder.
+ */
+export const CLOUD_RENDER_PHASE = Object.freeze({
+ /** Handing the job over: runtime prep, auth, the submit call, the provider's own queue. */
+ SUBMIT: 'submit',
+ /** The provider is rendering. */
+ RENDER: 'render',
+ /** Pulling the finished clip back onto this machine. */
+ FETCH: 'fetch',
+});
+
+/**
+ * Publish a cloud-lane status line on BOTH wires: the provider job's own SSE
+ * stream (legacy `/api/video-gen/stream/:id` consumers) and `videoGenEvents`,
+ * which is the only one the media-job queue relays to the Video Gen page. The
+ * cloud lanes used to broadcast on the first alone, so the page saw no status
+ * frame at all between "Starting render…" and completion — and its step list
+ * had no phase to advance on.
+ *
+ * The `activity` heartbeat fires on EVERY call, unconditionally: it is what
+ * keeps the queue watchdog from reaping a provider render that is slow rather
+ * than stuck, and these lanes call this on every stdout chunk (grok) and every
+ * poll tick (fal) precisely because that IS the evidence of life. The line
+ * itself is only re-published when it changed — the same prose repeated every
+ * two seconds tells the user nothing and churns the queue's debounced persist.
+ */
+export function emitCloudRenderStatus(job, jobId, phase, message) {
+ videoGenEvents.emit('activity', { generationId: jobId });
+ const line = `${phase}:${message}`;
+ if (job.cloudStatusLine === line) return;
+ job.cloudStatusLine = line;
+ publishRenderStatus(job, jobId, { message, phase });
+}
diff --git a/server/services/videoGen/generateVideoHelpers.test.js b/server/services/videoGen/generateVideoHelpers.test.js
index aca564588d..13aaa019ac 100644
--- a/server/services/videoGen/generateVideoHelpers.test.js
+++ b/server/services/videoGen/generateVideoHelpers.test.js
@@ -3,7 +3,7 @@ import { writeFileSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { EventEmitter } from 'events';
-import { makeVideoGenLineHandler, isWatchdogSuccess, finalizeGeneratedVideo, parseByteProgress, formatBytes, formatDownloadMessage, describeSignalDeath, formatRuntimeFingerprint, describeRenderConditioning, isPromptEncodingMetalWatchdog, planPromptEncodingRetry, DEFAULT_GEMMA_MAX_LENGTH, RETRY_GEMMA_MAX_LENGTH, bufferChildExit, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';
+import { makeVideoGenLineHandler, isWatchdogSuccess, finalizeGeneratedVideo, parseByteProgress, formatBytes, formatDownloadMessage, describeSignalDeath, formatRuntimeFingerprint, describeRenderConditioning, isPromptEncodingMetalWatchdog, planPromptEncodingRetry, DEFAULT_GEMMA_MAX_LENGTH, RETRY_GEMMA_MAX_LENGTH, bufferChildExit, RENDER_INPUTS_VERSION, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';
describe('parseByteProgress', () => {
it('parses single byte value (e.g., "2.5G")', () => {
@@ -664,3 +664,41 @@ describe('bufferChildExit', () => {
expect(() => proc.emit('error', new Error('abandoned'))).not.toThrow();
});
});
+
+
+// The cloud lanes used to broadcast their status lines on the provider job's
+// own SSE stream ONLY. The Video Gen page listens to the media-job queue, which
+// relays videoGenEvents — so it saw no status frame at all between "Starting
+// render…" and completion, and its step list had no phase to advance on.
+describe('emitCloudRenderStatus', () => {
+ it('publishes the phase on the provider SSE stream and on videoGenEvents', () => {
+ emitted.length = 0;
+ sse.mockClear();
+ const job = { clients: [], status: 'running' };
+
+ emitCloudRenderStatus(job, 'job-1', CLOUD_RENDER_PHASE.RENDER, 'Reactor session rendering…');
+
+ expect(sse).toHaveBeenCalledWith(job, { type: 'status', message: 'Reactor session rendering…', phase: 'render' });
+ expect(emitted).toEqual([
+ { type: 'activity', payload: { generationId: 'job-1' } },
+ { type: 'status', payload: { generationId: 'job-1', message: 'Reactor session rendering…', phase: 'render' } },
+ ]);
+ });
+
+ // grok narrates on every stdout chunk and fal re-reports the same poll status
+ // every couple of seconds. The heartbeat has to land each time (it is what
+ // the idle watchdog reads); the unchanged line does not.
+ it('repeats the heartbeat but not an unchanged line', () => {
+ emitted.length = 0;
+ sse.mockClear();
+ const job = { clients: [], status: 'running' };
+
+ emitCloudRenderStatus(job, 'job-2', CLOUD_RENDER_PHASE.RENDER, 'Running…');
+ emitCloudRenderStatus(job, 'job-2', CLOUD_RENDER_PHASE.RENDER, 'Running…');
+ emitCloudRenderStatus(job, 'job-2', CLOUD_RENDER_PHASE.FETCH, 'Downloading video…');
+
+ expect(emitted.filter((e) => e.type === 'activity')).toHaveLength(3);
+ expect(emitted.filter((e) => e.type === 'status').map((e) => e.payload.phase)).toEqual(['render', 'fetch']);
+ expect(sse).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.js
index 2dc1a69b24..dc6c125b87 100644
--- a/server/services/videoGen/grok.js
+++ b/server/services/videoGen/grok.js
@@ -33,7 +33,7 @@ import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { killProcessTree, prepareCliSpawn } from '../../lib/bufferedSpawn.js';
import { ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../../lib/grok.js';
import { videoGenEvents } from './events.js';
-import { finalizeGeneratedVideo } from './generateVideoHelpers.js';
+import { finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';
import { mutateVideoHistory } from './history.js';
import { noImageReason, deriveAspectRatio, GROK_ASPECT_RATIOS } from '../imageGen/grok.js';
import { resolveGrokDuration } from '../../lib/grokVideoClip.js';
@@ -182,7 +182,7 @@ export async function generateVideo({
console.log(`🎬 Generating video [${jobId.slice(0, 8)}] grok: ${prompt.slice(0, 60)}…`);
videoGenEvents.emit('started', { generationId: jobId, totalSteps: 1, ...meta });
activeJobs.set(jobId, { ...meta, generationId: jobId, totalSteps: 1, step: 0, progress: 0 });
- broadcastSse(job, { type: 'status', message: 'Spawning grok…' });
+ emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.SUBMIT, 'Spawning grok…');
runGrokVideo(job, jobId, bin, args, {
useStdin, fullPrompt, cleanupPromptFile, scratchDir, stagingPath, outputPath, filename, meta, uploadedTempPath,
@@ -244,7 +244,7 @@ async function runGrokVideo(job, jobId, bin, args, {
proc.stdout.on('data', (chunk) => {
stdoutTail += chunk.toString();
if (stdoutTail.length > STDOUT_TAIL_BYTES) stdoutTail = stdoutTail.slice(-STDOUT_TAIL_BYTES);
- broadcastSse(job, { type: 'status', message: 'Running…' });
+ emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.RENDER, 'Running…');
// Feed the mediaJobQueue's idle watchdog — grok narrates while working,
// so a genuinely wedged child stops emitting and still trips the 20-min
// idle cap, while a long-but-active image_to_video render doesn't.
diff --git a/server/services/videoGen/reactor.js b/server/services/videoGen/reactor.js
index 31fbd82e58..9f523a6847 100644
--- a/server/services/videoGen/reactor.js
+++ b/server/services/videoGen/reactor.js
@@ -8,7 +8,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
import { videoGenEvents } from './events.js';
-import { finalizeGeneratedVideo } from './generateVideoHelpers.js';
+import { finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';
import { mutateVideoHistory } from './history.js';
import { getSettings } from '../settings.js';
import {
@@ -175,8 +175,7 @@ function captureClip(entry, input, pythonPath, job, jobId) {
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…' });
- videoGenEvents.emit('activity', { generationId: jobId });
+ emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.RENDER, 'Reactor session rendering…');
}
} catch {
stop('Reactor renderer returned malformed output');
@@ -243,7 +242,7 @@ export async function generateVideo({
console.log(`🎬 Generating video [${jobId.slice(0, 8)}] reactor (${REACTOR_MODEL_ID}): ${prompt.slice(0, 60)}…`);
videoGenEvents.emit('started', { generationId: jobId, totalSteps: 1, ...meta });
activeJobs.set(jobId, { ...meta, generationId: jobId, totalSteps: 1, step: 0, progress: 0 });
- broadcastSse(job, { type: 'status', message: 'Preparing Reactor runtime…' });
+ emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.SUBMIT, 'Preparing Reactor runtime…');
runReactorVideo(job, jobId, {
apiKey, ...request, sourceImagePath, outputPath, filename, meta,
@@ -280,8 +279,7 @@ async function runReactorVideo(job, jobId, {
});
entry.stop = null;
if (entry.aborted) return finalizeCanceled(job, jobId);
- videoGenEvents.emit('activity', { generationId: jobId });
- broadcastSse(job, { type: 'status', message: 'Minting reactor.inc session…' });
+ emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.SUBMIT, 'Minting reactor.inc session…');
const { jwt } = await mintReactorToken(apiKey);
if (entry.aborted) return finalizeCanceled(job, jobId);
const result = await captureClip(entry, {
diff --git a/server/services/videoGen/reactor.test.js b/server/services/videoGen/reactor.test.js
index 6a01ee7695..0421a38142 100644
--- a/server/services/videoGen/reactor.test.js
+++ b/server/services/videoGen/reactor.test.js
@@ -9,7 +9,12 @@ const mocks = vi.hoisted(() => ({ spawn: vi.fn(), finalize: vi.fn(), settings: v
vi.mock('../../lib/childProcess.js', async (importOriginal) => ({ ...await importOriginal(), spawn: mocks.spawn }));
vi.mock('./reactorRuntime.js', () => ({ ensureReactorRuntime: mocks.runtime }));
vi.mock('../../lib/ffmpeg.js', () => ({ extractEvaluationFrames: mocks.samples }));
-vi.mock('./generateVideoHelpers.js', () => ({ finalizeGeneratedVideo: mocks.finalize }));
+// Partial: only the finalize is stubbed. emitCloudRenderStatus is real, so the
+// status/phase frames the Video Gen page reads stay covered by these tests.
+vi.mock('./generateVideoHelpers.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ finalizeGeneratedVideo: mocks.finalize,
+}));
vi.mock('../settings.js', () => ({ getSettings: mocks.settings }));
vi.mock('../../lib/fileUtils.js', async () => {
const actual = await vi.importActual('../../lib/fileUtils.js');