Skip to content

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

refactor([issue-2979]): dedupe fringe math, share the seed-artifact picker, fix prompt provenance

[._.]/ Adam Eivy64cb8445c83d
diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsx
index 66fefd3f16..24dcc1adb0 100644
--- a/client/src/components/sprites/ReferenceWorkflow.jsx
+++ b/client/src/components/sprites/ReferenceWorkflow.jsx
@@ -23,6 +23,10 @@ import CorrectionNote, { correctionPromptPayload } from './CorrectionNote.jsx';
// import server modules).
const CHROMA_KEYS = ['#FF00FF', '#00FF00', '#0000FF'];
+// Lock confirmations for the two directionless identity artifacts; every other
+// target is a named direction.
+const LOCK_TOAST = { turnaround: 'Turnaround sheet frozen', main: 'Main reference frozen' };
+
// Thin alias so the existing call sites keep their `className` semantics
// (sizing on the box) while the checkerboard + pixelation rules live in one
// place — see SpritePreview. Every reference-set image is click-to-enlarge
@@ -200,9 +204,7 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
delete next[candidate.path];
return next;
});
- toast.success(target === 'turnaround' ? 'Turnaround sheet frozen'
- : target === 'main' ? 'Main reference frozen'
- : `Anchor ${target} locked`);
+ toast.success(LOCK_TOAST[target] || `Anchor ${target} locked`);
onChanged();
}, { errorMessage: 'Lock failed' });
@@ -381,7 +383,9 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
className="flex items-center gap-1.5 px-3 py-1 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white rounded text-sm"
>
{pendingJobs.turnaround ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}
- {pendingJobs.turnaround ? 'Rendering…' : backfilling ? 'Generate from locked main' : 'Generate candidate'}
+ {pendingJobs.turnaround ? 'Rendering…'
+ : backfilling ? 'Generate from locked main'
+ : (candidatesByTarget.turnaround || []).length ? 'Regenerate' : 'Generate candidate'}
</button>
</div>
{(candidatesByTarget.turnaround || []).length > 0 && (
@@ -502,7 +506,10 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
/>
<button
onClick={() => generate(anchor.direction)}
- disabled={!mode || !!pendingJobs[anchor.direction]}
+ // Gated on the sheet, matching the server's
+ // TURNAROUND_NOT_LOCKED 409 and the note above — a
+ // pre-#2979 character must backfill one first.
+ disabled={!mode || !turnaroundLocked || !!pendingJobs[anchor.direction]}
className="flex items-center gap-1 w-full justify-center px-2 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50"
>
{pendingJobs[anchor.direction]
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 71460da0b0..6b849573d4 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -3,7 +3,7 @@ import { ServerError } from './errorHandler.js';
import { partialWithoutDefaults, emptyToUndefined, emptyToNull } from './zodCompat.js';
import { WORK_TRACKERS } from './workTracker.js';
import { SPRITE_ID_PATTERN, SPRITE_RECORD_KINDS } from '../services/sprites/recordsLogic.js';
-import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS } from '../services/sprites/prompts.js';
+import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS, TURNAROUND_ID } from '../services/sprites/prompts.js';
import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';
import {
WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT, WALK_MIN_FPS, WALK_MAX_FPS,
@@ -1041,7 +1041,7 @@ export const spriteCreateSchema = z.object({
// 'turnaround' is the identity root of the turnaround-first workflow (#2979) —
// generated and locked before the main, which the anchors then descend from.
-const spriteReferenceTargetSchema = z.enum(['turnaround', 'main', ...ANCHOR_DIRECTIONS]);
+const spriteReferenceTargetSchema = z.enum([TURNAROUND_ID, 'main', ...ANCHOR_DIRECTIONS]);
// Multipart callers send numbers as form-field strings — coerce before range
// checks ('' → undefined so an empty field doesn't become 0).
diff --git a/server/services/sprites/assetPrompt.js b/server/services/sprites/assetPrompt.js
index 4a7f21a1be..1c608d6718 100644
--- a/server/services/sprites/assetPrompt.js
+++ b/server/services/sprites/assetPrompt.js
@@ -30,7 +30,7 @@ import { spriteDir, resolveSpriteAssetPath, RUN_DIR_MATCH } from './paths.js';
import { getRecord } from './records.js';
import { loadManifest } from './reference.js';
import {
- buildMainReferencePrompt, buildAnchorPrompt, buildWalkVideoPrompt, buildTurnaroundPrompt,
+ buildMainReferencePrompt, buildAnchorPrompt, buildWalkVideoPrompt, buildTurnaroundPrompt, TURNAROUND_ID,
} from './prompts.js';
import { DEFAULT_CHROMA_KEY } from './chromaKey.js';
@@ -41,18 +41,22 @@ const CANDIDATE_RE = /^reference\/candidates\/(.+)\.png$/i;
* source }` result — the stored literal prompt when captured, otherwise a
* faithful rebuild from the parameters the sidecar did record.
*/
-function fromCandidateSidecar(sidecar, name, { fromTurnaround = false } = {}) {
+function fromCandidateSidecar(sidecar, name, fromTurnaround = false) {
if (!sidecar) return null;
if (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 prompt = sidecar.target === 'turnaround'
- ? buildTurnaroundPrompt({ name, designPrompt: sidecar.designPrompt, chromaKey: sidecar.chromaKey })
- : sidecar.target === 'main'
- ? buildMainReferencePrompt({ name, designPrompt: sidecar.designPrompt, chromaKey: sidecar.chromaKey, fromTurnaround })
- : buildAnchorPrompt({ name, direction: sidecar.direction || sidecar.target, chromaKey: sidecar.chromaKey, fromTurnaround });
- return { prompt, designPrompt: sidecar.designPrompt || null, source: 'candidate-reconstructed' };
+ const { designPrompt, chromaKey } = sidecar;
+ let prompt;
+ if (sidecar.target === TURNAROUND_ID) {
+ prompt = buildTurnaroundPrompt({ name, designPrompt, chromaKey });
+ } else if (sidecar.target === 'main') {
+ prompt = buildMainReferencePrompt({ name, designPrompt, chromaKey, fromTurnaround });
+ } else {
+ prompt = buildAnchorPrompt({ name, direction: sidecar.direction || sidecar.target, chromaKey, fromTurnaround });
+ }
+ return { prompt, designPrompt: designPrompt || null, source: 'candidate-reconstructed' };
}
async function candidateSidecarFor(recordId, candidateStem) {
@@ -81,23 +85,28 @@ export async function resolveSpriteAssetPrompt(recordId, relPath) {
if (/^reference\//i.test(relPath)) {
const manifest = await loadManifest(recordId);
if (manifest) {
- // Everything below the sheet was derived from it (#2979), so a rebuild
- // must use the turnaround-aware copy or it won't match what was sent.
- const derived = { fromTurnaround: manifest.turnaround?.locked === true };
const turnaround = manifest.turnaround;
- // `manifest.chromaKey` is the key FROZEN at a lock — which, when
- // auto-selected (user didn't pin), differs from the key the artifact that
- // TRIGGERED that selection was generated against: it was rendered before
- // the key existed, so its prompt embedded the default. Exactly one lock
- // per character freezes the key — the turnaround's on a turnaround-first
- // record, the main's on a legacy one (including a backfilled sheet, which
- // locks later and inherits) — so compare lock times to find it.
- const wasFreezer = (artifact) => {
- const other = artifact === turnaround ? manifest.mainReference : turnaround;
- return !other?.lockedAt || !artifact?.lockedAt || artifact.lockedAt <= other.lockedAt;
- };
- const renderKey = (artifact) => (
- manifest.chromaKeyAutoSelected && wasFreezer(artifact) ? DEFAULT_CHROMA_KEY : manifest.chromaKey
+ const main = manifest.mainReference;
+ // Both rebuild inputs below turn on the order the two identity artifacts
+ // were locked in, so express that once. `lockedBefore(a, b)` is true when
+ // `a` was frozen first (or `b` was never frozen at all).
+ const lockedBefore = (a, b) => !b?.lockedAt || !a?.lockedAt || a.lockedAt <= b.lockedAt;
+ // 1. Was this artifact derived FROM the sheet? Only if the sheet was
+ // already frozen when it locked — an anchor frozen before a legacy
+ // record backfilled its sheet was drawn from the main, so rebuilding
+ // it with the sheet-aware copy would misstate what was attached.
+ const fromTurnaround = (artifact) => (
+ turnaround?.locked === true && !lockedBefore(artifact, turnaround)
+ );
+ // 2. `manifest.chromaKey` is the key FROZEN at a lock — which, when
+ // auto-selected (user didn't pin), differs from the key the artifact
+ // that TRIGGERED that selection was generated against: it was rendered
+ // before the key existed, so its prompt embedded the default. Exactly
+ // one lock per character freezes the key — the turnaround's on a
+ // turnaround-first record, the main's on a legacy one (a backfilled
+ // sheet locks later and inherits).
+ const renderKey = (artifact, other) => (
+ manifest.chromaKeyAutoSelected && lockedBefore(artifact, other) ? DEFAULT_CHROMA_KEY : manifest.chromaKey
);
if (turnaround?.path === relPath) {
const stem = candidateStem(turnaround.lockedFrom);
@@ -106,25 +115,24 @@ export async function resolveSpriteAssetPrompt(recordId, relPath) {
prompt: buildTurnaroundPrompt({
name,
designPrompt: manifest.designPrompt,
- chromaKey: renderKey(turnaround),
+ chromaKey: renderKey(turnaround, main),
}),
designPrompt: manifest.designPrompt || null,
source: 'reference-turnaround',
};
}
- const main = manifest.mainReference;
if (main?.path === relPath) {
// Prefer the frozen candidate's literal prompt; fall back to a rebuild
// from the manifest's own recorded design prompt + key.
const stem = candidateStem(main.lockedFrom);
- const fromCandidate = stem ? fromCandidateSidecar(await candidateSidecarFor(recordId, stem), name, derived) : null;
+ const fromCandidate = stem ? fromCandidateSidecar(await candidateSidecarFor(recordId, stem), name, fromTurnaround(main)) : null;
// Fallback (source candidate sidecar gone): rebuild from the manifest.
return fromCandidate || {
prompt: buildMainReferencePrompt({
name,
designPrompt: manifest.designPrompt,
- chromaKey: renderKey(main),
- ...derived,
+ chromaKey: renderKey(main, turnaround),
+ fromTurnaround: fromTurnaround(main),
}),
designPrompt: manifest.designPrompt || null,
source: 'reference-main',
@@ -133,11 +141,11 @@ export async function resolveSpriteAssetPrompt(recordId, relPath) {
const anchor = (manifest.anchors || []).find((a) => a.path === relPath);
if (anchor) {
const stem = candidateStem(anchor.lockedFrom);
- const fromCandidate = stem ? fromCandidateSidecar(await candidateSidecarFor(recordId, stem), name, derived) : null;
+ const fromCandidate = stem ? fromCandidateSidecar(await candidateSidecarFor(recordId, stem), name, fromTurnaround(anchor)) : null;
return fromCandidate || {
// An anchor always locks after the key is frozen, so the frozen key
// is what its prompt embedded — no default-key caveat here.
- prompt: buildAnchorPrompt({ name, direction: anchor.direction, chromaKey: manifest.chromaKey, ...derived }),
+ prompt: buildAnchorPrompt({ name, direction: anchor.direction, chromaKey: manifest.chromaKey, fromTurnaround: fromTurnaround(anchor) }),
designPrompt: null,
source: 'reference-anchor',
};
diff --git a/server/services/sprites/normalize.js b/server/services/sprites/normalize.js
index 5edce272a0..9afa9aca37 100644
--- a/server/services/sprites/normalize.js
+++ b/server/services/sprites/normalize.js
@@ -107,6 +107,26 @@ function buildKeyDecontaminator(maskKeyHex, canvasKeyHex) {
};
}
+/**
+ * Write one masked foreground pixel into the destination canvas, shifting it
+ * off the old key when the composite re-keys onto a different one. Shared by
+ * both compositors (the reframing `normalizeFromAnalysis` and the
+ * geometry-preserving `recompositeOnKey`) so the fringe math — the subtlest
+ * code in this module — has exactly one definition.
+ */
+function writeForegroundPixel(canvas, dstI, data, srcI, decon) {
+ if (!decon) {
+ canvas[dstI] = data[srcI];
+ canvas[dstI + 1] = data[srcI + 1];
+ canvas[dstI + 2] = data[srcI + 2];
+ return;
+ }
+ const share = decon.share(data, srcI);
+ canvas[dstI] = clampByte(data[srcI] + share * decon.delta[0]);
+ canvas[dstI + 1] = clampByte(data[srcI + 1] + share * decon.delta[1]);
+ canvas[dstI + 2] = clampByte(data[srcI + 2] + share * decon.delta[2]);
+}
+
/**
* Histogram the foreground (non-key) pixels of an analysis, quantized to 4
* bits per channel so anti-aliased shades collapse into their parent color.
@@ -166,16 +186,7 @@ export async function normalizeFromAnalysis(analysis, src, dest, canvasKeyHex) {
if (!mask[y * width + x]) continue;
const srcI = (y * width + x) * 3;
const dstI = ((offsetY + (y - bbox.top)) * side + offsetX + (x - bbox.left)) * 3;
- if (decon) {
- const share = decon.share(data, srcI);
- canvas[dstI] = clampByte(data[srcI] + share * decon.delta[0]);
- canvas[dstI + 1] = clampByte(data[srcI + 1] + share * decon.delta[1]);
- canvas[dstI + 2] = clampByte(data[srcI + 2] + share * decon.delta[2]);
- } else {
- canvas[dstI] = data[srcI];
- canvas[dstI + 1] = data[srcI + 1];
- canvas[dstI + 2] = data[srcI + 2];
- }
+ writeForegroundPixel(canvas, dstI, data, srcI, decon);
}
}
await sharp(canvas, { raw: { width: side, height: side, channels: 3 } }).png().toFile(dest);
@@ -210,17 +221,8 @@ export async function recompositeOnKey(analysis, src, dest, canvasKeyHex) {
const decon = buildKeyDecontaminator(maskKey, canvasKeyHex);
for (let p = 0; p < width * height; p++) {
if (!mask[p]) continue;
- const i = p * 3;
- if (decon) {
- const share = decon.share(data, i);
- canvas[i] = clampByte(data[i] + share * decon.delta[0]);
- canvas[i + 1] = clampByte(data[i + 1] + share * decon.delta[1]);
- canvas[i + 2] = clampByte(data[i + 2] + share * decon.delta[2]);
- } else {
- canvas[i] = data[i];
- canvas[i + 1] = data[i + 1];
- canvas[i + 2] = data[i + 2];
- }
+ // Geometry is preserved, so source and destination indices coincide.
+ writeForegroundPixel(canvas, p * 3, data, p * 3, decon);
}
await sharp(canvas, { raw: { width, height, channels: 3 } }).png().toFile(dest);
return { width, height };
diff --git a/server/services/sprites/prompts.js b/server/services/sprites/prompts.js
index fde4ec9008..934d814128 100644
--- a/server/services/sprites/prompts.js
+++ b/server/services/sprites/prompts.js
@@ -62,13 +62,10 @@ export function keyColorPhrase(hex) {
// read a given facing from.
export const TURNAROUND_VIEWS = ['south', 'east', 'north', 'west'];
-// How each turnaround panel is described inside the sheet prompt.
-const TURNAROUND_PANEL_LABEL = {
- south: 'front view, facing the viewer',
- east: 'right-side profile, facing due east',
- north: 'back view, facing directly away from the viewer (no face)',
- west: 'left-side profile, facing due west',
-};
+// The sheet's candidate/asset id — the `anchorIdForDirection` analogue for the
+// one reference artifact that has no direction. Lives here with the other
+// target vocabulary so validation.js and the services share one spelling.
+export const TURNAROUND_ID = 'turnaround';
/**
* Stage-0 prompt (issue #2979): the character turnaround sheet — the identity
@@ -80,8 +77,12 @@ export function buildTurnaroundPrompt({ name, designPrompt, chromaKey }) {
const description = (typeof designPrompt === 'string' && designPrompt.trim())
? designPrompt.trim()
: 'Use the attached visual reference as the character design.';
+ // Panels are described with the SAME facing clauses the derive prompts use
+ // (`fromTurnaroundClause` below tells the model to find "the panel that shows
+ // the character <facing>") — two vocabularies would let the sheet's labels
+ // drift out of sync with the prompt that points into it.
const panels = TURNAROUND_VIEWS
- .map((view, i) => `${i + 1}) ${TURNAROUND_PANEL_LABEL[view] || view}`)
+ .map((view, i) => `${i + 1}) ${REFERENCE_FACING[view] || view}`)
.join(', ');
return (
`Create a character turnaround model sheet for a game character named ${name}. `
diff --git a/server/services/sprites/prompts.test.js b/server/services/sprites/prompts.test.js
index 3c1478af2d..c00760c6a2 100644
--- a/server/services/sprites/prompts.test.js
+++ b/server/services/sprites/prompts.test.js
@@ -94,10 +94,9 @@ describe('buildTurnaroundPrompt (#2979)', () => {
expect(p).toContain('named Scout');
expect(p).toContain('a wiry ranger');
expect(p).toContain(`exactly ${TURNAROUND_VIEWS.length} full-body figures`);
- expect(p).toContain('1) front view, facing the viewer');
- expect(p).toContain('2) right-side profile');
- expect(p).toContain('3) back view');
- expect(p).toContain('4) left-side profile');
+ // Panels reuse REFERENCE_FACING so the sheet's labels and the derive
+ // prompt that points into it can't drift apart.
+ TURNAROUND_VIEWS.forEach((view, i) => expect(p).toContain(`${i + 1}) ${REFERENCE_FACING[view]}`));
// The constraint the sheet exists to enforce.
expect(p).toContain('SAME anatomical side');
expect(p).toContain('green (#00FF00) background');
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index d7a3747e3e..3c2afbf903 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -33,7 +33,7 @@ import { getSettings } from '../settings.js';
import { getRecord, updateRecord, listRecords, createCharacter } from './records.js';
import { spriteDir, resolveSpriteAssetPath, listSpriteAssets } from './paths.js';
import {
- SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, anchorIdForDirection, TURNAROUND_VIEWS,
+ SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, anchorIdForDirection, TURNAROUND_VIEWS, TURNAROUND_ID,
buildMainReferencePrompt, buildAnchorPrompt, buildTurnaroundPrompt,
} from './prompts.js';
import { pickChromaKey, keyProximityWarning, CHROMA_KEY_HEXES, DEFAULT_CHROMA_KEY } from './chromaKey.js';
@@ -49,9 +49,9 @@ import {
const ANCHOR_DEFAULT_STRENGTH = 0.8;
const UPLOAD_DEFAULT_STRENGTH = 0.65;
-// The turnaround sheet's candidate/asset id — the `anchorIdForDirection`
-// analogue for the one reference artifact that has no direction.
-const TURNAROUND_ID = 'turnaround';
+// Sidecarless turnaround candidate (crash between the PNG copy and the sidecar
+// write) — module-scope so the candidate listing doesn't recompile it per file.
+const TURNAROUND_CANDIDATE_RE = /^turnaround-candidate-\d+\.png$/;
// Manifests seeded from #2979 onward are turnaround-first: the sheet is the
// identity root, the main descends from it, and so does every anchor. A v1
@@ -232,7 +232,7 @@ export async function getReferenceSet(recordId) {
// Sidecarless (crash between copy and sidecar write): infer the target
// from the filename so the client can't group it under the wrong slot.
const inferredDirection = /^walk-(.+)-candidate-\d+\.png$/.exec(name)?.[1] || null;
- const inferred = new RegExp(`^${TURNAROUND_ID}-candidate-\\d+\\.png$`).test(name)
+ const inferred = TURNAROUND_CANDIDATE_RE.test(name)
? TURNAROUND_ID
: (inferredDirection === 'south' ? 'main' : inferredDirection);
return {
@@ -282,20 +282,21 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
let correctionPrompt;
const turnaroundLocked = manifest.turnaround?.locked === true;
+ const designPrompt = typeof body.designPrompt === 'string' ? body.designPrompt.trim() : '';
+ // A render that establishes the character's look needs SOME input: a prompt,
+ // an uploaded image, a gallery pick, or another sprite's reference to seed
+ // from. `alsoSeeded` covers a source the branch supplies itself (the legacy
+ // main a backfilled sheet expands, the sheet the main descends from).
+ const requireDesignInput = (alsoSeeded = false) => {
+ if (designPrompt || alsoSeeded || upload || body.initImageGalleryFile || body.initImageSpriteId) return;
+ throw new ServerError('Provide a design prompt and/or a reference image', { status: 400, code: 'DESIGN_INPUT_REQUIRED' });
+ };
if (target === TURNAROUND_ID) {
if (turnaroundLocked) {
throw new ServerError('Turnaround sheet is locked — corrections require a new character version, never regeneration', { status: 409, code: 'REFERENCE_LOCKED' });
}
- const designPrompt = typeof body.designPrompt === 'string' ? body.designPrompt.trim() : '';
- // The sheet is the first render, so it needs SOME design input: a prompt,
- // an uploaded image, a gallery pick, another sprite's reference to seed
- // from — or, on a legacy record, the already-locked main it backfills from.
- const backfillFrom = !designPrompt && manifest.mainReference.locked ? manifest.mainReference.path : null;
- const hasInitSource = !!upload || !!body.initImageGalleryFile || !!body.initImageSpriteId || !!backfillFrom;
- if (!designPrompt && !hasInitSource) {
- throw new ServerError('Provide a design prompt and/or a reference image', { status: 400, code: 'DESIGN_INPUT_REQUIRED' });
- }
+ requireDesignInput(manifest.mainReference.locked);
anchorId = TURNAROUND_ID;
prompt = buildTurnaroundPrompt({
name: record.name,
@@ -307,17 +308,17 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
// one view we already have into the full sheet rather than inventing a new
// character from text.
if (!initImagePath && manifest.mainReference.locked) {
- initImagePath = resolveSpriteAssetPath(recordId, manifest.mainReference.path);
- if (!await pathExists(initImagePath)) {
- throw new ServerError('Locked main reference file is missing on disk', { status: 500, code: 'MAIN_REFERENCE_MISSING' });
- }
+ initImagePath = await requireLockedArtifactPath(recordId, manifest.mainReference.path, {
+ message: 'Locked main reference file is missing on disk', code: 'MAIN_REFERENCE_MISSING',
+ });
designReferencePath = manifest.mainReference.path;
}
if (initImagePath) initImageStrength ??= UPLOAD_DEFAULT_STRENGTH;
if (designPrompt) manifest.designPrompt = designPrompt;
- // Only the turnaround/main branches mutate (or may have just seeded) the
- // manifest — the anchor branch requires locked predecessors, so its
- // manifest already exists on disk unchanged.
+ // The sheet is the first render, so this save may be persisting a manifest
+ // that was only just seeded — it runs unconditionally. The later branches
+ // require locked predecessors, so their manifest is already on disk and
+ // only needs writing back when the design prompt actually changed.
await saveManifest(recordId, manifest);
} else if (target === 'main') {
if (manifest.mainReference.locked) {
@@ -330,7 +331,6 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
if (!turnaroundLocked && isTurnaroundFirst(manifest)) {
throw new ServerError('Lock the turnaround sheet before deriving the main reference', { status: 409, code: 'TURNAROUND_NOT_LOCKED' });
}
- const designPrompt = typeof body.designPrompt === 'string' ? body.designPrompt.trim() : '';
anchorId = anchorIdForDirection('south');
direction = 'south';
prompt = buildMainReferencePrompt({
@@ -343,17 +343,18 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
initImagePath = await requireLockedTurnaroundPath(recordId, manifest);
initImageStrength ??= ANCHOR_DEFAULT_STRENGTH;
} else {
- // Legacy v1 main: a prompt, an uploaded image, a gallery pick, or another
- // sprite's reference — one of them is required.
- const hasInitSource = !!upload || !!body.initImageGalleryFile || !!body.initImageSpriteId;
- if (!designPrompt && !hasInitSource) {
- throw new ServerError('Provide a design prompt and/or a reference image', { status: 400, code: 'DESIGN_INPUT_REQUIRED' });
- }
+ // Legacy v1 main, still on the main-first flow: a prompt, an uploaded
+ // image, a gallery pick, or another sprite's reference is required.
+ requireDesignInput();
({ initImagePath, designReferencePath } = await resolveSeedSource(recordId, body, upload));
if (initImagePath) initImageStrength ??= UPLOAD_DEFAULT_STRENGTH;
}
- if (designPrompt) manifest.designPrompt = designPrompt;
- await saveManifest(recordId, manifest);
+ // Nothing else in this branch mutates the manifest, so skip the write —
+ // and its per-record serialization — on the common no-prompt re-roll.
+ if (designPrompt) {
+ manifest.designPrompt = designPrompt;
+ await saveManifest(recordId, manifest);
+ }
} else {
if (!ANCHOR_DIRECTIONS.includes(target)) {
throw new ServerError(`Unknown reference target: ${target}`, { status: 400, code: 'INVALID_TARGET' });
@@ -424,19 +425,32 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
}
/**
- * The locked turnaround sheet as an on-disk init image. Every render that
- * descends from the sheet routes through here so a manifest that claims a lock
- * whose file vanished fails loudly instead of silently degrading to
- * text-to-image (which would reintroduce the invented-sides bug).
+ * A locked artifact's record-relative path resolved to an on-disk init image.
+ * Every render that descends from a locked reference routes through here so a
+ * manifest claiming a lock whose file vanished fails loudly instead of silently
+ * degrading to text-to-image (which would reintroduce the invented-sides bug).
*/
-async function requireLockedTurnaroundPath(recordId, manifest) {
- const abs = resolveSpriteAssetPath(recordId, manifest.turnaround.path);
- if (!await pathExists(abs)) {
- throw new ServerError('Locked turnaround sheet file is missing on disk', { status: 500, code: 'TURNAROUND_MISSING' });
- }
+async function requireLockedArtifactPath(recordId, relPath, { message, code }) {
+ const abs = resolveSpriteAssetPath(recordId, relPath);
+ if (!await pathExists(abs)) throw new ServerError(message, { status: 500, code });
return abs;
}
+const requireLockedTurnaroundPath = (recordId, manifest) => requireLockedArtifactPath(
+ recordId, manifest.turnaround.path,
+ { message: 'Locked turnaround sheet file is missing on disk', code: 'TURNAROUND_MISSING' },
+);
+
+/**
+ * The locked artifact a derive should seed from: the turnaround sheet when the
+ * record has one (all sides, so accessory placement carries over), else the
+ * locked main. One definition so the "select a reference sprite" picker can
+ * never advertise a different image than the render actually attaches.
+ */
+const lockedSeedArtifact = (manifest) => (
+ [manifest?.turnaround, manifest?.mainReference].find((a) => a?.locked && a.path) || null
+);
+
/**
* Resolve the optional i2i seed image from exactly one source — an upload wins,
* then a render-history gallery pick, then another sprite's locked reference.
@@ -480,15 +494,13 @@ async function resolveSeedSource(recordId, body, upload) {
async function resolveSourceReference(sourceId) {
// loadManifest, not getReferenceSet — we only need the locked artifacts, and
// the latter also enumerates + reads every candidate sidecar (wasted here).
- const manifest = await loadManifest(sourceId);
- const best = [manifest?.turnaround, manifest?.mainReference].find((a) => a?.locked && a.path);
+ const best = lockedSeedArtifact(await loadManifest(sourceId));
if (!best) {
throw new ServerError('The source sprite has no locked reference to seed from', { status: 400, code: 'SOURCE_REFERENCE_MISSING' });
}
- const absPath = resolveSpriteAssetPath(sourceId, best.path);
- if (!await pathExists(absPath)) {
- throw new ServerError('The source sprite reference file is missing on disk', { status: 500, code: 'SOURCE_REFERENCE_FILE_MISSING' });
- }
+ const absPath = await requireLockedArtifactPath(sourceId, best.path, {
+ message: 'The source sprite reference file is missing on disk', code: 'SOURCE_REFERENCE_FILE_MISSING',
+ });
return { absPath, relPath: best.path };
}
@@ -509,12 +521,13 @@ export async function listReferenceSources() {
for (const r of records) {
if (r.kind !== 'character' || r.deleted) continue;
const manifest = await loadManifest(r.id);
- const turnaround = manifest?.turnaround?.locked && manifest.turnaround.path ? manifest.turnaround.path : null;
- const main = manifest?.mainReference?.locked && manifest.mainReference.path ? manifest.mainReference.path : null;
- const path = turnaround || main;
- if (path) {
+ // Same picker resolveSourceReference uses, so the advertised image is
+ // exactly the one a seed will attach.
+ const seed = lockedSeedArtifact(manifest);
+ if (seed) {
+ const turnaround = manifest?.turnaround?.locked ? manifest.turnaround.path : null;
out.push({
- id: r.id, name: r.name, kind: r.kind, path, turnaroundPath: turnaround, mainPath: main,
+ id: r.id, name: r.name, kind: r.kind, path: seed.path, turnaroundPath: turnaround,
});
}
}
@@ -763,8 +776,9 @@ async function lockReferenceImpl(recordId, { target, candidate, acceptClipRisk =
// Record BEFORE manifest: a crash between the two leaves the record
// updated but the manifest unlocked — recoverable by re-locking. The
// reverse order would wedge (locked manifest + stale record, with both
- // relock and key PATCH returning 409 forever).
- await updateRecord(recordId, { chromaKey: selectedKey, status: 'reference' });
+ // relock and key PATCH returning 409 forever). Skipped entirely when the
+ // turnaround lock already froze the key and set the status.
+ if (!frozenKey) await updateRecord(recordId, { chromaKey: selectedKey, status: 'reference' });
await saveManifest(recordId, manifest);
} else {
if (!ANCHOR_DIRECTIONS.includes(target)) {
diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.js
index b65d6e2462..068aea7e21 100644
--- a/server/services/sprites/reference.test.js
+++ b/server/services/sprites/reference.test.js
@@ -134,8 +134,8 @@ describe('startReferenceGeneration', () => {
expect(call.params.prompt).toContain('a wiry ranger');
expect(call.params.prompt).toContain('magenta (#FF00FF)');
// The panels, in order, and the constraint the sheet exists to enforce.
- expect(call.params.prompt).toContain('1) front view');
- expect(call.params.prompt).toContain('3) back view');
+ expect(call.params.prompt).toContain('1) facing the viewer (front)');
+ expect(call.params.prompt).toContain('3) facing directly away from the viewer');
expect(call.params.prompt).toContain('SAME anatomical side');
expect(call.params.spriteRef).toMatchObject({
recordId: id, target: 'turnaround', anchorId: 'turnaround', chromaKey: '#FF00FF',