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 (claude): route sprite i2i through the image-input allowlist, fix multipart fileFilter signature, serialize manifest writes, canonical post-lock key, resilient render poll

[._.]/ Adam Eivyc0ce8a1e7588
diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsx
index 113ad10a3f..15b27a16d5 100644
--- a/client/src/components/sprites/ReferenceWorkflow.jsx
+++ b/client/src/components/sprites/ReferenceWorkflow.jsx
@@ -44,7 +44,7 @@ function CandidateTile({ recordId, candidate, locking, onLock }) {
{confirming ? (
<div className="flex items-center gap-1 text-xs">
<span className="text-port-warning">Freeze forever?</span>
- <button onClick={() => { setConfirming(false); onLock(candidate); }} className="px-1.5 py-0.5 bg-port-accent text-white rounded">Lock</button>
+ <button onClick={() => { setConfirming(false); onLock(candidate); }} disabled={locking} className="px-1.5 py-0.5 bg-port-accent text-white rounded disabled:opacity-50">Lock</button>
<button onClick={() => setConfirming(false)} className="px-1.5 py-0.5 text-gray-400 hover:text-white">Cancel</button>
</div>
) : (
@@ -92,10 +92,17 @@ 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]) => ({
- target, job: await getMediaJob(jobId).catch(() => null),
- })));
- const finished = results.filter(({ job }) => !job || ['completed', 'failed', 'canceled'].includes(job.status));
+ const results = await Promise.all(Object.entries(pendingJobs).map(async ([target, jobId]) => {
+ try {
+ return { target, job: await getMediaJob(jobId) };
+ } catch (err) {
+ // Only a 404 means the job is truly gone — a transient fetch
+ // failure must NOT drop the entry (that would re-enable Generate
+ // mid-render and stop the auto-refresh); retry on the next tick.
+ return { target, job: null, gone: err?.status === 404 };
+ }
+ }));
+ const finished = results.filter(({ job, gone }) => (job ? ['completed', 'failed', 'canceled'].includes(job.status) : gone));
if (finished.length === 0) return;
setPendingJobs((prev) => {
const next = { ...prev };
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index 1d49a32cf1..2aaec50ae3 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -1395,6 +1395,20 @@ export const resolveImageRef = makePathResolver(() => PATHS.imageRefs);
*/
export const resolveImageCleanTmp = makePathResolver(() => PATHS.imageCleanTmp);
+/**
+ * Resolve a sprite reference asset used as an image-gen init image (issue
+ * #2896 — anchors i2i from the locked main reference; uploaded design
+ * references). `data/sprites/` is a server-managed NESTED tree, so unlike
+ * the single-level basename resolvers above this accepts only an absolute
+ * path already inside the sprites root (no basename fallback — a bare
+ * filename is ambiguous across records) and validates containment.
+ */
+export function resolveSpriteImageInput(rawPath) {
+ if (typeof rawPath !== 'string' || !rawPath) return null;
+ const resolved = resolvePath(rawPath);
+ return isPathInsideDir(PATHS.sprites, resolved) ? resolved : null;
+}
+
/**
* Resolve a shipped visual template filename (e.g. character reference-sheet
* layout PNG) to an absolute path under `PATHS.visualTemplates`. Caches
@@ -1448,6 +1462,10 @@ const IMAGE_INPUT_RESOLVERS = [
// Image Cleaner temp init images (issue #2264) — the GPU FLUX round-trip
// stages sync-cleaned bytes here as the img2img init.
['imageCleanTmp', resolveImageCleanTmp],
+ // Sprite reference assets (issue #2896) — the locked main reference /
+ // uploaded design reference as the anchors' i2i init. Absolute-only
+ // (returns null on basename input, so the fall-through loop skips it).
+ ['sprites', resolveSpriteImageInput],
];
export function resolveImageInputPath(rawPath) {
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index f00f641bb7..2e5663aadc 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -34,7 +34,9 @@ const ACCEPTED_REFERENCE_MIME = new Set(['image/png', 'image/jpeg', 'image/webp'
const referenceUpload = optionalUploadFields(['referenceImage'], {
limits: { fileSize: MAX_REFERENCE_UPLOAD_BYTES },
- fileFilter: (file) => ACCEPTED_REFERENCE_MIME.has(file.mimetype),
+ // multer-style (req, file, cb) — streamMultipart requires the callback to
+ // be invoked synchronously (see routes/imageGen.js for the sibling).
+ fileFilter: (_req, file, cb) => cb(null, ACCEPTED_REFERENCE_MIME.has((file.mimetype || '').toLowerCase())),
});
router.get('/', asyncHandler(async (_req, res) => {
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index e38e39901e..382396560a 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -116,6 +116,55 @@ describe('sprites routes', () => {
expect(reference.startReferenceGeneration).not.toHaveBeenCalled();
});
+ // Build a multipart/form-data body with one file part + text fields —
+ // exercises the real streamMultipart path (the fileFilter signature bug
+ // class is invisible to JSON-only tests).
+ const buildMultipart = (boundary, { fileBytes = Buffer.from('\x89PNGfake'), mime = 'image/png', fields = {} } = {}) => {
+ const parts = [];
+ for (const [k, v] of Object.entries(fields)) {
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${k}"\r\n\r\n${v}\r\n`));
+ }
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="referenceImage"; filename="design.png"\r\nContent-Type: ${mime}\r\n\r\n`));
+ parts.push(fileBytes);
+ parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
+ return Buffer.concat(parts);
+ };
+
+ it('POST /:id/reference/generate accepts a multipart design-image upload for main', async () => {
+ const boundary = '----spritetest';
+ const res = await request(app)
+ .post('/api/sprites/pioneer/reference/generate')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(buildMultipart(boundary, { fields: { target: 'main', designPrompt: 'a ranger' } }));
+ expect(res.status).toBe(200);
+ expect(reference.startReferenceGeneration).toHaveBeenCalledWith(
+ 'pioneer',
+ expect.objectContaining({ target: 'main', designPrompt: 'a ranger' }),
+ expect.objectContaining({ originalname: 'design.png', tempPath: expect.any(String) }),
+ );
+ });
+
+ it('POST /:id/reference/generate rejects an upload for a non-main target', async () => {
+ const boundary = '----spritetest2';
+ const res = await request(app)
+ .post('/api/sprites/pioneer/reference/generate')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(buildMultipart(boundary, { fields: { target: 'east' } }));
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('UPLOAD_MAIN_ONLY');
+ expect(reference.startReferenceGeneration).not.toHaveBeenCalled();
+ });
+
+ it('POST /:id/reference/generate rejects a non-image mime upload', async () => {
+ const boundary = '----spritetest3';
+ const res = await request(app)
+ .post('/api/sprites/pioneer/reference/generate')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(buildMultipart(boundary, { mime: 'application/zip', fields: { target: 'main' } }));
+ expect(res.status).toBe(400);
+ expect(reference.startReferenceGeneration).not.toHaveBeenCalled();
+ });
+
it('POST /:id/reference/generate rejects a non-queueable mode', async () => {
const r = await request(app).post('/api/sprites/pioneer/reference/generate')
.send({ target: 'main', mode: 'external' });
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index e68925c207..4d499e566f 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -22,6 +22,7 @@ import {
importFileToDir, listDirectoryByExtension,
} from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { enqueueJob } from '../mediaJobQueue/index.js';
import { IMAGE_GEN_MODE, resolveQueueImageMode } from '../imageGen/modes.js';
import { resolveImageCleaners } from '../imageGen/index.js';
@@ -44,6 +45,13 @@ const UPLOAD_DEFAULT_STRENGTH = 0.65;
const manifestRelPath = (id) => `reference/${id}-reference-set-v1.json`;
+// Serialize the manifest read-modify-write per record: two overlapping locks
+// (or a generate racing a lock) would otherwise both load the pre-write
+// manifest and the second save would erase the first's locked state —
+// breaking the immutability contract. Same convention as the completion
+// hook's per-record queue.
+const manifestWriteTail = createKeyCachedQueue();
+
async function loadManifest(recordId) {
return readJSONFile(join(spriteDir(recordId), manifestRelPath(recordId)), null);
}
@@ -148,11 +156,18 @@ export async function getReferenceSet(recordId) {
* multipart parse (main target only) — copied into the record's
* reference/uploads/ so provenance survives the temp-file sweep.
*/
-export async function startReferenceGeneration(recordId, body, upload = null) {
+export function startReferenceGeneration(recordId, body, upload = null) {
+ return manifestWriteTail(recordId, () => startReferenceGenerationImpl(recordId, body, upload));
+}
+
+async function startReferenceGenerationImpl(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 || DEFAULT_CHROMA_KEY;
+ // Once the main is locked, the manifest's key is canonical (set at lock —
+ // possibly auto-selected); a later record-level repin must not fork
+ // subsequent anchors onto a different background than the frozen set.
+ const genKey = manifest.chromaKey || record.chromaKey || DEFAULT_CHROMA_KEY;
const settings = await getSettings();
const mode = resolveQueueImageMode(body.mode, settings);
@@ -277,7 +292,11 @@ async function loadCandidateSidecar(candAbs) {
* main also runs the dynamic chroma-key selection (unless the user already
* pinned one on the record).
*/
-export async function lockReference(recordId, { target, candidate }) {
+export function lockReference(recordId, args) {
+ return manifestWriteTail(recordId, () => lockReferenceImpl(recordId, args));
+}
+
+async function lockReferenceImpl(recordId, { target, candidate }) {
const record = await requireCharacter(recordId);
// Seed on demand — a candidate may predate the manifest (e.g. files placed
// by an import or a crash-recovered tree); the lock is what makes it real.
@@ -347,7 +366,8 @@ 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 || DEFAULT_CHROMA_KEY;
+ // Manifest key is canonical after main lock — see startReferenceGeneration.
+ const canvasKey = manifest.chromaKey || record.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 });
diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.js
index 2c54f28af4..b047444782 100644
--- a/server/services/sprites/reference.test.js
+++ b/server/services/sprites/reference.test.js
@@ -15,17 +15,18 @@ import { mkdir, writeFile, readFile } from 'fs/promises';
const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-reference-test-'));
+// MUTATE actual.PATHS (don't replace the object): fileUtils' internal
+// resolvers (resolveImageInputPath / resolveSpriteImageInput) close over the
+// module-level PATHS reference, and the initImagePath assertion below needs
+// them to see the test roots.
vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
const actual = await importOriginal();
- return {
- ...actual,
- PATHS: {
- ...actual.PATHS,
- data: TEST_ROOT,
- sprites: join(TEST_ROOT, 'sprites'),
- images: join(TEST_ROOT, 'images'),
- },
- };
+ Object.assign(actual.PATHS, {
+ data: TEST_ROOT,
+ sprites: join(TEST_ROOT, 'sprites'),
+ images: join(TEST_ROOT, 'images'),
+ });
+ return actual;
});
const enqueueJob = vi.fn(() => ({ jobId: 'job-1234567890', position: 0, status: 'queued' }));
@@ -154,6 +155,11 @@ describe('startReferenceGeneration', () => {
expect(result.anchorId).toBe('walk-east');
const call = enqueueJob.mock.calls[0][0];
expect(call.params.initImagePath).toContain(`${id}-walk-south-v1.png`);
+ // The queue's providers re-validate initImagePath through the approved
+ // image-input roots — a sprite path must survive that gate or the i2i
+ // silently degrades to text-to-image (identity drift).
+ const { resolveImageInputPath } = await import('../../lib/fileUtils.js');
+ expect(resolveImageInputPath(call.params.initImagePath)).toBe(call.params.initImagePath);
expect(call.params.initImageStrength).toBe(0.8);
expect(call.params.prompt).toContain('strict right-facing side profile');
expect(call.params.prompt).toContain('magenta (#FF00FF)'); // green char kept magenta