Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2980]): show a walk run's source frames and re-derive its loop in the trimmer
[._.]/ Adam Eivyeb9d2c2f00d2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 06801eb38b..0e084344fc 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -25,6 +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-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.jsxindex 01459b9aa6..6aac70226f 100644--- a/client/src/components/sprites/LoopTrimmer.jsx+++ b/client/src/components/sprites/LoopTrimmer.jsx@@ -9,6 +9,7 @@ import { trimSpriteWalk } from '../../services/apiSprites.js';import { useAsyncAction } from '../../hooks/useAsyncAction.js';import { spriteAssetUrl, checkerboardStyle, PIXELATED } from './spriteAssets.js';import SpritePreview from './SpritePreview.jsx';+import WalkSourceFrames from './WalkSourceFrames.jsx';import {buildTrimmerSources, allColumns, invertColumns, phaseLabelFor, sanitizeTrimSlug,} from '../../lib/spriteTrimmer.js';@@ -117,6 +118,11 @@ 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 without a cache-buster the browser would keep painting the old+ // geometry — the loaded <img> wouldn't even be re-requested, since its src+ // never changed.+ 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.@@ -138,9 +144,10 @@ export default function LoopTrimmer({if (!source) return undefined;const image = new Image();image.onload = () => setImg(image);- image.src = spriteAssetUrl(recordId, source.stripPath);+ const url = spriteAssetUrl(recordId, source.stripPath);+ image.src = stripVersion ? `${url}?v=${stripVersion}` : url;return () => { image.onload = null; };- }, [source?.id, source?.stripPath, recordId]);+ }, [source?.id, source?.stripPath, recordId, stripVersion]);const cellW = img && frameCount > 0 ? img.naturalWidth / frameCount : 0;const cellH = img ? img.naturalHeight : 0;@@ -355,6 +362,17 @@ export default function LoopTrimmer({</div></div>+ {/* 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. */}+ {source?.kind === 'run' && source.runId && (+ <WalkSourceFrames+ recordId={recordId}+ runId={source.runId}+ onSaved={() => { setStripVersion((v) => v + 1); onSaved(); }}+ />+ )}+{/* Save + result */}<div className="flex flex-wrap items-center gap-3 border-t border-port-border pt-3"><buttondiff --git a/client/src/components/sprites/LoopTrimmer.test.jsx b/client/src/components/sprites/LoopTrimmer.test.jsxindex 966a23125a..2c9f4cc9bc 100644--- a/client/src/components/sprites/LoopTrimmer.test.jsx+++ b/client/src/components/sprites/LoopTrimmer.test.jsx@@ -1,5 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import {+ render, screen, fireEvent, waitFor, act,+} from '@testing-library/react';// The trim endpoint is the whole point of Save — mock it so the test asserts// the exact payload the UI sends without hitting the network. Canvas painting@@ -13,6 +15,28 @@ vi.mock('../../services/apiSprites.js', () => ({frameCount: 7,disabledFrameCount: 1,})),+ // The source-frames panel (#2980) mounts for every run source. Its own+ // behavior is covered in WalkSourceFrames.test.jsx; here it just has to+ // resolve so the trimmer's frame math stays the subject.+ getSpriteWalkSourceFrames: vi.fn(() => Promise.resolve({+ available: true,+ reason: null,+ runId: 'walk-east-0a1b2c3d',+ direction: 'east',+ extractionFps: 12,+ maxSourceSeconds: 8,+ frames: [{ index: 1, path: 'runs/walk-east-0a1b2c3d/generated/raw/source-0001.png' }],+ cycle: null,+ selectedSourceIndices: [],+ current: { frameCount: 8, fps: 12 },+ target: { frameCount: 8, fps: 12, source: 'derived', sourceLabel: 'from the first approved direction' },+ editable: true,+ lockReason: null,+ })),+ postprocessSpriteWalk: vi.fn(() => Promise.resolve({})),+ setSpriteWalkTarget: vi.fn(() => Promise.resolve({})),+ unlockSpriteWalk: vi.fn(() => Promise.resolve({})),+ reopenSpriteWalk: vi.fn(() => Promise.resolve({})),}));import LoopTrimmer from './LoopTrimmer';@@ -81,24 +105,32 @@ const renderTrimmer = (props = {}) => render(const enabledToggles = () => screen.queryAllByRole('button', { pressed: true });+// The source-frames panel (#2980) fetches on mount, so every render leaves a+// pending promise behind. Settle it inside act() before asserting, or its state+// update lands outside act — which this suite's setup turns into a failure.+const settle = () => act(async () => {});+describe('LoopTrimmer', () => {beforeEach(() => vi.clearAllMocks());- it('seeds every frame enabled and gates Save at ≥2 frames', () => {+ it('seeds every frame enabled and gates Save at ≥2 frames', async () => {renderTrimmer();+ await settle();expect(enabledToggles()).toHaveLength(8);expect(screen.getByRole('button', { name: /Save trim \(8\/8\)/ })).not.toBeDisabled();});- it('toggles a frame off and reflects the count in Save', () => {+ it('toggles a frame off and reflects the count in Save', async () => {renderTrimmer();+ await settle();fireEvent.click(enabledToggles()[0]);expect(enabledToggles()).toHaveLength(7);expect(screen.getByRole('button', { name: /Save trim \(7\/8\)/ })).toBeTruthy();});- it('Enable all and Invert rewrite the whole selection', () => {+ it('Enable all and Invert rewrite the whole selection', async () => {renderTrimmer();+ await settle();fireEvent.click(screen.getByRole('button', { name: /Invert/ }));expect(enabledToggles()).toHaveLength(0); // all-on inverted → all-offexpect(screen.getByRole('button', { name: /Save trim \(0\/8\)/ })).toBeDisabled();@@ -129,10 +161,11 @@ describe('LoopTrimmer', () => {expect(trimSpriteWalk.mock.calls[0][1]).toMatchObject({ slug: 'east-loop-v2' });});- it('offers Save for an imported/redraw run (strip outside grok/ is trimmable now)', () => {+ it('offers Save for an imported/redraw run (strip outside grok/ is trimmable now)', async () => {renderTrimmer({walk: { runs: [{ ...grokRun, stripPreview: { ...grokRun.stripPreview, stripPath: 'imagegen/v19/clean-alpha.png' } }] },});+ await settle();expect(screen.getByRole('button', { name: /Save trim/ })).not.toBeDisabled();});diff --git a/client/src/components/sprites/WalkSourceFrames.jsx b/client/src/components/sprites/WalkSourceFrames.jsxnew file mode 100644index 0000000000..e866d9897c--- /dev/null+++ b/client/src/components/sprites/WalkSourceFrames.jsx@@ -0,0 +1,329 @@+import { useCallback, useEffect, useMemo, useState } from 'react';+import {+ Film, ChevronDown, ChevronRight, Gauge, RefreshCw, RotateCcw, Unlock,+} from 'lucide-react';+import toast from '../ui/Toast';+import {+ getSpriteWalkSourceFrames, postprocessSpriteWalk, setSpriteWalkTarget,+ unlockSpriteWalk, reopenSpriteWalk,+} from '../../services/apiSprites.js';+import { useAsyncAction } from '../../hooks/useAsyncAction.js';+import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';+import { spriteAssetUrl, PIXELATED } from './spriteAssets.js';+import {+ WALK_FRAME_COUNT_OPTIONS, walkFpsOptionsFor,+} from '../../lib/spriteTrimmer.js';++// Source frames + re-derive (#2980), inside the Loop Trimmer.+//+// The trimmer can only DROP columns from an already-packed strip, so an 8-frame+// run can never become a 12-frame one there — the extra source frames were+// discarded at pack time. This panel closes that gap in the workspace where the+// user notices the problem: it shows every frame ffmpeg extracted from the run's+// clip (the ~73 raw PNGs `listSpriteAssets` deliberately hides), marks the cycle+// window the packer chose and which frames became packed columns, and re-derives+// the loop from that SAME on-disk clip at a new geometry — no new paid render.+//+// The re-derive's frame count / fps are the SET-level cycle target (#2985), not+// a free per-run range: every direction of one walk occupies the same atlas+// columns, so re-deriving one direction to a value the rest of the set doesn't+// share just recreates a ragged set from the other end (and the server would+// 409 WALK_TARGET_MISMATCH anyway). Changing them here retargets the whole set,+// which is stated inline.++// 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.',+ 'run-not-packaged': 'This direction came from a redraw cycle rather than a rendered clip, so there are no source frames behind it.',+};++// 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+// API will refuse.+const LOCK_COPY = {+ finalized: {+ text: 'The walk set is frozen. Unlocking re-opens every direction for revision; the rendered clips are kept, so re-approval is one click each.',+ action: 'Unlock set',+ prompt: 'Unlock the whole set?',+ icon: Unlock,+ },+ approved: {+ text: 'This direction is approved, and approved runs are immutable. Reopening un-approves just this direction — the rendered clip is kept, so re-approval is one click.',+ action: 'Reopen direction',+ prompt: 'Reopen this direction?',+ icon: RotateCcw,+ },+ 'no-source-video': {+ text: 'The source clip for this run is not on disk, so there is nothing to re-derive the loop from.',+ action: null,+ },+};++// One raw frame. Deliberately NOT checkerboarded, unlike the trimmer's packed+// cells: these are pre-key frames that still carry the solid chroma matte, so+// there is no alpha for a checkerboard to show through — painting one behind+// them would imply a transparency they don't have.+function RawFrame({ recordId, frame, inWindow, packed }) {+ const marks = [+ inWindow ? 'in the selected cycle window' : null,+ packed ? 'packed into the strip' : null,+ ].filter(Boolean);+ return (+ <div+ className={`rounded overflow-hidden border ${+ packed ? 'border-port-accent ring-1 ring-port-accent'+ : inWindow ? 'border-port-warning/70' : 'border-port-border'+ } ${inWindow || packed ? '' : 'opacity-60'}`}+ title={`source frame ${frame.index}${marks.length ? ` — ${marks.join(', ')}` : ''}`}+ >+ <img+ src={spriteAssetUrl(recordId, frame.path)}+ alt={`source frame ${frame.index}`}+ loading="lazy"+ className="w-full h-auto block"+ style={PIXELATED}+ />+ <span className="block text-center text-[10px] text-gray-500 py-0.5 tabular-nums">+ {frame.index}+ </span>+ </div>+ );+}++export default function WalkSourceFrames({ recordId, runId, onSaved = () => {} }) {+ const [data, setData] = useState(null);+ const [loadError, setLoadError] = useState(null);+ const [loading, setLoading] = useState(false);+ const [open, setOpen] = useState(false);+ const [confirming, setConfirming] = useState(false);+ // The re-derive geometry. Seeded from the resolved SET target on every load so+ // the control can never show a value the set isn't actually on.+ const [frameCount, setFrameCount] = useState(null);+ const [fps, setFps] = useState(null);+ // The target PUT is a separate request from the reprocess; while it is in+ // flight the reprocess would be gated against a value the server has not+ // persisted yet, so it holds its own flag rather than riding on the action's.+ const [targetSaving, setTargetSaving] = useState(false);++ const load = useCallback(async () => {+ setLoading(true);+ setLoadError(null);+ // The component owns its own error UI (the line below), so the request is+ // silent — otherwise the helper toasts and this renders the same failure.+ const next = await getSpriteWalkSourceFrames(recordId, runId, { silent: true })+ .catch((err) => { setLoadError(err?.message || 'Could not read this run\'s source frames'); return null; });+ setLoading(false);+ if (!next) return;+ setData(next);+ setFrameCount(next.target?.frameCount ?? next.current?.frameCount ?? null);+ setFps(next.target?.fps ?? next.current?.fps ?? null);+ }, [recordId, runId]);++ useEffect(() => {+ setData(null);+ setOpen(false);+ setConfirming(false);+ load();+ }, [load]);++ const selected = useMemo(+ () => new Set(data?.selectedSourceIndices || []),+ [data?.selectedSourceIndices],+ );++ const target = data?.target || null;+ const retargets = Boolean(target) && (frameCount !== target.frameCount || fps !== target.fps);++ const [redrive, redriving] = useAsyncAction(async () => {+ // A geometry the set isn't on must be pinned at the SET level first — the+ // reprocess is refused (409 WALK_TARGET_MISMATCH) against a target it+ // disagrees with, by design.+ if (retargets) {+ setTargetSaving(true);+ try {+ await setSpriteWalkTarget(recordId, { frameCount, fps }, { silent: true });+ } finally {+ setTargetSaving(false);+ }+ }+ await postprocessSpriteWalk(recordId, { runId, frameCount, fps }, { silent: true });+ toast.success(`Re-derived from the source clip · ${frameCount}f @ ${fps}fps`);+ onSaved();+ await load();+ }, { errorMessage: 'Could not re-derive this loop' });++ const [unlock, unlocking] = useAsyncAction(async () => {+ if (data.lockReason === 'finalized') {+ await unlockSpriteWalk(recordId, { silent: true });+ toast.success('Walk set unlocked — every direction is editable again');+ } else {+ await reopenSpriteWalk(recordId, { direction: data.direction }, { silent: true });+ toast.success(`${data.direction} reopened`);+ }+ onSaved();+ await load();+ }, { errorMessage: 'Could not unlock this direction' });++ const busy = loading || redriving || unlocking || targetSaving;+ const lock = data && !data.editable ? LOCK_COPY[data.lockReason] : null;+ const frames = data?.frames || [];++ const sectionCls = 'bg-port-bg border border-port-border rounded p-3 space-y-3';++ if (loadError) {+ return (+ <div className={sectionCls}>+ <p className="text-xs text-port-error">+ {loadError}{' '}+ <button onClick={load} className="text-port-accent hover:underline">Retry</button>+ </p>+ </div>+ );+ }++ if (!data) {+ return (+ <div className={sectionCls}>+ <p className="text-xs text-gray-500">Reading source frames…</p>+ </div>+ );+ }++ return (+ <div className={sectionCls}>+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h4 className="text-xs font-semibold text-white flex items-center gap-1.5">+ <Film className="w-3.5 h-3.5" /> Source frames+ </h4>+ {data.available ? (+ <button+ onClick={() => setOpen((prev) => !prev)}+ aria-expanded={open}+ className="flex items-center gap-1 text-[11px] text-gray-400 hover:text-white"+ >+ {open ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}+ {frames.length} source frames @ {data.extractionFps}fps+ {data.current?.frameCount ? ` · packed ${data.current.frameCount}` : ''}+ </button>+ ) : (+ <span className="text-[11px] text-gray-500">none on disk</span>+ )}+ </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>+ )}++ {data.available && open && (+ <>+ <p className="text-[11px] text-gray-500">+ Extracted from this run's clip at {data.extractionFps}fps+ {data.maxSourceSeconds ? ` (first ${data.maxSourceSeconds}s)` : ''}.+ {data.cycle?.windowStartFrame != null && (+ <>+ {' '}Frames {data.cycle.windowStartFrame}–{data.cycle.windowEndFrame} 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's columns.+ </>+ )}+ </p>+ <div className="grid grid-cols-4 sm:grid-cols-8 lg:grid-cols-12 gap-1.5">+ {frames.map((frame) => (+ <RawFrame+ key={frame.index}+ recordId={recordId}+ frame={frame}+ inWindow={data.cycle?.windowStartFrame != null+ && frame.index >= data.cycle.windowStartFrame+ && frame.index < data.cycle.windowEndFrame}+ packed={selected.has(frame.index)}+ />+ ))}+ </div>+ </>+ )}++ {/* Re-derive. Present whenever the run has a clip behind it — the source+ grid above is context, not a precondition. */}+ <div className="border-t border-port-border pt-3 space-y-2">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">+ <label className="flex items-center gap-1.5 text-xs text-gray-400" htmlFor="trimmer-derive-frames">+ Re-derive at+ <select+ id="trimmer-derive-frames"+ value={frameCount ?? ''}+ disabled={busy || !data.editable || Boolean(target?.frameCountLocked)}+ onChange={(e) => setFrameCount(Number(e.target.value))}+ title="Frames in the walk cycle — shared by all 8 directions, because the atlas is a rectangular grid"+ className="bg-port-card border border-port-border rounded px-2 py-1 text-sm text-white disabled:opacity-60"+ >+ {WALK_FRAME_COUNT_OPTIONS.map((n) => <option key={n} value={n}>{n} frames</option>)}+ </select>+ </label>+ <label className="flex items-center gap-1.5 text-xs text-gray-400" htmlFor="trimmer-derive-fps">+ <span className="flex items-center gap-1"><Gauge className="w-3 h-3" /> Preview speed</span>+ <select+ id="trimmer-derive-fps"+ value={fps ?? ''}+ disabled={busy || !data.editable || Boolean(target?.fpsLocked)}+ onChange={(e) => setFps(Number(e.target.value))}+ title="Preview/authoring speed — the consuming app decides real in-game playback"+ className="bg-port-card border border-port-border rounded px-2 py-1 text-sm text-white disabled:opacity-60"+ >+ {walkFpsOptionsFor(fps).map((n) => <option key={n} value={n}>{n} fps</option>)}+ </select>+ </label>+ <button+ onClick={redrive}+ disabled={busy || !data.editable || !frameCount || !fps}+ title={data.editable+ ? 'Rebuild this loop from the clip already on disk — no new render'+ : 'This run is locked — see below'}+ className="flex items-center gap-1.5 px-3 py-1.5 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white rounded text-xs"+ >+ {redriving || targetSaving+ ? <><RefreshCw className="w-3.5 h-3.5 animate-spin" /> Re-deriving…</>+ : <><RefreshCw className="w-3.5 h-3.5" /> Re-derive from clip</>}+ </button>+ </div>+ <p className="text-[11px] text-gray-500">+ {retargets+ ? `Changing the cycle re-targets the whole set to ${frameCount}f @ ${fps}fps — the other directions will need re-deriving too.`+ : `The set targets ${target?.frameCount}f @ ${target?.fps}fps (${target?.sourceLabel || target?.source || 'default'}). Re-deriving repacks this run from its clip — no AI call, no new render.`}+ </p>++ {lock && (+ <div className="space-y-1.5">+ <p className="text-[11px] text-port-warning leading-relaxed">{lock.text}</p>+ {lock.action && (confirming ? (+ <ConfirmButtonPair+ prompt={lock.prompt}+ confirmText={lock.action}+ confirmIcon={lock.icon}+ tone="warning"+ busy={unlocking}+ busyText="Working…"+ ariaLabel={`Confirm ${lock.action}`}+ onConfirm={() => { setConfirming(false); unlock(); }}+ onCancel={() => setConfirming(false)}+ />+ ) : (+ <button+ onClick={() => setConfirming(true)}+ 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"+ >+ <lock.icon className="w-3.5 h-3.5" /> {lock.action}+ </button>+ ))}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/components/sprites/WalkSourceFrames.test.jsx b/client/src/components/sprites/WalkSourceFrames.test.jsxnew file mode 100644index 0000000000..10ffd27c6f--- /dev/null+++ b/client/src/components/sprites/WalkSourceFrames.test.jsx@@ -0,0 +1,190 @@+import {+ describe, it, expect, vi, beforeEach,+} from 'vitest';+import {+ render, screen, fireEvent, act,+} from '@testing-library/react';++// Every call this panel makes is mocked: the point of the suite is WHICH request+// the re-derive fires and with what payload — a per-run geometry resolved from+// the SET target (#2985), never a page-level form value.+vi.mock('../../services/apiSprites.js', () => ({+ getSpriteWalkSourceFrames: vi.fn(),+ postprocessSpriteWalk: vi.fn(() => Promise.resolve({})),+ setSpriteWalkTarget: vi.fn(() => Promise.resolve({})),+ unlockSpriteWalk: vi.fn(() => Promise.resolve({})),+ reopenSpriteWalk: vi.fn(() => Promise.resolve({})),+}));++import WalkSourceFrames from './WalkSourceFrames';+import {+ getSpriteWalkSourceFrames, postprocessSpriteWalk, setSpriteWalkTarget,+ unlockSpriteWalk, reopenSpriteWalk,+} from '../../services/apiSprites.js';++const RUN_ID = 'walk-east-0a1b2c3d';++// 8 raw frames; the packer selected a 4-long window starting at raw frame 3 and+// kept frames 3 and 5 as packed columns.+const payload = (overrides = {}) => ({+ available: true,+ reason: null,+ runId: RUN_ID,+ direction: 'east',+ extractionFps: 12,+ maxSourceSeconds: 8,+ frames: Array.from({ length: 8 }, (_, i) => ({+ index: i + 1,+ path: `runs/${RUN_ID}/generated/raw/source-000${i + 1}.png`,+ })),+ cycle: {+ windowStart: 1, windowLength: 4, windowStartFrame: 3, windowEndFrame: 7,+ },+ selectedSourceIndices: [3, 5],+ current: { frameCount: 8, fps: 12 },+ target: {+ frameCount: 8, fps: 12, source: 'derived', sourceLabel: 'from the first approved direction',+ },+ editable: true,+ lockReason: null,+ ...overrides,+});++const onSaved = vi.fn();+const renderPanel = async (data = payload()) => {+ getSpriteWalkSourceFrames.mockResolvedValue(data);+ const result = render(+ <WalkSourceFrames recordId="example-walker" runId={RUN_ID} onSaved={onSaved} />,+ );+ // Settle the mount fetch inside act() — the suite fails on act warnings.+ await act(async () => {});+ return result;+};++const expandGrid = () => fireEvent.click(screen.getByRole('button', { name: /source frames @/ }));+// Matches both resting ("Re-derive from clip") and in-flight ("Re-deriving…").+const deriveButton = () => screen.getByRole('button', { name: /Re-deriv(e|ing)/ });++describe('WalkSourceFrames', () => {+ beforeEach(() => vi.clearAllMocks());++ it('summarizes the extraction and expands to a grid of every raw frame', async () => {+ const { container } = await renderPanel();+ // The headroom above the packed count is the whole reason to show this.+ expect(screen.getByRole('button', { name: /8 source frames @ 12fps · packed 8/ })).toBeTruthy();+ expect(container.querySelectorAll('img')).toHaveLength(0); // collapsed by default++ expandGrid();+ const images = [...container.querySelectorAll('img')];+ expect(images).toHaveLength(8);+ expect(images[0].getAttribute('src'))+ .toBe(`/data/sprites/example-walker/runs/${RUN_ID}/generated/raw/source-0001.png`);+ });++ it('marks the selected cycle window and the frames that became packed columns', async () => {+ await renderPanel();+ expandGrid();+ const cellFor = (index) => screen.getByTitle(new RegExp(`^source frame ${index}\\b`));++ // Frame 1 is outside the window the packer chose.+ expect(cellFor(1).getAttribute('title')).toBe('source frame 1');+ // 4 is inside the window (3..6) but was not packed.+ expect(cellFor(4).getAttribute('title')).toBe('source frame 4 — in the selected cycle window');+ // 3 and 5 became strip columns.+ 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.+ expect(cellFor(7).getAttribute('title')).toBe('source frame 7');+ });++ it('re-derives the SELECTED run at the set target without retargeting it', async () => {+ await renderPanel();+ fireEvent.click(deriveButton());+ await act(async () => {});++ expect(setSpriteWalkTarget).not.toHaveBeenCalled();+ expect(postprocessSpriteWalk).toHaveBeenCalledWith(+ 'example-walker',+ { runId: RUN_ID, frameCount: 8, fps: 12 },+ { silent: true },+ );+ // The trimmer reloads its strip + toggles against the new geometry.+ expect(onSaved).toHaveBeenCalled();+ });++ it('pins the set target first when the user picks a different cycle', async () => {+ await renderPanel();+ fireEvent.change(screen.getByLabelText(/Re-derive at/), { target: { value: '12' } });+ // The retarget is stated before it happens — one direction cannot diverge.+ expect(screen.getByText(/re-targets the whole set to 12f @ 12fps/)).toBeTruthy();++ fireEvent.click(deriveButton());+ await act(async () => {});+ expect(setSpriteWalkTarget).toHaveBeenCalledWith(+ 'example-walker', { frameCount: 12, fps: 12 }, { silent: true },+ );+ expect(postprocessSpriteWalk).toHaveBeenCalledWith(+ 'example-walker',+ { runId: RUN_ID, frameCount: 12, fps: 12 },+ { silent: true },+ );+ });++ it('disables the controls while the re-derive is in flight', async () => {+ let release;+ postprocessSpriteWalk.mockReturnValue(new Promise((resolve) => { release = resolve; }));+ await renderPanel();++ fireEvent.click(deriveButton());+ expect(deriveButton()).toBeDisabled();+ expect(screen.getByLabelText(/Re-derive at/)).toBeDisabled();+ expect(screen.getByLabelText(/Preview speed/)).toBeDisabled();++ await act(async () => { release({}); });+ expect(deriveButton()).not.toBeDisabled();+ });++ 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',+ }));+ 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();+ });++ it('offers reopen for an approved direction and posts it on confirm', async () => {+ await renderPanel(payload({ editable: false, lockReason: 'approved' }));+ expect(deriveButton()).toBeDisabled();++ fireEvent.click(screen.getByRole('button', { name: /Reopen direction/ }));+ fireEvent.click(screen.getByRole('button', { name: /^Reopen direction$/ }));+ await act(async () => {});+ expect(reopenSpriteWalk).toHaveBeenCalledWith('example-walker', { direction: 'east' }, { silent: true });+ expect(unlockSpriteWalk).not.toHaveBeenCalled();+ });++ it('offers the set unlock for a finalized set', async () => {+ await renderPanel(payload({ editable: false, lockReason: 'finalized' }));+ fireEvent.click(screen.getByRole('button', { name: /Unlock set/ }));+ fireEvent.click(screen.getByRole('button', { name: /^Unlock set$/ }));+ await act(async () => {});+ expect(unlockSpriteWalk).toHaveBeenCalledWith('example-walker', { silent: true });+ expect(reopenSpriteWalk).not.toHaveBeenCalled();+ });++ it('reports a failed read with a retry instead of a silent empty panel', async () => {+ getSpriteWalkSourceFrames.mockRejectedValueOnce(new Error('boom'));+ render(<WalkSourceFrames recordId="example-walker" runId={RUN_ID} />);+ await act(async () => {});+ expect(screen.getByText(/boom/)).toBeTruthy();++ getSpriteWalkSourceFrames.mockResolvedValueOnce(payload());+ fireEvent.click(screen.getByRole('button', { name: /Retry/ }));+ await act(async () => {});+ expect(screen.getByRole('button', { name: /8 source frames @ 12fps/ })).toBeTruthy();+ });+});diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxindex 8cc954e639..843d7f5898 100644--- a/client/src/components/sprites/WalkWorkflow.jsx+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -11,7 +11,10 @@ import {import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';import { useAsyncAction } from '../../hooks/useAsyncAction.js';import { spriteAssetUrl, checkerboardStyle, PIXELATED } from './spriteAssets.js';-import { WALK_PHASES } from '../../lib/spriteTrimmer.js';+import {+ WALK_PHASES, WALK_DEFAULT_FRAME_COUNT, WALK_DEFAULT_FPS,+ WALK_FRAME_COUNT_OPTIONS as FRAME_COUNT_OPTIONS, walkFpsOptionsFor as fpsOptionsFor,+} from '../../lib/spriteTrimmer.js';// Walk workflow (issue #2897): one grok image_to_video clip per locked// directional anchor, deterministic server-side packaging into the 8-phase@@ -34,39 +37,10 @@ const LOOP_KEYFRAMES = '@keyframes sprite-walk-loop { to { background-position-xexport const WALK_DURATIONS = [6, 10];export const WALK_DEFAULT_DURATION = 6;-// Deterministic-postprocess authoring knobs (mirror walkPostprocess.js-// WALK_DEFAULT_*/WALK_MIN/MAX_*). Frame count = how many frames the packed cycle-// holds (more = smoother); fps = preview playback speed (lower = slower, more-// deliberate). Cycle duration = frameCount / fps seconds. Defaults pack a-// fuller, slower cycle (12 frames @ 10fps = 1.2s) so a walk reads as a walk.-//-// Both are pinned at the SET level (#2985), not per render: a walk cycle is N-// contiguous atlas columns × 8 direction rows, so every direction must agree or-// the atlas cannot compile. The server resolves the target and refuses a-// disagreeing render; these constants only seed the dropdown option lists.-export const WALK_DEFAULT_FRAME_COUNT = 12;-export const WALK_DEFAULT_FPS = 10;-export const WALK_FRAME_COUNT_RANGE = { min: 6, max: 16 };-export const WALK_FPS_RANGE = { min: 4, max: 24 };--// Inclusive integer sequence [min..max] by step. Both dropdown option lists are-// derived from module-level constants, so build them once at load rather than-// on every render.-const seq = (min, max, step) => {- const out = [];- for (let v = min; v <= max; v += step) out.push(v);- return out;-};-const FRAME_COUNT_OPTIONS = seq(WALK_FRAME_COUNT_RANGE.min, WALK_FRAME_COUNT_RANGE.max, 1);-// The speed picker offers even steps to keep the list short, but the server-// accepts ANY integer in range — an imported set (or a direct API call) can pin-// an odd fps like 15. A <select> whose value matches no <option> silently-// displays the FIRST option, so the control would claim "4 fps" while the set is-// really at 15. Splice the current value in so the control never lies.-const FPS_OPTIONS = seq(WALK_FPS_RANGE.min, WALK_FPS_RANGE.max, 2);-const fpsOptionsFor = (fps) => (FPS_OPTIONS.includes(fps) || !Number.isFinite(fps)- ? FPS_OPTIONS- : [...FPS_OPTIONS, fps].sort((a, b) => a - b));+// The deterministic-postprocess authoring knobs (frame count + preview fps) and+// their option lists moved to lib/spriteTrimmer.js (#2980) — the Loop Trimmer's+// re-derive control offers the same set-level target, and two copies of the+// bounds would be exactly the drift #2985 exists to prevent./*** Strip geometry for a preview/trim UI, defaulting to the native 8-phasediff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex f508fc4850..16e697ad4e 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -139,7 +139,7 @@ grep -i "what you want to do" client/src/lib/README.md| `spriteCollectionActions.js` | Gating for the Sprite Manager asset collection's inline actions (#2931). `buildCollectionActions({ detail, walkPending, referencePending, generateWalk, generateAnchor, onRequestTrim })` → `{ regenerateFor(asset), trimFor(asset) }`, each returning `null` for an asset it can't act on. Regenerate mirrors the authoritative workflow surfaces exactly — a walk direction is regenerable only when its anchor is locked, the direction isn't approved, the walk set isn't finalized and no render is in flight; a reference anchor only while it's an unlocked candidate (`south`/main is excluded, since it needs a design prompt or upload). Trim is offered only for a run that actually packed a strip (the trim endpoint 409s otherwise). Pure — takes callbacks, performs no I/O. Consumes the facets from `spriteFacets.js`. || `spriteFacets.js` | Client-side facet classifier for the Sprite Manager's asset collection (#2931), mirroring the source pipeline's `classify_asset()`. `classifySpriteAsset(path)` decodes a record-relative asset path into `{ family, status, role, direction, runId }` — `status ∈ runtime/approved/candidate/superseded/rejected/source`, `role ∈ reference/strip/animation/frame/atlas/evidence/sprite/manifest` — and is total (an unknown path degrades to `sprite`/`source` rather than throwing). `classifySpriteAssets(assets)` adds the one facet only knowable across a listing: an approved asset below the highest `-vN` of its stem becomes `superseded`. `groupSpriteAssetsByRole(assets)` returns render-ready `{ role, label, assets }` sections in `SPRITE_ASSET_ROLES` order — it does NOT render a `manifest` group: each runtime atlas's sidecar manifest is folded onto its atlas row as `row.manifest`, and other behind-the-scenes JSON is omitted. `runtimeVersionDir(path)` / `isRuntimeVersionPath(path)` / `isRuntimeSidecarManifest(path)` expose the `runtime/vN` grammar (the sidecar-pairing key and the "is this a build manifest" predicate) so callers like `AssetInspector` reuse one definition instead of re-regexing. Also exports `SPRITE_DIRECTIONS` (mirror of `server/services/sprites/prompts.js`) — the `direction`/`runId` facets are what drive the collection's Regenerate and Edit-in-Loop-Trimmer actions. Pure — no React, no I/O. || `spriteRecordGroups.js` | Grouping + search for the Sprite Manager sidebar's record picker (#2932). `groupSpriteRecords(records)` → ordered `[{ key, label, records }]` under **Characters / Places / Objects** (`props` folded into Objects alongside `object`, no migration). `filterSpriteRecords(records, query, limit=8)` is the autocomplete filter — multi-term (AND) substring over `name`/`id`/`kind`, capped at `limit`. `groupKeyForKind(kind)` maps a kind to its group key (unknown → `objects`). `SPRITE_RECORD_GROUPS` / `NEW_SPRITE_KINDS` back the browse disclosure and the create-panel kind selector. Pure — no React, no I/O; the page owns the per-group icons. |-| `spriteTrimmer.js` | Pure geometry + source-list math behind the Sprite Manager's Loop Trimmer workspace (#2933). `buildTrimmerSources(walk, assets)` → the ordered animation sources the trimmer can load (every preview-strip run first, then saved trims read from the asset listing), each `{ id, kind: 'run'\|'trim', runId, direction, label, stripPath, frameCount, fps, trimmable }` — every packed-strip run is `trimmable` (layout-agnostic), while saved trims are preview-only, mirroring `spriteCollectionActions`' gate. `stripFrameGeometry(stripPreview)` → `{ frameCount, fps, cellWidth, cellHeight }` with the native 8-phase / 12fps fallback; `phaseLabelFor(index, frameCount)` names the 8 walk phases (bare `frame N` for any other length); `sanitizeTrimSlug(name)` → the server's `[a-z0-9-]+` output slug; `allColumns(n)` / `invertColumns(n, enabled)` for the frame-toggle set. `WALK_PHASES` is the shared phase-label constant (WalkWorkflow imports it here). Pure — no React, no canvas, no I/O. |+| `spriteTrimmer.js` | Pure geometry + source-list math behind the Sprite Manager's Loop Trimmer workspace (#2933). `buildTrimmerSources(walk, assets)` → the ordered animation sources the trimmer can load (every preview-strip run first, then saved trims read from the asset listing), each `{ id, kind: 'run'\|'trim', runId, direction, label, stripPath, frameCount, fps, trimmable }` — every packed-strip run is `trimmable` (layout-agnostic), while saved trims are preview-only, mirroring `spriteCollectionActions`' gate. `stripFrameGeometry(stripPreview)` → `{ frameCount, fps, cellWidth, cellHeight }` with the native 8-phase / 12fps fallback; `phaseLabelFor(index, frameCount)` names the 8 walk phases (bare `frame N` for any other length); `sanitizeTrimSlug(name)` → the server's `[a-z0-9-]+` output slug; `allColumns(n)` / `invertColumns(n, enabled)` for the frame-toggle set. `WALK_PHASES` is the shared phase-label constant (WalkWorkflow imports it here). Also holds the walk-cycle authoring bounds mirrored from `walkBounds.js` — `WALK_DEFAULT_FRAME_COUNT` / `WALK_DEFAULT_FPS`, `WALK_FRAME_COUNT_RANGE` / `WALK_FPS_RANGE`, the `WALK_FRAME_COUNT_OPTIONS` list and `walkFpsOptionsFor(fps)` (splices a current odd fps into the even-step list so the `<select>` never lies) — shared by the walk workflow's set-level cycle target and the trimmer's re-derive control (#2980). Pure — no React, no canvas, no I/O. || `tribe.js` | Pure Tribe domain helpers shared by the Tribe page and its `TribeCircleMap` visualization: `RINGS` (support→core→tribe→village Dunbar rings + the uncapped `external` "outside the tribe" classification — caps, cadence defaults, Tailwind tones + `hex`), `TRIBE_RINGS` (the four inner rings the care queue/capacity/overdue counts operate over, excluding `external`), `ENERGY` (energy tiers + `hex`), `STATUS_HEX` (cadence-status → SVG stroke color), `contactStatus(contact)` (presentation wrapper over the shared `cadenceStatus` — attaches label/tone to the missing/overdue/soon/steady/`external` state) / `daysBetween(date)` (alias of the shared `daysSinceDate`), `ringFor` / `energyFor` lookups, `tagsToArray` / `tagsToInput`, and `initialsFor(name)` (node glyph). Ring `cadenceDays` mirror `DEFAULT_RING_CADENCE` in `server/services/tribe.js`; the cadence STATE MACHINE lives in `tribeCadence.js`. || `tribeCadence.js` | Mirror of `server/lib/tribeCadence.js` — the single authoritative Tribe care-cadence rules shared by the page, the Care dashboard widget, and the proactive alert: `cadenceStatus(entity)` → `{ state, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS`, `SOON_WINDOW_DAYS`. A cross-boundary contract test asserts it never drifts from the server copy. || `streakGlyph.js` | `streakGlyph(streak)` — the single POST streak emoji (✨ / ⚡ / 🔥 by day count) shared by the POST launcher, Morse trainer, daily widget, and dashboard streak widget. |diff --git a/client/src/lib/spriteTrimmer.js b/client/src/lib/spriteTrimmer.jsindex c237981974..022d8ab285 100644--- a/client/src/lib/spriteTrimmer.js+++ b/client/src/lib/spriteTrimmer.js@@ -21,6 +21,39 @@ export const WALK_PHASES = [const DEFAULT_FPS = 12;+// Walk-cycle authoring bounds (mirror server/services/sprites/walkBounds.js).+// Frame count = how many frames the packed cycle holds (more = smoother); fps =+// preview playback speed. Cycle duration = frameCount / fps seconds.+//+// Both are pinned at the SET level (#2985), never per render: a walk cycle is N+// contiguous atlas columns × 8 direction rows, so every direction must agree or+// the atlas cannot compile. These constants only seed the option lists — the+// server resolves the target and refuses a disagreeing render. They live here+// (not in a component) because two surfaces now offer the same control: the+// walk workflow's set-level picker and the Loop Trimmer's re-derive (#2980).+export const WALK_DEFAULT_FRAME_COUNT = 12;+export const WALK_DEFAULT_FPS = 10;+export const WALK_FRAME_COUNT_RANGE = { min: 6, max: 16 };+export const WALK_FPS_RANGE = { min: 4, max: 24 };++// Inclusive integer sequence [min..max] by step. Both option lists derive from+// module constants, so build them once at load rather than on every render.+const seq = (min, max, step) => {+ const out = [];+ for (let v = min; v <= max; v += step) out.push(v);+ return out;+};+export const WALK_FRAME_COUNT_OPTIONS = seq(WALK_FRAME_COUNT_RANGE.min, WALK_FRAME_COUNT_RANGE.max, 1);+// The speed picker offers even steps to keep the list short, but the server+// accepts ANY integer in range — an imported set (or a direct API call) can pin+// an odd fps like 15. A <select> whose value matches no <option> silently+// displays the FIRST option, so the control would claim "4 fps" while the set is+// really at 15. Splice the current value in so the control never lies.+const WALK_FPS_OPTIONS = seq(WALK_FPS_RANGE.min, WALK_FPS_RANGE.max, 2);+export const walkFpsOptionsFor = (fps) => (WALK_FPS_OPTIONS.includes(fps) || !Number.isFinite(fps)+ ? WALK_FPS_OPTIONS+ : [...WALK_FPS_OPTIONS, fps].sort((a, b) => a - b));+/*** Frame geometry for a packed strip, defaulting to the native 8-phase packaging* when a run predates (or omits) the richer stripPreview fields. `cellWidth` /diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 856d7c7f9f..5fa75b95a5 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -96,7 +96,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiCreativeDirector.js` | Creative Director (video production). || `apiCreativeCommission.js` | Creative Commissions (Autonomous Creation Engine — standing recurring briefs). || `apiMusicVideo.js` | Music Video projects + scene board + audio analysis. |-| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), walk workflow: generate/approve/trim/postprocess (#2897). |+| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), walk workflow: generate/approve/trim/postprocess (#2897), per-run source-frame listing for the Loop Trimmer's re-derive (#2980). || `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, and deletion. || `apiImageTo3d.js` | Image-to-3D (`/media/3d`): selectable targets (TRELLIS.2) with host availability/install status, and per-image model records — create/list/get/generate/delete + GLB asset URL. || `apiPipeline.js` | Pipeline (issues + stages + canon). |diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.jsindex 1893f73224..281f980e53 100644--- a/client/src/services/apiSprites.js+++ b/client/src/services/apiSprites.js@@ -128,6 +128,17 @@ export const reopenSpriteWalk = (id, body, options = {}) => request(`/sprites/${method: 'POST', body: JSON.stringify(body), ...options,});+// 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.+export const getSpriteWalkSourceFrames = (id, runId, options = {}) => request(+ `/sprites/${encodeURIComponent(id)}/walk/runs/${encodeURIComponent(runId)}/source-frames`,+ 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/lib/validation.js b/server/lib/validation.jsindex fccd5027ab..bbd7d5530e 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1115,6 +1115,18 @@ const spriteWalkDirectionSchema = z.enum(SPRITE_DIRECTIONS);const spriteWalkRunIdSchema = z.string().regex(/^walk-[a-z-]+-[0-9a-f]{8}$/);+// Any run the walk state can resolve, not just native `walk-<dir>-<hex>`+// generations: an imported run's id is its source-named directory slug, and a+// redraw run's id is a record-relative manifest path. The services that accept+// this resolve the id against server-owned walk state and only ever dereference+// paths the state itself recorded (through resolveSpriteAssetPath), so this+// bounds shape/length only — safe charset, no traversal. (Approve stays strict:+// it only ever freezes a natively-generated run into the set.)+const spriteResolvableRunIdSchema = z.string().min(1).max(1024)+ .refine((v) => /^[A-Za-z0-9._/-]+$/.test(v) && !v.split('/').includes('..'), {+ message: 'invalid run id',+ });+// Walk-cycle authoring bounds — imported from the sharp-free walkBounds leaf so// the request schema and the server-side clamp share ONE range definition (a// bounds change can't silently diverge). walkBounds pulls in no native deps.@@ -1157,7 +1169,15 @@ export const spriteWalkReopenSchema = z.object({});export const spriteWalkPostprocessSchema = z.object({- runId: spriteWalkRunIdSchema,+ // Any run the walk state can resolve, not just native `walk-<dir>-<hex>` ids:+ // since #2993 the reprocess is layout-aware and re-derives an IMPORTED run+ // (whose id is its source-named directory, e.g. `run-3`) in the directory it+ // was imported into — which the strict native shape rejected at the door, so+ // the one path back onto the set's target was unreachable for exactly the+ // population that needs it. Bounds shape/charset only, same argument as the+ // trim endpoint: the service resolves the id against server-owned walk state+ // and dereferences only paths that state recorded.+ runId: spriteResolvableRunIdSchema,// Reprocess the on-disk clip without regenerating. Omitted fields adopt the// set's pinned cycle target (#2985) — NOT the run's stored values, since a// reprocess is how a drifted direction is brought back onto the target. A@@ -1167,23 +1187,19 @@ export const spriteWalkPostprocessSchema = z.object({fps: spriteWalkFpsSchema.optional(),});-// The trimmer targets ANY resolvable run, not just native `walk-<dir>-<hex>`-// generations: an imported run's id is its directory slug, and a redraw run's-// id is a record-relative manifest path. The trim service resolves the id-// against server-owned walk state and only ever dereferences paths the state-// itself recorded (through resolveSpriteAssetPath), so this bounds shape/length-// only — safe charset, no traversal. (Approve/postprocess stay strict because-// they only ever act on native runs.)-const spriteTrimRunIdSchema = z.string().min(1).max(1024)- .refine((v) => /^[A-Za-z0-9._/-]+$/.test(v) && !v.split('/').includes('..'), {- message: 'invalid run id',- });+// The raw ffmpeg frames behind one run (#2980) — a read-only enumeration of the+// directory `listSpriteAssets` deliberately skips. Path params, so the run id+// arrives as a URL segment; the trimmer can select an imported or redraw run, so+// it takes the resolvable shape rather than the native one.+export const spriteWalkSourceFramesParamsSchema = z.object({+ runId: spriteResolvableRunIdSchema,+});// 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({- runId: spriteTrimRunIdSchema,+ runId: spriteResolvableRunIdSchema,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(),diff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex a43438c3c9..c589a42a72 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -25,6 +25,7 @@ import {spriteWalkReopenSchema,spriteWalkPostprocessSchema,spriteWalkTargetSchema,+ spriteWalkSourceFramesParamsSchema,spriteWalkTrimSchema,spritePublishBindingSchema,spriteAtlasCompileSchema,@@ -44,7 +45,7 @@ import {import { resolveSpriteAssetPrompt } from '../services/sprites/assetPrompt.js';import {getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,- reopenWalkDirection, setWalkTarget,+ reopenWalkDirection, setWalkTarget, getWalkSourceFrames,} from '../services/sprites/walk.js';import { saveLoopTrim } from '../services/sprites/walkTrims.js';import { compileAtlas, getAtlasState } from '../services/sprites/atlas.js';@@ -200,6 +201,16 @@ router.post('/:id/walk/postprocess', asyncHandler(async (req, res) => {res.json(await rerunWalkPostprocess(req.params.id, body));}));+// 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.+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));+}));+// 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.jsindex 035c41d239..c3e2bbc459 100644--- a/server/routes/sprites.test.js+++ b/server/routes/sprites.test.js@@ -40,6 +40,16 @@ vi.mock('../services/sprites/walk.js', () => ({walkSet: null,walkTarget: { track: 'walk', frameCount: 14, fps: 8, source: 'set' },})),+ getWalkSourceFrames: vi.fn(async () => ({+ available: true,+ reason: null,+ frames: [{ index: 1, path: 'runs/walk-east-0a1b2c3d/generated/raw/source-0001.png' }],+ cycle: { windowStart: 2, windowLength: 12, windowStartFrame: 5, windowEndFrame: 17 },+ selectedSourceIndices: [5, 7],+ current: { frameCount: 8, fps: 12 },+ editable: true,+ lockReason: null,+ })),}));vi.mock('../services/sprites/walkTrims.js', () => ({@@ -473,6 +483,38 @@ describe('sprites routes', () => {.send({ runId: 'walk-east-0a1b2c3d', frameCount: 3 })).status).toBe(400);});+ it('GET /:id/walk/runs/:runId/source-frames delegates with the decoded run id', async () => {+ const r = await request(app).get('/api/sprites/pioneer/walk/runs/walk-east-0a1b2c3d/source-frames');+ expect(r.status).toBe(200);+ expect(r.body.frames).toHaveLength(1);+ expect(walk.getWalkSourceFrames).toHaveBeenCalledWith('pioneer', 'walk-east-0a1b2c3d');++ // An imported run's id is its source-named directory, not the native+ // `walk-<dir>-<hex>` shape — the whole population this endpoint exists for.+ walk.getWalkSourceFrames.mockClear();+ expect((await request(app).get('/api/sprites/pioneer/walk/runs/run-3/source-frames')).status).toBe(200);+ expect(walk.getWalkSourceFrames).toHaveBeenCalledWith('pioneer', 'run-3');++ // Traversal is refused before the service is reached (%2E%2E%2F = `../`).+ walk.getWalkSourceFrames.mockClear();+ expect((await request(app).get('/api/sprites/pioneer/walk/runs/%2E%2E%2Fescape/source-frames')).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.+ it('POST /:id/walk/postprocess accepts an imported run id but still refuses traversal', async () => {+ walk.rerunWalkPostprocess.mockClear();+ const r = await request(app).post('/api/sprites/pioneer/walk/postprocess').send({ runId: 'run-3' });+ expect(r.status).toBe(200);+ expect(walk.rerunWalkPostprocess).toHaveBeenCalledWith('pioneer', { runId: 'run-3' });++ expect((await request(app).post('/api/sprites/pioneer/walk/postprocess')+ .send({ runId: '../escape' })).status).toBe(400);+ expect(walk.rerunWalkPostprocess).toHaveBeenCalledOnce();+ });+it('POST /:id/walk/trim validates and 201s', async () => {const payload = { runId: 'walk-east-0a1b2c3d', enabledColumns: [0, 2] };const r = await request(app).post('/api/sprites/pioneer/walk/trim').send(payload);diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex 4709b9e5d0..71e472a312 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -36,7 +36,8 @@ import {import { requireCharacter, loadManifest } from './reference.js';import { SPRITE_DIRECTIONS, anchorIdForDirection, buildWalkVideoPrompt } from './prompts.js';import {- prepareWalkAnchorChromaInput, runWalkPostprocess, WALK_CELL_SIZE, WALK_FPS,+ prepareWalkAnchorChromaInput, runWalkPostprocess, extractVideoFrames,+ WALK_CELL_SIZE, WALK_FPS, MAX_SOURCE_SECONDS,WALK_DEFAULT_FRAME_COUNT, WALK_DEFAULT_FPS,WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT, WALK_MIN_FPS, WALK_MAX_FPS,clampFrameCount, clampFps,@@ -1039,10 +1040,42 @@ async function packageRun(recordId, run, overrides = {}, location = {}) {run.completedAt = new Date().toISOString();}+/**+ * Why this run's cycle cannot be re-derived from its clip right now, or null+ * when it can — stated ONCE, in the order the write path applies the refusals.+ *+ * Both sides read it: `rerunWalkPostprocessImpl` throws the matching error, and+ * `getWalkSourceFrames` reports it as `lockReason` so the Loop Trimmer can offer+ * the unlock/reopen that clears it instead of a re-derive that would 409. A read+ * path with its own copy of this rule is precisely how the two would drift —+ * #2993 already moved the underlying question from provenance ("is this an+ * import?") to evidence ("is the clip actually on disk?"), and a second+ * definition would strand one of them on the old answer.+ *+ * A frozen set outranks an approved direction because the set gate is the+ * coarser one; a missing clip is last because it is the one state the user+ * cannot unlock their way out of.+ */+function reDeriveLockReason({+ walkSet, selection, run, runId, clipRel,+}) {+ if (walkSet) return 'finalized';+ if (selection?.directions?.[run.direction]?.runId === runId) return 'approved';+ if (!clipRel) return 'no-source-video';+ return null;+}++const RE_DERIVE_REFUSALS = {+ finalized: () => new ServerError('Walk set is finalized — revisions require a new character version', { status: 409, code: 'WALK_SET_FINAL' }),+ approved: () => new ServerError('Run is approved — approved runs are immutable', { status: 409, code: 'RUN_APPROVED' }),+ 'no-source-video': () => new ServerError('Run has no source video yet', { status: 409, code: 'VIDEO_NOT_READY' }),+};+/*** Re-run the deterministic postprocess for a run whose source video already- * landed (crash recovery, or determinism verification). Approved/finalized- * runs are immutable.+ * landed — crash recovery, determinism verification, or (the common case since+ * #2985/#2980) bringing a direction onto the set's cycle target from the clip+ * already on disk. Approved/finalized runs are immutable.*/export function rerunWalkPostprocess(recordId, { runId, frameCount, fps }) {return walkWriteTail(recordId, () => rerunWalkPostprocessImpl(recordId, runId, { frameCount, fps }));@@ -1050,21 +1083,18 @@ export function rerunWalkPostprocess(recordId, { runId, frameCount, fps }) {async function rerunWalkPostprocessImpl(recordId, runId, overrides) {await requireCharacter(recordId);- await requireUnfinalized(recordId);// Layout-aware (#2993): an imported run commonly lives under `grok/<run-id>/`,// and its regenerated frames + record must go back to that same directory.const found = await resolveRunById(recordId, runId);if (!found) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });const { run, runDirRel } = found;- // One state read serves both the immutability check and the target below.- const { walkTarget, selection } = await getWalkState(recordId);- if (selection?.directions?.[run.direction]?.runId === runId) {- throw new ServerError('Run is approved — approved runs are immutable', { status: 409, code: 'RUN_APPROVED' });- }+ // One state read serves the re-derive gate and the target below.+ const { walkTarget, selection, walkSet } = await getWalkState(recordId);const clipRel = await resolveRunClipRel(recordId, run, runDirRel);- if (!clipRel) {- throw new ServerError('Run has no source video yet', { status: 409, code: 'VIDEO_NOT_READY' });- }+ const refusal = reDeriveLockReason({+ walkSet, selection, run, runId, clipRel,+ });+ if (refusal) throw RE_DERIVE_REFUSALS[refusal]();// Same set-level gate as generation (#2985): a reprocess is exactly how a// drifted direction is brought INTO line with the target, so it must land on// the target — not somewhere new. An omitted override adopts the target.@@ -1083,6 +1113,169 @@ async function rerunWalkPostprocessImpl(recordId, runId, overrides) {return run;}+// The ffmpeg intermediates a run's clip was extracted into (#2980). Named here+// rather than rebuilt at each call site because `paths.js` excludes exactly this+// directory from `listSpriteAssets` (RUN_RAW_INTERMEDIATE) — the reader below is+// the sanctioned narrow window onto it, and the two must name the same place.+const RAW_FRAME_NAME = /^source-(\d{4})\.png$/;+const rawFramesRelOf = (runDirRel) => `${runDirRel}/generated/raw`;++async function listRawFrameNames(recordId, rawRel) {+ const names = await readdir(join(spriteDir(recordId), rawRel)).catch(() => []);+ return names.filter((name) => RAW_FRAME_NAME.test(name)).sort();+}++/**+ * Re-express the packer's chosen cycle window in the numbering the client+ * renders frames in.+ *+ * `cycleSelection.windowStart` counts from the start of the longest USABLE span+ * the packer kept (walkPostprocess.js slices the clip's fade-in frames off+ * before selecting), while `frames[].sourceFrameIndex` counts raw `source-NNNN`+ * files 1-based. The two are different coordinate spaces and differ by+ * `span.start`, which the manifest never records — but it doesn't need to:+ * `indices[0] === windowStart`, so the FIRST packed frame's source index IS the+ * window's first raw frame. Without this translation the highlight would sit+ * `span.start` frames to the left of the frames it claims to cover.+ *+ * Each field degrades to null independently rather than collapsing the whole+ * block, so a manifest that records the window but no frames[] still reports the+ * window length it selected.+ */+function cycleWindowOf(packaged) {+ const cycle = packaged?.cycleSelection;+ if (!cycle) return null;+ const windowLength = Number.isInteger(cycle.windowLength) ? cycle.windowLength : null;+ const first = packaged?.frames?.[0]?.sourceFrameIndex;+ const windowStartFrame = Number.isInteger(first) ? first : null;+ return {+ windowStart: Number.isInteger(cycle.windowStart) ? cycle.windowStart : null,+ windowLength,+ windowStartFrame,+ windowEndFrame: windowStartFrame !== null && windowLength !== null+ ? windowStartFrame + windowLength : null,+ endpointSeamScore: cycle.endpointSeamScore ?? null,+ medianMotionScore: cycle.medianMotionScore ?? null,+ };+}++/**+ * The fields every source-frame response carries, whatever it found — so the+ * "nothing to show" shape stays as informative as the populated one (the client+ * still seeds its re-derive control from `target` and labels the run's current+ * geometry) instead of degenerating into a bare flag.+ */+function sourceFrameHeader(runId, run, walkTarget) {+ return {+ runId,+ direction: run?.direction || null,+ extractionFps: WALK_FPS,+ maxSourceSeconds: MAX_SOURCE_SECONDS,+ // Older run records predate the persisted frameCount/fps fields, so the+ // packed preview is the fallback — and null (rather than a default) when+ // neither exists, so "unknown" can't masquerade as "packed at 12".+ current: {+ frameCount: run?.frameCount ?? run?.stripPreview?.frameCount ?? null,+ fps: run?.fps ?? run?.stripPreview?.fps ?? null,+ },+ // The set-level cycle target (#2985) — the re-derive control's bounds come+ // from here, not from a free authoring range: re-deriving ONE direction to a+ // geometry the rest of the set doesn't share just recreates a ragged set from+ // the other end (and the reprocess would 409 WALK_TARGET_MISMATCH anyway).+ target: walkTarget,+ };+}++/**+ * Every frame the run's source video produced, plus the provenance that maps+ * them onto the packed strip (#2980).+ *+ * The Loop Trimmer can only ever DROP columns from an already-packed strip, so+ * the raw frames are the only path back to a HIGHER frame count — and they are+ * invisible everywhere else by design (`listSpriteAssets` skips the directory so+ * ~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+ * - `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.+ *+ * `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+ * from), and a run with a clip can still be locked by approval or by a frozen+ * 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.+ */+export async function getWalkSourceFrames(recordId, runId) {+ await requireCharacter(recordId);+ // The state read serves the target, the approval check and the redraw fallback+ // below; it is independent of resolving the run, so overlap them.+ const [found, state] = await Promise.all([+ resolveRunById(recordId, runId),+ getWalkState(recordId),+ ]);+ const { walkTarget, selection, walkSet } = state;+ if (!found) {+ // A run the walk state knows but that has no run DIRECTORY is a redraw cycle+ // synthesized from an imagegen manifest — a legitimate trimmer source with no+ // clip behind it, so it gets the soft sentinel rather than the 404 an+ // unknown id earns.+ const known = state.runs.find((r) => r.id === runId);+ if (!known) throw new ServerError(`Unknown walk run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });+ return {+ ...sourceFrameHeader(runId, known, walkTarget),+ available: false,+ reason: 'run-not-packaged',+ frames: [],+ cycle: null,+ selectedSourceIndices: [],+ editable: false,+ lockReason: 'no-source-video',+ };+ }+ const { runDirRel } = found;+ const run = normalizeRunRecord(recordId, found.run, runDirRel);+ const clipRel = await resolveRunClipRel(recordId, run, runDirRel);+ const rawRel = rawFramesRelOf(runDirRel);+ let names = await listRawFrameNames(recordId, rawRel);+ if (!names.length && clipRel) {+ await walkWriteTail(recordId, () => extractVideoFrames(+ resolveSpriteAssetPath(recordId, clipRel),+ resolveSpriteAssetPath(recordId, rawRel),+ ));+ // Re-listed rather than taking the extractor's return, so what counts as a+ // raw frame is defined in exactly one place.+ names = await listRawFrameNames(recordId, rawRel);+ }+ const packaged = run.postprocessManifest+ ? await readJSONFile(join(spriteDir(recordId), run.postprocessManifest), null)+ : null;+ const frames = names.map((name) => ({+ index: Number(RAW_FRAME_NAME.exec(name)[1]),+ path: `${rawRel}/${name}`,+ }));+ const lockReason = reDeriveLockReason({+ walkSet, selection, run, runId, clipRel,+ });+ return {+ ...sourceFrameHeader(runId, run, walkTarget),+ available: frames.length > 0,+ reason: frames.length > 0 ? null : 'no-source-video',+ frames,+ cycle: cycleWindowOf(packaged),+ selectedSourceIndices: (Array.isArray(packaged?.frames) ? packaged.frames : [])+ .map((frame) => frame?.sourceFrameIndex)+ .filter((index) => Number.isInteger(index)),+ editable: !lockReason,+ lockReason,+ };+}+/*** Approve one direction's candidate run. When all 8 directions are approved* the finalized walk-set manifest is written and the record advances todiff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex c2431461ba..220ef56244 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -84,12 +84,25 @@ const runWalkPostprocess = vi.fn(async ({},};});+// The real extractor shells out to ffmpeg; the source-frame reader (#2980)+// re-extracts on demand when `raw/` was cleaned, so stand in for it with a mock+// that lands the same `source-NNNN.png` shape on disk and returns the sorted+// names, exactly as the real one does.+const EXTRACTED_FRAME_NAMES = ['source-0001.png', 'source-0002.png', 'source-0003.png'];+const extractVideoFrames = vi.fn(async (_videoPath, rawDir) => {+ await mkdir(rawDir, { recursive: true });+ for (const name of EXTRACTED_FRAME_NAMES) {+ await writeFile(join(rawDir, name), `re-extracted:${name}`);+ }+ return [...EXTRACTED_FRAME_NAMES];+});vi.mock('./walkPostprocess.js', async (importOriginal) => {const actual = await importOriginal();return {...actual,prepareWalkAnchorChromaInput: (...args) => prepareWalkAnchorChromaInput(...args),runWalkPostprocess: (...args) => runWalkPostprocess(...args),+ extractVideoFrames: (...args) => extractVideoFrames(...args),};});@@ -98,7 +111,7 @@ const { listSpriteAssets } = await import('./paths.js');const { lockReference } = await import('./reference.js');const {getWalkState, startWalkGeneration, attachTuiWalkResult, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,- reopenWalkDirection, setWalkTarget, importedWalkDirections,+ reopenWalkDirection, setWalkTarget, importedWalkDirections, getWalkSourceFrames,} = await import('./walk.js');const { SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS } = await import('./prompts.js');@@ -1061,6 +1074,203 @@ describe('imported walk sets — evidence-based re-derive', () => {});});+// The Loop Trimmer can only DROP columns from a packed strip, so the raw frames+// are the only path back to a HIGHER frame count — and they are invisible+// everywhere else by design. These cover the narrow read that surfaces them.+describe('getWalkSourceFrames', () => {+ // Braced deliberately: `mockClear()` RETURNS the mock, and a beforeEach that+ // returns a function hands vitest a teardown callback — which would then call+ // the extractor with no arguments after every test in this block.+ beforeEach(() => { extractVideoFrames.mockClear(); });++ const rawName = (i) => `source-${String(i).padStart(4, '0')}.png`;++ async function seedRawFrames(runAbs, count) {+ const rawAbs = join(runAbs, 'generated', 'raw');+ await mkdir(rawAbs, { recursive: true });+ for (let i = 1; i <= count; i++) await writeFile(join(rawAbs, rawName(i)), `raw-${i}`);+ return rawAbs;+ }++ // 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') {+ const manifestAbs = join(+ TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', `${id}-walk-${direction}-manifest.json`,+ );+ const manifest = JSON.parse(await readFile(manifestAbs, 'utf8'));+ manifest.cycleSelection = {+ windowStart: 2, windowLength: 4, endpointSeamScore: 1.25, medianMotionScore: 3.5,+ };+ manifest.frames = [{ sourceFrameIndex: 3 }, { sourceFrameIndex: 5 }];+ await writeFile(manifestAbs, JSON.stringify(manifest));+ }++ it('lists every raw frame, the cycle window, and the packed columns', async () => {+ 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);+ // 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');+ await stampCycleProvenance(id, runId);++ const out = await getWalkSourceFrames(id, runId);+ expect(out.available).toBe(true);+ expect(out.reason).toBeNull();+ expect(out.extractionFps).toBe(12);+ expect(out.frames).toHaveLength(6);+ 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.cycle).toMatchObject({+ windowStart: 2, windowLength: 4, windowStartFrame: 3, windowEndFrame: 7,+ });+ // 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 });+ expect(out.editable).toBe(true);+ expect(out.lockReason).toBeNull();+ // The set target, not a free authoring range, bounds the re-derive.+ expect(out.target).toMatchObject({ frameCount: 8, fps: 12 });+ expect(extractVideoFrames).not.toHaveBeenCalled();+ });++ it('re-extracts on demand when raw/ was cleaned but 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).toHaveBeenCalledWith(+ join(generatedAbs, 'source-video.mp4'),+ join(generatedAbs, 'raw'),+ );+ expect(out.available).toBe(true);+ expect(out.frames.map((f) => f.index)).toEqual([1, 2, 3]);+ // No packaged provenance stamped on this run: the window and the packed+ // columns report empty rather than inventing a selection.+ expect(out.cycle).toBeNull();+ expect(out.selectedSourceIndices).toEqual([]);+ });++ it('reports no-source-video rather than an empty-looking success', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const runIds = await importedCharacter(id, { east: { clip: false } });++ const out = await getWalkSourceFrames(id, runIds.east);+ expect(out.available).toBe(false);+ expect(out.reason).toBe('no-source-video');+ expect(out.frames).toEqual([]);+ expect(extractVideoFrames).not.toHaveBeenCalled();+ });++ // An imported run's manifest names everything under the SOURCE repo root, and+ // it commonly lives under `grok/` — both must resolve, or the trimmer would+ // show an empty grid for exactly the runs this feature exists for.+ it('re-anchors an imported run\'s frames onto the layout it actually lives in', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const runIds = await importedCharacter(id, { east: {} });+ await unlockWalkSet(id);+ const generatedAbs = join(TEST_ROOT, 'sprites', id, 'grok', runIds.east, 'generated');++ const out = await getWalkSourceFrames(id, runIds.east);+ 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.editable).toBe(true);+ expect(out.lockReason).toBeNull();+ });++ // `editable` answers a different question from `available`: these mirror the+ // guards rerunWalkPostprocess actually applies, so the UI never offers a+ // re-derive the server will 409.+ it('locks a finalized set and names the unlock as the reason', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const runIds = await importedCharacter(id, { east: {} });++ const out = await getWalkSourceFrames(id, runIds.east);+ expect(out.editable).toBe(false);+ expect(out.lockReason).toBe('finalized');+ await expect(rerunWalkPostprocess(id, { runId: runIds.east }))+ .rejects.toMatchObject({ code: 'WALK_SET_FINAL' });+ });++ it('locks an approved direction and names the reopen as the reason', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const { runId } = await makeCandidateRun(id, 'east');+ await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4'), 'CLIP');+ await approveWalkDirection(id, { direction: 'east', runId });++ const out = await getWalkSourceFrames(id, runId);+ expect(out.editable).toBe(false);+ expect(out.lockReason).toBe('approved');+ await expect(rerunWalkPostprocess(id, { runId }))+ .rejects.toMatchObject({ code: 'RUN_APPROVED' });+ });++ // Frames can exist for a run whose clip has since been deleted — listable, but+ // nothing to re-derive from. The two facts must not collapse.+ it('lists frames but refuses the re-derive when only the clip is gone', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const { runId } = await makeCandidateRun(id, 'east');+ await seedRawFrames(join(TEST_ROOT, 'sprites', id, 'runs', runId), 4);++ const out = await getWalkSourceFrames(id, runId);+ expect(out.available).toBe(true);+ expect(out.frames).toHaveLength(4);+ expect(out.editable).toBe(false);+ expect(out.lockReason).toBe('no-source-video');+ });++ // A synthesized redraw cycle (#2924) is a legitimate trimmer source with no+ // run directory behind it — a soft sentinel, not the 404 an unknown id earns.+ it('reports run-not-packaged for an imagegen redraw cycle', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const dir = join(TEST_ROOT, 'sprites', id, 'imagegen', 'v19');+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, 'clean-alpha.png'), 'strip');+ await writeFile(join(dir, 'walk-east-v19-manifest.json'), JSON.stringify({+ schemaVersion: 1,+ characterId: id,+ direction: 'east',+ cellSize: 384,+ cycle: { frameCount: 12, referenceFps: 12, stripAlpha: 'imagegen/v19/clean-alpha.png' },+ }));+ await mkdir(join(TEST_ROOT, 'sprites', id, 'walk'), { recursive: true });+ await writeFile(join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`), JSON.stringify({+ schemaVersion: 1,+ characterId: id,+ status: 'in-progress',+ directions: {+ east: {+ status: 'approved',+ runId: `${id}-v19-east`,+ runPath: 'imagegen/v19',+ runManifest: 'imagegen/v19/walk-east-v19-manifest.json',+ },+ },+ }));++ const out = await getWalkSourceFrames(id, `${id}-v19-east`);+ expect(out.available).toBe(false);+ expect(out.reason).toBe('run-not-packaged');+ expect(out.editable).toBe(false);+ expect(out.current).toEqual({ frameCount: 12, fps: 12 });+ });++ it('404s an unknown run', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ await expect(getWalkSourceFrames(id, 'walk-east-deadbeef'))+ .rejects.toMatchObject({ status: 404, code: 'RUN_NOT_FOUND' });+ });+});+describe('listSpriteAssets run-intermediate exclusion', () => {it('omits raw extraction frames but keeps packaged frames and the review sheet', async () => {const id = await characterWithLockedAnchors(newId(), []);