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

address review (codex): stop losing the render geometry to timing, restarts, and chunked renders (#4588)

[._.]/ Adam Eivyd6c46b9fab41
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index c87c814086..6311f32cd3 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -353,8 +353,8 @@ async function persistImpl() {
...archive,
];
// Strip non-serializable bits.
- const serializable = live.map(({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg, etaMs }) =>
- ({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg, etaMs }),
+ const serializable = live.map(({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg, etaMs, render }) =>
+ ({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg, etaMs, render }),
);
await atomicWrite(JOBS_FILE, { jobs: serializable });
}
@@ -713,9 +713,25 @@ function synthesizeMessage(e, kind) {
}
return undefined;
}
+// Two finite positive edges, or nothing. A runner that reports no geometry —
+// or a heartbeat-shaped frame with a zero/NaN edge — must produce NO geometry
+// rather than a ratio the client would have to defend against.
+const renderGeometryOf = (e) => {
+ const width = Number(e.width);
+ const height = Number(e.height);
+ if (!Number.isFinite(width) || width <= 0) return null;
+ if (!Number.isFinite(height) || height <= 0) return null;
+ return { width, height };
+};
+
function makeGenDispatcher(emitter, job, handlers) {
const onProgress = (e) => {
if (e.generationId !== job.id) return;
+ // A CHAINED video render never emits `started` under the queue's job id —
+ // `started` is per-chunk, under ids only the orchestrator knows — so its
+ // resolved geometry rides the outer progress frames instead (#4588).
+ const chainedGeometry = renderGeometryOf(e);
+ if (chainedGeometry) handlers.renderMeta?.(chainedGeometry);
const hasProgress = typeof e.progress === 'number' && Number.isFinite(e.progress);
const hasCurrentImage = typeof e.currentImage === 'string' && e.currentImage.length > 0;
const message = e.message !== undefined ? e.message : synthesizeMessage(e, job.kind);
@@ -756,16 +772,11 @@ function makeGenDispatcher(emitter, job, handlers) {
// submitted. A live preview stage has to size itself by the resolved edges or
// a portrait render renders into a landscape box. The queue's own `started`
// SSE frame is broadcast before the gen run begins and cannot carry this, so
- // it rides its own frame type (#4588). Guarded on two finite positive edges:
- // a runner that reports no geometry emits no frame at all, rather than a
- // zero/NaN ratio the client would have to defend against.
+ // it rides its own frame type (#4588).
const onStarted = (e) => {
if (e.generationId !== job.id) return;
- const width = Number(e.width);
- const height = Number(e.height);
- if (!Number.isFinite(width) || width <= 0) return;
- if (!Number.isFinite(height) || height <= 0) return;
- handlers.renderMeta?.({ width, height });
+ const geometry = renderGeometryOf(e);
+ if (geometry) handlers.renderMeta?.(geometry);
};
const onStatus = (e) => {
// Optional explicit `status` event for gens that want to push a status
@@ -1255,11 +1266,24 @@ function ensureSseEntry(jobId) {
// 3. Terminal job after the grace window — entry is gone; we synthesize a
// one-shot terminal frame from the archived job and end the stream so
// a late client doesn't hang on an empty SSE stream forever.
+// A client attaching to a live job also needs the render's resolved geometry
+// (#4588), and it cannot come from the replay slot: that slot holds exactly one
+// frame and must hold the one that says what the run is DOING. The geometry is
+// announced once, very early — routinely before the submitting page's
+// EventSource has even opened — so replay it from the job to each client as it
+// attaches instead of retaining it on the wire.
+const replayRenderMeta = (job, res) => {
+ if (!job.render) return;
+ res.write(`data: ${JSON.stringify({ type: 'render-meta', ...job.render })}\n\n`);
+};
+
export function attachSseClient(jobId, res) {
const job = findJob(jobId);
if (!job) return false;
if (sseJobs.has(jobId)) {
- return attachSse(sseJobs, jobId, res);
+ const attached = attachSse(sseJobs, jobId, res);
+ if (attached) replayRenderMeta(job, res);
+ return attached;
}
// No SSE entry but the job is still live (queued/running) — the entry was
// dropped or never created (e.g. crash recovery). Create one on the fly
@@ -1273,7 +1297,9 @@ export function attachSseClient(jobId, res) {
? { type: 'queued', position: job.position }
: { type: 'started', kind: job.kind };
broadcastSse(entry, heartbeat);
- return attachSse(sseJobs, jobId, res);
+ const attached = attachSse(sseJobs, jobId, res);
+ if (attached) replayRenderMeta(job, res);
+ return attached;
}
// Terminal job whose SSE entry was already cleaned up. Synthesize the
// expected terminal payload from the archived state and end immediately.
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index cdc404315a..48a4974457 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -434,10 +434,37 @@ describe('mediaJobQueue', () => {
videoGenEvents.emit('progress', { generationId: job.jobId, progress: 0.25 });
await waitFor(() => frames.some((f) => f.type === 'progress'));
+ // A client that attaches AFTER the geometry was announced (the normal case
+ // — the geometry lands before the submitting page's EventSource is even
+ // open) still gets it, replayed from the job rather than from the single
+ // retained slot, which keeps holding the frame that says what the run is
+ // doing.
const replayed = [];
expect(mediaJobQueue.attachSseClient(job.jobId, makeRes(replayed))).toBe(true);
- expect(replayed).toHaveLength(1);
+ expect(replayed).toHaveLength(2);
expect(replayed[0]).toMatchObject({ type: 'progress', progress: 0.25 });
+ expect(replayed[1]).toEqual({ type: 'render-meta', width: 704, height: 480 });
+
+ // A chained render emits `started` per CHUNK, under ids the queue ignores,
+ // so its geometry rides the outer progress frames instead — same handler,
+ // same dedupe, no second frame for an unchanged geometry.
+ videoGenEvents.emit('progress', { generationId: job.jobId, progress: 0.3, width: 704, height: 480 });
+ videoGenEvents.emit('progress', { generationId: job.jobId, progress: 0.4, width: 1280, height: 704 });
+ await waitFor(() => frames.filter((f) => f.type === 'render-meta').length === 2);
+ expect(frames.filter((f) => f.type === 'render-meta').at(-1))
+ .toEqual({ type: 'render-meta', width: 1280, height: 704 });
+ expect(mediaJobQueue.getJob(job.jobId).render).toEqual({ width: 1280, height: 704 });
+
+ // Restore the original geometry for the persistence assertion below.
+ videoGenEvents.emit('progress', { generationId: job.jobId, progress: 0.5, width: 704, height: 480 });
+ await waitFor(() => mediaJobQueue.getJob(job.jobId).render?.width === 704);
+
+ // Survives a server restart too — the geometry is part of the persisted
+ // projection, not just in-memory state.
+ await waitFor(() => {
+ const data = JSON.parse(readFileSync(join(tempDataDir, 'media-jobs.json'), 'utf-8'));
+ return data.jobs.find((j) => j.id === job.jobId)?.render?.width === 704;
+ });
videoGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.mp4` });
await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'completed');
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index ea0537291e..d5901c1907 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -2321,6 +2321,12 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
// Chunks 1+ take the resolved continuity path instead.
const firstMode = rest.mode || (currentSource ? 'image' : 'text');
+ // The geometry the chunks actually render at, learned from the first chunk's
+ // own `started` (see onChunkStarted below). `null` until then — an explicit
+ // "not reported yet", so the outer progress frames omit the keys entirely
+ // rather than carrying a placeholder.
+ let chainGeometry = null;
+
const runChunk = (i) => new Promise((resolve, reject) => {
const innerJobId = randomUUID();
chunkIds.push(innerJobId);
@@ -2337,6 +2343,10 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
// Chain-level estimate, NOT the inner chunk's — the outer id's
// consumers are watching the whole chain's clock.
...chainEtaField,
+ // Resolved geometry (#4588), recorded from the chunk's own `started`.
+ // Additive + presence-guarded, like `etaMs` above: absent until a chunk
+ // has reported it, never a zero the UI would size a stage by.
+ ...(chainGeometry || {}),
});
broadcastSse(outerJob, {
type: 'progress',
@@ -2344,7 +2354,21 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
message: `Chunk ${i + 1}/${totalChunks}`,
});
};
+ // A chained render never announces its own geometry: `started` is emitted
+ // per CHUNK, under an inner id nothing outside this function knows, and the
+ // outer id never gets a `started` at all. Record the chunk's RESOLVED edges
+ // here and let the outer `progress` frames carry them, so a chunked render
+ // sizes its preview stage the same way a single-shot one does (#4588). The
+ // chunk's other `started` fields are deliberately NOT forwarded — its
+ // `totalSteps` is not the chain's — and no synthetic outer `started` is
+ // emitted, because consumers read that event as "the run begins".
+ const onChunkStarted = (e) => {
+ if (e.generationId !== innerJobId) return;
+ if (!Number.isFinite(e.width) || !Number.isFinite(e.height)) return;
+ chainGeometry = { width: e.width, height: e.height };
+ };
const detach = () => {
+ videoGenEvents.off('started', onChunkStarted);
videoGenEvents.off('progress', onProgress);
videoGenEvents.off('completed', onCompleted);
videoGenEvents.off('failed', onFailed);
@@ -2359,6 +2383,7 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
detach();
reject(new Error(e.error || 'chunk failed'));
};
+ videoGenEvents.on('started', onChunkStarted);
videoGenEvents.on('progress', onProgress);
videoGenEvents.on('completed', onCompleted);
videoGenEvents.on('failed', onFailed);
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 9841c0eaa3..3b75a2201a 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -1111,6 +1111,68 @@ describe('generateChainedVideo — continuation strategy (context window vs last
});
});
+describe('generateChainedVideo — resolved geometry on the outer frames (#4588)', () => {
+ it('carries the chunk geometry on the chain progress frames without a synthetic outer started', async () => {
+ const { readJSONFile } = await import('../../lib/fileUtils.js');
+ const outerJobId = randomUUID();
+ const innerJobIds = [];
+ const startedIds = [];
+ const outerProgress = [];
+ const onStarted = (e) => {
+ startedIds.push(e.generationId);
+ if (e.generationId === outerJobId) return;
+ innerJobIds.push(e.generationId);
+ // Feed the live chunk a progress frame from a microtask: the chain's own
+ // `started` listener is registered AFTER this one, so it has to run (and
+ // record the geometry) before the progress frame goes out — and a
+ // microtask still lands before the chunk's first awaited I/O, while its
+ // per-chunk listeners are attached.
+ queueMicrotask(() => {
+ videoGenEvents.emit('progress', { generationId: e.generationId, progress: 0.5, step: 5, totalSteps: 10 });
+ });
+ };
+ const onProgress = (e) => { if (e.generationId === outerJobId) outerProgress.push(e); };
+ vi.mocked(readJSONFile).mockImplementation(async () =>
+ innerJobIds.map((id) => ({ id, filename: `${id}.mp4` })),
+ );
+ videoGenEvents.on('started', onStarted);
+ videoGenEvents.on('progress', onProgress);
+
+ generateChainedVideo({
+ chunks: 2,
+ jobId: outerJobId,
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'a chained render',
+ width: 512,
+ height: 512,
+ numFrames: 25,
+ fps: 24,
+ });
+
+ const deadline = Date.now() + 5000;
+ while (outerProgress.length === 0 && Date.now() < deadline) {
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((r) => setTimeout(r, 10));
+ }
+
+ expect(outerProgress[0]).toMatchObject({
+ generationId: outerJobId, width: 512, height: 512, step: 5, totalSteps: 10,
+ });
+ // No synthetic `started` under the outer id: consumers read that event as
+ // "the run begins", and a chain fires one per chunk.
+ expect(startedIds).not.toContain(outerJobId);
+
+ for (const id of [...innerJobIds]) {
+ videoGenEvents.emit('completed', { generationId: id, filename: `${id}.mp4`, path: `/data/videos/${id}.mp4` });
+ }
+ await waitForStitch();
+
+ videoGenEvents.off('started', onStarted);
+ videoGenEvents.off('progress', onProgress);
+ });
+});
+
describe('generateChainedVideo — per-chunk prompt beats (#3695)', () => {
/**
* Drive a text chain of `totalChunks` and return the `--prompt` value each