Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([issue-2980]): share the cycle-target control and collapse the duplicated gates

[._.]/ Adam Eivy52f2cd8504ab
diff --git a/client/src/components/sprites/CycleTarget.jsx b/client/src/components/sprites/CycleTarget.jsx
new file mode 100644
index 0000000000..516de73fa7
--- /dev/null
+++ b/client/src/components/sprites/CycleTarget.jsx
@@ -0,0 +1,92 @@
+import { Gauge } from 'lucide-react';
+import toast from '../ui/Toast';
+import { setSpriteWalkTarget } from '../../services/apiSprites.js';
+import { useAsyncAction } from '../../hooks/useAsyncAction.js';
+import { WALK_FRAME_COUNT_OPTIONS, walkFpsOptionsFor } from '../../lib/spriteTrimmer.js';
+
+/**
+ * The SET-level cycle target (#2985) — one control for the whole walk, not a
+ * per-render slider that can drift between directions. Saving PUTs the target
+ * and refreshes the walk state; while that write is in flight the host disables
+ * its own render/re-derive actions (via `onSavingChange`), so a click can't
+ * queue against a value the server has not persisted yet.
+ *
+ * Its own module because two surfaces offer it: the walk workflow's per-set
+ * header and the Loop Trimmer's re-derive panel (#2980). A second copy of these
+ * two `<select>`s is exactly the drift #2985 exists to prevent — the copies would
+ * disagree first about the app-lock hint, then about what the target means.
+ *
+ * `surfaceClass` lets a host on a `bg-port-bg` panel keep the inputs distinct
+ * from their backdrop; `appRetargetHint` names where the bound app's contract is
+ * actually edited, which differs per host.
+ */
+export default function CycleTarget({
+ recordId, target, disabled, onChanged, onSavingChange = () => {},
+ surfaceClass = 'bg-port-bg', appRetargetHint = 'change it in Publish below',
+}) {
+ const [save, saving] = useAsyncAction(async (next) => {
+ onSavingChange(true);
+ try {
+ await setSpriteWalkTarget(recordId, next, { silent: true });
+ toast.success(`Cycle target set · ${next.frameCount}f @ ${next.fps}fps`);
+ onChanged();
+ } finally {
+ onSavingChange(false);
+ }
+ }, { errorMessage: 'Could not set the cycle target' });
+
+ const cycleSeconds = (target.frameCount / target.fps).toFixed(2);
+ const selectCls = `${surfaceClass} border border-port-border rounded px-2 py-1 text-sm text-white disabled:opacity-60`;
+
+ return (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
+ <label className="flex items-center gap-1.5 text-xs text-gray-400" htmlFor={`walk-target-frames-${recordId}`}>
+ Cycle target
+ <select
+ id={`walk-target-frames-${recordId}`}
+ value={target.frameCount}
+ disabled={disabled || saving || target.frameCountLocked}
+ onChange={(e) => save({ frameCount: Number(e.target.value), fps: target.fps })}
+ title="Frames in the walk cycle — shared by all 8 directions, because the atlas is a rectangular grid"
+ className={selectCls}
+ >
+ {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={`walk-target-fps-${recordId}`}>
+ {/* fps is an AUTHORING/preview speed: it drives this page's loop preview
+ and is stamped on the manifest, but the consuming app decides how
+ fast the sprite actually walks in-game. It lives in the target
+ anyway because the atlas requires every direction to agree on it. */}
+ <span className="flex items-center gap-1"><Gauge className="w-3 h-3" /> Preview speed</span>
+ <select
+ id={`walk-target-fps-${recordId}`}
+ value={target.fps}
+ disabled={disabled || saving || target.fpsLocked}
+ onChange={(e) => save({ frameCount: target.frameCount, fps: Number(e.target.value) })}
+ title="Preview/authoring speed — the consuming app determines real in-game playback. Pinned per set because the atlas needs every direction to agree."
+ className={selectCls}
+ >
+ {walkFpsOptionsFor(target.fps).map((n) => <option key={n} value={n}>{n} fps</option>)}
+ </select>
+ </label>
+ <span
+ className="text-[11px] text-gray-500 tabular-nums"
+ title="cycle duration = frames ÷ preview speed"
+ >
+ {cycleSeconds}s / cycle
+ </span>
+ <span
+ className="text-[10px] text-gray-500"
+ title={target.source === 'app'
+ ? 'The bound app declares what its atlas may hold — retarget it through the publish binding.'
+ : undefined}
+ >
+ {/* Provenance wording is stamped by the server (describeTargetSource), so
+ this label and the 409 the user may hit always agree. */}
+ {saving ? 'saving…' : target.sourceLabel || target.source}
+ {target.source === 'app' && ` · ${appRetargetHint}`}
+ </span>
+ </div>
+ );
+}
diff --git a/client/src/components/sprites/LoopTrimmer.jsx b/client/src/components/sprites/LoopTrimmer.jsx
index 6aac70226f..5f90fe7229 100644
--- a/client/src/components/sprites/LoopTrimmer.jsx
+++ b/client/src/components/sprites/LoopTrimmer.jsx
@@ -118,10 +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.
+ // 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
@@ -144,8 +145,7 @@ export default function LoopTrimmer({
if (!source) return undefined;
const image = new Image();
image.onload = () => setImg(image);
- const url = spriteAssetUrl(recordId, source.stripPath);
- image.src = stripVersion ? `${url}?v=${stripVersion}` : url;
+ image.src = spriteAssetUrl(recordId, source.stripPath);
return () => { image.onload = null; };
}, [source?.id, source?.stripPath, recordId, stripVersion]);
@@ -179,6 +179,13 @@ 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, {
@@ -366,11 +373,7 @@ export default function LoopTrimmer({
(#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(); }}
- />
+ <WalkSourceFrames recordId={recordId} runId={source.runId} onSaved={onSourceFramesSaved} />
)}
{/* Save + result */}
diff --git a/client/src/components/sprites/WalkSourceFrames.jsx b/client/src/components/sprites/WalkSourceFrames.jsx
index e866d9897c..b12f0b2ed6 100644
--- a/client/src/components/sprites/WalkSourceFrames.jsx
+++ b/client/src/components/sprites/WalkSourceFrames.jsx
@@ -1,18 +1,18 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
import {
- Film, ChevronDown, ChevronRight, Gauge, RefreshCw, RotateCcw, Unlock,
+ memo, useCallback, useEffect, useMemo, useState,
+} from 'react';
+import {
+ Film, ChevronDown, ChevronRight, RefreshCw, RotateCcw, Unlock,
} from 'lucide-react';
import toast from '../ui/Toast';
import {
- getSpriteWalkSourceFrames, postprocessSpriteWalk, setSpriteWalkTarget,
+ getSpriteWalkSourceFrames, postprocessSpriteWalk,
unlockSpriteWalk, reopenSpriteWalk,
} from '../../services/apiSprites.js';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';
+import CycleTarget from './CycleTarget.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.
//
@@ -24,12 +24,14 @@ import {
// 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.
+// The geometry knob is the shared SET-level <CycleTarget> (#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). Re-derive itself sends only the run id and lets
+// the server adopt the pinned target — the same request WalkWorkflow's Reprocess
+// 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.
@@ -64,17 +66,20 @@ const LOCK_COPY = {
// 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 }) {
+// Memoized: the trimmer this panel lives in re-renders 12–24×/second while its
+// loop preview plays, and a run holds ~73 of these.
+const RawFrame = memo(function RawFrame({
+ recordId, frame, inWindow, packed,
+}) {
const marks = [
inWindow ? 'in the selected cycle window' : null,
packed ? 'packed into the strip' : null,
].filter(Boolean);
+ const tone = packed ? 'border-port-accent ring-1 ring-port-accent'
+ : inWindow ? 'border-port-warning/70' : 'border-port-border opacity-60';
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'}`}
+ className={`rounded overflow-hidden border ${tone}`}
title={`source frame ${frame.index}${marks.length ? ` — ${marks.join(', ')}` : ''}`}
>
<img
@@ -89,35 +94,25 @@ function RawFrame({ recordId, frame, inWindow, packed }) {
</span>
</div>
);
-}
+});
-export default function WalkSourceFrames({ recordId, runId, onSaved = () => {} }) {
+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.
+ // The cycle target's PUT is its own request; the re-derive below reads the
+ // target server-side, so it must not fire against a value the server has not
+ // persisted yet (CLAUDE.md: "in-flight saves must gate dependent actions").
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);
+ if (next) setData(next);
}, [recordId, runId]);
useEffect(() => {
@@ -132,40 +127,32 @@ export default function WalkSourceFrames({ recordId, runId, onSaved = () => {} }
[data?.selectedSourceIndices],
);
- const target = data?.target || null;
- const retargets = Boolean(target) && (frameCount !== target.frameCount || fps !== target.fps);
+ // Every mutation refreshes BOTH this panel (its own frames/lock state) and the
+ // trimmer around it (the repacked strip and its frame toggles).
+ const refresh = useCallback(async () => { onSaved(); await load(); }, [onSaved, load]);
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();
+ // Geometry deliberately NOT sent: the server adopts the set's pinned target
+ // 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`);
+ await refresh();
}, { 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');
+ toast.success('Walk set unlocked — directions are editable again');
} else {
await reopenSpriteWalk(recordId, { direction: data.direction }, { silent: true });
- toast.success(`${data.direction} reopened`);
+ toast.success(`Walk ${data.direction} reopened`);
}
- onSaved();
- await load();
+ await refresh();
}, { errorMessage: 'Could not unlock this direction' });
- const busy = loading || redriving || unlocking || targetSaving;
+ const busy = redriving || unlocking || targetSaving;
const lock = data && !data.editable ? LOCK_COPY[data.lockReason] : null;
const frames = data?.frames || [];
@@ -249,52 +236,39 @@ export default function WalkSourceFrames({ recordId, runId, onSaved = () => {} }
)}
{/* Re-derive. Present whenever the run has a clip behind it — the source
- grid above is context, not a precondition. */}
+ grid above is context, not a precondition. The geometry knob is the
+ shared set-level control, so changing it here means the same thing (and
+ carries the same app-lock explanation) as changing it in the walk
+ workflow; the button then repacks THIS run onto it. */}
<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>
+ {data.target && (
+ <CycleTarget
+ recordId={recordId}
+ target={data.target}
+ disabled={busy}
+ onChanged={refresh}
+ onSavingChange={setTargetSaving}
+ surfaceClass="bg-port-card"
+ appRetargetHint="change it in the Publish panel"
+ />
+ )}
<button
onClick={redrive}
- disabled={busy || !data.editable || !frameCount || !fps}
+ disabled={busy || !data.editable}
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</>}
+ <RefreshCw className={`w-3.5 h-3.5 ${redriving ? 'animate-spin' : ''}`} />
+ {redriving ? 'Re-deriving…' : '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.`}
+ Re-deriving repacks this run from its clip onto the set&apos;s cycle target — no AI
+ call, no new render. Changing the target re-targets every direction, so the others
+ will need re-deriving too.
</p>
{lock && (
@@ -327,3 +301,7 @@ export default function WalkSourceFrames({ recordId, runId, onSaved = () => {} }
</div>
);
}
+
+// Memoized for the same reason RawFrame is: the trimmer around this panel
+// re-renders on every loop-preview tick, and nothing here depends on that.
+export default memo(WalkSourceFrames);
diff --git a/client/src/components/sprites/WalkSourceFrames.test.jsx b/client/src/components/sprites/WalkSourceFrames.test.jsx
index 10ffd27c6f..98efa38151 100644
--- a/client/src/components/sprites/WalkSourceFrames.test.jsx
+++ b/client/src/components/sprites/WalkSourceFrames.test.jsx
@@ -98,37 +98,32 @@ describe('WalkSourceFrames', () => {
expect(cellFor(7).getAttribute('title')).toBe('source frame 7');
});
- it('re-derives the SELECTED run at the set target without retargeting it', async () => {
+ // Geometry is deliberately omitted so the server adopts the pinned target: a
+ // panel one refetch behind must not 409 on a value the user never chose.
+ it('re-derives the SELECTED run by id alone, letting the server adopt the target', 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 },
+ 'example-walker', { runId: RUN_ID }, { 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 () => {
+ // The geometry knob is the shared SET-level control, not a per-run one — the
+ // whole point of #2985 is that one direction cannot diverge from the set.
+ it('changes the cycle through the shared set target', 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());
+ fireEvent.change(screen.getByLabelText(/Cycle target/), { target: { value: '12' } });
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 },
- );
+ // A retarget refreshes the trimmer around it as well as this panel.
+ expect(onSaved).toHaveBeenCalled();
});
it('disables the controls while the re-derive is in flight', async () => {
@@ -138,13 +133,27 @@ describe('WalkSourceFrames', () => {
fireEvent.click(deriveButton());
expect(deriveButton()).toBeDisabled();
- expect(screen.getByLabelText(/Re-derive at/)).toBeDisabled();
+ expect(screen.getByLabelText(/Cycle target/)).toBeDisabled();
expect(screen.getByLabelText(/Preview speed/)).toBeDisabled();
await act(async () => { release({}); });
expect(deriveButton()).not.toBeDisabled();
});
+ // The dependent action must not fire against a target the server has not
+ // persisted yet (CLAUDE.md: in-flight saves gate dependent actions).
+ it('disables the re-derive while the target PUT is in flight', async () => {
+ let release;
+ setSpriteWalkTarget.mockReturnValue(new Promise((resolve) => { release = resolve; }));
+ await renderPanel();
+
+ fireEvent.change(screen.getByLabelText(/Cycle target/), { target: { value: '12' } });
+ expect(deriveButton()).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',
diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsx
index 843d7f5898..e2b02c19eb 100644
--- a/client/src/components/sprites/WalkWorkflow.jsx
+++ b/client/src/components/sprites/WalkWorkflow.jsx
@@ -6,14 +6,13 @@ import {
import toast from '../ui/Toast';
import {
approveSpriteWalk, postprocessSpriteWalk, unlockSpriteWalk, reopenSpriteWalk,
- setSpriteWalkTarget,
} from '../../services/apiSprites.js';
import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';
+import CycleTarget from './CycleTarget.jsx';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
import { spriteAssetUrl, checkerboardStyle, PIXELATED } from './spriteAssets.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
@@ -142,82 +141,6 @@ const driftRemedy = ({ approved, hasSourceClip, imported }) => {
return 'reprocess it from its clip';
};
-/**
- * The SET-level cycle target (#2985) — one control for the whole walk, not a
- * per-render slider that can drift between directions. Saving PUTs the target
- * and refreshes the walk state; while that write is in flight every render
- * action is disabled by the parent, so a click can't queue against a value the
- * server has not persisted yet.
- */
-function CycleTarget({
- recordId, target, disabled, onChanged, onSavingChange,
-}) {
- const [save, saving] = useAsyncAction(async (next) => {
- onSavingChange(true);
- try {
- await setSpriteWalkTarget(recordId, next, { silent: true });
- toast.success(`Cycle target set · ${next.frameCount}f @ ${next.fps}fps`);
- onChanged();
- } finally {
- onSavingChange(false);
- }
- }, { errorMessage: 'Could not set the cycle target' });
-
- const cycleSeconds = (target.frameCount / target.fps).toFixed(2);
-
- return (
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
- <label className="flex items-center gap-1.5 text-xs text-gray-400" htmlFor={`walk-target-frames-${recordId}`}>
- Cycle target
- <select
- id={`walk-target-frames-${recordId}`}
- value={target.frameCount}
- disabled={disabled || saving || target.frameCountLocked}
- onChange={(e) => save({ frameCount: Number(e.target.value), fps: target.fps })}
- title="Frames in the walk cycle — shared by all 8 directions, because the atlas is a rectangular grid"
- className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white disabled:opacity-60"
- >
- {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={`walk-target-fps-${recordId}`}>
- {/* fps is an AUTHORING/preview speed: it drives this page's loop preview
- and is stamped on the manifest, but the consuming app decides how
- fast the sprite actually walks in-game. It lives in the target
- anyway because the atlas requires every direction to agree on it. */}
- <span className="flex items-center gap-1"><Gauge className="w-3 h-3" /> Preview speed</span>
- <select
- id={`walk-target-fps-${recordId}`}
- value={target.fps}
- disabled={disabled || saving || target.fpsLocked}
- onChange={(e) => save({ frameCount: target.frameCount, fps: Number(e.target.value) })}
- title="Preview/authoring speed — the consuming app determines real in-game playback. Pinned per set because the atlas needs every direction to agree."
- className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white disabled:opacity-60"
- >
- {fpsOptionsFor(target.fps).map((n) => <option key={n} value={n}>{n} fps</option>)}
- </select>
- </label>
- <span
- className="text-[11px] text-gray-500 tabular-nums"
- title="cycle duration = frames ÷ preview speed"
- >
- {cycleSeconds}s / cycle
- </span>
- <span
- className="text-[10px] text-gray-500"
- title={target.source === 'app'
- ? 'The bound app declares what its atlas may hold — retarget it in the Publish panel below.'
- : undefined}
- >
- {/* Provenance wording is stamped by the server (describeTargetSource), so
- this label and the 409 the user may hit always agree. */}
- {saving ? 'saving…' : target.sourceLabel || target.source}
- {target.source === 'app' && ' · change it in Publish below'}
- </span>
- </div>
- );
-}
-
function DirectionCard({
recordId, direction, anchorLocked, run, approved, finalized, pending,
onOpenTrimmer, onGenerate, onApprove, onRetry, onReprocess, onReopen,
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 16e697ad4e..83508472a4 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). 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. |
+| `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 knobs mirrored from `walkBounds.js` — `WALK_DEFAULT_FRAME_COUNT` / `WALK_DEFAULT_FPS`, the `WALK_FRAME_COUNT_OPTIONS` list and `walkFpsOptionsFor(fps)` (splices a current odd fps into the even-step list so the `<select>` never lies) — feeding the shared `CycleTarget` control used by both the walk workflow and the trimmer's re-derive panel (#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.js
index 022d8ab285..eb32d3a9a2 100644
--- a/client/src/lib/spriteTrimmer.js
+++ b/client/src/lib/spriteTrimmer.js
@@ -33,8 +33,10 @@ const DEFAULT_FPS = 12;
// 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 };
+// Module-local: callers pick from the option lists below rather than re-deriving
+// them, so the bounds themselves have no consumer outside this file.
+const WALK_FRAME_COUNT_RANGE = { min: 6, max: 16 };
+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.
diff --git a/server/lib/validation.js b/server/lib/validation.js
index bbd7d5530e..84bd8dd890 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1113,19 +1113,16 @@ export const spriteReferenceLockSchema = z.object({
// animatable (south's anchor is the frozen main itself).
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.)
+// Any run the walk state can resolve — which is every run id PortOS actually
+// hands the client, not just the native `walk-<dir>-<hex>` shape: an imported
+// run's id is its source-named directory slug (`run-3`), and a redraw run's id
+// is a record-relative manifest path. Every service behind this resolves the id
+// against server-owned walk state and dereferences only paths that state itself
+// recorded (through resolveSpriteAssetPath), so the schema bounds shape and
+// length only — the shared `isSafeSubdirFilter` predicate (safe charset, no `..`
+// segment, no leading `/`), so a hardening tweak there reaches these routes too.
const spriteResolvableRunIdSchema = z.string().min(1).max(1024)
- .refine((v) => /^[A-Za-z0-9._/-]+$/.test(v) && !v.split('/').includes('..'), {
- message: 'invalid run id',
- });
+ .refine(isSafeSubdirFilter, { 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
@@ -1161,7 +1158,14 @@ export const spriteWalkTargetSchema = z.object({
export const spriteWalkApproveSchema = z.object({
direction: spriteWalkDirectionSchema,
- runId: spriteWalkRunIdSchema,
+ // Also the resolvable shape (#2980): approve has been layout-aware since
+ // #2993 — "a re-derived import stays in the run directory it was imported
+ // into, and its approval must record THAT path" — so the native-only regex
+ // dead-ended the reopen → re-derive → re-approve flow at its last click for
+ // exactly the imported runs that work was for. What makes an approval safe is
+ // approveWalkDirectionImpl's candidate/manifest/strip/frame tamper checks, not
+ // a charset that encodes an obsolete provenance assumption.
+ runId: spriteResolvableRunIdSchema,
});
export const spriteWalkReopenSchema = z.object({
@@ -1169,14 +1173,11 @@ export const spriteWalkReopenSchema = z.object({
});
export const spriteWalkPostprocessSchema = z.object({
- // 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.
+ // Resolvable, not native-only (#2980): since #2993 the reprocess is
+ // layout-aware and re-derives an IMPORTED run in the directory it was imported
+ // into — which the strict shape rejected at the door, leaving the one path
+ // back onto the set's target unreachable for exactly the population that
+ // needs it.
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
diff --git a/server/services/sprites/paths.js b/server/services/sprites/paths.js
index 5c1096e22e..f655fcdd67 100644
--- a/server/services/sprites/paths.js
+++ b/server/services/sprites/paths.js
@@ -141,14 +141,25 @@ export async function resolveDriftTolerantRel(baseDir, rel) {
return alt && (await pathExists(join(baseDir, alt))) ? alt : null;
}
-// Raw ffmpeg-extracted frame intermediates inside an animation run (30–96
-// near-identical PNGs per run, `grok|runs/<run>/generated/raw/`). Kept on
-// disk for the postprocessor but omitted from the asset listing — they'd
-// swamp the browser. Narrower than the importer's EXCLUDED_RUN_SEGMENTS
-// (which also skips frames/ and review/ to minimize cross-machine copies):
-// the packaged phase frames and the contrast review sheet exist FOR human
-// review, so the local browser keeps them.
-const RUN_RAW_INTERMEDIATE = new RegExp(`${RUN_DIR_MATCH.source}/generated/raw/`);
+/**
+ * Raw ffmpeg-extracted frame intermediates inside an animation run (30–96
+ * near-identical PNGs per run) — where they live and what they are named.
+ *
+ * Stated here, beside the exclusion built from it, because two readers disagree
+ * about them by design: `listSpriteAssets` skips the directory (the frames would
+ * swamp the asset browser) while the Loop Trimmer's source-frame endpoint (#2980)
+ * is the sanctioned narrow window onto it. Split those definitions and moving the
+ * directory — or widening the counter past four digits — silently publishes ~73
+ * PNGs into the browser while the trimmer reads an empty tree.
+ *
+ * The exclusion is narrower than the importer's EXCLUDED_RUN_SEGMENTS (which also
+ * skips frames/ and review/ to minimize cross-machine copies): the packaged phase
+ * frames and the contrast review sheet exist FOR human review, so the local
+ * browser keeps them.
+ */
+export const rawFramesRelOf = (runDirRel) => `${runDirRel}/generated/raw`;
+export const RAW_FRAME_NAME = /^source-(\d{4})\.png$/;
+const RUN_RAW_INTERMEDIATE = new RegExp(`${RUN_DIR_MATCH.source}${rawFramesRelOf('')}/`);
// Extensions sharp can parse a header for. Anything else (JSON manifests,
// videos, text) skips the metadata probe entirely.
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 71e472a312..a4b6305195 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -32,6 +32,7 @@ import { getRecord, updateRecord } from './records.js';
import {
spriteDir, resolveSpriteAssetPath, toRecordRelativeAssetPath, altRunLayoutPath,
runDirOfPath, resolveDriftTolerantRel, isSourcePipelinePath, SOURCE_CLIP_NAME,
+ rawFramesRelOf, RAW_FRAME_NAME,
} from './paths.js';
import { requireCharacter, loadManifest } from './reference.js';
import { SPRITE_DIRECTIONS, anchorIdForDirection, buildWalkVideoPrompt } from './prompts.js';
@@ -230,10 +231,14 @@ async function resolveRunClipRel(recordId, run, runDirRel) {
return resolved.find(Boolean) || null;
}
+// What a frozen set says when a mutating op reaches it. A factory rather than a
+// literal because two paths raise it: this guard, and the shared re-derive gate
+// below (which resolves the frozen set from state it already loaded rather than
+// re-reading the file). One producer, so the two can't drift apart.
+const walkSetFinalError = () => new ServerError('Walk set is finalized — revisions require a new character version', { status: 409, code: 'WALK_SET_FINAL' });
+
async function requireUnfinalized(recordId) {
- if (await loadWalkSet(recordId)) {
- throw new ServerError('Walk set is finalized — revisions require a new character version', { status: 409, code: 'WALK_SET_FINAL' });
- }
+ if (await loadWalkSet(recordId)) throw walkSetFinalError();
}
// PortOS stamps createdAt as an ISO string (Date.parse handles it); imported
@@ -500,16 +505,27 @@ async function directionClipRel(recordId, entry) {
return resolveRunClipRel(recordId, found?.run, found?.runDirRel || runDirRel);
}
+/**
+ * The cycle geometry ONE run was packed at.
+ *
+ * Native runs stamp `frameCount`/`fps` on the run record; imported and redraw
+ * runs only carry them inside `stripPreview`, and older native records predate
+ * the run-level fields entirely — so every reader has to look through both, and
+ * they do it through here rather than each re-deriving the fallback order.
+ * Absent reports as null rather than a default, so "unknown" can't masquerade as
+ * "packed at the default".
+ */
+const runCycleOf = (run) => ({
+ frameCount: run?.frameCount ?? run?.stripPreview?.frameCount ?? null,
+ fps: run?.fps ?? run?.stripPreview?.fps ?? null,
+});
+
/**
* The packed geometry of each direction that actually carries one, in ATLAS
* order (SPRITE_DIRECTIONS) so "the first packaged direction" means the same
* thing here as it does in the compiler's first-wins rule. An approved run wins
* over a candidate for the same direction — approval is what the atlas compiles.
*
- * Native runs stamp `frameCount`/`fps` on the run record; imported and redraw
- * runs only carry them inside `stripPreview`, so read through both or every
- * imported set would resolve as "no packaged geometry" and drift silently.
- *
* A run the server flagged `stripMissing` contributes nothing: its packed strip
* is gone from disk, so it can never compile, and letting it win the
* first-packaged slot would derive the whole set's target from artwork that no
@@ -528,11 +544,7 @@ function packagedCyclesFrom(runs, approvedDirections) {
|| forDirection.find((r) => r.status === 'approved')
|| forDirection.find((r) => r.status === 'candidate');
if (!run || run.stripMissing) return [];
- return [{
- direction,
- frameCount: run.frameCount ?? run.stripPreview?.frameCount,
- fps: run.fps ?? run.stripPreview?.fps,
- }];
+ return [{ direction, ...runCycleOf(run) }];
});
}
@@ -1066,7 +1078,7 @@ function reDeriveLockReason({
}
const RE_DERIVE_REFUSALS = {
- finalized: () => new ServerError('Walk set is finalized — revisions require a new character version', { status: 409, code: 'WALK_SET_FINAL' }),
+ finalized: walkSetFinalError,
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' }),
};
@@ -1113,13 +1125,9 @@ 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`;
-
+// The raw-frame location + naming come from paths.js, which builds
+// `listSpriteAssets`' exclusion from the same two values — this reader is the
+// sanctioned narrow window onto the directory that listing deliberately skips.
async function listRawFrameNames(recordId, rawRel) {
const names = await readdir(join(spriteDir(recordId), rawRel)).catch(() => []);
return names.filter((name) => RAW_FRAME_NAME.test(name)).sort();
@@ -1154,35 +1162,39 @@ function cycleWindowOf(packaged) {
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.
+ * One source-frame response, defaulted to the "nothing to show" shape and
+ * overridden with whatever was actually found.
+ *
+ * Written as one builder rather than two hand-assembled object literals so that
+ * adding a field is one edit: the absent case has to stay as informative as the
+ * populated one (the client still seeds its re-derive control from `target` and
+ * labels the run's current geometry off `current`), and a shape that only two
+ * thirds matched would defeat that quietly.
*/
-function sourceFrameHeader(runId, run, walkTarget) {
+function sourceFrameResponse(runId, run, walkTarget, found) {
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,
- },
+ current: runCycleOf(run),
// 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,
+ available: false,
+ reason: null,
+ frames: [],
+ cycle: null,
+ selectedSourceIndices: [],
+ editable: false,
+ lockReason: null,
+ ...found,
};
}
@@ -1212,10 +1224,11 @@ function sourceFrameHeader(runId, run, walkTarget) {
* 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([
+ // 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.
+ const [, found, state] = await Promise.all([
+ requireCharacter(recordId),
resolveRunById(recordId, runId),
getWalkState(recordId),
]);
@@ -1227,22 +1240,25 @@ export async function getWalkSourceFrames(recordId, runId) {
// 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,
+ return sourceFrameResponse(runId, known, walkTarget, {
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);
+ // Three independent probes (the clip, the raw listing, the packaged manifest)
+ // — none feeds the next, so they overlap rather than serializing three round
+ // trips onto a read the trimmer makes on every source switch.
+ const [clipRel, listed, packaged] = await Promise.all([
+ resolveRunClipRel(recordId, run, runDirRel),
+ listRawFrameNames(recordId, rawRel),
+ run.postprocessManifest
+ ? readJSONFile(join(spriteDir(recordId), run.postprocessManifest), null)
+ : null,
+ ]);
+ let names = listed;
if (!names.length && clipRel) {
await walkWriteTail(recordId, () => extractVideoFrames(
resolveSpriteAssetPath(recordId, clipRel),
@@ -1252,9 +1268,6 @@ export async function getWalkSourceFrames(recordId, runId) {
// 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}`,
@@ -1262,8 +1275,7 @@ export async function getWalkSourceFrames(recordId, runId) {
const lockReason = reDeriveLockReason({
walkSet, selection, run, runId, clipRel,
});
- return {
- ...sourceFrameHeader(runId, run, walkTarget),
+ return sourceFrameResponse(runId, run, walkTarget, {
available: frames.length > 0,
reason: frames.length > 0 ? null : 'no-source-video',
frames,
@@ -1273,7 +1285,7 @@ export async function getWalkSourceFrames(recordId, runId) {
.filter((index) => Number.isInteger(index)),
editable: !lockReason,
lockReason,
- };
+ });
}
/**