Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: correction notes on every sprite regeneration surface, not just turnaround and anchors (#3134)
[._.]/ Adam Eivycecdf3f3f95b
diff --git a/client/src/components/sprites/AmbientWorkflow.jsx b/client/src/components/sprites/AmbientWorkflow.jsxindex abe19ec687..8da84e2ae9 100644--- a/client/src/components/sprites/AmbientWorkflow.jsx+++ b/client/src/components/sprites/AmbientWorkflow.jsx@@ -3,6 +3,9 @@ import { Check, Film, Lock, RefreshCw, Wind } from 'lucide-react';import toast from '../ui/Toast';import { approveSpriteAmbient, 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 { checkerboardStyle, spriteAssetUrl } from './spriteAssets.js';// Places and objects have one identity root and one atlas row. Keeping this as@@ -10,6 +13,7 @@ import { checkerboardStyle, spriteAssetUrl } from './spriteAssets.js';// affordances from leaking into a track that has neither concept.export default function AmbientWorkflow({record, reference, ambient, renders, hasBackend, mode, onGenerateReference, onGenerateAmbient, onChanged,+ corrections = null, onCorrectionChange = null,}) {const [designPrompt, setDesignPrompt] = useState('');const main = reference?.manifest?.mainReference || null;@@ -62,6 +66,19 @@ export default function AmbientWorkflow({<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"+ />+ )}<buttontype="button"disabled={!hasBackend || !designPrompt.trim() || referenceBusy}@@ -78,9 +95,20 @@ export default function AmbientWorkflow({{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="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>}+ {!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>diff --git a/client/src/components/sprites/AmbientWorkflow.test.jsx b/client/src/components/sprites/AmbientWorkflow.test.jsxnew file mode 100644index 0000000000..4dde82dc0e--- /dev/null+++ b/client/src/components/sprites/AmbientWorkflow.test.jsx@@ -0,0 +1,99 @@+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.++vi.mock('../../services/apiSprites.js', () => ({+ approveSpriteAmbient: vi.fn(() => Promise.resolve({})),+ lockSpriteReference: vi.fn(() => Promise.resolve({})),+}));++import AmbientWorkflow from './AmbientWorkflow.jsx';++const record = { id: 'example-grove', kind: 'place', name: 'Example Grove' };+const CANDIDATE = { target: 'main', path: 'reference/candidates/main-candidate-01.png' };++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.+const lockedReference = { manifest: { mainReference: { locked: true, path: 'reference/example-grove-main-v1.png' } }, candidates: [] };++describe('AmbientWorkflow correction notes (#3134)', () => {+ it('offers a reference correction once there is a candidate to correct', () => {+ const onCorrectionChange = vi.fn();+ renderAmbient({ corrections: {}, onCorrectionChange });+ fireEvent.click(screen.getByRole('button', { name: /Show correction note for ambient reference/i }));+ fireEvent.change(screen.getByLabelText(/Correction guidance for the ambient reference/i), {+ target: { value: 'the trunk leans too far right' },+ });+ const merged = onCorrectionChange.mock.calls[0][0]({});+ expect(merged).toHaveProperty('ambient-reference');+ // The design prompt is a SEPARATE control — the correction is additive, so it+ // must not be written into the design field's state.+ expect(merged).not.toHaveProperty('designPrompt');+ });++ it('does not offer a reference correction before the first render exists', () => {+ renderAmbient({+ reference: { manifest: { mainReference: { locked: false } }, candidates: [] },+ corrections: {},+ onCorrectionChange: vi.fn(),+ });+ 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 });+ 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(),+ });+ expect(screen.queryByRole('button', { name: /correction note/i })).toBeNull();+ });+});diff --git a/client/src/components/sprites/AssetCollection.jsx b/client/src/components/sprites/AssetCollection.jsxindex 1d65138904..bdca77a76e 100644--- a/client/src/components/sprites/AssetCollection.jsx+++ b/client/src/components/sprites/AssetCollection.jsx@@ -16,9 +16,9 @@*/import { useMemo, useState } from 'react';-import { FolderOpen, RefreshCw, Scissors, Sparkles, Film, FileJson, NotebookPen } from 'lucide-react';+import { FolderOpen, RefreshCw, Scissors, Sparkles, Film, FileJson } from 'lucide-react';import AssetInspector from './AssetInspector.jsx';-import CorrectionNote from './CorrectionNote.jsx';+import CorrectionNote, { CorrectionToggleButton } from './CorrectionNote.jsx';import SpritePreview from './SpritePreview.jsx';import { hasSpritePreview, isVideoAsset, assetVersionToken, spriteAssetUrl } from './spriteAssets.js';import { groupSpriteAssetsByRole } from '../../lib/spriteFacets.js';@@ -53,14 +53,16 @@ function AssetCard({ recordId, asset, actions, corrections, onCorrectionChange,// links to its own build metadata — geometry, chroma key, provenance.const manifest = asset.manifest;- // Inline anchor-correction note (#2964): an anchor re-roll can carry the same- // per-direction correction the ReferenceWorkflow grid drives, so a note typed- // on either surface is visible on both and rides the re-roll. Only reference- // regenerates expose a `direction`; walk regenerates and non-character records- // (no `onCorrectionChange`) never show the affordance.- const correctionDir = regenerate?.kind === 'reference' ? regenerate.direction : null;- const canCorrect = Boolean(correctionDir && onCorrectionChange);- const correctionValue = canCorrect ? (corrections?.[correctionDir] || '') : '';+ // Inline correction note (#2964, extended to walk cards by #3134): a re-roll+ // can carry the same correction the authoritative workflow surface drives, so+ // a note typed on either surface is visible on both and rides the re-roll.+ // Every actionable regenerate names its own key in the page-owned map —+ // `correctionKey` — so an anchor (still-image) note can never leak into a walk+ // (video) re-roll. Non-character records (no `onCorrectionChange`) and assets+ // with no regenerate action never show the affordance.+ const correctionKey = regenerate?.correctionKey || null;+ const canCorrect = Boolean(correctionKey && onCorrectionChange);+ const correctionValue = canCorrect ? (corrections?.[correctionKey] || '') : '';const [noteOpen, setNoteOpen] = useState(Boolean(correctionValue));return (@@ -109,16 +111,12 @@ function AssetCard({ recordId, asset, actions, corrections, onCorrectionChange,</button>)}{canCorrect && (- <button- type="button"- onClick={() => setNoteOpen((o) => !o)}- aria-expanded={noteOpen}- aria-label={`${noteOpen ? 'Hide' : 'Show'} correction note for ${name}`}- title={correctionValue ? `Correction: ${correctionValue}` : 'Add a correction for this anchor re-roll'}- className={`px-1.5 py-0.5 text-[10px] bg-port-card border rounded hover:border-port-accent ${correctionValue ? 'border-port-accent text-port-accent' : 'border-port-border text-gray-300'}`}- >- <NotebookPen className="w-3 h-3" />- </button>+ <CorrectionToggleButton+ open={noteOpen}+ onToggle={() => setNoteOpen((o) => !o)}+ hasValue={Boolean(correctionValue.trim())}+ label={name}+ />)}{trim && (<button@@ -146,9 +144,11 @@ function AssetCard({ recordId, asset, actions, corrections, onCorrectionChange,)}{canCorrect && noteOpen && (<CorrectionNote- direction={correctionDir}+ noteKey={correctionKey}value={correctionValue}onChange={onCorrectionChange}+ ariaLabel={`Correction guidance for the ${regenerate.correctionLabel || correctionKey}`}+ placeholder={regenerate.correctionPlaceholder}className="text-[10px]"/>)}diff --git a/client/src/components/sprites/AssetCollection.test.jsx b/client/src/components/sprites/AssetCollection.test.jsxindex c4c15e7929..732eb48726 100644--- a/client/src/components/sprites/AssetCollection.test.jsx+++ b/client/src/components/sprites/AssetCollection.test.jsx@@ -231,3 +231,60 @@ describe('AssetCollection anchor correction note (#2964)', () => {expect(within(card).getByRole('button', { name: /Show correction note/i })).toBeTruthy();});});++// #3134 extended the card note to walk outputs. It is the WALK-namespaced key,+// which is the whole point: the same note WalkWorkflow's card drives, and NOT the+// bare-direction anchor note (a still-image fix must not ride a video re-roll).+describe('AssetCollection walk correction note (#3134)', () => {+ const stripCard = () => screen.getByTitle(STRIP).parentElement;++ it('surfaces a note on a walk output card bound to the walk-namespaced key', async () => {+ const onCorrectionChange = vi.fn();+ render(+ <AssetCollection+ recordId="example-walker"+ assets={ASSETS}+ actions={actionsFor()}+ corrections={{ 'walk:east': 'the legs barely lift' }}+ onCorrectionChange={onCorrectionChange}+ />,+ );+ const card = stripCard();+ // An existing note auto-opens and prefills from the shared map.+ const textarea = within(card).getByLabelText(/Correction guidance for the east walk cycle/i);+ expect(textarea).toHaveValue('the legs barely lift');+ await userEvent.type(textarea, '!');+ const merged = onCorrectionChange.mock.calls[0][0]({ east: 'anchor note' });+ expect(merged.east).toBe('anchor note');+ expect(merged).toHaveProperty('walk:east');+ });++ it('does not show an anchor note on a walk card', () => {+ render(+ <AssetCollection+ recordId="example-walker"+ assets={ASSETS}+ actions={actionsFor()}+ corrections={{ east: 'no pocket on the right sleeve' }}+ onCorrectionChange={vi.fn()}+ />,+ );+ // The anchor note exists in the map but belongs to a different surface, so+ // the walk card stays collapsed and shows none of its text.+ expect(within(stripCard()).queryByLabelText(/Correction guidance/i)).toBeNull();+ });++ it('leaves a non-actionable asset without a note affordance', () => {+ render(+ <AssetCollection+ recordId="example-walker"+ assets={ASSETS}+ actions={actionsFor()}+ corrections={{}}+ onCorrectionChange={vi.fn()}+ />,+ );+ // Exactly one actionable card in ASSETS → exactly one note toggle.+ expect(screen.getAllByRole('button', { name: /correction note/i })).toHaveLength(1);+ });+});diff --git a/client/src/components/sprites/CorrectionNote.jsx b/client/src/components/sprites/CorrectionNote.jsxindex 1a2ab70f73..7e14997c53 100644--- a/client/src/components/sprites/CorrectionNote.jsx+++ b/client/src/components/sprites/CorrectionNote.jsx@@ -1,40 +1,104 @@/**- * Shared per-direction anchor correction note (#2964).+ * Shared sprite correction note (#2964, extended to every regeneration surface+ * by #3134).*- * The ReferenceWorkflow anchor grid and the asset-collection card render the- * SAME control writing the SAME page-owned `corrections` map (lifted to- * `Sprites.jsx`), so the placeholder, aria-label, and updater shape live in one- * place and can't drift between the two surfaces. `className` lets each host- * keep its own chrome (full grid tile vs. compact toggle-revealed card).+ * Every surface that can re-roll a render — the turnaround sheet, the main+ * reference, the 7 directional anchors, the walk/scanner clips, and the ambient+ * reference + loop — renders the SAME control writing the SAME page-owned+ * `corrections` map (lifted to `Sprites.jsx`), so the placeholder, aria-label,+ * and updater shape live in one place and can't drift between surfaces.+ * `className` lets each host keep its own chrome (full grid tile vs. compact+ * toggle-revealed card).** `onChange` receives a setState-style updater so it composes with the- * page-owned `setCorrections` while preserving sibling directions' notes.- */-/**- * Build the anchor re-roll request fragment for a direction's shared correction- * (#2964). Returns `{ correctionPrompt }` only when the note is non-empty after- * trimming, else `{}` — so an absent or whitespace-only note is omitted from the- * request, matching the server's optional `correctionPrompt`. BOTH re-roll- * surfaces spread this (the ReferenceWorkflow anchor grid and the asset card via- * Sprites' `generateAnchor`), so they send byte-identical payloads — the single- * source guarantee at the request layer, not just the input layer.+ * page-owned `setCorrections` while preserving sibling notes.+ *+ * The map's KEY vocabulary and the request fragment live in+ * `client/src/lib/spriteCorrections.js` (pure, so the action-gating layer can+ * share them) and are re-exported here for the surfaces that already import+ * from this module.*/-export function correctionPromptPayload(corrections, direction) {- const note = corrections?.[direction]?.trim();- return note ? { correctionPrompt: note } : {};-}-export default function CorrectionNote({ direction, value, onChange, onValueChange, placeholder, ariaLabel, className = '' }) {+import { useState } from 'react';+import { NotebookPen } from 'lucide-react';++export {+ anchorCorrectionKey, walkCorrectionKey, scannerCorrectionKey,+ MAIN_CORRECTION_KEY, AMBIENT_REFERENCE_CORRECTION_KEY, AMBIENT_LOOP_CORRECTION_KEY,+ correctionPromptPayload,+} from '../../lib/spriteCorrections.js';++export default function CorrectionNote({+ noteKey, direction, value, onChange, onValueChange, placeholder, ariaLabel, className = '',+}) {+ // `direction` is the pre-#3134 spelling of the map key, kept so the anchor+ // grid's existing call sites read naturally.+ const key = noteKey ?? direction;return (<textareavalue={value || ''}onChange={(e) => onValueChange? onValueChange(e.target.value)- : onChange((prev) => ({ ...prev, [direction]: e.target.value }))}+ : onChange((prev) => ({ ...prev, [key]: e.target.value }))}rows={2}- aria-label={ariaLabel || `Correction guidance for the ${direction} pose`}+ aria-label={ariaLabel || `Correction guidance for the ${key} pose`}placeholder={placeholder || 'Correction (optional), e.g. no pocket on the right sleeve'}className={`w-full px-1.5 py-1 bg-port-bg border border-port-border rounded text-gray-300 placeholder-gray-600 resize-y focus:border-port-accent focus:outline-none ${className}`}/>);}++/**+ * The compact pill that reveals a note. Split out so a host whose layout puts+ * the toggle in an action ROW and the note BELOW it (the asset card) shares the+ * exact same button as the hosts that stack the two (`CorrectionNoteToggle`).+ */+export function CorrectionToggleButton({ open, onToggle, hasValue, label, text = null, className = '' }) {+ return (+ <button+ type="button"+ onClick={onToggle}+ aria-expanded={open}+ aria-label={`${open ? 'Hide' : 'Show'} correction note for ${label}`}+ title={hasValue ? 'A correction is set — it will be applied on the next regenerate' : `Add a correction for the ${label} re-roll`}+ className={`flex items-center justify-center gap-1 px-1.5 py-0.5 text-[10px] bg-port-card border rounded hover:border-port-accent ${hasValue ? 'border-port-accent text-port-accent' : 'border-port-border text-gray-300'} ${className}`}+ >+ <NotebookPen className="w-3 h-3" />{text}+ </button>+ );+}++/**+ * Toggle + revealed note, stacked — the affordance the walk / scanner / ambient+ * cards use. Opens by default when a note already exists so a set correction is+ * never invisible. Keeps the note out of the way on the (common) blind-re-roll+ * path, which matters on cards that are already dense on mobile.+ */+export function CorrectionNoteToggle({+ noteKey, label, corrections, onChange, placeholder, toggleText = 'Correction', className = '',+}) {+ const value = corrections?.[noteKey] || '';+ const [open, setOpen] = useState(Boolean(value));+ return (+ <div className={`space-y-1 ${className}`}>+ <CorrectionToggleButton+ open={open}+ onToggle={() => setOpen((o) => !o)}+ hasValue={Boolean(value.trim())}+ label={label}+ text={toggleText}+ className="w-full"+ />+ {open && (+ <CorrectionNote+ noteKey={noteKey}+ value={value}+ onChange={onChange}+ ariaLabel={`Correction guidance for the ${label} re-roll`}+ placeholder={placeholder}+ className="text-[10px]"+ />+ )}+ </div>+ );+}diff --git a/client/src/components/sprites/CorrectionNote.test.jsx b/client/src/components/sprites/CorrectionNote.test.jsxindex d69474424f..5c57edb366 100644--- a/client/src/components/sprites/CorrectionNote.test.jsx+++ b/client/src/components/sprites/CorrectionNote.test.jsx@@ -1,7 +1,12 @@import { describe, it, expect, vi } from 'vitest';+import { useState } from 'react';import { render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import CorrectionNote, { correctionPromptPayload } from './CorrectionNote.jsx';+import CorrectionNote, {+ CorrectionNoteToggle, correctionPromptPayload,+ anchorCorrectionKey, walkCorrectionKey, scannerCorrectionKey,+ MAIN_CORRECTION_KEY, AMBIENT_REFERENCE_CORRECTION_KEY, AMBIENT_LOOP_CORRECTION_KEY,+} from './CorrectionNote.jsx';// The shared anchor-correction module (#2964). `correctionPromptPayload` is the// single source at the REQUEST layer — both re-roll surfaces (the reference@@ -33,6 +38,41 @@ describe('correctionPromptPayload', () => {});});+// The whole point of namespacing (#3134): one page-owned map serves every+// surface, but a still-image anchor note must never ride a walk VIDEO re-roll.+describe('correction keys are namespaced per surface (#3134)', () => {+ it('keeps the bare direction for anchors so pre-#3134 state still resolves', () => {+ expect(anchorCorrectionKey('east')).toBe('east');+ });++ it('gives every other surface a distinct key', () => {+ const keys = [+ anchorCorrectionKey('east'),+ walkCorrectionKey('east'),+ scannerCorrectionKey('east'),+ MAIN_CORRECTION_KEY,+ AMBIENT_REFERENCE_CORRECTION_KEY,+ AMBIENT_LOOP_CORRECTION_KEY,+ ];+ expect(new Set(keys).size).toBe(keys.length);+ });++ it('does not let an anchor note leak into that direction\'s walk or scanner re-roll', () => {+ const corrections = { east: 'no pocket on the right sleeve' };+ expect(correctionPromptPayload(corrections, anchorCorrectionKey('east')))+ .toEqual({ correctionPrompt: 'no pocket on the right sleeve' });+ expect(correctionPromptPayload(corrections, walkCorrectionKey('east'))).toEqual({});+ expect(correctionPromptPayload(corrections, scannerCorrectionKey('east'))).toEqual({});+ });++ it('keeps each direction\'s walk note separate', () => {+ const corrections = { [walkCorrectionKey('east')]: 'the legs barely lift' };+ expect(correctionPromptPayload(corrections, walkCorrectionKey('east')))+ .toEqual({ correctionPrompt: 'the legs barely lift' });+ expect(correctionPromptPayload(corrections, walkCorrectionKey('west'))).toEqual({});+ });+});+describe('CorrectionNote component', () => {it('renders the shared value and writes a per-direction updater on change', async () => {const onChange = vi.fn();@@ -46,4 +86,57 @@ describe('CorrectionNote component', () => {expect(merged.west).toBe('other');expect(merged).toHaveProperty('east');});++ it('writes through an explicit noteKey, so a namespaced surface merges correctly', async () => {+ // Driven through real page-owned state (the production wiring): the updater+ // reads the event lazily, so only a live reducer proves the value lands.+ function Host() {+ const [corrections, setCorrections] = useState({ east: 'anchor note' });+ return (+ <>+ <CorrectionNote+ noteKey={walkCorrectionKey('east')}+ value={corrections[walkCorrectionKey('east')]}+ onChange={setCorrections}+ />+ <output data-testid="state">{JSON.stringify(corrections)}</output>+ </>+ );+ }+ render(<Host />);+ await userEvent.type(screen.getByLabelText(/Correction guidance/i), 'hi');+ // The anchor's still-image note survives; the walk note lands on its own key.+ expect(JSON.parse(screen.getByTestId('state').textContent))+ .toEqual({ east: 'anchor note', 'walk:east': 'hi' });+ });+});++describe('CorrectionNoteToggle', () => {+ it('starts collapsed with no note and reveals the textarea on toggle', async () => {+ const onChange = vi.fn();+ render(+ <CorrectionNoteToggle+ noteKey={walkCorrectionKey('east')}+ label="east walk cycle"+ corrections={{}}+ onChange={onChange}+ />,+ );+ expect(screen.queryByLabelText(/Correction guidance/i)).toBeNull();+ await userEvent.click(screen.getByRole('button', { name: /Show correction note for east walk cycle/i }));+ expect(screen.getByLabelText(/Correction guidance for the east walk cycle re-roll/i)).toBeInTheDocument();+ });++ it('auto-opens with an existing note so a set correction is never invisible', () => {+ render(+ <CorrectionNoteToggle+ noteKey={walkCorrectionKey('east')}+ label="east walk cycle"+ corrections={{ 'walk:east': 'the legs barely lift' }}+ onChange={vi.fn()}+ />,+ );+ expect(screen.getByLabelText(/Correction guidance for the east walk cycle re-roll/i))+ .toHaveValue('the legs barely lift');+ });});diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsxindex 7c28848b29..bef8c76ed8 100644--- a/client/src/components/sprites/ReferenceWorkflow.jsx+++ b/client/src/components/sprites/ReferenceWorkflow.jsx@@ -13,7 +13,9 @@ import SpritePreview from './SpritePreview.jsx';import GalleryImagePicker from '../imageGen/GalleryImagePicker.jsx';import SpriteReferencePicker from './SpriteReferencePicker.jsx';import ForkSpriteModal from './ForkSpriteModal.jsx';-import CorrectionNote, { correctionPromptPayload } from './CorrectionNote.jsx';+import CorrectionNote, {+ CorrectionNoteToggle, correctionPromptPayload, anchorCorrectionKey, MAIN_CORRECTION_KEY,+} from './CorrectionNote.jsx';import FilePickerButton from '../ui/FilePickerButton';import { IMAGE_ACCEPT } from '../../utils/fileUpload';@@ -296,14 +298,18 @@ export default function ReferenceWorkflow({ record, reference, renders, correctitarget,...(mode ? { mode } : {}),// The sheet owns the design inputs; the main derives from it with no- // inputs of its own; anchors carry only their correction note.+ // design inputs of its own; anchors carry only their correction note.+ // The main and every anchor DO carry a correction (#3134/#2964) — under+ // their own key in the shared map, so a main note can't ride an anchor....(target === 'turnaround' ? {designPrompt,...(refSource?.type === 'upload' ? { referenceImageFile: refSource.file } : {}),...(refSource?.type === 'gallery' ? { initImageGalleryFile: refSource.filename } : {}),...(refSource?.type === 'sprite' ? { initImageSpriteId: refSource.id } : {}),...(refSource ? { initImageStrength: strength } : {}),- } : target === 'main' ? {} : correctionPromptPayload(corrections, target)),+ } : target === 'main'+ ? correctionPromptPayload(corrections, MAIN_CORRECTION_KEY)+ : correctionPromptPayload(corrections, anchorCorrectionKey(target))),}, { silent: true });resolveSubmit(target, jobId);if (target === 'turnaround') clearSource();@@ -787,6 +793,16 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti{pendingJobs.main ? 'Rendering…' : mainCandidates.length ? 'Regenerate' : 'Generate candidate'}</button></div>+ {/* The main has no design input of its own (it derives from the+ sheet), but it CAN take a correction (#3134) — otherwise a bad+ front view could only be re-rolled blind. */}+ <CorrectionNoteToggle+ noteKey={MAIN_CORRECTION_KEY}+ label="main reference"+ corrections={corrections}+ onChange={onCorrectionChange}+ placeholder="Correction (optional), e.g. the cloak hem is cut off"+ />{mainCandidates.length > 0 && (<div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,11rem),1fr))] gap-3">{mainCandidates.map((candidate) => (diff --git a/client/src/components/sprites/ReferenceWorkflow.test.jsx b/client/src/components/sprites/ReferenceWorkflow.test.jsxindex ba2654d9bb..f2f4dd9881 100644--- a/client/src/components/sprites/ReferenceWorkflow.test.jsx+++ b/client/src/components/sprites/ReferenceWorkflow.test.jsx@@ -180,3 +180,65 @@ describe('ReferenceWorkflow workspace', () => {}, { silent: true });});});++// The main derives from the locked sheet with no design input of its own, so+// before #3134 it could only be re-rolled blind. It now takes the same additive+// correction the anchors do, under its OWN key in the shared page-owned map.+describe('main-reference correction note (#3134)', () => {+ const renderUnlockedMain = (props = {}) => render(+ <ReferenceWorkflow+ record={{ id: 'example-pioneer', name: 'Example Pioneer', chromaKey: '#FF00FF' }}+ reference={{+ manifest: {+ status: 'in-progress',+ turnaround: { locked: true, path: 'reference/example-pioneer-turnaround-v1.png' },+ mainReference: { locked: false },+ anchors: [],+ },+ candidates: [],+ }}+ renders={renders}+ corrections={{}}+ onCorrectionChange={vi.fn()}+ backends={[{ id: 'codex', label: 'Codex' }]}+ mode="codex"+ onModeChange={vi.fn()}+ onChanged={vi.fn()}+ onForked={vi.fn()}+ {...props}+ />,+ );++ it('sends the main note as correctionPrompt on the main re-roll', async () => {+ const user = userEvent.setup();+ generateSpriteReference.mockClear();+ renderUnlockedMain({ corrections: { main: ' the cloak hem is cut off ' } });+ const main = screen.getByRole('region', { name: 'Main reference' });+ await user.click(within(main).getByRole('button', { name: 'Generate candidate' }));+ expect(generateSpriteReference).toHaveBeenCalledWith('example-pioneer', {+ target: 'main',+ mode: 'codex',+ correctionPrompt: 'the cloak hem is cut off',+ }, { silent: true });+ });++ it('omits correctionPrompt entirely for a blank note (blind regenerate unchanged)', async () => {+ const user = userEvent.setup();+ generateSpriteReference.mockClear();+ renderUnlockedMain({ corrections: { main: ' ' } });+ const main = screen.getByRole('region', { name: 'Main reference' });+ await user.click(within(main).getByRole('button', { name: 'Generate candidate' }));+ expect(generateSpriteReference).toHaveBeenCalledWith(+ 'example-pioneer', { target: 'main', mode: 'codex' }, { silent: true },+ );+ });++ it('does not let an anchor note ride the main re-roll', async () => {+ const user = userEvent.setup();+ generateSpriteReference.mockClear();+ renderUnlockedMain({ corrections: { east: 'no pocket on the right sleeve' } });+ const main = screen.getByRole('region', { name: 'Main reference' });+ await user.click(within(main).getByRole('button', { name: 'Generate candidate' }));+ expect(generateSpriteReference.mock.calls[0][1]).not.toHaveProperty('correctionPrompt');+ });+});diff --git a/client/src/components/sprites/ScannerWorkflow.jsx b/client/src/components/sprites/ScannerWorkflow.jsxindex a883c3e056..f0b59c3767 100644--- a/client/src/components/sprites/ScannerWorkflow.jsx+++ b/client/src/components/sprites/ScannerWorkflow.jsx@@ -4,13 +4,16 @@ import toast from '../ui/Toast';import { approveSpriteScanner } from '../../services/apiSprites.js';import { useAsyncAction } from '../../hooks/useAsyncAction.js';import { SPRITE_DIRECTIONS } from '../../lib/spriteFacets.js';+import { CorrectionNoteToggle, scannerCorrectionKey } 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 }) {+export default function ScannerWorkflow({+ record, reference, scanner, onGenerate, onChanged, corrections = null, onCorrectionChange = null,+}) {const runs = scanner?.runs || [];const selection = scanner?.selection || null;const finalized = Boolean(scanner?.scannerSet);@@ -74,26 +77,39 @@ export default function ScannerWorkflow({ record, reference, scanner, onGenerate</div>)}{!finalized && !approved && (- <div className="flex gap-1.5">- <button- type="button"- disabled={busy}- onClick={() => onGenerate(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'}- </button>- {candidate && (+ <div className="space-y-1.5">+ {/* Optional correction the next render carries (#3134) — same+ shared page-owned map every other re-roll surface writes. */}+ {onCorrectionChange && (+ <CorrectionNoteToggle+ noteKey={scannerCorrectionKey(direction)}+ label={`${direction} scanner action`}+ corrections={corrections}+ onChange={onCorrectionChange}+ placeholder="Correction (optional), e.g. the sweep never returns to the start pose"+ />+ )}+ <div className="flex gap-1.5"><buttontype="button"- disabled={approving}- aria-label={`Approve scanner ${direction}`}- onClick={() => approve(direction, run.id)}- className="rounded bg-port-accent px-2 py-1 text-xs text-white disabled:opacity-50"+ disabled={busy}+ onClick={() => onGenerate(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">- <Check className="w-3 h-3" />+ {busy ? <RefreshCw className="mx-auto w-3 h-3 animate-spin" /> : run?.status === 'error' ? 'Retry' : 'Generate'}</button>- )}+ {candidate && (+ <button+ type="button"+ disabled={approving}+ aria-label={`Approve scanner ${direction}`}+ onClick={() => approve(direction, run.id)}+ 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>}diff --git a/client/src/components/sprites/ScannerWorkflow.test.jsx b/client/src/components/sprites/ScannerWorkflow.test.jsxindex cb27b2f0b0..0e42a5b507 100644--- a/client/src/components/sprites/ScannerWorkflow.test.jsx+++ b/client/src/components/sprites/ScannerWorkflow.test.jsx@@ -51,3 +51,45 @@ describe('ScannerWorkflow', () => {));});});++// 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/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxindex 3fdd80cbab..fdc4f11568 100644--- a/client/src/components/sprites/WalkWorkflow.jsx+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -10,6 +10,7 @@ import {import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';import Banner from '../ui/Banner.jsx';import CycleTarget from './CycleTarget.jsx';+import { CorrectionNoteToggle, walkCorrectionKey } from './CorrectionNote.jsx';import SpritePreview from './SpritePreview.jsx';import { useAsyncAction } from '../../hooks/useAsyncAction.js';import { spriteAssetUrl, checkerboardStyle, PIXELATED } from './spriteAssets.js';@@ -207,6 +208,7 @@ function DirectionCard({recordId, direction, anchorLocked, anchorPath, run, approved, finalized, pending,onOpenTrimmer, onGenerate, onApprove, onRetry, onReprocess, onReopen,reprocessing, retrying, cycleLabel, drift, targetSaving, imported,+ corrections, onCorrectionChange,}) {const [confirming, setConfirming] = useState(false);const [reopening, setReopening] = useState(false);@@ -379,6 +381,19 @@ function DirectionCard({{!finalized && !approved && (<div className="space-y-1.5">+ {/* Correction note for the NEXT render (#3134) — the same key the+ asset-collection walk card writes, so a note typed on either+ surface is visible on both and rides whichever Generate fires.+ Hidden when this direction can't be rendered at all. */}+ {anchorLocked && onCorrectionChange && (+ <CorrectionNoteToggle+ noteKey={walkCorrectionKey(direction)}+ label={`${direction} walk cycle`}+ corrections={corrections}+ onChange={onCorrectionChange}+ placeholder="Correction (optional), e.g. the legs barely lift"+ />+ )}<buttononClick={() => onGenerate(direction)}disabled={!anchorLocked || busy}@@ -507,7 +522,7 @@ function DirectionCard({export default function WalkWorkflow({record, reference, walk, renders, duration, onDurationChange, onGenerate,- onOpenTrimmer = () => {}, onChanged,+ onOpenTrimmer = () => {}, onChanged, corrections = null, onCorrectionChange = null,}) {const recordId = record.id;// The cycle target is server-resolved (app contract → set pin → first approved@@ -787,6 +802,8 @@ export default function WalkWorkflow({onReopen={reopen}reprocessing={reprocessingDir === anchor.direction}cycleLabel={cycleLabel}+ corrections={corrections}+ onCorrectionChange={onCorrectionChange}/>))}</div>diff --git a/client/src/components/sprites/WalkWorkflow.test.jsx b/client/src/components/sprites/WalkWorkflow.test.jsxindex 67f74e6e01..eb8170d432 100644--- a/client/src/components/sprites/WalkWorkflow.test.jsx+++ b/client/src/components/sprites/WalkWorkflow.test.jsx@@ -882,3 +882,56 @@ describe('delivered clip length', () => {expect(screen.queryByText(/0\.0s/)).toBeNull();});});++// Correction notes on the walk card (#3134). The card writes the WALK-namespaced+// key in the page-owned map, so a note typed here (or on the asset-collection+// walk card, which uses the same key) rides the next Generate.+describe('walk correction note (#3134)', () => {+ const renderCard = (props = {}) => render(+ <MemoryRouter>+ <WalkWorkflow+ record={{ id: 'example-walker' }}+ reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked', path: 'reference/example-walker-east-v1.png' }] } }}+ walk={{ runs: [], selection: { directions: {} }, walkSet: null }}+ renders={noRenders()}+ duration={6}+ onDurationChange={vi.fn()}+ onGenerate={vi.fn()}+ onChanged={vi.fn()}+ {...props}+ />+ </MemoryRouter>,+ );++ it('writes through to the shared map under the walk-namespaced key', () => {+ const onCorrectionChange = vi.fn();+ renderCard({ corrections: {}, onCorrectionChange });+ fireEvent.click(screen.getByRole('button', { name: /Show correction note for east walk cycle/i }));+ fireEvent.change(screen.getByLabelText(/Correction guidance for the east walk cycle/i), {+ target: { value: 'the legs barely lift' },+ });+ const merged = onCorrectionChange.mock.calls[0][0]({ east: 'anchor note' });+ // The anchor's still-image note survives, and the walk note is written to+ // its OWN key — that separation is the whole point of the namespace.+ expect(merged.east).toBe('anchor note');+ expect(merged).toHaveProperty('walk:east');+ });++ it('prefills an existing walk note and leaves the affordance out with no writer', () => {+ renderCard({ corrections: { 'walk:east': 'the legs barely lift' }, onCorrectionChange: vi.fn() });+ expect(screen.getByLabelText(/Correction guidance for the east walk cycle/i))+ .toHaveValue('the legs barely lift');+ cleanup();+ renderCard();+ expect(screen.queryByRole('button', { name: /correction note/i })).toBeNull();+ });++ it('hides the note for a direction whose anchor is not locked yet', () => {+ renderCard({+ reference: { manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'pending' }] } },+ corrections: {},+ onCorrectionChange: vi.fn(),+ });+ expect(screen.queryByRole('button', { name: /correction note/i })).toBeNull();+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 0a567f0590..c715c6bea3 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -141,7 +141,8 @@ grep -i "what you want to do" client/src/lib/README.md| `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`, and `rhythmShapeLabel(id)` (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). Pure data; pickers and docs read the same source so they can't drift. || `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). Pure — takes callbacks, performs no I/O. Consumes the facets from `spriteFacets.js`. |+| `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. || `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/index.js b/client/src/lib/index.jsindex 616c63f9cc..0933f50452 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -110,6 +110,7 @@ export * from './songCraft.js';export * from './songPlayback.js';export * from './songProgress.js';export * from './spriteCollectionActions.js';+export * from './spriteCorrections.js';export * from './spriteFacets.js';export * from './spriteRecordGroups.js';export * from './spriteTrimmer.js';diff --git a/client/src/lib/spriteCollectionActions.js b/client/src/lib/spriteCollectionActions.jsindex 370dfc83d1..184d51c380 100644--- a/client/src/lib/spriteCollectionActions.js+++ b/client/src/lib/spriteCollectionActions.js@@ -22,6 +22,8 @@* uses the same backend the workflow would, not a server default.*/+import { anchorCorrectionKey, walkCorrectionKey } from './spriteCorrections.js';+// Roles that represent a walk run's rendered output. A manifest or a review// sheet from the same run is not something you re-render on its own.const WALK_OUTPUT_ROLES = new Set(['strip', 'animation', 'frame']);@@ -77,6 +79,15 @@ export function buildCollectionActions({const pending = Boolean(walkPending[direction]);return {kind: 'walk',+ // The card binds an inline correction note to this key in the shared+ // page-owned corrections map (#3134). It is the WALK namespace, not the+ // bare direction the anchor re-roll uses — a still-image anchor note+ // ("no pocket on the right sleeve") must not ride a walk VIDEO re-roll.+ // The page's `generateWalk` reads the same key, so the note applies+ // whether it was typed here or in `WalkWorkflow`.+ correctionKey: walkCorrectionKey(direction),+ correctionLabel: `${direction} walk cycle`,+ correctionPlaceholder: 'Correction (optional), e.g. the legs barely lift',pending,disabled: finalized || approved || !locked || pending,title: finalized ? 'The walk set is finalized — regenerating is disabled'@@ -103,6 +114,8 @@ export function buildCollectionActions({// shared per-direction corrections state (#2964) — the same note the// ReferenceWorkflow anchor grid shows — before firing generateAnchor.direction,+ correctionKey: anchorCorrectionKey(direction),+ correctionLabel: `${direction} pose`,pending,disabled: !hasBackend || locked || pending,title: !hasBackenddiff --git a/client/src/lib/spriteCollectionActions.test.js b/client/src/lib/spriteCollectionActions.test.jsindex 72982b4e3b..56d000acfe 100644--- a/client/src/lib/spriteCollectionActions.test.js+++ b/client/src/lib/spriteCollectionActions.test.js@@ -48,6 +48,16 @@ describe('regenerateFor — walk outputs', () => {expect(r).toMatchObject({ disabled: true, pending: true });});+ it('names a WALK-namespaced correction key, never the bare direction (#3134)', () => {+ // Bare-direction would be the anchor's key, so an anchor's still-image note+ // ("no pocket on the right sleeve") would silently ride a walk VIDEO re-roll.+ const r = build().regenerateFor(STRIP_EAST);+ expect(r.correctionKey).toBe('walk:east');+ expect(r.correctionKey).not.toBe('east');+ // Every walk output role carries it, so the note is reachable from any card.+ expect(build().regenerateFor(FRAME_EAST).correctionKey).toBe('walk:east');+ });+it('treats the submitting sentinel as in flight — that is the double-click guard', () => {expect(build({}, { walkPending: { east: 'submitting' } }).regenerateFor(STRIP_EAST).disabled).toBe(true);});@@ -94,6 +104,8 @@ describe('regenerateFor — reference anchors', () => {const r = build({ reference: { manifest: { anchors: [{ direction: 'east', status: 'pending' }] } } }).regenerateFor(CANDIDATE_EAST);expect(r.direction).toBe('east');+ // The anchor's map key is the BARE direction (pre-#3134 state still resolves).+ expect(r.correctionKey).toBe('east');});it('disables the re-roll once the anchor is locked — locks are irreversible', () => {diff --git a/client/src/lib/spriteCorrections.js b/client/src/lib/spriteCorrections.jsnew file mode 100644index 0000000000..c4683c360a--- /dev/null+++ b/client/src/lib/spriteCorrections.js@@ -0,0 +1,49 @@+/**+ * Sprite correction-note keys + request fragment (#2964, extended to every+ * regeneration surface by #3134).+ *+ * Every Sprite Manager surface that can re-roll a render — the turnaround sheet,+ * the main reference, the 7 directional anchors, the walk and scanner clips, and+ * the ambient reference + loop — writes its note into ONE page-owned+ * `corrections` map (lifted to `Sprites.jsx`). This module owns that map's key+ * vocabulary and the single helper that turns a note into a request fragment, so+ * the pure action-gating layer (`spriteCollectionActions.js`) and the React+ * surfaces (`CorrectionNote.jsx` and its hosts) agree without the pure layer+ * having to import a component.+ *+ * ## Why keys are namespaced per SURFACE, not per direction+ *+ * An anchor note ("no pocket on the right sleeve" — a still-image fix) must not+ * silently ride the next walk-VIDEO re-roll for the same direction, and vice+ * versa. The anchors keep the bare direction key so pre-#3134 behavior and state+ * are untouched; every other surface prefixes.+ *+ * Pure — no React, no I/O.+ */++/** The 7 turnaround-derived anchors keep the bare direction key (pre-#3134). */+export const anchorCorrectionKey = (direction) => direction;+/** The frozen main/south reference — one per record, so no direction in the key. */+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}`;+/** The scanner action video for a direction. */+export const scannerCorrectionKey = (direction) => `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';++/**+ * Build the re-roll request fragment for one correction key. Returns+ * `{ correctionPrompt }` only when the note is non-empty after trimming, else+ * `{}` — so an absent or whitespace-only note is omitted from the request,+ * matching the server's optional `correctionPrompt` and keeping a blind+ * regenerate byte-identical. EVERY re-roll surface spreads this, so they all+ * send identical payloads — the single source guarantee at the request layer,+ * not just the input layer.+ */+export function correctionPromptPayload(corrections, key) {+ const note = corrections?.[key]?.trim();+ return note ? { correctionPrompt: note } : {};+}diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex cd4e52e236..e600c87aad 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -19,7 +19,10 @@ 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 } from '../components/sprites/CorrectionNote.jsx';+import {+ correctionPromptPayload, anchorCorrectionKey, walkCorrectionKey, scannerCorrectionKey,+ AMBIENT_REFERENCE_CORRECTION_KEY, AMBIENT_LOOP_CORRECTION_KEY,+} from '../components/sprites/CorrectionNote.jsx';import SpriteCatalog from '../components/sprites/SpriteCatalog.jsx';import SpriteDetailHeader from '../components/sprites/SpriteDetailHeader.jsx';import TabPills from '../components/ui/TabPills.jsx';@@ -438,13 +441,17 @@ export default function Sprites() {onChanged: onWorkflowChanged,});- // Per-direction anchor correction guidance is page-owned (#2964) so the- // ReferenceWorkflow anchor grid and the asset-collection Regenerate button+ // Correction guidance for EVERY regeneration surface is page-owned (#2964,+ // extended to the main reference / walk / scanner / ambient surfaces by+ // #3134) so a workflow panel and the asset-collection Regenerate button// read/write ONE source: a correction typed on either surface applies to the// other AND rides along as `correctionPrompt` on whichever re-roll fires.- // Keyed by direction — the 8 anchor keys are identical across characters, so- // reset on record switch to keep a leftover note from bleeding into the next- // sprite (the reset ReferenceWorkflow used to own before the state was lifted).+ // Keys are namespaced PER SURFACE by `lib/spriteCorrections.js` — anchors keep+ // the bare direction, everything else prefixes — so an anchor's still-image+ // note can't leak into that direction's walk video. Every key is identical+ // across characters, so reset on record switch to keep a leftover note from+ // bleeding into the next sprite (the reset ReferenceWorkflow used to own+ // before the state was lifted).const [corrections, setCorrections] = useState({});useEffect(() => { setCorrections({}); }, [id]);@@ -546,16 +553,25 @@ export default function Sprites() {}}, []);+ // The direction's walk-scoped correction (#3134) rides along, read from the+ // SAME page-owned map both WalkWorkflow's card and the asset-collection walk+ // card write — so a note typed on either surface applies to whichever+ // Generate the user clicks. The key is walk-namespaced, so an anchor+ // (still-image) note can never leak into the video prompt.const generateWalk = useCallback((direction) => submitRender(walkBegin, walkResolve, walkCancel, direction,- () => generateSpriteWalk(id, { direction, duration }, { silent: true }),+ () => generateSpriteWalk(id, {+ direction,+ duration,+ ...correctionPromptPayload(corrections, walkCorrectionKey(direction)),+ }, { silent: true }),`Failed to queue ${direction} walk`,// Refetch immediately so the server's 'rendering' run lands before the// media-job poll evicts the optimistic key (~4s) — otherwise the Generate// button briefly re-enables and a second click would 409 the in-flight// render. The server guard is the real backstop; this closes the UI gap.onWorkflowChanged,- ), [id, duration, walkBegin, walkResolve, walkCancel, submitRender, 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@@ -565,31 +581,40 @@ export default function Sprites() {// TUI run for polling.const generateScanner = useCallback(async (direction) => {try {- await generateSpriteScanner(id, { direction }, { silent: true });+ await generateSpriteScanner(id, {+ direction,+ ...correctionPromptPayload(corrections, scannerCorrectionKey(direction)),+ }, { silent: true });onWorkflowChanged();} catch (err) {toast.error(err?.message || `Failed to queue ${direction} scanner action`);}- }, [id, onWorkflowChanged]);+ }, [id, corrections, onWorkflowChanged]);+ // The ambient main takes BOTH inputs: `designPrompt` replaces the design+ // outright, while the correction (#3134) keeps it and fixes one thing about+ // the last render.const generateAmbientReference = useCallback((designPrompt) => submitRender(refBegin, refResolve, refCancel, 'main',() => generateSpriteReference(id, {target: 'main', designPrompt,...(imageMode ? { mode: imageMode } : {}),+ ...correctionPromptPayload(corrections, AMBIENT_REFERENCE_CORRECTION_KEY),}, { silent: true }),'Failed to queue ambient reference',onWorkflowChanged,- ), [id, imageMode, refBegin, refResolve, refCancel, submitRender, onWorkflowChanged]);+ ), [id, imageMode, corrections, refBegin, refResolve, refCancel, submitRender, onWorkflowChanged]);const generateAmbient = useCallback(async () => {try {- await generateSpriteAmbient(id, {}, { silent: true });+ await generateSpriteAmbient(id, {+ ...correctionPromptPayload(corrections, AMBIENT_LOOP_CORRECTION_KEY),+ }, { silent: true });onWorkflowChanged();} catch (err) {toast.error(err?.message || 'Failed to queue ambient loop');}- }, [id, onWorkflowChanged]);+ }, [id, corrections, onWorkflowChanged]);// `mode` is the workflow-selected backend, threaded from the asset card via// buildCollectionActions (#2938) so a re-roll uses the same backend the@@ -603,7 +628,7 @@ export default function Sprites() {() => generateSpriteReference(id, {target: direction,...((mode || imageMode) ? { mode: mode || imageMode } : {}),- ...correctionPromptPayload(corrections, direction),+ ...correctionPromptPayload(corrections, anchorCorrectionKey(direction)),}, { silent: true }),`Failed to queue ${direction} render`,), [id, imageMode, corrections, refBegin, refResolve, refCancel, submitRender]);@@ -744,6 +769,8 @@ export default function Sprites() {onGenerate={generateWalk}onOpenTrimmer={openTrimmer}onChanged={onWorkflowChanged}+ corrections={corrections}+ onCorrectionChange={setCorrections}/><ScannerWorkflowrecord={detail.record}@@ -751,6 +778,8 @@ export default function Sprites() {scanner={detail.scanner}onGenerate={generateScanner}onChanged={onWorkflowChanged}+ corrections={corrections}+ onCorrectionChange={setCorrections}/>{/* Keyed by record so form state and an armed publish/overwriteconfirmation never survive switching characters. */}@@ -775,6 +804,8 @@ export default function Sprites() {onGenerateReference={generateAmbientReference}onGenerateAmbient={generateAmbient}onChanged={onWorkflowChanged}+ corrections={corrections}+ onCorrectionChange={setCorrections}/><PublishWorkflowkey={detail.record.id}diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.jsindex ca2d967c81..05d7be88b1 100644--- a/client/src/services/apiSprites.js+++ b/client/src/services/apiSprites.js@@ -63,7 +63,9 @@ export const importSprites = (body, options = {}) => request('/sprites/import',// Queue one reference candidate render. `referenceImageFile` (main target// only) switches the POST to multipart so the design reference uploads with// the fields. `initImageCandidate` re-processes one turnaround candidate with-// a correctionPrompt. Returns { jobId, mode, target, anchorId }.+// a correctionPrompt; every target (turnaround, main, anchor) accepts a+// standalone `correctionPrompt` for a corrected re-roll. Returns+// { jobId, mode, target, anchorId }.export const generateSpriteReference = (id, { referenceImageFile, ...fields }, options = {}) => {let body;if (referenceImageFile) {@@ -116,12 +118,16 @@ export const forkSpriteRecord = (id, body, options = {}) => request(`/sprites/${// approval into the finalized walk set.// Queue one walk video render. Returns { jobId, runId, direction, duration }.+// An optional `correctionPrompt` (#3134) is appended to the motion prompt so a+// re-roll can be told what the previous clip got wrong; omit it (never send an+// empty string) for a blind regenerate — `correctionPromptPayload` handles that.export const generateSpriteWalk = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/walk/generate`, {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,});@@ -136,6 +142,8 @@ export const approveSpriteScanner = (id, body, options = {}) => request(`/spritemethod: '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,});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 528b3ae237..3da9729b8e 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1210,6 +1210,10 @@ export const spriteWalkGenerateSchema = z.object({// the geometry.frameCount: spriteWalkFrameCountSchema.optional(),fps: spriteWalkFpsSchema.optional(),+ // Free-text guidance appended to a re-roll's motion prompt (#3134) — the same+ // additive correction the reference/anchor renders take. Absent or blank+ // leaves the prompt byte-identical to a blind regenerate.+ correctionPrompt: z.string().max(4000).optional(),});// The scanner is a separate, short directional action. It deliberately has its@@ -1220,6 +1224,7 @@ export const spriteScannerGenerateSchema = z.object({duration: grokVideoDurationSchema.optional(),frameCount: spriteScannerFrameCountSchema.optional(),fps: spriteScannerFpsSchema.optional(),+ correctionPrompt: z.string().max(4000).optional(),});export const spriteScannerApproveSchema = z.object({@@ -1233,6 +1238,7 @@ 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({diff --git a/server/services/sprites/ambient.js b/server/services/sprites/ambient.jsindex 06ba0e6353..0afae117d4 100644--- a/server/services/sprites/ambient.js+++ b/server/services/sprites/ambient.js@@ -106,6 +106,9 @@ async function startAmbientGenerationImpl(recordId, body) {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');@@ -137,6 +140,7 @@ async function startAmbientGenerationImpl(recordId, body) {animationInputPath: `${runRel}/generated/input-main-chroma.png`,animationInputSha256: inputSha256,animationInputPreparation: preparation,+ ...(correctionPrompt ? { correctionPrompt } : {}),createdAt: new Date().toISOString(),};await saveRun(recordId, run);@@ -145,7 +149,12 @@ async function startAmbientGenerationImpl(recordId, body) {generatedAbs,videoAbs,grokPath: settings.imageGen?.grok?.grokPath,- task: ambientTask({ prompt: buildAmbientVideoPrompt({ name: record.name, kind: record.kind, chromaKey }), inputAbs, videoAbs, duration }),+ 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 };diff --git a/server/services/sprites/ambient.test.js b/server/services/sprites/ambient.test.jsindex 2e734d8d9e..7b01472148 100644--- a/server/services/sprites/ambient.test.js+++ b/server/services/sprites/ambient.test.js@@ -96,4 +96,28 @@ describe('ambient animation track', () => {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/assetPrompt.js b/server/services/sprites/assetPrompt.jsindex 727f0e0316..95782f38ed 100644--- a/server/services/sprites/assetPrompt.js+++ b/server/services/sprites/assetPrompt.js@@ -33,9 +33,10 @@ import { getRecord } from './records.js';import { loadManifest } from './reference.js';import {buildMainReferencePrompt, buildAmbientReferencePrompt, buildAnchorPrompt,- buildWalkVideoPrompt, buildAmbientVideoPrompt, buildTurnaroundPrompt, TURNAROUND_ID,+ buildWalkVideoPrompt, buildAmbientVideoPrompt, buildScannerPrompt,+ buildTurnaroundPrompt, TURNAROUND_ID,} from './prompts.js';-import { AMBIENT_TRACK } from './animationTracks.js';+import { AMBIENT_TRACK, SCANNER_TRACK } from './animationTracks.js';import { DEFAULT_CHROMA_KEY } from './chromaKey.js';const CANDIDATE_RE = /^reference\/candidates\/(.+)\.png$/i;@@ -50,17 +51,21 @@ function fromCandidateSidecar(sidecar, name, fromTurnaround = false, kind = 'chaif (typeof sidecar.prompt === 'string' && sidecar.prompt) {return { prompt: sidecar.prompt, designPrompt: sidecar.designPrompt || null, source: 'candidate' };}- // Pre-capture candidate — rebuild with the builder that produced it.- const { designPrompt, chromaKey } = sidecar;+ // Pre-capture candidate — rebuild with the builder that produced it. The+ // sidecar records the re-roll correction whenever one was used (#2964/#3134),+ // so the rebuild reproduces the corrected prompt rather than the blind one.+ const { designPrompt, chromaKey, correctionPrompt } = sidecar;let prompt;if (sidecar.target === TURNAROUND_ID) {- prompt = buildTurnaroundPrompt({ name, designPrompt, chromaKey });+ prompt = buildTurnaroundPrompt({ name, designPrompt, chromaKey, correctionPrompt });} else if (sidecar.target === 'main') {prompt = kind === 'character'- ? buildMainReferencePrompt({ name, designPrompt, chromaKey, fromTurnaround })- : buildAmbientReferencePrompt({ name, kind, designPrompt, chromaKey });+ ? buildMainReferencePrompt({ name, designPrompt, chromaKey, correctionPrompt, fromTurnaround })+ : buildAmbientReferencePrompt({ name, kind, designPrompt, chromaKey, correctionPrompt });} else {- prompt = buildAnchorPrompt({ name, direction: sidecar.direction || sidecar.target, chromaKey, fromTurnaround });+ prompt = buildAnchorPrompt({+ name, direction: sidecar.direction || sidecar.target, chromaKey, correctionPrompt, fromTurnaround,+ });}return { prompt, designPrompt: designPrompt || null, source: 'candidate-reconstructed' };}@@ -163,19 +168,25 @@ export async function resolveSpriteAssetPrompt(recordId, relPath) {}}- // 3. Walk-animation asset — rebuild the i2v motion prompt from the run record.+ // 3. Animation asset — rebuild the i2v motion prompt from the run record.+ // Each named track rebuilds with ITS OWN builder: reconstructing a scanner run+ // with the walk builder would report a prompt that was never sent. The run+ // record stamps `correctionPrompt` when the render carried one (#3134), so a+ // corrected re-roll rebuilds with its correction clause.const run = RUN_DIR_MATCH.exec(relPath);if (run) {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- : runRecord.track === AMBIENT_TRACK- ? buildAmbientVideoPrompt({ name, kind: record.kind, chromaKey: runRecord.chromaKey })- : buildWalkVideoPrompt({ name, direction: runRecord.direction, chromaKey: runRecord.chromaKey }),+ prompt: typeof runRecord.prompt === 'string' && runRecord.prompt ? runRecord.prompt : rebuild(),designPrompt: null,- source: runRecord.track === AMBIENT_TRACK ? 'ambient' : 'walk',+ source: track === AMBIENT_TRACK ? 'ambient' : track === SCANNER_TRACK ? 'scanner' : 'walk',};}}diff --git a/server/services/sprites/assetPrompt.test.js b/server/services/sprites/assetPrompt.test.jsindex 8c735b26b4..18f1724c9c 100644--- a/server/services/sprites/assetPrompt.test.js+++ b/server/services/sprites/assetPrompt.test.js@@ -247,6 +247,74 @@ describe('resolveSpriteAssetPrompt', () => {expect(res.prompt).toContain('Hero');});+ it('rebuilds each animation track with its OWN builder (#3134)', async () => {+ const id = newId();+ await records.createRecord({ kind: 'place', name: 'Old Grove' }, `${id}-grove`);+ await createCharacter(id);+ const writeRun = async (recordId, runId, run) => {+ const runDir = join(TEST_ROOT, 'sprites', recordId, 'runs', runId);+ await mkdir(join(runDir, 'generated'), { recursive: true });+ await writeFile(join(runDir, 'animation-run.json'), JSON.stringify({+ schemaVersion: 1, id: runId, characterId: recordId, direction: 'east', chromaKey: '#FF00FF', ...run,+ }));+ await writeFile(join(runDir, 'generated', 'source-video.mp4'), 'fake');+ return `runs/${runId}/generated/source-video.mp4`;+ };++ // Scanner used to rebuild with the WALK builder, reporting a prompt that was+ // never sent. It now has its own.+ const scannerRel = await writeRun(id, 'scanner-east-abc12345', { track: 'scanner' });+ const scanner = await resolveSpriteAssetPrompt(id, scannerRel);+ expect(scanner.source).toBe('scanner');+ expect(scanner.prompt).toContain('scanner action for Hero');+ expect(scanner.prompt).not.toContain('walk-in-place loop');++ const ambientRel = await writeRun(`${id}-grove`, 'ambient-abc12345', { track: 'ambient', direction: 'south' });+ const ambient = await resolveSpriteAssetPrompt(`${id}-grove`, ambientRel);+ expect(ambient.source).toBe('ambient');+ expect(ambient.prompt).toContain('at-rest place sprite Old Grove');+ });++ it('rebuilds a corrected animation re-roll with its correction clause (#3134)', async () => {+ const id = newId();+ await createCharacter(id);+ const runDir = join(TEST_ROOT, 'sprites', id, 'runs', 'walk-east-abc12345');+ await mkdir(join(runDir, 'generated'), { recursive: true });+ await writeFile(join(runDir, 'animation-run.json'), JSON.stringify({+ schemaVersion: 1,+ id: 'walk-east-abc12345',+ characterId: id,+ track: 'walk',+ direction: 'east',+ chromaKey: '#FF00FF',+ correctionPrompt: 'the legs barely lift',+ }));+ await writeFile(join(runDir, 'generated', 'source-video.mp4'), 'fake');++ const res = await resolveSpriteAssetPrompt(id, 'runs/walk-east-abc12345/generated/source-video.mp4');+ expect(res.source).toBe('walk');+ expect(res.prompt)+ .toContain('Important correction — apply this over the attached source image: the legs barely lift');+ });++ it('rebuilds a corrected reference candidate with its correction clause (#3134)', async () => {+ const id = newId();+ await createCharacter(id);+ const candDir = join(TEST_ROOT, 'sprites', id, 'reference', 'candidates');+ await mkdir(candDir, { recursive: true });+ await writeCandidatePng(join(candDir, 'walk-east-candidate-03.png'));+ // A pre-capture sidecar (no literal `prompt`) that DID record its correction.+ await writeFile(join(candDir, 'walk-east-candidate-03.generation.json'), JSON.stringify({+ schemaVersion: 1, target: 'east', direction: 'east', chromaKey: '#FF00FF',+ correctionPrompt: 'no pocket on the right sleeve',+ }));++ const res = await resolveSpriteAssetPrompt(id, 'reference/candidates/walk-east-candidate-03.png');+ expect(res.source).toBe('candidate-reconstructed');+ expect(res.prompt)+ .toContain('Important correction — apply this over the attached reference: no pocket on the right sleeve');+ });+it('returns null for an asset with no prompt provenance', async () => {const id = newId();await createCharacter(id);diff --git a/server/services/sprites/prompts.js b/server/services/sprites/prompts.jsindex 8b5dbb1c57..0bafdfa645 100644--- a/server/services/sprites/prompts.js+++ b/server/services/sprites/prompts.js@@ -138,6 +138,24 @@ export function viewGeometryClause(direction) {// target vocabulary so validation.js and the services share one spelling.export const TURNAROUND_ID = 'turnaround';+/**+ * The one appended clause that turns a blind re-roll into a corrected one+ * (#2964, extended to every surface by #3134). `subject` names what the model is+ * being corrected ON — the noun of whatever image/clip is attached ("turnaround",+ * "reference", "source image") — so each surface reads naturally while the+ * instruction shape stays identical everywhere.+ *+ * Returns `''` for absent/blank input, which is the hard contract every caller+ * depends on: a whitespace-only note must leave the prompt byte-identical to+ * today's blind regenerate. Callers append the result LAST so the correction+ * reads as an override of the base clauses rather than one more of them.+ */+export function correctionClause(correctionPrompt, subject) {+ return (typeof correctionPrompt === 'string' && correctionPrompt.trim())+ ? ` Important correction — apply this over the attached ${subject}: ${correctionPrompt.trim()}`+ : '';+}+/*** Stage-0 prompt (issue #2979): the character turnaround sheet — the identity* root every later render descends from. One image, `TURNAROUND_VIEWS.length`@@ -161,9 +179,7 @@ export function buildTurnaroundPrompt({ name, designPrompt, chromaKey, correctioconst panelRules = TURNAROUND_VIEWS.map((view, i) => `Panel ${i + 1} (${REFERENCE_FACING[view] || view}): ${viewGeometryClause(view)}`).join(' ');- const correction = (typeof correctionPrompt === 'string' && correctionPrompt.trim())- ? ` Important correction — apply this over the attached turnaround: ${correctionPrompt.trim()}`- : '';+ const correction = correctionClause(correctionPrompt, 'turnaround');return (`Create a character turnaround model sheet for a game character named ${name}. `+ `Character design: ${description} `@@ -241,12 +257,19 @@ const geometryRule = (direction) => {* Stage-1 prompt: create the frozen walk-south identity reference from a* text description and/or an attached visual reference. `fromTurnaround`* switches the copy for the turnaround-first flow (#2979), where the main is- * derived from the locked sheet like any other direction.+ * derived from the locked sheet like any other direction. `correctionPrompt`+ * (#3134) is the optional re-roll note — the same additive correction the+ * turnaround and anchors already take, so a bad main can be described rather+ * than only re-rolled blind.*/-export function buildMainReferencePrompt({ name, designPrompt, chromaKey, fromTurnaround = false }) {+export function buildMainReferencePrompt({ name, designPrompt, chromaKey, correctionPrompt, fromTurnaround = false }) {const description = (typeof designPrompt === 'string' && designPrompt.trim())? designPrompt.trim(): 'Use the attached visual reference as the character design.';+ // The main derives from the sheet when there is one, so name the sheet as+ // what the correction applies OVER; a legacy record has only its own+ // reference attached.+ const correction = correctionClause(correctionPrompt, fromTurnaround ? 'turnaround' : 'reference');return ((fromTurnaround ? fromTurnaroundClause('south') : '')+ `Create the frozen walk-south identity reference for a game character named ${name}. `@@ -257,15 +280,18 @@ export function buildMainReferencePrompt({ name, designPrompt, chromaKey, fromTu+ `accessories exactly. ${geometryRule('south')}Flat non-isometric pixel-art game sprite reference, centered on `+ `a plain exact ${keyColorPhrase(chromaKey)} background on a square 1:1 canvas. No motion, labels, grid, shadows, scenery, `+ 'wireframe, or extra figures. Return exactly one PNG.'+ + correction);}/*** The identity root for a place/object ambient loop. Unlike a character it has* no facing or turnaround: this one locked still is both the idle cell and the- * image-to-video source, so it must be legible on its own.+ * image-to-video source, so it must be legible on its own. `correctionPrompt`+ * (#3134) is additive — distinct from `designPrompt`, which REPLACES the design+ * outright: a correction keeps the design and fixes one thing about the render.*/-export function buildAmbientReferencePrompt({ name, kind, designPrompt, chromaKey }) {+export function buildAmbientReferencePrompt({ name, kind, designPrompt, chromaKey, correctionPrompt }) {const description = (typeof designPrompt === 'string' && designPrompt.trim())? designPrompt.trim(): 'Use the attached visual reference as the design.';@@ -274,17 +300,24 @@ export function buildAmbientReferencePrompt({ name, kind, designPrompt, chromaKe+ 'Show its at-rest state with a clear readable silhouette. Match the attached visual reference when provided. '+ `Use a plain exact ${keyColorPhrase(chromaKey)} background on a square 1:1 canvas. No people, scenery, text, labels, grid, `+ 'camera angle, shadows, wireframe, or extra objects. Return exactly one PNG.'+ + correctionClause(correctionPrompt, 'reference'));}-/** Ambient image-to-video instruction: preserve the still while moving only its natural loop detail. */-export function buildAmbientVideoPrompt({ name, kind, chromaKey }) {+/**+ * Ambient image-to-video instruction: preserve the still while moving only its+ * natural loop detail. `correctionPrompt` (#3134) describes what the previous+ * loop got wrong (e.g. "the branches barely move" / "the flame drifts off the+ * trunk") so a re-roll diverges instead of reproducing it.+ */+export function buildAmbientVideoPrompt({ name, kind, chromaKey, correctionPrompt }) {return (`The source image is the locked at-rest ${kind} sprite ${name}. Animate one subtle seamless ambient loop `+ '(for example wind, water, flame, or a gentle flicker appropriate to the source), then return to the exact starting pose. '+ 'Preserve its identity, silhouette, palette, scale, and centered ground position. Use a locked camera and an exactly '+ `uniform non-emissive ${keyColorPhrase(chromaKey)} background only as a compositing matte: no scenery, text, labels, `+ 'camera movement, cuts, added objects, or people.'+ + correctionClause(correctionPrompt, 'source image'));}@@ -295,8 +328,12 @@ export function buildAmbientVideoPrompt({ name, kind, chromaKey }) {* mechanics (one image_to_video call, save one MP4), so this carries only* the identity/matte/motion constraints — the source pipeline's* `animation_prompt` minus its CLI/tool scaffolding.+ *+ * `correctionPrompt` (#3134) is the optional re-roll note describing what the+ * previous clip got wrong (e.g. "the legs barely lift", "the cape clips through+ * the pack") — same additive contract as the reference builders.*/-export function buildWalkVideoPrompt({ name, direction, chromaKey }) {+export function buildWalkVideoPrompt({ name, direction, chromaKey, correctionPrompt }) {const facing = REFERENCE_FACING[direction] || direction;return (`The source image is the locked directional identity anchor for the game character ${name}, `@@ -309,9 +346,27 @@ export function buildWalkVideoPrompt({ name, direction, chromaKey }) {+ 'bounce light, reflections, color cast, glow, or shadow on the character. Keep a stable '+ 'pivot and ground line with loop-friendly walk-in-place motion. No scenery, no text, no '+ 'labels, no camera motion, no extra figures.'+ + correctionClause(correctionPrompt, 'source image'));}+/**+ * The named scanner action track's i2v instruction (#3134 promoted it out of+ * `services/sprites/scanner.js` so every stage's prompt lives in this one pure+ * module — which is also what lets `assetPrompt.js` rebuild a scanner run's+ * provenance with the builder that actually produced it instead of the walk's).+ *+ * The wording is unchanged from the version that lived in `scanner.js`, so an+ * existing scanner run's rebuilt provenance prompt still matches what was sent.+ */+export function buildScannerPrompt({ name, direction, chromaKey, correctionPrompt }) {+ return `Create a short, seamless scanner action for ${name}, facing ${direction}. `+ + 'The character raises a handheld scanner, makes one deliberate sweep, then returns to the exact starting pose. '+ + `Keep the character centered, full body visible, and animate only over a solid ${chromaKey} background. `+ + 'No text, UI, scenery, camera movement, cuts, or additional characters.'+ + correctionClause(correctionPrompt, 'source image');+}+/*** Stage-2 prompt: derive one directional anchor from the attached reference —* the locked turnaround sheet (`fromTurnaround`, the #2979 standard) or, on a@@ -323,9 +378,7 @@ export function buildWalkVideoPrompt({ name, direction, chromaKey }) {*/export function buildAnchorPrompt({ name, direction, chromaKey, correctionPrompt, fromTurnaround = false }) {const facing = REFERENCE_FACING[direction] || direction;- const correction = (typeof correctionPrompt === 'string' && correctionPrompt.trim())- ? ` Important correction — apply this over the attached reference: ${correctionPrompt.trim()}`- : '';+ const correction = correctionClause(correctionPrompt, 'reference');return ((fromTurnaround ? fromTurnaroundClause(direction) : '')+ `Redraw the attached ${name} character as one `diff --git a/server/services/sprites/prompts.test.js b/server/services/sprites/prompts.test.jsindex eb73001b0b..9b12d348cf 100644--- a/server/services/sprites/prompts.test.js+++ b/server/services/sprites/prompts.test.js@@ -2,7 +2,8 @@ import { describe, it, expect } from 'vitest';import {SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, REFERENCE_FACING, anchorIdForDirection,keyColorPhrase, buildMainReferencePrompt, buildAnchorPrompt, buildTurnaroundPrompt,- buildWalkVideoPrompt, viewGeometryClause, TURNAROUND_VIEWS, SPRITE_REFERENCE_CANVAS_SIZE,+ buildWalkVideoPrompt, buildScannerPrompt, buildAmbientReferencePrompt, buildAmbientVideoPrompt,+ correctionClause, viewGeometryClause, TURNAROUND_VIEWS, SPRITE_REFERENCE_CANVAS_SIZE,} from './prompts.js';describe('sprite direction contracts', () => {@@ -288,3 +289,87 @@ describe('fromTurnaround prompt variants (#2979)', () => {expect(p).toContain('a wiry ranger');});});++describe('correction prompts on every regeneration surface (#3134)', () => {+ // One table so a newly-added builder can't quietly ship without the+ // correction contract: each row is a builder plus the base params it needs and+ // the noun its clause is expected to name.+ const SURFACES = [+ {+ label: 'turnaround sheet',+ build: (extra) => buildTurnaroundPrompt({ name: 'Scout', designPrompt: 'a wiry ranger', chromaKey: '#FF00FF', ...extra }),+ subject: 'turnaround',+ },+ {+ label: 'main reference (from the sheet)',+ build: (extra) => buildMainReferencePrompt({ name: 'Scout', designPrompt: 'a wiry ranger', chromaKey: '#FF00FF', fromTurnaround: true, ...extra }),+ subject: 'turnaround',+ },+ {+ label: 'main reference (legacy, no sheet)',+ build: (extra) => buildMainReferencePrompt({ name: 'Scout', designPrompt: 'a wiry ranger', chromaKey: '#FF00FF', ...extra }),+ subject: 'reference',+ },+ {+ label: 'directional anchor',+ build: (extra) => buildAnchorPrompt({ name: 'Scout', direction: 'east', chromaKey: '#FF00FF', ...extra }),+ subject: 'reference',+ },+ {+ label: 'ambient/place reference',+ build: (extra) => buildAmbientReferencePrompt({ name: 'Old Willow', kind: 'place', designPrompt: 'a willow by a pond', chromaKey: '#FF00FF', ...extra }),+ subject: 'reference',+ },+ {+ label: 'walk video',+ build: (extra) => buildWalkVideoPrompt({ name: 'Scout', direction: 'east', chromaKey: '#FF00FF', ...extra }),+ subject: 'source image',+ },+ {+ label: 'scanner action video',+ build: (extra) => buildScannerPrompt({ name: 'Scout', direction: 'east', chromaKey: '#FF00FF', ...extra }),+ subject: 'source image',+ },+ {+ label: 'ambient loop video',+ build: (extra) => buildAmbientVideoPrompt({ name: 'Old Willow', kind: 'place', chromaKey: '#FF00FF', ...extra }),+ subject: 'source image',+ },+ ];++ for (const { label, build, subject } of SURFACES) {+ describe(label, () => {+ it('appends one trimmed correction clause, last', () => {+ const p = build({ correctionPrompt: ' the strap floats off the shoulder ' });+ expect(p).toContain(`Important correction — apply this over the attached ${subject}: the strap floats off the shoulder`);+ // Last so it reads as an override of the base clauses, not one more of them.+ expect(p.trimEnd().endsWith('the strap floats off the shoulder')).toBe(true);+ // Exactly one clause — a second would let the surfaces disagree on emphasis.+ expect(p.match(/Important correction/g)).toHaveLength(1);+ });++ // The hard acceptance criterion: a blank note must not perturb the blind+ // regenerate by even one byte, on any surface.+ it('is byte-identical to a blind regenerate for absent/blank input', () => {+ const base = build({});+ expect(base).not.toContain('Important correction');+ for (const blank of [undefined, null, '', ' ', '\n\t ', 42, {}]) {+ expect(build({ correctionPrompt: blank }), String(blank)).toBe(base);+ }+ });+ });+ }+});++describe('correctionClause', () => {+ it('names the subject the correction applies over', () => {+ expect(correctionClause('fix the arm', 'turnaround'))+ .toBe(' Important correction — apply this over the attached turnaround: fix the arm');+ });++ it('returns the empty string for anything blank or non-string', () => {+ for (const v of [undefined, null, '', ' ', 0, 7, [], {}, () => {}]) {+ expect(correctionClause(v, 'reference'), String(v)).toBe('');+ }+ });+});diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.jsindex e911fd3ecb..606807072f 100644--- a/server/services/sprites/reference.js+++ b/server/services/sprites/reference.js@@ -446,7 +446,13 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {}anchorId = 'main';direction = 'south';- prompt = buildAmbientReferencePrompt({ name: record.name, kind: record.kind, designPrompt, chromaKey: genKey });+ // A place/object main takes BOTH inputs (#3134): `designPrompt` replaces+ // the design outright, `correctionPrompt` keeps it and fixes one thing+ // about the last render. They compose — the user can do either or both.+ correctionPrompt = typeof body.correctionPrompt === 'string' ? body.correctionPrompt.trim() : '';+ prompt = buildAmbientReferencePrompt({+ name: record.name, kind: record.kind, designPrompt, chromaKey: genKey, correctionPrompt,+ });({ initImagePath, designReferencePath } = await resolveSeedSource(recordId, body, upload));if (initImagePath) initImageStrength ??= UPLOAD_DEFAULT_STRENGTH;if (designPrompt) manifest.designPrompt = designPrompt;@@ -461,10 +467,15 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {}anchorId = anchorIdForDirection('south');direction = 'south';+ // Same optional re-roll note the anchors take (#3134) — the main derives+ // from the sheet, so a bad front view can be described instead of only+ // re-rolled blind.+ correctionPrompt = typeof body.correctionPrompt === 'string' ? body.correctionPrompt.trim() : '';prompt = buildMainReferencePrompt({name: record.name,designPrompt: designPrompt || manifest.designPrompt,chromaKey: genKey,+ correctionPrompt,fromTurnaround: true,});// The sheet IS the seed here, so a caller-supplied one has nowhere to go.diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.jsindex adc8e0ce97..658a2d5df9 100644--- a/server/services/sprites/reference.test.js+++ b/server/services/sprites/reference.test.js@@ -373,6 +373,53 @@ describe('startReferenceGeneration', () => {})).rejects.toMatchObject({ code: 'CANDIDATE_TARGET_MISMATCH', status: 400 });});+ it('threads a correction prompt into the main-reference derive and its tag (#3134)', async () => {+ const id = newId();+ await createCharacter(id);+ await lockTurnaround(id);+ enqueueJob.mockClear();+ await startReferenceGeneration(id, { target: 'main', correctionPrompt: ' the cloak hem is cut off ' });+ const call = enqueueJob.mock.calls[0][0];+ expect(call.params.prompt)+ .toContain('Important correction — apply this over the attached turnaround: the cloak hem is cut off');+ expect(call.params.spriteRef.correctionPrompt).toBe('the cloak hem is cut off');+ });++ it('leaves a blank main-reference correction byte-identical to a blind re-roll (#3134)', async () => {+ const id = newId();+ await createCharacter(id);+ await lockTurnaround(id);+ enqueueJob.mockClear();+ await startReferenceGeneration(id, { target: 'main' });+ const blind = enqueueJob.mock.calls[0][0].params.prompt;+ enqueueJob.mockClear();+ await startReferenceGeneration(id, { target: 'main', correctionPrompt: ' ' });+ const call = enqueueJob.mock.calls[0][0];+ expect(call.params.prompt).toBe(blind);+ expect(call.params.spriteRef).not.toHaveProperty('correctionPrompt');+ });++ it('applies a correction alongside the ambient main\'s full-replace design prompt (#3134)', async () => {+ const id = 'grove-correction';+ await records.createRecord({ kind: 'place', name: 'Old Grove' }, id);+ enqueueJob.mockClear();+ await startReferenceGeneration(id, {+ target: 'main', designPrompt: 'a willow by a pond', correctionPrompt: ' the trunk leans too far right ',+ });+ const call = enqueueJob.mock.calls[0][0];+ // Both inputs land: designPrompt replaces the design, the correction is additive.+ expect(call.params.prompt).toContain('Design: a willow by a pond');+ expect(call.params.prompt)+ .toContain('Important correction — apply this over the attached reference: the trunk leans too far right');+ expect(call.params.spriteRef.correctionPrompt).toBe('the trunk leans too far right');++ enqueueJob.mockClear();+ await startReferenceGeneration(id, { target: 'main', designPrompt: 'a willow by a pond', correctionPrompt: ' ' });+ const blank = enqueueJob.mock.calls[0][0];+ expect(blank.params.prompt).not.toContain('Important correction');+ expect(blank.params.spriteRef).not.toHaveProperty('correctionPrompt');+ });+it('omits the correction from the tag when blank', async () => {const id = newId();await createCharacter(id);diff --git a/server/services/sprites/scanner.js b/server/services/sprites/scanner.jsindex 5d6006c116..05fab92563 100644--- a/server/services/sprites/scanner.js+++ b/server/services/sprites/scanner.js@@ -17,7 +17,7 @@ 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 } from './prompts.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';@@ -92,13 +92,6 @@ const lockedAnchorFor = (manifest, direction) => {return anchor?.status === 'locked' && anchor.path ? anchor : null;};-function scannerPrompt({ name, direction, chromaKey }) {- return `Create a short, seamless scanner action for ${name}, facing ${direction}. `- + 'The character raises a handheld scanner, makes one deliberate sweep, then returns to the exact starting pose. '- + `Keep the character centered, full body visible, and animate only over a solid ${chromaKey} background. `- + 'No text, UI, scenery, camera movement, cuts, or additional characters.';-}-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`@@ -125,6 +118,9 @@ async function startScannerGenerationImpl(recordId, body) {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');@@ -156,6 +152,7 @@ async function startScannerGenerationImpl(recordId, body) {animationInputPath: `${runRel}/generated/input-anchor-chroma.png`,animationInputSha256: inputSha256,animationInputPreparation: preparation,+ ...(correctionPrompt ? { correctionPrompt } : {}),createdAt: new Date().toISOString(),};await saveRun(recordId, run);@@ -165,7 +162,12 @@ async function startScannerGenerationImpl(recordId, body) {generatedAbs,videoAbs,grokPath: settings.imageGen?.grok?.grokPath,- task: scannerTask({ prompt: scannerPrompt({ name: record.name, direction, chromaKey }), inputAbs, videoAbs, duration }),+ 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 };diff --git a/server/services/sprites/scanner.test.js b/server/services/sprites/scanner.test.jsindex cd815e2a95..a1f9c8b63c 100644--- a/server/services/sprites/scanner.test.js+++ b/server/services/sprites/scanner.test.js@@ -97,4 +97,30 @@ describe('scanner animation track', () => {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/walk.js b/server/services/sprites/walk.jsindex f4ae9ed52b..8a85615eaf 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -1023,7 +1023,12 @@ async function startWalkGenerationImpl(recordId, body) {// resamples/labels the cycle afterward. Resolved from the set target above and// stored on the run so the completion hook's packageRun (and any later// reprocess) applies exactly what the set is pinned to.- const prompt = buildWalkVideoPrompt({ name: record.name, direction, chromaKey });+ // Optional re-roll note (#3134): appended to the motion prompt so a second+ // render can be told what the first got wrong. Trimmed here and stamped on the+ // run record below only when non-empty, so a blank note leaves both the prompt+ // and the persisted run byte-identical to a blind regenerate.+ const correctionPrompt = typeof body.correctionPrompt === 'string' ? body.correctionPrompt.trim() : '';+ const prompt = buildWalkVideoPrompt({ name: record.name, direction, chromaKey, correctionPrompt });const videoAbs = join(generatedAbs, 'source-video.mp4');const grokPath = settings.imageGen?.grok?.grokPath;@@ -1053,6 +1058,7 @@ async function startWalkGenerationImpl(recordId, body) {animationInputPath: `${runRel}/generated/input-anchor-chroma.png`,animationInputSha256: inputSha256,animationInputPreparation: preparation,+ ...(correctionPrompt ? { correctionPrompt } : {}),createdAt: now,};await saveRunRecord(recordId, run);diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex ce06e6edeb..764c7c55e8 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -349,6 +349,34 @@ describe('startWalkGeneration', () => {expect(runs[0].animationInputPreparation).toBe('composited-over-solid-chroma-matte');});+ it('appends a trimmed correction note to the motion prompt and stamps it on the run (#3134)', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const { runId } = await startWalkGeneration(id, {+ direction: 'east', correctionPrompt: ' the legs barely lift ',+ });+ expect(executeTuiRun.mock.calls[0][0].prompt)+ .toContain('Important correction — apply this over the attached source image: the legs barely lift');+ // Persisted on the run so the provenance rebuild can reproduce it.+ const { runs } = await getWalkState(id);+ expect(runs.find((r) => r.id === runId).correctionPrompt).toBe('the legs barely lift');+ });++ it('leaves a blank correction note out of the prompt and the run record (#3134)', async () => {+ // The TUI task is `<motion prompt>\n\n<per-run input/output paths>`, so+ // compare the motion prompt only — the paths legitimately differ per run.+ const motionPrompt = () => executeTuiRun.mock.calls[0][0].prompt.split('\n\n')[0];+ const plain = await characterWithLockedAnchors(newId(), ['east']);+ await startWalkGeneration(plain, { direction: 'east' });+ const blindPrompt = motionPrompt();+ executeTuiRun.mockClear();++ const blank = await characterWithLockedAnchors(newId(), ['east']);+ const { runId: blankRun } = await startWalkGeneration(blank, { direction: 'east', correctionPrompt: ' ' });+ expect(motionPrompt()).toBe(blindPrompt);+ const { runs } = await getWalkState(blank);+ expect(runs.find((r) => r.id === blankRun)).not.toHaveProperty('correctionPrompt');+ });+it('honors duration 10 (passed to the grok task)', async () => {const id = await characterWithLockedAnchors(newId(), []);const result = await startWalkGeneration(id, { direction: 'south', duration: 10 });