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): attach immutability guard, packaging-poll + stuck-run recovery, trim write-tail, sweep unmount gate
[._.]/ Adam Eivydbf22a3c4963
diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxindex ea924f1ec1..edbe49334d 100644--- a/client/src/components/sprites/WalkWorkflow.jsx+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -1,4 +1,4 @@-import { useMemo, useState } from 'react';+import { useEffect, useMemo, useState } from 'react';import { Check, Film, RefreshCw, Scissors, Lock } from 'lucide-react';import toast from '../ui/Toast';import {@@ -124,11 +124,16 @@ function DirectionCard({<StripLoop recordId={recordId} stripPath={run.stripPreview.stripPath} />)}- {run?.status === 'error' && (+ {/* Retry also covers a run wedged at 'postprocessing' (crash between+ the video copy and the packaged save) — the endpoint is the+ documented recovery path and validates readiness server-side. */}+ {(run?.status === 'error' || run?.status === 'postprocessing') && (<div className="space-y-1">- <p className="text-[10px] text-port-error break-words">{run.postprocessError || 'postprocess failed'}</p>+ {run.status === 'error' && (+ <p className="text-[10px] text-port-error break-words">{run.postprocessError || 'postprocess failed'}</p>+ )}<button onClick={() => onRetry(run)} className="px-2 py-0.5 text-[10px] bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent">- Retry postprocess+ {run.status === 'postprocessing' ? 'Re-run postprocess' : 'Retry postprocess'}</button></div>)}@@ -198,6 +203,17 @@ export default function WalkWorkflow({ record, reference, walk, onChanged }) {failMessage: (direction, job) => `Walk render failed for ${direction}: ${job?.error || 'see media jobs'}`,});+ // The deterministic postprocess runs server-side AFTER the video job+ // completes (frame extraction + per-pixel un-key can take many seconds on+ // slower machines) — the job-completion sweeps alone can both land while a+ // run is still 'postprocessing', which would strand the card on+ // "packaging…" forever. Keep refreshing until no run is packaging.+ useEffect(() => {+ if (!runs.some((r) => r.status === 'postprocessing')) return undefined;+ const timer = setInterval(onChanged, 4000);+ return () => clearInterval(timer);+ }, [runs, onChanged]);+const latestRunByDirection = useMemo(() => {const byDir = {};for (const run of runs) {diff --git a/client/src/hooks/useSpritePendingRenders.js b/client/src/hooks/useSpritePendingRenders.jsindex a24a826d3e..dc86acbeea 100644--- a/client/src/hooks/useSpritePendingRenders.js+++ b/client/src/hooks/useSpritePendingRenders.js@@ -1,4 +1,4 @@-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import toast from '../components/ui/Toast';import { getMediaJob, listMediaJobs } from '../services/apiMediaJobs.js';@@ -27,6 +27,10 @@ export function useSpritePendingRenders({failMessage = (key, job) => `Render failed for ${key}: ${job?.error || 'see media jobs'}`,}) {const [pendingJobs, setPendingJobs] = useState({});+ // Unmount guard for the deferred sweeps (repo convention: deferred work+ // respects unmount). Never reset to true — handles dev double-mount.+ const mountedRef = useRef(true);+ useEffect(() => () => { mountedRef.current = false; }, []);// Rehydrate in-flight renders on mount/record switch — a reload or// navigate-away-and-back would otherwise lose the map and re-enable@@ -76,7 +80,12 @@ export function useSpritePendingRenders({for (const { key, job } of finished) {if (job?.status === 'failed') toast.error(failMessage(key, job));}- for (const delay of sweepDelays(finished.length)) setTimeout(onChanged, delay);+ // Sweeps deliberately outlive this effect (dropping a finished entry+ // re-runs it) but not the component — hence the mountedRef gate, not+ // timer cleanup, per the repo's deferred-work convention.+ for (const delay of sweepDelays(finished.length)) {+ setTimeout(() => { if (mountedRef.current) onChanged(); }, delay);+ }}, 4000);// sweepDelays/failMessage are per-workflow config, not reactive inputs.return () => clearInterval(timer);diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex 7af7fd4935..9196b33620 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -43,10 +43,14 @@ const runRelPath = (runId) => `grok/${runId}`;const RUN_RECORD_NAME = 'animation-run.json';// Serialize walk-state read-modify-writes per record (run records, the-// selection file, and the walk set share one lifecycle) — same convention as-// reference.js's manifestWriteTail.+// selection file, the walk set, and trim versioning share one lifecycle) —+// same convention as reference.js's manifestWriteTail. Exported for+// walkTrims.js so its scan-then-write version claim can't race an attach or+// a concurrent trim.const walkWriteTail = createKeyCachedQueue();+export const withWalkWriteTail = (recordId, fn) => walkWriteTail(recordId, fn);+async function loadWalkSet(recordId) {return readJSONFile(join(spriteDir(recordId), walkSetRelPath(recordId)), null);}@@ -243,8 +247,24 @@ async function attachWalkVideoImpl({ recordId, runId, filename, jobId }) {console.error(`❌ sprite walk run record missing for ${recordId}/${runId} — skipping attach`);return null;}+ // Immutability guard, mirroring the rerun path: a Render Queue retry of a+ // terminal job re-carries the spriteWalk tag, so a clip can land AFTER the+ // run was approved (or the set finalized) — attaching would silently+ // replace frozen evidence and break the selection's recorded sha256s.+ if (await loadWalkSet(recordId)) {+ console.error(`❌ sprite walk attach skipped for ${recordId}/${runId} — walk set is finalized`);+ return null;+ }+ const selection = await loadSelection(recordId);+ if (selection?.directions?.[run.direction]?.runId === runId) {+ console.error(`❌ sprite walk attach skipped for ${recordId}/${runId} — run is approved (immutable)`);+ return null;+ }const src = join(PATHS.videos, filename);- if (!await pathExists(src)) return null;+ if (!await pathExists(src)) {+ console.error(`❌ sprite walk video missing for ${recordId}/${runId} (${filename}) — skipping attach`);+ return null;+ }const runAbs = join(spriteDir(recordId), runRelPath(runId));const videoAbs = join(runAbs, 'generated', 'source-video.mp4');await ensureDir(join(runAbs, 'generated'));diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex 0f26c87ee6..6b9f9f336a 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -233,6 +233,39 @@ describe('attachWalkVideo (completion hook)', () => {expect(runs[0].postprocessError).toMatch(/walk cycle/);});+ it('refuses to attach onto an approved run (Render Queue retry can re-fire the tag)', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const { runId } = await makeCandidateRun(id, 'east');+ await approveWalkDirection(id, { direction: 'east', runId });+ await mkdir(join(TEST_ROOT, 'videos'), { recursive: true });+ await writeFile(join(TEST_ROOT, 'videos', 'retry-clip.mp4'), 'retried');+ runWalkPostprocess.mockClear();+ expect(await attachWalkVideo({ recordId: id, direction: 'east', runId, filename: 'retry-clip.mp4' })).toBeNull();+ expect(runWalkPostprocess).not.toHaveBeenCalled();+ // The frozen artifacts were not touched.+ const { runs } = await getWalkState(id);+ expect(runs.find((r) => r.id === runId).status).toBe('candidate');+ });++ it('refuses to attach after the walk set is finalized', async () => {+ const id = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);+ for (const direction of SPRITE_DIRECTIONS) {+ const { runId } = await makeCandidateRun(id, direction);+ await approveWalkDirection(id, { direction, runId });+ }+ // A stale queued run whose clip lands after finalization must not attach.+ const staleRunId = 'walk-east-0badc0de';+ await mkdir(join(TEST_ROOT, 'sprites', id, 'grok', staleRunId), { recursive: true });+ await writeFile(join(TEST_ROOT, 'sprites', id, 'grok', staleRunId, 'animation-run.json'), JSON.stringify({+ schemaVersion: 1, id: staleRunId, status: 'queued', characterId: id, direction: 'east', chromaKey: '#FF00FF',+ }));+ await mkdir(join(TEST_ROOT, 'videos'), { recursive: true });+ await writeFile(join(TEST_ROOT, 'videos', 'late-clip.mp4'), 'late');+ runWalkPostprocess.mockClear();+ expect(await attachWalkVideo({ recordId: id, direction: 'east', runId: staleRunId, filename: 'late-clip.mp4' })).toBeNull();+ expect(runWalkPostprocess).not.toHaveBeenCalled();+ });+it('skips silently when the run record or video is missing', async () => {const id = await characterWithLockedAnchors(newId(), ['east']);expect(await attachWalkVideo({ recordId: id, direction: 'east', runId: 'walk-east-deadbeef', filename: 'x.mp4' })).toBeNull();diff --git a/server/services/sprites/walkTrims.js b/server/services/sprites/walkTrims.jsindex 9ad0596b5d..32f433175b 100644--- a/server/services/sprites/walkTrims.js+++ b/server/services/sprites/walkTrims.js@@ -25,6 +25,7 @@ import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';import { ServerError } from '../../lib/errorHandler.js';import { spriteDir, resolveSpriteAssetPath } from './paths.js';import { requireCharacter } from './reference.js';+import { withWalkWriteTail } from './walk.js';const TRIMS_DIR = 'walk/trims';const MAX_TRIM_VERSION = 999;@@ -70,8 +71,15 @@ async function encodeTrimGif(frames, fps, destAbs) {* Save one loop trim for a packaged run. `payload` is route-validated* (spriteWalkTrimSchema): runId, enabledColumns, optional fps and slug.* Geometry and labels are derived from the run's postprocess manifest.+ * Runs inside the per-record walk write tail — nextTrimPrefix is a+ * scan-then-write, so two concurrent trims could otherwise both claim the+ * same -vNNN and interleave writes over each other's artifacts.*/-export async function saveLoopTrim(recordId, payload) {+export function saveLoopTrim(recordId, payload) {+ return withWalkWriteTail(recordId, () => saveLoopTrimImpl(recordId, payload));+}++async function saveLoopTrimImpl(recordId, payload) {await requireCharacter(recordId);const { runId, enabledColumns } = payload;const run = await readJSONFile(join(spriteDir(recordId), 'grok', runId, RUN_RECORD_NAME), null);