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
reconcile transient entry ids before enqueueing, and report failed board renders
[._.]/ Adam Eivy9cc5ca01fe09
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex faecd459a7..4e9f4f3dd8 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. 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.+- **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. A second review round found the same mismatch in its other shape: on records written before entry ids were persisted at all, `ensureEntryId` mints a fresh uuid on every read, and `POST /render` migrates the record — persisting yet another set — before queueing jobs against it, so the draft is holding ids that exist nowhere. The render flow now reconciles from the persisted record before it enqueues, and the adopt rule is stated as "keep every id the server also has, replace the ones it does not": an id the server has never heard of cannot be the key anything is stored under, while a confirmed id is never re-pointed and so can never be pulled out from under an in-flight job. And a failed board render now says so — `EntryThumbSlot`'s settle bridge carries the terminal status alongside the filename, so the boards can toast the way the variation and canon rows already did instead of just having the spinner vanish, while a user-initiated cancel stays silent.diff --git a/client/src/components/universe/EntryThumbSlot.jsx b/client/src/components/universe/EntryThumbSlot.jsxindex 9e31e61bdd..70e526a012 100644--- a/client/src/components/universe/EntryThumbSlot.jsx+++ b/client/src/components/universe/EntryThumbSlot.jsx@@ -19,7 +19,7 @@* rendered states. Disabled when `canRender` is false (no backend selected,* save pending, etc.) so the button shape is still visible but inert.*/-import { useState, useEffect } from 'react';+import { useCallback, useState, useEffect } from 'react';import { Sparkles, Star } from 'lucide-react';import MediaJobThumb from '../pipeline/MediaJobThumb';@@ -29,9 +29,12 @@ export default function EntryThumbSlot({primaryImageRef = null,onRender = null,onPreview = null,- // Fired with the rendered filename when an in-flight job completes (forwarded- // to MediaJobThumb's onFilename) so callers can persist the new ref + clear- // the in-flight job without their own job subscription.+ // Fired as `(filename, status)` when an in-flight job reaches a terminal+ // state, so callers can persist the new ref + clear the in-flight job without+ // their own job subscription. `('<file>', 'completed')` on success;+ // `(null, 'failed' | 'canceled')` on a terminal failure, which carries no+ // filename — the status is what lets a caller tell a failed render (worth+ // surfacing) from a user-initiated cancel (not worth a toast).onComplete = null,canRender = true,alt = 'Render',@@ -43,6 +46,17 @@ export default function EntryThumbSlot({// 1024x1536 universe renders so the slot doesn't crop the subject.size = 'sm',}) {+ // Stable identities: MediaJobThumb fires these from effects keyed on+ // `[value, callback]`, so a fresh arrow per render would re-fire the terminal+ // callback on every parent render instead of once when the job settles.+ const onFilename = useCallback(+ (filename) => onComplete?.(filename, 'completed'),+ [onComplete],+ );+ const onStatus = useCallback(+ (s) => { if (s === 'failed' || s === 'canceled') onComplete?.(null, s); },+ [onComplete],+ );if (inFlightJobId) {// `xs` (48x80) matches the empty + completed states below so all three// states share a footprint and the row doesn't jump mid-render. `'lg'`@@ -57,14 +71,14 @@ export default function EntryThumbSlot({label={alt}size={pendingSize}onPreview={onPreview}- onFilename={onComplete}+ onFilename={onFilename}// A terminal failure/cancel never yields a filename, so `onComplete`// (which clears the in-flight job) would otherwise never fire and the// job stays pinned. Callers that scope render state per entity keep that// state across switches (no remount to reset it), so a failed job would// leave the slot stuck — clear it via the no-filename path so the slot// returns to an actionable state and the entity can be re-rendered.- onStatus={(s) => { if (s === 'failed' || s === 'canceled') onComplete?.(null); }}+ onStatus={onStatus}/>);}diff --git a/client/src/components/universe/EntryThumbSlot.test.jsx b/client/src/components/universe/EntryThumbSlot.test.jsxindex f2efe33eda..96cbc21702 100644--- a/client/src/components/universe/EntryThumbSlot.test.jsx+++ b/client/src/components/universe/EntryThumbSlot.test.jsx@@ -64,14 +64,16 @@ describe('EntryThumbSlot — three-state thumbnail', () => {render(<EntryThumbSlot inFlightJobId="job-x" onComplete={onComplete} canRender={false} />);// Terminal failure yields no filename, so without this the scoped job would// stay pinned forever (no remount to reset it) and regenerate stays disabled.- expect(onComplete).toHaveBeenCalledWith(null);+ // The status rides along so a caller can tell a failure worth reporting from+ // a user-initiated cancel.+ expect(onComplete).toHaveBeenCalledWith(null, 'failed');});- it('clears the in-flight job when the render is canceled', () => {+ it('clears the in-flight job when the render is canceled, tagged as a cancel', () => {jobStatus = 'canceled';const onComplete = vi.fn();render(<EntryThumbSlot inFlightJobId="job-y" onComplete={onComplete} canRender={false} />);- expect(onComplete).toHaveBeenCalledWith(null);+ expect(onComplete).toHaveBeenCalledWith(null, 'canceled');});it('does NOT clear the in-flight job for non-terminal statuses', () => {diff --git a/client/src/components/universeBuilder/CompositeSheetsEditor.jsx b/client/src/components/universeBuilder/CompositeSheetsEditor.jsxindex 0aa77bd8ac..5912e68ad9 100644--- a/client/src/components/universeBuilder/CompositeSheetsEditor.jsx+++ b/client/src/components/universeBuilder/CompositeSheetsEditor.jsx@@ -16,11 +16,12 @@ export default function CompositeSheetsEditor({onPreview = null,// Per-row render-pending plumbing, mirroring the variation grid:// `pendingByEntryId[sheet.id]` is the in-flight jobId (or undefined), and- // `onJobSettled(sheetId, filename | null, jobId)` fires when that job reaches- // a terminal state so the parent can append the new filename to the board's- // imageRefs[] and clear the pending entry. A terminal failure/cancel yields no- // filename, so it settles with `null` on the same callback rather than a- // second one — the parent's clear path is identical either way.+ // `onJobSettled(sheetId, filename | null, jobId, status)` fires when that job+ // reaches a terminal state so the parent can append the new filename to the+ // board's imageRefs[] and clear the pending entry. A terminal failure/cancel+ // yields no filename, so it settles with `null` on the same callback rather+ // than a second one — the parent's clear path is identical either way, and+ // `status` is what lets it tell a failure worth reporting from a cancel.pendingByEntryId = {}, onJobSettled = null,}) {const [adding, setAdding] = useState(false);@@ -251,7 +252,7 @@ function SheetRow({// draft) — each one a full listImageGallery() refetch — instead of once when// the job lands.const handleSettled = useCallback(- (filename) => onJobSettled?.(sheet.id, filename, inFlightJobId),+ (filename, status) => onJobSettled?.(sheet.id, filename, inFlightJobId, status),[onJobSettled, sheet.id, inFlightJobId],);// Three-state thumbnail (pending spinner / rendered image / empty placeholderdiff --git a/client/src/components/universeBuilder/CompositeSheetsEditor.test.jsx b/client/src/components/universeBuilder/CompositeSheetsEditor.test.jsxindex 7aaf9cd286..5ae6e6443b 100644--- a/client/src/components/universeBuilder/CompositeSheetsEditor.test.jsx+++ b/client/src/components/universeBuilder/CompositeSheetsEditor.test.jsx@@ -92,7 +92,7 @@ describe('CompositeSheetsEditor', () => {onJobSettled={onJobSettled}/>,);- await waitFor(() => expect(onJobSettled).toHaveBeenCalledWith('sheet-1', 'fresh.png', 'job-9'));+ await waitFor(() => expect(onJobSettled).toHaveBeenCalledWith('sheet-1', 'fresh.png', 'job-9', 'completed'));});// MediaJobThumb fires its onFilename effect on [effectiveFilename, onFilename],@@ -126,6 +126,6 @@ describe('CompositeSheetsEditor', () => {onJobSettled={onJobSettled}/>,);- await waitFor(() => expect(onJobSettled).toHaveBeenCalledWith('sheet-1', null, 'job-9'));+ await waitFor(() => expect(onJobSettled).toHaveBeenCalledWith('sheet-1', null, 'job-9', 'failed'));});});diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsxindex 14ba3b4cdc..b91ab532c2 100644--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx@@ -15,6 +15,7 @@ import {MapPin, Package, Plus, Save, Trash2, Users,} from 'lucide-react';import InlineConfirmRow from '../ui/InlineConfirmRow';+import toast from '../ui/Toast';import { WORLD_CATEGORY_KEY_MAX } from '../../services/api';import useUniverseBucketActions from '../../hooks/useUniverseBucketActions';import useUniverseDraft from '../../hooks/useUniverseDraft';@@ -143,6 +144,7 @@ export default function UniverseBuilder() {setSaving,setWorlds,styleProbeDirty,+ syncEntryIdsFromServer,toggleLock,universes,updateCategory,@@ -177,6 +179,7 @@ export default function UniverseBuilder() {runs,setRuns,preflight: flushDraftIfDirty,+ syncEntryIdsFromServer,});const { expanding, handleExpand, refine } = useUniverseExpand({selectedId,@@ -290,8 +293,12 @@ export default function UniverseBuilder() {);}, [settleEntryJob]);- // Composite boards on the Composites tab.- const handleSheetJobSettled = useCallback((sheetId, filename, settledJobId = null) => {+ // Composite boards on the Composites tab. A failed render is reported the same+ // way the variation and canon rows report theirs — otherwise the spinner just+ // vanishes and the user is left guessing. A user-initiated cancel is not a+ // failure, so it settles silently.+ const handleSheetJobSettled = useCallback((sheetId, filename, settledJobId = null, status = null) => {+ if (!filename && status === 'failed') toast.error('Render failed');settleEntryJob(sheetId,filename,diff --git a/client/src/hooks/useUniverseDraft.js b/client/src/hooks/useUniverseDraft.jsindex f851da694a..a81630883a 100644--- a/client/src/hooks/useUniverseDraft.js+++ b/client/src/hooks/useUniverseDraft.js@@ -342,6 +342,39 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {return result;};+ // Reconcile the draft's entry ids with the persisted record. `POST /render`+ // migrates a universe whose entries predate persisted ids — before that write,+ // `ensureEntryId` mints a fresh uuid on every read, so this draft is holding+ // transient ids while the queued jobs are keyed by the ones the migration just+ // wrote. Without this the pending-job map and the rows it drives use different+ // keys, and no row picks up its own render.+ //+ // Only the ids move: `adoptServerEntryIds` keeps every local id the server also+ // has, so a row is never re-keyed out from under an in-flight job, and nothing+ // else from the fetched record is merged in (it would clobber edits made since).+ // The saved baseline takes the same ids, or adopting them reads as a user edit+ // and the page stays permanently dirty.+ const syncEntryIdsFromServer = useCallback(async () => {+ const id = selectedIdRef.current;+ if (!id) return;+ const fresh = await getUniverse(id, { silent: true }).catch(() => null);+ // Dropping a response for a universe the user has navigated away from —+ // same rule every other mutator here follows.+ if (!fresh || !mountedRef.current || selectedIdRef.current !== id) return;+ const current = draftRef.current || {};+ if (adoptServerEntryIds(current.compositeSheets, fresh.compositeSheets) === current.compositeSheets+ && adoptServerCategoryIds(current.categories, fresh.categories) === current.categories) return;+ const saved = JSON.parse(savedDraftSnapshotRef.current);+ saved.compositeSheets = adoptServerEntryIds(saved.compositeSheets, fresh.compositeSheets);+ saved.categories = adoptServerCategoryIds(saved.categories, fresh.categories);+ savedDraftSnapshotRef.current = JSON.stringify(saved);+ setDraft((d) => ({+ ...d,+ compositeSheets: adoptServerEntryIds(d.compositeSheets, fresh.compositeSheets),+ categories: adoptServerCategoryIds(d.categories, fresh.categories),+ }));+ }, [mountedRef]);+// Preflight for any server action that reads the PERSISTED universe (the LLM// actions, batch render): persist a dirty draft first, so the server operates// on what the user is looking at rather than the last-saved snapshot. Lives@@ -666,6 +699,7 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {setSaving,setWorlds,styleProbeDirty,+ syncEntryIdsFromServer,toggleLock,universes,updateCategory,diff --git a/client/src/hooks/useUniverseDraft.test.jsx b/client/src/hooks/useUniverseDraft.test.jsxindex 6ce85a903c..701e94402b 100644--- a/client/src/hooks/useUniverseDraft.test.jsx+++ b/client/src/hooks/useUniverseDraft.test.jsx@@ -270,26 +270,44 @@ describe('useUniverseDraft', () => {expect(result.current.isDraftDirty()).toBe(false);});- it('leaves the draft untouched when every entry already carries an id', async () => {+ // The sanitizer echoes back any id the payload carried, so a row whose id the+ // server confirms must keep it — re-keying it would strand an in-flight job.+ it('keeps an id the saved record confirms', 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);});++ // The legacy shape: entries written before ids were persisted get a fresh+ // uuid minted on every read, so this draft's copy is transient. POST /render+ // persists a real set before queueing jobs against it — syncEntryIdsFromServer+ // is what re-points the rows at those ids.+ it('replaces transient ids with the persisted ones after a render migration', async () => {+ apiMocks.getUniverse.mockResolvedValue({+ ...universe,+ compositeSheets: [{ id: 'transient-1', kind: 'reference_sheet', label: 'Legacy board', prompt: 'p', locked: true }],+ });+ const { result } = renderDraft();+ await waitFor(() => expect(result.current.draft.compositeSheets[0]?.id).toBe('transient-1'));+ expect(result.current.isDraftDirty()).toBe(false);++ apiMocks.getUniverse.mockResolvedValueOnce({+ ...universe,+ compositeSheets: [{ id: 'persisted-1', kind: 'reference_sheet', label: 'Legacy board', prompt: 'p', locked: true }],+ });+ await act(async () => { await result.current.syncEntryIdsFromServer(); });++ expect(result.current.draft.compositeSheets[0].id).toBe('persisted-1');+ // Re-pointing an id is not a user edit.+ expect(result.current.isDraftDirty()).toBe(false);+ });});it('merges only pending canon additions onto a fresh server snapshot', async () => {diff --git a/client/src/hooks/useUniverseRender.js b/client/src/hooks/useUniverseRender.jsindex 7e5e956b6e..a7b5349c5f 100644--- a/client/src/hooks/useUniverseRender.js+++ b/client/src/hooks/useUniverseRender.js@@ -27,6 +27,10 @@ export default function useUniverseRender({// render") on one the UI is showing. A caller that forgets it should fail// loudly, not silently regress.preflight,+ // `useUniverseDraft`'s entry-id reconcile, run once per successful render.+ // Optional so a caller that only needs the render form isn't forced to wire+ // it; without it, a legacy universe's first render simply doesn't animate.+ syncEntryIdsFromServer = null,}) {const [rendering, setRendering] = useState(false);const [renderOpts, setRenderOpts] = useLocalStoragePersisted(@@ -103,6 +107,11 @@ export default function useUniverseRender({setRendering(false);if (!result) return;+ // BEFORE enqueueing: `/render` migrates a universe whose entries predate+ // persisted ids, minting a real set that these jobs are keyed by — while the+ // draft still holds the transient ids its own GET produced. Reconcile first+ // so every row can match its own job the moment the spinner would start.+ await syncEntryIdsFromServer?.();enqueueEntryJobs(result.entryJobs);toast.success(`Queued ${result.promptCount} renders → "${result.collectionName}"`);const updatedRuns = await listWorldRuns(selectedId).catch(() => runs);diff --git a/client/src/lib/universeBuilderShared.js b/client/src/lib/universeBuilderShared.jsindex 7be9a27ae3..97dedc68d7 100644--- a/client/src/lib/universeBuilderShared.js+++ b/client/src/lib/universeBuilderShared.js@@ -128,16 +128,29 @@ export const compositeKindLabel = (kind) =>// 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.+// The same mismatch has a second shape, on records written before entry ids were+// persisted at all: `ensureEntryId` mints a FRESH uuid on every read for an+// id-less entry, so the draft's copy is transient and differs from the one the+// next reader sees. `POST /render` detects that and persists a real set before+// queueing — so those jobs are keyed by ids this draft has never seen, and the+// draft's own ids exist nowhere on the server. So an id is adopted when the local+// entry has none OR when the id it has is absent from the server record: an id+// the server doesn't know is by definition not the key anything is stored under.+// An id that IS present server-side is always kept, so a row is never re-keyed+// out from under an in-flight job.+//+// Matching is by `label`, the same key the render `selection` / `sheetSelection`+// payloads already use to name an entry across the wire. Each server id is+// claimed at most once, so duplicate labels fill in order instead of collapsing+// onto the first match. Returns the SAME array when nothing changed (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 serverIds = new Set(server.map((entry) => entry?.id).filter(Boolean));+ const keepsOwnId = (entry) => !!entry?.id && serverIds.has(entry.id);+ // Ids already held by a local entry that keeps them are off the table.+ const claimed = new Set(local.filter(keepsOwnId).map((entry) => entry.id));const idsByLabel = new Map();for (const entry of server) {if (!entry?.id || typeof entry.label !== 'string' || claimed.has(entry.id)) continue;@@ -147,9 +160,9 @@ export const adoptServerEntryIds = (local, server) => {}let changed = false;const next = local.map((entry) => {- if (!entry || entry.id) return entry;+ if (!entry || keepsOwnId(entry)) return entry;const id = idsByLabel.get(entry.label)?.shift();- if (!id) return entry;+ if (!id || id === entry.id) return entry;changed = true;return { ...entry, id };});diff --git a/client/src/lib/universeBuilderShared.test.js b/client/src/lib/universeBuilderShared.test.jsindex 639dca469d..890912a81f 100644--- a/client/src/lib/universeBuilderShared.test.js+++ b/client/src/lib/universeBuilderShared.test.js@@ -101,10 +101,28 @@ describe('adoptServerEntryIds', () => {]);});- 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');+ it('keeps an id the server record also has', () => {+ const local = [{ label: 'A', id: 'real-a' }, { label: 'B', id: 'real-b' }];+ const server = [{ label: 'A', id: 'real-a' }, { label: 'B', id: 'real-b' }];+ expect(adoptServerEntryIds(local, server)).toBe(local);+ });++ // Records written before entry ids were persisted get a FRESH uuid minted on+ // every read, so the draft's copy is transient — and /render persists a+ // different set before queueing jobs against it. An id the server doesn't have+ // is not the key anything is stored under, so it gets replaced.+ it('replaces a transient id the server record does not have', () => {+ const local = [{ label: 'A', id: 'transient-a' }];+ const server = [{ label: 'A', id: 'persisted-a' }];+ expect(adoptServerEntryIds(local, server)[0].id).toBe('persisted-a');+ });++ // The guard that keeps this from re-keying a row out from under an in-flight+ // job: a real id always wins, even when a sibling row shares its label.+ it('does not hand a real id to a different row that shares the label', () => {+ const local = [{ label: 'Dup', id: 'transient' }, { label: 'Dup', id: 'real' }];+ const server = [{ label: 'Dup', id: 'real' }];+ expect(adoptServerEntryIds(local, server).map((e) => e.id)).toEqual(['transient', 'real']);});// Two boards can legitimately share a label. Claiming each server id at most@@ -129,6 +147,14 @@ describe('adoptServerEntryIds', () => {expect(adoptServerEntryIds(local, null)).toBe(local);});+ // An empty/failed server list must not strip ids off every row — "no server+ // entries" is not evidence that the local ids are fake.+ it('leaves ids alone when the server list has none to offer', () => {+ const local = [{ label: 'A', id: 'a' }, { label: 'B' }];+ expect(adoptServerEntryIds(local, [])).toBe(local);+ expect(adoptServerEntryIds(local, [{ label: 'C', id: 'c' }])).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);