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
feat([clear-pending-sheet-slot-on-entry-delete]): clear pending sheet slots on character/universe delete
[._.]/ Adam Eivyb7694576c2a6
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex 981e9c8ea8..3262a99979 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -40,6 +40,9 @@ import {import { sanitizeOrigin } from '../lib/sharingOrigin.js';import { emitRecordUpdated, emitRecordDeleted } from './sharing/recordEvents.js';import { renameCollectionForUniverse, unlinkCollectionsForUniverse } from './mediaCollections.js';+import {+ clearPendingSheetSlot, clearPendingSheetSlotsForUniverse,+} from './universeCharacterSheetSlot.js';// Bumped when a sanitizer-time backfill changes how on-disk universes are// shaped, so future migrations can gate on the prior version.@@ -916,7 +919,7 @@ export async function updateUniverse(id, patchOrMutator = {}) {// unchanged record (no `updatedAt` bump, no rename cascade, no// `recordUpdated` emit).const isMutator = typeof patchOrMutator === 'function';- const { merged, nameChanged, skipped } = await queueUniverseWrite(async () => {+ const { merged, nameChanged, skipped, removedCharacterIds } = await queueUniverseWrite(async () => {const state = await readState();const idx = state.universes.findIndex((w) => w.id === id);if (idx < 0) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);@@ -1072,9 +1075,30 @@ export async function updateUniverse(id, patchOrMutator = {}) {}state.universes[idx] = mergedRecord;await writeState(state);- return { merged: mergedRecord, nameChanged: mergedRecord.name !== cur.name, skipped: false };+ // Diff inside the queue so we read against the freshest merged state;+ // gate on patches that could have touched characters (mutator or+ // literal-PATCH carrying `characters`) — rename/scalar PATCHes are the+ // common case and skip the Set construction entirely.+ let removedCharacterIds = null;+ if (isMutator || 'characters' in patch) {+ const idsOf = (arr) => (Array.isArray(arr)+ ? arr.filter((c) => c?.id).map((c) => c.id) : []);+ const prevIds = new Set(idsOf(cur.characters));+ const nextIds = new Set(idsOf(mergedRecord.characters));+ removedCharacterIds = [...prevIds].filter((id) => !nextIds.has(id));+ }+ return {+ merged: mergedRecord,+ nameChanged: mergedRecord.name !== cur.name,+ skipped: false,+ removedCharacterIds,+ };});if (skipped) return merged;+ // Slot map is in-process; without this it persists past the logical delete.+ for (const removedId of removedCharacterIds ?? []) {+ clearPendingSheetSlot(id, removedId);+ }// Cascade rename onto the linked media collection — log but don't fail// the save: a stale collection name is recoverable, a failed save isn't.// Runs OUTSIDE the queue so the media-collections write tail can't stall@@ -1109,6 +1133,8 @@ export async function deleteUniverse(id) {await unlinkCollectionsForUniverse(id).catch((err) => {console.error(`❌ unlink media collections for deleted universe ${id} failed: ${err?.message || err}`);});+ // Slot map is in-process; persists across the logical delete without this.+ clearPendingSheetSlotsForUniverse(id);emitRecordDeleted('universe', id);return { id };}diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex c2651cf520..9ffb20afc9 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -1956,4 +1956,70 @@ describe("universeBuilder service", () => {expect(runs.map((r) => r.id).sort()).toEqual(["run-1", "run-2"]);});});++ // The slot map is in-process state; without these wirings entries persist+ // until the Node process restarts even after the character/universe is gone.+ describe("pending sheet slot cleanup", () => {+ it("updateUniverse clears slots for characters dropped from the PATCH", async () => {+ const slot = await import("./universeCharacterSheetSlot.js");+ const u = await svc.createUniverse({ name: "SlotPatchTest" });+ // Plant two characters via mutator (trusted path).+ await svc.updateUniverse(u.id, () => ({+ characters: [+ { id: "c-keep", name: "Keep" },+ { id: "c-drop", name: "Drop" },+ ],+ }));+ // Simulate two in-flight renders.+ slot.claimPendingSheetSlot(u.id, "c-keep", "job-keep");+ slot.claimPendingSheetSlot(u.id, "c-drop", "job-drop");+ // Drop one character via PATCH.+ await svc.updateUniverse(u.id, {+ characters: [{ id: "c-keep", name: "Keep" }],+ });+ // Slot for the dropped character is released; the survivor's slot+ // is untouched.+ expect(slot.getPendingSheetSlot(u.id, "c-drop")).toBeUndefined();+ expect(slot.getPendingSheetSlot(u.id, "c-keep")).toBe("job-keep");+ // teardown+ slot.clearPendingSheetSlotsForUniverse(u.id);+ });++ it("updateUniverse leaves slots intact when the PATCH does not remove characters", async () => {+ const slot = await import("./universeCharacterSheetSlot.js");+ const u = await svc.createUniverse({ name: "SlotIdempotentTest" });+ await svc.updateUniverse(u.id, () => ({+ characters: [{ id: "c-1", name: "One" }],+ }));+ slot.claimPendingSheetSlot(u.id, "c-1", "job-1");+ // PATCH that adds a sibling character — the original's slot must+ // survive.+ await svc.updateUniverse(u.id, {+ characters: [+ { id: "c-1", name: "One" },+ { id: "c-2", name: "Two" },+ ],+ });+ expect(slot.getPendingSheetSlot(u.id, "c-1")).toBe("job-1");+ // PATCH that touches an unrelated scalar must not disturb either.+ await svc.updateUniverse(u.id, { logline: "irrelevant" });+ expect(slot.getPendingSheetSlot(u.id, "c-1")).toBe("job-1");+ slot.clearPendingSheetSlotsForUniverse(u.id);+ });++ it("deleteUniverse releases every slot keyed by the universe", async () => {+ const slot = await import("./universeCharacterSheetSlot.js");+ const u1 = await svc.createUniverse({ name: "SlotDeleteA" });+ const u2 = await svc.createUniverse({ name: "SlotDeleteB" });+ slot.claimPendingSheetSlot(u1.id, "char-1", "job-a1");+ slot.claimPendingSheetSlot(u1.id, "char-2", "job-a2");+ slot.claimPendingSheetSlot(u2.id, "char-1", "job-b1");+ await svc.deleteUniverse(u1.id);+ expect(slot.getPendingSheetSlot(u1.id, "char-1")).toBeUndefined();+ expect(slot.getPendingSheetSlot(u1.id, "char-2")).toBeUndefined();+ // Sibling universe's slot survives.+ expect(slot.getPendingSheetSlot(u2.id, "char-1")).toBe("job-b1");+ slot.clearPendingSheetSlotsForUniverse(u2.id);+ });+ });});diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.jsindex 0b28fb21b0..4d6ec32056 100644--- a/server/services/universeCharacterSheet.js+++ b/server/services/universeCharacterSheet.js@@ -27,6 +27,9 @@ import { findOrCreateUniverseCollection } from './mediaCollections.js';import {flattenStats, flattenPalette, flattenWardrobes, flattenProps, flattenNamedList,} from '../lib/canonPrompt.js';+import {+ claimPendingSheetSlot, getPendingSheetSlot, releasePendingSheetSlot,+} from './universeCharacterSheetSlot.js';// 2048×1536 keeps panel labels legible while still rendering in a single// pass on Apple Silicon local backends. Codex / nano-banana ignore the@@ -159,14 +162,13 @@ export function buildCharacterReferenceSheetPrompt(universe, character) {const sheetFilename = (universeId, characterId, generationId) =>`universe-${shortId(universeId)}-${shortId(characterId)}-sheet-${shortId(generationId)}.png`;-// `(universeId, characterId) → latest generationId requested`. When a new-// render starts for a character it claims the slot; when a render completes,-// we only stamp `referenceSheetImageRef` if the slot STILL holds our-// generationId (no newer render started during ours). Prevents an-// older-but-slower render from clobbering a newer-but-finished one. The map-// grows bounded by the number of characters ever rendered.-const _latestPendingByCharacter = new Map();-const pendingKey = (universeId, characterId) => `${universeId}:${characterId}`;+// `(universeId, characterId) → latest generationId requested` is owned by+// `./universeCharacterSheetSlot.js` (extracted so universeBuilder.js can+// clear slots on delete without an import cycle). The supersede-aware+// contract is unchanged: a render claims the slot at enqueue, the+// completion handler only stamps `referenceSheetImageRef` when the slot+// still holds its jobId, and a newer render overwrites the slot so the+// older one sees itself as superseded.// Single-dispatcher subscription so N pending sheets don't attach 4*N// listeners on the global `mediaJobEvents` emitter (Node defaults to a@@ -299,7 +301,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options// Claim the latest-pending slot for this character. onSheetComplete checks// it before stamping — guards against an older-but-slower render finishing// after a newer one and overwriting the newer pointer.- _latestPendingByCharacter.set(pendingKey(universeId, entryId), jobId);+ claimPendingSheetSlot(universeId, entryId, jobId);// Subscribe to the queue's completion bus via the shared sheet// dispatcher (NOT imageGenEvents directly — the queue mediates the@@ -349,9 +351,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, optionsonFailed: (job) => {detach();// Release the slot so a retry render doesn't get superseded by this dead one.- if (_latestPendingByCharacter.get(pendingKey(universeId, entryId)) === jobId) {- _latestPendingByCharacter.delete(pendingKey(universeId, entryId));- }+ releasePendingSheetSlot(universeId, entryId, jobId);console.log(`⚠️ Character sheet render ${job.status} [${shortId(jobId)}]: ${job.error || 'unknown'}`);},});@@ -387,11 +387,12 @@ export async function onSheetComplete({ universeId, entryId, jobId, sourceFilenaconsole.log(`📸 Character sheet copied to image-refs: ${destFilename}`);// If a newer render has been started for this character while ours was in- // flight, the slot now holds someone else's jobId. Skip the stamp — the- // newer render will stamp its own filename when it finishes. Without this,- // an older-but-slower render could overwrite a newer-but-finished pointer.- const key = pendingKey(universeId, entryId);- if (_latestPendingByCharacter.get(key) !== jobId) {+ // flight (OR the character was deleted, which clears the slot), the slot+ // no longer holds our jobId. Skip the stamp — the newer render will stamp+ // its own filename when it finishes, and a deleted character would+ // re-introduce an orphaned pointer. Without this, an older-but-slower+ // render could overwrite a newer-but-finished pointer.+ if (getPendingSheetSlot(universeId, entryId) !== jobId) {console.log(`⏭️ Character sheet [${shortId(jobId)}] superseded by newer render — file saved, pointer not stamped`);return { filename: destFilename, path: destPath, superseded: true };}@@ -420,9 +421,7 @@ export async function onSheetComplete({ universeId, entryId, jobId, sourceFilena// and skip its own stamp — leaving the older filename persisted. A// failed stamp leaves the slot owned by us so the next render-start// cleanly overwrites it.- if (_latestPendingByCharacter.get(key) === jobId) {- _latestPendingByCharacter.delete(key);- }+ releasePendingSheetSlot(universeId, entryId, jobId);if (!stamped) {console.log(`⚠️ Character ${entryId} not found post-render — sheet saved but not linked`);return null;diff --git a/server/services/universeCharacterSheetSlot.js b/server/services/universeCharacterSheetSlot.jsnew file mode 100644index 0000000000..cd9f06fc8e--- /dev/null+++ b/server/services/universeCharacterSheetSlot.js@@ -0,0 +1,57 @@+/**+ * Character reference-sheet "latest pending render" slot map.+ * `${universeId}:${characterId} → jobId` of the most recently started+ * render; supersede-aware stamping in onSheetComplete relies on slot+ * identity. Extracted from universeCharacterSheet.js so universeBuilder.js+ * can clear slots on delete without an import cycle.+ */++const _latestPendingByCharacter = new Map();++const pendingKey = (universeId, characterId) => `${universeId}:${characterId}`;++export function claimPendingSheetSlot(universeId, characterId, jobId) {+ _latestPendingByCharacter.set(pendingKey(universeId, characterId), jobId);+}++export function getPendingSheetSlot(universeId, characterId) {+ return _latestPendingByCharacter.get(pendingKey(universeId, characterId));+}++// Conditional release — only deletes when the slot still belongs to the+// caller's jobId. Used by render-completion / render-failure paths where a+// newer render may have already claimed the slot in parallel.+export function releasePendingSheetSlot(universeId, characterId, jobId) {+ const key = pendingKey(universeId, characterId);+ if (_latestPendingByCharacter.get(key) === jobId) {+ _latestPendingByCharacter.delete(key);+ }+}++// Unconditional release for a single character — used by delete paths where+// the character is going away regardless of what render is in flight. Any+// pending render's onSheetComplete will see the empty slot, treat itself as+// superseded, and skip stamping a now-orphaned pointer.+export function clearPendingSheetSlot(universeId, characterId) {+ return _latestPendingByCharacter.delete(pendingKey(universeId, characterId));+}++// Universe-wide release — used when an entire universe is deleted. Walks+// the map once and drops every key prefixed with `${universeId}:`.+export function clearPendingSheetSlotsForUniverse(universeId) {+ if (!universeId) return 0;+ const prefix = `${universeId}:`;+ let cleared = 0;+ for (const key of _latestPendingByCharacter.keys()) {+ if (key.startsWith(prefix)) {+ _latestPendingByCharacter.delete(key);+ cleared += 1;+ }+ }+ return cleared;+}++export const __testing = {+ reset: () => _latestPendingByCharacter.clear(),+ size: () => _latestPendingByCharacter.size,+};diff --git a/server/services/universeCharacterSheetSlot.test.js b/server/services/universeCharacterSheetSlot.test.jsnew file mode 100644index 0000000000..3c5d1cf903--- /dev/null+++ b/server/services/universeCharacterSheetSlot.test.js@@ -0,0 +1,101 @@+import { describe, it, expect, beforeEach } from 'vitest';+import {+ claimPendingSheetSlot,+ getPendingSheetSlot,+ releasePendingSheetSlot,+ clearPendingSheetSlot,+ clearPendingSheetSlotsForUniverse,+ __testing,+} from './universeCharacterSheetSlot.js';++beforeEach(() => __testing.reset());++describe('universeCharacterSheetSlot — claim / get / release', () => {+ it('claim sets the slot; get reads it back', () => {+ claimPendingSheetSlot('u-a', 'char-1', 'job-1');+ expect(getPendingSheetSlot('u-a', 'char-1')).toBe('job-1');+ });++ it('claim overwrites the previous jobId for the same (universe, character)', () => {+ claimPendingSheetSlot('u-a', 'char-1', 'job-1');+ claimPendingSheetSlot('u-a', 'char-1', 'job-2');+ expect(getPendingSheetSlot('u-a', 'char-1')).toBe('job-2');+ });++ it('releasePendingSheetSlot only deletes when the jobId matches (no-op otherwise)', () => {+ claimPendingSheetSlot('u-a', 'char-1', 'job-1');+ releasePendingSheetSlot('u-a', 'char-1', 'job-other');+ expect(getPendingSheetSlot('u-a', 'char-1')).toBe('job-1');+ releasePendingSheetSlot('u-a', 'char-1', 'job-1');+ expect(getPendingSheetSlot('u-a', 'char-1')).toBeUndefined();+ });++ it('different (universe, character) pairs are independent', () => {+ claimPendingSheetSlot('u-a', 'char-1', 'job-a1');+ claimPendingSheetSlot('u-a', 'char-2', 'job-a2');+ claimPendingSheetSlot('u-b', 'char-1', 'job-b1');+ expect(getPendingSheetSlot('u-a', 'char-1')).toBe('job-a1');+ expect(getPendingSheetSlot('u-a', 'char-2')).toBe('job-a2');+ expect(getPendingSheetSlot('u-b', 'char-1')).toBe('job-b1');+ });+});++describe('universeCharacterSheetSlot — clearPendingSheetSlot (per-character)', () => {+ it('drops the slot unconditionally even if a newer jobId is present', () => {+ claimPendingSheetSlot('u-a', 'char-1', 'job-2'); // simulate the newest claim+ clearPendingSheetSlot('u-a', 'char-1');+ expect(getPendingSheetSlot('u-a', 'char-1')).toBeUndefined();+ });++ it('does not affect slots for other characters in the same universe', () => {+ claimPendingSheetSlot('u-a', 'char-1', 'job-1');+ claimPendingSheetSlot('u-a', 'char-2', 'job-2');+ clearPendingSheetSlot('u-a', 'char-1');+ expect(getPendingSheetSlot('u-a', 'char-1')).toBeUndefined();+ expect(getPendingSheetSlot('u-a', 'char-2')).toBe('job-2');+ });++ it('is a no-op when the slot is already empty', () => {+ expect(clearPendingSheetSlot('u-a', 'never-claimed')).toBe(false);+ });+});++describe('universeCharacterSheetSlot — clearPendingSheetSlotsForUniverse', () => {+ it('drops every slot whose key is prefixed by the universe id', () => {+ claimPendingSheetSlot('u-a', 'char-1', 'job-a1');+ claimPendingSheetSlot('u-a', 'char-2', 'job-a2');+ claimPendingSheetSlot('u-b', 'char-1', 'job-b1');+ const cleared = clearPendingSheetSlotsForUniverse('u-a');+ expect(cleared).toBe(2);+ expect(getPendingSheetSlot('u-a', 'char-1')).toBeUndefined();+ expect(getPendingSheetSlot('u-a', 'char-2')).toBeUndefined();+ expect(getPendingSheetSlot('u-b', 'char-1')).toBe('job-b1');+ });++ it('does NOT match a universe id that is a prefix of another (no false-positive on un-anchored substring)', () => {+ // `u-a` is a prefix of `u-ab` as a string, but the key includes the `:`+ // separator so a literal-prefix sweep must not collide. This is what the+ // `${universeId}:` suffix on the prefix is for.+ claimPendingSheetSlot('u-a', 'char-1', 'job-a1');+ claimPendingSheetSlot('u-ab', 'char-1', 'job-ab1');+ clearPendingSheetSlotsForUniverse('u-a');+ expect(getPendingSheetSlot('u-a', 'char-1')).toBeUndefined();+ expect(getPendingSheetSlot('u-ab', 'char-1')).toBe('job-ab1');+ // cleanup the residue so the next test's beforeEach doesn't have to chase it+ clearPendingSheetSlotsForUniverse('u-ab');+ });++ it('returns 0 when no slots match and is a no-op for an unknown universe', () => {+ claimPendingSheetSlot('u-a', 'char-1', 'job-1');+ expect(clearPendingSheetSlotsForUniverse('u-unknown')).toBe(0);+ expect(getPendingSheetSlot('u-a', 'char-1')).toBe('job-1');+ });++ it('returns 0 and is a no-op when called with a falsy universe id', () => {+ claimPendingSheetSlot('u-a', 'char-1', 'job-1');+ expect(clearPendingSheetSlotsForUniverse('')).toBe(0);+ expect(clearPendingSheetSlotsForUniverse(null)).toBe(0);+ expect(clearPendingSheetSlotsForUniverse(undefined)).toBe(0);+ expect(getPendingSheetSlot('u-a', 'char-1')).toBe('job-1');+ });+});