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: file each sprite animation run once, and give the track lane a stranded-run backstop
[._.]/ Adam Eivy7a025138d360
diff --git a/server/services/sprites/animationTrackWorkflow.js b/server/services/sprites/animationTrackWorkflow.jsindex 44e0b25e64..c2359ce27c 100644--- a/server/services/sprites/animationTrackWorkflow.js+++ b/server/services/sprites/animationTrackWorkflow.js@@ -47,6 +47,7 @@ import { GROK_TUI_ID } from '../../lib/grok.js';import { resolveGrokDuration } from '../../lib/grokVideoClip.js';import {planLocalAnimationRender, enqueueLocalAnimationRender, localRenderManifest,+ normalizeStaleAnimationRun,} from './localAnimationRender.js';import { getSettings } from '../settings.js';import { getRecord, listRecords } from './records.js';@@ -59,16 +60,17 @@ 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, runRelPath } from './paths.js';+import {+ spriteDir, resolveSpriteAssetPath, SOURCE_CLIP_NAME, runRelPath, RUN_RECORD_NAME,+} from './paths.js';import { prepareWalkAnchorChromaInput, runWalkPostprocess } from './walkPostprocess.js';import { verifyPackagedFrames } from './walkFrames.js';import {resolveChromaKey, withAnimationWriteTail, lockedAnchorFor, lockedMainFor,GROK_TUI_IDLE_MS, GROK_TUI_TIMEOUT_MS, grokTuiProvider, buildGrokI2vTask,- resolveAnimationProvider, isLocalProviderRun,+ resolveAnimationProvider, isLocalProviderRun, runCreatedAtMs,} from './animationWorkflow.js';-const RUN_RECORD_NAME = 'animation-run.json';/*** The facings a track is authored across: every direction for a directional@@ -116,7 +118,19 @@ async function saveRun(recordId, run) {await atomicWrite(join(dir, RUN_RECORD_NAME), run);}-/** Every run on disk belonging to `trackId`, newest first. */+/**+ * Every run on disk belonging to `trackId`, newest first.+ *+ * Stranded `rendering` runs are normalized to `error` at READ time — never+ * persisted — by the same rule the walk lane uses. Without it a run whose render+ * could no longer be resolved (its server died and the completion hook could not+ * reach it) sits at `rendering` forever, and the in-flight guard below then+ * refuses every regenerate for that facing with TRACK_RENDER_IN_PROGRESS — with+ * no per-run delete and `reopenTrackDirection` only touching APPROVED runs, that+ * is unrecoverable short of hand-editing the record. The walk lane always had+ * this backstop; the track lane never did, and the local lane's multi-hour+ * renders made the gap materially more reachable.+ */async function trackRuns(trackId, recordId) {const runsDir = join(spriteDir(recordId), 'runs');const entries = await readdir(runsDir, { withFileTypes: true }).catch(() => []);@@ -124,9 +138,16 @@ async function trackRuns(trackId, recordId) {readJSONFile(join(runsDir, entry.name, RUN_RECORD_NAME), null))));return runs.filter((run) => run?.track === trackId)- .sort((a, b) => Date.parse(b.createdAt || 0) - Date.parse(a.createdAt || 0));+ .map((run) => normalizeStaleAnimationRun(run, staleRenderError(trackId)))+ .sort((a, b) => runCreatedAtMs(b.createdAt) - runCreatedAtMs(a.createdAt));}+/** The read-time message a stranded run carries, named for the track it is on. */+const staleRenderError = (trackId) => (+ `The ${effectiveTrack(trackId).label.toLowerCase()} render was interrupted `+ + '(server restart or timeout) — regenerate to retry.'+);+/*** The track's authoring state: `{ track, definition, selection, set, runs }`.*diff --git a/server/services/sprites/animationTrackWorkflow.test.js b/server/services/sprites/animationTrackWorkflow.test.jsindex d3733a500e..b6578b4e28 100644--- a/server/services/sprites/animationTrackWorkflow.test.js+++ b/server/services/sprites/animationTrackWorkflow.test.js@@ -18,7 +18,7 @@ import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';import { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { mkdir, writeFile } from 'fs/promises';+import { mkdir, writeFile, readFile } from 'fs/promises';import { createHash } from 'crypto';import { lockAllAnchors, placeCandidate, expectCarriesCorrection } from './spriteTestFixtures.js';@@ -97,14 +97,18 @@ vi.mock('../../lib/hfCache.js', async (importOriginal) => ({findCachedRepoFiles: async () => ['/snap/a.safetensors'],}));const enqueuedVideoJobs = [];+// Job states are controllable so the staleness tests can state the queue answer+// they are about; an enqueue defaults its job to running.+const queuedJobsById = new Map();vi.mock('../mediaJobQueue/index.js', async (importOriginal) => ({...await importOriginal(),enqueueJob: (job) => {const id = `mjob-${enqueuedVideoJobs.length + 1}`;enqueuedVideoJobs.push({ id, ...job });+ queuedJobsById.set(id, { id, status: 'running' });return { jobId: id, position: 1, status: 'queued' };},- getJob: (id) => ({ id, status: 'running' }),+ getJob: (id) => queuedJobsById.get(id) || null,}));const records = await import('./records.js');@@ -343,6 +347,7 @@ describe('local render lane (#4876)', () => {beforeEach(() => {localRuntimeReady = true;enqueuedVideoJobs.length = 0;+ queuedJobsById.clear();});it.each(TRACKS)('$id defaults to the grok TUI when no provider is named', async (track) => {@@ -409,6 +414,84 @@ describe('local render lane (#4876)', () => {});});+// A track run stuck at `rendering` used to be UNRECOVERABLE: the in-flight guard+// 409s every regenerate for that facing, there is no per-run delete, and+// `reopenTrackDirection` only touches APPROVED runs. The walk lane always had a+// read-time backstop for this; the track lane never did, and the local lane's+// multi-hour renders (whose only resolver is a completion hook that a pruned+// archive or a throwing attach can miss) made the gap materially reachable.+describe('stranded-run normalization (#4876)', () => {+ const runRecordPath = (recordId, runId) => join(+ TEST_ROOT, 'sprites', recordId, 'runs', runId, 'animation-run.json',+ );+ const backdateRun = async (recordId, runId, ms) => {+ const stored = JSON.parse(await readFile(runRecordPath(recordId, runId), 'utf8'));+ stored.createdAt = new Date(Date.now() - ms).toISOString();+ await writeFile(runRecordPath(recordId, runId), JSON.stringify(stored));+ };++ beforeEach(() => {+ localRuntimeReady = true;+ enqueuedVideoJobs.length = 0;+ queuedJobsById.clear();+ });++ it.each(TRACKS)('$id: a grok run past the TUI cap reads as an error and unblocks regenerate', async (track) => {+ const id = await track.seed(newId());+ const { runId } = await startTrackGeneration(track.id, id, track.body);+ await backdateRun(id, runId, 31 * 60_000 + 60_000);+ const run = (await getTrackState(track.id, id)).runs.find((r) => r.id === runId);+ expect(run.status).toBe('error');+ expect(run.postprocessError).toMatch(/interrupted/);+ // The point of the normalization: the facing becomes renderable again.+ await expect(startTrackGeneration(track.id, id, track.body)).resolves.toBeTruthy();+ });++ it.each(TRACKS)('$id: a grok run inside the cap is left alone', async (track) => {+ const id = await track.seed(newId());+ const { runId } = await startTrackGeneration(track.id, id, track.body);+ await backdateRun(id, runId, 5 * 60_000);+ const run = (await getTrackState(track.id, id)).runs.find((r) => r.id === runId);+ expect(run.status).toBe('rendering');+ });++ it.each(TRACKS)('$id: a LOCAL run stays live for hours while its job runs', async (track) => {+ const id = await track.seed(newId());+ const { runId } = await startTrackGeneration(track.id, id, { ...track.body, provider: 'local' });+ await backdateRun(id, runId, 5 * 60 * 60_000);+ const run = (await getTrackState(track.id, id)).runs.find((r) => r.id === runId);+ expect(run.status).toBe('rendering');+ });++ it.each(TRACKS)('$id: a LOCAL run whose job died reads as an error immediately', async (track) => {+ const id = await track.seed(newId());+ const { runId, jobId } = await startTrackGeneration(track.id, id, { ...track.body, provider: 'local' });+ queuedJobsById.set(jobId, { id: jobId, status: 'failed', error: 'interrupted by restart' });+ const run = (await getTrackState(track.id, id)).runs.find((r) => r.id === runId);+ expect(run.status).toBe('error');+ });++ it.each(TRACKS)('$id: a LOCAL run whose job COMPLETED is settling, not dead', async (track) => {+ // The attach is copying and hashing the clip. Calling that dead would report+ // a successful render as interrupted and unblock a duplicate render.+ const id = await track.seed(newId());+ const { runId, jobId } = await startTrackGeneration(track.id, id, { ...track.body, provider: 'local' });+ queuedJobsById.set(jobId, { id: jobId, status: 'completed' });+ const run = (await getTrackState(track.id, id)).runs.find((r) => r.id === runId);+ expect(run.status).toBe('rendering');+ });++ it.each(TRACKS)('$id: a LOCAL run the queue has forgotten falls back to a DAY, not the grok cap', async (track) => {+ const id = await track.seed(newId());+ const { runId, jobId } = await startTrackGeneration(track.id, id, { ...track.body, provider: 'local' });+ queuedJobsById.delete(jobId);+ await backdateRun(id, runId, 5 * 60 * 60_000);+ expect((await getTrackState(track.id, id)).runs.find((r) => r.id === runId).status).toBe('rendering');+ await backdateRun(id, runId, 25 * 60 * 60_000);+ expect((await getTrackState(track.id, id)).runs.find((r) => r.id === runId).status).toBe('error');+ });+});+describe('registry-derived authoring shape (#3136)', () => {it('authors a directional track across every facing and a non-directional one across row 0 only', () => {// The rule the two clones each hardcoded — `SPRITE_DIRECTIONS.every(...)` indiff --git a/server/services/sprites/animationWorkflow.js b/server/services/sprites/animationWorkflow.jsindex 056f636fcc..6d481f4055 100644--- a/server/services/sprites/animationWorkflow.js+++ b/server/services/sprites/animationWorkflow.js@@ -127,3 +127,17 @@ export const resolveAnimationProvider = (value) => {/** Whether a run record was produced by the local lane. */export const isLocalProviderRun = (run) => run?.provider === LOCAL_VIDEO_PROVIDER_ID;++/**+ * A run record's creation instant in ms, comparable across both record flavors.+ *+ * PortOS stamps `createdAt` as an ISO string (Date.parse handles it); imported+ * source-pipeline run records (#2895) stamp a Python `time.time()` epoch-seconds+ * FLOAT instead — `.localeCompare` on that threw and 500'd the whole detail+ * endpoint. Unparseable stays 0 so the ordering is total.+ */+export function runCreatedAtMs(createdAt) {+ if (typeof createdAt === 'number') return createdAt * 1000;+ const ms = Date.parse(createdAt);+ return Number.isNaN(ms) ? 0 : ms;+}diff --git a/server/services/sprites/localAnimationJobHook.js b/server/services/sprites/localAnimationJobHook.jsindex ba18c3728f..5eb9c71b76 100644--- a/server/services/sprites/localAnimationJobHook.js+++ b/server/services/sprites/localAnimationJobHook.js@@ -29,8 +29,10 @@import { join } from 'path';import { mediaJobEvents, listJobs } from '../mediaJobQueue/index.js';-import { spriteDir, runRelPath, SOURCE_CLIP_NAME } from './paths.js';+import { readJSONFile } from '../../lib/fileUtils.js';+import { spriteDir, runRelPath, SOURCE_CLIP_NAME, RUN_RECORD_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';@@ -57,27 +59,38 @@ const decodeSpriteAnimationJob = (job) => {* 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.+ *+ * Both the staging and the attach run INSIDE the per-record write tail: the+ * clip lands at the same path a user-triggered Reprocess reads, and a copy racing+ * that read would hand ffmpeg a truncated MP4 and error a previously-good run.*/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+ const runRel = runRelPath(runId);+ const videoAbs = join(spriteDir(recordId), runRel, 'generated', SOURCE_CLIP_NAME);+ return withAnimationWriteTail(recordId, async () => {+ // Settle a run ONCE. Neither attach looks at `run.status` — they guard only+ // frozen evidence (a finalized set, an approved run) — so re-entering here+ // for a run that is already `candidate` would re-stage the clip and re-run+ // the whole postprocess: minutes of frame decoding, and a manifest restamped+ // with TODAY's anchor for a clip rendered from a previous one. That is not+ // hypothetical, because the boot pass sweeps the archive unconditionally and+ // a job outlives the run it filed by the archive's whole TTL.+ const record = await readJSONFile(join(spriteDir(recordId), runRel, RUN_RECORD_NAME), null);+ if (record?.status !== 'rendering') return false;+ if (job.status === 'completed') {+ await collectLocalAnimationClip({ jobId: job.id, videoAbs, label });+ } else {+ console.log(`🎞️ ${label} local render ${job.status} — filing the run as errored`);+ }+ await (track === WALK_TRACK? attachTuiWalkResult(recordId, runId, videoAbs)- : attachTrackTuiResult(track, recordId, runId, videoAbs)- ));- return true;+ : attachTrackTuiResult(track, recordId, runId, videoAbs));+ return true;+ });}let terminalHandler = null;@@ -85,10 +98,10 @@ 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.+ * An unconditional sweep of the restored archive — every already-filed job in it+ * is a no-op, because `settleSpriteAnimationJob` refuses any run that is not+ * still `rendering`. That is what keeps this pass safe to run on every boot for+ * the archive's whole retention window.*/async function reconcileSettledSpriteJobs() {const jobs = listJobs({ kind: 'video', owner: 'sprites' })diff --git a/server/services/sprites/localAnimationJobHook.test.js b/server/services/sprites/localAnimationJobHook.test.jsindex f60dfdfe70..991a6b45f0 100644--- a/server/services/sprites/localAnimationJobHook.test.js+++ b/server/services/sprites/localAnimationJobHook.test.js@@ -24,6 +24,17 @@ vi.mock('./paths.js', async (importOriginal) => ({spriteDir: (recordId) => `/sprites/${recordId}`,}));+// The on-disk run records, keyed by the record path the hook derives. Every test+// states the run state it is about — which is the whole point of the settle+// guard, so it must not be faked away.+let runRecords = {};+vi.mock('../../lib/fileUtils.js', async (importOriginal) => ({+ ...await importOriginal(),+ readJSONFile: async (path) => runRecords[path] ?? null,+}));++const runPath = (recordId, runId) => `/sprites/${recordId}/runs/${runId}/animation-run.json`;+const collectLocalAnimationClip = vi.fn(async () => true);vi.mock('./localAnimationRender.js', () => ({collectLocalAnimationClip: (...args) => collectLocalAnimationClip(...args),@@ -64,10 +75,16 @@ const trackJob = (overrides = {}) => ({beforeEach(() => {queuedJobs = [];+ runRecords = {+ [runPath('hero', 'walk-east-abc12345')]: { id: 'walk-east-abc12345', status: 'rendering' },+ [runPath('hero', 'scanner-east-abc12345')]: { id: 'scanner-east-abc12345', status: 'rendering' },+ };collectLocalAnimationClip.mockClear();collectLocalAnimationClip.mockResolvedValue(true);- attachTuiWalkResult.mockClear();- attachTrackTuiResult.mockClear();+ attachTuiWalkResult.mockReset();+ attachTuiWalkResult.mockResolvedValue(undefined);+ attachTrackTuiResult.mockReset();+ attachTrackTuiResult.mockResolvedValue(undefined);});afterEach(() => __testing.reset());@@ -155,6 +172,53 @@ describe('settleSpriteAnimationJob', () => {});});+describe('settle guard — a run is filed exactly once', () => {+ it('does nothing for a run that is already a candidate', async () => {+ // The boot pass sweeps the archive unconditionally, so a job outlives the+ // run it filed by the archive's whole retention. Re-settling would re-stage+ // the clip and re-run the entire postprocess — minutes of frame decoding —+ // and restamp the manifest with TODAY's anchor for a clip rendered from a+ // previous one.+ runRecords[runPath('hero', 'walk-east-abc12345')] = { status: 'candidate' };+ expect(await settleSpriteAnimationJob(walkJob())).toBe(false);+ expect(collectLocalAnimationClip).not.toHaveBeenCalled();+ expect(attachTuiWalkResult).not.toHaveBeenCalled();+ });++ it('does nothing for a run already filed as an error', async () => {+ runRecords[runPath('hero', 'walk-east-abc12345')] = { status: 'error' };+ expect(await settleSpriteAnimationJob(walkJob({ status: 'failed' }))).toBe(false);+ expect(attachTuiWalkResult).not.toHaveBeenCalled();+ });++ it('does nothing while an earlier settle is still postprocessing', async () => {+ runRecords[runPath('hero', 'scanner-east-abc12345')] = { status: 'postprocessing' };+ expect(await settleSpriteAnimationJob(trackJob())).toBe(false);+ expect(attachTrackTuiResult).not.toHaveBeenCalled();+ });++ it('does nothing when the run record is gone entirely', async () => {+ // A deleted sprite, or a record the write never landed for. Filing into a+ // phantom directory would litter, not help.+ runRecords = {};+ expect(await settleSpriteAnimationJob(walkJob())).toBe(false);+ expect(attachTuiWalkResult).not.toHaveBeenCalled();+ });++ it('files a rendering run, then ignores a second terminal event for it', async () => {+ // The one-shot property end to end: the guard reads the record, so the+ // second call only skips because the FIRST one moved the run on.+ let filed = 0;+ attachTuiWalkResult.mockImplementation(async () => {+ filed += 1;+ runRecords[runPath('hero', 'walk-east-abc12345')] = { status: 'candidate' };+ });+ expect(await settleSpriteAnimationJob(walkJob())).toBe(true);+ expect(await settleSpriteAnimationJob(walkJob({ status: 'canceled' }))).toBe(false);+ expect(filed).toBe(1);+ });+});+describe('initSpriteLocalAnimationHook', () => {it('files a job that settles while this process is up', async () => {initSpriteLocalAnimationHook();@@ -166,8 +230,8 @@ describe('initSpriteLocalAnimationHook', () => {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));+ mediaJobEvents.emit('canceled', trackJob({ status: 'canceled' }));+ await vi.waitFor(() => expect(attachTrackTuiResult).toHaveBeenCalledTimes(1));});it('is idempotent — a double init must not file every clip twice', async () => {diff --git a/server/services/sprites/localAnimationRender.js b/server/services/sprites/localAnimationRender.jsindex fd27529f52..14692bcffd 100644--- a/server/services/sprites/localAnimationRender.js+++ b/server/services/sprites/localAnimationRender.js@@ -35,7 +35,9 @@ import { inspectModelCache, findCachedRepoFiles } from '../../lib/hfCache.js';import { BYOV_RUNTIME_INFO, isByovRuntimeReady } from '../videoGen/runtimes.js';import { enqueueJob, getJob } from '../mediaJobQueue/index.js';import { minimaxH3ControlError } from '../videoGen/minimaxH3Controls.js';-import { LOCAL_VIDEO_PROVIDER_ID } from './animationWorkflow.js';+import {+ LOCAL_VIDEO_PROVIDER_ID, isLocalProviderRun, GROK_TUI_TIMEOUT_MS, runCreatedAtMs,+} 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@@ -415,3 +417,55 @@ export const localRunLiveness = (run) => {if (job.status === 'failed' || job.status === 'canceled') return 'dead';return 'live';};++// How long a GROK run may sit at `rendering` before a read treats it as+// stranded: its TUI hard cap plus a buffer. Past that the session and its+// completion handler can only have died with the process.+const GROK_RENDER_STALE_MS = GROK_TUI_TIMEOUT_MS + 60_000;+// The LOCAL lane's equivalent, 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;++/**+ * Read-time normalization of a run stuck at `rendering`, shared by both lanes+ * and never persisted.+ *+ * A run's status is flipped to a terminal state by its attach. So a run still+ * `rendering` long past when that could have happened is stranded — the server+ * died mid-render, and the in-memory session or awaiter went with it. Presenting+ * it as an error at read time is what stops the UI polling forever, surfaces+ * regenerate, and releases the in-flight guard that would otherwise refuse every+ * retry for that facing.+ *+ * For a LOCAL run the media-job queue is a better signal than the clock: it+ * persists and rehydrates across restarts, so it answers correctly both for a+ * render that has legitimately been going for hours and for one whose server+ * died. 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 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 start for the same facing.+ * - `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, which is the backstop for the+ * cases the completion hook cannot reach at all: an archive pruned while the+ * server was down for longer than its TTL, or an attach that threw.+ */+export const normalizeStaleAnimationRun = (run, errorMessage) => {+ if (run?.status !== 'rendering') return run;+ const local = isLocalProviderRun(run);+ if (local) {+ const liveness = localRunLiveness(run);+ if (liveness === 'live') return run;+ if (liveness === 'dead') return { ...run, status: 'error', postprocessError: errorMessage };+ }+ const staleAfterMs = local ? LOCAL_RENDER_STALE_MS : GROK_RENDER_STALE_MS;+ if (Date.now() - runCreatedAtMs(run.createdAt) <= staleAfterMs) return run;+ return { ...run, status: 'error', postprocessError: errorMessage };+};diff --git a/server/services/sprites/paths.js b/server/services/sprites/paths.jsindex 7440ab96be..c74c14e2cb 100644--- a/server/services/sprites/paths.js+++ b/server/services/sprites/paths.js@@ -56,6 +56,11 @@ export const SOURCE_CLIP_NAME = 'source-video.mp4';// — walk.js and animationTrackWorkflow.js had each declared their own copy.export const runRelPath = (runId) => `runs/${runId}`;+// The per-run record inside that directory. Hoisted for the same reason+// `runRelPath` was: walk.js, animationTrackWorkflow.js, and the local-render+// completion hook each need to name the same file.+export const RUN_RECORD_NAME = 'animation-run.json';+/*** Normalize an asset-path field read out of an imported manifest to the* record-relative form `spriteAssetUrl`/`resolveSpriteAssetPath` expect. Thediff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex 60b2e0e691..8d615f1d74 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, runRelPath,+ rawFramesRelOf, RAW_FRAME_NAME, runRelPath, RUN_RECORD_NAME,} from './paths.js';import {requireCharacter, loadManifest,@@ -57,13 +57,14 @@ import { resolveGrokDuration } from '../../lib/grokVideoClip.js';import {withAnimationWriteTail, resolveChromaKey, lockedAnchorFor,GROK_TUI_IDLE_MS, GROK_TUI_TIMEOUT_MS, grokTuiProvider, buildGrokI2vTask,- resolveAnimationProvider, isLocalProviderRun,+ resolveAnimationProvider, isLocalProviderRun, runCreatedAtMs,} from './animationWorkflow.js';import {SCANNER_TRACK, sourceReferenceFor,} from './animationTracks.js';import {- planLocalAnimationRender, enqueueLocalAnimationRender, localRenderManifest, localRunLiveness,+ planLocalAnimationRender, enqueueLocalAnimationRender, localRenderManifest,+ normalizeStaleAnimationRun,} 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@@ -101,7 +102,6 @@ export const walkSetRelPath = (id) => `walk/${id}-walk-set-v1.json`;// through their selection entry, so the scan covers unapproved candidates plus// any run whose entry has been dropped by an unlock/reopen.const RUN_SCAN_DIRS = ['runs', 'grok'];-const RUN_RECORD_NAME = 'animation-run.json';// Serialize walk-state read-modify-writes per record (run records, the// selection file, the walk set, and trim versioning share one lifecycle) —@@ -271,16 +271,6 @@ async function requireUnfinalized(recordId) {if (await loadWalkSet(recordId)) throw walkSetFinalError();}-// PortOS stamps createdAt as an ISO string (Date.parse handles it); imported-// source-pipeline run records (issue #2895 importer) stamp it as a Python-// time.time() epoch-seconds float instead — .localeCompare on that throws-// and 500s the whole detail endpoint. Normalize both to comparable ms.-function runCreatedAtMs(createdAt) {- if (typeof createdAt === 'number') return createdAt * 1000;- const ms = Date.parse(createdAt);- return Number.isNaN(ms) ? 0 : ms;-}-// A 'rendering' run's status is flipped to a terminal state by attachTuiWalkResult// when executeTuiRun settles — including on grok's 30-min hard timeout. So a run// still 'rendering' well past that cap can only be stranded: the server process@@ -288,40 +278,13 @@ function runCreatedAtMs(createdAt) {// Present it as an error at read time — never persisted — so the UI stops polling// 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 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;- // 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 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 === '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 };-}+// Both lanes' staleness rules live in one place (localAnimationRender.js) so the+// walk and non-walk tracks cannot drift on when a render counts as stranded —+// only the user-facing wording differs.+const normalizeStaleRendering = (run) => normalizeStaleAnimationRun(run, STALE_RENDER_ERROR);// PortOS's own postprocess stamps `stripPreview.stripPath` record-relative// (walkPostprocess.js). The imported source pipeline stamps the same field