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

feat([issue-2985]): pin walk frame count/fps per set and enforce it at queue time

[._.]/ Adam Eivy62d6f00db2e1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7cfb13e24a..b9ef398acd 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -27,6 +27,7 @@
- **[issue-2979] Characters now start from a turnaround sheet, so accessories stop jumping sides** — directional anchors used to be drawn from a single front-facing reference, which meant the AI had to invent every side it hadn't seen: a hip bag on the character's front would migrate to their back in the north view, and pockets or straps would swap sides between the east and west profiles. The reference workflow is now three ordered steps. **1 · Turnaround sheet**: describe the character (or attach a design image) and generate one image showing them from four angles — front, right, back, left — with every accessory pinned to the same side of the body in each panel. Lock it, and it becomes the character's identity root. **2 · Main reference**: redrawn from the sheet's front panel with one click, no separate design input. **3 · Directional anchors**: each pose is now redrawn from the sheet's panel for *that* side, so the model can see the hip bag instead of guessing at it. Picking the chroma-key background also moved to the sheet lock, where it can see the character from every angle — so a green backpack that's only visible from behind is accounted for up front instead of surprising you later. Forking a character now seeds the new one's sheet from the original's, inheriting every side.
- **[issue-2979] Existing characters can backfill a turnaround sheet from their locked main** — a character you built before this shows the same three steps, with step 1 offering **Generate from locked main**: it expands the front view you already froze into the full four-view sheet, keeps your existing chroma key exactly as-is, and unblocks the directional anchors you haven't locked yet — which are then drawn from the sheet like a new character's. Already-locked references and anchors are untouched (they're immutable by design), so the benefit applies to whatever poses you still have left to derive.
+- **[issue-2985] A walk set now has one cycle target, and a mismatched render is caught before you spend it** — frame count and playback speed used to be per-render controls, so it was easy to render one direction at 12 frames, nudge the slider, render the next at 8, and only find out eight renders and eight approvals later — when compiling the atlas refused with "reprocess all directions to the same frame count". Those two controls have moved out of the per-render form into a single **Cycle target** for the whole walk set, labeled with where the value came from (locked by the bound app · set target · from the first approved direction · default). Queuing a render or a reprocess that disagrees with the target is now refused up front, naming both values and how to fix it, instead of silently producing an artwork that can never compile. Any already-packaged direction that doesn't match shows a drift badge (with the fix for its situation — reprocess from its clip, reopen it first, or import its source clip), plus a set-level summary line, so an existing mixed set tells you what's wrong the moment you open it rather than at compile time. When a character is bound to a managed app, the app's declared frame count wins and the control goes read-only. The speed control is now labeled **Preview speed** — it drives the preview here and is recorded in the artwork, but the game decides how fast your sprite actually walks.
- **[issue-2977] Loop Trimmer frames now render pixel-crisp** — the frame thumbnails and the playback preview in the Loop Trimmer looked soft and washed-out, as if the artwork had been compressed, which made it impossible to judge a frame before saving a trim. Your artwork was never affected — the trimmer was shrinking each frame to a fraction of its real size to draw it, then blurrily stretching that back up. Frames now draw at their full source resolution with the same crisp pixel scaling every other sprite view uses, so what you review is exactly what gets saved. The transparency checkerboard behind each frame is drawn by the page now instead of being baked into the shrunken frame, so its squares stay crisp and a fixed size rather than coming out blurry and oversized.
- **[issue-2978] Saving a loop trim now works on imported characters** — for a character whose walk cycles came in through the source-pipeline import, the Loop Trimmer would load, scrub, and play the animation perfectly, then fail on **Save trim** with "Packaged run manifest is missing or inconsistent" — after you'd already picked your frames, and with nothing saved. The imported artwork was never damaged; PortOS was simply looking for the packaged manifest under the wrong folder and giving up. Trims now save on imported characters, keep the real gait-phase labels (left-contact, left-passing, …) for each kept frame, and record the correct source strip. A run whose manifest went missing entirely now falls back to the strip's own geometry and still trims, while a manifest that's genuinely corrupt still refuses loudly instead of quietly guessing. The same lookup fixed approving an imported walk direction, which would have failed the same way.
- **Steer a directional-anchor re-roll with a correction note** — when a directional anchor comes out wrong (say the north-east pose grew a pocket on the arm that has none in every other view), re-rolling it with the same inputs tended to just reproduce the same mistake. Each unlocked anchor tile now has a small **Correction (optional)** box: type what to fix ("no pocket on the right sleeve") and hit **Regenerate**, and the note is appended to that pose's prompt as an explicit override so the new render actually diverges. The button reads **Generate** on the first render and **Regenerate** once candidates exist, the correction is per-direction (so eight different fixes don't collide), and it rides into the candidate's saved prompt so the image preview shows exactly what was asked for. Main-reference iteration is unchanged — it already has its own design-prompt box.
diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsx
index 57ea716c00..c7a0eec933 100644
--- a/client/src/components/sprites/WalkWorkflow.jsx
+++ b/client/src/components/sprites/WalkWorkflow.jsx
@@ -6,6 +6,7 @@ import {
import toast from '../ui/Toast';
import {
approveSpriteWalk, postprocessSpriteWalk, unlockSpriteWalk, reopenSpriteWalk,
+ setSpriteWalkTarget,
} from '../../services/apiSprites.js';
import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
@@ -35,9 +36,14 @@ 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 = playback speed (lower = slower, more
+// 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 };
@@ -127,10 +133,94 @@ function StripLoop({ recordId, stripPreview }) {
);
}
+// Where the resolved target came from, in the user's words. Mirrors the
+// server's describeTargetSource so the label and the 409 message agree.
+const TARGET_SOURCE_LABEL = {
+ app: 'locked by the bound app',
+ set: 'set target',
+ derived: 'from the first approved direction',
+ default: 'default',
+};
+
+/**
+ * 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);
+ const provenance = TARGET_SOURCE_LABEL[target.source] || 'default';
+
+ 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"
+ >
+ {FPS_OPTIONS.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}
+ >
+ {saving ? 'saving…' : provenance}
+ {target.source === 'app' && ` (${target.appId || 'bound app'}) · change it in Publish below`}
+ </span>
+ </div>
+ );
+}
+
function DirectionCard({
recordId, direction, anchorLocked, run, approved, finalized, pending,
onOpenTrimmer, onGenerate, onApprove, onRetry, onReprocess, onReopen,
- reprocessing, cycleLabel,
+ reprocessing, cycleLabel, drift, targetSaving,
}) {
const [confirming, setConfirming] = useState(false);
const [reopening, setReopening] = useState(false);
@@ -140,7 +230,11 @@ function DirectionCard({
// Generate (server truth, since the client pending flag drops once the run is
// persisted). Only 'rendering' has a live Shell session to link to.
const rendering = run?.status === 'rendering';
- const busy = pending || rendering || run?.status === 'postprocessing';
+ // `targetSaving` blocks the render actions without claiming the direction is
+ // rendering: the set's cycle target is mid-PATCH, so a queue now would be
+ // gated against a value the server hasn't persisted yet (409 target mismatch).
+ const inFlight = pending || rendering || run?.status === 'postprocessing';
+ const busy = inFlight || targetSaving;
// Any run that carries a packed strip preview is trimmable — the trim service
// resolves geometry from the run's own manifest/stripPreview regardless of
// on-disk layout (native `runs/`, legacy `grok/`, imported `runs/`, or an
@@ -173,6 +267,25 @@ function DirectionCard({
unapproved candidate can just be regenerated (the Generate button
below). Deliberately not the status==='error' path, which offers a
"Retry postprocess" that 409s for a finalized/approved run. */}
+ {/* This direction is packaged at a geometry the set is no longer targeting
+ (#2985) — surfaced HERE rather than at atlas-compile time, which used to
+ be the first and only place a ragged set showed up. The remedy depends
+ on what the direction still has behind it: an unapproved candidate can
+ be re-derived from its on-disk clip with the Reprocess button below, an
+ approved one has to be reopened first, and an import with no clip needs
+ the source clip imported before it can be re-derived at all. */}
+ {drift && (
+ <p className="text-[10px] text-port-warning border border-port-warning/60 rounded px-1.5 py-1 leading-tight">
+ {[drift.frameCountDrifts && `${drift.frameCount}f`, drift.fpsDrifts && `${drift.fps}fps`]
+ .filter(Boolean).join(' · ')} · re-derive to {cycleLabel}
+ <span className="block text-gray-400">
+ {approved ? 'reopen this direction to re-derive it'
+ : run?.sourceVideoPath ? 'reprocess it from its clip'
+ : 'import this direction\'s source clip to re-derive it'}
+ </span>
+ </p>
+ )}
+
{(approved || candidate) && run?.stripMissing && (
<p className="text-[10px] text-port-error border border-port-error/60 rounded px-1.5 py-1 leading-tight">
Walk strip missing on disk — {finalized ? 'unlock the set to regenerate this direction' : 'regenerate to repack it'}.
@@ -229,7 +342,7 @@ function DirectionCard({
title={anchorLocked ? undefined : 'Lock this direction\'s reference anchor first'}
className="flex items-center gap-1 w-full justify-center px-2 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50"
>
- {busy
+ {inFlight
? <><RefreshCw className="w-3 h-3 animate-spin" /> {run?.status === 'postprocessing' ? 'Packaging…' : 'Rendering…'}</>
: <><Film className="w-3 h-3" /> {candidate ? 'Regenerate' : 'Generate walk'}</>}
</button>
@@ -310,11 +423,24 @@ function DirectionCard({
export default function WalkWorkflow({
record, reference, walk, renders, duration, onDurationChange, onGenerate,
- frameCount = WALK_DEFAULT_FRAME_COUNT, fps = WALK_DEFAULT_FPS,
- onFrameCountChange = () => {}, onFpsChange = () => {},
onOpenTrimmer = () => {}, onChanged,
}) {
const recordId = record.id;
+ // The cycle target is server-resolved (app contract → set pin → first approved
+ // direction → default) so the client never re-derives the precedence chain.
+ // The fallback only covers a walk state fetched by an older client/peer.
+ const target = walk?.walkTarget || {
+ frameCount: WALK_DEFAULT_FRAME_COUNT, fps: WALK_DEFAULT_FPS, source: 'default', drift: [],
+ };
+ const { frameCount, fps } = target;
+ const driftByDirection = useMemo(
+ () => Object.fromEntries((target.drift || []).map((d) => [d.direction, d])),
+ [target.drift],
+ );
+ // Every render action is gated on the target PATCH settling — otherwise the
+ // user picks a new target and clicks Generate before the server has it, and
+ // the queue-time guard 409s on a value they already changed.
+ const [targetSaving, setTargetSaving] = useState(false);
const manifest = reference?.manifest || null;
const runs = walk?.runs || [];
const selection = walk?.selection || null;
@@ -431,8 +557,8 @@ export default function WalkWorkflow({
const approvedCount = Object.values(selection?.directions || {})
.filter((d) => d?.status === 'approved').length;
- const cycleSeconds = (frameCount / fps).toFixed(2);
const cycleLabel = `${frameCount}f @ ${fps}fps`;
+ const driftCount = (target.drift || []).length;
return (
<div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
@@ -477,29 +603,17 @@ export default function WalkWorkflow({
</div>
) : (
<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">
- Frames
- <select
- value={frameCount}
- onChange={(e) => onFrameCountChange(Number(e.target.value))}
- className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"
- >
- {FRAME_COUNT_OPTIONS.map((n) => <option key={n} value={n}>{n}</option>)}
- </select>
- </label>
- <label className="flex items-center gap-1.5 text-xs text-gray-400">
- <span className="flex items-center gap-1"><Gauge className="w-3 h-3" /> Speed</span>
- <select
- value={fps}
- onChange={(e) => onFpsChange(Number(e.target.value))}
- className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"
- >
- {FPS_OPTIONS.map((n) => <option key={n} value={n}>{n} fps</option>)}
- </select>
- </label>
- <label className="flex items-center gap-1.5 text-xs text-gray-400" title="grok renders 6s or 10s clips; length only affects how much source footage the packer has to choose from">
+ <CycleTarget
+ recordId={recordId}
+ target={target}
+ disabled={finalized}
+ onChanged={onChanged}
+ onSavingChange={setTargetSaving}
+ />
+ <label className="flex items-center gap-1.5 text-xs text-gray-400" htmlFor={`walk-clip-${recordId}`} title="grok renders 6s or 10s clips; length only affects how much source footage the packer has to choose from">
Clip
<select
+ id={`walk-clip-${recordId}`}
value={duration}
onChange={(e) => onDurationChange(Number(e.target.value))}
className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"
@@ -507,12 +621,20 @@ export default function WalkWorkflow({
{WALK_DURATIONS.map((d) => <option key={d} value={d}>{d}s</option>)}
</select>
</label>
- <span className="text-[11px] text-gray-500 tabular-nums" title="cycle duration = frames ÷ speed">
- {cycleSeconds}s / cycle
- </span>
</div>
)}
</div>
+
+ {/* Set-level drift summary: visible BEFORE eight renders are spent, rather
+ than as an atlas-compile wall afterwards. Legacy mixed sets (generated
+ back when the count/fps were per-render page state) land here on load. */}
+ {driftCount > 0 && (
+ <p className="text-xs text-port-warning border border-port-warning/60 rounded px-2 py-1.5">
+ {driftCount === 1
+ ? `1 of 8 packaged directions differs from the ${cycleLabel} target — re-derive it before compiling the atlas.`
+ : `${driftCount} of 8 packaged directions differ from the ${cycleLabel} target — re-derive them before compiling the atlas.`}
+ </p>
+ )}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
{(manifest.anchors || []).map((anchor) => (
<DirectionCard
@@ -524,6 +646,8 @@ export default function WalkWorkflow({
approved={selection?.directions?.[anchor.direction]?.status === 'approved'}
finalized={finalized}
pending={Boolean(pendingJobs[anchor.direction])}
+ targetSaving={targetSaving}
+ drift={driftByDirection[anchor.direction] || null}
onOpenTrimmer={onOpenTrimmer}
onGenerate={onGenerate}
onApprove={approve}
diff --git a/client/src/components/sprites/WalkWorkflow.test.jsx b/client/src/components/sprites/WalkWorkflow.test.jsx
index 3fe997839b..1062272a24 100644
--- a/client/src/components/sprites/WalkWorkflow.test.jsx
+++ b/client/src/components/sprites/WalkWorkflow.test.jsx
@@ -1,5 +1,7 @@
import { describe, it, expect, vi } from 'vitest';
-import { render, screen, act } from '@testing-library/react';
+import {
+ render, screen, act, fireEvent,
+} from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
// Coverage for the walk viewer's loop preview (#2924). The load-bearing behavior:
@@ -13,10 +15,11 @@ vi.mock('../../services/apiSprites.js', () => ({
postprocessSpriteWalk: vi.fn(() => Promise.resolve({})),
unlockSpriteWalk: vi.fn(() => Promise.resolve({})),
reopenSpriteWalk: vi.fn(() => Promise.resolve({})),
+ setSpriteWalkTarget: vi.fn(() => Promise.resolve({})),
}));
import WalkWorkflow from './WalkWorkflow';
-import { postprocessSpriteWalk, reopenSpriteWalk } from '../../services/apiSprites.js';
+import { postprocessSpriteWalk, reopenSpriteWalk, setSpriteWalkTarget } from '../../services/apiSprites.js';
const CELL_PX = 96;
@@ -210,17 +213,26 @@ describe('WalkWorkflow loop trimmer link', () => {
// Render the workflow with a single run of the given shape. Router-wrapped so
// the card's <Link> (shown while rendering) resolves in every case.
-const renderRun = (run) => render(
+// `walkTarget` is the server-resolved set-level cycle target (#2985); tests that
+// care about provenance/drift override it, the rest get the plain default.
+const renderRun = (run, { walkTarget, onChanged = vi.fn() } = {}) => render(
<MemoryRouter>
<WalkWorkflow
record={{ id: 'example-walker' }}
reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
- walk={{ runs: [run], selection: { directions: {} }, walkSet: null }}
+ walk={{
+ runs: [run],
+ selection: { directions: {} },
+ walkSet: null,
+ walkTarget: walkTarget || {
+ track: 'walk', frameCount: 12, fps: 10, source: 'default', drift: [],
+ },
+ }}
renders={noRenders()}
duration={2}
onDurationChange={vi.fn()}
onGenerate={vi.fn()}
- onChanged={vi.fn()}
+ onChanged={onChanged}
/>
</MemoryRouter>,
);
@@ -269,17 +281,95 @@ describe('WalkWorkflow observable render', () => {
});
describe('WalkWorkflow authoring controls', () => {
- it('offers Frames, Speed, and grok-real Clip options plus a cycle readout', () => {
+ it('offers a set-level Cycle target, Preview speed, and grok-real Clip options', () => {
renderRun({ id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'x' });
// Clip length is now just grok's real 6s/10s options (shorter was a no-op).
const clip = screen.getByRole('combobox', { name: /Clip/ });
expect([...clip.options].map((o) => o.value)).toEqual(['6', '10']);
- // Frame count + speed controls exist…
- expect(screen.getByRole('combobox', { name: /Frames/ })).toBeTruthy();
- expect(screen.getByRole('combobox', { name: /Speed/ })).toBeTruthy();
+ // Frame count + speed are ONE set-level target now (#2985), not per-render
+ // inputs that can drift between directions.
+ expect(screen.getByRole('combobox', { name: /Cycle target/ })).toBeTruthy();
+ expect(screen.getByRole('combobox', { name: /Preview speed/ })).toBeTruthy();
// …and the cycle-duration readout reflects the defaults (12f / 10fps = 1.20s).
expect(screen.getByText(/1\.20s \/ cycle/)).toBeTruthy();
});
+
+ it('labels the target with where the value came from', () => {
+ renderRun(
+ { id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'x' },
+ { walkTarget: { frameCount: 8, fps: 12, source: 'derived', drift: [] } },
+ );
+ expect(screen.getByText('from the first approved direction')).toBeTruthy();
+ expect(screen.getByRole('combobox', { name: /Cycle target/ }).value).toBe('8');
+ });
+
+ it('renders the target read-only and names the app when the publish binding pins it', () => {
+ renderRun(
+ { id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'x' },
+ {
+ walkTarget: {
+ frameCount: 16, fps: 10, source: 'app', frameCountLocked: true, appId: 'example-game', drift: [],
+ },
+ },
+ );
+ expect(screen.getByRole('combobox', { name: /Cycle target/ }).disabled).toBe(true);
+ expect(screen.getByText(/locked by the bound app \(example-game\)/)).toBeTruthy();
+ // fps is not in the contract, so it stays editable.
+ expect(screen.getByRole('combobox', { name: /Preview speed/ }).disabled).toBe(false);
+ });
+
+ it('saves a new target to the set and refreshes', async () => {
+ const onChanged = vi.fn();
+ renderRun(
+ { id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'x' },
+ { onChanged },
+ );
+ const select = screen.getByRole('combobox', { name: /Cycle target/ });
+ await act(async () => {
+ fireEvent.change(select, { target: { value: '14' } });
+ });
+ expect(setSpriteWalkTarget).toHaveBeenCalledWith(
+ 'example-walker', { frameCount: 14, fps: 10 }, { silent: true },
+ );
+ expect(onChanged).toHaveBeenCalled();
+ });
+});
+
+describe('WalkWorkflow cycle-target drift', () => {
+ const DRIFTED = {
+ walkTarget: {
+ frameCount: 12,
+ fps: 10,
+ source: 'set',
+ drift: [{
+ direction: 'east', frameCount: 8, fps: 10, frameCountDrifts: true, fpsDrifts: false,
+ }],
+ },
+ };
+
+ it('badges a packaged direction that no longer matches the target', () => {
+ renderRun({
+ id: 'walk-east-abc12345',
+ direction: 'east',
+ status: 'candidate',
+ sourceVideoPath: 'runs/walk-east-abc12345/generated/source-video.mp4',
+ stripPreview: { stripPath: 'runs/walk-east-abc12345/generated/strip.png', frameCount: 8, fps: 10, cellWidth: 384, cellHeight: 384 },
+ }, DRIFTED);
+ expect(screen.getByText(/8f · re-derive to 12f @ 10fps/)).toBeTruthy();
+ expect(screen.getByText('reprocess it from its clip')).toBeTruthy();
+ // …and a set-level summary so it is visible before eight renders are spent.
+ expect(screen.getByText(/1 of 8 packaged directions differs from the 12f @ 10fps target/)).toBeTruthy();
+ });
+
+ it('points a drifted direction with no source clip at an import instead', () => {
+ renderRun({
+ id: 'imported-east',
+ direction: 'east',
+ status: 'candidate',
+ stripPreview: { stripPath: 'runs/imported-east/generated/strip.png', frameCount: 8, fps: 10, cellWidth: 384, cellHeight: 384 },
+ }, DRIFTED);
+ expect(screen.getByText('import this direction\'s source clip to re-derive it')).toBeTruthy();
+ });
});
describe('WalkWorkflow reprocess + reopen', () => {
diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsx
index 14575cb20f..90d4344f84 100644
--- a/client/src/pages/Sprites.jsx
+++ b/client/src/pages/Sprites.jsx
@@ -466,13 +466,16 @@ export default function Sprites() {
}, replace ? { replace: true } : undefined);
}, [setSearchParams]);
- // Clip length + frame count + playback speed live here rather than inside
- // WalkWorkflow so a Regenerate fired from an asset card honors what the user
- // picked in the walk panel instead of silently falling back to server
- // defaults. Frame count = cycle smoothness; fps = walk speed.
+ // Clip length is a per-render choice (how much source footage grok gives the
+ // packer) and stays page state so a Regenerate fired from an asset card honors
+ // what the user picked in the walk panel. Frame count + preview fps are NOT:
+ // they are pinned per walk SET on the server (#2985), because every direction
+ // in one atlas must share them, so both read from the resolved walk target.
const [duration, setDuration] = useState(WALK_DEFAULT_DURATION);
- const [walkFrameCount, setWalkFrameCount] = useState(WALK_DEFAULT_FRAME_COUNT);
- const [walkFps, setWalkFps] = useState(WALK_DEFAULT_FPS);
+ // Scalars, not the target object — `detail` gets a fresh identity on every
+ // refetch, which would rebuild the memoized generate action each poll.
+ const walkFrameCount = detail?.walk?.walkTarget?.frameCount ?? WALK_DEFAULT_FRAME_COUNT;
+ const walkFps = detail?.walk?.walkTarget?.fps ?? WALK_DEFAULT_FPS;
// Image-backend availability + the selected backend `mode` are page-owned
// (#2938): both ReferenceWorkflow's picker and the asset collection's anchor
@@ -704,10 +707,6 @@ export default function Sprites() {
renders={walkRenders}
duration={duration}
onDurationChange={setDuration}
- frameCount={walkFrameCount}
- onFrameCountChange={setWalkFrameCount}
- fps={walkFps}
- onFpsChange={setWalkFps}
onGenerate={generateWalk}
onOpenTrimmer={openTrimmer}
onChanged={onWorkflowChanged}
diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.js
index 15b678e8ee..1893f73224 100644
--- a/client/src/services/apiSprites.js
+++ b/client/src/services/apiSprites.js
@@ -110,6 +110,13 @@ export const postprocessSpriteWalk = (id, body, options = {}) => request(`/sprit
method: 'POST', body: JSON.stringify(body), ...options,
});
+// Pin the walk set's cycle target (#2985). Body: { frameCount, fps }. Returns
+// the refreshed walk state, whose `walkTarget` carries the resolved value, its
+// provenance, and the packaged directions that now drift from it.
+export const setSpriteWalkTarget = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/walk/target`, {
+ method: 'PUT', body: JSON.stringify(body), ...options,
+});
+
// Un-freeze a finalized walk set so its directions can be regenerated/re-approved.
export const unlockSpriteWalk = (id, options = {}) => request(`/sprites/${encodeURIComponent(id)}/walk/unlock`, {
method: 'POST', ...options,
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 6b849573d4..d2f2ac4985 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1113,11 +1113,23 @@ export const spriteWalkGenerateSchema = z.object({
// by frameCount/fps below.
duration: z.union([z.literal(6), z.literal(10)]).optional(),
// Deterministic-postprocess knobs (not grok's): how many frames the packed
- // cycle holds and how fast it plays back. Omitted → service defaults.
+ // cycle holds and how fast it plays back. Omitted → the set's pinned cycle
+ // target; a value that DISAGREES with that target is refused with 409
+ // WALK_TARGET_MISMATCH (#2985), since every direction in one atlas must share
+ // the geometry.
frameCount: spriteWalkFrameCountSchema.optional(),
fps: spriteWalkFpsSchema.optional(),
});
+// Pin the walk track's cycle target at the SET level (#2985). Both knobs are
+// required: the target is one atomic set-level decision, and a partial write
+// would leave "which value did I actually pin?" ambiguous on a record every
+// later render is gated against.
+export const spriteWalkTargetSchema = z.object({
+ frameCount: spriteWalkFrameCountSchema,
+ fps: spriteWalkFpsSchema,
+});
+
export const spriteWalkApproveSchema = z.object({
direction: spriteWalkDirectionSchema,
runId: spriteWalkRunIdSchema,
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index 7ea9a95e7f..6ae04d5bb2 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -24,6 +24,7 @@ import {
spriteWalkApproveSchema,
spriteWalkReopenSchema,
spriteWalkPostprocessSchema,
+ spriteWalkTargetSchema,
spriteWalkTrimSchema,
spritePublishBindingSchema,
spriteAtlasCompileSchema,
@@ -43,7 +44,7 @@ import {
import { resolveSpriteAssetPrompt } from '../services/sprites/assetPrompt.js';
import {
getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
- reopenWalkDirection,
+ reopenWalkDirection, setWalkTarget,
} from '../services/sprites/walk.js';
import { saveLoopTrim } from '../services/sprites/walkTrims.js';
import { compileAtlas, getAtlasState } from '../services/sprites/atlas.js';
@@ -184,6 +185,14 @@ router.post('/:id/walk/reopen', asyncHandler(async (req, res) => {
res.json(await reopenWalkDirection(req.params.id, body));
}));
+// Pin the walk track's cycle target for the whole set (#2985) — the deliberate
+// set-level action that replaces the old per-render frame-count/fps sliders.
+// 409s when the publish binding's runtime contract pins a different value.
+router.put('/:id/walk/target', asyncHandler(async (req, res) => {
+ const body = validateRequest(spriteWalkTargetSchema, req.body);
+ res.json(await setWalkTarget(req.params.id, body));
+}));
+
// Re-run the deterministic postprocess for a run whose video already landed
// (crash recovery / determinism verification). No AI call involved.
router.post('/:id/walk/postprocess', asyncHandler(async (req, res) => {
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index 0b73b1d2e5..8c60c7dd61 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -34,6 +34,12 @@ vi.mock('../services/sprites/walk.js', () => ({
rerunWalkPostprocess: vi.fn(async () => ({ id: 'walk-east-0a1b2c3d', status: 'candidate' })),
unlockWalkSet: vi.fn(async () => ({ runs: [], selection: { status: 'in-progress' }, walkSet: null })),
reopenWalkDirection: vi.fn(async () => ({ runs: [], selection: { status: 'in-progress' }, walkSet: null })),
+ setWalkTarget: vi.fn(async () => ({
+ runs: [],
+ selection: { status: 'in-progress' },
+ walkSet: null,
+ walkTarget: { track: 'walk', frameCount: 14, fps: 8, source: 'set' },
+ })),
}));
vi.mock('../services/sprites/walkTrims.js', () => ({
@@ -416,6 +422,22 @@ describe('sprites routes', () => {
.send({ direction: 'east', fps: 99 })).status).toBe(400);
});
+ it('PUT /:id/walk/target pins the set-level cycle target and bounds it', async () => {
+ const r = await request(app).put('/api/sprites/pioneer/walk/target')
+ .send({ frameCount: 14, fps: 8 });
+ expect(r.status).toBe(200);
+ expect(r.body.walkTarget).toMatchObject({ frameCount: 14, fps: 8, source: 'set' });
+ expect(walk.setWalkTarget).toHaveBeenCalledWith('pioneer', { frameCount: 14, fps: 8 });
+ // Both knobs are required — the target is one atomic set-level decision.
+ expect((await request(app).put('/api/sprites/pioneer/walk/target')
+ .send({ frameCount: 14 })).status).toBe(400);
+ // …and both are range-checked against walkBounds.
+ expect((await request(app).put('/api/sprites/pioneer/walk/target')
+ .send({ frameCount: 32, fps: 8 })).status).toBe(400);
+ expect((await request(app).put('/api/sprites/pioneer/walk/target')
+ .send({ frameCount: 14, fps: 99 })).status).toBe(400);
+ });
+
it('POST /:id/walk/reopen validates the direction and delegates', async () => {
const r = await request(app).post('/api/sprites/pioneer/walk/reopen')
.send({ direction: 'east' });
diff --git a/server/services/sprites/animationTargets.js b/server/services/sprites/animationTargets.js
new file mode 100644
index 0000000000..b524278471
--- /dev/null
+++ b/server/services/sprites/animationTargets.js
@@ -0,0 +1,169 @@
+/**
+ * Sprites — per-track animation targets (issue #2985).
+ *
+ * A walk cycle occupies N contiguous atlas columns × 8 direction rows, so every
+ * direction in ONE set must share a frame count and a playback fps — the atlas
+ * is a rectangular grid and a ragged set cannot compile. That invariant used to
+ * surface only at compile time (atlas.js), after eight renders and eight
+ * approvals were already spent. This module makes the target explicit and
+ * resolvable up front so it can be enforced when each render is QUEUED.
+ *
+ * The target is **track-keyed**, never record-level: uniformity is a property of
+ * one animation track, not of a character. A future portable-scanner action
+ * (4 frames) or an ambient loop (3 frames) legitimately differs from the walk,
+ * so the persisted shape is
+ *
+ * "animationTargets": { "walk": { "frameCount": 12, "fps": 10, "source": "set" } }
+ *
+ * and an unrecognized sibling track key MUST round-trip untouched (see
+ * `withTrackTarget`) — adding a track later is additive, not a reshape. Packing
+ * tracks of DIFFERING lengths into one atlas needs a column-span descriptor and
+ * is deliberately out of scope here.
+ *
+ * Dependency-free apart from the sharp-free `walkBounds` leaf, so the service
+ * layer and the (native-dep-free) validation graph can both reach it.
+ */
+
+import {
+ WALK_DEFAULT_FRAME_COUNT, WALK_DEFAULT_FPS,
+ WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT, WALK_MIN_FPS, WALK_MAX_FPS,
+} from './walkBounds.js';
+
+/** The only animation track that exists today. */
+export const WALK_TRACK = 'walk';
+
+/**
+ * Which `publishBinding.runtimeContract` field pins which knob, per track. The
+ * contract is the bound app's declared expectation for its own atlas (#2982) —
+ * a stronger authority than any per-render pick — and lands independently of
+ * this module, so every read is defensive: an absent contract simply falls
+ * through to the next rung of the precedence chain. A future track adds its own
+ * row here rather than reshaping the resolver.
+ */
+const TRACK_CONTRACT_FIELDS = {
+ [WALK_TRACK]: { frameCount: 'walkFrameCount', fps: 'walkFps' },
+};
+
+const intInRange = (v, min, max) => (Number.isInteger(v) && v >= min && v <= max ? v : null);
+const readFrameCount = (v) => intInRange(v, WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT);
+const readFps = (v) => intInRange(v, WALK_MIN_FPS, WALK_MAX_FPS);
+
+/**
+ * Resolve one track's pinned target from the precedence chain, newest authority
+ * first. `source` names the winning rung so the UI can explain itself instead of
+ * re-deriving the precedence:
+ *
+ * 'app' — the bound app's `runtimeContract` (#2982). The app decides what
+ * its atlas may hold, so this cannot be overridden per render.
+ * 'set' — an explicit `animationTargets.<track>` the user pinned.
+ * 'derived' — the first packaged direction's geometry (the same first-wins
+ * rule atlas.js already applies), auto-pinned on first resolve so
+ * it stops being implicit. Persisted with `source: 'derived'` so a
+ * value PortOS inferred never masquerades as one the user chose.
+ * 'default' — WALK_DEFAULT_FRAME_COUNT / WALK_DEFAULT_FPS.
+ *
+ * Out-of-range or non-integer values at any rung are ignored rather than
+ * clamped: a hand-edited record must not silently pin a value the packer would
+ * quietly rewrite. Each knob falls through independently (an app that pins only
+ * the frame count still takes its fps from the set/derived/default rungs), but
+ * `source` names the highest rung that supplied EITHER knob, and
+ * `frameCountLocked` / `fpsLocked` say precisely which the app nailed down.
+ *
+ * @param {object} input
+ * @param {string} [input.track] Track key (only 'walk' exists today).
+ * @param {object} [input.runtimeContract] `publishBinding.runtimeContract`, if any.
+ * @param {object} [input.animationTargets] The selection record's block.
+ * @param {Array<{direction?: string, frameCount?: number, fps?: number}>} [input.packagedCycles]
+ * Packaged directions in atlas order — first entry with a usable value wins.
+ * @returns {{track: string, frameCount: number, fps: number, source: string,
+ * frameCountLocked: boolean, fpsLocked: boolean}}
+ */
+export function resolveAnimationTarget({
+ track = WALK_TRACK,
+ runtimeContract = null,
+ animationTargets = null,
+ packagedCycles = [],
+} = {}) {
+ const fields = TRACK_CONTRACT_FIELDS[track] || {};
+ const appCount = fields.frameCount ? readFrameCount(runtimeContract?.[fields.frameCount]) : null;
+ const appFps = fields.fps ? readFps(runtimeContract?.[fields.fps]) : null;
+
+ const pinned = animationTargets?.[track] || null;
+ const setCount = readFrameCount(pinned?.frameCount);
+ const setFps = readFps(pinned?.fps);
+
+ const derivedCount = firstDefined(packagedCycles, (c) => readFrameCount(c?.frameCount));
+ const derivedFps = firstDefined(packagedCycles, (c) => readFps(c?.fps));
+
+ let source = 'default';
+ if (derivedCount !== null || derivedFps !== null) source = 'derived';
+ // A block PortOS auto-pinned from the set carries `source: 'derived'`; anything
+ // else (including a legacy block written before this field existed) is a
+ // deliberate user pin and reports as 'set'.
+ if (setCount !== null || setFps !== null) source = pinned?.source === 'derived' ? 'derived' : 'set';
+ if (appCount !== null || appFps !== null) source = 'app';
+
+ return {
+ track,
+ frameCount: appCount ?? setCount ?? derivedCount ?? WALK_DEFAULT_FRAME_COUNT,
+ fps: appFps ?? setFps ?? derivedFps ?? WALK_DEFAULT_FPS,
+ source,
+ frameCountLocked: appCount !== null,
+ fpsLocked: appFps !== null,
+ };
+}
+
+function firstDefined(list, read) {
+ for (const item of list || []) {
+ const value = read(item);
+ if (value !== null) return value;
+ }
+ return null;
+}
+
+/**
+ * Merge one track's target into an existing `animationTargets` map WITHOUT
+ * disturbing sibling tracks. Load-bearing forward-compatibility: a peer (or a
+ * later PortOS) may have written a `scanner` / ambient entry this build knows
+ * nothing about, and a naive `{ walk: … }` overwrite would silently drop it.
+ */
+export function withTrackTarget(animationTargets, track, { frameCount, fps, source }) {
+ const existing = (animationTargets && typeof animationTargets === 'object' && !Array.isArray(animationTargets))
+ ? animationTargets
+ : {};
+ return { ...existing, [track]: { frameCount, fps, source } };
+}
+
+/**
+ * Packaged directions whose geometry disagrees with the resolved target — the
+ * set is compilable only when this is empty. Reported per direction so the UI
+ * can badge exactly which ones need re-deriving, instead of the user discovering
+ * it at atlas-compile time. A cycle with no usable geometry (an import that
+ * never declared one) is not "drift" — there is nothing to compare.
+ */
+export function targetDrift(target, packagedCycles = []) {
+ return (packagedCycles || []).flatMap((cycle) => {
+ const frameCount = readFrameCount(cycle?.frameCount);
+ const fps = readFps(cycle?.fps);
+ if (frameCount === null && fps === null) return [];
+ const countDrifts = frameCount !== null && frameCount !== target.frameCount;
+ const fpsDrifts = fps !== null && fps !== target.fps;
+ if (!countDrifts && !fpsDrifts) return [];
+ return [{
+ direction: cycle.direction, frameCount, fps, frameCountDrifts: countDrifts, fpsDrifts,
+ }];
+ });
+}
+
+/**
+ * Human-readable provenance, shared by the 409 message and the UI label so the
+ * two can never describe the same target differently.
+ */
+export function describeTargetSource(target, appName = null) {
+ switch (target.source) {
+ case 'app': return `locked by ${appName || 'the bound app'}`;
+ case 'set': return 'set target';
+ case 'derived': return 'from the first approved direction';
+ default: return 'default';
+ }
+}
diff --git a/server/services/sprites/animationTargets.test.js b/server/services/sprites/animationTargets.test.js
new file mode 100644
index 0000000000..596e8d662e
--- /dev/null
+++ b/server/services/sprites/animationTargets.test.js
@@ -0,0 +1,139 @@
+/**
+ * Per-track animation targets (#2985) — the pure precedence chain, the
+ * sibling-preserving merge, and drift detection. The service-level wiring
+ * (queue-time enforcement, PUT /walk/target, lazy write-back) is covered by
+ * walk.test.js; this file pins the rules those depend on.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ WALK_TRACK, resolveAnimationTarget, withTrackTarget, targetDrift, describeTargetSource,
+} from './animationTargets.js';
+
+describe('resolveAnimationTarget precedence', () => {
+ it('falls back to the documented defaults when nothing is pinned or packaged', () => {
+ expect(resolveAnimationTarget()).toMatchObject({
+ track: WALK_TRACK, frameCount: 12, fps: 10, source: 'default', frameCountLocked: false,
+ });
+ });
+
+ it('derives from the FIRST packaged direction, mirroring the compiler\'s first-wins rule', () => {
+ expect(resolveAnimationTarget({
+ packagedCycles: [
+ { direction: 'south', frameCount: 8, fps: 12 },
+ { direction: 'east', frameCount: 16, fps: 6 },
+ ],
+ })).toMatchObject({ frameCount: 8, fps: 12, source: 'derived' });
+ });
+
+ it('prefers an explicit set pin over the derived geometry', () => {
+ expect(resolveAnimationTarget({
+ animationTargets: { walk: { frameCount: 14, fps: 8, source: 'set' } },
+ packagedCycles: [{ direction: 'south', frameCount: 8, fps: 12 }],
+ })).toMatchObject({ frameCount: 14, fps: 8, source: 'set' });
+ });
+
+ it('reports an auto-pinned block as "derived", not as a user-chosen target', () => {
+ // The lazy write-back stamps `source: 'derived'` so a value PortOS inferred
+ // never masquerades in the UI as one the user deliberately picked.
+ expect(resolveAnimationTarget({
+ animationTargets: { walk: { frameCount: 8, fps: 12, source: 'derived' } },
+ })).toMatchObject({ frameCount: 8, fps: 12, source: 'derived' });
+ });
+
+ it('treats a legacy pin with no source field as a user-set target', () => {
+ expect(resolveAnimationTarget({
+ animationTargets: { walk: { frameCount: 14, fps: 8 } },
+ })).toMatchObject({ source: 'set' });
+ });
+
+ it('lets the app contract beat every other rung and marks the knob locked', () => {
+ expect(resolveAnimationTarget({
+ runtimeContract: { walkFrameCount: 16 },
+ animationTargets: { walk: { frameCount: 14, fps: 8, source: 'set' } },
+ packagedCycles: [{ direction: 'south', frameCount: 8, fps: 12 }],
+ })).toMatchObject({
+ // The contract pins only the frame count today — fps still falls through
+ // to the set pin, but the target as a whole reports as app-authored.
+ frameCount: 16, fps: 8, source: 'app', frameCountLocked: true, fpsLocked: false,
+ });
+ });
+
+ it('honors a contract that also pins fps', () => {
+ expect(resolveAnimationTarget({
+ runtimeContract: { walkFrameCount: 16, walkFps: 24 },
+ })).toMatchObject({ frameCount: 16, fps: 24, fpsLocked: true });
+ });
+
+ it('ignores out-of-range and non-integer values at every rung instead of clamping them', () => {
+ // A hand-edited record must not silently pin something the packer would
+ // quietly rewrite — the rung is skipped, not coerced.
+ expect(resolveAnimationTarget({
+ runtimeContract: { walkFrameCount: 99 },
+ animationTargets: { walk: { frameCount: 2, fps: 'fast' } },
+ packagedCycles: [{ direction: 'south', frameCount: 12.5, fps: 0 }],
+ })).toMatchObject({ frameCount: 12, fps: 10, source: 'default', frameCountLocked: false });
+ });
+
+ it('ignores an unrelated track\'s pin when resolving walk', () => {
+ expect(resolveAnimationTarget({
+ animationTargets: { scanner: { frameCount: 6, fps: 4 } },
+ })).toMatchObject({ frameCount: 12, fps: 10, source: 'default' });
+ });
+});
+
+describe('withTrackTarget', () => {
+ it('preserves an unrecognized sibling track key on write', () => {
+ // Forward-compat: a newer PortOS (or a peer) may have written a track this
+ // build knows nothing about — a naive overwrite would silently drop it.
+ const merged = withTrackTarget(
+ { scanner: { frameCount: 4, fps: 6, source: 'set' } },
+ WALK_TRACK,
+ { frameCount: 12, fps: 10, source: 'set' },
+ );
+ expect(merged).toEqual({
+ scanner: { frameCount: 4, fps: 6, source: 'set' },
+ walk: { frameCount: 12, fps: 10, source: 'set' },
+ });
+ });
+
+ it('tolerates a missing or malformed map', () => {
+ expect(withTrackTarget(null, WALK_TRACK, { frameCount: 12, fps: 10, source: 'set' }))
+ .toEqual({ walk: { frameCount: 12, fps: 10, source: 'set' } });
+ expect(withTrackTarget(['nope'], WALK_TRACK, { frameCount: 12, fps: 10, source: 'set' }))
+ .toEqual({ walk: { frameCount: 12, fps: 10, source: 'set' } });
+ });
+});
+
+describe('targetDrift', () => {
+ const target = { frameCount: 12, fps: 10 };
+
+ it('reports only the directions that disagree, and which knob disagrees', () => {
+ expect(targetDrift(target, [
+ { direction: 'south', frameCount: 12, fps: 10 },
+ { direction: 'east', frameCount: 8, fps: 10 },
+ { direction: 'west', frameCount: 12, fps: 24 },
+ ])).toEqual([
+ {
+ direction: 'east', frameCount: 8, fps: 10, frameCountDrifts: true, fpsDrifts: false,
+ },
+ {
+ direction: 'west', frameCount: 12, fps: 24, frameCountDrifts: false, fpsDrifts: true,
+ },
+ ]);
+ });
+
+ it('does not call a direction with no declared geometry "drifted"', () => {
+ expect(targetDrift(target, [{ direction: 'south' }])).toEqual([]);
+ });
+});
+
+describe('describeTargetSource', () => {
+ it('names the winning rung in the user\'s words', () => {
+ expect(describeTargetSource({ source: 'app' }, 'example-game')).toBe('locked by example-game');
+ expect(describeTargetSource({ source: 'app' })).toBe('locked by the bound app');
+ expect(describeTargetSource({ source: 'set' })).toBe('set target');
+ expect(describeTargetSource({ source: 'derived' })).toBe('from the first approved direction');
+ expect(describeTargetSource({ source: 'default' })).toBe('default');
+ });
+});
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 54c3df3b59..8da2a434cf 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -28,7 +28,7 @@ import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { executeTuiRun } from '../../lib/tuiPromptRunner.js';
import { GROK_TUI_ID } from '../../lib/grok.js';
import { getSettings } from '../settings.js';
-import { updateRecord } from './records.js';
+import { getRecord, updateRecord } from './records.js';
import {
spriteDir, resolveSpriteAssetPath, toRecordRelativeAssetPath, RUN_DIR_MATCH,
} from './paths.js';
@@ -40,6 +40,9 @@ import {
WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT, WALK_MIN_FPS, WALK_MAX_FPS,
clampFrameCount, clampFps,
} from './walkPostprocess.js';
+import {
+ WALK_TRACK, resolveAnimationTarget, withTrackTarget, targetDrift, describeTargetSource,
+} from './animationTargets.js';
import { GROK_VIDEO_DURATIONS } from '../videoGen/grok.js';
// grok's image_to_video honors only 6s/10s and clamps shorter requests to ~6s,
@@ -110,6 +113,11 @@ function seedSelection(recordId) {
kind: 'reviewed-directional-walk-selection',
characterId: recordId,
status: 'in-progress',
+ // Per-track cycle targets (#2985), keyed by animation track — `walk` is the
+ // only member today. Seeded EMPTY and filled lazily on first resolve so a
+ // selection record stays byte-identical to what an older peer expects until
+ // there is an actual target to pin.
+ animationTargets: {},
directions: {},
};
}
@@ -343,9 +351,61 @@ async function loadRunForEntry(recordId, direction, entry) {
return loadRedrawRun(recordId, direction, entry);
}
+/**
+ * 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.
+ */
+function packagedCyclesFrom(runs, approvedDirections) {
+ return SPRITE_DIRECTIONS.flatMap((direction) => {
+ const forDirection = runs.filter((r) => r.direction === direction && r.stripPreview);
+ const approvedRunId = approvedDirections?.[direction]?.runId;
+ const run = forDirection.find((r) => r.id === approvedRunId)
+ || forDirection.find((r) => r.status === 'approved')
+ || forDirection.find((r) => r.status === 'candidate');
+ if (!run) return [];
+ return [{
+ direction,
+ frameCount: run.frameCount ?? run.stripPreview?.frameCount,
+ fps: run.fps ?? run.stripPreview?.fps,
+ }];
+ });
+}
+
+/**
+ * Resolve the walk track's pinned cycle target for a record, plus the packaged
+ * directions that disagree with it. Pure assembly over state the caller already
+ * loaded — `getWalkState` stamps the result so the client never re-derives the
+ * precedence chain, and the queue-time guards below compare against it.
+ */
+async function resolveWalkTargetFor(recordId, { selection, runs, approvedDirections }) {
+ // Read the app contract defensively: `publishBinding.runtimeContract` lands
+ // with #2982 and may be absent on this install, on an older peer's record, or
+ // on any record with no binding at all.
+ const record = await getRecord(recordId);
+ const packagedCycles = packagedCyclesFrom(runs, approvedDirections);
+ const target = resolveAnimationTarget({
+ track: WALK_TRACK,
+ runtimeContract: record?.publishBinding?.runtimeContract || null,
+ animationTargets: selection?.animationTargets,
+ packagedCycles,
+ });
+ return {
+ ...target,
+ appId: record?.publishBinding?.appId || null,
+ drift: targetDrift(target, packagedCycles),
+ };
+}
+
/**
* Walk-workflow view for the detail endpoint: every animation run (newest
- * first), the per-direction selection, and the finalized set when present.
+ * first), the per-direction selection, the resolved cycle target, and the
+ * finalized set when present.
*
* The selection (or the finalized walk set) is the index: each approved
* direction resolves through `loadRunForEntry`, whatever layout it names.
@@ -407,7 +467,104 @@ export async function getWalkState(recordId) {
// Stamp the imported flag so the client reads intent (`walkSet.imported`)
// instead of re-deriving the source-pipeline path convention itself.
const stampedWalkSet = walkSet ? { ...walkSet, imported: isImportedWalkSet(walkSet) } : null;
- return { runs: allRuns, selection, walkSet: stampedWalkSet };
+ const walkTarget = await resolveWalkTargetFor(recordId, {
+ selection, runs: allRuns, approvedDirections,
+ });
+ return {
+ runs: allRuns, selection, walkSet: stampedWalkSet, walkTarget,
+ };
+}
+
+/**
+ * Refuse a render/reprocess whose cycle geometry disagrees with the set's pinned
+ * target (#2985). Rejecting rather than clamping is deliberate: a silent clamp
+ * hands back an artifact the user did not ask for with no explanation, and the
+ * atlas would still refuse to compile later. Enforced server-side because the
+ * API is directly reachable — client gating alone would not hold.
+ *
+ * This moves the FIRST point of detection earlier; it does not move the
+ * invariant. atlas.js keeps its own compile-time checks as the backstop for
+ * imported and legacy sets that never passed this gate.
+ */
+function assertWalkTargetMatch(target, { frameCount, fps }) {
+ if (frameCount === target.frameCount && fps === target.fps) return;
+ throw new ServerError(
+ `This walk set targets ${target.frameCount} frames @ ${target.fps}fps (${describeTargetSource(target, target.appId)}). `
+ + `Requested ${frameCount} frames @ ${fps}fps — change the set's cycle target, `
+ + `or render at ${target.frameCount} frames @ ${target.fps}fps.`,
+ { status: 409, code: 'WALK_TARGET_MISMATCH' },
+ );
+}
+
+/**
+ * Write an inferred ('derived') target back onto the selection the first time a
+ * write path resolves one, so the value stops being implicit — the same
+ * first-approved-direction rule the compiler applies, but recorded. Deliberately
+ * lazy (write-on-first-resolve from a write path, never from a read) rather than
+ * an eager backfill, so a record an older peer holds stays byte-identical until
+ * PortOS actually acts on it. Never persists an 'app' target: the contract is
+ * the app's to change, and copying it here would strand a stale value on the
+ * record when the binding moves.
+ *
+ * Callers must already hold the per-record write tail.
+ */
+async function pinDerivedWalkTarget(recordId, target) {
+ if (target.source !== 'derived') return;
+ // A 'derived' target means the set already HAS packaged geometry, so the walk
+ // is underway even when no direction is approved yet — seed the selection
+ // rather than skipping the pin and letting the target stay implicit.
+ const selection = (await loadSelection(recordId)) || seedSelection(recordId);
+ const pinned = selection.animationTargets?.[WALK_TRACK];
+ if (pinned?.frameCount === target.frameCount && pinned?.fps === target.fps) return;
+ selection.animationTargets = withTrackTarget(selection.animationTargets, WALK_TRACK, {
+ frameCount: target.frameCount, fps: target.fps, source: 'derived',
+ });
+ await ensureDir(join(spriteDir(recordId), 'walk'));
+ await atomicWrite(join(spriteDir(recordId), selectionRelPath(recordId)), selection);
+ console.log(`📌 sprite walk target pinned for ${recordId} · ${target.frameCount}f @ ${target.fps}fps (derived)`);
+}
+
+/**
+ * Pin the walk track's cycle target explicitly — a deliberate SET-level action,
+ * not a per-render slider. Changing it does not mutate existing runs; it makes
+ * already-packaged directions *drift*, which `getWalkState`'s `walkTarget.drift`
+ * surfaces per direction so they can be re-derived from their clips.
+ *
+ * Refused when the bound app's `runtimeContract` pins a different frame count:
+ * changing the target then means changing the binding, which is the honest
+ * requirement.
+ */
+export function setWalkTarget(recordId, body) {
+ return walkWriteTail(recordId, () => setWalkTargetImpl(recordId, body));
+}
+
+async function setWalkTargetImpl(recordId, { frameCount, fps }) {
+ await requireCharacter(recordId);
+ await requireUnfinalized(recordId);
+ const state = await getWalkState(recordId);
+ const { walkTarget } = state;
+ if (walkTarget.frameCountLocked && walkTarget.frameCount !== frameCount) {
+ throw new ServerError(
+ `Frame count is locked to ${walkTarget.frameCount} by the publish binding (${walkTarget.appId || 'bound app'}) — change the binding's runtime contract to target ${frameCount}.`,
+ { status: 409, code: 'WALK_TARGET_LOCKED' },
+ );
+ }
+ if (walkTarget.fpsLocked && walkTarget.fps !== fps) {
+ throw new ServerError(
+ `Playback fps is locked to ${walkTarget.fps} by the publish binding (${walkTarget.appId || 'bound app'}) — change the binding's runtime contract to target ${fps}.`,
+ { status: 409, code: 'WALK_TARGET_LOCKED' },
+ );
+ }
+ const selection = (await loadSelection(recordId)) || seedSelection(recordId);
+ // `withTrackTarget` merges rather than replaces so a sibling track key written
+ // by a newer PortOS (or a peer) round-trips untouched.
+ selection.animationTargets = withTrackTarget(selection.animationTargets, WALK_TRACK, {
+ frameCount, fps, source: 'set',
+ });
+ await ensureDir(join(spriteDir(recordId), 'walk'));
+ await atomicWrite(join(spriteDir(recordId), selectionRelPath(recordId)), selection);
+ console.log(`🎯 sprite walk target set for ${recordId} · ${frameCount}f @ ${fps}fps`);
+ return getWalkState(recordId);
}
/**
@@ -446,10 +603,17 @@ async function startWalkGenerationImpl(recordId, body) {
// second paid grok render for the same direction. Serialized by the write tail,
// so no TOCTOU. getWalkState normalizes a stale 'rendering' run (server died
// mid-render) to 'error', so this blocks only a genuinely live render.
- const { runs: inFlight } = await getWalkState(recordId);
+ const { runs: inFlight, walkTarget } = await getWalkState(recordId);
if (inFlight.some((r) => r.direction === direction && (r.status === 'rendering' || r.status === 'postprocessing'))) {
throw new ServerError(`A walk render for ${direction} is already in progress`, { status: 409, code: 'WALK_RENDER_IN_PROGRESS' });
}
+ // Cycle geometry is pinned at the SET level (#2985) — every direction in one
+ // atlas must share it. An omitted count/fps adopts the target; a disagreeing
+ // one is refused here rather than at atlas-compile time, eight renders later.
+ const frameCount = body.frameCount === undefined ? walkTarget.frameCount : clampFrameCount(body.frameCount);
+ const fps = body.fps === undefined ? walkTarget.fps : clampFps(body.fps);
+ assertWalkTargetMatch(walkTarget, { frameCount, fps });
+ await pinDerivedWalkTarget(recordId, walkTarget);
const anchorAbs = resolveSpriteAssetPath(recordId, anchor.path);
if (!await pathExists(anchorAbs)) {
throw new ServerError('Locked anchor file is missing on disk', { status: 500, code: 'ANCHOR_MISSING' });
@@ -474,11 +638,9 @@ async function startWalkGenerationImpl(recordId, body) {
const duration = GROK_VIDEO_DURATIONS.includes(Number(body.duration)) ? Number(body.duration) : WALK_DEFAULT_DURATION;
// Frame count + playback fps are the deterministic-postprocess knobs, not the
// grok clip's — grok animates the same clip regardless, and the packer
- // resamples/labels the cycle afterward. Stored on the run so the completion
- // hook's packageRun (and any later reprocess) applies the count/fps the user
- // chose at generate time. Clamped here so a bad body can't reach the packer.
- const frameCount = clampFrameCount(body.frameCount ?? WALK_DEFAULT_FRAME_COUNT);
- const fps = clampFps(body.fps ?? WALK_DEFAULT_FPS);
+ // resamples/labels the cycle afterward. Resolved from the set target above and
+ // stored on the run so the completion hook's packageRun (and any later
+ // reprocess) applies exactly what the set is pinned to.
const prompt = buildWalkVideoPrompt({ name: record.name, direction, chromaKey });
const videoAbs = join(generatedAbs, 'source-video.mp4');
const grokPath = settings.imageGen?.grok?.grokPath;
@@ -672,11 +834,17 @@ async function rerunWalkPostprocessImpl(recordId, runId, overrides) {
if (!await pathExists(videoAbs)) {
throw new ServerError('Run has no source video yet', { status: 409, code: 'VIDEO_NOT_READY' });
}
- // Reprocess the SAME on-disk clip at a (possibly) new frame count / playback
- // speed — no grok call, no regeneration. packageRun's `?? run.x ?? default`
- // merge treats an absent override identically to `undefined`, so pass them
- // straight through — no need to strip the undefined fields first.
- await packageRun(recordId, run, overrides);
+ // 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.
+ const { walkTarget } = await getWalkState(recordId);
+ const frameCount = overrides.frameCount === undefined ? walkTarget.frameCount : clampFrameCount(overrides.frameCount);
+ const fps = overrides.fps === undefined ? walkTarget.fps : clampFps(overrides.fps);
+ assertWalkTargetMatch(walkTarget, { frameCount, fps });
+ await pinDerivedWalkTarget(recordId, walkTarget);
+ // Reprocess the SAME on-disk clip at the pinned frame count / playback speed —
+ // no grok call, no regeneration.
+ await packageRun(recordId, run, { frameCount, fps });
await saveRunRecord(recordId, run);
if (run.status === 'error') {
throw new ServerError(`Postprocess failed: ${run.postprocessError}`, { status: 422, code: 'POSTPROCESS_FAILED' });
@@ -751,7 +919,14 @@ async function unlockWalkSetImpl(recordId) {
// set gone each direction would still read `approved` from the old selection
// and keep the generate/regenerate buttons gated off, so reset it. The
// rendered runs remain on disk, so re-approval is a single click per direction.
- await atomicWrite(join(spriteDir(recordId), selectionRelPath(recordId)), seedSelection(recordId));
+ // The set's pinned cycle targets survive: unlocking revises the SAME set, and
+ // dropping them would silently re-derive a target from whatever direction the
+ // user happened to re-approve first.
+ const previous = await loadSelection(recordId);
+ await atomicWrite(join(spriteDir(recordId), selectionRelPath(recordId)), {
+ ...seedSelection(recordId),
+ animationTargets: previous?.animationTargets || {},
+ });
console.log(`🔓 sprite walk set unlocked for ${recordId}`);
return getWalkState(recordId);
}
diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.js
index c74089b638..9c0fc14181 100644
--- a/server/services/sprites/walk.test.js
+++ b/server/services/sprites/walk.test.js
@@ -81,7 +81,7 @@ const { listSpriteAssets } = await import('./paths.js');
const { lockReference } = await import('./reference.js');
const {
getWalkState, startWalkGeneration, attachTuiWalkResult, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
- reopenWalkDirection,
+ reopenWalkDirection, setWalkTarget,
} = await import('./walk.js');
const { SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS } = await import('./prompts.js');
@@ -99,7 +99,9 @@ async function characterWithLockedAnchors(id, directions = ['east']) {
// it (#2978): every embedded path stays anchored at the SOURCE repo root
// (`art-source/sprites/<id>/…`) because the importer copies manifests
// byte-for-byte against pinned hashes. Readers must re-anchor at read time.
-async function makeCandidateRun(recordId, direction, { stripBytes = `strip-${direction}`, anchored = false } = {}) {
+async function makeCandidateRun(recordId, direction, {
+ stripBytes = `strip-${direction}`, anchored = false, frameCount = 8, fps = 12,
+} = {}) {
const runId = `walk-${direction}-${(seq++).toString(16).padStart(8, '0')}`;
const runDir = join(TEST_ROOT, 'sprites', recordId, 'runs', runId, 'generated');
await mkdir(runDir, { recursive: true });
@@ -112,8 +114,8 @@ async function makeCandidateRun(recordId, direction, { stripBytes = `strip-${dir
kind: 'deterministically-packaged-grok-walk-video',
characterId: recordId,
direction,
- frameRate: 12,
- frameCount: 8,
+ frameRate: fps,
+ frameCount,
stripPath: anchor(stripRel),
stripSha256: sha256(Buffer.from(stripBytes)),
};
@@ -133,7 +135,7 @@ async function makeCandidateRun(recordId, direction, { stripBytes = `strip-${dir
// The importer stamps it as `path` (repo-anchored); PortOS uses `stripPath`.
stripPreview: {
...(anchored ? { path: anchor(stripRel) } : { stripPath: stripRel }),
- frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
+ frameCount, fps, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
},
}));
return { runId, manifestRel };
@@ -206,6 +208,9 @@ describe('startWalkGeneration', () => {
it('stores the chosen frame count + fps on the run and passes them to the packer', async () => {
const id = await characterWithLockedAnchors(newId(), ['east']);
+ // Frame count / fps are pinned at the SET level now (#2985) — a render must
+ // agree with the target, so pin it first, then generate against it.
+ await setWalkTarget(id, { frameCount: 14, fps: 8 });
executeTuiRun.mockImplementationOnce(async ({ workspacePath }) => {
await writeFile(join(workspacePath, 'source-video.mp4'), 'grok-clip-bytes');
});
@@ -356,9 +361,13 @@ describe('rerunWalkPostprocess', () => {
it('reprocesses the on-disk clip at a new frame count + fps (no regeneration)', async () => {
const id = await characterWithLockedAnchors(newId(), ['east']);
+ await setWalkTarget(id, { frameCount: 8, fps: 12 });
const { runId } = await startWalkGeneration(id, { direction: 'east', frameCount: 8, fps: 12 });
await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4'), 'landed');
runWalkPostprocess.mockClear();
+ // Retargeting the SET is what unlocks a reprocess at a new geometry — the
+ // reprocess is how a drifted direction is brought back into line.
+ await setWalkTarget(id, { frameCount: 16, fps: 6 });
const run = await rerunWalkPostprocess(id, { runId, frameCount: 16, fps: 6 });
// The override reaches the deterministic packer — same clip, new count/fps.
expect(runWalkPostprocess).toHaveBeenCalledOnce();
@@ -368,6 +377,123 @@ describe('rerunWalkPostprocess', () => {
});
});
+// #2985: the cycle geometry is pinned per SET and enforced when each render is
+// queued, instead of surfacing as an atlas-compile wall eight renders later.
+describe('walk cycle target', () => {
+ const readSelection = (id) => readFile(
+ join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`), 'utf8',
+ ).then(JSON.parse);
+
+ it('derives the target from the first packaged direction and reports drift', async () => {
+ // The exact shape this issue exists for: one direction packed at 12 frames
+ // and the rest at 8. It must LOAD, resolve a target, and name the drifted
+ // directions — not throw, and not wait until compile to complain.
+ const id = await characterWithLockedAnchors(newId(), SPRITE_DIRECTIONS);
+ await makeCandidateRun(id, 'south', { frameCount: 12, fps: 10 });
+ await makeCandidateRun(id, 'east');
+ await makeCandidateRun(id, 'west');
+ const { walkTarget } = await getWalkState(id);
+ expect(walkTarget).toMatchObject({ frameCount: 12, fps: 10, source: 'derived' });
+ expect(walkTarget.drift.map((d) => d.direction).sort()).toEqual(['east', 'west']);
+ expect(walkTarget.drift[0]).toMatchObject({ frameCount: 8, fps: 12, frameCountDrifts: true });
+ });
+
+ it('resolves the target from the bound app\'s runtime contract and refuses to override it', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ await records.updateRecord(id, {
+ publishBinding: { appId: 'example-game', runtimeContract: { walkFrameCount: 16 } },
+ });
+ const { walkTarget } = await getWalkState(id);
+ expect(walkTarget).toMatchObject({
+ frameCount: 16, source: 'app', frameCountLocked: true, appId: 'example-game',
+ });
+ // Per-render override → refused; the app decides what its atlas may hold.
+ await expect(startWalkGeneration(id, { direction: 'east', frameCount: 12, fps: 10 }))
+ .rejects.toMatchObject({ code: 'WALK_TARGET_MISMATCH' });
+ // …and so is retargeting the set behind the contract's back.
+ await expect(setWalkTarget(id, { frameCount: 12, fps: 10 }))
+ .rejects.toMatchObject({ code: 'WALK_TARGET_LOCKED' });
+ });
+
+ it('409s a generate whose geometry disagrees with the target, naming both values', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east', 'west']);
+ await setWalkTarget(id, { frameCount: 12, fps: 10 });
+ await expect(startWalkGeneration(id, { direction: 'east', frameCount: 8, fps: 10 }))
+ .rejects.toMatchObject({
+ code: 'WALK_TARGET_MISMATCH',
+ status: 409,
+ message: expect.stringContaining('targets 12 frames @ 10fps'),
+ });
+ await expect(startWalkGeneration(id, { direction: 'east', frameCount: 12, fps: 24 }))
+ .rejects.toMatchObject({ code: 'WALK_TARGET_MISMATCH' });
+ expect(executeTuiRun).not.toHaveBeenCalled();
+ // A matching request goes through, and an omitted geometry adopts the target.
+ const matching = await startWalkGeneration(id, { direction: 'east', frameCount: 12, fps: 10 });
+ expect(matching.runId).toMatch(/^walk-east-/);
+ await startWalkGeneration(id, { direction: 'west' });
+ const { runs } = await getWalkState(id);
+ expect(runs.every((r) => r.frameCount === 12 && r.fps === 10)).toBe(true);
+ });
+
+ it('409s a reprocess whose geometry disagrees with the target', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const { runId } = await startWalkGeneration(id, { direction: 'east' });
+ await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4'), 'landed');
+ runWalkPostprocess.mockClear();
+ await expect(rerunWalkPostprocess(id, { runId, frameCount: 6, fps: 10 }))
+ .rejects.toMatchObject({ code: 'WALK_TARGET_MISMATCH' });
+ expect(runWalkPostprocess).not.toHaveBeenCalled();
+ // Omitting the geometry adopts the target rather than 409ing.
+ await rerunWalkPostprocess(id, { runId });
+ expect(runWalkPostprocess.mock.calls[0][0]).toMatchObject({ frameCount: 12, fps: 10 });
+ });
+
+ it('persists an explicit target track-keyed, preserving an unknown sibling track', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ await setWalkTarget(id, { frameCount: 12, fps: 10 });
+ // Simulate a newer PortOS (or a peer) having written a track this build
+ // knows nothing about — it must survive the next write untouched.
+ const selection = await readSelection(id);
+ selection.animationTargets.scanner = { frameCount: 4, fps: 6, source: 'set' };
+ await writeFile(
+ join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`),
+ JSON.stringify(selection),
+ );
+ const state = await setWalkTarget(id, { frameCount: 14, fps: 8 });
+ expect(state.walkTarget).toMatchObject({ frameCount: 14, fps: 8, source: 'set' });
+ expect(await readSelection(id)).toMatchObject({
+ animationTargets: {
+ walk: { frameCount: 14, fps: 8, source: 'set' },
+ scanner: { frameCount: 4, fps: 6, source: 'set' },
+ },
+ });
+ });
+
+ it('lazily pins a derived target on the first write, stamped as derived', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east', 'west']);
+ await makeCandidateRun(id, 'east');
+ // Nothing written yet — a read never mutates the record, so an older peer
+ // keeps seeing exactly what it wrote.
+ expect((await getWalkState(id)).walkTarget).toMatchObject({ frameCount: 8, fps: 12, source: 'derived' });
+ await expect(readSelection(id)).rejects.toThrow();
+ // The first write path resolves it and records it, so it stops being implicit.
+ await startWalkGeneration(id, { direction: 'west', frameCount: 8, fps: 12 });
+ expect((await readSelection(id)).animationTargets.walk)
+ .toEqual({ frameCount: 8, fps: 12, source: 'derived' });
+ expect((await getWalkState(id)).walkTarget).toMatchObject({ source: 'derived' });
+ });
+
+ it('409s a retarget on a finalized set', async () => {
+ const id = await characterWithLockedAnchors(newId(), SPRITE_DIRECTIONS);
+ for (const direction of SPRITE_DIRECTIONS) {
+ const { runId } = await makeCandidateRun(id, direction);
+ await approveWalkDirection(id, { direction, runId });
+ }
+ await expect(setWalkTarget(id, { frameCount: 14, fps: 8 }))
+ .rejects.toMatchObject({ code: 'WALK_SET_FINAL' });
+ });
+});
+
describe('approveWalkDirection', () => {
it('validates run existence, direction, and candidate status', async () => {
const id = await characterWithLockedAnchors(newId(), ['east']);
@@ -583,7 +709,23 @@ describe('listSpriteAssets run-intermediate exclusion', () => {
describe('getWalkState', () => {
it('returns empty state for a fresh character and newest-first runs', async () => {
const id = await characterWithLockedAnchors(newId(), ['east', 'west']);
- expect(await getWalkState(id)).toEqual({ runs: [], selection: null, walkSet: null });
+ expect(await getWalkState(id)).toEqual({
+ runs: [],
+ selection: null,
+ walkSet: null,
+ // A fresh set has nothing pinned and nothing packaged, so the target is
+ // the documented default with no drift (#2985).
+ walkTarget: {
+ track: 'walk',
+ frameCount: 12,
+ fps: 10,
+ source: 'default',
+ frameCountLocked: false,
+ fpsLocked: false,
+ appId: null,
+ drift: [],
+ },
+ });
await startWalkGeneration(id, { direction: 'east' });
await new Promise((r) => { setTimeout(r, 5); });
const second = await startWalkGeneration(id, { direction: 'west' });