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
address review (claude): guard against double walk render + recover stranded rendering runs
[._.]/ Adam Eivydba4368625c1
diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex 16db35dc21..521126b651 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -510,7 +510,7 @@ export default function Sprites() {// the switch already wiped A's sentinel, so there's nothing to clean up.const idRef = useRef(id);useEffect(() => { idRef.current = id; }, [id]);- const submitRender = useCallback(async (begin, resolve, cancel, key, call, failMessage) => {+ const submitRender = useCallback(async (begin, resolve, cancel, key, call, failMessage, onSuccess) => {const startId = idRef.current;begin(key);try {@@ -518,7 +518,7 @@ export default function Sprites() {// is an observable grok-tui run (runId, no media job). Either reserves// the key so a double-submit can't fire two paid renders.const result = await call();- if (idRef.current === startId) resolve(key, result?.jobId || result?.runId);+ if (idRef.current === startId) { resolve(key, result?.jobId || result?.runId); onSuccess?.(); }} catch (err) {if (idRef.current === startId) cancel(key);toast.error(err?.message || failMessage);@@ -529,7 +529,12 @@ export default function Sprites() {walkBegin, walkResolve, walkCancel, direction,() => generateSpriteWalk(id, { direction, duration }, { silent: true }),`Failed to queue ${direction} walk`,- ), [id, duration, walkBegin, walkResolve, walkCancel, submitRender]);+ // Refetch immediately so the server's 'rendering' run lands before the+ // media-job poll evicts the optimistic key (~4s) — otherwise the Generate+ // button briefly re-enables and a second click would 409 the in-flight+ // render. The server guard is the real backstop; this closes the UI gap.+ onWorkflowChanged,+ ), [id, duration, walkBegin, walkResolve, walkCancel, submitRender, onWorkflowChanged]);// `mode` is the workflow-selected backend, threaded from the asset card via// buildCollectionActions (#2938) so a re-roll uses the same backend thediff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex 64c7970bb0..224ab01fa2 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -151,6 +151,20 @@ function runCreatedAtMs(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+// died mid-render (the in-memory PTY run and its completion handler went with it).+// 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;+function normalizeStaleRendering(run) {+ if (run?.status !== 'rendering') return run;+ if (Date.now() - runCreatedAtMs(run.createdAt) <= RENDER_STALE_MS) return run;+ return { ...run, status: 'error', postprocessError: 'Walk render was interrupted (server restart or timeout) — regenerate to retry.' };+}+// PortOS's own postprocess stamps `stripPreview.stripPath` record-relative// (walkPostprocess.js). The imported source pipeline stamps the same field// as `stripPreview.path`, anchored at ITS repo root — the importer copies@@ -334,6 +348,7 @@ export async function getWalkState(recordId) {.filter((run, i, all) => !resolvedRunIds.has(run.id) && all.findIndex((r) => r.id === run.id) === i);const allRuns = [...entryRuns, ...scannedRuns]+ .map(normalizeStaleRendering).sort((a, b) => runCreatedAtMs(b.createdAt) - runCreatedAtMs(a.createdAt));// Stamp the imported flag so the client reads intent (`walkSet.imported`)// instead of re-deriving the source-pipeline path convention itself.@@ -370,6 +385,17 @@ async function startWalkGenerationImpl(recordId, body) {if (!chromaKey) {throw new ServerError('Reference set has no frozen chroma key', { status: 409, code: 'MAIN_NOT_LOCKED' });}+ // Refuse a second render for a direction already in flight. A fresh runId per+ // call is the only reservation, and the client's Generate button can briefly+ // re-enable between the media-poll eviction of its optimistic key and the next+ // getWalkState refetch — without this backstop, a click in that window fires a+ // second paid grok render for the same direction. Serialized by the write tail,+ // so no TOCTOU. getWalkState normalizes a stale 'rendering' run (server died+ // mid-render) to 'error', so this blocks only a genuinely live render.+ const { runs: inFlight } = await getWalkState(recordId);+ if (inFlight.some((r) => r.direction === direction && (r.status === 'rendering' || r.status === 'postprocessing'))) {+ throw new ServerError(`A walk render for ${direction} is already in progress`, { status: 409, code: 'WALK_RENDER_IN_PROGRESS' });+ }const anchorAbs = resolveSpriteAssetPath(recordId, anchor.path);if (!await pathExists(anchorAbs)) {throw new ServerError('Locked anchor file is missing on disk', { status: 500, code: 'ANCHOR_MISSING' });diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex f83afc6112..8f7c1bfd92 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -215,6 +215,34 @@ describe('startWalkGeneration', () => {expect(runs[0].postprocessError).toMatch(/without writing the walk video/);expect(runWalkPostprocess).not.toHaveBeenCalled();});++ it('refuses a second render while one is already in flight for the direction', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ // Default executeTuiRun mock never resolves → the first run stays 'rendering'.+ await startWalkGeneration(id, { direction: 'east' });+ await expect(startWalkGeneration(id, { direction: 'east' }))+ .rejects.toMatchObject({ code: 'WALK_RENDER_IN_PROGRESS' });+ expect(executeTuiRun).toHaveBeenCalledTimes(1); // the second never dispatched+ });++ it('treats a long-stale rendering run as errored and allows regenerating it', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ // A run left 'rendering' by a server that died mid-render, well past the cap.+ const staleId = 'walk-east-deadbeef';+ await mkdir(join(TEST_ROOT, 'sprites', id, 'runs', staleId, 'generated'), { recursive: true });+ await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', staleId, 'animation-run.json'), JSON.stringify({+ schemaVersion: 1, id: staleId, status: 'rendering', characterId: id, direction: 'east',+ chromaKey: '#FF00FF', createdAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(),+ }));+ const { runs } = await getWalkState(id);+ const stale = runs.find((r) => r.id === staleId);+ expect(stale.status).toBe('error');+ expect(stale.postprocessError).toMatch(/interrupted/);+ // The in-flight guard must NOT treat a stale run as live — regeneration works.+ const result = await startWalkGeneration(id, { direction: 'east' });+ expect(result.runId).toMatch(/^walk-east-[0-9a-f]{8}$/);+ expect(result.runId).not.toBe(staleId);+ });});describe('attachTuiWalkResult (grok-tui completion)', () => {