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

address review (codex r1): clip-risk warning, legacy manifest path rebase, upload sweep before validation, backend picker fixes

[._.]/ Adam Eivyf7b55a95f15d
diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsx
index 15b27a16d5..c0faaddbd9 100644
--- a/client/src/components/sprites/ReferenceWorkflow.jsx
+++ b/client/src/components/sprites/ReferenceWorkflow.jsx
@@ -66,7 +66,8 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {
const candidates = reference?.candidates || [];
const mainLocked = manifest?.mainReference?.locked === true;
- const [backends, setBackends] = useState([]);
+ // null = settings not loaded yet; [] = loaded, no queue backend configured.
+ const [backends, setBackends] = useState(null);
const [mode, setMode] = useState('');
const [designPrompt, setDesignPrompt] = useState(manifest?.designPrompt || '');
const [uploadFile, setUploadFile] = useState(null);
@@ -79,7 +80,11 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {
.then((settings) => {
const available = deriveAvailableBackends(settings, { excludeExternal: true });
setBackends(available);
- setMode((m) => m || available[0]?.id || '');
+ // Prefer the configured dispatcher default when it's available —
+ // defaulting to the first list entry would silently send an explicit
+ // `local` override on installs configured for codex/grok.
+ const configured = available.find((b) => b.id === settings?.imageGen?.mode)?.id;
+ setMode((m) => m || configured || available[0]?.id || '');
})
.catch(() => setBackends([]));
}, []);
@@ -113,6 +118,9 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {
if (job?.status === 'failed') toast.error(`Render failed for ${target}: ${job.error || 'see media jobs'}`);
}
setTimeout(onChanged, 500);
+ // Several jobs finishing in one tick attach serially server-side — a
+ // later attach can land after the first refetch, so sweep once more.
+ if (finished.length > 1) setTimeout(onChanged, 2500);
}, 4000);
return () => clearInterval(timer);
}, [pendingJobs, onChanged]);
@@ -149,7 +157,8 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {
onChanged();
}, { errorMessage: 'Failed to set chroma key' });
- const modePicker = backends.length > 0 && (
+ const noBackend = Array.isArray(backends) && backends.length === 0;
+ const modePicker = Array.isArray(backends) && backends.length > 0 && (
<label className="flex items-center gap-2 text-xs text-gray-400">
Backend
<select
@@ -186,6 +195,11 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {
{manifest?.chromaKeyWarning && (
<p className="text-xs text-port-warning">{manifest.chromaKeyWarning}</p>
)}
+ {noBackend && (
+ <p className="text-xs text-port-warning">
+ No image backend configured — enable Codex or Grok, or set a local Python path, in Settings → Image Gen to generate references.
+ </p>
+ )}
{/* Main reference — the immutable identity root */}
<div className="space-y-2">
@@ -219,7 +233,7 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {
{modePicker}
<button
onClick={() => generate('main')}
- disabled={!!pendingJobs.main || (!designPrompt.trim() && !uploadFile)}
+ disabled={!mode || !!pendingJobs.main || (!designPrompt.trim() && !uploadFile)}
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.main ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}
@@ -257,7 +271,7 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {
<div className="space-y-1.5">
<button
onClick={() => generate(anchor.direction)}
- disabled={!!pendingJobs[anchor.direction]}
+ disabled={!mode || !!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/routes/sprites.js b/server/routes/sprites.js
index 2e5663aadc..514da66402 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -69,13 +69,14 @@ router.get('/:id', asyncHandler(async (req, res) => {
// Accepts JSON, or multipart with an optional `referenceImage` file for the
// main target (an uploaded visual design reference → i2i).
router.post('/:id/reference/generate', referenceUpload, asyncHandler(async (req, res) => {
- const body = validateRequest(spriteReferenceGenerateSchema, req.body ?? {});
+ // Capture + register the temp-file sweep BEFORE validation — a 400 thrown
+ // by validateRequest would otherwise leak the already-finalized upload.
+ // The service moves the file on success, so the unlink is a harmless
+ // ENOENT there.
const file = req.files?.referenceImage;
const upload = file ? { tempPath: file.path, originalname: file.originalname } : null;
- // Sweep the staged temp file whenever the request ends without the service
- // having consumed it (validation failure, locked target, etc). The service
- // moves it on success, so this unlink is a harmless ENOENT there.
if (upload) res.on('close', () => { unlink(upload.tempPath).catch(() => {}); });
+ const body = validateRequest(spriteReferenceGenerateSchema, req.body ?? {});
if (upload && body.target !== 'main') {
throw new ServerError('Reference image uploads apply to the main target only — anchors always derive from the locked main', { status: 400, code: 'UPLOAD_MAIN_ONLY' });
}
diff --git a/server/services/sprites/chromaKey.js b/server/services/sprites/chromaKey.js
index 79b5c9aa2b..0d4a318a48 100644
--- a/server/services/sprites/chromaKey.js
+++ b/server/services/sprites/chromaKey.js
@@ -27,6 +27,13 @@ export const DEFAULT_CHROMA_KEY = CHROMA_KEYS[0].hex;
// selection still returns the best key but carries a warning.
export const MIN_HUE_SEPARATION = 60;
+export function hexToRgb(hex) {
+ const m = /^#?([0-9a-fA-F]{6})$/.exec(typeof hex === 'string' ? hex : '');
+ if (!m) throw new Error(`Invalid hex color: ${hex}`);
+ const n = parseInt(m[1], 16);
+ return { r: (n >> 16) & 0xff, g: (n >> 8) & 0xff, b: n & 0xff };
+}
+
export function rgbToHsv(r, g, b) {
const rn = r / 255; const gn = g / 255; const bn = b / 255;
const max = Math.max(rn, gn, bn);
@@ -60,16 +67,35 @@ export function hueDistance(a, b) {
* achromatic palette conflicts with nothing, so the first key (magenta, the
* legacy default) wins with distance Infinity.
*/
-export function pickChromaKey(palette, {
- minCountFrac = 0.005,
- minSaturation = 0.25,
- minValue = 0.15,
-} = {}) {
+function significantHues(palette, { minCountFrac = 0.005, minSaturation = 0.25, minValue = 0.15 } = {}) {
const entries = Array.isArray(palette) ? palette : [];
const total = entries.reduce((sum, e) => sum + (e.count || 0), 0);
- const significant = entries
+ return entries
.map((e) => ({ ...rgbToHsv(e.r, e.g, e.b), count: e.count || 0 }))
.filter((c) => c.count >= total * minCountFrac && c.s >= minSaturation && c.v >= minValue);
+}
+
+/**
+ * Warn when the character's surviving palette sits close in hue to the key
+ * it was GENERATED on: the normalize mask has already discarded any pixel
+ * within the luma threshold of that key, so near-key palette colors imply
+ * exact-key details (a magenta garment on the magenta default) may have been
+ * silently clipped from the immutable locked artifact. Returns a warning
+ * string or null.
+ */
+export function keyProximityWarning(palette, genKeyHex, opts = {}) {
+ const { r, g, b } = hexToRgb(genKeyHex);
+ const keyHue = rgbToHsv(r, g, b).h;
+ const significant = significantHues(palette, opts);
+ if (!significant.length) return null;
+ const minDist = Math.min(...significant.map((c) => hueDistance(keyHue, c.h)));
+ return minDist < MIN_HUE_SEPARATION
+ ? `Character palette sits within ${Math.round(minDist)}° of the generation key ${genKeyHex} — exact-key details may have been clipped by the mask; consider pinning a different key and regenerating before locking`
+ : null;
+}
+
+export function pickChromaKey(palette, opts = {}) {
+ const significant = significantHues(palette, opts);
let best = null;
for (const key of CHROMA_KEYS) {
diff --git a/server/services/sprites/chromaKey.test.js b/server/services/sprites/chromaKey.test.js
index daf0c80e76..88aa39502d 100644
--- a/server/services/sprites/chromaKey.test.js
+++ b/server/services/sprites/chromaKey.test.js
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest';
import {
CHROMA_KEYS, CHROMA_KEY_HEXES, MIN_HUE_SEPARATION,
- rgbToHsv, hueDistance, pickChromaKey,
+ rgbToHsv, hueDistance, pickChromaKey, keyProximityWarning,
} from './chromaKey.js';
describe('chroma key set', () => {
@@ -86,3 +86,21 @@ describe('pickChromaKey', () => {
expect(pick.warning).toBeNull();
});
});
+
+describe('keyProximityWarning', () => {
+ const solid = (r, g, b, count = 1000) => ({ r, g, b, count });
+
+ it('warns when surviving palette hues sit near the generation key', () => {
+ const warning = keyProximityWarning([solid(255, 80, 230)], '#FF00FF'); // pink near magenta
+ expect(warning).toMatch(/generation key #FF00FF/);
+ });
+
+ it('stays quiet for a palette far from the generation key', () => {
+ expect(keyProximityWarning([solid(23, 107, 101)], '#FF00FF')).toBeNull(); // teal vs magenta
+ });
+
+ it('stays quiet for achromatic/empty palettes', () => {
+ expect(keyProximityWarning([solid(40, 40, 40)], '#FF00FF')).toBeNull();
+ expect(keyProximityWarning([], '#FF00FF')).toBeNull();
+ });
+});
diff --git a/server/services/sprites/normalize.js b/server/services/sprites/normalize.js
index b4c88d0a0b..d0713ad94d 100644
--- a/server/services/sprites/normalize.js
+++ b/server/services/sprites/normalize.js
@@ -18,18 +18,16 @@
import sharp from 'sharp';
import { copyFile } from 'fs/promises';
+import { hexToRgb } from './chromaKey.js';
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 : '');
- if (!m) throw new Error(`Invalid hex color: ${hex}`);
- const n = parseInt(m[1], 16);
- return { r: (n >> 16) & 0xff, g: (n >> 8) & 0xff, b: n & 0xff };
-}
+// Re-export for existing consumers/tests; the definition lives in the pure
+// color-math module so chromaKey.js can use it without importing sharp.
+export { hexToRgb };
/**
* Decode `src` as flat RGB (alpha dropped over white like Pillow's
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index 4d499e566f..eed4c00c8d 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -33,7 +33,7 @@ import {
SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, anchorIdForDirection,
buildMainReferencePrompt, buildAnchorPrompt,
} from './prompts.js';
-import { pickChromaKey, CHROMA_KEY_HEXES, DEFAULT_CHROMA_KEY } from './chromaKey.js';
+import { pickChromaKey, keyProximityWarning, 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
@@ -52,8 +52,27 @@ const manifestRelPath = (id) => `reference/${id}-reference-set-v1.json`;
// hook's per-record queue.
const manifestWriteTail = createKeyCachedQueue();
+// Phase-1 imported manifests are copied verbatim from the source pipeline
+// and carry repo-root paths (`art-source/sprites/<id>/reference/...`), while
+// the files themselves live record-relative under data/sprites/<id>/.
+// Rebase on read so imported characters render and derive anchors correctly.
+function rebaseLegacyPath(p, recordId) {
+ const marker = `art-source/sprites/${recordId}/`;
+ return typeof p === 'string' && p.startsWith(marker) ? p.slice(marker.length) : p;
+}
+
async function loadManifest(recordId) {
- return readJSONFile(join(spriteDir(recordId), manifestRelPath(recordId)), null);
+ const manifest = await readJSONFile(join(spriteDir(recordId), manifestRelPath(recordId)), null);
+ if (!manifest) return null;
+ if (manifest.mainReference) {
+ manifest.mainReference.path = rebaseLegacyPath(manifest.mainReference.path, recordId);
+ manifest.mainReference.lockedFrom = rebaseLegacyPath(manifest.mainReference.lockedFrom, recordId);
+ }
+ for (const anchor of manifest.anchors || []) {
+ anchor.path = rebaseLegacyPath(anchor.path, recordId);
+ anchor.lockedFrom = rebaseLegacyPath(anchor.lockedFrom, recordId);
+ }
+ return manifest;
}
async function saveManifest(recordId, manifest) {
@@ -326,19 +345,26 @@ async function lockReferenceImpl(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 (then skip the histogram entirely).
- // One analyzeForeground decode feeds both the palette and the composite.
+ // already pinned a key on the record. One analyzeForeground decode feeds
+ // the palette and the composite; the palette is computed even when
+ // pinned because the clip warning below needs it.
const analysis = await analyzeForeground(candAbs, maskKey);
+ const palette = paletteFromAnalysis(analysis);
const userPinned = CHROMA_KEY_HEXES.includes(record.chromaKey);
- const auto = userPinned ? null : pickChromaKey(paletteFromAnalysis(analysis));
+ const auto = userPinned ? null : pickChromaKey(palette);
const selectedKey = userPinned ? record.chromaKey : auto.hex;
+ // Selection only sees pixels that SURVIVED the generation-key mask —
+ // exact-key details (magenta garment on the magenta default) are already
+ // gone from the palette, so surface the risk instead of silently locking
+ // a clipped identity root.
+ const clipWarning = keyProximityWarning(palette, maskKey);
const rel = `reference/${await nextVersionPath(refDir, `${recordId}-walk-south`)}`;
const destAbs = join(spriteDir(recordId), rel);
await normalizeFromAnalysis(analysis, candAbs, destAbs, selectedKey);
const sha256 = await sha256File(destAbs);
manifest.chromaKey = selectedKey;
manifest.chromaKeyAutoSelected = !userPinned;
- manifest.chromaKeyWarning = auto?.warning ?? null;
+ manifest.chromaKeyWarning = [auto?.warning, clipWarning].filter(Boolean).join(' — ') || null;
manifest.mainReference = {
...manifest.mainReference,
path: rel,
diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.js
index b047444782..4b5e6f6381 100644
--- a/server/services/sprites/reference.test.js
+++ b/server/services/sprites/reference.test.js
@@ -239,7 +239,7 @@ describe('lockReference', () => {
expect(record.status).toBe('reference');
});
- it('auto-selects AWAY from the key a magenta-clothed character would clash with', async () => {
+ it('auto-selects AWAY from the key a magenta-clothed character would clash with, and warns about clip risk', async () => {
const id = newId();
await createCharacter(id);
const rel = await placeCandidate(id, 'main', 'walk-south-candidate-01.png', {
@@ -249,6 +249,36 @@ describe('lockReference', () => {
expect(result.manifest.chromaKey).not.toBe('#FF00FF');
const record = await records.getRecord(id);
expect(record.chromaKey).toBe(result.manifest.chromaKey);
+ // Near-generation-key palette ⇒ exact-key details may already be masked
+ // out of the locked artifact — the manifest must say so.
+ expect(result.manifest.chromaKeyWarning).toMatch(/generation key #FF00FF/);
+ });
+
+ it('rebases legacy repo-root manifest paths from a phase-1 import', async () => {
+ const id = newId();
+ await createCharacter(id);
+ const refDir = join(TEST_ROOT, 'sprites', id, 'reference');
+ await mkdir(refDir, { recursive: true });
+ await writeCandidatePng(join(refDir, `${id}-walk-south-v1.png`));
+ await writeFile(join(refDir, `${id}-reference-set-v1.json`), JSON.stringify({
+ schemaVersion: 1,
+ status: 'in-progress',
+ chromaKey: '#FF00FF',
+ mainReference: { path: `art-source/sprites/${id}/reference/${id}-walk-south-v1.png`, locked: true },
+ anchors: [
+ { id: 'walk-south', direction: 'south', status: 'locked', path: `art-source/sprites/${id}/reference/${id}-walk-south-v1.png` },
+ { id: 'walk-east', direction: 'east', status: 'pending', source: 'derive-from-main' },
+ ],
+ }));
+
+ const { manifest } = await getReferenceSet(id);
+ expect(manifest.mainReference.path).toBe(`reference/${id}-walk-south-v1.png`);
+ expect(manifest.anchors[0].path).toBe(`reference/${id}-walk-south-v1.png`);
+
+ // Anchor derivation must resolve the rebased main as its i2i init.
+ const result = await startReferenceGeneration(id, { target: 'east' });
+ expect(result.anchorId).toBe('walk-east');
+ expect(enqueueJob.mock.calls[0][0].params.initImagePath).toBe(join(TEST_ROOT, 'sprites', id, `reference/${id}-walk-south-v1.png`));
});
it('respects a user-pinned key instead of auto-selecting', async () => {