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

improve sprite reference workflow

[._.]/ Adam Eivyca34869dae4e
diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsx
index aad1cdd8cd..bf290fc29d 100644
--- a/client/src/components/sprites/ReferenceWorkflow.jsx
+++ b/client/src/components/sprites/ReferenceWorkflow.jsx
@@ -1,10 +1,12 @@
import { useEffect, useMemo, useState } from 'react';
import {
Lock, Sparkles, RefreshCw, Upload, ChevronDown, ChevronRight,
- Images, PersonStanding, GitFork, X,
+ Images, PersonStanding, GitFork, Unlock, X,
} from 'lucide-react';
import toast from '../ui/Toast';
-import { generateSpriteReference, lockSpriteReference, updateSpriteRecord } from '../../services/apiSprites.js';
+import {
+ generateSpriteReference, lockSpriteReference, unlockSpriteReferenceAnchor, updateSpriteRecord,
+} from '../../services/apiSprites.js';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
import SpritePreview from './SpritePreview.jsx';
import GalleryImagePicker from '../imageGen/GalleryImagePicker.jsx';
@@ -45,24 +47,28 @@ function SpriteImg({ recordId, path, className }) {
function CandidateTile({ recordId, candidate, locking, onLock, clipRisk }) {
const [confirming, setConfirming] = useState(false);
return (
- <div className="bg-port-bg border border-port-border rounded p-1 space-y-1">
- <SpriteImg recordId={recordId} path={candidate.path} className="w-full aspect-square object-contain" />
- <p className="text-[10px] text-gray-500 truncate" title={candidate.path}>
+ <div className="flex min-w-0 flex-col gap-2 rounded-lg border border-port-border bg-port-card p-2">
+ <SpriteImg
+ recordId={recordId}
+ path={candidate.path}
+ className="w-full aspect-square rounded-md border border-port-border object-contain"
+ />
+ <p className="truncate px-0.5 text-[10px] text-gray-500" title={candidate.path}>
{candidate.path.split('/').pop()}{candidate.mode ? ` · ${candidate.mode}` : ''}
</p>
{clipRisk ? (
- <div className="space-y-1 text-[10px]">
+ <div className="mt-auto space-y-1 text-[10px]">
<p className="text-port-warning">{clipRisk}</p>
<button
onClick={() => onLock(candidate, true)}
disabled={locking}
- className="w-full px-1.5 py-0.5 text-xs bg-port-warning/20 border border-port-warning rounded text-port-warning disabled:opacity-50"
+ className="w-full rounded border border-port-warning bg-port-warning/20 px-1.5 py-1 text-xs text-port-warning disabled:opacity-50"
>
Lock anyway
</button>
</div>
) : confirming ? (
- <div className="flex items-center gap-1 text-xs">
+ <div className="mt-auto flex flex-wrap items-center gap-1 text-xs">
<span className="text-port-warning">Freeze forever?</span>
<button onClick={() => { setConfirming(false); onLock(candidate); }} disabled={locking} className="px-1.5 py-0.5 bg-port-accent text-white rounded disabled:opacity-50">Lock</button>
<button onClick={() => setConfirming(false)} className="px-1.5 py-0.5 text-gray-400 hover:text-white">Cancel</button>
@@ -71,7 +77,7 @@ function CandidateTile({ recordId, candidate, locking, onLock, clipRisk }) {
<button
onClick={() => setConfirming(true)}
disabled={locking}
- className="flex items-center gap-1 w-full justify-center px-1.5 py-0.5 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50"
+ className="mt-auto flex w-full items-center justify-center gap-1 rounded border border-port-border bg-port-bg px-1.5 py-1 text-xs text-gray-300 hover:border-port-accent disabled:opacity-50"
>
<Lock className="w-3 h-3" /> Lock
</button>
@@ -80,6 +86,92 @@ function CandidateTile({ recordId, candidate, locking, onLock, clipRisk }) {
);
}
+// A directional-anchor unlock is deliberately narrower than unlocking the
+// identity root: it preserves the old versioned PNG, reopens this card, and
+// invalidates only the walk that depended on it. Keep the consequential action
+// behind the same inline-confirm convention as locking.
+function LockedAnchor({ recordId, anchor, canUnlock, unlocking, onUnlock }) {
+ const [confirming, setConfirming] = useState(false);
+ const direction = anchor.direction;
+ return (
+ <div className="space-y-2">
+ <SpriteImg
+ recordId={recordId}
+ path={anchor.path}
+ className="w-full aspect-square rounded border border-port-border object-contain"
+ />
+ {canUnlock && (confirming ? (
+ <div className="rounded border border-port-warning/40 bg-port-warning/10 p-1.5 text-[10px]">
+ <p className="mb-1.5 text-port-warning">Regenerate {direction} from turnaround?</p>
+ <div className="flex gap-1">
+ <button
+ type="button"
+ aria-label={`Confirm unlock ${direction} anchor`}
+ onClick={() => { setConfirming(false); onUnlock(direction); }}
+ disabled={unlocking}
+ className="flex-1 rounded bg-port-warning px-1.5 py-1 font-medium text-black disabled:opacity-50"
+ >
+ Unlock
+ </button>
+ <button
+ type="button"
+ onClick={() => setConfirming(false)}
+ disabled={unlocking}
+ className="rounded px-1.5 py-1 text-gray-400 hover:text-white disabled:opacity-50"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ ) : (
+ <button
+ type="button"
+ aria-label={`Unlock ${direction} anchor`}
+ onClick={() => setConfirming(true)}
+ disabled={unlocking}
+ className="flex min-h-8 w-full items-center justify-center gap-1 rounded border border-port-border bg-port-card px-2 py-1 text-xs text-gray-400 hover:border-port-warning hover:text-port-warning disabled:opacity-50"
+ >
+ <Unlock className="h-3 w-3" /> Unlock anchor
+ </button>
+ ))}
+ </div>
+ );
+}
+
+const STEP_TONE = {
+ complete: 'border-port-success/40 bg-port-success/10 text-port-success',
+ active: 'border-port-accent/50 bg-port-accent/10 text-port-accent',
+ waiting: 'border-port-border bg-port-bg text-gray-500',
+};
+
+function StepSummary({ number, label, status, tone }) {
+ return (
+ <div className={`flex min-w-0 items-center gap-2 rounded-lg border px-2.5 py-2 ${STEP_TONE[tone]}`}>
+ <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full border border-current text-[10px] font-semibold">
+ {number}
+ </span>
+ <span className="min-w-0">
+ <span className="block truncate text-[10px] uppercase tracking-wide">{label}</span>
+ <span className="block truncate text-[11px] font-medium">{status}</span>
+ </span>
+ </div>
+ );
+}
+
+function StageHeading({ id, number, title, status, statusTone = 'text-gray-500' }) {
+ return (
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-port-border bg-port-bg text-xs font-semibold text-gray-300">
+ {number}
+ </span>
+ <div className="min-w-0">
+ <h4 id={id} className="truncate text-xs font-semibold uppercase tracking-wide text-gray-300">{title}</h4>
+ <p className={`text-[10px] ${statusTone}`}>{status}</p>
+ </div>
+ </div>
+ );
+}
+
export default function ReferenceWorkflow({ record, reference, renders, corrections, onCorrectionChange, backends, mode, onModeChange, onChanged, onForked }) {
const recordId = record.id;
const manifest = reference?.manifest || null;
@@ -102,6 +194,10 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
// grid as the user left it.
const anchorList = manifest?.anchors || [];
const allAnchorsLocked = anchorList.length > 0 && anchorList.every((a) => a.status === 'locked');
+ const lockedAnchorCount = anchorList.filter((a) => a.status === 'locked').length;
+ const anchorProgress = anchorList.length > 0
+ ? `${lockedAnchorCount}/${anchorList.length} locked`
+ : 'Waiting for main';
// A legacy character with every anchor already frozen has nothing left for a
// sheet to improve — main and anchors are immutable — so the backfill stops
// being a step it's missing and becomes an optional extra that only helps
@@ -211,6 +307,18 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
onChanged();
}, { errorMessage: 'Lock failed' });
+ const [unlockAnchor, anchorUnlocking] = useAsyncAction(async (direction) => {
+ const result = await unlockSpriteReferenceAnchor(
+ recordId,
+ { direction },
+ { silent: true },
+ );
+ toast.success(result.walkInvalidated
+ ? `${direction} anchor unlocked; its walk was reopened`
+ : `${direction} anchor unlocked`);
+ onChanged();
+ }, { errorMessage: 'Failed to unlock anchor' });
+
const [setChromaKey, keySaving] = useAsyncAction(async (hex) => {
await updateSpriteRecord(recordId, { chromaKey: hex }, { silent: true });
// A key change invalidates any clip-risk warning the user was shown —
@@ -233,305 +341,433 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
</select>
</label>
);
+ const turnaroundCandidates = candidatesByTarget.turnaround || [];
+ const mainCandidates = candidatesByTarget.main || [];
return (
- <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">
- <div className="flex flex-wrap items-center justify-between gap-2">
- <h3 className="text-sm font-semibold text-white flex items-center gap-1.5">
- <Sparkles className="w-4 h-4" /> Reference Set
- <span className="text-xs font-normal text-gray-500">{manifest?.status || 'not started'}</span>
- </h3>
+ <div className="@container space-y-4 rounded-lg border border-port-border bg-port-card p-3 sm:p-4">
+ <div className="flex flex-col gap-3 @4xl:flex-row @4xl:items-start">
+ <div className="min-w-[13rem] flex-1">
+ <h3 className="flex items-center gap-1.5 text-sm font-semibold text-white">
+ <Sparkles className="h-4 w-4" /> Reference Set
+ <span className="text-xs font-normal text-gray-500">{manifest?.status || 'not started'}</span>
+ </h3>
+ <p className="mt-1 max-w-xl text-[11px] text-gray-500">
+ Establish the character once, then derive every animation from the same locked identity.
+ </p>
+ </div>
+
+ <div className="grid flex-[1.4] grid-cols-1 gap-2 sm:grid-cols-3">
+ <StepSummary
+ number="1"
+ label="Turnaround"
+ status={turnaroundLocked ? 'Locked' : backfillOptional ? 'Optional backfill' : turnaroundCandidates.length > 0 ? 'Candidate ready' : 'Design'}
+ tone={turnaroundLocked ? 'complete' : 'active'}
+ />
+ <StepSummary
+ number="2"
+ label="Main"
+ status={mainLocked ? 'Locked' : turnaroundLocked ? 'Ready to derive' : 'Waiting'}
+ tone={mainLocked ? 'complete' : turnaroundLocked ? 'active' : 'waiting'}
+ />
+ <StepSummary
+ number="3"
+ label="Anchors"
+ status={anchorProgress}
+ tone={allAnchorsLocked ? 'complete' : mainLocked ? 'active' : 'waiting'}
+ />
+ </div>
+
<div
- className="flex items-center gap-1.5"
+ className="flex shrink-0 items-center gap-1.5 rounded-lg border border-port-border bg-port-bg px-2.5 py-2"
title={keyFrozen
? 'Chroma key is frozen with the locked reference set'
: 'Chroma key — auto-selected when the turnaround sheet locks; pin one of the three standard keys, or auto to let the lock decide'}
>
- <span className="text-xs text-gray-500">key</span>
+ <span className="mr-1 text-[10px] uppercase tracking-wide text-gray-500">Chroma key</span>
<button
+ type="button"
onClick={() => setChromaKey(null)}
disabled={keySaving || keyFrozen}
- className={`px-1.5 h-5 rounded-sm border text-[10px] ${!record.chromaKey ? 'border-white ring-1 ring-port-accent text-white' : 'border-port-border text-gray-400 opacity-60 hover:opacity-100'} disabled:opacity-40`}
+ className={`h-6 rounded-sm border px-2 text-[10px] ${!record.chromaKey ? 'border-white ring-1 ring-port-accent text-white' : 'border-port-border text-gray-400 opacity-60 hover:opacity-100'} disabled:opacity-40`}
>
auto
</button>
{CHROMA_KEYS.map((hex) => (
<button
+ type="button"
key={hex}
onClick={() => setChromaKey(hex)}
disabled={keySaving || keyFrozen}
aria-label={`Set chroma key ${hex}`}
- className={`w-5 h-5 rounded-sm border ${record.chromaKey === hex ? 'border-white ring-1 ring-port-accent' : 'border-port-border opacity-60 hover:opacity-100'} disabled:opacity-40`}
+ className={`h-6 w-6 rounded-sm border ${record.chromaKey === hex ? 'border-white ring-1 ring-port-accent' : 'border-port-border opacity-60 hover:opacity-100'} disabled:opacity-40`}
style={{ backgroundColor: hex }}
/>
))}
</div>
</div>
+
{manifest?.chromaKeyWarning && (
- <p className="text-xs text-port-warning">{manifest.chromaKeyWarning}</p>
+ <p className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-2 text-xs text-port-warning">
+ {manifest.chromaKeyWarning}
+ </p>
)}
{noBackend && (
- <p className="text-xs text-port-warning">
+ <p className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-2 text-xs text-port-warning">
No image backend configured — enable Codex or Grok, or set a local Python path, in Settings → Image Gen to generate references.
</p>
)}
- {/* Step 1 — the turnaround sheet, the identity root every later render
- descends from. A character created before #2979 backfills one from its
- already-locked main so its remaining anchors get all sides too. */}
- <div className="space-y-2">
- <h4 className="text-xs uppercase tracking-wide text-gray-500">
- 1 · Turnaround sheet
- {turnaroundLocked && <span className="ml-1 text-[10px] text-port-success normal-case tracking-normal">· locked</span>}
- {backfillOptional && <span className="ml-1 text-[10px] text-gray-600 normal-case tracking-normal">· optional</span>}
- </h4>
- {turnaroundLocked ? (
- // The sheet is a square PNG (four figures in a 1:1 canvas), so render
- // it as a large square — a fixed landscape box letterboxed it into a
- // tiny center strip and wasted the sides. It's the identity root, so
- // it gets more room than the single-figure anchors below.
- <div className="flex flex-col sm:flex-row items-start gap-3">
- <SpriteImg recordId={recordId} path={manifest.turnaround.path} className="w-full max-w-sm aspect-square object-contain bg-port-bg border border-port-border rounded" />
- <p className="text-xs text-gray-500 flex items-center gap-1">
- <Lock className="w-3 h-3" /> frozen · identity root
- </p>
- </div>
- ) : (
- <div className="space-y-2">
- <p className="text-[11px] text-gray-500">
- {backfillOptional
- ? 'This character predates turnaround sheets and its reference set is already complete, so a sheet won’t change any locked artifact. Generating one is optional — it only gives future forks of this character all four sides to work from.'
- : backfilling
- ? 'This character was built before turnaround sheets. Generate one from its locked main reference — the remaining directional anchors will be drawn from it, so accessories stay on the same side of the body.'
- : 'One image, four views (front · right · back · left). Every later render is redrawn from it, so a bag or pocket keeps the same anatomical side from every angle.'}
- </p>
- <textarea
- value={designPrompt}
- onChange={(e) => setDesignPrompt(e.target.value)}
- placeholder="Describe the character (or attach a design reference image)…"
- rows={2}
- className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white"
- />
- {/* Reference image (optional, i2i seed) — pick ONE of three sources. */}
- {refSource ? (
- <div className="flex items-center gap-3 bg-port-bg border border-port-border rounded p-2">
- {refSource.type === 'sprite' ? (
- <SpriteImg recordId={refSource.id} path={refSource.path} className="w-14 h-14 object-contain shrink-0" />
+ <div className="grid items-start gap-4 @5xl:grid-cols-[minmax(0,1.65fr)_minmax(19rem,0.75fr)]">
+ {/* Step 1 — the turnaround sheet, the identity root every later render
+ descends from. On desktop, design controls and candidate review sit
+ beside each other instead of leaving the right side of the panel
+ empty; below that breakpoint they preserve the guided linear flow. */}
+ <section
+ aria-labelledby="sprite-turnaround-heading"
+ className="min-w-0 space-y-4 rounded-xl border border-port-border bg-port-bg/50 p-3 sm:p-4"
+ >
+ <StageHeading
+ id="sprite-turnaround-heading"
+ number="1"
+ title="Turnaround sheet"
+ status={turnaroundLocked ? 'Locked identity root' : backfillOptional ? 'Optional for future forks' : backfilling ? 'Backfill from the locked main' : 'Design the four-view identity root'}
+ statusTone={turnaroundLocked ? 'text-port-success' : backfillOptional ? 'text-gray-500' : 'text-port-accent'}
+ />
+
+ {turnaroundLocked ? (
+ <div className="grid items-start gap-4 @3xl:grid-cols-[minmax(16rem,1.15fr)_minmax(14rem,0.65fr)]">
+ <SpriteImg
+ recordId={recordId}
+ path={manifest.turnaround.path}
+ className="w-full aspect-square rounded-lg border border-port-border bg-port-bg object-contain"
+ />
+ <div className="rounded-lg border border-port-success/30 bg-port-success/10 p-3">
+ <p className="flex items-center gap-1.5 text-xs font-medium text-port-success">
+ <Lock className="h-3.5 w-3.5" /> Frozen identity root
+ </p>
+ <p className="mt-2 text-[11px] leading-relaxed text-gray-500">
+ The front, right, back, and left views are fixed. The main reference and every directional anchor derive from this sheet.
+ </p>
+ </div>
+ </div>
+ ) : (
+ <div className={`grid items-start gap-4 ${turnaroundCandidates.length > 0 ? '@3xl:grid-cols-[minmax(17rem,0.72fr)_minmax(20rem,1.28fr)]' : ''}`}>
+ <div className="min-w-0 space-y-3">
+ <p className="text-[11px] leading-relaxed text-gray-500">
+ {backfillOptional
+ ? 'This character predates turnaround sheets and its reference set is already complete, so a sheet won’t change any locked artifact. Generating one is optional — it only gives future forks of this character all four sides to work from.'
+ : backfilling
+ ? 'This character was built before turnaround sheets. Generate one from its locked main reference — the remaining directional anchors will be drawn from it, so accessories stay on the same side of the body.'
+ : 'One image, four views (front · right · back · left). Every later render is redrawn from it, so a bag or pocket keeps the same anatomical side from every angle.'}
+ </p>
+
+ <div>
+ <label htmlFor="sprite-turnaround-design-prompt" className="mb-1 block text-[10px] font-medium uppercase tracking-wide text-gray-500">
+ Character design
+ </label>
+ <textarea
+ id="sprite-turnaround-design-prompt"
+ value={designPrompt}
+ onChange={(e) => setDesignPrompt(e.target.value)}
+ placeholder="Describe the character (or attach a design reference image)…"
+ rows={4}
+ className="w-full resize-y rounded-lg border border-port-border bg-port-bg px-3 py-2 text-sm text-white"
+ />
+ </div>
+
+ {/* Reference image (optional, i2i seed) — pick ONE of three sources. */}
+ {refSource ? (
+ <div className="flex items-center gap-3 rounded-lg border border-port-border bg-port-bg p-2">
+ {refSource.type === 'sprite' ? (
+ <SpriteImg recordId={refSource.id} path={refSource.path} className="h-16 w-16 shrink-0 rounded object-contain" />
+ ) : (
+ <img src={refSource.previewUrl} alt="reference" className="h-16 w-16 shrink-0 rounded object-contain" />
+ )}
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-xs text-gray-300">
+ {refSource.type === 'upload' ? refSource.file.name
+ : refSource.type === 'gallery' ? (refSource.label || 'gallery image')
+ : refSource.name}
+ </p>
+ <p className="text-[10px] text-gray-500">
+ {refSource.type === 'upload' ? 'uploaded image'
+ : refSource.type === 'gallery' ? 'from render history'
+ : 'from reference sprite'}
+ </p>
+ <label className="mt-1 flex flex-wrap items-center gap-2 text-[10px] text-gray-500">
+ Fidelity
+ <input
+ type="range" min="0" max="1" step="0.05" value={strength}
+ onChange={(e) => setStrength(Number(e.target.value))}
+ className="min-w-24 flex-1 accent-port-accent"
+ aria-label="Reference fidelity"
+ />
+ <span className="w-8 tabular-nums">{strength.toFixed(2)}</span>
+ </label>
+ </div>
+ <button
+ type="button"
+ onClick={clearSource}
+ aria-label="Remove reference image"
+ className="shrink-0 p-1 text-gray-400 hover:text-white"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ </div>
) : (
- <img src={refSource.previewUrl} alt="reference" className="w-14 h-14 object-contain rounded shrink-0" />
+ <div className="space-y-2">
+ <p className="text-[10px] font-medium uppercase tracking-wide text-gray-500">Reference image <span className="normal-case tracking-normal">(optional)</span></p>
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-3 @3xl:grid-cols-1">
+ <FilePickerButton
+ accept={IMAGE_ACCEPT}
+ onChange={(e) => pickUpload(e.target.files?.[0] || null)}
+ ariaLabel="Upload a reference image"
+ className="flex min-h-9 items-center justify-center gap-1.5 rounded border border-port-border bg-port-card px-2.5 py-1 text-xs text-gray-300 hover:border-port-accent"
+ >
+ <Upload className="h-3.5 w-3.5" /> Upload
+ </FilePickerButton>
+ <button
+ type="button"
+ onClick={() => setGalleryOpen(true)}
+ className="flex min-h-9 items-center justify-center gap-1.5 rounded border border-port-border bg-port-card px-2.5 py-1 text-xs text-gray-300 hover:border-port-accent"
+ >
+ <Images className="h-3.5 w-3.5" /> History
+ </button>
+ <button
+ type="button"
+ onClick={() => setSpritePickerOpen(true)}
+ className="flex min-h-9 items-center justify-center gap-1.5 rounded border border-port-border bg-port-card px-2.5 py-1 text-xs text-gray-300 hover:border-port-accent"
+ >
+ <PersonStanding className="h-3.5 w-3.5" /> Sprite
+ </button>
+ </div>
+ </div>
)}
- <div className="min-w-0 flex-1">
- <p className="text-xs text-gray-300 truncate">
- {refSource.type === 'upload' ? refSource.file.name
- : refSource.type === 'gallery' ? (refSource.label || 'gallery image')
- : refSource.name}
- </p>
- <p className="text-[10px] text-gray-500">
- {refSource.type === 'upload' ? 'uploaded image'
- : refSource.type === 'gallery' ? 'from render history'
- : 'from reference sprite'}
- </p>
- <label className="mt-1 flex items-center gap-2 text-[10px] text-gray-500">
- fidelity
- <input
- type="range" min="0" max="1" step="0.05" value={strength}
- onChange={(e) => setStrength(Number(e.target.value))}
- className="accent-port-accent"
- aria-label="Reference fidelity"
- />
- <span className="tabular-nums w-8">{strength.toFixed(2)}</span>
- </label>
+
+ <div className="flex flex-col gap-2 border-t border-port-border pt-3 sm:flex-row sm:flex-wrap sm:items-end">
+ {modePicker}
+ <button
+ type="button"
+ onClick={() => generate('turnaround')}
+ disabled={!mode || !!pendingJobs.turnaround || (!designPrompt.trim() && !refSource && !backfilling)}
+ className="flex min-h-9 flex-1 items-center justify-center gap-1.5 rounded bg-port-accent px-3 py-1.5 text-sm text-white hover:bg-blue-600 disabled:opacity-50"
+ >
+ {pendingJobs.turnaround ? <RefreshCw className="h-3.5 w-3.5 animate-spin" /> : <Sparkles className="h-3.5 w-3.5" />}
+ {pendingJobs.turnaround ? 'Rendering…'
+ : backfilling ? 'Generate from locked main'
+ : turnaroundCandidates.length ? 'Regenerate' : 'Generate candidate'}
+ </button>
</div>
- <button
- type="button"
- onClick={clearSource}
- aria-label="Remove reference image"
- className="p-1 text-gray-400 hover:text-white shrink-0"
- >
- <X className="w-4 h-4" />
- </button>
</div>
- ) : (
- <div className="flex flex-wrap items-center gap-2">
- <span className="text-xs text-gray-500">Reference image (optional):</span>
- <FilePickerButton
- accept={IMAGE_ACCEPT}
- onChange={(e) => pickUpload(e.target.files?.[0] || null)}
- ariaLabel="Upload a reference image"
- className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"
- >
- <Upload className="w-3.5 h-3.5" /> Upload
- </FilePickerButton>
+
+ {turnaroundCandidates.length > 0 && (
+ <div className="min-w-0 rounded-lg border border-port-border bg-port-bg p-3">
+ <div className="mb-3 flex items-start justify-between gap-3">
+ <div>
+ <h5 className="text-xs font-semibold text-gray-300">Candidate review</h5>
+ <p className="mt-0.5 text-[10px] text-gray-500">Inspect at full size, then freeze the identity you want to keep.</p>
+ </div>
+ <span className="rounded-full border border-port-border px-2 py-0.5 text-[10px] text-gray-500">
+ {turnaroundCandidates.length}
+ </span>
+ </div>
+ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,18rem),1fr))] gap-3">
+ {turnaroundCandidates.map((candidate) => (
+ <CandidateTile
+ key={candidate.path}
+ recordId={recordId}
+ candidate={candidate}
+ locking={locking}
+ clipRisk={clipRisks[candidate.path]}
+ onLock={(picked, accept) => lock('turnaround', picked, accept)}
+ />
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </section>
+
+ {/* Step 2 stays visible beside the active turnaround workspace on wide
+ screens. At narrower widths it follows step 1 in reading order. */}
+ <section
+ aria-labelledby="sprite-main-reference-heading"
+ className="min-w-0 space-y-4 rounded-xl border border-port-border bg-port-bg/50 p-3 sm:p-4"
+ >
+ <StageHeading
+ id="sprite-main-reference-heading"
+ number="2"
+ title="Main reference"
+ status={mainLocked ? 'Locked walk-south identity' : turnaroundLocked ? 'Ready to derive from the front view' : 'Waiting for the turnaround sheet'}
+ statusTone={mainLocked ? 'text-port-success' : turnaroundLocked ? 'text-port-accent' : 'text-gray-500'}
+ />
+
+ {mainLocked ? (
+ <div className="grid items-start gap-3 @3xl:grid-cols-[minmax(12rem,18rem)_1fr] @5xl:grid-cols-1">
+ <SpriteImg
+ recordId={recordId}
+ path={manifest.mainReference.path}
+ className="w-full aspect-square rounded-lg border border-port-border bg-port-bg object-contain"
+ />
+ <div className="space-y-3">
+ <p className="flex items-center gap-1.5 text-xs text-port-success">
+ <Lock className="h-3.5 w-3.5" /> Frozen · immutable root
+ </p>
+ <p className="text-[11px] leading-relaxed text-gray-500">
+ This front-facing reference seeds thumbnails and the walk-south identity. Fork to make a new editable version.
+ </p>
<button
type="button"
- onClick={() => setGalleryOpen(true)}
- className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"
+ onClick={() => setForkOpen(true)}
+ className="flex min-h-9 w-full items-center justify-center gap-1.5 rounded border border-port-border bg-port-card px-2.5 py-1.5 text-xs text-gray-300 hover:border-port-accent"
>
- <Images className="w-3.5 h-3.5" /> From history
+ <GitFork className="h-3.5 w-3.5" /> Fork from this reference
</button>
+ </div>
+ </div>
+ ) : turnaroundLocked ? (
+ <div className="space-y-3">
+ <p className="text-[11px] leading-relaxed text-gray-500">
+ Redrawn from the sheet&rsquo;s front panel — no separate design input.
+ </p>
+ <div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-end @5xl:flex-col @5xl:items-stretch">
+ {modePicker}
<button
type="button"
- onClick={() => setSpritePickerOpen(true)}
- className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"
+ onClick={() => generate('main')}
+ disabled={!mode || !!pendingJobs.main}
+ className="flex min-h-9 flex-1 items-center justify-center gap-1.5 rounded bg-port-accent px-3 py-1.5 text-sm text-white hover:bg-blue-600 disabled:opacity-50"
>
- <PersonStanding className="w-3.5 h-3.5" /> From sprite
+ {pendingJobs.main ? <RefreshCw className="h-3.5 w-3.5 animate-spin" /> : <Sparkles className="h-3.5 w-3.5" />}
+ {pendingJobs.main ? 'Rendering…' : mainCandidates.length ? 'Regenerate' : 'Generate candidate'}
</button>
</div>
- )}
- <div className="flex flex-wrap items-center gap-3">
- {modePicker}
- <button
- onClick={() => generate('turnaround')}
- disabled={!mode || !!pendingJobs.turnaround || (!designPrompt.trim() && !refSource && !backfilling)}
- className="flex items-center gap-1.5 px-3 py-1 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white rounded text-sm"
- >
- {pendingJobs.turnaround ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}
- {pendingJobs.turnaround ? 'Rendering…'
- : backfilling ? 'Generate from locked main'
- : (candidatesByTarget.turnaround || []).length ? 'Regenerate' : 'Generate candidate'}
- </button>
+ {mainCandidates.length > 0 && (
+ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,11rem),1fr))] gap-3">
+ {mainCandidates.map((candidate) => (
+ <CandidateTile
+ key={candidate.path}
+ recordId={recordId}
+ candidate={candidate}
+ locking={locking}
+ clipRisk={clipRisks[candidate.path]}
+ onLock={(picked, accept) => lock('main', picked, accept)}
+ />
+ ))}
+ </div>
+ )}
</div>
- {(candidatesByTarget.turnaround || []).length > 0 && (
- <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
- {candidatesByTarget.turnaround.map((c) => (
- <CandidateTile key={c.path} recordId={recordId} candidate={c} locking={locking} clipRisk={clipRisks[c.path]} onLock={(cand, accept) => lock('turnaround', cand, accept)} />
- ))}
- </div>
- )}
- </div>
- )}
+ ) : (
+ <div className="flex min-h-40 items-center justify-center rounded-lg border border-dashed border-port-border bg-port-bg px-4 text-center">
+ <p className="max-w-xs text-[11px] text-gray-600">Lock the turnaround sheet to unlock this stage.</p>
+ </div>
+ )}
+ </section>
</div>
- {/* Step 2 — the main reference: the sheet's front view, and the sprite's
- canonical face (thumbnails, fork seeds, the walk-south anchor). */}
- <div className="space-y-2">
- <h4 className="text-xs uppercase tracking-wide text-gray-500">
- 2 · Main reference (walk-south)
- {mainLocked && <span className="ml-1 text-[10px] text-port-success normal-case tracking-normal">· locked</span>}
- </h4>
- {mainLocked ? (
- <div className="flex items-start gap-3">
- <SpriteImg recordId={recordId} path={manifest.mainReference.path} className="w-32 h-32 object-contain bg-port-bg border border-port-border rounded" />
- <div className="space-y-2">
- <p className="text-xs text-gray-500 flex items-center gap-1"><Lock className="w-3 h-3" /> frozen · immutable root</p>
- {/* A locked main can never be regenerated — to iterate on it, fork
- into a new character seeded from this reference (image+text→image). */}
+ {/* Step 3 spans the workspace because active anchors need repeatable card
+ width. A complete set stays collapsed and compact by default. */}
+ {mainLocked && (
+ <section
+ aria-labelledby="sprite-directional-anchors-heading"
+ className="space-y-3 rounded-xl border border-port-border bg-port-bg/50 p-3 sm:p-4"
+ >
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <StageHeading
+ id="sprite-directional-anchors-heading"
+ number="3"
+ title="Directional anchors"
+ status={allAnchorsLocked ? `${anchorProgress} · complete` : anchorProgress}
+ statusTone={allAnchorsLocked ? 'text-port-success' : turnaroundLocked ? 'text-port-accent' : 'text-gray-500'}
+ />
+ <div className="flex flex-wrap items-center gap-2">
+ {anchorsOpen && !allAnchorsLocked && modePicker}
<button
type="button"
- onClick={() => setForkOpen(true)}
- className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"
- >
- <GitFork className="w-3.5 h-3.5" /> Fork from this reference
- </button>
- </div>
- </div>
- ) : turnaroundLocked ? (
- <div className="space-y-2">
- <p className="text-[11px] text-gray-500">Redrawn from the sheet&rsquo;s front panel — no separate design input.</p>
- <div className="flex flex-wrap items-center gap-3">
- {modePicker}
- <button
- onClick={() => generate('main')}
- disabled={!mode || !!pendingJobs.main}
- className="flex items-center gap-1.5 px-3 py-1 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white rounded text-sm"
+ onClick={() => setAnchorsOpen((open) => !open)}
+ aria-expanded={anchorsOpen}
+ className="flex min-h-8 items-center gap-1 rounded border border-port-border bg-port-card px-2.5 py-1 text-xs text-gray-300 hover:border-port-accent"
>
- {pendingJobs.main ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}
- {pendingJobs.main ? 'Rendering…' : (candidatesByTarget.main || []).length ? 'Regenerate' : 'Generate candidate'}
+ {anchorsOpen ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
+ {anchorsOpen ? 'Hide anchors' : 'Show anchors'}
</button>
</div>
- {(candidatesByTarget.main || []).length > 0 && (
- <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 gap-2">
- {candidatesByTarget.main.map((c) => (
- <CandidateTile key={c.path} recordId={recordId} candidate={c} locking={locking} clipRisk={clipRisks[c.path]} onLock={(cand, accept) => lock('main', cand, accept)} />
- ))}
- </div>
- )}
</div>
- ) : (
- <p className="text-[11px] text-gray-600">Lock the turnaround sheet first.</p>
- )}
- </div>
- {/* Step 3 — directional anchors, each redrawn from the sheet's panel for
- that side (gated on the sheet even for pre-#2979 characters). */}
- {mainLocked && (
- <div className="space-y-2">
- <div className="flex items-center gap-3">
- <button
- type="button"
- onClick={() => setAnchorsOpen((o) => !o)}
- aria-expanded={anchorsOpen}
- className="flex items-center gap-1 text-xs uppercase tracking-wide text-gray-500 hover:text-gray-300"
- >
- {anchorsOpen ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
- 3 · Directional anchors
- {allAnchorsLocked && (
- <span className="text-[10px] text-port-success normal-case tracking-normal flex items-center gap-0.5">
- · <Lock className="w-2.5 h-2.5" /> all locked
- </span>
- )}
- </button>
- {anchorsOpen && modePicker}
- </div>
- {!anchorsOpen && allAnchorsLocked && (
- <p className="text-[10px] text-gray-600">Locked anchors are listed under “Reference set” below.</p>
+ {!anchorsOpen && (
+ <p className="text-[10px] text-gray-600">
+ {allAnchorsLocked
+ ? 'The frozen files remain available in the Reference set asset collection below.'
+ : 'Expand to generate, review, and lock each directional identity.'}
+ </p>
)}
{anchorsOpen && !allAnchorsLocked && (
<p className="text-[10px] text-gray-600">
{turnaroundLocked
- ? 'Each anchor is redrawn from the turnaround sheet’s panel for that side.'
+ ? 'Each anchor is redrawn from the turnaround sheet’s matching side.'
: 'Blocked: generate and lock the turnaround sheet above first — anchors are drawn from it.'}
</p>
)}
{anchorsOpen && (
- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
- {manifest.anchors.map((anchor) => {
- const cands = candidatesByTarget[anchor.direction] || [];
- return (
- <div key={anchor.id} className="bg-port-bg border border-port-border rounded p-2 space-y-1.5">
- <p className="text-xs text-gray-400 flex items-center justify-between">
- {anchor.direction}
- {anchor.status === 'locked' && <Lock className="w-3 h-3 text-port-success" />}
- </p>
- {anchor.status === 'locked' ? (
- <SpriteImg recordId={recordId} path={anchor.path} className="w-full aspect-square object-contain" />
- ) : (
- <div className="space-y-1.5">
- {/* Optional correction guidance re-appended to the prompt on
- each re-roll — without it, regenerating with the same
- inputs tends to reproduce the same mistake. Shared with
- the asset card so both surfaces write one source (#2964). */}
- <CorrectionNote
- direction={anchor.direction}
- value={corrections[anchor.direction]}
- onChange={onCorrectionChange}
- className="text-[11px]"
- />
- <button
- onClick={() => generate(anchor.direction)}
- // Gated on the sheet, matching the server's
- // TURNAROUND_NOT_LOCKED 409 and the note above — a
- // pre-#2979 character must backfill one first.
- disabled={!mode || !turnaroundLocked || !!pendingJobs[anchor.direction]}
- className="flex items-center gap-1 w-full justify-center px-2 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50"
- >
- {pendingJobs[anchor.direction]
- ? <><RefreshCw className="w-3 h-3 animate-spin" /> Rendering…</>
- : cands.length
- ? <><RefreshCw className="w-3 h-3" /> Regenerate</>
- : <><Sparkles className="w-3 h-3" /> Generate</>}
- </button>
- {cands.map((c) => (
- <CandidateTile key={c.path} recordId={recordId} candidate={c} locking={locking} clipRisk={clipRisks[c.path]} onLock={(cand, accept) => lock(anchor.direction, cand, accept)} />
- ))}
+ <div className={`grid grid-cols-2 gap-3 @3xl:grid-cols-4 ${allAnchorsLocked ? '@5xl:grid-cols-8' : ''}`}>
+ {manifest.anchors.map((anchor) => {
+ const anchorCandidates = candidatesByTarget[anchor.direction] || [];
+ return (
+ <div key={anchor.id} className="min-w-0 space-y-2 rounded-lg border border-port-border bg-port-bg p-2">
+ <h5 className="flex items-center justify-between text-xs capitalize text-gray-400">
+ {anchor.direction}
+ {anchor.status === 'locked' && <Lock className="h-3 w-3 text-port-success" />}
+ </h5>
+ {anchor.status === 'locked' ? (
+ <LockedAnchor
+ recordId={recordId}
+ anchor={anchor}
+ // South is the immutable main reference, not a
+ // turnaround-derived directional anchor.
+ canUnlock={turnaroundLocked && anchor.direction !== 'south'}
+ unlocking={anchorUnlocking}
+ onUnlock={unlockAnchor}
+ />
+ ) : (
+ <div className="space-y-2">
+ <CorrectionNote
+ direction={anchor.direction}
+ value={corrections[anchor.direction]}
+ onChange={onCorrectionChange}
+ className="text-[11px]"
+ />
+ <button
+ type="button"
+ onClick={() => generate(anchor.direction)}
+ disabled={!mode || !turnaroundLocked || !!pendingJobs[anchor.direction]}
+ className="flex min-h-8 w-full items-center justify-center gap-1 rounded border border-port-border bg-port-card px-2 py-1 text-xs text-gray-300 hover:border-port-accent disabled:opacity-50"
+ >
+ {pendingJobs[anchor.direction]
+ ? <><RefreshCw className="h-3 w-3 animate-spin" /> Rendering…</>
+ : anchorCandidates.length
+ ? <><RefreshCw className="h-3 w-3" /> Regenerate</>
+ : <><Sparkles className="h-3 w-3" /> Generate</>}
+ </button>
+ {anchorCandidates.map((candidate) => (
+ <CandidateTile
+ key={candidate.path}
+ recordId={recordId}
+ candidate={candidate}
+ locking={locking}
+ clipRisk={clipRisks[candidate.path]}
+ onLock={(picked, accept) => lock(anchor.direction, picked, accept)}
+ />
+ ))}
+ </div>
+ )}
</div>
- )}
- </div>
- );
- })}
- </div>
+ );
+ })}
+ </div>
)}
- </div>
+ </section>
)}
{/* Reference-image source pickers + fork. Portal-based modals, so their
diff --git a/client/src/components/sprites/ReferenceWorkflow.test.jsx b/client/src/components/sprites/ReferenceWorkflow.test.jsx
new file mode 100644
index 0000000000..ea06fbe741
--- /dev/null
+++ b/client/src/components/sprites/ReferenceWorkflow.test.jsx
@@ -0,0 +1,121 @@
+import { describe, expect, it, vi } from 'vitest';
+import { render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+vi.mock('../../services/apiSprites.js', () => ({
+ generateSpriteReference: vi.fn(() => Promise.resolve({ jobId: 'job-1' })),
+ lockSpriteReference: vi.fn(() => Promise.resolve({})),
+ unlockSpriteReferenceAnchor: vi.fn(() => Promise.resolve({ walkInvalidated: true })),
+ updateSpriteRecord: vi.fn(() => Promise.resolve({})),
+}));
+
+vi.mock('../ui/Toast', () => ({
+ default: { error: vi.fn(), success: vi.fn() },
+}));
+
+vi.mock('../imageGen/GalleryImagePicker.jsx', () => ({ default: () => null }));
+vi.mock('./SpriteReferencePicker.jsx', () => ({ default: () => null }));
+vi.mock('./ForkSpriteModal.jsx', () => ({ default: () => null }));
+vi.mock('./SpritePreview.jsx', () => ({
+ default: ({ path, className }) => (
+ <button type="button" aria-label={`Enlarge ${path}`} className={className} />
+ ),
+}));
+
+import ReferenceWorkflow from './ReferenceWorkflow.jsx';
+import { unlockSpriteReferenceAnchor } from '../../services/apiSprites.js';
+
+const DIRECTIONS = ['south', 'south-east', 'east', 'north-east', 'north', 'north-west', 'west', 'south-west'];
+
+const renders = {
+ pendingJobs: {},
+ beginSubmit: vi.fn(),
+ resolveSubmit: vi.fn(),
+ cancelSubmit: vi.fn(),
+};
+
+const renderWorkflow = ({ turnaround } = {}) => render(
+ <ReferenceWorkflow
+ record={{ id: 'example-pioneer', name: 'Example Pioneer', chromaKey: '#FF00FF' }}
+ reference={{
+ manifest: {
+ status: 'complete',
+ ...(turnaround ? { turnaround } : {}),
+ mainReference: { locked: true, path: 'reference/example-pioneer-main-v1.png' },
+ anchors: DIRECTIONS.map((direction) => ({
+ id: `anchor-${direction}`,
+ direction,
+ status: 'locked',
+ path: `reference/example-pioneer-${direction}-v1.png`,
+ })),
+ },
+ candidates: [{
+ target: 'turnaround',
+ path: 'reference/example-pioneer-turnaround-candidate-01.png',
+ mode: 'codex',
+ }],
+ }}
+ renders={renders}
+ corrections={{}}
+ onCorrectionChange={vi.fn()}
+ backends={[{ id: 'codex', label: 'Codex' }]}
+ mode="codex"
+ onModeChange={vi.fn()}
+ onChanged={vi.fn()}
+ onForked={vi.fn()}
+ />,
+);
+
+describe('ReferenceWorkflow workspace', () => {
+ it('pairs the active turnaround review with the locked main on wide containers', () => {
+ renderWorkflow();
+
+ const turnaround = screen.getByRole('region', { name: 'Turnaround sheet' });
+ const main = screen.getByRole('region', { name: 'Main reference' });
+ const desktopWorkspace = turnaround.parentElement;
+
+ expect(desktopWorkspace).toContainElement(main);
+ expect(desktopWorkspace.className).toContain('@5xl:grid-cols-');
+ expect(within(turnaround).getByRole('heading', { name: 'Candidate review' })).toBeInTheDocument();
+ expect(within(turnaround).getByRole('button', { name: /Enlarge .*turnaround-candidate-01/ })).toBeInTheDocument();
+ expect(within(main).getByRole('button', { name: 'Fork from this reference' })).toBeInTheDocument();
+ expect(screen.getAllByText('8/8 locked').length).toBeGreaterThan(0);
+ });
+
+ it('keeps a complete anchor set compact until the user asks to inspect it', async () => {
+ const user = userEvent.setup();
+ renderWorkflow();
+
+ const anchors = screen.getByRole('region', { name: 'Directional anchors' });
+ expect(within(anchors).queryByRole('button', { name: /Enlarge .*north-v1/ })).not.toBeInTheDocument();
+
+ await user.click(within(anchors).getByRole('button', { name: 'Show anchors' }));
+
+ expect(within(anchors).getByRole('button', { name: /Enlarge .*north-v1/ })).toBeInTheDocument();
+ expect(within(anchors).getByRole('button', { name: 'Hide anchors' })).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('confirms and unlocks one turnaround-derived anchor without exposing south', async () => {
+ const user = userEvent.setup();
+ renderWorkflow({
+ turnaround: {
+ locked: true,
+ path: 'reference/example-pioneer-turnaround-v1.png',
+ },
+ });
+
+ const anchors = screen.getByRole('region', { name: 'Directional anchors' });
+ await user.click(within(anchors).getByRole('button', { name: 'Show anchors' }));
+ expect(within(anchors).queryByRole('button', { name: 'Unlock south anchor' })).not.toBeInTheDocument();
+
+ await user.click(within(anchors).getByRole('button', { name: 'Unlock north anchor' }));
+ expect(within(anchors).getByText('Regenerate north from turnaround?')).toBeInTheDocument();
+ await user.click(within(anchors).getByRole('button', { name: 'Confirm unlock north anchor' }));
+
+ expect(unlockSpriteReferenceAnchor).toHaveBeenCalledWith(
+ 'example-pioneer',
+ { direction: 'north' },
+ { silent: true },
+ );
+ });
+});
diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsx
index e2b02c19eb..4e6a5f00c8 100644
--- a/client/src/components/sprites/WalkWorkflow.jsx
+++ b/client/src/components/sprites/WalkWorkflow.jsx
@@ -9,6 +9,7 @@ import {
} from '../../services/apiSprites.js';
import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';
import CycleTarget from './CycleTarget.jsx';
+import SpritePreview from './SpritePreview.jsx';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
import { spriteAssetUrl, checkerboardStyle, PIXELATED } from './spriteAssets.js';
import {
@@ -142,7 +143,7 @@ const driftRemedy = ({ approved, hasSourceClip, imported }) => {
};
function DirectionCard({
- recordId, direction, anchorLocked, run, approved, finalized, pending,
+ recordId, direction, anchorLocked, anchorPath, run, approved, finalized, pending,
onOpenTrimmer, onGenerate, onApprove, onRetry, onReprocess, onReopen,
reprocessing, retrying, cycleLabel, drift, targetSaving, imported,
}) {
@@ -154,6 +155,7 @@ function DirectionCard({
// Generate (server truth, since the client pending flag drops once the run is
// persisted). Only 'rendering' has a live Shell session to link to.
const rendering = run?.status === 'rendering';
+ const supersededAnchor = run?.status === 'superseded-anchor';
// `targetSaving` blocks the render actions without claiming the direction is
// rendering: the set's cycle target is mid-PATCH, so a queue now would be
// gated against a value the server hasn't persisted yet (409 target mismatch).
@@ -165,7 +167,13 @@ function DirectionCard({
// imagegen redraw), so there's no vendor-directory coupling here anymore. The
// link stands for approved and finalized runs too, since a trim is a
// non-destructive derived artifact under `walk/trims/`.
- const trimmable = Boolean(run?.stripPreview?.stripPath);
+ const trimmable = Boolean(run?.stripPreview?.stripPath) && !supersededAnchor;
+ // Before a packaged animation exists, keep the exact locked directional
+ // anchor visible in the card. It is the idle/source pose the walk will be
+ // conditioned on, and reviewing it here prevents spending a render on a
+ // direction whose identity or anatomy is already wrong. A candidate or
+ // approved strip replaces it as soon as there is an animation to inspect.
+ const hasWalkPreview = Boolean((approved || candidate) && run?.stripPreview?.stripPath);
const hasSourceClip = hasClip(run);
// The dead end: still packaged by the source pipeline AND no clip to re-derive
// from. Everything the server refuses for this direction refuses on exactly
@@ -177,7 +185,8 @@ function DirectionCard({
const statusLabel = approved ? 'approved'
: (pending || rendering) ? 'rendering…'
: run?.status === 'postprocessing' ? 'packaging…'
- : run?.status || (anchorLocked ? 'ready' : 'anchor not locked');
+ : supersededAnchor ? 'anchor revised'
+ : run?.status || (anchorLocked ? 'ready' : 'anchor not locked');
return (
<div className="bg-port-bg border border-port-border rounded p-2 space-y-1.5">
@@ -188,9 +197,26 @@ function DirectionCard({
</span>
</p>
- {(approved || candidate) && run?.stripPreview?.stripPath && (
+ {hasWalkPreview && (
<StripLoop recordId={recordId} stripPreview={run.stripPreview} />
)}
+ {!hasWalkPreview && anchorLocked && anchorPath && (
+ <div className="flex items-end gap-2">
+ <SpritePreview
+ recordId={recordId}
+ path={anchorPath}
+ alt={`${direction} reference idle pose`}
+ className="h-24 w-24 shrink-0 rounded border border-port-border"
+ zoomable
+ />
+ <span className="pb-1 text-[9px] leading-tight text-gray-600">reference idle</span>
+ </div>
+ )}
+ {supersededAnchor && (
+ <p className="rounded border border-port-warning/40 px-1.5 py-1 text-[10px] leading-tight text-port-warning">
+ Previous walk kept in history · generate again from the current anchor.
+ </p>
+ )}
{/* This direction is packaged at a geometry the set is no longer targeting
(#2985) — surfaced HERE rather than at atlas-compile time, which used to
@@ -628,6 +654,7 @@ export default function WalkWorkflow({
recordId={recordId}
direction={anchor.direction}
anchorLocked={anchor.status === 'locked'}
+ anchorPath={anchor.path}
run={latestRunByDirection[anchor.direction] || null}
approved={selection?.directions?.[anchor.direction]?.status === 'approved'}
finalized={finalized}
diff --git a/client/src/components/sprites/WalkWorkflow.test.jsx b/client/src/components/sprites/WalkWorkflow.test.jsx
index 8bde99e1eb..cd8446eccf 100644
--- a/client/src/components/sprites/WalkWorkflow.test.jsx
+++ b/client/src/components/sprites/WalkWorkflow.test.jsx
@@ -36,7 +36,7 @@ const renderWalk = (stripPreview, props = {}) => {
render(
<WalkWorkflow
record={{ id: 'example-walker' }}
- reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
+ reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked', path: 'reference/example-walker-east-v1.png' }] } }}
walk={{
runs: [run],
selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },
@@ -179,6 +179,80 @@ describe('WalkWorkflow loop preview', () => {
});
});
+describe('WalkWorkflow idle anchor preview', () => {
+ it('shows the locked directional anchor until the direction has a packaged animation', () => {
+ render(
+ <MemoryRouter>
+ <WalkWorkflow
+ record={{ id: 'example-walker' }}
+ reference={{
+ manifest: {
+ mainReference: { locked: true },
+ anchors: [{ direction: 'north-east', status: 'locked', path: 'reference/example-walker-north-east-v1.png' }],
+ },
+ }}
+ walk={{ runs: [], selection: { directions: {} }, walkSet: null }}
+ renders={noRenders()}
+ duration={6}
+ onDurationChange={vi.fn()}
+ onGenerate={vi.fn()}
+ onChanged={vi.fn()}
+ />
+ </MemoryRouter>,
+ );
+
+ const idle = screen.getByRole('img', { name: 'north-east reference idle pose' });
+ expect(idle.getAttribute('src')).toBe('/data/sprites/example-walker/reference/example-walker-north-east-v1.png');
+ expect(screen.getByText('reference idle')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Generate walk' })).toBeEnabled();
+ });
+
+ it('replaces the idle anchor with the packaged walk preview', () => {
+ renderWalk(APPROVED_STRIP);
+
+ expect(screen.queryByRole('img', { name: 'east reference idle pose' })).toBeNull();
+ expect(screen.getByRole('img', { name: 'walk loop preview' })).toBeInTheDocument();
+ });
+
+ it('returns to the current idle anchor when the previous walk used a superseded anchor', () => {
+ render(
+ <MemoryRouter>
+ <WalkWorkflow
+ record={{ id: 'example-walker' }}
+ reference={{
+ manifest: {
+ mainReference: { locked: true },
+ anchors: [{ direction: 'east', status: 'locked', path: 'reference/example-walker-east-v2.png' }],
+ },
+ }}
+ walk={{
+ runs: [{
+ id: 'run-east-old',
+ direction: 'east',
+ status: 'superseded-anchor',
+ stripPreview: APPROVED_STRIP,
+ }],
+ selection: { directions: {} },
+ walkSet: null,
+ }}
+ renders={noRenders()}
+ duration={6}
+ onDurationChange={vi.fn()}
+ onGenerate={vi.fn()}
+ onChanged={vi.fn()}
+ />
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByRole('img', { name: 'east reference idle pose' }).getAttribute('src'))
+ .toBe('/data/sprites/example-walker/reference/example-walker-east-v2.png');
+ expect(screen.getByText(/Previous walk kept in history/)).toBeInTheDocument();
+ expect(screen.queryByRole('img', { name: 'walk loop preview' })).toBeNull();
+ expect(screen.queryByRole('button', { name: /Edit in Loop Trimmer/ })).toBeNull();
+ expect(screen.getByRole('button', { name: 'Generate walk' })).toBeEnabled();
+ });
+});
+
// Loop trimming moved to its own deep-linkable workspace (#2933): the inline
// TrimPanel is gone and each card just links into the trimmer. The link stands
// for approved/finalized directions too (a trim is a non-destructive artifact),
diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.js
index 6858ea580d..3bba3a7ef7 100644
--- a/client/src/services/apiSprites.js
+++ b/client/src/services/apiSprites.js
@@ -83,6 +83,12 @@ export const lockSpriteReference = (id, body, options = {}) => request(`/sprites
method: 'POST', body: JSON.stringify(body), ...options,
});
+// Re-open one turnaround-derived directional anchor. Its old PNG stays
+// versioned on disk; any approved walk for the direction is invalidated.
+export const unlockSpriteReferenceAnchor = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/reference/unlock`, {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+
// Fork `id` into a new character seeded (image+text→image) from its locked main
// reference. Body: { name, id?, designPrompt, mode?, model?, effort?,
// initImageStrength? }. Returns { record, jobId, mode, target, anchorId }.
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 84bd8dd890..af07cd3da8 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1109,6 +1109,12 @@ export const spriteReferenceLockSchema = z.object({
acceptClipRisk: z.boolean().optional(),
});
+// Only the seven turnaround-derived anchors can be revised in place. The
+// turnaround and main remain frozen identity evidence, and south is the main.
+export const spriteReferenceUnlockSchema = z.object({
+ direction: z.enum(ANCHOR_DIRECTIONS),
+});
+
// Phase 3 (issue #2897): walk-animation workflow. All 8 directions are
// animatable (south's anchor is the frozen main itself).
const spriteWalkDirectionSchema = z.enum(SPRITE_DIRECTIONS);
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index 0dc7a84e89..a0e3b15834 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -19,6 +19,7 @@ import {
spriteCreateSchema,
spriteReferenceGenerateSchema,
spriteReferenceLockSchema,
+ spriteReferenceUnlockSchema,
spriteForkSchema,
spriteWalkGenerateSchema,
spriteWalkApproveSchema,
@@ -43,6 +44,7 @@ import {
listReferenceSources, listSpriteThumbnails, forkSprite,
} from '../services/sprites/reference.js';
import { resolveSpriteAssetPrompt } from '../services/sprites/assetPrompt.js';
+import { unlockDirectionalAnchor } from '../services/sprites/referenceRevision.js';
import {
getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
reopenWalkDirection, setWalkTarget, getWalkSourceFrames,
@@ -148,6 +150,14 @@ router.post('/:id/reference/lock', asyncHandler(async (req, res) => {
res.json(await lockReference(req.params.id, body));
}));
+// Re-open one turnaround-derived directional anchor for correction. The old
+// versioned PNG remains on disk, and any approved walk conditioned on it is
+// reopened so stale animation cannot survive the reference revision.
+router.post('/:id/reference/unlock', asyncHandler(async (req, res) => {
+ const body = validateRequest(spriteReferenceUnlockSchema, req.body);
+ res.json(await unlockDirectionalAnchor(req.params.id, body));
+}));
+
// Fork `:id` into a new character seeded (image+text→image) from its locked
// main reference. Creates the record then queues the main render; returns the
// new record + jobId. User-triggered per the AI-provider policy.
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index 04732561c3..bd2edd23f1 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -27,6 +27,14 @@ vi.mock('../services/sprites/assetPrompt.js', () => ({
resolveSpriteAssetPrompt: vi.fn(async () => ({ prompt: 'the built prompt', designPrompt: 'a knight', source: 'candidate' })),
}));
+vi.mock('../services/sprites/referenceRevision.js', () => ({
+ unlockDirectionalAnchor: vi.fn(async () => ({
+ manifest: { status: 'in-progress' },
+ candidates: [],
+ walkInvalidated: true,
+ })),
+}));
+
vi.mock('../services/sprites/walk.js', () => ({
getWalkState: vi.fn(async () => ({ runs: [], selection: null, walkSet: null })),
startWalkGeneration: vi.fn(async () => ({ jobId: 'v1', runId: 'walk-east-0a1b2c3d', direction: 'east', duration: 6 })),
@@ -73,6 +81,7 @@ vi.mock('../services/sprites/assets.js', () => ({
import * as records from '../services/sprites/records.js';
import * as importer from '../services/sprites/importer.js';
import * as reference from '../services/sprites/reference.js';
+import * as referenceRevision from '../services/sprites/referenceRevision.js';
import * as assetPrompt from '../services/sprites/assetPrompt.js';
import * as walk from '../services/sprites/walk.js';
import * as walkTrims from '../services/sprites/walkTrims.js';
@@ -344,6 +353,17 @@ describe('sprites routes', () => {
expect(r.status).toBe(400);
});
+ it('POST /:id/reference/unlock accepts only turnaround-derived directions', async () => {
+ const unlocked = await request(app).post('/api/sprites/pioneer/reference/unlock').send({ direction: 'east' });
+ expect(unlocked.status).toBe(200);
+ expect(unlocked.body.walkInvalidated).toBe(true);
+ expect(referenceRevision.unlockDirectionalAnchor).toHaveBeenCalledWith('pioneer', { direction: 'east' });
+
+ const south = await request(app).post('/api/sprites/pioneer/reference/unlock').send({ direction: 'south' });
+ expect(south.status).toBe(400);
+ expect(referenceRevision.unlockDirectionalAnchor).toHaveBeenCalledTimes(1);
+ });
+
it('PATCH /:id accepts the three standard chroma keys and null, delegating to the lock-aware patch', async () => {
for (const chromaKey of ['#FF00FF', '#00FF00', '#0000FF', null]) {
const r = await request(app).patch('/api/sprites/pioneer').send({ chromaKey });
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index 7cfbc76814..8390511cf6 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -14,9 +14,10 @@
* renders into reference/candidates/); locking is deterministic sharp work
* (normalize.js) plus the dynamic chroma-key selection (chromaKey.js).
*
- * Immutability contract: a locked artifact is never regenerated or
- * overwritten — locked targets 409 on generate/lock, and versioned filenames
- * (`-vN`) always land on the first free version.
+ * Evidence contract: a locked artifact is never regenerated or overwritten.
+ * The turnaround and main remain frozen identity roots; a turnaround-derived
+ * directional anchor may be deliberately reopened, but its old versioned PNG
+ * stays on disk and the replacement lands at the next `-vN` filename.
*/
import { join } from 'path';
@@ -140,7 +141,7 @@ function seedManifest(recordId) {
status: 'needs-turnaround',
characterFamily: recordId,
projection: 'flat',
- rule: 'Every reference descends from the frozen turnaround sheet: the main reference is its front view, and every directional anchor is redrawn from the panel that shows that side. Locked artifacts are immutable evidence. Walk cycles are conditioned only on a locked directional anchor plus the deterministic pose scaffold, never on prior walk output, and the identity anchor is never regenerated.',
+ rule: 'Every reference descends from the frozen turnaround sheet: the main reference is its front view, and every directional anchor is redrawn from the panel that shows that side. The turnaround and main are immutable identity evidence. A directional anchor can be reopened for correction without overwriting its prior version. Walk cycles are conditioned only on the current locked directional anchor plus the deterministic pose scaffold, never on prior walk output, and the identity root is never regenerated.',
chromaKey: null,
turnaround: {
path: null, role: 'identity-root', background: 'chroma-key', locked: false, views: TURNAROUND_VIEWS,
@@ -167,8 +168,8 @@ export async function requireCharacter(recordId) {
}
// First free `-vN` filename — locked artifacts are never overwritten; a
-// correction after a crash (or a future unlock flow) lands on the next
-// version instead of replacing evidence.
+// correction after a crash or an anchor unlock lands on the next version
+// instead of replacing evidence.
async function nextVersionPath(dir, base) {
for (let n = 1; ; n++) {
const rel = `${base}-v${n}.png`;
@@ -676,6 +677,63 @@ export function lockReference(recordId, args) {
return manifestWriteTail(recordId, () => lockReferenceImpl(recordId, args));
}
+/**
+ * Re-open one turnaround-derived directional anchor for correction.
+ *
+ * The old locked PNG remains immutable evidence on disk. Clearing only the
+ * manifest's active pointer makes generation available again, and
+ * `nextVersionPath` guarantees the next lock cannot overwrite that evidence.
+ * South is intentionally excluded because its anchor is the frozen main.
+ */
+export function unlockReferenceAnchor(recordId, args) {
+ return manifestWriteTail(recordId, () => unlockReferenceAnchorImpl(recordId, args));
+}
+
+async function loadUnlockableReferenceAnchor(recordId, direction) {
+ await requireCharacter(recordId);
+ if (!ANCHOR_DIRECTIONS.includes(direction)) {
+ throw new ServerError(`Direction ${direction} is not a revisable anchor`, { status: 400, code: 'INVALID_TARGET' });
+ }
+ const manifest = await loadManifest(recordId);
+ if (!manifest?.turnaround?.locked) {
+ throw new ServerError('Lock the turnaround sheet before revising its directional anchors', { status: 409, code: 'TURNAROUND_NOT_LOCKED' });
+ }
+ const anchor = findAnchor(manifest, anchorIdForDirection(direction));
+ if (anchor?.status !== 'locked') {
+ throw new ServerError(`Direction ${direction} is not locked`, { status: 409, code: 'ANCHOR_NOT_LOCKED' });
+ }
+ return { manifest, anchor };
+}
+
+// Read-only preflight for the cross-service revision coordinator. It prevents
+// dropping a walk approval before discovering that the reference cannot be
+// reopened; unlockReferenceAnchor repeats the check inside its write tail.
+export async function assertReferenceAnchorUnlockable(recordId, { direction }) {
+ await loadUnlockableReferenceAnchor(recordId, direction);
+}
+
+async function unlockReferenceAnchorImpl(recordId, { direction }) {
+ const { manifest, anchor } = await loadUnlockableReferenceAnchor(recordId, direction);
+ Object.assign(anchor, {
+ status: 'pending',
+ source: 'derive-from-turnaround',
+ });
+ delete anchor.path;
+ delete anchor.lockedFrom;
+ delete anchor.lockedAt;
+ delete anchor.sha256;
+ delete anchor.clipWarning;
+ manifest.status = 'in-progress';
+
+ // Record first, then manifest, matching the lock path's crash-recovery
+ // ordering: a stale status is cosmetic, while a manifest is the artifact
+ // authority. The orchestration layer may also invalidate a stale walk.
+ await updateRecord(recordId, { status: 'reference' });
+ await saveManifest(recordId, manifest);
+ console.log(`🔓 sprite reference anchor ${recordId}/${direction} unlocked`);
+ return getReferenceSet(recordId);
+}
+
async function lockReferenceImpl(recordId, { target, candidate, acceptClipRisk = false }) {
const record = await requireCharacter(recordId);
// Seed on demand — a candidate may predate the manifest (e.g. files placed
diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.js
index 40c0b45b8c..d4dae5ea81 100644
--- a/server/services/sprites/reference.test.js
+++ b/server/services/sprites/reference.test.js
@@ -53,7 +53,7 @@ vi.mock('../settings.js', () => ({ getSettings: async () => settings }));
const records = await import('./records.js');
const {
getReferenceSet, startReferenceGeneration, attachReferenceCandidate, lockReference, patchSpriteRecord,
- listReferenceSources, listSpriteThumbnails, forkSprite,
+ unlockReferenceAnchor, listReferenceSources, listSpriteThumbnails, forkSprite,
} = await import('./reference.js');
let seq = 0;
@@ -758,6 +758,48 @@ describe('lockReference', () => {
expect(await readFile(join(refDir, `${id}-walk-south-v1.png`), 'utf8')).toBe('stale-bytes');
});
+ it('reopens one anchor, preserves v1, derives from the turnaround, and locks the replacement as v2', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await lockMain(id);
+ const firstCandidate = await placeCandidate(id, 'east', 'walk-east-candidate-01.png');
+ const firstLock = await lockReference(id, { target: 'east', candidate: firstCandidate });
+ const firstAnchor = firstLock.manifest.anchors.find((a) => a.direction === 'east');
+ const firstBytes = await readFile(join(TEST_ROOT, 'sprites', id, firstAnchor.path));
+
+ const reopened = await unlockReferenceAnchor(id, { direction: 'east' });
+ const pending = reopened.manifest.anchors.find((a) => a.direction === 'east');
+ expect(pending).toMatchObject({ status: 'pending', source: 'derive-from-turnaround' });
+ // loadManifest normalizes every anchor with a `path` key, so the cleared
+ // manifest pointer reads back as undefined rather than an absent property.
+ expect(pending.path).toBeUndefined();
+ expect(pending).not.toHaveProperty('sha256');
+ expect(reopened.manifest.status).toBe('in-progress');
+ expect(await readFile(join(TEST_ROOT, 'sprites', id, firstAnchor.path))).toEqual(firstBytes);
+ expect((await records.getRecord(id)).status).toBe('reference');
+
+ await startReferenceGeneration(id, { target: 'east' });
+ expect(enqueueJob.mock.calls[0][0].params.initImagePath).toBe(
+ join(TEST_ROOT, 'sprites', id, reopened.manifest.turnaround.path),
+ );
+
+ const secondCandidate = await placeCandidate(id, 'east', 'walk-east-candidate-02.png');
+ const secondLock = await lockReference(id, { target: 'east', candidate: secondCandidate });
+ expect(secondLock.manifest.anchors.find((a) => a.direction === 'east').path)
+ .toBe(`reference/${id}-walk-east-v2.png`);
+ expect(await readFile(join(TEST_ROOT, 'sprites', id, firstAnchor.path))).toEqual(firstBytes);
+ });
+
+ it('refuses to reopen south or an anchor that is already pending', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await lockMain(id);
+ await expect(unlockReferenceAnchor(id, { direction: 'south' }))
+ .rejects.toMatchObject({ status: 400, code: 'INVALID_TARGET' });
+ await expect(unlockReferenceAnchor(id, { direction: 'east' }))
+ .rejects.toMatchObject({ status: 409, code: 'ANCHOR_NOT_LOCKED' });
+ });
+
it('completes the set when the last anchor locks', async () => {
const id = newId();
await createCharacter(id);
diff --git a/server/services/sprites/referenceRevision.js b/server/services/sprites/referenceRevision.js
new file mode 100644
index 0000000000..a171abf19f
--- /dev/null
+++ b/server/services/sprites/referenceRevision.js
@@ -0,0 +1,21 @@
+/**
+ * Coordinate a directional-reference revision with its dependent walk.
+ *
+ * Reference state owns whether the anchor can be reopened; walk state owns the
+ * approval that may have been conditioned on the old image. Keeping the
+ * cross-service sequence here leaves the HTTP route declarative.
+ */
+
+import { assertReferenceAnchorUnlockable, unlockReferenceAnchor } from './reference.js';
+import { invalidateWalkDirectionForAnchorRevision } from './walk.js';
+
+export async function unlockDirectionalAnchor(recordId, { direction }) {
+ // Preflight before touching the dependent selection, then remove the stale
+ // approval before clearing the anchor pointer. If the second write ever
+ // fails, the safe partial state has no approved walk claiming a stale source;
+ // rendered runs and the old locked anchor file both remain recoverable.
+ await assertReferenceAnchorUnlockable(recordId, { direction });
+ const walkInvalidated = await invalidateWalkDirectionForAnchorRevision(recordId, { direction });
+ const reference = await unlockReferenceAnchor(recordId, { direction });
+ return { ...reference, walkInvalidated };
+}
diff --git a/server/services/sprites/referenceRevision.test.js b/server/services/sprites/referenceRevision.test.js
new file mode 100644
index 0000000000..5afadb2138
--- /dev/null
+++ b/server/services/sprites/referenceRevision.test.js
@@ -0,0 +1,34 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const unlockReferenceAnchor = vi.fn(async () => ({
+ manifest: { status: 'in-progress' },
+ candidates: [{ path: 'reference/candidates/example.png' }],
+}));
+const assertReferenceAnchorUnlockable = vi.fn(async () => {});
+const invalidateWalkDirectionForAnchorRevision = vi.fn(async () => true);
+
+vi.mock('./reference.js', () => ({ assertReferenceAnchorUnlockable, unlockReferenceAnchor }));
+vi.mock('./walk.js', () => ({ invalidateWalkDirectionForAnchorRevision }));
+
+const { unlockDirectionalAnchor } = await import('./referenceRevision.js');
+
+describe('unlockDirectionalAnchor', () => {
+ it('preflights the anchor, invalidates the dependent walk, then unlocks the reference', async () => {
+ const result = await unlockDirectionalAnchor('example-pioneer', { direction: 'east' });
+
+ expect(assertReferenceAnchorUnlockable).toHaveBeenCalledWith('example-pioneer', { direction: 'east' });
+ expect(unlockReferenceAnchor).toHaveBeenCalledWith('example-pioneer', { direction: 'east' });
+ expect(invalidateWalkDirectionForAnchorRevision).toHaveBeenCalledWith(
+ 'example-pioneer',
+ { direction: 'east' },
+ );
+ expect(assertReferenceAnchorUnlockable.mock.invocationCallOrder[0])
+ .toBeLessThan(invalidateWalkDirectionForAnchorRevision.mock.invocationCallOrder[0]);
+ expect(invalidateWalkDirectionForAnchorRevision.mock.invocationCallOrder[0])
+ .toBeLessThan(unlockReferenceAnchor.mock.invocationCallOrder[0]);
+ expect(result).toMatchObject({
+ manifest: { status: 'in-progress' },
+ walkInvalidated: true,
+ });
+ });
+});
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 2af71fd9db..26e8e6e25e 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -13,8 +13,9 @@
* walk/<id>-walk-selection-v1.json, walk/<id>-walk-set-v1.json
* walk/trims/<slug>-vNNN-{strip.png,.gif,.json}
*
- * Immutability: a finalized walk set 409s generation/approval/postprocess —
- * revisions require a new character version, matching the reference contract.
+ * A finalized walk set 409s generation/approval/postprocess until deliberately
+ * reopened. Revising a directional anchor also removes the approval for the
+ * walk conditioned on that stale anchor while preserving its rendered run.
*/
import { join } from 'path';
@@ -1479,9 +1480,9 @@ async function assertDirectionReDerivable(recordId, walkSet, entry, direction) {
// crash mid-unfinalize can only leave a cosmetic stale status, never a
// walk-complete record with no frozen set behind it. Shared by unlock (re-opens
// all directions) and reopen (re-opens one).
-async function dropFinalizedWalkSet(recordId) {
+async function dropFinalizedWalkSet(recordId, recordStatus = 'reference-complete') {
await rm(join(spriteDir(recordId), walkSetRelPath(recordId)), { force: true });
- await updateRecord(recordId, { status: 'reference-complete' });
+ await updateRecord(recordId, { status: recordStatus });
}
async function unlockWalkSetImpl(recordId) {
@@ -1527,6 +1528,53 @@ export function reopenWalkDirection(recordId, { direction }) {
return walkWriteTail(recordId, () => reopenWalkDirectionImpl(recordId, direction));
}
+/**
+ * Drop the approval for a walk whose conditioning anchor is being revised.
+ *
+ * This differs from the user's "reopen walk" action: a stale walk must be
+ * discarded even when an imported run has no source clip, because the next
+ * valid action is a fresh generation from the replacement anchor. The old run
+ * stays on disk; only its approval pointer is removed.
+ */
+export function invalidateWalkDirectionForAnchorRevision(recordId, { direction }) {
+ return walkWriteTail(recordId, () => invalidateWalkDirectionForAnchorRevisionImpl(recordId, direction));
+}
+
+async function invalidateWalkDirectionForAnchorRevisionImpl(recordId, direction) {
+ await requireCharacter(recordId);
+ const [walkSet, loaded] = await Promise.all([loadWalkSet(recordId), loadSelection(recordId)]);
+ const approved = loaded?.directions?.[direction] || walkSet?.directions?.[direction];
+ if (approved?.status !== 'approved') return false;
+
+ const selection = loaded || {
+ ...seedSelection(recordId),
+ directions: { ...(walkSet?.directions || {}) },
+ };
+ if (walkSet) await dropFinalizedWalkSet(recordId, 'reference');
+ delete selection.directions[direction];
+ selection.status = 'in-progress';
+ await ensureDir(join(spriteDir(recordId), 'walk'));
+ await atomicWrite(join(spriteDir(recordId), selectionRelPath(recordId)), selection);
+ // Preserve the run as reviewable history, but remove its candidate status so
+ // the UI and approval endpoint cannot promote an animation conditioned on
+ // the superseded anchor. Redraw-manifest imports have no mutable run record;
+ // once their selection pointer is gone they are no longer addressable here.
+ const runDirRel = runDirOfPath(entryLayoutPath(recordId, approved));
+ if (runDirRel) {
+ const found = await resolveRunAt(recordId, runDirRel);
+ if (found?.run?.direction === direction) {
+ await saveRunRecordAt(recordId, {
+ ...found.run,
+ status: 'superseded-anchor',
+ supersededAt: new Date().toISOString(),
+ supersededReason: 'directional-anchor-revised',
+ }, found.runDirRel);
+ }
+ }
+ console.log(`♻️ sprite walk direction ${recordId}/${direction} invalidated after anchor revision`);
+ return true;
+}
+
async function reopenWalkDirectionImpl(recordId, direction) {
await requireCharacter(recordId);
const [walkSet, loaded] = await Promise.all([loadWalkSet(recordId), loadSelection(recordId)]);
@@ -1563,6 +1611,23 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {
if (run.status !== 'candidate' || !run.postprocessManifest) {
throw new ServerError('Run has no packaged candidate to approve', { status: 409, code: 'RUN_NOT_CANDIDATE' });
}
+ // A candidate is valid only for the exact locked anchor that conditioned its
+ // render. Native runs carry the anchor hash; imported legacy runs may not, so
+ // retain their existing compatibility path while still requiring a current
+ // locked anchor. This backstops the revision flow even if an old candidate
+ // remains addressable outside the normal UI.
+ const referenceManifest = await loadManifest(recordId);
+ const currentAnchor = referenceManifest?.anchors?.find((anchor) => anchor.direction === direction);
+ if (currentAnchor?.status !== 'locked' || !currentAnchor.path) {
+ throw new ServerError(`Lock the ${anchorIdForDirection(direction)} anchor before approving its walk`, { status: 409, code: 'ANCHOR_NOT_LOCKED' });
+ }
+ if (run.anchorSha256) {
+ const currentAnchorSha256 = currentAnchor.sha256
+ || await sha256File(resolveSpriteAssetPath(recordId, currentAnchor.path));
+ if (run.anchorSha256 !== currentAnchorSha256) {
+ throw new ServerError('This walk was rendered from an older directional anchor — generate a new walk from the current anchor', { status: 409, code: 'RUN_ANCHOR_STALE' });
+ }
+ }
// Tamper check: the packaged manifest and strip must still be on disk with
// self-consistent geometry before their approval is frozen into the selection.
// Frame count / fps are no longer pinned to a single value (variable-frame
diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.js
index 981dce9612..298d7f8c59 100644
--- a/server/services/sprites/walk.test.js
+++ b/server/services/sprites/walk.test.js
@@ -111,7 +111,7 @@ const { listSpriteAssets } = await import('./paths.js');
const { lockReference } = await import('./reference.js');
const {
getWalkState, startWalkGeneration, attachTuiWalkResult, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
- reopenWalkDirection, setWalkTarget, importedWalkDirections, getWalkSourceFrames,
+ reopenWalkDirection, invalidateWalkDirectionForAnchorRevision, setWalkTarget, importedWalkDirections, getWalkSourceFrames,
} = await import('./walk.js');
const { SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS } = await import('./prompts.js');
@@ -131,6 +131,7 @@ async function characterWithLockedAnchors(id, directions = ['east']) {
// byte-for-byte against pinned hashes. Readers must re-anchor at read time.
async function makeCandidateRun(recordId, direction, {
stripBytes = `strip-${direction}`, anchored = false, frameCount = 8, fps = 12,
+ anchorSha256,
} = {}) {
const runId = `walk-${direction}-${(seq++).toString(16).padStart(8, '0')}`;
const runDir = join(TEST_ROOT, 'sprites', recordId, 'runs', runId, 'generated');
@@ -159,6 +160,7 @@ async function makeCandidateRun(recordId, direction, {
characterId: recordId,
direction,
chromaKey: '#FF00FF',
+ ...(anchorSha256 ? { anchorSha256 } : {}),
createdAt: new Date().toISOString(),
postprocessManifest: anchor(manifestRel),
// The run's i2v clip — imported alongside the run since #2984, and
@@ -718,6 +720,13 @@ describe('approveWalkDirection', () => {
.rejects.toMatchObject({ code: 'RUN_STRIP_INVALID' });
});
+ it('rejects a candidate rendered from a superseded anchor hash', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ const { runId } = await makeCandidateRun(id, 'east', { anchorSha256: '0'.repeat(64) });
+ await expect(approveWalkDirection(id, { direction: 'east', runId }))
+ .rejects.toMatchObject({ code: 'RUN_ANCHOR_STALE' });
+ });
+
it('records the approval in the selection', async () => {
const id = await characterWithLockedAnchors(newId(), ['east']);
const { runId, manifestRel } = await makeCandidateRun(id, 'east');
@@ -889,6 +898,38 @@ describe('reopenWalkDirection', () => {
});
});
+describe('invalidateWalkDirectionForAnchorRevision', () => {
+ it('un-finalizes the set, drops only the stale approval, and preserves every rendered run', async () => {
+ const id = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);
+ const runIds = {};
+ for (const direction of SPRITE_DIRECTIONS) {
+ const { runId } = await makeCandidateRun(id, direction);
+ runIds[direction] = runId;
+ await approveWalkDirection(id, { direction, runId });
+ }
+
+ const invalidated = await invalidateWalkDirectionForAnchorRevision(id, { direction: 'east' });
+ const state = await getWalkState(id);
+ expect(invalidated).toBe(true);
+ expect(state.walkSet).toBeNull();
+ expect(state.selection.status).toBe('in-progress');
+ expect(state.selection.directions.east).toBeUndefined();
+ expect(state.selection.directions.north.status).toBe('approved');
+ expect(state.runs.find((run) => run.id === runIds.east)).toMatchObject({
+ status: 'superseded-anchor',
+ supersededReason: 'directional-anchor-revised',
+ });
+ await expect(approveWalkDirection(id, { direction: 'east', runId: runIds.east }))
+ .rejects.toMatchObject({ code: 'RUN_NOT_CANDIDATE' });
+ expect((await records.getRecord(id)).status).toBe('reference');
+ });
+
+ it('is a no-op when the direction has no approved walk', async () => {
+ const id = await characterWithLockedAnchors(newId(), ['east']);
+ await expect(invalidateWalkDirectionForAnchorRevision(id, { direction: 'east' })).resolves.toBe(false);
+ });
+});
+
/**
* #2993 — the un-finalize gate keys on EVIDENCE (is a clip on disk?), not on the
* set's imported-looking provenance. #2984 made the importer copy each run's