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
refactor([issue-2896]): apply /simplify pass — shared mode ladder, single-decode lock, service-owned create
[._.]/ Adam Eivy59f245c5246c
diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsxindex f2dc2fec78..113ad10a3f 100644--- a/client/src/components/sprites/ReferenceWorkflow.jsx+++ b/client/src/components/sprites/ReferenceWorkflow.jsx@@ -5,6 +5,8 @@ import { generateSpriteReference, lockSpriteReference, updateSpriteRecord } fromimport { getMediaJob } from '../../services/apiMediaJobs.js';import { getSettings } from '../../services/apiSystem.js';import { deriveAvailableBackends } from '../../lib/imageGenBackends.js';+import { useAsyncAction } from '../../hooks/useAsyncAction.js';+import { spriteAssetUrl } from './spriteAssets.js';// Reference workflow (issue #2896): generate main-reference candidates from// text + optional uploaded design image, freeze the approved main, then@@ -12,14 +14,14 @@ import { deriveAvailableBackends } from '../../lib/imageGenBackends.js';// source of truth for status; this component only renders it and fires the// generate/lock/override actions.+// Mirrors server/services/sprites/chromaKey.js CHROMA_KEYS (client can't+// import server modules).const CHROMA_KEYS = ['#FF00FF', '#00FF00', '#0000FF'];-const assetUrl = (recordId, relPath) => `/data/sprites/${encodeURIComponent(recordId)}/${relPath.split('/').map(encodeURIComponent).join('/')}`;-function SpriteImg({ recordId, path, className }) {return (<img- src={assetUrl(recordId, path)}+ src={spriteAssetUrl(recordId, path)}alt={path}loading="lazy"className={className}@@ -70,8 +72,6 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {const [uploadFile, setUploadFile] = useState(null);// target → jobId for in-flight renders; polled until the candidate lands.const [pendingJobs, setPendingJobs] = useState({});- const [locking, setLocking] = useState(false);- const [keySaving, setKeySaving] = useState(false);const fileInputRef = useRef(null);useEffect(() => {@@ -84,26 +84,28 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {.catch(() => setBackends([]));}, []);- // Poll in-flight render jobs; on a terminal state drop the entry and- // refresh the detail so the new candidate (or the failure) shows up.+ // Poll in-flight render jobs (parallel — they're independent); on a+ // terminal state drop the entry and refresh the detail once so the new+ // candidates (or the failure) show up. The completion hook's candidate+ // copy is same-process and millisecond-fast against the 4s poll grain, so+ // one short deferral covers the copy-vs-refetch ordering.useEffect(() => {- const jobIds = Object.values(pendingJobs);- if (jobIds.length === 0) return undefined;+ if (Object.keys(pendingJobs).length === 0) return undefined;const timer = setInterval(async () => {- for (const [target, jobId] of Object.entries(pendingJobs)) {- const job = await getMediaJob(jobId).catch(() => null);- if (!job || ['completed', 'failed', 'canceled'].includes(job.status)) {- setPendingJobs((prev) => {- const next = { ...prev };- delete next[target];- return next;- });- if (job?.status === 'failed') toast.error(`Render failed for ${target}: ${job.error || 'see media jobs'}`);- // Completed candidates land server-side via the completion hook —- // small delay so the copy is on disk before the refetch.- setTimeout(onChanged, 500);- }+ const results = await Promise.all(Object.entries(pendingJobs).map(async ([target, jobId]) => ({+ target, job: await getMediaJob(jobId).catch(() => null),+ })));+ const finished = results.filter(({ job }) => !job || ['completed', 'failed', 'canceled'].includes(job.status));+ if (finished.length === 0) return;+ setPendingJobs((prev) => {+ const next = { ...prev };+ for (const { target } of finished) delete next[target];+ return next;+ });+ for (const { target, job } of finished) {+ if (job?.status === 'failed') toast.error(`Render failed for ${target}: ${job.error || 'see media jobs'}`);}+ setTimeout(onChanged, 500);}, 4000);return () => clearInterval(timer);}, [pendingJobs, onChanged]);@@ -129,30 +131,16 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {}};- const lock = async (target, candidate) => {- setLocking(true);- try {- await lockSpriteReference(recordId, { target, candidate: candidate.path }, { silent: true });- toast.success(target === 'main' ? 'Main reference frozen' : `Anchor ${target} locked`);- onChanged();- } catch (err) {- toast.error(err?.message || 'Lock failed');- } finally {- setLocking(false);- }- };+ const [lock, locking] = useAsyncAction(async (target, candidate) => {+ await lockSpriteReference(recordId, { target, candidate: candidate.path }, { silent: true });+ toast.success(target === 'main' ? 'Main reference frozen' : `Anchor ${target} locked`);+ onChanged();+ }, { errorMessage: 'Lock failed' });- const setChromaKey = async (hex) => {- setKeySaving(true);- try {- await updateSpriteRecord(recordId, { chromaKey: hex }, { silent: true });- onChanged();- } catch (err) {- toast.error(err?.message || 'Failed to set chroma key');- } finally {- setKeySaving(false);- }- };+ const [setChromaKey, keySaving] = useAsyncAction(async (hex) => {+ await updateSpriteRecord(recordId, { chromaKey: hex }, { silent: true });+ onChanged();+ }, { errorMessage: 'Failed to set chroma key' });const modePicker = backends.length > 0 && (<label className="flex items-center gap-2 text-xs text-gray-400">diff --git a/client/src/components/sprites/spriteAssets.js b/client/src/components/sprites/spriteAssets.jsnew file mode 100644index 0000000000..d490ed4e0c--- /dev/null+++ b/client/src/components/sprites/spriteAssets.js@@ -0,0 +1,3 @@+// Shared URL builder for sprite record assets served by the /data/sprites+// static mount — one place for the per-segment encoding rules.+export const spriteAssetUrl = (recordId, relPath) => `/data/sprites/${encodeURIComponent(recordId)}/${relPath.split('/').map(encodeURIComponent).join('/')}`;diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex d0ca6a78aa..0bb42c5941 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -4,6 +4,8 @@ import { PersonStanding, Package, Download, FolderOpen, X, RefreshCw, Plus } froimport toast from '../components/ui/Toast';import { listSpriteRecords, getSpriteRecord, importSprites, createSpriteRecord } from '../services/apiSprites.js';import ReferenceWorkflow from '../components/sprites/ReferenceWorkflow.jsx';+import { spriteAssetUrl } from '../components/sprites/spriteAssets.js';+import { useAsyncAction } from '../hooks/useAsyncAction.js';import { formatBytes, timeAgo } from '../utils/formatters.js';// Sprite Manager: library over imported production sprites — characters@@ -112,21 +114,13 @@ function ImportPanel({ onImported }) {function NewCharacterPanel({ onCreated }) {const [open, setOpen] = useState(false);const [name, setName] = useState('');- const [creating, setCreating] = useState(false);- const create = async () => {- setCreating(true);- try {- const record = await createSpriteRecord({ name: name.trim() });- setOpen(false);- setName('');- onCreated(record);- } catch {- // request() already toasted — keep the panel open for a retry.- } finally {- setCreating(false);- }- };+ const [create, creating] = useAsyncAction(async () => {+ const record = await createSpriteRecord({ name: name.trim() }, { silent: true });+ setOpen(false);+ setName('');+ onCreated(record);+ }, { errorMessage: 'Failed to create character' });if (!open) {return (@@ -221,7 +215,7 @@ function AssetGroups({ recordId, assets }) {</h4><div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-2">{files.map((a) => {- const url = `/data/sprites/${encodeURIComponent(recordId)}/${a.path.split('/').map(encodeURIComponent).join('/')}`;+ const url = spriteAssetUrl(recordId, a.path);return IMAGE_EXT.test(a.path) ? (<buttonkey={a.path}@@ -282,12 +276,22 @@ export default function Sprites() {listSpriteRecords().then(setRecords).catch(() => setRecords([]));}, []);+ // Stable identity — ReferenceWorkflow's poll effect depends on it, and an+ // inline arrow would tear down/recreate the interval every parent render.+ const onWorkflowChanged = useCallback(() => {+ refresh();+ setRetryTick((t) => t + 1);+ }, [refresh]);+useEffect(() => { refresh(); }, [refresh]);+ // Same-id refetches (retryTick bumps from locks/renders/imports) keep the+ // current detail rendered — nulling it would unmount ReferenceWorkflow and+ // drop its in-flight render polling. Only an actual id switch clears.useEffect(() => {if (!id) { setDetail(null); setDetailState('idle'); return undefined; }let stale = false; // rapid A→B clicks: a late A response must not clobber B- setDetail(null);+ setDetail((prev) => (prev?.record?.id === id ? prev : null));setDetailState('loading');getSpriteRecord(id, { silent: true }).then((d) => { if (!stale) { setDetail(d); setDetailState('loaded'); } })@@ -353,7 +357,7 @@ export default function Sprites() {<ReferenceWorkflowrecord={detail.record}reference={detail.reference}- onChanged={() => { refresh(); setRetryTick((t) => t + 1); }}+ onChanged={onWorkflowChanged}/>)}{detail.assets.length === 0 ? (diff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex 86f4488896..f00f641bb7 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -22,11 +22,10 @@ import {} from '../lib/validation.js';import { optionalUploadFields } from '../lib/multipart.js';import {- listRecords, getRecordWithAssets, createRecord, updateRecord, deleteRecord,+ listRecords, getRecordWithAssets, createCharacter, updateRecord, deleteRecord,} from '../services/sprites/records.js';import { importFromSource } from '../services/sprites/importer.js';import { getReferenceSet, startReferenceGeneration, lockReference } from '../services/sprites/reference.js';-import { SPRITE_ID_PATTERN } from '../services/sprites/recordsLogic.js';const router = Router();@@ -38,21 +37,15 @@ const referenceUpload = optionalUploadFields(['referenceImage'], {fileFilter: (file) => ACCEPTED_REFERENCE_MIME.has(file.mimetype),});-const slugify = (name) => name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64);-router.get('/', asyncHandler(async (_req, res) => {res.json(await listRecords());}));// Create a character record — the entry point of the reference workflow.-// Props families remain import-only.+// Id derivation and the kind live in the service (createCharacter).router.post('/', asyncHandler(async (req, res) => {const input = validateRequest(spriteCreateSchema, req.body);- const id = input.id || slugify(input.name);- if (!SPRITE_ID_PATTERN.test(id)) {- throw new ServerError(`Cannot derive a valid sprite id from "${input.name}" — pass an explicit id`, { status: 400, code: 'INVALID_SPRITE_ID' });- }- res.status(201).json(await createRecord({ kind: 'character', name: input.name, spec: input.spec ?? null }, id));+ res.status(201).json(await createCharacter(input));}));// Import approved production assets from a source tree. A direct user actiondiff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.jsindex 84f8eab78c..e38e39901e 100644--- a/server/routes/sprites.test.js+++ b/server/routes/sprites.test.js@@ -5,7 +5,7 @@ import { request } from '../lib/testHelper.js';vi.mock('../services/sprites/records.js', () => ({listRecords: vi.fn(async () => [{ id: 'pioneer', kind: 'character', name: 'Pioneer' }]),getRecordWithAssets: vi.fn(),- createRecord: vi.fn(async (input, id) => ({ id, ...input })),+ createCharacter: vi.fn(async (input) => ({ id: input.id || 'derived', kind: 'character', ...input })),updateRecord: vi.fn(async (id, patch) => ({ id, ...patch })),deleteRecord: vi.fn(async () => ({ ok: true })),}));@@ -44,27 +44,16 @@ describe('sprites routes', () => {expect(r.body).toEqual([{ id: 'pioneer', kind: 'character', name: 'Pioneer' }]);});- it('POST / creates a character, slugifying the name into an id', async () => {+ it('POST / validates and delegates to createCharacter', async () => {const r = await request(app).post('/api/sprites').send({ name: 'Trail Hand #2' });expect(r.status).toBe(201);- expect(records.createRecord).toHaveBeenCalledWith(- { kind: 'character', name: 'Trail Hand #2', spec: null },- 'trail-hand-2',- );+ expect(records.createCharacter).toHaveBeenCalledWith({ name: 'Trail Hand #2' });});- it('POST / honors an explicit id and rejects an invalid one', async () => {- await request(app).post('/api/sprites').send({ name: 'Hero', id: 'hero-alt' });- expect(records.createRecord).toHaveBeenCalledWith(expect.anything(), 'hero-alt');-+ it('POST / rejects an invalid explicit id at the schema', async () => {const bad = await request(app).post('/api/sprites').send({ name: 'Hero', id: 'Not A Slug' });expect(bad.status).toBe(400);- });-- it('POST / 400s a name that slugifies to nothing', async () => {- const r = await request(app).post('/api/sprites').send({ name: '!!!' });- expect(r.status).toBe(400);- expect(r.body.error).toMatch(/explicit id/);+ expect(records.createCharacter).not.toHaveBeenCalled();});it('GET /:id returns record + assets + reference set for characters', async () => {diff --git a/server/services/imageGen/modes.js b/server/services/imageGen/modes.jsindex 4facc8d053..99f54d7f58 100644--- a/server/services/imageGen/modes.js+++ b/server/services/imageGen/modes.js@@ -56,3 +56,26 @@ export const describeFidelity = (strength) => {// Settings still wins. Effort is one of providerModels' CODEX_EFFORT_LEVELS.export const CODEX_IMAGEGEN_DEFAULT_MODEL = 'gpt-5.6-luna';export const CODEX_IMAGEGEN_DEFAULT_EFFORT = 'low';++/**+ * Resolve the queue-capable image mode for a render request: the per-request+ * override (honored only when that backend is enabled/available), else the+ * saved dispatcher default, else codex → grok → local. External never queues.+ * Hoisted from the pipeline visual stages (#2896) so sprite renders and any+ * future queued surface share one enable-gating ladder — see issue #2881 for+ * the wider param-assembly consolidation.+ */+export function resolveQueueImageMode(requested, settings) {+ const codexEnabled = settings?.imageGen?.codex?.enabled === true;+ const grokEnabled = settings?.imageGen?.grok?.enabled === true;+ if (requested === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;+ if (requested === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;+ if (requested === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;+ const settingsMode = settings?.imageGen?.mode;+ if (settingsMode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;+ if (settingsMode === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;+ if (settingsMode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;+ if (codexEnabled) return IMAGE_GEN_MODE.CODEX;+ if (grokEnabled) return IMAGE_GEN_MODE.GROK;+ return IMAGE_GEN_MODE.LOCAL;+}diff --git a/server/services/pipeline/visualStageHelpers.js b/server/services/pipeline/visualStageHelpers.jsindex e72558f4f5..4e8fcd55db 100644--- a/server/services/pipeline/visualStageHelpers.js+++ b/server/services/pipeline/visualStageHelpers.js@@ -21,7 +21,7 @@ import { getImageModels } from '../../lib/mediaModels.js';import { loraCompatKey } from '../../lib/runners.js';import { resolveCharacterLoras } from '../characterLoraResolver.js';import { pickCanon } from './seriesCanon.js';-import { IMAGE_GEN_MODE } from '../imageGen/modes.js';+import { IMAGE_GEN_MODE, resolveQueueImageMode } from '../imageGen/modes.js';import { resolveImageCleaners } from '../imageGen/index.js';const joinStyleParts = (...parts) =>@@ -53,31 +53,11 @@ const applyWorldStyle = (prompt, world, series = null) => {};// Resolution order for the image-gen mode on a pipeline visual stage:-// 1. Per-request override (`options.mode`) — set by the stage's persisted-// `genConfig` or an explicit UI selection. Codex is only honored when-// `imageGen.codex.enabled` is true; a stale 'codex' override from-// before the toggle was turned off falls through to the next step.-// 2. Saved dispatcher default (`settings.imageGen.mode`) — but only when-// it names a mode this surface supports (visual pipeline doesn't-// proxy the external SD-API path) AND, for 'codex', Codex is enabled.-// 3. Auto-default — prefer Codex when the user has enabled it-// (`imageGen.codex.enabled`), since cloud image gen produces-// print-quality comic pages out of the box. Otherwise fall back to-// local diffusion (flux-1) the way the original default behaved.-const resolveMode = (options, settings) => {- const codexEnabled = settings?.imageGen?.codex?.enabled === true;- const grokEnabled = settings?.imageGen?.grok?.enabled === true;- if (options.mode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (options.mode === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;- if (options.mode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;- const settingsMode = settings?.imageGen?.mode;- if (settingsMode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (settingsMode === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;- if (settingsMode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;- if (codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (grokEnabled) return IMAGE_GEN_MODE.GROK;- return IMAGE_GEN_MODE.LOCAL;-};+// per-request override (enable-gated) → saved dispatcher default → codex →+// grok → local. The ladder itself is the shared `resolveQueueImageMode`+// (imageGen/modes.js) — hoisted in #2896 so sprite renders use the same+// policy; this wrapper just adapts the pipeline's `options` bag.+const resolveMode = (options, settings) => resolveQueueImageMode(options.mode, settings);/*** Resolve trained character LoRAs for a pipeline render. Local mode only —diff --git a/server/services/spriteReferenceImageHook.js b/server/services/spriteReferenceImageHook.jsindex 585e1a5483..e4310a51d7 100644--- a/server/services/spriteReferenceImageHook.js+++ b/server/services/spriteReferenceImageHook.js@@ -17,22 +17,15 @@ const hook = createMediaJobImageHook({label: 'sprite reference-candidate',initLog: '🧍 Sprite reference-candidate hook initialized',tagKey: 'spriteRef',+ // The tag is authored by reference.js itself (startReferenceGeneration), so+ // pass it through wholesale — new tag fields flow to the sidecar without+ // touching this hook.identify: (tag, job) => (tag?.recordId && tag.target && tag.anchorId- ? {- recordId: tag.recordId,- target: tag.target,- direction: tag.direction,- anchorId: tag.anchorId,- chromaKey: tag.chromaKey,- mode: tag.mode,- model: tag.model,- designPrompt: tag.designPrompt,- jobId: job?.id || null,- }+ ? { ...tag, jobId: job?.id || null }: null),serializeKey: ({ recordId }) => recordId,describe: ({ recordId, anchorId }) => `${recordId}/${anchorId}`,- attach: (ctx) => attachReferenceCandidate(ctx),+ attach: attachReferenceCandidate,onAttached: ({ recordId, anchorId }, result) => {console.log(`🧍 sprite reference candidate ${recordId}/${anchorId} ← ${result.candidatePath}`);},diff --git a/server/services/sprites/chromaKey.js b/server/services/sprites/chromaKey.jsindex 0dc9c9cfc0..79b5c9aa2b 100644--- a/server/services/sprites/chromaKey.js+++ b/server/services/sprites/chromaKey.js@@ -18,6 +18,10 @@ export const CHROMA_KEYS = [export const CHROMA_KEY_HEXES = CHROMA_KEYS.map((k) => k.hex);+// Magenta — the source pipeline's only key; the fallback wherever no key has+// been selected yet (pre-lock generation, legacy imports).+export const DEFAULT_CHROMA_KEY = CHROMA_KEYS[0].hex;+// Below this hue separation (degrees) between the chosen key and the nearest// significant palette color, keying will likely eat character pixels — the// selection still returns the best key but carries a warning.diff --git a/server/services/sprites/normalize.js b/server/services/sprites/normalize.jsindex 86e895f4ff..b4c88d0a0b 100644--- a/server/services/sprites/normalize.js+++ b/server/services/sprites/normalize.js@@ -12,19 +12,17 @@* Geometry contract (verbatim from the source): character height is 80% of* the square side (or width fits inside 10% side margins, whichever needs a* bigger canvas), feet baseline sits 7% above the bottom edge, pixels are- * never rescaled — only the canvas is sized around them.+ * never rescaled — only the canvas is sized around them. Mask threshold:+ * a pixel is foreground when luma(|pixel − key|) > 40 (Pillow's L convert).*/import sharp from 'sharp';import { copyFile } from 'fs/promises';-export const REFERENCE_FRAME_HEIGHT_FRAC = 0.80;-export const REFERENCE_FRAME_BOTTOM_FRAC = 0.07;-export const REFERENCE_FRAME_SIDE_FRAC = 0.10;--// Pillow's mask threshold: a pixel is foreground when the luminance of its-// per-channel difference from the key color exceeds this.-export const MASK_LUMA_THRESHOLD = 40;+const FRAME_HEIGHT_FRAC = 0.80;+const FRAME_BOTTOM_FRAC = 0.07;+const FRAME_SIDE_FRAC = 0.10;+const MASK_LUMA_THRESHOLD = 40;export function hexToRgb(hex) {const m = /^#?([0-9a-fA-F]{6})$/.exec(typeof hex === 'string' ? hex : '');@@ -33,10 +31,14 @@ export function hexToRgb(hex) {return { r: (n >> 16) & 0xff, g: (n >> 8) & 0xff, b: n & 0xff };}-// Load as flat RGB (alpha dropped over white like Pillow's convert("RGB")-// after flatten; generated candidates are opaque PNGs so this is a no-op in-// practice) plus a foreground mask + tight bounding box vs the key color.-async function loadMasked(src, maskKeyHex) {+/**+ * Decode `src` as flat RGB (alpha dropped over white like Pillow's+ * convert("RGB"); generated candidates are opaque PNGs so this is a no-op in+ * practice) and compute the foreground mask + tight bounding box vs the key+ * color. The lock path runs palette extraction AND normalization off ONE+ * analysis so a multi-MP candidate is decoded and scanned once.+ */+export async function analyzeForeground(src, maskKeyHex) {const key = hexToRgb(maskKeyHex);const { data, info } = await sharp(src).flatten({ background: { r: 255, g: 255, b: 255 } })@@ -67,12 +69,11 @@ async function loadMasked(src, maskKeyHex) {}/**- * Histogram the foreground (non-key) pixels of an image, quantized to 4 bits- * per channel so anti-aliased shades collapse into their parent color.+ * Histogram the foreground (non-key) pixels of an analysis, quantized to 4+ * bits per channel so anti-aliased shades collapse into their parent color.* Returns `[{ r, g, b, count }]` sorted by count desc — pickChromaKey's input.*/-export async function extractForegroundPalette(src, maskKeyHex) {- const { data, width, height, mask } = await loadMasked(src, maskKeyHex);+export function paletteFromAnalysis({ data, width, height, mask }) {const counts = new Map();for (let p = 0; p < width * height; p++) {if (!mask[p]) continue;@@ -91,15 +92,17 @@ export async function extractForegroundPalette(src, maskKeyHex) {.sort((a, b) => b.count - a.count);}+/** One-shot palette extraction (decode + histogram). */+export async function extractForegroundPalette(src, maskKeyHex) {+ return paletteFromAnalysis(await analyzeForeground(src, maskKeyHex));+}+/**- * Normalize a candidate into the canonical key-color square described above.- * `maskKeyHex` is the background the candidate was GENERATED on (what to key- * out); `canvasKeyHex` is the key to composite onto (the selected key). An- * image with no detectable foreground copies through unchanged, mirroring- * the source behavior.+ * Composite a pre-analyzed candidate onto the canonical key-color square.+ * `src` is still needed for the no-foreground copy-through path.*/-export async function normalizeAnchorFrame(src, dest, { maskKeyHex, canvasKeyHex }) {- const { data, width, mask, bbox } = await loadMasked(src, maskKeyHex);+export async function normalizeFromAnalysis(analysis, src, dest, canvasKeyHex) {+ const { data, width, mask, bbox } = analysis;if (!bbox) {await copyFile(src, dest);return { copiedThrough: true };@@ -107,18 +110,13 @@ export async function normalizeAnchorFrame(src, dest, { maskKeyHex, canvasKeyHexconst charW = bbox.right - bbox.left;const charH = bbox.bottom - bbox.top;const side = Math.max(- Math.round(charH / REFERENCE_FRAME_HEIGHT_FRAC),- Math.round(charW / (1 - 2 * REFERENCE_FRAME_SIDE_FRAC)),+ Math.round(charH / FRAME_HEIGHT_FRAC),+ Math.round(charW / (1 - 2 * FRAME_SIDE_FRAC)),);const fill = hexToRgb(canvasKeyHex);- const canvas = Buffer.alloc(side * side * 3);- for (let p = 0; p < side * side; p++) {- canvas[p * 3] = fill.r;- canvas[p * 3 + 1] = fill.g;- canvas[p * 3 + 2] = fill.b;- }+ const canvas = Buffer.alloc(side * side * 3, Buffer.from([fill.r, fill.g, fill.b]));const offsetX = Math.floor((side - charW) / 2);- const feetY = side - Math.round(side * REFERENCE_FRAME_BOTTOM_FRAC);+ const feetY = side - Math.round(side * FRAME_BOTTOM_FRAC);const offsetY = feetY - charH;for (let y = bbox.top; y < bbox.bottom; y++) {for (let x = bbox.left; x < bbox.right; x++) {@@ -133,3 +131,12 @@ export async function normalizeAnchorFrame(src, dest, { maskKeyHex, canvasKeyHexawait sharp(canvas, { raw: { width: side, height: side, channels: 3 } }).png().toFile(dest);return { side, charW, charH };}++/**+ * One-shot normalize: mask `src` against the key it was GENERATED on, then+ * composite onto the SELECTED key. An image with no detectable foreground+ * copies through unchanged, mirroring the source behavior.+ */+export async function normalizeAnchorFrame(src, dest, { maskKeyHex, canvasKeyHex }) {+ return normalizeFromAnalysis(await analyzeForeground(src, maskKeyHex), src, dest, canvasKeyHex);+}diff --git a/server/services/sprites/prompts.js b/server/services/sprites/prompts.jsindex eb9edc77aa..379cc8f9e0 100644--- a/server/services/sprites/prompts.js+++ b/server/services/sprites/prompts.js@@ -7,8 +7,8 @@* background color is a parameter (the source hardcoded magenta) so the* per-character key selected at lock time flows into every later prompt.*- * Pure module — no I/O, no imports from the rest of the server — so- * validation.js and the client can lean on its constants safely.+ * Pure module — no I/O, no imports outside the sibling pure sprite modules —+ * so validation.js and the client can lean on its constants safely.*/// Canonical 8-direction order (the source pipeline's RUNTIME_DIRECTION_ORDER)@@ -42,7 +42,9 @@ export const REFERENCE_FACING = {'north-west': 'a three-quarter rear view angled up and to screen-left (no face)',};-const KEY_NAMES = { '#FF00FF': 'magenta', '#00FF00': 'green', '#0000FF': 'blue' };+import { CHROMA_KEYS } from './chromaKey.js';++const KEY_NAMES = Object.fromEntries(CHROMA_KEYS.map((k) => [k.hex, k.name]));/** "magenta (#FF00FF)" — the phrase both prompt templates embed. */export function keyColorPhrase(hex) {diff --git a/server/services/sprites/records.js b/server/services/sprites/records.jsindex c110e7a138..62111b44c5 100644--- a/server/services/sprites/records.js+++ b/server/services/sprites/records.js@@ -15,7 +15,9 @@*/import { checkHealth, ensureSchema, isTestRunner } from '../../lib/db.js';+import { ServerError } from '../../lib/errorHandler.js';import { listSpriteAssets } from './paths.js';+import { deriveSpriteId, isValidSpriteId } from './recordsLogic.js';let backend = null;@@ -61,6 +63,18 @@ export async function createRecord(input, id) {return (await selectBackend()).createRecord(input, id);}+/**+ * Create a character record (the reference-workflow entry point) — derives+ * the id from the name when not supplied. Props families stay import-only.+ */+export async function createCharacter({ id, name, spec = null }) {+ const recordId = id || deriveSpriteId(name);+ if (!isValidSpriteId(recordId)) {+ throw new ServerError(`Cannot derive a valid sprite id from "${name}" — pass an explicit id`, { status: 400, code: 'INVALID_SPRITE_ID' });+ }+ return createRecord({ kind: 'character', name, spec }, recordId);+}+export async function updateRecord(id, patch) {return (await selectBackend()).updateRecord(id, patch);}diff --git a/server/services/sprites/recordsLogic.js b/server/services/sprites/recordsLogic.jsindex 75347f8d41..fc0de06e36 100644--- a/server/services/sprites/recordsLogic.js+++ b/server/services/sprites/recordsLogic.js@@ -20,6 +20,17 @@ export function isValidSpriteId(id) {return typeof id === 'string' && SPRITE_ID_PATTERN.test(id);}+/**+ * Derive a record id from a display name (kebab, pattern-conformant), or+ * null when nothing derivable remains. (lib/planIds' slugify was considered+ * but its 'item' fallback and collision suffixing don't fit — sprite creation+ * 400s on an underivable name and 409s on a duplicate id instead.)+ */+export function deriveSpriteId(name) {+ const id = String(name || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64);+ return isValidSpriteId(id) ? id : null;+}+export function mirrorTimestamp(value, fallback) {return typeof value === 'string' && value ? value : fallback;}diff --git a/server/services/sprites/recordsLogic.test.js b/server/services/sprites/recordsLogic.test.jsindex b358c6938f..c7e1cd555d 100644--- a/server/services/sprites/recordsLogic.test.js+++ b/server/services/sprites/recordsLogic.test.js@@ -93,3 +93,18 @@ describe('mergeImportedRecord', () => {expect(next.chromaKey).toBeNull(); // || would resurrect the import default});});++describe('deriveSpriteId', () => {+ it('kebabs a display name into a valid id', async () => {+ const { deriveSpriteId } = await import('./recordsLogic.js');+ expect(deriveSpriteId('Trail Hand #2')).toBe('trail-hand-2');+ expect(deriveSpriteId(' Pioneer ')).toBe('pioneer');+ });++ it('returns null when nothing derivable remains', async () => {+ const { deriveSpriteId } = await import('./recordsLogic.js');+ expect(deriveSpriteId('!!!')).toBeNull();+ expect(deriveSpriteId('')).toBeNull();+ expect(deriveSpriteId(null)).toBeNull();+ });+});diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.jsindex 30020f1c7a..e68925c207 100644--- a/server/services/sprites/reference.js+++ b/server/services/sprites/reference.js@@ -16,13 +16,14 @@*/import { join } from 'path';-import { readdir, copyFile, unlink } from 'fs/promises';+import { readdir, copyFile } from 'fs/promises';import {PATHS, ensureDir, sha256File, atomicWrite, pathExists, readJSONFile,+ importFileToDir, listDirectoryByExtension,} from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { enqueueJob } from '../mediaJobQueue/index.js';-import { IMAGE_GEN_MODE } from '../imageGen/modes.js';+import { IMAGE_GEN_MODE, resolveQueueImageMode } from '../imageGen/modes.js';import { resolveImageCleaners } from '../imageGen/index.js';import { getSettings } from '../settings.js';import { getRecord, updateRecord } from './records.js';@@ -31,10 +32,8 @@ import {SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, anchorIdForDirection,buildMainReferencePrompt, buildAnchorPrompt,} from './prompts.js';-import { pickChromaKey, CHROMA_KEY_HEXES } from './chromaKey.js';-import { normalizeAnchorFrame, extractForegroundPalette } from './normalize.js';--const LEGACY_KEY = '#FF00FF';+import { pickChromaKey, CHROMA_KEY_HEXES, DEFAULT_CHROMA_KEY } from './chromaKey.js';+import { analyzeForeground, paletteFromAnalysis, normalizeFromAnalysis, normalizeAnchorFrame } from './normalize.js';// Default i2i strengths: anchors redraw a NEW facing from the main (mostly// follow the prompt, borrow identity), an uploaded visual reference guides@@ -110,24 +109,6 @@ async function nextCandidateName(candidatesDir, anchorId) {return `${anchorId}-candidate-${String(max + 1).padStart(2, '0')}.png`;}-// Mirrors the pipeline visual stages' mode resolution: per-request override-// (honored only when that backend is enabled), else the saved dispatcher-// default, else codex → grok → local. External never queues.-function resolveGenMode(requested, settings) {- const codexEnabled = settings?.imageGen?.codex?.enabled === true;- const grokEnabled = settings?.imageGen?.grok?.enabled === true;- if (requested === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (requested === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;- if (requested === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;- const settingsMode = settings?.imageGen?.mode;- if (settingsMode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (settingsMode === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;- if (settingsMode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;- if (codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (grokEnabled) return IMAGE_GEN_MODE.GROK;- return IMAGE_GEN_MODE.LOCAL;-}-function findAnchor(manifest, anchorId) {return manifest.anchors.find((a) => a.id === anchorId) || null;}@@ -140,15 +121,9 @@ function findAnchor(manifest, anchorId) {export async function getReferenceSet(recordId) {const manifest = await loadManifest(recordId);const candidatesDir = join(spriteDir(recordId), 'reference', 'candidates');- let entries = [];- try {- entries = await readdir(candidatesDir);- } catch {- // no candidates yet- }- const candidates = (await Promise.all(entries- .filter((name) => name.endsWith('.png'))- .map(async (name) => {+ const candidates = (await listDirectoryByExtension(candidatesDir, {+ extensions: ['.png'],+ mapEntry: async (name) => {const sidecar = await readJSONFile(join(candidatesDir, `${name.replace(/\.png$/, '')}.generation.json`), null);return {path: `reference/candidates/${name}`,@@ -159,7 +134,8 @@ export async function getReferenceSet(recordId) {model: sidecar?.model || null,generatedAt: sidecar?.generatedAt || null,};- })))+ },+ })).sort((a, b) => (b.generatedAt || '').localeCompare(a.generatedAt || '') || a.path.localeCompare(b.path));return { manifest, candidates };}@@ -176,9 +152,9 @@ export async function startReferenceGeneration(recordId, body, upload = null) {const record = await requireCharacter(recordId);const manifest = (await loadManifest(recordId)) || seedManifest(recordId);const target = body.target;- const genKey = record.chromaKey || manifest.chromaKey || LEGACY_KEY;+ const genKey = record.chromaKey || manifest.chromaKey || DEFAULT_CHROMA_KEY;const settings = await getSettings();- const mode = resolveGenMode(body.mode, settings);+ const mode = resolveQueueImageMode(body.mode, settings);let prompt;let initImagePath;@@ -198,17 +174,18 @@ export async function startReferenceGeneration(recordId, body, upload = null) {direction = 'south';prompt = buildMainReferencePrompt({ name: record.name, designPrompt, chromaKey: genKey });if (upload) {+ // Shared temp-import (uuid-prefixed name, EXDEV-safe copy+unlink) —+ // the upload persists in the record dir as design provenance.const uploadsDir = join(spriteDir(recordId), 'reference', 'uploads');- await ensureDir(uploadsDir);- const ext = /\.(png|jpe?g|webp)$/i.exec(upload.originalname || '')?.[0]?.toLowerCase() || '.png';- // Timestamp-named (not -vN): uploads may mix extensions, which would- // defeat a .png-only version scan and overwrite an earlier upload.- initImagePath = join(uploadsDir, `design-reference-${Date.now()}${ext}`);- await copyFile(upload.tempPath, initImagePath);- await unlink(upload.tempPath).catch(() => {});+ const { filename } = await importFileToDir(upload.tempPath, upload.originalname || 'design-reference.png', uploadsDir);+ initImagePath = join(uploadsDir, filename);initImageStrength ??= UPLOAD_DEFAULT_STRENGTH;}if (designPrompt) manifest.designPrompt = designPrompt;+ // Only the main branch mutates (or may have just seeded) the manifest —+ // the anchor branch requires a locked main, so its manifest already+ // exists on disk unchanged.+ await saveManifest(recordId, manifest);} else {if (!ANCHOR_DIRECTIONS.includes(target)) {throw new ServerError(`Unknown reference target: ${target}`, { status: 400, code: 'INVALID_TARGET' });@@ -250,7 +227,6 @@ export async function startReferenceGeneration(recordId, body, upload = null) {? { mode, grokPath: settings.imageGen?.grok?.grokPath, aspectRatio: settings.imageGen?.grok?.aspectRatio, ...baseParams }: { mode, pythonPath: settings.imageGen?.local?.pythonPath || null, ...(body.model ? { modelId: body.model } : {}), ...baseParams };- await saveManifest(recordId, manifest);const { jobId } = enqueueJob({ kind: 'image', params, owner: 'sprites' });console.log(`🧍 sprite reference render queued ${recordId}/${anchorId} mode=${mode} jobId=${jobId.slice(0, 8)}`);return { jobId, mode, target, anchorId };@@ -322,7 +298,7 @@ export async function lockReference(recordId, { target, candidate }) {}// Mask on the key the candidate was GENERATED against (its actual// background), which may differ from the key selected at lock time.- const maskKey = sidecar?.chromaKey || record.chromaKey || LEGACY_KEY;+ const maskKey = sidecar?.chromaKey || record.chromaKey || DEFAULT_CHROMA_KEY;const now = new Date().toISOString();if (target === 'main') {@@ -331,17 +307,19 @@ export async function lockReference(recordId, { target, candidate }) {}// Dynamic key selection (#2895): histogram the character's own palette// and pick the standard key farthest from it in hue — unless the user- // already pinned a key on the record.- const auto = pickChromaKey(await extractForegroundPalette(candAbs, maskKey));+ // already pinned a key on the record (then skip the histogram entirely).+ // One analyzeForeground decode feeds both the palette and the composite.+ const analysis = await analyzeForeground(candAbs, maskKey);const userPinned = CHROMA_KEY_HEXES.includes(record.chromaKey);+ const auto = userPinned ? null : pickChromaKey(paletteFromAnalysis(analysis));const selectedKey = userPinned ? record.chromaKey : auto.hex;const rel = `reference/${await nextVersionPath(refDir, `${recordId}-walk-south`)}`;const destAbs = join(spriteDir(recordId), rel);- await normalizeAnchorFrame(candAbs, destAbs, { maskKeyHex: maskKey, canvasKeyHex: selectedKey });+ await normalizeFromAnalysis(analysis, candAbs, destAbs, selectedKey);const sha256 = await sha256File(destAbs);manifest.chromaKey = selectedKey;manifest.chromaKeyAutoSelected = !userPinned;- manifest.chromaKeyWarning = userPinned ? null : auto.warning;+ manifest.chromaKeyWarning = auto?.warning ?? null;manifest.mainReference = {...manifest.mainReference,path: rel,@@ -369,7 +347,7 @@ export async function lockReference(recordId, { target, candidate }) {if (anchor.status === 'locked') {throw new ServerError(`Anchor ${anchorId} is already locked`, { status: 409, code: 'REFERENCE_LOCKED' });}- const canvasKey = record.chromaKey || manifest.chromaKey || LEGACY_KEY;+ const canvasKey = record.chromaKey || manifest.chromaKey || DEFAULT_CHROMA_KEY;const rel = `reference/${await nextVersionPath(refDir, `${recordId}-${anchorId}`)}`;const destAbs = join(spriteDir(recordId), rel);await normalizeAnchorFrame(candAbs, destAbs, { maskKeyHex: maskKey, canvasKeyHex: canvasKey });