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

address review (claude): make the source-frames read side-effect free and verify its provenance

[._.]/ Adam Eivy8bda1b14f022
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0e084344fc..4e1e7db9c9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -25,7 +25,7 @@
## Sprite Manager
-- **[issue-2980] See every frame a walk's video produced — and rebuild the loop at a new frame count without re-rendering** — the Loop Trimmer could only *drop* columns from a strip that was already packed, so an 8-frame walk could never become a 12-frame one there: the extra source frames were thrown away at pack time and nothing in the workspace showed they had ever existed. The trimmer now has a **Source frames** section listing every frame extracted from that run's clip (typically ~70 at 12fps), with the gait cycle the packer picked marked in amber and the frames that became the strip's columns highlighted — so the headroom above the current count is visible at a glance. A **Re-derive from clip** control beside it repacks the loop from that same on-disk video at a new frame count / speed, with no AI call and no new render; the frame count and speed are the walk set's shared cycle target rather than a free per-run range, since every direction of one walk has to agree for the atlas to compile, and changing them says so before it retargets the set. A run whose `raw/` frames were cleaned up re-extracts them on demand; an approved direction or a frozen set offers the matching inline Reopen / Unlock instead of failing on click; and a run imported without its clip explains that in one line rather than showing an empty grid. Re-deriving an *imported* run also works now — its run id was rejected by the reprocess endpoint before it ever reached the service that #2993 taught to handle it.
+- **[issue-2980] See every frame a walk's video produced — and rebuild the loop at a new frame count without re-rendering** — the Loop Trimmer could only *drop* columns from a strip that was already packed, so an 8-frame walk could never become a 12-frame one there: the extra source frames were thrown away at pack time and nothing in the workspace showed they had ever existed. The trimmer now has a **Source frames** section listing every frame extracted from that run's clip (typically ~70 at 12fps), with the gait cycle the packer picked marked in amber and the frames that became the strip's columns highlighted — so the headroom above the current count is visible at a glance. A **Re-derive from clip** control beside it repacks the loop from that same on-disk video at a new frame count / speed, with no AI call and no new render; the frame count and speed are the walk set's shared cycle target rather than a free per-run range, since every direction of one walk has to agree for the atlas to compile, and changing them says so before it retargets the set. A run whose extracted frames were cleaned up (which is every imported run — the importer doesn't copy them) says so and offers a one-click "Extract frames from clip" rather than quietly running ffmpeg for every direction you happen to click through; an approved direction or a frozen set offers the matching inline Reopen / Unlock instead of failing on click; a run with no clip at all explains that in one line rather than showing an empty grid, and names the right remedy for how it got there; and if the frames on disk turn out not to be the ones the strip was packed from, the cycle markers are withheld rather than pointing at the wrong frames. Re-deriving an *imported* run also works now — its run id was rejected by the reprocess endpoint before it ever reached the service that #2993 taught to handle it.
- **[issue-2993] Imported characters can finally be re-derived — smoother walks, and an atlas you can compile here** — a character brought over from a source art pipeline was frozen the moment it arrived: Unlock, Reopen and Compile all refused it outright, so an imported 8-frame walk could never be brought up to 12 and its atlas could only ever be re-published, never rebuilt. That refusal was written when the import genuinely left nothing behind to work from — but the importer now copies each direction's source clip, so it had become a lie. Those actions are now gated on whether the clip is actually there: a direction with its clip on disk reopens and reprocesses at any frame count and speed, with no new render and no new spend, and the buttons appear instead of being hidden. A direction with no clip is still refused, but now says so plainly and tells you to re-import the character. Compiling is likewise per-direction: the atlas names the directions still packaged by the source pipeline instead of refusing the whole set, so an imported character becomes compilable one direction at a time as you re-derive them — and approving a direction whose packaged frames were never imported is now caught up front, rather than surfacing much later as an unexplained compile error.
- **[issue-2996] A character you'd started but not locked now begins at the turnaround sheet too** — when turnaround sheets landed, characters already in progress kept the old flow: they'd still ask for a main reference first, and only pick up sheets afterward. Now a character that hasn't frozen anything yet simply starts at step 1 like a new one — nothing of yours is lost, because nothing was locked. Characters that *have* frozen a main reference are untouched: their locked artwork stays exactly as it is, and they still backfill a sheet from it. Uploading a design image is now accepted only on the turnaround step, since that's the render it actually seeds — the main reference and every anchor are drawn from the sheet, so attaching a separate image to them has nowhere to go and is rejected with a clear message.
- **[issue-2982] Publishing an atlas your game can't read now stops instead of silently breaking it** — the atlas PNG used to be the *entire* export: nothing described how many walk frames were in it, so a game with an 8-frame walk baked in as a constant would happily accept a 12-frame publish and then draw the wrong frames from the wrong columns forever, with no crash and no log. Two things fix that. A publish target can now declare the grid it was built against (`runtimeContract`: walk frame count, cell size, column count), and a publish whose compiled atlas disagrees is refused with a message naming both numbers — "Atlas has 14 columns (12 walk frames) but Example App expects 10 (8 walk frames)" — plus the two ways to resolve it. And every publish now writes a small `….layout.json` file beside the atlas describing the grid PortOS actually produced: cell size, ordered column names, per-track column spans (so a future multi-frame scanner or ambient action is additive, not a rewrite), row order, and the atlas checksum — so the game can resolve columns by name and verify what it loaded instead of trusting a constant. Targets with no declared contract publish exactly as before. Also documented: playback **fps in PortOS is preview-only**. It ships in the sidecar labeled as authoring metadata, because the consuming game drives its walk from movement distance and has no frame-rate concept at all — a 6 fps preview and a 24 fps preview export byte-identical atlases. See `docs/features/sprite-export-contract.md`.
diff --git a/client/src/components/sprites/LoopTrimmer.jsx b/client/src/components/sprites/LoopTrimmer.jsx
index 5f90fe7229..a5a05d38d3 100644
--- a/client/src/components/sprites/LoopTrimmer.jsx
+++ b/client/src/components/sprites/LoopTrimmer.jsx
@@ -118,12 +118,6 @@ export default function LoopTrimmer({
const [outputName, setOutputName] = useState('');
const [result, setResult] = useState(null);
const [img, setImg] = useState(null);
- // Bumped when the run is re-derived (#2980). The repacked strip lands at the
- // SAME path, so nothing in the load effect's other deps changes and the <img>
- // would never be re-requested — it would keep painting the old geometry. The
- // asset mount serves `max-age=0` with an ETag, so the re-request itself
- // revalidates and picks up the new bytes; only the trigger was missing.
- const [stripVersion, setStripVersion] = useState(0);
// Re-seed everything the moment the source changes — a stale enabled set from
// a previous strip could hold out-of-range indices and 400 the endpoint.
@@ -147,7 +141,16 @@ export default function LoopTrimmer({
image.onload = () => setImg(image);
image.src = spriteAssetUrl(recordId, source.stripPath);
return () => { image.onload = null; };
- }, [source?.id, source?.stripPath, recordId, stripVersion]);
+ // Geometry is in the deps, not just the path: a re-derive (#2980) repacks the
+ // strip at the SAME path, so nothing else here changes and the <img> would
+ // never be re-requested — it would keep painting the old column count. Keying
+ // on the refreshed frameCount/fps also sequences the reload correctly: it
+ // fires when the parent's new walk state lands, so `cellW` can never slice a
+ // freshly-loaded 12-column strip by the stale count of 8. (The asset mount
+ // serves max-age=0 with an ETag, so the re-request revalidates for free; a
+ // re-derive at unchanged geometry is deterministic and byte-identical, so
+ // skipping the reload there is correct rather than a missed refresh.)
+ }, [source?.id, source?.stripPath, recordId, frameCount, source?.fps]);
const cellW = img && frameCount > 0 ? img.naturalWidth / frameCount : 0;
const cellH = img ? img.naturalHeight : 0;
@@ -179,13 +182,6 @@ export default function LoopTrimmer({
setFrameIndex((prev) => (prev + delta + frameCount) % frameCount);
};
- // Stable identity so the memoized source-frames panel doesn't re-render on
- // every loop-preview tick (the playback interval fires 12–24×/second).
- const onSourceFramesSaved = useCallback(() => {
- setStripVersion((v) => v + 1);
- onSaved();
- }, [onSaved]);
-
const slug = sanitizeTrimSlug(outputName);
const [save, saving] = useAsyncAction(async () => {
const trim = await trimSpriteWalk(recordId, {
@@ -372,8 +368,11 @@ export default function LoopTrimmer({
{/* Every frame the run's clip produced, plus the in-place re-derive
(#2980). Run sources only: a saved trim has no run (and no clip)
behind it, so there is nothing to enumerate or re-derive. */}
+ {/* `onSaved` is passed straight through: the parent already hands down a
+ stable callback, and the panel is memoized so it doesn't re-render on
+ every loop-preview tick. */}
{source?.kind === 'run' && source.runId && (
- <WalkSourceFrames recordId={recordId} runId={source.runId} onSaved={onSourceFramesSaved} />
+ <WalkSourceFrames recordId={recordId} runId={source.runId} onSaved={onSaved} />
)}
{/* Save + result */}
diff --git a/client/src/components/sprites/WalkSourceFrames.jsx b/client/src/components/sprites/WalkSourceFrames.jsx
index b12f0b2ed6..ce8801d95d 100644
--- a/client/src/components/sprites/WalkSourceFrames.jsx
+++ b/client/src/components/sprites/WalkSourceFrames.jsx
@@ -6,7 +6,7 @@ import {
} from 'lucide-react';
import toast from '../ui/Toast';
import {
- getSpriteWalkSourceFrames, postprocessSpriteWalk,
+ getSpriteWalkSourceFrames, extractSpriteWalkSourceFrames, postprocessSpriteWalk,
unlockSpriteWalk, reopenSpriteWalk,
} from '../../services/apiSprites.js';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
@@ -33,12 +33,18 @@ import { spriteAssetUrl, PIXELATED } from './spriteAssets.js';
// makes, so a target this panel's fetch is one refetch behind on can't 409 a
// value the user never chose.
-// Why a run has no frames to show. Both are real states on this install, and
-// neither is an error — the panel explains rather than rendering an empty grid.
-const UNAVAILABLE_COPY = {
- 'no-source-video': 'This run was imported without its source clip, so the packed strip is all that exists here — frames can be dropped but not added. Re-import this character to bring its clip across.',
+// Why a run has no frames to show. All three are real states on this install,
+// and none is an error — the panel explains rather than rendering an empty grid.
+// `no-source-video` takes the run's provenance because the remedy differs: an
+// import needs its clip brought across, while a run generated here had its clip
+// cleaned up locally and re-importing is not the answer.
+const unavailableCopy = ({ reason, imported }) => ({
+ 'no-source-video': imported
+ ? 'This run was imported without its source clip, so the packed strip is all that exists here — frames can be dropped but not added. Re-import this character to bring its clip across.'
+ : 'This run\'s source clip is no longer on disk, so the packed strip is all that is left — frames can be dropped but not added. Regenerate the direction to get a new clip.',
+ 'raw-frames-cleaned': 'The source clip is here, but the frames extracted from it were cleaned up. They can be re-extracted from the clip — no new render.',
'run-not-packaged': 'This direction came from a redraw cycle rather than a rendered clip, so there are no source frames behind it.',
-};
+}[reason] || 'No source frames are available for this run.');
// What the user has to do before the loop can be re-derived. Mirrors the server's
// own guards (walk.js#reDeriveLockReason) so the panel never offers an action the
@@ -136,11 +142,24 @@ function WalkSourceFrames({ recordId, runId, onSaved = () => {} }) {
// for an omitted count/fps, so the request can't 409 against a target this
// panel's fetch is one refetch behind on (#2985) — same call WalkWorkflow's
// Reprocess makes.
- await postprocessSpriteWalk(recordId, { runId }, { silent: true });
- toast.success(`Re-derived from the source clip · ${data.target?.frameCount}f @ ${data.target?.fps}fps`);
+ // Report the geometry the SERVER packed (it echoes the updated run record),
+ // not the target this panel last fetched — those differ exactly when another
+ // surface retargeted the set, which is when a wrong number would mislead.
+ const run = await postprocessSpriteWalk(recordId, { runId }, { silent: true });
+ toast.success(`Re-derived from the source clip · ${run?.frameCount}f @ ${run?.fps}fps`);
await refresh();
}, { errorMessage: 'Could not re-derive this loop' });
+ // The 'raw-frames-cleaned' remedy. Explicitly user-triggered: the read above is
+ // side-effect free precisely so opening the trimmer on an imported character
+ // doesn't spawn an ffmpeg decode per direction.
+ const [extractFrames, extracting] = useAsyncAction(async () => {
+ const next = await extractSpriteWalkSourceFrames(recordId, runId, { silent: true });
+ setData(next);
+ setOpen(true);
+ toast.success(`Extracted ${next.frames?.length ?? 0} source frames from the clip`);
+ }, { errorMessage: 'Could not extract frames from this clip' });
+
const [unlock, unlocking] = useAsyncAction(async () => {
if (data.lockReason === 'finalized') {
await unlockSpriteWalk(recordId, { silent: true });
@@ -152,8 +171,13 @@ function WalkSourceFrames({ recordId, runId, onSaved = () => {} }) {
await refresh();
}, { errorMessage: 'Could not unlock this direction' });
- const busy = redriving || unlocking || targetSaving;
- const lock = data && !data.editable ? LOCK_COPY[data.lockReason] : null;
+ const busy = redriving || unlocking || targetSaving || extracting;
+ // Suppressed when the unavailable line above already said the same thing (a
+ // clipless run reports both `reason` and `lockReason` as the missing clip) —
+ // printing the explanation twice reads like two different problems.
+ const lock = data && !data.editable && !(!data.available && data.lockReason === 'no-source-video')
+ ? LOCK_COPY[data.lockReason]
+ : null;
const frames = data?.frames || [];
const sectionCls = 'bg-port-bg border border-port-border rounded p-3 space-y-3';
@@ -199,9 +223,21 @@ function WalkSourceFrames({ recordId, runId, onSaved = () => {} }) {
</div>
{!data.available && (
- <p className="text-[11px] text-gray-500 leading-relaxed">
- {UNAVAILABLE_COPY[data.reason] || 'No source frames are available for this run.'}
- </p>
+ <div className="space-y-1.5">
+ <p className="text-[11px] text-gray-500 leading-relaxed">
+ {unavailableCopy(data)}
+ </p>
+ {data.reason === 'raw-frames-cleaned' && (
+ <button
+ onClick={extractFrames}
+ disabled={busy}
+ className="flex items-center gap-1 px-2 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50"
+ >
+ <RefreshCw className={`w-3.5 h-3.5 ${extracting ? 'animate-spin' : ''}`} />
+ {extracting ? 'Extracting…' : 'Extract frames from clip'}
+ </button>
+ )}
+ </div>
)}
{data.available && open && (
@@ -211,13 +247,23 @@ function WalkSourceFrames({ recordId, runId, onSaved = () => {} }) {
{data.maxSourceSeconds ? ` (first ${data.maxSourceSeconds}s)` : ''}.
{data.cycle?.windowStartFrame != null && (
<>
- {' '}Frames {data.cycle.windowStartFrame}–{data.cycle.windowEndFrame} are the gait
- cycle the packer selected (
+ {/* windowEndFrame is the exclusive seam frame — the last frame
+ IN the cycle is the one before it, which is also what the
+ grid's marking uses. */}
+ {' '}Frames {data.cycle.windowStartFrame}–{data.cycle.windowEndFrame - 1} are the
+ gait cycle the packer selected (
<span className="text-port-warning">amber</span>); the{' '}
<span className="text-port-accent">highlighted</span> ones became the packed
strip&apos;s columns.
</>
)}
+ {data.cycleProvenance === 'stale' && (
+ <>
+ {' '}These frames were re-extracted here and don&apos;t match the ones the packed
+ strip was built from, so the cycle window and packed columns aren&apos;t marked —
+ re-derive to rebuild the strip from these frames.
+ </>
+ )}
</p>
<div className="grid grid-cols-4 sm:grid-cols-8 lg:grid-cols-12 gap-1.5">
{frames.map((frame) => (
diff --git a/client/src/components/sprites/WalkSourceFrames.test.jsx b/client/src/components/sprites/WalkSourceFrames.test.jsx
index 98efa38151..b530574f16 100644
--- a/client/src/components/sprites/WalkSourceFrames.test.jsx
+++ b/client/src/components/sprites/WalkSourceFrames.test.jsx
@@ -10,7 +10,9 @@ import {
// the SET target (#2985), never a page-level form value.
vi.mock('../../services/apiSprites.js', () => ({
getSpriteWalkSourceFrames: vi.fn(),
- postprocessSpriteWalk: vi.fn(() => Promise.resolve({})),
+ extractSpriteWalkSourceFrames: vi.fn(),
+ // Echoes the updated run record, which is what the success toast reports.
+ postprocessSpriteWalk: vi.fn(() => Promise.resolve({ id: 'walk-east-0a1b2c3d', frameCount: 12, fps: 12 })),
setSpriteWalkTarget: vi.fn(() => Promise.resolve({})),
unlockSpriteWalk: vi.fn(() => Promise.resolve({})),
reopenSpriteWalk: vi.fn(() => Promise.resolve({})),
@@ -18,8 +20,8 @@ vi.mock('../../services/apiSprites.js', () => ({
import WalkSourceFrames from './WalkSourceFrames';
import {
- getSpriteWalkSourceFrames, postprocessSpriteWalk, setSpriteWalkTarget,
- unlockSpriteWalk, reopenSpriteWalk,
+ getSpriteWalkSourceFrames, extractSpriteWalkSourceFrames, postprocessSpriteWalk,
+ setSpriteWalkTarget, unlockSpriteWalk, reopenSpriteWalk,
} from '../../services/apiSprites.js';
const RUN_ID = 'walk-east-0a1b2c3d';
@@ -41,6 +43,8 @@ const payload = (overrides = {}) => ({
windowStart: 1, windowLength: 4, windowStartFrame: 3, windowEndFrame: 7,
},
selectedSourceIndices: [3, 5],
+ cycleProvenance: 'verified',
+ imported: false,
current: { frameCount: 8, fps: 12 },
target: {
frameCount: 8, fps: 12, source: 'derived', sourceLabel: 'from the first approved direction',
@@ -94,8 +98,10 @@ describe('WalkSourceFrames', () => {
expect(cellFor(3).getAttribute('title'))
.toBe('source frame 3 — in the selected cycle window, packed into the strip');
expect(cellFor(5).className).toContain('ring-port-accent');
- // 7 is the window's exclusive end.
+ // 7 is the window's exclusive end — so the prose must say 3–6, or the label
+ // would claim a frame the grid leaves unmarked.
expect(cellFor(7).getAttribute('title')).toBe('source frame 7');
+ expect(screen.getByText(/Frames 3–6 are the/)).toBeTruthy();
});
// Geometry is deliberately omitted so the server adopts the pinned target: a
@@ -156,13 +162,58 @@ describe('WalkSourceFrames', () => {
it('explains an imported run with no clip instead of showing an empty grid', async () => {
await renderPanel(payload({
- available: false, reason: 'no-source-video', frames: [], cycle: null, selectedSourceIndices: [], editable: false, lockReason: 'no-source-video',
+ available: false,
+ reason: 'no-source-video',
+ imported: true,
+ frames: [],
+ cycle: null,
+ selectedSourceIndices: [],
+ cycleProvenance: 'none',
+ editable: false,
+ lockReason: 'no-source-video',
}));
expect(screen.getByText(/imported without its source clip/)).toBeTruthy();
expect(screen.queryByRole('button', { name: /source frames @/ })).toBeNull();
expect(deriveButton()).toBeDisabled();
- // Nothing to unlock — a missing clip has no action behind it.
- expect(screen.queryByRole('button', { name: /Reopen|Unlock/ })).toBeNull();
+ // Nothing to unlock — a missing clip has no action behind it — and the
+ // explanation is printed once, not echoed by the lock block.
+ expect(screen.queryByRole('button', { name: /Reopen|Unlock|Extract/ })).toBeNull();
+ expect(screen.queryByText(/not on disk, so there is nothing to re-derive/)).toBeNull();
+ });
+
+ // The remedy differs by provenance: a run generated here can be regenerated,
+ // and telling that user to "re-import this character" would be wrong.
+ it('does not blame the importer for a natively-generated run whose clip is gone', async () => {
+ await renderPanel(payload({
+ available: false, reason: 'no-source-video', imported: false, frames: [], editable: false, lockReason: 'no-source-video',
+ }));
+ expect(screen.getByText(/Regenerate the direction to get a new clip/)).toBeTruthy();
+ expect(screen.queryByText(/Re-import this character/)).toBeNull();
+ });
+
+ // The read is side-effect free by design; extraction is one explicit click.
+ it('offers an explicit extract action when only the raw frames were cleaned', async () => {
+ extractSpriteWalkSourceFrames.mockResolvedValue(payload());
+ await renderPanel(payload({
+ available: false, reason: 'raw-frames-cleaned', frames: [], cycle: null, selectedSourceIndices: [], editable: true, lockReason: null,
+ }));
+ expect(screen.getByText(/frames extracted from it were cleaned up/)).toBeTruthy();
+ // The re-derive still works — that depends on the clip, not on the frames.
+ expect(deriveButton()).not.toBeDisabled();
+
+ fireEvent.click(screen.getByRole('button', { name: /Extract frames from clip/ }));
+ await act(async () => {});
+ expect(extractSpriteWalkSourceFrames).toHaveBeenCalledWith('example-walker', RUN_ID, { silent: true });
+ // The grid opens on the freshly extracted frames rather than staying closed.
+ expect(screen.getAllByRole('img').length).toBe(8);
+ });
+
+ // Marking the wrong frames as "the gait cycle" is worse than marking none.
+ it('withholds the markers and says why when the manifest frames are stale', async () => {
+ await renderPanel(payload({ cycle: null, selectedSourceIndices: [], cycleProvenance: 'stale' }));
+ expandGrid();
+ expect(screen.getByText(/don't match the ones the packed strip was built from/)).toBeTruthy();
+ expect(screen.getByTitle('source frame 3').className).not.toContain('ring-port-accent');
});
it('offers reopen for an approved direction and posts it on confirm', async () => {
diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.js
index 281f980e53..6858ea580d 100644
--- a/client/src/services/apiSprites.js
+++ b/client/src/services/apiSprites.js
@@ -129,16 +129,24 @@ export const reopenSpriteWalk = (id, body, options = {}) => request(`/sprites/${
});
// Every frame one run's source video produced (#2980): `{ available, reason,
-// frames, cycle, selectedSourceIndices, current, target, editable, lockReason }`.
-// `available: false` carries a reason ('no-source-video' | 'run-not-packaged')
-// rather than an empty list, so "nothing to show" never reads like "no frames".
-// Re-extracts server-side on demand when the clip is on disk but `raw/` was
-// cleaned, so a slow first call is expected for such a run.
+// frames, cycle, selectedSourceIndices, cycleProvenance, current, target,
+// editable, lockReason }`. Strictly read-only. `available: false` carries a
+// reason ('no-source-video' | 'raw-frames-cleaned' | 'run-not-packaged') rather
+// than an empty list, so "nothing to show" never reads like "no frames".
export const getSpriteWalkSourceFrames = (id, runId, options = {}) => request(
`/sprites/${encodeURIComponent(id)}/walk/runs/${encodeURIComponent(runId)}/source-frames`,
options,
);
+// Re-extract a run's raw frames from its on-disk clip (the 'raw-frames-cleaned'
+// remedy) and return the same payload. Deliberately a separate, user-triggered
+// call: the read above must not spawn ffmpeg for every imported run just because
+// the trimmer rendered.
+export const extractSpriteWalkSourceFrames = (id, runId, options = {}) => request(
+ `/sprites/${encodeURIComponent(id)}/walk/runs/${encodeURIComponent(runId)}/source-frames/extract`,
+ { method: 'POST', ...options },
+);
+
// Save a non-destructive loop trim (strip + GIF + manifest, versioned).
export const trimSpriteWalk = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/walk/trim`, {
method: 'POST', body: JSON.stringify(body), ...options,
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index c589a42a72..5582ada341 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -204,13 +204,22 @@ router.post('/:id/walk/postprocess', asyncHandler(async (req, res) => {
// Every frame the run's source video produced (#2980), the cycle window the
// packer selected out of them, and which became packed columns — the Loop
// Trimmer's window onto the raw intermediates `listSpriteAssets` excludes.
-// Read-only; re-extracts on demand when the clip is on disk but `raw/` was
-// cleaned. Multi-segment, so it can't be captured by the `/:id` GET.
+// Strictly read-only. Multi-segment, so it can't be captured by the `/:id` GET.
router.get('/:id/walk/runs/:runId/source-frames', asyncHandler(async (req, res) => {
const { runId } = validateRequest(spriteWalkSourceFramesParamsSchema, req.params);
res.json(await getWalkSourceFrames(req.params.id, runId));
}));
+// Re-extract a run's raw frames from the clip already on disk, then return the
+// same payload. Separate from the GET because the importer never copies `raw/`,
+// so every imported run would otherwise spawn an ffmpeg decode (~96 PNGs) just
+// from rendering the trimmer — this keeps the work behind an explicit click. No
+// AI call; deterministic ffmpeg only.
+router.post('/:id/walk/runs/:runId/source-frames/extract', asyncHandler(async (req, res) => {
+ const { runId } = validateRequest(spriteWalkSourceFramesParamsSchema, req.params);
+ res.json(await getWalkSourceFrames(req.params.id, runId, { extract: true }));
+}));
+
// Non-destructive loop trim: re-pack enabled frames from a packed strip into
// a versioned trimmed strip + preview GIF. Never mutates the source atlas.
router.post('/:id/walk/trim', asyncHandler(async (req, res) => {
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index c3e2bbc459..04732561c3 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -463,9 +463,17 @@ describe('sprites routes', () => {
expect(r.status).toBe(200);
expect(walk.approveWalkDirection).toHaveBeenCalledWith('pioneer', { direction: 'east', runId: 'walk-east-0a1b2c3d' });
+ // An imported run's id is its source-named directory — approve has been
+ // layout-aware since #2993, so the reopen → re-derive → re-approve flow
+ // must survive its last click.
+ const imported = await request(app).post('/api/sprites/pioneer/walk/approve')
+ .send({ direction: 'east', runId: 'run-3' });
+ expect(imported.status).toBe(200);
+ expect(walk.approveWalkDirection).toHaveBeenCalledWith('pioneer', { direction: 'east', runId: 'run-3' });
+
expect((await request(app).post('/api/sprites/pioneer/walk/approve')
.send({ direction: 'east', runId: '../escape' })).status).toBe(400);
- expect(walk.approveWalkDirection).toHaveBeenCalledOnce();
+ expect(walk.approveWalkDirection).toHaveBeenCalledTimes(2);
});
it('POST /:id/walk/postprocess delegates the rerun (with optional reprocess count/fps)', async () => {
@@ -501,6 +509,22 @@ describe('sprites routes', () => {
expect(walk.getWalkSourceFrames).not.toHaveBeenCalled();
});
+ // The GET must never extract — the importer leaves every imported run without
+ // `raw/`, so a side-effecting read would spawn ffmpeg per direction on render.
+ it('only asks the service to extract from the explicit extract endpoint', async () => {
+ await request(app).get('/api/sprites/pioneer/walk/runs/walk-east-0a1b2c3d/source-frames');
+ expect(walk.getWalkSourceFrames).toHaveBeenCalledWith('pioneer', 'walk-east-0a1b2c3d');
+
+ walk.getWalkSourceFrames.mockClear();
+ const r = await request(app).post('/api/sprites/pioneer/walk/runs/run-3/source-frames/extract');
+ expect(r.status).toBe(200);
+ expect(walk.getWalkSourceFrames).toHaveBeenCalledWith('pioneer', 'run-3', { extract: true });
+
+ walk.getWalkSourceFrames.mockClear();
+ expect((await request(app).post('/api/sprites/pioneer/walk/runs/%2E%2E%2Fescape/source-frames/extract')).status).toBe(400);
+ expect(walk.getWalkSourceFrames).not.toHaveBeenCalled();
+ });
+
// Since #2993 the reprocess re-derives an IMPORTED run in place, so the route
// has to accept an imported run id — the strict native shape made the one path
// back onto the set's target unreachable for exactly those runs.
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index a4b6305195..c4db3092cc 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -1165,6 +1165,48 @@ function cycleWindowOf(packaged) {
};
}
+/**
+ * The packed-strip provenance to report against the raw frames actually on disk:
+ * the cycle window, the source indices that became columns, and whether the two
+ * can be trusted to address the same files.
+ *
+ * The check is not paranoia. `cycleSelection` and `frames[].sourceFrameIndex`
+ * were recorded when the run was PACKAGED — for an imported run, by the source
+ * pipeline's own extraction — while the frames listed here may have been
+ * re-extracted by this install's ffmpeg (`fps=12`, first 8s). If those two
+ * extractions disagree at all, the indices address different PNGs and the panel
+ * would confidently mark the wrong frames as "the gait cycle" and "packed into
+ * the strip" — a false claim about provenance is worse than no claim. The
+ * manifest already records each packed frame's `sourcePath`, so verify the
+ * basenames are among the files on disk and report:
+ *
+ * 'verified' the manifest's source frames are all present → markers are real
+ * 'stale' they are not → markers withheld, and the client says why
+ * 'none' the run carries no packaged cycle to map (never packaged, or a
+ * minimal manifest) → nothing to verify, nothing to withhold
+ */
+function manifestCycleProvenance(packaged, names) {
+ const packedFrames = Array.isArray(packaged?.frames) ? packaged.frames : [];
+ const indices = packedFrames
+ .map((frame) => frame?.sourceFrameIndex)
+ .filter((index) => Number.isInteger(index));
+ if (!indices.length) return { cycle: null, selectedSourceIndices: [], cycleProvenance: 'none' };
+ const onDisk = new Set(names);
+ const declared = packedFrames
+ .map((frame) => (typeof frame?.sourcePath === 'string' ? frame.sourcePath.split('/').pop() : null))
+ .filter(Boolean);
+ // A manifest that declares no sourcePath at all (older/minimal packaging) is
+ // taken at its word — there is nothing to compare, and withholding the markers
+ // would punish a record for being terse rather than wrong.
+ const matches = !declared.length || declared.every((name) => onDisk.has(name));
+ if (!matches) return { cycle: null, selectedSourceIndices: [], cycleProvenance: 'stale' };
+ return {
+ cycle: cycleWindowOf(packaged),
+ selectedSourceIndices: indices,
+ cycleProvenance: 'verified',
+ };
+}
+
/**
* One source-frame response, defaulted to the "nothing to show" shape and
* overridden with whatever was actually found.
@@ -1179,6 +1221,10 @@ function sourceFrameResponse(runId, run, walkTarget, found) {
return {
runId,
direction: run?.direction || null,
+ // Whether the run is still packaged by the source pipeline — the client picks
+ // the right remedy from it (re-import vs "this was generated here"), rather
+ // than assuming every clipless run is an import.
+ imported: Boolean(run?.importedPackaging),
extractionFps: WALK_FPS,
maxSourceSeconds: MAX_SOURCE_SECONDS,
current: runCycleOf(run),
@@ -1192,6 +1238,7 @@ function sourceFrameResponse(runId, run, walkTarget, found) {
frames: [],
cycle: null,
selectedSourceIndices: [],
+ cycleProvenance: 'none',
editable: false,
lockReason: null,
...found,
@@ -1208,11 +1255,13 @@ function sourceFrameResponse(runId, run, walkTarget, found) {
* ~73 near-identical PNGs don't swamp the asset browser). This is the narrow
* read that surfaces them, and only them.
*
- * Two absence sentinels, kept distinct per the repo's absent-vs-empty rule:
- * - `available: false, reason: 'no-source-video'` no clip on disk to extract from
+ * Three absence sentinels, kept distinct per the repo's absent-vs-empty rule:
+ * - `available: false, reason: 'no-source-video'` no clip on disk at all
+ * - `available: false, reason: 'raw-frames-cleaned'` the clip IS here, but its
+ * extracted frames were pruned — recoverable, see `extract` below
* - `available: false, reason: 'run-not-packaged'` a synthesized redraw cycle
* (#2924), which never had an i2v clip or a run directory behind it
- * …and neither is a 500, nor an empty-looking success.
+ * …none of which is a 500, nor an empty-looking success.
*
* `editable`/`lockReason` answer a SEPARATE question from `available`: frames can
* be listed for a run whose clip has since been deleted (nothing to re-derive
@@ -1220,10 +1269,20 @@ function sourceFrameResponse(runId, run, walkTarget, found) {
* set. Collapsing the two would make the UI claim a re-derive is possible whenever
* it had something to show.
*
- * `raw/` absent but the clip present → re-extract on demand (`ffmpeg -y`, so
- * idempotent), inside the per-record write tail like every other walk write.
+ * **`extract` is opt-in, and this read is otherwise side-effect free.** The
+ * importer never copies `raw/` (its EXCLUDED_RUN_SEGMENTS skips it), so EVERY
+ * imported run reaches this with an empty raw directory — exactly the population
+ * the feature exists for. Extracting from the read would therefore mean opening
+ * the trimmer and clicking through eight directions silently spawns eight ffmpeg
+ * decodes (~96 PNGs each), each holding the per-record write tail while an
+ * approve or trim queues behind it, and lands >100MB of re-derivable
+ * intermediates that flow into backups — all for a panel the user may never
+ * expand. So the plain read reports `raw-frames-cleaned` and the caller asks for
+ * `extract: true` from an explicit user action (`POST …/source-frames/extract`).
+ * The extraction itself is idempotent (`ffmpeg -y`) and runs inside the
+ * per-record write tail like every other walk write.
*/
-export async function getWalkSourceFrames(recordId, runId) {
+export async function getWalkSourceFrames(recordId, runId, { extract = false } = {}) {
// All three reads are independent — the character gate, the run lookup, and
// the walk state (which serves the target, the lock gate, and the redraw
// fallback below) — so pay for them once, concurrently.
@@ -1259,7 +1318,7 @@ export async function getWalkSourceFrames(recordId, runId) {
: null,
]);
let names = listed;
- if (!names.length && clipRel) {
+ if (!names.length && clipRel && extract) {
await walkWriteTail(recordId, () => extractVideoFrames(
resolveSpriteAssetPath(recordId, clipRel),
resolveSpriteAssetPath(recordId, rawRel),
@@ -1277,12 +1336,11 @@ export async function getWalkSourceFrames(recordId, runId) {
});
return sourceFrameResponse(runId, run, walkTarget, {
available: frames.length > 0,
- reason: frames.length > 0 ? null : 'no-source-video',
+ // "No clip at all" and "clip present, frames pruned" are different states
+ // with different remedies — the second is one click from recoverable.
+ reason: frames.length > 0 ? null : (clipRel ? 'raw-frames-cleaned' : 'no-source-video'),
frames,
- cycle: cycleWindowOf(packaged),
- selectedSourceIndices: (Array.isArray(packaged?.frames) ? packaged.frames : [])
- .map((frame) => frame?.sourceFrameIndex)
- .filter((index) => Number.isInteger(index)),
+ ...manifestCycleProvenance(packaged, names),
editable: !lockReason,
lockReason,
});
diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.js
index 220ef56244..c67672aef2 100644
--- a/server/services/sprites/walk.test.js
+++ b/server/services/sprites/walk.test.js
@@ -1094,7 +1094,13 @@ describe('getWalkSourceFrames', () => {
// The provenance the packer records: the window it chose out of the usable
// span, plus which raw frames became packed columns.
- async function stampCycleProvenance(id, runId, direction = 'east') {
+ //
+ // `windowStart: 2` with a first packed frame at raw index 5 encodes a usable
+ // span starting at raw frame 3 (span.start = 2) — deliberately NOT the
+ // degenerate span.start = 0 case, where `windowStart + 1` and
+ // `frames[0].sourceFrameIndex` coincide and a translation that ignored the
+ // packed frames entirely would still look correct.
+ async function stampCycleProvenance(id, runId, direction = 'east', { sourcePaths = true } = {}) {
const manifestAbs = join(
TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', `${id}-walk-${direction}-manifest.json`,
);
@@ -1102,7 +1108,12 @@ describe('getWalkSourceFrames', () => {
manifest.cycleSelection = {
windowStart: 2, windowLength: 4, endpointSeamScore: 1.25, medianMotionScore: 3.5,
};
- manifest.frames = [{ sourceFrameIndex: 3 }, { sourceFrameIndex: 5 }];
+ manifest.frames = [5, 7].map((index) => ({
+ sourceFrameIndex: index,
+ ...(sourcePaths
+ ? { sourcePath: `runs/${runId}/generated/raw/${rawName(index)}` }
+ : {}),
+ }));
await writeFile(manifestAbs, JSON.stringify(manifest));
}
@@ -1110,7 +1121,7 @@ describe('getWalkSourceFrames', () => {
const id = await characterWithLockedAnchors(newId(), ['east']);
const { runId } = await makeCandidateRun(id, 'east');
const runAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId);
- const rawAbs = await seedRawFrames(runAbs, 6);
+ const rawAbs = await seedRawFrames(runAbs, 8);
// A non-frame file in the same directory must not be listed as a frame.
await writeFile(join(rawAbs, 'notes.txt'), 'scratch');
await writeFile(join(runAbs, 'generated', 'source-video.mp4'), 'CLIP');
@@ -1120,14 +1131,17 @@ describe('getWalkSourceFrames', () => {
expect(out.available).toBe(true);
expect(out.reason).toBeNull();
expect(out.extractionFps).toBe(12);
- expect(out.frames).toHaveLength(6);
+ expect(out.frames).toHaveLength(8);
expect(out.frames[0]).toEqual({ index: 1, path: `runs/${runId}/generated/raw/source-0001.png` });
- expect(out.selectedSourceIndices).toEqual([3, 5]);
- // `windowStart` counts from the usable span; the client renders raw 1-based
- // numbering, so the window is re-expressed there off the first packed frame.
+ expect(out.selectedSourceIndices).toEqual([5, 7]);
+ // `windowStart` counts from the usable span the packer kept (here starting at
+ // raw frame 3), while the client renders raw 1-based numbering — so the
+ // window is re-expressed off the FIRST PACKED frame, not off windowStart+1
+ // (which would be 3, four frames to the left of the frames it covers).
expect(out.cycle).toMatchObject({
- windowStart: 2, windowLength: 4, windowStartFrame: 3, windowEndFrame: 7,
+ windowStart: 2, windowLength: 4, windowStartFrame: 5, windowEndFrame: 9,
});
+ expect(out.cycleProvenance).toBe('verified');
// Older records predate run.frameCount/run.fps — the packed preview is the
// fallback the re-derive control seeds from.
expect(out.current).toEqual({ frameCount: 8, fps: 12 });
@@ -1138,13 +1152,31 @@ describe('getWalkSourceFrames', () => {
expect(extractVideoFrames).not.toHaveBeenCalled();
});
- it('re-extracts on demand when raw/ was cleaned but the clip is on disk', async () => {
+ // The read must stay side-effect free: the importer never copies raw/, so
+ // every imported run lands here — extracting from the read would spawn an
+ // ffmpeg decode per direction just because the trimmer rendered.
+ it('reports raw-frames-cleaned WITHOUT extracting when the clip is on disk', async () => {
const id = await characterWithLockedAnchors(newId(), ['east']);
const { runId } = await makeCandidateRun(id, 'east');
const generatedAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated');
await writeFile(join(generatedAbs, 'source-video.mp4'), 'CLIP');
const out = await getWalkSourceFrames(id, runId);
+ expect(extractVideoFrames).not.toHaveBeenCalled();
+ expect(out.available).toBe(false);
+ expect(out.reason).toBe('raw-frames-cleaned');
+ expect(out.frames).toEqual([]);
+ // …and the run is still re-derivable: the clip is what that depends on.
+ expect(out.editable).toBe(true);
+ });
+
+ it('re-extracts from the clip only when the caller asks for it', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const { runId } = await makeCandidateRun(id, 'east');
+ const generatedAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated');
+ await writeFile(join(generatedAbs, 'source-video.mp4'), 'CLIP');
+
+ const out = await getWalkSourceFrames(id, runId, { extract: true });
expect(extractVideoFrames).toHaveBeenCalledWith(
join(generatedAbs, 'source-video.mp4'),
join(generatedAbs, 'raw'),
@@ -1155,6 +1187,37 @@ describe('getWalkSourceFrames', () => {
// columns report empty rather than inventing a selection.
expect(out.cycle).toBeNull();
expect(out.selectedSourceIndices).toEqual([]);
+ expect(out.cycleProvenance).toBe('none');
+ });
+
+ // A manifest's frame indices were recorded against the extraction that packed
+ // the strip; frames re-extracted here may not be the same files. Marking the
+ // wrong frames as "the gait cycle" is worse than marking none.
+ it('withholds the cycle markers when the manifest\'s source frames are not on disk', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const { runId } = await makeCandidateRun(id, 'east');
+ const runAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId);
+ await seedRawFrames(runAbs, 4); // only 1–4 exist; the manifest names 5 and 7
+ await stampCycleProvenance(id, runId);
+
+ const out = await getWalkSourceFrames(id, runId);
+ expect(out.available).toBe(true);
+ expect(out.cycleProvenance).toBe('stale');
+ expect(out.cycle).toBeNull();
+ expect(out.selectedSourceIndices).toEqual([]);
+ });
+
+ // A minimal manifest that declares no sourcePath has nothing to verify — take
+ // it at its word rather than punishing it for being terse.
+ it('trusts a manifest that declares no source paths', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const { runId } = await makeCandidateRun(id, 'east');
+ await seedRawFrames(join(TEST_ROOT, 'sprites', id, 'runs', runId), 4);
+ await stampCycleProvenance(id, runId, 'east', { sourcePaths: false });
+
+ const out = await getWalkSourceFrames(id, runId);
+ expect(out.cycleProvenance).toBe('verified');
+ expect(out.selectedSourceIndices).toEqual([5, 7]);
});
it('reports no-source-video rather than an empty-looking success', async () => {
@@ -1177,12 +1240,13 @@ describe('getWalkSourceFrames', () => {
await unlockWalkSet(id);
const generatedAbs = join(TEST_ROOT, 'sprites', id, 'grok', runIds.east, 'generated');
- const out = await getWalkSourceFrames(id, runIds.east);
+ const out = await getWalkSourceFrames(id, runIds.east, { extract: true });
expect(extractVideoFrames).toHaveBeenCalledWith(
join(generatedAbs, 'source-video.mp4'),
join(generatedAbs, 'raw'),
);
expect(out.frames[0].path).toBe(`grok/${runIds.east}/generated/raw/source-0001.png`);
+ expect(out.imported).toBe(true);
expect(out.editable).toBe(true);
expect(out.lockReason).toBeNull();
});