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

refactor([issue-2897]): apply /simplify pass — shared render-poll hook, run-manifest-driven trims, packageRun extraction

[._.]/ Adam Eivyc06859a49d25
diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsx
index ed7b901857..1aabaa3054 100644
--- a/client/src/components/sprites/ReferenceWorkflow.jsx
+++ b/client/src/components/sprites/ReferenceWorkflow.jsx
@@ -2,10 +2,10 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { Lock, Sparkles, RefreshCw, Upload } from 'lucide-react';
import toast from '../ui/Toast';
import { generateSpriteReference, lockSpriteReference, updateSpriteRecord } from '../../services/apiSprites.js';
-import { getMediaJob, listMediaJobs } from '../../services/apiMediaJobs.js';
import { getSettings } from '../../services/apiSystem.js';
import { deriveAvailableBackends } from '../../lib/imageGenBackends.js';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
+import { useSpritePendingRenders } from '../../hooks/useSpritePendingRenders.js';
import { spriteAssetUrl } from './spriteAssets.js';
// Reference workflow (issue #2896): generate main-reference candidates from
@@ -82,9 +82,12 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {
const [mode, setMode] = useState('');
const [designPrompt, setDesignPrompt] = useState(manifest?.designPrompt || '');
const [uploadFile, setUploadFile] = useState(null);
- // target → jobId for in-flight renders; polled until the candidate lands.
- const [pendingJobs, setPendingJobs] = useState({});
const fileInputRef = useRef(null);
+ // target → jobId for in-flight renders; rehydrated + polled by the shared
+ // sprite render-tracking hook until each candidate lands.
+ const { pendingJobs, beginSubmit, resolveSubmit, cancelSubmit } = useSpritePendingRenders({
+ recordId, kind: 'image', tagKey: 'spriteRef', tagField: 'target', onChanged,
+ });
useEffect(() => {
getSettings({ silent: true })
@@ -100,93 +103,25 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {
.catch(() => setBackends([]));
}, []);
- // Rehydrate in-flight renders on mount/record switch — a reload or
- // navigate-away-and-back would otherwise lose pendingJobs and re-enable
- // Generate mid-render, inviting a duplicate paid render for the same
- // target. Locally-started jobs win over the snapshot on key collision.
- useEffect(() => {
- let stale = false;
- listMediaJobs({ kind: 'image', owner: 'sprites' }, { silent: true })
- .then((jobs) => {
- if (stale) return;
- const active = {};
- for (const job of jobs || []) {
- const tag = job.params?.spriteRef;
- if (tag?.recordId === recordId && ['queued', 'running'].includes(job.status)) {
- active[tag.target] = job.id;
- }
- }
- if (Object.keys(active).length > 0) setPendingJobs((prev) => ({ ...active, ...prev }));
- })
- .catch(() => {}); // best-effort — the poll and server guards still apply
- return () => { stale = true; };
- }, [recordId]);
-
- // Poll in-flight render jobs (parallel — they're independent); on a
- // terminal state drop the entry and refresh the detail once so the new
- // candidates (or the failure) show up. The completion hook's candidate
- // copy is same-process and millisecond-fast against the 4s poll grain, so
- // one short deferral covers the copy-vs-refetch ordering.
- useEffect(() => {
- if (Object.keys(pendingJobs).length === 0) return undefined;
- const timer = setInterval(async () => {
- const entries = Object.entries(pendingJobs).filter(([, jobId]) => jobId !== 'submitting');
- const results = await Promise.all(entries.map(async ([target, jobId]) => {
- try {
- return { target, job: await getMediaJob(jobId) };
- } catch (err) {
- // Only a 404 means the job is truly gone — a transient fetch
- // failure must NOT drop the entry (that would re-enable Generate
- // mid-render and stop the auto-refresh); retry on the next tick.
- return { target, job: null, gone: err?.status === 404 };
- }
- }));
- const finished = results.filter(({ job, gone }) => (job ? ['completed', 'failed', 'canceled'].includes(job.status) : gone));
- if (finished.length === 0) return;
- setPendingJobs((prev) => {
- const next = { ...prev };
- for (const { target } of finished) delete next[target];
- return next;
- });
- for (const { target, job } of finished) {
- if (job?.status === 'failed') toast.error(`Render failed for ${target}: ${job.error || 'see media jobs'}`);
- }
- setTimeout(onChanged, 500);
- // Several jobs finishing in one tick attach serially server-side — a
- // later attach can land after the first refetch, so sweep once more.
- if (finished.length > 1) setTimeout(onChanged, 2500);
- }, 4000);
- return () => clearInterval(timer);
- }, [pendingJobs, onChanged]);
-
const candidatesByTarget = useMemo(() => candidates.reduce((acc, c) => {
const t = c.target || 'main';
(acc[t] ||= []).push(c);
return acc;
}, {}), [candidates]);
- // Sentinel jobId while the enqueue request is in flight — reserves the
- // target immediately so a double-click (or a slow multipart upload) can't
- // submit two paid renders. The poll skips sentinel entries.
- const SUBMITTING = 'submitting';
-
const generate = async (target) => {
- setPendingJobs((prev) => ({ ...prev, [target]: SUBMITTING }));
+ beginSubmit(target);
try {
const { jobId } = await generateSpriteReference(recordId, {
target,
...(mode ? { mode } : {}),
...(target === 'main' ? { designPrompt, referenceImageFile: uploadFile || undefined } : {}),
}, { silent: true });
- setPendingJobs((prev) => ({ ...prev, [target]: jobId }));
+ resolveSubmit(target, jobId);
setUploadFile(null);
if (fileInputRef.current) fileInputRef.current.value = '';
} catch (err) {
- setPendingJobs((prev) => {
- const next = { ...prev };
- if (next[target] === SUBMITTING) delete next[target];
- return next;
- });
+ cancelSubmit(target);
toast.error(err?.message || `Failed to queue ${target} render`);
}
};
diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsx
index 8c466d4ab1..ea924f1ec1 100644
--- a/client/src/components/sprites/WalkWorkflow.jsx
+++ b/client/src/components/sprites/WalkWorkflow.jsx
@@ -1,11 +1,11 @@
-import { useEffect, useMemo, useState } from 'react';
+import { useMemo, useState } from 'react';
import { Check, Film, RefreshCw, Scissors, Lock } from 'lucide-react';
import toast from '../ui/Toast';
import {
generateSpriteWalk, approveSpriteWalk, postprocessSpriteWalk, trimSpriteWalk,
} from '../../services/apiSprites.js';
-import { getMediaJob, listMediaJobs } from '../../services/apiMediaJobs.js';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
+import { useSpritePendingRenders } from '../../hooks/useSpritePendingRenders.js';
import { spriteAssetUrl } from './spriteAssets.js';
// Walk workflow (issue #2897): one grok image_to_video clip per locked
@@ -19,12 +19,15 @@ const WALK_PHASES = [
'left-contact', 'left-down', 'left-passing', 'left-up',
'right-contact', 'right-down', 'right-passing', 'right-up',
];
+const ALL_COLUMNS = WALK_PHASES.map((_, i) => i);
const CELL_PX = 96; // preview cell size — the strip animates at 96px/frame
const LOOP_KEYFRAMES = `@keyframes sprite-walk-loop { to { background-position-x: -${CELL_PX * 8}px } }`;
+// Grok image_to_video clip lengths (videoGen/grok.js GROK_VIDEO_DURATIONS).
+const WALK_DURATIONS = [6, 10];
// Animated preview of a packed 8-frame strip: the strip PNG as a stepped
// background animation (8 frames at 12fps ≈ 0.67s per loop).
-function StripLoop({ recordId, stripPath, paused = false }) {
+function StripLoop({ recordId, stripPath }) {
return (
<div
role="img"
@@ -36,16 +39,17 @@ function StripLoop({ recordId, stripPath, paused = false }) {
backgroundImage: `url(${spriteAssetUrl(recordId, stripPath)})`,
backgroundSize: `${CELL_PX * 8}px ${CELL_PX}px`,
imageRendering: 'pixelated',
- animation: paused ? 'none' : 'sprite-walk-loop 0.667s steps(8) infinite',
+ animation: 'sprite-walk-loop 0.667s steps(8) infinite',
}}
/>
);
}
// Frame enable/disable trimmer for one packaged run — non-destructive: the
-// server re-packs enabled frames into a versioned strip + GIF.
+// server derives the strip geometry from the run manifest and re-packs the
+// enabled frames into a versioned strip + GIF.
function TrimPanel({ recordId, run, onClose }) {
- const [enabled, setEnabled] = useState(() => new Set(WALK_PHASES.map((_, i) => i)));
+ const [enabled, setEnabled] = useState(() => new Set(ALL_COLUMNS));
const [result, setResult] = useState(null);
const toggle = (i) => setEnabled((prev) => {
const next = new Set(prev);
@@ -54,15 +58,8 @@ function TrimPanel({ recordId, run, onClose }) {
});
const [save, saving] = useAsyncAction(async () => {
const trim = await trimSpriteWalk(recordId, {
- slug: `${run.direction}-loop`,
- atlasPath: run.stripPreview.stripPath,
- row: 0,
- cellWidth: run.stripPreview.cellWidth,
- cellHeight: run.stripPreview.cellHeight,
- fps: run.stripPreview.fps,
- allColumns: WALK_PHASES.map((_, i) => i),
+ runId: run.id,
enabledColumns: [...enabled].sort((a, b) => a - b),
- sourceFrameLabels: [...enabled].sort((a, b) => a - b).map((i) => WALK_PHASES[i]),
}, { silent: true });
setResult(trim);
toast.success(`Trim saved (${trim.frameCount} frames)`);
@@ -185,61 +182,21 @@ export default function WalkWorkflow({ record, reference, walk, onChanged }) {
const runs = walk?.runs || [];
const selection = walk?.selection || null;
const finalized = Boolean(walk?.walkSet);
- // direction → jobId for in-flight video renders.
- const [pendingJobs, setPendingJobs] = useState({});
+ const [duration, setDuration] = useState(WALK_DURATIONS[0]);
- // Rehydrate in-flight walk renders on mount/record switch (same contract
- // as ReferenceWorkflow's rehydrate — a reload must not re-enable Generate
- // mid-render).
- useEffect(() => {
- let stale = false;
- listMediaJobs({ kind: 'video', owner: 'sprites' }, { silent: true })
- .then((jobs) => {
- if (stale) return;
- const active = {};
- for (const job of jobs || []) {
- const tag = job.params?.spriteWalk;
- if (tag?.recordId === recordId && ['queued', 'running'].includes(job.status)) {
- active[tag.direction] = job.id;
- }
- }
- if (Object.keys(active).length > 0) setPendingJobs((prev) => ({ ...active, ...prev }));
- })
- .catch(() => {});
- return () => { stale = true; };
- }, [recordId]);
-
- // Poll in-flight renders; the completion hook packages server-side, so a
- // finished job needs one deferred refetch (plus a late sweep — the
- // postprocess takes seconds, unlike the reference hook's instant copy).
- useEffect(() => {
- if (Object.keys(pendingJobs).length === 0) return undefined;
- const timer = setInterval(async () => {
- const entries = Object.entries(pendingJobs).filter(([, jobId]) => jobId !== 'submitting');
- const results = await Promise.all(entries.map(async ([direction, jobId]) => {
- try {
- return { direction, job: await getMediaJob(jobId) };
- } catch (err) {
- return { direction, job: null, gone: err?.status === 404 };
- }
- }));
- const finished = results.filter(({ job, gone }) => (job ? ['completed', 'failed', 'canceled'].includes(job.status) : gone));
- if (finished.length === 0) return;
- setPendingJobs((prev) => {
- const next = { ...prev };
- for (const { direction } of finished) delete next[direction];
- return next;
- });
- for (const { direction, job } of finished) {
- if (job?.status === 'failed') toast.error(`Walk render failed for ${direction}: ${job.error || 'see media jobs'}`);
- }
- // The deterministic postprocess runs after the job completes — sweep
- // twice so the packaged candidate (or its error) lands in the UI.
- setTimeout(onChanged, 1500);
- setTimeout(onChanged, 8000);
- }, 4000);
- return () => clearInterval(timer);
- }, [pendingJobs, onChanged]);
+ // direction → jobId for in-flight video renders — rehydrated + polled by
+ // the shared sprite render-tracking hook. The deterministic postprocess
+ // runs server-side after the job completes, so the sweeps land later (and
+ // twice) compared to the reference workflow's instant candidate copy.
+ const { pendingJobs, beginSubmit, resolveSubmit, cancelSubmit } = useSpritePendingRenders({
+ recordId,
+ kind: 'video',
+ tagKey: 'spriteWalk',
+ tagField: 'direction',
+ onChanged,
+ sweepDelays: () => [1500, 8000],
+ failMessage: (direction, job) => `Walk render failed for ${direction}: ${job?.error || 'see media jobs'}`,
+ });
const latestRunByDirection = useMemo(() => {
const byDir = {};
@@ -255,16 +212,12 @@ export default function WalkWorkflow({ record, reference, walk, onChanged }) {
}, [runs, selection]);
const generate = async (direction) => {
- setPendingJobs((prev) => ({ ...prev, [direction]: 'submitting' }));
+ beginSubmit(direction);
try {
- const { jobId } = await generateSpriteWalk(recordId, { direction }, { silent: true });
- setPendingJobs((prev) => ({ ...prev, [direction]: jobId }));
+ const { jobId } = await generateSpriteWalk(recordId, { direction, duration }, { silent: true });
+ resolveSubmit(direction, jobId);
} catch (err) {
- setPendingJobs((prev) => {
- const next = { ...prev };
- if (next[direction] === 'submitting') delete next[direction];
- return next;
- });
+ cancelSubmit(direction);
toast.error(err?.message || `Failed to queue ${direction} walk`);
}
};
@@ -298,10 +251,21 @@ export default function WalkWorkflow({ record, reference, walk, onChanged }) {
{finalized ? 'finalized' : `${approvedCount}/8 approved`}
</span>
</h3>
- {finalized && (
+ {finalized ? (
<p className="text-xs text-port-success flex items-center gap-1">
<Lock className="w-3 h-3" /> walk set frozen · immutable
</p>
+ ) : (
+ <label className="flex items-center gap-2 text-xs text-gray-400">
+ Clip length
+ <select
+ value={duration}
+ onChange={(e) => setDuration(Number(e.target.value))}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"
+ >
+ {WALK_DURATIONS.map((d) => <option key={d} value={d}>{d}s</option>)}
+ </select>
+ </label>
)}
</div>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 45684bf529..d2013d7a64 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -40,6 +40,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useSseJobSlot` | Generic single-slot SSE job: `pending`/`job` state, terminal-frame handling (`complete`/`error`/`canceled`), and `sse.closed`-without-terminal-frame recovery in one place. Returns `{ active, percent, stage, context, start, cancel }`; pass `startRequest`/`eventsUrl`/`cancelRequest` + per-feature toast copy. | Any "kick off a job → stream SSE → settle on terminal frame" hook. The reference-audio/YouTube/video-download/MIDI hooks all wrap this — don't re-roll the terminal-frame + lost-connection dance. |
| `useInstallStream` | BYO-runtime install-log EventSource lifecycle: `stage`/`log`/`complete`/`error` frame dispatch, capped + optionally-debounced log accumulation, "connection lost" handling, ref-stashed `onComplete`, auto-scroll. | A streamed install/setup modal that shows live SSE log lines (FLUX.2, video runtimes). Don't re-roll the EventSource teardown/onComplete-ref dance. |
| `useModelDownloadStatus` | Image/video model cache-status + SSE pre-download. | Surfacing "Available" vs "Download" badge inline in the gen form. |
+| `useSpritePendingRenders` | Sprite-workflow in-flight render map: queue rehydrate + 4s poll keyed by a media-job tag field, `'submitting'` double-render guard, 404-only drop, deferred `onChanged` sweeps. | A sprite workflow tracking `queued/running` media jobs by tag (reference renders, walk videos, phase-4 publish) — don't re-roll the rehydrate/poll dance. |
| `useImageGenProgress` | Live diffusion progress for an image-gen call. | Showing per-call image-gen progress. |
| `useImporterProgress` | Live analyze-phase stage checklist via the `importer:progress` socket (runId-filtered); exports `stageStatusIcon` for the status→icon lookup. | Importer analyze progress UI only. |
| `useMediaJobProgress` | Live progress for a single `mediaJobQueue` job. | Subscribing to a known media-job id. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 51b9bd232f..d15100c8f9 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -94,6 +94,7 @@ export * from './useModelDownloadStatus.js';
// === Media (annotations, completion, attachments) ===
export * from './useMediaAnnotations.js';
+export * from './useSpritePendingRenders.js';
export * from './useMediaCompletionRefresh.js';
export * from './useOpenClawAttachments.js';
diff --git a/client/src/hooks/useSpritePendingRenders.js b/client/src/hooks/useSpritePendingRenders.js
new file mode 100644
index 0000000000..a24a826d3e
--- /dev/null
+++ b/client/src/hooks/useSpritePendingRenders.js
@@ -0,0 +1,99 @@
+import { useEffect, useState } from 'react';
+import toast from '../components/ui/Toast';
+import { getMediaJob, listMediaJobs } from '../services/apiMediaJobs.js';
+
+/**
+ * Shared in-flight render tracking for the sprite workflows (#2896 reference
+ * renders, #2897 walk videos): a `key → jobId` map with mount-time
+ * rehydration from the media-job queue and a 4s poll that drops terminal
+ * jobs, toasts failures, and fires deferred `onChanged()` refetch sweeps.
+ * This is the client counterpart of the server's `createMediaJobImageHook`
+ * scaffold — one copy of the subtle invariants (the `'submitting'` sentinel
+ * that blocks a double paid render, the 404-only "gone" heuristic so a
+ * transient fetch failure doesn't re-enable Generate mid-render, the
+ * local-wins rehydrate merge) instead of one per workflow.
+ *
+ * - `kind`/`tagKey`/`tagField`: which jobs belong to this workflow and which
+ * tag field keys the map (e.g. kind 'image' + `spriteRef.target`, or kind
+ * 'video' + `spriteWalk.direction`).
+ * - `sweepDelays(finishedCount) → ms[]`: how long after a job finishes to
+ * refetch — workflows whose completion hook does slow server-side work
+ * (the walk postprocess) sweep later/twice.
+ * - `failMessage(key, job)`: the toast for a failed job.
+ */
+export function useSpritePendingRenders({
+ recordId, kind, tagKey, tagField, onChanged,
+ sweepDelays = (finished) => (finished > 1 ? [500, 2500] : [500]),
+ failMessage = (key, job) => `Render failed for ${key}: ${job?.error || 'see media jobs'}`,
+}) {
+ const [pendingJobs, setPendingJobs] = useState({});
+
+ // Rehydrate in-flight renders on mount/record switch — a reload or
+ // navigate-away-and-back would otherwise lose the map and re-enable
+ // Generate mid-render, inviting a duplicate paid render for the same key.
+ // Locally-started jobs win over the snapshot on key collision.
+ useEffect(() => {
+ let stale = false;
+ listMediaJobs({ kind, owner: 'sprites' }, { silent: true })
+ .then((jobs) => {
+ if (stale) return;
+ const active = {};
+ for (const job of jobs || []) {
+ const tag = job.params?.[tagKey];
+ if (tag?.recordId === recordId && ['queued', 'running'].includes(job.status)) {
+ active[tag[tagField]] = job.id;
+ }
+ }
+ if (Object.keys(active).length > 0) setPendingJobs((prev) => ({ ...active, ...prev }));
+ })
+ .catch(() => {}); // best-effort — the poll and server guards still apply
+ return () => { stale = true; };
+ }, [recordId, kind, tagKey, tagField]);
+
+ // Poll in-flight jobs (parallel — they're independent); on a terminal
+ // state drop the entry and fire the workflow's refetch sweep(s).
+ useEffect(() => {
+ if (Object.keys(pendingJobs).length === 0) return undefined;
+ const timer = setInterval(async () => {
+ const entries = Object.entries(pendingJobs).filter(([, jobId]) => jobId !== 'submitting');
+ const results = await Promise.all(entries.map(async ([key, jobId]) => {
+ try {
+ return { key, job: await getMediaJob(jobId) };
+ } catch (err) {
+ // Only a 404 means the job is truly gone — a transient fetch
+ // failure must NOT drop the entry (that would re-enable Generate
+ // mid-render and stop the auto-refresh); retry on the next tick.
+ return { key, job: null, gone: err?.status === 404 };
+ }
+ }));
+ const finished = results.filter(({ job, gone }) => (job ? ['completed', 'failed', 'canceled'].includes(job.status) : gone));
+ if (finished.length === 0) return;
+ setPendingJobs((prev) => {
+ const next = { ...prev };
+ for (const { key } of finished) delete next[key];
+ return next;
+ });
+ 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);
+ }, 4000);
+ // sweepDelays/failMessage are per-workflow config, not reactive inputs.
+ return () => clearInterval(timer);
+ }, [pendingJobs, onChanged]);
+
+ // Sentinel jobId while the enqueue request is in flight — reserves the key
+ // immediately so a double-click (or a slow multipart upload) can't submit
+ // two paid renders. The poll skips sentinel entries.
+ const beginSubmit = (key) => setPendingJobs((prev) => ({ ...prev, [key]: 'submitting' }));
+ const resolveSubmit = (key, jobId) => setPendingJobs((prev) => ({ ...prev, [key]: jobId }));
+ const cancelSubmit = (key) => setPendingJobs((prev) => {
+ const next = { ...prev };
+ if (next[key] === 'submitting') delete next[key];
+ return next;
+ });
+
+ return { pendingJobs, beginSubmit, resolveSubmit, cancelSubmit };
+}
+
+export default useSpritePendingRenders;
diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsx
index e0a30b70e0..e6d0abf681 100644
--- a/client/src/pages/Sprites.jsx
+++ b/client/src/pages/Sprites.jsx
@@ -218,17 +218,8 @@ function RecordList({ records, selectedId, onSelect }) {
);
}
-// Raw ffmpeg-extracted frame intermediates (30–96 PNGs per walk run) would
-// swamp the asset browser — hide them, matching the importer's exclusion of
-// raw/ from cross-machine copies. They stay on disk for the postprocessor.
-const RUN_RAW_INTERMEDIATE = /^grok\/[^/]+\/generated\/raw\//;
-
-function AssetGroups({ recordId, assets: allAssets }) {
+function AssetGroups({ recordId, assets }) {
const [preview, setPreview] = useState(null);
- const assets = useMemo(
- () => allAssets.filter((a) => !RUN_RAW_INTERMEDIATE.test(a.path)),
- [allAssets],
- );
const groups = useMemo(() => assets.reduce((acc, a) => {
const g = topLevelGroup(a.path) || 'files';
(acc[g] ||= []).push(a);
diff --git a/server/lib/validation.js b/server/lib/validation.js
index d086e74845..d3b8f2b2a5 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1031,20 +1031,15 @@ export const spriteWalkPostprocessSchema = z.object({
runId: spriteWalkRunIdSchema,
});
-const trimColumnsSchema = z.array(z.number().int().min(0).max(255)).min(2).max(256)
- .refine((cols) => new Set(cols).size === cols.length, { message: 'columns must be unique' });
-
+// Trim geometry (strip path, cell size, frame labels) derives server-side
+// from the run's packaged manifest — the client only names the run and
+// which frames stay enabled.
export const spriteWalkTrimSchema = z.object({
- slug: z.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/),
- atlasPath: z.string().min(1).max(500),
- row: z.number().int().min(0).max(63),
- cellWidth: z.number().int().min(1).max(4096),
- cellHeight: z.number().int().min(1).max(4096),
- fps: z.number().int().min(1).max(60),
- allColumns: trimColumnsSchema,
- enabledColumns: trimColumnsSchema,
- sourceFrameIndices: z.array(z.number().int().min(0)).max(256).optional(),
- sourceFrameLabels: z.array(z.string().max(200)).max(256).optional(),
+ runId: spriteWalkRunIdSchema,
+ enabledColumns: z.array(z.number().int().min(0).max(63)).min(2).max(64)
+ .refine((cols) => new Set(cols).size === cols.length, { message: 'columns must be unique' }),
+ fps: z.number().int().min(1).max(60).optional(),
+ slug: z.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/).optional(),
});
// =============================================================================
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index e5b2dd1fa8..8ba8de4063 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -279,12 +279,7 @@ describe('sprites routes', () => {
});
it('POST /:id/walk/trim validates and 201s', async () => {
- const payload = {
- slug: 'east-loop',
- atlasPath: 'grok/walk-east-0a1b2c3d/generated/strip.png',
- row: 0, cellWidth: 384, cellHeight: 384, fps: 12,
- allColumns: [0, 1, 2, 3], enabledColumns: [0, 2],
- };
+ const payload = { runId: 'walk-east-0a1b2c3d', enabledColumns: [0, 2] };
const r = await request(app).post('/api/sprites/pioneer/walk/trim').send(payload);
expect(r.status).toBe(201);
expect(walkTrims.saveLoopTrim).toHaveBeenCalledWith('pioneer', payload);
@@ -294,7 +289,9 @@ describe('sprites routes', () => {
expect((await request(app).post('/api/sprites/pioneer/walk/trim')
.send({ ...payload, enabledColumns: [0] })).status).toBe(400);
expect((await request(app).post('/api/sprites/pioneer/walk/trim')
- .send({ ...payload, allColumns: [0, 0, 1, 2] })).status).toBe(400);
+ .send({ ...payload, enabledColumns: [0, 0, 2] })).status).toBe(400);
+ expect((await request(app).post('/api/sprites/pioneer/walk/trim')
+ .send({ runId: '../escape', enabledColumns: [0, 2] })).status).toBe(400);
expect(walkTrims.saveLoopTrim).toHaveBeenCalledOnce();
});
});
diff --git a/server/services/sprites/paths.js b/server/services/sprites/paths.js
index fcfe3a0c60..e15ead65a6 100644
--- a/server/services/sprites/paths.js
+++ b/server/services/sprites/paths.js
@@ -41,11 +41,20 @@ export function resolveSpriteAssetPath(recordId, relPath) {
return abs;
}
+// Raw ffmpeg-extracted frame intermediates inside an animation run (30–96
+// near-identical PNGs per run, `grok|runs/<run>/generated/raw/`). Kept on
+// disk for the postprocessor but omitted from the asset listing — they'd
+// swamp the browser. Narrower than the importer's EXCLUDED_RUN_SEGMENTS
+// (which also skips frames/ and review/ to minimize cross-machine copies):
+// the packaged phase frames and the contrast review sheet exist FOR human
+// review, so the local browser keeps them.
+const RUN_RAW_INTERMEDIATE = /^(grok|runs)\/[^/]+\/generated\/raw\//;
+
/**
* Recursively list a record's on-disk assets as `[{ path, size, mtime }]`
- * with `path` relative (posix separators) to the record dir. Dotfiles are
- * skipped; per-directory stats and subdirectory descents run in parallel.
- * A record with no directory yet returns [].
+ * with `path` relative (posix separators) to the record dir. Dotfiles and
+ * raw run intermediates are skipped; per-directory stats and subdirectory
+ * descents run in parallel. A record with no directory yet returns [].
*/
export async function listSpriteAssets(recordId) {
const dir = spriteDir(recordId);
@@ -61,6 +70,7 @@ export async function listSpriteAssets(recordId) {
if (entry.name.startsWith('.')) return;
const rel = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
+ if (RUN_RAW_INTERMEDIATE.test(`${rel}/`)) return;
await walk(join(current, entry.name), rel);
} else if (entry.isFile()) {
const s = await stat(join(current, entry.name));
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 3e6233c042..7af7fd4935 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -33,7 +33,7 @@ import { spriteDir, resolveSpriteAssetPath } from './paths.js';
import { requireCharacter, loadManifest } from './reference.js';
import { SPRITE_DIRECTIONS, anchorIdForDirection, buildWalkVideoPrompt } from './prompts.js';
import {
- prepareWalkAnchorInput, runWalkPostprocess, WALK_FPS, WALK_CELL_SIZE, WALK_FRAME_COUNT,
+ prepareWalkAnchorInput, runWalkPostprocess, WALK_FPS, WALK_FRAME_COUNT,
} from './walkPostprocess.js';
import { GROK_VIDEO_DURATIONS } from '../videoGen/grok.js';
@@ -93,18 +93,18 @@ export async function getWalkState(recordId) {
} catch {
// no runs yet
}
- const runs = (await Promise.all(
- entries
- .filter((e) => e.isDirectory() && e.name.startsWith('walk-'))
- .map((e) => loadRunRecord(recordId, e.name)),
- ))
- .filter(Boolean)
- .sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
- return {
- runs,
- selection: await loadSelection(recordId),
- walkSet: await loadWalkSet(recordId),
- };
+ const [runs, selection, walkSet] = await Promise.all([
+ Promise.all(
+ entries
+ .filter((e) => e.isDirectory() && e.name.startsWith('walk-'))
+ .map((e) => loadRunRecord(recordId, e.name)),
+ ).then((loaded) => loaded
+ .filter(Boolean)
+ .sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''))),
+ loadSelection(recordId),
+ loadWalkSet(recordId),
+ ]);
+ return { runs, selection, walkSet };
}
/**
@@ -143,7 +143,7 @@ async function startWalkGenerationImpl(recordId, body) {
// Transparent i2v motion input derived from the locked anchor without
// mutating it (measured-key alpha recovery + despill).
const inputAbs = join(generatedAbs, 'input-anchor-transparent.png');
- const { preparation } = await prepareWalkAnchorInput(anchorAbs, inputAbs, chromaKey);
+ const { preparation, sha256: inputSha256 } = await prepareWalkAnchorInput(anchorAbs, inputAbs, chromaKey);
const settings = await getSettings();
const duration = GROK_VIDEO_DURATIONS.includes(Number(body.duration)) ? Number(body.duration) : GROK_VIDEO_DURATIONS[0];
@@ -165,7 +165,7 @@ async function startWalkGenerationImpl(recordId, body) {
anchorPath: anchor.path,
anchorSha256: anchor.sha256 || await sha256File(anchorAbs),
animationInputPath: `${runRel}/generated/input-anchor-transparent.png`,
- animationInputSha256: await sha256File(inputAbs),
+ animationInputSha256: inputSha256,
animationInputPreparation: preparation,
createdAt: now,
};
@@ -191,6 +191,42 @@ async function startWalkGenerationImpl(recordId, body) {
return { jobId, runId, direction, duration };
}
+/**
+ * Run the deterministic postprocess for a run and apply the outcome to the
+ * run record (candidate on success, captured error otherwise) — shared by
+ * the completion-hook attach and the manual rerun so the two can't drift.
+ * The caller persists the mutated record.
+ */
+async function packageRun(recordId, run) {
+ const runRel = runRelPath(run.id);
+ const runAbs = join(spriteDir(recordId), runRel);
+ try {
+ const manifest = await loadManifest(recordId);
+ const anchor = manifest?.anchors?.find((a) => a.direction === run.direction);
+ if (!anchor?.path) throw new Error(`No locked ${run.direction} anchor in the reference manifest`);
+ const result = await runWalkPostprocess({
+ recordId,
+ direction: run.direction,
+ chromaKey: run.chromaKey || manifest.chromaKey,
+ runAbs,
+ runRel,
+ anchorRel: anchor.path,
+ anchorAbs: resolveSpriteAssetPath(recordId, anchor.path),
+ videoAbs: join(runAbs, 'generated', 'source-video.mp4'),
+ });
+ run.status = 'candidate';
+ run.postprocessManifest = result.manifestPath;
+ run.stripPreview = result.stripPreview;
+ delete run.postprocessError;
+ } catch (err) {
+ // May run outside the request lifecycle (hook) — capture, don't crash.
+ run.status = 'error';
+ run.postprocessError = err.message;
+ console.error(`❌ sprite walk postprocess failed ${recordId}/${run.id}: ${err.message}`);
+ }
+ run.completedAt = new Date().toISOString();
+}
+
/**
* Completion-hook attach: copy the finished grok video into the run root and
* run the deterministic postprocess. Errors are captured onto the run record
@@ -201,7 +237,7 @@ export function attachWalkVideo(ctx) {
return walkWriteTail(ctx.recordId, () => attachWalkVideoImpl(ctx));
}
-async function attachWalkVideoImpl({ recordId, direction, runId, filename, jobId }) {
+async function attachWalkVideoImpl({ recordId, runId, filename, jobId }) {
const run = await loadRunRecord(recordId, runId);
if (!run) {
console.error(`❌ sprite walk run record missing for ${recordId}/${runId} — skipping attach`);
@@ -209,8 +245,7 @@ async function attachWalkVideoImpl({ recordId, direction, runId, filename, jobId
}
const src = join(PATHS.videos, filename);
if (!await pathExists(src)) return null;
- const runRel = runRelPath(runId);
- const runAbs = join(spriteDir(recordId), runRel);
+ const runAbs = join(spriteDir(recordId), runRelPath(runId));
const videoAbs = join(runAbs, 'generated', 'source-video.mp4');
await ensureDir(join(runAbs, 'generated'));
await copyFile(src, videoAbs);
@@ -219,32 +254,7 @@ async function attachWalkVideoImpl({ recordId, direction, runId, filename, jobId
run.status = 'postprocessing';
await saveRunRecord(recordId, run);
- try {
- const manifest = await loadManifest(recordId);
- const anchor = manifest?.anchors?.find((a) => a.direction === direction);
- if (!anchor?.path) throw new Error(`No locked ${direction} anchor in the reference manifest`);
- const result = await runWalkPostprocess({
- recordId,
- direction,
- chromaKey: run.chromaKey || manifest.chromaKey,
- runAbs,
- runRel,
- anchorRel: anchor.path,
- anchorAbs: resolveSpriteAssetPath(recordId, anchor.path),
- videoAbs,
- });
- run.status = 'candidate';
- run.completedAt = new Date().toISOString();
- run.postprocessManifest = result.manifestPath;
- run.stripPreview = result.stripPreview;
- delete run.postprocessError;
- } catch (err) {
- // Outside the request lifecycle — capture instead of crashing the hook.
- run.status = 'error';
- run.completedAt = new Date().toISOString();
- run.postprocessError = err.message;
- console.error(`❌ sprite walk postprocess failed ${recordId}/${runId}: ${err.message}`);
- }
+ await packageRun(recordId, run);
await saveRunRecord(recordId, run);
return { runId, status: run.status };
}
@@ -267,37 +277,11 @@ async function rerunWalkPostprocessImpl(recordId, runId) {
if (selection?.directions?.[run.direction]?.runId === runId) {
throw new ServerError('Run is approved — approved runs are immutable', { status: 409, code: 'RUN_APPROVED' });
}
- const runRel = runRelPath(runId);
- const runAbs = join(spriteDir(recordId), runRel);
- const videoAbs = join(runAbs, 'generated', 'source-video.mp4');
+ const videoAbs = join(spriteDir(recordId), runRelPath(runId), 'generated', 'source-video.mp4');
if (!await pathExists(videoAbs)) {
throw new ServerError('Run has no source video yet', { status: 409, code: 'VIDEO_NOT_READY' });
}
- const manifest = await loadManifest(recordId);
- const anchor = manifest?.anchors?.find((a) => a.direction === run.direction);
- if (!anchor?.path) {
- throw new ServerError(`No locked ${run.direction} anchor in the reference manifest`, { status: 409, code: 'ANCHOR_NOT_LOCKED' });
- }
- try {
- const result = await runWalkPostprocess({
- recordId,
- direction: run.direction,
- chromaKey: run.chromaKey || manifest.chromaKey,
- runAbs,
- runRel,
- anchorRel: anchor.path,
- anchorAbs: resolveSpriteAssetPath(recordId, anchor.path),
- videoAbs,
- });
- run.status = 'candidate';
- run.completedAt = new Date().toISOString();
- run.postprocessManifest = result.manifestPath;
- run.stripPreview = result.stripPreview;
- delete run.postprocessError;
- } catch (err) {
- run.status = 'error';
- run.postprocessError = err.message;
- }
+ await packageRun(recordId, run);
await saveRunRecord(recordId, run);
if (run.status === 'error') {
throw new ServerError(`Postprocess failed: ${run.postprocessError}`, { status: 422, code: 'POSTPROCESS_FAILED' });
@@ -376,5 +360,3 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {
console.log(`✅ sprite walk ${recordId}/${direction} approved from ${runId}`);
return getWalkState(recordId);
}
-
-export { WALK_CELL_SIZE, WALK_FPS, WALK_FRAME_COUNT };
diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.js
index 3d8448ae5d..4f485c35b8 100644
--- a/server/services/sprites/walkPostprocess.js
+++ b/server/services/sprites/walkPostprocess.js
@@ -21,7 +21,7 @@
import sharp from 'sharp';
import { join } from 'path';
-import { readdir } from 'fs/promises';
+import { readdir, writeFile } from 'fs/promises';
import { createHash } from 'crypto';
import { ensureDir, atomicWrite, sha256File } from '../../lib/fileUtils.js';
import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';
@@ -87,10 +87,14 @@ export async function decodeRgbaFrame(src) {
return { data, width: info.width, height: info.height };
}
-async function encodePng(frame, dest, channels = 4) {
- await sharp(frame.data, { raw: { width: frame.width, height: frame.height, channels } })
+// Encode + write + hash in one pass — hashing the in-memory PNG buffer saves
+// reading every just-written artifact back off disk purely to checksum it.
+async function encodePngWithHash(frame, dest, channels = 4) {
+ const buf = await sharp(frame.data, { raw: { width: frame.width, height: frame.height, channels } })
.png()
- .toFile(dest);
+ .toBuffer();
+ await writeFile(dest, buf);
+ return sha256Buffer(buf);
}
/**
@@ -579,8 +583,8 @@ export async function prepareWalkAnchorInput(anchorAbs, destAbs, chromaKey) {
prepared = recoverAlphaFrame(frame, measured, split);
}
prepared = despillKeyFrame(prepared, split);
- await encodePng(prepared, destAbs);
- return { preparation: 'measured-key-alpha-recovery-plus-despill' };
+ const sha256 = await encodePngWithHash(prepared, destAbs);
+ return { preparation: 'measured-key-alpha-recovery-plus-despill', sha256 };
}
/**
@@ -599,14 +603,12 @@ export async function runWalkPostprocess({
const rawDir = join(generatedAbs, 'raw');
const rawNames = await extractVideoFrames(videoAbs, rawDir);
- const rawFrames = [];
const recovered = [];
const measuredKeys = [];
for (const name of rawNames) {
const frame = await decodeRgbaFrame(join(rawDir, name));
const measured = sampleBorderKey(frame);
validateMeasuredKey(measured, split, chromaKey);
- rawFrames.push(frame);
measuredKeys.push(measured);
recovered.push(recoverAlphaFrame(frame, measured, split));
}
@@ -625,8 +627,6 @@ export async function runWalkPostprocess({
for (let i = 0; i < despilled.length; i++) {
const phase = WALK_PHASES[i];
const name = `${String(i).padStart(2, '0')}-${phase}.png`;
- const dest = join(framesDir, name);
- await encodePng(despilled[i], dest);
frameRecords.push({
outputIndex: i,
phase,
@@ -635,20 +635,17 @@ export async function runWalkPostprocess({
sourceSha256: await sha256File(join(rawDir, rawNames[indices[i]])),
measuredKeyRgb: measuredKeys[indices[i]],
path: `${generatedRel}/frames/${name}`,
- sha256: await sha256File(dest),
+ sha256: await encodePngWithHash(despilled[i], join(framesDir, name)),
});
}
const stripName = `${recordId}-walk-${direction}-strip.png`;
- const stripAbs = join(generatedAbs, stripName);
- await encodePng(packStrip(despilled), stripAbs);
+ const stripSha256 = await encodePngWithHash(packStrip(despilled), join(generatedAbs, stripName));
const reviewDir = join(generatedAbs, 'review');
await ensureDir(reviewDir);
const contrastName = `${recordId}-walk-${direction}-contrast-review.png`;
- const contrastAbs = join(reviewDir, contrastName);
- const sheet = await buildContrastSheet(despilled);
- await encodePng(sheet, contrastAbs, 3);
+ const comparisonSha256 = await encodePngWithHash(await buildContrastSheet(despilled), join(reviewDir, contrastName), 3);
const manifestName = `${recordId}-walk-${direction}-manifest.json`;
const manifest = {
@@ -677,9 +674,9 @@ export async function runWalkPostprocess({
validation,
frames: frameRecords,
stripPath: `${generatedRel}/${stripName}`,
- stripSha256: await sha256File(stripAbs),
+ stripSha256,
comparisonPath: `${generatedRel}/review/${contrastName}`,
- comparisonSha256: await sha256File(contrastAbs),
+ comparisonSha256,
};
await atomicWrite(join(generatedAbs, manifestName), manifest);
diff --git a/server/services/sprites/walkTrims.js b/server/services/sprites/walkTrims.js
index 3634ed05b1..9ad0596b5d 100644
--- a/server/services/sprites/walkTrims.js
+++ b/server/services/sprites/walkTrims.js
@@ -1,20 +1,26 @@
/**
* Sprites — non-destructive loop trimmer (issue #2897, phase 3).
*
- * Port of the source pipeline's `loop_trims.save_loop_trim`: crop the
- * enabled cells out of a packed atlas row (never mutating the atlas),
- * re-pack them as a trimmed strip + preview GIF + manifest, versioned
- * `<slug>-vNNN` so every trim is additive evidence. PortOS scopes trims to
- * the record (`walk/trims/`) instead of the source's global debug-captures
- * root, and encodes the GIF with ffmpeg (palettegen/paletteuse with
- * transparency) since PIL's GIF writer has no Node sibling.
+ * Port of the source pipeline's `loop_trims.save_loop_trim`, re-anchored on
+ * the run manifest: the caller names a packaged candidate run and which of
+ * its frames stay enabled; the strip path, cell geometry, fps, and frame
+ * labels all come from the run's own postprocess manifest (the server-owned
+ * source of truth), never from client-echoed geometry. Enabled cells are
+ * cropped out of the packed strip (never mutating it) and re-packed as a
+ * trimmed strip + preview GIF + manifest, versioned `<slug>-vNNN` so every
+ * trim is additive evidence. Trims land under the record's `walk/trims/`
+ * (the source pipeline's global debug-captures root, scoped per record);
+ * the GIF is encoded with ffmpeg (palettegen/paletteuse with transparency)
+ * since PIL's GIF writer has no Node sibling.
*/
import { join } from 'path';
-import { mkdtemp, rm } from 'fs/promises';
+import { mkdtemp, rm, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import sharp from 'sharp';
-import { ensureDir, atomicWrite, pathExists, sha256File } from '../../lib/fileUtils.js';
+import {
+ ensureDir, atomicWrite, pathExists, sha256File, readJSONFile,
+} from '../../lib/fileUtils.js';
import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';
import { ServerError } from '../../lib/errorHandler.js';
import { spriteDir, resolveSpriteAssetPath } from './paths.js';
@@ -22,6 +28,7 @@ import { requireCharacter } from './reference.js';
const TRIMS_DIR = 'walk/trims';
const MAX_TRIM_VERSION = 999;
+const RUN_RECORD_NAME = 'animation-run.json';
// First free -vNNN triple (strip + gif + json all absent), matching the
// source's next_trim_prefix scan.
@@ -60,90 +67,95 @@ async function encodeTrimGif(frames, fps, destAbs) {
}
/**
- * Save one loop trim. `payload` is route-validated (spriteWalkTrimSchema):
- * slug, atlasPath (record-relative), row, cellWidth/cellHeight, fps,
- * allColumns, enabledColumns (subset), optional sourceFrameIndices/Labels.
+ * 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.
*/
export async function saveLoopTrim(recordId, payload) {
await requireCharacter(recordId);
- const {
- slug, atlasPath, row, cellWidth, cellHeight, fps, allColumns, enabledColumns,
- } = payload;
- if (!enabledColumns.every((c) => allColumns.includes(c))) {
- throw new ServerError('enabledColumns must be a subset of allColumns', { status: 400, code: 'TRIM_COLUMNS_INVALID' });
+ const { runId, enabledColumns } = payload;
+ const run = await readJSONFile(join(spriteDir(recordId), 'grok', runId, RUN_RECORD_NAME), null);
+ if (!run) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });
+ if (!run.postprocessManifest) {
+ throw new ServerError('Run has no packaged candidate to trim', { status: 409, code: 'RUN_NOT_CANDIDATE' });
}
- const sourceFrameIndices = payload.sourceFrameIndices ?? enabledColumns;
- if (sourceFrameIndices.length !== enabledColumns.length) {
- throw new ServerError('sourceFrameIndices must match enabledColumns length', { status: 400, code: 'TRIM_COLUMNS_INVALID' });
+ const packaged = await readJSONFile(resolveSpriteAssetPath(recordId, run.postprocessManifest), null);
+ if (!packaged?.stripPath || !packaged.alignment?.cellSize || !Array.isArray(packaged.frames)) {
+ throw new ServerError('Packaged run manifest is missing or inconsistent', { status: 409, code: 'RUN_MANIFEST_INVALID' });
}
- const sourceFrameLabels = (payload.sourceFrameLabels ?? sourceFrameIndices.map(String))
- .map((l) => String(l).slice(0, 80));
- if (sourceFrameLabels.length !== enabledColumns.length) {
- throw new ServerError('sourceFrameLabels must match enabledColumns length', { status: 400, code: 'TRIM_COLUMNS_INVALID' });
+ const cellSize = packaged.alignment.cellSize;
+ const allColumns = packaged.frames.map((f) => f.outputIndex);
+ const invalid = enabledColumns.filter((c) => !allColumns.includes(c));
+ if (invalid.length) {
+ throw new ServerError(`Enabled frames not in the packed strip: ${invalid.join(', ')}`, { status: 400, code: 'TRIM_COLUMNS_INVALID' });
}
+ const enabled = [...enabledColumns].sort((a, b) => a - b);
+ const fps = payload.fps ?? packaged.frameRate;
+ const slug = payload.slug || `${run.direction}-loop`;
- const atlasAbs = resolveSpriteAssetPath(recordId, atlasPath);
+ const atlasAbs = resolveSpriteAssetPath(recordId, packaged.stripPath);
if (!await pathExists(atlasAbs)) {
- throw new ServerError(`Atlas not found: ${atlasPath}`, { status: 404, code: 'ATLAS_NOT_FOUND' });
+ throw new ServerError(`Packed strip not found: ${packaged.stripPath}`, { status: 404, code: 'ATLAS_NOT_FOUND' });
}
const { data, info } = await sharp(atlasAbs).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
- const maxColumn = Math.max(...allColumns);
- if ((maxColumn + 1) * cellWidth > info.width || (row + 1) * cellHeight > info.height) {
- throw new ServerError('Requested cells fall outside the atlas', { status: 400, code: 'TRIM_BOUNDS_INVALID' });
+ if ((Math.max(...allColumns) + 1) * cellSize > info.width || cellSize > info.height) {
+ throw new ServerError('Packed strip does not match its manifest geometry', { status: 409, code: 'RUN_STRIP_INVALID' });
}
// Crop the enabled cells — straight pixel copies, no resampling.
- const frames = enabledColumns.map((col) => {
- const out = Buffer.alloc(cellWidth * cellHeight * 4);
- for (let y = 0; y < cellHeight; y++) {
- const srcStart = (((row * cellHeight) + y) * info.width + col * cellWidth) * 4;
- data.copy(out, y * cellWidth * 4, srcStart, srcStart + cellWidth * 4);
+ const frames = enabled.map((col) => {
+ const out = Buffer.alloc(cellSize * cellSize * 4);
+ for (let y = 0; y < cellSize; y++) {
+ const srcStart = (y * info.width + col * cellSize) * 4;
+ data.copy(out, y * cellSize * 4, srcStart, srcStart + cellSize * 4);
}
- return { data: out, width: cellWidth, height: cellHeight };
+ return { data: out, width: cellSize, height: cellSize };
});
const trimsAbs = join(spriteDir(recordId), TRIMS_DIR);
await ensureDir(trimsAbs);
const prefix = await nextTrimPrefix(trimsAbs, slug);
- const strip = Buffer.alloc(cellWidth * frames.length * cellHeight * 4);
+ const strip = Buffer.alloc(cellSize * frames.length * cellSize * 4);
frames.forEach((frame, i) => {
- for (let y = 0; y < cellHeight; y++) {
+ for (let y = 0; y < cellSize; y++) {
frame.data.copy(
strip,
- (y * cellWidth * frames.length + i * cellWidth) * 4,
- y * cellWidth * 4,
- (y + 1) * cellWidth * 4,
+ (y * cellSize * frames.length + i * cellSize) * 4,
+ y * cellSize * 4,
+ (y + 1) * cellSize * 4,
);
}
});
const stripName = `${prefix}-strip.png`;
- const stripAbs = join(trimsAbs, stripName);
- await sharp(strip, { raw: { width: cellWidth * frames.length, height: cellHeight, channels: 4 } })
+ const stripBuf = await sharp(strip, { raw: { width: cellSize * frames.length, height: cellSize, channels: 4 } })
.png()
- .toFile(stripAbs);
+ .toBuffer();
+ await writeFile(join(trimsAbs, stripName), stripBuf);
const gifName = `${prefix}.gif`;
await encodeTrimGif(frames, fps, join(trimsAbs, gifName));
+ const phaseByColumn = Object.fromEntries(packaged.frames.map((f) => [f.outputIndex, f.phase]));
const manifest = {
schemaVersion: 1,
kind: 'animation-loop-trim',
status: 'candidate',
- sourceAtlasPath: atlasPath,
+ runId,
+ sourceAtlasPath: packaged.stripPath,
sourceAtlasSha256: await sha256File(atlasAbs),
- row,
- cellWidth,
- cellHeight,
+ row: 0,
+ cellWidth: cellSize,
+ cellHeight: cellSize,
fps,
allAtlasColumns: allColumns,
- enabledAtlasColumns: enabledColumns,
- disabledAtlasColumns: allColumns.filter((c) => !enabledColumns.includes(c)),
- selectedFrames: enabledColumns.map((atlasColumn, outputIndex) => ({
+ enabledAtlasColumns: enabled,
+ disabledAtlasColumns: allColumns.filter((c) => !enabled.includes(c)),
+ selectedFrames: enabled.map((atlasColumn, outputIndex) => ({
outputIndex,
atlasColumn,
- sourceFrameIndex: sourceFrameIndices[outputIndex],
- sourceFrameLabel: sourceFrameLabels[outputIndex],
+ sourceFrameIndex: atlasColumn,
+ sourceFrameLabel: phaseByColumn[atlasColumn] || String(atlasColumn),
})),
stripPath: `${TRIMS_DIR}/${stripName}`,
gifPath: `${TRIMS_DIR}/${gifName}`,
diff --git a/server/services/sprites/walkTrims.test.js b/server/services/sprites/walkTrims.test.js
index 6b0a3ea0cc..65794c9d0a 100644
--- a/server/services/sprites/walkTrims.test.js
+++ b/server/services/sprites/walkTrims.test.js
@@ -1,7 +1,8 @@
/**
- * Loop trimmer (#2897): non-destructive re-pack of enabled atlas cells into
- * versioned strip + GIF + manifest. ffmpeg is mocked (the GIF encode is a
- * spawn); the pixel re-pack is asserted for real via sharp.
+ * Loop trimmer (#2897): non-destructive re-pack of enabled strip cells into
+ * versioned strip + GIF + manifest, with all geometry derived from the run's
+ * packaged manifest. ffmpeg is mocked (the GIF encode is a spawn); the pixel
+ * re-pack is asserted for real via sharp.
*/
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
@@ -39,11 +40,13 @@ const CELL = 8;
const CELL_COLORS = [
[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 0, 255],
];
+const PHASES4 = ['left-contact', 'left-down', 'left-passing', 'left-up'];
+const RUN_ID = 'walk-east-00000000';
let seq = 0;
const newId = () => `trimmer-${++seq}`;
-async function characterWithAtlas(id) {
+async function characterWithRun(id) {
await records.createRecord({ kind: 'character', name: 'Trimmer' }, id);
const width = CELL * CELL_COLORS.length;
const buf = Buffer.alloc(width * CELL * 4);
@@ -52,23 +55,26 @@ async function characterWithAtlas(id) {
buf.set(CELL_COLORS[Math.floor(x / CELL)], (y * width + x) * 4);
}
}
- const dir = join(TEST_ROOT, 'sprites', id, 'grok', 'walk-east-00000000', 'generated');
- await mkdir(dir, { recursive: true });
- await sharp(buf, { raw: { width, height: CELL, channels: 4 } }).png().toFile(join(dir, 'strip.png'));
- return { id, atlasPath: 'grok/walk-east-00000000/generated/strip.png' };
+ const runDir = join(TEST_ROOT, 'sprites', id, 'grok', RUN_ID);
+ await mkdir(join(runDir, 'generated'), { recursive: true });
+ const stripRel = `grok/${RUN_ID}/generated/strip.png`;
+ await sharp(buf, { raw: { width, height: CELL, channels: 4 } }).png()
+ .toFile(join(runDir, 'generated', 'strip.png'));
+ const manifestRel = `grok/${RUN_ID}/generated/manifest.json`;
+ await writeFile(join(runDir, 'generated', 'manifest.json'), JSON.stringify({
+ schemaVersion: 1,
+ stripPath: stripRel,
+ frameRate: 12,
+ frameCount: 4,
+ alignment: { cellSize: CELL },
+ frames: PHASES4.map((phase, outputIndex) => ({ outputIndex, phase })),
+ }));
+ await writeFile(join(runDir, 'animation-run.json'), JSON.stringify({
+ schemaVersion: 1, id: RUN_ID, status: 'candidate', direction: 'east', postprocessManifest: manifestRel,
+ }));
+ return id;
}
-const basePayload = (atlasPath) => ({
- slug: 'east-loop',
- atlasPath,
- row: 0,
- cellWidth: CELL,
- cellHeight: CELL,
- fps: 12,
- allColumns: [0, 1, 2, 3],
- enabledColumns: [0, 2, 3],
-});
-
beforeEach(() => {
runFfmpegProcess.mockClear();
rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });
@@ -76,9 +82,9 @@ beforeEach(() => {
afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
describe('saveLoopTrim', () => {
- it('re-packs only the enabled cells, in order, without resampling', async () => {
- const { id, atlasPath } = await characterWithAtlas(newId());
- const result = await saveLoopTrim(id, basePayload(atlasPath));
+ it('re-packs only the enabled cells with manifest-derived geometry and labels', async () => {
+ const id = await characterWithRun(newId());
+ const result = await saveLoopTrim(id, { runId: RUN_ID, enabledColumns: [0, 2, 3] });
expect(result).toMatchObject({
strip: 'walk/trims/east-loop-v001-strip.png',
loop: 'walk/trims/east-loop-v001.gif',
@@ -99,41 +105,48 @@ describe('saveLoopTrim', () => {
expect(manifest).toMatchObject({
kind: 'animation-loop-trim',
status: 'candidate',
- sourceAtlasPath: atlasPath,
+ runId: RUN_ID,
+ sourceAtlasPath: `grok/${RUN_ID}/generated/strip.png`,
row: 0,
- fps: 12,
+ cellWidth: CELL,
+ fps: 12, // derived from the run manifest's frameRate
allAtlasColumns: [0, 1, 2, 3],
enabledAtlasColumns: [0, 2, 3],
disabledAtlasColumns: [1],
});
expect(manifest.selectedFrames).toEqual([
- { outputIndex: 0, atlasColumn: 0, sourceFrameIndex: 0, sourceFrameLabel: '0' },
- { outputIndex: 1, atlasColumn: 2, sourceFrameIndex: 2, sourceFrameLabel: '2' },
- { outputIndex: 2, atlasColumn: 3, sourceFrameIndex: 3, sourceFrameLabel: '3' },
+ { outputIndex: 0, atlasColumn: 0, sourceFrameIndex: 0, sourceFrameLabel: 'left-contact' },
+ { outputIndex: 1, atlasColumn: 2, sourceFrameIndex: 2, sourceFrameLabel: 'left-passing' },
+ { outputIndex: 2, atlasColumn: 3, sourceFrameIndex: 3, sourceFrameLabel: 'left-up' },
]);
expect(manifest.sourceAtlasSha256).toMatch(/^[0-9a-f]{64}$/);
- // GIF encoded through the ffmpeg primitive with the requested fps.
+ // GIF encoded through the ffmpeg primitive with the manifest fps.
const gifArgs = runFfmpegProcess.mock.calls[0][0].args;
- expect(gifArgs).toContain('-framerate');
expect(gifArgs[gifArgs.indexOf('-framerate') + 1]).toBe('12');
});
- it('versions successive trims of the same slug', async () => {
- const { id, atlasPath } = await characterWithAtlas(newId());
- await saveLoopTrim(id, basePayload(atlasPath));
- const second = await saveLoopTrim(id, basePayload(atlasPath));
- expect(second.strip).toBe('walk/trims/east-loop-v002-strip.png');
+ it('versions successive trims and honors fps/slug overrides', async () => {
+ const id = await characterWithRun(newId());
+ await saveLoopTrim(id, { runId: RUN_ID, enabledColumns: [0, 1] });
+ const second = await saveLoopTrim(id, { runId: RUN_ID, enabledColumns: [0, 1], fps: 6, slug: 'custom' });
+ expect(second.strip).toBe('walk/trims/custom-v001-strip.png');
+ const gifArgs = runFfmpegProcess.mock.calls[1][0].args;
+ expect(gifArgs[gifArgs.indexOf('-framerate') + 1]).toBe('6');
+ const third = await saveLoopTrim(id, { runId: RUN_ID, enabledColumns: [0, 1] });
+ expect(third.strip).toBe('walk/trims/east-loop-v002-strip.png');
});
- it('rejects a non-subset, mismatched labels, and out-of-bounds cells', async () => {
- const { id, atlasPath } = await characterWithAtlas(newId());
- await expect(saveLoopTrim(id, { ...basePayload(atlasPath), enabledColumns: [0, 9] }))
- .rejects.toMatchObject({ code: 'TRIM_COLUMNS_INVALID' });
- await expect(saveLoopTrim(id, { ...basePayload(atlasPath), sourceFrameLabels: ['only-one'] }))
+ it('rejects unknown runs, unpackaged runs, and out-of-strip columns', async () => {
+ const id = await characterWithRun(newId());
+ await expect(saveLoopTrim(id, { runId: 'walk-east-deadbeef', enabledColumns: [0, 1] }))
+ .rejects.toMatchObject({ code: 'RUN_NOT_FOUND' });
+ await expect(saveLoopTrim(id, { runId: RUN_ID, enabledColumns: [0, 9] }))
.rejects.toMatchObject({ code: 'TRIM_COLUMNS_INVALID' });
- await expect(saveLoopTrim(id, { ...basePayload(atlasPath), allColumns: [0, 1, 2, 3, 4], enabledColumns: [0, 4] }))
- .rejects.toMatchObject({ code: 'TRIM_BOUNDS_INVALID' });
- await expect(saveLoopTrim(id, { ...basePayload(atlasPath), atlasPath: 'grok/nope.png' }))
- .rejects.toMatchObject({ code: 'ATLAS_NOT_FOUND' });
+ const runDir = join(TEST_ROOT, 'sprites', id, 'grok', RUN_ID);
+ await writeFile(join(runDir, 'animation-run.json'), JSON.stringify({
+ schemaVersion: 1, id: RUN_ID, status: 'queued', direction: 'east',
+ }));
+ await expect(saveLoopTrim(id, { runId: RUN_ID, enabledColumns: [0, 1] }))
+ .rejects.toMatchObject({ code: 'RUN_NOT_CANDIDATE' });
});
});