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

adopt server-minted entry ids into the draft after a save

[._.]/ Adam Eivycfc9e5ca23c8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5a1872d7a4..faecd459a7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -74,4 +74,4 @@
- **The "Pick from Gallery" picker could only be narrowed by typing, so finding one object in one universe meant recalling a word from its prompt.** It now carries two dropdowns beside the search box: a scope select that groups every universe and media collection under `<optgroup>`s, and a type select built from the `entryCategory`/`entryKind` tags the Universe Builder stamps onto sidecars, labelled through the same `humanizeCategory` the Builder uses. Those two are separate vocabularies — a user-authored bucket can legitimately be keyed `canon` — so the type options are prefixed by which field they filter and grouped under Categories/Entry kinds rather than flattened into one list where the bucket and the stage would silently match each other. All three filters AND-combine, and both dropdowns list only universes/collections/types that actually match an image currently in the picker — a scope that can only ever produce an empty grid isn't offered, and a selection that stops matching resets itself to "All" rather than silently blanking the grid. Collection membership is matched on the stored `{ kind, ref }` pair (the same `<kind>:<ref>` string `normalizeImage` puts on `item.key`), not on a bare filename, so a collection holding video refs alongside images filters correctly. Both option fetches are best-effort: if the collections or universes call fails the picker keeps working, falling back to the universe name stamped on each sidecar, and the fetched lists are dropped on close so a reopen can't filter fresh images against stale membership. Sidecars are unvalidated JSON that also arrive from peers, so a tag that isn't a usable string is skipped rather than crashing the render — which surfaced a latent bug in the shared `humanizeCategory`: its label lookup wasn't `hasOwn`-guarded, so a user-authored category keyed `constructor` or `toString` resolved to an inherited function and handed every caller a label that throws on the next string method (#3479).
-- **Composite boards were the only Universe Builder surface with no thumbnail, so a rendered board looked unrendered.** Characters, places, objects and category variations all show their latest render as an `EntryThumbSlot` avatar with a click-to-preview lightbox; the Composites tab showed label + prompt only. Nothing was missing server-side — `compile.js` already stamps an `entryRef` of kind `sheet` on each queued board render and the completion hook already appends the resulting filename to that board's `imageRefs[]`, so the data was sitting in the record with nothing reading it. Composite rows now render through the same `EntryCard` shell + three-state `EntryThumbSlot` the variation and canon rows use (in-flight spinner → rendered thumbnail → empty placeholder with a one-click render button), so their spacing and locked accent can no longer drift from the other surfaces, and clicking a board opens the same page-level lightbox with the real render prompt hydrated from the gallery sidecar. `useRenderJobQueue` had been dropping `sheet`-kind jobs on the grounds that no row consumed them; with every kind the server stamps now settled by a row, the filter is deleted rather than widened — an allowlist that already covers everything can only ever fail closed on the next kind added, silently, with no spinner and no error. Two things this collapsed rather than copied: the row settles through `EntryThumbSlot`'s existing `onComplete` bridge instead of opening a second `useMediaJobProgress` subscription against a jobId the slot is already watching (which is what the variation and canon rows do, at the cost of a row re-render per diffusion tick), and the two page-level job handlers that had each inlined the same append-dedupe-cap now share `appendImageRefById` in `lib/bibleLimits.js`, the client mirror of the server's `mapAppendImageRef` (three other surfaces still inline their own copy). The settle callback is memoized rather than rebuilt per render: `MediaJobThumb` fires its completion effect on `[filename, onFilename]`, so a fresh arrow would re-settle the same job on every keystroke in the builder draft, each one a full gallery refetch — there is a test that fails against the unstable form.
+- **Composite boards were the only Universe Builder surface with no thumbnail, so a rendered board looked unrendered.** Characters, places, objects and category variations all show their latest render as an `EntryThumbSlot` avatar with a click-to-preview lightbox; the Composites tab showed label + prompt only. Nothing was missing server-side — `compile.js` already stamps an `entryRef` of kind `sheet` on each queued board render and the completion hook already appends the resulting filename to that board's `imageRefs[]`, so the data was sitting in the record with nothing reading it. Composite rows now render through the same `EntryCard` shell + three-state `EntryThumbSlot` the variation and canon rows use (in-flight spinner → rendered thumbnail → empty placeholder with a one-click render button), so their spacing and locked accent can no longer drift from the other surfaces, and clicking a board opens the same page-level lightbox with the real render prompt hydrated from the gallery sidecar. `useRenderJobQueue` had been dropping `sheet`-kind jobs on the grounds that no row consumed them; with every kind the server stamps now settled by a row, the filter is deleted rather than widened — an allowlist that already covers everything can only ever fail closed on the next kind added, silently, with no spinner and no error. Two things this collapsed rather than copied: the row settles through `EntryThumbSlot`'s existing `onComplete` bridge instead of opening a second `useMediaJobProgress` subscription against a jobId the slot is already watching (which is what the variation and canon rows do, at the cost of a row re-render per diffusion tick), and the two page-level job handlers that had each inlined the same append-dedupe-cap now share `appendImageRefById` in `lib/bibleLimits.js`, the client mirror of the server's `mapAppendImageRef` (three other surfaces still inline their own copy). The settle callback is memoized rather than rebuilt per render: `MediaJobThumb` fires its completion effect on `[filename, onFilename]`, so a fresh arrow would re-settle the same job on every keystroke in the builder draft, each one a full gallery refetch — there is a test that fails against the unstable form. Codex review then surfaced the gap that made the whole thing conditional: the draft never adopted the ids the server sanitizer mints, so a board added and rendered in the same session had no `id` to match the one the server stamped onto `entryJobs` — no spinner, no thumbnail until reload, and (now that sheet jobs are tracked) a pending entry with no consumer to clear it. `handleSave` had the server record in hand the whole time and only ever used it for the universe list, so it now adopts the minted ids into both the draft and its dirty baseline — backfilling only the draft would leave the page permanently dirty. That fixes variations, which had the identical latent bug, in the same place rather than special-casing boards.
diff --git a/client/src/hooks/useUniverseDraft.js b/client/src/hooks/useUniverseDraft.js
index 7d0409e901..f851da694a 100644
--- a/client/src/hooks/useUniverseDraft.js
+++ b/client/src/hooks/useUniverseDraft.js
@@ -24,6 +24,8 @@ import { upsertByIdPrepend } from '../lib/upsertByIdPrepend';
import { mergeCanonByName } from '../lib/universeBuilderExpand';
import {
TRUNK_BY_KIND,
+ adoptServerCategoryIds,
+ adoptServerEntryIds,
ensureDraftCategories,
humanizeCategory,
normalizeCategoryKey,
@@ -311,7 +313,24 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
setCanonDirty(false);
clearPendingCanonAdditions();
}
- markDraftSaved(payload);
+ // Adopt the ids the server sanitizer minted for entries this save created,
+ // so per-entry client state keyed by id (the render queue's pending-job map)
+ // can match a board or variation added and used in the same session. Both
+ // the draft AND the saved baseline take the ids — backfilling only the draft
+ // would read as an unsaved edit and leave the page permanently dirty.
+ const savedSheets = adoptServerEntryIds(payload.compositeSheets, result.compositeSheets);
+ const savedCategories = adoptServerCategoryIds(payload.categories, result.categories);
+ markDraftSaved({ ...payload, compositeSheets: savedSheets, categories: savedCategories });
+ if (savedSheets !== payload.compositeSheets || savedCategories !== payload.categories) {
+ // Re-derive from the CURRENT draft rather than assigning `savedSheets`
+ // wholesale — edits made while the save was in flight must survive, and
+ // adopting an id is additive to whatever the row looks like now.
+ setDraft((d) => ({
+ ...d,
+ compositeSheets: adoptServerEntryIds(d.compositeSheets, result.compositeSheets),
+ categories: adoptServerCategoryIds(d.categories, result.categories),
+ }));
+ }
// Watermark this save so a re-hydration GET it raced (navigate away and back
// mid-save) re-reads instead of showing the pre-save record — the same guard
// the style-reference mutators get, which is why it keys on the server's
diff --git a/client/src/hooks/useUniverseDraft.test.jsx b/client/src/hooks/useUniverseDraft.test.jsx
index b81937ced0..6ce85a903c 100644
--- a/client/src/hooks/useUniverseDraft.test.jsx
+++ b/client/src/hooks/useUniverseDraft.test.jsx
@@ -238,6 +238,60 @@ describe('useUniverseDraft', () => {
expect(result.current.isDraftDirty()).toBe(false);
});
+ // The render flow keys its per-row pending-job map on the id the SERVER
+ // stamped onto `entryJobs`. A board or variation created in this session has
+ // no id until a save mints one, so without adopting it the row can never match
+ // its own job — no spinner, no thumbnail until reload, and a pending entry
+ // with no consumer to clear it.
+ describe('adopting server-minted entry ids on save', () => {
+ it('backfills ids onto sheets and variations the save created', async () => {
+ const { result } = renderDraft();
+ await waitFor(() => expect(result.current.draft.id).toBe('u1'));
+
+ act(() => {
+ result.current.updateCompositeSheets([{ kind: 'reference_sheet', label: 'New board', prompt: 'p', locked: true }]);
+ result.current.updateCategory('heroes', [{ label: 'New hero', prompt: 'p' }]);
+ });
+ // The server sanitizer mints ids for both id-less entries.
+ apiMocks.updateUniverse.mockImplementationOnce(async (id, payload) => ({
+ ...universe,
+ id,
+ compositeSheets: payload.compositeSheets.map((s) => ({ ...s, id: 'sheet-minted' })),
+ categories: {
+ heroes: { ...payload.categories.heroes, variations: [{ ...payload.categories.heroes.variations[0], id: 'var-minted' }] },
+ },
+ updatedAt: tickServerClock(),
+ }));
+ await act(async () => { await result.current.handleSave(); });
+
+ expect(result.current.draft.compositeSheets[0].id).toBe('sheet-minted');
+ expect(result.current.draft.categories.heroes.variations[0].id).toBe('var-minted');
+ // Adopting the ids is not a user edit — the page must not read as dirty.
+ expect(result.current.isDraftDirty()).toBe(false);
+ });
+
+ it('leaves the draft untouched when every entry already carries an id', async () => {
+ const { result } = renderDraft();
+ await waitFor(() => expect(result.current.draft.id).toBe('u1'));
+
+ act(() => {
+ result.current.updateCompositeSheets([{ id: 'mine', kind: 'reference_sheet', label: 'Board', prompt: 'p', locked: true }]);
+ });
+ apiMocks.updateUniverse.mockImplementationOnce(async (id, payload) => ({
+ ...universe,
+ id,
+ // Server echoes a DIFFERENT id for the same label — an existing local id
+ // must win, or a row would be re-keyed out from under its in-flight job.
+ compositeSheets: payload.compositeSheets.map((s) => ({ ...s, id: 'server-other' })),
+ updatedAt: tickServerClock(),
+ }));
+ await act(async () => { await result.current.handleSave(); });
+
+ expect(result.current.draft.compositeSheets[0].id).toBe('mine');
+ expect(result.current.isDraftDirty()).toBe(false);
+ });
+ });
+
it('merges only pending canon additions onto a fresh server snapshot', async () => {
const { result } = renderDraft();
await waitFor(() => expect(result.current.draft.id).toBe('u1'));
diff --git a/client/src/lib/universeBuilderShared.js b/client/src/lib/universeBuilderShared.js
index d796504596..7be9a27ae3 100644
--- a/client/src/lib/universeBuilderShared.js
+++ b/client/src/lib/universeBuilderShared.js
@@ -118,3 +118,58 @@ export const COMPOSITE_BOARD_KINDS = [
export const compositeKindLabel = (kind) =>
COMPOSITE_BOARD_KINDS.find((k) => k.value === kind)?.label || 'Reference sheet';
+
+// The server sanitizer mints an `id` for every entry that arrives without one,
+// but a save returns that record without the draft adopting it — so an entry
+// created and used in the same session stays id-less on the client. That breaks
+// any client state keyed by entry id: the render queue's per-row pending-job map
+// is keyed by the id the SERVER stamped onto `entryJobs`, so a board (or
+// variation) added and immediately rendered would never match its own job — no
+// spinner, no thumbnail until reload, and a pending entry with no consumer to
+// clear it.
+//
+// Copy the minted ids back onto the local list. Matching is by `label`, the same
+// key the render `selection` / `sheetSelection` payloads already use to name an
+// entry across the wire. Only id-less entries are filled, so an existing id is
+// never rewritten, and each server id is claimed at most once — duplicate labels
+// fill in order instead of collapsing onto the first match. Returns the SAME
+// array when nothing was filled (the common case, since the sanitizer has
+// already stamped ids on anything round-tripped) so callers can skip the write.
+export const adoptServerEntryIds = (local, server) => {
+ if (!Array.isArray(local) || !Array.isArray(server)) return local;
+ const claimed = new Set(local.map((entry) => entry?.id).filter(Boolean));
+ const idsByLabel = new Map();
+ for (const entry of server) {
+ if (!entry?.id || typeof entry.label !== 'string' || claimed.has(entry.id)) continue;
+ const queue = idsByLabel.get(entry.label);
+ if (queue) queue.push(entry.id);
+ else idsByLabel.set(entry.label, [entry.id]);
+ }
+ let changed = false;
+ const next = local.map((entry) => {
+ if (!entry || entry.id) return entry;
+ const id = idsByLabel.get(entry.label)?.shift();
+ if (!id) return entry;
+ changed = true;
+ return { ...entry, id };
+ });
+ return changed ? next : local;
+};
+
+// `adoptServerEntryIds` over every bucket's `variations`, for the keyed
+// `categories` map. Same same-reference-when-unchanged contract.
+export const adoptServerCategoryIds = (local, server) => {
+ if (!local || typeof local !== 'object' || !server || typeof server !== 'object') return local;
+ let changed = false;
+ const next = {};
+ for (const [key, bucket] of Object.entries(local)) {
+ const variations = adoptServerEntryIds(bucket?.variations, server[key]?.variations);
+ if (variations !== bucket?.variations) {
+ changed = true;
+ next[key] = { ...bucket, variations };
+ } else {
+ next[key] = bucket;
+ }
+ }
+ return changed ? next : local;
+};
diff --git a/client/src/lib/universeBuilderShared.test.js b/client/src/lib/universeBuilderShared.test.js
index 6a1a1b7c49..639dca469d 100644
--- a/client/src/lib/universeBuilderShared.test.js
+++ b/client/src/lib/universeBuilderShared.test.js
@@ -3,6 +3,7 @@ import {
TRUNK_TABS, TRUNK_BY_ID, TRUNK_BY_KIND, BUCKET_CANON,
groupBucketsByKind, normalizeCategoryKey, humanizeCategory,
ensureDraftCategories, getCategoryKeys, compositeKindLabel, COMPOSITE_BOARD_KINDS,
+ adoptServerEntryIds, adoptServerCategoryIds,
} from './universeBuilderShared.js';
describe('universeBuilderShared — trunk maps', () => {
@@ -89,3 +90,68 @@ describe('universeBuilderShared — compositeKindLabel', () => {
expect(COMPOSITE_BOARD_KINDS.length).toBeGreaterThan(0);
});
});
+
+describe('adoptServerEntryIds', () => {
+ it('fills ids onto id-less entries by label', () => {
+ const local = [{ label: 'A' }, { label: 'B', id: 'keep-me' }];
+ const server = [{ label: 'A', id: 'sheet-a' }, { label: 'B', id: 'keep-me' }];
+ expect(adoptServerEntryIds(local, server)).toEqual([
+ { label: 'A', id: 'sheet-a' },
+ { label: 'B', id: 'keep-me' },
+ ]);
+ });
+
+ it('never rewrites an id the local entry already has', () => {
+ const local = [{ label: 'A', id: 'local-a' }];
+ const server = [{ label: 'A', id: 'server-a' }];
+ expect(adoptServerEntryIds(local, server)[0].id).toBe('local-a');
+ });
+
+ // Two boards can legitimately share a label. Claiming each server id at most
+ // once makes them fill in order rather than both taking the first match — and
+ // an id already held locally is excluded from the pool so it can't be handed
+ // to a different row.
+ it('claims each server id once across duplicate labels', () => {
+ const local = [{ label: 'Dup' }, { label: 'Dup' }, { label: 'Dup', id: 'held' }];
+ const server = [
+ { label: 'Dup', id: 'held' },
+ { label: 'Dup', id: 's1' },
+ { label: 'Dup', id: 's2' },
+ ];
+ expect(adoptServerEntryIds(local, server).map((e) => e.id)).toEqual(['s1', 's2', 'held']);
+ });
+
+ // Same-reference-when-unchanged is the contract callers use to skip a setState.
+ it('returns the same array when nothing needed filling', () => {
+ const local = [{ label: 'A', id: 'a' }];
+ expect(adoptServerEntryIds(local, [{ label: 'A', id: 'a' }])).toBe(local);
+ expect(adoptServerEntryIds(local, [])).toBe(local);
+ expect(adoptServerEntryIds(local, null)).toBe(local);
+ });
+
+ it('leaves an entry alone when no server entry shares its label', () => {
+ const local = [{ label: 'Missing' }];
+ expect(adoptServerEntryIds(local, [{ label: 'Other', id: 'x' }])).toBe(local);
+ });
+});
+
+describe('adoptServerCategoryIds', () => {
+ it('fills variation ids per bucket and preserves untouched buckets by reference', () => {
+ const untouched = { kind: 'places', variations: [{ label: 'P', id: 'p1' }] };
+ const local = { cast: { kind: 'characters', variations: [{ label: 'V' }] }, places: untouched };
+ const server = {
+ cast: { variations: [{ label: 'V', id: 'v1' }] },
+ places: { variations: [{ label: 'P', id: 'p1' }] },
+ };
+ const next = adoptServerCategoryIds(local, server);
+ expect(next.cast.variations[0].id).toBe('v1');
+ expect(next.cast.kind).toBe('characters');
+ expect(next.places).toBe(untouched);
+ });
+
+ it('returns the same object when no bucket changed', () => {
+ const local = { cast: { variations: [{ label: 'V', id: 'v1' }] } };
+ expect(adoptServerCategoryIds(local, { cast: { variations: [{ label: 'V', id: 'v1' }] } })).toBe(local);
+ expect(adoptServerCategoryIds(local, null)).toBe(local);
+ });
+});