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

fix: add explicit canon image-ref removal route that PATCH's stale-write guard can't revert (#13208)

Adam Eivy0abc227baecd
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index 4f23035a18..22b0e7d042 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -464,6 +464,14 @@ export const removeUniverseCanonEntry = (universeId, kind, entryId, options = {}
...options,
}));
+// Remove one reference image from a canon entry's imageRefs[] (PATCH can't:
+// the server restores shorter lists as stale). Returns `{ universe, entry }`.
+export const removeUniverseCanonImageRef = (universeId, kind, entryId, filename, options = {}) =>
+ trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/canon/${encodeURIComponent(kind)}/${encodeURIComponent(entryId)}/image-refs/${encodeURIComponent(filename)}`, {
+ method: 'DELETE',
+ ...options,
+ }));
+
// Bulk lock/unlock every canon entry of a single kind. Returns
// `{ universe, kind, locked, changed, total }`.
export const setUniverseCanonLockAll = (universeId, kind, locked, options = {}) =>
diff --git a/server/routes/universeBuilder/canon.js b/server/routes/universeBuilder/canon.js
index 88495eb9b5..02947374d3 100644
--- a/server/routes/universeBuilder/canon.js
+++ b/server/routes/universeBuilder/canon.js
@@ -182,6 +182,19 @@ router.delete('/:id/canon/:kind/:entryId', asyncHandler(async (req, res) => {
res.json(result);
}));
+// Remove ONE reference image from a canon entry. PATCH can't do this: the
+// stale-write guard (`preserveImageRefsById`) restores any shorter imageRefs
+// list. The image file stays in the gallery.
+const imageRefParamsSchema = lockParamsSchema.extend({
+ filename: z.string().trim().min(1).max(512),
+});
+router.delete('/:id/canon/:kind/:entryId/image-refs/:filename', asyncHandler(async (req, res) => {
+ const { kind, filename } = validateRequest(imageRefParamsSchema, req.params);
+ const result = await canonSvc.removeCanonEntryImageRef(req.params.id, kind, req.params.entryId, filename)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
// Bulk lock/unlock every canon entry of a single kind. Powers the
// "Lock all / Unlock all" buttons in the Universe Builder canon section.
router.patch('/:id/canon/:kind/lock-all', asyncHandler(async (req, res) => {
diff --git a/server/routes/universeBuilder/index.test.js b/server/routes/universeBuilder/index.test.js
index a3c86591ee..b63dce1a0f 100644
--- a/server/routes/universeBuilder/index.test.js
+++ b/server/routes/universeBuilder/index.test.js
@@ -55,6 +55,9 @@ const applyCanonImageCorrectionMock = vi.fn(async (_universeId, kind, entryId, b
universe: { id: _universeId },
entry: { id: entryId, [kind === 'character' ? 'physicalDescription' : 'description']: body.description, primaryImageRef: body.imageFilename },
}));
+const removeCanonEntryImageRefMock = vi.fn(async (universeId, kind, entryId) => ({
+ universe: { id: universeId }, entry: { id: entryId, imageRefs: [] },
+}));
const removeCanonEntryMock = vi.fn(async (universeId, kind, entryId) => ({
universe: { id: universeId, characters: [], places: [], objects: [] },
entry: { id: entryId, name: 'Alex', imageRefs: ['alex.png'], ingredientId: 'ing-alex' },
@@ -65,6 +68,7 @@ vi.mock('../../services/universeCanon.js', async () => {
...actual,
applyCanonImageCorrection: (...args) => applyCanonImageCorrectionMock(...args),
removeCanonEntry: (...args) => removeCanonEntryMock(...args),
+ removeCanonEntryImageRef: (...args) => removeCanonEntryImageRefMock(...args),
};
});
const expandEntityFromImagesMock = vi.fn(async () => ({ fields: { pronouns: 'she/her' }, updatedFields: ['pronouns'], llm: { provider: 'mock', model: null } }));
@@ -1600,6 +1604,24 @@ describe('universe-builder routes', () => {
});
});
+ describe('DELETE /:id/canon/:kind/:entryId/image-refs/:filename', () => {
+ it('routes to the service with the decoded filename', async () => {
+ removeCanonEntryImageRefMock.mockClear();
+ const res = await request(buildApp())
+ .delete('/api/universe-builder/uni-1/canon/character/chr-1/image-refs/alex%20a.png');
+ expect(res.status).toBe(200);
+ expect(removeCanonEntryImageRefMock).toHaveBeenCalledWith('uni-1', 'character', 'chr-1', 'alex a.png');
+ });
+
+ it('rejects an unknown kind before invoking the service', async () => {
+ removeCanonEntryImageRefMock.mockClear();
+ const res = await request(buildApp())
+ .delete('/api/universe-builder/uni-1/canon/monster/chr-1/image-refs/a.png');
+ expect(res.status).toBe(400);
+ expect(removeCanonEntryImageRefMock).not.toHaveBeenCalled();
+ });
+ });
+
describe('POST /refine-prompts (style-reference image)', () => {
it('resolves the image filename to an absolute path before the service', async () => {
const res = await request(buildApp())
diff --git a/server/services/universeCanon.js b/server/services/universeCanon.js
index 0dfde54239..52548fde40 100644
--- a/server/services/universeCanon.js
+++ b/server/services/universeCanon.js
@@ -822,6 +822,51 @@ export async function removeCanonEntry(universeId, kind, entryId) {
return { universe: updated, entry: removed };
}
+/**
+ * Deliberately remove ONE reference image from a canon entry's `imageRefs[]`.
+ * PATCH can't express this: `preserveImageRefsById` treats any shorter list as
+ * a stale round-trip and restores it, so removal gets its own mutator-form
+ * write (which bypasses that guard and still projects to the catalog row).
+ * Also clears `primaryImageRef` when it pointed at the file and drops
+ * identity-pack assets using it, so nothing dangles. The image file itself
+ * stays in the gallery. Returns `{ universe, entry }`.
+ */
+export async function removeCanonEntryImageRef(universeId, kind, entryId, filename) {
+ assertCanonKind(kind);
+ const field = BIBLE_FIELD[kind];
+ let entryFound = false;
+ let refFound = false;
+ const updated = await updateUniverse(universeId, (cur) => {
+ entryFound = false;
+ refFound = false;
+ const list = Array.isArray(cur[field]) ? cur[field] : [];
+ const target = list.find((e) => e.id === entryId);
+ if (!target) return null;
+ entryFound = true;
+ const refs = Array.isArray(target.imageRefs) ? target.imageRefs : [];
+ if (!refs.includes(filename)) return null;
+ refFound = true;
+ const next = { ...target, imageRefs: refs.filter((f) => f !== filename) };
+ if (target.primaryImageRef === filename) next.primaryImageRef = null;
+ if (Array.isArray(target.identityPack?.assets)) {
+ next.identityPack = {
+ ...target.identityPack,
+ assets: target.identityPack.assets.filter((a) => a?.imageRef !== filename),
+ };
+ }
+ return { [field]: list.map((e) => (e === target ? next : e)) };
+ });
+ if (!entryFound) {
+ throw new ServerError(`Canon ${kind} ${entryId} not found in universe`, { status: 404, code: 'UNIVERSE_CANON_NOT_FOUND' });
+ }
+ if (!refFound) {
+ throw new ServerError(`Image ${filename} is not attached to ${kind} ${entryId}`, { status: 404, code: 'UNIVERSE_CANON_IMAGE_REF_NOT_FOUND' });
+ }
+ console.log(`🗑️ Removed image ref ${filename} from canon ${kind} ${entryId} in universe ${shortId(universeId)}`);
+ const entry = (updated[field] || []).find((e) => e.id === entryId) || null;
+ return { universe: updated, entry };
+}
+
/**
* Strip a filename from every `imageRefs[]` across every universe's
* characters/places/objects, and from every top-level `styleReferences[]`
diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.js
index 02582ee253..4c08541460 100644
--- a/server/services/universeCanon.test.js
+++ b/server/services/universeCanon.test.js
@@ -120,6 +120,40 @@ describe('universeCanon — setCanonEntryLock', () => {
});
});
+describe('universeCanon — removeCanonEntryImageRef', () => {
+ it('removes the ref, clears primary + identity-pack use, and survives where PATCH is reverted', async () => {
+ const w = await seedUniverseWithCharacters([
+ {
+ name: 'Alex', physicalDescription: 'jacket',
+ imageRefs: ['alex-a.png', 'alex-b.png'], primaryImageRef: 'alex-b.png',
+ identityPack: { assets: [
+ { role: 'front', imageRef: 'alex-b.png', approved: true },
+ { role: 'profile', imageRef: 'alex-a.png', approved: true },
+ ] },
+ },
+ ]);
+ const id = w.characters[0].id;
+ // The stale-write guard still restores a shorter list sent via PATCH.
+ const patched = await svc.updateUniverse(w.id, { characters: [{ ...w.characters[0], imageRefs: [] }] });
+ expect(patched.characters[0].imageRefs).toEqual(['alex-a.png', 'alex-b.png']);
+
+ const { entry } = await canonSvc.removeCanonEntryImageRef(w.id, 'character', id, 'alex-b.png');
+ expect(entry.imageRefs).toEqual(['alex-a.png']);
+ expect(entry.primaryImageRef).toBeNull();
+ expect(entry.identityPack.assets.map((a) => a.imageRef)).toEqual(['alex-a.png']);
+ const reread = (await svc.listUniverses())[0];
+ expect(reread.characters[0].imageRefs).toEqual(['alex-a.png']);
+ });
+
+ it('404s on an unknown entry or an unattached image', async () => {
+ const w = await seedUniverseWithCharacters([{ name: 'Alex', physicalDescription: 'jacket', imageRefs: ['a.png'] }]);
+ await expect(canonSvc.removeCanonEntryImageRef(w.id, 'character', 'nope', 'a.png'))
+ .rejects.toMatchObject({ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND' });
+ await expect(canonSvc.removeCanonEntryImageRef(w.id, 'character', w.characters[0].id, 'other.png'))
+ .rejects.toMatchObject({ status: 404, code: 'UNIVERSE_CANON_IMAGE_REF_NOT_FOUND' });
+ });
+});
+
describe('universeCanon — removeCanonEntry', () => {
it('drops only the target entry, persists, and scrubs neither its image refs nor its catalog link', async () => {
// Removal is scoped to the canon array: it must not purge imageRefs (the