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 r5): max-channel mask metric, lock-serialized key patch, tombstone guard, submit sentinel, shared local default

[._.]/ Adam Eivyc0400c92557d
diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsx
index 406d95bcf8..0c815aed09 100644
--- a/client/src/components/sprites/ReferenceWorkflow.jsx
+++ b/client/src/components/sprites/ReferenceWorkflow.jsx
@@ -130,7 +130,8 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {
useEffect(() => {
if (Object.keys(pendingJobs).length === 0) return undefined;
const timer = setInterval(async () => {
- const results = await Promise.all(Object.entries(pendingJobs).map(async ([target, jobId]) => {
+ const entries = Object.entries(pendingJobs).filter(([, jobId]) => jobId !== 'submitting');
+ const results = await Promise.all(entries.map(async ([target, jobId]) => {
try {
return { target, job: await getMediaJob(jobId) };
} catch (err) {
@@ -164,7 +165,13 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {
return acc;
}, {}), [candidates]);
+ // Sentinel jobId while the enqueue request is in flight — reserves the
+ // target immediately so a double-click (or a slow multipart upload) can't
+ // submit two paid renders. The poll skips sentinel entries.
+ const SUBMITTING = 'submitting';
+
const generate = async (target) => {
+ setPendingJobs((prev) => ({ ...prev, [target]: SUBMITTING }));
try {
const { jobId } = await generateSpriteReference(recordId, {
target,
@@ -175,6 +182,11 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {
setUploadFile(null);
if (fileInputRef.current) fileInputRef.current.value = '';
} catch (err) {
+ setPendingJobs((prev) => {
+ const next = { ...prev };
+ if (next[target] === SUBMITTING) delete next[target];
+ return next;
+ });
toast.error(err?.message || `Failed to queue ${target} render`);
}
};
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index 3d94524df5..ee84c82830 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -22,10 +22,12 @@ import {
} from '../lib/validation.js';
import { optionalUploadFields } from '../lib/multipart.js';
import {
- listRecords, getRecordWithAssets, createCharacter, updateRecord, deleteRecord,
+ listRecords, getRecordWithAssets, createCharacter, deleteRecord,
} from '../services/sprites/records.js';
import { importFromSource } from '../services/sprites/importer.js';
-import { getReferenceSet, startReferenceGeneration, lockReference } from '../services/sprites/reference.js';
+import {
+ getReferenceSet, startReferenceGeneration, lockReference, patchSpriteRecord,
+} from '../services/sprites/reference.js';
const router = Router();
@@ -90,18 +92,12 @@ router.post('/:id/reference/lock', asyncHandler(async (req, res) => {
res.json(await lockReference(req.params.id, body));
}));
+// Chroma-key changes route through patchSpriteRecord, which re-checks the
+// lock state inside the same per-record write tail as `/reference/lock`
+// (409 CHROMA_KEY_LOCKED after the main freezes).
router.patch('/:id', asyncHandler(async (req, res) => {
const patch = validateRequest(spriteRecordUpdateSchema, req.body);
- // Once the main reference is locked the manifest key is frozen with the
- // artifacts — a record-level repin would only make the record/UI disagree
- // with the immutable set.
- if ('chromaKey' in patch) {
- const reference = await getReferenceSet(req.params.id);
- if (reference.manifest?.mainReference?.locked) {
- throw new ServerError('Chroma key is frozen with the locked reference set', { status: 409, code: 'CHROMA_KEY_LOCKED' });
- }
- }
- res.json(await updateRecord(req.params.id, patch));
+ res.json(await patchSpriteRecord(req.params.id, patch));
}));
router.delete('/:id', asyncHandler(async (req, res) => {
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index 6cda0227ec..0a0da49ed2 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -18,6 +18,7 @@ vi.mock('../services/sprites/reference.js', () => ({
getReferenceSet: vi.fn(async () => ({ manifest: null, candidates: [] })),
startReferenceGeneration: vi.fn(async () => ({ jobId: 'j1', mode: 'codex', target: 'main', anchorId: 'walk-south' })),
lockReference: vi.fn(async () => ({ manifest: { status: 'in-progress' }, candidates: [] })),
+ patchSpriteRecord: vi.fn(async (id, patch) => ({ id, ...patch })),
}));
import * as records from '../services/sprites/records.js';
@@ -185,25 +186,21 @@ describe('sprites routes', () => {
expect(r.status).toBe(400);
});
- it('PATCH /:id accepts the three standard chroma keys and null', async () => {
+ it('PATCH /:id accepts the three standard chroma keys and null, delegating to the lock-aware patch', async () => {
for (const chromaKey of ['#FF00FF', '#00FF00', '#0000FF', null]) {
const r = await request(app).patch('/api/sprites/pioneer').send({ chromaKey });
expect(r.status, String(chromaKey)).toBe(200);
}
+ expect(reference.patchSpriteRecord).toHaveBeenCalledTimes(4);
+ expect(reference.patchSpriteRecord).toHaveBeenLastCalledWith('pioneer', { chromaKey: null });
});
- it('PATCH /:id 409s a chroma-key change once the main reference is locked', async () => {
- reference.getReferenceSet.mockResolvedValueOnce({ manifest: { mainReference: { locked: true } }, candidates: [] });
+ it('PATCH /:id surfaces the service 409 for a post-lock chroma-key change', async () => {
+ const err = Object.assign(new Error('Chroma key is frozen with the locked reference set'), { status: 409, code: 'CHROMA_KEY_LOCKED' });
+ reference.patchSpriteRecord.mockRejectedValueOnce(err);
const r = await request(app).patch('/api/sprites/pioneer').send({ chromaKey: '#00FF00' });
expect(r.status).toBe(409);
expect(r.body.code).toBe('CHROMA_KEY_LOCKED');
- expect(records.updateRecord).not.toHaveBeenCalled();
- });
-
- it('PATCH /:id without a chromaKey change skips the reference lookup', async () => {
- const r = await request(app).patch('/api/sprites/pioneer').send({ notes: 'n' });
- expect(r.status).toBe(200);
- expect(reference.getReferenceSet).not.toHaveBeenCalled();
});
it('PATCH /:id rejects hex colors outside the three-key set', async () => {
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index a3f613f3e3..3643539b86 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -30,7 +30,7 @@ import { extractGatedRepo, isGatedRepoError } from '../../lib/hfErrors.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { createLineReader } from '../../lib/streamLines.js';
-import { IMAGE_GEN_MODE } from './modes.js';
+import { IMAGE_GEN_MODE, LOCAL_IMAGEGEN_DEFAULT_MODEL } from './modes.js';
import { computePixelDelta } from './regen.js';
import { parseByteProgress, formatDownloadMessage } from '../videoGen/generateVideoHelpers.js';
@@ -456,7 +456,7 @@ export function resolveOutputPlacement(outputTarget) {
return { outputDir, skipSidecar, isGallery };
}
-export async function generateImage({ pythonPath, prompt = '', negativePrompt = '', modelId = 'dev', width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], jobId: providedJobId = null, cleanC2PA = false, denoise = false, regenOf = null, upscaleTo = null, outputTarget = null }) {
+export async function generateImage({ pythonPath, prompt = '', negativePrompt = '', modelId = LOCAL_IMAGEGEN_DEFAULT_MODEL, width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], jobId: providedJobId = null, cleanC2PA = false, denoise = false, regenOf = null, upscaleTo = null, outputTarget = null }) {
// Empty prompt is allowed: img2img / edit / unconditional renders are driven
// by the init image (or run unconditionally), so text isn't required. The
// mflux/diffusers runners accept an empty `--prompt` — the regen pass (#912)
diff --git a/server/services/imageGen/modes.js b/server/services/imageGen/modes.js
index 99f54d7f58..3ec5873fdc 100644
--- a/server/services/imageGen/modes.js
+++ b/server/services/imageGen/modes.js
@@ -57,6 +57,12 @@ export const describeFidelity = (strength) => {
export const CODEX_IMAGEGEN_DEFAULT_MODEL = 'gpt-5.6-luna';
export const CODEX_IMAGEGEN_DEFAULT_EFFORT = 'low';
+// The local runner's fallback model id when neither the request nor
+// settings.imageGen.local.modelId names one (local.js's parameter default).
+// Exported so provenance writers (sprite candidate sidecars, #2896) can
+// record the model that actually ran without hardcoding a second copy.
+export const LOCAL_IMAGEGEN_DEFAULT_MODEL = 'dev';
+
/**
* Resolve the queue-capable image mode for a render request: the per-request
* override (honored only when that backend is enabled/available), else the
diff --git a/server/services/sprites/normalize.js b/server/services/sprites/normalize.js
index d0713ad94d..bc6b100946 100644
--- a/server/services/sprites/normalize.js
+++ b/server/services/sprites/normalize.js
@@ -12,8 +12,10 @@
* 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. Mask threshold:
- * a pixel is foreground when luma(|pixel − key|) > 40 (Pillow's L convert).
+ * never rescaled — only the canvas is sized around them. Mask threshold: a
+ * pixel is foreground when max-channel |pixel − key| > 40 — a DELIBERATE
+ * deviation from the source's luma metric, which is blind to black-vs-blue
+ * (see MASK_CHANNEL_THRESHOLD).
*/
import sharp from 'sharp';
@@ -23,7 +25,14 @@ 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;
+// Max-channel distance from the key, NOT the source pipeline's luma-of-diff:
+// luma weights blue at 0.114, so against the blue key a BLACK pixel scores
+// 255·0.114 ≈ 29 — under any usable threshold — and black outlines/hair
+// would be silently erased. Luma was safe only because the source pipeline
+// hardcoded magenta; the dynamic key set (#2895) makes the metric wrong.
+// Max-channel treats all three keys symmetrically (black vs any pure key
+// differs by 255 in at least one channel).
+const MASK_CHANNEL_THRESHOLD = 40;
// Re-export for existing consumers/tests; the definition lives in the pure
// color-math module so chromaKey.js can use it without importing sharp.
@@ -51,9 +60,7 @@ export async function analyzeForeground(src, maskKeyHex) {
const dr = Math.abs(data[i] - key.r);
const dg = Math.abs(data[i + 1] - key.g);
const db = Math.abs(data[i + 2] - key.b);
- // Pillow convert("L") luminance of the difference image.
- const luma = (dr * 299 + dg * 587 + db * 114) / 1000;
- if (luma > MASK_LUMA_THRESHOLD) {
+ if (Math.max(dr, dg, db) > MASK_CHANNEL_THRESHOLD) {
mask[y * width + x] = 1;
if (x < left) left = x;
if (x > right) right = x;
diff --git a/server/services/sprites/normalize.test.js b/server/services/sprites/normalize.test.js
index 91e179e51f..c2e85dfb2a 100644
--- a/server/services/sprites/normalize.test.js
+++ b/server/services/sprites/normalize.test.js
@@ -74,6 +74,21 @@ describe('normalizeAnchorFrame', () => {
expect(px(img, 7, 3)).toEqual(GREEN); // character pixels untouched
});
+ it('preserves black pixels against the blue key (max-channel mask, not luma)', async () => {
+ const src = join(dir, 'blue-black.png');
+ const dest = join(dir, 'blue-black-out.png');
+ const BLUE = { r: 0, g: 0, b: 255 };
+ const BLACK = { r: 0, g: 0, b: 0 };
+ await writeCandidate(src, { bg: BLUE, fg: BLACK });
+ const result = await normalizeAnchorFrame(src, dest, { maskKeyHex: '#0000FF', canvasKeyHex: '#0000FF' });
+ // Under the source pipeline's luma metric this black rect scores
+ // 255·0.114 ≈ 29 < 40 and would vanish entirely (copiedThrough).
+ expect(result).toMatchObject({ charW: 10, charH: 20 });
+ const img = await readRaw(dest);
+ expect(px(img, 7, 3)).toEqual(BLACK);
+ expect(px(img, 0, 0)).toEqual(BLUE);
+ });
+
it('copies through an image with no detectable foreground', async () => {
const src = join(dir, 'blank.png');
const dest = join(dir, 'blank-out.png');
diff --git a/server/services/sprites/records.js b/server/services/sprites/records.js
index 62111b44c5..100fabcb0a 100644
--- a/server/services/sprites/records.js
+++ b/server/services/sprites/records.js
@@ -72,6 +72,13 @@ export async function createCharacter({ id, name, spec = null }) {
if (!isValidSpriteId(recordId)) {
throw new ServerError(`Cannot derive a valid sprite id from "${name}" — pass an explicit id`, { status: 400, code: 'INVALID_SPRITE_ID' });
}
+ // Tombstoned ids stay taken: the old data/sprites/<id> tree (possibly a
+ // LOCKED reference set) is still on disk, so a re-created record would
+ // silently inherit a frozen identity it can never regenerate.
+ const existing = await getRecord(recordId, { includeDeleted: true });
+ if (existing?.deleted) {
+ throw new ServerError(`A deleted record still holds the id "${recordId}" (its assets remain on disk) — pass a different id`, { status: 409, code: 'ID_TOMBSTONED' });
+ }
return createRecord({ kind: 'character', name, spec }, recordId);
}
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index d7178e2325..0985032ca5 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -24,7 +24,10 @@ import {
import { ServerError } from '../../lib/errorHandler.js';
import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { enqueueJob } from '../mediaJobQueue/index.js';
-import { IMAGE_GEN_MODE, resolveQueueImageMode, CODEX_IMAGEGEN_DEFAULT_MODEL } from '../imageGen/modes.js';
+import {
+ IMAGE_GEN_MODE, resolveQueueImageMode,
+ CODEX_IMAGEGEN_DEFAULT_MODEL, LOCAL_IMAGEGEN_DEFAULT_MODEL,
+} from '../imageGen/modes.js';
import { resolveImageCleaners } from '../imageGen/index.js';
import { getSettings } from '../settings.js';
import { getRecord, updateRecord } from './records.js';
@@ -153,6 +156,24 @@ function combinedClipWarning(palette, maskKeyHex, canvasKeyHex) {
].filter(Boolean).join(' — ') || null;
}
+/**
+ * Record patch that is safe against a concurrent lock: a chromaKey change
+ * must re-check the manifest INSIDE the per-record write tail, or a PATCH
+ * racing `/reference/lock` could observe an unlocked manifest and then land
+ * a pin that disagrees with the just-frozen canonical key (permanently,
+ * since post-lock changes 409). Non-key patches pass straight through.
+ */
+export function patchSpriteRecord(recordId, patch) {
+ if (!('chromaKey' in patch)) return updateRecord(recordId, patch);
+ return manifestWriteTail(recordId, async () => {
+ const manifest = await loadManifest(recordId);
+ if (manifest?.mainReference?.locked) {
+ throw new ServerError('Chroma key is frozen with the locked reference set', { status: 409, code: 'CHROMA_KEY_LOCKED' });
+ }
+ return updateRecord(recordId, patch);
+ });
+}
+
/**
* Reference-set view for the detail endpoint: the manifest (null until the
* first generate) plus the reviewable candidates parsed from their
@@ -261,7 +282,7 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
const effectiveModel = mode === IMAGE_GEN_MODE.CODEX
? codexModel
: mode === IMAGE_GEN_MODE.LOCAL
- ? (body.model || settings.imageGen?.local?.modelId || null)
+ ? (body.model || settings.imageGen?.local?.modelId || LOCAL_IMAGEGEN_DEFAULT_MODEL)
: null;
const baseParams = {
prompt,
diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.js
index bfe93ec7de..14e01be632 100644
--- a/server/services/sprites/reference.test.js
+++ b/server/services/sprites/reference.test.js
@@ -51,7 +51,7 @@ vi.mock('../settings.js', () => ({ getSettings: async () => settings }));
const records = await import('./records.js');
const {
- getReferenceSet, startReferenceGeneration, attachReferenceCandidate, lockReference,
+ getReferenceSet, startReferenceGeneration, attachReferenceCandidate, lockReference, patchSpriteRecord,
} = await import('./reference.js');
let seq = 0;
@@ -367,6 +367,28 @@ describe('lockReference', () => {
.rejects.toMatchObject({ code: 'INVALID_ASSET_PATH' });
});
+ it('patchSpriteRecord allows a key change pre-lock and 409s it post-lock', async () => {
+ const id = newId();
+ await createCharacter(id);
+ const patched = await patchSpriteRecord(id, { chromaKey: '#0000FF' });
+ expect(patched.chromaKey).toBe('#0000FF');
+ await patchSpriteRecord(id, { chromaKey: null }); // back to auto so lockMain selects
+ await lockMain(id);
+ await expect(patchSpriteRecord(id, { chromaKey: '#00FF00' }))
+ .rejects.toMatchObject({ status: 409, code: 'CHROMA_KEY_LOCKED' });
+ // Non-key fields stay patchable after lock.
+ const notes = await patchSpriteRecord(id, { notes: 'still editable' });
+ expect(notes.notes).toBe('still editable');
+ });
+
+ it('refuses to recreate a character over a tombstoned id', async () => {
+ const id = newId();
+ await records.createCharacter({ id, name: 'Hero' });
+ await records.deleteRecord(id);
+ await expect(records.createCharacter({ id, name: 'Hero' }))
+ .rejects.toMatchObject({ status: 409, code: 'ID_TOMBSTONED' });
+ });
+
it('never overwrites an existing versioned artifact (crash-recovery lands on v2)', async () => {
const id = newId();
await createCharacter(id);