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 review: phase-id collision with ltx2's retry sentinel, and three mislabeled phases
[._.]/ Adam Eivy0cd0034e5c5b
diff --git a/client/src/lib/videoRenderPhase.js b/client/src/lib/videoRenderPhase.jsindex 89a818eb38..727e689dcc 100644--- a/client/src/lib/videoRenderPhase.js+++ b/client/src/lib/videoRenderPhase.js@@ -38,7 +38,13 @@ const STEP_INDEX = Object.fromEntries(VIDEO_RENDER_STEPS.map((step, index) => [s// `STAGE:` there); anything unmatched falls through to `null`, which the caller// must treat as "unknown phase", never as step 0 — reporting "Queued" for an// unrecognized marker would read as the render having gone backwards.-const PHASE_STEP = Object.freeze({+const PHASE_STEP = Object.freeze(Object.assign(Object.create(null), {+ // The bare marker, which is what a `DOWNLOAD:` line sets and what+ // hf_download_repo.py emits as `STAGE:download:<n>/<total>:<file>`. It does+ // NOT match the `download-` prefix below, so without this entry the step+ // this list exists for never activates and a multi-GB first-run download+ // reads as "Rendering".+ download: 'download',// The download helper's own preamble, not separate user-visible work.'resolve-cache': 'download',verify: 'download',@@ -54,7 +60,16 @@ const PHASE_STEP = Object.freeze({// Conditioning.'encode-prompt': 'encode',+ conditioning: 'encode','precompute-latents': 'encode',+ // …and its END marker, which means the OPPOSITE of the one above. It is the+ // last STAGE line generate_ltx2.py emits before denoising, and the server+ // pins it as the phase on every progress frame that follows, so mapping it+ // back to `encode` (as its `encode-prompt` prefix otherwise would) leaves+ // LTX-2 — the primary local runtime — reading "Encoding prompt" for the+ // whole sampler run. Exact entries win over prefixes, which is what makes+ // this correction possible.+ 'encode-prompt-done': 'render',// The sampler itself.inference: 'render',@@ -72,7 +87,7 @@ const PHASE_STEP = Object.freeze({// The queue's own state, so a caller has one vocabulary rather than a// separate "is it queued" flag alongside the phase.queued: 'queued',-});+}));// Prefix families, longest-prefix-first. The runners name their markers by// family (`download-text-encoder`, `load-transformer`, `swap-video-decoder`,@@ -95,6 +110,9 @@ const PHASE_PREFIX_STEP = Object.freeze([*/export function videoRenderStepFor(phase) {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 (PHASE_STEP[id]) return PHASE_STEP[id];return PHASE_PREFIX_STEP.find(([prefix]) => id.startsWith(prefix))?.[1] || null;@@ -136,5 +154,7 @@ export function resolveVideoRenderSteps({ generating = false, phase = null, progconst activeId = !generating ? null: videoRenderStepFor(phase)|| (Number.isFinite(progressPct) && progressPct > 0 ? 'render' : 'load');- return { activeId, steps: STEPS_BY_ACTIVE_ID[String(activeId)] };+ // `?? 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 };}diff --git a/client/src/lib/videoRenderPhase.test.js b/client/src/lib/videoRenderPhase.test.jsindex 0d7a256f4a..fc6ea2bad2 100644--- a/client/src/lib/videoRenderPhase.test.js+++ b/client/src/lib/videoRenderPhase.test.js@@ -18,12 +18,36 @@ describe('videoRenderStepFor', () => {expect(videoRenderStepFor('download-some-new-shard')).toBe('download');expect(videoRenderStepFor('load-audio-vae')).toBe('load');expect(videoRenderStepFor('swap-video-decoder')).toBe('load');- expect(videoRenderStepFor('encode-prompt-done')).toBe('encode');// generate_wan22.py emits STAGE:wan-i2v / STAGE:wan-t2v, never bare "wan".expect(videoRenderStepFor('wan-i2v')).toBe('render');expect(videoRenderStepFor('ref2va-mux')).toBe('render');});+ // Each of these was wrong before the exact/bare entries were added, and each+ // mislabels the LONGEST phase of a real render.+ it('maps the phases the shipped runners actually pin during their slowest work', () => {+ // `DOWNLOAD:` lines and hf_download_repo.py both pin the BARE marker, which+ // does not match the `download-` prefix.+ expect(videoRenderStepFor('download')).toBe('download');+ // generate_ltx2.py's LAST stage marker before denoising. It means the+ // encode FINISHED, so the `encode-prompt` prefix would read it backwards+ // and leave LTX-2 showing "Encoding prompt" for its entire sampler run.+ expect(videoRenderStepFor('encode-prompt-done')).toBe('render');+ // generate_fastvideo.py's conditioning phase is named 'conditioning'+ // precisely so it can't collide with ltx2's prompt-encode sentinel.+ expect(videoRenderStepFor('conditioning')).toBe('encode');+ });++ // A runner is free to emit any STAGE id; one that collides with an+ // Object.prototype key must not resolve to a function the caller then treats+ // as a step id (and whose step list comes back undefined to .map over).+ it('is not fooled by a phase named after an Object.prototype key', () => {+ expect(videoRenderStepFor('constructor')).toBeNull();+ expect(videoRenderStepFor('toString')).toBeNull();+ expect(resolveVideoRenderSteps({ generating: true, phase: 'constructor' }).steps)+ .toHaveLength(6);+ });+it('normalizes case, because BYOV helpers are not required to agree on it', () => {expect(videoRenderStepFor('Load-Pipeline')).toBe('load');});diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex da24b1f570..73fb67267b 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -432,6 +432,9 @@ export default function VideoGen() {// Out of the queue, but the runner hasn't named a phase yet — clear it// rather than guessing, and let the card default to "Loading model".setPhase(null);+ // The clock starts HERE, not at submit: time spent waiting in the queue+ // is not render time, and counting it would make the elapsed figure+ // jump backwards on a reload (which reads the worker's own startedAt).setRenderStartedAt((at) => at ?? Date.now());setStatusMsg('Starting render…');},@@ -496,8 +499,10 @@ export default function VideoGen() {setGenerating(true);setPhase(job.status === 'queued' ? 'queued' : null);// The worker's own start time, so a reload keeps a truthful elapsed clock- // instead of restarting it and reading as a fresh render.- setRenderStartedAt(job.startedAt ? new Date(job.startedAt).getTime() : Date.now());+ // instead of restarting it and reading as a fresh render. A job still in+ // the queue has no start time yet and gets no clock — the same rule the+ // live path follows.+ setRenderStartedAt(job.startedAt ? new Date(job.startedAt).getTime() : null);// Skip a forced setProgress(0) here — attachJobEvents will replay the// server's last SSE payload synchronously after EventSource open, and// a job mid-render would otherwise visibly flash 0% before jumping@@ -692,9 +697,10 @@ export default function VideoGen() {setStatusMsg('Starting...');setError(null);// Stale-job isolation: the previous run's phase and clock must not be shown- // as if they belonged to this one.+ // as if they belonged to this one. The clock stays null until `started`+ // lands, so it measures the render rather than the queue wait.setPhase(null);- setRenderStartedAt(Date.now());+ setRenderStartedAt(null);const myToken = ++runTokenRef.current;const isCurrent = () => myToken === runTokenRef.current;diff --git a/scripts/_runner_common.py b/scripts/_runner_common.pyindex 0e669c1f1e..569ab68fdd 100644--- a/scripts/_runner_common.py+++ b/scripts/_runner_common.py@@ -84,7 +84,12 @@ def heartbeat(stage: "str | Callable[[], str]", interval: float = 20.0):elapsed = 0while not stop.wait(interval):elapsed += int(interval)- print(f"STAGE:{resolve_stage()}:heartbeat:{elapsed}s", file=sys.stderr, flush=True)+ # One write, not print()'s two — a caller that also writes to stderr+ # from the main thread (generate_fastvideo.py streams its child's+ # output there) would otherwise see the beat land between a line's+ # text and its newline, gluing two protocol lines together.+ sys.stderr.write(f"STAGE:{resolve_stage()}:heartbeat:{elapsed}s\n")+ sys.stderr.flush()t = threading.Thread(target=beat, daemon=True)t.start()diff --git a/scripts/generate_fastvideo.py b/scripts/generate_fastvideo.pyindex 2140013298..234be72283 100755--- a/scripts/generate_fastvideo.py+++ b/scripts/generate_fastvideo.py@@ -54,7 +54,14 @@ _PERCENT_PATTERN = re.compile(r'\d+%')# The phase progression, earliest first. Ordering is load-bearing — it is what# keeps `advance_phase` monotonic — so it is declared here rather than inferred# from the key order of the label table below.-_PHASE_ORDER = ("load-pipeline", "encode-prompt", "sampling", "mux")+# NOT "encode-prompt": that exact marker is generate_ltx2.py's Gemma+# prompt-encode BEGIN sentinel (PROMPT_ENCODE_BEGIN_MARKER in+# generateVideoHelpers.js), and the server arms an ltx2-specific relaunch on it.+# Emitting it here would open a phase this runner never closes, so a FastVideo+# render killed by the Metal watchdog would be "retried" with ltx2's+# --gemma-max-length flag, which this script's argparse rejects — replacing the+# real watchdog error with an exit-2 after a wasted full model re-spawn.+_PHASE_ORDER = ("load-pipeline", "conditioning", "sampling", "mux")# Phase id -> the sentence the user reads, emitted once per transition. Ids are# drawn from the STAGE: vocabulary the server already parses@@ -62,7 +69,7 @@ _PHASE_ORDER = ("load-pipeline", "encode-prompt", "sampling", "mux")# FastVideo-specific entries.PHASE_LABELS = {"load-pipeline": "Loading the FastVideo pipeline",- "encode-prompt": "Encoding the prompt and streaming model weights",+ "conditioning": "Encoding the prompt and streaming model weights","sampling": "Rendering (denoising)","mux": "Decoding and muxing video + audio",}@@ -76,7 +83,7 @@ INITIAL_PHASE = _PHASE_ORDER[0]_PHASE_MARKERS = (# `Geometry: output=...` is the first line generate() logs, i.e. the# pipeline object is constructed and the long conditioning leg starts here.- ("geometry:", "encode-prompt"),+ ("geometry:", "conditioning"),# Text conditioning is done — either freshly encoded or read from cache.("loaded prompt embeddings", "sampling"),# The DiT finished streaming in; denoising is the only thing left before@@ -293,8 +300,12 @@ def main() -> int:cwd=str(repo_dir),)+ # One write per line, not print()'s two (text, then newline): the heartbeat+ # thread writes to this same stream, and an interleave between the two halves+ # would glue two protocol lines together and lose a marker.def emit(text: str) -> None:- print(text, file=sys.stderr, flush=True)+ sys.stderr.write(f"{text}\n")+ sys.stderr.flush()phase = INITIAL_PHASEemit(f"STAGE:{phase}")diff --git a/scripts/generate_fastvideo.test.js b/scripts/generate_fastvideo.test.jsindex 8dcd731dca..2f69289767 100644--- a/scripts/generate_fastvideo.test.js+++ b/scripts/generate_fastvideo.test.js@@ -63,7 +63,10 @@ describe.skipIf(!pyBin)('generate_fastvideo.py phase reporting', () => {' print(phase)',].join('\n')}`);- expect(lines(output)).toEqual(['encode-prompt', 'sampling', 'sampling', 'mux']);+ // 'conditioning', deliberately NOT 'encode-prompt' — that exact marker is+ // generate_ltx2.py's prompt-encode BEGIN sentinel, and emitting it here+ // would arm an ltx2-only relaunch against a FastVideo render.+ expect(lines(output)).toEqual(['conditioning', 'sampling', 'sampling', 'mux']);});it('never moves the phase backwards when a milestone line repeats', () => {diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex bc26da4a6a..1d4fc8120b 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -76,6 +76,10 @@ vi.mock('../services/videoGen/runtimes.js', async (importOriginal) => ({resolveByovRuntimeLoraCapable: vi.fn(async (runtime) => runtime === 'minimax_h3' && loraCapability.capable),}));+vi.mock('../services/displayPower.js', () => ({+ isDisplaySleepEnabled: vi.fn(() => false),+}));+vi.mock('../services/settings.js', () => ({getSettings: vi.fn(async () => ({ imageGen: { local: { pythonPath: '/usr/bin/python3' } } })),updateSettingsWith: vi.fn(async (mutate) => mutate({ imageGen: { local: { pythonPath: '/usr/bin/python3' } } })),@@ -407,20 +411,28 @@ describe('videoGen routes', () => {});// #5872 — the page warns the user BEFORE the screen goes dark, which it can- // only do if the server says whether THIS install will actually sleep it- // (macOS, and the user hasn't opted out). Warning a user who opted out- // would teach them to ignore the warning that matters.- it('reports whether a render will sleep the display, honoring the opt-out', async () => {+ // only do if the server says whether THIS install will actually sleep it.+ // The predicate is stubbed rather than exercised for real: it is+ // macOS-only, so a live call returns false on every other runner and the+ // assertions would pass against a hardcoded false — pinning nothing.+ it('reports whether a render will sleep the display, and passes the videoGen slice', async () => {+ const { isDisplaySleepEnabled } = await import('../services/displayPower.js');const { getSettings } = await import('../services/settings.js');- const dflt = await request(app).get('/api/video-gen/status');- expect(typeof dflt.body.displaySleepOnRender).toBe('boolean');+ isDisplaySleepEnabled.mockReturnValueOnce(true);getSettings.mockResolvedValueOnce({imageGen: { local: { pythonPath: '/usr/bin/python3' } },- videoGen: { displaySleep: false },+ videoGen: { displaySleep: true },});- const optedOut = await request(app).get('/api/video-gen/status');- expect(optedOut.body.displaySleepOnRender).toBe(false);+ const on = await request(app).get('/api/video-gen/status');+ expect(on.body.displaySleepOnRender).toBe(true);+ // The videoGen slice, not the whole settings object — the predicate reads+ // `.displaySleep` off what it is handed.+ expect(isDisplaySleepEnabled).toHaveBeenCalledWith({ displaySleep: true });++ isDisplaySleepEnabled.mockReturnValueOnce(false);+ const off = await request(app).get('/api/video-gen/status');+ expect(off.body.displaySleepOnRender).toBe(false);});it('passes each model entry through with its registry disclosure block', async () => {diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex e954fef0ab..1dbaa92dad 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -428,8 +428,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, render }) =>- ({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg, etaMs, render }),+ 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 }),);await atomicWrite(JOBS_FILE, { jobs: serializable });}diff --git a/server/services/videoGen/chainedVideo.js b/server/services/videoGen/chainedVideo.jsindex 5de426504f..34e6937165 100644--- a/server/services/videoGen/chainedVideo.js+++ b/server/services/videoGen/chainedVideo.js@@ -186,12 +186,6 @@ 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);@@ -208,10 +202,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 || {}),+ // The chunk's own render phase, so a chained render names its step the+ // same way a single-shot one does instead of falling back to the+ // page's load/render heuristic for the whole chain (#5872).+ phase: typeof e.phase === 'string' && e.phase ? e.phase : undefined,});broadcastSse(outerJob, {type: 'progress',@@ -219,21 +213,7 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFramesmessage: `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);@@ -248,7 +228,6 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFramesdetach();reject(new Error(e.error || 'chunk failed'));};- videoGenEvents.on('started', onChunkStarted);videoGenEvents.on('progress', onProgress);videoGenEvents.on('completed', onCompleted);videoGenEvents.on('failed', onFailed);