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: make the local sprite render lane survive a restart and its own attach gap

[._.]/ Adam Eivy19f44cb08fbf
diff --git a/client/src/components/sprites/AnimationProviderPicker.jsx b/client/src/components/sprites/AnimationProviderPicker.jsx
index e48fc65e33..d62a76c0f7 100644
--- a/client/src/components/sprites/AnimationProviderPicker.jsx
+++ b/client/src/components/sprites/AnimationProviderPicker.jsx
@@ -12,9 +12,10 @@
* one-option dropdown implying a choice it does not have.
*
* An unready lane stays visible but disabled, with the server's own `reason`
- * shown as text beside it. That is deliberate — hiding it would leave the user
- * with no way to discover the local lane exists, and per the repo's UI rules a
- * warning that lives only in a `title` is missed on touch.
+ * shown as text beside the control whether or not that lane is selected. That is
+ * deliberate — hiding it would leave the user with no way to discover the local
+ * lane exists or what would make it work, and per the repo's UI rules a warning
+ * that lives only in a `title` is missed on touch.
*/
export default function AnimationProviderPicker({
id, providers, provider, onChange, disabled = false,
@@ -22,8 +23,11 @@ export default function AnimationProviderPicker({
// `null` = not fetched yet (distinct from `[]` = fetched and empty), so a
// slow or failed probe never flashes a picker that then disappears.
if (!Array.isArray(providers) || providers.length < 2) return null;
- const selected = providers.find((entry) => entry.id === provider) || null;
- const blockedReason = selected && selected.ready === false ? selected.reason : null;
+ // Reasons for EVERY unready lane, not just the selected one. Keying this off
+ // the selection made it unreachable in practice: an unready lane is a disabled
+ // <option>, so it can never BE the selection — and the reason is the only place
+ // the one thing to fix is named.
+ const blocked = providers.filter((entry) => entry.ready === false && entry.reason);
return (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<label className="flex items-center gap-1.5 text-xs text-gray-400" htmlFor={id}>
@@ -43,9 +47,9 @@ export default function AnimationProviderPicker({
))}
</select>
</label>
- {blockedReason && (
- <p className="text-xs text-port-warning basis-full sm:basis-auto">{blockedReason}</p>
- )}
+ {blocked.map((entry) => (
+ <p key={entry.id} className="text-xs text-port-warning basis-full sm:basis-auto">{entry.reason}</p>
+ ))}
</div>
);
}
diff --git a/client/src/components/sprites/AnimationProviderPicker.test.jsx b/client/src/components/sprites/AnimationProviderPicker.test.jsx
index 1824070725..93f1f8f1c9 100644
--- a/client/src/components/sprites/AnimationProviderPicker.test.jsx
+++ b/client/src/components/sprites/AnimationProviderPicker.test.jsx
@@ -68,16 +68,27 @@ describe('AnimationProviderPicker', () => {
expect(screen.getByRole('option', { name: 'Grok (cloud)' })).not.toBeDisabled();
});
- it('shows the blocking reason as TEXT once that lane is the selected one', () => {
- // Not a `title`: per the repo's UI rules a tooltip-only warning is missed on
- // touch, and this is the only place the fix is named.
- renderPicker({ providers: [GROK, LOCAL_BLOCKED], provider: 'local' });
+ it('shows the blocking reason as TEXT while another lane is selected', () => {
+ // The reachable case, and the one that matters: an unready lane is a
+ // DISABLED option, so it can never be the selection. Gating the reason on
+ // being selected made it dead code, and the reason is the only place the one
+ // thing to fix is named. Not a `title` either — per the repo's UI rules a
+ // tooltip-only warning is missed on touch.
+ renderPicker({ providers: [GROK, LOCAL_BLOCKED], provider: 'grok' });
expect(screen.getByText(/runtime is not installed/)).toBeInTheDocument();
});
- it('stays quiet about a blocked lane the user has not selected', () => {
- renderPicker({ providers: [GROK, LOCAL_BLOCKED], provider: 'grok' });
+ it('says nothing when every lane is ready', () => {
+ renderPicker({ providers: [GROK, LOCAL_READY], provider: 'grok' });
expect(screen.queryByText(/runtime is not installed/)).toBeNull();
+ expect(screen.queryByText(/not downloaded/)).toBeNull();
+ });
+
+ it('names EACH unready lane rather than only the first', () => {
+ const other = { id: 'other', label: 'Other', ready: false, reason: 'Other lane is not downloaded.' };
+ renderPicker({ providers: [GROK, LOCAL_BLOCKED, other], provider: 'grok' });
+ expect(screen.getByText(/runtime is not installed/)).toBeInTheDocument();
+ expect(screen.getByText(/Other lane is not downloaded/)).toBeInTheDocument();
});
it('disables the whole control when the caller says the set is frozen', () => {
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index 1f4f3d857d..70e4e41911 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -1405,6 +1405,27 @@ const platformBroken = (broken) =>
// normalizeRegistry) and peer-synced entries in one place, and keeps the derived
// list out of data/media-models.json — a persisted copy would read back as a
// *declared* list that no later correction to VIDEO_RUNTIME_MODES could reach.
+/**
+ * Every pinned file group a model needs resolvable in the HF cache.
+ *
+ * Two shapes, and a caller that checks only one gets the other wrong: a
+ * selective row pins its subset with `repoFiles` against its OWN repo (the H3
+ * CUDA entry, whose base repo is ~498 GB and whose diffusers layout is ~144 GB
+ * of it), while a row that composes weights from a SECOND repo pins them in
+ * `requiredWeights` (the H3 MLX entry's upstream FL2VA checkpoint). Checking
+ * `requiredWeights` alone reports a half-downloaded CUDA model as complete.
+ *
+ * An empty result means "the base snapshot is the whole answer".
+ */
+export const requiredModelCacheGroups = (model) => {
+ const groups = [];
+ if (Array.isArray(model?.repoFiles)) {
+ groups.push({ repo: model.repo, revision: model.revision, files: model.repoFiles });
+ }
+ if (Array.isArray(model?.requiredWeights)) groups.push(...model.requiredWeights);
+ return groups;
+};
+
export const getVideoModels = () => {
const reg = loadMediaModels();
const list = readVideoBucket(reg.video, activeVideoBucket()) || [];
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index ebbe653de5..7475f8b2b8 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -112,6 +112,7 @@ import { initSyncLog } from './brainSyncLog.js';
import { backfillOriginInstanceId, brainCollectionStores } from './brainStorage.js';
import { initSyncOrchestrator } from './syncOrchestrator.js';
import { initMediaJobQueue } from './mediaJobQueue/index.js';
+import { initSpriteLocalAnimationHook } from './sprites/localAnimationJobHook.js';
import { initLoraTraining } from './loraTraining/index.js';
import { initSharing } from './sharing/index.js';
import { initMortalLoomStore } from './mortalLoomStore.js';
@@ -478,6 +479,12 @@ const initMediaJobDependentHooks = () => {
// Universe Builder needs the media job queue running before it can listen
// for `completed` events — so initialize the hook here.
initUniverseBuilderCollectionHook();
+ // Sprite local-render hook (#4876) — stages a finished MiniMax H3 clip into
+ // its animation run and files the outcome, for renders that outlive the
+ // request that started them. Its boot pass also reconciles jobs that settled
+ // while the server was down, which is the only thing that can rescue a
+ // multi-hour render interrupted by a restart.
+ initSpriteLocalAnimationHook();
// Catalog image-attach hook — durably files a queued render onto its target
// ingredient on completion, even if the editor page unmounted mid-render
// (#1359).
diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.js
index c17d07d34d..fcfa06e243 100644
--- a/server/services/federatedMediaProvider.js
+++ b/server/services/federatedMediaProvider.js
@@ -15,7 +15,7 @@ import {
PATHS, makePathResolver, resolveGalleryImage, sha256File, sha256Text,
} from '../lib/fileUtils.js';
import { findCachedRepoFiles, inspectModelCache } from '../lib/hfCache.js';
-import { getImageModels, getVideoModels, isEditOnly, isFlux2, repoForModel } from '../lib/mediaModels.js';
+import { getImageModels, getVideoModels, isEditOnly, isFlux2, repoForModel, requiredModelCacheGroups } from '../lib/mediaModels.js';
import { isMiniMaxH3Runtime, usesDiffusersRunner } from '../lib/runners.js';
import {
FEDERATED_MEDIA_ASSET_MAX_BYTES,
@@ -246,15 +246,6 @@ async function resolveSubmissionInputAssets({ callerId, input, capability }) {
return params;
}
-const requiredModelCacheGroups = (model) => {
- const groups = [];
- if (Array.isArray(model?.repoFiles)) {
- groups.push({ repo: model.repo, revision: model.revision, files: model.repoFiles });
- }
- if (Array.isArray(model?.requiredWeights)) groups.push(...model.requiredWeights);
- return groups;
-};
-
const inspectFederatedModelCache = async (model, repo) => {
const revision = model?.revision ? { revision: model.revision } : undefined;
const base = repo
diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.js
index 3bd150e7cf..8251fe4589 100644
--- a/server/services/federatedMediaProvider.test.js
+++ b/server/services/federatedMediaProvider.test.js
@@ -20,7 +20,11 @@ vi.mock('./settings.js', () => ({
getSettings: vi.fn(async () => state.settings),
}));
-vi.mock('../lib/mediaModels.js', () => ({
+// Only the CATALOG accessors are stubbed — the pure row-shape helpers come from
+// the real module, so a change to what "must be cached" is felt here rather than
+// re-stated in a mock that could drift from it.
+vi.mock('../lib/mediaModels.js', async (importOriginal) => ({
+ ...await importOriginal(),
getImageModels: vi.fn(() => state.imageModels),
getVideoModels: vi.fn(() => state.videoModels),
isEditOnly: (model) => model?.editOnly === true,
diff --git a/server/services/sprites/animationTrackWorkflow.js b/server/services/sprites/animationTrackWorkflow.js
index 710ef78b89..44e0b25e64 100644
--- a/server/services/sprites/animationTrackWorkflow.js
+++ b/server/services/sprites/animationTrackWorkflow.js
@@ -46,8 +46,7 @@ import { executeTuiRun } from '../../lib/tuiPromptRunner.js';
import { GROK_TUI_ID } from '../../lib/grok.js';
import { resolveGrokDuration } from '../../lib/grokVideoClip.js';
import {
- planLocalAnimationRender, enqueueLocalAnimationRender, collectLocalAnimationRender,
- localRenderManifest,
+ planLocalAnimationRender, enqueueLocalAnimationRender, localRenderManifest,
} from './localAnimationRender.js';
import { getSettings } from '../settings.js';
import { getRecord, listRecords } from './records.js';
@@ -60,7 +59,7 @@ import { clampTrackFrameCount, clampTrackFps, sourceReferenceFor } from './anima
// track reaches generate/approve through exactly this path with no new code.
import { effectiveTrack, getEffectiveAnimationTracks } from './animationTrackStore.js';
import { trackDirections } from './atlasGrid.js';
-import { spriteDir, resolveSpriteAssetPath, SOURCE_CLIP_NAME } from './paths.js';
+import { spriteDir, resolveSpriteAssetPath, SOURCE_CLIP_NAME, runRelPath } from './paths.js';
import { prepareWalkAnchorChromaInput, runWalkPostprocess } from './walkPostprocess.js';
import { verifyPackagedFrames } from './walkFrames.js';
import {
@@ -87,7 +86,6 @@ export const trackAuthoringDirections = (trackId) => trackDirections(trackId);
// which is exactly what scanner.js and ambient.js each spelled for themselves.
const selectionRelPath = (trackId, id) => `${trackId}/${id}-${trackId}-selection-v1.json`;
export const trackSetRelPath = (trackId, id) => `${trackId}/${id}-${trackId}-set-v1.json`;
-const runRelPath = (runId) => `runs/${runId}`;
const setFinalError = (row) => new ServerError(
row.directional
@@ -315,13 +313,6 @@ async function startTrackGenerationImpl(trackId, recordId, body) {
const prompt = buildTrackVideoPrompt(row.id, {
name: record.name, kind: record.kind, direction, chromaKey, correctionPrompt,
});
- // Stamped on the run record BEFORE anything awaits the job — see the walk
- // lane's note: a local run with no `jobId` can never be told from a dead one.
- const jobId = localPlan
- ? enqueueLocalAnimationRender({
- plan: localPlan, canvas, prompt, inputAbs, owner: `sprite-${row.id}:${recordId}:${direction}`,
- })
- : null;
const run = {
schemaVersion: 1,
kind: 'grok-game-animation-frames-run',
@@ -349,13 +340,19 @@ async function startTrackGenerationImpl(trackId, recordId, body) {
// Spread LAST so the local lane's provider/geometry provenance wins over the
// grok defaults above. A local render is a queued media job, not a PTY, so it
// carries `jobId` in place of an attachable `shellSession`.
- ...(localPlan ? { ...localRenderManifest(localPlan, canvas), jobId, shellSession: null } : {}),
+ ...(localPlan ? { ...localRenderManifest(localPlan, canvas), shellSession: null } : {}),
};
await saveRun(recordId, run);
if (localPlan) {
- collectLocalAnimationRender({ jobId, videoAbs, label: `sprite ${row.id} ${recordId}/${direction}` })
- .then(() => withAnimationWriteTail(recordId, () => attachTrackTuiResult(row.id, recordId, runId, videoAbs)))
- .catch((err) => console.error(`❌ sprite ${row.id} local render crashed ${recordId}/${runId}: ${err?.message || err}`));
+ // Queued after the record is durable, and never awaited here — the
+ // boot-registered completion hook stages the clip and runs the attach. See
+ // the walk lane's note: that is what survives a restart, which matters most
+ // on this lane because track runs have no wall-clock backstop at all.
+ const jobId = enqueueLocalAnimationRender({
+ plan: localPlan, canvas, prompt, inputAbs, recordId, runId, track: row.id, direction,
+ });
+ run.jobId = jobId;
+ await saveRun(recordId, run);
console.log(`📡 sprite ${row.id} local render started ${recordId}/${runId} (job ${jobId.slice(0, 8)}, ${localPlan.numFrames}f @ ${localPlan.fps}fps)`);
return row.directional
? { runId, direction, duration, provider: 'local', jobId }
diff --git a/server/services/sprites/localAnimationJobHook.js b/server/services/sprites/localAnimationJobHook.js
new file mode 100644
index 0000000000..ba18c3728f
--- /dev/null
+++ b/server/services/sprites/localAnimationJobHook.js
@@ -0,0 +1,146 @@
+/**
+ * Sprite local-render completion hook (#4876).
+ *
+ * The local lane queues ONE media job per animation clip and then has to be
+ * told when it settles. Awaiting that in the request that started it — a promise
+ * held in the enqueueing process — cannot survive the thing it most needs to
+ * survive: a restart. `initMediaJobQueue` re-enqueues jobs that were merely
+ * `queued` at shutdown, so a per-call awaiter meant an H3 render could run for
+ * HOURS after the restart, write its MP4, and have nothing file it — the run sat
+ * at `rendering` (blocking regeneration the whole time) and then reported itself
+ * interrupted, burning the render the user waited for.
+ *
+ * So this hook holds NO in-memory state about in-flight work. It decodes each
+ * job from its own persisted `params.spriteAnimation` tag, exactly like the
+ * other durable media-job hooks (`mediaJobImageHook`, `universeBuilderCollectionHook`).
+ * Two halves, and both are needed:
+ *
+ * 1. A live subscription to every TERMINAL event, so a job that settles while
+ * this process is up is filed immediately.
+ * 2. A boot reconcile, because a job that settled while the process was DOWN
+ * emits nothing — it is simply sitting in the restored archive. Without this
+ * pass those runs would only ever be resolved by the walk lane's wall-clock
+ * backstop (a day later, as an error), and never at all on the track lane.
+ *
+ * It listens for `failed`/`canceled` as well as `completed` on purpose: the
+ * attach treats "no clip on disk" as a terminal, user-visible error, so routing
+ * every outcome through it is what guarantees a run always leaves `rendering`.
+ */
+
+import { join } from 'path';
+import { mediaJobEvents, listJobs } from '../mediaJobQueue/index.js';
+import { spriteDir, runRelPath, SOURCE_CLIP_NAME } from './paths.js';
+import { WALK_TRACK } from './animationTargets.js';
+import { withAnimationWriteTail } from './animationWorkflow.js';
+import { collectLocalAnimationClip } from './localAnimationRender.js';
+import { attachTuiWalkResult } from './walk.js';
+import { attachTrackTuiResult } from './animationTrackWorkflow.js';
+
+/** The tag a sprite-animation job carries, or null for every other media job. */
+const decodeSpriteAnimationJob = (job) => {
+ if (job?.kind !== 'video') return null;
+ const tag = job.params?.spriteAnimation;
+ if (!tag || typeof tag !== 'object') return null;
+ const { recordId, runId, track, direction } = tag;
+ if (typeof recordId !== 'string' || !recordId) return null;
+ if (typeof runId !== 'string' || !runId) return null;
+ if (typeof track !== 'string' || !track) return null;
+ return { recordId, runId, track, direction: typeof direction === 'string' ? direction : null };
+};
+
+/**
+ * Stage the clip (when there is one) and run the track's attach.
+ *
+ * The attach is the single place a run leaves `rendering`, on either outcome:
+ * it packages the clip into a candidate when the MP4 is there, and writes a
+ * terminal error naming the Render Queue when it is not. So this deliberately
+ * does NOT branch on the job's status beyond deciding whether staging is worth
+ * attempting — a failed, canceled, and clip-less-but-completed job all converge
+ * on the same honest error.
+ */
+async function settleSpriteAnimationJob(job) {
+ const decoded = decodeSpriteAnimationJob(job);
+ if (!decoded) return false;
+ const { recordId, runId, track, direction } = decoded;
+ const label = `sprite ${track} ${recordId}/${direction || 'row-0'}`;
+ const videoAbs = join(spriteDir(recordId), runRelPath(runId), 'generated', SOURCE_CLIP_NAME);
+ if (job.status === 'completed') {
+ await collectLocalAnimationClip({ jobId: job.id, videoAbs, label });
+ } else {
+ console.log(`🎞️ ${label} local render ${job.status} — filing the run as errored`);
+ }
+ // Both attaches re-read the run record and no-op on frozen evidence (a
+ // finalized set, an approved run), so a duplicate settle is harmless — which
+ // is what lets the boot reconcile be unconditional.
+ await withAnimationWriteTail(recordId, () => (
+ track === WALK_TRACK
+ ? attachTuiWalkResult(recordId, runId, videoAbs)
+ : attachTrackTuiResult(track, recordId, runId, videoAbs)
+ ));
+ return true;
+}
+
+let terminalHandler = null;
+
+/**
+ * Reconcile jobs that reached a terminal state while this process was down.
+ *
+ * Only jobs whose run is still `rendering` need anything, but that check lives
+ * in the attach (which re-reads the record and skips frozen evidence), so this
+ * stays a simple sweep over the restored archive rather than a second copy of
+ * the run-state rules.
+ */
+async function reconcileSettledSpriteJobs() {
+ const jobs = listJobs({ kind: 'video', owner: 'sprites' })
+ .filter((job) => ['completed', 'failed', 'canceled'].includes(job.status))
+ .filter(decodeSpriteAnimationJob);
+ if (!jobs.length) return 0;
+ let settled = 0;
+ for (const job of jobs) {
+ // Serialized on purpose: these share the per-record write tail anyway, and a
+ // boot sweep has no reason to contend with the requests now arriving.
+ // eslint-disable-next-line no-await-in-loop
+ await settleSpriteAnimationJob(job).then(() => { settled += 1; }).catch((err) => (
+ console.error(`❌ sprite local render boot reconcile failed for job ${job.id.slice(0, 8)}: ${err?.message || err}`)
+ ));
+ }
+ console.log(`🎞️ sprite local renders: reconciled ${settled} settled job(s) on boot`);
+ return settled;
+}
+
+/**
+ * Mount the hook. Idempotent — a double init would otherwise file every
+ * completed clip twice.
+ */
+export function initSpriteLocalAnimationHook() {
+ if (terminalHandler) return;
+ terminalHandler = (job) => {
+ // Outside the request lifecycle, so a throw here would take the process
+ // down rather than reaching error middleware (AGENTS.md boundary exception).
+ void settleSpriteAnimationJob(job).catch((err) => (
+ console.error(`❌ sprite local render hook failed for job ${job?.id?.slice(0, 8)}: ${err?.message || err}`)
+ ));
+ };
+ mediaJobEvents.on('completed', terminalHandler);
+ mediaJobEvents.on('failed', terminalHandler);
+ mediaJobEvents.on('canceled', terminalHandler);
+ console.log('🎞️ Sprite local-render hook initialized');
+ // Fire-and-forget: a boot sweep must not delay the server accepting requests,
+ // and every run it would fix is already parked rather than lost.
+ void reconcileSettledSpriteJobs().catch((err) => (
+ console.error(`❌ sprite local render boot reconcile failed: ${err?.message || err}`)
+ ));
+}
+
+export const __testing = {
+ decodeSpriteAnimationJob,
+ settleSpriteAnimationJob,
+ reconcileSettledSpriteJobs,
+ reset: () => {
+ if (!terminalHandler) return;
+ mediaJobEvents.off('completed', terminalHandler);
+ mediaJobEvents.off('failed', terminalHandler);
+ mediaJobEvents.off('canceled', terminalHandler);
+ terminalHandler = null;
+ },
+};
diff --git a/server/services/sprites/localAnimationJobHook.test.js b/server/services/sprites/localAnimationJobHook.test.js
new file mode 100644
index 0000000000..f60dfdfe70
--- /dev/null
+++ b/server/services/sprites/localAnimationJobHook.test.js
@@ -0,0 +1,227 @@
+/**
+ * The sprite local-render completion hook (#4876).
+ *
+ * The property under test is DURABILITY: this hook holds no in-memory record of
+ * in-flight work, so every path — a job settling live, a job that settled while
+ * the process was down, a job that produced no clip — has to be recoverable from
+ * the job's own persisted params alone. A hook that quietly depended on state
+ * from the enqueueing request would pass a happy-path test and still lose a
+ * multi-hour render to a restart, which is exactly the bug it replaced.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { EventEmitter } from 'events';
+
+const mediaJobEvents = new EventEmitter();
+let queuedJobs = [];
+vi.mock('../mediaJobQueue/index.js', () => ({
+ mediaJobEvents,
+ listJobs: () => queuedJobs,
+}));
+
+vi.mock('./paths.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ spriteDir: (recordId) => `/sprites/${recordId}`,
+}));
+
+const collectLocalAnimationClip = vi.fn(async () => true);
+vi.mock('./localAnimationRender.js', () => ({
+ collectLocalAnimationClip: (...args) => collectLocalAnimationClip(...args),
+}));
+
+const attachTuiWalkResult = vi.fn(async () => {});
+vi.mock('./walk.js', () => ({
+ attachTuiWalkResult: (...args) => attachTuiWalkResult(...args),
+}));
+
+const attachTrackTuiResult = vi.fn(async () => {});
+vi.mock('./animationTrackWorkflow.js', () => ({
+ attachTrackTuiResult: (...args) => attachTrackTuiResult(...args),
+}));
+
+const { initSpriteLocalAnimationHook, __testing } = await import('./localAnimationJobHook.js');
+const { decodeSpriteAnimationJob, settleSpriteAnimationJob, reconcileSettledSpriteJobs } = __testing;
+
+const walkJob = (overrides = {}) => ({
+ id: 'mjob-1',
+ kind: 'video',
+ status: 'completed',
+ params: {
+ spriteAnimation: { recordId: 'hero', runId: 'walk-east-abc12345', track: 'walk', direction: 'east' },
+ },
+ ...overrides,
+});
+
+const trackJob = (overrides = {}) => ({
+ id: 'mjob-2',
+ kind: 'video',
+ status: 'completed',
+ params: {
+ spriteAnimation: { recordId: 'hero', runId: 'scanner-east-abc12345', track: 'scanner', direction: 'east' },
+ },
+ ...overrides,
+});
+
+beforeEach(() => {
+ queuedJobs = [];
+ collectLocalAnimationClip.mockClear();
+ collectLocalAnimationClip.mockResolvedValue(true);
+ attachTuiWalkResult.mockClear();
+ attachTrackTuiResult.mockClear();
+});
+afterEach(() => __testing.reset());
+
+describe('decodeSpriteAnimationJob', () => {
+ it('accepts a fully-formed sprite animation job', () => {
+ expect(decodeSpriteAnimationJob(walkJob())).toEqual({
+ recordId: 'hero', runId: 'walk-east-abc12345', track: 'walk', direction: 'east',
+ });
+ });
+
+ it('ignores every other media job on the queue', () => {
+ expect(decodeSpriteAnimationJob({ kind: 'image', params: { spriteAnimation: {} } })).toBeNull();
+ expect(decodeSpriteAnimationJob({ kind: 'video', params: {} })).toBeNull();
+ expect(decodeSpriteAnimationJob({ kind: 'video', params: { musicVideo: { projectId: 'p' } } })).toBeNull();
+ expect(decodeSpriteAnimationJob(null)).toBeNull();
+ });
+
+ it('refuses a tag missing any id it would need to find the run', () => {
+ // A partial tag would otherwise reach `spriteDir(undefined)` and file the
+ // clip into a phantom directory.
+ for (const partial of [
+ { runId: 'r', track: 'walk' },
+ { recordId: 'hero', track: 'walk' },
+ { recordId: 'hero', runId: 'r' },
+ ]) {
+ expect(decodeSpriteAnimationJob({ kind: 'video', params: { spriteAnimation: partial } })).toBeNull();
+ }
+ });
+
+ it('accepts a non-directional track, whose facing is derived server-side', () => {
+ const decoded = decodeSpriteAnimationJob({
+ kind: 'video',
+ params: { spriteAnimation: { recordId: 'hero', runId: 'ambient-abc', track: 'ambient' } },
+ });
+ expect(decoded).toEqual({ recordId: 'hero', runId: 'ambient-abc', track: 'ambient', direction: null });
+ });
+});
+
+describe('settleSpriteAnimationJob', () => {
+ it('stages the clip and files it through the WALK attach', async () => {
+ await settleSpriteAnimationJob(walkJob());
+ expect(collectLocalAnimationClip).toHaveBeenCalledWith(expect.objectContaining({
+ jobId: 'mjob-1',
+ videoAbs: '/sprites/hero/runs/walk-east-abc12345/generated/source-video.mp4',
+ }));
+ expect(attachTuiWalkResult).toHaveBeenCalledWith(
+ 'hero', 'walk-east-abc12345', '/sprites/hero/runs/walk-east-abc12345/generated/source-video.mp4',
+ );
+ expect(attachTrackTuiResult).not.toHaveBeenCalled();
+ });
+
+ it('routes a non-walk track to the TRACK attach, naming its track', async () => {
+ await settleSpriteAnimationJob(trackJob());
+ expect(attachTrackTuiResult).toHaveBeenCalledWith(
+ 'scanner', 'hero', 'scanner-east-abc12345',
+ '/sprites/hero/runs/scanner-east-abc12345/generated/source-video.mp4',
+ );
+ expect(attachTuiWalkResult).not.toHaveBeenCalled();
+ });
+
+ it('still runs the attach on a FAILED job, so the run leaves rendering', async () => {
+ // The attach is the only thing that writes a terminal state. Skipping it for
+ // a failed job strands the run at 'rendering' — permanently on the track
+ // lane, whose in-flight guard then 409s every retry.
+ await settleSpriteAnimationJob(walkJob({ status: 'failed' }));
+ expect(collectLocalAnimationClip).not.toHaveBeenCalled();
+ expect(attachTuiWalkResult).toHaveBeenCalled();
+ });
+
+ it('still runs the attach on a CANCELED job', async () => {
+ await settleSpriteAnimationJob(trackJob({ status: 'canceled' }));
+ expect(attachTrackTuiResult).toHaveBeenCalled();
+ });
+
+ it('still runs the attach when staging the clip failed', async () => {
+ collectLocalAnimationClip.mockResolvedValue(false);
+ await settleSpriteAnimationJob(walkJob());
+ expect(attachTuiWalkResult).toHaveBeenCalled();
+ });
+
+ it('does nothing at all for a job that is not a sprite render', async () => {
+ expect(await settleSpriteAnimationJob({ kind: 'video', params: {} })).toBe(false);
+ expect(attachTuiWalkResult).not.toHaveBeenCalled();
+ expect(attachTrackTuiResult).not.toHaveBeenCalled();
+ });
+});
+
+describe('initSpriteLocalAnimationHook', () => {
+ it('files a job that settles while this process is up', async () => {
+ initSpriteLocalAnimationHook();
+ mediaJobEvents.emit('completed', walkJob());
+ await vi.waitFor(() => expect(attachTuiWalkResult).toHaveBeenCalled());
+ });
+
+ it('subscribes to failed and canceled too, not only completed', async () => {
+ initSpriteLocalAnimationHook();
+ mediaJobEvents.emit('failed', walkJob({ status: 'failed' }));
+ await vi.waitFor(() => expect(attachTuiWalkResult).toHaveBeenCalledTimes(1));
+ mediaJobEvents.emit('canceled', walkJob({ status: 'canceled' }));
+ await vi.waitFor(() => expect(attachTuiWalkResult).toHaveBeenCalledTimes(2));
+ });
+
+ it('is idempotent — a double init must not file every clip twice', async () => {
+ initSpriteLocalAnimationHook();
+ initSpriteLocalAnimationHook();
+ mediaJobEvents.emit('completed', walkJob());
+ await vi.waitFor(() => expect(attachTuiWalkResult).toHaveBeenCalledTimes(1));
+ });
+
+ it('stops listening after reset, so a suite that re-inits does not leak handlers', async () => {
+ initSpriteLocalAnimationHook();
+ __testing.reset();
+ mediaJobEvents.emit('completed', walkJob());
+ await Promise.resolve();
+ expect(attachTuiWalkResult).not.toHaveBeenCalled();
+ });
+});
+
+describe('reconcileSettledSpriteJobs (boot pass)', () => {
+ it('files jobs that reached a terminal state while the process was DOWN', async () => {
+ // These emit nothing — they are simply sitting in the restored archive. The
+ // live subscription can never see them, so without this pass the run is only
+ // ever resolved by a wall-clock backstop a day later (and never at all on
+ // the track lane).
+ queuedJobs = [walkJob(), trackJob({ status: 'failed' })];
+ expect(await reconcileSettledSpriteJobs()).toBe(2);
+ expect(attachTuiWalkResult).toHaveBeenCalled();
+ expect(attachTrackTuiResult).toHaveBeenCalled();
+ });
+
+ it('leaves still-queued and still-running jobs alone', async () => {
+ // Those will emit their own terminal event later; settling them now would
+ // file an error over a render that is still going.
+ queuedJobs = [walkJob({ status: 'queued' }), trackJob({ status: 'running' })];
+ expect(await reconcileSettledSpriteJobs()).toBe(0);
+ expect(attachTuiWalkResult).not.toHaveBeenCalled();
+ expect(attachTrackTuiResult).not.toHaveBeenCalled();
+ });
+
+ it('skips terminal jobs that are not sprite renders', async () => {
+ queuedJobs = [{ id: 'x', kind: 'video', status: 'completed', params: { musicVideo: {} } }];
+ expect(await reconcileSettledSpriteJobs()).toBe(0);
+ });
+
+ it('keeps going when one job throws, rather than abandoning the rest', async () => {
+ attachTuiWalkResult.mockRejectedValueOnce(new Error('disk full'));
+ queuedJobs = [walkJob(), trackJob()];
+ await reconcileSettledSpriteJobs();
+ expect(attachTrackTuiResult).toHaveBeenCalled();
+ });
+
+ it('runs on init without being awaited by it', async () => {
+ queuedJobs = [walkJob()];
+ initSpriteLocalAnimationHook();
+ await vi.waitFor(() => expect(attachTuiWalkResult).toHaveBeenCalled());
+ });
+});
diff --git a/server/services/sprites/localAnimationRender.js b/server/services/sprites/localAnimationRender.js
index dea73993b5..fd27529f52 100644
--- a/server/services/sprites/localAnimationRender.js
+++ b/server/services/sprites/localAnimationRender.js
@@ -30,11 +30,13 @@ import { join } from 'path';
import { copyFile } from 'fs/promises';
import { PATHS, pathExists } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
-import { getVideoModels } from '../../lib/mediaModels.js';
+import { getVideoModels, requiredModelCacheGroups } from '../../lib/mediaModels.js';
import { inspectModelCache, findCachedRepoFiles } from '../../lib/hfCache.js';
import { BYOV_RUNTIME_INFO, isByovRuntimeReady } from '../videoGen/runtimes.js';
-import { enqueueJob, getJob, mediaJobEvents } from '../mediaJobQueue/index.js';
+import { enqueueJob, getJob } from '../mediaJobQueue/index.js';
+import { minimaxH3ControlError } from '../videoGen/minimaxH3Controls.js';
import { LOCAL_VIDEO_PROVIDER_ID } from './animationWorkflow.js';
+import { WALK_TRACK } from './animationTargets.js';
// H3's video VAE decodes only 17n+5 frame counts and the model runs at a fixed
// 24 fps (both enforced by `videoGen/minimaxH3Controls.js`), so a sprite's
@@ -153,27 +155,33 @@ export const pickLocalRenderCanvas = (model, { width, height } = {}) => {
/**
* Whether every weight `model` needs is resolvable in the HF cache.
*
- * Coarse ON PURPOSE relative to the render path's own preflight
- * (`assertMiniMaxH3Preflight`), which additionally verifies the pinned runtime
- * checkout is clean. Restating that contract here would be a second copy free to
- * drift; this answers the question the UI actually asks — "is there any point
- * offering the button?" — and a deeper failure still surfaces as a captured
- * error on the run record, naming the exact missing piece.
+ * `requiredModelCacheGroups` is what makes this correct on BOTH platforms: the
+ * MLX row pins its upstream FL2VA checkpoint in `requiredWeights`, while the
+ * CUDA row pins its ~144 GB diffusers subset in `repoFiles` against its own
+ * (~498 GB) repo. Checking only `requiredWeights` reported a CUDA download that
+ * was interrupted after a few shards as complete, so the picker offered a render
+ * that then died inside the runner's cache-only resolve.
+ *
+ * Still coarser than the render path's own preflight (`assertMiniMaxH3Preflight`
+ * additionally verifies the pinned runtime checkout is clean). Restating THAT
+ * here would be a second copy free to drift; this answers the question the UI
+ * asks — "is there any point offering the button?" — and a deeper failure still
+ * surfaces as a captured error on the run record naming the exact missing piece.
*/
const localModelWeightsCached = async (model) => {
- const [base, ...deps] = await Promise.all([
+ const groups = requiredModelCacheGroups(model);
+ const [base, ...resolved] = await Promise.all([
inspectModelCache(model.repo, model.revision ? { revision: model.revision } : {}),
- ...(Array.isArray(model.requiredWeights) ? model.requiredWeights : []).map((dep) => (
- Array.isArray(dep?.files) && dep.files.length && dep.repo
- ? findCachedRepoFiles(dep.repo, dep.files, dep.revision ? { revision: dep.revision } : {})
+ ...groups.map((group) => (
+ group?.repo && Array.isArray(group.files) && group.files.length
+ ? findCachedRepoFiles(group.repo, group.files, group.revision ? { revision: group.revision } : {})
: Promise.resolve(null)
)),
]);
if (!base.cached) return false;
- // findCachedRepoFiles resolves to null when ANY pinned file is missing, so a
- // dependency that has no resolvable set is a hard no — but a model with no
- // requiredWeights at all (the CUDA row) never enters this loop.
- return deps.every((resolved) => Array.isArray(resolved) && resolved.length > 0);
+ // findCachedRepoFiles resolves to null when ANY pinned file is missing. A row
+ // with no groups at all never enters this loop, so its base snapshot stands.
+ return resolved.every((files) => Array.isArray(files) && files.length > 0);
};
/**
@@ -266,10 +274,24 @@ export async function planLocalAnimationRender({ durationSeconds } = {}) {
{ status: 500, code: 'LOCAL_VIDEO_MODEL_MISCONFIGURED' },
);
}
+ const fps = localRenderFps(model);
+ // Validate the plan against the RENDER BOUNDARY'S OWN gate rather than a
+ // restatement of it. `data/media-models.json` is user-editable, so an install
+ // that edits `fpsOptions` or the frame grid would otherwise get a plan this
+ // module happily accepts and a job that 400s hours later inside the runner
+ // args. Calling the real checker means every current and future H3 control
+ // rule is inherited here for free instead of drifting from a local copy.
+ const controlError = minimaxH3ControlError({ model, numFrames, fps });
+ if (controlError) {
+ throw new ServerError(
+ `${model.name} cannot render this clip: ${controlError.message}`,
+ { status: 500, code: 'LOCAL_VIDEO_MODEL_MISCONFIGURED' },
+ );
+ }
return {
model,
numFrames,
- fps: localRenderFps(model),
+ fps,
chooseCanvas: (anchorSize) => pickLocalRenderCanvas(model, anchorSize),
};
}
@@ -290,8 +312,24 @@ export const localRenderManifest = (plan, canvas) => ({
});
/**
- * Queue the render. Returns the media-job id synchronously enough to stamp on
- * the run record before anything awaits the result.
+ * The media-job params tag that makes a queued render self-describing.
+ *
+ * Load-bearing, not decoration: the completion hook decodes ONLY this — it holds
+ * no in-memory state — so a render that outlives the request, the client, or the
+ * whole server process can still be filed onto the run it belongs to. The
+ * shipped `spriteWalk` tag rides along for the walk lane because the client's
+ * `useSpritePendingRenders` rehydrate already keys off it (`owner: 'sprites'` +
+ * `params.spriteWalk.direction`), so a browser reload mid-render shows the
+ * direction as in-flight instead of re-enabling its Generate button.
+ */
+export const spriteAnimationJobTag = ({ recordId, runId, track, direction }) => ({
+ spriteAnimation: { recordId, runId, track, direction },
+ ...(track === WALK_TRACK ? { spriteWalk: { recordId, direction } } : {}),
+});
+
+/**
+ * Queue the render. Returns the media-job id synchronously so the caller can
+ * stamp it on an already-persisted run record.
*
* `hidden: true` keeps the clip out of the user's video gallery: it is an
* intermediate the sprite pipeline consumes, not a video they asked to keep.
@@ -299,10 +337,11 @@ export const localRenderManifest = (plan, canvas) => ({
* explicitly chose the LOCAL provider, and the unattended helper's default
* routing could send the job to a peer instead.
*/
-export function enqueueLocalAnimationRender({ plan, canvas, prompt, inputAbs, owner }) {
+export function enqueueLocalAnimationRender({ plan, canvas, prompt, inputAbs, recordId, runId, track, direction }) {
return enqueueJob({
kind: 'video',
- owner,
+ // The owner the client's sprite pending-render hook filters on.
+ owner: 'sprites',
params: {
modelId: plan.model.id,
prompt,
@@ -312,83 +351,67 @@ export function enqueueLocalAnimationRender({ plan, canvas, prompt, inputAbs, ow
numFrames: plan.numFrames,
fps: plan.fps,
hidden: true,
+ ...spriteAnimationJobTag({ recordId, runId, track, direction }),
},
}).jobId;
}
-const TERMINAL_JOB_STATUSES = Object.freeze(['completed', 'failed', 'canceled']);
-
/**
- * Resolve when `jobId` reaches a terminal state, as `{ status, error }`.
+ * Copy a finished render's clip to where the deterministic postprocess reads it.
*
- * The immediate re-check after the listeners are attached is load-bearing, not
- * belt-and-braces: `enqueueJob` starts the worker synchronously, so a job that
- * fails fast (an unconfigured interpreter, a buildArgs throw) can settle in the
- * gap between the enqueue and this subscription — and a missed terminal event
- * strands the run at `rendering` forever with nothing to advance it.
- */
-export function awaitMediaJobTerminalState(jobId) {
- return new Promise((resolve) => {
- let settled = false;
- const settle = (job) => {
- if (settled || job?.id !== jobId) return;
- settled = true;
- mediaJobEvents.off('completed', settle);
- mediaJobEvents.off('failed', settle);
- mediaJobEvents.off('canceled', settle);
- resolve({ status: job.status, error: job.error || null });
- };
- mediaJobEvents.on('completed', settle);
- mediaJobEvents.on('failed', settle);
- mediaJobEvents.on('canceled', settle);
- const current = getJob(jobId);
- if (current && TERMINAL_JOB_STATUSES.includes(current.status)) settle(current);
- });
-}
-
-/**
- * Drive one queued local render to completion and put its clip where the
- * deterministic postprocess expects it.
+ * NEVER throws. The caller's contract is that the attach runs either way — the
+ * attach already treats "no clip at videoAbs" as a terminal, user-visible error,
+ * so a copy failure that propagated instead would skip that attach and strand
+ * the run at `rendering` with nothing to move it (permanently, on the track
+ * lane, whose in-flight guard then refuses every retry).
*
- * Resolves either way — like the grok lane, the attach decides the outcome from
- * whether the MP4 actually landed on disk, so a failure here needs only to leave
- * the destination absent (and say why in the log).
+ * COPY rather than move: the (hidden) gallery record generateVideo wrote still
+ * points at this file, and its thumbnail sits beside it.
*/
-export async function collectLocalAnimationRender({ jobId, videoAbs, label }) {
- const { status, error } = await awaitMediaJobTerminalState(jobId);
- if (status !== 'completed') {
- console.error(`❌ ${label} local render ${status} [${jobId.slice(0, 8)}]: ${error || 'no error reported'}`);
- return;
- }
+export async function collectLocalAnimationClip({ jobId, videoAbs, label }) {
// generateVideo names its output after the job id (`filename = ${jobId}.mp4`).
const renderedAbs = join(PATHS.videos, `${jobId}.mp4`);
if (!await pathExists(renderedAbs)) {
- console.error(`❌ ${label} local render completed without an MP4 at ${renderedAbs}`);
- return;
+ console.error(`❌ ${label} local render reported complete with no MP4 at ${renderedAbs}`);
+ return false;
+ }
+ try {
+ await copyFile(renderedAbs, videoAbs);
+ return true;
+ } catch (err) {
+ console.error(`❌ ${label} could not stage the local clip into its run: ${err?.message || err}`);
+ return false;
}
- // COPY rather than move: the gallery record generateVideo wrote still points
- // at this file (hidden, but real), and its thumbnail sits beside it. Moving it
- // would leave a history row pointing at nothing.
- await copyFile(renderedAbs, videoAbs);
}
/**
- * Whether a `rendering` local run is still genuinely live.
+ * What the media-job queue says about a `rendering` local run.
+ *
+ * FOUR states, and collapsing any pair of them breaks something concrete:
*
- * A local H3 render is a multi-HOUR job on current Apple Silicon, so the grok
- * lane's wall-clock staleness cutoff (its TUI hard cap plus a minute) would
- * declare a perfectly healthy render dead less than an hour in. The media job
- * is the real signal, and it survives a restart because the queue persists and
- * rehydrates both its queue and its archive.
+ * - `live` — queued or running. A local H3 clip is a multi-HOUR render, so
+ * the grok lane's wall-clock cutoff would call this dead.
+ * - `settling` — the job COMPLETED and the attach is in flight (or the boot hook
+ * is about to run it). Reading this as dead is the bug that
+ * mattered: the attach spends a second or two copying and
+ * hashing a 20–80 MB clip, and a detail poll landing in that gap
+ * would report a SUCCESSFUL render as "interrupted" — and, worse,
+ * unblock the in-flight guard so a second multi-hour render could
+ * be started for the same direction.
+ * - `dead` — failed or canceled, including the `interrupted by restart` the
+ * queue stamps on a job that was running when the server died.
+ * - `unknown` — no job id, or a job the archive has rolled past. NOT `dead`:
+ * that would error a live run the moment its job aged out.
*
- * Three outcomes, deliberately not two: a job the queue has never heard of is
- * `unknown`, NOT `terminal`. Collapsing those would turn "the archive has rolled
- * past this job" into "this render failed" and mark a live run errored.
+ * Only `dead` is decided here; `settling` and `unknown` defer to the caller's
+ * wall clock, which is generous enough that the boot hook wins the race.
*/
export const localRunLiveness = (run) => {
const jobId = run?.jobId;
if (typeof jobId !== 'string' || !jobId) return 'unknown';
const job = getJob(jobId);
if (!job) return 'unknown';
- return TERMINAL_JOB_STATUSES.includes(job.status) ? 'terminal' : 'live';
+ if (job.status === 'completed') return 'settling';
+ if (job.status === 'failed' || job.status === 'canceled') return 'dead';
+ return 'live';
};
diff --git a/server/services/sprites/localAnimationRender.test.js b/server/services/sprites/localAnimationRender.test.js
index 8db8b3c801..2560a2dcb2 100644
--- a/server/services/sprites/localAnimationRender.test.js
+++ b/server/services/sprites/localAnimationRender.test.js
@@ -30,7 +30,10 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
// each test states the environment it is about rather than depending on what
// this machine happens to have installed.
let videoModels = [];
-vi.mock('../../lib/mediaModels.js', () => ({
+// Only the CATALOG accessor is stubbed; the pure row-shape helpers stay real so
+// "what must be cached" is exercised rather than restated in a mock.
+vi.mock('../../lib/mediaModels.js', async (importOriginal) => ({
+ ...await importOriginal(),
getVideoModels: () => videoModels,
}));
@@ -49,22 +52,19 @@ vi.mock('../../lib/hfCache.js', () => ({
const enqueued = [];
let queueJobs = new Map();
-const { EventEmitter } = await import('events');
-const mediaJobEvents = new EventEmitter();
vi.mock('../mediaJobQueue/index.js', () => ({
enqueueJob: (job) => {
enqueued.push(job);
return { jobId: `job-${enqueued.length}` };
},
getJob: (id) => queueJobs.get(id) || null,
- mediaJobEvents,
}));
const {
resolveLocalVideoModel, resolveLocalFrameCount, pickLocalRenderCanvas, localRenderFps,
getLocalAnimationProviderStatus, listAnimationProviders, planLocalAnimationRender,
- localRenderManifest, enqueueLocalAnimationRender, awaitMediaJobTerminalState,
- collectLocalAnimationRender, localRunLiveness,
+ localRenderManifest, enqueueLocalAnimationRender, collectLocalAnimationClip,
+ localRunLiveness, spriteAnimationJobTag,
} = await import('./localAnimationRender.js');
// The lane VOCABULARY (ids, the request normalizer, the run-record predicate)
// lives in animationWorkflow.js so lib/spriteValidation.js can build its enum
@@ -105,7 +105,6 @@ beforeEach(() => {
cachedFiles = ['/cache/a.safetensors'];
enqueued.length = 0;
queueJobs = new Map();
- mediaJobEvents.removeAllListeners();
});
describe('resolveLocalVideoModel', () => {
@@ -368,13 +367,20 @@ describe('localRenderManifest', () => {
});
describe('enqueueLocalAnimationRender', () => {
+ const enqueueWalk = () => enqueueLocalAnimationRender({
+ plan: { model: H3_MLX, numFrames: 141, fps: 24 },
+ canvas: { width: 768, height: 1344 },
+ prompt: 'walk east',
+ inputAbs: '/in.png',
+ recordId: 'hero',
+ runId: 'walk-east-abc12345',
+ track: 'walk',
+ direction: 'east',
+ });
+
it('queues an image-conditioned, hidden render at the planned geometry', () => {
- const plan = { model: H3_MLX, numFrames: 141, fps: 24 };
- const jobId = enqueueLocalAnimationRender({
- plan, canvas: { width: 768, height: 1344 }, prompt: 'walk east', inputAbs: '/in.png', owner: 'sprite-walk:a:east',
- });
- expect(jobId).toBe('job-1');
- expect(enqueued[0]).toMatchObject({ kind: 'video', owner: 'sprite-walk:a:east' });
+ expect(enqueueWalk()).toBe('job-1');
+ expect(enqueued[0]).toMatchObject({ kind: 'video', owner: 'sprites' });
expect(enqueued[0].params).toMatchObject({
modelId: 'minimax_h3_8bit',
prompt: 'walk east',
@@ -388,73 +394,62 @@ describe('enqueueLocalAnimationRender', () => {
hidden: true,
});
});
-});
-describe('awaitMediaJobTerminalState', () => {
- it('resolves when the queue emits the job terminal', async () => {
- const pending = awaitMediaJobTerminalState('job-9');
- mediaJobEvents.emit('completed', { id: 'job-9', status: 'completed' });
- await expect(pending).resolves.toEqual({ status: 'completed', error: null });
- });
-
- it('ignores terminal events for OTHER jobs', async () => {
- let settled = false;
- const pending = awaitMediaJobTerminalState('job-9').then((r) => { settled = true; return r; });
- mediaJobEvents.emit('failed', { id: 'job-other', status: 'failed', error: 'nope' });
- await Promise.resolve();
- expect(settled).toBe(false);
- mediaJobEvents.emit('failed', { id: 'job-9', status: 'failed', error: 'boom' });
- await expect(pending).resolves.toEqual({ status: 'failed', error: 'boom' });
- });
-
- it('settles from queue state when the job ALREADY finished before we subscribed', async () => {
- // enqueueJob starts the worker synchronously, so a fast failure can settle
- // in the gap before this subscription — without the re-check the run would
- // sit at 'rendering' forever.
- queueJobs.set('job-fast', { id: 'job-fast', status: 'failed', error: 'PYTHON not configured' });
- await expect(awaitMediaJobTerminalState('job-fast')).resolves.toEqual({
- status: 'failed', error: 'PYTHON not configured',
+ it('tags the job so the completion hook can file it with no in-memory state', () => {
+ enqueueWalk();
+ expect(enqueued[0].params.spriteAnimation).toEqual({
+ recordId: 'hero', runId: 'walk-east-abc12345', track: 'walk', direction: 'east',
});
});
- it('does NOT settle early for a job the queue reports still running', async () => {
- queueJobs.set('job-live', { id: 'job-live', status: 'running' });
- let settled = false;
- awaitMediaJobTerminalState('job-live').then(() => { settled = true; });
- await Promise.resolve();
- expect(settled).toBe(false);
+ it('also carries the shipped spriteWalk tag the client rehydrate keys off', () => {
+ // owner 'sprites' + params.spriteWalk.direction is what
+ // useSpritePendingRenders reads, so a browser reload mid-render still shows
+ // the direction in flight instead of re-enabling its Generate button.
+ enqueueWalk();
+ expect(enqueued[0].params.spriteWalk).toEqual({ recordId: 'hero', direction: 'east' });
+ });
+
+ it('leaves spriteWalk OFF a non-walk track, whose cards do not use that map', () => {
+ expect(spriteAnimationJobTag({
+ recordId: 'hero', runId: 'scanner-east-abc', track: 'scanner', direction: 'east',
+ })).toEqual({
+ spriteAnimation: { recordId: 'hero', runId: 'scanner-east-abc', track: 'scanner', direction: 'east' },
+ });
});
});
-describe('collectLocalAnimationRender', () => {
+describe('collectLocalAnimationClip', () => {
const videosDir = join(TEST_ROOT, 'videos');
- it('copies the rendered clip to where the postprocess reads it', async () => {
+ it('stages the rendered clip where the postprocess reads it', async () => {
await mkdir(videosDir, { recursive: true });
await writeFile(join(videosDir, 'job-ok.mp4'), 'clip-bytes');
const dest = join(TEST_ROOT, 'run', 'source-video.mp4');
await mkdir(join(TEST_ROOT, 'run'), { recursive: true });
- const pending = collectLocalAnimationRender({ jobId: 'job-ok', videoAbs: dest, label: 'walk east' });
- mediaJobEvents.emit('completed', { id: 'job-ok', status: 'completed' });
- await pending;
+ await expect(collectLocalAnimationClip({ jobId: 'job-ok', videoAbs: dest, label: 'walk east' }))
+ .resolves.toBe(true);
expect(await readFile(dest, 'utf8')).toBe('clip-bytes');
});
- it('leaves the destination ABSENT on a failed job, so the attach reports the failure', async () => {
+ it('reports false — never throws — when the render wrote no MP4', async () => {
const dest = join(TEST_ROOT, 'run2', 'source-video.mp4');
await mkdir(join(TEST_ROOT, 'run2'), { recursive: true });
- const pending = collectLocalAnimationRender({ jobId: 'job-bad', videoAbs: dest, label: 'walk east' });
- mediaJobEvents.emit('failed', { id: 'job-bad', status: 'failed', error: 'oom' });
- await pending;
+ await expect(collectLocalAnimationClip({ jobId: 'job-empty', videoAbs: dest, label: 'walk east' }))
+ .resolves.toBe(false);
await expect(readFile(dest, 'utf8')).rejects.toThrow();
});
- it('does not throw when a completed job wrote no MP4', async () => {
- const dest = join(TEST_ROOT, 'run3', 'source-video.mp4');
- await mkdir(join(TEST_ROOT, 'run3'), { recursive: true });
- const pending = collectLocalAnimationRender({ jobId: 'job-empty', videoAbs: dest, label: 'walk east' });
- mediaJobEvents.emit('completed', { id: 'job-empty', status: 'completed' });
- await expect(pending).resolves.toBeUndefined();
+ it('reports false — never throws — when the COPY itself fails', async () => {
+ // A throw here would skip the caller's attach, and the attach is the only
+ // thing that moves a run out of 'rendering'. On the track lane (no staleness
+ // normalization) that wedges the facing behind TRACK_RENDER_IN_PROGRESS
+ // forever.
+ await mkdir(videosDir, { recursive: true });
+ await writeFile(join(videosDir, 'job-nodir.mp4'), 'clip-bytes');
+ const dest = join(TEST_ROOT, 'no-such-dir', 'source-video.mp4');
+ await expect(collectLocalAnimationClip({ jobId: 'job-nodir', videoAbs: dest, label: 'walk east' }))
+ .resolves.toBe(false);
});
});
@@ -466,16 +461,25 @@ describe('localRunLiveness', () => {
expect(localRunLiveness({ jobId: 'j' })).toBe('live');
});
- it('reports a settled job as terminal', () => {
- for (const status of ['completed', 'failed', 'canceled']) {
+ it('reports a failed or canceled job as DEAD', () => {
+ for (const status of ['failed', 'canceled']) {
queueJobs.set('j', { id: 'j', status });
- expect(localRunLiveness({ jobId: 'j' })).toBe('terminal');
+ expect(localRunLiveness({ jobId: 'j' })).toBe('dead');
}
});
- it('reports UNKNOWN — not terminal — for a job the queue has forgotten', () => {
- // Collapsing this into 'terminal' would flip a live run to error the moment
- // its job aged out of the archive.
+ it('reports a COMPLETED job as settling, not dead', () => {
+ // The attach spends a second or two copying and hashing a 20-80 MB clip
+ // after the job completes. Calling that window dead would report a
+ // SUCCESSFUL render as interrupted — and unblock the in-flight guard, so a
+ // poll landing there could start a second multi-hour render.
+ queueJobs.set('j', { id: 'j', status: 'completed' });
+ expect(localRunLiveness({ jobId: 'j' })).toBe('settling');
+ });
+
+ it('reports UNKNOWN — not dead — for a job the queue has forgotten', () => {
+ // Collapsing this into 'dead' would flip a live run to error the moment its
+ // job aged out of the archive.
expect(localRunLiveness({ jobId: 'gone' })).toBe('unknown');
expect(localRunLiveness({})).toBe('unknown');
expect(localRunLiveness(null)).toBe('unknown');
diff --git a/server/services/sprites/paths.js b/server/services/sprites/paths.js
index d2e2ba63d6..7440ab96be 100644
--- a/server/services/sprites/paths.js
+++ b/server/services/sprites/paths.js
@@ -49,6 +49,13 @@ export const isSourcePipelinePath = (p) => typeof p === 'string' && p.includes(S
// postprocess reads it, and the walk service re-derives from it.
export const SOURCE_CLIP_NAME = 'source-video.mp4';
+// The record-relative home of one animation run, in the VENDOR-NEUTRAL layout
+// every new generation writes (migration 202 renamed the historical `grok/`
+// tree into it; RUN_DIR_MATCH below still accepts both prefixes on read).
+// Hoisted here when the local-render completion hook became the third consumer
+// — walk.js and animationTrackWorkflow.js had each declared their own copy.
+export const runRelPath = (runId) => `runs/${runId}`;
+
/**
* Normalize an asset-path field read out of an imported manifest to the
* record-relative form `spriteAssetUrl`/`resolveSpriteAssetPath` expect. The
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 2934706a58..60b2e0e691 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -32,7 +32,7 @@ import { getRecord, updateRecord } from './records.js';
import {
spriteDir, resolveSpriteAssetPath, toRecordRelativeAssetPath, altRunLayoutPath,
runDirOfPath, resolveDriftTolerantRel, isSourcePipelinePath, SOURCE_CLIP_NAME,
- rawFramesRelOf, RAW_FRAME_NAME,
+ rawFramesRelOf, RAW_FRAME_NAME, runRelPath,
} from './paths.js';
import {
requireCharacter, loadManifest,
@@ -63,8 +63,7 @@ import {
SCANNER_TRACK, sourceReferenceFor,
} from './animationTracks.js';
import {
- planLocalAnimationRender, enqueueLocalAnimationRender, collectLocalAnimationRender,
- localRenderManifest, localRunLiveness,
+ planLocalAnimationRender, enqueueLocalAnimationRender, localRenderManifest, localRunLiveness,
} from './localAnimationRender.js';
// #3152 — the anchor-invalidation sweep below must cover a USER-DEFINED track too:
// a stored row seeded from a directional anchor holds approvals descended from the
@@ -94,7 +93,6 @@ export const walkSetRelPath = (id) => `walk/${id}-walk-set-v1.json`;
// the historical `grok/<runId>/` layout into this one; the reader still scans
// `grok/` too (RUN_SCAN_DIRS) for pre-migration installs and forks, and
// RUN_DIR_MATCH (paths.js) still accepts both prefixes.
-const runRelPath = (runId) => `runs/${runId}`;
// The two on-disk homes a run can be found in: the neutral `runs/` layout (all
// new generations, post-migration) and `grok/` — both a straggler on an
// un-migrated install/fork AND where a source-pipeline import lands whenever its
@@ -291,29 +289,36 @@ function runCreatedAtMs(createdAt) {
// forever, surfaces regenerate, and the in-flight guard in startWalkGeneration
// stops treating it as live. RENDER_STALE_MS is the hard cap plus a buffer.
const RENDER_STALE_MS = WALK_TUI_TIMEOUT_MS + 60_000;
-// The LOCAL lane's backstop, used only when the media-job queue can no longer
-// answer for a run (its archive has rolled past that job). Deliberately a day
-// rather than grok's half hour: a local H3 clip is a multi-HOUR render on
-// current Apple Silicon, so anything tighter would report healthy work as dead.
+// The LOCAL lane's backstop, used only when the media-job queue cannot answer
+// for a run — it has no job id, its job has rolled out of the archive, or the
+// job COMPLETED and its attach has not landed yet. Deliberately a day rather
+// than grok's half hour: a local H3 clip is a multi-HOUR render on current
+// Apple Silicon, and the completion hook wins this race in every normal case.
const LOCAL_RENDER_STALE_MS = 24 * 60 * 60_000;
// Which lane a run came from, for logs shared by both.
const runProviderLabel = (run) => (isLocalProviderRun(run) ? 'local' : 'grok-tui');
const STALE_RENDER_ERROR = 'Walk render was interrupted (server restart or timeout) — regenerate to retry.';
function normalizeStaleRendering(run) {
if (run?.status !== 'rendering') return run;
- const staleAfterMs = isLocalProviderRun(run) ? LOCAL_RENDER_STALE_MS : RENDER_STALE_MS;
// A local render's real liveness signal is its queued media job, not the wall
// clock — the queue persists and rehydrates across restarts, so it answers
- // correctly for a render that has legitimately been going for hours AND for
- // one whose server died. The clock is only the fallback for `unknown` (no job
- // id, or a job the archive has forgotten), which is why the three-way liveness
- // is not collapsed to a boolean: treating `unknown` as `terminal` would error
- // a live run the moment its job aged out of the archive.
+ // correctly both for a render that has legitimately been going for hours and
+ // for one whose server died mid-flight.
+ //
+ // Only `dead` (failed / canceled, including the queue's own "interrupted by
+ // restart") decides anything here. `settling` — the job finished and the
+ // attach is copying and hashing a 20-80 MB clip — must NOT read as dead, or a
+ // detail poll landing in that window reports a SUCCESSFUL render as
+ // interrupted and, worse, unblocks the in-flight guard so a second multi-hour
+ // render can be started for the same direction. `unknown` must not either, or
+ // a live run errors the moment its job ages out of the archive. Both fall
+ // through to the (generous) local clock below.
if (isLocalProviderRun(run)) {
const liveness = localRunLiveness(run);
if (liveness === 'live') return run;
- if (liveness === 'terminal') return { ...run, status: 'error', postprocessError: STALE_RENDER_ERROR };
+ if (liveness === 'dead') return { ...run, status: 'error', postprocessError: STALE_RENDER_ERROR };
}
+ const staleAfterMs = isLocalProviderRun(run) ? LOCAL_RENDER_STALE_MS : RENDER_STALE_MS;
if (Date.now() - runCreatedAtMs(run.createdAt) <= staleAfterMs) return run;
return { ...run, status: 'error', postprocessError: STALE_RENDER_ERROR };
}
@@ -1073,19 +1078,13 @@ async function startWalkGenerationImpl(recordId, body) {
const prompt = buildWalkVideoPrompt({ name: record.name, direction, chromaKey, correctionPrompt });
const videoAbs = join(generatedAbs, 'source-video.mp4');
const grokPath = settings.imageGen?.grok?.grokPath;
- // The local job id has to be on the run record BEFORE anything awaits it —
- // `localRunLiveness` reads it to tell a live multi-hour render from one the
- // server died inside, and a run saved without it would read as `unknown`
- // forever. `enqueueJob` returns synchronously, so there is no window here.
- const jobId = localPlan
- ? enqueueLocalAnimationRender({
- plan: localPlan, canvas, prompt, inputAbs, owner: `sprite-walk:${recordId}:${direction}`,
- })
- : null;
-
- // Run record BEFORE the render starts: a crash between the two leaves an inert
- // 'rendering' run (harmless, regenerable) rather than a session the attach
- // can't file. `shellSession` is the id the walk card deep-links to.
+ // Run record BEFORE the job is queued: the completion hook finds the run by
+ // `runId` out of the job's own params, so the record must already exist when
+ // the job can first settle. (The grok lane persists first for the mirror
+ // reason — a crash between the two leaves an inert 'rendering' run rather
+ // than a session the attach can't file.) `shellSession` is the id the walk
+ // card deep-links to; a local render is a queued media job, not a PTY, so it
+ // carries `jobId` instead — the two are mutually exclusive on purpose.
const now = new Date().toISOString();
const run = {
schemaVersion: 1,
@@ -1097,8 +1096,6 @@ async function startWalkGenerationImpl(recordId, body) {
id: runId,
// The TUI run id doubles as the attachable Shell session id (executeTuiRun
// registers the PTY under this id), so the card can link to /shell/<id>.
- // A local render is a queued media job, not a PTY, so it carries `jobId`
- // instead — the two are mutually exclusive on purpose.
shellSession: runId,
characterId: recordId,
direction,
@@ -1115,21 +1112,31 @@ async function startWalkGenerationImpl(recordId, body) {
createdAt: now,
// Spread LAST so the local lane's provider/geometry provenance overrides the
// grok defaults above rather than being silently overwritten by them.
- ...(localPlan ? { ...localRenderManifest(localPlan, canvas), jobId, shellSession: null } : {}),
+ ...(localPlan ? { ...localRenderManifest(localPlan, canvas), shellSession: null } : {}),
};
await saveRunRecord(recordId, run);
- // Fire the render off fire-and-forget (do NOT await — this impl holds the
- // per-record write tail, which a long render must not). Completion re-enters
- // the tail via attachTuiWalkResult; errors are captured onto the run record
- // (no request lifecycle to bubble to).
if (localPlan) {
- collectLocalAnimationRender({ jobId, videoAbs, label: `sprite walk ${recordId}/${direction}` })
- .then(() => walkWriteTail(recordId, () => attachTuiWalkResult(recordId, runId, videoAbs)))
- .catch((err) => console.error(`❌ sprite walk local render crashed ${recordId}/${runId}: ${err?.message || err}`));
+ // Queued AFTER the record is durable. Nothing here awaits the render: the
+ // boot-registered completion hook stages the clip and runs the attach, which
+ // is what lets a render outlive this request, the client, and a restart.
+ const jobId = enqueueLocalAnimationRender({
+ plan: localPlan, canvas, prompt, inputAbs, recordId, runId, track: WALK_TRACK, direction,
+ });
+ // Stamped in a SECOND write so a failure here cannot strand the job: the
+ // hook already has everything it needs from the job's own params, and a run
+ // that misses this only degrades `localRunLiveness` to `unknown`, whose
+ // wall-clock fallback still resolves it.
+ run.jobId = jobId;
+ await saveRunRecord(recordId, run);
console.log(`🚶 sprite walk local render started ${recordId}/${runId} (job ${jobId.slice(0, 8)}, ${localPlan.numFrames}f @ ${localPlan.fps}fps)`);
return { runId, direction, duration, provider: 'local', jobId };
}
+
+ // Fire the observable grok-tui render fire-and-forget (do NOT await — this
+ // impl holds the per-record write tail, which a ~10-min render must not).
+ // Completion re-enters the tail via attachTuiWalkResult; errors are captured
+ // onto the run record (no request lifecycle to bubble to).
runWalkTuiRender(recordId, {
runId, direction, grokPath, task: buildGrokI2vTask({ prompt, inputAbs, videoAbs, duration }),
generatedAbs, videoAbs,
diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.js
index a92583e015..b230633cab 100644
--- a/server/services/sprites/walk.test.js
+++ b/server/services/sprites/walk.test.js
@@ -589,7 +589,12 @@ describe('startWalkGeneration — local render lane (#4876)', () => {
expect(res.jobId).toBe('mjob-1');
// No PTY exists, so the card must not offer a Shell deep-link.
expect(res.shellSession).toBeUndefined();
- expect(enqueuedVideoJobs[0]).toMatchObject({ kind: 'video', owner: `sprite-walk:${id}:east` });
+ // owner 'sprites' + the spriteWalk tag is the shipped contract the client's
+ // pending-render rehydrate reads; spriteAnimation is what the durable
+ // completion hook decodes.
+ expect(enqueuedVideoJobs[0]).toMatchObject({ kind: 'video', owner: 'sprites' });
+ expect(enqueuedVideoJobs[0].params.spriteWalk).toEqual({ recordId: id, direction: 'east' });
+ expect(enqueuedVideoJobs[0].params.spriteAnimation).toMatchObject({ recordId: id, track: 'walk', direction: 'east' });
expect(enqueuedVideoJobs[0].params).toMatchObject({
modelId: 'minimax_h3_8bit',
mode: 'image',