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-3136]): collapse the scanner/ambient clones into one registry-driven track workflow

[._.]/ Adam Eivy452b4976bca7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c6812aa8c7..6abaec2b84 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -18,6 +18,7 @@
## Sprites
+- **[issue-3136] Every animation type beyond the walk cycle now runs through one shared workflow.** The Scanner action and Ambient loop used to be two separate, hardcoded surfaces with their own buttons, endpoints, and copy; they are now the same generate/review/approve flow, each reading its own label, frame count, playback speed, and facing count from a single description of that animation type. Nothing changes about the sprites, atlases, or approvals you already have — but a future release can add a new animation sequence (a chest opening, a flower blossoming, a jetpack burst) as a definition rather than as new code, and it will appear with its own workflow automatically. Places and objects now show their identity reference and their animation loop as two clear steps rather than one panel that swapped contents.
- Locked main references can now be explicitly reopened from Sprite Manager while keeping the turnaround and the other directional anchors intact. Reopening the main preserves versioned evidence, clears only the south identity, and reopens its dependent walk/scanner approvals so a better turnaround-derived main can be reviewed and locked as the next version.
- Sprite turnaround and directional-reference candidates now request a square canvas from image generation and explicitly treat the locked turnaround as the source of truth for accessory side and occlusion. This prevents arbitrary Codex ImageGen candidate aspect ratios and reduces mirrored hip-bag drift before an anchor is locked.
diff --git a/client/src/components/sprites/AmbientWorkflow.jsx b/client/src/components/sprites/AmbientWorkflow.jsx
index a19b61f111..2683247033 100644
--- a/client/src/components/sprites/AmbientWorkflow.jsx
+++ b/client/src/components/sprites/AmbientWorkflow.jsx
@@ -1,18 +1,24 @@
import { useEffect, useMemo, useState } from 'react';
-import { Check, Film, Lock, RefreshCw, Wind } from 'lucide-react';
+import { Film, Lock, RefreshCw, Wind } from 'lucide-react';
import toast from '../ui/Toast';
-import { approveSpriteAmbient, lockSpriteReference } from '../../services/apiSprites.js';
+import { lockSpriteReference } from '../../services/apiSprites.js';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
-import {
- CorrectionNoteToggle, AMBIENT_REFERENCE_CORRECTION_KEY, AMBIENT_LOOP_CORRECTION_KEY,
-} from './CorrectionNote.jsx';
+import { CorrectionNoteToggle, AMBIENT_REFERENCE_CORRECTION_KEY } from './CorrectionNote.jsx';
import { checkerboardStyle, spriteAssetUrl } from './spriteAssets.js';
-// Places and objects have one identity root and one atlas row. Keeping this as
-// a compact, dedicated surface prevents the character turnaround/8-direction
-// affordances from leaking into a track that has neither concept.
+/**
+ * The identity-root half of a place/object's workflow: describe it, render a
+ * candidate, freeze it.
+ *
+ * A place has one identity root rather than a turnaround + eight anchors, so this
+ * stays a dedicated surface — the character affordances would be meaningless
+ * here. What it NO LONGER owns (#3136) is the ambient loop itself: that is one
+ * animation track among any number the user may define, and it renders through
+ * the generic `TrackWorkflow` alongside every other track. Keeping the loop here
+ * would have meant a user-defined place animation had no surface at all.
+ */
export default function AmbientWorkflow({
- record, reference, ambient, renders, hasBackend, mode, onGenerateReference, onGenerateAmbient, onChanged,
+ record, reference, renders, hasBackend, mode, onGenerateReference, onChanged,
corrections = null, onCorrectionChange = null,
}) {
// Seeded from the manifest's stored design (the server persists it on every
@@ -28,16 +34,7 @@ export default function AmbientWorkflow({
() => (reference?.candidates || []).find((item) => item.target === 'main') || null,
[reference?.candidates],
);
- const run = ambient?.runs?.[0] || null;
- const finalized = Boolean(ambient?.ambientSet);
const referenceBusy = Boolean(renders?.pendingJobs?.main);
- const ambientBusy = ['rendering', 'postprocessing'].includes(run?.status);
-
- useEffect(() => {
- if (!ambientBusy) return undefined;
- const timer = setInterval(onChanged, 4000);
- return () => clearInterval(timer);
- }, [ambientBusy, onChanged]);
const [lock, locking] = useAsyncAction(async () => {
await lockSpriteReference(record.id, { target: 'main', candidate: candidate.path }, { silent: true });
@@ -45,81 +42,54 @@ export default function AmbientWorkflow({
onChanged();
}, { errorMessage: 'Could not freeze the ambient reference' });
- const [approve, approving] = useAsyncAction(async () => {
- await approveSpriteAmbient(record.id, { runId: run.id }, { silent: true });
- toast.success('Ambient loop approved');
- onChanged();
- }, { errorMessage: 'Ambient approval failed' });
+ // Once frozen there is nothing left for this surface to do — the animation
+ // tracks take over, each on its own `TrackWorkflow` section.
+ if (main?.locked) return null;
return (
<section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
- <h3 className="flex items-center gap-1.5 text-sm font-semibold text-white"><Wind className="w-4 h-4" /> Ambient Loop</h3>
- <span className="text-[11px] text-gray-500">one at-rest reference · one atlas row</span>
+ <h3 className="flex items-center gap-1.5 text-sm font-semibold text-white"><Wind className="w-4 h-4" /> Identity Reference</h3>
+ <span className="text-[11px] text-gray-500">one at-rest still, frozen once</span>
</div>
- {!main?.locked ? (
- <div className="space-y-2">
- <label htmlFor={`ambient-design-${record.id}`} className="block text-xs text-gray-400">Describe this {record.kind}</label>
- <textarea
- id={`ambient-design-${record.id}`}
- value={designPrompt}
- onChange={(event) => setDesignPrompt(event.target.value)}
- placeholder="A willow tree with long branches moving gently in the wind"
- className="min-h-20 w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-white"
+ <div className="space-y-2">
+ <label htmlFor={`ambient-design-${record.id}`} className="block text-xs text-gray-400">Describe this {record.kind}</label>
+ <textarea
+ id={`ambient-design-${record.id}`}
+ value={designPrompt}
+ onChange={(event) => setDesignPrompt(event.target.value)}
+ placeholder="A willow tree with long branches moving gently in the wind"
+ className="min-h-20 w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-white"
+ />
+ {candidate?.path && (
+ <div className="flex items-center gap-2">
+ <img className="h-20 w-20 rounded object-contain" style={checkerboardStyle(5)} src={spriteAssetUrl(record.id, candidate.path)} alt="Ambient reference candidate" />
+ <button type="button" disabled={locking} onClick={lock} className="flex items-center gap-1 rounded bg-port-accent px-2 py-1.5 text-xs text-white disabled:opacity-50"><Lock className="w-3 h-3" /> Freeze reference</button>
+ </div>
+ )}
+ {/* A correction is ADDITIVE (#3134) — it keeps the design above and
+ fixes one thing about the last render, unlike editing the design
+ prompt, which replaces the design outright. Only useful once there
+ is a render to correct. */}
+ {candidate && onCorrectionChange && (
+ <CorrectionNoteToggle
+ noteKey={AMBIENT_REFERENCE_CORRECTION_KEY}
+ label="ambient reference"
+ corrections={corrections}
+ onChange={onCorrectionChange}
+ placeholder="Correction (optional), e.g. the trunk leans too far right"
/>
- {candidate?.path && (
- <div className="flex items-center gap-2">
- <img className="h-20 w-20 rounded object-contain" style={checkerboardStyle(5)} src={spriteAssetUrl(record.id, candidate.path)} alt="Ambient reference candidate" />
- <button type="button" disabled={locking} onClick={lock} className="flex items-center gap-1 rounded bg-port-accent px-2 py-1.5 text-xs text-white disabled:opacity-50"><Lock className="w-3 h-3" /> Freeze reference</button>
- </div>
- )}
- {/* A correction is ADDITIVE (#3134) — it keeps the design above and
- fixes one thing about the last render, unlike editing the design
- prompt, which replaces the design outright. Only useful once there
- is a render to correct. */}
- {candidate && onCorrectionChange && (
- <CorrectionNoteToggle
- noteKey={AMBIENT_REFERENCE_CORRECTION_KEY}
- label="ambient reference"
- corrections={corrections}
- onChange={onCorrectionChange}
- placeholder="Correction (optional), e.g. the trunk leans too far right"
- />
- )}
- <button
- type="button"
- disabled={!hasBackend || !designPrompt.trim() || referenceBusy}
- onClick={() => onGenerateReference(designPrompt)}
- className="flex items-center gap-1 rounded border border-port-border px-2 py-1.5 text-xs text-gray-200 hover:border-port-accent disabled:opacity-50"
- >
- {referenceBusy ? <RefreshCw className="w-3 h-3 animate-spin" /> : <Film className="w-3 h-3" />}
- {candidate ? 'Regenerate reference' : 'Generate reference'}{mode ? '' : ' (select an image backend)'}
- </button>
- </div>
- ) : (
- <article className="rounded border border-port-border bg-port-bg p-2 space-y-2">
- <div className="flex items-center justify-between"><span className="text-xs font-medium text-white">Ambient row 0</span><span className={`text-[10px] ${finalized ? 'text-port-success' : ambientBusy ? 'text-port-accent' : 'text-gray-500'}`}>{finalized ? 'approved' : ambientBusy ? run.status : run?.status === 'candidate' ? 'review' : 'not generated'}</span></div>
- {run?.stripPreview?.stripPath ? (
- <img className="h-24 w-full rounded object-contain" style={checkerboardStyle(5)} src={spriteAssetUrl(record.id, run.stripPreview.stripPath, run.stripPreview.stripSha256)} alt="Ambient loop preview" />
- ) : <div className="h-24 grid place-items-center rounded text-gray-600" style={checkerboardStyle(5)}><Film className="w-4 h-4" /></div>}
- {!finalized && <div className="space-y-1.5">
- {onCorrectionChange && (
- <CorrectionNoteToggle
- noteKey={AMBIENT_LOOP_CORRECTION_KEY}
- label="ambient loop"
- corrections={corrections}
- onChange={onCorrectionChange}
- placeholder="Correction (optional), e.g. the branches barely move"
- />
- )}
- <div className="flex gap-1.5">
- <button type="button" disabled={ambientBusy} onClick={onGenerateAmbient} className="flex-1 rounded border border-port-border px-2 py-1 text-xs text-gray-300 hover:border-port-accent disabled:opacity-50">{ambientBusy ? 'Rendering…' : run?.status === 'error' ? 'Retry' : 'Generate loop'}</button>
- {run?.status === 'candidate' && <button type="button" disabled={approving} aria-label="Approve ambient loop" onClick={approve} className="rounded bg-port-accent px-2 py-1 text-xs text-white disabled:opacity-50"><Check className="w-3 h-3" /></button>}
- </div>
- </div>}
- {run?.postprocessError && <p className="text-[10px] text-red-300">{run.postprocessError}</p>}
- </article>
- )}
+ )}
+ <button
+ type="button"
+ disabled={!hasBackend || !designPrompt.trim() || referenceBusy}
+ onClick={() => onGenerateReference(designPrompt)}
+ className="flex items-center gap-1 rounded border border-port-border px-2 py-1.5 text-xs text-gray-200 hover:border-port-accent disabled:opacity-50"
+ >
+ {referenceBusy ? <RefreshCw className="w-3 h-3 animate-spin" /> : <Film className="w-3 h-3" />}
+ {candidate ? 'Regenerate reference' : 'Generate reference'}{mode ? '' : ' (select an image backend)'}
+ </button>
+ </div>
</section>
);
}
diff --git a/client/src/components/sprites/AmbientWorkflow.test.jsx b/client/src/components/sprites/AmbientWorkflow.test.jsx
index 78949fb0d0..b6f696c860 100644
--- a/client/src/components/sprites/AmbientWorkflow.test.jsx
+++ b/client/src/components/sprites/AmbientWorkflow.test.jsx
@@ -1,15 +1,16 @@
import { describe, it, expect, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
-// The place/object surface has two independent regeneration actions — the at-rest
-// identity still and the image-to-video loop — and #3134 gave each its own
-// correction note in the shared page-owned map. The load-bearing behavior here is
-// that the two notes stay separate (a reference fix must not ride the loop
-// prompt) and that the reference note is ADDITIVE to the design prompt rather
-// than a replacement for it.
+// The place/object IDENTITY-REFERENCE surface: describe it, render a candidate,
+// freeze it. #3134 gave the reference render its own correction note in the shared
+// page-owned map; the load-bearing behavior here is that the note is ADDITIVE to
+// the design prompt rather than a replacement for it.
+//
+// Since #3136 the ambient LOOP is no longer this component's concern — it is one
+// animation track among any number the user may define, and it renders through
+// the generic `TrackWorkflow` (see `TrackWorkflow.test.jsx` for the loop note).
vi.mock('../../services/apiSprites.js', () => ({
- approveSpriteAmbient: vi.fn(() => Promise.resolve({})),
lockSpriteReference: vi.fn(() => Promise.resolve({})),
}));
@@ -22,18 +23,16 @@ const renderAmbient = (props = {}) => render(
<AmbientWorkflow
record={record}
reference={{ manifest: { mainReference: { locked: false } }, candidates: [CANDIDATE] }}
- ambient={{ runs: [], selection: null, ambientSet: null }}
renders={{ pendingJobs: {} }}
hasBackend
mode="codex"
onGenerateReference={vi.fn()}
- onGenerateAmbient={vi.fn()}
onChanged={vi.fn()}
{...props}
/>,
);
-// A locked main flips the panel from the reference step to the loop step.
+// A locked main means this surface is DONE — the animation tracks take over.
const lockedReference = { manifest: { mainReference: { locked: true, path: 'reference/example-grove-main-v1.png' } }, candidates: [] };
describe('AmbientWorkflow correction notes (#3134)', () => {
@@ -60,41 +59,19 @@ describe('AmbientWorkflow correction notes (#3134)', () => {
expect(screen.queryByRole('button', { name: /correction note/i })).toBeNull();
});
- it('gives the loop its own note, distinct from the reference note', () => {
- const onCorrectionChange = vi.fn();
- renderAmbient({ reference: lockedReference, corrections: {}, onCorrectionChange });
- fireEvent.click(screen.getByRole('button', { name: /Show correction note for ambient loop/i }));
- fireEvent.change(screen.getByLabelText(/Correction guidance for the ambient loop/i), {
- target: { value: 'the branches barely move' },
- });
- const merged = onCorrectionChange.mock.calls[0][0]({ 'ambient-reference': 'keep me' });
- expect(merged['ambient-reference']).toBe('keep me');
- expect(merged).toHaveProperty('ambient-loop');
- });
-
- it('prefills an existing loop note so a set correction is never invisible', () => {
- renderAmbient({
- reference: lockedReference,
- corrections: { 'ambient-loop': 'the branches barely move' },
- onCorrectionChange: vi.fn(),
- });
- expect(screen.getByLabelText(/Correction guidance for the ambient loop/i))
- .toHaveValue('the branches barely move');
- });
-
it('omits every affordance when the page supplies no writer', () => {
- renderAmbient({ reference: lockedReference });
+ renderAmbient();
expect(screen.queryByRole('button', { name: /correction note/i })).toBeNull();
});
- it('hides the loop note once the ambient set is finalized', () => {
- renderAmbient({
- reference: lockedReference,
- ambient: { runs: [], selection: null, ambientSet: { status: 'final' } },
- corrections: {},
- onCorrectionChange: vi.fn(),
+ it('retires itself once the identity reference is frozen (#3136)', () => {
+ // The reference step is one-and-done; leaving it on screen would offer a
+ // Freeze for an already-frozen still. Everything after this point is an
+ // animation track, rendered by TrackWorkflow.
+ const { container } = renderAmbient({
+ reference: lockedReference, corrections: {}, onCorrectionChange: vi.fn(),
});
- expect(screen.queryByRole('button', { name: /correction note/i })).toBeNull();
+ expect(container).toBeEmptyDOMElement();
});
});
diff --git a/client/src/components/sprites/CorrectionNote.jsx b/client/src/components/sprites/CorrectionNote.jsx
index 7e14997c53..4dea6ebbd1 100644
--- a/client/src/components/sprites/CorrectionNote.jsx
+++ b/client/src/components/sprites/CorrectionNote.jsx
@@ -23,7 +23,7 @@ import { useState } from 'react';
import { NotebookPen } from 'lucide-react';
export {
- anchorCorrectionKey, walkCorrectionKey, scannerCorrectionKey,
+ anchorCorrectionKey, walkCorrectionKey, scannerCorrectionKey, trackCorrectionKey,
MAIN_CORRECTION_KEY, AMBIENT_REFERENCE_CORRECTION_KEY, AMBIENT_LOOP_CORRECTION_KEY,
correctionPromptPayload,
} from '../../lib/spriteCorrections.js';
diff --git a/client/src/components/sprites/PublishWorkflow.jsx b/client/src/components/sprites/PublishWorkflow.jsx
index ad85ea37b4..15ddc65d1c 100644
--- a/client/src/components/sprites/PublishWorkflow.jsx
+++ b/client/src/components/sprites/PublishWorkflow.jsx
@@ -59,7 +59,12 @@ function ambientFrameCountOf(geometry) {
}
export default function PublishWorkflow({ record, walk, ambient, atlas, onChanged }) {
- const finalized = Boolean(walk?.walkSet || ambient?.ambientSet);
+ // `ambient` is the generic track state since #3136, whose finalized set is
+ // `set` (the per-track `ambientSet` key went away with the clone). The old key
+ // is still accepted so a caller that hasn't been updated — and any cached
+ // pre-upgrade payload in flight — still reads as finalized rather than
+ // silently re-offering an approve on a frozen loop.
+ const finalized = Boolean(walk?.walkSet || ambient?.set || ambient?.ambientSet);
const current = atlas?.current || null;
const publications = atlas?.publications || [];
const saved = record.publishBinding || null;
diff --git a/client/src/components/sprites/ScannerWorkflow.test.jsx b/client/src/components/sprites/ScannerWorkflow.test.jsx
deleted file mode 100644
index 0e42a5b507..0000000000
--- a/client/src/components/sprites/ScannerWorkflow.test.jsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import { describe, it, expect, vi } from 'vitest';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-
-vi.mock('../../services/apiSprites.js', () => ({
- approveSpriteScanner: vi.fn(() => Promise.resolve({})),
-}));
-
-import ScannerWorkflow from './ScannerWorkflow.jsx';
-import { approveSpriteScanner } from '../../services/apiSprites.js';
-
-const record = { id: 'example-walker' };
-const reference = { manifest: { mainReference: { locked: true } } };
-
-describe('ScannerWorkflow', () => {
- it('exposes the user-triggered scanner generation path and reviews a candidate strip', () => {
- const onGenerate = vi.fn();
- render(
- <ScannerWorkflow
- record={record}
- reference={reference}
- scanner={{
- runs: [{
- id: 'scanner-east-12345678', direction: 'east', status: 'candidate',
- stripPreview: { stripPath: 'runs/scanner-east-12345678/generated/example-scanner-east-strip.png', stripSha256: 'abc' },
- }],
- selection: { directions: {} },
- }}
- onGenerate={onGenerate}
- onChanged={vi.fn()}
- />,
- );
- expect(screen.getByText(/Scanner Action/)).toBeInTheDocument();
- fireEvent.click(screen.getAllByRole('button', { name: 'Generate' })[0]);
- expect(onGenerate).toHaveBeenCalled();
- expect(screen.getByRole('img', { name: /east scanner action preview/i })).toBeInTheDocument();
- });
-
- it('approves the reviewed scanner candidate through the named endpoint', async () => {
- render(
- <ScannerWorkflow
- record={record}
- reference={reference}
- scanner={{ runs: [{ id: 'scanner-east-12345678', direction: 'east', status: 'candidate' }], selection: { directions: {} } }}
- onGenerate={vi.fn()}
- onChanged={vi.fn()}
- />,
- );
- fireEvent.click(screen.getByRole('button', { name: 'Approve scanner east' }));
- await waitFor(() => expect(approveSpriteScanner).toHaveBeenCalledWith(
- 'example-walker', { direction: 'east', runId: 'scanner-east-12345678' }, { silent: true },
- ));
- });
-});
-
-// Correction note on the scanner card (#3134) — the same shared page-owned map
-// every other regeneration surface writes, under a scanner-namespaced key.
-describe('scanner correction note (#3134)', () => {
- const scanner = { runs: [], selection: { directions: {} } };
-
- it('writes through to the shared map under the scanner-namespaced key', () => {
- const onCorrectionChange = vi.fn();
- render(
- <ScannerWorkflow
- record={record}
- reference={reference}
- scanner={scanner}
- onGenerate={vi.fn()}
- onChanged={vi.fn()}
- corrections={{}}
- onCorrectionChange={onCorrectionChange}
- />,
- );
- fireEvent.click(screen.getByRole('button', { name: /Show correction note for east scanner action/i }));
- fireEvent.change(screen.getByLabelText(/Correction guidance for the east scanner action/i), {
- target: { value: 'the sweep never returns to the start pose' },
- });
- const merged = onCorrectionChange.mock.calls[0][0]({ east: 'anchor note' });
- // The anchor's still-image note is untouched; the scanner note gets its own key.
- expect(merged.east).toBe('anchor note');
- expect(merged).toHaveProperty('scanner:east');
- });
-
- it('omits the affordance when the page supplies no writer', () => {
- render(
- <ScannerWorkflow
- record={record}
- reference={reference}
- scanner={scanner}
- onGenerate={vi.fn()}
- onChanged={vi.fn()}
- />,
- );
- expect(screen.queryByRole('button', { name: /correction note/i })).toBeNull();
- });
-});
diff --git a/client/src/components/sprites/ScannerWorkflow.jsx b/client/src/components/sprites/TrackWorkflow.jsx
similarity index 51%
rename from client/src/components/sprites/ScannerWorkflow.jsx
rename to client/src/components/sprites/TrackWorkflow.jsx
index f0b59c3767..a6fe2d306a 100644
--- a/client/src/components/sprites/ScannerWorkflow.jsx
+++ b/client/src/components/sprites/TrackWorkflow.jsx
@@ -1,27 +1,48 @@
import { useEffect, useMemo } from 'react';
-import { Check, Film, Radio, RefreshCw } from 'lucide-react';
+import { Check, Film, Radio, RefreshCw, Wind } from 'lucide-react';
import toast from '../ui/Toast';
-import { approveSpriteScanner } from '../../services/apiSprites.js';
+import { approveSpriteTrack } from '../../services/apiSprites.js';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
import { SPRITE_DIRECTIONS } from '../../lib/spriteFacets.js';
-import { CorrectionNoteToggle, scannerCorrectionKey } from './CorrectionNote.jsx';
+import { CorrectionNoteToggle, trackCorrectionKey } from './CorrectionNote.jsx';
import { checkerboardStyle, spriteAssetUrl } from './spriteAssets.js';
-// Scanner is intentionally compact: it is a named action track, not a second
-// walk editor. The server owns the 4-frame / 6fps default and validates its
-// track-specific range; this UI exposes the direct user action, candidate review
-// strip, and per-direction approval that freezes its atlas input.
-export default function ScannerWorkflow({
- record, reference, scanner, onGenerate, onChanged, corrections = null, onCorrectionChange = null,
+/**
+ * One review/approve surface for EVERY non-walk animation track (#3136).
+ *
+ * Replaces `ScannerWorkflow.jsx` and the loop half of `AmbientWorkflow.jsx`,
+ * which were the same grid of candidate cards with different copy hardcoded in.
+ * Everything track-specific is read from the server's `definition` (the registry
+ * row): the heading label, the frame/fps summary, whether there are eight facing
+ * cards or one, and the approval count. So a user-defined track renders here with
+ * no client change — which is the whole point of the epic, and the reason this
+ * component must never grow an `if (track === …)`.
+ *
+ * Deliberately compact: a named action or an environment loop is not a second
+ * walk editor. The server owns each track's defaults and validates its own range;
+ * this exposes the direct user action, the candidate strip, and approval.
+ *
+ * `AmbientWorkflow.jsx` still owns the *reference* half for a place/object (the
+ * design prompt + freeze step), which is a reference-set concern rather than an
+ * animation-track one.
+ */
+export default function TrackWorkflow({
+ record, reference, state, onGenerate, onChanged, corrections = null, onCorrectionChange = null,
}) {
- const runs = scanner?.runs || [];
- const selection = scanner?.selection || null;
- const finalized = Boolean(scanner?.scannerSet);
- const renderable = Boolean(reference?.manifest?.mainReference?.locked);
- const latestByDirection = useMemo(() => Object.fromEntries(SPRITE_DIRECTIONS.map((direction) => [
+ const definition = state?.definition || null;
+ const runs = state?.runs || [];
+ const selection = state?.selection || null;
+ const finalized = Boolean(state?.set);
+ // A directional track fills one card per facing; a non-directional one is the
+ // single row 0. Derived from the row, not from the track's id.
+ const directions = useMemo(
+ () => (definition?.directional ? SPRITE_DIRECTIONS : [SPRITE_DIRECTIONS[0]]),
+ [definition?.directional],
+ );
+ const latestByDirection = useMemo(() => Object.fromEntries(directions.map((direction) => [
direction,
runs.find((run) => run.direction === direction),
- ])), [runs]);
+ ])), [runs, directions]);
const working = runs.some((run) => ['rendering', 'postprocessing'].includes(run.status));
useEffect(() => {
@@ -31,35 +52,47 @@ export default function ScannerWorkflow({
}, [working, onChanged]);
const [approve, approving] = useAsyncAction(async (direction, runId) => {
- await approveSpriteScanner(record.id, { direction, runId }, { silent: true });
- toast.success(`Scanner ${direction} approved`);
+ await approveSpriteTrack(record.id, definition.id, { direction, runId }, { silent: true });
+ toast.success(`${definition.label} ${directions.length > 1 ? `${direction} ` : ''}approved`);
onChanged();
- }, { errorMessage: 'Scanner approval failed' });
+ }, { errorMessage: `${definition?.label || 'Track'} approval failed` });
- if (!renderable) return null;
+ // A track can only render from a locked reference, so the surface stays hidden
+ // until one exists — otherwise it offers a Generate that always 409s. The main
+ // lock is the right gate for BOTH source shapes: it's the direct source for a
+ // non-directional track, and on a directional one it's the first thing the
+ // turnaround-first flow freezes, so per-facing anchor readiness is the card's
+ // problem (the server 409s that facing by name), not this section's.
+ if (!definition || !reference?.manifest?.mainReference?.locked) return null;
const approvedCount = Object.values(selection?.directions || {})
.filter((entry) => entry?.status === 'approved').length;
+ // The row's own bounds, so the summary can't drift from what the server clamps.
+ const Icon = definition.directional ? Radio : Wind;
return (
<section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<h3 className="flex items-center gap-1.5 text-sm font-semibold text-white">
- <Radio className="w-4 h-4" /> Scanner Action
- <span className="text-xs font-normal text-gray-500">{finalized ? 'finalized' : `${approvedCount}/8 approved`} · 4f @ 6fps</span>
+ <Icon className="w-4 h-4" /> {definition.label}
+ <span className="text-xs font-normal text-gray-500">
+ {finalized ? 'finalized' : `${approvedCount}/${directions.length} approved`}
+ {' · '}{definition.defaultFrameCount}f @ {definition.defaultFps}fps
+ </span>
</h3>
<span className="text-[11px] text-gray-500">directly requested Grok render; local deterministic packing</span>
</div>
- <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
- {SPRITE_DIRECTIONS.map((direction) => {
+ <div className={`grid gap-2 ${directions.length > 1 ? 'sm:grid-cols-2 xl:grid-cols-4' : ''}`}>
+ {directions.map((direction) => {
const run = latestByDirection[direction];
const approved = selection?.directions?.[direction]?.status === 'approved';
const busy = ['rendering', 'postprocessing'].includes(run?.status);
const candidate = run?.status === 'candidate';
const preview = run?.stripPreview;
+ const cardLabel = directions.length > 1 ? direction : `${definition.label} row 0`;
return (
<article key={direction} className="rounded border border-port-border bg-port-bg p-2 space-y-2">
<div className="flex items-center justify-between gap-2">
- <span className="text-xs font-medium text-white">{direction}</span>
+ <span className="text-xs font-medium text-white">{cardLabel}</span>
<span className={`text-[10px] ${approved ? 'text-port-success' : busy ? 'text-port-accent' : 'text-gray-500'}`}>
{approved ? 'approved' : busy ? run.status : candidate ? 'review' : 'not generated'}
</span>
@@ -69,7 +102,7 @@ export default function ScannerWorkflow({
className="h-20 w-full rounded object-contain"
style={checkerboardStyle(5)}
src={spriteAssetUrl(record.id, preview.stripPath, preview.stripSha256)}
- alt={`${direction} scanner action preview`}
+ alt={`${cardLabel} ${definition.label} preview`}
/>
) : (
<div className="h-20 rounded text-xs text-gray-600 grid place-items-center" style={checkerboardStyle(5)}>
@@ -79,21 +112,22 @@ export default function ScannerWorkflow({
{!finalized && !approved && (
<div className="space-y-1.5">
{/* Optional correction the next render carries (#3134) — same
- shared page-owned map every other re-roll surface writes. */}
+ shared page-owned map every other re-roll surface writes,
+ keyed per track+facing (#3136). */}
{onCorrectionChange && (
<CorrectionNoteToggle
- noteKey={scannerCorrectionKey(direction)}
- label={`${direction} scanner action`}
+ noteKey={trackCorrectionKey(definition.id, direction)}
+ label={`${cardLabel} ${definition.label.toLowerCase()}`}
corrections={corrections}
onChange={onCorrectionChange}
- placeholder="Correction (optional), e.g. the sweep never returns to the start pose"
+ placeholder="Correction (optional), e.g. the motion never returns to the start pose"
/>
)}
<div className="flex gap-1.5">
<button
type="button"
disabled={busy}
- onClick={() => onGenerate(direction)}
+ onClick={() => onGenerate(definition.id, direction)}
className="flex-1 rounded border border-port-border px-2 py-1 text-xs text-gray-300 hover:border-port-accent disabled:opacity-50"
>
{busy ? <RefreshCw className="mx-auto w-3 h-3 animate-spin" /> : run?.status === 'error' ? 'Retry' : 'Generate'}
@@ -102,7 +136,7 @@ export default function ScannerWorkflow({
<button
type="button"
disabled={approving}
- aria-label={`Approve scanner ${direction}`}
+ aria-label={`Approve ${definition.label} ${cardLabel}`}
onClick={() => approve(direction, run.id)}
className="rounded bg-port-accent px-2 py-1 text-xs text-white disabled:opacity-50"
>
diff --git a/client/src/components/sprites/TrackWorkflow.test.jsx b/client/src/components/sprites/TrackWorkflow.test.jsx
new file mode 100644
index 0000000000..397a9bd511
--- /dev/null
+++ b/client/src/components/sprites/TrackWorkflow.test.jsx
@@ -0,0 +1,193 @@
+import { describe, it, expect, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+/**
+ * The one review/approve surface for every non-walk animation track (#3136).
+ *
+ * Replaces `ScannerWorkflow.test.jsx` and the loop half of
+ * `AmbientWorkflow.test.jsx`, which asserted the same behaviors twice against two
+ * components. Everything here runs table-driven over BOTH shipped track shapes —
+ * directional (8 facing cards) and non-directional (1 row) — because the property
+ * under test is that the component reads the server's `definition` rather than
+ * branching on a track id. Two separate suites could pass while the component
+ * secretly special-cased one of them.
+ *
+ * The definitions below mirror the registry rows the server sends verbatim; the
+ * `jetpack` case is a track no client build has ever heard of, which is the real
+ * acceptance criterion for the epic.
+ */
+
+vi.mock('../../services/apiSprites.js', () => ({
+ approveSpriteTrack: vi.fn(() => Promise.resolve({})),
+}));
+
+import TrackWorkflow from './TrackWorkflow.jsx';
+import { approveSpriteTrack } from '../../services/apiSprites.js';
+
+const record = { id: 'example-walker' };
+const reference = { manifest: { mainReference: { locked: true } } };
+
+const SCANNER_DEF = {
+ id: 'scanner', label: 'Scanner action', directional: true, sourceReference: 'anchor',
+ defaultFrameCount: 4, defaultFps: 6,
+};
+const AMBIENT_DEF = {
+ id: 'ambient', label: 'Ambient loop', directional: false, sourceReference: 'main',
+ defaultFrameCount: 3, defaultFps: 4,
+};
+
+const renderTrack = (definition, state = {}, props = {}) => render(
+ <TrackWorkflow
+ record={record}
+ reference={reference}
+ state={{ definition, runs: [], selection: { directions: {} }, set: null, ...state }}
+ onGenerate={vi.fn()}
+ onChanged={vi.fn()}
+ {...props}
+ />,
+);
+
+// `facing` is the card the assertions target: a directional track's cards are the
+// eight facings, a non-directional one's single card is row 0.
+const TRACKS = [
+ { definition: SCANNER_DEF, facing: 'east', cardLabel: 'east', cardCount: 8 },
+ { definition: AMBIENT_DEF, facing: 'south', cardLabel: 'Ambient loop row 0', cardCount: 1 },
+];
+
+describe.each(TRACKS)('TrackWorkflow renders the $definition.id track from its definition', (track) => {
+ const { definition, facing, cardLabel } = track;
+ const candidateRun = {
+ id: `${definition.id}-${facing}-12345678`,
+ direction: facing,
+ status: 'candidate',
+ stripPreview: { stripPath: `runs/${definition.id}-${facing}-12345678/generated/strip.png`, stripSha256: 'abc' },
+ };
+
+ it('labels itself and its geometry from the registry row, not from component copy', () => {
+ renderTrack(definition);
+ expect(screen.getByText(definition.label)).toBeInTheDocument();
+ // The frame/fps summary and the approval denominator both come from the row,
+ // so they can't drift from what the server clamps.
+ expect(screen.getByText(
+ new RegExp(`0/${track.cardCount} approved · ${definition.defaultFrameCount}f @ ${definition.defaultFps}fps`),
+ )).toBeInTheDocument();
+ });
+
+ it('renders one card per facing the row declares', () => {
+ renderTrack(definition);
+ expect(screen.getAllByRole('button', { name: 'Generate' })).toHaveLength(track.cardCount);
+ });
+
+ it('exposes the user-triggered generation path, naming the track it is for', () => {
+ const onGenerate = vi.fn();
+ renderTrack(definition, {}, { onGenerate });
+ fireEvent.click(screen.getAllByRole('button', { name: 'Generate' })[0]);
+ // The track id rides along, which is what lets ONE page handler serve every
+ // track — including one added after this build shipped.
+ expect(onGenerate).toHaveBeenCalledWith(definition.id, 'south');
+ });
+
+ it('reviews a packaged candidate strip', () => {
+ renderTrack(definition, { runs: [candidateRun] });
+ expect(screen.getByRole('img', { name: new RegExp(`${cardLabel} ${definition.label} preview`, 'i') })).toBeInTheDocument();
+ });
+
+ it('approves the reviewed candidate through the generic endpoint', async () => {
+ renderTrack(definition, { runs: [candidateRun] });
+ fireEvent.click(screen.getByRole('button', { name: `Approve ${definition.label} ${cardLabel}` }));
+ await waitFor(() => expect(approveSpriteTrack).toHaveBeenCalledWith(
+ 'example-walker', definition.id, { direction: facing, runId: candidateRun.id }, { silent: true },
+ ));
+ });
+
+ it('writes a correction through to the shared map under a track-namespaced key (#3134)', () => {
+ const onCorrectionChange = vi.fn();
+ renderTrack(definition, {}, { corrections: {}, onCorrectionChange });
+ const cards = screen.getAllByRole('button', { name: /Show correction note for/i });
+ fireEvent.click(cards[0]);
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'the motion never returns to the start pose' } });
+ // A still-image ANCHOR note for the same facing must survive untouched — the
+ // whole reason keys are namespaced per surface rather than per direction.
+ const merged = onCorrectionChange.mock.calls[0][0]({ south: 'anchor note' });
+ expect(merged.south).toBe('anchor note');
+ expect(merged).toHaveProperty(`${definition.id}:south`);
+ });
+
+ it('omits the correction affordance when the page supplies no writer', () => {
+ renderTrack(definition);
+ expect(screen.queryByRole('button', { name: /correction note/i })).toBeNull();
+ });
+
+ it('hides every action once the track\'s set is finalized', () => {
+ renderTrack(definition, { set: { status: 'final' } }, { corrections: {}, onCorrectionChange: vi.fn() });
+ expect(screen.getByText(/finalized/)).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Generate' })).toBeNull();
+ expect(screen.queryByRole('button', { name: /correction note/i })).toBeNull();
+ });
+
+ it('stays hidden until the identity reference is locked', () => {
+ // Before a lock the Generate would always 409 server-side, so offering it
+ // would be a button that cannot work.
+ const { container } = render(
+ <TrackWorkflow
+ record={record}
+ reference={{ manifest: { mainReference: { locked: false } } }}
+ state={{ definition, runs: [], selection: null, set: null }}
+ onGenerate={vi.fn()}
+ onChanged={vi.fn()}
+ />,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+});
+
+describe('a track this client build has never heard of (#3136)', () => {
+ // The acceptance criterion for the epic: a user-defined track renders with no
+ // client change at all, because every track-specific string and count is read
+ // from the definition the server sent.
+ const JETPACK = {
+ id: 'jetpack', label: 'Jetpack burst', directional: true, sourceReference: 'anchor',
+ defaultFrameCount: 5, defaultFps: 8,
+ };
+
+ it('renders, generates, and approves with nothing hardcoded for it', async () => {
+ const onGenerate = vi.fn();
+ render(
+ <TrackWorkflow
+ record={record}
+ reference={reference}
+ state={{
+ definition: JETPACK,
+ runs: [{ id: 'jetpack-east-12345678', direction: 'east', status: 'candidate' }],
+ selection: { directions: {} },
+ set: null,
+ }}
+ onGenerate={onGenerate}
+ onChanged={vi.fn()}
+ />,
+ );
+ expect(screen.getByText('Jetpack burst')).toBeInTheDocument();
+ expect(screen.getByText(/0\/8 approved · 5f @ 8fps/)).toBeInTheDocument();
+ fireEvent.click(screen.getAllByRole('button', { name: 'Generate' })[0]);
+ expect(onGenerate).toHaveBeenCalledWith('jetpack', 'south');
+ fireEvent.click(screen.getByRole('button', { name: 'Approve Jetpack burst east' }));
+ await waitFor(() => expect(approveSpriteTrack).toHaveBeenCalledWith(
+ 'example-walker', 'jetpack', { direction: 'east', runId: 'jetpack-east-12345678' }, { silent: true },
+ ));
+ });
+
+ it('renders nothing at all without a definition', () => {
+ // A state payload with no row is unrenderable — better blank than a section
+ // titled "undefined" with buttons that can't resolve a track.
+ const { container } = render(
+ <TrackWorkflow
+ record={record}
+ reference={reference}
+ state={{ runs: [], selection: null, set: null }}
+ onGenerate={vi.fn()}
+ onChanged={vi.fn()}
+ />,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index cf01a3d01e..9f0669c409 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -143,7 +143,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. |
| `songProgress.js` | Pure training-progress core for the song system's memorize/learn/track mode. `deriveTrainingSections(score, lyricSections?)` slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); `recordAttempt(progress, scope, summary)` appends a graded take to a scope's bounded rolling history (drops zero-note takes); `scopeStats(progress, scope)`/`wholeSongStats` derive `{ attempts, best, average, last, streak, learned }` (learned = streak of ≥`LEARNED_PERCENT` takes ≥`LEARNED_STREAK`); `weakestSections(progress, sections)` ranks weak/un-attempted sections for spaced-repetition; `memorizationPercent` is the learned-section share; `hideLevelFor(average)` maps a rolling average to a progressive lyric/note-hiding level (`show`/`dim`/`hide`/`blind`). No React/audio — `useSongTraining` drives it. |
| `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). Each actionable regenerate also names the `correctionKey` (#3134) the card binds its inline correction note to — `walk:<dir>` for a walk output, the bare direction for an anchor — so the card can never write a still-image note into a video re-roll. Pure — takes callbacks, performs no I/O. Consumes the facets from `spriteFacets.js` and the key vocabulary from `spriteCorrections.js`. |
-| `spriteCorrections.js` | The Sprite Manager's correction-note key vocabulary + request fragment (#2964, extended to every regeneration surface by #3134). Every re-roll surface writes into ONE page-owned `corrections` map (`Sprites.jsx`); this module owns its keys so the pure gating layer (`spriteCollectionActions.js`) and the React surfaces (`CorrectionNote.jsx` + hosts) agree without the pure layer importing a component. Keys are namespaced per SURFACE, not per direction — `anchorCorrectionKey(dir)` keeps the bare direction (pre-#3134 state untouched) while `walkCorrectionKey(dir)` / `scannerCorrectionKey(dir)` / `MAIN_CORRECTION_KEY` / `AMBIENT_REFERENCE_CORRECTION_KEY` / `AMBIENT_LOOP_CORRECTION_KEY` prefix, so a still-image anchor note can never ride a walk-VIDEO re-roll. `correctionPromptPayload(corrections, key)` → `{ correctionPrompt }` only when the note is non-empty after trimming, else `{}` — the guarantee that a blank note leaves the server prompt byte-identical to a blind regenerate. Pure — no React, no I/O. |
+| `spriteCorrections.js` | The Sprite Manager's correction-note key vocabulary + request fragment (#2964, extended to every regeneration surface by #3134). Every re-roll surface writes into ONE page-owned `corrections` map (`Sprites.jsx`); this module owns its keys so the pure gating layer (`spriteCollectionActions.js`) and the React surfaces (`CorrectionNote.jsx` + hosts) agree without the pure layer importing a component. Keys are namespaced per SURFACE, not per direction — `anchorCorrectionKey(dir)` keeps the bare direction (pre-#3134 state untouched) while `walkCorrectionKey(dir)` / `MAIN_CORRECTION_KEY` / `AMBIENT_REFERENCE_CORRECTION_KEY` prefix, so a still-image anchor note can never ride a walk-VIDEO re-roll. `trackCorrectionKey(trackId, dir)` (#3136) generalizes what the scanner/ambient keys each spelled by hand, so a user-defined animation track gets a namespaced key with nothing to add here; `scannerCorrectionKey(dir)` and `AMBIENT_LOOP_CORRECTION_KEY` are readability aliases over it. `correctionPromptPayload(corrections, key)` → `{ correctionPrompt }` only when the note is non-empty after trimming, else `{}` — the guarantee that a blank note leaves the server prompt byte-identical to a blind regenerate. Pure — no React, no I/O. |
| `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 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. |
diff --git a/client/src/lib/spriteCorrections.js b/client/src/lib/spriteCorrections.js
index c4683c360a..ed406b1063 100644
--- a/client/src/lib/spriteCorrections.js
+++ b/client/src/lib/spriteCorrections.js
@@ -27,12 +27,30 @@ export const anchorCorrectionKey = (direction) => direction;
export const MAIN_CORRECTION_KEY = 'main';
/** The walk-cycle video for a direction — shared by WalkWorkflow and the asset card. */
export const walkCorrectionKey = (direction) => `walk:${direction}`;
+/**
+ * Any non-walk animation track's clip, for one facing (#3136).
+ *
+ * Generalizes what `scanner:<dir>`/`ambient-loop` each spelled by hand, so a
+ * user-defined track's note gets a namespaced key with nothing to add here. The
+ * facing is part of the key for the same reason it is for walk: a directional
+ * track's eight clips are eight separate re-rolls, and a note about one must not
+ * ride the next.
+ *
+ * Deliberately NOT byte-compatible with the two old keys — `corrections` is
+ * transient page state (typed in this session, never persisted), so there is no
+ * stored note to migrate; the aliases below exist for call-site readability, not
+ * for on-disk compatibility.
+ */
+export const trackCorrectionKey = (trackId, direction) => `${trackId}:${direction}`;
/** The scanner action video for a direction. */
-export const scannerCorrectionKey = (direction) => `scanner:${direction}`;
+export const scannerCorrectionKey = (direction) => trackCorrectionKey('scanner', direction);
/** A place/object's at-rest identity still. */
export const AMBIENT_REFERENCE_CORRECTION_KEY = 'ambient-reference';
-/** A place/object's image-to-video ambient loop. */
-export const AMBIENT_LOOP_CORRECTION_KEY = 'ambient-loop';
+/**
+ * A place/object's image-to-video ambient loop. Its facing is the single row 0,
+ * so the generic key resolves to one value rather than eight.
+ */
+export const AMBIENT_LOOP_CORRECTION_KEY = trackCorrectionKey('ambient', 'south');
/**
* Build the re-roll request fragment for one correction key. Returns
diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsx
index e600c87aad..56e2bbe6b4 100644
--- a/client/src/pages/Sprites.jsx
+++ b/client/src/pages/Sprites.jsx
@@ -5,7 +5,7 @@ import toast from '../components/ui/Toast';
import Modal from '../components/ui/Modal.jsx';
import {
listSpriteRecords, getSpriteRecord, importSprites, createSpriteRecord,
- generateSpriteWalk, generateSpriteScanner, generateSpriteAmbient, generateSpriteReference, listSpriteThumbnails,
+ generateSpriteWalk, generateSpriteTrack, generateSpriteReference, listSpriteThumbnails,
} from '../services/apiSprites.js';
import { getApps } from '../services/apiApps.js';
import { getSettings } from '../services/apiSystem.js';
@@ -13,15 +13,15 @@ import { deriveAvailableBackends } from '../lib/imageGenBackends.js';
import AppContextPicker from '../components/AppContextPicker.jsx';
import ReferenceWorkflow from '../components/sprites/ReferenceWorkflow.jsx';
import WalkWorkflow from '../components/sprites/WalkWorkflow.jsx';
-import ScannerWorkflow from '../components/sprites/ScannerWorkflow.jsx';
+import TrackWorkflow from '../components/sprites/TrackWorkflow.jsx';
import AmbientWorkflow from '../components/sprites/AmbientWorkflow.jsx';
import { GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokVideoClip.js';
import LoopTrimmer from '../components/sprites/LoopTrimmer.jsx';
import PublishWorkflow from '../components/sprites/PublishWorkflow.jsx';
import AssetCollection from '../components/sprites/AssetCollection.jsx';
import {
- correctionPromptPayload, anchorCorrectionKey, walkCorrectionKey, scannerCorrectionKey,
- AMBIENT_REFERENCE_CORRECTION_KEY, AMBIENT_LOOP_CORRECTION_KEY,
+ correctionPromptPayload, anchorCorrectionKey, walkCorrectionKey, trackCorrectionKey,
+ AMBIENT_REFERENCE_CORRECTION_KEY,
} from '../components/sprites/CorrectionNote.jsx';
import SpriteCatalog from '../components/sprites/SpriteCatalog.jsx';
import SpriteDetailHeader from '../components/sprites/SpriteDetailHeader.jsx';
@@ -518,8 +518,12 @@ export default function Sprites() {
};
collect(detail?.walk?.selection?.directions);
collect(detail?.walk?.walkSet?.directions);
- collect(detail?.scanner?.selection?.directions);
- collect(detail?.scanner?.scannerSet?.directions);
+ // Every non-walk track's approvals, keyed by track id (#3136) — so a
+ // user-defined track's approved runs badge correctly with nothing added here.
+ for (const state of Object.values(detail?.tracks || {})) {
+ collect(state?.selection?.directions);
+ collect(state?.set?.directions);
+ }
return set;
}, [detail]);
@@ -573,23 +577,28 @@ export default function Sprites() {
onWorkflowChanged,
), [id, duration, corrections, walkBegin, walkResolve, walkCancel, submitRender, onWorkflowChanged]);
- // Scanner has its own server-side in-flight guard and independent named set;
- // keeping its submit path separate means a scanner render never occupies the
- // walk direction's optimistic reservation (both can legitimately be authored
- // at once). It also owns its short default source clip instead of inheriting
- // the walk duration picker. The immediate refetch persists the observable
- // TUI run for polling.
- const generateScanner = useCallback(async (direction) => {
+ // ONE submit path for every non-walk track (#3136) — the track id is a
+ // parameter, so a user-defined track needs no new handler here.
+ //
+ // Kept separate from `generateWalk` for the same reason the scanner clone was:
+ // each track has its own server-side in-flight guard and its own finalized set,
+ // so a track render must not occupy the walk direction's optimistic
+ // reservation (both can legitimately be authored at once), and each owns its
+ // short default source clip rather than inheriting the walk duration picker.
+ // The immediate refetch persists the observable TUI run for polling.
+ const generateTrack = useCallback(async (trackId, direction) => {
try {
- await generateSpriteScanner(id, {
- direction,
- ...correctionPromptPayload(corrections, scannerCorrectionKey(direction)),
+ await generateSpriteTrack(id, trackId, {
+ // A non-directional track derives row 0 server-side; sending its facing
+ // anyway would be a value the server must then agree with.
+ ...(direction && detail?.tracks?.[trackId]?.definition?.directional ? { direction } : {}),
+ ...correctionPromptPayload(corrections, trackCorrectionKey(trackId, direction)),
}, { silent: true });
onWorkflowChanged();
} catch (err) {
- toast.error(err?.message || `Failed to queue ${direction} scanner action`);
+ toast.error(err?.message || `Failed to queue the ${trackId} render`);
}
- }, [id, corrections, onWorkflowChanged]);
+ }, [id, corrections, onWorkflowChanged, detail?.tracks]);
// The ambient main takes BOTH inputs: `designPrompt` replaces the design
// outright, while the correction (#3134) keeps it and fixes one thing about
@@ -605,16 +614,25 @@ export default function Sprites() {
onWorkflowChanged,
), [id, imageMode, corrections, refBegin, refResolve, refCancel, submitRender, onWorkflowChanged]);
- const generateAmbient = useCallback(async () => {
- try {
- await generateSpriteAmbient(id, {
- ...correctionPromptPayload(corrections, AMBIENT_LOOP_CORRECTION_KEY),
- }, { silent: true });
- onWorkflowChanged();
- } catch (err) {
- toast.error(err?.message || 'Failed to queue ambient loop');
- }
- }, [id, corrections, onWorkflowChanged]);
+ // One section per non-walk track this record's kind carries (#3136), rendered
+ // in registry order from the server's keyed `tracks` payload. The list is DATA,
+ // so a user-defined track appears here without a page edit — which is the
+ // client-side half of "an animation type is a row, not a code path". Keyed by
+ // track id so switching records can't carry one track's card state into
+ // another's.
+ const trackSections = useMemo(() => Object.entries(detail?.tracks || {}).map(([trackId, state]) => (
+ <TrackWorkflow
+ key={trackId}
+ record={detail.record}
+ reference={detail.reference}
+ state={state}
+ onGenerate={generateTrack}
+ onChanged={onWorkflowChanged}
+ corrections={corrections}
+ onCorrectionChange={setCorrections}
+ />
+ )), [detail?.tracks, detail?.record, detail?.reference, generateTrack, onWorkflowChanged, corrections]);
+
// `mode` is the workflow-selected backend, threaded from the asset card via
// buildCollectionActions (#2938) so a re-roll uses the same backend the
@@ -772,15 +790,7 @@ export default function Sprites() {
corrections={corrections}
onCorrectionChange={setCorrections}
/>
- <ScannerWorkflow
- record={detail.record}
- reference={detail.reference}
- scanner={detail.scanner}
- onGenerate={generateScanner}
- onChanged={onWorkflowChanged}
- corrections={corrections}
- onCorrectionChange={setCorrections}
- />
+ {trackSections}
{/* Keyed by record so form state and an armed publish/overwrite
confirmation never survive switching characters. */}
<PublishWorkflow
@@ -792,26 +802,25 @@ export default function Sprites() {
/>
</>
)}
- {detail.record.kind !== 'character' && detail.ambient && (
+ {detail.record.kind !== 'character' && (
<>
<AmbientWorkflow
record={detail.record}
reference={detail.reference}
- ambient={detail.ambient}
renders={referenceRenders}
hasBackend={hasImageBackend}
mode={imageMode}
onGenerateReference={generateAmbientReference}
- onGenerateAmbient={generateAmbient}
onChanged={onWorkflowChanged}
corrections={corrections}
onCorrectionChange={setCorrections}
/>
+ {trackSections}
<PublishWorkflow
key={detail.record.id}
record={detail.record}
walk={detail.walk}
- ambient={detail.ambient}
+ ambient={detail.tracks?.ambient}
atlas={detail.atlas}
onChanged={onWorkflowChanged}
/>
diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.js
index 05d7be88b1..9f5d8922d7 100644
--- a/client/src/services/apiSprites.js
+++ b/client/src/services/apiSprites.js
@@ -125,12 +125,17 @@ export const generateSpriteWalk = (id, body, options = {}) => request(`/sprites/
method: 'POST', body: JSON.stringify(body), ...options,
});
-// Queue one user-requested scanner action. Its 2–8 frame, 2–12fps contract is
-// validated by the named scanner track on the server, independently of walk.
-// Takes the same optional `correctionPrompt` as the walk render.
-export const generateSpriteScanner = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/scanner/generate`, {
- method: 'POST', body: JSON.stringify(body), ...options,
-});
+// Queue one user-requested render for ANY non-walk animation track (#3136) —
+// `scanner`, `ambient`, or a user-defined one. Each track's frame/fps range,
+// facing count and prompt are resolved server-side from its registry row, so
+// this one wrapper replaces the per-track pairs (`generateSpriteScanner` /
+// `generateSpriteAmbient`) that would otherwise have grown one per type. Takes
+// the same optional `correctionPrompt` as the walk render; `direction` is
+// required for a directional track and derived server-side for a single-row one.
+export const generateSpriteTrack = (id, trackId, body = {}, options = {}) => request(
+ `/sprites/${encodeURIComponent(id)}/tracks/${encodeURIComponent(trackId)}/generate`,
+ { method: 'POST', body: JSON.stringify(body), ...options },
+);
// Approve a packaged candidate run for its direction. Returns the updated
// { runs, selection, walkSet } walk state.
@@ -138,19 +143,12 @@ export const approveSpriteWalk = (id, body, options = {}) => request(`/sprites/$
method: 'POST', body: JSON.stringify(body), ...options,
});
-export const approveSpriteScanner = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/scanner/approve`, {
- method: 'POST', body: JSON.stringify(body), ...options,
-});
-
-// Queue the one non-directional ambient loop. Also takes the optional
-// `correctionPrompt` (#3134).
-export const generateSpriteAmbient = (id, body = {}, options = {}) => request(`/sprites/${encodeURIComponent(id)}/ambient/generate`, {
- method: 'POST', body: JSON.stringify(body), ...options,
-});
-
-export const approveSpriteAmbient = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/ambient/approve`, {
- method: 'POST', body: JSON.stringify(body), ...options,
-});
+// Approve one packaged candidate for a non-walk track. Returns that track's
+// updated `{ track, bounds, selection, set, runs }` state.
+export const approveSpriteTrack = (id, trackId, body, options = {}) => request(
+ `/sprites/${encodeURIComponent(id)}/tracks/${encodeURIComponent(trackId)}/approve`,
+ { method: 'POST', body: JSON.stringify(body), ...options },
+);
// Re-run the deterministic postprocess on a run whose video already landed.
export const postprocessSpriteWalk = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/walk/postprocess`, {
diff --git a/docs/features/sprite-export-contract.md b/docs/features/sprite-export-contract.md
index 77407d2ed0..7dfc1aeb95 100644
--- a/docs/features/sprite-export-contract.md
+++ b/docs/features/sprite-export-contract.md
@@ -18,7 +18,15 @@ The compiler (`server/services/sprites/atlas.js`) produces one PNG: a fixed-cell
`N` is read from the approved run manifests — every direction of a track must share it — so the atlas width tracks the authored count. **That makes the column layout a moving target for anything that hardcodes it.**
-Frame-count and fps uniformity is a **within-track** rule, never a between-track one: every facing of a given track shares a column span because the atlas is a rectangular grid, but two different tracks may legally differ in both length and speed. The shipped directional `scanner` action is four frames at 6fps by default beside the 6–16-frame walk; its source video is generated only by an explicit scanner action, then packed and approved through its own evidence chain. Each track's authoring range comes from its own row in `server/services/sprites/animationTracks.js`, and its column span is recorded in `geometry.tracks` and republished in the sidecar.
+Frame-count and fps uniformity is a **within-track** rule, never a between-track one: every facing of a given track shares a column span because the atlas is a rectangular grid, but two different tracks may legally differ in both length and speed. The shipped directional `scanner` action is four frames at 6fps by default beside the 6–16-frame walk; its source video is generated only by an explicit request, then packed and approved through its own evidence chain. Each track's authoring range comes from its own row in `server/services/sprites/animationTracks.js`, and its column span is recorded in `geometry.tracks` and republished in the sidecar.
+
+### Animation tracks are data, with `walk` the one built-in
+
+**Which tracks exist is not a fixed list.** `walk` is the mandatory baseline for a character — the one animation every character has, and the only one this document can promise a reader will be there. Everything else, including the shipped `scanner` action and `ambient` loop, is an ordinary **row** in the track registry describing its own label, facing count, frame/fps range, the locked reference its render is seeded from, and the `runtimeContract` field it occupies. A consuming app must therefore treat the track set as **discovered from `geometry.tracks`, never enumerated in code** (see "Resolve columns by name, not by constant" below) — the atlas it reads next year may carry a track nobody had named when it was written.
+
+The consequence for the app side is small but load-bearing: a track's *presence* is optional and its *name* is user-chosen, so an app keys off the track ids it actually needs and ignores the rest. Nothing about the grid, cell metrics, pivot, or row semantics changes when a track is added.
+
+One generic authoring path serves every non-walk track — `POST /api/sprites/:id/tracks/:trackId/generate` and `/approve`, resolved against that track's registry row (`server/services/sprites/animationTrackWorkflow.js`). Walk keeps its own `/walk/*` endpoints because it additionally carries reprocessing, loop trims, per-direction reopen and set-level cycle targets that no other track has.
**Not every track has eight rows.** A track is *directional* (one row per facing — a character walk) or *non-directional* (one row, period — a tree moving in the wind, water, a flickering lamp, which have no facing at all). A non-directional track occupies **row 0** across its whole column span and leaves the remaining rows transparent. Its span says so: `rows: 1`. There is still exactly **one atlas per record** — a second image would double the publish and binding surface for no gain, and the transparent cells cost only file size, which PNG compresses to near nothing.
@@ -117,7 +125,9 @@ Two mechanisms guard that:
|---|---|
| `server/services/sprites/atlas.js` | Compiles the atlas; owns the geometry block and the pre-pixel up-to-date check |
| `server/services/sprites/atlasGrid.js` | The grid itself: column spans and row spans per track, within-track uniformity, reading a persisted (or legacy) grid back |
-| `server/services/sprites/animationTracks.js` | One row per animation track — its bounds, defaults, directionality, and which record kinds may carry it |
+| `server/services/sprites/animationTracks.js` | One row per animation track — its bounds, defaults, directionality, which record kinds may carry it, and the workflow shape (source reference, on-disk set/selection kinds) |
+| `server/services/sprites/animationTrackWorkflow.js` | The ONE generate/package/review/approve implementation every non-walk track runs, parameterized by its registry row |
+| `server/services/sprites/trackPrompts.js` | Resolves a track id to its image-to-video prompt builder |
| `server/services/sprites/reference.js` | The two animation gates: `requireCharacter` (walk workflow) and `requireAnimatable` (compile/publish) |
| `server/services/sprites/atlasLayout.js` | Builds the sidecar payload; compares geometry against a runtime contract |
| `server/services/sprites/publish.js` | Binding validation, the publish-time guard, the atomic PNG + sidecar write |
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 3da9729b8e..c0df476e95 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -5,7 +5,9 @@ import { WORK_TRACKERS } from './workTracker.js';
import { SPRITE_ID_PATTERN, SPRITE_RECORD_KINDS } from '../services/sprites/recordsLogic.js';
import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS, TURNAROUND_ID } from '../services/sprites/prompts.js';
import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';
-import { WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, getAnimationTrack } from '../services/sprites/animationTracks.js';
+import {
+ WALK_TRACK, ANIMATION_TRACK_IDS, getAnimationTrack, tracksForKind,
+} from '../services/sprites/animationTracks.js';
import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
import { GROK_VIDEO_DURATIONS } from './grokVideoClip.js';
import { PR_COMPLETION_VALUES } from './prDisposition.js';
@@ -1041,23 +1043,56 @@ const spriteRepoRelativePath = z.string().min(1).max(1024)
// A directional consumer names `walkFrameCount`; an ambient-only consumer names
// `ambientFrameCount`. Playback speed is deliberately absent: consumers own
// timing, so PortOS's fps is preview-only and never part of the contract.
+//
+// The per-track frame-count keys are BUILT from the registry (#3136) rather than
+// named one by one: each row already declares the `contractFrameCountField` it
+// occupies, and `assertAnimationTrackRows` refuses two rows claiming the same
+// one, so deriving the schema from those declarations is what lets a
+// user-defined track's contract field validate against ITS bounds with no schema
+// edit. Before this, adding a track meant remembering to add a fourth literal
+// here — and forgetting meant the field was silently stripped by Zod and the
+// app rung of the target-precedence chain went dead for that track.
+const spriteTrackContractFields = Object.fromEntries(
+ ANIMATION_TRACK_IDS.map((id) => {
+ const row = getAnimationTrack(id);
+ return [row.contractFrameCountField, spriteTrackFrameCountSchema(id).optional()];
+ }),
+);
+
+// The tracks whose frame count is enough ON ITS OWN to make a contract
+// meaningful — a record can't be published without one of these authored, so a
+// contract that pins none of them describes no atlas that could ever exist.
+//
+// The discriminator is PRIMACY: a track is primary when it is the first
+// registered track for at least one record kind it supports. Walk is a
+// character's primary (`tracksForKind('character')` leads with it) and ambient is
+// a place/object's; scanner is a character's SECOND track — a short action that
+// always rides beside the walk it shares a row with, so `scannerFrameCount`
+// alone was never a publishable contract. That reproduces the historical
+// "walkFrameCount or ambientFrameCount" rule exactly while staying true for a
+// user-defined track: one that unlocks a new record kind becomes that kind's
+// primary and joins this set, and a second action on an existing kind doesn't.
+//
+// It also matches the compile side, which requires the primary track's finalized
+// set before it will emit an atlas at all (`atlas.js` — a walk set for a
+// character, an ambient set for a place).
+const SPRITE_STANDALONE_CONTRACT_FIELDS = ANIMATION_TRACK_IDS
+ .filter((id) => getAnimationTrack(id).kinds.some((kind) => tracksForKind(kind)[0]?.id === id))
+ .map((id) => getAnimationTrack(id).contractFrameCountField);
+
export const spriteRuntimeContractSchema = z.object({
- // Range from the walk registry row (#3015). The KEY stays a literal so
- // `grep walkFrameCount` still finds the schema that validates it — the row's
- // `contractFrameCountField` is asserted to agree in animationTargets.test.js.
- walkFrameCount: spriteTrackFrameCountSchema(WALK_TRACK).optional(),
- // Optional because older consumers only know walk. A scanner-aware consumer
- // can pin the named action span without relaxing its independent 2–8 range.
- scannerFrameCount: spriteTrackFrameCountSchema(SCANNER_TRACK).optional(),
- ambientFrameCount: spriteTrackFrameCountSchema(AMBIENT_TRACK).optional(),
+ // Ranges come from each track's registry row (#3015/#3136). `walkFrameCount`
+ // and its siblings are spread in from `spriteTrackContractFields` above —
+ // `grep walkFrameCount` finds the row in animationTracks.js that names it.
+ ...spriteTrackContractFields,
cellSize: z.number().int().min(16).max(1024).nullable().optional(),
columnCount: z.number().int().min(1).max(256).nullable().optional(),
}).superRefine((value, ctx) => {
- if (value.walkFrameCount === undefined && value.ambientFrameCount === undefined) {
+ if (SPRITE_STANDALONE_CONTRACT_FIELDS.every((field) => value[field] === undefined)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
- path: ['walkFrameCount'],
- message: 'walkFrameCount or ambientFrameCount is required for a runtime contract',
+ path: [SPRITE_STANDALONE_CONTRACT_FIELDS[0]],
+ message: `${SPRITE_STANDALONE_CONTRACT_FIELDS.join(' or ')} is required for a runtime contract`,
});
}
});
@@ -1192,10 +1227,6 @@ const spriteResolvableRunIdSchema = z.string().min(1).max(1024)
// animationTracks pulls in no deps at all, native or otherwise.
const spriteWalkFrameCountSchema = spriteTrackFrameCountSchema(WALK_TRACK);
const spriteWalkFpsSchema = spriteTrackFpsSchema(WALK_TRACK);
-const spriteScannerFrameCountSchema = spriteTrackFrameCountSchema(SCANNER_TRACK);
-const spriteScannerFpsSchema = spriteTrackFpsSchema(SCANNER_TRACK);
-const spriteAmbientFrameCountSchema = spriteTrackFrameCountSchema(AMBIENT_TRACK);
-const spriteAmbientFpsSchema = spriteTrackFpsSchema(AMBIENT_TRACK);
export const spriteWalkGenerateSchema = z.object({
direction: spriteWalkDirectionSchema,
@@ -1216,33 +1247,40 @@ export const spriteWalkGenerateSchema = z.object({
correctionPrompt: z.string().max(4000).optional(),
});
-// The scanner is a separate, short directional action. It deliberately has its
-// own bounds (2–8 frames, 2–12fps) rather than inheriting the walk cycle's
-// 6–16 / 4–24 shape.
-export const spriteScannerGenerateSchema = z.object({
- direction: spriteWalkDirectionSchema,
- duration: grokVideoDurationSchema.optional(),
- frameCount: spriteScannerFrameCountSchema.optional(),
- fps: spriteScannerFpsSchema.optional(),
- correctionPrompt: z.string().max(4000).optional(),
-});
+// Non-walk animation tracks share ONE generate/approve request shape, built per
+// track from its registry row (#3136) — `scanner` gets 2–8 frames / 2–12fps and
+// `ambient` gets 2–6 / 2–12 from the same factory, so a user-defined track needs
+// no schema edit at all. Two facts make one shape work for both:
+//
+// - `direction` is OPTIONAL here even for a directional track, because the
+// route builds the schema for the track it resolved and a non-directional
+// one derives row 0 server-side. The route requires it (below) exactly when
+// the resolved row is directional, so a directional generate can't slip
+// through without a facing — that check reads the same registry the bounds
+// came from, rather than being restated as a second enum.
+// - the remaining knobs are already registry-derived.
+export function spriteTrackGenerateSchema(track) {
+ return z.object({
+ direction: spriteWalkDirectionSchema.optional(),
+ duration: grokVideoDurationSchema.optional(),
+ frameCount: spriteTrackFrameCountSchema(track).optional(),
+ fps: spriteTrackFpsSchema(track).optional(),
+ correctionPrompt: z.string().max(4000).optional(),
+ });
+}
-export const spriteScannerApproveSchema = z.object({
- direction: spriteWalkDirectionSchema,
+export const spriteTrackApproveSchema = z.object({
+ direction: spriteWalkDirectionSchema.optional(),
runId: spriteResolvableRunIdSchema,
});
-// One non-directional row lives at the first atlas row, so no user-supplied
-// direction can drift from the registry's `trackDirections()` result.
-export const spriteAmbientGenerateSchema = z.object({
- duration: grokVideoDurationSchema.optional(),
- frameCount: spriteAmbientFrameCountSchema.optional(),
- fps: spriteAmbientFpsSchema.optional(),
- correctionPrompt: z.string().max(4000).optional(),
-});
-
-export const spriteAmbientApproveSchema = z.object({
- runId: spriteResolvableRunIdSchema,
+// The `:trackId` path param. Shape gate only — whether the id names a REGISTERED
+// track (and whether this record's kind may carry it) is the service's job, so
+// the 404/400 names the known tracks instead of a regex failure. The charset
+// matches the registry's slug ids and, load-bearingly, can never contain a `/`
+// or `.` that would let the id widen the route's path.
+export const spriteTrackParamsSchema = z.object({
+ trackId: z.string().min(1).max(64).regex(/^[a-z0-9][a-z0-9-]*$/, 'invalid animation track id'),
});
// Pin the walk track's cycle target at the SET level (#2985). Both knobs are
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index d1187f64e2..ec13cd01e5 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -49,9 +49,11 @@ import {
spriteTrackFpsSchema,
spriteRuntimeContractSchema,
spriteWalkGenerateSchema,
- spriteScannerGenerateSchema,
- spriteAmbientGenerateSchema,
+ spriteTrackGenerateSchema,
} from './validation.js';
+import {
+ WALK_TRACK, ANIMATION_TRACK_IDS, getAnimationTrack, tracksForKind,
+} from '../services/sprites/animationTracks.js';
import {
telegramForwardTypesSchema,
} from './telegramValidation.js';
@@ -1903,10 +1905,52 @@ describe('ad-hoc route schemas (#2521)', () => {
expect(spriteWalkGenerateSchema.safeParse({
direction: 'south', frameCount: 3,
}).success).toBe(false);
- expect(spriteScannerGenerateSchema.safeParse({ direction: 'south', frameCount: 4, fps: 6 }).success).toBe(true);
- expect(spriteScannerGenerateSchema.safeParse({ direction: 'south', frameCount: 9 }).success).toBe(false);
- expect(spriteAmbientGenerateSchema.safeParse({ frameCount: 3, fps: 4 }).success).toBe(true);
- expect(spriteAmbientGenerateSchema.safeParse({ frameCount: 7 }).success).toBe(false);
+ // One generate shape, built per track from its own row (#3136) — so the
+ // scanner's 2–8 and the ambient's 2–6 are enforced by the same factory
+ // that a user-defined track's schema will come from.
+ expect(spriteTrackGenerateSchema('scanner').safeParse({ direction: 'south', frameCount: 4, fps: 6 }).success).toBe(true);
+ expect(spriteTrackGenerateSchema('scanner').safeParse({ direction: 'south', frameCount: 9 }).success).toBe(false);
+ expect(spriteTrackGenerateSchema('ambient').safeParse({ frameCount: 3, fps: 4 }).success).toBe(true);
+ expect(spriteTrackGenerateSchema('ambient').safeParse({ frameCount: 7 }).success).toBe(false);
+ });
+
+ it('builds every registered track\'s contract field into the runtime contract (#3136)', () => {
+ // The regression this replaces: each track's `contractFrameCountField` was
+ // a hand-written literal in the schema, so a new row's field was silently
+ // STRIPPED by Zod and the app rung of the target-precedence chain went
+ // dead for it with no error anywhere. Derived from the registry, every
+ // registered row's field is accepted at its own bounds by construction.
+ for (const id of ANIMATION_TRACK_IDS) {
+ const row = getAnimationTrack(id);
+ // Pair a non-primary track's field with walk's so the contract is
+ // publishable — this asserts the FIELD is known, not the primacy rule
+ // (covered below).
+ const base = { walkFrameCount: 12 };
+ expect(spriteRuntimeContractSchema.safeParse({
+ ...base, [row.contractFrameCountField]: row.defaultFrameCount,
+ }).success, `${id}.${row.contractFrameCountField} at its default`).toBe(true);
+ expect(spriteRuntimeContractSchema.safeParse({
+ ...base, [row.contractFrameCountField]: row.maxFrameCount + 1,
+ }).success, `${id}.${row.contractFrameCountField} above its max`).toBe(false);
+ }
+ });
+
+ it('requires a PRIMARY track\'s frame count, not just any track\'s (#3136)', () => {
+ // A primary track is the first registered one for some record kind — walk
+ // for a character, ambient for a place. A contract naming only a SECOND
+ // track on an existing kind (scanner) describes no publishable atlas,
+ // because the compiler requires the primary's finalized set before it
+ // emits anything at all.
+ const primaries = ANIMATION_TRACK_IDS.filter(
+ (id) => getAnimationTrack(id).kinds.some((kind) => tracksForKind(kind)[0]?.id === id),
+ );
+ expect(primaries).toEqual([WALK_TRACK, 'ambient']);
+ for (const id of primaries) {
+ expect(spriteRuntimeContractSchema.safeParse({
+ [getAnimationTrack(id).contractFrameCountField]: getAnimationTrack(id).defaultFrameCount,
+ }).success, `${id} alone is a publishable contract`).toBe(true);
+ }
+ expect(spriteRuntimeContractSchema.safeParse({ scannerFrameCount: 4 }).success).toBe(false);
});
});
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index d3a65a70e0..557217771b 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -22,10 +22,9 @@ import {
spriteReferenceLockSchema,
spriteReferenceUnlockSchema,
spriteForkSchema,
- spriteScannerGenerateSchema,
- spriteScannerApproveSchema,
- spriteAmbientGenerateSchema,
- spriteAmbientApproveSchema,
+ spriteTrackGenerateSchema,
+ spriteTrackApproveSchema,
+ spriteTrackParamsSchema,
spriteWalkGenerateSchema,
spriteWalkApproveSchema,
spriteWalkReopenSchema,
@@ -50,14 +49,17 @@ import {
listReferenceSources, listSpriteThumbnails, forkSprite,
} from '../services/sprites/reference.js';
import { resolveSpriteAssetPrompt } from '../services/sprites/assetPrompt.js';
-import { WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, kindSupportsTrack, tracksForKind } from '../services/sprites/animationTracks.js';
+import {
+ WALK_TRACK, ANIMATION_TRACK_IDS,
+ isAnimationTrack, kindSupportsTrack, tracksForKind,
+ getAnimationTrack as getAnimationTrackRow,
+} from '../services/sprites/animationTracks.js';
import {
getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
reopenWalkDirection, setWalkTarget, getWalkSourceFrames,
unlockDirectionalAnchor, unlockMainReference, unlockTurnaroundReference,
} from '../services/sprites/walk.js';
-import { getScannerState, startScannerGeneration, approveScannerDirection } from '../services/sprites/scanner.js';
-import { getAmbientState, startAmbientGeneration, approveAmbientLoop } from '../services/sprites/ambient.js';
+import { getTrackState, startTrackGeneration, approveTrackRun } from '../services/sprites/animationTrackWorkflow.js';
import { saveLoopTrim } from '../services/sprites/walkTrims.js';
import { compileAtlas, getAtlasState } from '../services/sprites/atlas.js';
import { setPublishBinding, publishAtlas } from '../services/sprites/publish.js';
@@ -68,6 +70,55 @@ const router = Router();
const MAX_REFERENCE_UPLOAD_BYTES = 20 * 1024 * 1024;
const ACCEPTED_REFERENCE_MIME = new Set(['image/png', 'image/jpeg', 'image/webp']);
+/**
+ * Validate + resolve the `:trackId` path param to a registered track id (#3136).
+ *
+ * Two distinct rejections, deliberately not collapsed: a malformed id is a 400
+ * from the shape schema, while a well-formed id that names no registered track is
+ * a 404 that LISTS the tracks — because "there is no such animation type" is a
+ * fact about the registry the user can act on, and a bare 400 would read as "your
+ * request was malformed" for a perfectly-formed one.
+ *
+ * `walk` is refused here on purpose: it keeps its own `/:id/walk/*` routes with
+ * reprocess, trims, per-direction reopen and set targets that the generic
+ * workflow does not implement, so accepting it would 404-on-disk later (walk
+ * writes `walk/<id>-walk-set-v1.json` through walk.js, not through this path)
+ * instead of failing here with a message that explains where to go.
+ */
+function resolveTrackParam(params) {
+ const { trackId } = validateRequest(spriteTrackParamsSchema, params);
+ if (trackId === WALK_TRACK) {
+ throw new ServerError(
+ 'The walk cycle has its own endpoints (/walk/generate, /walk/approve) — it carries reprocessing, trims, and set targets the generic track routes do not',
+ { status: 400, code: 'WALK_NOT_GENERIC' },
+ );
+ }
+ if (!isAnimationTrack(trackId)) {
+ throw new ServerError(
+ `Unknown animation track '${trackId}' — the registered tracks are: ${ANIMATION_TRACK_IDS.join(', ')}`,
+ { status: 404, code: 'UNKNOWN_ANIMATION_TRACK' },
+ );
+ }
+ return trackId;
+}
+
+/**
+ * A directional track needs a facing; a non-directional one derives row 0 itself.
+ *
+ * The generic request schema marks `direction` optional because ONE shape serves
+ * both, so this is where the requirement lands — asking the registry rather than
+ * restating which tracks are directional. Without it a directional generate with
+ * no `direction` would fall through to the service and 409 "lock the undefined
+ * anchor", blaming the reference set for a missing request field.
+ */
+function requireDirectionForTrack(trackId, body) {
+ if (!getAnimationTrackRow(trackId).directional || body.direction) return;
+ throw new ServerError(
+ `The ${trackId} track is directional — name the facing to animate`,
+ { status: 400, code: 'DIRECTION_REQUIRED' },
+ );
+}
+
const referenceUpload = optionalUploadFields(['referenceImage'], {
limits: { fileSize: MAX_REFERENCE_UPLOAD_BYTES },
// multer-style (req, file, cb) — streamMultipart requires the callback to
@@ -119,16 +170,23 @@ router.get('/:id', asyncHandler(async (req, res) => {
// records the registry had just admitted.
const { kind } = detail.record;
const runsWalk = kindSupportsTrack(kind, WALK_TRACK);
- const runsScanner = kindSupportsTrack(kind, SCANNER_TRACK);
- const runsAmbient = kindSupportsTrack(kind, AMBIENT_TRACK);
- const [reference, walk, scanner, ambient, atlas] = await Promise.all([
+ // Every non-walk track this record's kind may carry, resolved from the registry
+ // (#3136) instead of one hand-written `runsScanner`/`runsAmbient` flag per
+ // track. `definition` rides along so the client renders a track's label and
+ // bounds from the row rather than mirroring them as component copy — which is
+ // what lets ONE workflow component serve a track the client has never heard of.
+ const genericTracks = tracksForKind(kind).filter((row) => row.id !== WALK_TRACK);
+ const [reference, walk, atlas, ...trackStates] = await Promise.all([
tracksForKind(kind).length ? getReferenceSet(req.params.id) : null,
runsWalk ? getWalkState(req.params.id) : null,
- runsScanner ? getScannerState(req.params.id) : null,
- runsAmbient ? getAmbientState(req.params.id) : null,
tracksForKind(kind).length ? getAtlasState(req.params.id) : null,
+ ...genericTracks.map((row) => getTrackState(row.id, req.params.id)),
]);
- res.json({ ...detail, reference, walk, scanner, ambient, atlas });
+ const tracks = Object.fromEntries(genericTracks.map((row, index) => [
+ row.id,
+ { ...trackStates[index], definition: row },
+ ]));
+ res.json({ ...detail, reference, walk, tracks, atlas });
}));
// The generation prompt behind one on-disk asset (record-relative `path`) —
@@ -207,28 +265,27 @@ router.post('/:id/walk/generate', asyncHandler(async (req, res) => {
res.json(await startWalkGeneration(req.params.id, body));
}));
-// The scanner action is a distinct named track with its own short bounds and
-// its own finalized set. This endpoint is the only path that starts its Grok
-// render, preserving the no-cold-bootstrap provider contract.
-router.post('/:id/scanner/generate', asyncHandler(async (req, res) => {
- const body = validateRequest(spriteScannerGenerateSchema, req.body);
- res.json(await startScannerGeneration(req.params.id, body));
-}));
-
-router.post('/:id/scanner/approve', asyncHandler(async (req, res) => {
- const body = validateRequest(spriteScannerApproveSchema, req.body);
- res.json(await approveScannerDirection(req.params.id, body));
-}));
-
-// One user-requested image-to-video clip for the non-directional ambient row.
-router.post('/:id/ambient/generate', asyncHandler(async (req, res) => {
- const body = validateRequest(spriteAmbientGenerateSchema, req.body);
- res.json(await startAmbientGeneration(req.params.id, body));
-}));
-
-router.post('/:id/ambient/approve', asyncHandler(async (req, res) => {
- const body = validateRequest(spriteAmbientApproveSchema, req.body);
- res.json(await approveAmbientLoop(req.params.id, body));
+// Every non-walk animation track — the shipped `scanner`/`ambient` rows and any
+// later user-defined one — generates and approves through ONE pair of routes
+// (#3136). What used to be `/:id/scanner/generate` and `/:id/ambient/generate`
+// (two hand-written pairs that would have become N pairs) is now
+// `/:id/tracks/:trackId/generate`, with the track's bounds, facing count, source
+// reference, and prompt all resolved from its registry row.
+//
+// Generation stays the only path that starts a Grok render, preserving the
+// no-cold-bootstrap provider contract.
+router.post('/:id/tracks/:trackId/generate', asyncHandler(async (req, res) => {
+ const trackId = resolveTrackParam(req.params);
+ const body = validateRequest(spriteTrackGenerateSchema(trackId), req.body ?? {});
+ requireDirectionForTrack(trackId, body);
+ res.json(await startTrackGeneration(trackId, req.params.id, body));
+}));
+
+router.post('/:id/tracks/:trackId/approve', asyncHandler(async (req, res) => {
+ const trackId = resolveTrackParam(req.params);
+ const body = validateRequest(spriteTrackApproveSchema, req.body);
+ requireDirectionForTrack(trackId, body);
+ res.json(await approveTrackRun(trackId, req.params.id, body));
}));
// Approve one direction's packaged candidate; the 8th approval freezes the
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index 9fb826f215..397274bd23 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -68,10 +68,13 @@ vi.mock('../services/sprites/walk.js', () => ({
})),
}));
-vi.mock('../services/sprites/scanner.js', () => ({
- getScannerState: vi.fn(async () => ({ track: 'scanner', runs: [], selection: null, scannerSet: null })),
- startScannerGeneration: vi.fn(async () => ({ runId: 'scanner-east-0a1b2c3d', direction: 'east', duration: 6 })),
- approveScannerDirection: vi.fn(async () => ({ track: 'scanner', runs: [], selection: { status: 'in-progress' }, scannerSet: null })),
+// One mock for every non-walk track (#3136) — the generic workflow the
+// `/:id/tracks/:trackId/*` routes drive, echoing the track it was asked for so a
+// test can assert the route resolved the right one.
+vi.mock('../services/sprites/animationTrackWorkflow.js', () => ({
+ getTrackState: vi.fn(async (track) => ({ track, runs: [], selection: null, set: null })),
+ startTrackGeneration: vi.fn(async (track) => ({ runId: `${track}-east-0a1b2c3d`, direction: 'east', duration: 6 })),
+ approveTrackRun: vi.fn(async (track) => ({ track, runs: [], selection: { status: 'in-progress' }, set: null })),
}));
vi.mock('../services/sprites/walkTrims.js', () => ({
@@ -97,7 +100,7 @@ import * as importer from '../services/sprites/importer.js';
import * as reference from '../services/sprites/reference.js';
import * as assetPrompt from '../services/sprites/assetPrompt.js';
import * as walk from '../services/sprites/walk.js';
-import * as scanner from '../services/sprites/scanner.js';
+import * as trackWorkflow from '../services/sprites/animationTrackWorkflow.js';
import * as walkTrims from '../services/sprites/walkTrims.js';
import * as atlas from '../services/sprites/atlas.js';
import * as publish from '../services/sprites/publish.js';
@@ -442,22 +445,34 @@ describe('sprites routes', () => {
expect(assets.deleteSpriteAsset).not.toHaveBeenCalled();
});
- it('GET /:id includes the walk and scanner states for characters only', async () => {
+ it('GET /:id keys every non-walk track state by track id, per record kind (#3136)', async () => {
records.getRecordWithAssets.mockResolvedValueOnce({
record: { id: 'pioneer', kind: 'character' }, assets: [],
});
const r = await request(app).get('/api/sprites/pioneer');
expect(r.body.walk).toEqual({ runs: [], selection: null, walkSet: null });
- expect(r.body.scanner).toEqual({ track: 'scanner', runs: [], selection: null, scannerSet: null });
expect(walk.getWalkState).toHaveBeenCalledWith('pioneer');
- expect(scanner.getScannerState).toHaveBeenCalledWith('pioneer');
+ // A character carries scanner but NOT ambient, so only scanner is keyed —
+ // and the payload carries the registry row so the client renders the track's
+ // label/bounds from data rather than mirroring them.
+ expect(Object.keys(r.body.tracks)).toEqual(['scanner']);
+ expect(r.body.tracks.scanner).toMatchObject({
+ track: 'scanner', runs: [], selection: null, set: null,
+ definition: { id: 'scanner', label: 'Scanner action', directional: true },
+ });
+ expect(trackWorkflow.getTrackState).toHaveBeenCalledWith('scanner', 'pioneer');
records.getRecordWithAssets.mockResolvedValueOnce({
record: { id: 'crates', kind: 'props' }, assets: [],
});
const props = await request(app).get('/api/sprites/crates');
+ // A props family has no gait, so no walk — and ambient, not scanner. The
+ // whole point of keying by id: neither kind needs a route-level branch.
expect(props.body.walk).toBeNull();
- expect(props.body.scanner).toBeNull();
+ expect(Object.keys(props.body.tracks)).toEqual(['ambient']);
+ expect(props.body.tracks.ambient).toMatchObject({
+ track: 'ambient', definition: { id: 'ambient', directional: false },
+ });
});
it('POST /:id/walk/generate validates direction and duration', async () => {
@@ -488,22 +503,56 @@ describe('sprites routes', () => {
.send({ direction: 'east', fps: 99 })).status).toBe(400);
});
- it('POST /:id/scanner/generate validates scanner-specific short bounds', async () => {
- const r = await request(app).post('/api/sprites/pioneer/scanner/generate')
+ it('POST /:id/tracks/:trackId/generate bounds each track against its OWN row (#3136)', async () => {
+ trackWorkflow.startTrackGeneration.mockClear();
+ const r = await request(app).post('/api/sprites/pioneer/tracks/scanner/generate')
.send({ direction: 'east', frameCount: 4, fps: 6 });
expect(r.status).toBe(200);
- expect(scanner.startScannerGeneration).toHaveBeenCalledWith('pioneer', { direction: 'east', frameCount: 4, fps: 6 });
- expect((await request(app).post('/api/sprites/pioneer/scanner/generate')
+ expect(trackWorkflow.startTrackGeneration).toHaveBeenCalledWith('scanner', 'pioneer', { direction: 'east', frameCount: 4, fps: 6 });
+ // Scanner's own 2–8 / 2–12, not walk's 6–16 / 4–24.
+ expect((await request(app).post('/api/sprites/pioneer/tracks/scanner/generate')
.send({ direction: 'east', frameCount: 9 })).status).toBe(400);
- expect((await request(app).post('/api/sprites/pioneer/scanner/generate')
+ expect((await request(app).post('/api/sprites/pioneer/tracks/scanner/generate')
.send({ direction: 'east', fps: 13 })).status).toBe(400);
- });
-
- it('POST /:id/scanner/approve forwards a reviewed scanner candidate', async () => {
- const r = await request(app).post('/api/sprites/pioneer/scanner/approve')
+ // …and the SAME route bounds ambient against ITS 2–6, which is the property
+ // that makes a user-defined track's schema come for free.
+ expect((await request(app).post('/api/sprites/crates/tracks/ambient/generate')
+ .send({ frameCount: 3 })).status).toBe(200);
+ expect((await request(app).post('/api/sprites/crates/tracks/ambient/generate')
+ .send({ frameCount: 7 })).status).toBe(400);
+ });
+
+ it('POST /:id/tracks/:trackId/generate requires a facing only for a directional track', async () => {
+ // Without this the service would 409 "lock the undefined anchor", blaming
+ // the reference set for a missing request field.
+ expect((await request(app).post('/api/sprites/pioneer/tracks/scanner/generate').send({})).status).toBe(400);
+ // A non-directional track derives row 0 server-side, so no facing is needed.
+ expect((await request(app).post('/api/sprites/crates/tracks/ambient/generate').send({})).status).toBe(200);
+ });
+
+ it('POST /:id/tracks/:trackId/* refuses an unknown track and walk itself', async () => {
+ trackWorkflow.startTrackGeneration.mockClear();
+ // Well-formed but unregistered → 404 naming the known tracks, not a bare 400
+ // that reads as "your request was malformed".
+ const unknown = await request(app).post('/api/sprites/pioneer/tracks/jetpack/generate').send({ direction: 'east' });
+ expect(unknown.status).toBe(404);
+ expect(unknown.body.error).toMatch(/Unknown animation track 'jetpack'/);
+ // Malformed id → 400 from the shape schema.
+ expect((await request(app).post('/api/sprites/pioneer/tracks/Bad_Id/generate').send({ direction: 'east' })).status).toBe(400);
+ // Walk keeps its own endpoints (reprocess/trims/targets live there), so the
+ // generic route refuses it rather than writing walk state through a service
+ // that doesn't implement any of that.
+ const asWalk = await request(app).post('/api/sprites/pioneer/tracks/walk/generate').send({ direction: 'east' });
+ expect(asWalk.status).toBe(400);
+ expect(asWalk.body.error).toMatch(/walk cycle has its own endpoints/);
+ expect(trackWorkflow.startTrackGeneration).not.toHaveBeenCalled();
+ });
+
+ it('POST /:id/tracks/:trackId/approve forwards a reviewed candidate', async () => {
+ const r = await request(app).post('/api/sprites/pioneer/tracks/scanner/approve')
.send({ direction: 'east', runId: 'scanner-east-0a1b2c3d' });
expect(r.status).toBe(200);
- expect(scanner.approveScannerDirection).toHaveBeenCalledWith('pioneer', {
+ expect(trackWorkflow.approveTrackRun).toHaveBeenCalledWith('scanner', 'pioneer', {
direction: 'east', runId: 'scanner-east-0a1b2c3d',
});
});
diff --git a/server/services/sprites/ambient.js b/server/services/sprites/ambient.js
deleted file mode 100644
index 0afae117d4..0000000000
--- a/server/services/sprites/ambient.js
+++ /dev/null
@@ -1,287 +0,0 @@
-/**
- * The first real non-directional animation track: one ambient loop for a
- * place, object, or imported prop. The only provider call is the explicit
- * generate route; packing, review, approval, and atlas input are local.
- */
-
-import { join } from 'path';
-import { readdir } from 'fs/promises';
-import { randomUUID } from 'crypto';
-import { atomicWrite, ensureDir, pathExists, readJSONFile, sha256File } from '../../lib/fileUtils.js';
-import { ServerError } from '../../lib/errorHandler.js';
-import { executeTuiRun } from '../../lib/tuiPromptRunner.js';
-import { GROK_TUI_ID } from '../../lib/grok.js';
-import { getSettings } from '../settings.js';
-import { getRecord } from './records.js';
-import { requireTrack, loadManifest } from './reference.js';
-import { AMBIENT_TRACK, clampTrackFrameCount, clampTrackFps, getAnimationTrack } from './animationTracks.js';
-import { spriteDir, resolveSpriteAssetPath, SOURCE_CLIP_NAME } from './paths.js';
-import { prepareWalkAnchorChromaInput, runWalkPostprocess } from './walkPostprocess.js';
-import { verifyPackagedFrames } from './walkFrames.js';
-import { resolveChromaKey, withAnimationWriteTail } from './animationWorkflow.js';
-import { resolveGrokDuration } from '../../lib/grokVideoClip.js';
-import { buildAmbientVideoPrompt } from './prompts.js';
-
-const RUN_RECORD_NAME = 'animation-run.json';
-const AMBIENT_DIRECTION = 'south';
-const TUI_IDLE_MS = 90_000;
-const TUI_TIMEOUT_MS = 30 * 60_000;
-const selectionRelPath = (id) => `ambient/${id}-ambient-selection-v1.json`;
-export const ambientSetRelPath = (id) => `ambient/${id}-ambient-set-v1.json`;
-const runRelPath = (runId) => `runs/${runId}`;
-
-const ambientSetFinalError = () => new ServerError(
- 'Ambient loop is finalized and immutable',
- { status: 409, code: 'AMBIENT_SET_FINAL' },
-);
-
-const loadSelection = (recordId) => readJSONFile(join(spriteDir(recordId), selectionRelPath(recordId)), null);
-const loadSet = (recordId) => readJSONFile(join(spriteDir(recordId), ambientSetRelPath(recordId)), null);
-const loadRun = (recordId, runId) => readJSONFile(join(spriteDir(recordId), runRelPath(runId), RUN_RECORD_NAME), null);
-
-const seedSelection = (recordId) => ({
- schemaVersion: 1,
- kind: 'reviewed-single-row-ambient-selection',
- track: AMBIENT_TRACK,
- characterId: recordId,
- status: 'in-progress',
- directions: {},
-});
-
-async function saveRun(recordId, run) {
- const dir = join(spriteDir(recordId), runRelPath(run.id));
- await ensureDir(dir);
- await atomicWrite(join(dir, RUN_RECORD_NAME), run);
-}
-
-async function ambientRuns(recordId) {
- const runsDir = join(spriteDir(recordId), 'runs');
- const entries = await readdir(runsDir, { withFileTypes: true }).catch(() => []);
- const runs = await Promise.all(entries.filter((entry) => entry.isDirectory()).map((entry) => (
- readJSONFile(join(runsDir, entry.name, RUN_RECORD_NAME), null)
- )));
- return runs.filter((run) => run?.track === AMBIENT_TRACK)
- .sort((a, b) => Date.parse(b.createdAt || 0) - Date.parse(a.createdAt || 0));
-}
-
-export async function getAmbientState(recordId) {
- const [selection, ambientSet, runs] = await Promise.all([
- loadSelection(recordId), loadSet(recordId), ambientRuns(recordId),
- ]);
- return {
- track: AMBIENT_TRACK,
- bounds: getAnimationTrack(AMBIENT_TRACK),
- selection,
- ambientSet,
- runs,
- };
-}
-
-const lockedMain = (manifest) => (
- manifest?.mainReference?.locked && manifest.mainReference.path ? manifest.mainReference : null
-);
-
-const ambientTask = ({ prompt, inputAbs, videoAbs, duration }) => (
- `${prompt}\n\nUse your built-in image_to_video tool to animate this exact image for ${duration} seconds:\n${inputAbs}\n\n`
- + `Save the resulting animation as an MP4 file at exactly this path:\n${videoAbs}\n\n`
- + 'Do not create or modify any other files, and do not run any tools beyond what is needed to render and save that MP4.'
-);
-
-export function startAmbientGeneration(recordId, body) {
- return withAnimationWriteTail(recordId, () => startAmbientGenerationImpl(recordId, body));
-}
-
-async function startAmbientGenerationImpl(recordId, body) {
- const [record, reference, ambientSet, existingRuns] = await Promise.all([
- requireTrack(recordId, AMBIENT_TRACK), loadManifest(recordId), loadSet(recordId), ambientRuns(recordId),
- ]);
- if (ambientSet) throw ambientSetFinalError();
- const main = lockedMain(reference);
- if (!main) throw new ServerError('Lock the main reference before generating an ambient loop', { status: 409, code: 'MAIN_NOT_LOCKED' });
- const chromaKey = resolveChromaKey({ manifest: reference, record });
- if (!chromaKey) throw new ServerError('No frozen chroma key is available for this sprite', { status: 409, code: 'CHROMA_KEY_REQUIRED' });
- if (existingRuns.some((run) => ['rendering', 'postprocessing'].includes(run.status))) {
- throw new ServerError('An ambient render is already in progress', { status: 409, code: 'AMBIENT_RENDER_IN_PROGRESS' });
- }
-
- const frameCount = clampTrackFrameCount(body.frameCount, AMBIENT_TRACK);
- const fps = clampTrackFps(body.fps, AMBIENT_TRACK);
- // Optional re-roll note (#3134) — blank leaves the prompt and the run record
- // exactly as a blind regenerate would.
- const correctionPrompt = typeof body.correctionPrompt === 'string' ? body.correctionPrompt.trim() : '';
- const runId = `${AMBIENT_TRACK}-${randomUUID().slice(0, 8)}`;
- const runRel = runRelPath(runId);
- const generatedAbs = join(spriteDir(recordId), runRel, 'generated');
- await ensureDir(generatedAbs);
- const mainAbs = resolveSpriteAssetPath(recordId, main.path);
- if (!await pathExists(mainAbs)) throw new ServerError('Locked main reference file is missing on disk', { status: 500, code: 'MAIN_REFERENCE_MISSING' });
- const inputAbs = join(generatedAbs, 'input-main-chroma.png');
- const [{ preparation, sha256: inputSha256 }, settings] = await Promise.all([
- prepareWalkAnchorChromaInput(mainAbs, inputAbs, chromaKey), getSettings(),
- ]);
- const duration = resolveGrokDuration(body.duration);
- const videoAbs = join(generatedAbs, SOURCE_CLIP_NAME);
- const run = {
- schemaVersion: 1,
- kind: 'grok-game-animation-frames-run',
- track: AMBIENT_TRACK,
- provider: GROK_TUI_ID,
- status: 'rendering',
- id: runId,
- shellSession: runId,
- characterId: recordId,
- direction: AMBIENT_DIRECTION,
- chromaKey,
- duration,
- frameCount,
- fps,
- anchorPath: main.path,
- anchorSha256: main.sha256 || await sha256File(mainAbs),
- animationInputPath: `${runRel}/generated/input-main-chroma.png`,
- animationInputSha256: inputSha256,
- animationInputPreparation: preparation,
- ...(correctionPrompt ? { correctionPrompt } : {}),
- createdAt: new Date().toISOString(),
- };
- await saveRun(recordId, run);
- runAmbientTuiRender(recordId, {
- runId,
- generatedAbs,
- videoAbs,
- grokPath: settings.imageGen?.grok?.grokPath,
- task: ambientTask({
- prompt: buildAmbientVideoPrompt({ name: record.name, kind: record.kind, chromaKey, correctionPrompt }),
- inputAbs,
- videoAbs,
- duration,
- }),
- }).catch((err) => console.error(`❌ sprite ambient grok-tui render crashed ${recordId}/${runId}: ${err?.message || err}`));
- console.log(`📡 sprite ambient grok-tui render started ${recordId}/${runId}`);
- return { runId, duration, shellSession: runId };
-}
-
-async function runAmbientTuiRender(recordId, { runId, generatedAbs, videoAbs, grokPath, task }) {
- await executeTuiRun({
- runId,
- provider: { id: GROK_TUI_ID, type: 'tui', command: grokPath || 'grok', args: [] },
- prompt: task,
- workspacePath: generatedAbs,
- idleMs: TUI_IDLE_MS,
- timeout: TUI_TIMEOUT_MS,
- label: `sprite ambient ${recordId}`,
- }).catch((err) => console.error(`❌ sprite ambient grok-tui run failed ${recordId}/${runId}: ${err?.message || err}`));
- await withAnimationWriteTail(recordId, () => attachAmbientTuiResult(recordId, runId, videoAbs));
-}
-
-export async function attachAmbientTuiResult(recordId, runId, videoAbs) {
- const run = await loadRun(recordId, runId);
- if (!run || run.track !== AMBIENT_TRACK || await loadSet(recordId)) return;
- const selection = await loadSelection(recordId);
- if (selection?.directions?.[AMBIENT_DIRECTION]?.runId === runId) return;
- if (!await pathExists(videoAbs)) {
- run.status = 'error';
- run.postprocessError = 'Grok finished without writing the ambient video — check the shell session output';
- run.completedAt = new Date().toISOString();
- await saveRun(recordId, run);
- return;
- }
- run.status = 'postprocessing';
- run.sourceVideoPath = `${runRelPath(run.id)}/generated/${SOURCE_CLIP_NAME}`;
- await saveRun(recordId, run);
- await packageAmbientRun(recordId, run);
- await saveRun(recordId, run);
-}
-
-async function packageAmbientRun(recordId, run) {
- try {
- const [reference, record] = await Promise.all([loadManifest(recordId), getRecord(recordId)]);
- const main = lockedMain(reference);
- if (!main) throw new Error('No locked main reference in the reference manifest');
- const chromaKey = resolveChromaKey({ manifest: reference, record, run });
- if (!chromaKey) throw new Error('No chroma key is available for the ambient matte');
- const runRel = runRelPath(run.id);
- const result = await runWalkPostprocess({
- recordId,
- track: AMBIENT_TRACK,
- direction: AMBIENT_DIRECTION,
- chromaKey,
- runAbs: join(spriteDir(recordId), runRel),
- runRel,
- anchorRel: main.path,
- anchorAbs: resolveSpriteAssetPath(recordId, main.path),
- videoAbs: resolveSpriteAssetPath(recordId, run.sourceVideoPath),
- frameCount: clampTrackFrameCount(run.frameCount, AMBIENT_TRACK),
- fps: clampTrackFps(run.fps, AMBIENT_TRACK),
- });
- run.frameCount = result.manifest.frameCount;
- run.fps = result.manifest.frameRate;
- run.status = 'candidate';
- run.postprocessManifest = result.manifestPath;
- run.stripPreview = result.stripPreview;
- delete run.postprocessError;
- } catch (err) {
- run.status = 'error';
- run.postprocessError = err.message;
- console.error(`❌ sprite ambient postprocess failed ${recordId}/${run.id}: ${err.message}`);
- }
- run.completedAt = new Date().toISOString();
-}
-
-export function approveAmbientLoop(recordId, args) {
- return withAnimationWriteTail(recordId, () => approveAmbientLoopImpl(recordId, args));
-}
-
-async function approveAmbientLoopImpl(recordId, { runId }) {
- await requireTrack(recordId, AMBIENT_TRACK);
- if (await loadSet(recordId)) throw ambientSetFinalError();
- const run = await loadRun(recordId, runId);
- if (!run || run.track !== AMBIENT_TRACK) throw new ServerError(`Unknown ambient run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });
- if (run.status !== 'candidate' || !run.postprocessManifest) throw new ServerError('Run has no packaged candidate to approve', { status: 409, code: 'RUN_NOT_CANDIDATE' });
- const [reference, packaged] = await Promise.all([
- loadManifest(recordId), readJSONFile(resolveSpriteAssetPath(recordId, run.postprocessManifest), null),
- ]);
- const main = lockedMain(reference);
- if (!main) throw new ServerError('Lock the main reference before approving its ambient loop', { status: 409, code: 'MAIN_NOT_LOCKED' });
- if (run.anchorSha256) {
- const currentMainSha256 = main.sha256 || await sha256File(resolveSpriteAssetPath(recordId, main.path));
- if (run.anchorSha256 !== currentMainSha256) {
- throw new ServerError('This ambient loop was rendered from an older main reference — generate it again from the current reference', { status: 409, code: 'RUN_ANCHOR_STALE' });
- }
- }
- if (!packaged || packaged.track !== AMBIENT_TRACK || packaged.direction !== AMBIENT_DIRECTION || packaged.characterId !== recordId
- || packaged.frameCount !== run.frameCount || packaged.frameRate !== run.fps) {
- throw new ServerError('Packaged ambient manifest is missing or inconsistent', { status: 409, code: 'RUN_MANIFEST_INVALID' });
- }
- const frameCheck = await verifyPackagedFrames(recordId, packaged, { track: AMBIENT_TRACK });
- if (frameCheck.missing) throw new ServerError(
- `${frameCheck.missing} of this ambient run's ${frameCheck.total} packaged frames are missing on disk`,
- { status: 409, code: 'RUN_FRAMES_MISSING' },
- );
- const selection = (await loadSelection(recordId)) || seedSelection(recordId);
- selection.directions[AMBIENT_DIRECTION] = {
- status: 'approved',
- runId,
- runPath: runRelPath(runId),
- runManifest: run.postprocessManifest,
- runManifestSha256: await sha256File(resolveSpriteAssetPath(recordId, run.postprocessManifest)),
- approvedAt: new Date().toISOString(),
- };
- selection.status = 'complete';
- const selectionAbs = join(spriteDir(recordId), selectionRelPath(recordId));
- await ensureDir(join(spriteDir(recordId), AMBIENT_TRACK));
- await atomicWrite(selectionAbs, selection);
- await atomicWrite(join(spriteDir(recordId), ambientSetRelPath(recordId)), {
- schemaVersion: 1,
- kind: 'finalized-single-row-ambient-set',
- track: AMBIENT_TRACK,
- characterId: recordId,
- status: 'final',
- directionOrder: [AMBIENT_DIRECTION],
- selectionPath: selectionRelPath(recordId),
- selectionSha256: await sha256File(selectionAbs),
- directions: selection.directions,
- finalizedAt: new Date().toISOString(),
- });
- console.log(`🏁 sprite ambient loop finalized for ${recordId}`);
- return getAmbientState(recordId);
-}
diff --git a/server/services/sprites/ambient.test.js b/server/services/sprites/ambient.test.js
deleted file mode 100644
index 7b01472148..0000000000
--- a/server/services/sprites/ambient.test.js
+++ /dev/null
@@ -1,123 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
-import { mkdtempSync, rmSync } from 'fs';
-import { tmpdir } from 'os';
-import { join } from 'path';
-import { mkdir, writeFile } from 'fs/promises';
-import { createHash } from 'crypto';
-import { placeCandidate } from './spriteTestFixtures.js';
-
-const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-ambient-test-'));
-
-vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
- const actual = await importOriginal();
- Object.assign(actual.PATHS, {
- data: TEST_ROOT,
- sprites: join(TEST_ROOT, 'sprites'),
- images: join(TEST_ROOT, 'images'),
- videos: join(TEST_ROOT, 'videos'),
- });
- return actual;
-});
-
-const executeTuiRun = vi.fn(() => new Promise(() => {}));
-vi.mock('../../lib/tuiPromptRunner.js', () => ({
- executeTuiRun: (...args) => executeTuiRun(...args),
-}));
-
-vi.mock('../settings.js', () => ({
- getSettings: async () => ({ imageGen: { grok: { grokPath: '/usr/local/bin/grok' } } }),
-}));
-
-const prepareWalkAnchorChromaInput = vi.fn(async (_mainAbs, inputAbs) => {
- await mkdir(join(inputAbs, '..'), { recursive: true });
- const bytes = Buffer.from('ambient-chroma-input');
- await writeFile(inputAbs, bytes);
- return {
- preparation: 'composited-over-solid-chroma-matte',
- sha256: createHash('sha256').update(bytes).digest('hex'),
- };
-});
-vi.mock('./walkPostprocess.js', async (importOriginal) => ({
- ...await importOriginal(),
- prepareWalkAnchorChromaInput: (...args) => prepareWalkAnchorChromaInput(...args),
-}));
-
-const records = await import('./records.js');
-const { lockReference } = await import('./reference.js');
-const { getAmbientState, startAmbientGeneration } = await import('./ambient.js');
-
-let sequence = 0;
-const newId = () => `ambient-${++sequence}`;
-
-async function placeWithLockedMain(id) {
- await records.createRecord({ kind: 'place', name: 'Willow' }, id);
- const candidate = await placeCandidate(TEST_ROOT, id, 'main', 'main-candidate-01.png');
- await lockReference(id, { target: 'main', candidate });
- return id;
-}
-
-beforeEach(() => {
- executeTuiRun.mockClear();
- executeTuiRun.mockImplementation(() => new Promise(() => {}));
- prepareWalkAnchorChromaInput.mockClear();
- rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });
-});
-afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
-
-describe('ambient animation track', () => {
- it('is provider-silent on reads, then starts one explicit non-directional image-to-video loop', async () => {
- const id = await placeWithLockedMain(newId());
-
- const initial = await getAmbientState(id);
- expect(initial).toMatchObject({
- track: 'ambient',
- bounds: { minFrameCount: 2, maxFrameCount: 6, defaultFrameCount: 3, defaultFps: 4 },
- runs: [],
- });
- expect(executeTuiRun).not.toHaveBeenCalled();
-
- const result = await startAmbientGeneration(id, {});
- expect(result).toMatchObject({ duration: 6 });
- expect(result.runId).toMatch(/^ambient-[0-9a-f]{8}$/);
- expect(result.shellSession).toBe(result.runId);
- expect(executeTuiRun).toHaveBeenCalledOnce();
- expect(executeTuiRun.mock.calls[0][0]).toMatchObject({
- runId: result.runId,
- workspacePath: join(TEST_ROOT, 'sprites', id, 'runs', result.runId, 'generated'),
- });
- expect(executeTuiRun.mock.calls[0][0].prompt).toContain('image_to_video');
-
- expect((await getAmbientState(id)).runs).toMatchObject([{
- id: result.runId,
- track: 'ambient',
- status: 'rendering',
- frameCount: 3,
- fps: 4,
- direction: 'south',
- }]);
- });
-
- it('appends a trimmed correction note to the loop prompt and stamps it on the run (#3134)', async () => {
- const id = await placeWithLockedMain(newId());
- const { runId } = await startAmbientGeneration(id, { correctionPrompt: ' the branches barely move ' });
- expect(executeTuiRun.mock.calls[0][0].prompt)
- .toContain('Important correction — apply this over the attached source image: the branches barely move');
- const { runs } = await getAmbientState(id);
- expect(runs.find((r) => r.id === runId).correctionPrompt).toBe('the branches barely move');
- });
-
- it('leaves a blank correction note out of the prompt and the run record (#3134)', async () => {
- // The task is `<loop prompt>\n\n<per-run paths>` — compare the prompt only.
- const loopPrompt = () => executeTuiRun.mock.calls[0][0].prompt.split('\n\n')[0];
- const plain = await placeWithLockedMain(newId());
- await startAmbientGeneration(plain, {});
- const blindPrompt = loopPrompt();
- executeTuiRun.mockClear();
-
- const blank = await placeWithLockedMain(newId());
- const { runId } = await startAmbientGeneration(blank, { correctionPrompt: ' ' });
- expect(loopPrompt()).toBe(blindPrompt);
- const { runs } = await getAmbientState(blank);
- expect(runs.find((r) => r.id === runId)).not.toHaveProperty('correctionPrompt');
- });
-});
diff --git a/server/services/sprites/animationTrackWorkflow.js b/server/services/sprites/animationTrackWorkflow.js
new file mode 100644
index 0000000000..2bad994e71
--- /dev/null
+++ b/server/services/sprites/animationTrackWorkflow.js
@@ -0,0 +1,483 @@
+/**
+ * The generic per-track animation workflow (#3136).
+ *
+ * `scanner.js` and `ambient.js` were two ~300-line copies of one control flow:
+ * load the track's review selection / finalized set / runs → require a locked
+ * source reference → prepare a chroma matte → start ONE user-requested Grok
+ * image-to-video render → package it deterministically → review → approve →
+ * freeze the set. Nothing about that sequence is scanner-shaped or ambient
+ * shaped; they differed only in three registry facts (#3136 promoted each to a
+ * field on the track row):
+ *
+ * - `sourceReference` which locked image seeds the render (`anchor` per
+ * facing, or the one `main`)
+ * - `directional` how many facings must be approved before the set freezes
+ * - `selectionKind` / `setKind` / `finalErrorCode`
+ * the on-disk discriminators and the 409 code
+ *
+ * plus one prompt builder. So this module is that flow ONCE, parameterized by
+ * track id, and a new animation type is a registry row + a prompt — not a fourth
+ * copy of this file. Walk deliberately stays on its own service (`walk.js`): it
+ * carries reprocess, loop trims, per-direction reopen, source-frame extraction
+ * and set-level targets that no other track has, and folding those in would make
+ * this module the union of every track's features rather than their intersection.
+ *
+ * **On-disk compatibility is exact, not approximate.** Every path, `kind`
+ * string, run field, error code and message this writes is byte-identical to
+ * what the two clones wrote, because installs already hold approved scanner sets
+ * and ambient loops whose evidence chain the atlas compiler re-verifies by those
+ * exact strings. The clone collapse is a code change only.
+ *
+ * The render is reachable only through `startTrackGeneration` — a direct user
+ * action per the AI-provider policy. Everything after Grok writes the MP4 is
+ * deterministic local packing, review, approval, and atlas input; no boot path
+ * or read endpoint calls a provider.
+ */
+
+import { join } from 'path';
+import { readdir, rm } from 'fs/promises';
+import { randomUUID } from 'crypto';
+import { atomicWrite, ensureDir, pathExists, readJSONFile, sha256File } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { executeTuiRun } from '../../lib/tuiPromptRunner.js';
+import { GROK_TUI_ID } from '../../lib/grok.js';
+import { resolveGrokDuration } from '../../lib/grokVideoClip.js';
+import { getSettings } from '../settings.js';
+import { getRecord } from './records.js';
+import { requireTrack, loadManifest } from './reference.js';
+import { SPRITE_DIRECTIONS, anchorIdForDirection } from './prompts.js';
+import { buildTrackVideoPrompt } from './trackPrompts.js';
+import { clampTrackFrameCount, clampTrackFps, getAnimationTrack } from './animationTracks.js';
+import { spriteDir, resolveSpriteAssetPath, SOURCE_CLIP_NAME } from './paths.js';
+import { prepareWalkAnchorChromaInput, runWalkPostprocess } from './walkPostprocess.js';
+import { verifyPackagedFrames } from './walkFrames.js';
+import { resolveChromaKey, withAnimationWriteTail } from './animationWorkflow.js';
+
+const RUN_RECORD_NAME = 'animation-run.json';
+const TUI_IDLE_MS = 90_000;
+const TUI_TIMEOUT_MS = 30 * 60_000;
+
+/**
+ * The single atlas row a non-directional track occupies.
+ *
+ * Row 0 of the grid is `SPRITE_DIRECTIONS[0]`, and `trackDirections()` already
+ * slices exactly that entry for a non-directional track — so this reads the
+ * facing list rather than restating `'south'`, keeping the authoring side and
+ * the compile side derived from one list. The ambient clone hardcoded the
+ * literal; the value is identical.
+ */
+const nonDirectionalRow = () => SPRITE_DIRECTIONS[0];
+
+/**
+ * The facings a track is authored across: every direction for a directional
+ * track, the single row 0 for a non-directional one. This is the authoring twin
+ * of `atlasGrid.trackDirections` — kept here rather than imported because
+ * atlasGrid reaches the grid/compile layer, and the authoring side needs only
+ * the registry's `directional` flag.
+ */
+export function trackAuthoringDirections(trackId) {
+ const row = getAnimationTrack(trackId);
+ return row.directional ? [...SPRITE_DIRECTIONS] : [nonDirectionalRow()];
+}
+
+// The on-disk layout, per track. `<track>/` subdirectory and `-<track>-` infix,
+// which is exactly what scanner.js and ambient.js each spelled for themselves.
+const selectionRelPath = (trackId, id) => `${trackId}/${id}-${trackId}-selection-v1.json`;
+export const trackSetRelPath = (trackId, id) => `${trackId}/${id}-${trackId}-set-v1.json`;
+const runRelPath = (runId) => `runs/${runId}`;
+
+const setFinalError = (row) => new ServerError(
+ row.directional
+ ? `${row.label} set is finalized — reopen it before generating or approving another ${row.label.toLowerCase()}`
+ : `${row.label} is finalized and immutable`,
+ { status: 409, code: row.finalErrorCode },
+);
+
+const loadSelection = (trackId, recordId) =>
+ readJSONFile(join(spriteDir(recordId), selectionRelPath(trackId, recordId)), null);
+const loadSet = (trackId, recordId) =>
+ readJSONFile(join(spriteDir(recordId), trackSetRelPath(trackId, recordId)), null);
+const loadRun = (recordId, runId) =>
+ readJSONFile(join(spriteDir(recordId), runRelPath(runId), RUN_RECORD_NAME), null);
+
+const seedSelection = (row, recordId) => ({
+ schemaVersion: 1,
+ kind: row.selectionKind,
+ track: row.id,
+ characterId: recordId,
+ status: 'in-progress',
+ directions: {},
+});
+
+async function saveRun(recordId, run) {
+ const dir = join(spriteDir(recordId), runRelPath(run.id));
+ await ensureDir(dir);
+ await atomicWrite(join(dir, RUN_RECORD_NAME), run);
+}
+
+/** Every run on disk belonging to `trackId`, newest first. */
+async function trackRuns(trackId, recordId) {
+ const runsDir = join(spriteDir(recordId), 'runs');
+ const entries = await readdir(runsDir, { withFileTypes: true }).catch(() => []);
+ const runs = await Promise.all(entries.filter((entry) => entry.isDirectory()).map((entry) => (
+ readJSONFile(join(runsDir, entry.name, RUN_RECORD_NAME), null)
+ )));
+ return runs.filter((run) => run?.track === trackId)
+ .sort((a, b) => Date.parse(b.createdAt || 0) - Date.parse(a.createdAt || 0));
+}
+
+/**
+ * The track's authoring state: `{ track, bounds, selection, set, runs }`.
+ *
+ * `set` is the generic key. The route layer additionally aliases it to the
+ * historical per-track key (`scannerSet` / `ambientSet`) so an existing client
+ * keeps reading the field it always did — see `routes/sprites.js`.
+ */
+export async function getTrackState(trackId, recordId) {
+ const row = getAnimationTrack(trackId);
+ const [selection, set, runs] = await Promise.all([
+ loadSelection(row.id, recordId), loadSet(row.id, recordId), trackRuns(row.id, recordId),
+ ]);
+ return { track: row.id, bounds: row, selection, set, runs };
+}
+
+/**
+ * The locked reference image this track's render is seeded from, or null.
+ *
+ * Two shapes behind one resolver so the caller never branches on
+ * `sourceReference`: a directional track reads THIS facing's locked anchor, a
+ * non-directional one reads the single locked main. `label` is what the
+ * "lock it first" 409 names, so the message points at the artifact the row
+ * actually asked for.
+ */
+function lockedSourceFor(row, manifest, direction) {
+ if (row.sourceReference === 'main') {
+ const main = manifest?.mainReference;
+ return main?.locked && main.path
+ ? { path: main.path, sha256: main.sha256 || null, label: 'main reference', inputName: 'input-main-chroma.png' }
+ : null;
+ }
+ const anchor = manifest?.anchors?.find((item) => item.direction === direction);
+ return anchor?.status === 'locked' && anchor.path
+ ? {
+ path: anchor.path,
+ sha256: anchor.sha256 || null,
+ label: `${anchorIdForDirection(direction)} anchor`,
+ inputName: 'input-anchor-chroma.png',
+ }
+ : null;
+}
+
+// The provider task wrapper — identical in both clones, verbatim.
+const trackTask = ({ prompt, inputAbs, videoAbs, duration }) => (
+ `${prompt}\n\nUse your built-in image_to_video tool to animate this exact image for ${duration} seconds:\n${inputAbs}\n\n`
+ + `Save the resulting animation as an MP4 file at exactly this path:\n${videoAbs}\n\n`
+ + 'Do not create or modify any other files, and do not run any tools beyond what is needed to render and save that MP4.'
+);
+
+export function startTrackGeneration(trackId, recordId, body) {
+ return withAnimationWriteTail(recordId, () => startTrackGenerationImpl(trackId, recordId, body));
+}
+
+async function startTrackGenerationImpl(trackId, recordId, body) {
+ const row = getAnimationTrack(trackId);
+ const [record, reference, existingSet, existingRuns] = await Promise.all([
+ requireTrack(recordId, row.id), loadManifest(recordId), loadSet(row.id, recordId), trackRuns(row.id, recordId),
+ ]);
+ if (existingSet) throw setFinalError(row);
+ // A non-directional track occupies exactly row 0, so its facing is derived
+ // from the registry rather than accepted from the request — no user-supplied
+ // direction can drift from what `trackDirections()` will later compile.
+ const direction = row.directional ? body.direction : nonDirectionalRow();
+ const source = lockedSourceFor(row, reference, direction);
+ if (!source) {
+ throw new ServerError(
+ `Lock the ${source?.label || (row.sourceReference === 'main' ? 'main reference' : `${anchorIdForDirection(direction)} anchor`)} before generating its ${row.label.toLowerCase()}`,
+ { status: 409, code: row.sourceReference === 'main' ? 'MAIN_NOT_LOCKED' : 'ANCHOR_NOT_LOCKED' },
+ );
+ }
+ const chromaKey = resolveChromaKey({ manifest: reference, record });
+ if (!chromaKey) throw new ServerError('No frozen chroma key is available for this sprite', { status: 409, code: 'CHROMA_KEY_REQUIRED' });
+ // In-flight guard, per facing for a directional track and per record for a
+ // single-row one (where "another facing" doesn't exist).
+ const inFlight = existingRuns.some((run) => (
+ ['rendering', 'postprocessing'].includes(run.status) && (!row.directional || run.direction === direction)
+ ));
+ if (inFlight) {
+ throw new ServerError(
+ row.directional
+ ? `A ${row.label.toLowerCase()} render for ${direction} is already in progress`
+ : `A ${row.label.toLowerCase()} render is already in progress`,
+ { status: 409, code: 'TRACK_RENDER_IN_PROGRESS' },
+ );
+ }
+
+ const frameCount = clampTrackFrameCount(body.frameCount, row.id);
+ const fps = clampTrackFps(body.fps, row.id);
+ // Optional re-roll note (#3134) — blank leaves the prompt and the run record
+ // exactly as a blind regenerate would.
+ const correctionPrompt = typeof body.correctionPrompt === 'string' ? body.correctionPrompt.trim() : '';
+ // Run ids stay in the clones' shapes: `<track>-<direction>-<uuid8>` for a
+ // directional track, `<track>-<uuid8>` for a single-row one.
+ const runId = row.directional
+ ? `${row.id}-${direction}-${randomUUID().slice(0, 8)}`
+ : `${row.id}-${randomUUID().slice(0, 8)}`;
+ const runRel = runRelPath(runId);
+ const generatedAbs = join(spriteDir(recordId), runRel, 'generated');
+ await ensureDir(generatedAbs);
+ const sourceAbs = resolveSpriteAssetPath(recordId, source.path);
+ if (!await pathExists(sourceAbs)) {
+ throw new ServerError(
+ `Locked ${source.label} file is missing on disk`,
+ { status: 500, code: row.sourceReference === 'main' ? 'MAIN_REFERENCE_MISSING' : 'ANCHOR_MISSING' },
+ );
+ }
+ const inputAbs = join(generatedAbs, source.inputName);
+ const [{ preparation, sha256: inputSha256 }, settings] = await Promise.all([
+ prepareWalkAnchorChromaInput(sourceAbs, inputAbs, chromaKey), getSettings(),
+ ]);
+ const duration = resolveGrokDuration(body.duration);
+ const videoAbs = join(generatedAbs, SOURCE_CLIP_NAME);
+ const run = {
+ schemaVersion: 1,
+ kind: 'grok-game-animation-frames-run',
+ track: row.id,
+ provider: GROK_TUI_ID,
+ status: 'rendering',
+ id: runId,
+ shellSession: runId,
+ characterId: recordId,
+ direction,
+ chromaKey,
+ duration,
+ frameCount,
+ fps,
+ // `anchorPath`/`anchorSha256` name the SOURCE reference whatever it was —
+ // the ambient clone already used these keys for the main reference, and the
+ // approve gate's staleness check reads them, so the spelling stays.
+ anchorPath: source.path,
+ anchorSha256: source.sha256 || await sha256File(sourceAbs),
+ animationInputPath: `${runRel}/generated/${source.inputName}`,
+ animationInputSha256: inputSha256,
+ animationInputPreparation: preparation,
+ ...(correctionPrompt ? { correctionPrompt } : {}),
+ createdAt: new Date().toISOString(),
+ };
+ await saveRun(recordId, run);
+ runTrackTuiRender(row, recordId, {
+ runId,
+ direction,
+ generatedAbs,
+ videoAbs,
+ grokPath: settings.imageGen?.grok?.grokPath,
+ task: trackTask({
+ prompt: buildTrackVideoPrompt(row.id, {
+ name: record.name, kind: record.kind, direction, chromaKey, correctionPrompt,
+ }),
+ inputAbs,
+ videoAbs,
+ duration,
+ }),
+ }).catch((err) => console.error(`❌ sprite ${row.id} grok-tui render crashed ${recordId}/${runId}: ${err?.message || err}`));
+ console.log(`📡 sprite ${row.id} grok-tui render started ${recordId}/${runId}`);
+ return row.directional
+ ? { runId, direction, duration, shellSession: runId }
+ : { runId, duration, shellSession: runId };
+}
+
+async function runTrackTuiRender(row, recordId, { runId, direction, generatedAbs, videoAbs, grokPath, task }) {
+ await executeTuiRun({
+ runId,
+ provider: { id: GROK_TUI_ID, type: 'tui', command: grokPath || 'grok', args: [] },
+ prompt: task,
+ workspacePath: generatedAbs,
+ idleMs: TUI_IDLE_MS,
+ timeout: TUI_TIMEOUT_MS,
+ label: row.directional ? `sprite ${row.id} ${recordId}/${direction}` : `sprite ${row.id} ${recordId}`,
+ }).catch((err) => console.error(`❌ sprite ${row.id} grok-tui run failed ${recordId}/${runId}: ${err?.message || err}`));
+ await withAnimationWriteTail(recordId, () => attachTrackTuiResult(row.id, recordId, runId, videoAbs));
+}
+
+export async function attachTrackTuiResult(trackId, recordId, runId, videoAbs) {
+ const row = getAnimationTrack(trackId);
+ const run = await loadRun(recordId, runId);
+ if (!run || run.track !== row.id || await loadSet(row.id, recordId)) return;
+ const selection = await loadSelection(row.id, recordId);
+ if (selection?.directions?.[run.direction]?.runId === runId) return;
+ if (!await pathExists(videoAbs)) {
+ run.status = 'error';
+ run.postprocessError = `Grok finished without writing the ${row.label.toLowerCase()} video — check the shell session output`;
+ run.completedAt = new Date().toISOString();
+ await saveRun(recordId, run);
+ return;
+ }
+ run.status = 'postprocessing';
+ run.sourceVideoPath = `${runRelPath(run.id)}/generated/${SOURCE_CLIP_NAME}`;
+ await saveRun(recordId, run);
+ await packageTrackRun(row, recordId, run);
+ await saveRun(recordId, run);
+}
+
+async function packageTrackRun(row, recordId, run) {
+ // Runs outside the request lifecycle (the TUI completion tail), so a throw
+ // here would take the process down rather than reaching error middleware —
+ // hence the try/catch, per the CLAUDE.md boundary exception.
+ try {
+ const [reference, record] = await Promise.all([loadManifest(recordId), getRecord(recordId)]);
+ const source = lockedSourceFor(row, reference, run.direction);
+ if (!source) throw new Error(`No locked ${row.sourceReference === 'main' ? 'main reference' : `${run.direction} anchor`} in the reference manifest`);
+ const chromaKey = resolveChromaKey({ manifest: reference, record, run });
+ if (!chromaKey) throw new Error(`No chroma key is available for the ${row.label.toLowerCase()} matte`);
+ const runRel = runRelPath(run.id);
+ const result = await runWalkPostprocess({
+ recordId,
+ track: row.id,
+ direction: run.direction,
+ chromaKey,
+ runAbs: join(spriteDir(recordId), runRel),
+ runRel,
+ anchorRel: source.path,
+ anchorAbs: resolveSpriteAssetPath(recordId, source.path),
+ videoAbs: resolveSpriteAssetPath(recordId, run.sourceVideoPath),
+ frameCount: clampTrackFrameCount(run.frameCount, row.id),
+ fps: clampTrackFps(run.fps, row.id),
+ });
+ run.frameCount = result.manifest.frameCount;
+ run.fps = result.manifest.frameRate;
+ run.status = 'candidate';
+ run.postprocessManifest = result.manifestPath;
+ run.stripPreview = result.stripPreview;
+ delete run.postprocessError;
+ } catch (err) {
+ run.status = 'error';
+ run.postprocessError = err.message;
+ console.error(`❌ sprite ${row.id} postprocess failed ${recordId}/${run.id}: ${err.message}`);
+ }
+ run.completedAt = new Date().toISOString();
+}
+
+export function approveTrackRun(trackId, recordId, args) {
+ return withAnimationWriteTail(recordId, () => approveTrackRunImpl(trackId, recordId, args));
+}
+
+async function approveTrackRunImpl(trackId, recordId, { direction: requested, runId }) {
+ const row = getAnimationTrack(trackId);
+ await requireTrack(recordId, row.id);
+ if (await loadSet(row.id, recordId)) throw setFinalError(row);
+ const direction = row.directional ? requested : nonDirectionalRow();
+ const label = row.label.toLowerCase();
+ const run = await loadRun(recordId, runId);
+ if (!run || run.track !== row.id) throw new ServerError(`Unknown ${label} run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });
+ if (run.direction !== direction) throw new ServerError(`Run ${runId} animates '${run.direction}', not '${direction}'`, { status: 400, code: 'RUN_DIRECTION_MISMATCH' });
+ if (run.status !== 'candidate' || !run.postprocessManifest) throw new ServerError('Run has no packaged candidate to approve', { status: 409, code: 'RUN_NOT_CANDIDATE' });
+ const [reference, packaged] = await Promise.all([
+ loadManifest(recordId), readJSONFile(resolveSpriteAssetPath(recordId, run.postprocessManifest), null),
+ ]);
+ const source = lockedSourceFor(row, reference, direction);
+ if (!source) {
+ throw new ServerError(
+ `Lock the ${row.sourceReference === 'main' ? 'main reference' : `${anchorIdForDirection(direction)} anchor`} before approving its ${label}`,
+ { status: 409, code: row.sourceReference === 'main' ? 'MAIN_NOT_LOCKED' : 'ANCHOR_NOT_LOCKED' },
+ );
+ }
+ if (run.anchorSha256) {
+ const currentSha256 = source.sha256 || await sha256File(resolveSpriteAssetPath(recordId, source.path));
+ if (run.anchorSha256 !== currentSha256) {
+ throw new ServerError(
+ `This ${label} was rendered from an older ${source.label} — generate it again from the current reference`,
+ { status: 409, code: 'RUN_ANCHOR_STALE' },
+ );
+ }
+ }
+ if (!packaged || packaged.track !== row.id || packaged.direction !== direction || packaged.characterId !== recordId
+ || packaged.frameCount !== run.frameCount || packaged.frameRate !== run.fps) {
+ throw new ServerError(`Packaged ${label} manifest is missing or inconsistent`, { status: 409, code: 'RUN_MANIFEST_INVALID' });
+ }
+ const frameCheck = await verifyPackagedFrames(recordId, packaged, { track: row.id });
+ if (frameCheck.missing) throw new ServerError(
+ `${frameCheck.missing} of this ${label} run's ${frameCheck.total} packaged frames are missing on disk`,
+ { status: 409, code: 'RUN_FRAMES_MISSING' },
+ );
+ const selection = (await loadSelection(row.id, recordId)) || seedSelection(row, recordId);
+ selection.directions[direction] = {
+ status: 'approved',
+ runId,
+ runPath: runRelPath(runId),
+ runManifest: run.postprocessManifest,
+ runManifestSha256: await sha256File(resolveSpriteAssetPath(recordId, run.postprocessManifest)),
+ approvedAt: new Date().toISOString(),
+ };
+ // How many facings must land before the set freezes is registry data, so a
+ // single-row track freezes on its first approval and a directional one on its
+ // eighth — the two clones' `allApproved` rules, unified.
+ const authoringDirections = trackAuthoringDirections(row.id);
+ const allApproved = authoringDirections.every((item) => selection.directions[item]?.status === 'approved');
+ selection.status = allApproved ? 'complete' : 'in-progress';
+ const selectionAbs = join(spriteDir(recordId), selectionRelPath(row.id, recordId));
+ await ensureDir(join(spriteDir(recordId), row.id));
+ await atomicWrite(selectionAbs, selection);
+ if (allApproved) {
+ await atomicWrite(join(spriteDir(recordId), trackSetRelPath(row.id, recordId)), {
+ schemaVersion: 1,
+ kind: row.setKind,
+ track: row.id,
+ characterId: recordId,
+ status: 'final',
+ directionOrder: authoringDirections,
+ selectionPath: selectionRelPath(row.id, recordId),
+ selectionSha256: await sha256File(selectionAbs),
+ directions: selection.directions,
+ finalizedAt: new Date().toISOString(),
+ });
+ console.log(`🏁 sprite ${row.id} set finalized for ${recordId}`);
+ }
+ return getTrackState(row.id, recordId);
+}
+
+/**
+ * Drop one facing's approval because the reference it was rendered from changed.
+ *
+ * Called from the reference-unlock paths in `walk.js`: a revised anchor or a
+ * regenerated turnaround must not leave a stale approved clip standing, since
+ * the atlas would then compile frames drawn from an image that no longer exists.
+ * Returns true when something was actually invalidated.
+ */
+export function invalidateTrackDirectionForAnchorRevision(trackId, recordId, { direction }) {
+ return withAnimationWriteTail(recordId, () => invalidateTrackDirectionImpl(trackId, recordId, direction));
+}
+
+/** Every facing of `trackId`, for a turnaround revision that resets them all. */
+export function invalidateTrackForTurnaroundRevision(trackId, recordId) {
+ return withAnimationWriteTail(recordId, async () => {
+ const invalidated = [];
+ for (const direction of trackAuthoringDirections(trackId)) {
+ // eslint-disable-next-line no-await-in-loop -- ordered: each facing's selection write must settle before the next reads it
+ if (await invalidateTrackDirectionImpl(trackId, recordId, direction)) invalidated.push(direction);
+ }
+ return invalidated;
+ });
+}
+
+async function invalidateTrackDirectionImpl(trackId, recordId, direction) {
+ const row = getAnimationTrack(trackId);
+ const [finalizedSet, loaded] = await Promise.all([loadSet(row.id, recordId), loadSelection(row.id, recordId)]);
+ const approved = loaded?.directions?.[direction] || finalizedSet?.directions?.[direction];
+ if (approved?.status !== 'approved') return false;
+ const selection = loaded || { ...seedSelection(row, recordId), directions: { ...(finalizedSet?.directions || {}) } };
+ if (finalizedSet) await rm(join(spriteDir(recordId), trackSetRelPath(row.id, recordId)), { force: true });
+ delete selection.directions[direction];
+ selection.status = 'in-progress';
+ await ensureDir(join(spriteDir(recordId), row.id));
+ await atomicWrite(join(spriteDir(recordId), selectionRelPath(row.id, recordId)), selection);
+ const run = approved.runId ? await loadRun(recordId, approved.runId) : null;
+ if (run?.track === row.id) {
+ await saveRun(recordId, {
+ ...run,
+ status: 'superseded-anchor',
+ supersededAt: new Date().toISOString(),
+ supersededReason: 'directional-anchor-revised',
+ });
+ }
+ console.log(`♻️ sprite ${row.id} direction ${recordId}/${direction} invalidated after anchor revision`);
+ return true;
+}
diff --git a/server/services/sprites/animationTrackWorkflow.test.js b/server/services/sprites/animationTrackWorkflow.test.js
new file mode 100644
index 0000000000..9984c9392d
--- /dev/null
+++ b/server/services/sprites/animationTrackWorkflow.test.js
@@ -0,0 +1,281 @@
+/**
+ * The generic per-track animation workflow (#3136).
+ *
+ * Replaces `scanner.test.js` + `ambient.test.js`, which asserted the same six
+ * behaviors twice against two copies of one control flow. Here every behavior is
+ * asserted ONCE, table-driven across both shipped non-walk tracks — which is the
+ * property that actually matters now: the module must read the track's registry
+ * row rather than branch on its id. A per-track copy of these assertions could
+ * pass while the module secretly `if (track === 'ambient')`d its way through.
+ *
+ * The two rows differ in exactly the ways the registry says they do — a
+ * directional track seeded per-facing from its locked anchor vs. a
+ * non-directional one seeded from the one locked main — so running one table over
+ * both is also the regression test for the fields #3136 introduced.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { mkdir, writeFile } from 'fs/promises';
+import { createHash } from 'crypto';
+import { lockAllAnchors, placeCandidate } from './spriteTestFixtures.js';
+
+const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-track-workflow-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ Object.assign(actual.PATHS, {
+ data: TEST_ROOT,
+ sprites: join(TEST_ROOT, 'sprites'),
+ images: join(TEST_ROOT, 'images'),
+ videos: join(TEST_ROOT, 'videos'),
+ });
+ return actual;
+});
+
+const executeTuiRun = vi.fn(() => new Promise(() => {}));
+vi.mock('../../lib/tuiPromptRunner.js', () => ({
+ executeTuiRun: (...args) => executeTuiRun(...args),
+}));
+
+vi.mock('../settings.js', () => ({
+ getSettings: async () => ({ imageGen: { grok: { grokPath: '/usr/local/bin/grok' } } }),
+}));
+
+const prepareWalkAnchorChromaInput = vi.fn(async (_sourceAbs, inputAbs) => {
+ await mkdir(join(inputAbs, '..'), { recursive: true });
+ const bytes = Buffer.from('track-chroma-input');
+ await writeFile(inputAbs, bytes);
+ return {
+ preparation: 'composited-over-solid-chroma-matte',
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ };
+});
+vi.mock('./walkPostprocess.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ prepareWalkAnchorChromaInput: (...args) => prepareWalkAnchorChromaInput(...args),
+}));
+
+const records = await import('./records.js');
+const { lockReference } = await import('./reference.js');
+const {
+ getTrackState, startTrackGeneration, approveTrackRun, trackAuthoringDirections, trackSetRelPath,
+} = await import('./animationTrackWorkflow.js');
+const { getAnimationTrack, SCANNER_TRACK, AMBIENT_TRACK } = await import('./animationTracks.js');
+
+let sequence = 0;
+const newId = () => `track-${++sequence}`;
+
+// One fixture per SOURCE-REFERENCE shape, not per track: a directional track
+// needs a locked anchor for the facing it animates, a non-directional one needs
+// the record's single locked main. That is the registry difference under test.
+async function characterWithEastAnchor(id) {
+ await records.createRecord({ kind: 'character', name: 'Placeholder Hero' }, id);
+ await lockAllAnchors(TEST_ROOT, id, { lockReference, directions: ['east'] });
+ return id;
+}
+
+async function placeWithLockedMain(id) {
+ await records.createRecord({ kind: 'place', name: 'Example Willow' }, id);
+ const candidate = await placeCandidate(TEST_ROOT, id, 'main', 'main-candidate-01.png');
+ await lockReference(id, { target: 'main', candidate });
+ return id;
+}
+
+// The table every behavior below runs over. `direction` is the facing the
+// generate call names (absent for a non-directional track, which derives row 0
+// itself) and `promptMarker` is a phrase only THAT track's prompt contains — so a
+// module that sent the wrong track's prompt fails here rather than at render time.
+const TRACKS = [
+ {
+ id: SCANNER_TRACK,
+ seed: characterWithEastAnchor,
+ body: { direction: 'east' },
+ expectedDirection: 'east',
+ runIdPattern: /^scanner-east-[0-9a-f]{8}$/,
+ promptMarker: 'scanner action',
+ correction: 'the sweep never returns to the start pose',
+ inputName: 'input-anchor-chroma.png',
+ },
+ {
+ id: AMBIENT_TRACK,
+ seed: placeWithLockedMain,
+ body: {},
+ expectedDirection: 'south',
+ runIdPattern: /^ambient-[0-9a-f]{8}$/,
+ promptMarker: 'ambient loop',
+ correction: 'the branches barely move',
+ inputName: 'input-main-chroma.png',
+ },
+];
+
+beforeEach(() => {
+ executeTuiRun.mockClear();
+ executeTuiRun.mockImplementation(() => new Promise(() => {}));
+ prepareWalkAnchorChromaInput.mockClear();
+ rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });
+});
+afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
+
+describe.each(TRACKS)('the generic workflow drives the $id track', (track) => {
+ const row = () => getAnimationTrack(track.id);
+
+ it('is provider-silent on reads, then starts one user-triggered render at the row\'s defaults', async () => {
+ const id = await track.seed(newId());
+
+ // The AI-provider policy: reading state must never reach a provider.
+ const initial = await getTrackState(track.id, id);
+ expect(initial).toMatchObject({
+ track: track.id,
+ bounds: {
+ minFrameCount: row().minFrameCount,
+ maxFrameCount: row().maxFrameCount,
+ defaultFrameCount: row().defaultFrameCount,
+ defaultFps: row().defaultFps,
+ },
+ selection: null,
+ set: null,
+ runs: [],
+ });
+ expect(executeTuiRun).not.toHaveBeenCalled();
+
+ const result = await startTrackGeneration(track.id, id, track.body);
+ expect(result).toMatchObject({ duration: 6 });
+ expect(result.runId).toMatch(track.runIdPattern);
+ expect(result.shellSession).toBe(result.runId);
+ expect(executeTuiRun).toHaveBeenCalledOnce();
+ const call = executeTuiRun.mock.calls[0][0];
+ expect(call).toMatchObject({
+ runId: result.runId,
+ workspacePath: join(TEST_ROOT, 'sprites', id, 'runs', result.runId, 'generated'),
+ });
+ // This track's OWN prompt, not a fallback to walk's.
+ expect(call.prompt).toContain(track.promptMarker);
+ expect(call.prompt).toContain('image_to_video');
+
+ // Defaults come from the row — the whole point of the parameterization.
+ expect((await getTrackState(track.id, id)).runs).toMatchObject([{
+ id: result.runId,
+ track: track.id,
+ status: 'rendering',
+ frameCount: row().defaultFrameCount,
+ fps: row().defaultFps,
+ direction: track.expectedDirection,
+ }]);
+ });
+
+ it('seeds the render from the reference its row names', async () => {
+ const id = await track.seed(newId());
+ const { runId } = await startTrackGeneration(track.id, id, track.body);
+ // A directional track prepares its facing's anchor; a non-directional one the
+ // single main. Distinguishable by the prepared input's filename, which is
+ // also what the run record stamps as provenance.
+ const [, inputAbs] = prepareWalkAnchorChromaInput.mock.calls[0];
+ expect(inputAbs.endsWith(track.inputName), `${track.id} prepares ${track.inputName}`).toBe(true);
+ const { runs } = await getTrackState(track.id, id);
+ const run = runs.find((r) => r.id === runId);
+ expect(run.animationInputPath).toBe(`runs/${runId}/generated/${track.inputName}`);
+ // `anchorPath` names whichever reference seeded it, and is what the approve
+ // gate's staleness check re-hashes.
+ expect(run.anchorPath).toBeTruthy();
+ expect(run.anchorSha256).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ it('clamps a requested frame count and fps into the row\'s range', async () => {
+ const id = await track.seed(newId());
+ const { runId } = await startTrackGeneration(track.id, id, {
+ ...track.body, frameCount: 999, fps: 999,
+ });
+ const { runs } = await getTrackState(track.id, id);
+ expect(runs.find((r) => r.id === runId)).toMatchObject({
+ frameCount: row().maxFrameCount,
+ fps: row().maxFps,
+ });
+ });
+
+ it('appends a trimmed correction note to the prompt and stamps it on the run (#3134)', async () => {
+ const id = await track.seed(newId());
+ const { runId } = await startTrackGeneration(track.id, id, {
+ ...track.body, correctionPrompt: ` ${track.correction} `,
+ });
+ expect(executeTuiRun.mock.calls[0][0].prompt)
+ .toContain(`Important correction — apply this over the attached source image: ${track.correction}`);
+ const { runs } = await getTrackState(track.id, id);
+ expect(runs.find((r) => r.id === runId).correctionPrompt).toBe(track.correction);
+ });
+
+ it('leaves a blank correction note out of the prompt and the run record (#3134)', async () => {
+ // The task is `<track prompt>\n\n<per-run paths>` — compare the prompt only.
+ const trackPrompt = () => executeTuiRun.mock.calls[0][0].prompt.split('\n\n')[0];
+ const plain = await track.seed(newId());
+ await startTrackGeneration(track.id, plain, track.body);
+ const blindPrompt = trackPrompt();
+ executeTuiRun.mockClear();
+
+ const blank = await track.seed(newId());
+ const { runId } = await startTrackGeneration(track.id, blank, { ...track.body, correctionPrompt: ' \n ' });
+ expect(trackPrompt()).toBe(blindPrompt);
+ const { runs } = await getTrackState(track.id, blank);
+ expect(runs.find((r) => r.id === runId)).not.toHaveProperty('correctionPrompt');
+ });
+
+ it('refuses a second in-flight render for the same target', async () => {
+ const id = await track.seed(newId());
+ await startTrackGeneration(track.id, id, track.body);
+ await expect(startTrackGeneration(track.id, id, track.body))
+ .rejects.toMatchObject({ status: 409, code: 'TRACK_RENDER_IN_PROGRESS' });
+ });
+
+ it('refuses to generate before the source reference is locked', async () => {
+ // A record with NO locked reference at all: the 409 must name the artifact
+ // this row asked for, and its code must distinguish the two shapes.
+ const id = newId();
+ await records.createRecord(
+ { kind: row().kinds[0] === 'character' ? 'character' : 'place', name: 'Unlocked' },
+ id,
+ );
+ await expect(startTrackGeneration(track.id, id, track.body)).rejects.toMatchObject({
+ status: 409,
+ code: row().sourceReference === 'main' ? 'MAIN_NOT_LOCKED' : 'ANCHOR_NOT_LOCKED',
+ });
+ expect(executeTuiRun).not.toHaveBeenCalled();
+ });
+
+ it('refuses to approve a run that was never packaged', async () => {
+ const id = await track.seed(newId());
+ const { runId } = await startTrackGeneration(track.id, id, track.body);
+ await expect(approveTrackRun(track.id, id, { ...track.body, runId }))
+ .rejects.toMatchObject({ status: 409, code: 'RUN_NOT_CANDIDATE' });
+ });
+
+ it('refuses to approve an unknown run id', async () => {
+ const id = await track.seed(newId());
+ await expect(approveTrackRun(track.id, id, { ...track.body, runId: 'no-such-run' }))
+ .rejects.toMatchObject({ status: 404, code: 'RUN_NOT_FOUND' });
+ });
+});
+
+describe('registry-derived authoring shape (#3136)', () => {
+ it('authors a directional track across every facing and a non-directional one across row 0 only', () => {
+ // The rule the two clones each hardcoded — `SPRITE_DIRECTIONS.every(...)` in
+ // one and "freeze on first approval" in the other — now derived from
+ // `directional`, which is what decides when a set is complete.
+ expect(trackAuthoringDirections(SCANNER_TRACK)).toHaveLength(8);
+ expect(trackAuthoringDirections(SCANNER_TRACK)[0]).toBe('south');
+ expect(trackAuthoringDirections(AMBIENT_TRACK)).toEqual(['south']);
+ });
+
+ it('keeps each track\'s on-disk set path in the shape its clone wrote', () => {
+ // Load-bearing for upgrades: installs already hold approved sets at these
+ // exact paths, and the atlas compiler re-verifies the evidence chain by them.
+ expect(trackSetRelPath(SCANNER_TRACK, 'pioneer')).toBe('scanner/pioneer-scanner-set-v1.json');
+ expect(trackSetRelPath(AMBIENT_TRACK, 'willow')).toBe('ambient/willow-ambient-set-v1.json');
+ });
+
+ it('throws for an unregistered track rather than defaulting to walk', async () => {
+ // The sentinel rule: a mis-keyed track must not silently author walk state.
+ await expect(getTrackState('jetpack', 'pioneer')).rejects.toThrow(/Unknown animation track 'jetpack'/);
+ });
+});
diff --git a/server/services/sprites/animationTracks.js b/server/services/sprites/animationTracks.js
index bfe2c90de7..99bead3779 100644
--- a/server/services/sprites/animationTracks.js
+++ b/server/services/sprites/animationTracks.js
@@ -38,6 +38,16 @@
* (`tracksForKind` / `kindSupportsTrack`) instead of naming a kind. Walk stays
* character-only, so behavior is unchanged today; a row that lists `place` is
* all it takes to unlock those records, with no gate edit anywhere.
+ *
+ * **The per-track WORKFLOW is registry data too (#3136).** `scanner` and
+ * `ambient` each shipped as a ~300-line clone of walk's state/start/package/
+ * approve/invalidate stack — identical control flow differing only in which
+ * reference image seeds the render, what the on-disk selection/set files are
+ * called, and which prompt text goes to the provider. Those three differences
+ * are now FIELDS on the row (`sourceReference`, `selectionKind`/`setKind`, and
+ * the workflow's prompt builder key), and `animationTrackWorkflow.js` is the one
+ * implementation both drive. A user-defined track is therefore a row plus a
+ * prompt template — no new service module, no new routes.
*/
/** The default track — the only one that exists today. */
@@ -47,6 +57,15 @@ export const SCANNER_TRACK = 'scanner';
/** The first non-directional environment loop (#3045). */
export const AMBIENT_TRACK = 'ambient';
+/**
+ * The locked reference artifacts a track's image-to-video render may be seeded
+ * from (#3136). A closed set: the generic workflow dispatches on it to decide
+ * which lock to require and which file to hand the provider, so an unrecognized
+ * spelling is a boot failure rather than a render that 409s on an artifact
+ * nothing declared.
+ */
+export const SOURCE_REFERENCES = Object.freeze(['anchor', 'main']);
+
/**
* Every known animation track.
*
@@ -66,6 +85,22 @@ export const AMBIENT_TRACK = 'ambient';
* the app rung of the precedence chain is track-driven rather than hard-coded
* to `walkFrameCount`. `contractFpsField` may be `null` for a track whose
* speed an app has no say in.
+ * - `sourceReference` (#3136) — which locked reference image the i2v render is
+ * seeded from: `'anchor'` (this facing's locked directional anchor) or
+ * `'main'` (the one locked main reference). A directional track needs a per
+ * facing anchor; a non-directional one has only the main to work from, which
+ * is why the two clones differed on this line and nowhere else structurally.
+ * - `selectionKind` / `setKind` (#3136) — the `kind` discriminators the track's
+ * on-disk review selection and finalized set carry. Registry data because the
+ * atlas compiler VALIDATES them (`atlas.js`), so a track's on-disk contract
+ * and the compiler's expectation cannot drift.
+ * - `finalErrorCode` (#3136) — the `code` on the 409 a finalized set answers
+ * generate/approve with. Named per row so an existing client that matches on
+ * `SCANNER_SET_FINAL` keeps working after the clone collapsed.
+ * - `builtin` (#3136) — true for a row compiled into this module. `walk` is the
+ * mandatory character baseline and can never be removed or edited; the other
+ * rows are ordinary registry data that a later phase moves into a
+ * user-editable store (see #3136's remaining children).
*/
export const ANIMATION_TRACKS = Object.freeze({
[WALK_TRACK]: Object.freeze({
@@ -89,6 +124,15 @@ export const ANIMATION_TRACKS = Object.freeze({
// nulled, because dropping it would change resolution behavior for those.
// A second track copying this row should decide its own answer.
contractFpsField: 'walkFps',
+ // Walk predates the generic workflow and keeps its own bespoke service
+ // (walk.js — reprocess, trims, per-direction reopen, source-frame
+ // extraction, set-level targets), so these describe its on-disk contract
+ // for the compiler's benefit without routing it through the generic module.
+ sourceReference: 'anchor',
+ selectionKind: 'reviewed-directional-walk-selection',
+ setKind: 'finalized-eight-direction-walk-set',
+ finalErrorCode: 'WALK_SET_FINAL',
+ builtin: true,
}),
[SCANNER_TRACK]: Object.freeze({
id: SCANNER_TRACK,
@@ -106,6 +150,16 @@ export const ANIMATION_TRACKS = Object.freeze({
contractFrameCountField: 'scannerFrameCount',
// The game owns action timing; PortOS carries fps as preview provenance.
contractFpsField: null,
+ // Every facing renders from its own locked anchor, so the run is seeded per
+ // direction exactly like walk's.
+ sourceReference: 'anchor',
+ // The historical on-disk spellings, kept verbatim: an already-approved
+ // scanner set on any install must keep validating after the clone collapsed
+ // into the generic workflow, and the compiler matches these exact strings.
+ selectionKind: 'reviewed-directional-scanner-selection',
+ setKind: 'finalized-eight-direction-scanner-set',
+ finalErrorCode: 'SCANNER_SET_FINAL',
+ builtin: true,
}),
[AMBIENT_TRACK]: Object.freeze({
id: AMBIENT_TRACK,
@@ -124,6 +178,14 @@ export const ANIMATION_TRACKS = Object.freeze({
// Ambient cadence belongs to the consuming app. PortOS keeps fps only as
// authoring-preview provenance, like scanner.
contractFpsField: null,
+ // A place has no facing and therefore no directional anchor — its one
+ // locked main reference is both the idle cell and the i2v source. This ONE
+ // field is the whole structural difference the ambient clone existed for.
+ sourceReference: 'main',
+ selectionKind: 'reviewed-single-row-ambient-selection',
+ setKind: 'finalized-single-row-ambient-set',
+ finalErrorCode: 'AMBIENT_SET_FINAL',
+ builtin: true,
}),
});
@@ -147,6 +209,7 @@ export const ANIMATION_TRACK_IDS = Object.freeze(Object.keys(ANIMATION_TRACKS));
*/
export function assertAnimationTrackRows(tracks) {
const claimedContractFields = new Map();
+ const claimedOnDiskKinds = new Map();
for (const id of Object.keys(tracks)) {
const row = tracks[id];
if (row.id !== id) throw new Error(`animationTracks: row '${id}' declares mismatched id '${row.id}'`);
@@ -169,6 +232,46 @@ export function assertAnimationTrackRows(tracks) {
if (row.contractFpsField !== null && (typeof row.contractFpsField !== 'string' || !row.contractFpsField)) {
throw new Error(`animationTracks: track '${id}' needs a contractFpsField (or null)`);
}
+ // #3136 — the workflow shape. `sourceReference` is a closed set because the
+ // generic workflow dispatches on it: a third spelling would silently resolve
+ // to no reference at all and every render would 409 "not locked" naming an
+ // artifact the row never asked for.
+ if (!SOURCE_REFERENCES.includes(row.sourceReference)) {
+ throw new Error(
+ `animationTracks: track '${id}' needs a sourceReference of ${SOURCE_REFERENCES.join(' or ')}, got '${String(row.sourceReference)}'`,
+ );
+ }
+ // A directional track renders one clip per facing, so it must seed from that
+ // facing's own anchor — seeding eight directional rows from the single main
+ // reference would render the same south-facing clip eight times and pass
+ // every later check, since the packer never sees which facing it was asked
+ // for. The inverse (a non-directional track pointed at 'anchor') has no
+ // anchor to read: a place record never generates directional anchors at all.
+ const expectedSource = row.directional ? 'anchor' : 'main';
+ if (row.sourceReference !== expectedSource) {
+ throw new Error(
+ `animationTracks: ${row.directional ? 'directional' : 'non-directional'} track '${id}' must seed from the ${expectedSource} reference, not '${row.sourceReference}'`,
+ );
+ }
+ for (const field of ['selectionKind', 'setKind', 'finalErrorCode']) {
+ if (typeof row[field] !== 'string' || !row[field]) {
+ throw new Error(`animationTracks: track '${id}' needs a non-empty '${field}'`);
+ }
+ }
+ if (typeof row.builtin !== 'boolean') throw new Error(`animationTracks: track '${id}' needs a boolean 'builtin'`);
+ // Two tracks sharing a selection/set `kind` is the same class of bug as two
+ // sharing a contract field: the compiler validates a set by its `kind`, so a
+ // duplicate would let one track's finalized set satisfy the other's evidence
+ // check and compile the wrong frames into its span.
+ for (const knob of ['selectionKind', 'setKind']) {
+ const owner = claimedOnDiskKinds.get(row[knob]);
+ if (owner) {
+ throw new Error(
+ `animationTracks: on-disk kind '${row[knob]}' is claimed by both '${owner.id}.${owner.knob}' and '${id}.${knob}'`,
+ );
+ }
+ claimedOnDiskKinds.set(row[knob], { id, knob });
+ }
for (const [min, def, max] of [
['minFrameCount', 'defaultFrameCount', 'maxFrameCount'],
['minFps', 'defaultFps', 'maxFps'],
diff --git a/server/services/sprites/animationTracks.test.js b/server/services/sprites/animationTracks.test.js
index 787ab3805b..0871fb350b 100644
--- a/server/services/sprites/animationTracks.test.js
+++ b/server/services/sprites/animationTracks.test.js
@@ -130,6 +130,12 @@ describe('the module-load row guard', () => {
const second = {
...walk, id: 'scanner', label: 'Scanner', minFrameCount: 3, defaultFrameCount: 4, maxFrameCount: 8,
contractFrameCountField: 'scannerFrameCount', contractFpsField: 'scannerFps',
+ // #3136: the on-disk `kind` discriminators are per-row unique for the same
+ // reason the contract fields are, so a row copy-pasted from walk's must
+ // rename them too or the guard (correctly) refuses it.
+ selectionKind: 'reviewed-directional-scanner-selection',
+ setKind: 'finalized-eight-direction-scanner-set',
+ finalErrorCode: 'SCANNER_SET_FINAL',
};
const twoRows = (overrides = {}) => ({ walk, scanner: { ...second, ...overrides } });
@@ -174,9 +180,40 @@ describe('the module-load row guard', () => {
['a default fps outside its range', { defaultFps: 99 }, /minFps <= defaultFps <= maxFps/],
['an empty contract frame-count field', { contractFrameCountField: '' }, /needs a contractFrameCountField/],
['an undefined contract fps field', { contractFpsField: undefined }, /contractFpsField \(or null\)/],
+ // #3136 — the workflow shape the generic track service dispatches on.
+ ['an unrecognized sourceReference', { sourceReference: 'turnaround' }, /sourceReference of anchor or main/],
+ ['a missing sourceReference', { sourceReference: undefined }, /sourceReference of anchor or main/],
+ ['a missing selectionKind', { selectionKind: '' }, /needs a non-empty 'selectionKind'/],
+ ['a missing setKind', { setKind: undefined }, /needs a non-empty 'setKind'/],
+ ['a missing finalErrorCode', { finalErrorCode: '' }, /needs a non-empty 'finalErrorCode'/],
+ ['a non-boolean builtin', { builtin: 'yes' }, /boolean 'builtin'/],
])('rejects %s', (_label, overrides, message) => {
expect(() => assertAnimationTrackRows(twoRows(overrides))).toThrow(message);
});
+
+ it('rejects a second row that copy-pastes walk\'s on-disk set kind (#3136)', () => {
+ // The mirror of the contract-field collision, one layer down: the atlas
+ // compiler validates a finalized set by its `kind`, so two tracks sharing
+ // one would let this track's set satisfy the OTHER's evidence check and
+ // compile the wrong frames into its span.
+ expect(() => assertAnimationTrackRows(twoRows({ setKind: 'finalized-eight-direction-walk-set' })))
+ .toThrow(/claimed by both 'walk\.setKind' and 'scanner\.setKind'/);
+ expect(() => assertAnimationTrackRows(twoRows({ selectionKind: 'reviewed-directional-walk-selection' })))
+ .toThrow(/claimed by both 'walk\.selectionKind' and 'scanner\.selectionKind'/);
+ });
+
+ it('binds sourceReference to directionality (#3136)', () => {
+ // A directional track seeded from the single `main` would render the SAME
+ // south-facing clip for all eight facings and pass every later check, since
+ // nothing downstream re-reads which facing was asked for. The inverse has no
+ // anchor to read at all — a place record never generates directional anchors.
+ expect(() => assertAnimationTrackRows(twoRows({ sourceReference: 'main' })))
+ .toThrow(/directional track 'scanner' must seed from the anchor reference/);
+ expect(() => assertAnimationTrackRows(twoRows({ directional: false, sourceReference: 'anchor' })))
+ .toThrow(/non-directional track 'scanner' must seed from the main reference/);
+ // …and the well-formed non-directional pairing is accepted.
+ expect(() => assertAnimationTrackRows(twoRows({ directional: false, sourceReference: 'main' }))).not.toThrow();
+ });
});
describe('getAnimationTrack — absent vs unrecognized', () => {
diff --git a/server/services/sprites/assetPrompt.js b/server/services/sprites/assetPrompt.js
index 95782f38ed..000346a7a8 100644
--- a/server/services/sprites/assetPrompt.js
+++ b/server/services/sprites/assetPrompt.js
@@ -33,10 +33,10 @@ import { getRecord } from './records.js';
import { loadManifest } from './reference.js';
import {
buildMainReferencePrompt, buildAmbientReferencePrompt, buildAnchorPrompt,
- buildWalkVideoPrompt, buildAmbientVideoPrompt, buildScannerPrompt,
buildTurnaroundPrompt, TURNAROUND_ID,
} from './prompts.js';
-import { AMBIENT_TRACK, SCANNER_TRACK } from './animationTracks.js';
+import { buildTrackVideoPrompt, hasTrackVideoPrompt } from './trackPrompts.js';
+import { WALK_TRACK } from './animationTracks.js';
import { DEFAULT_CHROMA_KEY } from './chromaKey.js';
const CANDIDATE_RE = /^reference\/candidates\/(.+)\.png$/i;
@@ -178,16 +178,25 @@ export async function resolveSpriteAssetPrompt(recordId, relPath) {
const runRecord = await readJSONFile(join(spriteDir(recordId), run[0], 'animation-run.json'), null);
if (runRecord?.direction) {
const { chromaKey, correctionPrompt, track } = runRecord;
- const rebuild = () => {
- if (track === AMBIENT_TRACK) return buildAmbientVideoPrompt({ name, kind: record.kind, chromaKey, correctionPrompt });
- if (track === SCANNER_TRACK) return buildScannerPrompt({ name, direction: runRecord.direction, chromaKey, correctionPrompt });
- return buildWalkVideoPrompt({ name, direction: runRecord.direction, chromaKey, correctionPrompt });
- };
- return {
- prompt: typeof runRecord.prompt === 'string' && runRecord.prompt ? runRecord.prompt : rebuild(),
- designPrompt: null,
- source: track === AMBIENT_TRACK ? 'ambient' : track === SCANNER_TRACK ? 'scanner' : 'walk',
- };
+ // One dispatch through `buildTrackVideoPrompt` (#3136) rather than a
+ // per-track branch here — so a user-defined track's provenance rebuilds
+ // with its own prompt instead of silently falling through to walk's.
+ // An UNREGISTERED track (a run written by a newer peer, or one whose row
+ // the user has since deleted) can't be rebuilt at all: report the prompt
+ // the run itself stamped, and otherwise null, rather than mislabelling it
+ // as a walk. `source` is the track id, which is what it always was for
+ // the shipped rows.
+ const rebuild = () => (
+ hasTrackVideoPrompt(track ?? WALK_TRACK)
+ ? buildTrackVideoPrompt(track ?? WALK_TRACK, {
+ name, kind: record.kind, direction: runRecord.direction, chromaKey, correctionPrompt,
+ })
+ : null
+ );
+ const stamped = typeof runRecord.prompt === 'string' && runRecord.prompt ? runRecord.prompt : null;
+ const prompt = stamped ?? rebuild();
+ if (!prompt) return null;
+ return { prompt, designPrompt: null, source: track ?? WALK_TRACK };
}
}
diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.js
index 3ddd3ed53c..9ffea83ea3 100644
--- a/server/services/sprites/atlas.js
+++ b/server/services/sprites/atlas.js
@@ -51,7 +51,7 @@ import {
} from './walkPostprocess.js';
import { ATLAS_IDLE_COLUMN } from './walkBounds.js';
import {
- WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, ANIMATION_TRACK_IDS, kindSupportsTrack,
+ WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK, ANIMATION_TRACK_IDS, kindSupportsTrack, getAnimationTrack,
} from './animationTracks.js';
import {
buildAtlasGrid, resolveTrackUniformity, compiledGridUpToDate, trackDirections,
@@ -59,8 +59,7 @@ import {
import {
withWalkWriteTail, walkSetRelPath, importedWalkDirections, resolveChromaKey,
} from './walk.js';
-import { scannerSetRelPath } from './scanner.js';
-import { ambientSetRelPath } from './ambient.js';
+import { trackSetRelPath } from './animationTrackWorkflow.js';
import { verifyPackagedFrames } from './walkFrames.js';
import { getRecord } from './records.js';
@@ -372,7 +371,7 @@ export async function validateForCompile(recordId) {
// `trackDirections` is called ONCE per track and the result kept, so the
// facings a track was collected against and the count it is later held to are
// the same value rather than two derivations that could drift.
- const scannerSetRel = scannerSetRelPath(recordId);
+ const scannerSetRel = trackSetRelPath(SCANNER_TRACK, recordId);
const scannerSetBytes = await readFile(join(dir, scannerSetRel)).catch(() => null);
let scannerSet = null;
if (scannerSetBytes) {
@@ -381,7 +380,10 @@ export async function validateForCompile(recordId) {
} catch {
throw compileError('Scanner set manifest is unreadable');
}
- if (scannerSet.kind !== 'finalized-eight-direction-scanner-set' || scannerSet.track !== SCANNER_TRACK
+ // `setKind` comes from the registry row (#3136) rather than a literal, so
+ // the track that WRITES the set and the compiler that re-verifies it share
+ // one definition — the same single-source rule the contract fields follow.
+ if (scannerSet.kind !== getAnimationTrack(SCANNER_TRACK).setKind || scannerSet.track !== SCANNER_TRACK
|| scannerSet.status !== 'final' || scannerSet.characterId !== recordId
|| JSON.stringify(scannerSet.directionOrder) !== JSON.stringify(SPRITE_DIRECTIONS)) {
throw compileError('Scanner set manifest is not a finalized directional scanner set');
@@ -509,7 +511,7 @@ async function validateAmbientForCompile(recordId, record) {
return bytes;
};
const dir = spriteDir(recordId);
- const setRel = ambientSetRelPath(recordId);
+ const setRel = trackSetRelPath(AMBIENT_TRACK, recordId);
const setBytes = await readFile(join(dir, setRel)).catch(() => null);
if (!setBytes) throw compileError('No finalized ambient loop — approve its single row first', 'AMBIENT_SET_REQUIRED');
let ambientSet;
@@ -518,7 +520,7 @@ async function validateAmbientForCompile(recordId, record) {
} catch {
throw compileError('Ambient set manifest is unreadable');
}
- if (ambientSet.kind !== 'finalized-single-row-ambient-set' || ambientSet.track !== AMBIENT_TRACK
+ if (ambientSet.kind !== getAnimationTrack(AMBIENT_TRACK).setKind || ambientSet.track !== AMBIENT_TRACK
|| ambientSet.status !== 'final' || ambientSet.characterId !== recordId
|| JSON.stringify(ambientSet.directionOrder) !== JSON.stringify(['south'])) {
throw compileError('Ambient set manifest is not a finalized single-row ambient set');
diff --git a/server/services/sprites/scanner.js b/server/services/sprites/scanner.js
deleted file mode 100644
index 05fab92563..0000000000
--- a/server/services/sprites/scanner.js
+++ /dev/null
@@ -1,341 +0,0 @@
-/**
- * The first named, non-walk animation track: a short directional scanner action.
- *
- * The render is deliberately reachable only through `startScannerGeneration`.
- * Everything after Grok writes the requested MP4 is deterministic local packing,
- * review, approval, and atlas input; no boot path or read endpoint calls a
- * provider.
- */
-
-import { join } from 'path';
-import { readdir, rm } from 'fs/promises';
-import { randomUUID } from 'crypto';
-import { atomicWrite, ensureDir, pathExists, readJSONFile, sha256File } from '../../lib/fileUtils.js';
-import { ServerError } from '../../lib/errorHandler.js';
-import { executeTuiRun } from '../../lib/tuiPromptRunner.js';
-import { GROK_TUI_ID } from '../../lib/grok.js';
-import { getSettings } from '../settings.js';
-import { getRecord } from './records.js';
-import { requireTrack, loadManifest } from './reference.js';
-import { SPRITE_DIRECTIONS, anchorIdForDirection, buildScannerPrompt } from './prompts.js';
-import { SCANNER_TRACK, clampTrackFrameCount, clampTrackFps, getAnimationTrack } from './animationTracks.js';
-import { spriteDir, resolveSpriteAssetPath, SOURCE_CLIP_NAME } from './paths.js';
-import { prepareWalkAnchorChromaInput, runWalkPostprocess } from './walkPostprocess.js';
-import { verifyPackagedFrames } from './walkFrames.js';
-import { resolveChromaKey, withAnimationWriteTail } from './animationWorkflow.js';
-import { resolveGrokDuration } from '../../lib/grokVideoClip.js';
-
-const RUN_RECORD_NAME = 'animation-run.json';
-const selectionRelPath = (id) => `scanner/${id}-scanner-selection-v1.json`;
-export const scannerSetRelPath = (id) => `scanner/${id}-scanner-set-v1.json`;
-const runRelPath = (runId) => `runs/${runId}`;
-const TUI_IDLE_MS = 90_000;
-const TUI_TIMEOUT_MS = 30 * 60_000;
-
-const scannerSetFinalError = () => new ServerError(
- 'Scanner set is finalized — reopen it before generating or approving another scanner action',
- { status: 409, code: 'SCANNER_SET_FINAL' },
-);
-
-async function loadSelection(recordId) {
- return readJSONFile(join(spriteDir(recordId), selectionRelPath(recordId)), null);
-}
-
-async function loadSet(recordId) {
- return readJSONFile(join(spriteDir(recordId), scannerSetRelPath(recordId)), null);
-}
-
-const seedSelection = (recordId) => ({
- schemaVersion: 1,
- kind: 'reviewed-directional-scanner-selection',
- track: SCANNER_TRACK,
- characterId: recordId,
- status: 'in-progress',
- directions: {},
-});
-
-async function saveRun(recordId, run) {
- const dir = join(spriteDir(recordId), runRelPath(run.id));
- await ensureDir(dir);
- await atomicWrite(join(dir, RUN_RECORD_NAME), run);
-}
-
-async function loadRun(recordId, runId) {
- return readJSONFile(join(spriteDir(recordId), runRelPath(runId), RUN_RECORD_NAME), null);
-}
-
-async function scannerRuns(recordId) {
- const runsDir = join(spriteDir(recordId), 'runs');
- const entries = await readdir(runsDir, { withFileTypes: true }).catch(() => []);
- const runs = await Promise.all(entries.filter((entry) => entry.isDirectory()).map((entry) => (
- readJSONFile(join(runsDir, entry.name, RUN_RECORD_NAME), null)
- )));
- return runs.filter((run) => run?.track === SCANNER_TRACK)
- .sort((a, b) => Date.parse(b.createdAt || 0) - Date.parse(a.createdAt || 0));
-}
-
-export async function getScannerState(recordId) {
- const [selection, scannerSet, runs] = await Promise.all([
- loadSelection(recordId), loadSet(recordId), scannerRuns(recordId),
- ]);
- return {
- track: SCANNER_TRACK,
- bounds: getAnimationTrack(SCANNER_TRACK),
- selection,
- scannerSet,
- runs,
- };
-}
-
-const lockedAnchorFor = (manifest, direction) => {
- const anchor = manifest?.anchors?.find((item) => item.direction === direction);
- return anchor?.status === 'locked' && anchor.path ? anchor : null;
-};
-
-function scannerTask({ prompt, inputAbs, videoAbs, duration }) {
- return `${prompt}\n\nUse your built-in image_to_video tool to animate this exact image for ${duration} seconds:\n${inputAbs}\n\n`
- + `Save the resulting animation as an MP4 file at exactly this path:\n${videoAbs}\n\n`
- + 'Do not create or modify any other files, and do not run any tools beyond what is needed to render and save that MP4.';
-}
-
-export function startScannerGeneration(recordId, body) {
- return withAnimationWriteTail(recordId, () => startScannerGenerationImpl(recordId, body));
-}
-
-async function startScannerGenerationImpl(recordId, body) {
- const [record, reference, scannerSet, existingRuns] = await Promise.all([
- requireTrack(recordId, SCANNER_TRACK), loadManifest(recordId), loadSet(recordId), scannerRuns(recordId),
- ]);
- if (scannerSet) throw scannerSetFinalError();
- const { direction } = body;
- const anchor = lockedAnchorFor(reference, direction);
- if (!anchor) throw new ServerError(`Lock the ${anchorIdForDirection(direction)} anchor before generating its scanner action`, { status: 409, code: 'ANCHOR_NOT_LOCKED' });
- const chromaKey = resolveChromaKey({ manifest: reference, record });
- if (!chromaKey) throw new ServerError('No frozen chroma key is available for this character', { status: 409, code: 'CHROMA_KEY_REQUIRED' });
- if (existingRuns.some((run) => run.direction === direction && ['rendering', 'postprocessing'].includes(run.status))) {
- throw new ServerError(`A scanner render for ${direction} is already in progress`, { status: 409, code: 'SCANNER_RENDER_IN_PROGRESS' });
- }
-
- const frameCount = clampTrackFrameCount(body.frameCount, SCANNER_TRACK);
- const fps = clampTrackFps(body.fps, SCANNER_TRACK);
- // Optional re-roll note (#3134) — blank leaves the prompt and the run record
- // exactly as a blind regenerate would.
- const correctionPrompt = typeof body.correctionPrompt === 'string' ? body.correctionPrompt.trim() : '';
- const runId = `${SCANNER_TRACK}-${direction}-${randomUUID().slice(0, 8)}`;
- const runRel = runRelPath(runId);
- const generatedAbs = join(spriteDir(recordId), runRel, 'generated');
- await ensureDir(generatedAbs);
- 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' });
- const inputAbs = join(generatedAbs, 'input-anchor-chroma.png');
- const [{ preparation, sha256: inputSha256 }, settings] = await Promise.all([
- prepareWalkAnchorChromaInput(anchorAbs, inputAbs, chromaKey), getSettings(),
- ]);
- const duration = resolveGrokDuration(body.duration);
- const videoAbs = join(generatedAbs, SOURCE_CLIP_NAME);
- const run = {
- schemaVersion: 1,
- kind: 'grok-game-animation-frames-run',
- track: SCANNER_TRACK,
- provider: GROK_TUI_ID,
- status: 'rendering',
- id: runId,
- shellSession: runId,
- characterId: recordId,
- direction,
- chromaKey,
- duration,
- frameCount,
- fps,
- anchorPath: anchor.path,
- anchorSha256: anchor.sha256 || await sha256File(anchorAbs),
- animationInputPath: `${runRel}/generated/input-anchor-chroma.png`,
- animationInputSha256: inputSha256,
- animationInputPreparation: preparation,
- ...(correctionPrompt ? { correctionPrompt } : {}),
- createdAt: new Date().toISOString(),
- };
- await saveRun(recordId, run);
- runScannerTuiRender(recordId, {
- runId,
- direction,
- generatedAbs,
- videoAbs,
- grokPath: settings.imageGen?.grok?.grokPath,
- task: scannerTask({
- prompt: buildScannerPrompt({ name: record.name, direction, chromaKey, correctionPrompt }),
- inputAbs,
- videoAbs,
- duration,
- }),
- }).catch((err) => console.error(`❌ sprite scanner grok-tui render crashed ${recordId}/${runId}: ${err?.message || err}`));
- console.log(`📡 sprite scanner grok-tui render started ${recordId}/${runId}`);
- return { runId, direction, duration, shellSession: runId };
-}
-
-async function runScannerTuiRender(recordId, { runId, direction, generatedAbs, videoAbs, grokPath, task }) {
- await executeTuiRun({
- runId,
- provider: { id: GROK_TUI_ID, type: 'tui', command: grokPath || 'grok', args: [] },
- prompt: task,
- workspacePath: generatedAbs,
- idleMs: TUI_IDLE_MS,
- timeout: TUI_TIMEOUT_MS,
- label: `sprite scanner ${recordId}/${direction}`,
- }).catch((err) => console.error(`❌ sprite scanner grok-tui run failed ${recordId}/${runId}: ${err?.message || err}`));
- await withAnimationWriteTail(recordId, () => attachScannerTuiResult(recordId, runId, videoAbs));
-}
-
-export async function attachScannerTuiResult(recordId, runId, videoAbs) {
- const run = await loadRun(recordId, runId);
- if (!run || run.track !== SCANNER_TRACK || await loadSet(recordId)) return;
- const selection = await loadSelection(recordId);
- if (selection?.directions?.[run.direction]?.runId === runId) return;
- if (!await pathExists(videoAbs)) {
- run.status = 'error';
- run.postprocessError = 'Grok finished without writing the scanner video — check the shell session output';
- run.completedAt = new Date().toISOString();
- await saveRun(recordId, run);
- return;
- }
- run.status = 'postprocessing';
- run.sourceVideoPath = `${runRelPath(run.id)}/generated/${SOURCE_CLIP_NAME}`;
- await saveRun(recordId, run);
- await packageScannerRun(recordId, run);
- await saveRun(recordId, run);
-}
-
-async function packageScannerRun(recordId, run) {
- try {
- const [reference, record] = await Promise.all([loadManifest(recordId), getRecord(recordId)]);
- const anchor = lockedAnchorFor(reference, run.direction);
- if (!anchor) throw new Error(`No locked ${run.direction} anchor in the reference manifest`);
- const chromaKey = resolveChromaKey({ manifest: reference, record, run });
- if (!chromaKey) throw new Error('No chroma key is available for the scanner matte');
- const runRel = runRelPath(run.id);
- const result = await runWalkPostprocess({
- recordId,
- track: SCANNER_TRACK,
- direction: run.direction,
- chromaKey,
- runAbs: join(spriteDir(recordId), runRel),
- runRel,
- anchorRel: anchor.path,
- anchorAbs: resolveSpriteAssetPath(recordId, anchor.path),
- videoAbs: resolveSpriteAssetPath(recordId, run.sourceVideoPath),
- frameCount: clampTrackFrameCount(run.frameCount, SCANNER_TRACK),
- fps: clampTrackFps(run.fps, SCANNER_TRACK),
- });
- run.frameCount = result.manifest.frameCount;
- run.fps = result.manifest.frameRate;
- run.status = 'candidate';
- run.postprocessManifest = result.manifestPath;
- run.stripPreview = result.stripPreview;
- delete run.postprocessError;
- } catch (err) {
- run.status = 'error';
- run.postprocessError = err.message;
- console.error(`❌ sprite scanner postprocess failed ${recordId}/${run.id}: ${err.message}`);
- }
- run.completedAt = new Date().toISOString();
-}
-
-export function approveScannerDirection(recordId, args) {
- return withAnimationWriteTail(recordId, () => approveScannerDirectionImpl(recordId, args));
-}
-
-async function approveScannerDirectionImpl(recordId, { direction, runId }) {
- await requireTrack(recordId, SCANNER_TRACK);
- if (await loadSet(recordId)) throw scannerSetFinalError();
- const run = await loadRun(recordId, runId);
- if (!run || run.track !== SCANNER_TRACK) throw new ServerError(`Unknown scanner run: ${runId}`, { status: 404, code: 'RUN_NOT_FOUND' });
- if (run.direction !== direction) throw new ServerError(`Run ${runId} animates '${run.direction}', not '${direction}'`, { status: 400, code: 'RUN_DIRECTION_MISMATCH' });
- if (run.status !== 'candidate' || !run.postprocessManifest) throw new ServerError('Run has no packaged candidate to approve', { status: 409, code: 'RUN_NOT_CANDIDATE' });
- const [reference, packaged] = await Promise.all([
- loadManifest(recordId), readJSONFile(resolveSpriteAssetPath(recordId, run.postprocessManifest), null),
- ]);
- const anchor = lockedAnchorFor(reference, direction);
- if (!anchor) throw new ServerError(`Lock the ${anchorIdForDirection(direction)} anchor before approving its scanner action`, { status: 409, code: 'ANCHOR_NOT_LOCKED' });
- if (run.anchorSha256) {
- const currentAnchorSha256 = anchor.sha256 || await sha256File(resolveSpriteAssetPath(recordId, anchor.path));
- if (run.anchorSha256 !== currentAnchorSha256) {
- throw new ServerError('This scanner action was rendered from an older directional anchor — generate it again from the current anchor', { status: 409, code: 'RUN_ANCHOR_STALE' });
- }
- }
- if (!packaged || packaged.track !== SCANNER_TRACK || packaged.direction !== direction || packaged.characterId !== recordId
- || packaged.frameCount !== run.frameCount || packaged.frameRate !== run.fps) {
- throw new ServerError('Packaged scanner manifest is missing or inconsistent', { status: 409, code: 'RUN_MANIFEST_INVALID' });
- }
- const frameCheck = await verifyPackagedFrames(recordId, packaged, { track: SCANNER_TRACK });
- if (frameCheck.missing) throw new ServerError(
- `${frameCheck.missing} of this scanner run's ${frameCheck.total} packaged frames are missing on disk`,
- { status: 409, code: 'RUN_FRAMES_MISSING' },
- );
- const selection = (await loadSelection(recordId)) || seedSelection(recordId);
- selection.directions[direction] = {
- status: 'approved',
- runId,
- runPath: runRelPath(runId),
- runManifest: run.postprocessManifest,
- runManifestSha256: await sha256File(resolveSpriteAssetPath(recordId, run.postprocessManifest)),
- approvedAt: new Date().toISOString(),
- };
- const allApproved = SPRITE_DIRECTIONS.every((item) => selection.directions[item]?.status === 'approved');
- selection.status = allApproved ? 'complete' : 'in-progress';
- const selectionAbs = join(spriteDir(recordId), selectionRelPath(recordId));
- await ensureDir(join(spriteDir(recordId), SCANNER_TRACK));
- await atomicWrite(selectionAbs, selection);
- if (allApproved) {
- await atomicWrite(join(spriteDir(recordId), scannerSetRelPath(recordId)), {
- schemaVersion: 1,
- kind: 'finalized-eight-direction-scanner-set',
- track: SCANNER_TRACK,
- characterId: recordId,
- status: 'final',
- directionOrder: SPRITE_DIRECTIONS,
- selectionPath: selectionRelPath(recordId),
- selectionSha256: await sha256File(selectionAbs),
- directions: selection.directions,
- finalizedAt: new Date().toISOString(),
- });
- console.log(`🏁 sprite scanner set finalized for ${recordId}`);
- }
- return getScannerState(recordId);
-}
-
-export function invalidateScannerDirectionForAnchorRevision(recordId, { direction }) {
- return withAnimationWriteTail(recordId, () => invalidateScannerDirectionForAnchorRevisionImpl(recordId, direction));
-}
-
-export function invalidateScannerForTurnaroundRevision(recordId) {
- return withAnimationWriteTail(recordId, async () => {
- const invalidated = [];
- for (const direction of SPRITE_DIRECTIONS) {
- if (await invalidateScannerDirectionForAnchorRevisionImpl(recordId, direction)) invalidated.push(direction);
- }
- return invalidated;
- });
-}
-
-async function invalidateScannerDirectionForAnchorRevisionImpl(recordId, direction) {
- const [scannerSet, loaded] = await Promise.all([loadSet(recordId), loadSelection(recordId)]);
- const approved = loaded?.directions?.[direction] || scannerSet?.directions?.[direction];
- if (approved?.status !== 'approved') return false;
- const selection = loaded || { ...seedSelection(recordId), directions: { ...(scannerSet?.directions || {}) } };
- if (scannerSet) await rm(join(spriteDir(recordId), scannerSetRelPath(recordId)), { force: true });
- delete selection.directions[direction];
- selection.status = 'in-progress';
- await ensureDir(join(spriteDir(recordId), SCANNER_TRACK));
- await atomicWrite(join(spriteDir(recordId), selectionRelPath(recordId)), selection);
- const run = approved.runId ? await loadRun(recordId, approved.runId) : null;
- if (run?.track === SCANNER_TRACK) {
- await saveRun(recordId, {
- ...run,
- status: 'superseded-anchor',
- supersededAt: new Date().toISOString(),
- supersededReason: 'directional-anchor-revised',
- });
- }
- console.log(`♻️ sprite scanner direction ${recordId}/${direction} invalidated after anchor revision`);
- return true;
-}
diff --git a/server/services/sprites/scanner.test.js b/server/services/sprites/scanner.test.js
deleted file mode 100644
index a1f9c8b63c..0000000000
--- a/server/services/sprites/scanner.test.js
+++ /dev/null
@@ -1,126 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
-import { mkdtempSync, rmSync } from 'fs';
-import { tmpdir } from 'os';
-import { join } from 'path';
-import { mkdir, writeFile } from 'fs/promises';
-import { createHash } from 'crypto';
-import { lockAllAnchors } from './spriteTestFixtures.js';
-
-const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-scanner-test-'));
-
-vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
- const actual = await importOriginal();
- Object.assign(actual.PATHS, {
- data: TEST_ROOT,
- sprites: join(TEST_ROOT, 'sprites'),
- images: join(TEST_ROOT, 'images'),
- videos: join(TEST_ROOT, 'videos'),
- });
- return actual;
-});
-
-const executeTuiRun = vi.fn(() => new Promise(() => {}));
-vi.mock('../../lib/tuiPromptRunner.js', () => ({
- executeTuiRun: (...args) => executeTuiRun(...args),
-}));
-
-vi.mock('../settings.js', () => ({
- getSettings: async () => ({
- imageGen: { grok: { grokPath: '/usr/local/bin/grok' } },
- }),
-}));
-
-const prepareWalkAnchorChromaInput = vi.fn(async (_anchorAbs, inputAbs) => {
- await mkdir(join(inputAbs, '..'), { recursive: true });
- const bytes = Buffer.from('scanner-chroma-input');
- await writeFile(inputAbs, bytes);
- return {
- preparation: 'composited-over-solid-chroma-matte',
- sha256: createHash('sha256').update(bytes).digest('hex'),
- };
-});
-vi.mock('./walkPostprocess.js', async (importOriginal) => ({
- ...await importOriginal(),
- prepareWalkAnchorChromaInput: (...args) => prepareWalkAnchorChromaInput(...args),
-}));
-
-const records = await import('./records.js');
-const { lockReference } = await import('./reference.js');
-const { getScannerState, startScannerGeneration } = await import('./scanner.js');
-
-let sequence = 0;
-const newId = () => `scanner-${++sequence}`;
-
-async function characterWithEastAnchor(id) {
- await records.createRecord({ kind: 'character', name: 'Scanner' }, id);
- await lockAllAnchors(TEST_ROOT, id, { lockReference, directions: ['east'] });
- return id;
-}
-
-beforeEach(() => {
- executeTuiRun.mockClear();
- executeTuiRun.mockImplementation(() => new Promise(() => {}));
- prepareWalkAnchorChromaInput.mockClear();
- rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });
-});
-afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
-
-describe('scanner animation track', () => {
- it('is provider-silent on reads, then starts a user-triggered four-frame scanner render', async () => {
- const id = await characterWithEastAnchor(newId());
-
- const initial = await getScannerState(id);
- expect(initial).toMatchObject({
- track: 'scanner',
- bounds: { minFrameCount: 2, maxFrameCount: 8, defaultFrameCount: 4, defaultFps: 6 },
- runs: [],
- });
- expect(executeTuiRun).not.toHaveBeenCalled();
-
- const result = await startScannerGeneration(id, { direction: 'east' });
- expect(result).toMatchObject({ direction: 'east', duration: 6 });
- expect(result.runId).toMatch(/^scanner-east-[0-9a-f]{8}$/);
- expect(result.shellSession).toBe(result.runId);
- expect(executeTuiRun).toHaveBeenCalledOnce();
- expect(executeTuiRun.mock.calls[0][0]).toMatchObject({
- runId: result.runId,
- workspacePath: join(TEST_ROOT, 'sprites', id, 'runs', result.runId, 'generated'),
- });
- expect(executeTuiRun.mock.calls[0][0].prompt).toContain('scanner action');
-
- expect((await getScannerState(id)).runs).toMatchObject([{
- id: result.runId,
- track: 'scanner',
- status: 'rendering',
- frameCount: 4,
- fps: 6,
- direction: 'east',
- }]);
- });
-
- it('appends a trimmed correction note to the prompt and stamps it on the run (#3134)', async () => {
- const id = await characterWithEastAnchor(newId());
- const { runId } = await startScannerGeneration(id, {
- direction: 'east', correctionPrompt: ' the sweep never returns to the start pose ',
- });
- expect(executeTuiRun.mock.calls[0][0].prompt)
- .toContain('Important correction — apply this over the attached source image: the sweep never returns to the start pose');
- const { runs } = await getScannerState(id);
- expect(runs.find((r) => r.id === runId).correctionPrompt).toBe('the sweep never returns to the start pose');
- });
-
- it('leaves a blank correction note out of the prompt and the run record (#3134)', async () => {
- // The task is `<action prompt>\n\n<per-run paths>` — compare the prompt only.
- const actionPrompt = () => executeTuiRun.mock.calls[0][0].prompt.split('\n\n')[0];
- const plain = await characterWithEastAnchor(newId());
- await startScannerGeneration(plain, { direction: 'east' });
- const blindPrompt = actionPrompt();
- executeTuiRun.mockClear();
-
- const blank = await characterWithEastAnchor(newId());
- const { runId } = await startScannerGeneration(blank, { direction: 'east', correctionPrompt: ' \n ' });
- expect(actionPrompt()).toBe(blindPrompt);
- const { runs } = await getScannerState(blank);
- expect(runs.find((r) => r.id === runId)).not.toHaveProperty('correctionPrompt');
- });
-});
diff --git a/server/services/sprites/spriteTestFixtures.js b/server/services/sprites/spriteTestFixtures.js
index 65983e84e7..720568ef19 100644
--- a/server/services/sprites/spriteTestFixtures.js
+++ b/server/services/sprites/spriteTestFixtures.js
@@ -88,6 +88,11 @@ export const trackSpan = (start, count, rows = SPRITE_DIRECTIONS.length) => ({ s
* character-only, so a test written against it alone could not tell "reads the
* row" from "hardcodes 8 / hardcodes 'character'". Same injected-table idiom
* `assertAnimationTrackRows(tracks)` uses. Shipping the real row is #3045.
+ *
+ * Deliberately kept as its own literal rather than re-exporting the now-shipped
+ * `ANIMATION_TRACKS.ambient`: the injected-table tests exist to prove callers
+ * read the row they were HANDED, and sourcing the fixture from the shipped table
+ * would let a caller that secretly reads the global registry pass anyway.
*/
export const AMBIENT_TRACK_ROW = Object.freeze({
id: 'ambient',
@@ -102,4 +107,12 @@ export const AMBIENT_TRACK_ROW = Object.freeze({
defaultFps: 4,
contractFrameCountField: 'ambientFrameCount',
contractFpsField: null,
+ // #3136 workflow shape. A non-directional row must seed from the main
+ // reference (it has no per-facing anchor to read), and its on-disk kinds must
+ // not collide with any other row this fixture is combined with.
+ sourceReference: 'main',
+ selectionKind: 'reviewed-single-row-ambient-selection',
+ setKind: 'finalized-single-row-ambient-set',
+ finalErrorCode: 'AMBIENT_SET_FINAL',
+ builtin: true,
});
diff --git a/server/services/sprites/trackPrompts.js b/server/services/sprites/trackPrompts.js
new file mode 100644
index 0000000000..3c2052937c
--- /dev/null
+++ b/server/services/sprites/trackPrompts.js
@@ -0,0 +1,57 @@
+/**
+ * Per-track image-to-video prompt resolution (#3136).
+ *
+ * The generic animation workflow needs ONE call that answers "what do I send the
+ * provider for this track?" — because that question is the last thing that was
+ * still track-specific code rather than track-specific data. Today the answer is
+ * a lookup into the builders `prompts.js` already owns; when a user-defined
+ * track store lands, an unknown id resolves to that track's stored
+ * `promptTemplate` here instead of throwing, and no caller changes.
+ *
+ * Kept separate from `prompts.js` deliberately: that module is the pure catalog
+ * of prompt TEXT (and its tests assert the exact wording of each stage), while
+ * this is the small dispatch layer over it. Folding the dispatch in would make
+ * every prompt-wording test also a routing test.
+ *
+ * Pure — no I/O, no state.
+ */
+
+import { buildWalkVideoPrompt, buildScannerPrompt, buildAmbientVideoPrompt } from './prompts.js';
+import { WALK_TRACK, SCANNER_TRACK, AMBIENT_TRACK } from './animationTracks.js';
+
+/**
+ * The i2v prompt builder for each track compiled into this build.
+ *
+ * Every builder takes the same superset argument object and reads only what it
+ * needs, so the dispatch below passes one shape and never has to know which
+ * fields a given track's wording happens to embed.
+ */
+const TRACK_VIDEO_PROMPTS = Object.freeze({
+ [WALK_TRACK]: buildWalkVideoPrompt,
+ [SCANNER_TRACK]: buildScannerPrompt,
+ [AMBIENT_TRACK]: buildAmbientVideoPrompt,
+});
+
+/**
+ * The image-to-video instruction for one track's render.
+ *
+ * Throws on an unregistered track rather than falling back to walk's wording —
+ * the same unknown-id boundary `getAnimationTrack` draws, and for the same
+ * reason: a mis-keyed track that silently sent the walk prompt would render a
+ * gait loop and pass every later check, since nothing downstream re-reads what
+ * was asked for.
+ */
+export function buildTrackVideoPrompt(trackId, args) {
+ const build = TRACK_VIDEO_PROMPTS[trackId];
+ if (!build) {
+ throw new Error(
+ `No image-to-video prompt is registered for animation track '${String(trackId)}' `
+ + `— known tracks: ${Object.keys(TRACK_VIDEO_PROMPTS).join(', ')}.`,
+ );
+ }
+ return build(args);
+}
+
+/** True when `trackId` has a registered i2v prompt builder. */
+export const hasTrackVideoPrompt = (trackId) =>
+ Object.prototype.hasOwnProperty.call(TRACK_VIDEO_PROMPTS, trackId);
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 8a85615eaf..4c3a724f2d 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -55,9 +55,10 @@ import { verifyPackagedFrames } from './walkFrames.js';
import { probeVideoDuration } from '../../lib/ffmpeg.js';
import { resolveGrokDuration } from '../../lib/grokVideoClip.js';
import { withAnimationWriteTail, resolveChromaKey } from './animationWorkflow.js';
+import { SCANNER_TRACK } from './animationTracks.js';
import {
- invalidateScannerDirectionForAnchorRevision, invalidateScannerForTurnaroundRevision,
-} from './scanner.js';
+ invalidateTrackDirectionForAnchorRevision, invalidateTrackForTurnaroundRevision,
+} from './animationTrackWorkflow.js';
// grok's walk render runs as an OBSERVABLE TUI session (issue: user wants to
// watch/course-correct grok in the Shell) rather than a headless mediaJobQueue
@@ -1883,7 +1884,7 @@ export function invalidateWalkDirectionForAnchorRevision(recordId, { direction }
export async function unlockDirectionalAnchor(recordId, { direction }) {
await assertReferenceAnchorUnlockable(recordId, { direction });
const walkInvalidated = await invalidateWalkDirectionForAnchorRevision(recordId, { direction });
- const scannerInvalidated = await invalidateScannerDirectionForAnchorRevision(recordId, { direction });
+ const scannerInvalidated = await invalidateTrackDirectionForAnchorRevision(SCANNER_TRACK, recordId, { direction });
const reference = await unlockReferenceAnchor(recordId, { direction });
return { ...reference, walkInvalidated, scannerInvalidated };
}
@@ -1896,7 +1897,7 @@ export async function unlockMainReference(recordId) {
await assertReferenceMainUnlockable(recordId);
const direction = 'south';
const walkInvalidated = await invalidateWalkDirectionForAnchorRevision(recordId, { direction });
- const scannerInvalidated = await invalidateScannerDirectionForAnchorRevision(recordId, { direction });
+ const scannerInvalidated = await invalidateTrackDirectionForAnchorRevision(SCANNER_TRACK, recordId, { direction });
const reference = await unlockReferenceMain(recordId);
return { ...reference, walkInvalidated, scannerInvalidated };
}
@@ -1912,7 +1913,7 @@ export async function unlockMainReference(recordId) {
export async function unlockTurnaroundReference(recordId) {
await assertReferenceTurnaroundUnlockable(recordId);
const walkInvalidatedDirections = await invalidateWalkForTurnaroundRevision(recordId);
- const scannerInvalidatedDirections = await invalidateScannerForTurnaroundRevision(recordId);
+ const scannerInvalidatedDirections = await invalidateTrackForTurnaroundRevision(SCANNER_TRACK, recordId);
const reference = await unlockReferenceTurnaround(recordId);
return { ...reference, walkInvalidatedDirections, scannerInvalidatedDirections };
}